xref: /onnv-gate/usr/src/uts/common/fs/zfs/arc.c (revision 7046)
1789Sahrens /*
2789Sahrens  * CDDL HEADER START
3789Sahrens  *
4789Sahrens  * The contents of this file are subject to the terms of the
51484Sek110237  * Common Development and Distribution License (the "License").
61484Sek110237  * You may not use this file except in compliance with the License.
7789Sahrens  *
8789Sahrens  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9789Sahrens  * or http://www.opensolaris.org/os/licensing.
10789Sahrens  * See the License for the specific language governing permissions
11789Sahrens  * and limitations under the License.
12789Sahrens  *
13789Sahrens  * When distributing Covered Code, include this CDDL HEADER in each
14789Sahrens  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15789Sahrens  * If applicable, add the following below this CDDL HEADER, with the
16789Sahrens  * fields enclosed by brackets "[]" replaced with your own identifying
17789Sahrens  * information: Portions Copyright [yyyy] [name of copyright owner]
18789Sahrens  *
19789Sahrens  * CDDL HEADER END
20789Sahrens  */
21789Sahrens /*
226018Sbrendan  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23789Sahrens  * Use is subject to license terms.
24789Sahrens  */
25789Sahrens 
26789Sahrens #pragma ident	"%Z%%M%	%I%	%E% SMI"
27789Sahrens 
28789Sahrens /*
293403Sbmc  * DVA-based Adjustable Replacement Cache
30789Sahrens  *
311544Seschrock  * While much of the theory of operation used here is
321544Seschrock  * based on the self-tuning, low overhead replacement cache
33789Sahrens  * presented by Megiddo and Modha at FAST 2003, there are some
34789Sahrens  * significant differences:
35789Sahrens  *
36789Sahrens  * 1. The Megiddo and Modha model assumes any page is evictable.
37789Sahrens  * Pages in its cache cannot be "locked" into memory.  This makes
38789Sahrens  * the eviction algorithm simple: evict the last page in the list.
39789Sahrens  * This also make the performance characteristics easy to reason
40789Sahrens  * about.  Our cache is not so simple.  At any given moment, some
41789Sahrens  * subset of the blocks in the cache are un-evictable because we
42789Sahrens  * have handed out a reference to them.  Blocks are only evictable
43789Sahrens  * when there are no external references active.  This makes
44789Sahrens  * eviction far more problematic:  we choose to evict the evictable
45789Sahrens  * blocks that are the "lowest" in the list.
46789Sahrens  *
47789Sahrens  * There are times when it is not possible to evict the requested
48789Sahrens  * space.  In these circumstances we are unable to adjust the cache
49789Sahrens  * size.  To prevent the cache growing unbounded at these times we
505450Sbrendan  * implement a "cache throttle" that slows the flow of new data
515450Sbrendan  * into the cache until we can make space available.
52789Sahrens  *
53789Sahrens  * 2. The Megiddo and Modha model assumes a fixed cache size.
54789Sahrens  * Pages are evicted when the cache is full and there is a cache
55789Sahrens  * miss.  Our model has a variable sized cache.  It grows with
565450Sbrendan  * high use, but also tries to react to memory pressure from the
57789Sahrens  * operating system: decreasing its size when system memory is
58789Sahrens  * tight.
59789Sahrens  *
60789Sahrens  * 3. The Megiddo and Modha model assumes a fixed page size. All
61789Sahrens  * elements of the cache are therefor exactly the same size.  So
62789Sahrens  * when adjusting the cache size following a cache miss, its simply
63789Sahrens  * a matter of choosing a single page to evict.  In our model, we
64789Sahrens  * have variable sized cache blocks (rangeing from 512 bytes to
65789Sahrens  * 128K bytes).  We therefor choose a set of blocks to evict to make
66789Sahrens  * space for a cache miss that approximates as closely as possible
67789Sahrens  * the space used by the new block.
68789Sahrens  *
69789Sahrens  * See also:  "ARC: A Self-Tuning, Low Overhead Replacement Cache"
70789Sahrens  * by N. Megiddo & D. Modha, FAST 2003
71789Sahrens  */
72789Sahrens 
73789Sahrens /*
74789Sahrens  * The locking model:
75789Sahrens  *
76789Sahrens  * A new reference to a cache buffer can be obtained in two
77789Sahrens  * ways: 1) via a hash table lookup using the DVA as a key,
785450Sbrendan  * or 2) via one of the ARC lists.  The arc_read() interface
79789Sahrens  * uses method 1, while the internal arc algorithms for
80789Sahrens  * adjusting the cache use method 2.  We therefor provide two
81789Sahrens  * types of locks: 1) the hash table lock array, and 2) the
82789Sahrens  * arc list locks.
83789Sahrens  *
84789Sahrens  * Buffers do not have their own mutexs, rather they rely on the
85789Sahrens  * hash table mutexs for the bulk of their protection (i.e. most
86789Sahrens  * fields in the arc_buf_hdr_t are protected by these mutexs).
87789Sahrens  *
88789Sahrens  * buf_hash_find() returns the appropriate mutex (held) when it
89789Sahrens  * locates the requested buffer in the hash table.  It returns
90789Sahrens  * NULL for the mutex if the buffer was not in the table.
91789Sahrens  *
92789Sahrens  * buf_hash_remove() expects the appropriate hash mutex to be
93789Sahrens  * already held before it is invoked.
94789Sahrens  *
95789Sahrens  * Each arc state also has a mutex which is used to protect the
96789Sahrens  * buffer list associated with the state.  When attempting to
97789Sahrens  * obtain a hash table lock while holding an arc list lock you
98789Sahrens  * must use: mutex_tryenter() to avoid deadlock.  Also note that
992688Smaybee  * the active state mutex must be held before the ghost state mutex.
100789Sahrens  *
1011544Seschrock  * Arc buffers may have an associated eviction callback function.
1021544Seschrock  * This function will be invoked prior to removing the buffer (e.g.
1031544Seschrock  * in arc_do_user_evicts()).  Note however that the data associated
1041544Seschrock  * with the buffer may be evicted prior to the callback.  The callback
1051544Seschrock  * must be made with *no locks held* (to prevent deadlock).  Additionally,
1061544Seschrock  * the users of callbacks must ensure that their private data is
1071544Seschrock  * protected from simultaneous callbacks from arc_buf_evict()
1081544Seschrock  * and arc_do_user_evicts().
1091544Seschrock  *
110789Sahrens  * Note that the majority of the performance stats are manipulated
111789Sahrens  * with atomic operations.
1125450Sbrendan  *
1135450Sbrendan  * The L2ARC uses the l2arc_buflist_mtx global mutex for the following:
1145450Sbrendan  *
1155450Sbrendan  *	- L2ARC buflist creation
1165450Sbrendan  *	- L2ARC buflist eviction
1175450Sbrendan  *	- L2ARC write completion, which walks L2ARC buflists
1185450Sbrendan  *	- ARC header destruction, as it removes from L2ARC buflists
1195450Sbrendan  *	- ARC header release, as it removes from L2ARC buflists
120789Sahrens  */
121789Sahrens 
122789Sahrens #include <sys/spa.h>
123789Sahrens #include <sys/zio.h>
1243093Sahrens #include <sys/zio_checksum.h>
125789Sahrens #include <sys/zfs_context.h>
126789Sahrens #include <sys/arc.h>
127789Sahrens #include <sys/refcount.h>
1286643Seschrock #include <sys/vdev.h>
129789Sahrens #ifdef _KERNEL
130789Sahrens #include <sys/vmsystm.h>
131789Sahrens #include <vm/anon.h>
132789Sahrens #include <sys/fs/swapnode.h>
1331484Sek110237 #include <sys/dnlc.h>
134789Sahrens #endif
135789Sahrens #include <sys/callb.h>
1363403Sbmc #include <sys/kstat.h>
137789Sahrens 
138789Sahrens static kmutex_t		arc_reclaim_thr_lock;
139789Sahrens static kcondvar_t	arc_reclaim_thr_cv;	/* used to signal reclaim thr */
140789Sahrens static uint8_t		arc_thread_exit;
141789Sahrens 
1426245Smaybee extern int zfs_write_limit_shift;
1436245Smaybee extern uint64_t zfs_write_limit_max;
1446245Smaybee extern uint64_t zfs_write_limit_inflated;
1456245Smaybee 
1461484Sek110237 #define	ARC_REDUCE_DNLC_PERCENT	3
1471484Sek110237 uint_t arc_reduce_dnlc_percent = ARC_REDUCE_DNLC_PERCENT;
1481484Sek110237 
149789Sahrens typedef enum arc_reclaim_strategy {
150789Sahrens 	ARC_RECLAIM_AGGR,		/* Aggressive reclaim strategy */
151789Sahrens 	ARC_RECLAIM_CONS		/* Conservative reclaim strategy */
152789Sahrens } arc_reclaim_strategy_t;
153789Sahrens 
154789Sahrens /* number of seconds before growing cache again */
155789Sahrens static int		arc_grow_retry = 60;
156789Sahrens 
1572391Smaybee /*
1582638Sperrin  * minimum lifespan of a prefetch block in clock ticks
1592638Sperrin  * (initialized in arc_init())
1602391Smaybee  */
1612638Sperrin static int		arc_min_prefetch_lifespan;
1622391Smaybee 
163789Sahrens static int arc_dead;
164789Sahrens 
165789Sahrens /*
1666987Sbrendan  * The arc has filled available memory and has now warmed up.
1676987Sbrendan  */
1686987Sbrendan static boolean_t arc_warm;
1696987Sbrendan 
1706987Sbrendan /*
1712885Sahrens  * These tunables are for performance analysis.
1722885Sahrens  */
1732885Sahrens uint64_t zfs_arc_max;
1742885Sahrens uint64_t zfs_arc_min;
1754645Sek110237 uint64_t zfs_arc_meta_limit = 0;
176*7046Sahrens int zfs_mdcomp_disable = 0;
1772885Sahrens 
1782885Sahrens /*
1795450Sbrendan  * Note that buffers can be in one of 6 states:
180789Sahrens  *	ARC_anon	- anonymous (discussed below)
1811544Seschrock  *	ARC_mru		- recently used, currently cached
1821544Seschrock  *	ARC_mru_ghost	- recentely used, no longer in cache
1831544Seschrock  *	ARC_mfu		- frequently used, currently cached
1841544Seschrock  *	ARC_mfu_ghost	- frequently used, no longer in cache
1855450Sbrendan  *	ARC_l2c_only	- exists in L2ARC but not other states
1864309Smaybee  * When there are no active references to the buffer, they are
1874309Smaybee  * are linked onto a list in one of these arc states.  These are
1884309Smaybee  * the only buffers that can be evicted or deleted.  Within each
1894309Smaybee  * state there are multiple lists, one for meta-data and one for
1904309Smaybee  * non-meta-data.  Meta-data (indirect blocks, blocks of dnodes,
1914309Smaybee  * etc.) is tracked separately so that it can be managed more
1925450Sbrendan  * explicitly: favored over data, limited explicitly.
193789Sahrens  *
194789Sahrens  * Anonymous buffers are buffers that are not associated with
195789Sahrens  * a DVA.  These are buffers that hold dirty block copies
196789Sahrens  * before they are written to stable storage.  By definition,
1971544Seschrock  * they are "ref'd" and are considered part of arc_mru
198789Sahrens  * that cannot be freed.  Generally, they will aquire a DVA
1991544Seschrock  * as they are written and migrate onto the arc_mru list.
2005450Sbrendan  *
2015450Sbrendan  * The ARC_l2c_only state is for buffers that are in the second
2025450Sbrendan  * level ARC but no longer in any of the ARC_m* lists.  The second
2035450Sbrendan  * level ARC itself may also contain buffers that are in any of
2045450Sbrendan  * the ARC_m* states - meaning that a buffer can exist in two
2055450Sbrendan  * places.  The reason for the ARC_l2c_only state is to keep the
2065450Sbrendan  * buffer header in the hash table, so that reads that hit the
2075450Sbrendan  * second level ARC benefit from these fast lookups.
208789Sahrens  */
209789Sahrens 
210789Sahrens typedef struct arc_state {
2114309Smaybee 	list_t	arcs_list[ARC_BUFC_NUMTYPES];	/* list of evictable buffers */
2124309Smaybee 	uint64_t arcs_lsize[ARC_BUFC_NUMTYPES];	/* amount of evictable data */
2134309Smaybee 	uint64_t arcs_size;	/* total amount of data in this state */
2143403Sbmc 	kmutex_t arcs_mtx;
215789Sahrens } arc_state_t;
216789Sahrens 
2175450Sbrendan /* The 6 states: */
218789Sahrens static arc_state_t ARC_anon;
2191544Seschrock static arc_state_t ARC_mru;
2201544Seschrock static arc_state_t ARC_mru_ghost;
2211544Seschrock static arc_state_t ARC_mfu;
2221544Seschrock static arc_state_t ARC_mfu_ghost;
2235450Sbrendan static arc_state_t ARC_l2c_only;
224789Sahrens 
2253403Sbmc typedef struct arc_stats {
2263403Sbmc 	kstat_named_t arcstat_hits;
2273403Sbmc 	kstat_named_t arcstat_misses;
2283403Sbmc 	kstat_named_t arcstat_demand_data_hits;
2293403Sbmc 	kstat_named_t arcstat_demand_data_misses;
2303403Sbmc 	kstat_named_t arcstat_demand_metadata_hits;
2313403Sbmc 	kstat_named_t arcstat_demand_metadata_misses;
2323403Sbmc 	kstat_named_t arcstat_prefetch_data_hits;
2333403Sbmc 	kstat_named_t arcstat_prefetch_data_misses;
2343403Sbmc 	kstat_named_t arcstat_prefetch_metadata_hits;
2353403Sbmc 	kstat_named_t arcstat_prefetch_metadata_misses;
2363403Sbmc 	kstat_named_t arcstat_mru_hits;
2373403Sbmc 	kstat_named_t arcstat_mru_ghost_hits;
2383403Sbmc 	kstat_named_t arcstat_mfu_hits;
2393403Sbmc 	kstat_named_t arcstat_mfu_ghost_hits;
2403403Sbmc 	kstat_named_t arcstat_deleted;
2413403Sbmc 	kstat_named_t arcstat_recycle_miss;
2423403Sbmc 	kstat_named_t arcstat_mutex_miss;
2433403Sbmc 	kstat_named_t arcstat_evict_skip;
2443403Sbmc 	kstat_named_t arcstat_hash_elements;
2453403Sbmc 	kstat_named_t arcstat_hash_elements_max;
2463403Sbmc 	kstat_named_t arcstat_hash_collisions;
2473403Sbmc 	kstat_named_t arcstat_hash_chains;
2483403Sbmc 	kstat_named_t arcstat_hash_chain_max;
2493403Sbmc 	kstat_named_t arcstat_p;
2503403Sbmc 	kstat_named_t arcstat_c;
2513403Sbmc 	kstat_named_t arcstat_c_min;
2523403Sbmc 	kstat_named_t arcstat_c_max;
2533403Sbmc 	kstat_named_t arcstat_size;
2545450Sbrendan 	kstat_named_t arcstat_hdr_size;
2555450Sbrendan 	kstat_named_t arcstat_l2_hits;
2565450Sbrendan 	kstat_named_t arcstat_l2_misses;
2575450Sbrendan 	kstat_named_t arcstat_l2_feeds;
2585450Sbrendan 	kstat_named_t arcstat_l2_rw_clash;
2595450Sbrendan 	kstat_named_t arcstat_l2_writes_sent;
2605450Sbrendan 	kstat_named_t arcstat_l2_writes_done;
2615450Sbrendan 	kstat_named_t arcstat_l2_writes_error;
2625450Sbrendan 	kstat_named_t arcstat_l2_writes_hdr_miss;
2635450Sbrendan 	kstat_named_t arcstat_l2_evict_lock_retry;
2645450Sbrendan 	kstat_named_t arcstat_l2_evict_reading;
2655450Sbrendan 	kstat_named_t arcstat_l2_free_on_write;
2665450Sbrendan 	kstat_named_t arcstat_l2_abort_lowmem;
2675450Sbrendan 	kstat_named_t arcstat_l2_cksum_bad;
2685450Sbrendan 	kstat_named_t arcstat_l2_io_error;
2695450Sbrendan 	kstat_named_t arcstat_l2_size;
2705450Sbrendan 	kstat_named_t arcstat_l2_hdr_size;
2716245Smaybee 	kstat_named_t arcstat_memory_throttle_count;
2723403Sbmc } arc_stats_t;
2733403Sbmc 
2743403Sbmc static arc_stats_t arc_stats = {
2753403Sbmc 	{ "hits",			KSTAT_DATA_UINT64 },
2763403Sbmc 	{ "misses",			KSTAT_DATA_UINT64 },
2773403Sbmc 	{ "demand_data_hits",		KSTAT_DATA_UINT64 },
2783403Sbmc 	{ "demand_data_misses",		KSTAT_DATA_UINT64 },
2793403Sbmc 	{ "demand_metadata_hits",	KSTAT_DATA_UINT64 },
2803403Sbmc 	{ "demand_metadata_misses",	KSTAT_DATA_UINT64 },
2813403Sbmc 	{ "prefetch_data_hits",		KSTAT_DATA_UINT64 },
2823403Sbmc 	{ "prefetch_data_misses",	KSTAT_DATA_UINT64 },
2833403Sbmc 	{ "prefetch_metadata_hits",	KSTAT_DATA_UINT64 },
2843403Sbmc 	{ "prefetch_metadata_misses",	KSTAT_DATA_UINT64 },
2853403Sbmc 	{ "mru_hits",			KSTAT_DATA_UINT64 },
2863403Sbmc 	{ "mru_ghost_hits",		KSTAT_DATA_UINT64 },
2873403Sbmc 	{ "mfu_hits",			KSTAT_DATA_UINT64 },
2883403Sbmc 	{ "mfu_ghost_hits",		KSTAT_DATA_UINT64 },
2893403Sbmc 	{ "deleted",			KSTAT_DATA_UINT64 },
2903403Sbmc 	{ "recycle_miss",		KSTAT_DATA_UINT64 },
2913403Sbmc 	{ "mutex_miss",			KSTAT_DATA_UINT64 },
2923403Sbmc 	{ "evict_skip",			KSTAT_DATA_UINT64 },
2933403Sbmc 	{ "hash_elements",		KSTAT_DATA_UINT64 },
2943403Sbmc 	{ "hash_elements_max",		KSTAT_DATA_UINT64 },
2953403Sbmc 	{ "hash_collisions",		KSTAT_DATA_UINT64 },
2963403Sbmc 	{ "hash_chains",		KSTAT_DATA_UINT64 },
2973403Sbmc 	{ "hash_chain_max",		KSTAT_DATA_UINT64 },
2983403Sbmc 	{ "p",				KSTAT_DATA_UINT64 },
2993403Sbmc 	{ "c",				KSTAT_DATA_UINT64 },
3003403Sbmc 	{ "c_min",			KSTAT_DATA_UINT64 },
3013403Sbmc 	{ "c_max",			KSTAT_DATA_UINT64 },
3025450Sbrendan 	{ "size",			KSTAT_DATA_UINT64 },
3035450Sbrendan 	{ "hdr_size",			KSTAT_DATA_UINT64 },
3045450Sbrendan 	{ "l2_hits",			KSTAT_DATA_UINT64 },
3055450Sbrendan 	{ "l2_misses",			KSTAT_DATA_UINT64 },
3065450Sbrendan 	{ "l2_feeds",			KSTAT_DATA_UINT64 },
3075450Sbrendan 	{ "l2_rw_clash",		KSTAT_DATA_UINT64 },
3085450Sbrendan 	{ "l2_writes_sent",		KSTAT_DATA_UINT64 },
3095450Sbrendan 	{ "l2_writes_done",		KSTAT_DATA_UINT64 },
3105450Sbrendan 	{ "l2_writes_error",		KSTAT_DATA_UINT64 },
3115450Sbrendan 	{ "l2_writes_hdr_miss",		KSTAT_DATA_UINT64 },
3125450Sbrendan 	{ "l2_evict_lock_retry",	KSTAT_DATA_UINT64 },
3135450Sbrendan 	{ "l2_evict_reading",		KSTAT_DATA_UINT64 },
3145450Sbrendan 	{ "l2_free_on_write",		KSTAT_DATA_UINT64 },
3155450Sbrendan 	{ "l2_abort_lowmem",		KSTAT_DATA_UINT64 },
3165450Sbrendan 	{ "l2_cksum_bad",		KSTAT_DATA_UINT64 },
3175450Sbrendan 	{ "l2_io_error",		KSTAT_DATA_UINT64 },
3185450Sbrendan 	{ "l2_size",			KSTAT_DATA_UINT64 },
3196245Smaybee 	{ "l2_hdr_size",		KSTAT_DATA_UINT64 },
3206245Smaybee 	{ "memory_throttle_count",	KSTAT_DATA_UINT64 }
3213403Sbmc };
322789Sahrens 
3233403Sbmc #define	ARCSTAT(stat)	(arc_stats.stat.value.ui64)
3243403Sbmc 
3253403Sbmc #define	ARCSTAT_INCR(stat, val) \
3263403Sbmc 	atomic_add_64(&arc_stats.stat.value.ui64, (val));
3273403Sbmc 
3283403Sbmc #define	ARCSTAT_BUMP(stat) 	ARCSTAT_INCR(stat, 1)
3293403Sbmc #define	ARCSTAT_BUMPDOWN(stat)	ARCSTAT_INCR(stat, -1)
3303403Sbmc 
3313403Sbmc #define	ARCSTAT_MAX(stat, val) {					\
3323403Sbmc 	uint64_t m;							\
3333403Sbmc 	while ((val) > (m = arc_stats.stat.value.ui64) &&		\
3343403Sbmc 	    (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val))))	\
3353403Sbmc 		continue;						\
3363403Sbmc }
3373403Sbmc 
3383403Sbmc #define	ARCSTAT_MAXSTAT(stat) \
3393403Sbmc 	ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
340789Sahrens 
3413403Sbmc /*
3423403Sbmc  * We define a macro to allow ARC hits/misses to be easily broken down by
3433403Sbmc  * two separate conditions, giving a total of four different subtypes for
3443403Sbmc  * each of hits and misses (so eight statistics total).
3453403Sbmc  */
3463403Sbmc #define	ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
3473403Sbmc 	if (cond1) {							\
3483403Sbmc 		if (cond2) {						\
3493403Sbmc 			ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
3503403Sbmc 		} else {						\
3513403Sbmc 			ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
3523403Sbmc 		}							\
3533403Sbmc 	} else {							\
3543403Sbmc 		if (cond2) {						\
3553403Sbmc 			ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
3563403Sbmc 		} else {						\
3573403Sbmc 			ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
3583403Sbmc 		}							\
3593403Sbmc 	}
360789Sahrens 
3613403Sbmc kstat_t			*arc_ksp;
3623403Sbmc static arc_state_t 	*arc_anon;
3633403Sbmc static arc_state_t	*arc_mru;
3643403Sbmc static arc_state_t	*arc_mru_ghost;
3653403Sbmc static arc_state_t	*arc_mfu;
3663403Sbmc static arc_state_t	*arc_mfu_ghost;
3675450Sbrendan static arc_state_t	*arc_l2c_only;
3683403Sbmc 
3693403Sbmc /*
3703403Sbmc  * There are several ARC variables that are critical to export as kstats --
3713403Sbmc  * but we don't want to have to grovel around in the kstat whenever we wish to
3723403Sbmc  * manipulate them.  For these variables, we therefore define them to be in
3733403Sbmc  * terms of the statistic variable.  This assures that we are not introducing
3743403Sbmc  * the possibility of inconsistency by having shadow copies of the variables,
3753403Sbmc  * while still allowing the code to be readable.
3763403Sbmc  */
3773403Sbmc #define	arc_size	ARCSTAT(arcstat_size)	/* actual total arc size */
3783403Sbmc #define	arc_p		ARCSTAT(arcstat_p)	/* target size of MRU */
3793403Sbmc #define	arc_c		ARCSTAT(arcstat_c)	/* target size of cache */
3803403Sbmc #define	arc_c_min	ARCSTAT(arcstat_c_min)	/* min target cache size */
3813403Sbmc #define	arc_c_max	ARCSTAT(arcstat_c_max)	/* max target cache size */
3823403Sbmc 
3833403Sbmc static int		arc_no_grow;	/* Don't try to grow cache size */
3843403Sbmc static uint64_t		arc_tempreserve;
3854309Smaybee static uint64_t		arc_meta_used;
3864309Smaybee static uint64_t		arc_meta_limit;
3874309Smaybee static uint64_t		arc_meta_max = 0;
388789Sahrens 
3895450Sbrendan typedef struct l2arc_buf_hdr l2arc_buf_hdr_t;
3905450Sbrendan 
391789Sahrens typedef struct arc_callback arc_callback_t;
392789Sahrens 
393789Sahrens struct arc_callback {
3943547Smaybee 	void			*acb_private;
395789Sahrens 	arc_done_func_t		*acb_done;
396789Sahrens 	arc_buf_t		*acb_buf;
397789Sahrens 	zio_t			*acb_zio_dummy;
398789Sahrens 	arc_callback_t		*acb_next;
399789Sahrens };
400789Sahrens 
4013547Smaybee typedef struct arc_write_callback arc_write_callback_t;
4023547Smaybee 
4033547Smaybee struct arc_write_callback {
4043547Smaybee 	void		*awcb_private;
4053547Smaybee 	arc_done_func_t	*awcb_ready;
4063547Smaybee 	arc_done_func_t	*awcb_done;
4073547Smaybee 	arc_buf_t	*awcb_buf;
4083547Smaybee };
4093547Smaybee 
410789Sahrens struct arc_buf_hdr {
411789Sahrens 	/* protected by hash lock */
412789Sahrens 	dva_t			b_dva;
413789Sahrens 	uint64_t		b_birth;
414789Sahrens 	uint64_t		b_cksum0;
415789Sahrens 
4163093Sahrens 	kmutex_t		b_freeze_lock;
4173093Sahrens 	zio_cksum_t		*b_freeze_cksum;
4183093Sahrens 
419789Sahrens 	arc_buf_hdr_t		*b_hash_next;
420789Sahrens 	arc_buf_t		*b_buf;
421789Sahrens 	uint32_t		b_flags;
4221544Seschrock 	uint32_t		b_datacnt;
423789Sahrens 
4243290Sjohansen 	arc_callback_t		*b_acb;
425789Sahrens 	kcondvar_t		b_cv;
4263290Sjohansen 
4273290Sjohansen 	/* immutable */
4283290Sjohansen 	arc_buf_contents_t	b_type;
4293290Sjohansen 	uint64_t		b_size;
4303290Sjohansen 	spa_t			*b_spa;
431789Sahrens 
432789Sahrens 	/* protected by arc state mutex */
433789Sahrens 	arc_state_t		*b_state;
434789Sahrens 	list_node_t		b_arc_node;
435789Sahrens 
436789Sahrens 	/* updated atomically */
437789Sahrens 	clock_t			b_arc_access;
438789Sahrens 
439789Sahrens 	/* self protecting */
440789Sahrens 	refcount_t		b_refcnt;
4415450Sbrendan 
4425450Sbrendan 	l2arc_buf_hdr_t		*b_l2hdr;
4435450Sbrendan 	list_node_t		b_l2node;
444*7046Sahrens 	/*
445*7046Sahrens 	 * scrub code can lockout access to the buf while it changes
446*7046Sahrens 	 * bp's contained within it.
447*7046Sahrens 	 */
448*7046Sahrens 	krwlock_t		b_datalock;
449789Sahrens };
450789Sahrens 
4511544Seschrock static arc_buf_t *arc_eviction_list;
4521544Seschrock static kmutex_t arc_eviction_mtx;
4532887Smaybee static arc_buf_hdr_t arc_eviction_hdr;
4542688Smaybee static void arc_get_data_buf(arc_buf_t *buf);
4552688Smaybee static void arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock);
4564309Smaybee static int arc_evict_needed(arc_buf_contents_t type);
4575642Smaybee static void arc_evict_ghost(arc_state_t *state, spa_t *spa, int64_t bytes);
4581544Seschrock 
4591544Seschrock #define	GHOST_STATE(state)	\
4605450Sbrendan 	((state) == arc_mru_ghost || (state) == arc_mfu_ghost ||	\
4615450Sbrendan 	(state) == arc_l2c_only)
4621544Seschrock 
463789Sahrens /*
464789Sahrens  * Private ARC flags.  These flags are private ARC only flags that will show up
465789Sahrens  * in b_flags in the arc_hdr_buf_t.  Some flags are publicly declared, and can
466789Sahrens  * be passed in as arc_flags in things like arc_read.  However, these flags
467789Sahrens  * should never be passed and should only be set by ARC code.  When adding new
468789Sahrens  * public flags, make sure not to smash the private ones.
469789Sahrens  */
470789Sahrens 
4711544Seschrock #define	ARC_IN_HASH_TABLE	(1 << 9)	/* this buffer is hashed */
472789Sahrens #define	ARC_IO_IN_PROGRESS	(1 << 10)	/* I/O in progress for buf */
473789Sahrens #define	ARC_IO_ERROR		(1 << 11)	/* I/O failed for buf */
474789Sahrens #define	ARC_FREED_IN_READ	(1 << 12)	/* buf freed while in read */
4751544Seschrock #define	ARC_BUF_AVAILABLE	(1 << 13)	/* block not in active use */
4762391Smaybee #define	ARC_INDIRECT		(1 << 14)	/* this is an indirect block */
4775450Sbrendan #define	ARC_FREE_IN_PROGRESS	(1 << 15)	/* hdr about to be freed */
4785450Sbrendan #define	ARC_DONT_L2CACHE	(1 << 16)	/* originated by prefetch */
4796987Sbrendan #define	ARC_L2_WRITING		(1 << 17)	/* L2ARC write in progress */
4806987Sbrendan #define	ARC_L2_EVICTED		(1 << 18)	/* evicted during I/O */
4816987Sbrendan #define	ARC_L2_WRITE_HEAD	(1 << 19)	/* head of write list */
482*7046Sahrens #define	ARC_STORED		(1 << 20)	/* has been store()d to */
483789Sahrens 
4841544Seschrock #define	HDR_IN_HASH_TABLE(hdr)	((hdr)->b_flags & ARC_IN_HASH_TABLE)
485789Sahrens #define	HDR_IO_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_IO_IN_PROGRESS)
486789Sahrens #define	HDR_IO_ERROR(hdr)	((hdr)->b_flags & ARC_IO_ERROR)
487789Sahrens #define	HDR_FREED_IN_READ(hdr)	((hdr)->b_flags & ARC_FREED_IN_READ)
4881544Seschrock #define	HDR_BUF_AVAILABLE(hdr)	((hdr)->b_flags & ARC_BUF_AVAILABLE)
4895450Sbrendan #define	HDR_FREE_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_FREE_IN_PROGRESS)
4905450Sbrendan #define	HDR_DONT_L2CACHE(hdr)	((hdr)->b_flags & ARC_DONT_L2CACHE)
4916987Sbrendan #define	HDR_L2_READING(hdr)	((hdr)->b_flags & ARC_IO_IN_PROGRESS &&	\
4926987Sbrendan 				    (hdr)->b_l2hdr != NULL)
4935450Sbrendan #define	HDR_L2_WRITING(hdr)	((hdr)->b_flags & ARC_L2_WRITING)
4945450Sbrendan #define	HDR_L2_EVICTED(hdr)	((hdr)->b_flags & ARC_L2_EVICTED)
4955450Sbrendan #define	HDR_L2_WRITE_HEAD(hdr)	((hdr)->b_flags & ARC_L2_WRITE_HEAD)
496789Sahrens 
497789Sahrens /*
4986018Sbrendan  * Other sizes
4996018Sbrendan  */
5006018Sbrendan 
5016018Sbrendan #define	HDR_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
5026018Sbrendan #define	L2HDR_SIZE ((int64_t)sizeof (l2arc_buf_hdr_t))
5036018Sbrendan 
5046018Sbrendan /*
505789Sahrens  * Hash table routines
506789Sahrens  */
507789Sahrens 
508789Sahrens #define	HT_LOCK_PAD	64
509789Sahrens 
510789Sahrens struct ht_lock {
511789Sahrens 	kmutex_t	ht_lock;
512789Sahrens #ifdef _KERNEL
513789Sahrens 	unsigned char	pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
514789Sahrens #endif
515789Sahrens };
516789Sahrens 
517789Sahrens #define	BUF_LOCKS 256
518789Sahrens typedef struct buf_hash_table {
519789Sahrens 	uint64_t ht_mask;
520789Sahrens 	arc_buf_hdr_t **ht_table;
521789Sahrens 	struct ht_lock ht_locks[BUF_LOCKS];
522789Sahrens } buf_hash_table_t;
523789Sahrens 
524789Sahrens static buf_hash_table_t buf_hash_table;
525789Sahrens 
526789Sahrens #define	BUF_HASH_INDEX(spa, dva, birth) \
527789Sahrens 	(buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
528789Sahrens #define	BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
529789Sahrens #define	BUF_HASH_LOCK(idx)	(&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
530789Sahrens #define	HDR_LOCK(buf) \
531789Sahrens 	(BUF_HASH_LOCK(BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth)))
532789Sahrens 
533789Sahrens uint64_t zfs_crc64_table[256];
534789Sahrens 
5355450Sbrendan /*
5365450Sbrendan  * Level 2 ARC
5375450Sbrendan  */
5385450Sbrendan 
5395450Sbrendan #define	L2ARC_WRITE_SIZE	(8 * 1024 * 1024)	/* initial write max */
5405450Sbrendan #define	L2ARC_HEADROOM		4		/* num of writes */
5415450Sbrendan #define	L2ARC_FEED_SECS		1		/* caching interval */
5425450Sbrendan 
5435450Sbrendan #define	l2arc_writes_sent	ARCSTAT(arcstat_l2_writes_sent)
5445450Sbrendan #define	l2arc_writes_done	ARCSTAT(arcstat_l2_writes_done)
5455450Sbrendan 
5465450Sbrendan /*
5475450Sbrendan  * L2ARC Performance Tunables
5485450Sbrendan  */
5495450Sbrendan uint64_t l2arc_write_max = L2ARC_WRITE_SIZE;	/* default max write size */
5506987Sbrendan uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE;	/* extra write during warmup */
5515450Sbrendan uint64_t l2arc_headroom = L2ARC_HEADROOM;	/* number of dev writes */
5525450Sbrendan uint64_t l2arc_feed_secs = L2ARC_FEED_SECS;	/* interval seconds */
5535450Sbrendan boolean_t l2arc_noprefetch = B_TRUE;		/* don't cache prefetch bufs */
5545450Sbrendan 
5555450Sbrendan /*
5565450Sbrendan  * L2ARC Internals
5575450Sbrendan  */
5585450Sbrendan typedef struct l2arc_dev {
5595450Sbrendan 	vdev_t			*l2ad_vdev;	/* vdev */
5605450Sbrendan 	spa_t			*l2ad_spa;	/* spa */
5615450Sbrendan 	uint64_t		l2ad_hand;	/* next write location */
5625450Sbrendan 	uint64_t		l2ad_write;	/* desired write size, bytes */
5636987Sbrendan 	uint64_t		l2ad_boost;	/* warmup write boost, bytes */
5645450Sbrendan 	uint64_t		l2ad_start;	/* first addr on device */
5655450Sbrendan 	uint64_t		l2ad_end;	/* last addr on device */
5665450Sbrendan 	uint64_t		l2ad_evict;	/* last addr eviction reached */
5675450Sbrendan 	boolean_t		l2ad_first;	/* first sweep through */
5685450Sbrendan 	list_t			*l2ad_buflist;	/* buffer list */
5695450Sbrendan 	list_node_t		l2ad_node;	/* device list node */
5705450Sbrendan } l2arc_dev_t;
5715450Sbrendan 
5725450Sbrendan static list_t L2ARC_dev_list;			/* device list */
5735450Sbrendan static list_t *l2arc_dev_list;			/* device list pointer */
5745450Sbrendan static kmutex_t l2arc_dev_mtx;			/* device list mutex */
5755450Sbrendan static l2arc_dev_t *l2arc_dev_last;		/* last device used */
5765450Sbrendan static kmutex_t l2arc_buflist_mtx;		/* mutex for all buflists */
5775450Sbrendan static list_t L2ARC_free_on_write;		/* free after write buf list */
5785450Sbrendan static list_t *l2arc_free_on_write;		/* free after write list ptr */
5795450Sbrendan static kmutex_t l2arc_free_on_write_mtx;	/* mutex for list */
5805450Sbrendan static uint64_t l2arc_ndev;			/* number of devices */
5815450Sbrendan 
5825450Sbrendan typedef struct l2arc_read_callback {
5835450Sbrendan 	arc_buf_t	*l2rcb_buf;		/* read buffer */
5845450Sbrendan 	spa_t		*l2rcb_spa;		/* spa */
5855450Sbrendan 	blkptr_t	l2rcb_bp;		/* original blkptr */
5865450Sbrendan 	zbookmark_t	l2rcb_zb;		/* original bookmark */
5875450Sbrendan 	int		l2rcb_flags;		/* original flags */
5885450Sbrendan } l2arc_read_callback_t;
5895450Sbrendan 
5905450Sbrendan typedef struct l2arc_write_callback {
5915450Sbrendan 	l2arc_dev_t	*l2wcb_dev;		/* device info */
5925450Sbrendan 	arc_buf_hdr_t	*l2wcb_head;		/* head of write buflist */
5935450Sbrendan } l2arc_write_callback_t;
5945450Sbrendan 
5955450Sbrendan struct l2arc_buf_hdr {
5965450Sbrendan 	/* protected by arc_buf_hdr  mutex */
5975450Sbrendan 	l2arc_dev_t	*b_dev;			/* L2ARC device */
5985450Sbrendan 	daddr_t		b_daddr;		/* disk address, offset byte */
5995450Sbrendan };
6005450Sbrendan 
6015450Sbrendan typedef struct l2arc_data_free {
6025450Sbrendan 	/* protected by l2arc_free_on_write_mtx */
6035450Sbrendan 	void		*l2df_data;
6045450Sbrendan 	size_t		l2df_size;
6055450Sbrendan 	void		(*l2df_func)(void *, size_t);
6065450Sbrendan 	list_node_t	l2df_list_node;
6075450Sbrendan } l2arc_data_free_t;
6085450Sbrendan 
6095450Sbrendan static kmutex_t l2arc_feed_thr_lock;
6105450Sbrendan static kcondvar_t l2arc_feed_thr_cv;
6115450Sbrendan static uint8_t l2arc_thread_exit;
6125450Sbrendan 
6135450Sbrendan static void l2arc_read_done(zio_t *zio);
6145450Sbrendan static void l2arc_hdr_stat_add(void);
6155450Sbrendan static void l2arc_hdr_stat_remove(void);
6165450Sbrendan 
617789Sahrens static uint64_t
618*7046Sahrens buf_hash(spa_t *spa, const dva_t *dva, uint64_t birth)
619789Sahrens {
620789Sahrens 	uintptr_t spav = (uintptr_t)spa;
621789Sahrens 	uint8_t *vdva = (uint8_t *)dva;
622789Sahrens 	uint64_t crc = -1ULL;
623789Sahrens 	int i;
624789Sahrens 
625789Sahrens 	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
626789Sahrens 
627789Sahrens 	for (i = 0; i < sizeof (dva_t); i++)
628789Sahrens 		crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
629789Sahrens 
630789Sahrens 	crc ^= (spav>>8) ^ birth;
631789Sahrens 
632789Sahrens 	return (crc);
633789Sahrens }
634789Sahrens 
635789Sahrens #define	BUF_EMPTY(buf)						\
636789Sahrens 	((buf)->b_dva.dva_word[0] == 0 &&			\
637789Sahrens 	(buf)->b_dva.dva_word[1] == 0 &&			\
638789Sahrens 	(buf)->b_birth == 0)
639789Sahrens 
640789Sahrens #define	BUF_EQUAL(spa, dva, birth, buf)				\
641789Sahrens 	((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) &&	\
642789Sahrens 	((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) &&	\
643789Sahrens 	((buf)->b_birth == birth) && ((buf)->b_spa == spa)
644789Sahrens 
645789Sahrens static arc_buf_hdr_t *
646*7046Sahrens buf_hash_find(spa_t *spa, const dva_t *dva, uint64_t birth, kmutex_t **lockp)
647789Sahrens {
648789Sahrens 	uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
649789Sahrens 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
650789Sahrens 	arc_buf_hdr_t *buf;
651789Sahrens 
652789Sahrens 	mutex_enter(hash_lock);
653789Sahrens 	for (buf = buf_hash_table.ht_table[idx]; buf != NULL;
654789Sahrens 	    buf = buf->b_hash_next) {
655789Sahrens 		if (BUF_EQUAL(spa, dva, birth, buf)) {
656789Sahrens 			*lockp = hash_lock;
657789Sahrens 			return (buf);
658789Sahrens 		}
659789Sahrens 	}
660789Sahrens 	mutex_exit(hash_lock);
661789Sahrens 	*lockp = NULL;
662789Sahrens 	return (NULL);
663789Sahrens }
664789Sahrens 
665789Sahrens /*
666789Sahrens  * Insert an entry into the hash table.  If there is already an element
667789Sahrens  * equal to elem in the hash table, then the already existing element
668789Sahrens  * will be returned and the new element will not be inserted.
669789Sahrens  * Otherwise returns NULL.
670789Sahrens  */
671789Sahrens static arc_buf_hdr_t *
672789Sahrens buf_hash_insert(arc_buf_hdr_t *buf, kmutex_t **lockp)
673789Sahrens {
674789Sahrens 	uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
675789Sahrens 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
676789Sahrens 	arc_buf_hdr_t *fbuf;
6773403Sbmc 	uint32_t i;
678789Sahrens 
6791544Seschrock 	ASSERT(!HDR_IN_HASH_TABLE(buf));
680789Sahrens 	*lockp = hash_lock;
681789Sahrens 	mutex_enter(hash_lock);
682789Sahrens 	for (fbuf = buf_hash_table.ht_table[idx], i = 0; fbuf != NULL;
683789Sahrens 	    fbuf = fbuf->b_hash_next, i++) {
684789Sahrens 		if (BUF_EQUAL(buf->b_spa, &buf->b_dva, buf->b_birth, fbuf))
685789Sahrens 			return (fbuf);
686789Sahrens 	}
687789Sahrens 
688789Sahrens 	buf->b_hash_next = buf_hash_table.ht_table[idx];
689789Sahrens 	buf_hash_table.ht_table[idx] = buf;
6901544Seschrock 	buf->b_flags |= ARC_IN_HASH_TABLE;
691789Sahrens 
692789Sahrens 	/* collect some hash table performance data */
693789Sahrens 	if (i > 0) {
6943403Sbmc 		ARCSTAT_BUMP(arcstat_hash_collisions);
695789Sahrens 		if (i == 1)
6963403Sbmc 			ARCSTAT_BUMP(arcstat_hash_chains);
6973403Sbmc 
6983403Sbmc 		ARCSTAT_MAX(arcstat_hash_chain_max, i);
699789Sahrens 	}
7003403Sbmc 
7013403Sbmc 	ARCSTAT_BUMP(arcstat_hash_elements);
7023403Sbmc 	ARCSTAT_MAXSTAT(arcstat_hash_elements);
703789Sahrens 
704789Sahrens 	return (NULL);
705789Sahrens }
706789Sahrens 
707789Sahrens static void
708789Sahrens buf_hash_remove(arc_buf_hdr_t *buf)
709789Sahrens {
710789Sahrens 	arc_buf_hdr_t *fbuf, **bufp;
711789Sahrens 	uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
712789Sahrens 
713789Sahrens 	ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
7141544Seschrock 	ASSERT(HDR_IN_HASH_TABLE(buf));
715789Sahrens 
716789Sahrens 	bufp = &buf_hash_table.ht_table[idx];
717789Sahrens 	while ((fbuf = *bufp) != buf) {
718789Sahrens 		ASSERT(fbuf != NULL);
719789Sahrens 		bufp = &fbuf->b_hash_next;
720789Sahrens 	}
721789Sahrens 	*bufp = buf->b_hash_next;
722789Sahrens 	buf->b_hash_next = NULL;
7231544Seschrock 	buf->b_flags &= ~ARC_IN_HASH_TABLE;
724789Sahrens 
725789Sahrens 	/* collect some hash table performance data */
7263403Sbmc 	ARCSTAT_BUMPDOWN(arcstat_hash_elements);
7273403Sbmc 
728789Sahrens 	if (buf_hash_table.ht_table[idx] &&
729789Sahrens 	    buf_hash_table.ht_table[idx]->b_hash_next == NULL)
7303403Sbmc 		ARCSTAT_BUMPDOWN(arcstat_hash_chains);
731789Sahrens }
732789Sahrens 
733789Sahrens /*
734789Sahrens  * Global data structures and functions for the buf kmem cache.
735789Sahrens  */
736789Sahrens static kmem_cache_t *hdr_cache;
737789Sahrens static kmem_cache_t *buf_cache;
738789Sahrens 
739789Sahrens static void
740789Sahrens buf_fini(void)
741789Sahrens {
742789Sahrens 	int i;
743789Sahrens 
744789Sahrens 	kmem_free(buf_hash_table.ht_table,
745789Sahrens 	    (buf_hash_table.ht_mask + 1) * sizeof (void *));
746789Sahrens 	for (i = 0; i < BUF_LOCKS; i++)
747789Sahrens 		mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
748789Sahrens 	kmem_cache_destroy(hdr_cache);
749789Sahrens 	kmem_cache_destroy(buf_cache);
750789Sahrens }
751789Sahrens 
752789Sahrens /*
753789Sahrens  * Constructor callback - called when the cache is empty
754789Sahrens  * and a new buf is requested.
755789Sahrens  */
756789Sahrens /* ARGSUSED */
757789Sahrens static int
758789Sahrens hdr_cons(void *vbuf, void *unused, int kmflag)
759789Sahrens {
760789Sahrens 	arc_buf_hdr_t *buf = vbuf;
761789Sahrens 
762789Sahrens 	bzero(buf, sizeof (arc_buf_hdr_t));
763789Sahrens 	refcount_create(&buf->b_refcnt);
764789Sahrens 	cv_init(&buf->b_cv, NULL, CV_DEFAULT, NULL);
7654831Sgw25295 	mutex_init(&buf->b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
766*7046Sahrens 	rw_init(&buf->b_datalock, NULL, RW_DEFAULT, NULL);
7675450Sbrendan 
7686018Sbrendan 	ARCSTAT_INCR(arcstat_hdr_size, HDR_SIZE);
769789Sahrens 	return (0);
770789Sahrens }
771789Sahrens 
772789Sahrens /*
773789Sahrens  * Destructor callback - called when a cached buf is
774789Sahrens  * no longer required.
775789Sahrens  */
776789Sahrens /* ARGSUSED */
777789Sahrens static void
778789Sahrens hdr_dest(void *vbuf, void *unused)
779789Sahrens {
780789Sahrens 	arc_buf_hdr_t *buf = vbuf;
781789Sahrens 
782789Sahrens 	refcount_destroy(&buf->b_refcnt);
783789Sahrens 	cv_destroy(&buf->b_cv);
7844831Sgw25295 	mutex_destroy(&buf->b_freeze_lock);
785*7046Sahrens 	rw_destroy(&buf->b_datalock);
7865450Sbrendan 
7876018Sbrendan 	ARCSTAT_INCR(arcstat_hdr_size, -HDR_SIZE);
788789Sahrens }
789789Sahrens 
790789Sahrens /*
791789Sahrens  * Reclaim callback -- invoked when memory is low.
792789Sahrens  */
793789Sahrens /* ARGSUSED */
794789Sahrens static void
795789Sahrens hdr_recl(void *unused)
796789Sahrens {
797789Sahrens 	dprintf("hdr_recl called\n");
7983158Smaybee 	/*
7993158Smaybee 	 * umem calls the reclaim func when we destroy the buf cache,
8003158Smaybee 	 * which is after we do arc_fini().
8013158Smaybee 	 */
8023158Smaybee 	if (!arc_dead)
8033158Smaybee 		cv_signal(&arc_reclaim_thr_cv);
804789Sahrens }
805789Sahrens 
806789Sahrens static void
807789Sahrens buf_init(void)
808789Sahrens {
809789Sahrens 	uint64_t *ct;
8101544Seschrock 	uint64_t hsize = 1ULL << 12;
811789Sahrens 	int i, j;
812789Sahrens 
813789Sahrens 	/*
814789Sahrens 	 * The hash table is big enough to fill all of physical memory
8151544Seschrock 	 * with an average 64K block size.  The table will take up
8161544Seschrock 	 * totalmem*sizeof(void*)/64K (eg. 128KB/GB with 8-byte pointers).
817789Sahrens 	 */
8181544Seschrock 	while (hsize * 65536 < physmem * PAGESIZE)
819789Sahrens 		hsize <<= 1;
8201544Seschrock retry:
821789Sahrens 	buf_hash_table.ht_mask = hsize - 1;
8221544Seschrock 	buf_hash_table.ht_table =
8231544Seschrock 	    kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
8241544Seschrock 	if (buf_hash_table.ht_table == NULL) {
8251544Seschrock 		ASSERT(hsize > (1ULL << 8));
8261544Seschrock 		hsize >>= 1;
8271544Seschrock 		goto retry;
8281544Seschrock 	}
829789Sahrens 
830789Sahrens 	hdr_cache = kmem_cache_create("arc_buf_hdr_t", sizeof (arc_buf_hdr_t),
831789Sahrens 	    0, hdr_cons, hdr_dest, hdr_recl, NULL, NULL, 0);
832789Sahrens 	buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
833789Sahrens 	    0, NULL, NULL, NULL, NULL, NULL, 0);
834789Sahrens 
835789Sahrens 	for (i = 0; i < 256; i++)
836789Sahrens 		for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
837789Sahrens 			*ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
838789Sahrens 
839789Sahrens 	for (i = 0; i < BUF_LOCKS; i++) {
840789Sahrens 		mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
841789Sahrens 		    NULL, MUTEX_DEFAULT, NULL);
842789Sahrens 	}
843789Sahrens }
844789Sahrens 
845789Sahrens #define	ARC_MINTIME	(hz>>4) /* 62 ms */
846789Sahrens 
847789Sahrens static void
8483093Sahrens arc_cksum_verify(arc_buf_t *buf)
8493093Sahrens {
8503093Sahrens 	zio_cksum_t zc;
8513093Sahrens 
8523312Sahrens 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
8533093Sahrens 		return;
8543093Sahrens 
8553093Sahrens 	mutex_enter(&buf->b_hdr->b_freeze_lock);
8563265Sahrens 	if (buf->b_hdr->b_freeze_cksum == NULL ||
8573265Sahrens 	    (buf->b_hdr->b_flags & ARC_IO_ERROR)) {
8583093Sahrens 		mutex_exit(&buf->b_hdr->b_freeze_lock);
8593093Sahrens 		return;
8603093Sahrens 	}
8613093Sahrens 	fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
8623093Sahrens 	if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
8633093Sahrens 		panic("buffer modified while frozen!");
8643093Sahrens 	mutex_exit(&buf->b_hdr->b_freeze_lock);
8653093Sahrens }
8663093Sahrens 
8675450Sbrendan static int
8685450Sbrendan arc_cksum_equal(arc_buf_t *buf)
8695450Sbrendan {
8705450Sbrendan 	zio_cksum_t zc;
8715450Sbrendan 	int equal;
8725450Sbrendan 
8735450Sbrendan 	mutex_enter(&buf->b_hdr->b_freeze_lock);
8745450Sbrendan 	fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
8755450Sbrendan 	equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
8765450Sbrendan 	mutex_exit(&buf->b_hdr->b_freeze_lock);
8775450Sbrendan 
8785450Sbrendan 	return (equal);
8795450Sbrendan }
8805450Sbrendan 
8813093Sahrens static void
8825450Sbrendan arc_cksum_compute(arc_buf_t *buf, boolean_t force)
8833093Sahrens {
8845450Sbrendan 	if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
8853093Sahrens 		return;
8863093Sahrens 
8873093Sahrens 	mutex_enter(&buf->b_hdr->b_freeze_lock);
8883093Sahrens 	if (buf->b_hdr->b_freeze_cksum != NULL) {
8893093Sahrens 		mutex_exit(&buf->b_hdr->b_freeze_lock);
8903093Sahrens 		return;
8913093Sahrens 	}
8923093Sahrens 	buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
8933093Sahrens 	fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
8943093Sahrens 	    buf->b_hdr->b_freeze_cksum);
8953093Sahrens 	mutex_exit(&buf->b_hdr->b_freeze_lock);
8963093Sahrens }
8973093Sahrens 
8983093Sahrens void
8993093Sahrens arc_buf_thaw(arc_buf_t *buf)
9003093Sahrens {
9015450Sbrendan 	if (zfs_flags & ZFS_DEBUG_MODIFY) {
9025450Sbrendan 		if (buf->b_hdr->b_state != arc_anon)
9035450Sbrendan 			panic("modifying non-anon buffer!");
9045450Sbrendan 		if (buf->b_hdr->b_flags & ARC_IO_IN_PROGRESS)
9055450Sbrendan 			panic("modifying buffer while i/o in progress!");
9065450Sbrendan 		arc_cksum_verify(buf);
9075450Sbrendan 	}
9085450Sbrendan 
9093093Sahrens 	mutex_enter(&buf->b_hdr->b_freeze_lock);
9103093Sahrens 	if (buf->b_hdr->b_freeze_cksum != NULL) {
9113093Sahrens 		kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
9123093Sahrens 		buf->b_hdr->b_freeze_cksum = NULL;
9133093Sahrens 	}
9143093Sahrens 	mutex_exit(&buf->b_hdr->b_freeze_lock);
9153093Sahrens }
9163093Sahrens 
9173093Sahrens void
9183093Sahrens arc_buf_freeze(arc_buf_t *buf)
9193093Sahrens {
9203312Sahrens 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
9213312Sahrens 		return;
9223312Sahrens 
9233093Sahrens 	ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
9243403Sbmc 	    buf->b_hdr->b_state == arc_anon);
9255450Sbrendan 	arc_cksum_compute(buf, B_FALSE);
9263093Sahrens }
9273093Sahrens 
9283093Sahrens static void
929789Sahrens add_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
930789Sahrens {
931789Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
932789Sahrens 
933789Sahrens 	if ((refcount_add(&ab->b_refcnt, tag) == 1) &&
9343403Sbmc 	    (ab->b_state != arc_anon)) {
9353700Sek110237 		uint64_t delta = ab->b_size * ab->b_datacnt;
9364309Smaybee 		list_t *list = &ab->b_state->arcs_list[ab->b_type];
9374309Smaybee 		uint64_t *size = &ab->b_state->arcs_lsize[ab->b_type];
938789Sahrens 
9393403Sbmc 		ASSERT(!MUTEX_HELD(&ab->b_state->arcs_mtx));
9403403Sbmc 		mutex_enter(&ab->b_state->arcs_mtx);
941789Sahrens 		ASSERT(list_link_active(&ab->b_arc_node));
9424309Smaybee 		list_remove(list, ab);
9431544Seschrock 		if (GHOST_STATE(ab->b_state)) {
9441544Seschrock 			ASSERT3U(ab->b_datacnt, ==, 0);
9451544Seschrock 			ASSERT3P(ab->b_buf, ==, NULL);
9461544Seschrock 			delta = ab->b_size;
9471544Seschrock 		}
9481544Seschrock 		ASSERT(delta > 0);
9494309Smaybee 		ASSERT3U(*size, >=, delta);
9504309Smaybee 		atomic_add_64(size, -delta);
9513403Sbmc 		mutex_exit(&ab->b_state->arcs_mtx);
952*7046Sahrens 		/* remove the prefetch flag if we get a reference */
9532391Smaybee 		if (ab->b_flags & ARC_PREFETCH)
9542391Smaybee 			ab->b_flags &= ~ARC_PREFETCH;
955789Sahrens 	}
956789Sahrens }
957789Sahrens 
958789Sahrens static int
959789Sahrens remove_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
960789Sahrens {
961789Sahrens 	int cnt;
9623403Sbmc 	arc_state_t *state = ab->b_state;
963789Sahrens 
9643403Sbmc 	ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
9653403Sbmc 	ASSERT(!GHOST_STATE(state));
966789Sahrens 
967789Sahrens 	if (((cnt = refcount_remove(&ab->b_refcnt, tag)) == 0) &&
9683403Sbmc 	    (state != arc_anon)) {
9694309Smaybee 		uint64_t *size = &state->arcs_lsize[ab->b_type];
9704309Smaybee 
9713403Sbmc 		ASSERT(!MUTEX_HELD(&state->arcs_mtx));
9723403Sbmc 		mutex_enter(&state->arcs_mtx);
973789Sahrens 		ASSERT(!list_link_active(&ab->b_arc_node));
9744309Smaybee 		list_insert_head(&state->arcs_list[ab->b_type], ab);
9751544Seschrock 		ASSERT(ab->b_datacnt > 0);
9764309Smaybee 		atomic_add_64(size, ab->b_size * ab->b_datacnt);
9773403Sbmc 		mutex_exit(&state->arcs_mtx);
978789Sahrens 	}
979789Sahrens 	return (cnt);
980789Sahrens }
981789Sahrens 
982789Sahrens /*
983789Sahrens  * Move the supplied buffer to the indicated state.  The mutex
984789Sahrens  * for the buffer must be held by the caller.
985789Sahrens  */
986789Sahrens static void
9871544Seschrock arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *ab, kmutex_t *hash_lock)
988789Sahrens {
9891544Seschrock 	arc_state_t *old_state = ab->b_state;
9903700Sek110237 	int64_t refcnt = refcount_count(&ab->b_refcnt);
9913700Sek110237 	uint64_t from_delta, to_delta;
992789Sahrens 
993789Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
9941544Seschrock 	ASSERT(new_state != old_state);
9951544Seschrock 	ASSERT(refcnt == 0 || ab->b_datacnt > 0);
9961544Seschrock 	ASSERT(ab->b_datacnt == 0 || !GHOST_STATE(new_state));
9971544Seschrock 
9981544Seschrock 	from_delta = to_delta = ab->b_datacnt * ab->b_size;
999789Sahrens 
1000789Sahrens 	/*
1001789Sahrens 	 * If this buffer is evictable, transfer it from the
1002789Sahrens 	 * old state list to the new state list.
1003789Sahrens 	 */
10041544Seschrock 	if (refcnt == 0) {
10053403Sbmc 		if (old_state != arc_anon) {
10063403Sbmc 			int use_mutex = !MUTEX_HELD(&old_state->arcs_mtx);
10074309Smaybee 			uint64_t *size = &old_state->arcs_lsize[ab->b_type];
10081544Seschrock 
10091544Seschrock 			if (use_mutex)
10103403Sbmc 				mutex_enter(&old_state->arcs_mtx);
10111544Seschrock 
10121544Seschrock 			ASSERT(list_link_active(&ab->b_arc_node));
10134309Smaybee 			list_remove(&old_state->arcs_list[ab->b_type], ab);
1014789Sahrens 
10152391Smaybee 			/*
10162391Smaybee 			 * If prefetching out of the ghost cache,
10172391Smaybee 			 * we will have a non-null datacnt.
10182391Smaybee 			 */
10192391Smaybee 			if (GHOST_STATE(old_state) && ab->b_datacnt == 0) {
10202391Smaybee 				/* ghost elements have a ghost size */
10211544Seschrock 				ASSERT(ab->b_buf == NULL);
10221544Seschrock 				from_delta = ab->b_size;
1023789Sahrens 			}
10244309Smaybee 			ASSERT3U(*size, >=, from_delta);
10254309Smaybee 			atomic_add_64(size, -from_delta);
10261544Seschrock 
10271544Seschrock 			if (use_mutex)
10283403Sbmc 				mutex_exit(&old_state->arcs_mtx);
1029789Sahrens 		}
10303403Sbmc 		if (new_state != arc_anon) {
10313403Sbmc 			int use_mutex = !MUTEX_HELD(&new_state->arcs_mtx);
10324309Smaybee 			uint64_t *size = &new_state->arcs_lsize[ab->b_type];
1033789Sahrens 
10341544Seschrock 			if (use_mutex)
10353403Sbmc 				mutex_enter(&new_state->arcs_mtx);
10361544Seschrock 
10374309Smaybee 			list_insert_head(&new_state->arcs_list[ab->b_type], ab);
10381544Seschrock 
10391544Seschrock 			/* ghost elements have a ghost size */
10401544Seschrock 			if (GHOST_STATE(new_state)) {
10411544Seschrock 				ASSERT(ab->b_datacnt == 0);
10421544Seschrock 				ASSERT(ab->b_buf == NULL);
10431544Seschrock 				to_delta = ab->b_size;
10441544Seschrock 			}
10454309Smaybee 			atomic_add_64(size, to_delta);
10461544Seschrock 
10471544Seschrock 			if (use_mutex)
10483403Sbmc 				mutex_exit(&new_state->arcs_mtx);
1049789Sahrens 		}
1050789Sahrens 	}
1051789Sahrens 
1052789Sahrens 	ASSERT(!BUF_EMPTY(ab));
10535450Sbrendan 	if (new_state == arc_anon) {
1054789Sahrens 		buf_hash_remove(ab);
1055789Sahrens 	}
1056789Sahrens 
10571544Seschrock 	/* adjust state sizes */
10581544Seschrock 	if (to_delta)
10593403Sbmc 		atomic_add_64(&new_state->arcs_size, to_delta);
10601544Seschrock 	if (from_delta) {
10613403Sbmc 		ASSERT3U(old_state->arcs_size, >=, from_delta);
10623403Sbmc 		atomic_add_64(&old_state->arcs_size, -from_delta);
1063789Sahrens 	}
1064789Sahrens 	ab->b_state = new_state;
10655450Sbrendan 
10665450Sbrendan 	/* adjust l2arc hdr stats */
10675450Sbrendan 	if (new_state == arc_l2c_only)
10685450Sbrendan 		l2arc_hdr_stat_add();
10695450Sbrendan 	else if (old_state == arc_l2c_only)
10705450Sbrendan 		l2arc_hdr_stat_remove();
1071789Sahrens }
1072789Sahrens 
10734309Smaybee void
10744309Smaybee arc_space_consume(uint64_t space)
10754309Smaybee {
10764309Smaybee 	atomic_add_64(&arc_meta_used, space);
10774309Smaybee 	atomic_add_64(&arc_size, space);
10784309Smaybee }
10794309Smaybee 
10804309Smaybee void
10814309Smaybee arc_space_return(uint64_t space)
10824309Smaybee {
10834309Smaybee 	ASSERT(arc_meta_used >= space);
10844309Smaybee 	if (arc_meta_max < arc_meta_used)
10854309Smaybee 		arc_meta_max = arc_meta_used;
10864309Smaybee 	atomic_add_64(&arc_meta_used, -space);
10874309Smaybee 	ASSERT(arc_size >= space);
10884309Smaybee 	atomic_add_64(&arc_size, -space);
10894309Smaybee }
10904309Smaybee 
10914309Smaybee void *
10924309Smaybee arc_data_buf_alloc(uint64_t size)
10934309Smaybee {
10944309Smaybee 	if (arc_evict_needed(ARC_BUFC_DATA))
10954309Smaybee 		cv_signal(&arc_reclaim_thr_cv);
10964309Smaybee 	atomic_add_64(&arc_size, size);
10974309Smaybee 	return (zio_data_buf_alloc(size));
10984309Smaybee }
10994309Smaybee 
11004309Smaybee void
11014309Smaybee arc_data_buf_free(void *buf, uint64_t size)
11024309Smaybee {
11034309Smaybee 	zio_data_buf_free(buf, size);
11044309Smaybee 	ASSERT(arc_size >= size);
11054309Smaybee 	atomic_add_64(&arc_size, -size);
11064309Smaybee }
11074309Smaybee 
1108789Sahrens arc_buf_t *
11093290Sjohansen arc_buf_alloc(spa_t *spa, int size, void *tag, arc_buf_contents_t type)
1110789Sahrens {
1111789Sahrens 	arc_buf_hdr_t *hdr;
1112789Sahrens 	arc_buf_t *buf;
1113789Sahrens 
1114789Sahrens 	ASSERT3U(size, >, 0);
11156245Smaybee 	hdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
1116789Sahrens 	ASSERT(BUF_EMPTY(hdr));
1117789Sahrens 	hdr->b_size = size;
11183290Sjohansen 	hdr->b_type = type;
1119789Sahrens 	hdr->b_spa = spa;
11203403Sbmc 	hdr->b_state = arc_anon;
1121789Sahrens 	hdr->b_arc_access = 0;
11226245Smaybee 	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1123789Sahrens 	buf->b_hdr = hdr;
11242688Smaybee 	buf->b_data = NULL;
11251544Seschrock 	buf->b_efunc = NULL;
11261544Seschrock 	buf->b_private = NULL;
1127789Sahrens 	buf->b_next = NULL;
1128789Sahrens 	hdr->b_buf = buf;
11292688Smaybee 	arc_get_data_buf(buf);
11301544Seschrock 	hdr->b_datacnt = 1;
1131789Sahrens 	hdr->b_flags = 0;
1132789Sahrens 	ASSERT(refcount_is_zero(&hdr->b_refcnt));
1133789Sahrens 	(void) refcount_add(&hdr->b_refcnt, tag);
1134789Sahrens 
1135789Sahrens 	return (buf);
1136789Sahrens }
1137789Sahrens 
11382688Smaybee static arc_buf_t *
11392688Smaybee arc_buf_clone(arc_buf_t *from)
11401544Seschrock {
11412688Smaybee 	arc_buf_t *buf;
11422688Smaybee 	arc_buf_hdr_t *hdr = from->b_hdr;
11432688Smaybee 	uint64_t size = hdr->b_size;
11441544Seschrock 
11456245Smaybee 	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
11462688Smaybee 	buf->b_hdr = hdr;
11472688Smaybee 	buf->b_data = NULL;
11482688Smaybee 	buf->b_efunc = NULL;
11492688Smaybee 	buf->b_private = NULL;
11502688Smaybee 	buf->b_next = hdr->b_buf;
11512688Smaybee 	hdr->b_buf = buf;
11522688Smaybee 	arc_get_data_buf(buf);
11532688Smaybee 	bcopy(from->b_data, buf->b_data, size);
11542688Smaybee 	hdr->b_datacnt += 1;
11552688Smaybee 	return (buf);
11561544Seschrock }
11571544Seschrock 
11581544Seschrock void
11591544Seschrock arc_buf_add_ref(arc_buf_t *buf, void* tag)
11601544Seschrock {
11612887Smaybee 	arc_buf_hdr_t *hdr;
11621544Seschrock 	kmutex_t *hash_lock;
11631544Seschrock 
11642724Smaybee 	/*
11652724Smaybee 	 * Check to see if this buffer is currently being evicted via
11662887Smaybee 	 * arc_do_user_evicts().
11672724Smaybee 	 */
11682887Smaybee 	mutex_enter(&arc_eviction_mtx);
11692887Smaybee 	hdr = buf->b_hdr;
11702887Smaybee 	if (hdr == NULL) {
11712887Smaybee 		mutex_exit(&arc_eviction_mtx);
11722724Smaybee 		return;
11732887Smaybee 	}
11742887Smaybee 	hash_lock = HDR_LOCK(hdr);
11752887Smaybee 	mutex_exit(&arc_eviction_mtx);
11762724Smaybee 
11772724Smaybee 	mutex_enter(hash_lock);
11781544Seschrock 	if (buf->b_data == NULL) {
11791544Seschrock 		/*
11801544Seschrock 		 * This buffer is evicted.
11811544Seschrock 		 */
11822724Smaybee 		mutex_exit(hash_lock);
11831544Seschrock 		return;
11841544Seschrock 	}
11851544Seschrock 
11862724Smaybee 	ASSERT(buf->b_hdr == hdr);
11873403Sbmc 	ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
11881544Seschrock 	add_reference(hdr, hash_lock, tag);
11892688Smaybee 	arc_access(hdr, hash_lock);
11902688Smaybee 	mutex_exit(hash_lock);
11913403Sbmc 	ARCSTAT_BUMP(arcstat_hits);
11923403Sbmc 	ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
11933403Sbmc 	    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
11943403Sbmc 	    data, metadata, hits);
11951544Seschrock }
11961544Seschrock 
11975450Sbrendan /*
11985450Sbrendan  * Free the arc data buffer.  If it is an l2arc write in progress,
11995450Sbrendan  * the buffer is placed on l2arc_free_on_write to be freed later.
12005450Sbrendan  */
12015450Sbrendan static void
12025450Sbrendan arc_buf_data_free(arc_buf_hdr_t *hdr, void (*free_func)(void *, size_t),
12035450Sbrendan     void *data, size_t size)
12045450Sbrendan {
12055450Sbrendan 	if (HDR_L2_WRITING(hdr)) {
12065450Sbrendan 		l2arc_data_free_t *df;
12075450Sbrendan 		df = kmem_alloc(sizeof (l2arc_data_free_t), KM_SLEEP);
12085450Sbrendan 		df->l2df_data = data;
12095450Sbrendan 		df->l2df_size = size;
12105450Sbrendan 		df->l2df_func = free_func;
12115450Sbrendan 		mutex_enter(&l2arc_free_on_write_mtx);
12125450Sbrendan 		list_insert_head(l2arc_free_on_write, df);
12135450Sbrendan 		mutex_exit(&l2arc_free_on_write_mtx);
12145450Sbrendan 		ARCSTAT_BUMP(arcstat_l2_free_on_write);
12155450Sbrendan 	} else {
12165450Sbrendan 		free_func(data, size);
12175450Sbrendan 	}
12185450Sbrendan }
12195450Sbrendan 
1220789Sahrens static void
12212688Smaybee arc_buf_destroy(arc_buf_t *buf, boolean_t recycle, boolean_t all)
12221544Seschrock {
12231544Seschrock 	arc_buf_t **bufp;
12241544Seschrock 
12251544Seschrock 	/* free up data associated with the buf */
12261544Seschrock 	if (buf->b_data) {
12271544Seschrock 		arc_state_t *state = buf->b_hdr->b_state;
12281544Seschrock 		uint64_t size = buf->b_hdr->b_size;
12293290Sjohansen 		arc_buf_contents_t type = buf->b_hdr->b_type;
12301544Seschrock 
12313093Sahrens 		arc_cksum_verify(buf);
12322688Smaybee 		if (!recycle) {
12333290Sjohansen 			if (type == ARC_BUFC_METADATA) {
12345450Sbrendan 				arc_buf_data_free(buf->b_hdr, zio_buf_free,
12355450Sbrendan 				    buf->b_data, size);
12364309Smaybee 				arc_space_return(size);
12373290Sjohansen 			} else {
12383290Sjohansen 				ASSERT(type == ARC_BUFC_DATA);
12395450Sbrendan 				arc_buf_data_free(buf->b_hdr,
12405450Sbrendan 				    zio_data_buf_free, buf->b_data, size);
12414309Smaybee 				atomic_add_64(&arc_size, -size);
12423290Sjohansen 			}
12432688Smaybee 		}
12441544Seschrock 		if (list_link_active(&buf->b_hdr->b_arc_node)) {
12454309Smaybee 			uint64_t *cnt = &state->arcs_lsize[type];
12464309Smaybee 
12471544Seschrock 			ASSERT(refcount_is_zero(&buf->b_hdr->b_refcnt));
12483403Sbmc 			ASSERT(state != arc_anon);
12494309Smaybee 
12504309Smaybee 			ASSERT3U(*cnt, >=, size);
12514309Smaybee 			atomic_add_64(cnt, -size);
12521544Seschrock 		}
12533403Sbmc 		ASSERT3U(state->arcs_size, >=, size);
12543403Sbmc 		atomic_add_64(&state->arcs_size, -size);
12551544Seschrock 		buf->b_data = NULL;
12561544Seschrock 		ASSERT(buf->b_hdr->b_datacnt > 0);
12571544Seschrock 		buf->b_hdr->b_datacnt -= 1;
12581544Seschrock 	}
12591544Seschrock 
12601544Seschrock 	/* only remove the buf if requested */
12611544Seschrock 	if (!all)
12621544Seschrock 		return;
12631544Seschrock 
12641544Seschrock 	/* remove the buf from the hdr list */
12651544Seschrock 	for (bufp = &buf->b_hdr->b_buf; *bufp != buf; bufp = &(*bufp)->b_next)
12661544Seschrock 		continue;
12671544Seschrock 	*bufp = buf->b_next;
12681544Seschrock 
12691544Seschrock 	ASSERT(buf->b_efunc == NULL);
12701544Seschrock 
12711544Seschrock 	/* clean up the buf */
12721544Seschrock 	buf->b_hdr = NULL;
12731544Seschrock 	kmem_cache_free(buf_cache, buf);
12741544Seschrock }
12751544Seschrock 
12761544Seschrock static void
12771544Seschrock arc_hdr_destroy(arc_buf_hdr_t *hdr)
1278789Sahrens {
1279789Sahrens 	ASSERT(refcount_is_zero(&hdr->b_refcnt));
12803403Sbmc 	ASSERT3P(hdr->b_state, ==, arc_anon);
12811544Seschrock 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1282*7046Sahrens 	ASSERT(!(hdr->b_flags & ARC_STORED));
1283789Sahrens 
12845450Sbrendan 	if (hdr->b_l2hdr != NULL) {
12855450Sbrendan 		if (!MUTEX_HELD(&l2arc_buflist_mtx)) {
12865450Sbrendan 			/*
12875450Sbrendan 			 * To prevent arc_free() and l2arc_evict() from
12885450Sbrendan 			 * attempting to free the same buffer at the same time,
12895450Sbrendan 			 * a FREE_IN_PROGRESS flag is given to arc_free() to
12905450Sbrendan 			 * give it priority.  l2arc_evict() can't destroy this
12915450Sbrendan 			 * header while we are waiting on l2arc_buflist_mtx.
12925450Sbrendan 			 */
12935450Sbrendan 			mutex_enter(&l2arc_buflist_mtx);
12945450Sbrendan 			ASSERT(hdr->b_l2hdr != NULL);
12955450Sbrendan 
12965450Sbrendan 			list_remove(hdr->b_l2hdr->b_dev->l2ad_buflist, hdr);
12975450Sbrendan 			mutex_exit(&l2arc_buflist_mtx);
12985450Sbrendan 		} else {
12995450Sbrendan 			list_remove(hdr->b_l2hdr->b_dev->l2ad_buflist, hdr);
13005450Sbrendan 		}
13015450Sbrendan 		ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
13025450Sbrendan 		kmem_free(hdr->b_l2hdr, sizeof (l2arc_buf_hdr_t));
13035450Sbrendan 		if (hdr->b_state == arc_l2c_only)
13045450Sbrendan 			l2arc_hdr_stat_remove();
13055450Sbrendan 		hdr->b_l2hdr = NULL;
13065450Sbrendan 	}
13075450Sbrendan 
1308789Sahrens 	if (!BUF_EMPTY(hdr)) {
13091544Seschrock 		ASSERT(!HDR_IN_HASH_TABLE(hdr));
1310789Sahrens 		bzero(&hdr->b_dva, sizeof (dva_t));
1311789Sahrens 		hdr->b_birth = 0;
1312789Sahrens 		hdr->b_cksum0 = 0;
1313789Sahrens 	}
13141544Seschrock 	while (hdr->b_buf) {
1315789Sahrens 		arc_buf_t *buf = hdr->b_buf;
1316789Sahrens 
13171544Seschrock 		if (buf->b_efunc) {
13181544Seschrock 			mutex_enter(&arc_eviction_mtx);
13191544Seschrock 			ASSERT(buf->b_hdr != NULL);
13202688Smaybee 			arc_buf_destroy(hdr->b_buf, FALSE, FALSE);
13211544Seschrock 			hdr->b_buf = buf->b_next;
13222887Smaybee 			buf->b_hdr = &arc_eviction_hdr;
13231544Seschrock 			buf->b_next = arc_eviction_list;
13241544Seschrock 			arc_eviction_list = buf;
13251544Seschrock 			mutex_exit(&arc_eviction_mtx);
13261544Seschrock 		} else {
13272688Smaybee 			arc_buf_destroy(hdr->b_buf, FALSE, TRUE);
13281544Seschrock 		}
1329789Sahrens 	}
13303093Sahrens 	if (hdr->b_freeze_cksum != NULL) {
13313093Sahrens 		kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
13323093Sahrens 		hdr->b_freeze_cksum = NULL;
13333093Sahrens 	}
13341544Seschrock 
1335789Sahrens 	ASSERT(!list_link_active(&hdr->b_arc_node));
1336789Sahrens 	ASSERT3P(hdr->b_hash_next, ==, NULL);
1337789Sahrens 	ASSERT3P(hdr->b_acb, ==, NULL);
1338789Sahrens 	kmem_cache_free(hdr_cache, hdr);
1339789Sahrens }
1340789Sahrens 
1341789Sahrens void
1342789Sahrens arc_buf_free(arc_buf_t *buf, void *tag)
1343789Sahrens {
1344789Sahrens 	arc_buf_hdr_t *hdr = buf->b_hdr;
13453403Sbmc 	int hashed = hdr->b_state != arc_anon;
13461544Seschrock 
13471544Seschrock 	ASSERT(buf->b_efunc == NULL);
13481544Seschrock 	ASSERT(buf->b_data != NULL);
13491544Seschrock 
13501544Seschrock 	if (hashed) {
13511544Seschrock 		kmutex_t *hash_lock = HDR_LOCK(hdr);
13521544Seschrock 
13531544Seschrock 		mutex_enter(hash_lock);
13541544Seschrock 		(void) remove_reference(hdr, hash_lock, tag);
13551544Seschrock 		if (hdr->b_datacnt > 1)
13562688Smaybee 			arc_buf_destroy(buf, FALSE, TRUE);
13571544Seschrock 		else
13581544Seschrock 			hdr->b_flags |= ARC_BUF_AVAILABLE;
13591544Seschrock 		mutex_exit(hash_lock);
13601544Seschrock 	} else if (HDR_IO_IN_PROGRESS(hdr)) {
13611544Seschrock 		int destroy_hdr;
13621544Seschrock 		/*
13631544Seschrock 		 * We are in the middle of an async write.  Don't destroy
13641544Seschrock 		 * this buffer unless the write completes before we finish
13651544Seschrock 		 * decrementing the reference count.
13661544Seschrock 		 */
13671544Seschrock 		mutex_enter(&arc_eviction_mtx);
13681544Seschrock 		(void) remove_reference(hdr, NULL, tag);
13691544Seschrock 		ASSERT(refcount_is_zero(&hdr->b_refcnt));
13701544Seschrock 		destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
13711544Seschrock 		mutex_exit(&arc_eviction_mtx);
13721544Seschrock 		if (destroy_hdr)
13731544Seschrock 			arc_hdr_destroy(hdr);
13741544Seschrock 	} else {
13751544Seschrock 		if (remove_reference(hdr, NULL, tag) > 0) {
13761544Seschrock 			ASSERT(HDR_IO_ERROR(hdr));
13772688Smaybee 			arc_buf_destroy(buf, FALSE, TRUE);
13781544Seschrock 		} else {
13791544Seschrock 			arc_hdr_destroy(hdr);
13801544Seschrock 		}
13811544Seschrock 	}
13821544Seschrock }
13831544Seschrock 
13841544Seschrock int
13851544Seschrock arc_buf_remove_ref(arc_buf_t *buf, void* tag)
13861544Seschrock {
13871544Seschrock 	arc_buf_hdr_t *hdr = buf->b_hdr;
1388789Sahrens 	kmutex_t *hash_lock = HDR_LOCK(hdr);
13891544Seschrock 	int no_callback = (buf->b_efunc == NULL);
13901544Seschrock 
13913403Sbmc 	if (hdr->b_state == arc_anon) {
13921544Seschrock 		arc_buf_free(buf, tag);
13931544Seschrock 		return (no_callback);
13941544Seschrock 	}
1395789Sahrens 
1396789Sahrens 	mutex_enter(hash_lock);
13973403Sbmc 	ASSERT(hdr->b_state != arc_anon);
13981544Seschrock 	ASSERT(buf->b_data != NULL);
1399789Sahrens 
14001544Seschrock 	(void) remove_reference(hdr, hash_lock, tag);
14011544Seschrock 	if (hdr->b_datacnt > 1) {
14021544Seschrock 		if (no_callback)
14032688Smaybee 			arc_buf_destroy(buf, FALSE, TRUE);
14041544Seschrock 	} else if (no_callback) {
14051544Seschrock 		ASSERT(hdr->b_buf == buf && buf->b_next == NULL);
14061544Seschrock 		hdr->b_flags |= ARC_BUF_AVAILABLE;
1407789Sahrens 	}
14081544Seschrock 	ASSERT(no_callback || hdr->b_datacnt > 1 ||
14091544Seschrock 	    refcount_is_zero(&hdr->b_refcnt));
1410789Sahrens 	mutex_exit(hash_lock);
14111544Seschrock 	return (no_callback);
1412789Sahrens }
1413789Sahrens 
1414789Sahrens int
1415789Sahrens arc_buf_size(arc_buf_t *buf)
1416789Sahrens {
1417789Sahrens 	return (buf->b_hdr->b_size);
1418789Sahrens }
1419789Sahrens 
1420789Sahrens /*
1421789Sahrens  * Evict buffers from list until we've removed the specified number of
1422789Sahrens  * bytes.  Move the removed buffers to the appropriate evict state.
14232688Smaybee  * If the recycle flag is set, then attempt to "recycle" a buffer:
14242688Smaybee  * - look for a buffer to evict that is `bytes' long.
14252688Smaybee  * - return the data block from this buffer rather than freeing it.
14262688Smaybee  * This flag is used by callers that are trying to make space for a
14272688Smaybee  * new buffer in a full arc cache.
14285642Smaybee  *
14295642Smaybee  * This function makes a "best effort".  It skips over any buffers
14305642Smaybee  * it can't get a hash_lock on, and so may not catch all candidates.
14315642Smaybee  * It may also return without evicting as much space as requested.
1432789Sahrens  */
14332688Smaybee static void *
14345642Smaybee arc_evict(arc_state_t *state, spa_t *spa, int64_t bytes, boolean_t recycle,
14353290Sjohansen     arc_buf_contents_t type)
1436789Sahrens {
1437789Sahrens 	arc_state_t *evicted_state;
14382688Smaybee 	uint64_t bytes_evicted = 0, skipped = 0, missed = 0;
14392918Smaybee 	arc_buf_hdr_t *ab, *ab_prev = NULL;
14404309Smaybee 	list_t *list = &state->arcs_list[type];
1441789Sahrens 	kmutex_t *hash_lock;
14422688Smaybee 	boolean_t have_lock;
14432918Smaybee 	void *stolen = NULL;
1444789Sahrens 
14453403Sbmc 	ASSERT(state == arc_mru || state == arc_mfu);
1446789Sahrens 
14473403Sbmc 	evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
1448789Sahrens 
14493403Sbmc 	mutex_enter(&state->arcs_mtx);
14503403Sbmc 	mutex_enter(&evicted_state->arcs_mtx);
1451789Sahrens 
14524309Smaybee 	for (ab = list_tail(list); ab; ab = ab_prev) {
14534309Smaybee 		ab_prev = list_prev(list, ab);
14542391Smaybee 		/* prefetch buffers have a minimum lifespan */
14552688Smaybee 		if (HDR_IO_IN_PROGRESS(ab) ||
14565642Smaybee 		    (spa && ab->b_spa != spa) ||
14572688Smaybee 		    (ab->b_flags & (ARC_PREFETCH|ARC_INDIRECT) &&
14582688Smaybee 		    lbolt - ab->b_arc_access < arc_min_prefetch_lifespan)) {
14592391Smaybee 			skipped++;
14602391Smaybee 			continue;
14612391Smaybee 		}
14622918Smaybee 		/* "lookahead" for better eviction candidate */
14632918Smaybee 		if (recycle && ab->b_size != bytes &&
14642918Smaybee 		    ab_prev && ab_prev->b_size == bytes)
14652688Smaybee 			continue;
1466789Sahrens 		hash_lock = HDR_LOCK(ab);
14672688Smaybee 		have_lock = MUTEX_HELD(hash_lock);
14682688Smaybee 		if (have_lock || mutex_tryenter(hash_lock)) {
1469789Sahrens 			ASSERT3U(refcount_count(&ab->b_refcnt), ==, 0);
14701544Seschrock 			ASSERT(ab->b_datacnt > 0);
14711544Seschrock 			while (ab->b_buf) {
14721544Seschrock 				arc_buf_t *buf = ab->b_buf;
14732688Smaybee 				if (buf->b_data) {
14741544Seschrock 					bytes_evicted += ab->b_size;
14753290Sjohansen 					if (recycle && ab->b_type == type &&
14765450Sbrendan 					    ab->b_size == bytes &&
14775450Sbrendan 					    !HDR_L2_WRITING(ab)) {
14782918Smaybee 						stolen = buf->b_data;
14792918Smaybee 						recycle = FALSE;
14802918Smaybee 					}
14812688Smaybee 				}
14821544Seschrock 				if (buf->b_efunc) {
14831544Seschrock 					mutex_enter(&arc_eviction_mtx);
14842918Smaybee 					arc_buf_destroy(buf,
14852918Smaybee 					    buf->b_data == stolen, FALSE);
14861544Seschrock 					ab->b_buf = buf->b_next;
14872887Smaybee 					buf->b_hdr = &arc_eviction_hdr;
14881544Seschrock 					buf->b_next = arc_eviction_list;
14891544Seschrock 					arc_eviction_list = buf;
14901544Seschrock 					mutex_exit(&arc_eviction_mtx);
14911544Seschrock 				} else {
14922918Smaybee 					arc_buf_destroy(buf,
14932918Smaybee 					    buf->b_data == stolen, TRUE);
14941544Seschrock 				}
14951544Seschrock 			}
14961544Seschrock 			ASSERT(ab->b_datacnt == 0);
1497789Sahrens 			arc_change_state(evicted_state, ab, hash_lock);
14981544Seschrock 			ASSERT(HDR_IN_HASH_TABLE(ab));
14995450Sbrendan 			ab->b_flags |= ARC_IN_HASH_TABLE;
15005450Sbrendan 			ab->b_flags &= ~ARC_BUF_AVAILABLE;
1501789Sahrens 			DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, ab);
15022688Smaybee 			if (!have_lock)
15032688Smaybee 				mutex_exit(hash_lock);
15041544Seschrock 			if (bytes >= 0 && bytes_evicted >= bytes)
1505789Sahrens 				break;
1506789Sahrens 		} else {
15072688Smaybee 			missed += 1;
1508789Sahrens 		}
1509789Sahrens 	}
15103403Sbmc 
15113403Sbmc 	mutex_exit(&evicted_state->arcs_mtx);
15123403Sbmc 	mutex_exit(&state->arcs_mtx);
1513789Sahrens 
1514789Sahrens 	if (bytes_evicted < bytes)
1515789Sahrens 		dprintf("only evicted %lld bytes from %x",
1516789Sahrens 		    (longlong_t)bytes_evicted, state);
1517789Sahrens 
15182688Smaybee 	if (skipped)
15193403Sbmc 		ARCSTAT_INCR(arcstat_evict_skip, skipped);
15203403Sbmc 
15212688Smaybee 	if (missed)
15223403Sbmc 		ARCSTAT_INCR(arcstat_mutex_miss, missed);
15233403Sbmc 
15244709Smaybee 	/*
15254709Smaybee 	 * We have just evicted some date into the ghost state, make
15264709Smaybee 	 * sure we also adjust the ghost state size if necessary.
15274709Smaybee 	 */
15284709Smaybee 	if (arc_no_grow &&
15294709Smaybee 	    arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size > arc_c) {
15304709Smaybee 		int64_t mru_over = arc_anon->arcs_size + arc_mru->arcs_size +
15314709Smaybee 		    arc_mru_ghost->arcs_size - arc_c;
15324709Smaybee 
15334709Smaybee 		if (mru_over > 0 && arc_mru_ghost->arcs_lsize[type] > 0) {
15344709Smaybee 			int64_t todelete =
15354709Smaybee 			    MIN(arc_mru_ghost->arcs_lsize[type], mru_over);
15365642Smaybee 			arc_evict_ghost(arc_mru_ghost, NULL, todelete);
15374709Smaybee 		} else if (arc_mfu_ghost->arcs_lsize[type] > 0) {
15384709Smaybee 			int64_t todelete = MIN(arc_mfu_ghost->arcs_lsize[type],
15394709Smaybee 			    arc_mru_ghost->arcs_size +
15404709Smaybee 			    arc_mfu_ghost->arcs_size - arc_c);
15415642Smaybee 			arc_evict_ghost(arc_mfu_ghost, NULL, todelete);
15424709Smaybee 		}
15434709Smaybee 	}
15444709Smaybee 
15452918Smaybee 	return (stolen);
1546789Sahrens }
1547789Sahrens 
1548789Sahrens /*
1549789Sahrens  * Remove buffers from list until we've removed the specified number of
1550789Sahrens  * bytes.  Destroy the buffers that are removed.
1551789Sahrens  */
1552789Sahrens static void
15535642Smaybee arc_evict_ghost(arc_state_t *state, spa_t *spa, int64_t bytes)
1554789Sahrens {
1555789Sahrens 	arc_buf_hdr_t *ab, *ab_prev;
15564309Smaybee 	list_t *list = &state->arcs_list[ARC_BUFC_DATA];
1557789Sahrens 	kmutex_t *hash_lock;
15581544Seschrock 	uint64_t bytes_deleted = 0;
15593700Sek110237 	uint64_t bufs_skipped = 0;
1560789Sahrens 
15611544Seschrock 	ASSERT(GHOST_STATE(state));
1562789Sahrens top:
15633403Sbmc 	mutex_enter(&state->arcs_mtx);
15644309Smaybee 	for (ab = list_tail(list); ab; ab = ab_prev) {
15654309Smaybee 		ab_prev = list_prev(list, ab);
15665642Smaybee 		if (spa && ab->b_spa != spa)
15675642Smaybee 			continue;
1568789Sahrens 		hash_lock = HDR_LOCK(ab);
1569789Sahrens 		if (mutex_tryenter(hash_lock)) {
15702391Smaybee 			ASSERT(!HDR_IO_IN_PROGRESS(ab));
15711544Seschrock 			ASSERT(ab->b_buf == NULL);
15723403Sbmc 			ARCSTAT_BUMP(arcstat_deleted);
15731544Seschrock 			bytes_deleted += ab->b_size;
15745450Sbrendan 
15755450Sbrendan 			if (ab->b_l2hdr != NULL) {
15765450Sbrendan 				/*
15775450Sbrendan 				 * This buffer is cached on the 2nd Level ARC;
15785450Sbrendan 				 * don't destroy the header.
15795450Sbrendan 				 */
15805450Sbrendan 				arc_change_state(arc_l2c_only, ab, hash_lock);
15815450Sbrendan 				mutex_exit(hash_lock);
15825450Sbrendan 			} else {
15835450Sbrendan 				arc_change_state(arc_anon, ab, hash_lock);
15845450Sbrendan 				mutex_exit(hash_lock);
15855450Sbrendan 				arc_hdr_destroy(ab);
15865450Sbrendan 			}
15875450Sbrendan 
1588789Sahrens 			DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, ab);
1589789Sahrens 			if (bytes >= 0 && bytes_deleted >= bytes)
1590789Sahrens 				break;
1591789Sahrens 		} else {
1592789Sahrens 			if (bytes < 0) {
15933403Sbmc 				mutex_exit(&state->arcs_mtx);
1594789Sahrens 				mutex_enter(hash_lock);
1595789Sahrens 				mutex_exit(hash_lock);
1596789Sahrens 				goto top;
1597789Sahrens 			}
1598789Sahrens 			bufs_skipped += 1;
1599789Sahrens 		}
1600789Sahrens 	}
16013403Sbmc 	mutex_exit(&state->arcs_mtx);
1602789Sahrens 
16034309Smaybee 	if (list == &state->arcs_list[ARC_BUFC_DATA] &&
16044309Smaybee 	    (bytes < 0 || bytes_deleted < bytes)) {
16054309Smaybee 		list = &state->arcs_list[ARC_BUFC_METADATA];
16064309Smaybee 		goto top;
16074309Smaybee 	}
16084309Smaybee 
1609789Sahrens 	if (bufs_skipped) {
16103403Sbmc 		ARCSTAT_INCR(arcstat_mutex_miss, bufs_skipped);
1611789Sahrens 		ASSERT(bytes >= 0);
1612789Sahrens 	}
1613789Sahrens 
1614789Sahrens 	if (bytes_deleted < bytes)
1615789Sahrens 		dprintf("only deleted %lld bytes from %p",
1616789Sahrens 		    (longlong_t)bytes_deleted, state);
1617789Sahrens }
1618789Sahrens 
1619789Sahrens static void
1620789Sahrens arc_adjust(void)
1621789Sahrens {
16223403Sbmc 	int64_t top_sz, mru_over, arc_over, todelete;
1623789Sahrens 
16245642Smaybee 	top_sz = arc_anon->arcs_size + arc_mru->arcs_size + arc_meta_used;
1625789Sahrens 
16264309Smaybee 	if (top_sz > arc_p && arc_mru->arcs_lsize[ARC_BUFC_DATA] > 0) {
16274309Smaybee 		int64_t toevict =
16284309Smaybee 		    MIN(arc_mru->arcs_lsize[ARC_BUFC_DATA], top_sz - arc_p);
16295642Smaybee 		(void) arc_evict(arc_mru, NULL, toevict, FALSE, ARC_BUFC_DATA);
16304309Smaybee 		top_sz = arc_anon->arcs_size + arc_mru->arcs_size;
16314309Smaybee 	}
16324309Smaybee 
16334309Smaybee 	if (top_sz > arc_p && arc_mru->arcs_lsize[ARC_BUFC_METADATA] > 0) {
16344309Smaybee 		int64_t toevict =
16354309Smaybee 		    MIN(arc_mru->arcs_lsize[ARC_BUFC_METADATA], top_sz - arc_p);
16365642Smaybee 		(void) arc_evict(arc_mru, NULL, toevict, FALSE,
16375642Smaybee 		    ARC_BUFC_METADATA);
16383403Sbmc 		top_sz = arc_anon->arcs_size + arc_mru->arcs_size;
1639789Sahrens 	}
1640789Sahrens 
16413403Sbmc 	mru_over = top_sz + arc_mru_ghost->arcs_size - arc_c;
1642789Sahrens 
1643789Sahrens 	if (mru_over > 0) {
16444309Smaybee 		if (arc_mru_ghost->arcs_size > 0) {
16454309Smaybee 			todelete = MIN(arc_mru_ghost->arcs_size, mru_over);
16465642Smaybee 			arc_evict_ghost(arc_mru_ghost, NULL, todelete);
1647789Sahrens 		}
1648789Sahrens 	}
1649789Sahrens 
16503403Sbmc 	if ((arc_over = arc_size - arc_c) > 0) {
16511544Seschrock 		int64_t tbl_over;
1652789Sahrens 
16534309Smaybee 		if (arc_mfu->arcs_lsize[ARC_BUFC_DATA] > 0) {
16544309Smaybee 			int64_t toevict =
16554309Smaybee 			    MIN(arc_mfu->arcs_lsize[ARC_BUFC_DATA], arc_over);
16565642Smaybee 			(void) arc_evict(arc_mfu, NULL, toevict, FALSE,
16574309Smaybee 			    ARC_BUFC_DATA);
16584309Smaybee 			arc_over = arc_size - arc_c;
1659789Sahrens 		}
1660789Sahrens 
16614309Smaybee 		if (arc_over > 0 &&
16624309Smaybee 		    arc_mfu->arcs_lsize[ARC_BUFC_METADATA] > 0) {
16634309Smaybee 			int64_t toevict =
16644309Smaybee 			    MIN(arc_mfu->arcs_lsize[ARC_BUFC_METADATA],
16654309Smaybee 			    arc_over);
16665642Smaybee 			(void) arc_evict(arc_mfu, NULL, toevict, FALSE,
16674309Smaybee 			    ARC_BUFC_METADATA);
16684309Smaybee 		}
16694309Smaybee 
16704309Smaybee 		tbl_over = arc_size + arc_mru_ghost->arcs_size +
16714309Smaybee 		    arc_mfu_ghost->arcs_size - arc_c * 2;
16724309Smaybee 
16734309Smaybee 		if (tbl_over > 0 && arc_mfu_ghost->arcs_size > 0) {
16744309Smaybee 			todelete = MIN(arc_mfu_ghost->arcs_size, tbl_over);
16755642Smaybee 			arc_evict_ghost(arc_mfu_ghost, NULL, todelete);
1676789Sahrens 		}
1677789Sahrens 	}
1678789Sahrens }
1679789Sahrens 
16801544Seschrock static void
16811544Seschrock arc_do_user_evicts(void)
16821544Seschrock {
16831544Seschrock 	mutex_enter(&arc_eviction_mtx);
16841544Seschrock 	while (arc_eviction_list != NULL) {
16851544Seschrock 		arc_buf_t *buf = arc_eviction_list;
16861544Seschrock 		arc_eviction_list = buf->b_next;
16871544Seschrock 		buf->b_hdr = NULL;
16881544Seschrock 		mutex_exit(&arc_eviction_mtx);
16891544Seschrock 
16901819Smaybee 		if (buf->b_efunc != NULL)
16911819Smaybee 			VERIFY(buf->b_efunc(buf) == 0);
16921544Seschrock 
16931544Seschrock 		buf->b_efunc = NULL;
16941544Seschrock 		buf->b_private = NULL;
16951544Seschrock 		kmem_cache_free(buf_cache, buf);
16961544Seschrock 		mutex_enter(&arc_eviction_mtx);
16971544Seschrock 	}
16981544Seschrock 	mutex_exit(&arc_eviction_mtx);
16991544Seschrock }
17001544Seschrock 
1701789Sahrens /*
17025642Smaybee  * Flush all *evictable* data from the cache for the given spa.
1703789Sahrens  * NOTE: this will not touch "active" (i.e. referenced) data.
1704789Sahrens  */
1705789Sahrens void
17065642Smaybee arc_flush(spa_t *spa)
1707789Sahrens {
17085642Smaybee 	while (list_head(&arc_mru->arcs_list[ARC_BUFC_DATA])) {
17095642Smaybee 		(void) arc_evict(arc_mru, spa, -1, FALSE, ARC_BUFC_DATA);
17105642Smaybee 		if (spa)
17115642Smaybee 			break;
17125642Smaybee 	}
17135642Smaybee 	while (list_head(&arc_mru->arcs_list[ARC_BUFC_METADATA])) {
17145642Smaybee 		(void) arc_evict(arc_mru, spa, -1, FALSE, ARC_BUFC_METADATA);
17155642Smaybee 		if (spa)
17165642Smaybee 			break;
17175642Smaybee 	}
17185642Smaybee 	while (list_head(&arc_mfu->arcs_list[ARC_BUFC_DATA])) {
17195642Smaybee 		(void) arc_evict(arc_mfu, spa, -1, FALSE, ARC_BUFC_DATA);
17205642Smaybee 		if (spa)
17215642Smaybee 			break;
17225642Smaybee 	}
17235642Smaybee 	while (list_head(&arc_mfu->arcs_list[ARC_BUFC_METADATA])) {
17245642Smaybee 		(void) arc_evict(arc_mfu, spa, -1, FALSE, ARC_BUFC_METADATA);
17255642Smaybee 		if (spa)
17265642Smaybee 			break;
17275642Smaybee 	}
17285642Smaybee 
17295642Smaybee 	arc_evict_ghost(arc_mru_ghost, spa, -1);
17305642Smaybee 	arc_evict_ghost(arc_mfu_ghost, spa, -1);
17311544Seschrock 
17321544Seschrock 	mutex_enter(&arc_reclaim_thr_lock);
17331544Seschrock 	arc_do_user_evicts();
17341544Seschrock 	mutex_exit(&arc_reclaim_thr_lock);
17355642Smaybee 	ASSERT(spa || arc_eviction_list == NULL);
1736789Sahrens }
1737789Sahrens 
17383158Smaybee int arc_shrink_shift = 5;		/* log2(fraction of arc to reclaim) */
17392391Smaybee 
1740789Sahrens void
17413158Smaybee arc_shrink(void)
1742789Sahrens {
17433403Sbmc 	if (arc_c > arc_c_min) {
17443158Smaybee 		uint64_t to_free;
1745789Sahrens 
17462048Sstans #ifdef _KERNEL
17473403Sbmc 		to_free = MAX(arc_c >> arc_shrink_shift, ptob(needfree));
17482048Sstans #else
17493403Sbmc 		to_free = arc_c >> arc_shrink_shift;
17502048Sstans #endif
17513403Sbmc 		if (arc_c > arc_c_min + to_free)
17523403Sbmc 			atomic_add_64(&arc_c, -to_free);
17533158Smaybee 		else
17543403Sbmc 			arc_c = arc_c_min;
17552048Sstans 
17563403Sbmc 		atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
17573403Sbmc 		if (arc_c > arc_size)
17583403Sbmc 			arc_c = MAX(arc_size, arc_c_min);
17593403Sbmc 		if (arc_p > arc_c)
17603403Sbmc 			arc_p = (arc_c >> 1);
17613403Sbmc 		ASSERT(arc_c >= arc_c_min);
17623403Sbmc 		ASSERT((int64_t)arc_p >= 0);
17633158Smaybee 	}
1764789Sahrens 
17653403Sbmc 	if (arc_size > arc_c)
17663158Smaybee 		arc_adjust();
1767789Sahrens }
1768789Sahrens 
1769789Sahrens static int
1770789Sahrens arc_reclaim_needed(void)
1771789Sahrens {
1772789Sahrens 	uint64_t extra;
1773789Sahrens 
1774789Sahrens #ifdef _KERNEL
17752048Sstans 
17762048Sstans 	if (needfree)
17772048Sstans 		return (1);
17782048Sstans 
1779789Sahrens 	/*
1780789Sahrens 	 * take 'desfree' extra pages, so we reclaim sooner, rather than later
1781789Sahrens 	 */
1782789Sahrens 	extra = desfree;
1783789Sahrens 
1784789Sahrens 	/*
1785789Sahrens 	 * check that we're out of range of the pageout scanner.  It starts to
1786789Sahrens 	 * schedule paging if freemem is less than lotsfree and needfree.
1787789Sahrens 	 * lotsfree is the high-water mark for pageout, and needfree is the
1788789Sahrens 	 * number of needed free pages.  We add extra pages here to make sure
1789789Sahrens 	 * the scanner doesn't start up while we're freeing memory.
1790789Sahrens 	 */
1791789Sahrens 	if (freemem < lotsfree + needfree + extra)
1792789Sahrens 		return (1);
1793789Sahrens 
1794789Sahrens 	/*
1795789Sahrens 	 * check to make sure that swapfs has enough space so that anon
17965450Sbrendan 	 * reservations can still succeed. anon_resvmem() checks that the
1797789Sahrens 	 * availrmem is greater than swapfs_minfree, and the number of reserved
1798789Sahrens 	 * swap pages.  We also add a bit of extra here just to prevent
1799789Sahrens 	 * circumstances from getting really dire.
1800789Sahrens 	 */
1801789Sahrens 	if (availrmem < swapfs_minfree + swapfs_reserve + extra)
1802789Sahrens 		return (1);
1803789Sahrens 
18041936Smaybee #if defined(__i386)
1805789Sahrens 	/*
1806789Sahrens 	 * If we're on an i386 platform, it's possible that we'll exhaust the
1807789Sahrens 	 * kernel heap space before we ever run out of available physical
1808789Sahrens 	 * memory.  Most checks of the size of the heap_area compare against
1809789Sahrens 	 * tune.t_minarmem, which is the minimum available real memory that we
1810789Sahrens 	 * can have in the system.  However, this is generally fixed at 25 pages
1811789Sahrens 	 * which is so low that it's useless.  In this comparison, we seek to
1812789Sahrens 	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
18135450Sbrendan 	 * heap is allocated.  (Or, in the calculation, if less than 1/4th is
1814789Sahrens 	 * free)
1815789Sahrens 	 */
1816789Sahrens 	if (btop(vmem_size(heap_arena, VMEM_FREE)) <
1817789Sahrens 	    (btop(vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC)) >> 2))
1818789Sahrens 		return (1);
1819789Sahrens #endif
1820789Sahrens 
1821789Sahrens #else
1822789Sahrens 	if (spa_get_random(100) == 0)
1823789Sahrens 		return (1);
1824789Sahrens #endif
1825789Sahrens 	return (0);
1826789Sahrens }
1827789Sahrens 
1828789Sahrens static void
1829789Sahrens arc_kmem_reap_now(arc_reclaim_strategy_t strat)
1830789Sahrens {
1831789Sahrens 	size_t			i;
1832789Sahrens 	kmem_cache_t		*prev_cache = NULL;
18333290Sjohansen 	kmem_cache_t		*prev_data_cache = NULL;
1834789Sahrens 	extern kmem_cache_t	*zio_buf_cache[];
18353290Sjohansen 	extern kmem_cache_t	*zio_data_buf_cache[];
1836789Sahrens 
18371484Sek110237 #ifdef _KERNEL
18384309Smaybee 	if (arc_meta_used >= arc_meta_limit) {
18394309Smaybee 		/*
18404309Smaybee 		 * We are exceeding our meta-data cache limit.
18414309Smaybee 		 * Purge some DNLC entries to release holds on meta-data.
18424309Smaybee 		 */
18434309Smaybee 		dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
18444309Smaybee 	}
18451936Smaybee #if defined(__i386)
18461936Smaybee 	/*
18471936Smaybee 	 * Reclaim unused memory from all kmem caches.
18481936Smaybee 	 */
18491936Smaybee 	kmem_reap();
18501936Smaybee #endif
18511484Sek110237 #endif
18521484Sek110237 
1853789Sahrens 	/*
18545450Sbrendan 	 * An aggressive reclamation will shrink the cache size as well as
18551544Seschrock 	 * reap free buffers from the arc kmem caches.
1856789Sahrens 	 */
1857789Sahrens 	if (strat == ARC_RECLAIM_AGGR)
18583158Smaybee 		arc_shrink();
1859789Sahrens 
1860789Sahrens 	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
1861789Sahrens 		if (zio_buf_cache[i] != prev_cache) {
1862789Sahrens 			prev_cache = zio_buf_cache[i];
1863789Sahrens 			kmem_cache_reap_now(zio_buf_cache[i]);
1864789Sahrens 		}
18653290Sjohansen 		if (zio_data_buf_cache[i] != prev_data_cache) {
18663290Sjohansen 			prev_data_cache = zio_data_buf_cache[i];
18673290Sjohansen 			kmem_cache_reap_now(zio_data_buf_cache[i]);
18683290Sjohansen 		}
1869789Sahrens 	}
18701544Seschrock 	kmem_cache_reap_now(buf_cache);
18711544Seschrock 	kmem_cache_reap_now(hdr_cache);
1872789Sahrens }
1873789Sahrens 
1874789Sahrens static void
1875789Sahrens arc_reclaim_thread(void)
1876789Sahrens {
1877789Sahrens 	clock_t			growtime = 0;
1878789Sahrens 	arc_reclaim_strategy_t	last_reclaim = ARC_RECLAIM_CONS;
1879789Sahrens 	callb_cpr_t		cpr;
1880789Sahrens 
1881789Sahrens 	CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
1882789Sahrens 
1883789Sahrens 	mutex_enter(&arc_reclaim_thr_lock);
1884789Sahrens 	while (arc_thread_exit == 0) {
1885789Sahrens 		if (arc_reclaim_needed()) {
1886789Sahrens 
18873403Sbmc 			if (arc_no_grow) {
1888789Sahrens 				if (last_reclaim == ARC_RECLAIM_CONS) {
1889789Sahrens 					last_reclaim = ARC_RECLAIM_AGGR;
1890789Sahrens 				} else {
1891789Sahrens 					last_reclaim = ARC_RECLAIM_CONS;
1892789Sahrens 				}
1893789Sahrens 			} else {
18943403Sbmc 				arc_no_grow = TRUE;
1895789Sahrens 				last_reclaim = ARC_RECLAIM_AGGR;
1896789Sahrens 				membar_producer();
1897789Sahrens 			}
1898789Sahrens 
1899789Sahrens 			/* reset the growth delay for every reclaim */
1900789Sahrens 			growtime = lbolt + (arc_grow_retry * hz);
1901789Sahrens 
1902789Sahrens 			arc_kmem_reap_now(last_reclaim);
19036987Sbrendan 			arc_warm = B_TRUE;
1904789Sahrens 
19054309Smaybee 		} else if (arc_no_grow && lbolt >= growtime) {
19063403Sbmc 			arc_no_grow = FALSE;
1907789Sahrens 		}
1908789Sahrens 
19093403Sbmc 		if (2 * arc_c < arc_size +
19103403Sbmc 		    arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size)
19113298Smaybee 			arc_adjust();
19123298Smaybee 
19131544Seschrock 		if (arc_eviction_list != NULL)
19141544Seschrock 			arc_do_user_evicts();
19151544Seschrock 
1916789Sahrens 		/* block until needed, or one second, whichever is shorter */
1917789Sahrens 		CALLB_CPR_SAFE_BEGIN(&cpr);
1918789Sahrens 		(void) cv_timedwait(&arc_reclaim_thr_cv,
1919789Sahrens 		    &arc_reclaim_thr_lock, (lbolt + hz));
1920789Sahrens 		CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
1921789Sahrens 	}
1922789Sahrens 
1923789Sahrens 	arc_thread_exit = 0;
1924789Sahrens 	cv_broadcast(&arc_reclaim_thr_cv);
1925789Sahrens 	CALLB_CPR_EXIT(&cpr);		/* drops arc_reclaim_thr_lock */
1926789Sahrens 	thread_exit();
1927789Sahrens }
1928789Sahrens 
19291544Seschrock /*
19301544Seschrock  * Adapt arc info given the number of bytes we are trying to add and
19311544Seschrock  * the state that we are comming from.  This function is only called
19321544Seschrock  * when we are adding new content to the cache.
19331544Seschrock  */
1934789Sahrens static void
19351544Seschrock arc_adapt(int bytes, arc_state_t *state)
1936789Sahrens {
19371544Seschrock 	int mult;
19381544Seschrock 
19395450Sbrendan 	if (state == arc_l2c_only)
19405450Sbrendan 		return;
19415450Sbrendan 
19421544Seschrock 	ASSERT(bytes > 0);
1943789Sahrens 	/*
19441544Seschrock 	 * Adapt the target size of the MRU list:
19451544Seschrock 	 *	- if we just hit in the MRU ghost list, then increase
19461544Seschrock 	 *	  the target size of the MRU list.
19471544Seschrock 	 *	- if we just hit in the MFU ghost list, then increase
19481544Seschrock 	 *	  the target size of the MFU list by decreasing the
19491544Seschrock 	 *	  target size of the MRU list.
1950789Sahrens 	 */
19513403Sbmc 	if (state == arc_mru_ghost) {
19523403Sbmc 		mult = ((arc_mru_ghost->arcs_size >= arc_mfu_ghost->arcs_size) ?
19533403Sbmc 		    1 : (arc_mfu_ghost->arcs_size/arc_mru_ghost->arcs_size));
19541544Seschrock 
19553403Sbmc 		arc_p = MIN(arc_c, arc_p + bytes * mult);
19563403Sbmc 	} else if (state == arc_mfu_ghost) {
19573403Sbmc 		mult = ((arc_mfu_ghost->arcs_size >= arc_mru_ghost->arcs_size) ?
19583403Sbmc 		    1 : (arc_mru_ghost->arcs_size/arc_mfu_ghost->arcs_size));
19591544Seschrock 
19603403Sbmc 		arc_p = MAX(0, (int64_t)arc_p - bytes * mult);
19611544Seschrock 	}
19623403Sbmc 	ASSERT((int64_t)arc_p >= 0);
1963789Sahrens 
1964789Sahrens 	if (arc_reclaim_needed()) {
1965789Sahrens 		cv_signal(&arc_reclaim_thr_cv);
1966789Sahrens 		return;
1967789Sahrens 	}
1968789Sahrens 
19693403Sbmc 	if (arc_no_grow)
1970789Sahrens 		return;
1971789Sahrens 
19723403Sbmc 	if (arc_c >= arc_c_max)
19731544Seschrock 		return;
19741544Seschrock 
1975789Sahrens 	/*
19761544Seschrock 	 * If we're within (2 * maxblocksize) bytes of the target
19771544Seschrock 	 * cache size, increment the target cache size
1978789Sahrens 	 */
19793403Sbmc 	if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
19803403Sbmc 		atomic_add_64(&arc_c, (int64_t)bytes);
19813403Sbmc 		if (arc_c > arc_c_max)
19823403Sbmc 			arc_c = arc_c_max;
19833403Sbmc 		else if (state == arc_anon)
19843403Sbmc 			atomic_add_64(&arc_p, (int64_t)bytes);
19853403Sbmc 		if (arc_p > arc_c)
19863403Sbmc 			arc_p = arc_c;
1987789Sahrens 	}
19883403Sbmc 	ASSERT((int64_t)arc_p >= 0);
1989789Sahrens }
1990789Sahrens 
1991789Sahrens /*
19921544Seschrock  * Check if the cache has reached its limits and eviction is required
19931544Seschrock  * prior to insert.
1994789Sahrens  */
1995789Sahrens static int
19964309Smaybee arc_evict_needed(arc_buf_contents_t type)
1997789Sahrens {
19984309Smaybee 	if (type == ARC_BUFC_METADATA && arc_meta_used >= arc_meta_limit)
19994309Smaybee 		return (1);
20004309Smaybee 
20014309Smaybee #ifdef _KERNEL
20024309Smaybee 	/*
20034309Smaybee 	 * If zio data pages are being allocated out of a separate heap segment,
20044309Smaybee 	 * then enforce that the size of available vmem for this area remains
20054309Smaybee 	 * above about 1/32nd free.
20064309Smaybee 	 */
20074309Smaybee 	if (type == ARC_BUFC_DATA && zio_arena != NULL &&
20084309Smaybee 	    vmem_size(zio_arena, VMEM_FREE) <
20094309Smaybee 	    (vmem_size(zio_arena, VMEM_ALLOC) >> 5))
20104309Smaybee 		return (1);
20114309Smaybee #endif
20124309Smaybee 
2013789Sahrens 	if (arc_reclaim_needed())
2014789Sahrens 		return (1);
2015789Sahrens 
20163403Sbmc 	return (arc_size > arc_c);
2017789Sahrens }
2018789Sahrens 
2019789Sahrens /*
20202688Smaybee  * The buffer, supplied as the first argument, needs a data block.
20212688Smaybee  * So, if we are at cache max, determine which cache should be victimized.
20222688Smaybee  * We have the following cases:
2023789Sahrens  *
20243403Sbmc  * 1. Insert for MRU, p > sizeof(arc_anon + arc_mru) ->
2025789Sahrens  * In this situation if we're out of space, but the resident size of the MFU is
2026789Sahrens  * under the limit, victimize the MFU cache to satisfy this insertion request.
2027789Sahrens  *
20283403Sbmc  * 2. Insert for MRU, p <= sizeof(arc_anon + arc_mru) ->
2029789Sahrens  * Here, we've used up all of the available space for the MRU, so we need to
2030789Sahrens  * evict from our own cache instead.  Evict from the set of resident MRU
2031789Sahrens  * entries.
2032789Sahrens  *
20333403Sbmc  * 3. Insert for MFU (c - p) > sizeof(arc_mfu) ->
2034789Sahrens  * c minus p represents the MFU space in the cache, since p is the size of the
2035789Sahrens  * cache that is dedicated to the MRU.  In this situation there's still space on
2036789Sahrens  * the MFU side, so the MRU side needs to be victimized.
2037789Sahrens  *
20383403Sbmc  * 4. Insert for MFU (c - p) < sizeof(arc_mfu) ->
2039789Sahrens  * MFU's resident set is consuming more space than it has been allotted.  In
2040789Sahrens  * this situation, we must victimize our own cache, the MFU, for this insertion.
2041789Sahrens  */
2042789Sahrens static void
20432688Smaybee arc_get_data_buf(arc_buf_t *buf)
2044789Sahrens {
20453290Sjohansen 	arc_state_t		*state = buf->b_hdr->b_state;
20463290Sjohansen 	uint64_t		size = buf->b_hdr->b_size;
20473290Sjohansen 	arc_buf_contents_t	type = buf->b_hdr->b_type;
20482688Smaybee 
20492688Smaybee 	arc_adapt(size, state);
2050789Sahrens 
20512688Smaybee 	/*
20522688Smaybee 	 * We have not yet reached cache maximum size,
20532688Smaybee 	 * just allocate a new buffer.
20542688Smaybee 	 */
20554309Smaybee 	if (!arc_evict_needed(type)) {
20563290Sjohansen 		if (type == ARC_BUFC_METADATA) {
20573290Sjohansen 			buf->b_data = zio_buf_alloc(size);
20584309Smaybee 			arc_space_consume(size);
20593290Sjohansen 		} else {
20603290Sjohansen 			ASSERT(type == ARC_BUFC_DATA);
20613290Sjohansen 			buf->b_data = zio_data_buf_alloc(size);
20624309Smaybee 			atomic_add_64(&arc_size, size);
20633290Sjohansen 		}
20642688Smaybee 		goto out;
20652688Smaybee 	}
20662688Smaybee 
20672688Smaybee 	/*
20682688Smaybee 	 * If we are prefetching from the mfu ghost list, this buffer
20692688Smaybee 	 * will end up on the mru list; so steal space from there.
20702688Smaybee 	 */
20713403Sbmc 	if (state == arc_mfu_ghost)
20723403Sbmc 		state = buf->b_hdr->b_flags & ARC_PREFETCH ? arc_mru : arc_mfu;
20733403Sbmc 	else if (state == arc_mru_ghost)
20743403Sbmc 		state = arc_mru;
2075789Sahrens 
20763403Sbmc 	if (state == arc_mru || state == arc_anon) {
20773403Sbmc 		uint64_t mru_used = arc_anon->arcs_size + arc_mru->arcs_size;
20784309Smaybee 		state = (arc_mfu->arcs_lsize[type] > 0 &&
20794309Smaybee 		    arc_p > mru_used) ? arc_mfu : arc_mru;
2080789Sahrens 	} else {
20812688Smaybee 		/* MFU cases */
20823403Sbmc 		uint64_t mfu_space = arc_c - arc_p;
20834309Smaybee 		state =  (arc_mru->arcs_lsize[type] > 0 &&
20844309Smaybee 		    mfu_space > arc_mfu->arcs_size) ? arc_mru : arc_mfu;
20852688Smaybee 	}
20865642Smaybee 	if ((buf->b_data = arc_evict(state, NULL, size, TRUE, type)) == NULL) {
20873290Sjohansen 		if (type == ARC_BUFC_METADATA) {
20883290Sjohansen 			buf->b_data = zio_buf_alloc(size);
20894309Smaybee 			arc_space_consume(size);
20903290Sjohansen 		} else {
20913290Sjohansen 			ASSERT(type == ARC_BUFC_DATA);
20923290Sjohansen 			buf->b_data = zio_data_buf_alloc(size);
20934309Smaybee 			atomic_add_64(&arc_size, size);
20943290Sjohansen 		}
20953403Sbmc 		ARCSTAT_BUMP(arcstat_recycle_miss);
20962688Smaybee 	}
20972688Smaybee 	ASSERT(buf->b_data != NULL);
20982688Smaybee out:
20992688Smaybee 	/*
21002688Smaybee 	 * Update the state size.  Note that ghost states have a
21012688Smaybee 	 * "ghost size" and so don't need to be updated.
21022688Smaybee 	 */
21032688Smaybee 	if (!GHOST_STATE(buf->b_hdr->b_state)) {
21042688Smaybee 		arc_buf_hdr_t *hdr = buf->b_hdr;
21052688Smaybee 
21063403Sbmc 		atomic_add_64(&hdr->b_state->arcs_size, size);
21072688Smaybee 		if (list_link_active(&hdr->b_arc_node)) {
21082688Smaybee 			ASSERT(refcount_is_zero(&hdr->b_refcnt));
21094309Smaybee 			atomic_add_64(&hdr->b_state->arcs_lsize[type], size);
2110789Sahrens 		}
21113298Smaybee 		/*
21123298Smaybee 		 * If we are growing the cache, and we are adding anonymous
21133403Sbmc 		 * data, and we have outgrown arc_p, update arc_p
21143298Smaybee 		 */
21153403Sbmc 		if (arc_size < arc_c && hdr->b_state == arc_anon &&
21163403Sbmc 		    arc_anon->arcs_size + arc_mru->arcs_size > arc_p)
21173403Sbmc 			arc_p = MIN(arc_c, arc_p + size);
2118789Sahrens 	}
2119789Sahrens }
2120789Sahrens 
2121789Sahrens /*
2122789Sahrens  * This routine is called whenever a buffer is accessed.
21231544Seschrock  * NOTE: the hash lock is dropped in this function.
2124789Sahrens  */
2125789Sahrens static void
21262688Smaybee arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock)
2127789Sahrens {
2128789Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
2129789Sahrens 
21303403Sbmc 	if (buf->b_state == arc_anon) {
2131789Sahrens 		/*
2132789Sahrens 		 * This buffer is not in the cache, and does not
2133789Sahrens 		 * appear in our "ghost" list.  Add the new buffer
2134789Sahrens 		 * to the MRU state.
2135789Sahrens 		 */
2136789Sahrens 
2137789Sahrens 		ASSERT(buf->b_arc_access == 0);
2138789Sahrens 		buf->b_arc_access = lbolt;
21391544Seschrock 		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
21403403Sbmc 		arc_change_state(arc_mru, buf, hash_lock);
2141789Sahrens 
21423403Sbmc 	} else if (buf->b_state == arc_mru) {
2143789Sahrens 		/*
21442391Smaybee 		 * If this buffer is here because of a prefetch, then either:
21452391Smaybee 		 * - clear the flag if this is a "referencing" read
21462391Smaybee 		 *   (any subsequent access will bump this into the MFU state).
21472391Smaybee 		 * or
21482391Smaybee 		 * - move the buffer to the head of the list if this is
21492391Smaybee 		 *   another prefetch (to make it less likely to be evicted).
2150789Sahrens 		 */
2151789Sahrens 		if ((buf->b_flags & ARC_PREFETCH) != 0) {
21522391Smaybee 			if (refcount_count(&buf->b_refcnt) == 0) {
21532391Smaybee 				ASSERT(list_link_active(&buf->b_arc_node));
21542391Smaybee 			} else {
21552391Smaybee 				buf->b_flags &= ~ARC_PREFETCH;
21563403Sbmc 				ARCSTAT_BUMP(arcstat_mru_hits);
21572391Smaybee 			}
21582391Smaybee 			buf->b_arc_access = lbolt;
2159789Sahrens 			return;
2160789Sahrens 		}
2161789Sahrens 
2162789Sahrens 		/*
2163789Sahrens 		 * This buffer has been "accessed" only once so far,
2164789Sahrens 		 * but it is still in the cache. Move it to the MFU
2165789Sahrens 		 * state.
2166789Sahrens 		 */
2167789Sahrens 		if (lbolt > buf->b_arc_access + ARC_MINTIME) {
2168789Sahrens 			/*
2169789Sahrens 			 * More than 125ms have passed since we
2170789Sahrens 			 * instantiated this buffer.  Move it to the
2171789Sahrens 			 * most frequently used state.
2172789Sahrens 			 */
2173789Sahrens 			buf->b_arc_access = lbolt;
21741544Seschrock 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
21753403Sbmc 			arc_change_state(arc_mfu, buf, hash_lock);
2176789Sahrens 		}
21773403Sbmc 		ARCSTAT_BUMP(arcstat_mru_hits);
21783403Sbmc 	} else if (buf->b_state == arc_mru_ghost) {
2179789Sahrens 		arc_state_t	*new_state;
2180789Sahrens 		/*
2181789Sahrens 		 * This buffer has been "accessed" recently, but
2182789Sahrens 		 * was evicted from the cache.  Move it to the
2183789Sahrens 		 * MFU state.
2184789Sahrens 		 */
2185789Sahrens 
2186789Sahrens 		if (buf->b_flags & ARC_PREFETCH) {
21873403Sbmc 			new_state = arc_mru;
21882391Smaybee 			if (refcount_count(&buf->b_refcnt) > 0)
21892391Smaybee 				buf->b_flags &= ~ARC_PREFETCH;
21901544Seschrock 			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2191789Sahrens 		} else {
21923403Sbmc 			new_state = arc_mfu;
21931544Seschrock 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2194789Sahrens 		}
2195789Sahrens 
2196789Sahrens 		buf->b_arc_access = lbolt;
2197789Sahrens 		arc_change_state(new_state, buf, hash_lock);
2198789Sahrens 
21993403Sbmc 		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
22003403Sbmc 	} else if (buf->b_state == arc_mfu) {
2201789Sahrens 		/*
2202789Sahrens 		 * This buffer has been accessed more than once and is
2203789Sahrens 		 * still in the cache.  Keep it in the MFU state.
2204789Sahrens 		 *
22052391Smaybee 		 * NOTE: an add_reference() that occurred when we did
22062391Smaybee 		 * the arc_read() will have kicked this off the list.
22072391Smaybee 		 * If it was a prefetch, we will explicitly move it to
22082391Smaybee 		 * the head of the list now.
2209789Sahrens 		 */
22102391Smaybee 		if ((buf->b_flags & ARC_PREFETCH) != 0) {
22112391Smaybee 			ASSERT(refcount_count(&buf->b_refcnt) == 0);
22122391Smaybee 			ASSERT(list_link_active(&buf->b_arc_node));
22132391Smaybee 		}
22143403Sbmc 		ARCSTAT_BUMP(arcstat_mfu_hits);
22152391Smaybee 		buf->b_arc_access = lbolt;
22163403Sbmc 	} else if (buf->b_state == arc_mfu_ghost) {
22173403Sbmc 		arc_state_t	*new_state = arc_mfu;
2218789Sahrens 		/*
2219789Sahrens 		 * This buffer has been accessed more than once but has
2220789Sahrens 		 * been evicted from the cache.  Move it back to the
2221789Sahrens 		 * MFU state.
2222789Sahrens 		 */
2223789Sahrens 
22242391Smaybee 		if (buf->b_flags & ARC_PREFETCH) {
22252391Smaybee 			/*
22262391Smaybee 			 * This is a prefetch access...
22272391Smaybee 			 * move this block back to the MRU state.
22282391Smaybee 			 */
22292391Smaybee 			ASSERT3U(refcount_count(&buf->b_refcnt), ==, 0);
22303403Sbmc 			new_state = arc_mru;
22312391Smaybee 		}
22322391Smaybee 
2233789Sahrens 		buf->b_arc_access = lbolt;
22341544Seschrock 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
22352391Smaybee 		arc_change_state(new_state, buf, hash_lock);
2236789Sahrens 
22373403Sbmc 		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
22385450Sbrendan 	} else if (buf->b_state == arc_l2c_only) {
22395450Sbrendan 		/*
22405450Sbrendan 		 * This buffer is on the 2nd Level ARC.
22415450Sbrendan 		 */
22425450Sbrendan 
22435450Sbrendan 		buf->b_arc_access = lbolt;
22445450Sbrendan 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
22455450Sbrendan 		arc_change_state(arc_mfu, buf, hash_lock);
2246789Sahrens 	} else {
2247789Sahrens 		ASSERT(!"invalid arc state");
2248789Sahrens 	}
2249789Sahrens }
2250789Sahrens 
2251789Sahrens /* a generic arc_done_func_t which you can use */
2252789Sahrens /* ARGSUSED */
2253789Sahrens void
2254789Sahrens arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
2255789Sahrens {
2256789Sahrens 	bcopy(buf->b_data, arg, buf->b_hdr->b_size);
22571544Seschrock 	VERIFY(arc_buf_remove_ref(buf, arg) == 1);
2258789Sahrens }
2259789Sahrens 
22604309Smaybee /* a generic arc_done_func_t */
2261789Sahrens void
2262789Sahrens arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
2263789Sahrens {
2264789Sahrens 	arc_buf_t **bufp = arg;
2265789Sahrens 	if (zio && zio->io_error) {
22661544Seschrock 		VERIFY(arc_buf_remove_ref(buf, arg) == 1);
2267789Sahrens 		*bufp = NULL;
2268789Sahrens 	} else {
2269789Sahrens 		*bufp = buf;
2270789Sahrens 	}
2271789Sahrens }
2272789Sahrens 
2273789Sahrens static void
2274789Sahrens arc_read_done(zio_t *zio)
2275789Sahrens {
22761589Smaybee 	arc_buf_hdr_t	*hdr, *found;
2277789Sahrens 	arc_buf_t	*buf;
2278789Sahrens 	arc_buf_t	*abuf;	/* buffer we're assigning to callback */
2279789Sahrens 	kmutex_t	*hash_lock;
2280789Sahrens 	arc_callback_t	*callback_list, *acb;
2281789Sahrens 	int		freeable = FALSE;
2282789Sahrens 
2283789Sahrens 	buf = zio->io_private;
2284789Sahrens 	hdr = buf->b_hdr;
2285789Sahrens 
22861589Smaybee 	/*
22871589Smaybee 	 * The hdr was inserted into hash-table and removed from lists
22881589Smaybee 	 * prior to starting I/O.  We should find this header, since
22891589Smaybee 	 * it's in the hash table, and it should be legit since it's
22901589Smaybee 	 * not possible to evict it during the I/O.  The only possible
22911589Smaybee 	 * reason for it not to be found is if we were freed during the
22921589Smaybee 	 * read.
22931589Smaybee 	 */
22941589Smaybee 	found = buf_hash_find(zio->io_spa, &hdr->b_dva, hdr->b_birth,
22953093Sahrens 	    &hash_lock);
2296789Sahrens 
22971589Smaybee 	ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) && hash_lock == NULL) ||
22985450Sbrendan 	    (found == hdr && DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
22995450Sbrendan 	    (found == hdr && HDR_L2_READING(hdr)));
23005450Sbrendan 
23016987Sbrendan 	hdr->b_flags &= ~ARC_L2_EVICTED;
23025450Sbrendan 	if (l2arc_noprefetch && (hdr->b_flags & ARC_PREFETCH))
23035450Sbrendan 		hdr->b_flags |= ARC_DONT_L2CACHE;
2304789Sahrens 
2305789Sahrens 	/* byteswap if necessary */
2306789Sahrens 	callback_list = hdr->b_acb;
2307789Sahrens 	ASSERT(callback_list != NULL);
2308*7046Sahrens 	if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
2309*7046Sahrens 		arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
2310*7046Sahrens 		    byteswap_uint64_array :
2311*7046Sahrens 		    dmu_ot[BP_GET_TYPE(zio->io_bp)].ot_byteswap;
2312*7046Sahrens 		func(buf->b_data, hdr->b_size);
2313*7046Sahrens 	}
2314789Sahrens 
23155450Sbrendan 	arc_cksum_compute(buf, B_FALSE);
23163093Sahrens 
2317789Sahrens 	/* create copies of the data buffer for the callers */
2318789Sahrens 	abuf = buf;
2319789Sahrens 	for (acb = callback_list; acb; acb = acb->acb_next) {
2320789Sahrens 		if (acb->acb_done) {
23212688Smaybee 			if (abuf == NULL)
23222688Smaybee 				abuf = arc_buf_clone(buf);
2323789Sahrens 			acb->acb_buf = abuf;
2324789Sahrens 			abuf = NULL;
2325789Sahrens 		}
2326789Sahrens 	}
2327789Sahrens 	hdr->b_acb = NULL;
2328789Sahrens 	hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
23291544Seschrock 	ASSERT(!HDR_BUF_AVAILABLE(hdr));
23301544Seschrock 	if (abuf == buf)
23311544Seschrock 		hdr->b_flags |= ARC_BUF_AVAILABLE;
2332789Sahrens 
2333789Sahrens 	ASSERT(refcount_is_zero(&hdr->b_refcnt) || callback_list != NULL);
2334789Sahrens 
2335789Sahrens 	if (zio->io_error != 0) {
2336789Sahrens 		hdr->b_flags |= ARC_IO_ERROR;
23373403Sbmc 		if (hdr->b_state != arc_anon)
23383403Sbmc 			arc_change_state(arc_anon, hdr, hash_lock);
23391544Seschrock 		if (HDR_IN_HASH_TABLE(hdr))
23401544Seschrock 			buf_hash_remove(hdr);
2341789Sahrens 		freeable = refcount_is_zero(&hdr->b_refcnt);
23422391Smaybee 		/* convert checksum errors into IO errors */
23431544Seschrock 		if (zio->io_error == ECKSUM)
23441544Seschrock 			zio->io_error = EIO;
2345789Sahrens 	}
2346789Sahrens 
23471544Seschrock 	/*
23482391Smaybee 	 * Broadcast before we drop the hash_lock to avoid the possibility
23492391Smaybee 	 * that the hdr (and hence the cv) might be freed before we get to
23502391Smaybee 	 * the cv_broadcast().
23511544Seschrock 	 */
23521544Seschrock 	cv_broadcast(&hdr->b_cv);
23531544Seschrock 
23541589Smaybee 	if (hash_lock) {
2355789Sahrens 		/*
2356789Sahrens 		 * Only call arc_access on anonymous buffers.  This is because
2357789Sahrens 		 * if we've issued an I/O for an evicted buffer, we've already
2358789Sahrens 		 * called arc_access (to prevent any simultaneous readers from
2359789Sahrens 		 * getting confused).
2360789Sahrens 		 */
23613403Sbmc 		if (zio->io_error == 0 && hdr->b_state == arc_anon)
23622688Smaybee 			arc_access(hdr, hash_lock);
23632688Smaybee 		mutex_exit(hash_lock);
2364789Sahrens 	} else {
2365789Sahrens 		/*
2366789Sahrens 		 * This block was freed while we waited for the read to
2367789Sahrens 		 * complete.  It has been removed from the hash table and
2368789Sahrens 		 * moved to the anonymous state (so that it won't show up
2369789Sahrens 		 * in the cache).
2370789Sahrens 		 */
23713403Sbmc 		ASSERT3P(hdr->b_state, ==, arc_anon);
2372789Sahrens 		freeable = refcount_is_zero(&hdr->b_refcnt);
2373789Sahrens 	}
2374789Sahrens 
2375789Sahrens 	/* execute each callback and free its structure */
2376789Sahrens 	while ((acb = callback_list) != NULL) {
2377789Sahrens 		if (acb->acb_done)
2378789Sahrens 			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
2379789Sahrens 
2380789Sahrens 		if (acb->acb_zio_dummy != NULL) {
2381789Sahrens 			acb->acb_zio_dummy->io_error = zio->io_error;
2382789Sahrens 			zio_nowait(acb->acb_zio_dummy);
2383789Sahrens 		}
2384789Sahrens 
2385789Sahrens 		callback_list = acb->acb_next;
2386789Sahrens 		kmem_free(acb, sizeof (arc_callback_t));
2387789Sahrens 	}
2388789Sahrens 
2389789Sahrens 	if (freeable)
23901544Seschrock 		arc_hdr_destroy(hdr);
2391789Sahrens }
2392789Sahrens 
2393789Sahrens /*
2394789Sahrens  * "Read" the block block at the specified DVA (in bp) via the
2395789Sahrens  * cache.  If the block is found in the cache, invoke the provided
2396789Sahrens  * callback immediately and return.  Note that the `zio' parameter
2397789Sahrens  * in the callback will be NULL in this case, since no IO was
2398789Sahrens  * required.  If the block is not in the cache pass the read request
2399789Sahrens  * on to the spa with a substitute callback function, so that the
2400789Sahrens  * requested block will be added to the cache.
2401789Sahrens  *
2402789Sahrens  * If a read request arrives for a block that has a read in-progress,
2403789Sahrens  * either wait for the in-progress read to complete (and return the
2404789Sahrens  * results); or, if this is a read with a "done" func, add a record
2405789Sahrens  * to the read to invoke the "done" func when the read completes,
2406789Sahrens  * and return; or just return.
2407789Sahrens  *
2408789Sahrens  * arc_read_done() will invoke all the requested "done" functions
2409789Sahrens  * for readers of this block.
2410*7046Sahrens  *
2411*7046Sahrens  * Normal callers should use arc_read and pass the arc buffer and offset
2412*7046Sahrens  * for the bp.  But if you know you don't need locking, you can use
2413*7046Sahrens  * arc_read_bp.
2414789Sahrens  */
2415789Sahrens int
2416*7046Sahrens arc_read(zio_t *pio, spa_t *spa, blkptr_t *bp, arc_buf_t *pbuf,
2417789Sahrens     arc_done_func_t *done, void *private, int priority, int flags,
2418*7046Sahrens     uint32_t *arc_flags, const zbookmark_t *zb)
2419*7046Sahrens {
2420*7046Sahrens 	int err;
2421*7046Sahrens 
2422*7046Sahrens 	ASSERT(!refcount_is_zero(&pbuf->b_hdr->b_refcnt));
2423*7046Sahrens 	ASSERT3U((char *)bp - (char *)pbuf->b_data, <, pbuf->b_hdr->b_size);
2424*7046Sahrens 	rw_enter(&pbuf->b_hdr->b_datalock, RW_READER);
2425*7046Sahrens 
2426*7046Sahrens 	err = arc_read_nolock(pio, spa, bp, done, private, priority,
2427*7046Sahrens 	    flags, arc_flags, zb);
2428*7046Sahrens 
2429*7046Sahrens 	rw_exit(&pbuf->b_hdr->b_datalock);
2430*7046Sahrens 	return (err);
2431*7046Sahrens }
2432*7046Sahrens 
2433*7046Sahrens int
2434*7046Sahrens arc_read_nolock(zio_t *pio, spa_t *spa, blkptr_t *bp,
2435*7046Sahrens     arc_done_func_t *done, void *private, int priority, int flags,
2436*7046Sahrens     uint32_t *arc_flags, const zbookmark_t *zb)
2437789Sahrens {
2438789Sahrens 	arc_buf_hdr_t *hdr;
2439789Sahrens 	arc_buf_t *buf;
2440789Sahrens 	kmutex_t *hash_lock;
24415450Sbrendan 	zio_t *rzio;
2442789Sahrens 
2443789Sahrens top:
2444789Sahrens 	hdr = buf_hash_find(spa, BP_IDENTITY(bp), bp->blk_birth, &hash_lock);
24451544Seschrock 	if (hdr && hdr->b_datacnt > 0) {
2446789Sahrens 
24472391Smaybee 		*arc_flags |= ARC_CACHED;
24482391Smaybee 
2449789Sahrens 		if (HDR_IO_IN_PROGRESS(hdr)) {
24502391Smaybee 
24512391Smaybee 			if (*arc_flags & ARC_WAIT) {
24522391Smaybee 				cv_wait(&hdr->b_cv, hash_lock);
24532391Smaybee 				mutex_exit(hash_lock);
24542391Smaybee 				goto top;
24552391Smaybee 			}
24562391Smaybee 			ASSERT(*arc_flags & ARC_NOWAIT);
24572391Smaybee 
24582391Smaybee 			if (done) {
2459789Sahrens 				arc_callback_t	*acb = NULL;
2460789Sahrens 
2461789Sahrens 				acb = kmem_zalloc(sizeof (arc_callback_t),
2462789Sahrens 				    KM_SLEEP);
2463789Sahrens 				acb->acb_done = done;
2464789Sahrens 				acb->acb_private = private;
2465789Sahrens 				if (pio != NULL)
2466789Sahrens 					acb->acb_zio_dummy = zio_null(pio,
2467789Sahrens 					    spa, NULL, NULL, flags);
2468789Sahrens 
2469789Sahrens 				ASSERT(acb->acb_done != NULL);
2470789Sahrens 				acb->acb_next = hdr->b_acb;
2471789Sahrens 				hdr->b_acb = acb;
2472789Sahrens 				add_reference(hdr, hash_lock, private);
2473789Sahrens 				mutex_exit(hash_lock);
2474789Sahrens 				return (0);
2475789Sahrens 			}
2476789Sahrens 			mutex_exit(hash_lock);
2477789Sahrens 			return (0);
2478789Sahrens 		}
2479789Sahrens 
24803403Sbmc 		ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
2481789Sahrens 
24821544Seschrock 		if (done) {
24832688Smaybee 			add_reference(hdr, hash_lock, private);
24841544Seschrock 			/*
24851544Seschrock 			 * If this block is already in use, create a new
24861544Seschrock 			 * copy of the data so that we will be guaranteed
24871544Seschrock 			 * that arc_release() will always succeed.
24881544Seschrock 			 */
24891544Seschrock 			buf = hdr->b_buf;
24901544Seschrock 			ASSERT(buf);
24911544Seschrock 			ASSERT(buf->b_data);
24922688Smaybee 			if (HDR_BUF_AVAILABLE(hdr)) {
24931544Seschrock 				ASSERT(buf->b_efunc == NULL);
24941544Seschrock 				hdr->b_flags &= ~ARC_BUF_AVAILABLE;
24952688Smaybee 			} else {
24962688Smaybee 				buf = arc_buf_clone(buf);
24971544Seschrock 			}
24982391Smaybee 		} else if (*arc_flags & ARC_PREFETCH &&
24992391Smaybee 		    refcount_count(&hdr->b_refcnt) == 0) {
25002391Smaybee 			hdr->b_flags |= ARC_PREFETCH;
2501789Sahrens 		}
2502789Sahrens 		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
25032688Smaybee 		arc_access(hdr, hash_lock);
25042688Smaybee 		mutex_exit(hash_lock);
25053403Sbmc 		ARCSTAT_BUMP(arcstat_hits);
25063403Sbmc 		ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
25073403Sbmc 		    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
25083403Sbmc 		    data, metadata, hits);
25093403Sbmc 
2510789Sahrens 		if (done)
2511789Sahrens 			done(NULL, buf, private);
2512789Sahrens 	} else {
2513789Sahrens 		uint64_t size = BP_GET_LSIZE(bp);
2514789Sahrens 		arc_callback_t	*acb;
25156987Sbrendan 		vdev_t *vd = NULL;
25166987Sbrendan 		daddr_t addr;
2517789Sahrens 
2518789Sahrens 		if (hdr == NULL) {
2519789Sahrens 			/* this block is not in the cache */
2520789Sahrens 			arc_buf_hdr_t	*exists;
25213290Sjohansen 			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
25223290Sjohansen 			buf = arc_buf_alloc(spa, size, private, type);
2523789Sahrens 			hdr = buf->b_hdr;
2524789Sahrens 			hdr->b_dva = *BP_IDENTITY(bp);
2525789Sahrens 			hdr->b_birth = bp->blk_birth;
2526789Sahrens 			hdr->b_cksum0 = bp->blk_cksum.zc_word[0];
2527789Sahrens 			exists = buf_hash_insert(hdr, &hash_lock);
2528789Sahrens 			if (exists) {
2529789Sahrens 				/* somebody beat us to the hash insert */
2530789Sahrens 				mutex_exit(hash_lock);
2531789Sahrens 				bzero(&hdr->b_dva, sizeof (dva_t));
2532789Sahrens 				hdr->b_birth = 0;
2533789Sahrens 				hdr->b_cksum0 = 0;
25341544Seschrock 				(void) arc_buf_remove_ref(buf, private);
2535789Sahrens 				goto top; /* restart the IO request */
2536789Sahrens 			}
25372391Smaybee 			/* if this is a prefetch, we don't have a reference */
25382391Smaybee 			if (*arc_flags & ARC_PREFETCH) {
25392391Smaybee 				(void) remove_reference(hdr, hash_lock,
25402391Smaybee 				    private);
25412391Smaybee 				hdr->b_flags |= ARC_PREFETCH;
25422391Smaybee 			}
25432391Smaybee 			if (BP_GET_LEVEL(bp) > 0)
25442391Smaybee 				hdr->b_flags |= ARC_INDIRECT;
2545789Sahrens 		} else {
2546789Sahrens 			/* this block is in the ghost cache */
25471544Seschrock 			ASSERT(GHOST_STATE(hdr->b_state));
25481544Seschrock 			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
25492391Smaybee 			ASSERT3U(refcount_count(&hdr->b_refcnt), ==, 0);
25502391Smaybee 			ASSERT(hdr->b_buf == NULL);
2551789Sahrens 
25522391Smaybee 			/* if this is a prefetch, we don't have a reference */
25532391Smaybee 			if (*arc_flags & ARC_PREFETCH)
25542391Smaybee 				hdr->b_flags |= ARC_PREFETCH;
25552391Smaybee 			else
25562391Smaybee 				add_reference(hdr, hash_lock, private);
25576245Smaybee 			buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
25581544Seschrock 			buf->b_hdr = hdr;
25592688Smaybee 			buf->b_data = NULL;
25601544Seschrock 			buf->b_efunc = NULL;
25611544Seschrock 			buf->b_private = NULL;
25621544Seschrock 			buf->b_next = NULL;
25631544Seschrock 			hdr->b_buf = buf;
25642688Smaybee 			arc_get_data_buf(buf);
25651544Seschrock 			ASSERT(hdr->b_datacnt == 0);
25661544Seschrock 			hdr->b_datacnt = 1;
25672391Smaybee 
2568789Sahrens 		}
2569789Sahrens 
2570789Sahrens 		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
2571789Sahrens 		acb->acb_done = done;
2572789Sahrens 		acb->acb_private = private;
2573789Sahrens 
2574789Sahrens 		ASSERT(hdr->b_acb == NULL);
2575789Sahrens 		hdr->b_acb = acb;
2576789Sahrens 		hdr->b_flags |= ARC_IO_IN_PROGRESS;
2577789Sahrens 
2578789Sahrens 		/*
2579789Sahrens 		 * If the buffer has been evicted, migrate it to a present state
2580789Sahrens 		 * before issuing the I/O.  Once we drop the hash-table lock,
2581789Sahrens 		 * the header will be marked as I/O in progress and have an
2582789Sahrens 		 * attached buffer.  At this point, anybody who finds this
2583789Sahrens 		 * buffer ought to notice that it's legit but has a pending I/O.
2584789Sahrens 		 */
2585789Sahrens 
25861544Seschrock 		if (GHOST_STATE(hdr->b_state))
25872688Smaybee 			arc_access(hdr, hash_lock);
2588789Sahrens 
25896987Sbrendan 		if (hdr->b_l2hdr != NULL) {
25906987Sbrendan 			vd = hdr->b_l2hdr->b_dev->l2ad_vdev;
25916987Sbrendan 			addr = hdr->b_l2hdr->b_daddr;
25926987Sbrendan 		}
25936987Sbrendan 
25946987Sbrendan 		mutex_exit(hash_lock);
25956987Sbrendan 
2596789Sahrens 		ASSERT3U(hdr->b_size, ==, size);
25971596Sahrens 		DTRACE_PROBE3(arc__miss, blkptr_t *, bp, uint64_t, size,
25981596Sahrens 		    zbookmark_t *, zb);
25993403Sbmc 		ARCSTAT_BUMP(arcstat_misses);
26003403Sbmc 		ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
26013403Sbmc 		    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
26023403Sbmc 		    data, metadata, misses);
26031544Seschrock 
26045450Sbrendan 		if (l2arc_ndev != 0) {
26055450Sbrendan 			/*
26066987Sbrendan 			 * Lock out device removal.
26075450Sbrendan 			 */
26086987Sbrendan 			spa_config_enter(spa, RW_READER, FTAG);
26096987Sbrendan 
26106987Sbrendan 			/*
26116987Sbrendan 			 * Read from the L2ARC if the following are true:
26126987Sbrendan 			 * 1. The L2ARC vdev was previously cached.
26136987Sbrendan 			 * 2. This buffer still has L2ARC metadata.
26146987Sbrendan 			 * 3. This buffer isn't currently writing to the L2ARC.
26156987Sbrendan 			 * 4. The L2ARC entry wasn't evicted, which may
26166987Sbrendan 			 *    also have invalidated the vdev.
26176987Sbrendan 			 */
26186987Sbrendan 			if (vd != NULL && hdr->b_l2hdr != NULL &&
26196987Sbrendan 			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr)) {
26205450Sbrendan 				l2arc_read_callback_t *cb;
26215450Sbrendan 
26226643Seschrock 				if (vdev_is_dead(vd))
26236987Sbrendan 					goto l2skip;
26245450Sbrendan 
26256643Seschrock 				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
26266643Seschrock 				ARCSTAT_BUMP(arcstat_l2_hits);
26276643Seschrock 
26285450Sbrendan 				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
26295450Sbrendan 				    KM_SLEEP);
26305450Sbrendan 				cb->l2rcb_buf = buf;
26315450Sbrendan 				cb->l2rcb_spa = spa;
26325450Sbrendan 				cb->l2rcb_bp = *bp;
26335450Sbrendan 				cb->l2rcb_zb = *zb;
26345450Sbrendan 				cb->l2rcb_flags = flags;
26355450Sbrendan 
26365450Sbrendan 				/*
26375450Sbrendan 				 * l2arc read.
26385450Sbrendan 				 */
26395450Sbrendan 				rzio = zio_read_phys(pio, vd, addr, size,
26405450Sbrendan 				    buf->b_data, ZIO_CHECKSUM_OFF,
26416987Sbrendan 				    l2arc_read_done, cb, priority, flags |
26426987Sbrendan 				    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_CANFAIL,
26436987Sbrendan 				    B_FALSE);
26445450Sbrendan 				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
26455450Sbrendan 				    zio_t *, rzio);
26466987Sbrendan 				spa_config_exit(spa, FTAG);
26476987Sbrendan 
26486987Sbrendan 				if (*arc_flags & ARC_NOWAIT) {
26496987Sbrendan 					zio_nowait(rzio);
26506987Sbrendan 					return (0);
26516987Sbrendan 				}
26526987Sbrendan 
26536987Sbrendan 				ASSERT(*arc_flags & ARC_WAIT);
26546987Sbrendan 				if (zio_wait(rzio) == 0)
26556987Sbrendan 					return (0);
26566987Sbrendan 
26576987Sbrendan 				/* l2arc read error; goto zio_read() */
26585450Sbrendan 			} else {
26595450Sbrendan 				DTRACE_PROBE1(l2arc__miss,
26605450Sbrendan 				    arc_buf_hdr_t *, hdr);
26615450Sbrendan 				ARCSTAT_BUMP(arcstat_l2_misses);
26625450Sbrendan 				if (HDR_L2_WRITING(hdr))
26635450Sbrendan 					ARCSTAT_BUMP(arcstat_l2_rw_clash);
26646987Sbrendan l2skip:
26656987Sbrendan 				spa_config_exit(spa, FTAG);
26665450Sbrendan 			}
26675450Sbrendan 		}
26686643Seschrock 
2669789Sahrens 		rzio = zio_read(pio, spa, bp, buf->b_data, size,
26701544Seschrock 		    arc_read_done, buf, priority, flags, zb);
2671789Sahrens 
26722391Smaybee 		if (*arc_flags & ARC_WAIT)
2673789Sahrens 			return (zio_wait(rzio));
2674789Sahrens 
26752391Smaybee 		ASSERT(*arc_flags & ARC_NOWAIT);
2676789Sahrens 		zio_nowait(rzio);
2677789Sahrens 	}
2678789Sahrens 	return (0);
2679789Sahrens }
2680789Sahrens 
2681789Sahrens /*
2682789Sahrens  * arc_read() variant to support pool traversal.  If the block is already
2683789Sahrens  * in the ARC, make a copy of it; otherwise, the caller will do the I/O.
2684789Sahrens  * The idea is that we don't want pool traversal filling up memory, but
2685789Sahrens  * if the ARC already has the data anyway, we shouldn't pay for the I/O.
2686789Sahrens  */
2687789Sahrens int
2688789Sahrens arc_tryread(spa_t *spa, blkptr_t *bp, void *data)
2689789Sahrens {
2690789Sahrens 	arc_buf_hdr_t *hdr;
2691789Sahrens 	kmutex_t *hash_mtx;
2692789Sahrens 	int rc = 0;
2693789Sahrens 
2694789Sahrens 	hdr = buf_hash_find(spa, BP_IDENTITY(bp), bp->blk_birth, &hash_mtx);
2695789Sahrens 
26961544Seschrock 	if (hdr && hdr->b_datacnt > 0 && !HDR_IO_IN_PROGRESS(hdr)) {
26971544Seschrock 		arc_buf_t *buf = hdr->b_buf;
26981544Seschrock 
26991544Seschrock 		ASSERT(buf);
27001544Seschrock 		while (buf->b_data == NULL) {
27011544Seschrock 			buf = buf->b_next;
27021544Seschrock 			ASSERT(buf);
27031544Seschrock 		}
27041544Seschrock 		bcopy(buf->b_data, data, hdr->b_size);
27051544Seschrock 	} else {
2706789Sahrens 		rc = ENOENT;
27071544Seschrock 	}
2708789Sahrens 
2709789Sahrens 	if (hash_mtx)
2710789Sahrens 		mutex_exit(hash_mtx);
2711789Sahrens 
2712789Sahrens 	return (rc);
2713789Sahrens }
2714789Sahrens 
27151544Seschrock void
27161544Seschrock arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
27171544Seschrock {
27181544Seschrock 	ASSERT(buf->b_hdr != NULL);
27193403Sbmc 	ASSERT(buf->b_hdr->b_state != arc_anon);
27201544Seschrock 	ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt) || func == NULL);
27211544Seschrock 	buf->b_efunc = func;
27221544Seschrock 	buf->b_private = private;
27231544Seschrock }
27241544Seschrock 
27251544Seschrock /*
27261544Seschrock  * This is used by the DMU to let the ARC know that a buffer is
27271544Seschrock  * being evicted, so the ARC should clean up.  If this arc buf
27281544Seschrock  * is not yet in the evicted state, it will be put there.
27291544Seschrock  */
27301544Seschrock int
27311544Seschrock arc_buf_evict(arc_buf_t *buf)
27321544Seschrock {
27332887Smaybee 	arc_buf_hdr_t *hdr;
27341544Seschrock 	kmutex_t *hash_lock;
27351544Seschrock 	arc_buf_t **bufp;
27361544Seschrock 
27372887Smaybee 	mutex_enter(&arc_eviction_mtx);
27382887Smaybee 	hdr = buf->b_hdr;
27391544Seschrock 	if (hdr == NULL) {
27401544Seschrock 		/*
27411544Seschrock 		 * We are in arc_do_user_evicts().
27421544Seschrock 		 */
27431544Seschrock 		ASSERT(buf->b_data == NULL);
27442887Smaybee 		mutex_exit(&arc_eviction_mtx);
27451544Seschrock 		return (0);
27461544Seschrock 	}
27472887Smaybee 	hash_lock = HDR_LOCK(hdr);
27482887Smaybee 	mutex_exit(&arc_eviction_mtx);
27491544Seschrock 
27501544Seschrock 	mutex_enter(hash_lock);
27511544Seschrock 
27522724Smaybee 	if (buf->b_data == NULL) {
27532724Smaybee 		/*
27542724Smaybee 		 * We are on the eviction list.
27552724Smaybee 		 */
27562724Smaybee 		mutex_exit(hash_lock);
27572724Smaybee 		mutex_enter(&arc_eviction_mtx);
27582724Smaybee 		if (buf->b_hdr == NULL) {
27592724Smaybee 			/*
27602724Smaybee 			 * We are already in arc_do_user_evicts().
27612724Smaybee 			 */
27622724Smaybee 			mutex_exit(&arc_eviction_mtx);
27632724Smaybee 			return (0);
27642724Smaybee 		} else {
27652724Smaybee 			arc_buf_t copy = *buf; /* structure assignment */
27662724Smaybee 			/*
27672724Smaybee 			 * Process this buffer now
27682724Smaybee 			 * but let arc_do_user_evicts() do the reaping.
27692724Smaybee 			 */
27702724Smaybee 			buf->b_efunc = NULL;
27712724Smaybee 			mutex_exit(&arc_eviction_mtx);
27722724Smaybee 			VERIFY(copy.b_efunc(&copy) == 0);
27732724Smaybee 			return (1);
27742724Smaybee 		}
27752724Smaybee 	}
27762724Smaybee 
27772724Smaybee 	ASSERT(buf->b_hdr == hdr);
27782724Smaybee 	ASSERT3U(refcount_count(&hdr->b_refcnt), <, hdr->b_datacnt);
27793403Sbmc 	ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
27801544Seschrock 
27811544Seschrock 	/*
27821544Seschrock 	 * Pull this buffer off of the hdr
27831544Seschrock 	 */
27841544Seschrock 	bufp = &hdr->b_buf;
27851544Seschrock 	while (*bufp != buf)
27861544Seschrock 		bufp = &(*bufp)->b_next;
27871544Seschrock 	*bufp = buf->b_next;
27881544Seschrock 
27891544Seschrock 	ASSERT(buf->b_data != NULL);
27902688Smaybee 	arc_buf_destroy(buf, FALSE, FALSE);
27911544Seschrock 
27921544Seschrock 	if (hdr->b_datacnt == 0) {
27931544Seschrock 		arc_state_t *old_state = hdr->b_state;
27941544Seschrock 		arc_state_t *evicted_state;
27951544Seschrock 
27961544Seschrock 		ASSERT(refcount_is_zero(&hdr->b_refcnt));
27971544Seschrock 
27981544Seschrock 		evicted_state =
27993403Sbmc 		    (old_state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
28001544Seschrock 
28013403Sbmc 		mutex_enter(&old_state->arcs_mtx);
28023403Sbmc 		mutex_enter(&evicted_state->arcs_mtx);
28031544Seschrock 
28041544Seschrock 		arc_change_state(evicted_state, hdr, hash_lock);
28051544Seschrock 		ASSERT(HDR_IN_HASH_TABLE(hdr));
28065450Sbrendan 		hdr->b_flags |= ARC_IN_HASH_TABLE;
28075450Sbrendan 		hdr->b_flags &= ~ARC_BUF_AVAILABLE;
28081544Seschrock 
28093403Sbmc 		mutex_exit(&evicted_state->arcs_mtx);
28103403Sbmc 		mutex_exit(&old_state->arcs_mtx);
28111544Seschrock 	}
28121544Seschrock 	mutex_exit(hash_lock);
28131819Smaybee 
28141544Seschrock 	VERIFY(buf->b_efunc(buf) == 0);
28151544Seschrock 	buf->b_efunc = NULL;
28161544Seschrock 	buf->b_private = NULL;
28171544Seschrock 	buf->b_hdr = NULL;
28181544Seschrock 	kmem_cache_free(buf_cache, buf);
28191544Seschrock 	return (1);
28201544Seschrock }
28211544Seschrock 
2822789Sahrens /*
2823789Sahrens  * Release this buffer from the cache.  This must be done
2824789Sahrens  * after a read and prior to modifying the buffer contents.
2825789Sahrens  * If the buffer has more than one reference, we must make
2826*7046Sahrens  * a new hdr for the buffer.
2827789Sahrens  */
2828789Sahrens void
2829789Sahrens arc_release(arc_buf_t *buf, void *tag)
2830789Sahrens {
2831789Sahrens 	arc_buf_hdr_t *hdr = buf->b_hdr;
2832789Sahrens 	kmutex_t *hash_lock = HDR_LOCK(hdr);
28335450Sbrendan 	l2arc_buf_hdr_t *l2hdr = NULL;
28345450Sbrendan 	uint64_t buf_size;
2835789Sahrens 
2836789Sahrens 	/* this buffer is not on any list */
2837789Sahrens 	ASSERT(refcount_count(&hdr->b_refcnt) > 0);
2838*7046Sahrens 	ASSERT(!(hdr->b_flags & ARC_STORED));
2839789Sahrens 
28403403Sbmc 	if (hdr->b_state == arc_anon) {
2841789Sahrens 		/* this buffer is already released */
2842789Sahrens 		ASSERT3U(refcount_count(&hdr->b_refcnt), ==, 1);
2843789Sahrens 		ASSERT(BUF_EMPTY(hdr));
28441544Seschrock 		ASSERT(buf->b_efunc == NULL);
28453093Sahrens 		arc_buf_thaw(buf);
2846789Sahrens 		return;
2847789Sahrens 	}
2848789Sahrens 
2849789Sahrens 	mutex_enter(hash_lock);
2850789Sahrens 
28511544Seschrock 	/*
28521544Seschrock 	 * Do we have more than one buf?
28531544Seschrock 	 */
28541544Seschrock 	if (hdr->b_buf != buf || buf->b_next != NULL) {
2855789Sahrens 		arc_buf_hdr_t *nhdr;
2856789Sahrens 		arc_buf_t **bufp;
2857789Sahrens 		uint64_t blksz = hdr->b_size;
2858789Sahrens 		spa_t *spa = hdr->b_spa;
28593290Sjohansen 		arc_buf_contents_t type = hdr->b_type;
28605450Sbrendan 		uint32_t flags = hdr->b_flags;
2861789Sahrens 
28621544Seschrock 		ASSERT(hdr->b_datacnt > 1);
2863789Sahrens 		/*
2864789Sahrens 		 * Pull the data off of this buf and attach it to
2865789Sahrens 		 * a new anonymous buf.
2866789Sahrens 		 */
28671544Seschrock 		(void) remove_reference(hdr, hash_lock, tag);
2868789Sahrens 		bufp = &hdr->b_buf;
28691544Seschrock 		while (*bufp != buf)
2870789Sahrens 			bufp = &(*bufp)->b_next;
2871789Sahrens 		*bufp = (*bufp)->b_next;
28723897Smaybee 		buf->b_next = NULL;
28731544Seschrock 
28743403Sbmc 		ASSERT3U(hdr->b_state->arcs_size, >=, hdr->b_size);
28753403Sbmc 		atomic_add_64(&hdr->b_state->arcs_size, -hdr->b_size);
28761544Seschrock 		if (refcount_is_zero(&hdr->b_refcnt)) {
28774309Smaybee 			uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
28784309Smaybee 			ASSERT3U(*size, >=, hdr->b_size);
28794309Smaybee 			atomic_add_64(size, -hdr->b_size);
28801544Seschrock 		}
28811544Seschrock 		hdr->b_datacnt -= 1;
28825450Sbrendan 		if (hdr->b_l2hdr != NULL) {
28835450Sbrendan 			mutex_enter(&l2arc_buflist_mtx);
28845450Sbrendan 			l2hdr = hdr->b_l2hdr;
28855450Sbrendan 			hdr->b_l2hdr = NULL;
28865450Sbrendan 			buf_size = hdr->b_size;
28875450Sbrendan 		}
28883547Smaybee 		arc_cksum_verify(buf);
28891544Seschrock 
2890789Sahrens 		mutex_exit(hash_lock);
2891789Sahrens 
28926245Smaybee 		nhdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
2893789Sahrens 		nhdr->b_size = blksz;
2894789Sahrens 		nhdr->b_spa = spa;
28953290Sjohansen 		nhdr->b_type = type;
2896789Sahrens 		nhdr->b_buf = buf;
28973403Sbmc 		nhdr->b_state = arc_anon;
2898789Sahrens 		nhdr->b_arc_access = 0;
28995450Sbrendan 		nhdr->b_flags = flags & ARC_L2_WRITING;
29005450Sbrendan 		nhdr->b_l2hdr = NULL;
29011544Seschrock 		nhdr->b_datacnt = 1;
29023547Smaybee 		nhdr->b_freeze_cksum = NULL;
29033897Smaybee 		(void) refcount_add(&nhdr->b_refcnt, tag);
2904789Sahrens 		buf->b_hdr = nhdr;
29053403Sbmc 		atomic_add_64(&arc_anon->arcs_size, blksz);
2906789Sahrens 	} else {
29071544Seschrock 		ASSERT(refcount_count(&hdr->b_refcnt) == 1);
2908789Sahrens 		ASSERT(!list_link_active(&hdr->b_arc_node));
2909789Sahrens 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
29103403Sbmc 		arc_change_state(arc_anon, hdr, hash_lock);
2911789Sahrens 		hdr->b_arc_access = 0;
29125450Sbrendan 		if (hdr->b_l2hdr != NULL) {
29135450Sbrendan 			mutex_enter(&l2arc_buflist_mtx);
29145450Sbrendan 			l2hdr = hdr->b_l2hdr;
29155450Sbrendan 			hdr->b_l2hdr = NULL;
29165450Sbrendan 			buf_size = hdr->b_size;
29175450Sbrendan 		}
2918789Sahrens 		mutex_exit(hash_lock);
29195450Sbrendan 
2920789Sahrens 		bzero(&hdr->b_dva, sizeof (dva_t));
2921789Sahrens 		hdr->b_birth = 0;
2922789Sahrens 		hdr->b_cksum0 = 0;
29233547Smaybee 		arc_buf_thaw(buf);
2924789Sahrens 	}
29251544Seschrock 	buf->b_efunc = NULL;
29261544Seschrock 	buf->b_private = NULL;
29275450Sbrendan 
29285450Sbrendan 	if (l2hdr) {
29295450Sbrendan 		list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
29305450Sbrendan 		kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
29315450Sbrendan 		ARCSTAT_INCR(arcstat_l2_size, -buf_size);
29325450Sbrendan 	}
29335450Sbrendan 	if (MUTEX_HELD(&l2arc_buflist_mtx))
29345450Sbrendan 		mutex_exit(&l2arc_buflist_mtx);
2935789Sahrens }
2936789Sahrens 
2937789Sahrens int
2938789Sahrens arc_released(arc_buf_t *buf)
2939789Sahrens {
29403403Sbmc 	return (buf->b_data != NULL && buf->b_hdr->b_state == arc_anon);
29411544Seschrock }
29421544Seschrock 
29431544Seschrock int
29441544Seschrock arc_has_callback(arc_buf_t *buf)
29451544Seschrock {
29461544Seschrock 	return (buf->b_efunc != NULL);
2947789Sahrens }
2948789Sahrens 
29491544Seschrock #ifdef ZFS_DEBUG
29501544Seschrock int
29511544Seschrock arc_referenced(arc_buf_t *buf)
29521544Seschrock {
29531544Seschrock 	return (refcount_count(&buf->b_hdr->b_refcnt));
29541544Seschrock }
29551544Seschrock #endif
29561544Seschrock 
2957789Sahrens static void
29583547Smaybee arc_write_ready(zio_t *zio)
29593547Smaybee {
29603547Smaybee 	arc_write_callback_t *callback = zio->io_private;
29613547Smaybee 	arc_buf_t *buf = callback->awcb_buf;
29625329Sgw25295 	arc_buf_hdr_t *hdr = buf->b_hdr;
29635329Sgw25295 
29645329Sgw25295 	if (zio->io_error == 0 && callback->awcb_ready) {
29653547Smaybee 		ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt));
29663547Smaybee 		callback->awcb_ready(zio, buf, callback->awcb_private);
29673547Smaybee 	}
29685329Sgw25295 	/*
29695329Sgw25295 	 * If the IO is already in progress, then this is a re-write
29705329Sgw25295 	 * attempt, so we need to thaw and re-compute the cksum. It is
29715329Sgw25295 	 * the responsibility of the callback to handle the freeing
29725329Sgw25295 	 * and accounting for any re-write attempt. If we don't have a
29735329Sgw25295 	 * callback registered then simply free the block here.
29745329Sgw25295 	 */
29755329Sgw25295 	if (HDR_IO_IN_PROGRESS(hdr)) {
29765329Sgw25295 		if (!BP_IS_HOLE(&zio->io_bp_orig) &&
29775329Sgw25295 		    callback->awcb_ready == NULL) {
29785329Sgw25295 			zio_nowait(zio_free(zio, zio->io_spa, zio->io_txg,
29795329Sgw25295 			    &zio->io_bp_orig, NULL, NULL));
29805329Sgw25295 		}
29815329Sgw25295 		mutex_enter(&hdr->b_freeze_lock);
29825329Sgw25295 		if (hdr->b_freeze_cksum != NULL) {
29835329Sgw25295 			kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
29845329Sgw25295 			hdr->b_freeze_cksum = NULL;
29855329Sgw25295 		}
29865329Sgw25295 		mutex_exit(&hdr->b_freeze_lock);
29875329Sgw25295 	}
29885450Sbrendan 	arc_cksum_compute(buf, B_FALSE);
29895329Sgw25295 	hdr->b_flags |= ARC_IO_IN_PROGRESS;
29903547Smaybee }
29913547Smaybee 
29923547Smaybee static void
2993789Sahrens arc_write_done(zio_t *zio)
2994789Sahrens {
29953547Smaybee 	arc_write_callback_t *callback = zio->io_private;
29963547Smaybee 	arc_buf_t *buf = callback->awcb_buf;
29973547Smaybee 	arc_buf_hdr_t *hdr = buf->b_hdr;
2998789Sahrens 
2999789Sahrens 	hdr->b_acb = NULL;
3000789Sahrens 
3001789Sahrens 	hdr->b_dva = *BP_IDENTITY(zio->io_bp);
3002789Sahrens 	hdr->b_birth = zio->io_bp->blk_birth;
3003789Sahrens 	hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
30041544Seschrock 	/*
30051544Seschrock 	 * If the block to be written was all-zero, we may have
30061544Seschrock 	 * compressed it away.  In this case no write was performed
30071544Seschrock 	 * so there will be no dva/birth-date/checksum.  The buffer
30081544Seschrock 	 * must therefor remain anonymous (and uncached).
30091544Seschrock 	 */
3010789Sahrens 	if (!BUF_EMPTY(hdr)) {
3011789Sahrens 		arc_buf_hdr_t *exists;
3012789Sahrens 		kmutex_t *hash_lock;
3013789Sahrens 
30143093Sahrens 		arc_cksum_verify(buf);
30153093Sahrens 
3016789Sahrens 		exists = buf_hash_insert(hdr, &hash_lock);
3017789Sahrens 		if (exists) {
3018789Sahrens 			/*
3019789Sahrens 			 * This can only happen if we overwrite for
3020789Sahrens 			 * sync-to-convergence, because we remove
3021789Sahrens 			 * buffers from the hash table when we arc_free().
3022789Sahrens 			 */
3023789Sahrens 			ASSERT(DVA_EQUAL(BP_IDENTITY(&zio->io_bp_orig),
3024789Sahrens 			    BP_IDENTITY(zio->io_bp)));
3025789Sahrens 			ASSERT3U(zio->io_bp_orig.blk_birth, ==,
3026789Sahrens 			    zio->io_bp->blk_birth);
3027789Sahrens 
3028789Sahrens 			ASSERT(refcount_is_zero(&exists->b_refcnt));
30293403Sbmc 			arc_change_state(arc_anon, exists, hash_lock);
3030789Sahrens 			mutex_exit(hash_lock);
30311544Seschrock 			arc_hdr_destroy(exists);
3032789Sahrens 			exists = buf_hash_insert(hdr, &hash_lock);
3033789Sahrens 			ASSERT3P(exists, ==, NULL);
3034789Sahrens 		}
30351544Seschrock 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3036*7046Sahrens 		/* if it's not anon, we are doing a scrub */
3037*7046Sahrens 		if (hdr->b_state == arc_anon)
3038*7046Sahrens 			arc_access(hdr, hash_lock);
30392688Smaybee 		mutex_exit(hash_lock);
30403547Smaybee 	} else if (callback->awcb_done == NULL) {
30411544Seschrock 		int destroy_hdr;
30421544Seschrock 		/*
30431544Seschrock 		 * This is an anonymous buffer with no user callback,
30441544Seschrock 		 * destroy it if there are no active references.
30451544Seschrock 		 */
30461544Seschrock 		mutex_enter(&arc_eviction_mtx);
30471544Seschrock 		destroy_hdr = refcount_is_zero(&hdr->b_refcnt);
30481544Seschrock 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
30491544Seschrock 		mutex_exit(&arc_eviction_mtx);
30501544Seschrock 		if (destroy_hdr)
30511544Seschrock 			arc_hdr_destroy(hdr);
30521544Seschrock 	} else {
30531544Seschrock 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3054789Sahrens 	}
3055*7046Sahrens 	hdr->b_flags &= ~ARC_STORED;
30561544Seschrock 
30573547Smaybee 	if (callback->awcb_done) {
3058789Sahrens 		ASSERT(!refcount_is_zero(&hdr->b_refcnt));
30593547Smaybee 		callback->awcb_done(zio, buf, callback->awcb_private);
3060789Sahrens 	}
3061789Sahrens 
30623547Smaybee 	kmem_free(callback, sizeof (arc_write_callback_t));
3063789Sahrens }
3064789Sahrens 
3065*7046Sahrens static void
3066*7046Sahrens write_policy(spa_t *spa, const writeprops_t *wp,
3067*7046Sahrens     int *cksump, int *compp, int *copiesp)
3068*7046Sahrens {
3069*7046Sahrens 	int copies = wp->wp_copies;
3070*7046Sahrens 	boolean_t ismd = (wp->wp_level > 0 || dmu_ot[wp->wp_type].ot_metadata);
3071*7046Sahrens 
3072*7046Sahrens 	/* Determine copies setting */
3073*7046Sahrens 	if (ismd)
3074*7046Sahrens 		copies++;
3075*7046Sahrens 	*copiesp = MIN(copies, spa_max_replication(spa));
3076*7046Sahrens 
3077*7046Sahrens 	/* Determine checksum setting */
3078*7046Sahrens 	if (ismd) {
3079*7046Sahrens 		/*
3080*7046Sahrens 		 * Metadata always gets checksummed.  If the data
3081*7046Sahrens 		 * checksum is multi-bit correctable, and it's not a
3082*7046Sahrens 		 * ZBT-style checksum, then it's suitable for metadata
3083*7046Sahrens 		 * as well.  Otherwise, the metadata checksum defaults
3084*7046Sahrens 		 * to fletcher4.
3085*7046Sahrens 		 */
3086*7046Sahrens 		if (zio_checksum_table[wp->wp_oschecksum].ci_correctable &&
3087*7046Sahrens 		    !zio_checksum_table[wp->wp_oschecksum].ci_zbt)
3088*7046Sahrens 			*cksump = wp->wp_oschecksum;
3089*7046Sahrens 		else
3090*7046Sahrens 			*cksump = ZIO_CHECKSUM_FLETCHER_4;
3091*7046Sahrens 	} else {
3092*7046Sahrens 		*cksump = zio_checksum_select(wp->wp_dnchecksum,
3093*7046Sahrens 		    wp->wp_oschecksum);
3094*7046Sahrens 	}
3095*7046Sahrens 
3096*7046Sahrens 	/* Determine compression setting */
3097*7046Sahrens 	if (ismd) {
3098*7046Sahrens 		/*
3099*7046Sahrens 		 * XXX -- we should design a compression algorithm
3100*7046Sahrens 		 * that specializes in arrays of bps.
3101*7046Sahrens 		 */
3102*7046Sahrens 		*compp = zfs_mdcomp_disable ? ZIO_COMPRESS_EMPTY :
3103*7046Sahrens 		    ZIO_COMPRESS_LZJB;
3104*7046Sahrens 	} else {
3105*7046Sahrens 		*compp = zio_compress_select(wp->wp_dncompress,
3106*7046Sahrens 		    wp->wp_oscompress);
3107*7046Sahrens 	}
3108*7046Sahrens }
3109*7046Sahrens 
31103547Smaybee zio_t *
3111*7046Sahrens arc_write(zio_t *pio, spa_t *spa, const writeprops_t *wp,
3112789Sahrens     uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
31133547Smaybee     arc_done_func_t *ready, arc_done_func_t *done, void *private, int priority,
3114*7046Sahrens     int flags, const zbookmark_t *zb)
3115789Sahrens {
3116789Sahrens 	arc_buf_hdr_t *hdr = buf->b_hdr;
31173547Smaybee 	arc_write_callback_t *callback;
31183547Smaybee 	zio_t	*zio;
3119*7046Sahrens 	int cksum, comp, copies;
3120*7046Sahrens 
3121789Sahrens 	ASSERT(!HDR_IO_ERROR(hdr));
31222237Smaybee 	ASSERT((hdr->b_flags & ARC_IO_IN_PROGRESS) == 0);
31232237Smaybee 	ASSERT(hdr->b_acb == 0);
31243547Smaybee 	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
31253547Smaybee 	callback->awcb_ready = ready;
31263547Smaybee 	callback->awcb_done = done;
31273547Smaybee 	callback->awcb_private = private;
31283547Smaybee 	callback->awcb_buf = buf;
3129*7046Sahrens 
3130*7046Sahrens 	write_policy(spa, wp, &cksum, &comp, &copies);
3131*7046Sahrens 	zio = zio_write(pio, spa, cksum, comp, copies, txg, bp,
3132*7046Sahrens 	    buf->b_data, hdr->b_size, arc_write_ready, arc_write_done,
3133*7046Sahrens 	    callback, priority, flags, zb);
3134789Sahrens 
31353547Smaybee 	return (zio);
3136789Sahrens }
3137789Sahrens 
3138789Sahrens int
3139789Sahrens arc_free(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
3140789Sahrens     zio_done_func_t *done, void *private, uint32_t arc_flags)
3141789Sahrens {
3142789Sahrens 	arc_buf_hdr_t *ab;
3143789Sahrens 	kmutex_t *hash_lock;
3144789Sahrens 	zio_t	*zio;
3145789Sahrens 
3146789Sahrens 	/*
3147789Sahrens 	 * If this buffer is in the cache, release it, so it
3148789Sahrens 	 * can be re-used.
3149789Sahrens 	 */
3150789Sahrens 	ab = buf_hash_find(spa, BP_IDENTITY(bp), bp->blk_birth, &hash_lock);
3151789Sahrens 	if (ab != NULL) {
3152789Sahrens 		/*
3153789Sahrens 		 * The checksum of blocks to free is not always
3154789Sahrens 		 * preserved (eg. on the deadlist).  However, if it is
3155789Sahrens 		 * nonzero, it should match what we have in the cache.
3156789Sahrens 		 */
3157789Sahrens 		ASSERT(bp->blk_cksum.zc_word[0] == 0 ||
3158789Sahrens 		    ab->b_cksum0 == bp->blk_cksum.zc_word[0]);
31593403Sbmc 		if (ab->b_state != arc_anon)
31603403Sbmc 			arc_change_state(arc_anon, ab, hash_lock);
31612391Smaybee 		if (HDR_IO_IN_PROGRESS(ab)) {
31622391Smaybee 			/*
31632391Smaybee 			 * This should only happen when we prefetch.
31642391Smaybee 			 */
31652391Smaybee 			ASSERT(ab->b_flags & ARC_PREFETCH);
31662391Smaybee 			ASSERT3U(ab->b_datacnt, ==, 1);
31672391Smaybee 			ab->b_flags |= ARC_FREED_IN_READ;
31682391Smaybee 			if (HDR_IN_HASH_TABLE(ab))
31692391Smaybee 				buf_hash_remove(ab);
31702391Smaybee 			ab->b_arc_access = 0;
31712391Smaybee 			bzero(&ab->b_dva, sizeof (dva_t));
31722391Smaybee 			ab->b_birth = 0;
31732391Smaybee 			ab->b_cksum0 = 0;
31742391Smaybee 			ab->b_buf->b_efunc = NULL;
31752391Smaybee 			ab->b_buf->b_private = NULL;
31762391Smaybee 			mutex_exit(hash_lock);
31772391Smaybee 		} else if (refcount_is_zero(&ab->b_refcnt)) {
31785450Sbrendan 			ab->b_flags |= ARC_FREE_IN_PROGRESS;
3179789Sahrens 			mutex_exit(hash_lock);
31801544Seschrock 			arc_hdr_destroy(ab);
31813403Sbmc 			ARCSTAT_BUMP(arcstat_deleted);
3182789Sahrens 		} else {
31831589Smaybee 			/*
31842391Smaybee 			 * We still have an active reference on this
31852391Smaybee 			 * buffer.  This can happen, e.g., from
31862391Smaybee 			 * dbuf_unoverride().
31871589Smaybee 			 */
31882391Smaybee 			ASSERT(!HDR_IN_HASH_TABLE(ab));
3189789Sahrens 			ab->b_arc_access = 0;
3190789Sahrens 			bzero(&ab->b_dva, sizeof (dva_t));
3191789Sahrens 			ab->b_birth = 0;
3192789Sahrens 			ab->b_cksum0 = 0;
31931544Seschrock 			ab->b_buf->b_efunc = NULL;
31941544Seschrock 			ab->b_buf->b_private = NULL;
3195789Sahrens 			mutex_exit(hash_lock);
3196789Sahrens 		}
3197789Sahrens 	}
3198789Sahrens 
3199789Sahrens 	zio = zio_free(pio, spa, txg, bp, done, private);
3200789Sahrens 
3201789Sahrens 	if (arc_flags & ARC_WAIT)
3202789Sahrens 		return (zio_wait(zio));
3203789Sahrens 
3204789Sahrens 	ASSERT(arc_flags & ARC_NOWAIT);
3205789Sahrens 	zio_nowait(zio);
3206789Sahrens 
3207789Sahrens 	return (0);
3208789Sahrens }
3209789Sahrens 
32106245Smaybee static int
32116245Smaybee arc_memory_throttle(uint64_t reserve, uint64_t txg)
32126245Smaybee {
32136245Smaybee #ifdef _KERNEL
32146245Smaybee 	uint64_t inflight_data = arc_anon->arcs_size;
32156245Smaybee 	uint64_t available_memory = ptob(freemem);
32166245Smaybee 	static uint64_t page_load = 0;
32176245Smaybee 	static uint64_t last_txg = 0;
32186245Smaybee 
32196245Smaybee #if defined(__i386)
32206245Smaybee 	available_memory =
32216245Smaybee 	    MIN(available_memory, vmem_size(heap_arena, VMEM_FREE));
32226245Smaybee #endif
32236245Smaybee 	if (available_memory >= zfs_write_limit_max)
32246245Smaybee 		return (0);
32256245Smaybee 
32266245Smaybee 	if (txg > last_txg) {
32276245Smaybee 		last_txg = txg;
32286245Smaybee 		page_load = 0;
32296245Smaybee 	}
32306245Smaybee 	/*
32316245Smaybee 	 * If we are in pageout, we know that memory is already tight,
32326245Smaybee 	 * the arc is already going to be evicting, so we just want to
32336245Smaybee 	 * continue to let page writes occur as quickly as possible.
32346245Smaybee 	 */
32356245Smaybee 	if (curproc == proc_pageout) {
32366245Smaybee 		if (page_load > MAX(ptob(minfree), available_memory) / 4)
32376245Smaybee 			return (ERESTART);
32386245Smaybee 		/* Note: reserve is inflated, so we deflate */
32396245Smaybee 		page_load += reserve / 8;
32406245Smaybee 		return (0);
32416245Smaybee 	} else if (page_load > 0 && arc_reclaim_needed()) {
32426245Smaybee 		/* memory is low, delay before restarting */
32436245Smaybee 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
32446245Smaybee 		return (EAGAIN);
32456245Smaybee 	}
32466245Smaybee 	page_load = 0;
32476245Smaybee 
32486245Smaybee 	if (arc_size > arc_c_min) {
32496245Smaybee 		uint64_t evictable_memory =
32506245Smaybee 		    arc_mru->arcs_lsize[ARC_BUFC_DATA] +
32516245Smaybee 		    arc_mru->arcs_lsize[ARC_BUFC_METADATA] +
32526245Smaybee 		    arc_mfu->arcs_lsize[ARC_BUFC_DATA] +
32536245Smaybee 		    arc_mfu->arcs_lsize[ARC_BUFC_METADATA];
32546245Smaybee 		available_memory += MIN(evictable_memory, arc_size - arc_c_min);
32556245Smaybee 	}
32566245Smaybee 
32576245Smaybee 	if (inflight_data > available_memory / 4) {
32586245Smaybee 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
32596245Smaybee 		return (ERESTART);
32606245Smaybee 	}
32616245Smaybee #endif
32626245Smaybee 	return (0);
32636245Smaybee }
32646245Smaybee 
3265789Sahrens void
32666245Smaybee arc_tempreserve_clear(uint64_t reserve)
3267789Sahrens {
32686245Smaybee 	atomic_add_64(&arc_tempreserve, -reserve);
3269789Sahrens 	ASSERT((int64_t)arc_tempreserve >= 0);
3270789Sahrens }
3271789Sahrens 
3272789Sahrens int
32736245Smaybee arc_tempreserve_space(uint64_t reserve, uint64_t txg)
3274789Sahrens {
32756245Smaybee 	int error;
32766245Smaybee 
3277789Sahrens #ifdef ZFS_DEBUG
3278789Sahrens 	/*
3279789Sahrens 	 * Once in a while, fail for no reason.  Everything should cope.
3280789Sahrens 	 */
3281789Sahrens 	if (spa_get_random(10000) == 0) {
3282789Sahrens 		dprintf("forcing random failure\n");
3283789Sahrens 		return (ERESTART);
3284789Sahrens 	}
3285789Sahrens #endif
32866245Smaybee 	if (reserve > arc_c/4 && !arc_no_grow)
32876245Smaybee 		arc_c = MIN(arc_c_max, reserve * 4);
32886245Smaybee 	if (reserve > arc_c)
3289982Smaybee 		return (ENOMEM);
3290982Smaybee 
3291789Sahrens 	/*
32926245Smaybee 	 * Writes will, almost always, require additional memory allocations
32936245Smaybee 	 * in order to compress/encrypt/etc the data.  We therefor need to
32946245Smaybee 	 * make sure that there is sufficient available memory for this.
32956245Smaybee 	 */
32966245Smaybee 	if (error = arc_memory_throttle(reserve, txg))
32976245Smaybee 		return (error);
32986245Smaybee 
32996245Smaybee 	/*
3300982Smaybee 	 * Throttle writes when the amount of dirty data in the cache
3301982Smaybee 	 * gets too large.  We try to keep the cache less than half full
3302982Smaybee 	 * of dirty blocks so that our sync times don't grow too large.
3303982Smaybee 	 * Note: if two requests come in concurrently, we might let them
3304982Smaybee 	 * both succeed, when one of them should fail.  Not a huge deal.
3305789Sahrens 	 */
33066245Smaybee 	if (reserve + arc_tempreserve + arc_anon->arcs_size > arc_c / 2 &&
33076245Smaybee 	    arc_anon->arcs_size > arc_c / 4) {
33084309Smaybee 		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
33094309Smaybee 		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
33104309Smaybee 		    arc_tempreserve>>10,
33114309Smaybee 		    arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
33124309Smaybee 		    arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
33136245Smaybee 		    reserve>>10, arc_c>>10);
3314789Sahrens 		return (ERESTART);
3315789Sahrens 	}
33166245Smaybee 	atomic_add_64(&arc_tempreserve, reserve);
3317789Sahrens 	return (0);
3318789Sahrens }
3319789Sahrens 
3320789Sahrens void
3321789Sahrens arc_init(void)
3322789Sahrens {
3323789Sahrens 	mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
3324789Sahrens 	cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
3325789Sahrens 
33262391Smaybee 	/* Convert seconds to clock ticks */
33272638Sperrin 	arc_min_prefetch_lifespan = 1 * hz;
33282391Smaybee 
3329789Sahrens 	/* Start out with 1/8 of all memory */
33303403Sbmc 	arc_c = physmem * PAGESIZE / 8;
3331789Sahrens 
3332789Sahrens #ifdef _KERNEL
3333789Sahrens 	/*
3334789Sahrens 	 * On architectures where the physical memory can be larger
3335789Sahrens 	 * than the addressable space (intel in 32-bit mode), we may
3336789Sahrens 	 * need to limit the cache to 1/8 of VM size.
3337789Sahrens 	 */
33383403Sbmc 	arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
3339789Sahrens #endif
3340789Sahrens 
3341982Smaybee 	/* set min cache to 1/32 of all memory, or 64MB, whichever is more */
33423403Sbmc 	arc_c_min = MAX(arc_c / 4, 64<<20);
3343982Smaybee 	/* set max to 3/4 of all memory, or all but 1GB, whichever is more */
33443403Sbmc 	if (arc_c * 8 >= 1<<30)
33453403Sbmc 		arc_c_max = (arc_c * 8) - (1<<30);
3346789Sahrens 	else
33473403Sbmc 		arc_c_max = arc_c_min;
33483403Sbmc 	arc_c_max = MAX(arc_c * 6, arc_c_max);
33492885Sahrens 
33502885Sahrens 	/*
33512885Sahrens 	 * Allow the tunables to override our calculations if they are
33522885Sahrens 	 * reasonable (ie. over 64MB)
33532885Sahrens 	 */
33542885Sahrens 	if (zfs_arc_max > 64<<20 && zfs_arc_max < physmem * PAGESIZE)
33553403Sbmc 		arc_c_max = zfs_arc_max;
33563403Sbmc 	if (zfs_arc_min > 64<<20 && zfs_arc_min <= arc_c_max)
33573403Sbmc 		arc_c_min = zfs_arc_min;
33582885Sahrens 
33593403Sbmc 	arc_c = arc_c_max;
33603403Sbmc 	arc_p = (arc_c >> 1);
3361789Sahrens 
33624309Smaybee 	/* limit meta-data to 1/4 of the arc capacity */
33634309Smaybee 	arc_meta_limit = arc_c_max / 4;
33644645Sek110237 
33654645Sek110237 	/* Allow the tunable to override if it is reasonable */
33664645Sek110237 	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
33674645Sek110237 		arc_meta_limit = zfs_arc_meta_limit;
33684645Sek110237 
33694309Smaybee 	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
33704309Smaybee 		arc_c_min = arc_meta_limit / 2;
33714309Smaybee 
3372789Sahrens 	/* if kmem_flags are set, lets try to use less memory */
3373789Sahrens 	if (kmem_debugging())
33743403Sbmc 		arc_c = arc_c / 2;
33753403Sbmc 	if (arc_c < arc_c_min)
33763403Sbmc 		arc_c = arc_c_min;
3377789Sahrens 
33783403Sbmc 	arc_anon = &ARC_anon;
33793403Sbmc 	arc_mru = &ARC_mru;
33803403Sbmc 	arc_mru_ghost = &ARC_mru_ghost;
33813403Sbmc 	arc_mfu = &ARC_mfu;
33823403Sbmc 	arc_mfu_ghost = &ARC_mfu_ghost;
33835450Sbrendan 	arc_l2c_only = &ARC_l2c_only;
33843403Sbmc 	arc_size = 0;
3385789Sahrens 
33863403Sbmc 	mutex_init(&arc_anon->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
33873403Sbmc 	mutex_init(&arc_mru->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
33883403Sbmc 	mutex_init(&arc_mru_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
33893403Sbmc 	mutex_init(&arc_mfu->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
33903403Sbmc 	mutex_init(&arc_mfu_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
33915450Sbrendan 	mutex_init(&arc_l2c_only->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
33922688Smaybee 
33934309Smaybee 	list_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
33944309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
33954309Smaybee 	list_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
33964309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
33974309Smaybee 	list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
33984309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
33994309Smaybee 	list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
34004309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
34014309Smaybee 	list_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
34024309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
34034309Smaybee 	list_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
34044309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
34054309Smaybee 	list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
34064309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
34074309Smaybee 	list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
34084309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
34095450Sbrendan 	list_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
34105450Sbrendan 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
34115450Sbrendan 	list_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
34125450Sbrendan 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3413789Sahrens 
3414789Sahrens 	buf_init();
3415789Sahrens 
3416789Sahrens 	arc_thread_exit = 0;
34171544Seschrock 	arc_eviction_list = NULL;
34181544Seschrock 	mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
34192887Smaybee 	bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
3420789Sahrens 
34213403Sbmc 	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
34223403Sbmc 	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
34233403Sbmc 
34243403Sbmc 	if (arc_ksp != NULL) {
34253403Sbmc 		arc_ksp->ks_data = &arc_stats;
34263403Sbmc 		kstat_install(arc_ksp);
34273403Sbmc 	}
34283403Sbmc 
3429789Sahrens 	(void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
3430789Sahrens 	    TS_RUN, minclsyspri);
34313158Smaybee 
34323158Smaybee 	arc_dead = FALSE;
34336987Sbrendan 	arc_warm = B_FALSE;
34346245Smaybee 
34356245Smaybee 	if (zfs_write_limit_max == 0)
34366245Smaybee 		zfs_write_limit_max = physmem * PAGESIZE >>
34376245Smaybee 		    zfs_write_limit_shift;
34386245Smaybee 	else
34396245Smaybee 		zfs_write_limit_shift = 0;
3440789Sahrens }
3441789Sahrens 
3442789Sahrens void
3443789Sahrens arc_fini(void)
3444789Sahrens {
3445789Sahrens 	mutex_enter(&arc_reclaim_thr_lock);
3446789Sahrens 	arc_thread_exit = 1;
3447789Sahrens 	while (arc_thread_exit != 0)
3448789Sahrens 		cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
3449789Sahrens 	mutex_exit(&arc_reclaim_thr_lock);
3450789Sahrens 
34515642Smaybee 	arc_flush(NULL);
3452789Sahrens 
3453789Sahrens 	arc_dead = TRUE;
3454789Sahrens 
34553403Sbmc 	if (arc_ksp != NULL) {
34563403Sbmc 		kstat_delete(arc_ksp);
34573403Sbmc 		arc_ksp = NULL;
34583403Sbmc 	}
34593403Sbmc 
34601544Seschrock 	mutex_destroy(&arc_eviction_mtx);
3461789Sahrens 	mutex_destroy(&arc_reclaim_thr_lock);
3462789Sahrens 	cv_destroy(&arc_reclaim_thr_cv);
3463789Sahrens 
34644309Smaybee 	list_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
34654309Smaybee 	list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
34664309Smaybee 	list_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
34674309Smaybee 	list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
34684309Smaybee 	list_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
34694309Smaybee 	list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
34704309Smaybee 	list_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
34714309Smaybee 	list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
3472789Sahrens 
34733403Sbmc 	mutex_destroy(&arc_anon->arcs_mtx);
34743403Sbmc 	mutex_destroy(&arc_mru->arcs_mtx);
34753403Sbmc 	mutex_destroy(&arc_mru_ghost->arcs_mtx);
34763403Sbmc 	mutex_destroy(&arc_mfu->arcs_mtx);
34773403Sbmc 	mutex_destroy(&arc_mfu_ghost->arcs_mtx);
34782856Snd150628 
3479789Sahrens 	buf_fini();
3480789Sahrens }
34815450Sbrendan 
34825450Sbrendan /*
34835450Sbrendan  * Level 2 ARC
34845450Sbrendan  *
34855450Sbrendan  * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
34865450Sbrendan  * It uses dedicated storage devices to hold cached data, which are populated
34875450Sbrendan  * using large infrequent writes.  The main role of this cache is to boost
34885450Sbrendan  * the performance of random read workloads.  The intended L2ARC devices
34895450Sbrendan  * include short-stroked disks, solid state disks, and other media with
34905450Sbrendan  * substantially faster read latency than disk.
34915450Sbrendan  *
34925450Sbrendan  *                 +-----------------------+
34935450Sbrendan  *                 |         ARC           |
34945450Sbrendan  *                 +-----------------------+
34955450Sbrendan  *                    |         ^     ^
34965450Sbrendan  *                    |         |     |
34975450Sbrendan  *      l2arc_feed_thread()    arc_read()
34985450Sbrendan  *                    |         |     |
34995450Sbrendan  *                    |  l2arc read   |
35005450Sbrendan  *                    V         |     |
35015450Sbrendan  *               +---------------+    |
35025450Sbrendan  *               |     L2ARC     |    |
35035450Sbrendan  *               +---------------+    |
35045450Sbrendan  *                   |    ^           |
35055450Sbrendan  *          l2arc_write() |           |
35065450Sbrendan  *                   |    |           |
35075450Sbrendan  *                   V    |           |
35085450Sbrendan  *                 +-------+      +-------+
35095450Sbrendan  *                 | vdev  |      | vdev  |
35105450Sbrendan  *                 | cache |      | cache |
35115450Sbrendan  *                 +-------+      +-------+
35125450Sbrendan  *                 +=========+     .-----.
35135450Sbrendan  *                 :  L2ARC  :    |-_____-|
35145450Sbrendan  *                 : devices :    | Disks |
35155450Sbrendan  *                 +=========+    `-_____-'
35165450Sbrendan  *
35175450Sbrendan  * Read requests are satisfied from the following sources, in order:
35185450Sbrendan  *
35195450Sbrendan  *	1) ARC
35205450Sbrendan  *	2) vdev cache of L2ARC devices
35215450Sbrendan  *	3) L2ARC devices
35225450Sbrendan  *	4) vdev cache of disks
35235450Sbrendan  *	5) disks
35245450Sbrendan  *
35255450Sbrendan  * Some L2ARC device types exhibit extremely slow write performance.
35265450Sbrendan  * To accommodate for this there are some significant differences between
35275450Sbrendan  * the L2ARC and traditional cache design:
35285450Sbrendan  *
35295450Sbrendan  * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
35305450Sbrendan  * the ARC behave as usual, freeing buffers and placing headers on ghost
35315450Sbrendan  * lists.  The ARC does not send buffers to the L2ARC during eviction as
35325450Sbrendan  * this would add inflated write latencies for all ARC memory pressure.
35335450Sbrendan  *
35345450Sbrendan  * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
35355450Sbrendan  * It does this by periodically scanning buffers from the eviction-end of
35365450Sbrendan  * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
35375450Sbrendan  * not already there.  It scans until a headroom of buffers is satisfied,
35385450Sbrendan  * which itself is a buffer for ARC eviction.  The thread that does this is
35395450Sbrendan  * l2arc_feed_thread(), illustrated below; example sizes are included to
35405450Sbrendan  * provide a better sense of ratio than this diagram:
35415450Sbrendan  *
35425450Sbrendan  *	       head -->                        tail
35435450Sbrendan  *	        +---------------------+----------+
35445450Sbrendan  *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
35455450Sbrendan  *	        +---------------------+----------+   |   o L2ARC eligible
35465450Sbrendan  *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
35475450Sbrendan  *	        +---------------------+----------+   |
35485450Sbrendan  *	             15.9 Gbytes      ^ 32 Mbytes    |
35495450Sbrendan  *	                           headroom          |
35505450Sbrendan  *	                                      l2arc_feed_thread()
35515450Sbrendan  *	                                             |
35525450Sbrendan  *	                 l2arc write hand <--[oooo]--'
35535450Sbrendan  *	                         |           8 Mbyte
35545450Sbrendan  *	                         |          write max
35555450Sbrendan  *	                         V
35565450Sbrendan  *		  +==============================+
35575450Sbrendan  *	L2ARC dev |####|#|###|###|    |####| ... |
35585450Sbrendan  *	          +==============================+
35595450Sbrendan  *	                     32 Gbytes
35605450Sbrendan  *
35615450Sbrendan  * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
35625450Sbrendan  * evicted, then the L2ARC has cached a buffer much sooner than it probably
35635450Sbrendan  * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
35645450Sbrendan  * safe to say that this is an uncommon case, since buffers at the end of
35655450Sbrendan  * the ARC lists have moved there due to inactivity.
35665450Sbrendan  *
35675450Sbrendan  * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
35685450Sbrendan  * then the L2ARC simply misses copying some buffers.  This serves as a
35695450Sbrendan  * pressure valve to prevent heavy read workloads from both stalling the ARC
35705450Sbrendan  * with waits and clogging the L2ARC with writes.  This also helps prevent
35715450Sbrendan  * the potential for the L2ARC to churn if it attempts to cache content too
35725450Sbrendan  * quickly, such as during backups of the entire pool.
35735450Sbrendan  *
35746987Sbrendan  * 5. After system boot and before the ARC has filled main memory, there are
35756987Sbrendan  * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
35766987Sbrendan  * lists can remain mostly static.  Instead of searching from tail of these
35776987Sbrendan  * lists as pictured, the l2arc_feed_thread() will search from the list heads
35786987Sbrendan  * for eligible buffers, greatly increasing its chance of finding them.
35796987Sbrendan  *
35806987Sbrendan  * The L2ARC device write speed is also boosted during this time so that
35816987Sbrendan  * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
35826987Sbrendan  * there are no L2ARC reads, and no fear of degrading read performance
35836987Sbrendan  * through increased writes.
35846987Sbrendan  *
35856987Sbrendan  * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
35865450Sbrendan  * the vdev queue can aggregate them into larger and fewer writes.  Each
35875450Sbrendan  * device is written to in a rotor fashion, sweeping writes through
35885450Sbrendan  * available space then repeating.
35895450Sbrendan  *
35906987Sbrendan  * 7. The L2ARC does not store dirty content.  It never needs to flush
35915450Sbrendan  * write buffers back to disk based storage.
35925450Sbrendan  *
35936987Sbrendan  * 8. If an ARC buffer is written (and dirtied) which also exists in the
35945450Sbrendan  * L2ARC, the now stale L2ARC buffer is immediately dropped.
35955450Sbrendan  *
35965450Sbrendan  * The performance of the L2ARC can be tweaked by a number of tunables, which
35975450Sbrendan  * may be necessary for different workloads:
35985450Sbrendan  *
35995450Sbrendan  *	l2arc_write_max		max write bytes per interval
36006987Sbrendan  *	l2arc_write_boost	extra write bytes during device warmup
36015450Sbrendan  *	l2arc_noprefetch	skip caching prefetched buffers
36025450Sbrendan  *	l2arc_headroom		number of max device writes to precache
36035450Sbrendan  *	l2arc_feed_secs		seconds between L2ARC writing
36045450Sbrendan  *
36055450Sbrendan  * Tunables may be removed or added as future performance improvements are
36065450Sbrendan  * integrated, and also may become zpool properties.
36075450Sbrendan  */
36085450Sbrendan 
36095450Sbrendan static void
36105450Sbrendan l2arc_hdr_stat_add(void)
36115450Sbrendan {
36126018Sbrendan 	ARCSTAT_INCR(arcstat_l2_hdr_size, HDR_SIZE + L2HDR_SIZE);
36136018Sbrendan 	ARCSTAT_INCR(arcstat_hdr_size, -HDR_SIZE);
36145450Sbrendan }
36155450Sbrendan 
36165450Sbrendan static void
36175450Sbrendan l2arc_hdr_stat_remove(void)
36185450Sbrendan {
36196018Sbrendan 	ARCSTAT_INCR(arcstat_l2_hdr_size, -(HDR_SIZE + L2HDR_SIZE));
36206018Sbrendan 	ARCSTAT_INCR(arcstat_hdr_size, HDR_SIZE);
36215450Sbrendan }
36225450Sbrendan 
36235450Sbrendan /*
36245450Sbrendan  * Cycle through L2ARC devices.  This is how L2ARC load balances.
36256987Sbrendan  * If a device is returned, this also returns holding the spa config lock.
36265450Sbrendan  */
36275450Sbrendan static l2arc_dev_t *
36285450Sbrendan l2arc_dev_get_next(void)
36295450Sbrendan {
36306987Sbrendan 	l2arc_dev_t *first, *next = NULL;
36316987Sbrendan 
36326987Sbrendan 	/*
36336987Sbrendan 	 * Lock out the removal of spas (spa_namespace_lock), then removal
36346987Sbrendan 	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
36356987Sbrendan 	 * both locks will be dropped and a spa config lock held instead.
36366987Sbrendan 	 */
36376987Sbrendan 	mutex_enter(&spa_namespace_lock);
36386987Sbrendan 	mutex_enter(&l2arc_dev_mtx);
36396643Seschrock 
36406643Seschrock 	/* if there are no vdevs, there is nothing to do */
36416643Seschrock 	if (l2arc_ndev == 0)
36426987Sbrendan 		goto out;
36436643Seschrock 
36446643Seschrock 	first = NULL;
36456643Seschrock 	next = l2arc_dev_last;
36466643Seschrock 	do {
36476643Seschrock 		/* loop around the list looking for a non-faulted vdev */
36486643Seschrock 		if (next == NULL) {
36495450Sbrendan 			next = list_head(l2arc_dev_list);
36506643Seschrock 		} else {
36516643Seschrock 			next = list_next(l2arc_dev_list, next);
36526643Seschrock 			if (next == NULL)
36536643Seschrock 				next = list_head(l2arc_dev_list);
36546643Seschrock 		}
36556643Seschrock 
36566643Seschrock 		/* if we have come back to the start, bail out */
36576643Seschrock 		if (first == NULL)
36586643Seschrock 			first = next;
36596643Seschrock 		else if (next == first)
36606643Seschrock 			break;
36616643Seschrock 
36626643Seschrock 	} while (vdev_is_dead(next->l2ad_vdev));
36636643Seschrock 
36646643Seschrock 	/* if we were unable to find any usable vdevs, return NULL */
36656643Seschrock 	if (vdev_is_dead(next->l2ad_vdev))
36666987Sbrendan 		next = NULL;
36675450Sbrendan 
36685450Sbrendan 	l2arc_dev_last = next;
36695450Sbrendan 
36706987Sbrendan out:
36716987Sbrendan 	mutex_exit(&l2arc_dev_mtx);
36726987Sbrendan 
36736987Sbrendan 	/*
36746987Sbrendan 	 * Grab the config lock to prevent the 'next' device from being
36756987Sbrendan 	 * removed while we are writing to it.
36766987Sbrendan 	 */
36776987Sbrendan 	if (next != NULL)
36786987Sbrendan 		spa_config_enter(next->l2ad_spa, RW_READER, next);
36796987Sbrendan 	mutex_exit(&spa_namespace_lock);
36806987Sbrendan 
36815450Sbrendan 	return (next);
36825450Sbrendan }
36835450Sbrendan 
36845450Sbrendan /*
36856987Sbrendan  * Free buffers that were tagged for destruction.
36866987Sbrendan  */
36876987Sbrendan static void
36886987Sbrendan l2arc_do_free_on_write()
36896987Sbrendan {
36906987Sbrendan 	list_t *buflist;
36916987Sbrendan 	l2arc_data_free_t *df, *df_prev;
36926987Sbrendan 
36936987Sbrendan 	mutex_enter(&l2arc_free_on_write_mtx);
36946987Sbrendan 	buflist = l2arc_free_on_write;
36956987Sbrendan 
36966987Sbrendan 	for (df = list_tail(buflist); df; df = df_prev) {
36976987Sbrendan 		df_prev = list_prev(buflist, df);
36986987Sbrendan 		ASSERT(df->l2df_data != NULL);
36996987Sbrendan 		ASSERT(df->l2df_func != NULL);
37006987Sbrendan 		df->l2df_func(df->l2df_data, df->l2df_size);
37016987Sbrendan 		list_remove(buflist, df);
37026987Sbrendan 		kmem_free(df, sizeof (l2arc_data_free_t));
37036987Sbrendan 	}
37046987Sbrendan 
37056987Sbrendan 	mutex_exit(&l2arc_free_on_write_mtx);
37066987Sbrendan }
37076987Sbrendan 
37086987Sbrendan /*
37095450Sbrendan  * A write to a cache device has completed.  Update all headers to allow
37105450Sbrendan  * reads from these buffers to begin.
37115450Sbrendan  */
37125450Sbrendan static void
37135450Sbrendan l2arc_write_done(zio_t *zio)
37145450Sbrendan {
37155450Sbrendan 	l2arc_write_callback_t *cb;
37165450Sbrendan 	l2arc_dev_t *dev;
37175450Sbrendan 	list_t *buflist;
37185450Sbrendan 	arc_buf_hdr_t *head, *ab, *ab_prev;
37196987Sbrendan 	l2arc_buf_hdr_t *abl2;
37205450Sbrendan 	kmutex_t *hash_lock;
37215450Sbrendan 
37225450Sbrendan 	cb = zio->io_private;
37235450Sbrendan 	ASSERT(cb != NULL);
37245450Sbrendan 	dev = cb->l2wcb_dev;
37255450Sbrendan 	ASSERT(dev != NULL);
37265450Sbrendan 	head = cb->l2wcb_head;
37275450Sbrendan 	ASSERT(head != NULL);
37285450Sbrendan 	buflist = dev->l2ad_buflist;
37295450Sbrendan 	ASSERT(buflist != NULL);
37305450Sbrendan 	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
37315450Sbrendan 	    l2arc_write_callback_t *, cb);
37325450Sbrendan 
37335450Sbrendan 	if (zio->io_error != 0)
37345450Sbrendan 		ARCSTAT_BUMP(arcstat_l2_writes_error);
37355450Sbrendan 
37365450Sbrendan 	mutex_enter(&l2arc_buflist_mtx);
37375450Sbrendan 
37385450Sbrendan 	/*
37395450Sbrendan 	 * All writes completed, or an error was hit.
37405450Sbrendan 	 */
37415450Sbrendan 	for (ab = list_prev(buflist, head); ab; ab = ab_prev) {
37425450Sbrendan 		ab_prev = list_prev(buflist, ab);
37435450Sbrendan 
37445450Sbrendan 		hash_lock = HDR_LOCK(ab);
37455450Sbrendan 		if (!mutex_tryenter(hash_lock)) {
37465450Sbrendan 			/*
37475450Sbrendan 			 * This buffer misses out.  It may be in a stage
37485450Sbrendan 			 * of eviction.  Its ARC_L2_WRITING flag will be
37495450Sbrendan 			 * left set, denying reads to this buffer.
37505450Sbrendan 			 */
37515450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_writes_hdr_miss);
37525450Sbrendan 			continue;
37535450Sbrendan 		}
37545450Sbrendan 
37555450Sbrendan 		if (zio->io_error != 0) {
37565450Sbrendan 			/*
37576987Sbrendan 			 * Error - drop L2ARC entry.
37585450Sbrendan 			 */
37596987Sbrendan 			list_remove(buflist, ab);
37606987Sbrendan 			abl2 = ab->b_l2hdr;
37615450Sbrendan 			ab->b_l2hdr = NULL;
37626987Sbrendan 			kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
37636987Sbrendan 			ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
37645450Sbrendan 		}
37655450Sbrendan 
37665450Sbrendan 		/*
37675450Sbrendan 		 * Allow ARC to begin reads to this L2ARC entry.
37685450Sbrendan 		 */
37695450Sbrendan 		ab->b_flags &= ~ARC_L2_WRITING;
37705450Sbrendan 
37715450Sbrendan 		mutex_exit(hash_lock);
37725450Sbrendan 	}
37735450Sbrendan 
37745450Sbrendan 	atomic_inc_64(&l2arc_writes_done);
37755450Sbrendan 	list_remove(buflist, head);
37765450Sbrendan 	kmem_cache_free(hdr_cache, head);
37775450Sbrendan 	mutex_exit(&l2arc_buflist_mtx);
37785450Sbrendan 
37796987Sbrendan 	l2arc_do_free_on_write();
37805450Sbrendan 
37815450Sbrendan 	kmem_free(cb, sizeof (l2arc_write_callback_t));
37825450Sbrendan }
37835450Sbrendan 
37845450Sbrendan /*
37855450Sbrendan  * A read to a cache device completed.  Validate buffer contents before
37865450Sbrendan  * handing over to the regular ARC routines.
37875450Sbrendan  */
37885450Sbrendan static void
37895450Sbrendan l2arc_read_done(zio_t *zio)
37905450Sbrendan {
37915450Sbrendan 	l2arc_read_callback_t *cb;
37925450Sbrendan 	arc_buf_hdr_t *hdr;
37935450Sbrendan 	arc_buf_t *buf;
37945450Sbrendan 	zio_t *rzio;
37955450Sbrendan 	kmutex_t *hash_lock;
37966987Sbrendan 	int equal;
37975450Sbrendan 
37985450Sbrendan 	cb = zio->io_private;
37995450Sbrendan 	ASSERT(cb != NULL);
38005450Sbrendan 	buf = cb->l2rcb_buf;
38015450Sbrendan 	ASSERT(buf != NULL);
38025450Sbrendan 	hdr = buf->b_hdr;
38035450Sbrendan 	ASSERT(hdr != NULL);
38045450Sbrendan 
38055450Sbrendan 	hash_lock = HDR_LOCK(hdr);
38065450Sbrendan 	mutex_enter(hash_lock);
38075450Sbrendan 
38085450Sbrendan 	/*
38095450Sbrendan 	 * Check this survived the L2ARC journey.
38105450Sbrendan 	 */
38115450Sbrendan 	equal = arc_cksum_equal(buf);
38125450Sbrendan 	if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
38135450Sbrendan 		mutex_exit(hash_lock);
38145450Sbrendan 		zio->io_private = buf;
38155450Sbrendan 		arc_read_done(zio);
38165450Sbrendan 	} else {
38175450Sbrendan 		mutex_exit(hash_lock);
38185450Sbrendan 		/*
38195450Sbrendan 		 * Buffer didn't survive caching.  Increment stats and
38205450Sbrendan 		 * reissue to the original storage device.
38215450Sbrendan 		 */
38226987Sbrendan 		if (zio->io_error != 0) {
38235450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_io_error);
38246987Sbrendan 		} else {
38256987Sbrendan 			zio->io_error = EIO;
38266987Sbrendan 		}
38275450Sbrendan 		if (!equal)
38285450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
38295450Sbrendan 
38306987Sbrendan 		if (zio->io_waiter == NULL) {
38316987Sbrendan 			/*
38326987Sbrendan 			 * Let the resent I/O call arc_read_done() instead.
38336987Sbrendan 			 */
38346987Sbrendan 			zio->io_done = NULL;
38356987Sbrendan 			zio->io_flags &= ~ZIO_FLAG_DONT_CACHE;
38366987Sbrendan 
38376987Sbrendan 			rzio = zio_read(NULL, cb->l2rcb_spa, &cb->l2rcb_bp,
38386987Sbrendan 			    buf->b_data, zio->io_size, arc_read_done, buf,
38396987Sbrendan 			    zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb);
38406987Sbrendan 
38416987Sbrendan 			(void) zio_nowait(rzio);
38426987Sbrendan 		}
38435450Sbrendan 	}
38445450Sbrendan 
38455450Sbrendan 	kmem_free(cb, sizeof (l2arc_read_callback_t));
38465450Sbrendan }
38475450Sbrendan 
38485450Sbrendan /*
38495450Sbrendan  * This is the list priority from which the L2ARC will search for pages to
38505450Sbrendan  * cache.  This is used within loops (0..3) to cycle through lists in the
38515450Sbrendan  * desired order.  This order can have a significant effect on cache
38525450Sbrendan  * performance.
38535450Sbrendan  *
38545450Sbrendan  * Currently the metadata lists are hit first, MFU then MRU, followed by
38555450Sbrendan  * the data lists.  This function returns a locked list, and also returns
38565450Sbrendan  * the lock pointer.
38575450Sbrendan  */
38585450Sbrendan static list_t *
38595450Sbrendan l2arc_list_locked(int list_num, kmutex_t **lock)
38605450Sbrendan {
38615450Sbrendan 	list_t *list;
38625450Sbrendan 
38635450Sbrendan 	ASSERT(list_num >= 0 && list_num <= 3);
38645450Sbrendan 
38655450Sbrendan 	switch (list_num) {
38665450Sbrendan 	case 0:
38675450Sbrendan 		list = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
38685450Sbrendan 		*lock = &arc_mfu->arcs_mtx;
38695450Sbrendan 		break;
38705450Sbrendan 	case 1:
38715450Sbrendan 		list = &arc_mru->arcs_list[ARC_BUFC_METADATA];
38725450Sbrendan 		*lock = &arc_mru->arcs_mtx;
38735450Sbrendan 		break;
38745450Sbrendan 	case 2:
38755450Sbrendan 		list = &arc_mfu->arcs_list[ARC_BUFC_DATA];
38765450Sbrendan 		*lock = &arc_mfu->arcs_mtx;
38775450Sbrendan 		break;
38785450Sbrendan 	case 3:
38795450Sbrendan 		list = &arc_mru->arcs_list[ARC_BUFC_DATA];
38805450Sbrendan 		*lock = &arc_mru->arcs_mtx;
38815450Sbrendan 		break;
38825450Sbrendan 	}
38835450Sbrendan 
38845450Sbrendan 	ASSERT(!(MUTEX_HELD(*lock)));
38855450Sbrendan 	mutex_enter(*lock);
38865450Sbrendan 	return (list);
38875450Sbrendan }
38885450Sbrendan 
38895450Sbrendan /*
38905450Sbrendan  * Evict buffers from the device write hand to the distance specified in
38915450Sbrendan  * bytes.  This distance may span populated buffers, it may span nothing.
38925450Sbrendan  * This is clearing a region on the L2ARC device ready for writing.
38935450Sbrendan  * If the 'all' boolean is set, every buffer is evicted.
38945450Sbrendan  */
38955450Sbrendan static void
38965450Sbrendan l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
38975450Sbrendan {
38985450Sbrendan 	list_t *buflist;
38995450Sbrendan 	l2arc_buf_hdr_t *abl2;
39005450Sbrendan 	arc_buf_hdr_t *ab, *ab_prev;
39015450Sbrendan 	kmutex_t *hash_lock;
39025450Sbrendan 	uint64_t taddr;
39035450Sbrendan 
39045450Sbrendan 	buflist = dev->l2ad_buflist;
39055450Sbrendan 
39065450Sbrendan 	if (buflist == NULL)
39075450Sbrendan 		return;
39085450Sbrendan 
39095450Sbrendan 	if (!all && dev->l2ad_first) {
39105450Sbrendan 		/*
39115450Sbrendan 		 * This is the first sweep through the device.  There is
39125450Sbrendan 		 * nothing to evict.
39135450Sbrendan 		 */
39145450Sbrendan 		return;
39155450Sbrendan 	}
39165450Sbrendan 
39176987Sbrendan 	if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
39185450Sbrendan 		/*
39195450Sbrendan 		 * When nearing the end of the device, evict to the end
39205450Sbrendan 		 * before the device write hand jumps to the start.
39215450Sbrendan 		 */
39225450Sbrendan 		taddr = dev->l2ad_end;
39235450Sbrendan 	} else {
39245450Sbrendan 		taddr = dev->l2ad_hand + distance;
39255450Sbrendan 	}
39265450Sbrendan 	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
39275450Sbrendan 	    uint64_t, taddr, boolean_t, all);
39285450Sbrendan 
39295450Sbrendan top:
39305450Sbrendan 	mutex_enter(&l2arc_buflist_mtx);
39315450Sbrendan 	for (ab = list_tail(buflist); ab; ab = ab_prev) {
39325450Sbrendan 		ab_prev = list_prev(buflist, ab);
39335450Sbrendan 
39345450Sbrendan 		hash_lock = HDR_LOCK(ab);
39355450Sbrendan 		if (!mutex_tryenter(hash_lock)) {
39365450Sbrendan 			/*
39375450Sbrendan 			 * Missed the hash lock.  Retry.
39385450Sbrendan 			 */
39395450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
39405450Sbrendan 			mutex_exit(&l2arc_buflist_mtx);
39415450Sbrendan 			mutex_enter(hash_lock);
39425450Sbrendan 			mutex_exit(hash_lock);
39435450Sbrendan 			goto top;
39445450Sbrendan 		}
39455450Sbrendan 
39465450Sbrendan 		if (HDR_L2_WRITE_HEAD(ab)) {
39475450Sbrendan 			/*
39485450Sbrendan 			 * We hit a write head node.  Leave it for
39495450Sbrendan 			 * l2arc_write_done().
39505450Sbrendan 			 */
39515450Sbrendan 			list_remove(buflist, ab);
39525450Sbrendan 			mutex_exit(hash_lock);
39535450Sbrendan 			continue;
39545450Sbrendan 		}
39555450Sbrendan 
39565450Sbrendan 		if (!all && ab->b_l2hdr != NULL &&
39575450Sbrendan 		    (ab->b_l2hdr->b_daddr > taddr ||
39585450Sbrendan 		    ab->b_l2hdr->b_daddr < dev->l2ad_hand)) {
39595450Sbrendan 			/*
39605450Sbrendan 			 * We've evicted to the target address,
39615450Sbrendan 			 * or the end of the device.
39625450Sbrendan 			 */
39635450Sbrendan 			mutex_exit(hash_lock);
39645450Sbrendan 			break;
39655450Sbrendan 		}
39665450Sbrendan 
39675450Sbrendan 		if (HDR_FREE_IN_PROGRESS(ab)) {
39685450Sbrendan 			/*
39695450Sbrendan 			 * Already on the path to destruction.
39705450Sbrendan 			 */
39715450Sbrendan 			mutex_exit(hash_lock);
39725450Sbrendan 			continue;
39735450Sbrendan 		}
39745450Sbrendan 
39755450Sbrendan 		if (ab->b_state == arc_l2c_only) {
39765450Sbrendan 			ASSERT(!HDR_L2_READING(ab));
39775450Sbrendan 			/*
39785450Sbrendan 			 * This doesn't exist in the ARC.  Destroy.
39795450Sbrendan 			 * arc_hdr_destroy() will call list_remove()
39805450Sbrendan 			 * and decrement arcstat_l2_size.
39815450Sbrendan 			 */
39825450Sbrendan 			arc_change_state(arc_anon, ab, hash_lock);
39835450Sbrendan 			arc_hdr_destroy(ab);
39845450Sbrendan 		} else {
39855450Sbrendan 			/*
39866987Sbrendan 			 * Invalidate issued or about to be issued
39876987Sbrendan 			 * reads, since we may be about to write
39886987Sbrendan 			 * over this location.
39896987Sbrendan 			 */
39906987Sbrendan 			if (HDR_L2_READING(ab)) {
39916987Sbrendan 				ARCSTAT_BUMP(arcstat_l2_evict_reading);
39926987Sbrendan 				ab->b_flags |= ARC_L2_EVICTED;
39936987Sbrendan 			}
39946987Sbrendan 
39956987Sbrendan 			/*
39965450Sbrendan 			 * Tell ARC this no longer exists in L2ARC.
39975450Sbrendan 			 */
39985450Sbrendan 			if (ab->b_l2hdr != NULL) {
39995450Sbrendan 				abl2 = ab->b_l2hdr;
40005450Sbrendan 				ab->b_l2hdr = NULL;
40015450Sbrendan 				kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
40025450Sbrendan 				ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
40035450Sbrendan 			}
40045450Sbrendan 			list_remove(buflist, ab);
40055450Sbrendan 
40065450Sbrendan 			/*
40075450Sbrendan 			 * This may have been leftover after a
40085450Sbrendan 			 * failed write.
40095450Sbrendan 			 */
40105450Sbrendan 			ab->b_flags &= ~ARC_L2_WRITING;
40115450Sbrendan 		}
40125450Sbrendan 		mutex_exit(hash_lock);
40135450Sbrendan 	}
40145450Sbrendan 	mutex_exit(&l2arc_buflist_mtx);
40155450Sbrendan 
40165450Sbrendan 	spa_l2cache_space_update(dev->l2ad_vdev, 0, -(taddr - dev->l2ad_evict));
40175450Sbrendan 	dev->l2ad_evict = taddr;
40185450Sbrendan }
40195450Sbrendan 
40205450Sbrendan /*
40215450Sbrendan  * Find and write ARC buffers to the L2ARC device.
40225450Sbrendan  *
40235450Sbrendan  * An ARC_L2_WRITING flag is set so that the L2ARC buffers are not valid
40245450Sbrendan  * for reading until they have completed writing.
40255450Sbrendan  */
40265450Sbrendan static void
40276987Sbrendan l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
40285450Sbrendan {
40295450Sbrendan 	arc_buf_hdr_t *ab, *ab_prev, *head;
40305450Sbrendan 	l2arc_buf_hdr_t *hdrl2;
40315450Sbrendan 	list_t *list;
40326987Sbrendan 	uint64_t passed_sz, write_sz, buf_sz, headroom;
40335450Sbrendan 	void *buf_data;
40345450Sbrendan 	kmutex_t *hash_lock, *list_lock;
40355450Sbrendan 	boolean_t have_lock, full;
40365450Sbrendan 	l2arc_write_callback_t *cb;
40375450Sbrendan 	zio_t *pio, *wzio;
40385450Sbrendan 
40395450Sbrendan 	ASSERT(dev->l2ad_vdev != NULL);
40405450Sbrendan 
40415450Sbrendan 	pio = NULL;
40425450Sbrendan 	write_sz = 0;
40435450Sbrendan 	full = B_FALSE;
40446245Smaybee 	head = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
40455450Sbrendan 	head->b_flags |= ARC_L2_WRITE_HEAD;
40465450Sbrendan 
40475450Sbrendan 	/*
40485450Sbrendan 	 * Copy buffers for L2ARC writing.
40495450Sbrendan 	 */
40505450Sbrendan 	mutex_enter(&l2arc_buflist_mtx);
40515450Sbrendan 	for (int try = 0; try <= 3; try++) {
40525450Sbrendan 		list = l2arc_list_locked(try, &list_lock);
40535450Sbrendan 		passed_sz = 0;
40545450Sbrendan 
40556987Sbrendan 		/*
40566987Sbrendan 		 * L2ARC fast warmup.
40576987Sbrendan 		 *
40586987Sbrendan 		 * Until the ARC is warm and starts to evict, read from the
40596987Sbrendan 		 * head of the ARC lists rather than the tail.
40606987Sbrendan 		 */
40616987Sbrendan 		headroom = target_sz * l2arc_headroom;
40626987Sbrendan 		if (arc_warm == B_FALSE)
40636987Sbrendan 			ab = list_head(list);
40646987Sbrendan 		else
40656987Sbrendan 			ab = list_tail(list);
40666987Sbrendan 
40676987Sbrendan 		for (; ab; ab = ab_prev) {
40686987Sbrendan 			if (arc_warm == B_FALSE)
40696987Sbrendan 				ab_prev = list_next(list, ab);
40706987Sbrendan 			else
40716987Sbrendan 				ab_prev = list_prev(list, ab);
40725450Sbrendan 
40735450Sbrendan 			hash_lock = HDR_LOCK(ab);
40745450Sbrendan 			have_lock = MUTEX_HELD(hash_lock);
40755450Sbrendan 			if (!have_lock && !mutex_tryenter(hash_lock)) {
40765450Sbrendan 				/*
40775450Sbrendan 				 * Skip this buffer rather than waiting.
40785450Sbrendan 				 */
40795450Sbrendan 				continue;
40805450Sbrendan 			}
40815450Sbrendan 
40825450Sbrendan 			passed_sz += ab->b_size;
40835450Sbrendan 			if (passed_sz > headroom) {
40845450Sbrendan 				/*
40855450Sbrendan 				 * Searched too far.
40865450Sbrendan 				 */
40875450Sbrendan 				mutex_exit(hash_lock);
40885450Sbrendan 				break;
40895450Sbrendan 			}
40905450Sbrendan 
40915450Sbrendan 			if (ab->b_spa != spa) {
40925450Sbrendan 				mutex_exit(hash_lock);
40935450Sbrendan 				continue;
40945450Sbrendan 			}
40955450Sbrendan 
40965450Sbrendan 			if (ab->b_l2hdr != NULL) {
40975450Sbrendan 				/*
40985450Sbrendan 				 * Already in L2ARC.
40995450Sbrendan 				 */
41005450Sbrendan 				mutex_exit(hash_lock);
41015450Sbrendan 				continue;
41025450Sbrendan 			}
41035450Sbrendan 
41045450Sbrendan 			if (HDR_IO_IN_PROGRESS(ab) || HDR_DONT_L2CACHE(ab)) {
41055450Sbrendan 				mutex_exit(hash_lock);
41065450Sbrendan 				continue;
41075450Sbrendan 			}
41085450Sbrendan 
41095450Sbrendan 			if ((write_sz + ab->b_size) > target_sz) {
41105450Sbrendan 				full = B_TRUE;
41115450Sbrendan 				mutex_exit(hash_lock);
41125450Sbrendan 				break;
41135450Sbrendan 			}
41145450Sbrendan 
41155450Sbrendan 			if (ab->b_buf == NULL) {
41165450Sbrendan 				DTRACE_PROBE1(l2arc__buf__null, void *, ab);
41175450Sbrendan 				mutex_exit(hash_lock);
41185450Sbrendan 				continue;
41195450Sbrendan 			}
41205450Sbrendan 
41215450Sbrendan 			if (pio == NULL) {
41225450Sbrendan 				/*
41235450Sbrendan 				 * Insert a dummy header on the buflist so
41245450Sbrendan 				 * l2arc_write_done() can find where the
41255450Sbrendan 				 * write buffers begin without searching.
41265450Sbrendan 				 */
41275450Sbrendan 				list_insert_head(dev->l2ad_buflist, head);
41285450Sbrendan 
41295450Sbrendan 				cb = kmem_alloc(
41305450Sbrendan 				    sizeof (l2arc_write_callback_t), KM_SLEEP);
41315450Sbrendan 				cb->l2wcb_dev = dev;
41325450Sbrendan 				cb->l2wcb_head = head;
41335450Sbrendan 				pio = zio_root(spa, l2arc_write_done, cb,
41345450Sbrendan 				    ZIO_FLAG_CANFAIL);
41355450Sbrendan 			}
41365450Sbrendan 
41375450Sbrendan 			/*
41385450Sbrendan 			 * Create and add a new L2ARC header.
41395450Sbrendan 			 */
41405450Sbrendan 			hdrl2 = kmem_zalloc(sizeof (l2arc_buf_hdr_t), KM_SLEEP);
41415450Sbrendan 			hdrl2->b_dev = dev;
41425450Sbrendan 			hdrl2->b_daddr = dev->l2ad_hand;
41435450Sbrendan 
41445450Sbrendan 			ab->b_flags |= ARC_L2_WRITING;
41455450Sbrendan 			ab->b_l2hdr = hdrl2;
41465450Sbrendan 			list_insert_head(dev->l2ad_buflist, ab);
41475450Sbrendan 			buf_data = ab->b_buf->b_data;
41485450Sbrendan 			buf_sz = ab->b_size;
41495450Sbrendan 
41505450Sbrendan 			/*
41515450Sbrendan 			 * Compute and store the buffer cksum before
41525450Sbrendan 			 * writing.  On debug the cksum is verified first.
41535450Sbrendan 			 */
41545450Sbrendan 			arc_cksum_verify(ab->b_buf);
41555450Sbrendan 			arc_cksum_compute(ab->b_buf, B_TRUE);
41565450Sbrendan 
41575450Sbrendan 			mutex_exit(hash_lock);
41585450Sbrendan 
41595450Sbrendan 			wzio = zio_write_phys(pio, dev->l2ad_vdev,
41605450Sbrendan 			    dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
41615450Sbrendan 			    NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
41625450Sbrendan 			    ZIO_FLAG_CANFAIL, B_FALSE);
41635450Sbrendan 
41645450Sbrendan 			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
41655450Sbrendan 			    zio_t *, wzio);
41665450Sbrendan 			(void) zio_nowait(wzio);
41675450Sbrendan 
41685450Sbrendan 			write_sz += buf_sz;
41695450Sbrendan 			dev->l2ad_hand += buf_sz;
41705450Sbrendan 		}
41715450Sbrendan 
41725450Sbrendan 		mutex_exit(list_lock);
41735450Sbrendan 
41745450Sbrendan 		if (full == B_TRUE)
41755450Sbrendan 			break;
41765450Sbrendan 	}
41775450Sbrendan 	mutex_exit(&l2arc_buflist_mtx);
41785450Sbrendan 
41795450Sbrendan 	if (pio == NULL) {
41805450Sbrendan 		ASSERT3U(write_sz, ==, 0);
41815450Sbrendan 		kmem_cache_free(hdr_cache, head);
41825450Sbrendan 		return;
41835450Sbrendan 	}
41845450Sbrendan 
41855450Sbrendan 	ASSERT3U(write_sz, <=, target_sz);
41865450Sbrendan 	ARCSTAT_BUMP(arcstat_l2_writes_sent);
41875450Sbrendan 	ARCSTAT_INCR(arcstat_l2_size, write_sz);
41885450Sbrendan 	spa_l2cache_space_update(dev->l2ad_vdev, 0, write_sz);
41895450Sbrendan 
41905450Sbrendan 	/*
41915450Sbrendan 	 * Bump device hand to the device start if it is approaching the end.
41925450Sbrendan 	 * l2arc_evict() will already have evicted ahead for this case.
41935450Sbrendan 	 */
41946987Sbrendan 	if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
41955450Sbrendan 		spa_l2cache_space_update(dev->l2ad_vdev, 0,
41965450Sbrendan 		    dev->l2ad_end - dev->l2ad_hand);
41975450Sbrendan 		dev->l2ad_hand = dev->l2ad_start;
41985450Sbrendan 		dev->l2ad_evict = dev->l2ad_start;
41995450Sbrendan 		dev->l2ad_first = B_FALSE;
42005450Sbrendan 	}
42015450Sbrendan 
42025450Sbrendan 	(void) zio_wait(pio);
42035450Sbrendan }
42045450Sbrendan 
42055450Sbrendan /*
42065450Sbrendan  * This thread feeds the L2ARC at regular intervals.  This is the beating
42075450Sbrendan  * heart of the L2ARC.
42085450Sbrendan  */
42095450Sbrendan static void
42105450Sbrendan l2arc_feed_thread(void)
42115450Sbrendan {
42125450Sbrendan 	callb_cpr_t cpr;
42135450Sbrendan 	l2arc_dev_t *dev;
42145450Sbrendan 	spa_t *spa;
42156987Sbrendan 	uint64_t size;
42165450Sbrendan 
42175450Sbrendan 	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
42185450Sbrendan 
42195450Sbrendan 	mutex_enter(&l2arc_feed_thr_lock);
42205450Sbrendan 
42215450Sbrendan 	while (l2arc_thread_exit == 0) {
42225450Sbrendan 		/*
42236987Sbrendan 		 * Pause for l2arc_feed_secs seconds between writes.
42245450Sbrendan 		 */
42255450Sbrendan 		CALLB_CPR_SAFE_BEGIN(&cpr);
42266987Sbrendan 		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
42276987Sbrendan 		    lbolt + (hz * l2arc_feed_secs));
42286987Sbrendan 		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
42296987Sbrendan 
42306987Sbrendan 		/*
42316987Sbrendan 		 * Quick check for L2ARC devices.
42326987Sbrendan 		 */
42336987Sbrendan 		mutex_enter(&l2arc_dev_mtx);
42346987Sbrendan 		if (l2arc_ndev == 0) {
42356987Sbrendan 			mutex_exit(&l2arc_dev_mtx);
42366987Sbrendan 			continue;
42375450Sbrendan 		}
42386987Sbrendan 		mutex_exit(&l2arc_dev_mtx);
42396643Seschrock 
42405450Sbrendan 		/*
42416643Seschrock 		 * This selects the next l2arc device to write to, and in
42426643Seschrock 		 * doing so the next spa to feed from: dev->l2ad_spa.   This
42436987Sbrendan 		 * will return NULL if there are now no l2arc devices or if
42446987Sbrendan 		 * they are all faulted.
42456987Sbrendan 		 *
42466987Sbrendan 		 * If a device is returned, its spa's config lock is also
42476987Sbrendan 		 * held to prevent device removal.  l2arc_dev_get_next()
42486987Sbrendan 		 * will grab and release l2arc_dev_mtx.
42495450Sbrendan 		 */
42506987Sbrendan 		if ((dev = l2arc_dev_get_next()) == NULL)
42515450Sbrendan 			continue;
42526987Sbrendan 
42536987Sbrendan 		spa = dev->l2ad_spa;
42546987Sbrendan 		ASSERT(spa != NULL);
42555450Sbrendan 
42565450Sbrendan 		/*
42575450Sbrendan 		 * Avoid contributing to memory pressure.
42585450Sbrendan 		 */
42595450Sbrendan 		if (arc_reclaim_needed()) {
42605450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
42616987Sbrendan 			spa_config_exit(spa, dev);
42625450Sbrendan 			continue;
42635450Sbrendan 		}
42645450Sbrendan 
42655450Sbrendan 		ARCSTAT_BUMP(arcstat_l2_feeds);
42665450Sbrendan 
42676987Sbrendan 		size = dev->l2ad_write;
42686987Sbrendan 		if (arc_warm == B_FALSE)
42696987Sbrendan 			size += dev->l2ad_boost;
42706987Sbrendan 
42715450Sbrendan 		/*
42725450Sbrendan 		 * Evict L2ARC buffers that will be overwritten.
42735450Sbrendan 		 */
42746987Sbrendan 		l2arc_evict(dev, size, B_FALSE);
42755450Sbrendan 
42765450Sbrendan 		/*
42775450Sbrendan 		 * Write ARC buffers.
42785450Sbrendan 		 */
42796987Sbrendan 		l2arc_write_buffers(spa, dev, size);
42806987Sbrendan 		spa_config_exit(spa, dev);
42815450Sbrendan 	}
42825450Sbrendan 
42835450Sbrendan 	l2arc_thread_exit = 0;
42845450Sbrendan 	cv_broadcast(&l2arc_feed_thr_cv);
42855450Sbrendan 	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
42865450Sbrendan 	thread_exit();
42875450Sbrendan }
42885450Sbrendan 
42896643Seschrock boolean_t
42906643Seschrock l2arc_vdev_present(vdev_t *vd)
42916643Seschrock {
42926643Seschrock 	l2arc_dev_t *dev;
42936643Seschrock 
42946643Seschrock 	mutex_enter(&l2arc_dev_mtx);
42956643Seschrock 	for (dev = list_head(l2arc_dev_list); dev != NULL;
42966643Seschrock 	    dev = list_next(l2arc_dev_list, dev)) {
42976643Seschrock 		if (dev->l2ad_vdev == vd)
42986643Seschrock 			break;
42996643Seschrock 	}
43006643Seschrock 	mutex_exit(&l2arc_dev_mtx);
43016643Seschrock 
43026643Seschrock 	return (dev != NULL);
43036643Seschrock }
43046643Seschrock 
43055450Sbrendan /*
43065450Sbrendan  * Add a vdev for use by the L2ARC.  By this point the spa has already
43075450Sbrendan  * validated the vdev and opened it.
43085450Sbrendan  */
43095450Sbrendan void
43105450Sbrendan l2arc_add_vdev(spa_t *spa, vdev_t *vd, uint64_t start, uint64_t end)
43115450Sbrendan {
43125450Sbrendan 	l2arc_dev_t *adddev;
43135450Sbrendan 
43146643Seschrock 	ASSERT(!l2arc_vdev_present(vd));
43156643Seschrock 
43165450Sbrendan 	/*
43175450Sbrendan 	 * Create a new l2arc device entry.
43185450Sbrendan 	 */
43195450Sbrendan 	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
43205450Sbrendan 	adddev->l2ad_spa = spa;
43215450Sbrendan 	adddev->l2ad_vdev = vd;
43225450Sbrendan 	adddev->l2ad_write = l2arc_write_max;
43236987Sbrendan 	adddev->l2ad_boost = l2arc_write_boost;
43245450Sbrendan 	adddev->l2ad_start = start;
43255450Sbrendan 	adddev->l2ad_end = end;
43265450Sbrendan 	adddev->l2ad_hand = adddev->l2ad_start;
43275450Sbrendan 	adddev->l2ad_evict = adddev->l2ad_start;
43285450Sbrendan 	adddev->l2ad_first = B_TRUE;
43295450Sbrendan 	ASSERT3U(adddev->l2ad_write, >, 0);
43305450Sbrendan 
43315450Sbrendan 	/*
43325450Sbrendan 	 * This is a list of all ARC buffers that are still valid on the
43335450Sbrendan 	 * device.
43345450Sbrendan 	 */
43355450Sbrendan 	adddev->l2ad_buflist = kmem_zalloc(sizeof (list_t), KM_SLEEP);
43365450Sbrendan 	list_create(adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
43375450Sbrendan 	    offsetof(arc_buf_hdr_t, b_l2node));
43385450Sbrendan 
43395450Sbrendan 	spa_l2cache_space_update(vd, adddev->l2ad_end - adddev->l2ad_hand, 0);
43405450Sbrendan 
43415450Sbrendan 	/*
43425450Sbrendan 	 * Add device to global list
43435450Sbrendan 	 */
43445450Sbrendan 	mutex_enter(&l2arc_dev_mtx);
43455450Sbrendan 	list_insert_head(l2arc_dev_list, adddev);
43465450Sbrendan 	atomic_inc_64(&l2arc_ndev);
43475450Sbrendan 	mutex_exit(&l2arc_dev_mtx);
43485450Sbrendan }
43495450Sbrendan 
43505450Sbrendan /*
43515450Sbrendan  * Remove a vdev from the L2ARC.
43525450Sbrendan  */
43535450Sbrendan void
43545450Sbrendan l2arc_remove_vdev(vdev_t *vd)
43555450Sbrendan {
43565450Sbrendan 	l2arc_dev_t *dev, *nextdev, *remdev = NULL;
43575450Sbrendan 
43585450Sbrendan 	/*
43595450Sbrendan 	 * Find the device by vdev
43605450Sbrendan 	 */
43615450Sbrendan 	mutex_enter(&l2arc_dev_mtx);
43625450Sbrendan 	for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
43635450Sbrendan 		nextdev = list_next(l2arc_dev_list, dev);
43645450Sbrendan 		if (vd == dev->l2ad_vdev) {
43655450Sbrendan 			remdev = dev;
43665450Sbrendan 			break;
43675450Sbrendan 		}
43685450Sbrendan 	}
43695450Sbrendan 	ASSERT(remdev != NULL);
43705450Sbrendan 
43715450Sbrendan 	/*
43725450Sbrendan 	 * Remove device from global list
43735450Sbrendan 	 */
43745450Sbrendan 	list_remove(l2arc_dev_list, remdev);
43755450Sbrendan 	l2arc_dev_last = NULL;		/* may have been invalidated */
43766987Sbrendan 	atomic_dec_64(&l2arc_ndev);
43776987Sbrendan 	mutex_exit(&l2arc_dev_mtx);
43785450Sbrendan 
43795450Sbrendan 	/*
43805450Sbrendan 	 * Clear all buflists and ARC references.  L2ARC device flush.
43815450Sbrendan 	 */
43825450Sbrendan 	l2arc_evict(remdev, 0, B_TRUE);
43835450Sbrendan 	list_destroy(remdev->l2ad_buflist);
43845450Sbrendan 	kmem_free(remdev->l2ad_buflist, sizeof (list_t));
43855450Sbrendan 	kmem_free(remdev, sizeof (l2arc_dev_t));
43865450Sbrendan }
43875450Sbrendan 
43885450Sbrendan void
43895450Sbrendan l2arc_init()
43905450Sbrendan {
43915450Sbrendan 	l2arc_thread_exit = 0;
43925450Sbrendan 	l2arc_ndev = 0;
43935450Sbrendan 	l2arc_writes_sent = 0;
43945450Sbrendan 	l2arc_writes_done = 0;
43955450Sbrendan 
43965450Sbrendan 	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
43975450Sbrendan 	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
43985450Sbrendan 	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
43995450Sbrendan 	mutex_init(&l2arc_buflist_mtx, NULL, MUTEX_DEFAULT, NULL);
44005450Sbrendan 	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
44015450Sbrendan 
44025450Sbrendan 	l2arc_dev_list = &L2ARC_dev_list;
44035450Sbrendan 	l2arc_free_on_write = &L2ARC_free_on_write;
44045450Sbrendan 	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
44055450Sbrendan 	    offsetof(l2arc_dev_t, l2ad_node));
44065450Sbrendan 	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
44075450Sbrendan 	    offsetof(l2arc_data_free_t, l2df_list_node));
44085450Sbrendan 
44095450Sbrendan 	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
44105450Sbrendan 	    TS_RUN, minclsyspri);
44115450Sbrendan }
44125450Sbrendan 
44135450Sbrendan void
44145450Sbrendan l2arc_fini()
44155450Sbrendan {
44166987Sbrendan 	/*
44176987Sbrendan 	 * This is called from dmu_fini(), which is called from spa_fini();
44186987Sbrendan 	 * Because of this, we can assume that all l2arc devices have
44196987Sbrendan 	 * already been removed when the pools themselves were removed.
44206987Sbrendan 	 */
44216987Sbrendan 
44225450Sbrendan 	mutex_enter(&l2arc_feed_thr_lock);
44235450Sbrendan 	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
44245450Sbrendan 	l2arc_thread_exit = 1;
44255450Sbrendan 	while (l2arc_thread_exit != 0)
44265450Sbrendan 		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
44275450Sbrendan 	mutex_exit(&l2arc_feed_thr_lock);
44285450Sbrendan 
44296987Sbrendan 	l2arc_do_free_on_write();
44306987Sbrendan 
44315450Sbrendan 	mutex_destroy(&l2arc_feed_thr_lock);
44325450Sbrendan 	cv_destroy(&l2arc_feed_thr_cv);
44335450Sbrendan 	mutex_destroy(&l2arc_dev_mtx);
44345450Sbrendan 	mutex_destroy(&l2arc_buflist_mtx);
44355450Sbrendan 	mutex_destroy(&l2arc_free_on_write_mtx);
44365450Sbrendan 
44375450Sbrendan 	list_destroy(l2arc_dev_list);
44385450Sbrendan 	list_destroy(l2arc_free_on_write);
44395450Sbrendan }
4440