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