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