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