xref: /titanic_52/usr/src/uts/common/fs/zfs/arc.c (revision ba3594ba9b5dd4c846c472a8d657edcb7c8109ac)
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 void *
1314 arc_data_buf_alloc(uint64_t size)
1315 {
1316 	if (arc_evict_needed(ARC_BUFC_DATA))
1317 		cv_signal(&arc_reclaim_thr_cv);
1318 	atomic_add_64(&arc_size, size);
1319 	return (zio_data_buf_alloc(size));
1320 }
1321 
1322 void
1323 arc_data_buf_free(void *buf, uint64_t size)
1324 {
1325 	zio_data_buf_free(buf, size);
1326 	ASSERT(arc_size >= size);
1327 	atomic_add_64(&arc_size, -size);
1328 }
1329 
1330 arc_buf_t *
1331 arc_buf_alloc(spa_t *spa, int size, void *tag, arc_buf_contents_t type)
1332 {
1333 	arc_buf_hdr_t *hdr;
1334 	arc_buf_t *buf;
1335 
1336 	ASSERT3U(size, >, 0);
1337 	hdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
1338 	ASSERT(BUF_EMPTY(hdr));
1339 	hdr->b_size = size;
1340 	hdr->b_type = type;
1341 	hdr->b_spa = spa_load_guid(spa);
1342 	hdr->b_state = arc_anon;
1343 	hdr->b_arc_access = 0;
1344 	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1345 	buf->b_hdr = hdr;
1346 	buf->b_data = NULL;
1347 	buf->b_efunc = NULL;
1348 	buf->b_private = NULL;
1349 	buf->b_next = NULL;
1350 	hdr->b_buf = buf;
1351 	arc_get_data_buf(buf);
1352 	hdr->b_datacnt = 1;
1353 	hdr->b_flags = 0;
1354 	ASSERT(refcount_is_zero(&hdr->b_refcnt));
1355 	(void) refcount_add(&hdr->b_refcnt, tag);
1356 
1357 	return (buf);
1358 }
1359 
1360 static char *arc_onloan_tag = "onloan";
1361 
1362 /*
1363  * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
1364  * flight data by arc_tempreserve_space() until they are "returned". Loaned
1365  * buffers must be returned to the arc before they can be used by the DMU or
1366  * freed.
1367  */
1368 arc_buf_t *
1369 arc_loan_buf(spa_t *spa, int size)
1370 {
1371 	arc_buf_t *buf;
1372 
1373 	buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
1374 
1375 	atomic_add_64(&arc_loaned_bytes, size);
1376 	return (buf);
1377 }
1378 
1379 /*
1380  * Return a loaned arc buffer to the arc.
1381  */
1382 void
1383 arc_return_buf(arc_buf_t *buf, void *tag)
1384 {
1385 	arc_buf_hdr_t *hdr = buf->b_hdr;
1386 
1387 	ASSERT(buf->b_data != NULL);
1388 	(void) refcount_add(&hdr->b_refcnt, tag);
1389 	(void) refcount_remove(&hdr->b_refcnt, arc_onloan_tag);
1390 
1391 	atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
1392 }
1393 
1394 /* Detach an arc_buf from a dbuf (tag) */
1395 void
1396 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
1397 {
1398 	arc_buf_hdr_t *hdr;
1399 
1400 	ASSERT(buf->b_data != NULL);
1401 	hdr = buf->b_hdr;
1402 	(void) refcount_add(&hdr->b_refcnt, arc_onloan_tag);
1403 	(void) refcount_remove(&hdr->b_refcnt, tag);
1404 	buf->b_efunc = NULL;
1405 	buf->b_private = NULL;
1406 
1407 	atomic_add_64(&arc_loaned_bytes, hdr->b_size);
1408 }
1409 
1410 static arc_buf_t *
1411 arc_buf_clone(arc_buf_t *from)
1412 {
1413 	arc_buf_t *buf;
1414 	arc_buf_hdr_t *hdr = from->b_hdr;
1415 	uint64_t size = hdr->b_size;
1416 
1417 	ASSERT(hdr->b_state != arc_anon);
1418 
1419 	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1420 	buf->b_hdr = hdr;
1421 	buf->b_data = NULL;
1422 	buf->b_efunc = NULL;
1423 	buf->b_private = NULL;
1424 	buf->b_next = hdr->b_buf;
1425 	hdr->b_buf = buf;
1426 	arc_get_data_buf(buf);
1427 	bcopy(from->b_data, buf->b_data, size);
1428 
1429 	/*
1430 	 * This buffer already exists in the arc so create a duplicate
1431 	 * copy for the caller.  If the buffer is associated with user data
1432 	 * then track the size and number of duplicates.  These stats will be
1433 	 * updated as duplicate buffers are created and destroyed.
1434 	 */
1435 	if (hdr->b_type == ARC_BUFC_DATA) {
1436 		ARCSTAT_BUMP(arcstat_duplicate_buffers);
1437 		ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
1438 	}
1439 	hdr->b_datacnt += 1;
1440 	return (buf);
1441 }
1442 
1443 void
1444 arc_buf_add_ref(arc_buf_t *buf, void* tag)
1445 {
1446 	arc_buf_hdr_t *hdr;
1447 	kmutex_t *hash_lock;
1448 
1449 	/*
1450 	 * Check to see if this buffer is evicted.  Callers
1451 	 * must verify b_data != NULL to know if the add_ref
1452 	 * was successful.
1453 	 */
1454 	mutex_enter(&buf->b_evict_lock);
1455 	if (buf->b_data == NULL) {
1456 		mutex_exit(&buf->b_evict_lock);
1457 		return;
1458 	}
1459 	hash_lock = HDR_LOCK(buf->b_hdr);
1460 	mutex_enter(hash_lock);
1461 	hdr = buf->b_hdr;
1462 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1463 	mutex_exit(&buf->b_evict_lock);
1464 
1465 	ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
1466 	add_reference(hdr, hash_lock, tag);
1467 	DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
1468 	arc_access(hdr, hash_lock);
1469 	mutex_exit(hash_lock);
1470 	ARCSTAT_BUMP(arcstat_hits);
1471 	ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
1472 	    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
1473 	    data, metadata, hits);
1474 }
1475 
1476 /*
1477  * Free the arc data buffer.  If it is an l2arc write in progress,
1478  * the buffer is placed on l2arc_free_on_write to be freed later.
1479  */
1480 static void
1481 arc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
1482 {
1483 	arc_buf_hdr_t *hdr = buf->b_hdr;
1484 
1485 	if (HDR_L2_WRITING(hdr)) {
1486 		l2arc_data_free_t *df;
1487 		df = kmem_alloc(sizeof (l2arc_data_free_t), KM_SLEEP);
1488 		df->l2df_data = buf->b_data;
1489 		df->l2df_size = hdr->b_size;
1490 		df->l2df_func = free_func;
1491 		mutex_enter(&l2arc_free_on_write_mtx);
1492 		list_insert_head(l2arc_free_on_write, df);
1493 		mutex_exit(&l2arc_free_on_write_mtx);
1494 		ARCSTAT_BUMP(arcstat_l2_free_on_write);
1495 	} else {
1496 		free_func(buf->b_data, hdr->b_size);
1497 	}
1498 }
1499 
1500 /*
1501  * Free up buf->b_data and if 'remove' is set, then pull the
1502  * arc_buf_t off of the the arc_buf_hdr_t's list and free it.
1503  */
1504 static void
1505 arc_buf_destroy(arc_buf_t *buf, boolean_t recycle, boolean_t remove)
1506 {
1507 	arc_buf_t **bufp;
1508 
1509 	/* free up data associated with the buf */
1510 	if (buf->b_data) {
1511 		arc_state_t *state = buf->b_hdr->b_state;
1512 		uint64_t size = buf->b_hdr->b_size;
1513 		arc_buf_contents_t type = buf->b_hdr->b_type;
1514 
1515 		arc_cksum_verify(buf);
1516 		arc_buf_unwatch(buf);
1517 
1518 		if (!recycle) {
1519 			if (type == ARC_BUFC_METADATA) {
1520 				arc_buf_data_free(buf, zio_buf_free);
1521 				arc_space_return(size, ARC_SPACE_DATA);
1522 			} else {
1523 				ASSERT(type == ARC_BUFC_DATA);
1524 				arc_buf_data_free(buf, zio_data_buf_free);
1525 				ARCSTAT_INCR(arcstat_data_size, -size);
1526 				atomic_add_64(&arc_size, -size);
1527 			}
1528 		}
1529 		if (list_link_active(&buf->b_hdr->b_arc_node)) {
1530 			uint64_t *cnt = &state->arcs_lsize[type];
1531 
1532 			ASSERT(refcount_is_zero(&buf->b_hdr->b_refcnt));
1533 			ASSERT(state != arc_anon);
1534 
1535 			ASSERT3U(*cnt, >=, size);
1536 			atomic_add_64(cnt, -size);
1537 		}
1538 		ASSERT3U(state->arcs_size, >=, size);
1539 		atomic_add_64(&state->arcs_size, -size);
1540 		buf->b_data = NULL;
1541 
1542 		/*
1543 		 * If we're destroying a duplicate buffer make sure
1544 		 * that the appropriate statistics are updated.
1545 		 */
1546 		if (buf->b_hdr->b_datacnt > 1 &&
1547 		    buf->b_hdr->b_type == ARC_BUFC_DATA) {
1548 			ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
1549 			ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
1550 		}
1551 		ASSERT(buf->b_hdr->b_datacnt > 0);
1552 		buf->b_hdr->b_datacnt -= 1;
1553 	}
1554 
1555 	/* only remove the buf if requested */
1556 	if (!remove)
1557 		return;
1558 
1559 	/* remove the buf from the hdr list */
1560 	for (bufp = &buf->b_hdr->b_buf; *bufp != buf; bufp = &(*bufp)->b_next)
1561 		continue;
1562 	*bufp = buf->b_next;
1563 	buf->b_next = NULL;
1564 
1565 	ASSERT(buf->b_efunc == NULL);
1566 
1567 	/* clean up the buf */
1568 	buf->b_hdr = NULL;
1569 	kmem_cache_free(buf_cache, buf);
1570 }
1571 
1572 static void
1573 arc_hdr_destroy(arc_buf_hdr_t *hdr)
1574 {
1575 	ASSERT(refcount_is_zero(&hdr->b_refcnt));
1576 	ASSERT3P(hdr->b_state, ==, arc_anon);
1577 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1578 	l2arc_buf_hdr_t *l2hdr = hdr->b_l2hdr;
1579 
1580 	if (l2hdr != NULL) {
1581 		boolean_t buflist_held = MUTEX_HELD(&l2arc_buflist_mtx);
1582 		/*
1583 		 * To prevent arc_free() and l2arc_evict() from
1584 		 * attempting to free the same buffer at the same time,
1585 		 * a FREE_IN_PROGRESS flag is given to arc_free() to
1586 		 * give it priority.  l2arc_evict() can't destroy this
1587 		 * header while we are waiting on l2arc_buflist_mtx.
1588 		 *
1589 		 * The hdr may be removed from l2ad_buflist before we
1590 		 * grab l2arc_buflist_mtx, so b_l2hdr is rechecked.
1591 		 */
1592 		if (!buflist_held) {
1593 			mutex_enter(&l2arc_buflist_mtx);
1594 			l2hdr = hdr->b_l2hdr;
1595 		}
1596 
1597 		if (l2hdr != NULL) {
1598 			list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
1599 			ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
1600 			ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
1601 			vdev_space_update(l2hdr->b_dev->l2ad_vdev,
1602 			    -l2hdr->b_asize, 0, 0);
1603 			kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
1604 			if (hdr->b_state == arc_l2c_only)
1605 				l2arc_hdr_stat_remove();
1606 			hdr->b_l2hdr = NULL;
1607 		}
1608 
1609 		if (!buflist_held)
1610 			mutex_exit(&l2arc_buflist_mtx);
1611 	}
1612 
1613 	if (!BUF_EMPTY(hdr)) {
1614 		ASSERT(!HDR_IN_HASH_TABLE(hdr));
1615 		buf_discard_identity(hdr);
1616 	}
1617 	while (hdr->b_buf) {
1618 		arc_buf_t *buf = hdr->b_buf;
1619 
1620 		if (buf->b_efunc) {
1621 			mutex_enter(&arc_eviction_mtx);
1622 			mutex_enter(&buf->b_evict_lock);
1623 			ASSERT(buf->b_hdr != NULL);
1624 			arc_buf_destroy(hdr->b_buf, FALSE, FALSE);
1625 			hdr->b_buf = buf->b_next;
1626 			buf->b_hdr = &arc_eviction_hdr;
1627 			buf->b_next = arc_eviction_list;
1628 			arc_eviction_list = buf;
1629 			mutex_exit(&buf->b_evict_lock);
1630 			mutex_exit(&arc_eviction_mtx);
1631 		} else {
1632 			arc_buf_destroy(hdr->b_buf, FALSE, TRUE);
1633 		}
1634 	}
1635 	if (hdr->b_freeze_cksum != NULL) {
1636 		kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1637 		hdr->b_freeze_cksum = NULL;
1638 	}
1639 	if (hdr->b_thawed) {
1640 		kmem_free(hdr->b_thawed, 1);
1641 		hdr->b_thawed = NULL;
1642 	}
1643 
1644 	ASSERT(!list_link_active(&hdr->b_arc_node));
1645 	ASSERT3P(hdr->b_hash_next, ==, NULL);
1646 	ASSERT3P(hdr->b_acb, ==, NULL);
1647 	kmem_cache_free(hdr_cache, hdr);
1648 }
1649 
1650 void
1651 arc_buf_free(arc_buf_t *buf, void *tag)
1652 {
1653 	arc_buf_hdr_t *hdr = buf->b_hdr;
1654 	int hashed = hdr->b_state != arc_anon;
1655 
1656 	ASSERT(buf->b_efunc == NULL);
1657 	ASSERT(buf->b_data != NULL);
1658 
1659 	if (hashed) {
1660 		kmutex_t *hash_lock = HDR_LOCK(hdr);
1661 
1662 		mutex_enter(hash_lock);
1663 		hdr = buf->b_hdr;
1664 		ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1665 
1666 		(void) remove_reference(hdr, hash_lock, tag);
1667 		if (hdr->b_datacnt > 1) {
1668 			arc_buf_destroy(buf, FALSE, TRUE);
1669 		} else {
1670 			ASSERT(buf == hdr->b_buf);
1671 			ASSERT(buf->b_efunc == NULL);
1672 			hdr->b_flags |= ARC_BUF_AVAILABLE;
1673 		}
1674 		mutex_exit(hash_lock);
1675 	} else if (HDR_IO_IN_PROGRESS(hdr)) {
1676 		int destroy_hdr;
1677 		/*
1678 		 * We are in the middle of an async write.  Don't destroy
1679 		 * this buffer unless the write completes before we finish
1680 		 * decrementing the reference count.
1681 		 */
1682 		mutex_enter(&arc_eviction_mtx);
1683 		(void) remove_reference(hdr, NULL, tag);
1684 		ASSERT(refcount_is_zero(&hdr->b_refcnt));
1685 		destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
1686 		mutex_exit(&arc_eviction_mtx);
1687 		if (destroy_hdr)
1688 			arc_hdr_destroy(hdr);
1689 	} else {
1690 		if (remove_reference(hdr, NULL, tag) > 0)
1691 			arc_buf_destroy(buf, FALSE, TRUE);
1692 		else
1693 			arc_hdr_destroy(hdr);
1694 	}
1695 }
1696 
1697 boolean_t
1698 arc_buf_remove_ref(arc_buf_t *buf, void* tag)
1699 {
1700 	arc_buf_hdr_t *hdr = buf->b_hdr;
1701 	kmutex_t *hash_lock = HDR_LOCK(hdr);
1702 	boolean_t no_callback = (buf->b_efunc == NULL);
1703 
1704 	if (hdr->b_state == arc_anon) {
1705 		ASSERT(hdr->b_datacnt == 1);
1706 		arc_buf_free(buf, tag);
1707 		return (no_callback);
1708 	}
1709 
1710 	mutex_enter(hash_lock);
1711 	hdr = buf->b_hdr;
1712 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1713 	ASSERT(hdr->b_state != arc_anon);
1714 	ASSERT(buf->b_data != NULL);
1715 
1716 	(void) remove_reference(hdr, hash_lock, tag);
1717 	if (hdr->b_datacnt > 1) {
1718 		if (no_callback)
1719 			arc_buf_destroy(buf, FALSE, TRUE);
1720 	} else if (no_callback) {
1721 		ASSERT(hdr->b_buf == buf && buf->b_next == NULL);
1722 		ASSERT(buf->b_efunc == NULL);
1723 		hdr->b_flags |= ARC_BUF_AVAILABLE;
1724 	}
1725 	ASSERT(no_callback || hdr->b_datacnt > 1 ||
1726 	    refcount_is_zero(&hdr->b_refcnt));
1727 	mutex_exit(hash_lock);
1728 	return (no_callback);
1729 }
1730 
1731 int
1732 arc_buf_size(arc_buf_t *buf)
1733 {
1734 	return (buf->b_hdr->b_size);
1735 }
1736 
1737 /*
1738  * Called from the DMU to determine if the current buffer should be
1739  * evicted. In order to ensure proper locking, the eviction must be initiated
1740  * from the DMU. Return true if the buffer is associated with user data and
1741  * duplicate buffers still exist.
1742  */
1743 boolean_t
1744 arc_buf_eviction_needed(arc_buf_t *buf)
1745 {
1746 	arc_buf_hdr_t *hdr;
1747 	boolean_t evict_needed = B_FALSE;
1748 
1749 	if (zfs_disable_dup_eviction)
1750 		return (B_FALSE);
1751 
1752 	mutex_enter(&buf->b_evict_lock);
1753 	hdr = buf->b_hdr;
1754 	if (hdr == NULL) {
1755 		/*
1756 		 * We are in arc_do_user_evicts(); let that function
1757 		 * perform the eviction.
1758 		 */
1759 		ASSERT(buf->b_data == NULL);
1760 		mutex_exit(&buf->b_evict_lock);
1761 		return (B_FALSE);
1762 	} else if (buf->b_data == NULL) {
1763 		/*
1764 		 * We have already been added to the arc eviction list;
1765 		 * recommend eviction.
1766 		 */
1767 		ASSERT3P(hdr, ==, &arc_eviction_hdr);
1768 		mutex_exit(&buf->b_evict_lock);
1769 		return (B_TRUE);
1770 	}
1771 
1772 	if (hdr->b_datacnt > 1 && hdr->b_type == ARC_BUFC_DATA)
1773 		evict_needed = B_TRUE;
1774 
1775 	mutex_exit(&buf->b_evict_lock);
1776 	return (evict_needed);
1777 }
1778 
1779 /*
1780  * Evict buffers from list until we've removed the specified number of
1781  * bytes.  Move the removed buffers to the appropriate evict state.
1782  * If the recycle flag is set, then attempt to "recycle" a buffer:
1783  * - look for a buffer to evict that is `bytes' long.
1784  * - return the data block from this buffer rather than freeing it.
1785  * This flag is used by callers that are trying to make space for a
1786  * new buffer in a full arc cache.
1787  *
1788  * This function makes a "best effort".  It skips over any buffers
1789  * it can't get a hash_lock on, and so may not catch all candidates.
1790  * It may also return without evicting as much space as requested.
1791  */
1792 static void *
1793 arc_evict(arc_state_t *state, uint64_t spa, int64_t bytes, boolean_t recycle,
1794     arc_buf_contents_t type)
1795 {
1796 	arc_state_t *evicted_state;
1797 	uint64_t bytes_evicted = 0, skipped = 0, missed = 0;
1798 	arc_buf_hdr_t *ab, *ab_prev = NULL;
1799 	list_t *list = &state->arcs_list[type];
1800 	kmutex_t *hash_lock;
1801 	boolean_t have_lock;
1802 	void *stolen = NULL;
1803 	arc_buf_hdr_t marker = { 0 };
1804 	int count = 0;
1805 
1806 	ASSERT(state == arc_mru || state == arc_mfu);
1807 
1808 	evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
1809 
1810 	mutex_enter(&state->arcs_mtx);
1811 	mutex_enter(&evicted_state->arcs_mtx);
1812 
1813 	for (ab = list_tail(list); ab; ab = ab_prev) {
1814 		ab_prev = list_prev(list, ab);
1815 		/* prefetch buffers have a minimum lifespan */
1816 		if (HDR_IO_IN_PROGRESS(ab) ||
1817 		    (spa && ab->b_spa != spa) ||
1818 		    (ab->b_flags & (ARC_PREFETCH|ARC_INDIRECT) &&
1819 		    ddi_get_lbolt() - ab->b_arc_access <
1820 		    arc_min_prefetch_lifespan)) {
1821 			skipped++;
1822 			continue;
1823 		}
1824 		/* "lookahead" for better eviction candidate */
1825 		if (recycle && ab->b_size != bytes &&
1826 		    ab_prev && ab_prev->b_size == bytes)
1827 			continue;
1828 
1829 		/* ignore markers */
1830 		if (ab->b_spa == 0)
1831 			continue;
1832 
1833 		/*
1834 		 * It may take a long time to evict all the bufs requested.
1835 		 * To avoid blocking all arc activity, periodically drop
1836 		 * the arcs_mtx and give other threads a chance to run
1837 		 * before reacquiring the lock.
1838 		 *
1839 		 * If we are looking for a buffer to recycle, we are in
1840 		 * the hot code path, so don't sleep.
1841 		 */
1842 		if (!recycle && count++ > arc_evict_iterations) {
1843 			list_insert_after(list, ab, &marker);
1844 			mutex_exit(&evicted_state->arcs_mtx);
1845 			mutex_exit(&state->arcs_mtx);
1846 			kpreempt(KPREEMPT_SYNC);
1847 			mutex_enter(&state->arcs_mtx);
1848 			mutex_enter(&evicted_state->arcs_mtx);
1849 			ab_prev = list_prev(list, &marker);
1850 			list_remove(list, &marker);
1851 			count = 0;
1852 			continue;
1853 		}
1854 
1855 		hash_lock = HDR_LOCK(ab);
1856 		have_lock = MUTEX_HELD(hash_lock);
1857 		if (have_lock || mutex_tryenter(hash_lock)) {
1858 			ASSERT0(refcount_count(&ab->b_refcnt));
1859 			ASSERT(ab->b_datacnt > 0);
1860 			while (ab->b_buf) {
1861 				arc_buf_t *buf = ab->b_buf;
1862 				if (!mutex_tryenter(&buf->b_evict_lock)) {
1863 					missed += 1;
1864 					break;
1865 				}
1866 				if (buf->b_data) {
1867 					bytes_evicted += ab->b_size;
1868 					if (recycle && ab->b_type == type &&
1869 					    ab->b_size == bytes &&
1870 					    !HDR_L2_WRITING(ab)) {
1871 						stolen = buf->b_data;
1872 						recycle = FALSE;
1873 					}
1874 				}
1875 				if (buf->b_efunc) {
1876 					mutex_enter(&arc_eviction_mtx);
1877 					arc_buf_destroy(buf,
1878 					    buf->b_data == stolen, FALSE);
1879 					ab->b_buf = buf->b_next;
1880 					buf->b_hdr = &arc_eviction_hdr;
1881 					buf->b_next = arc_eviction_list;
1882 					arc_eviction_list = buf;
1883 					mutex_exit(&arc_eviction_mtx);
1884 					mutex_exit(&buf->b_evict_lock);
1885 				} else {
1886 					mutex_exit(&buf->b_evict_lock);
1887 					arc_buf_destroy(buf,
1888 					    buf->b_data == stolen, TRUE);
1889 				}
1890 			}
1891 
1892 			if (ab->b_l2hdr) {
1893 				ARCSTAT_INCR(arcstat_evict_l2_cached,
1894 				    ab->b_size);
1895 			} else {
1896 				if (l2arc_write_eligible(ab->b_spa, ab)) {
1897 					ARCSTAT_INCR(arcstat_evict_l2_eligible,
1898 					    ab->b_size);
1899 				} else {
1900 					ARCSTAT_INCR(
1901 					    arcstat_evict_l2_ineligible,
1902 					    ab->b_size);
1903 				}
1904 			}
1905 
1906 			if (ab->b_datacnt == 0) {
1907 				arc_change_state(evicted_state, ab, hash_lock);
1908 				ASSERT(HDR_IN_HASH_TABLE(ab));
1909 				ab->b_flags |= ARC_IN_HASH_TABLE;
1910 				ab->b_flags &= ~ARC_BUF_AVAILABLE;
1911 				DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, ab);
1912 			}
1913 			if (!have_lock)
1914 				mutex_exit(hash_lock);
1915 			if (bytes >= 0 && bytes_evicted >= bytes)
1916 				break;
1917 		} else {
1918 			missed += 1;
1919 		}
1920 	}
1921 
1922 	mutex_exit(&evicted_state->arcs_mtx);
1923 	mutex_exit(&state->arcs_mtx);
1924 
1925 	if (bytes_evicted < bytes)
1926 		dprintf("only evicted %lld bytes from %x",
1927 		    (longlong_t)bytes_evicted, state);
1928 
1929 	if (skipped)
1930 		ARCSTAT_INCR(arcstat_evict_skip, skipped);
1931 
1932 	if (missed)
1933 		ARCSTAT_INCR(arcstat_mutex_miss, missed);
1934 
1935 	/*
1936 	 * Note: we have just evicted some data into the ghost state,
1937 	 * potentially putting the ghost size over the desired size.  Rather
1938 	 * that evicting from the ghost list in this hot code path, leave
1939 	 * this chore to the arc_reclaim_thread().
1940 	 */
1941 
1942 	return (stolen);
1943 }
1944 
1945 /*
1946  * Remove buffers from list until we've removed the specified number of
1947  * bytes.  Destroy the buffers that are removed.
1948  */
1949 static void
1950 arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes)
1951 {
1952 	arc_buf_hdr_t *ab, *ab_prev;
1953 	arc_buf_hdr_t marker = { 0 };
1954 	list_t *list = &state->arcs_list[ARC_BUFC_DATA];
1955 	kmutex_t *hash_lock;
1956 	uint64_t bytes_deleted = 0;
1957 	uint64_t bufs_skipped = 0;
1958 	int count = 0;
1959 
1960 	ASSERT(GHOST_STATE(state));
1961 top:
1962 	mutex_enter(&state->arcs_mtx);
1963 	for (ab = list_tail(list); ab; ab = ab_prev) {
1964 		ab_prev = list_prev(list, ab);
1965 		if (ab->b_type > ARC_BUFC_NUMTYPES)
1966 			panic("invalid ab=%p", (void *)ab);
1967 		if (spa && ab->b_spa != spa)
1968 			continue;
1969 
1970 		/* ignore markers */
1971 		if (ab->b_spa == 0)
1972 			continue;
1973 
1974 		hash_lock = HDR_LOCK(ab);
1975 		/* caller may be trying to modify this buffer, skip it */
1976 		if (MUTEX_HELD(hash_lock))
1977 			continue;
1978 
1979 		/*
1980 		 * It may take a long time to evict all the bufs requested.
1981 		 * To avoid blocking all arc activity, periodically drop
1982 		 * the arcs_mtx and give other threads a chance to run
1983 		 * before reacquiring the lock.
1984 		 */
1985 		if (count++ > arc_evict_iterations) {
1986 			list_insert_after(list, ab, &marker);
1987 			mutex_exit(&state->arcs_mtx);
1988 			kpreempt(KPREEMPT_SYNC);
1989 			mutex_enter(&state->arcs_mtx);
1990 			ab_prev = list_prev(list, &marker);
1991 			list_remove(list, &marker);
1992 			count = 0;
1993 			continue;
1994 		}
1995 		if (mutex_tryenter(hash_lock)) {
1996 			ASSERT(!HDR_IO_IN_PROGRESS(ab));
1997 			ASSERT(ab->b_buf == NULL);
1998 			ARCSTAT_BUMP(arcstat_deleted);
1999 			bytes_deleted += ab->b_size;
2000 
2001 			if (ab->b_l2hdr != NULL) {
2002 				/*
2003 				 * This buffer is cached on the 2nd Level ARC;
2004 				 * don't destroy the header.
2005 				 */
2006 				arc_change_state(arc_l2c_only, ab, hash_lock);
2007 				mutex_exit(hash_lock);
2008 			} else {
2009 				arc_change_state(arc_anon, ab, hash_lock);
2010 				mutex_exit(hash_lock);
2011 				arc_hdr_destroy(ab);
2012 			}
2013 
2014 			DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, ab);
2015 			if (bytes >= 0 && bytes_deleted >= bytes)
2016 				break;
2017 		} else if (bytes < 0) {
2018 			/*
2019 			 * Insert a list marker and then wait for the
2020 			 * hash lock to become available. Once its
2021 			 * available, restart from where we left off.
2022 			 */
2023 			list_insert_after(list, ab, &marker);
2024 			mutex_exit(&state->arcs_mtx);
2025 			mutex_enter(hash_lock);
2026 			mutex_exit(hash_lock);
2027 			mutex_enter(&state->arcs_mtx);
2028 			ab_prev = list_prev(list, &marker);
2029 			list_remove(list, &marker);
2030 		} else {
2031 			bufs_skipped += 1;
2032 		}
2033 
2034 	}
2035 	mutex_exit(&state->arcs_mtx);
2036 
2037 	if (list == &state->arcs_list[ARC_BUFC_DATA] &&
2038 	    (bytes < 0 || bytes_deleted < bytes)) {
2039 		list = &state->arcs_list[ARC_BUFC_METADATA];
2040 		goto top;
2041 	}
2042 
2043 	if (bufs_skipped) {
2044 		ARCSTAT_INCR(arcstat_mutex_miss, bufs_skipped);
2045 		ASSERT(bytes >= 0);
2046 	}
2047 
2048 	if (bytes_deleted < bytes)
2049 		dprintf("only deleted %lld bytes from %p",
2050 		    (longlong_t)bytes_deleted, state);
2051 }
2052 
2053 static void
2054 arc_adjust(void)
2055 {
2056 	int64_t adjustment, delta;
2057 
2058 	/*
2059 	 * Adjust MRU size
2060 	 */
2061 
2062 	adjustment = MIN((int64_t)(arc_size - arc_c),
2063 	    (int64_t)(arc_anon->arcs_size + arc_mru->arcs_size + arc_meta_used -
2064 	    arc_p));
2065 
2066 	if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_DATA] > 0) {
2067 		delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_DATA], adjustment);
2068 		(void) arc_evict(arc_mru, NULL, delta, FALSE, ARC_BUFC_DATA);
2069 		adjustment -= delta;
2070 	}
2071 
2072 	if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2073 		delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_METADATA], adjustment);
2074 		(void) arc_evict(arc_mru, NULL, delta, FALSE,
2075 		    ARC_BUFC_METADATA);
2076 	}
2077 
2078 	/*
2079 	 * Adjust MFU size
2080 	 */
2081 
2082 	adjustment = arc_size - arc_c;
2083 
2084 	if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_DATA] > 0) {
2085 		delta = MIN(adjustment, arc_mfu->arcs_lsize[ARC_BUFC_DATA]);
2086 		(void) arc_evict(arc_mfu, NULL, delta, FALSE, ARC_BUFC_DATA);
2087 		adjustment -= delta;
2088 	}
2089 
2090 	if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2091 		int64_t delta = MIN(adjustment,
2092 		    arc_mfu->arcs_lsize[ARC_BUFC_METADATA]);
2093 		(void) arc_evict(arc_mfu, NULL, delta, FALSE,
2094 		    ARC_BUFC_METADATA);
2095 	}
2096 
2097 	/*
2098 	 * Adjust ghost lists
2099 	 */
2100 
2101 	adjustment = arc_mru->arcs_size + arc_mru_ghost->arcs_size - arc_c;
2102 
2103 	if (adjustment > 0 && arc_mru_ghost->arcs_size > 0) {
2104 		delta = MIN(arc_mru_ghost->arcs_size, adjustment);
2105 		arc_evict_ghost(arc_mru_ghost, NULL, delta);
2106 	}
2107 
2108 	adjustment =
2109 	    arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size - arc_c;
2110 
2111 	if (adjustment > 0 && arc_mfu_ghost->arcs_size > 0) {
2112 		delta = MIN(arc_mfu_ghost->arcs_size, adjustment);
2113 		arc_evict_ghost(arc_mfu_ghost, NULL, delta);
2114 	}
2115 }
2116 
2117 static void
2118 arc_do_user_evicts(void)
2119 {
2120 	mutex_enter(&arc_eviction_mtx);
2121 	while (arc_eviction_list != NULL) {
2122 		arc_buf_t *buf = arc_eviction_list;
2123 		arc_eviction_list = buf->b_next;
2124 		mutex_enter(&buf->b_evict_lock);
2125 		buf->b_hdr = NULL;
2126 		mutex_exit(&buf->b_evict_lock);
2127 		mutex_exit(&arc_eviction_mtx);
2128 
2129 		if (buf->b_efunc != NULL)
2130 			VERIFY0(buf->b_efunc(buf->b_private));
2131 
2132 		buf->b_efunc = NULL;
2133 		buf->b_private = NULL;
2134 		kmem_cache_free(buf_cache, buf);
2135 		mutex_enter(&arc_eviction_mtx);
2136 	}
2137 	mutex_exit(&arc_eviction_mtx);
2138 }
2139 
2140 /*
2141  * Flush all *evictable* data from the cache for the given spa.
2142  * NOTE: this will not touch "active" (i.e. referenced) data.
2143  */
2144 void
2145 arc_flush(spa_t *spa)
2146 {
2147 	uint64_t guid = 0;
2148 
2149 	if (spa)
2150 		guid = spa_load_guid(spa);
2151 
2152 	while (list_head(&arc_mru->arcs_list[ARC_BUFC_DATA])) {
2153 		(void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_DATA);
2154 		if (spa)
2155 			break;
2156 	}
2157 	while (list_head(&arc_mru->arcs_list[ARC_BUFC_METADATA])) {
2158 		(void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_METADATA);
2159 		if (spa)
2160 			break;
2161 	}
2162 	while (list_head(&arc_mfu->arcs_list[ARC_BUFC_DATA])) {
2163 		(void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_DATA);
2164 		if (spa)
2165 			break;
2166 	}
2167 	while (list_head(&arc_mfu->arcs_list[ARC_BUFC_METADATA])) {
2168 		(void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_METADATA);
2169 		if (spa)
2170 			break;
2171 	}
2172 
2173 	arc_evict_ghost(arc_mru_ghost, guid, -1);
2174 	arc_evict_ghost(arc_mfu_ghost, guid, -1);
2175 
2176 	mutex_enter(&arc_reclaim_thr_lock);
2177 	arc_do_user_evicts();
2178 	mutex_exit(&arc_reclaim_thr_lock);
2179 	ASSERT(spa || arc_eviction_list == NULL);
2180 }
2181 
2182 void
2183 arc_shrink(void)
2184 {
2185 	if (arc_c > arc_c_min) {
2186 		uint64_t to_free;
2187 
2188 #ifdef _KERNEL
2189 		to_free = MAX(arc_c >> arc_shrink_shift, ptob(needfree));
2190 #else
2191 		to_free = arc_c >> arc_shrink_shift;
2192 #endif
2193 		if (arc_c > arc_c_min + to_free)
2194 			atomic_add_64(&arc_c, -to_free);
2195 		else
2196 			arc_c = arc_c_min;
2197 
2198 		atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
2199 		if (arc_c > arc_size)
2200 			arc_c = MAX(arc_size, arc_c_min);
2201 		if (arc_p > arc_c)
2202 			arc_p = (arc_c >> 1);
2203 		ASSERT(arc_c >= arc_c_min);
2204 		ASSERT((int64_t)arc_p >= 0);
2205 	}
2206 
2207 	if (arc_size > arc_c)
2208 		arc_adjust();
2209 }
2210 
2211 /*
2212  * Determine if the system is under memory pressure and is asking
2213  * to reclaim memory. A return value of 1 indicates that the system
2214  * is under memory pressure and that the arc should adjust accordingly.
2215  */
2216 static int
2217 arc_reclaim_needed(void)
2218 {
2219 	uint64_t extra;
2220 
2221 #ifdef _KERNEL
2222 
2223 	if (needfree)
2224 		return (1);
2225 
2226 	/*
2227 	 * take 'desfree' extra pages, so we reclaim sooner, rather than later
2228 	 */
2229 	extra = desfree;
2230 
2231 	/*
2232 	 * check that we're out of range of the pageout scanner.  It starts to
2233 	 * schedule paging if freemem is less than lotsfree and needfree.
2234 	 * lotsfree is the high-water mark for pageout, and needfree is the
2235 	 * number of needed free pages.  We add extra pages here to make sure
2236 	 * the scanner doesn't start up while we're freeing memory.
2237 	 */
2238 	if (freemem < lotsfree + needfree + extra)
2239 		return (1);
2240 
2241 	/*
2242 	 * check to make sure that swapfs has enough space so that anon
2243 	 * reservations can still succeed. anon_resvmem() checks that the
2244 	 * availrmem is greater than swapfs_minfree, and the number of reserved
2245 	 * swap pages.  We also add a bit of extra here just to prevent
2246 	 * circumstances from getting really dire.
2247 	 */
2248 	if (availrmem < swapfs_minfree + swapfs_reserve + extra)
2249 		return (1);
2250 
2251 	/*
2252 	 * Check that we have enough availrmem that memory locking (e.g., via
2253 	 * mlock(3C) or memcntl(2)) can still succeed.  (pages_pp_maximum
2254 	 * stores the number of pages that cannot be locked; when availrmem
2255 	 * drops below pages_pp_maximum, page locking mechanisms such as
2256 	 * page_pp_lock() will fail.)
2257 	 */
2258 	if (availrmem <= pages_pp_maximum)
2259 		return (1);
2260 
2261 #if defined(__i386)
2262 	/*
2263 	 * If we're on an i386 platform, it's possible that we'll exhaust the
2264 	 * kernel heap space before we ever run out of available physical
2265 	 * memory.  Most checks of the size of the heap_area compare against
2266 	 * tune.t_minarmem, which is the minimum available real memory that we
2267 	 * can have in the system.  However, this is generally fixed at 25 pages
2268 	 * which is so low that it's useless.  In this comparison, we seek to
2269 	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
2270 	 * heap is allocated.  (Or, in the calculation, if less than 1/4th is
2271 	 * free)
2272 	 */
2273 	if (vmem_size(heap_arena, VMEM_FREE) <
2274 	    (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2))
2275 		return (1);
2276 #endif
2277 
2278 	/*
2279 	 * If zio data pages are being allocated out of a separate heap segment,
2280 	 * then enforce that the size of available vmem for this arena remains
2281 	 * above about 1/16th free.
2282 	 *
2283 	 * Note: The 1/16th arena free requirement was put in place
2284 	 * to aggressively evict memory from the arc in order to avoid
2285 	 * memory fragmentation issues.
2286 	 */
2287 	if (zio_arena != NULL &&
2288 	    vmem_size(zio_arena, VMEM_FREE) <
2289 	    (vmem_size(zio_arena, VMEM_ALLOC) >> 4))
2290 		return (1);
2291 #else
2292 	if (spa_get_random(100) == 0)
2293 		return (1);
2294 #endif
2295 	return (0);
2296 }
2297 
2298 static void
2299 arc_kmem_reap_now(arc_reclaim_strategy_t strat)
2300 {
2301 	size_t			i;
2302 	kmem_cache_t		*prev_cache = NULL;
2303 	kmem_cache_t		*prev_data_cache = NULL;
2304 	extern kmem_cache_t	*zio_buf_cache[];
2305 	extern kmem_cache_t	*zio_data_buf_cache[];
2306 
2307 #ifdef _KERNEL
2308 	if (arc_meta_used >= arc_meta_limit) {
2309 		/*
2310 		 * We are exceeding our meta-data cache limit.
2311 		 * Purge some DNLC entries to release holds on meta-data.
2312 		 */
2313 		dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
2314 	}
2315 #if defined(__i386)
2316 	/*
2317 	 * Reclaim unused memory from all kmem caches.
2318 	 */
2319 	kmem_reap();
2320 #endif
2321 #endif
2322 
2323 	/*
2324 	 * An aggressive reclamation will shrink the cache size as well as
2325 	 * reap free buffers from the arc kmem caches.
2326 	 */
2327 	if (strat == ARC_RECLAIM_AGGR)
2328 		arc_shrink();
2329 
2330 	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
2331 		if (zio_buf_cache[i] != prev_cache) {
2332 			prev_cache = zio_buf_cache[i];
2333 			kmem_cache_reap_now(zio_buf_cache[i]);
2334 		}
2335 		if (zio_data_buf_cache[i] != prev_data_cache) {
2336 			prev_data_cache = zio_data_buf_cache[i];
2337 			kmem_cache_reap_now(zio_data_buf_cache[i]);
2338 		}
2339 	}
2340 	kmem_cache_reap_now(buf_cache);
2341 	kmem_cache_reap_now(hdr_cache);
2342 
2343 	/*
2344 	 * Ask the vmem areana to reclaim unused memory from its
2345 	 * quantum caches.
2346 	 */
2347 	if (zio_arena != NULL && strat == ARC_RECLAIM_AGGR)
2348 		vmem_qcache_reap(zio_arena);
2349 }
2350 
2351 static void
2352 arc_reclaim_thread(void)
2353 {
2354 	clock_t			growtime = 0;
2355 	arc_reclaim_strategy_t	last_reclaim = ARC_RECLAIM_CONS;
2356 	callb_cpr_t		cpr;
2357 
2358 	CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
2359 
2360 	mutex_enter(&arc_reclaim_thr_lock);
2361 	while (arc_thread_exit == 0) {
2362 		if (arc_reclaim_needed()) {
2363 
2364 			if (arc_no_grow) {
2365 				if (last_reclaim == ARC_RECLAIM_CONS) {
2366 					last_reclaim = ARC_RECLAIM_AGGR;
2367 				} else {
2368 					last_reclaim = ARC_RECLAIM_CONS;
2369 				}
2370 			} else {
2371 				arc_no_grow = TRUE;
2372 				last_reclaim = ARC_RECLAIM_AGGR;
2373 				membar_producer();
2374 			}
2375 
2376 			/* reset the growth delay for every reclaim */
2377 			growtime = ddi_get_lbolt() + (arc_grow_retry * hz);
2378 
2379 			arc_kmem_reap_now(last_reclaim);
2380 			arc_warm = B_TRUE;
2381 
2382 		} else if (arc_no_grow && ddi_get_lbolt() >= growtime) {
2383 			arc_no_grow = FALSE;
2384 		}
2385 
2386 		arc_adjust();
2387 
2388 		if (arc_eviction_list != NULL)
2389 			arc_do_user_evicts();
2390 
2391 		/* block until needed, or one second, whichever is shorter */
2392 		CALLB_CPR_SAFE_BEGIN(&cpr);
2393 		(void) cv_timedwait(&arc_reclaim_thr_cv,
2394 		    &arc_reclaim_thr_lock, (ddi_get_lbolt() + hz));
2395 		CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
2396 	}
2397 
2398 	arc_thread_exit = 0;
2399 	cv_broadcast(&arc_reclaim_thr_cv);
2400 	CALLB_CPR_EXIT(&cpr);		/* drops arc_reclaim_thr_lock */
2401 	thread_exit();
2402 }
2403 
2404 /*
2405  * Adapt arc info given the number of bytes we are trying to add and
2406  * the state that we are comming from.  This function is only called
2407  * when we are adding new content to the cache.
2408  */
2409 static void
2410 arc_adapt(int bytes, arc_state_t *state)
2411 {
2412 	int mult;
2413 	uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
2414 
2415 	if (state == arc_l2c_only)
2416 		return;
2417 
2418 	ASSERT(bytes > 0);
2419 	/*
2420 	 * Adapt the target size of the MRU list:
2421 	 *	- if we just hit in the MRU ghost list, then increase
2422 	 *	  the target size of the MRU list.
2423 	 *	- if we just hit in the MFU ghost list, then increase
2424 	 *	  the target size of the MFU list by decreasing the
2425 	 *	  target size of the MRU list.
2426 	 */
2427 	if (state == arc_mru_ghost) {
2428 		mult = ((arc_mru_ghost->arcs_size >= arc_mfu_ghost->arcs_size) ?
2429 		    1 : (arc_mfu_ghost->arcs_size/arc_mru_ghost->arcs_size));
2430 		mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
2431 
2432 		arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
2433 	} else if (state == arc_mfu_ghost) {
2434 		uint64_t delta;
2435 
2436 		mult = ((arc_mfu_ghost->arcs_size >= arc_mru_ghost->arcs_size) ?
2437 		    1 : (arc_mru_ghost->arcs_size/arc_mfu_ghost->arcs_size));
2438 		mult = MIN(mult, 10);
2439 
2440 		delta = MIN(bytes * mult, arc_p);
2441 		arc_p = MAX(arc_p_min, arc_p - delta);
2442 	}
2443 	ASSERT((int64_t)arc_p >= 0);
2444 
2445 	if (arc_reclaim_needed()) {
2446 		cv_signal(&arc_reclaim_thr_cv);
2447 		return;
2448 	}
2449 
2450 	if (arc_no_grow)
2451 		return;
2452 
2453 	if (arc_c >= arc_c_max)
2454 		return;
2455 
2456 	/*
2457 	 * If we're within (2 * maxblocksize) bytes of the target
2458 	 * cache size, increment the target cache size
2459 	 */
2460 	if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
2461 		atomic_add_64(&arc_c, (int64_t)bytes);
2462 		if (arc_c > arc_c_max)
2463 			arc_c = arc_c_max;
2464 		else if (state == arc_anon)
2465 			atomic_add_64(&arc_p, (int64_t)bytes);
2466 		if (arc_p > arc_c)
2467 			arc_p = arc_c;
2468 	}
2469 	ASSERT((int64_t)arc_p >= 0);
2470 }
2471 
2472 /*
2473  * Check if the cache has reached its limits and eviction is required
2474  * prior to insert.
2475  */
2476 static int
2477 arc_evict_needed(arc_buf_contents_t type)
2478 {
2479 	if (type == ARC_BUFC_METADATA && arc_meta_used >= arc_meta_limit)
2480 		return (1);
2481 
2482 	if (arc_reclaim_needed())
2483 		return (1);
2484 
2485 	return (arc_size > arc_c);
2486 }
2487 
2488 /*
2489  * The buffer, supplied as the first argument, needs a data block.
2490  * So, if we are at cache max, determine which cache should be victimized.
2491  * We have the following cases:
2492  *
2493  * 1. Insert for MRU, p > sizeof(arc_anon + arc_mru) ->
2494  * In this situation if we're out of space, but the resident size of the MFU is
2495  * under the limit, victimize the MFU cache to satisfy this insertion request.
2496  *
2497  * 2. Insert for MRU, p <= sizeof(arc_anon + arc_mru) ->
2498  * Here, we've used up all of the available space for the MRU, so we need to
2499  * evict from our own cache instead.  Evict from the set of resident MRU
2500  * entries.
2501  *
2502  * 3. Insert for MFU (c - p) > sizeof(arc_mfu) ->
2503  * c minus p represents the MFU space in the cache, since p is the size of the
2504  * cache that is dedicated to the MRU.  In this situation there's still space on
2505  * the MFU side, so the MRU side needs to be victimized.
2506  *
2507  * 4. Insert for MFU (c - p) < sizeof(arc_mfu) ->
2508  * MFU's resident set is consuming more space than it has been allotted.  In
2509  * this situation, we must victimize our own cache, the MFU, for this insertion.
2510  */
2511 static void
2512 arc_get_data_buf(arc_buf_t *buf)
2513 {
2514 	arc_state_t		*state = buf->b_hdr->b_state;
2515 	uint64_t		size = buf->b_hdr->b_size;
2516 	arc_buf_contents_t	type = buf->b_hdr->b_type;
2517 
2518 	arc_adapt(size, state);
2519 
2520 	/*
2521 	 * We have not yet reached cache maximum size,
2522 	 * just allocate a new buffer.
2523 	 */
2524 	if (!arc_evict_needed(type)) {
2525 		if (type == ARC_BUFC_METADATA) {
2526 			buf->b_data = zio_buf_alloc(size);
2527 			arc_space_consume(size, ARC_SPACE_DATA);
2528 		} else {
2529 			ASSERT(type == ARC_BUFC_DATA);
2530 			buf->b_data = zio_data_buf_alloc(size);
2531 			ARCSTAT_INCR(arcstat_data_size, size);
2532 			atomic_add_64(&arc_size, size);
2533 		}
2534 		goto out;
2535 	}
2536 
2537 	/*
2538 	 * If we are prefetching from the mfu ghost list, this buffer
2539 	 * will end up on the mru list; so steal space from there.
2540 	 */
2541 	if (state == arc_mfu_ghost)
2542 		state = buf->b_hdr->b_flags & ARC_PREFETCH ? arc_mru : arc_mfu;
2543 	else if (state == arc_mru_ghost)
2544 		state = arc_mru;
2545 
2546 	if (state == arc_mru || state == arc_anon) {
2547 		uint64_t mru_used = arc_anon->arcs_size + arc_mru->arcs_size;
2548 		state = (arc_mfu->arcs_lsize[type] >= size &&
2549 		    arc_p > mru_used) ? arc_mfu : arc_mru;
2550 	} else {
2551 		/* MFU cases */
2552 		uint64_t mfu_space = arc_c - arc_p;
2553 		state =  (arc_mru->arcs_lsize[type] >= size &&
2554 		    mfu_space > arc_mfu->arcs_size) ? arc_mru : arc_mfu;
2555 	}
2556 	if ((buf->b_data = arc_evict(state, NULL, size, TRUE, type)) == NULL) {
2557 		if (type == ARC_BUFC_METADATA) {
2558 			buf->b_data = zio_buf_alloc(size);
2559 			arc_space_consume(size, ARC_SPACE_DATA);
2560 		} else {
2561 			ASSERT(type == ARC_BUFC_DATA);
2562 			buf->b_data = zio_data_buf_alloc(size);
2563 			ARCSTAT_INCR(arcstat_data_size, size);
2564 			atomic_add_64(&arc_size, size);
2565 		}
2566 		ARCSTAT_BUMP(arcstat_recycle_miss);
2567 	}
2568 	ASSERT(buf->b_data != NULL);
2569 out:
2570 	/*
2571 	 * Update the state size.  Note that ghost states have a
2572 	 * "ghost size" and so don't need to be updated.
2573 	 */
2574 	if (!GHOST_STATE(buf->b_hdr->b_state)) {
2575 		arc_buf_hdr_t *hdr = buf->b_hdr;
2576 
2577 		atomic_add_64(&hdr->b_state->arcs_size, size);
2578 		if (list_link_active(&hdr->b_arc_node)) {
2579 			ASSERT(refcount_is_zero(&hdr->b_refcnt));
2580 			atomic_add_64(&hdr->b_state->arcs_lsize[type], size);
2581 		}
2582 		/*
2583 		 * If we are growing the cache, and we are adding anonymous
2584 		 * data, and we have outgrown arc_p, update arc_p
2585 		 */
2586 		if (arc_size < arc_c && hdr->b_state == arc_anon &&
2587 		    arc_anon->arcs_size + arc_mru->arcs_size > arc_p)
2588 			arc_p = MIN(arc_c, arc_p + size);
2589 	}
2590 }
2591 
2592 /*
2593  * This routine is called whenever a buffer is accessed.
2594  * NOTE: the hash lock is dropped in this function.
2595  */
2596 static void
2597 arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock)
2598 {
2599 	clock_t now;
2600 
2601 	ASSERT(MUTEX_HELD(hash_lock));
2602 
2603 	if (buf->b_state == arc_anon) {
2604 		/*
2605 		 * This buffer is not in the cache, and does not
2606 		 * appear in our "ghost" list.  Add the new buffer
2607 		 * to the MRU state.
2608 		 */
2609 
2610 		ASSERT(buf->b_arc_access == 0);
2611 		buf->b_arc_access = ddi_get_lbolt();
2612 		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2613 		arc_change_state(arc_mru, buf, hash_lock);
2614 
2615 	} else if (buf->b_state == arc_mru) {
2616 		now = ddi_get_lbolt();
2617 
2618 		/*
2619 		 * If this buffer is here because of a prefetch, then either:
2620 		 * - clear the flag if this is a "referencing" read
2621 		 *   (any subsequent access will bump this into the MFU state).
2622 		 * or
2623 		 * - move the buffer to the head of the list if this is
2624 		 *   another prefetch (to make it less likely to be evicted).
2625 		 */
2626 		if ((buf->b_flags & ARC_PREFETCH) != 0) {
2627 			if (refcount_count(&buf->b_refcnt) == 0) {
2628 				ASSERT(list_link_active(&buf->b_arc_node));
2629 			} else {
2630 				buf->b_flags &= ~ARC_PREFETCH;
2631 				ARCSTAT_BUMP(arcstat_mru_hits);
2632 			}
2633 			buf->b_arc_access = now;
2634 			return;
2635 		}
2636 
2637 		/*
2638 		 * This buffer has been "accessed" only once so far,
2639 		 * but it is still in the cache. Move it to the MFU
2640 		 * state.
2641 		 */
2642 		if (now > buf->b_arc_access + ARC_MINTIME) {
2643 			/*
2644 			 * More than 125ms have passed since we
2645 			 * instantiated this buffer.  Move it to the
2646 			 * most frequently used state.
2647 			 */
2648 			buf->b_arc_access = now;
2649 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2650 			arc_change_state(arc_mfu, buf, hash_lock);
2651 		}
2652 		ARCSTAT_BUMP(arcstat_mru_hits);
2653 	} else if (buf->b_state == arc_mru_ghost) {
2654 		arc_state_t	*new_state;
2655 		/*
2656 		 * This buffer has been "accessed" recently, but
2657 		 * was evicted from the cache.  Move it to the
2658 		 * MFU state.
2659 		 */
2660 
2661 		if (buf->b_flags & ARC_PREFETCH) {
2662 			new_state = arc_mru;
2663 			if (refcount_count(&buf->b_refcnt) > 0)
2664 				buf->b_flags &= ~ARC_PREFETCH;
2665 			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2666 		} else {
2667 			new_state = arc_mfu;
2668 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2669 		}
2670 
2671 		buf->b_arc_access = ddi_get_lbolt();
2672 		arc_change_state(new_state, buf, hash_lock);
2673 
2674 		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
2675 	} else if (buf->b_state == arc_mfu) {
2676 		/*
2677 		 * This buffer has been accessed more than once and is
2678 		 * still in the cache.  Keep it in the MFU state.
2679 		 *
2680 		 * NOTE: an add_reference() that occurred when we did
2681 		 * the arc_read() will have kicked this off the list.
2682 		 * If it was a prefetch, we will explicitly move it to
2683 		 * the head of the list now.
2684 		 */
2685 		if ((buf->b_flags & ARC_PREFETCH) != 0) {
2686 			ASSERT(refcount_count(&buf->b_refcnt) == 0);
2687 			ASSERT(list_link_active(&buf->b_arc_node));
2688 		}
2689 		ARCSTAT_BUMP(arcstat_mfu_hits);
2690 		buf->b_arc_access = ddi_get_lbolt();
2691 	} else if (buf->b_state == arc_mfu_ghost) {
2692 		arc_state_t	*new_state = arc_mfu;
2693 		/*
2694 		 * This buffer has been accessed more than once but has
2695 		 * been evicted from the cache.  Move it back to the
2696 		 * MFU state.
2697 		 */
2698 
2699 		if (buf->b_flags & ARC_PREFETCH) {
2700 			/*
2701 			 * This is a prefetch access...
2702 			 * move this block back to the MRU state.
2703 			 */
2704 			ASSERT0(refcount_count(&buf->b_refcnt));
2705 			new_state = arc_mru;
2706 		}
2707 
2708 		buf->b_arc_access = ddi_get_lbolt();
2709 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2710 		arc_change_state(new_state, buf, hash_lock);
2711 
2712 		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
2713 	} else if (buf->b_state == arc_l2c_only) {
2714 		/*
2715 		 * This buffer is on the 2nd Level ARC.
2716 		 */
2717 
2718 		buf->b_arc_access = ddi_get_lbolt();
2719 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2720 		arc_change_state(arc_mfu, buf, hash_lock);
2721 	} else {
2722 		ASSERT(!"invalid arc state");
2723 	}
2724 }
2725 
2726 /* a generic arc_done_func_t which you can use */
2727 /* ARGSUSED */
2728 void
2729 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
2730 {
2731 	if (zio == NULL || zio->io_error == 0)
2732 		bcopy(buf->b_data, arg, buf->b_hdr->b_size);
2733 	VERIFY(arc_buf_remove_ref(buf, arg));
2734 }
2735 
2736 /* a generic arc_done_func_t */
2737 void
2738 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
2739 {
2740 	arc_buf_t **bufp = arg;
2741 	if (zio && zio->io_error) {
2742 		VERIFY(arc_buf_remove_ref(buf, arg));
2743 		*bufp = NULL;
2744 	} else {
2745 		*bufp = buf;
2746 		ASSERT(buf->b_data);
2747 	}
2748 }
2749 
2750 static void
2751 arc_read_done(zio_t *zio)
2752 {
2753 	arc_buf_hdr_t	*hdr;
2754 	arc_buf_t	*buf;
2755 	arc_buf_t	*abuf;	/* buffer we're assigning to callback */
2756 	kmutex_t	*hash_lock = NULL;
2757 	arc_callback_t	*callback_list, *acb;
2758 	int		freeable = FALSE;
2759 
2760 	buf = zio->io_private;
2761 	hdr = buf->b_hdr;
2762 
2763 	/*
2764 	 * The hdr was inserted into hash-table and removed from lists
2765 	 * prior to starting I/O.  We should find this header, since
2766 	 * it's in the hash table, and it should be legit since it's
2767 	 * not possible to evict it during the I/O.  The only possible
2768 	 * reason for it not to be found is if we were freed during the
2769 	 * read.
2770 	 */
2771 	if (HDR_IN_HASH_TABLE(hdr)) {
2772 		ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
2773 		ASSERT3U(hdr->b_dva.dva_word[0], ==,
2774 		    BP_IDENTITY(zio->io_bp)->dva_word[0]);
2775 		ASSERT3U(hdr->b_dva.dva_word[1], ==,
2776 		    BP_IDENTITY(zio->io_bp)->dva_word[1]);
2777 
2778 		arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
2779 		    &hash_lock);
2780 
2781 		ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) &&
2782 		    hash_lock == NULL) ||
2783 		    (found == hdr &&
2784 		    DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
2785 		    (found == hdr && HDR_L2_READING(hdr)));
2786 	}
2787 
2788 	hdr->b_flags &= ~ARC_L2_EVICTED;
2789 	if (l2arc_noprefetch && (hdr->b_flags & ARC_PREFETCH))
2790 		hdr->b_flags &= ~ARC_L2CACHE;
2791 
2792 	/* byteswap if necessary */
2793 	callback_list = hdr->b_acb;
2794 	ASSERT(callback_list != NULL);
2795 	if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
2796 		dmu_object_byteswap_t bswap =
2797 		    DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
2798 		arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
2799 		    byteswap_uint64_array :
2800 		    dmu_ot_byteswap[bswap].ob_func;
2801 		func(buf->b_data, hdr->b_size);
2802 	}
2803 
2804 	arc_cksum_compute(buf, B_FALSE);
2805 	arc_buf_watch(buf);
2806 
2807 	if (hash_lock && zio->io_error == 0 && hdr->b_state == arc_anon) {
2808 		/*
2809 		 * Only call arc_access on anonymous buffers.  This is because
2810 		 * if we've issued an I/O for an evicted buffer, we've already
2811 		 * called arc_access (to prevent any simultaneous readers from
2812 		 * getting confused).
2813 		 */
2814 		arc_access(hdr, hash_lock);
2815 	}
2816 
2817 	/* create copies of the data buffer for the callers */
2818 	abuf = buf;
2819 	for (acb = callback_list; acb; acb = acb->acb_next) {
2820 		if (acb->acb_done) {
2821 			if (abuf == NULL) {
2822 				ARCSTAT_BUMP(arcstat_duplicate_reads);
2823 				abuf = arc_buf_clone(buf);
2824 			}
2825 			acb->acb_buf = abuf;
2826 			abuf = NULL;
2827 		}
2828 	}
2829 	hdr->b_acb = NULL;
2830 	hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
2831 	ASSERT(!HDR_BUF_AVAILABLE(hdr));
2832 	if (abuf == buf) {
2833 		ASSERT(buf->b_efunc == NULL);
2834 		ASSERT(hdr->b_datacnt == 1);
2835 		hdr->b_flags |= ARC_BUF_AVAILABLE;
2836 	}
2837 
2838 	ASSERT(refcount_is_zero(&hdr->b_refcnt) || callback_list != NULL);
2839 
2840 	if (zio->io_error != 0) {
2841 		hdr->b_flags |= ARC_IO_ERROR;
2842 		if (hdr->b_state != arc_anon)
2843 			arc_change_state(arc_anon, hdr, hash_lock);
2844 		if (HDR_IN_HASH_TABLE(hdr))
2845 			buf_hash_remove(hdr);
2846 		freeable = refcount_is_zero(&hdr->b_refcnt);
2847 	}
2848 
2849 	/*
2850 	 * Broadcast before we drop the hash_lock to avoid the possibility
2851 	 * that the hdr (and hence the cv) might be freed before we get to
2852 	 * the cv_broadcast().
2853 	 */
2854 	cv_broadcast(&hdr->b_cv);
2855 
2856 	if (hash_lock) {
2857 		mutex_exit(hash_lock);
2858 	} else {
2859 		/*
2860 		 * This block was freed while we waited for the read to
2861 		 * complete.  It has been removed from the hash table and
2862 		 * moved to the anonymous state (so that it won't show up
2863 		 * in the cache).
2864 		 */
2865 		ASSERT3P(hdr->b_state, ==, arc_anon);
2866 		freeable = refcount_is_zero(&hdr->b_refcnt);
2867 	}
2868 
2869 	/* execute each callback and free its structure */
2870 	while ((acb = callback_list) != NULL) {
2871 		if (acb->acb_done)
2872 			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
2873 
2874 		if (acb->acb_zio_dummy != NULL) {
2875 			acb->acb_zio_dummy->io_error = zio->io_error;
2876 			zio_nowait(acb->acb_zio_dummy);
2877 		}
2878 
2879 		callback_list = acb->acb_next;
2880 		kmem_free(acb, sizeof (arc_callback_t));
2881 	}
2882 
2883 	if (freeable)
2884 		arc_hdr_destroy(hdr);
2885 }
2886 
2887 /*
2888  * "Read" the block at the specified DVA (in bp) via the
2889  * cache.  If the block is found in the cache, invoke the provided
2890  * callback immediately and return.  Note that the `zio' parameter
2891  * in the callback will be NULL in this case, since no IO was
2892  * required.  If the block is not in the cache pass the read request
2893  * on to the spa with a substitute callback function, so that the
2894  * requested block will be added to the cache.
2895  *
2896  * If a read request arrives for a block that has a read in-progress,
2897  * either wait for the in-progress read to complete (and return the
2898  * results); or, if this is a read with a "done" func, add a record
2899  * to the read to invoke the "done" func when the read completes,
2900  * and return; or just return.
2901  *
2902  * arc_read_done() will invoke all the requested "done" functions
2903  * for readers of this block.
2904  */
2905 int
2906 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
2907     void *private, zio_priority_t priority, int zio_flags, uint32_t *arc_flags,
2908     const zbookmark_phys_t *zb)
2909 {
2910 	arc_buf_hdr_t *hdr = NULL;
2911 	arc_buf_t *buf = NULL;
2912 	kmutex_t *hash_lock = NULL;
2913 	zio_t *rzio;
2914 	uint64_t guid = spa_load_guid(spa);
2915 
2916 	ASSERT(!BP_IS_EMBEDDED(bp) ||
2917 	    BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
2918 
2919 top:
2920 	if (!BP_IS_EMBEDDED(bp)) {
2921 		/*
2922 		 * Embedded BP's have no DVA and require no I/O to "read".
2923 		 * Create an anonymous arc buf to back it.
2924 		 */
2925 		hdr = buf_hash_find(guid, bp, &hash_lock);
2926 	}
2927 
2928 	if (hdr != NULL && hdr->b_datacnt > 0) {
2929 
2930 		*arc_flags |= ARC_CACHED;
2931 
2932 		if (HDR_IO_IN_PROGRESS(hdr)) {
2933 
2934 			if (*arc_flags & ARC_WAIT) {
2935 				cv_wait(&hdr->b_cv, hash_lock);
2936 				mutex_exit(hash_lock);
2937 				goto top;
2938 			}
2939 			ASSERT(*arc_flags & ARC_NOWAIT);
2940 
2941 			if (done) {
2942 				arc_callback_t	*acb = NULL;
2943 
2944 				acb = kmem_zalloc(sizeof (arc_callback_t),
2945 				    KM_SLEEP);
2946 				acb->acb_done = done;
2947 				acb->acb_private = private;
2948 				if (pio != NULL)
2949 					acb->acb_zio_dummy = zio_null(pio,
2950 					    spa, NULL, NULL, NULL, zio_flags);
2951 
2952 				ASSERT(acb->acb_done != NULL);
2953 				acb->acb_next = hdr->b_acb;
2954 				hdr->b_acb = acb;
2955 				add_reference(hdr, hash_lock, private);
2956 				mutex_exit(hash_lock);
2957 				return (0);
2958 			}
2959 			mutex_exit(hash_lock);
2960 			return (0);
2961 		}
2962 
2963 		ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
2964 
2965 		if (done) {
2966 			add_reference(hdr, hash_lock, private);
2967 			/*
2968 			 * If this block is already in use, create a new
2969 			 * copy of the data so that we will be guaranteed
2970 			 * that arc_release() will always succeed.
2971 			 */
2972 			buf = hdr->b_buf;
2973 			ASSERT(buf);
2974 			ASSERT(buf->b_data);
2975 			if (HDR_BUF_AVAILABLE(hdr)) {
2976 				ASSERT(buf->b_efunc == NULL);
2977 				hdr->b_flags &= ~ARC_BUF_AVAILABLE;
2978 			} else {
2979 				buf = arc_buf_clone(buf);
2980 			}
2981 
2982 		} else if (*arc_flags & ARC_PREFETCH &&
2983 		    refcount_count(&hdr->b_refcnt) == 0) {
2984 			hdr->b_flags |= ARC_PREFETCH;
2985 		}
2986 		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
2987 		arc_access(hdr, hash_lock);
2988 		if (*arc_flags & ARC_L2CACHE)
2989 			hdr->b_flags |= ARC_L2CACHE;
2990 		if (*arc_flags & ARC_L2COMPRESS)
2991 			hdr->b_flags |= ARC_L2COMPRESS;
2992 		mutex_exit(hash_lock);
2993 		ARCSTAT_BUMP(arcstat_hits);
2994 		ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
2995 		    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
2996 		    data, metadata, hits);
2997 
2998 		if (done)
2999 			done(NULL, buf, private);
3000 	} else {
3001 		uint64_t size = BP_GET_LSIZE(bp);
3002 		arc_callback_t *acb;
3003 		vdev_t *vd = NULL;
3004 		uint64_t addr = 0;
3005 		boolean_t devw = B_FALSE;
3006 		enum zio_compress b_compress = ZIO_COMPRESS_OFF;
3007 		uint64_t b_asize = 0;
3008 
3009 		if (hdr == NULL) {
3010 			/* this block is not in the cache */
3011 			arc_buf_hdr_t *exists = NULL;
3012 			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
3013 			buf = arc_buf_alloc(spa, size, private, type);
3014 			hdr = buf->b_hdr;
3015 			if (!BP_IS_EMBEDDED(bp)) {
3016 				hdr->b_dva = *BP_IDENTITY(bp);
3017 				hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
3018 				hdr->b_cksum0 = bp->blk_cksum.zc_word[0];
3019 				exists = buf_hash_insert(hdr, &hash_lock);
3020 			}
3021 			if (exists != NULL) {
3022 				/* somebody beat us to the hash insert */
3023 				mutex_exit(hash_lock);
3024 				buf_discard_identity(hdr);
3025 				(void) arc_buf_remove_ref(buf, private);
3026 				goto top; /* restart the IO request */
3027 			}
3028 			/* if this is a prefetch, we don't have a reference */
3029 			if (*arc_flags & ARC_PREFETCH) {
3030 				(void) remove_reference(hdr, hash_lock,
3031 				    private);
3032 				hdr->b_flags |= ARC_PREFETCH;
3033 			}
3034 			if (*arc_flags & ARC_L2CACHE)
3035 				hdr->b_flags |= ARC_L2CACHE;
3036 			if (*arc_flags & ARC_L2COMPRESS)
3037 				hdr->b_flags |= ARC_L2COMPRESS;
3038 			if (BP_GET_LEVEL(bp) > 0)
3039 				hdr->b_flags |= ARC_INDIRECT;
3040 		} else {
3041 			/* this block is in the ghost cache */
3042 			ASSERT(GHOST_STATE(hdr->b_state));
3043 			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3044 			ASSERT0(refcount_count(&hdr->b_refcnt));
3045 			ASSERT(hdr->b_buf == NULL);
3046 
3047 			/* if this is a prefetch, we don't have a reference */
3048 			if (*arc_flags & ARC_PREFETCH)
3049 				hdr->b_flags |= ARC_PREFETCH;
3050 			else
3051 				add_reference(hdr, hash_lock, private);
3052 			if (*arc_flags & ARC_L2CACHE)
3053 				hdr->b_flags |= ARC_L2CACHE;
3054 			if (*arc_flags & ARC_L2COMPRESS)
3055 				hdr->b_flags |= ARC_L2COMPRESS;
3056 			buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
3057 			buf->b_hdr = hdr;
3058 			buf->b_data = NULL;
3059 			buf->b_efunc = NULL;
3060 			buf->b_private = NULL;
3061 			buf->b_next = NULL;
3062 			hdr->b_buf = buf;
3063 			ASSERT(hdr->b_datacnt == 0);
3064 			hdr->b_datacnt = 1;
3065 			arc_get_data_buf(buf);
3066 			arc_access(hdr, hash_lock);
3067 		}
3068 
3069 		ASSERT(!GHOST_STATE(hdr->b_state));
3070 
3071 		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
3072 		acb->acb_done = done;
3073 		acb->acb_private = private;
3074 
3075 		ASSERT(hdr->b_acb == NULL);
3076 		hdr->b_acb = acb;
3077 		hdr->b_flags |= ARC_IO_IN_PROGRESS;
3078 
3079 		if (hdr->b_l2hdr != NULL &&
3080 		    (vd = hdr->b_l2hdr->b_dev->l2ad_vdev) != NULL) {
3081 			devw = hdr->b_l2hdr->b_dev->l2ad_writing;
3082 			addr = hdr->b_l2hdr->b_daddr;
3083 			b_compress = hdr->b_l2hdr->b_compress;
3084 			b_asize = hdr->b_l2hdr->b_asize;
3085 			/*
3086 			 * Lock out device removal.
3087 			 */
3088 			if (vdev_is_dead(vd) ||
3089 			    !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
3090 				vd = NULL;
3091 		}
3092 
3093 		if (hash_lock != NULL)
3094 			mutex_exit(hash_lock);
3095 
3096 		/*
3097 		 * At this point, we have a level 1 cache miss.  Try again in
3098 		 * L2ARC if possible.
3099 		 */
3100 		ASSERT3U(hdr->b_size, ==, size);
3101 		DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
3102 		    uint64_t, size, zbookmark_phys_t *, zb);
3103 		ARCSTAT_BUMP(arcstat_misses);
3104 		ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
3105 		    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3106 		    data, metadata, misses);
3107 
3108 		if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
3109 			/*
3110 			 * Read from the L2ARC if the following are true:
3111 			 * 1. The L2ARC vdev was previously cached.
3112 			 * 2. This buffer still has L2ARC metadata.
3113 			 * 3. This buffer isn't currently writing to the L2ARC.
3114 			 * 4. The L2ARC entry wasn't evicted, which may
3115 			 *    also have invalidated the vdev.
3116 			 * 5. This isn't prefetch and l2arc_noprefetch is set.
3117 			 */
3118 			if (hdr->b_l2hdr != NULL &&
3119 			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
3120 			    !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
3121 				l2arc_read_callback_t *cb;
3122 
3123 				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
3124 				ARCSTAT_BUMP(arcstat_l2_hits);
3125 
3126 				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
3127 				    KM_SLEEP);
3128 				cb->l2rcb_buf = buf;
3129 				cb->l2rcb_spa = spa;
3130 				cb->l2rcb_bp = *bp;
3131 				cb->l2rcb_zb = *zb;
3132 				cb->l2rcb_flags = zio_flags;
3133 				cb->l2rcb_compress = b_compress;
3134 
3135 				ASSERT(addr >= VDEV_LABEL_START_SIZE &&
3136 				    addr + size < vd->vdev_psize -
3137 				    VDEV_LABEL_END_SIZE);
3138 
3139 				/*
3140 				 * l2arc read.  The SCL_L2ARC lock will be
3141 				 * released by l2arc_read_done().
3142 				 * Issue a null zio if the underlying buffer
3143 				 * was squashed to zero size by compression.
3144 				 */
3145 				if (b_compress == ZIO_COMPRESS_EMPTY) {
3146 					rzio = zio_null(pio, spa, vd,
3147 					    l2arc_read_done, cb,
3148 					    zio_flags | ZIO_FLAG_DONT_CACHE |
3149 					    ZIO_FLAG_CANFAIL |
3150 					    ZIO_FLAG_DONT_PROPAGATE |
3151 					    ZIO_FLAG_DONT_RETRY);
3152 				} else {
3153 					rzio = zio_read_phys(pio, vd, addr,
3154 					    b_asize, buf->b_data,
3155 					    ZIO_CHECKSUM_OFF,
3156 					    l2arc_read_done, cb, priority,
3157 					    zio_flags | ZIO_FLAG_DONT_CACHE |
3158 					    ZIO_FLAG_CANFAIL |
3159 					    ZIO_FLAG_DONT_PROPAGATE |
3160 					    ZIO_FLAG_DONT_RETRY, B_FALSE);
3161 				}
3162 				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
3163 				    zio_t *, rzio);
3164 				ARCSTAT_INCR(arcstat_l2_read_bytes, b_asize);
3165 
3166 				if (*arc_flags & ARC_NOWAIT) {
3167 					zio_nowait(rzio);
3168 					return (0);
3169 				}
3170 
3171 				ASSERT(*arc_flags & ARC_WAIT);
3172 				if (zio_wait(rzio) == 0)
3173 					return (0);
3174 
3175 				/* l2arc read error; goto zio_read() */
3176 			} else {
3177 				DTRACE_PROBE1(l2arc__miss,
3178 				    arc_buf_hdr_t *, hdr);
3179 				ARCSTAT_BUMP(arcstat_l2_misses);
3180 				if (HDR_L2_WRITING(hdr))
3181 					ARCSTAT_BUMP(arcstat_l2_rw_clash);
3182 				spa_config_exit(spa, SCL_L2ARC, vd);
3183 			}
3184 		} else {
3185 			if (vd != NULL)
3186 				spa_config_exit(spa, SCL_L2ARC, vd);
3187 			if (l2arc_ndev != 0) {
3188 				DTRACE_PROBE1(l2arc__miss,
3189 				    arc_buf_hdr_t *, hdr);
3190 				ARCSTAT_BUMP(arcstat_l2_misses);
3191 			}
3192 		}
3193 
3194 		rzio = zio_read(pio, spa, bp, buf->b_data, size,
3195 		    arc_read_done, buf, priority, zio_flags, zb);
3196 
3197 		if (*arc_flags & ARC_WAIT)
3198 			return (zio_wait(rzio));
3199 
3200 		ASSERT(*arc_flags & ARC_NOWAIT);
3201 		zio_nowait(rzio);
3202 	}
3203 	return (0);
3204 }
3205 
3206 void
3207 arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
3208 {
3209 	ASSERT(buf->b_hdr != NULL);
3210 	ASSERT(buf->b_hdr->b_state != arc_anon);
3211 	ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt) || func == NULL);
3212 	ASSERT(buf->b_efunc == NULL);
3213 	ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
3214 
3215 	buf->b_efunc = func;
3216 	buf->b_private = private;
3217 }
3218 
3219 /*
3220  * Notify the arc that a block was freed, and thus will never be used again.
3221  */
3222 void
3223 arc_freed(spa_t *spa, const blkptr_t *bp)
3224 {
3225 	arc_buf_hdr_t *hdr;
3226 	kmutex_t *hash_lock;
3227 	uint64_t guid = spa_load_guid(spa);
3228 
3229 	ASSERT(!BP_IS_EMBEDDED(bp));
3230 
3231 	hdr = buf_hash_find(guid, bp, &hash_lock);
3232 	if (hdr == NULL)
3233 		return;
3234 	if (HDR_BUF_AVAILABLE(hdr)) {
3235 		arc_buf_t *buf = hdr->b_buf;
3236 		add_reference(hdr, hash_lock, FTAG);
3237 		hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3238 		mutex_exit(hash_lock);
3239 
3240 		arc_release(buf, FTAG);
3241 		(void) arc_buf_remove_ref(buf, FTAG);
3242 	} else {
3243 		mutex_exit(hash_lock);
3244 	}
3245 
3246 }
3247 
3248 /*
3249  * Clear the user eviction callback set by arc_set_callback(), first calling
3250  * it if it exists.  Because the presence of a callback keeps an arc_buf cached
3251  * clearing the callback may result in the arc_buf being destroyed.  However,
3252  * it will not result in the *last* arc_buf being destroyed, hence the data
3253  * will remain cached in the ARC. We make a copy of the arc buffer here so
3254  * that we can process the callback without holding any locks.
3255  *
3256  * It's possible that the callback is already in the process of being cleared
3257  * by another thread.  In this case we can not clear the callback.
3258  *
3259  * Returns B_TRUE if the callback was successfully called and cleared.
3260  */
3261 boolean_t
3262 arc_clear_callback(arc_buf_t *buf)
3263 {
3264 	arc_buf_hdr_t *hdr;
3265 	kmutex_t *hash_lock;
3266 	arc_evict_func_t *efunc = buf->b_efunc;
3267 	void *private = buf->b_private;
3268 
3269 	mutex_enter(&buf->b_evict_lock);
3270 	hdr = buf->b_hdr;
3271 	if (hdr == NULL) {
3272 		/*
3273 		 * We are in arc_do_user_evicts().
3274 		 */
3275 		ASSERT(buf->b_data == NULL);
3276 		mutex_exit(&buf->b_evict_lock);
3277 		return (B_FALSE);
3278 	} else if (buf->b_data == NULL) {
3279 		/*
3280 		 * We are on the eviction list; process this buffer now
3281 		 * but let arc_do_user_evicts() do the reaping.
3282 		 */
3283 		buf->b_efunc = NULL;
3284 		mutex_exit(&buf->b_evict_lock);
3285 		VERIFY0(efunc(private));
3286 		return (B_TRUE);
3287 	}
3288 	hash_lock = HDR_LOCK(hdr);
3289 	mutex_enter(hash_lock);
3290 	hdr = buf->b_hdr;
3291 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3292 
3293 	ASSERT3U(refcount_count(&hdr->b_refcnt), <, hdr->b_datacnt);
3294 	ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3295 
3296 	buf->b_efunc = NULL;
3297 	buf->b_private = NULL;
3298 
3299 	if (hdr->b_datacnt > 1) {
3300 		mutex_exit(&buf->b_evict_lock);
3301 		arc_buf_destroy(buf, FALSE, TRUE);
3302 	} else {
3303 		ASSERT(buf == hdr->b_buf);
3304 		hdr->b_flags |= ARC_BUF_AVAILABLE;
3305 		mutex_exit(&buf->b_evict_lock);
3306 	}
3307 
3308 	mutex_exit(hash_lock);
3309 	VERIFY0(efunc(private));
3310 	return (B_TRUE);
3311 }
3312 
3313 /*
3314  * Release this buffer from the cache, making it an anonymous buffer.  This
3315  * must be done after a read and prior to modifying the buffer contents.
3316  * If the buffer has more than one reference, we must make
3317  * a new hdr for the buffer.
3318  */
3319 void
3320 arc_release(arc_buf_t *buf, void *tag)
3321 {
3322 	arc_buf_hdr_t *hdr;
3323 	kmutex_t *hash_lock = NULL;
3324 	l2arc_buf_hdr_t *l2hdr;
3325 	uint64_t buf_size;
3326 
3327 	/*
3328 	 * It would be nice to assert that if it's DMU metadata (level >
3329 	 * 0 || it's the dnode file), then it must be syncing context.
3330 	 * But we don't know that information at this level.
3331 	 */
3332 
3333 	mutex_enter(&buf->b_evict_lock);
3334 	hdr = buf->b_hdr;
3335 
3336 	/* this buffer is not on any list */
3337 	ASSERT(refcount_count(&hdr->b_refcnt) > 0);
3338 
3339 	if (hdr->b_state == arc_anon) {
3340 		/* this buffer is already released */
3341 		ASSERT(buf->b_efunc == NULL);
3342 	} else {
3343 		hash_lock = HDR_LOCK(hdr);
3344 		mutex_enter(hash_lock);
3345 		hdr = buf->b_hdr;
3346 		ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3347 	}
3348 
3349 	l2hdr = hdr->b_l2hdr;
3350 	if (l2hdr) {
3351 		mutex_enter(&l2arc_buflist_mtx);
3352 		hdr->b_l2hdr = NULL;
3353 		list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
3354 	}
3355 	buf_size = hdr->b_size;
3356 
3357 	/*
3358 	 * Do we have more than one buf?
3359 	 */
3360 	if (hdr->b_datacnt > 1) {
3361 		arc_buf_hdr_t *nhdr;
3362 		arc_buf_t **bufp;
3363 		uint64_t blksz = hdr->b_size;
3364 		uint64_t spa = hdr->b_spa;
3365 		arc_buf_contents_t type = hdr->b_type;
3366 		uint32_t flags = hdr->b_flags;
3367 
3368 		ASSERT(hdr->b_buf != buf || buf->b_next != NULL);
3369 		/*
3370 		 * Pull the data off of this hdr and attach it to
3371 		 * a new anonymous hdr.
3372 		 */
3373 		(void) remove_reference(hdr, hash_lock, tag);
3374 		bufp = &hdr->b_buf;
3375 		while (*bufp != buf)
3376 			bufp = &(*bufp)->b_next;
3377 		*bufp = buf->b_next;
3378 		buf->b_next = NULL;
3379 
3380 		ASSERT3U(hdr->b_state->arcs_size, >=, hdr->b_size);
3381 		atomic_add_64(&hdr->b_state->arcs_size, -hdr->b_size);
3382 		if (refcount_is_zero(&hdr->b_refcnt)) {
3383 			uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
3384 			ASSERT3U(*size, >=, hdr->b_size);
3385 			atomic_add_64(size, -hdr->b_size);
3386 		}
3387 
3388 		/*
3389 		 * We're releasing a duplicate user data buffer, update
3390 		 * our statistics accordingly.
3391 		 */
3392 		if (hdr->b_type == ARC_BUFC_DATA) {
3393 			ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
3394 			ARCSTAT_INCR(arcstat_duplicate_buffers_size,
3395 			    -hdr->b_size);
3396 		}
3397 		hdr->b_datacnt -= 1;
3398 		arc_cksum_verify(buf);
3399 		arc_buf_unwatch(buf);
3400 
3401 		mutex_exit(hash_lock);
3402 
3403 		nhdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
3404 		nhdr->b_size = blksz;
3405 		nhdr->b_spa = spa;
3406 		nhdr->b_type = type;
3407 		nhdr->b_buf = buf;
3408 		nhdr->b_state = arc_anon;
3409 		nhdr->b_arc_access = 0;
3410 		nhdr->b_flags = flags & ARC_L2_WRITING;
3411 		nhdr->b_l2hdr = NULL;
3412 		nhdr->b_datacnt = 1;
3413 		nhdr->b_freeze_cksum = NULL;
3414 		(void) refcount_add(&nhdr->b_refcnt, tag);
3415 		buf->b_hdr = nhdr;
3416 		mutex_exit(&buf->b_evict_lock);
3417 		atomic_add_64(&arc_anon->arcs_size, blksz);
3418 	} else {
3419 		mutex_exit(&buf->b_evict_lock);
3420 		ASSERT(refcount_count(&hdr->b_refcnt) == 1);
3421 		ASSERT(!list_link_active(&hdr->b_arc_node));
3422 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3423 		if (hdr->b_state != arc_anon)
3424 			arc_change_state(arc_anon, hdr, hash_lock);
3425 		hdr->b_arc_access = 0;
3426 		if (hash_lock)
3427 			mutex_exit(hash_lock);
3428 
3429 		buf_discard_identity(hdr);
3430 		arc_buf_thaw(buf);
3431 	}
3432 	buf->b_efunc = NULL;
3433 	buf->b_private = NULL;
3434 
3435 	if (l2hdr) {
3436 		ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
3437 		vdev_space_update(l2hdr->b_dev->l2ad_vdev,
3438 		    -l2hdr->b_asize, 0, 0);
3439 		kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
3440 		ARCSTAT_INCR(arcstat_l2_size, -buf_size);
3441 		mutex_exit(&l2arc_buflist_mtx);
3442 	}
3443 }
3444 
3445 int
3446 arc_released(arc_buf_t *buf)
3447 {
3448 	int released;
3449 
3450 	mutex_enter(&buf->b_evict_lock);
3451 	released = (buf->b_data != NULL && buf->b_hdr->b_state == arc_anon);
3452 	mutex_exit(&buf->b_evict_lock);
3453 	return (released);
3454 }
3455 
3456 #ifdef ZFS_DEBUG
3457 int
3458 arc_referenced(arc_buf_t *buf)
3459 {
3460 	int referenced;
3461 
3462 	mutex_enter(&buf->b_evict_lock);
3463 	referenced = (refcount_count(&buf->b_hdr->b_refcnt));
3464 	mutex_exit(&buf->b_evict_lock);
3465 	return (referenced);
3466 }
3467 #endif
3468 
3469 static void
3470 arc_write_ready(zio_t *zio)
3471 {
3472 	arc_write_callback_t *callback = zio->io_private;
3473 	arc_buf_t *buf = callback->awcb_buf;
3474 	arc_buf_hdr_t *hdr = buf->b_hdr;
3475 
3476 	ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt));
3477 	callback->awcb_ready(zio, buf, callback->awcb_private);
3478 
3479 	/*
3480 	 * If the IO is already in progress, then this is a re-write
3481 	 * attempt, so we need to thaw and re-compute the cksum.
3482 	 * It is the responsibility of the callback to handle the
3483 	 * accounting for any re-write attempt.
3484 	 */
3485 	if (HDR_IO_IN_PROGRESS(hdr)) {
3486 		mutex_enter(&hdr->b_freeze_lock);
3487 		if (hdr->b_freeze_cksum != NULL) {
3488 			kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
3489 			hdr->b_freeze_cksum = NULL;
3490 		}
3491 		mutex_exit(&hdr->b_freeze_lock);
3492 	}
3493 	arc_cksum_compute(buf, B_FALSE);
3494 	hdr->b_flags |= ARC_IO_IN_PROGRESS;
3495 }
3496 
3497 /*
3498  * The SPA calls this callback for each physical write that happens on behalf
3499  * of a logical write.  See the comment in dbuf_write_physdone() for details.
3500  */
3501 static void
3502 arc_write_physdone(zio_t *zio)
3503 {
3504 	arc_write_callback_t *cb = zio->io_private;
3505 	if (cb->awcb_physdone != NULL)
3506 		cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
3507 }
3508 
3509 static void
3510 arc_write_done(zio_t *zio)
3511 {
3512 	arc_write_callback_t *callback = zio->io_private;
3513 	arc_buf_t *buf = callback->awcb_buf;
3514 	arc_buf_hdr_t *hdr = buf->b_hdr;
3515 
3516 	ASSERT(hdr->b_acb == NULL);
3517 
3518 	if (zio->io_error == 0) {
3519 		if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
3520 			buf_discard_identity(hdr);
3521 		} else {
3522 			hdr->b_dva = *BP_IDENTITY(zio->io_bp);
3523 			hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
3524 			hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
3525 		}
3526 	} else {
3527 		ASSERT(BUF_EMPTY(hdr));
3528 	}
3529 
3530 	/*
3531 	 * If the block to be written was all-zero or compressed enough to be
3532 	 * embedded in the BP, no write was performed so there will be no
3533 	 * dva/birth/checksum.  The buffer must therefore remain anonymous
3534 	 * (and uncached).
3535 	 */
3536 	if (!BUF_EMPTY(hdr)) {
3537 		arc_buf_hdr_t *exists;
3538 		kmutex_t *hash_lock;
3539 
3540 		ASSERT(zio->io_error == 0);
3541 
3542 		arc_cksum_verify(buf);
3543 
3544 		exists = buf_hash_insert(hdr, &hash_lock);
3545 		if (exists) {
3546 			/*
3547 			 * This can only happen if we overwrite for
3548 			 * sync-to-convergence, because we remove
3549 			 * buffers from the hash table when we arc_free().
3550 			 */
3551 			if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
3552 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3553 					panic("bad overwrite, hdr=%p exists=%p",
3554 					    (void *)hdr, (void *)exists);
3555 				ASSERT(refcount_is_zero(&exists->b_refcnt));
3556 				arc_change_state(arc_anon, exists, hash_lock);
3557 				mutex_exit(hash_lock);
3558 				arc_hdr_destroy(exists);
3559 				exists = buf_hash_insert(hdr, &hash_lock);
3560 				ASSERT3P(exists, ==, NULL);
3561 			} else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
3562 				/* nopwrite */
3563 				ASSERT(zio->io_prop.zp_nopwrite);
3564 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3565 					panic("bad nopwrite, hdr=%p exists=%p",
3566 					    (void *)hdr, (void *)exists);
3567 			} else {
3568 				/* Dedup */
3569 				ASSERT(hdr->b_datacnt == 1);
3570 				ASSERT(hdr->b_state == arc_anon);
3571 				ASSERT(BP_GET_DEDUP(zio->io_bp));
3572 				ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
3573 			}
3574 		}
3575 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3576 		/* if it's not anon, we are doing a scrub */
3577 		if (!exists && hdr->b_state == arc_anon)
3578 			arc_access(hdr, hash_lock);
3579 		mutex_exit(hash_lock);
3580 	} else {
3581 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3582 	}
3583 
3584 	ASSERT(!refcount_is_zero(&hdr->b_refcnt));
3585 	callback->awcb_done(zio, buf, callback->awcb_private);
3586 
3587 	kmem_free(callback, sizeof (arc_write_callback_t));
3588 }
3589 
3590 zio_t *
3591 arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
3592     blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
3593     const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *physdone,
3594     arc_done_func_t *done, void *private, zio_priority_t priority,
3595     int zio_flags, const zbookmark_phys_t *zb)
3596 {
3597 	arc_buf_hdr_t *hdr = buf->b_hdr;
3598 	arc_write_callback_t *callback;
3599 	zio_t *zio;
3600 
3601 	ASSERT(ready != NULL);
3602 	ASSERT(done != NULL);
3603 	ASSERT(!HDR_IO_ERROR(hdr));
3604 	ASSERT((hdr->b_flags & ARC_IO_IN_PROGRESS) == 0);
3605 	ASSERT(hdr->b_acb == NULL);
3606 	if (l2arc)
3607 		hdr->b_flags |= ARC_L2CACHE;
3608 	if (l2arc_compress)
3609 		hdr->b_flags |= ARC_L2COMPRESS;
3610 	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
3611 	callback->awcb_ready = ready;
3612 	callback->awcb_physdone = physdone;
3613 	callback->awcb_done = done;
3614 	callback->awcb_private = private;
3615 	callback->awcb_buf = buf;
3616 
3617 	zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
3618 	    arc_write_ready, arc_write_physdone, arc_write_done, callback,
3619 	    priority, zio_flags, zb);
3620 
3621 	return (zio);
3622 }
3623 
3624 static int
3625 arc_memory_throttle(uint64_t reserve, uint64_t txg)
3626 {
3627 #ifdef _KERNEL
3628 	uint64_t available_memory = ptob(freemem);
3629 	static uint64_t page_load = 0;
3630 	static uint64_t last_txg = 0;
3631 
3632 #if defined(__i386)
3633 	available_memory =
3634 	    MIN(available_memory, vmem_size(heap_arena, VMEM_FREE));
3635 #endif
3636 
3637 	if (freemem > physmem * arc_lotsfree_percent / 100)
3638 		return (0);
3639 
3640 	if (txg > last_txg) {
3641 		last_txg = txg;
3642 		page_load = 0;
3643 	}
3644 	/*
3645 	 * If we are in pageout, we know that memory is already tight,
3646 	 * the arc is already going to be evicting, so we just want to
3647 	 * continue to let page writes occur as quickly as possible.
3648 	 */
3649 	if (curproc == proc_pageout) {
3650 		if (page_load > MAX(ptob(minfree), available_memory) / 4)
3651 			return (SET_ERROR(ERESTART));
3652 		/* Note: reserve is inflated, so we deflate */
3653 		page_load += reserve / 8;
3654 		return (0);
3655 	} else if (page_load > 0 && arc_reclaim_needed()) {
3656 		/* memory is low, delay before restarting */
3657 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
3658 		return (SET_ERROR(EAGAIN));
3659 	}
3660 	page_load = 0;
3661 #endif
3662 	return (0);
3663 }
3664 
3665 void
3666 arc_tempreserve_clear(uint64_t reserve)
3667 {
3668 	atomic_add_64(&arc_tempreserve, -reserve);
3669 	ASSERT((int64_t)arc_tempreserve >= 0);
3670 }
3671 
3672 int
3673 arc_tempreserve_space(uint64_t reserve, uint64_t txg)
3674 {
3675 	int error;
3676 	uint64_t anon_size;
3677 
3678 	if (reserve > arc_c/4 && !arc_no_grow)
3679 		arc_c = MIN(arc_c_max, reserve * 4);
3680 	if (reserve > arc_c)
3681 		return (SET_ERROR(ENOMEM));
3682 
3683 	/*
3684 	 * Don't count loaned bufs as in flight dirty data to prevent long
3685 	 * network delays from blocking transactions that are ready to be
3686 	 * assigned to a txg.
3687 	 */
3688 	anon_size = MAX((int64_t)(arc_anon->arcs_size - arc_loaned_bytes), 0);
3689 
3690 	/*
3691 	 * Writes will, almost always, require additional memory allocations
3692 	 * in order to compress/encrypt/etc the data.  We therefore need to
3693 	 * make sure that there is sufficient available memory for this.
3694 	 */
3695 	error = arc_memory_throttle(reserve, txg);
3696 	if (error != 0)
3697 		return (error);
3698 
3699 	/*
3700 	 * Throttle writes when the amount of dirty data in the cache
3701 	 * gets too large.  We try to keep the cache less than half full
3702 	 * of dirty blocks so that our sync times don't grow too large.
3703 	 * Note: if two requests come in concurrently, we might let them
3704 	 * both succeed, when one of them should fail.  Not a huge deal.
3705 	 */
3706 
3707 	if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
3708 	    anon_size > arc_c / 4) {
3709 		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
3710 		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
3711 		    arc_tempreserve>>10,
3712 		    arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
3713 		    arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
3714 		    reserve>>10, arc_c>>10);
3715 		return (SET_ERROR(ERESTART));
3716 	}
3717 	atomic_add_64(&arc_tempreserve, reserve);
3718 	return (0);
3719 }
3720 
3721 void
3722 arc_init(void)
3723 {
3724 	mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
3725 	cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
3726 
3727 	/* Convert seconds to clock ticks */
3728 	arc_min_prefetch_lifespan = 1 * hz;
3729 
3730 	/* Start out with 1/8 of all memory */
3731 	arc_c = physmem * PAGESIZE / 8;
3732 
3733 #ifdef _KERNEL
3734 	/*
3735 	 * On architectures where the physical memory can be larger
3736 	 * than the addressable space (intel in 32-bit mode), we may
3737 	 * need to limit the cache to 1/8 of VM size.
3738 	 */
3739 	arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
3740 #endif
3741 
3742 	/* set min cache to 1/32 of all memory, or 64MB, whichever is more */
3743 	arc_c_min = MAX(arc_c / 4, 64<<20);
3744 	/* set max to 3/4 of all memory, or all but 1GB, whichever is more */
3745 	if (arc_c * 8 >= 1<<30)
3746 		arc_c_max = (arc_c * 8) - (1<<30);
3747 	else
3748 		arc_c_max = arc_c_min;
3749 	arc_c_max = MAX(arc_c * 6, arc_c_max);
3750 
3751 	/*
3752 	 * Allow the tunables to override our calculations if they are
3753 	 * reasonable (ie. over 64MB)
3754 	 */
3755 	if (zfs_arc_max > 64<<20 && zfs_arc_max < physmem * PAGESIZE)
3756 		arc_c_max = zfs_arc_max;
3757 	if (zfs_arc_min > 64<<20 && zfs_arc_min <= arc_c_max)
3758 		arc_c_min = zfs_arc_min;
3759 
3760 	arc_c = arc_c_max;
3761 	arc_p = (arc_c >> 1);
3762 
3763 	/* limit meta-data to 1/4 of the arc capacity */
3764 	arc_meta_limit = arc_c_max / 4;
3765 
3766 	/* Allow the tunable to override if it is reasonable */
3767 	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
3768 		arc_meta_limit = zfs_arc_meta_limit;
3769 
3770 	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
3771 		arc_c_min = arc_meta_limit / 2;
3772 
3773 	if (zfs_arc_grow_retry > 0)
3774 		arc_grow_retry = zfs_arc_grow_retry;
3775 
3776 	if (zfs_arc_shrink_shift > 0)
3777 		arc_shrink_shift = zfs_arc_shrink_shift;
3778 
3779 	if (zfs_arc_p_min_shift > 0)
3780 		arc_p_min_shift = zfs_arc_p_min_shift;
3781 
3782 	/* if kmem_flags are set, lets try to use less memory */
3783 	if (kmem_debugging())
3784 		arc_c = arc_c / 2;
3785 	if (arc_c < arc_c_min)
3786 		arc_c = arc_c_min;
3787 
3788 	arc_anon = &ARC_anon;
3789 	arc_mru = &ARC_mru;
3790 	arc_mru_ghost = &ARC_mru_ghost;
3791 	arc_mfu = &ARC_mfu;
3792 	arc_mfu_ghost = &ARC_mfu_ghost;
3793 	arc_l2c_only = &ARC_l2c_only;
3794 	arc_size = 0;
3795 
3796 	mutex_init(&arc_anon->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3797 	mutex_init(&arc_mru->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3798 	mutex_init(&arc_mru_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3799 	mutex_init(&arc_mfu->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3800 	mutex_init(&arc_mfu_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3801 	mutex_init(&arc_l2c_only->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3802 
3803 	list_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
3804 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3805 	list_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
3806 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3807 	list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
3808 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3809 	list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
3810 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3811 	list_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
3812 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3813 	list_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
3814 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3815 	list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
3816 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3817 	list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
3818 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3819 	list_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
3820 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3821 	list_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
3822 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3823 
3824 	buf_init();
3825 
3826 	arc_thread_exit = 0;
3827 	arc_eviction_list = NULL;
3828 	mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
3829 	bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
3830 
3831 	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
3832 	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
3833 
3834 	if (arc_ksp != NULL) {
3835 		arc_ksp->ks_data = &arc_stats;
3836 		kstat_install(arc_ksp);
3837 	}
3838 
3839 	(void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
3840 	    TS_RUN, minclsyspri);
3841 
3842 	arc_dead = FALSE;
3843 	arc_warm = B_FALSE;
3844 
3845 	/*
3846 	 * Calculate maximum amount of dirty data per pool.
3847 	 *
3848 	 * If it has been set by /etc/system, take that.
3849 	 * Otherwise, use a percentage of physical memory defined by
3850 	 * zfs_dirty_data_max_percent (default 10%) with a cap at
3851 	 * zfs_dirty_data_max_max (default 4GB).
3852 	 */
3853 	if (zfs_dirty_data_max == 0) {
3854 		zfs_dirty_data_max = physmem * PAGESIZE *
3855 		    zfs_dirty_data_max_percent / 100;
3856 		zfs_dirty_data_max = MIN(zfs_dirty_data_max,
3857 		    zfs_dirty_data_max_max);
3858 	}
3859 }
3860 
3861 void
3862 arc_fini(void)
3863 {
3864 	mutex_enter(&arc_reclaim_thr_lock);
3865 	arc_thread_exit = 1;
3866 	while (arc_thread_exit != 0)
3867 		cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
3868 	mutex_exit(&arc_reclaim_thr_lock);
3869 
3870 	arc_flush(NULL);
3871 
3872 	arc_dead = TRUE;
3873 
3874 	if (arc_ksp != NULL) {
3875 		kstat_delete(arc_ksp);
3876 		arc_ksp = NULL;
3877 	}
3878 
3879 	mutex_destroy(&arc_eviction_mtx);
3880 	mutex_destroy(&arc_reclaim_thr_lock);
3881 	cv_destroy(&arc_reclaim_thr_cv);
3882 
3883 	list_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
3884 	list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
3885 	list_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
3886 	list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
3887 	list_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
3888 	list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
3889 	list_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
3890 	list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
3891 
3892 	mutex_destroy(&arc_anon->arcs_mtx);
3893 	mutex_destroy(&arc_mru->arcs_mtx);
3894 	mutex_destroy(&arc_mru_ghost->arcs_mtx);
3895 	mutex_destroy(&arc_mfu->arcs_mtx);
3896 	mutex_destroy(&arc_mfu_ghost->arcs_mtx);
3897 	mutex_destroy(&arc_l2c_only->arcs_mtx);
3898 
3899 	buf_fini();
3900 
3901 	ASSERT(arc_loaned_bytes == 0);
3902 }
3903 
3904 /*
3905  * Level 2 ARC
3906  *
3907  * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
3908  * It uses dedicated storage devices to hold cached data, which are populated
3909  * using large infrequent writes.  The main role of this cache is to boost
3910  * the performance of random read workloads.  The intended L2ARC devices
3911  * include short-stroked disks, solid state disks, and other media with
3912  * substantially faster read latency than disk.
3913  *
3914  *                 +-----------------------+
3915  *                 |         ARC           |
3916  *                 +-----------------------+
3917  *                    |         ^     ^
3918  *                    |         |     |
3919  *      l2arc_feed_thread()    arc_read()
3920  *                    |         |     |
3921  *                    |  l2arc read   |
3922  *                    V         |     |
3923  *               +---------------+    |
3924  *               |     L2ARC     |    |
3925  *               +---------------+    |
3926  *                   |    ^           |
3927  *          l2arc_write() |           |
3928  *                   |    |           |
3929  *                   V    |           |
3930  *                 +-------+      +-------+
3931  *                 | vdev  |      | vdev  |
3932  *                 | cache |      | cache |
3933  *                 +-------+      +-------+
3934  *                 +=========+     .-----.
3935  *                 :  L2ARC  :    |-_____-|
3936  *                 : devices :    | Disks |
3937  *                 +=========+    `-_____-'
3938  *
3939  * Read requests are satisfied from the following sources, in order:
3940  *
3941  *	1) ARC
3942  *	2) vdev cache of L2ARC devices
3943  *	3) L2ARC devices
3944  *	4) vdev cache of disks
3945  *	5) disks
3946  *
3947  * Some L2ARC device types exhibit extremely slow write performance.
3948  * To accommodate for this there are some significant differences between
3949  * the L2ARC and traditional cache design:
3950  *
3951  * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
3952  * the ARC behave as usual, freeing buffers and placing headers on ghost
3953  * lists.  The ARC does not send buffers to the L2ARC during eviction as
3954  * this would add inflated write latencies for all ARC memory pressure.
3955  *
3956  * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
3957  * It does this by periodically scanning buffers from the eviction-end of
3958  * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
3959  * not already there. It scans until a headroom of buffers is satisfied,
3960  * which itself is a buffer for ARC eviction. If a compressible buffer is
3961  * found during scanning and selected for writing to an L2ARC device, we
3962  * temporarily boost scanning headroom during the next scan cycle to make
3963  * sure we adapt to compression effects (which might significantly reduce
3964  * the data volume we write to L2ARC). The thread that does this is
3965  * l2arc_feed_thread(), illustrated below; example sizes are included to
3966  * provide a better sense of ratio than this diagram:
3967  *
3968  *	       head -->                        tail
3969  *	        +---------------------+----------+
3970  *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
3971  *	        +---------------------+----------+   |   o L2ARC eligible
3972  *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
3973  *	        +---------------------+----------+   |
3974  *	             15.9 Gbytes      ^ 32 Mbytes    |
3975  *	                           headroom          |
3976  *	                                      l2arc_feed_thread()
3977  *	                                             |
3978  *	                 l2arc write hand <--[oooo]--'
3979  *	                         |           8 Mbyte
3980  *	                         |          write max
3981  *	                         V
3982  *		  +==============================+
3983  *	L2ARC dev |####|#|###|###|    |####| ... |
3984  *	          +==============================+
3985  *	                     32 Gbytes
3986  *
3987  * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
3988  * evicted, then the L2ARC has cached a buffer much sooner than it probably
3989  * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
3990  * safe to say that this is an uncommon case, since buffers at the end of
3991  * the ARC lists have moved there due to inactivity.
3992  *
3993  * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
3994  * then the L2ARC simply misses copying some buffers.  This serves as a
3995  * pressure valve to prevent heavy read workloads from both stalling the ARC
3996  * with waits and clogging the L2ARC with writes.  This also helps prevent
3997  * the potential for the L2ARC to churn if it attempts to cache content too
3998  * quickly, such as during backups of the entire pool.
3999  *
4000  * 5. After system boot and before the ARC has filled main memory, there are
4001  * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
4002  * lists can remain mostly static.  Instead of searching from tail of these
4003  * lists as pictured, the l2arc_feed_thread() will search from the list heads
4004  * for eligible buffers, greatly increasing its chance of finding them.
4005  *
4006  * The L2ARC device write speed is also boosted during this time so that
4007  * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
4008  * there are no L2ARC reads, and no fear of degrading read performance
4009  * through increased writes.
4010  *
4011  * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
4012  * the vdev queue can aggregate them into larger and fewer writes.  Each
4013  * device is written to in a rotor fashion, sweeping writes through
4014  * available space then repeating.
4015  *
4016  * 7. The L2ARC does not store dirty content.  It never needs to flush
4017  * write buffers back to disk based storage.
4018  *
4019  * 8. If an ARC buffer is written (and dirtied) which also exists in the
4020  * L2ARC, the now stale L2ARC buffer is immediately dropped.
4021  *
4022  * The performance of the L2ARC can be tweaked by a number of tunables, which
4023  * may be necessary for different workloads:
4024  *
4025  *	l2arc_write_max		max write bytes per interval
4026  *	l2arc_write_boost	extra write bytes during device warmup
4027  *	l2arc_noprefetch	skip caching prefetched buffers
4028  *	l2arc_headroom		number of max device writes to precache
4029  *	l2arc_headroom_boost	when we find compressed buffers during ARC
4030  *				scanning, we multiply headroom by this
4031  *				percentage factor for the next scan cycle,
4032  *				since more compressed buffers are likely to
4033  *				be present
4034  *	l2arc_feed_secs		seconds between L2ARC writing
4035  *
4036  * Tunables may be removed or added as future performance improvements are
4037  * integrated, and also may become zpool properties.
4038  *
4039  * There are three key functions that control how the L2ARC warms up:
4040  *
4041  *	l2arc_write_eligible()	check if a buffer is eligible to cache
4042  *	l2arc_write_size()	calculate how much to write
4043  *	l2arc_write_interval()	calculate sleep delay between writes
4044  *
4045  * These three functions determine what to write, how much, and how quickly
4046  * to send writes.
4047  */
4048 
4049 static boolean_t
4050 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *ab)
4051 {
4052 	/*
4053 	 * A buffer is *not* eligible for the L2ARC if it:
4054 	 * 1. belongs to a different spa.
4055 	 * 2. is already cached on the L2ARC.
4056 	 * 3. has an I/O in progress (it may be an incomplete read).
4057 	 * 4. is flagged not eligible (zfs property).
4058 	 */
4059 	if (ab->b_spa != spa_guid || ab->b_l2hdr != NULL ||
4060 	    HDR_IO_IN_PROGRESS(ab) || !HDR_L2CACHE(ab))
4061 		return (B_FALSE);
4062 
4063 	return (B_TRUE);
4064 }
4065 
4066 static uint64_t
4067 l2arc_write_size(void)
4068 {
4069 	uint64_t size;
4070 
4071 	/*
4072 	 * Make sure our globals have meaningful values in case the user
4073 	 * altered them.
4074 	 */
4075 	size = l2arc_write_max;
4076 	if (size == 0) {
4077 		cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
4078 		    "be greater than zero, resetting it to the default (%d)",
4079 		    L2ARC_WRITE_SIZE);
4080 		size = l2arc_write_max = L2ARC_WRITE_SIZE;
4081 	}
4082 
4083 	if (arc_warm == B_FALSE)
4084 		size += l2arc_write_boost;
4085 
4086 	return (size);
4087 
4088 }
4089 
4090 static clock_t
4091 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
4092 {
4093 	clock_t interval, next, now;
4094 
4095 	/*
4096 	 * If the ARC lists are busy, increase our write rate; if the
4097 	 * lists are stale, idle back.  This is achieved by checking
4098 	 * how much we previously wrote - if it was more than half of
4099 	 * what we wanted, schedule the next write much sooner.
4100 	 */
4101 	if (l2arc_feed_again && wrote > (wanted / 2))
4102 		interval = (hz * l2arc_feed_min_ms) / 1000;
4103 	else
4104 		interval = hz * l2arc_feed_secs;
4105 
4106 	now = ddi_get_lbolt();
4107 	next = MAX(now, MIN(now + interval, began + interval));
4108 
4109 	return (next);
4110 }
4111 
4112 static void
4113 l2arc_hdr_stat_add(void)
4114 {
4115 	ARCSTAT_INCR(arcstat_l2_hdr_size, HDR_SIZE + L2HDR_SIZE);
4116 	ARCSTAT_INCR(arcstat_hdr_size, -HDR_SIZE);
4117 }
4118 
4119 static void
4120 l2arc_hdr_stat_remove(void)
4121 {
4122 	ARCSTAT_INCR(arcstat_l2_hdr_size, -(HDR_SIZE + L2HDR_SIZE));
4123 	ARCSTAT_INCR(arcstat_hdr_size, HDR_SIZE);
4124 }
4125 
4126 /*
4127  * Cycle through L2ARC devices.  This is how L2ARC load balances.
4128  * If a device is returned, this also returns holding the spa config lock.
4129  */
4130 static l2arc_dev_t *
4131 l2arc_dev_get_next(void)
4132 {
4133 	l2arc_dev_t *first, *next = NULL;
4134 
4135 	/*
4136 	 * Lock out the removal of spas (spa_namespace_lock), then removal
4137 	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
4138 	 * both locks will be dropped and a spa config lock held instead.
4139 	 */
4140 	mutex_enter(&spa_namespace_lock);
4141 	mutex_enter(&l2arc_dev_mtx);
4142 
4143 	/* if there are no vdevs, there is nothing to do */
4144 	if (l2arc_ndev == 0)
4145 		goto out;
4146 
4147 	first = NULL;
4148 	next = l2arc_dev_last;
4149 	do {
4150 		/* loop around the list looking for a non-faulted vdev */
4151 		if (next == NULL) {
4152 			next = list_head(l2arc_dev_list);
4153 		} else {
4154 			next = list_next(l2arc_dev_list, next);
4155 			if (next == NULL)
4156 				next = list_head(l2arc_dev_list);
4157 		}
4158 
4159 		/* if we have come back to the start, bail out */
4160 		if (first == NULL)
4161 			first = next;
4162 		else if (next == first)
4163 			break;
4164 
4165 	} while (vdev_is_dead(next->l2ad_vdev));
4166 
4167 	/* if we were unable to find any usable vdevs, return NULL */
4168 	if (vdev_is_dead(next->l2ad_vdev))
4169 		next = NULL;
4170 
4171 	l2arc_dev_last = next;
4172 
4173 out:
4174 	mutex_exit(&l2arc_dev_mtx);
4175 
4176 	/*
4177 	 * Grab the config lock to prevent the 'next' device from being
4178 	 * removed while we are writing to it.
4179 	 */
4180 	if (next != NULL)
4181 		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
4182 	mutex_exit(&spa_namespace_lock);
4183 
4184 	return (next);
4185 }
4186 
4187 /*
4188  * Free buffers that were tagged for destruction.
4189  */
4190 static void
4191 l2arc_do_free_on_write()
4192 {
4193 	list_t *buflist;
4194 	l2arc_data_free_t *df, *df_prev;
4195 
4196 	mutex_enter(&l2arc_free_on_write_mtx);
4197 	buflist = l2arc_free_on_write;
4198 
4199 	for (df = list_tail(buflist); df; df = df_prev) {
4200 		df_prev = list_prev(buflist, df);
4201 		ASSERT(df->l2df_data != NULL);
4202 		ASSERT(df->l2df_func != NULL);
4203 		df->l2df_func(df->l2df_data, df->l2df_size);
4204 		list_remove(buflist, df);
4205 		kmem_free(df, sizeof (l2arc_data_free_t));
4206 	}
4207 
4208 	mutex_exit(&l2arc_free_on_write_mtx);
4209 }
4210 
4211 /*
4212  * A write to a cache device has completed.  Update all headers to allow
4213  * reads from these buffers to begin.
4214  */
4215 static void
4216 l2arc_write_done(zio_t *zio)
4217 {
4218 	l2arc_write_callback_t *cb;
4219 	l2arc_dev_t *dev;
4220 	list_t *buflist;
4221 	arc_buf_hdr_t *head, *ab, *ab_prev;
4222 	l2arc_buf_hdr_t *abl2;
4223 	kmutex_t *hash_lock;
4224 	int64_t bytes_dropped = 0;
4225 
4226 	cb = zio->io_private;
4227 	ASSERT(cb != NULL);
4228 	dev = cb->l2wcb_dev;
4229 	ASSERT(dev != NULL);
4230 	head = cb->l2wcb_head;
4231 	ASSERT(head != NULL);
4232 	buflist = dev->l2ad_buflist;
4233 	ASSERT(buflist != NULL);
4234 	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
4235 	    l2arc_write_callback_t *, cb);
4236 
4237 	if (zio->io_error != 0)
4238 		ARCSTAT_BUMP(arcstat_l2_writes_error);
4239 
4240 	mutex_enter(&l2arc_buflist_mtx);
4241 
4242 	/*
4243 	 * All writes completed, or an error was hit.
4244 	 */
4245 	for (ab = list_prev(buflist, head); ab; ab = ab_prev) {
4246 		ab_prev = list_prev(buflist, ab);
4247 		abl2 = ab->b_l2hdr;
4248 
4249 		/*
4250 		 * Release the temporary compressed buffer as soon as possible.
4251 		 */
4252 		if (abl2->b_compress != ZIO_COMPRESS_OFF)
4253 			l2arc_release_cdata_buf(ab);
4254 
4255 		hash_lock = HDR_LOCK(ab);
4256 		if (!mutex_tryenter(hash_lock)) {
4257 			/*
4258 			 * This buffer misses out.  It may be in a stage
4259 			 * of eviction.  Its ARC_L2_WRITING flag will be
4260 			 * left set, denying reads to this buffer.
4261 			 */
4262 			ARCSTAT_BUMP(arcstat_l2_writes_hdr_miss);
4263 			continue;
4264 		}
4265 
4266 		if (zio->io_error != 0) {
4267 			/*
4268 			 * Error - drop L2ARC entry.
4269 			 */
4270 			list_remove(buflist, ab);
4271 			ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
4272 			bytes_dropped += abl2->b_asize;
4273 			ab->b_l2hdr = NULL;
4274 			kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
4275 			ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
4276 		}
4277 
4278 		/*
4279 		 * Allow ARC to begin reads to this L2ARC entry.
4280 		 */
4281 		ab->b_flags &= ~ARC_L2_WRITING;
4282 
4283 		mutex_exit(hash_lock);
4284 	}
4285 
4286 	atomic_inc_64(&l2arc_writes_done);
4287 	list_remove(buflist, head);
4288 	kmem_cache_free(hdr_cache, head);
4289 	mutex_exit(&l2arc_buflist_mtx);
4290 
4291 	vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
4292 
4293 	l2arc_do_free_on_write();
4294 
4295 	kmem_free(cb, sizeof (l2arc_write_callback_t));
4296 }
4297 
4298 /*
4299  * A read to a cache device completed.  Validate buffer contents before
4300  * handing over to the regular ARC routines.
4301  */
4302 static void
4303 l2arc_read_done(zio_t *zio)
4304 {
4305 	l2arc_read_callback_t *cb;
4306 	arc_buf_hdr_t *hdr;
4307 	arc_buf_t *buf;
4308 	kmutex_t *hash_lock;
4309 	int equal;
4310 
4311 	ASSERT(zio->io_vd != NULL);
4312 	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
4313 
4314 	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
4315 
4316 	cb = zio->io_private;
4317 	ASSERT(cb != NULL);
4318 	buf = cb->l2rcb_buf;
4319 	ASSERT(buf != NULL);
4320 
4321 	hash_lock = HDR_LOCK(buf->b_hdr);
4322 	mutex_enter(hash_lock);
4323 	hdr = buf->b_hdr;
4324 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4325 
4326 	/*
4327 	 * If the buffer was compressed, decompress it first.
4328 	 */
4329 	if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
4330 		l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
4331 	ASSERT(zio->io_data != NULL);
4332 
4333 	/*
4334 	 * Check this survived the L2ARC journey.
4335 	 */
4336 	equal = arc_cksum_equal(buf);
4337 	if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
4338 		mutex_exit(hash_lock);
4339 		zio->io_private = buf;
4340 		zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
4341 		zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
4342 		arc_read_done(zio);
4343 	} else {
4344 		mutex_exit(hash_lock);
4345 		/*
4346 		 * Buffer didn't survive caching.  Increment stats and
4347 		 * reissue to the original storage device.
4348 		 */
4349 		if (zio->io_error != 0) {
4350 			ARCSTAT_BUMP(arcstat_l2_io_error);
4351 		} else {
4352 			zio->io_error = SET_ERROR(EIO);
4353 		}
4354 		if (!equal)
4355 			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
4356 
4357 		/*
4358 		 * If there's no waiter, issue an async i/o to the primary
4359 		 * storage now.  If there *is* a waiter, the caller must
4360 		 * issue the i/o in a context where it's OK to block.
4361 		 */
4362 		if (zio->io_waiter == NULL) {
4363 			zio_t *pio = zio_unique_parent(zio);
4364 
4365 			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
4366 
4367 			zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
4368 			    buf->b_data, zio->io_size, arc_read_done, buf,
4369 			    zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
4370 		}
4371 	}
4372 
4373 	kmem_free(cb, sizeof (l2arc_read_callback_t));
4374 }
4375 
4376 /*
4377  * This is the list priority from which the L2ARC will search for pages to
4378  * cache.  This is used within loops (0..3) to cycle through lists in the
4379  * desired order.  This order can have a significant effect on cache
4380  * performance.
4381  *
4382  * Currently the metadata lists are hit first, MFU then MRU, followed by
4383  * the data lists.  This function returns a locked list, and also returns
4384  * the lock pointer.
4385  */
4386 static list_t *
4387 l2arc_list_locked(int list_num, kmutex_t **lock)
4388 {
4389 	list_t *list = NULL;
4390 
4391 	ASSERT(list_num >= 0 && list_num <= 3);
4392 
4393 	switch (list_num) {
4394 	case 0:
4395 		list = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
4396 		*lock = &arc_mfu->arcs_mtx;
4397 		break;
4398 	case 1:
4399 		list = &arc_mru->arcs_list[ARC_BUFC_METADATA];
4400 		*lock = &arc_mru->arcs_mtx;
4401 		break;
4402 	case 2:
4403 		list = &arc_mfu->arcs_list[ARC_BUFC_DATA];
4404 		*lock = &arc_mfu->arcs_mtx;
4405 		break;
4406 	case 3:
4407 		list = &arc_mru->arcs_list[ARC_BUFC_DATA];
4408 		*lock = &arc_mru->arcs_mtx;
4409 		break;
4410 	}
4411 
4412 	ASSERT(!(MUTEX_HELD(*lock)));
4413 	mutex_enter(*lock);
4414 	return (list);
4415 }
4416 
4417 /*
4418  * Evict buffers from the device write hand to the distance specified in
4419  * bytes.  This distance may span populated buffers, it may span nothing.
4420  * This is clearing a region on the L2ARC device ready for writing.
4421  * If the 'all' boolean is set, every buffer is evicted.
4422  */
4423 static void
4424 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
4425 {
4426 	list_t *buflist;
4427 	l2arc_buf_hdr_t *abl2;
4428 	arc_buf_hdr_t *ab, *ab_prev;
4429 	kmutex_t *hash_lock;
4430 	uint64_t taddr;
4431 	int64_t bytes_evicted = 0;
4432 
4433 	buflist = dev->l2ad_buflist;
4434 
4435 	if (buflist == NULL)
4436 		return;
4437 
4438 	if (!all && dev->l2ad_first) {
4439 		/*
4440 		 * This is the first sweep through the device.  There is
4441 		 * nothing to evict.
4442 		 */
4443 		return;
4444 	}
4445 
4446 	if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
4447 		/*
4448 		 * When nearing the end of the device, evict to the end
4449 		 * before the device write hand jumps to the start.
4450 		 */
4451 		taddr = dev->l2ad_end;
4452 	} else {
4453 		taddr = dev->l2ad_hand + distance;
4454 	}
4455 	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
4456 	    uint64_t, taddr, boolean_t, all);
4457 
4458 top:
4459 	mutex_enter(&l2arc_buflist_mtx);
4460 	for (ab = list_tail(buflist); ab; ab = ab_prev) {
4461 		ab_prev = list_prev(buflist, ab);
4462 
4463 		hash_lock = HDR_LOCK(ab);
4464 		if (!mutex_tryenter(hash_lock)) {
4465 			/*
4466 			 * Missed the hash lock.  Retry.
4467 			 */
4468 			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
4469 			mutex_exit(&l2arc_buflist_mtx);
4470 			mutex_enter(hash_lock);
4471 			mutex_exit(hash_lock);
4472 			goto top;
4473 		}
4474 
4475 		if (HDR_L2_WRITE_HEAD(ab)) {
4476 			/*
4477 			 * We hit a write head node.  Leave it for
4478 			 * l2arc_write_done().
4479 			 */
4480 			list_remove(buflist, ab);
4481 			mutex_exit(hash_lock);
4482 			continue;
4483 		}
4484 
4485 		if (!all && ab->b_l2hdr != NULL &&
4486 		    (ab->b_l2hdr->b_daddr > taddr ||
4487 		    ab->b_l2hdr->b_daddr < dev->l2ad_hand)) {
4488 			/*
4489 			 * We've evicted to the target address,
4490 			 * or the end of the device.
4491 			 */
4492 			mutex_exit(hash_lock);
4493 			break;
4494 		}
4495 
4496 		if (HDR_FREE_IN_PROGRESS(ab)) {
4497 			/*
4498 			 * Already on the path to destruction.
4499 			 */
4500 			mutex_exit(hash_lock);
4501 			continue;
4502 		}
4503 
4504 		if (ab->b_state == arc_l2c_only) {
4505 			ASSERT(!HDR_L2_READING(ab));
4506 			/*
4507 			 * This doesn't exist in the ARC.  Destroy.
4508 			 * arc_hdr_destroy() will call list_remove()
4509 			 * and decrement arcstat_l2_size.
4510 			 */
4511 			arc_change_state(arc_anon, ab, hash_lock);
4512 			arc_hdr_destroy(ab);
4513 		} else {
4514 			/*
4515 			 * Invalidate issued or about to be issued
4516 			 * reads, since we may be about to write
4517 			 * over this location.
4518 			 */
4519 			if (HDR_L2_READING(ab)) {
4520 				ARCSTAT_BUMP(arcstat_l2_evict_reading);
4521 				ab->b_flags |= ARC_L2_EVICTED;
4522 			}
4523 
4524 			/*
4525 			 * Tell ARC this no longer exists in L2ARC.
4526 			 */
4527 			if (ab->b_l2hdr != NULL) {
4528 				abl2 = ab->b_l2hdr;
4529 				ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
4530 				bytes_evicted += abl2->b_asize;
4531 				ab->b_l2hdr = NULL;
4532 				kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
4533 				ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
4534 			}
4535 			list_remove(buflist, ab);
4536 
4537 			/*
4538 			 * This may have been leftover after a
4539 			 * failed write.
4540 			 */
4541 			ab->b_flags &= ~ARC_L2_WRITING;
4542 		}
4543 		mutex_exit(hash_lock);
4544 	}
4545 	mutex_exit(&l2arc_buflist_mtx);
4546 
4547 	vdev_space_update(dev->l2ad_vdev, -bytes_evicted, 0, 0);
4548 	dev->l2ad_evict = taddr;
4549 }
4550 
4551 /*
4552  * Find and write ARC buffers to the L2ARC device.
4553  *
4554  * An ARC_L2_WRITING flag is set so that the L2ARC buffers are not valid
4555  * for reading until they have completed writing.
4556  * The headroom_boost is an in-out parameter used to maintain headroom boost
4557  * state between calls to this function.
4558  *
4559  * Returns the number of bytes actually written (which may be smaller than
4560  * the delta by which the device hand has changed due to alignment).
4561  */
4562 static uint64_t
4563 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
4564     boolean_t *headroom_boost)
4565 {
4566 	arc_buf_hdr_t *ab, *ab_prev, *head;
4567 	list_t *list;
4568 	uint64_t write_asize, write_psize, write_sz, headroom,
4569 	    buf_compress_minsz;
4570 	void *buf_data;
4571 	kmutex_t *list_lock;
4572 	boolean_t full;
4573 	l2arc_write_callback_t *cb;
4574 	zio_t *pio, *wzio;
4575 	uint64_t guid = spa_load_guid(spa);
4576 	const boolean_t do_headroom_boost = *headroom_boost;
4577 
4578 	ASSERT(dev->l2ad_vdev != NULL);
4579 
4580 	/* Lower the flag now, we might want to raise it again later. */
4581 	*headroom_boost = B_FALSE;
4582 
4583 	pio = NULL;
4584 	write_sz = write_asize = write_psize = 0;
4585 	full = B_FALSE;
4586 	head = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
4587 	head->b_flags |= ARC_L2_WRITE_HEAD;
4588 
4589 	/*
4590 	 * We will want to try to compress buffers that are at least 2x the
4591 	 * device sector size.
4592 	 */
4593 	buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
4594 
4595 	/*
4596 	 * Copy buffers for L2ARC writing.
4597 	 */
4598 	mutex_enter(&l2arc_buflist_mtx);
4599 	for (int try = 0; try <= 3; try++) {
4600 		uint64_t passed_sz = 0;
4601 
4602 		list = l2arc_list_locked(try, &list_lock);
4603 
4604 		/*
4605 		 * L2ARC fast warmup.
4606 		 *
4607 		 * Until the ARC is warm and starts to evict, read from the
4608 		 * head of the ARC lists rather than the tail.
4609 		 */
4610 		if (arc_warm == B_FALSE)
4611 			ab = list_head(list);
4612 		else
4613 			ab = list_tail(list);
4614 
4615 		headroom = target_sz * l2arc_headroom;
4616 		if (do_headroom_boost)
4617 			headroom = (headroom * l2arc_headroom_boost) / 100;
4618 
4619 		for (; ab; ab = ab_prev) {
4620 			l2arc_buf_hdr_t *l2hdr;
4621 			kmutex_t *hash_lock;
4622 			uint64_t buf_sz;
4623 
4624 			if (arc_warm == B_FALSE)
4625 				ab_prev = list_next(list, ab);
4626 			else
4627 				ab_prev = list_prev(list, ab);
4628 
4629 			hash_lock = HDR_LOCK(ab);
4630 			if (!mutex_tryenter(hash_lock)) {
4631 				/*
4632 				 * Skip this buffer rather than waiting.
4633 				 */
4634 				continue;
4635 			}
4636 
4637 			passed_sz += ab->b_size;
4638 			if (passed_sz > headroom) {
4639 				/*
4640 				 * Searched too far.
4641 				 */
4642 				mutex_exit(hash_lock);
4643 				break;
4644 			}
4645 
4646 			if (!l2arc_write_eligible(guid, ab)) {
4647 				mutex_exit(hash_lock);
4648 				continue;
4649 			}
4650 
4651 			if ((write_sz + ab->b_size) > target_sz) {
4652 				full = B_TRUE;
4653 				mutex_exit(hash_lock);
4654 				break;
4655 			}
4656 
4657 			if (pio == NULL) {
4658 				/*
4659 				 * Insert a dummy header on the buflist so
4660 				 * l2arc_write_done() can find where the
4661 				 * write buffers begin without searching.
4662 				 */
4663 				list_insert_head(dev->l2ad_buflist, head);
4664 
4665 				cb = kmem_alloc(
4666 				    sizeof (l2arc_write_callback_t), KM_SLEEP);
4667 				cb->l2wcb_dev = dev;
4668 				cb->l2wcb_head = head;
4669 				pio = zio_root(spa, l2arc_write_done, cb,
4670 				    ZIO_FLAG_CANFAIL);
4671 			}
4672 
4673 			/*
4674 			 * Create and add a new L2ARC header.
4675 			 */
4676 			l2hdr = kmem_zalloc(sizeof (l2arc_buf_hdr_t), KM_SLEEP);
4677 			l2hdr->b_dev = dev;
4678 			ab->b_flags |= ARC_L2_WRITING;
4679 
4680 			/*
4681 			 * Temporarily stash the data buffer in b_tmp_cdata.
4682 			 * The subsequent write step will pick it up from
4683 			 * there. This is because can't access ab->b_buf
4684 			 * without holding the hash_lock, which we in turn
4685 			 * can't access without holding the ARC list locks
4686 			 * (which we want to avoid during compression/writing).
4687 			 */
4688 			l2hdr->b_compress = ZIO_COMPRESS_OFF;
4689 			l2hdr->b_asize = ab->b_size;
4690 			l2hdr->b_tmp_cdata = ab->b_buf->b_data;
4691 
4692 			buf_sz = ab->b_size;
4693 			ab->b_l2hdr = l2hdr;
4694 
4695 			list_insert_head(dev->l2ad_buflist, ab);
4696 
4697 			/*
4698 			 * Compute and store the buffer cksum before
4699 			 * writing.  On debug the cksum is verified first.
4700 			 */
4701 			arc_cksum_verify(ab->b_buf);
4702 			arc_cksum_compute(ab->b_buf, B_TRUE);
4703 
4704 			mutex_exit(hash_lock);
4705 
4706 			write_sz += buf_sz;
4707 		}
4708 
4709 		mutex_exit(list_lock);
4710 
4711 		if (full == B_TRUE)
4712 			break;
4713 	}
4714 
4715 	/* No buffers selected for writing? */
4716 	if (pio == NULL) {
4717 		ASSERT0(write_sz);
4718 		mutex_exit(&l2arc_buflist_mtx);
4719 		kmem_cache_free(hdr_cache, head);
4720 		return (0);
4721 	}
4722 
4723 	/*
4724 	 * Now start writing the buffers. We're starting at the write head
4725 	 * and work backwards, retracing the course of the buffer selector
4726 	 * loop above.
4727 	 */
4728 	for (ab = list_prev(dev->l2ad_buflist, head); ab;
4729 	    ab = list_prev(dev->l2ad_buflist, ab)) {
4730 		l2arc_buf_hdr_t *l2hdr;
4731 		uint64_t buf_sz;
4732 
4733 		/*
4734 		 * We shouldn't need to lock the buffer here, since we flagged
4735 		 * it as ARC_L2_WRITING in the previous step, but we must take
4736 		 * care to only access its L2 cache parameters. In particular,
4737 		 * ab->b_buf may be invalid by now due to ARC eviction.
4738 		 */
4739 		l2hdr = ab->b_l2hdr;
4740 		l2hdr->b_daddr = dev->l2ad_hand;
4741 
4742 		if ((ab->b_flags & ARC_L2COMPRESS) &&
4743 		    l2hdr->b_asize >= buf_compress_minsz) {
4744 			if (l2arc_compress_buf(l2hdr)) {
4745 				/*
4746 				 * If compression succeeded, enable headroom
4747 				 * boost on the next scan cycle.
4748 				 */
4749 				*headroom_boost = B_TRUE;
4750 			}
4751 		}
4752 
4753 		/*
4754 		 * Pick up the buffer data we had previously stashed away
4755 		 * (and now potentially also compressed).
4756 		 */
4757 		buf_data = l2hdr->b_tmp_cdata;
4758 		buf_sz = l2hdr->b_asize;
4759 
4760 		/* Compression may have squashed the buffer to zero length. */
4761 		if (buf_sz != 0) {
4762 			uint64_t buf_p_sz;
4763 
4764 			wzio = zio_write_phys(pio, dev->l2ad_vdev,
4765 			    dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
4766 			    NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
4767 			    ZIO_FLAG_CANFAIL, B_FALSE);
4768 
4769 			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
4770 			    zio_t *, wzio);
4771 			(void) zio_nowait(wzio);
4772 
4773 			write_asize += buf_sz;
4774 			/*
4775 			 * Keep the clock hand suitably device-aligned.
4776 			 */
4777 			buf_p_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
4778 			write_psize += buf_p_sz;
4779 			dev->l2ad_hand += buf_p_sz;
4780 		}
4781 	}
4782 
4783 	mutex_exit(&l2arc_buflist_mtx);
4784 
4785 	ASSERT3U(write_asize, <=, target_sz);
4786 	ARCSTAT_BUMP(arcstat_l2_writes_sent);
4787 	ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
4788 	ARCSTAT_INCR(arcstat_l2_size, write_sz);
4789 	ARCSTAT_INCR(arcstat_l2_asize, write_asize);
4790 	vdev_space_update(dev->l2ad_vdev, write_asize, 0, 0);
4791 
4792 	/*
4793 	 * Bump device hand to the device start if it is approaching the end.
4794 	 * l2arc_evict() will already have evicted ahead for this case.
4795 	 */
4796 	if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
4797 		dev->l2ad_hand = dev->l2ad_start;
4798 		dev->l2ad_evict = dev->l2ad_start;
4799 		dev->l2ad_first = B_FALSE;
4800 	}
4801 
4802 	dev->l2ad_writing = B_TRUE;
4803 	(void) zio_wait(pio);
4804 	dev->l2ad_writing = B_FALSE;
4805 
4806 	return (write_asize);
4807 }
4808 
4809 /*
4810  * Compresses an L2ARC buffer.
4811  * The data to be compressed must be prefilled in l2hdr->b_tmp_cdata and its
4812  * size in l2hdr->b_asize. This routine tries to compress the data and
4813  * depending on the compression result there are three possible outcomes:
4814  * *) The buffer was incompressible. The original l2hdr contents were left
4815  *    untouched and are ready for writing to an L2 device.
4816  * *) The buffer was all-zeros, so there is no need to write it to an L2
4817  *    device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
4818  *    set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
4819  * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
4820  *    data buffer which holds the compressed data to be written, and b_asize
4821  *    tells us how much data there is. b_compress is set to the appropriate
4822  *    compression algorithm. Once writing is done, invoke
4823  *    l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
4824  *
4825  * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
4826  * buffer was incompressible).
4827  */
4828 static boolean_t
4829 l2arc_compress_buf(l2arc_buf_hdr_t *l2hdr)
4830 {
4831 	void *cdata;
4832 	size_t csize, len, rounded;
4833 
4834 	ASSERT(l2hdr->b_compress == ZIO_COMPRESS_OFF);
4835 	ASSERT(l2hdr->b_tmp_cdata != NULL);
4836 
4837 	len = l2hdr->b_asize;
4838 	cdata = zio_data_buf_alloc(len);
4839 	csize = zio_compress_data(ZIO_COMPRESS_LZ4, l2hdr->b_tmp_cdata,
4840 	    cdata, l2hdr->b_asize);
4841 
4842 	rounded = P2ROUNDUP(csize, (size_t)SPA_MINBLOCKSIZE);
4843 	if (rounded > csize) {
4844 		bzero((char *)cdata + csize, rounded - csize);
4845 		csize = rounded;
4846 	}
4847 
4848 	if (csize == 0) {
4849 		/* zero block, indicate that there's nothing to write */
4850 		zio_data_buf_free(cdata, len);
4851 		l2hdr->b_compress = ZIO_COMPRESS_EMPTY;
4852 		l2hdr->b_asize = 0;
4853 		l2hdr->b_tmp_cdata = NULL;
4854 		ARCSTAT_BUMP(arcstat_l2_compress_zeros);
4855 		return (B_TRUE);
4856 	} else if (csize > 0 && csize < len) {
4857 		/*
4858 		 * Compression succeeded, we'll keep the cdata around for
4859 		 * writing and release it afterwards.
4860 		 */
4861 		l2hdr->b_compress = ZIO_COMPRESS_LZ4;
4862 		l2hdr->b_asize = csize;
4863 		l2hdr->b_tmp_cdata = cdata;
4864 		ARCSTAT_BUMP(arcstat_l2_compress_successes);
4865 		return (B_TRUE);
4866 	} else {
4867 		/*
4868 		 * Compression failed, release the compressed buffer.
4869 		 * l2hdr will be left unmodified.
4870 		 */
4871 		zio_data_buf_free(cdata, len);
4872 		ARCSTAT_BUMP(arcstat_l2_compress_failures);
4873 		return (B_FALSE);
4874 	}
4875 }
4876 
4877 /*
4878  * Decompresses a zio read back from an l2arc device. On success, the
4879  * underlying zio's io_data buffer is overwritten by the uncompressed
4880  * version. On decompression error (corrupt compressed stream), the
4881  * zio->io_error value is set to signal an I/O error.
4882  *
4883  * Please note that the compressed data stream is not checksummed, so
4884  * if the underlying device is experiencing data corruption, we may feed
4885  * corrupt data to the decompressor, so the decompressor needs to be
4886  * able to handle this situation (LZ4 does).
4887  */
4888 static void
4889 l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
4890 {
4891 	ASSERT(L2ARC_IS_VALID_COMPRESS(c));
4892 
4893 	if (zio->io_error != 0) {
4894 		/*
4895 		 * An io error has occured, just restore the original io
4896 		 * size in preparation for a main pool read.
4897 		 */
4898 		zio->io_orig_size = zio->io_size = hdr->b_size;
4899 		return;
4900 	}
4901 
4902 	if (c == ZIO_COMPRESS_EMPTY) {
4903 		/*
4904 		 * An empty buffer results in a null zio, which means we
4905 		 * need to fill its io_data after we're done restoring the
4906 		 * buffer's contents.
4907 		 */
4908 		ASSERT(hdr->b_buf != NULL);
4909 		bzero(hdr->b_buf->b_data, hdr->b_size);
4910 		zio->io_data = zio->io_orig_data = hdr->b_buf->b_data;
4911 	} else {
4912 		ASSERT(zio->io_data != NULL);
4913 		/*
4914 		 * We copy the compressed data from the start of the arc buffer
4915 		 * (the zio_read will have pulled in only what we need, the
4916 		 * rest is garbage which we will overwrite at decompression)
4917 		 * and then decompress back to the ARC data buffer. This way we
4918 		 * can minimize copying by simply decompressing back over the
4919 		 * original compressed data (rather than decompressing to an
4920 		 * aux buffer and then copying back the uncompressed buffer,
4921 		 * which is likely to be much larger).
4922 		 */
4923 		uint64_t csize;
4924 		void *cdata;
4925 
4926 		csize = zio->io_size;
4927 		cdata = zio_data_buf_alloc(csize);
4928 		bcopy(zio->io_data, cdata, csize);
4929 		if (zio_decompress_data(c, cdata, zio->io_data, csize,
4930 		    hdr->b_size) != 0)
4931 			zio->io_error = EIO;
4932 		zio_data_buf_free(cdata, csize);
4933 	}
4934 
4935 	/* Restore the expected uncompressed IO size. */
4936 	zio->io_orig_size = zio->io_size = hdr->b_size;
4937 }
4938 
4939 /*
4940  * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
4941  * This buffer serves as a temporary holder of compressed data while
4942  * the buffer entry is being written to an l2arc device. Once that is
4943  * done, we can dispose of it.
4944  */
4945 static void
4946 l2arc_release_cdata_buf(arc_buf_hdr_t *ab)
4947 {
4948 	l2arc_buf_hdr_t *l2hdr = ab->b_l2hdr;
4949 
4950 	if (l2hdr->b_compress == ZIO_COMPRESS_LZ4) {
4951 		/*
4952 		 * If the data was compressed, then we've allocated a
4953 		 * temporary buffer for it, so now we need to release it.
4954 		 */
4955 		ASSERT(l2hdr->b_tmp_cdata != NULL);
4956 		zio_data_buf_free(l2hdr->b_tmp_cdata, ab->b_size);
4957 	}
4958 	l2hdr->b_tmp_cdata = NULL;
4959 }
4960 
4961 /*
4962  * This thread feeds the L2ARC at regular intervals.  This is the beating
4963  * heart of the L2ARC.
4964  */
4965 static void
4966 l2arc_feed_thread(void)
4967 {
4968 	callb_cpr_t cpr;
4969 	l2arc_dev_t *dev;
4970 	spa_t *spa;
4971 	uint64_t size, wrote;
4972 	clock_t begin, next = ddi_get_lbolt();
4973 	boolean_t headroom_boost = B_FALSE;
4974 
4975 	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
4976 
4977 	mutex_enter(&l2arc_feed_thr_lock);
4978 
4979 	while (l2arc_thread_exit == 0) {
4980 		CALLB_CPR_SAFE_BEGIN(&cpr);
4981 		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
4982 		    next);
4983 		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
4984 		next = ddi_get_lbolt() + hz;
4985 
4986 		/*
4987 		 * Quick check for L2ARC devices.
4988 		 */
4989 		mutex_enter(&l2arc_dev_mtx);
4990 		if (l2arc_ndev == 0) {
4991 			mutex_exit(&l2arc_dev_mtx);
4992 			continue;
4993 		}
4994 		mutex_exit(&l2arc_dev_mtx);
4995 		begin = ddi_get_lbolt();
4996 
4997 		/*
4998 		 * This selects the next l2arc device to write to, and in
4999 		 * doing so the next spa to feed from: dev->l2ad_spa.   This
5000 		 * will return NULL if there are now no l2arc devices or if
5001 		 * they are all faulted.
5002 		 *
5003 		 * If a device is returned, its spa's config lock is also
5004 		 * held to prevent device removal.  l2arc_dev_get_next()
5005 		 * will grab and release l2arc_dev_mtx.
5006 		 */
5007 		if ((dev = l2arc_dev_get_next()) == NULL)
5008 			continue;
5009 
5010 		spa = dev->l2ad_spa;
5011 		ASSERT(spa != NULL);
5012 
5013 		/*
5014 		 * If the pool is read-only then force the feed thread to
5015 		 * sleep a little longer.
5016 		 */
5017 		if (!spa_writeable(spa)) {
5018 			next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
5019 			spa_config_exit(spa, SCL_L2ARC, dev);
5020 			continue;
5021 		}
5022 
5023 		/*
5024 		 * Avoid contributing to memory pressure.
5025 		 */
5026 		if (arc_reclaim_needed()) {
5027 			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
5028 			spa_config_exit(spa, SCL_L2ARC, dev);
5029 			continue;
5030 		}
5031 
5032 		ARCSTAT_BUMP(arcstat_l2_feeds);
5033 
5034 		size = l2arc_write_size();
5035 
5036 		/*
5037 		 * Evict L2ARC buffers that will be overwritten.
5038 		 */
5039 		l2arc_evict(dev, size, B_FALSE);
5040 
5041 		/*
5042 		 * Write ARC buffers.
5043 		 */
5044 		wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
5045 
5046 		/*
5047 		 * Calculate interval between writes.
5048 		 */
5049 		next = l2arc_write_interval(begin, size, wrote);
5050 		spa_config_exit(spa, SCL_L2ARC, dev);
5051 	}
5052 
5053 	l2arc_thread_exit = 0;
5054 	cv_broadcast(&l2arc_feed_thr_cv);
5055 	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
5056 	thread_exit();
5057 }
5058 
5059 boolean_t
5060 l2arc_vdev_present(vdev_t *vd)
5061 {
5062 	l2arc_dev_t *dev;
5063 
5064 	mutex_enter(&l2arc_dev_mtx);
5065 	for (dev = list_head(l2arc_dev_list); dev != NULL;
5066 	    dev = list_next(l2arc_dev_list, dev)) {
5067 		if (dev->l2ad_vdev == vd)
5068 			break;
5069 	}
5070 	mutex_exit(&l2arc_dev_mtx);
5071 
5072 	return (dev != NULL);
5073 }
5074 
5075 /*
5076  * Add a vdev for use by the L2ARC.  By this point the spa has already
5077  * validated the vdev and opened it.
5078  */
5079 void
5080 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
5081 {
5082 	l2arc_dev_t *adddev;
5083 
5084 	ASSERT(!l2arc_vdev_present(vd));
5085 
5086 	/*
5087 	 * Create a new l2arc device entry.
5088 	 */
5089 	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
5090 	adddev->l2ad_spa = spa;
5091 	adddev->l2ad_vdev = vd;
5092 	adddev->l2ad_start = VDEV_LABEL_START_SIZE;
5093 	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
5094 	adddev->l2ad_hand = adddev->l2ad_start;
5095 	adddev->l2ad_evict = adddev->l2ad_start;
5096 	adddev->l2ad_first = B_TRUE;
5097 	adddev->l2ad_writing = B_FALSE;
5098 
5099 	/*
5100 	 * This is a list of all ARC buffers that are still valid on the
5101 	 * device.
5102 	 */
5103 	adddev->l2ad_buflist = kmem_zalloc(sizeof (list_t), KM_SLEEP);
5104 	list_create(adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
5105 	    offsetof(arc_buf_hdr_t, b_l2node));
5106 
5107 	vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
5108 
5109 	/*
5110 	 * Add device to global list
5111 	 */
5112 	mutex_enter(&l2arc_dev_mtx);
5113 	list_insert_head(l2arc_dev_list, adddev);
5114 	atomic_inc_64(&l2arc_ndev);
5115 	mutex_exit(&l2arc_dev_mtx);
5116 }
5117 
5118 /*
5119  * Remove a vdev from the L2ARC.
5120  */
5121 void
5122 l2arc_remove_vdev(vdev_t *vd)
5123 {
5124 	l2arc_dev_t *dev, *nextdev, *remdev = NULL;
5125 
5126 	/*
5127 	 * Find the device by vdev
5128 	 */
5129 	mutex_enter(&l2arc_dev_mtx);
5130 	for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
5131 		nextdev = list_next(l2arc_dev_list, dev);
5132 		if (vd == dev->l2ad_vdev) {
5133 			remdev = dev;
5134 			break;
5135 		}
5136 	}
5137 	ASSERT(remdev != NULL);
5138 
5139 	/*
5140 	 * Remove device from global list
5141 	 */
5142 	list_remove(l2arc_dev_list, remdev);
5143 	l2arc_dev_last = NULL;		/* may have been invalidated */
5144 	atomic_dec_64(&l2arc_ndev);
5145 	mutex_exit(&l2arc_dev_mtx);
5146 
5147 	/*
5148 	 * Clear all buflists and ARC references.  L2ARC device flush.
5149 	 */
5150 	l2arc_evict(remdev, 0, B_TRUE);
5151 	list_destroy(remdev->l2ad_buflist);
5152 	kmem_free(remdev->l2ad_buflist, sizeof (list_t));
5153 	kmem_free(remdev, sizeof (l2arc_dev_t));
5154 }
5155 
5156 void
5157 l2arc_init(void)
5158 {
5159 	l2arc_thread_exit = 0;
5160 	l2arc_ndev = 0;
5161 	l2arc_writes_sent = 0;
5162 	l2arc_writes_done = 0;
5163 
5164 	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
5165 	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
5166 	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
5167 	mutex_init(&l2arc_buflist_mtx, NULL, MUTEX_DEFAULT, NULL);
5168 	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
5169 
5170 	l2arc_dev_list = &L2ARC_dev_list;
5171 	l2arc_free_on_write = &L2ARC_free_on_write;
5172 	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
5173 	    offsetof(l2arc_dev_t, l2ad_node));
5174 	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
5175 	    offsetof(l2arc_data_free_t, l2df_list_node));
5176 }
5177 
5178 void
5179 l2arc_fini(void)
5180 {
5181 	/*
5182 	 * This is called from dmu_fini(), which is called from spa_fini();
5183 	 * Because of this, we can assume that all l2arc devices have
5184 	 * already been removed when the pools themselves were removed.
5185 	 */
5186 
5187 	l2arc_do_free_on_write();
5188 
5189 	mutex_destroy(&l2arc_feed_thr_lock);
5190 	cv_destroy(&l2arc_feed_thr_cv);
5191 	mutex_destroy(&l2arc_dev_mtx);
5192 	mutex_destroy(&l2arc_buflist_mtx);
5193 	mutex_destroy(&l2arc_free_on_write_mtx);
5194 
5195 	list_destroy(l2arc_dev_list);
5196 	list_destroy(l2arc_free_on_write);
5197 }
5198 
5199 void
5200 l2arc_start(void)
5201 {
5202 	if (!(spa_mode_global & FWRITE))
5203 		return;
5204 
5205 	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
5206 	    TS_RUN, minclsyspri);
5207 }
5208 
5209 void
5210 l2arc_stop(void)
5211 {
5212 	if (!(spa_mode_global & FWRITE))
5213 		return;
5214 
5215 	mutex_enter(&l2arc_feed_thr_lock);
5216 	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
5217 	l2arc_thread_exit = 1;
5218 	while (l2arc_thread_exit != 0)
5219 		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
5220 	mutex_exit(&l2arc_feed_thr_lock);
5221 }
5222