xref: /onnv-gate/usr/src/uts/common/fs/zfs/arc.c (revision 10839)
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 /*
228582SBrendan.Gregg@Sun.COM  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23789Sahrens  * Use is subject to license terms.
24789Sahrens  */
25789Sahrens 
26789Sahrens /*
273403Sbmc  * DVA-based Adjustable Replacement Cache
28789Sahrens  *
291544Seschrock  * While much of the theory of operation used here is
301544Seschrock  * based on the self-tuning, low overhead replacement cache
31789Sahrens  * presented by Megiddo and Modha at FAST 2003, there are some
32789Sahrens  * significant differences:
33789Sahrens  *
34789Sahrens  * 1. The Megiddo and Modha model assumes any page is evictable.
35789Sahrens  * Pages in its cache cannot be "locked" into memory.  This makes
36789Sahrens  * the eviction algorithm simple: evict the last page in the list.
37789Sahrens  * This also make the performance characteristics easy to reason
38789Sahrens  * about.  Our cache is not so simple.  At any given moment, some
39789Sahrens  * subset of the blocks in the cache are un-evictable because we
40789Sahrens  * have handed out a reference to them.  Blocks are only evictable
41789Sahrens  * when there are no external references active.  This makes
42789Sahrens  * eviction far more problematic:  we choose to evict the evictable
43789Sahrens  * blocks that are the "lowest" in the list.
44789Sahrens  *
45789Sahrens  * There are times when it is not possible to evict the requested
46789Sahrens  * space.  In these circumstances we are unable to adjust the cache
47789Sahrens  * size.  To prevent the cache growing unbounded at these times we
485450Sbrendan  * implement a "cache throttle" that slows the flow of new data
495450Sbrendan  * into the cache until we can make space available.
50789Sahrens  *
51789Sahrens  * 2. The Megiddo and Modha model assumes a fixed cache size.
52789Sahrens  * Pages are evicted when the cache is full and there is a cache
53789Sahrens  * miss.  Our model has a variable sized cache.  It grows with
545450Sbrendan  * high use, but also tries to react to memory pressure from the
55789Sahrens  * operating system: decreasing its size when system memory is
56789Sahrens  * tight.
57789Sahrens  *
58789Sahrens  * 3. The Megiddo and Modha model assumes a fixed page size. All
59789Sahrens  * elements of the cache are therefor exactly the same size.  So
60789Sahrens  * when adjusting the cache size following a cache miss, its simply
61789Sahrens  * a matter of choosing a single page to evict.  In our model, we
62789Sahrens  * have variable sized cache blocks (rangeing from 512 bytes to
63789Sahrens  * 128K bytes).  We therefor choose a set of blocks to evict to make
64789Sahrens  * space for a cache miss that approximates as closely as possible
65789Sahrens  * the space used by the new block.
66789Sahrens  *
67789Sahrens  * See also:  "ARC: A Self-Tuning, Low Overhead Replacement Cache"
68789Sahrens  * by N. Megiddo & D. Modha, FAST 2003
69789Sahrens  */
70789Sahrens 
71789Sahrens /*
72789Sahrens  * The locking model:
73789Sahrens  *
74789Sahrens  * A new reference to a cache buffer can be obtained in two
75789Sahrens  * ways: 1) via a hash table lookup using the DVA as a key,
765450Sbrendan  * or 2) via one of the ARC lists.  The arc_read() interface
77789Sahrens  * uses method 1, while the internal arc algorithms for
78789Sahrens  * adjusting the cache use method 2.  We therefor provide two
79789Sahrens  * types of locks: 1) the hash table lock array, and 2) the
80789Sahrens  * arc list locks.
81789Sahrens  *
82789Sahrens  * Buffers do not have their own mutexs, rather they rely on the
83789Sahrens  * hash table mutexs for the bulk of their protection (i.e. most
84789Sahrens  * fields in the arc_buf_hdr_t are protected by these mutexs).
85789Sahrens  *
86789Sahrens  * buf_hash_find() returns the appropriate mutex (held) when it
87789Sahrens  * locates the requested buffer in the hash table.  It returns
88789Sahrens  * NULL for the mutex if the buffer was not in the table.
89789Sahrens  *
90789Sahrens  * buf_hash_remove() expects the appropriate hash mutex to be
91789Sahrens  * already held before it is invoked.
92789Sahrens  *
93789Sahrens  * Each arc state also has a mutex which is used to protect the
94789Sahrens  * buffer list associated with the state.  When attempting to
95789Sahrens  * obtain a hash table lock while holding an arc list lock you
96789Sahrens  * must use: mutex_tryenter() to avoid deadlock.  Also note that
972688Smaybee  * the active state mutex must be held before the ghost state mutex.
98789Sahrens  *
991544Seschrock  * Arc buffers may have an associated eviction callback function.
1001544Seschrock  * This function will be invoked prior to removing the buffer (e.g.
1011544Seschrock  * in arc_do_user_evicts()).  Note however that the data associated
1021544Seschrock  * with the buffer may be evicted prior to the callback.  The callback
1031544Seschrock  * must be made with *no locks held* (to prevent deadlock).  Additionally,
1041544Seschrock  * the users of callbacks must ensure that their private data is
1051544Seschrock  * protected from simultaneous callbacks from arc_buf_evict()
1061544Seschrock  * and arc_do_user_evicts().
1071544Seschrock  *
108789Sahrens  * Note that the majority of the performance stats are manipulated
109789Sahrens  * with atomic operations.
1105450Sbrendan  *
1115450Sbrendan  * The L2ARC uses the l2arc_buflist_mtx global mutex for the following:
1125450Sbrendan  *
1135450Sbrendan  *	- L2ARC buflist creation
1145450Sbrendan  *	- L2ARC buflist eviction
1155450Sbrendan  *	- L2ARC write completion, which walks L2ARC buflists
1165450Sbrendan  *	- ARC header destruction, as it removes from L2ARC buflists
1175450Sbrendan  *	- ARC header release, as it removes from L2ARC buflists
118789Sahrens  */
119789Sahrens 
120789Sahrens #include <sys/spa.h>
121789Sahrens #include <sys/zio.h>
1223093Sahrens #include <sys/zio_checksum.h>
123789Sahrens #include <sys/zfs_context.h>
124789Sahrens #include <sys/arc.h>
125789Sahrens #include <sys/refcount.h>
1266643Seschrock #include <sys/vdev.h>
1279816SGeorge.Wilson@Sun.COM #include <sys/vdev_impl.h>
128789Sahrens #ifdef _KERNEL
129789Sahrens #include <sys/vmsystm.h>
130789Sahrens #include <vm/anon.h>
131789Sahrens #include <sys/fs/swapnode.h>
1321484Sek110237 #include <sys/dnlc.h>
133789Sahrens #endif
134789Sahrens #include <sys/callb.h>
1353403Sbmc #include <sys/kstat.h>
136789Sahrens 
137789Sahrens static kmutex_t		arc_reclaim_thr_lock;
138789Sahrens static kcondvar_t	arc_reclaim_thr_cv;	/* used to signal reclaim thr */
139789Sahrens static uint8_t		arc_thread_exit;
140789Sahrens 
1416245Smaybee extern int zfs_write_limit_shift;
1426245Smaybee extern uint64_t zfs_write_limit_max;
1437468SMark.Maybee@Sun.COM extern kmutex_t zfs_write_limit_lock;
1446245Smaybee 
1451484Sek110237 #define	ARC_REDUCE_DNLC_PERCENT	3
1461484Sek110237 uint_t arc_reduce_dnlc_percent = ARC_REDUCE_DNLC_PERCENT;
1471484Sek110237 
148789Sahrens typedef enum arc_reclaim_strategy {
149789Sahrens 	ARC_RECLAIM_AGGR,		/* Aggressive reclaim strategy */
150789Sahrens 	ARC_RECLAIM_CONS		/* Conservative reclaim strategy */
151789Sahrens } arc_reclaim_strategy_t;
152789Sahrens 
153789Sahrens /* number of seconds before growing cache again */
154789Sahrens static int		arc_grow_retry = 60;
155789Sahrens 
1568582SBrendan.Gregg@Sun.COM /* shift of arc_c for calculating both min and max arc_p */
1578582SBrendan.Gregg@Sun.COM static int		arc_p_min_shift = 4;
1588582SBrendan.Gregg@Sun.COM 
1598582SBrendan.Gregg@Sun.COM /* log2(fraction of arc to reclaim) */
1608582SBrendan.Gregg@Sun.COM static int		arc_shrink_shift = 5;
1618582SBrendan.Gregg@Sun.COM 
1622391Smaybee /*
1632638Sperrin  * minimum lifespan of a prefetch block in clock ticks
1642638Sperrin  * (initialized in arc_init())
1652391Smaybee  */
1662638Sperrin static int		arc_min_prefetch_lifespan;
1672391Smaybee 
168789Sahrens static int arc_dead;
169789Sahrens 
170789Sahrens /*
1716987Sbrendan  * The arc has filled available memory and has now warmed up.
1726987Sbrendan  */
1736987Sbrendan static boolean_t arc_warm;
1746987Sbrendan 
1756987Sbrendan /*
1762885Sahrens  * These tunables are for performance analysis.
1772885Sahrens  */
1782885Sahrens uint64_t zfs_arc_max;
1792885Sahrens uint64_t zfs_arc_min;
1804645Sek110237 uint64_t zfs_arc_meta_limit = 0;
1817046Sahrens int zfs_mdcomp_disable = 0;
1828582SBrendan.Gregg@Sun.COM int zfs_arc_grow_retry = 0;
1838582SBrendan.Gregg@Sun.COM int zfs_arc_shrink_shift = 0;
1848582SBrendan.Gregg@Sun.COM int zfs_arc_p_min_shift = 0;
1852885Sahrens 
1862885Sahrens /*
1875450Sbrendan  * Note that buffers can be in one of 6 states:
188789Sahrens  *	ARC_anon	- anonymous (discussed below)
1891544Seschrock  *	ARC_mru		- recently used, currently cached
1901544Seschrock  *	ARC_mru_ghost	- recentely used, no longer in cache
1911544Seschrock  *	ARC_mfu		- frequently used, currently cached
1921544Seschrock  *	ARC_mfu_ghost	- frequently used, no longer in cache
1935450Sbrendan  *	ARC_l2c_only	- exists in L2ARC but not other states
1944309Smaybee  * When there are no active references to the buffer, they are
1954309Smaybee  * are linked onto a list in one of these arc states.  These are
1964309Smaybee  * the only buffers that can be evicted or deleted.  Within each
1974309Smaybee  * state there are multiple lists, one for meta-data and one for
1984309Smaybee  * non-meta-data.  Meta-data (indirect blocks, blocks of dnodes,
1994309Smaybee  * etc.) is tracked separately so that it can be managed more
2005450Sbrendan  * explicitly: favored over data, limited explicitly.
201789Sahrens  *
202789Sahrens  * Anonymous buffers are buffers that are not associated with
203789Sahrens  * a DVA.  These are buffers that hold dirty block copies
204789Sahrens  * before they are written to stable storage.  By definition,
2051544Seschrock  * they are "ref'd" and are considered part of arc_mru
206789Sahrens  * that cannot be freed.  Generally, they will aquire a DVA
2071544Seschrock  * as they are written and migrate onto the arc_mru list.
2085450Sbrendan  *
2095450Sbrendan  * The ARC_l2c_only state is for buffers that are in the second
2105450Sbrendan  * level ARC but no longer in any of the ARC_m* lists.  The second
2115450Sbrendan  * level ARC itself may also contain buffers that are in any of
2125450Sbrendan  * the ARC_m* states - meaning that a buffer can exist in two
2135450Sbrendan  * places.  The reason for the ARC_l2c_only state is to keep the
2145450Sbrendan  * buffer header in the hash table, so that reads that hit the
2155450Sbrendan  * second level ARC benefit from these fast lookups.
216789Sahrens  */
217789Sahrens 
218789Sahrens typedef struct arc_state {
2194309Smaybee 	list_t	arcs_list[ARC_BUFC_NUMTYPES];	/* list of evictable buffers */
2204309Smaybee 	uint64_t arcs_lsize[ARC_BUFC_NUMTYPES];	/* amount of evictable data */
2214309Smaybee 	uint64_t arcs_size;	/* total amount of data in this state */
2223403Sbmc 	kmutex_t arcs_mtx;
223789Sahrens } arc_state_t;
224789Sahrens 
2255450Sbrendan /* The 6 states: */
226789Sahrens static arc_state_t ARC_anon;
2271544Seschrock static arc_state_t ARC_mru;
2281544Seschrock static arc_state_t ARC_mru_ghost;
2291544Seschrock static arc_state_t ARC_mfu;
2301544Seschrock static arc_state_t ARC_mfu_ghost;
2315450Sbrendan static arc_state_t ARC_l2c_only;
232789Sahrens 
2333403Sbmc typedef struct arc_stats {
2343403Sbmc 	kstat_named_t arcstat_hits;
2353403Sbmc 	kstat_named_t arcstat_misses;
2363403Sbmc 	kstat_named_t arcstat_demand_data_hits;
2373403Sbmc 	kstat_named_t arcstat_demand_data_misses;
2383403Sbmc 	kstat_named_t arcstat_demand_metadata_hits;
2393403Sbmc 	kstat_named_t arcstat_demand_metadata_misses;
2403403Sbmc 	kstat_named_t arcstat_prefetch_data_hits;
2413403Sbmc 	kstat_named_t arcstat_prefetch_data_misses;
2423403Sbmc 	kstat_named_t arcstat_prefetch_metadata_hits;
2433403Sbmc 	kstat_named_t arcstat_prefetch_metadata_misses;
2443403Sbmc 	kstat_named_t arcstat_mru_hits;
2453403Sbmc 	kstat_named_t arcstat_mru_ghost_hits;
2463403Sbmc 	kstat_named_t arcstat_mfu_hits;
2473403Sbmc 	kstat_named_t arcstat_mfu_ghost_hits;
2483403Sbmc 	kstat_named_t arcstat_deleted;
2493403Sbmc 	kstat_named_t arcstat_recycle_miss;
2503403Sbmc 	kstat_named_t arcstat_mutex_miss;
2513403Sbmc 	kstat_named_t arcstat_evict_skip;
25210357SBrendan.Gregg@Sun.COM 	kstat_named_t arcstat_evict_l2_cached;
25310357SBrendan.Gregg@Sun.COM 	kstat_named_t arcstat_evict_l2_eligible;
25410357SBrendan.Gregg@Sun.COM 	kstat_named_t arcstat_evict_l2_ineligible;
2553403Sbmc 	kstat_named_t arcstat_hash_elements;
2563403Sbmc 	kstat_named_t arcstat_hash_elements_max;
2573403Sbmc 	kstat_named_t arcstat_hash_collisions;
2583403Sbmc 	kstat_named_t arcstat_hash_chains;
2593403Sbmc 	kstat_named_t arcstat_hash_chain_max;
2603403Sbmc 	kstat_named_t arcstat_p;
2613403Sbmc 	kstat_named_t arcstat_c;
2623403Sbmc 	kstat_named_t arcstat_c_min;
2633403Sbmc 	kstat_named_t arcstat_c_max;
2643403Sbmc 	kstat_named_t arcstat_size;
2655450Sbrendan 	kstat_named_t arcstat_hdr_size;
2668582SBrendan.Gregg@Sun.COM 	kstat_named_t arcstat_data_size;
2678582SBrendan.Gregg@Sun.COM 	kstat_named_t arcstat_other_size;
2685450Sbrendan 	kstat_named_t arcstat_l2_hits;
2695450Sbrendan 	kstat_named_t arcstat_l2_misses;
2705450Sbrendan 	kstat_named_t arcstat_l2_feeds;
2715450Sbrendan 	kstat_named_t arcstat_l2_rw_clash;
2728582SBrendan.Gregg@Sun.COM 	kstat_named_t arcstat_l2_read_bytes;
2738582SBrendan.Gregg@Sun.COM 	kstat_named_t arcstat_l2_write_bytes;
2745450Sbrendan 	kstat_named_t arcstat_l2_writes_sent;
2755450Sbrendan 	kstat_named_t arcstat_l2_writes_done;
2765450Sbrendan 	kstat_named_t arcstat_l2_writes_error;
2775450Sbrendan 	kstat_named_t arcstat_l2_writes_hdr_miss;
2785450Sbrendan 	kstat_named_t arcstat_l2_evict_lock_retry;
2795450Sbrendan 	kstat_named_t arcstat_l2_evict_reading;
2805450Sbrendan 	kstat_named_t arcstat_l2_free_on_write;
2815450Sbrendan 	kstat_named_t arcstat_l2_abort_lowmem;
2825450Sbrendan 	kstat_named_t arcstat_l2_cksum_bad;
2835450Sbrendan 	kstat_named_t arcstat_l2_io_error;
2845450Sbrendan 	kstat_named_t arcstat_l2_size;
2855450Sbrendan 	kstat_named_t arcstat_l2_hdr_size;
2866245Smaybee 	kstat_named_t arcstat_memory_throttle_count;
2873403Sbmc } arc_stats_t;
2883403Sbmc 
2893403Sbmc static arc_stats_t arc_stats = {
2903403Sbmc 	{ "hits",			KSTAT_DATA_UINT64 },
2913403Sbmc 	{ "misses",			KSTAT_DATA_UINT64 },
2923403Sbmc 	{ "demand_data_hits",		KSTAT_DATA_UINT64 },
2933403Sbmc 	{ "demand_data_misses",		KSTAT_DATA_UINT64 },
2943403Sbmc 	{ "demand_metadata_hits",	KSTAT_DATA_UINT64 },
2953403Sbmc 	{ "demand_metadata_misses",	KSTAT_DATA_UINT64 },
2963403Sbmc 	{ "prefetch_data_hits",		KSTAT_DATA_UINT64 },
2973403Sbmc 	{ "prefetch_data_misses",	KSTAT_DATA_UINT64 },
2983403Sbmc 	{ "prefetch_metadata_hits",	KSTAT_DATA_UINT64 },
2993403Sbmc 	{ "prefetch_metadata_misses",	KSTAT_DATA_UINT64 },
3003403Sbmc 	{ "mru_hits",			KSTAT_DATA_UINT64 },
3013403Sbmc 	{ "mru_ghost_hits",		KSTAT_DATA_UINT64 },
3023403Sbmc 	{ "mfu_hits",			KSTAT_DATA_UINT64 },
3033403Sbmc 	{ "mfu_ghost_hits",		KSTAT_DATA_UINT64 },
3043403Sbmc 	{ "deleted",			KSTAT_DATA_UINT64 },
3053403Sbmc 	{ "recycle_miss",		KSTAT_DATA_UINT64 },
3063403Sbmc 	{ "mutex_miss",			KSTAT_DATA_UINT64 },
3073403Sbmc 	{ "evict_skip",			KSTAT_DATA_UINT64 },
30810357SBrendan.Gregg@Sun.COM 	{ "evict_l2_cached",		KSTAT_DATA_UINT64 },
30910357SBrendan.Gregg@Sun.COM 	{ "evict_l2_eligible",		KSTAT_DATA_UINT64 },
31010357SBrendan.Gregg@Sun.COM 	{ "evict_l2_ineligible",	KSTAT_DATA_UINT64 },
3113403Sbmc 	{ "hash_elements",		KSTAT_DATA_UINT64 },
3123403Sbmc 	{ "hash_elements_max",		KSTAT_DATA_UINT64 },
3133403Sbmc 	{ "hash_collisions",		KSTAT_DATA_UINT64 },
3143403Sbmc 	{ "hash_chains",		KSTAT_DATA_UINT64 },
3153403Sbmc 	{ "hash_chain_max",		KSTAT_DATA_UINT64 },
3163403Sbmc 	{ "p",				KSTAT_DATA_UINT64 },
3173403Sbmc 	{ "c",				KSTAT_DATA_UINT64 },
3183403Sbmc 	{ "c_min",			KSTAT_DATA_UINT64 },
3193403Sbmc 	{ "c_max",			KSTAT_DATA_UINT64 },
3205450Sbrendan 	{ "size",			KSTAT_DATA_UINT64 },
3215450Sbrendan 	{ "hdr_size",			KSTAT_DATA_UINT64 },
3228582SBrendan.Gregg@Sun.COM 	{ "data_size",			KSTAT_DATA_UINT64 },
3238582SBrendan.Gregg@Sun.COM 	{ "other_size",			KSTAT_DATA_UINT64 },
3245450Sbrendan 	{ "l2_hits",			KSTAT_DATA_UINT64 },
3255450Sbrendan 	{ "l2_misses",			KSTAT_DATA_UINT64 },
3265450Sbrendan 	{ "l2_feeds",			KSTAT_DATA_UINT64 },
3275450Sbrendan 	{ "l2_rw_clash",		KSTAT_DATA_UINT64 },
3288582SBrendan.Gregg@Sun.COM 	{ "l2_read_bytes",		KSTAT_DATA_UINT64 },
3298582SBrendan.Gregg@Sun.COM 	{ "l2_write_bytes",		KSTAT_DATA_UINT64 },
3305450Sbrendan 	{ "l2_writes_sent",		KSTAT_DATA_UINT64 },
3315450Sbrendan 	{ "l2_writes_done",		KSTAT_DATA_UINT64 },
3325450Sbrendan 	{ "l2_writes_error",		KSTAT_DATA_UINT64 },
3335450Sbrendan 	{ "l2_writes_hdr_miss",		KSTAT_DATA_UINT64 },
3345450Sbrendan 	{ "l2_evict_lock_retry",	KSTAT_DATA_UINT64 },
3355450Sbrendan 	{ "l2_evict_reading",		KSTAT_DATA_UINT64 },
3365450Sbrendan 	{ "l2_free_on_write",		KSTAT_DATA_UINT64 },
3375450Sbrendan 	{ "l2_abort_lowmem",		KSTAT_DATA_UINT64 },
3385450Sbrendan 	{ "l2_cksum_bad",		KSTAT_DATA_UINT64 },
3395450Sbrendan 	{ "l2_io_error",		KSTAT_DATA_UINT64 },
3405450Sbrendan 	{ "l2_size",			KSTAT_DATA_UINT64 },
3416245Smaybee 	{ "l2_hdr_size",		KSTAT_DATA_UINT64 },
3426245Smaybee 	{ "memory_throttle_count",	KSTAT_DATA_UINT64 }
3433403Sbmc };
344789Sahrens 
3453403Sbmc #define	ARCSTAT(stat)	(arc_stats.stat.value.ui64)
3463403Sbmc 
3473403Sbmc #define	ARCSTAT_INCR(stat, val) \
3483403Sbmc 	atomic_add_64(&arc_stats.stat.value.ui64, (val));
3493403Sbmc 
3503403Sbmc #define	ARCSTAT_BUMP(stat) 	ARCSTAT_INCR(stat, 1)
3513403Sbmc #define	ARCSTAT_BUMPDOWN(stat)	ARCSTAT_INCR(stat, -1)
3523403Sbmc 
3533403Sbmc #define	ARCSTAT_MAX(stat, val) {					\
3543403Sbmc 	uint64_t m;							\
3553403Sbmc 	while ((val) > (m = arc_stats.stat.value.ui64) &&		\
3563403Sbmc 	    (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val))))	\
3573403Sbmc 		continue;						\
3583403Sbmc }
3593403Sbmc 
3603403Sbmc #define	ARCSTAT_MAXSTAT(stat) \
3613403Sbmc 	ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
362789Sahrens 
3633403Sbmc /*
3643403Sbmc  * We define a macro to allow ARC hits/misses to be easily broken down by
3653403Sbmc  * two separate conditions, giving a total of four different subtypes for
3663403Sbmc  * each of hits and misses (so eight statistics total).
3673403Sbmc  */
3683403Sbmc #define	ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
3693403Sbmc 	if (cond1) {							\
3703403Sbmc 		if (cond2) {						\
3713403Sbmc 			ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
3723403Sbmc 		} else {						\
3733403Sbmc 			ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
3743403Sbmc 		}							\
3753403Sbmc 	} else {							\
3763403Sbmc 		if (cond2) {						\
3773403Sbmc 			ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
3783403Sbmc 		} else {						\
3793403Sbmc 			ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
3803403Sbmc 		}							\
3813403Sbmc 	}
382789Sahrens 
3833403Sbmc kstat_t			*arc_ksp;
3843403Sbmc static arc_state_t 	*arc_anon;
3853403Sbmc static arc_state_t	*arc_mru;
3863403Sbmc static arc_state_t	*arc_mru_ghost;
3873403Sbmc static arc_state_t	*arc_mfu;
3883403Sbmc static arc_state_t	*arc_mfu_ghost;
3895450Sbrendan static arc_state_t	*arc_l2c_only;
3903403Sbmc 
3913403Sbmc /*
3923403Sbmc  * There are several ARC variables that are critical to export as kstats --
3933403Sbmc  * but we don't want to have to grovel around in the kstat whenever we wish to
3943403Sbmc  * manipulate them.  For these variables, we therefore define them to be in
3953403Sbmc  * terms of the statistic variable.  This assures that we are not introducing
3963403Sbmc  * the possibility of inconsistency by having shadow copies of the variables,
3973403Sbmc  * while still allowing the code to be readable.
3983403Sbmc  */
3993403Sbmc #define	arc_size	ARCSTAT(arcstat_size)	/* actual total arc size */
4003403Sbmc #define	arc_p		ARCSTAT(arcstat_p)	/* target size of MRU */
4013403Sbmc #define	arc_c		ARCSTAT(arcstat_c)	/* target size of cache */
4023403Sbmc #define	arc_c_min	ARCSTAT(arcstat_c_min)	/* min target cache size */
4033403Sbmc #define	arc_c_max	ARCSTAT(arcstat_c_max)	/* max target cache size */
4043403Sbmc 
4053403Sbmc static int		arc_no_grow;	/* Don't try to grow cache size */
4063403Sbmc static uint64_t		arc_tempreserve;
4079412SAleksandr.Guzovskiy@Sun.COM static uint64_t		arc_loaned_bytes;
4084309Smaybee static uint64_t		arc_meta_used;
4094309Smaybee static uint64_t		arc_meta_limit;
4104309Smaybee static uint64_t		arc_meta_max = 0;
411789Sahrens 
4125450Sbrendan typedef struct l2arc_buf_hdr l2arc_buf_hdr_t;
4135450Sbrendan 
414789Sahrens typedef struct arc_callback arc_callback_t;
415789Sahrens 
416789Sahrens struct arc_callback {
4173547Smaybee 	void			*acb_private;
418789Sahrens 	arc_done_func_t		*acb_done;
419789Sahrens 	arc_buf_t		*acb_buf;
420789Sahrens 	zio_t			*acb_zio_dummy;
421789Sahrens 	arc_callback_t		*acb_next;
422789Sahrens };
423789Sahrens 
4243547Smaybee typedef struct arc_write_callback arc_write_callback_t;
4253547Smaybee 
4263547Smaybee struct arc_write_callback {
4273547Smaybee 	void		*awcb_private;
4283547Smaybee 	arc_done_func_t	*awcb_ready;
4293547Smaybee 	arc_done_func_t	*awcb_done;
4303547Smaybee 	arc_buf_t	*awcb_buf;
4313547Smaybee };
4323547Smaybee 
433789Sahrens struct arc_buf_hdr {
434789Sahrens 	/* protected by hash lock */
435789Sahrens 	dva_t			b_dva;
436789Sahrens 	uint64_t		b_birth;
437789Sahrens 	uint64_t		b_cksum0;
438789Sahrens 
4393093Sahrens 	kmutex_t		b_freeze_lock;
4403093Sahrens 	zio_cksum_t		*b_freeze_cksum;
4413093Sahrens 
442789Sahrens 	arc_buf_hdr_t		*b_hash_next;
443789Sahrens 	arc_buf_t		*b_buf;
444789Sahrens 	uint32_t		b_flags;
4451544Seschrock 	uint32_t		b_datacnt;
446789Sahrens 
4473290Sjohansen 	arc_callback_t		*b_acb;
448789Sahrens 	kcondvar_t		b_cv;
4493290Sjohansen 
4503290Sjohansen 	/* immutable */
4513290Sjohansen 	arc_buf_contents_t	b_type;
4523290Sjohansen 	uint64_t		b_size;
4538636SMark.Maybee@Sun.COM 	uint64_t		b_spa;
454789Sahrens 
455789Sahrens 	/* protected by arc state mutex */
456789Sahrens 	arc_state_t		*b_state;
457789Sahrens 	list_node_t		b_arc_node;
458789Sahrens 
459789Sahrens 	/* updated atomically */
460789Sahrens 	clock_t			b_arc_access;
461789Sahrens 
462789Sahrens 	/* self protecting */
463789Sahrens 	refcount_t		b_refcnt;
4645450Sbrendan 
4655450Sbrendan 	l2arc_buf_hdr_t		*b_l2hdr;
4665450Sbrendan 	list_node_t		b_l2node;
467789Sahrens };
468789Sahrens 
4691544Seschrock static arc_buf_t *arc_eviction_list;
4701544Seschrock static kmutex_t arc_eviction_mtx;
4712887Smaybee static arc_buf_hdr_t arc_eviction_hdr;
4722688Smaybee static void arc_get_data_buf(arc_buf_t *buf);
4732688Smaybee static void arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock);
4744309Smaybee static int arc_evict_needed(arc_buf_contents_t type);
4758636SMark.Maybee@Sun.COM static void arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes);
4761544Seschrock 
47710357SBrendan.Gregg@Sun.COM static boolean_t l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *ab);
47810357SBrendan.Gregg@Sun.COM 
4791544Seschrock #define	GHOST_STATE(state)	\
4805450Sbrendan 	((state) == arc_mru_ghost || (state) == arc_mfu_ghost ||	\
4815450Sbrendan 	(state) == arc_l2c_only)
4821544Seschrock 
483789Sahrens /*
484789Sahrens  * Private ARC flags.  These flags are private ARC only flags that will show up
485789Sahrens  * in b_flags in the arc_hdr_buf_t.  Some flags are publicly declared, and can
486789Sahrens  * be passed in as arc_flags in things like arc_read.  However, these flags
487789Sahrens  * should never be passed and should only be set by ARC code.  When adding new
488789Sahrens  * public flags, make sure not to smash the private ones.
489789Sahrens  */
490789Sahrens 
4911544Seschrock #define	ARC_IN_HASH_TABLE	(1 << 9)	/* this buffer is hashed */
492789Sahrens #define	ARC_IO_IN_PROGRESS	(1 << 10)	/* I/O in progress for buf */
493789Sahrens #define	ARC_IO_ERROR		(1 << 11)	/* I/O failed for buf */
494789Sahrens #define	ARC_FREED_IN_READ	(1 << 12)	/* buf freed while in read */
4951544Seschrock #define	ARC_BUF_AVAILABLE	(1 << 13)	/* block not in active use */
4962391Smaybee #define	ARC_INDIRECT		(1 << 14)	/* this is an indirect block */
4975450Sbrendan #define	ARC_FREE_IN_PROGRESS	(1 << 15)	/* hdr about to be freed */
4987237Sek110237 #define	ARC_L2_WRITING		(1 << 16)	/* L2ARC write in progress */
4997237Sek110237 #define	ARC_L2_EVICTED		(1 << 17)	/* evicted during I/O */
5007237Sek110237 #define	ARC_L2_WRITE_HEAD	(1 << 18)	/* head of write list */
5017237Sek110237 #define	ARC_STORED		(1 << 19)	/* has been store()d to */
502789Sahrens 
5031544Seschrock #define	HDR_IN_HASH_TABLE(hdr)	((hdr)->b_flags & ARC_IN_HASH_TABLE)
504789Sahrens #define	HDR_IO_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_IO_IN_PROGRESS)
505789Sahrens #define	HDR_IO_ERROR(hdr)	((hdr)->b_flags & ARC_IO_ERROR)
5068582SBrendan.Gregg@Sun.COM #define	HDR_PREFETCH(hdr)	((hdr)->b_flags & ARC_PREFETCH)
507789Sahrens #define	HDR_FREED_IN_READ(hdr)	((hdr)->b_flags & ARC_FREED_IN_READ)
5081544Seschrock #define	HDR_BUF_AVAILABLE(hdr)	((hdr)->b_flags & ARC_BUF_AVAILABLE)
5095450Sbrendan #define	HDR_FREE_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_FREE_IN_PROGRESS)
5107237Sek110237 #define	HDR_L2CACHE(hdr)	((hdr)->b_flags & ARC_L2CACHE)
5116987Sbrendan #define	HDR_L2_READING(hdr)	((hdr)->b_flags & ARC_IO_IN_PROGRESS &&	\
5126987Sbrendan 				    (hdr)->b_l2hdr != NULL)
5135450Sbrendan #define	HDR_L2_WRITING(hdr)	((hdr)->b_flags & ARC_L2_WRITING)
5145450Sbrendan #define	HDR_L2_EVICTED(hdr)	((hdr)->b_flags & ARC_L2_EVICTED)
5155450Sbrendan #define	HDR_L2_WRITE_HEAD(hdr)	((hdr)->b_flags & ARC_L2_WRITE_HEAD)
516789Sahrens 
517789Sahrens /*
5186018Sbrendan  * Other sizes
5196018Sbrendan  */
5206018Sbrendan 
5216018Sbrendan #define	HDR_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
5226018Sbrendan #define	L2HDR_SIZE ((int64_t)sizeof (l2arc_buf_hdr_t))
5236018Sbrendan 
5246018Sbrendan /*
525789Sahrens  * Hash table routines
526789Sahrens  */
527789Sahrens 
528789Sahrens #define	HT_LOCK_PAD	64
529789Sahrens 
530789Sahrens struct ht_lock {
531789Sahrens 	kmutex_t	ht_lock;
532789Sahrens #ifdef _KERNEL
533789Sahrens 	unsigned char	pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
534789Sahrens #endif
535789Sahrens };
536789Sahrens 
537789Sahrens #define	BUF_LOCKS 256
538789Sahrens typedef struct buf_hash_table {
539789Sahrens 	uint64_t ht_mask;
540789Sahrens 	arc_buf_hdr_t **ht_table;
541789Sahrens 	struct ht_lock ht_locks[BUF_LOCKS];
542789Sahrens } buf_hash_table_t;
543789Sahrens 
544789Sahrens static buf_hash_table_t buf_hash_table;
545789Sahrens 
546789Sahrens #define	BUF_HASH_INDEX(spa, dva, birth) \
547789Sahrens 	(buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
548789Sahrens #define	BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
549789Sahrens #define	BUF_HASH_LOCK(idx)	(&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
550789Sahrens #define	HDR_LOCK(buf) \
551789Sahrens 	(BUF_HASH_LOCK(BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth)))
552789Sahrens 
553789Sahrens uint64_t zfs_crc64_table[256];
554789Sahrens 
5555450Sbrendan /*
5565450Sbrendan  * Level 2 ARC
5575450Sbrendan  */
5585450Sbrendan 
5595450Sbrendan #define	L2ARC_WRITE_SIZE	(8 * 1024 * 1024)	/* initial write max */
5608582SBrendan.Gregg@Sun.COM #define	L2ARC_HEADROOM		2		/* num of writes */
5618582SBrendan.Gregg@Sun.COM #define	L2ARC_FEED_SECS		1		/* caching interval secs */
5628582SBrendan.Gregg@Sun.COM #define	L2ARC_FEED_MIN_MS	200		/* min caching interval ms */
5635450Sbrendan 
5645450Sbrendan #define	l2arc_writes_sent	ARCSTAT(arcstat_l2_writes_sent)
5655450Sbrendan #define	l2arc_writes_done	ARCSTAT(arcstat_l2_writes_done)
5665450Sbrendan 
5675450Sbrendan /*
5685450Sbrendan  * L2ARC Performance Tunables
5695450Sbrendan  */
5705450Sbrendan uint64_t l2arc_write_max = L2ARC_WRITE_SIZE;	/* default max write size */
5716987Sbrendan uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE;	/* extra write during warmup */
5725450Sbrendan uint64_t l2arc_headroom = L2ARC_HEADROOM;	/* number of dev writes */
5735450Sbrendan uint64_t l2arc_feed_secs = L2ARC_FEED_SECS;	/* interval seconds */
5748582SBrendan.Gregg@Sun.COM uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS;	/* min interval milliseconds */
5755450Sbrendan boolean_t l2arc_noprefetch = B_TRUE;		/* don't cache prefetch bufs */
5768582SBrendan.Gregg@Sun.COM boolean_t l2arc_feed_again = B_TRUE;		/* turbo warmup */
5778582SBrendan.Gregg@Sun.COM boolean_t l2arc_norw = B_TRUE;			/* no reads during writes */
5785450Sbrendan 
5795450Sbrendan /*
5805450Sbrendan  * L2ARC Internals
5815450Sbrendan  */
5825450Sbrendan typedef struct l2arc_dev {
5835450Sbrendan 	vdev_t			*l2ad_vdev;	/* vdev */
5845450Sbrendan 	spa_t			*l2ad_spa;	/* spa */
5855450Sbrendan 	uint64_t		l2ad_hand;	/* next write location */
5865450Sbrendan 	uint64_t		l2ad_write;	/* desired write size, bytes */
5876987Sbrendan 	uint64_t		l2ad_boost;	/* warmup write boost, bytes */
5885450Sbrendan 	uint64_t		l2ad_start;	/* first addr on device */
5895450Sbrendan 	uint64_t		l2ad_end;	/* last addr on device */
5905450Sbrendan 	uint64_t		l2ad_evict;	/* last addr eviction reached */
5915450Sbrendan 	boolean_t		l2ad_first;	/* first sweep through */
5928582SBrendan.Gregg@Sun.COM 	boolean_t		l2ad_writing;	/* currently writing */
5935450Sbrendan 	list_t			*l2ad_buflist;	/* buffer list */
5945450Sbrendan 	list_node_t		l2ad_node;	/* device list node */
5955450Sbrendan } l2arc_dev_t;
5965450Sbrendan 
5975450Sbrendan static list_t L2ARC_dev_list;			/* device list */
5985450Sbrendan static list_t *l2arc_dev_list;			/* device list pointer */
5995450Sbrendan static kmutex_t l2arc_dev_mtx;			/* device list mutex */
6005450Sbrendan static l2arc_dev_t *l2arc_dev_last;		/* last device used */
6015450Sbrendan static kmutex_t l2arc_buflist_mtx;		/* mutex for all buflists */
6025450Sbrendan static list_t L2ARC_free_on_write;		/* free after write buf list */
6035450Sbrendan static list_t *l2arc_free_on_write;		/* free after write list ptr */
6045450Sbrendan static kmutex_t l2arc_free_on_write_mtx;	/* mutex for list */
6055450Sbrendan static uint64_t l2arc_ndev;			/* number of devices */
6065450Sbrendan 
6075450Sbrendan typedef struct l2arc_read_callback {
6085450Sbrendan 	arc_buf_t	*l2rcb_buf;		/* read buffer */
6095450Sbrendan 	spa_t		*l2rcb_spa;		/* spa */
6105450Sbrendan 	blkptr_t	l2rcb_bp;		/* original blkptr */
6115450Sbrendan 	zbookmark_t	l2rcb_zb;		/* original bookmark */
6125450Sbrendan 	int		l2rcb_flags;		/* original flags */
6135450Sbrendan } l2arc_read_callback_t;
6145450Sbrendan 
6155450Sbrendan typedef struct l2arc_write_callback {
6165450Sbrendan 	l2arc_dev_t	*l2wcb_dev;		/* device info */
6175450Sbrendan 	arc_buf_hdr_t	*l2wcb_head;		/* head of write buflist */
6185450Sbrendan } l2arc_write_callback_t;
6195450Sbrendan 
6205450Sbrendan struct l2arc_buf_hdr {
6215450Sbrendan 	/* protected by arc_buf_hdr  mutex */
6225450Sbrendan 	l2arc_dev_t	*b_dev;			/* L2ARC device */
6239215SGeorge.Wilson@Sun.COM 	uint64_t	b_daddr;		/* disk address, offset byte */
6245450Sbrendan };
6255450Sbrendan 
6265450Sbrendan typedef struct l2arc_data_free {
6275450Sbrendan 	/* protected by l2arc_free_on_write_mtx */
6285450Sbrendan 	void		*l2df_data;
6295450Sbrendan 	size_t		l2df_size;
6305450Sbrendan 	void		(*l2df_func)(void *, size_t);
6315450Sbrendan 	list_node_t	l2df_list_node;
6325450Sbrendan } l2arc_data_free_t;
6335450Sbrendan 
6345450Sbrendan static kmutex_t l2arc_feed_thr_lock;
6355450Sbrendan static kcondvar_t l2arc_feed_thr_cv;
6365450Sbrendan static uint8_t l2arc_thread_exit;
6375450Sbrendan 
6385450Sbrendan static void l2arc_read_done(zio_t *zio);
6395450Sbrendan static void l2arc_hdr_stat_add(void);
6405450Sbrendan static void l2arc_hdr_stat_remove(void);
6415450Sbrendan 
642789Sahrens static uint64_t
6438636SMark.Maybee@Sun.COM buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
644789Sahrens {
645789Sahrens 	uint8_t *vdva = (uint8_t *)dva;
646789Sahrens 	uint64_t crc = -1ULL;
647789Sahrens 	int i;
648789Sahrens 
649789Sahrens 	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
650789Sahrens 
651789Sahrens 	for (i = 0; i < sizeof (dva_t); i++)
652789Sahrens 		crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
653789Sahrens 
6548636SMark.Maybee@Sun.COM 	crc ^= (spa>>8) ^ birth;
655789Sahrens 
656789Sahrens 	return (crc);
657789Sahrens }
658789Sahrens 
659789Sahrens #define	BUF_EMPTY(buf)						\
660789Sahrens 	((buf)->b_dva.dva_word[0] == 0 &&			\
661789Sahrens 	(buf)->b_dva.dva_word[1] == 0 &&			\
662789Sahrens 	(buf)->b_birth == 0)
663789Sahrens 
664789Sahrens #define	BUF_EQUAL(spa, dva, birth, buf)				\
665789Sahrens 	((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) &&	\
666789Sahrens 	((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) &&	\
667789Sahrens 	((buf)->b_birth == birth) && ((buf)->b_spa == spa)
668789Sahrens 
669789Sahrens static arc_buf_hdr_t *
6708636SMark.Maybee@Sun.COM buf_hash_find(uint64_t spa, const dva_t *dva, uint64_t birth, kmutex_t **lockp)
671789Sahrens {
672789Sahrens 	uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
673789Sahrens 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
674789Sahrens 	arc_buf_hdr_t *buf;
675789Sahrens 
676789Sahrens 	mutex_enter(hash_lock);
677789Sahrens 	for (buf = buf_hash_table.ht_table[idx]; buf != NULL;
678789Sahrens 	    buf = buf->b_hash_next) {
679789Sahrens 		if (BUF_EQUAL(spa, dva, birth, buf)) {
680789Sahrens 			*lockp = hash_lock;
681789Sahrens 			return (buf);
682789Sahrens 		}
683789Sahrens 	}
684789Sahrens 	mutex_exit(hash_lock);
685789Sahrens 	*lockp = NULL;
686789Sahrens 	return (NULL);
687789Sahrens }
688789Sahrens 
689789Sahrens /*
690789Sahrens  * Insert an entry into the hash table.  If there is already an element
691789Sahrens  * equal to elem in the hash table, then the already existing element
692789Sahrens  * will be returned and the new element will not be inserted.
693789Sahrens  * Otherwise returns NULL.
694789Sahrens  */
695789Sahrens static arc_buf_hdr_t *
696789Sahrens buf_hash_insert(arc_buf_hdr_t *buf, kmutex_t **lockp)
697789Sahrens {
698789Sahrens 	uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
699789Sahrens 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
700789Sahrens 	arc_buf_hdr_t *fbuf;
7013403Sbmc 	uint32_t i;
702789Sahrens 
7031544Seschrock 	ASSERT(!HDR_IN_HASH_TABLE(buf));
704789Sahrens 	*lockp = hash_lock;
705789Sahrens 	mutex_enter(hash_lock);
706789Sahrens 	for (fbuf = buf_hash_table.ht_table[idx], i = 0; fbuf != NULL;
707789Sahrens 	    fbuf = fbuf->b_hash_next, i++) {
708789Sahrens 		if (BUF_EQUAL(buf->b_spa, &buf->b_dva, buf->b_birth, fbuf))
709789Sahrens 			return (fbuf);
710789Sahrens 	}
711789Sahrens 
712789Sahrens 	buf->b_hash_next = buf_hash_table.ht_table[idx];
713789Sahrens 	buf_hash_table.ht_table[idx] = buf;
7141544Seschrock 	buf->b_flags |= ARC_IN_HASH_TABLE;
715789Sahrens 
716789Sahrens 	/* collect some hash table performance data */
717789Sahrens 	if (i > 0) {
7183403Sbmc 		ARCSTAT_BUMP(arcstat_hash_collisions);
719789Sahrens 		if (i == 1)
7203403Sbmc 			ARCSTAT_BUMP(arcstat_hash_chains);
7213403Sbmc 
7223403Sbmc 		ARCSTAT_MAX(arcstat_hash_chain_max, i);
723789Sahrens 	}
7243403Sbmc 
7253403Sbmc 	ARCSTAT_BUMP(arcstat_hash_elements);
7263403Sbmc 	ARCSTAT_MAXSTAT(arcstat_hash_elements);
727789Sahrens 
728789Sahrens 	return (NULL);
729789Sahrens }
730789Sahrens 
731789Sahrens static void
732789Sahrens buf_hash_remove(arc_buf_hdr_t *buf)
733789Sahrens {
734789Sahrens 	arc_buf_hdr_t *fbuf, **bufp;
735789Sahrens 	uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
736789Sahrens 
737789Sahrens 	ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
7381544Seschrock 	ASSERT(HDR_IN_HASH_TABLE(buf));
739789Sahrens 
740789Sahrens 	bufp = &buf_hash_table.ht_table[idx];
741789Sahrens 	while ((fbuf = *bufp) != buf) {
742789Sahrens 		ASSERT(fbuf != NULL);
743789Sahrens 		bufp = &fbuf->b_hash_next;
744789Sahrens 	}
745789Sahrens 	*bufp = buf->b_hash_next;
746789Sahrens 	buf->b_hash_next = NULL;
7471544Seschrock 	buf->b_flags &= ~ARC_IN_HASH_TABLE;
748789Sahrens 
749789Sahrens 	/* collect some hash table performance data */
7503403Sbmc 	ARCSTAT_BUMPDOWN(arcstat_hash_elements);
7513403Sbmc 
752789Sahrens 	if (buf_hash_table.ht_table[idx] &&
753789Sahrens 	    buf_hash_table.ht_table[idx]->b_hash_next == NULL)
7543403Sbmc 		ARCSTAT_BUMPDOWN(arcstat_hash_chains);
755789Sahrens }
756789Sahrens 
757789Sahrens /*
758789Sahrens  * Global data structures and functions for the buf kmem cache.
759789Sahrens  */
760789Sahrens static kmem_cache_t *hdr_cache;
761789Sahrens static kmem_cache_t *buf_cache;
762789Sahrens 
763789Sahrens static void
764789Sahrens buf_fini(void)
765789Sahrens {
766789Sahrens 	int i;
767789Sahrens 
768789Sahrens 	kmem_free(buf_hash_table.ht_table,
769789Sahrens 	    (buf_hash_table.ht_mask + 1) * sizeof (void *));
770789Sahrens 	for (i = 0; i < BUF_LOCKS; i++)
771789Sahrens 		mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
772789Sahrens 	kmem_cache_destroy(hdr_cache);
773789Sahrens 	kmem_cache_destroy(buf_cache);
774789Sahrens }
775789Sahrens 
776789Sahrens /*
777789Sahrens  * Constructor callback - called when the cache is empty
778789Sahrens  * and a new buf is requested.
779789Sahrens  */
780789Sahrens /* ARGSUSED */
781789Sahrens static int
782789Sahrens hdr_cons(void *vbuf, void *unused, int kmflag)
783789Sahrens {
784789Sahrens 	arc_buf_hdr_t *buf = vbuf;
785789Sahrens 
786789Sahrens 	bzero(buf, sizeof (arc_buf_hdr_t));
787789Sahrens 	refcount_create(&buf->b_refcnt);
788789Sahrens 	cv_init(&buf->b_cv, NULL, CV_DEFAULT, NULL);
7894831Sgw25295 	mutex_init(&buf->b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
7908582SBrendan.Gregg@Sun.COM 	arc_space_consume(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
7918582SBrendan.Gregg@Sun.COM 
792789Sahrens 	return (0);
793789Sahrens }
794789Sahrens 
7957545SMark.Maybee@Sun.COM /* ARGSUSED */
7967545SMark.Maybee@Sun.COM static int
7977545SMark.Maybee@Sun.COM buf_cons(void *vbuf, void *unused, int kmflag)
7987545SMark.Maybee@Sun.COM {
7997545SMark.Maybee@Sun.COM 	arc_buf_t *buf = vbuf;
8007545SMark.Maybee@Sun.COM 
8017545SMark.Maybee@Sun.COM 	bzero(buf, sizeof (arc_buf_t));
8027545SMark.Maybee@Sun.COM 	rw_init(&buf->b_lock, NULL, RW_DEFAULT, NULL);
8038582SBrendan.Gregg@Sun.COM 	arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
8048582SBrendan.Gregg@Sun.COM 
8057545SMark.Maybee@Sun.COM 	return (0);
8067545SMark.Maybee@Sun.COM }
8077545SMark.Maybee@Sun.COM 
808789Sahrens /*
809789Sahrens  * Destructor callback - called when a cached buf is
810789Sahrens  * no longer required.
811789Sahrens  */
812789Sahrens /* ARGSUSED */
813789Sahrens static void
814789Sahrens hdr_dest(void *vbuf, void *unused)
815789Sahrens {
816789Sahrens 	arc_buf_hdr_t *buf = vbuf;
817789Sahrens 
818789Sahrens 	refcount_destroy(&buf->b_refcnt);
819789Sahrens 	cv_destroy(&buf->b_cv);
8204831Sgw25295 	mutex_destroy(&buf->b_freeze_lock);
8218582SBrendan.Gregg@Sun.COM 	arc_space_return(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
822789Sahrens }
823789Sahrens 
8247545SMark.Maybee@Sun.COM /* ARGSUSED */
8257545SMark.Maybee@Sun.COM static void
8267545SMark.Maybee@Sun.COM buf_dest(void *vbuf, void *unused)
8277545SMark.Maybee@Sun.COM {
8287545SMark.Maybee@Sun.COM 	arc_buf_t *buf = vbuf;
8297545SMark.Maybee@Sun.COM 
8307545SMark.Maybee@Sun.COM 	rw_destroy(&buf->b_lock);
8318582SBrendan.Gregg@Sun.COM 	arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
8327545SMark.Maybee@Sun.COM }
8337545SMark.Maybee@Sun.COM 
834789Sahrens /*
835789Sahrens  * Reclaim callback -- invoked when memory is low.
836789Sahrens  */
837789Sahrens /* ARGSUSED */
838789Sahrens static void
839789Sahrens hdr_recl(void *unused)
840789Sahrens {
841789Sahrens 	dprintf("hdr_recl called\n");
8423158Smaybee 	/*
8433158Smaybee 	 * umem calls the reclaim func when we destroy the buf cache,
8443158Smaybee 	 * which is after we do arc_fini().
8453158Smaybee 	 */
8463158Smaybee 	if (!arc_dead)
8473158Smaybee 		cv_signal(&arc_reclaim_thr_cv);
848789Sahrens }
849789Sahrens 
850789Sahrens static void
851789Sahrens buf_init(void)
852789Sahrens {
853789Sahrens 	uint64_t *ct;
8541544Seschrock 	uint64_t hsize = 1ULL << 12;
855789Sahrens 	int i, j;
856789Sahrens 
857789Sahrens 	/*
858789Sahrens 	 * The hash table is big enough to fill all of physical memory
8591544Seschrock 	 * with an average 64K block size.  The table will take up
8601544Seschrock 	 * totalmem*sizeof(void*)/64K (eg. 128KB/GB with 8-byte pointers).
861789Sahrens 	 */
8621544Seschrock 	while (hsize * 65536 < physmem * PAGESIZE)
863789Sahrens 		hsize <<= 1;
8641544Seschrock retry:
865789Sahrens 	buf_hash_table.ht_mask = hsize - 1;
8661544Seschrock 	buf_hash_table.ht_table =
8671544Seschrock 	    kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
8681544Seschrock 	if (buf_hash_table.ht_table == NULL) {
8691544Seschrock 		ASSERT(hsize > (1ULL << 8));
8701544Seschrock 		hsize >>= 1;
8711544Seschrock 		goto retry;
8721544Seschrock 	}
873789Sahrens 
874789Sahrens 	hdr_cache = kmem_cache_create("arc_buf_hdr_t", sizeof (arc_buf_hdr_t),
875789Sahrens 	    0, hdr_cons, hdr_dest, hdr_recl, NULL, NULL, 0);
876789Sahrens 	buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
8777545SMark.Maybee@Sun.COM 	    0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
878789Sahrens 
879789Sahrens 	for (i = 0; i < 256; i++)
880789Sahrens 		for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
881789Sahrens 			*ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
882789Sahrens 
883789Sahrens 	for (i = 0; i < BUF_LOCKS; i++) {
884789Sahrens 		mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
885789Sahrens 		    NULL, MUTEX_DEFAULT, NULL);
886789Sahrens 	}
887789Sahrens }
888789Sahrens 
889789Sahrens #define	ARC_MINTIME	(hz>>4) /* 62 ms */
890789Sahrens 
891789Sahrens static void
8923093Sahrens arc_cksum_verify(arc_buf_t *buf)
8933093Sahrens {
8943093Sahrens 	zio_cksum_t zc;
8953093Sahrens 
8963312Sahrens 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
8973093Sahrens 		return;
8983093Sahrens 
8993093Sahrens 	mutex_enter(&buf->b_hdr->b_freeze_lock);
9003265Sahrens 	if (buf->b_hdr->b_freeze_cksum == NULL ||
9013265Sahrens 	    (buf->b_hdr->b_flags & ARC_IO_ERROR)) {
9023093Sahrens 		mutex_exit(&buf->b_hdr->b_freeze_lock);
9033093Sahrens 		return;
9043093Sahrens 	}
9053093Sahrens 	fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
9063093Sahrens 	if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
9073093Sahrens 		panic("buffer modified while frozen!");
9083093Sahrens 	mutex_exit(&buf->b_hdr->b_freeze_lock);
9093093Sahrens }
9103093Sahrens 
9115450Sbrendan static int
9125450Sbrendan arc_cksum_equal(arc_buf_t *buf)
9135450Sbrendan {
9145450Sbrendan 	zio_cksum_t zc;
9155450Sbrendan 	int equal;
9165450Sbrendan 
9175450Sbrendan 	mutex_enter(&buf->b_hdr->b_freeze_lock);
9185450Sbrendan 	fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
9195450Sbrendan 	equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
9205450Sbrendan 	mutex_exit(&buf->b_hdr->b_freeze_lock);
9215450Sbrendan 
9225450Sbrendan 	return (equal);
9235450Sbrendan }
9245450Sbrendan 
9253093Sahrens static void
9265450Sbrendan arc_cksum_compute(arc_buf_t *buf, boolean_t force)
9273093Sahrens {
9285450Sbrendan 	if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
9293093Sahrens 		return;
9303093Sahrens 
9313093Sahrens 	mutex_enter(&buf->b_hdr->b_freeze_lock);
9323093Sahrens 	if (buf->b_hdr->b_freeze_cksum != NULL) {
9333093Sahrens 		mutex_exit(&buf->b_hdr->b_freeze_lock);
9343093Sahrens 		return;
9353093Sahrens 	}
9363093Sahrens 	buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
9373093Sahrens 	fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
9383093Sahrens 	    buf->b_hdr->b_freeze_cksum);
9393093Sahrens 	mutex_exit(&buf->b_hdr->b_freeze_lock);
9403093Sahrens }
9413093Sahrens 
9423093Sahrens void
9433093Sahrens arc_buf_thaw(arc_buf_t *buf)
9443093Sahrens {
9455450Sbrendan 	if (zfs_flags & ZFS_DEBUG_MODIFY) {
9465450Sbrendan 		if (buf->b_hdr->b_state != arc_anon)
9475450Sbrendan 			panic("modifying non-anon buffer!");
9485450Sbrendan 		if (buf->b_hdr->b_flags & ARC_IO_IN_PROGRESS)
9495450Sbrendan 			panic("modifying buffer while i/o in progress!");
9505450Sbrendan 		arc_cksum_verify(buf);
9515450Sbrendan 	}
9525450Sbrendan 
9533093Sahrens 	mutex_enter(&buf->b_hdr->b_freeze_lock);
9543093Sahrens 	if (buf->b_hdr->b_freeze_cksum != NULL) {
9553093Sahrens 		kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
9563093Sahrens 		buf->b_hdr->b_freeze_cksum = NULL;
9573093Sahrens 	}
9583093Sahrens 	mutex_exit(&buf->b_hdr->b_freeze_lock);
9593093Sahrens }
9603093Sahrens 
9613093Sahrens void
9623093Sahrens arc_buf_freeze(arc_buf_t *buf)
9633093Sahrens {
9643312Sahrens 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
9653312Sahrens 		return;
9663312Sahrens 
9673093Sahrens 	ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
9683403Sbmc 	    buf->b_hdr->b_state == arc_anon);
9695450Sbrendan 	arc_cksum_compute(buf, B_FALSE);
9703093Sahrens }
9713093Sahrens 
9723093Sahrens static void
973789Sahrens add_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
974789Sahrens {
975789Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
976789Sahrens 
977789Sahrens 	if ((refcount_add(&ab->b_refcnt, tag) == 1) &&
9783403Sbmc 	    (ab->b_state != arc_anon)) {
9793700Sek110237 		uint64_t delta = ab->b_size * ab->b_datacnt;
9804309Smaybee 		list_t *list = &ab->b_state->arcs_list[ab->b_type];
9814309Smaybee 		uint64_t *size = &ab->b_state->arcs_lsize[ab->b_type];
982789Sahrens 
9833403Sbmc 		ASSERT(!MUTEX_HELD(&ab->b_state->arcs_mtx));
9843403Sbmc 		mutex_enter(&ab->b_state->arcs_mtx);
985789Sahrens 		ASSERT(list_link_active(&ab->b_arc_node));
9864309Smaybee 		list_remove(list, ab);
9871544Seschrock 		if (GHOST_STATE(ab->b_state)) {
9881544Seschrock 			ASSERT3U(ab->b_datacnt, ==, 0);
9891544Seschrock 			ASSERT3P(ab->b_buf, ==, NULL);
9901544Seschrock 			delta = ab->b_size;
9911544Seschrock 		}
9921544Seschrock 		ASSERT(delta > 0);
9934309Smaybee 		ASSERT3U(*size, >=, delta);
9944309Smaybee 		atomic_add_64(size, -delta);
9953403Sbmc 		mutex_exit(&ab->b_state->arcs_mtx);
9967046Sahrens 		/* remove the prefetch flag if we get a reference */
9972391Smaybee 		if (ab->b_flags & ARC_PREFETCH)
9982391Smaybee 			ab->b_flags &= ~ARC_PREFETCH;
999789Sahrens 	}
1000789Sahrens }
1001789Sahrens 
1002789Sahrens static int
1003789Sahrens remove_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
1004789Sahrens {
1005789Sahrens 	int cnt;
10063403Sbmc 	arc_state_t *state = ab->b_state;
1007789Sahrens 
10083403Sbmc 	ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
10093403Sbmc 	ASSERT(!GHOST_STATE(state));
1010789Sahrens 
1011789Sahrens 	if (((cnt = refcount_remove(&ab->b_refcnt, tag)) == 0) &&
10123403Sbmc 	    (state != arc_anon)) {
10134309Smaybee 		uint64_t *size = &state->arcs_lsize[ab->b_type];
10144309Smaybee 
10153403Sbmc 		ASSERT(!MUTEX_HELD(&state->arcs_mtx));
10163403Sbmc 		mutex_enter(&state->arcs_mtx);
1017789Sahrens 		ASSERT(!list_link_active(&ab->b_arc_node));
10184309Smaybee 		list_insert_head(&state->arcs_list[ab->b_type], ab);
10191544Seschrock 		ASSERT(ab->b_datacnt > 0);
10204309Smaybee 		atomic_add_64(size, ab->b_size * ab->b_datacnt);
10213403Sbmc 		mutex_exit(&state->arcs_mtx);
1022789Sahrens 	}
1023789Sahrens 	return (cnt);
1024789Sahrens }
1025789Sahrens 
1026789Sahrens /*
1027789Sahrens  * Move the supplied buffer to the indicated state.  The mutex
1028789Sahrens  * for the buffer must be held by the caller.
1029789Sahrens  */
1030789Sahrens static void
10311544Seschrock arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *ab, kmutex_t *hash_lock)
1032789Sahrens {
10331544Seschrock 	arc_state_t *old_state = ab->b_state;
10343700Sek110237 	int64_t refcnt = refcount_count(&ab->b_refcnt);
10353700Sek110237 	uint64_t from_delta, to_delta;
1036789Sahrens 
1037789Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
10381544Seschrock 	ASSERT(new_state != old_state);
10391544Seschrock 	ASSERT(refcnt == 0 || ab->b_datacnt > 0);
10401544Seschrock 	ASSERT(ab->b_datacnt == 0 || !GHOST_STATE(new_state));
10411544Seschrock 
10421544Seschrock 	from_delta = to_delta = ab->b_datacnt * ab->b_size;
1043789Sahrens 
1044789Sahrens 	/*
1045789Sahrens 	 * If this buffer is evictable, transfer it from the
1046789Sahrens 	 * old state list to the new state list.
1047789Sahrens 	 */
10481544Seschrock 	if (refcnt == 0) {
10493403Sbmc 		if (old_state != arc_anon) {
10503403Sbmc 			int use_mutex = !MUTEX_HELD(&old_state->arcs_mtx);
10514309Smaybee 			uint64_t *size = &old_state->arcs_lsize[ab->b_type];
10521544Seschrock 
10531544Seschrock 			if (use_mutex)
10543403Sbmc 				mutex_enter(&old_state->arcs_mtx);
10551544Seschrock 
10561544Seschrock 			ASSERT(list_link_active(&ab->b_arc_node));
10574309Smaybee 			list_remove(&old_state->arcs_list[ab->b_type], ab);
1058789Sahrens 
10592391Smaybee 			/*
10602391Smaybee 			 * If prefetching out of the ghost cache,
10612391Smaybee 			 * we will have a non-null datacnt.
10622391Smaybee 			 */
10632391Smaybee 			if (GHOST_STATE(old_state) && ab->b_datacnt == 0) {
10642391Smaybee 				/* ghost elements have a ghost size */
10651544Seschrock 				ASSERT(ab->b_buf == NULL);
10661544Seschrock 				from_delta = ab->b_size;
1067789Sahrens 			}
10684309Smaybee 			ASSERT3U(*size, >=, from_delta);
10694309Smaybee 			atomic_add_64(size, -from_delta);
10701544Seschrock 
10711544Seschrock 			if (use_mutex)
10723403Sbmc 				mutex_exit(&old_state->arcs_mtx);
1073789Sahrens 		}
10743403Sbmc 		if (new_state != arc_anon) {
10753403Sbmc 			int use_mutex = !MUTEX_HELD(&new_state->arcs_mtx);
10764309Smaybee 			uint64_t *size = &new_state->arcs_lsize[ab->b_type];
1077789Sahrens 
10781544Seschrock 			if (use_mutex)
10793403Sbmc 				mutex_enter(&new_state->arcs_mtx);
10801544Seschrock 
10814309Smaybee 			list_insert_head(&new_state->arcs_list[ab->b_type], ab);
10821544Seschrock 
10831544Seschrock 			/* ghost elements have a ghost size */
10841544Seschrock 			if (GHOST_STATE(new_state)) {
10851544Seschrock 				ASSERT(ab->b_datacnt == 0);
10861544Seschrock 				ASSERT(ab->b_buf == NULL);
10871544Seschrock 				to_delta = ab->b_size;
10881544Seschrock 			}
10894309Smaybee 			atomic_add_64(size, to_delta);
10901544Seschrock 
10911544Seschrock 			if (use_mutex)
10923403Sbmc 				mutex_exit(&new_state->arcs_mtx);
1093789Sahrens 		}
1094789Sahrens 	}
1095789Sahrens 
1096789Sahrens 	ASSERT(!BUF_EMPTY(ab));
10975450Sbrendan 	if (new_state == arc_anon) {
1098789Sahrens 		buf_hash_remove(ab);
1099789Sahrens 	}
1100789Sahrens 
11011544Seschrock 	/* adjust state sizes */
11021544Seschrock 	if (to_delta)
11033403Sbmc 		atomic_add_64(&new_state->arcs_size, to_delta);
11041544Seschrock 	if (from_delta) {
11053403Sbmc 		ASSERT3U(old_state->arcs_size, >=, from_delta);
11063403Sbmc 		atomic_add_64(&old_state->arcs_size, -from_delta);
1107789Sahrens 	}
1108789Sahrens 	ab->b_state = new_state;
11095450Sbrendan 
11105450Sbrendan 	/* adjust l2arc hdr stats */
11115450Sbrendan 	if (new_state == arc_l2c_only)
11125450Sbrendan 		l2arc_hdr_stat_add();
11135450Sbrendan 	else if (old_state == arc_l2c_only)
11145450Sbrendan 		l2arc_hdr_stat_remove();
1115789Sahrens }
1116789Sahrens 
11174309Smaybee void
11188582SBrendan.Gregg@Sun.COM arc_space_consume(uint64_t space, arc_space_type_t type)
11194309Smaybee {
11208582SBrendan.Gregg@Sun.COM 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
11218582SBrendan.Gregg@Sun.COM 
11228582SBrendan.Gregg@Sun.COM 	switch (type) {
11238582SBrendan.Gregg@Sun.COM 	case ARC_SPACE_DATA:
11248582SBrendan.Gregg@Sun.COM 		ARCSTAT_INCR(arcstat_data_size, space);
11258582SBrendan.Gregg@Sun.COM 		break;
11268582SBrendan.Gregg@Sun.COM 	case ARC_SPACE_OTHER:
11278582SBrendan.Gregg@Sun.COM 		ARCSTAT_INCR(arcstat_other_size, space);
11288582SBrendan.Gregg@Sun.COM 		break;
11298582SBrendan.Gregg@Sun.COM 	case ARC_SPACE_HDRS:
11308582SBrendan.Gregg@Sun.COM 		ARCSTAT_INCR(arcstat_hdr_size, space);
11318582SBrendan.Gregg@Sun.COM 		break;
11328582SBrendan.Gregg@Sun.COM 	case ARC_SPACE_L2HDRS:
11338582SBrendan.Gregg@Sun.COM 		ARCSTAT_INCR(arcstat_l2_hdr_size, space);
11348582SBrendan.Gregg@Sun.COM 		break;
11358582SBrendan.Gregg@Sun.COM 	}
11368582SBrendan.Gregg@Sun.COM 
11374309Smaybee 	atomic_add_64(&arc_meta_used, space);
11384309Smaybee 	atomic_add_64(&arc_size, space);
11394309Smaybee }
11404309Smaybee 
11414309Smaybee void
11428582SBrendan.Gregg@Sun.COM arc_space_return(uint64_t space, arc_space_type_t type)
11434309Smaybee {
11448582SBrendan.Gregg@Sun.COM 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
11458582SBrendan.Gregg@Sun.COM 
11468582SBrendan.Gregg@Sun.COM 	switch (type) {
11478582SBrendan.Gregg@Sun.COM 	case ARC_SPACE_DATA:
11488582SBrendan.Gregg@Sun.COM 		ARCSTAT_INCR(arcstat_data_size, -space);
11498582SBrendan.Gregg@Sun.COM 		break;
11508582SBrendan.Gregg@Sun.COM 	case ARC_SPACE_OTHER:
11518582SBrendan.Gregg@Sun.COM 		ARCSTAT_INCR(arcstat_other_size, -space);
11528582SBrendan.Gregg@Sun.COM 		break;
11538582SBrendan.Gregg@Sun.COM 	case ARC_SPACE_HDRS:
11548582SBrendan.Gregg@Sun.COM 		ARCSTAT_INCR(arcstat_hdr_size, -space);
11558582SBrendan.Gregg@Sun.COM 		break;
11568582SBrendan.Gregg@Sun.COM 	case ARC_SPACE_L2HDRS:
11578582SBrendan.Gregg@Sun.COM 		ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
11588582SBrendan.Gregg@Sun.COM 		break;
11598582SBrendan.Gregg@Sun.COM 	}
11608582SBrendan.Gregg@Sun.COM 
11614309Smaybee 	ASSERT(arc_meta_used >= space);
11624309Smaybee 	if (arc_meta_max < arc_meta_used)
11634309Smaybee 		arc_meta_max = arc_meta_used;
11644309Smaybee 	atomic_add_64(&arc_meta_used, -space);
11654309Smaybee 	ASSERT(arc_size >= space);
11664309Smaybee 	atomic_add_64(&arc_size, -space);
11674309Smaybee }
11684309Smaybee 
11694309Smaybee void *
11704309Smaybee arc_data_buf_alloc(uint64_t size)
11714309Smaybee {
11724309Smaybee 	if (arc_evict_needed(ARC_BUFC_DATA))
11734309Smaybee 		cv_signal(&arc_reclaim_thr_cv);
11744309Smaybee 	atomic_add_64(&arc_size, size);
11754309Smaybee 	return (zio_data_buf_alloc(size));
11764309Smaybee }
11774309Smaybee 
11784309Smaybee void
11794309Smaybee arc_data_buf_free(void *buf, uint64_t size)
11804309Smaybee {
11814309Smaybee 	zio_data_buf_free(buf, size);
11824309Smaybee 	ASSERT(arc_size >= size);
11834309Smaybee 	atomic_add_64(&arc_size, -size);
11844309Smaybee }
11854309Smaybee 
1186789Sahrens arc_buf_t *
11873290Sjohansen arc_buf_alloc(spa_t *spa, int size, void *tag, arc_buf_contents_t type)
1188789Sahrens {
1189789Sahrens 	arc_buf_hdr_t *hdr;
1190789Sahrens 	arc_buf_t *buf;
1191789Sahrens 
1192789Sahrens 	ASSERT3U(size, >, 0);
11936245Smaybee 	hdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
1194789Sahrens 	ASSERT(BUF_EMPTY(hdr));
1195789Sahrens 	hdr->b_size = size;
11963290Sjohansen 	hdr->b_type = type;
11978636SMark.Maybee@Sun.COM 	hdr->b_spa = spa_guid(spa);
11983403Sbmc 	hdr->b_state = arc_anon;
1199789Sahrens 	hdr->b_arc_access = 0;
12006245Smaybee 	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1201789Sahrens 	buf->b_hdr = hdr;
12022688Smaybee 	buf->b_data = NULL;
12031544Seschrock 	buf->b_efunc = NULL;
12041544Seschrock 	buf->b_private = NULL;
1205789Sahrens 	buf->b_next = NULL;
1206789Sahrens 	hdr->b_buf = buf;
12072688Smaybee 	arc_get_data_buf(buf);
12081544Seschrock 	hdr->b_datacnt = 1;
1209789Sahrens 	hdr->b_flags = 0;
1210789Sahrens 	ASSERT(refcount_is_zero(&hdr->b_refcnt));
1211789Sahrens 	(void) refcount_add(&hdr->b_refcnt, tag);
1212789Sahrens 
1213789Sahrens 	return (buf);
1214789Sahrens }
1215789Sahrens 
12169412SAleksandr.Guzovskiy@Sun.COM static char *arc_onloan_tag = "onloan";
12179412SAleksandr.Guzovskiy@Sun.COM 
12189412SAleksandr.Guzovskiy@Sun.COM /*
12199412SAleksandr.Guzovskiy@Sun.COM  * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
12209412SAleksandr.Guzovskiy@Sun.COM  * flight data by arc_tempreserve_space() until they are "returned". Loaned
12219412SAleksandr.Guzovskiy@Sun.COM  * buffers must be returned to the arc before they can be used by the DMU or
12229412SAleksandr.Guzovskiy@Sun.COM  * freed.
12239412SAleksandr.Guzovskiy@Sun.COM  */
12249412SAleksandr.Guzovskiy@Sun.COM arc_buf_t *
12259412SAleksandr.Guzovskiy@Sun.COM arc_loan_buf(spa_t *spa, int size)
12269412SAleksandr.Guzovskiy@Sun.COM {
12279412SAleksandr.Guzovskiy@Sun.COM 	arc_buf_t *buf;
12289412SAleksandr.Guzovskiy@Sun.COM 
12299412SAleksandr.Guzovskiy@Sun.COM 	buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
12309412SAleksandr.Guzovskiy@Sun.COM 
12319412SAleksandr.Guzovskiy@Sun.COM 	atomic_add_64(&arc_loaned_bytes, size);
12329412SAleksandr.Guzovskiy@Sun.COM 	return (buf);
12339412SAleksandr.Guzovskiy@Sun.COM }
12349412SAleksandr.Guzovskiy@Sun.COM 
12359412SAleksandr.Guzovskiy@Sun.COM /*
12369412SAleksandr.Guzovskiy@Sun.COM  * Return a loaned arc buffer to the arc.
12379412SAleksandr.Guzovskiy@Sun.COM  */
12389412SAleksandr.Guzovskiy@Sun.COM void
12399412SAleksandr.Guzovskiy@Sun.COM arc_return_buf(arc_buf_t *buf, void *tag)
12409412SAleksandr.Guzovskiy@Sun.COM {
12419412SAleksandr.Guzovskiy@Sun.COM 	arc_buf_hdr_t *hdr = buf->b_hdr;
12429412SAleksandr.Guzovskiy@Sun.COM 
12439412SAleksandr.Guzovskiy@Sun.COM 	ASSERT(hdr->b_state == arc_anon);
12449412SAleksandr.Guzovskiy@Sun.COM 	ASSERT(buf->b_data != NULL);
12459412SAleksandr.Guzovskiy@Sun.COM 	VERIFY(refcount_remove(&hdr->b_refcnt, arc_onloan_tag) == 0);
12469412SAleksandr.Guzovskiy@Sun.COM 	VERIFY(refcount_add(&hdr->b_refcnt, tag) == 1);
12479412SAleksandr.Guzovskiy@Sun.COM 
12489412SAleksandr.Guzovskiy@Sun.COM 	atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
12499412SAleksandr.Guzovskiy@Sun.COM }
12509412SAleksandr.Guzovskiy@Sun.COM 
12512688Smaybee static arc_buf_t *
12522688Smaybee arc_buf_clone(arc_buf_t *from)
12531544Seschrock {
12542688Smaybee 	arc_buf_t *buf;
12552688Smaybee 	arc_buf_hdr_t *hdr = from->b_hdr;
12562688Smaybee 	uint64_t size = hdr->b_size;
12571544Seschrock 
12586245Smaybee 	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
12592688Smaybee 	buf->b_hdr = hdr;
12602688Smaybee 	buf->b_data = NULL;
12612688Smaybee 	buf->b_efunc = NULL;
12622688Smaybee 	buf->b_private = NULL;
12632688Smaybee 	buf->b_next = hdr->b_buf;
12642688Smaybee 	hdr->b_buf = buf;
12652688Smaybee 	arc_get_data_buf(buf);
12662688Smaybee 	bcopy(from->b_data, buf->b_data, size);
12672688Smaybee 	hdr->b_datacnt += 1;
12682688Smaybee 	return (buf);
12691544Seschrock }
12701544Seschrock 
12711544Seschrock void
12721544Seschrock arc_buf_add_ref(arc_buf_t *buf, void* tag)
12731544Seschrock {
12742887Smaybee 	arc_buf_hdr_t *hdr;
12751544Seschrock 	kmutex_t *hash_lock;
12761544Seschrock 
12772724Smaybee 	/*
12787545SMark.Maybee@Sun.COM 	 * Check to see if this buffer is evicted.  Callers
12797545SMark.Maybee@Sun.COM 	 * must verify b_data != NULL to know if the add_ref
12807545SMark.Maybee@Sun.COM 	 * was successful.
12812724Smaybee 	 */
12827545SMark.Maybee@Sun.COM 	rw_enter(&buf->b_lock, RW_READER);
12837545SMark.Maybee@Sun.COM 	if (buf->b_data == NULL) {
12847545SMark.Maybee@Sun.COM 		rw_exit(&buf->b_lock);
12852724Smaybee 		return;
12862887Smaybee 	}
12877545SMark.Maybee@Sun.COM 	hdr = buf->b_hdr;
12887545SMark.Maybee@Sun.COM 	ASSERT(hdr != NULL);
12892887Smaybee 	hash_lock = HDR_LOCK(hdr);
12902724Smaybee 	mutex_enter(hash_lock);
12917545SMark.Maybee@Sun.COM 	rw_exit(&buf->b_lock);
12927545SMark.Maybee@Sun.COM 
12933403Sbmc 	ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
12941544Seschrock 	add_reference(hdr, hash_lock, tag);
12958582SBrendan.Gregg@Sun.COM 	DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
12962688Smaybee 	arc_access(hdr, hash_lock);
12972688Smaybee 	mutex_exit(hash_lock);
12983403Sbmc 	ARCSTAT_BUMP(arcstat_hits);
12993403Sbmc 	ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
13003403Sbmc 	    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
13013403Sbmc 	    data, metadata, hits);
13021544Seschrock }
13031544Seschrock 
13045450Sbrendan /*
13055450Sbrendan  * Free the arc data buffer.  If it is an l2arc write in progress,
13065450Sbrendan  * the buffer is placed on l2arc_free_on_write to be freed later.
13075450Sbrendan  */
13085450Sbrendan static void
13095450Sbrendan arc_buf_data_free(arc_buf_hdr_t *hdr, void (*free_func)(void *, size_t),
13105450Sbrendan     void *data, size_t size)
13115450Sbrendan {
13125450Sbrendan 	if (HDR_L2_WRITING(hdr)) {
13135450Sbrendan 		l2arc_data_free_t *df;
13145450Sbrendan 		df = kmem_alloc(sizeof (l2arc_data_free_t), KM_SLEEP);
13155450Sbrendan 		df->l2df_data = data;
13165450Sbrendan 		df->l2df_size = size;
13175450Sbrendan 		df->l2df_func = free_func;
13185450Sbrendan 		mutex_enter(&l2arc_free_on_write_mtx);
13195450Sbrendan 		list_insert_head(l2arc_free_on_write, df);
13205450Sbrendan 		mutex_exit(&l2arc_free_on_write_mtx);
13215450Sbrendan 		ARCSTAT_BUMP(arcstat_l2_free_on_write);
13225450Sbrendan 	} else {
13235450Sbrendan 		free_func(data, size);
13245450Sbrendan 	}
13255450Sbrendan }
13265450Sbrendan 
1327789Sahrens static void
13282688Smaybee arc_buf_destroy(arc_buf_t *buf, boolean_t recycle, boolean_t all)
13291544Seschrock {
13301544Seschrock 	arc_buf_t **bufp;
13311544Seschrock 
13321544Seschrock 	/* free up data associated with the buf */
13331544Seschrock 	if (buf->b_data) {
13341544Seschrock 		arc_state_t *state = buf->b_hdr->b_state;
13351544Seschrock 		uint64_t size = buf->b_hdr->b_size;
13363290Sjohansen 		arc_buf_contents_t type = buf->b_hdr->b_type;
13371544Seschrock 
13383093Sahrens 		arc_cksum_verify(buf);
13392688Smaybee 		if (!recycle) {
13403290Sjohansen 			if (type == ARC_BUFC_METADATA) {
13415450Sbrendan 				arc_buf_data_free(buf->b_hdr, zio_buf_free,
13425450Sbrendan 				    buf->b_data, size);
13438582SBrendan.Gregg@Sun.COM 				arc_space_return(size, ARC_SPACE_DATA);
13443290Sjohansen 			} else {
13453290Sjohansen 				ASSERT(type == ARC_BUFC_DATA);
13465450Sbrendan 				arc_buf_data_free(buf->b_hdr,
13475450Sbrendan 				    zio_data_buf_free, buf->b_data, size);
13488582SBrendan.Gregg@Sun.COM 				ARCSTAT_INCR(arcstat_data_size, -size);
13494309Smaybee 				atomic_add_64(&arc_size, -size);
13503290Sjohansen 			}
13512688Smaybee 		}
13521544Seschrock 		if (list_link_active(&buf->b_hdr->b_arc_node)) {
13534309Smaybee 			uint64_t *cnt = &state->arcs_lsize[type];
13544309Smaybee 
13551544Seschrock 			ASSERT(refcount_is_zero(&buf->b_hdr->b_refcnt));
13563403Sbmc 			ASSERT(state != arc_anon);
13574309Smaybee 
13584309Smaybee 			ASSERT3U(*cnt, >=, size);
13594309Smaybee 			atomic_add_64(cnt, -size);
13601544Seschrock 		}
13613403Sbmc 		ASSERT3U(state->arcs_size, >=, size);
13623403Sbmc 		atomic_add_64(&state->arcs_size, -size);
13631544Seschrock 		buf->b_data = NULL;
13641544Seschrock 		ASSERT(buf->b_hdr->b_datacnt > 0);
13651544Seschrock 		buf->b_hdr->b_datacnt -= 1;
13661544Seschrock 	}
13671544Seschrock 
13681544Seschrock 	/* only remove the buf if requested */
13691544Seschrock 	if (!all)
13701544Seschrock 		return;
13711544Seschrock 
13721544Seschrock 	/* remove the buf from the hdr list */
13731544Seschrock 	for (bufp = &buf->b_hdr->b_buf; *bufp != buf; bufp = &(*bufp)->b_next)
13741544Seschrock 		continue;
13751544Seschrock 	*bufp = buf->b_next;
13761544Seschrock 
13771544Seschrock 	ASSERT(buf->b_efunc == NULL);
13781544Seschrock 
13791544Seschrock 	/* clean up the buf */
13801544Seschrock 	buf->b_hdr = NULL;
13811544Seschrock 	kmem_cache_free(buf_cache, buf);
13821544Seschrock }
13831544Seschrock 
13841544Seschrock static void
13851544Seschrock arc_hdr_destroy(arc_buf_hdr_t *hdr)
1386789Sahrens {
1387789Sahrens 	ASSERT(refcount_is_zero(&hdr->b_refcnt));
13883403Sbmc 	ASSERT3P(hdr->b_state, ==, arc_anon);
13891544Seschrock 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
13907046Sahrens 	ASSERT(!(hdr->b_flags & ARC_STORED));
1391789Sahrens 
13925450Sbrendan 	if (hdr->b_l2hdr != NULL) {
13935450Sbrendan 		if (!MUTEX_HELD(&l2arc_buflist_mtx)) {
13945450Sbrendan 			/*
13955450Sbrendan 			 * To prevent arc_free() and l2arc_evict() from
13965450Sbrendan 			 * attempting to free the same buffer at the same time,
13975450Sbrendan 			 * a FREE_IN_PROGRESS flag is given to arc_free() to
13985450Sbrendan 			 * give it priority.  l2arc_evict() can't destroy this
13995450Sbrendan 			 * header while we are waiting on l2arc_buflist_mtx.
14007361SBrendan.Gregg@Sun.COM 			 *
14017361SBrendan.Gregg@Sun.COM 			 * The hdr may be removed from l2ad_buflist before we
14027361SBrendan.Gregg@Sun.COM 			 * grab l2arc_buflist_mtx, so b_l2hdr is rechecked.
14035450Sbrendan 			 */
14045450Sbrendan 			mutex_enter(&l2arc_buflist_mtx);
14057361SBrendan.Gregg@Sun.COM 			if (hdr->b_l2hdr != NULL) {
14067361SBrendan.Gregg@Sun.COM 				list_remove(hdr->b_l2hdr->b_dev->l2ad_buflist,
14077361SBrendan.Gregg@Sun.COM 				    hdr);
14087361SBrendan.Gregg@Sun.COM 			}
14095450Sbrendan 			mutex_exit(&l2arc_buflist_mtx);
14105450Sbrendan 		} else {
14115450Sbrendan 			list_remove(hdr->b_l2hdr->b_dev->l2ad_buflist, hdr);
14125450Sbrendan 		}
14135450Sbrendan 		ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
14145450Sbrendan 		kmem_free(hdr->b_l2hdr, sizeof (l2arc_buf_hdr_t));
14155450Sbrendan 		if (hdr->b_state == arc_l2c_only)
14165450Sbrendan 			l2arc_hdr_stat_remove();
14175450Sbrendan 		hdr->b_l2hdr = NULL;
14185450Sbrendan 	}
14195450Sbrendan 
1420789Sahrens 	if (!BUF_EMPTY(hdr)) {
14211544Seschrock 		ASSERT(!HDR_IN_HASH_TABLE(hdr));
1422789Sahrens 		bzero(&hdr->b_dva, sizeof (dva_t));
1423789Sahrens 		hdr->b_birth = 0;
1424789Sahrens 		hdr->b_cksum0 = 0;
1425789Sahrens 	}
14261544Seschrock 	while (hdr->b_buf) {
1427789Sahrens 		arc_buf_t *buf = hdr->b_buf;
1428789Sahrens 
14291544Seschrock 		if (buf->b_efunc) {
14301544Seschrock 			mutex_enter(&arc_eviction_mtx);
14317545SMark.Maybee@Sun.COM 			rw_enter(&buf->b_lock, RW_WRITER);
14321544Seschrock 			ASSERT(buf->b_hdr != NULL);
14332688Smaybee 			arc_buf_destroy(hdr->b_buf, FALSE, FALSE);
14341544Seschrock 			hdr->b_buf = buf->b_next;
14352887Smaybee 			buf->b_hdr = &arc_eviction_hdr;
14361544Seschrock 			buf->b_next = arc_eviction_list;
14371544Seschrock 			arc_eviction_list = buf;
14387545SMark.Maybee@Sun.COM 			rw_exit(&buf->b_lock);
14391544Seschrock 			mutex_exit(&arc_eviction_mtx);
14401544Seschrock 		} else {
14412688Smaybee 			arc_buf_destroy(hdr->b_buf, FALSE, TRUE);
14421544Seschrock 		}
1443789Sahrens 	}
14443093Sahrens 	if (hdr->b_freeze_cksum != NULL) {
14453093Sahrens 		kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
14463093Sahrens 		hdr->b_freeze_cksum = NULL;
14473093Sahrens 	}
14481544Seschrock 
1449789Sahrens 	ASSERT(!list_link_active(&hdr->b_arc_node));
1450789Sahrens 	ASSERT3P(hdr->b_hash_next, ==, NULL);
1451789Sahrens 	ASSERT3P(hdr->b_acb, ==, NULL);
1452789Sahrens 	kmem_cache_free(hdr_cache, hdr);
1453789Sahrens }
1454789Sahrens 
1455789Sahrens void
1456789Sahrens arc_buf_free(arc_buf_t *buf, void *tag)
1457789Sahrens {
1458789Sahrens 	arc_buf_hdr_t *hdr = buf->b_hdr;
14593403Sbmc 	int hashed = hdr->b_state != arc_anon;
14601544Seschrock 
14611544Seschrock 	ASSERT(buf->b_efunc == NULL);
14621544Seschrock 	ASSERT(buf->b_data != NULL);
14631544Seschrock 
14641544Seschrock 	if (hashed) {
14651544Seschrock 		kmutex_t *hash_lock = HDR_LOCK(hdr);
14661544Seschrock 
14671544Seschrock 		mutex_enter(hash_lock);
14681544Seschrock 		(void) remove_reference(hdr, hash_lock, tag);
14691544Seschrock 		if (hdr->b_datacnt > 1)
14702688Smaybee 			arc_buf_destroy(buf, FALSE, TRUE);
14711544Seschrock 		else
14721544Seschrock 			hdr->b_flags |= ARC_BUF_AVAILABLE;
14731544Seschrock 		mutex_exit(hash_lock);
14741544Seschrock 	} else if (HDR_IO_IN_PROGRESS(hdr)) {
14751544Seschrock 		int destroy_hdr;
14761544Seschrock 		/*
14771544Seschrock 		 * We are in the middle of an async write.  Don't destroy
14781544Seschrock 		 * this buffer unless the write completes before we finish
14791544Seschrock 		 * decrementing the reference count.
14801544Seschrock 		 */
14811544Seschrock 		mutex_enter(&arc_eviction_mtx);
14821544Seschrock 		(void) remove_reference(hdr, NULL, tag);
14831544Seschrock 		ASSERT(refcount_is_zero(&hdr->b_refcnt));
14841544Seschrock 		destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
14851544Seschrock 		mutex_exit(&arc_eviction_mtx);
14861544Seschrock 		if (destroy_hdr)
14871544Seschrock 			arc_hdr_destroy(hdr);
14881544Seschrock 	} else {
14891544Seschrock 		if (remove_reference(hdr, NULL, tag) > 0) {
14901544Seschrock 			ASSERT(HDR_IO_ERROR(hdr));
14912688Smaybee 			arc_buf_destroy(buf, FALSE, TRUE);
14921544Seschrock 		} else {
14931544Seschrock 			arc_hdr_destroy(hdr);
14941544Seschrock 		}
14951544Seschrock 	}
14961544Seschrock }
14971544Seschrock 
14981544Seschrock int
14991544Seschrock arc_buf_remove_ref(arc_buf_t *buf, void* tag)
15001544Seschrock {
15011544Seschrock 	arc_buf_hdr_t *hdr = buf->b_hdr;
1502789Sahrens 	kmutex_t *hash_lock = HDR_LOCK(hdr);
15031544Seschrock 	int no_callback = (buf->b_efunc == NULL);
15041544Seschrock 
15053403Sbmc 	if (hdr->b_state == arc_anon) {
15061544Seschrock 		arc_buf_free(buf, tag);
15071544Seschrock 		return (no_callback);
15081544Seschrock 	}
1509789Sahrens 
1510789Sahrens 	mutex_enter(hash_lock);
15113403Sbmc 	ASSERT(hdr->b_state != arc_anon);
15121544Seschrock 	ASSERT(buf->b_data != NULL);
1513789Sahrens 
15141544Seschrock 	(void) remove_reference(hdr, hash_lock, tag);
15151544Seschrock 	if (hdr->b_datacnt > 1) {
15161544Seschrock 		if (no_callback)
15172688Smaybee 			arc_buf_destroy(buf, FALSE, TRUE);
15181544Seschrock 	} else if (no_callback) {
15191544Seschrock 		ASSERT(hdr->b_buf == buf && buf->b_next == NULL);
15201544Seschrock 		hdr->b_flags |= ARC_BUF_AVAILABLE;
1521789Sahrens 	}
15221544Seschrock 	ASSERT(no_callback || hdr->b_datacnt > 1 ||
15231544Seschrock 	    refcount_is_zero(&hdr->b_refcnt));
1524789Sahrens 	mutex_exit(hash_lock);
15251544Seschrock 	return (no_callback);
1526789Sahrens }
1527789Sahrens 
1528789Sahrens int
1529789Sahrens arc_buf_size(arc_buf_t *buf)
1530789Sahrens {
1531789Sahrens 	return (buf->b_hdr->b_size);
1532789Sahrens }
1533789Sahrens 
1534789Sahrens /*
1535789Sahrens  * Evict buffers from list until we've removed the specified number of
1536789Sahrens  * bytes.  Move the removed buffers to the appropriate evict state.
15372688Smaybee  * If the recycle flag is set, then attempt to "recycle" a buffer:
15382688Smaybee  * - look for a buffer to evict that is `bytes' long.
15392688Smaybee  * - return the data block from this buffer rather than freeing it.
15402688Smaybee  * This flag is used by callers that are trying to make space for a
15412688Smaybee  * new buffer in a full arc cache.
15425642Smaybee  *
15435642Smaybee  * This function makes a "best effort".  It skips over any buffers
15445642Smaybee  * it can't get a hash_lock on, and so may not catch all candidates.
15455642Smaybee  * It may also return without evicting as much space as requested.
1546789Sahrens  */
15472688Smaybee static void *
15488636SMark.Maybee@Sun.COM arc_evict(arc_state_t *state, uint64_t spa, int64_t bytes, boolean_t recycle,
15493290Sjohansen     arc_buf_contents_t type)
1550789Sahrens {
1551789Sahrens 	arc_state_t *evicted_state;
15522688Smaybee 	uint64_t bytes_evicted = 0, skipped = 0, missed = 0;
15532918Smaybee 	arc_buf_hdr_t *ab, *ab_prev = NULL;
15544309Smaybee 	list_t *list = &state->arcs_list[type];
1555789Sahrens 	kmutex_t *hash_lock;
15562688Smaybee 	boolean_t have_lock;
15572918Smaybee 	void *stolen = NULL;
1558789Sahrens 
15593403Sbmc 	ASSERT(state == arc_mru || state == arc_mfu);
1560789Sahrens 
15613403Sbmc 	evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
1562789Sahrens 
15633403Sbmc 	mutex_enter(&state->arcs_mtx);
15643403Sbmc 	mutex_enter(&evicted_state->arcs_mtx);
1565789Sahrens 
15664309Smaybee 	for (ab = list_tail(list); ab; ab = ab_prev) {
15674309Smaybee 		ab_prev = list_prev(list, ab);
15682391Smaybee 		/* prefetch buffers have a minimum lifespan */
15692688Smaybee 		if (HDR_IO_IN_PROGRESS(ab) ||
15705642Smaybee 		    (spa && ab->b_spa != spa) ||
15712688Smaybee 		    (ab->b_flags & (ARC_PREFETCH|ARC_INDIRECT) &&
15722688Smaybee 		    lbolt - ab->b_arc_access < arc_min_prefetch_lifespan)) {
15732391Smaybee 			skipped++;
15742391Smaybee 			continue;
15752391Smaybee 		}
15762918Smaybee 		/* "lookahead" for better eviction candidate */
15772918Smaybee 		if (recycle && ab->b_size != bytes &&
15782918Smaybee 		    ab_prev && ab_prev->b_size == bytes)
15792688Smaybee 			continue;
1580789Sahrens 		hash_lock = HDR_LOCK(ab);
15812688Smaybee 		have_lock = MUTEX_HELD(hash_lock);
15822688Smaybee 		if (have_lock || mutex_tryenter(hash_lock)) {
1583789Sahrens 			ASSERT3U(refcount_count(&ab->b_refcnt), ==, 0);
15841544Seschrock 			ASSERT(ab->b_datacnt > 0);
15851544Seschrock 			while (ab->b_buf) {
15861544Seschrock 				arc_buf_t *buf = ab->b_buf;
15877545SMark.Maybee@Sun.COM 				if (!rw_tryenter(&buf->b_lock, RW_WRITER)) {
15887545SMark.Maybee@Sun.COM 					missed += 1;
15897545SMark.Maybee@Sun.COM 					break;
15907545SMark.Maybee@Sun.COM 				}
15912688Smaybee 				if (buf->b_data) {
15921544Seschrock 					bytes_evicted += ab->b_size;
15933290Sjohansen 					if (recycle && ab->b_type == type &&
15945450Sbrendan 					    ab->b_size == bytes &&
15955450Sbrendan 					    !HDR_L2_WRITING(ab)) {
15962918Smaybee 						stolen = buf->b_data;
15972918Smaybee 						recycle = FALSE;
15982918Smaybee 					}
15992688Smaybee 				}
16001544Seschrock 				if (buf->b_efunc) {
16011544Seschrock 					mutex_enter(&arc_eviction_mtx);
16022918Smaybee 					arc_buf_destroy(buf,
16032918Smaybee 					    buf->b_data == stolen, FALSE);
16041544Seschrock 					ab->b_buf = buf->b_next;
16052887Smaybee 					buf->b_hdr = &arc_eviction_hdr;
16061544Seschrock 					buf->b_next = arc_eviction_list;
16071544Seschrock 					arc_eviction_list = buf;
16081544Seschrock 					mutex_exit(&arc_eviction_mtx);
16097545SMark.Maybee@Sun.COM 					rw_exit(&buf->b_lock);
16101544Seschrock 				} else {
16117545SMark.Maybee@Sun.COM 					rw_exit(&buf->b_lock);
16122918Smaybee 					arc_buf_destroy(buf,
16132918Smaybee 					    buf->b_data == stolen, TRUE);
16141544Seschrock 				}
16151544Seschrock 			}
161610357SBrendan.Gregg@Sun.COM 
161710357SBrendan.Gregg@Sun.COM 			if (ab->b_l2hdr) {
161810357SBrendan.Gregg@Sun.COM 				ARCSTAT_INCR(arcstat_evict_l2_cached,
161910357SBrendan.Gregg@Sun.COM 				    ab->b_size);
162010357SBrendan.Gregg@Sun.COM 			} else {
162110357SBrendan.Gregg@Sun.COM 				if (l2arc_write_eligible(ab->b_spa, ab)) {
162210357SBrendan.Gregg@Sun.COM 					ARCSTAT_INCR(arcstat_evict_l2_eligible,
162310357SBrendan.Gregg@Sun.COM 					    ab->b_size);
162410357SBrendan.Gregg@Sun.COM 				} else {
162510357SBrendan.Gregg@Sun.COM 					ARCSTAT_INCR(
162610357SBrendan.Gregg@Sun.COM 					    arcstat_evict_l2_ineligible,
162710357SBrendan.Gregg@Sun.COM 					    ab->b_size);
162810357SBrendan.Gregg@Sun.COM 				}
162910357SBrendan.Gregg@Sun.COM 			}
163010357SBrendan.Gregg@Sun.COM 
16317545SMark.Maybee@Sun.COM 			if (ab->b_datacnt == 0) {
16327545SMark.Maybee@Sun.COM 				arc_change_state(evicted_state, ab, hash_lock);
16337545SMark.Maybee@Sun.COM 				ASSERT(HDR_IN_HASH_TABLE(ab));
16347545SMark.Maybee@Sun.COM 				ab->b_flags |= ARC_IN_HASH_TABLE;
16357545SMark.Maybee@Sun.COM 				ab->b_flags &= ~ARC_BUF_AVAILABLE;
16367545SMark.Maybee@Sun.COM 				DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, ab);
16377545SMark.Maybee@Sun.COM 			}
16382688Smaybee 			if (!have_lock)
16392688Smaybee 				mutex_exit(hash_lock);
16401544Seschrock 			if (bytes >= 0 && bytes_evicted >= bytes)
1641789Sahrens 				break;
1642789Sahrens 		} else {
16432688Smaybee 			missed += 1;
1644789Sahrens 		}
1645789Sahrens 	}
16463403Sbmc 
16473403Sbmc 	mutex_exit(&evicted_state->arcs_mtx);
16483403Sbmc 	mutex_exit(&state->arcs_mtx);
1649789Sahrens 
1650789Sahrens 	if (bytes_evicted < bytes)
1651789Sahrens 		dprintf("only evicted %lld bytes from %x",
1652789Sahrens 		    (longlong_t)bytes_evicted, state);
1653789Sahrens 
16542688Smaybee 	if (skipped)
16553403Sbmc 		ARCSTAT_INCR(arcstat_evict_skip, skipped);
16563403Sbmc 
16572688Smaybee 	if (missed)
16583403Sbmc 		ARCSTAT_INCR(arcstat_mutex_miss, missed);
16593403Sbmc 
16604709Smaybee 	/*
16614709Smaybee 	 * We have just evicted some date into the ghost state, make
16624709Smaybee 	 * sure we also adjust the ghost state size if necessary.
16634709Smaybee 	 */
16644709Smaybee 	if (arc_no_grow &&
16654709Smaybee 	    arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size > arc_c) {
16664709Smaybee 		int64_t mru_over = arc_anon->arcs_size + arc_mru->arcs_size +
16674709Smaybee 		    arc_mru_ghost->arcs_size - arc_c;
16684709Smaybee 
16694709Smaybee 		if (mru_over > 0 && arc_mru_ghost->arcs_lsize[type] > 0) {
16704709Smaybee 			int64_t todelete =
16714709Smaybee 			    MIN(arc_mru_ghost->arcs_lsize[type], mru_over);
16725642Smaybee 			arc_evict_ghost(arc_mru_ghost, NULL, todelete);
16734709Smaybee 		} else if (arc_mfu_ghost->arcs_lsize[type] > 0) {
16744709Smaybee 			int64_t todelete = MIN(arc_mfu_ghost->arcs_lsize[type],
16754709Smaybee 			    arc_mru_ghost->arcs_size +
16764709Smaybee 			    arc_mfu_ghost->arcs_size - arc_c);
16775642Smaybee 			arc_evict_ghost(arc_mfu_ghost, NULL, todelete);
16784709Smaybee 		}
16794709Smaybee 	}
16804709Smaybee 
16812918Smaybee 	return (stolen);
1682789Sahrens }
1683789Sahrens 
1684789Sahrens /*
1685789Sahrens  * Remove buffers from list until we've removed the specified number of
1686789Sahrens  * bytes.  Destroy the buffers that are removed.
1687789Sahrens  */
1688789Sahrens static void
16898636SMark.Maybee@Sun.COM arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes)
1690789Sahrens {
1691789Sahrens 	arc_buf_hdr_t *ab, *ab_prev;
16924309Smaybee 	list_t *list = &state->arcs_list[ARC_BUFC_DATA];
1693789Sahrens 	kmutex_t *hash_lock;
16941544Seschrock 	uint64_t bytes_deleted = 0;
16953700Sek110237 	uint64_t bufs_skipped = 0;
1696789Sahrens 
16971544Seschrock 	ASSERT(GHOST_STATE(state));
1698789Sahrens top:
16993403Sbmc 	mutex_enter(&state->arcs_mtx);
17004309Smaybee 	for (ab = list_tail(list); ab; ab = ab_prev) {
17014309Smaybee 		ab_prev = list_prev(list, ab);
17025642Smaybee 		if (spa && ab->b_spa != spa)
17035642Smaybee 			continue;
1704789Sahrens 		hash_lock = HDR_LOCK(ab);
1705789Sahrens 		if (mutex_tryenter(hash_lock)) {
17062391Smaybee 			ASSERT(!HDR_IO_IN_PROGRESS(ab));
17071544Seschrock 			ASSERT(ab->b_buf == NULL);
17083403Sbmc 			ARCSTAT_BUMP(arcstat_deleted);
17091544Seschrock 			bytes_deleted += ab->b_size;
17105450Sbrendan 
17115450Sbrendan 			if (ab->b_l2hdr != NULL) {
17125450Sbrendan 				/*
17135450Sbrendan 				 * This buffer is cached on the 2nd Level ARC;
17145450Sbrendan 				 * don't destroy the header.
17155450Sbrendan 				 */
17165450Sbrendan 				arc_change_state(arc_l2c_only, ab, hash_lock);
17175450Sbrendan 				mutex_exit(hash_lock);
17185450Sbrendan 			} else {
17195450Sbrendan 				arc_change_state(arc_anon, ab, hash_lock);
17205450Sbrendan 				mutex_exit(hash_lock);
17215450Sbrendan 				arc_hdr_destroy(ab);
17225450Sbrendan 			}
17235450Sbrendan 
1724789Sahrens 			DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, ab);
1725789Sahrens 			if (bytes >= 0 && bytes_deleted >= bytes)
1726789Sahrens 				break;
1727789Sahrens 		} else {
1728789Sahrens 			if (bytes < 0) {
17293403Sbmc 				mutex_exit(&state->arcs_mtx);
1730789Sahrens 				mutex_enter(hash_lock);
1731789Sahrens 				mutex_exit(hash_lock);
1732789Sahrens 				goto top;
1733789Sahrens 			}
1734789Sahrens 			bufs_skipped += 1;
1735789Sahrens 		}
1736789Sahrens 	}
17373403Sbmc 	mutex_exit(&state->arcs_mtx);
1738789Sahrens 
17394309Smaybee 	if (list == &state->arcs_list[ARC_BUFC_DATA] &&
17404309Smaybee 	    (bytes < 0 || bytes_deleted < bytes)) {
17414309Smaybee 		list = &state->arcs_list[ARC_BUFC_METADATA];
17424309Smaybee 		goto top;
17434309Smaybee 	}
17444309Smaybee 
1745789Sahrens 	if (bufs_skipped) {
17463403Sbmc 		ARCSTAT_INCR(arcstat_mutex_miss, bufs_skipped);
1747789Sahrens 		ASSERT(bytes >= 0);
1748789Sahrens 	}
1749789Sahrens 
1750789Sahrens 	if (bytes_deleted < bytes)
1751789Sahrens 		dprintf("only deleted %lld bytes from %p",
1752789Sahrens 		    (longlong_t)bytes_deleted, state);
1753789Sahrens }
1754789Sahrens 
1755789Sahrens static void
1756789Sahrens arc_adjust(void)
1757789Sahrens {
17588582SBrendan.Gregg@Sun.COM 	int64_t adjustment, delta;
17598582SBrendan.Gregg@Sun.COM 
17608582SBrendan.Gregg@Sun.COM 	/*
17618582SBrendan.Gregg@Sun.COM 	 * Adjust MRU size
17628582SBrendan.Gregg@Sun.COM 	 */
17638582SBrendan.Gregg@Sun.COM 
17648582SBrendan.Gregg@Sun.COM 	adjustment = MIN(arc_size - arc_c,
17658582SBrendan.Gregg@Sun.COM 	    arc_anon->arcs_size + arc_mru->arcs_size + arc_meta_used - arc_p);
17668582SBrendan.Gregg@Sun.COM 
17678582SBrendan.Gregg@Sun.COM 	if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_DATA] > 0) {
17688582SBrendan.Gregg@Sun.COM 		delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_DATA], adjustment);
17698582SBrendan.Gregg@Sun.COM 		(void) arc_evict(arc_mru, NULL, delta, FALSE, ARC_BUFC_DATA);
17708582SBrendan.Gregg@Sun.COM 		adjustment -= delta;
17714309Smaybee 	}
17724309Smaybee 
17738582SBrendan.Gregg@Sun.COM 	if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_METADATA] > 0) {
17748582SBrendan.Gregg@Sun.COM 		delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_METADATA], adjustment);
17758582SBrendan.Gregg@Sun.COM 		(void) arc_evict(arc_mru, NULL, delta, FALSE,
17765642Smaybee 		    ARC_BUFC_METADATA);
1777789Sahrens 	}
1778789Sahrens 
17798582SBrendan.Gregg@Sun.COM 	/*
17808582SBrendan.Gregg@Sun.COM 	 * Adjust MFU size
17818582SBrendan.Gregg@Sun.COM 	 */
17828582SBrendan.Gregg@Sun.COM 
17838582SBrendan.Gregg@Sun.COM 	adjustment = arc_size - arc_c;
17848582SBrendan.Gregg@Sun.COM 
17858582SBrendan.Gregg@Sun.COM 	if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_DATA] > 0) {
17868582SBrendan.Gregg@Sun.COM 		delta = MIN(adjustment, arc_mfu->arcs_lsize[ARC_BUFC_DATA]);
17878582SBrendan.Gregg@Sun.COM 		(void) arc_evict(arc_mfu, NULL, delta, FALSE, ARC_BUFC_DATA);
17888582SBrendan.Gregg@Sun.COM 		adjustment -= delta;
17898582SBrendan.Gregg@Sun.COM 	}
17908582SBrendan.Gregg@Sun.COM 
17918582SBrendan.Gregg@Sun.COM 	if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_METADATA] > 0) {
17928582SBrendan.Gregg@Sun.COM 		int64_t delta = MIN(adjustment,
17938582SBrendan.Gregg@Sun.COM 		    arc_mfu->arcs_lsize[ARC_BUFC_METADATA]);
17948582SBrendan.Gregg@Sun.COM 		(void) arc_evict(arc_mfu, NULL, delta, FALSE,
17958582SBrendan.Gregg@Sun.COM 		    ARC_BUFC_METADATA);
17968582SBrendan.Gregg@Sun.COM 	}
17978582SBrendan.Gregg@Sun.COM 
17988582SBrendan.Gregg@Sun.COM 	/*
17998582SBrendan.Gregg@Sun.COM 	 * Adjust ghost lists
18008582SBrendan.Gregg@Sun.COM 	 */
18018582SBrendan.Gregg@Sun.COM 
18028582SBrendan.Gregg@Sun.COM 	adjustment = arc_mru->arcs_size + arc_mru_ghost->arcs_size - arc_c;
18038582SBrendan.Gregg@Sun.COM 
18048582SBrendan.Gregg@Sun.COM 	if (adjustment > 0 && arc_mru_ghost->arcs_size > 0) {
18058582SBrendan.Gregg@Sun.COM 		delta = MIN(arc_mru_ghost->arcs_size, adjustment);
18068582SBrendan.Gregg@Sun.COM 		arc_evict_ghost(arc_mru_ghost, NULL, delta);
18078582SBrendan.Gregg@Sun.COM 	}
18088582SBrendan.Gregg@Sun.COM 
18098582SBrendan.Gregg@Sun.COM 	adjustment =
18108582SBrendan.Gregg@Sun.COM 	    arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size - arc_c;
18118582SBrendan.Gregg@Sun.COM 
18128582SBrendan.Gregg@Sun.COM 	if (adjustment > 0 && arc_mfu_ghost->arcs_size > 0) {
18138582SBrendan.Gregg@Sun.COM 		delta = MIN(arc_mfu_ghost->arcs_size, adjustment);
18148582SBrendan.Gregg@Sun.COM 		arc_evict_ghost(arc_mfu_ghost, NULL, delta);
1815789Sahrens 	}
1816789Sahrens }
1817789Sahrens 
18181544Seschrock static void
18191544Seschrock arc_do_user_evicts(void)
18201544Seschrock {
18211544Seschrock 	mutex_enter(&arc_eviction_mtx);
18221544Seschrock 	while (arc_eviction_list != NULL) {
18231544Seschrock 		arc_buf_t *buf = arc_eviction_list;
18241544Seschrock 		arc_eviction_list = buf->b_next;
18257545SMark.Maybee@Sun.COM 		rw_enter(&buf->b_lock, RW_WRITER);
18261544Seschrock 		buf->b_hdr = NULL;
18277545SMark.Maybee@Sun.COM 		rw_exit(&buf->b_lock);
18281544Seschrock 		mutex_exit(&arc_eviction_mtx);
18291544Seschrock 
18301819Smaybee 		if (buf->b_efunc != NULL)
18311819Smaybee 			VERIFY(buf->b_efunc(buf) == 0);
18321544Seschrock 
18331544Seschrock 		buf->b_efunc = NULL;
18341544Seschrock 		buf->b_private = NULL;
18351544Seschrock 		kmem_cache_free(buf_cache, buf);
18361544Seschrock 		mutex_enter(&arc_eviction_mtx);
18371544Seschrock 	}
18381544Seschrock 	mutex_exit(&arc_eviction_mtx);
18391544Seschrock }
18401544Seschrock 
1841789Sahrens /*
18425642Smaybee  * Flush all *evictable* data from the cache for the given spa.
1843789Sahrens  * NOTE: this will not touch "active" (i.e. referenced) data.
1844789Sahrens  */
1845789Sahrens void
18465642Smaybee arc_flush(spa_t *spa)
1847789Sahrens {
18488636SMark.Maybee@Sun.COM 	uint64_t guid = 0;
18498636SMark.Maybee@Sun.COM 
18508636SMark.Maybee@Sun.COM 	if (spa)
18518636SMark.Maybee@Sun.COM 		guid = spa_guid(spa);
18528636SMark.Maybee@Sun.COM 
18535642Smaybee 	while (list_head(&arc_mru->arcs_list[ARC_BUFC_DATA])) {
18548636SMark.Maybee@Sun.COM 		(void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_DATA);
18555642Smaybee 		if (spa)
18565642Smaybee 			break;
18575642Smaybee 	}
18585642Smaybee 	while (list_head(&arc_mru->arcs_list[ARC_BUFC_METADATA])) {
18598636SMark.Maybee@Sun.COM 		(void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_METADATA);
18605642Smaybee 		if (spa)
18615642Smaybee 			break;
18625642Smaybee 	}
18635642Smaybee 	while (list_head(&arc_mfu->arcs_list[ARC_BUFC_DATA])) {
18648636SMark.Maybee@Sun.COM 		(void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_DATA);
18655642Smaybee 		if (spa)
18665642Smaybee 			break;
18675642Smaybee 	}
18685642Smaybee 	while (list_head(&arc_mfu->arcs_list[ARC_BUFC_METADATA])) {
18698636SMark.Maybee@Sun.COM 		(void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_METADATA);
18705642Smaybee 		if (spa)
18715642Smaybee 			break;
18725642Smaybee 	}
18735642Smaybee 
18748636SMark.Maybee@Sun.COM 	arc_evict_ghost(arc_mru_ghost, guid, -1);
18758636SMark.Maybee@Sun.COM 	arc_evict_ghost(arc_mfu_ghost, guid, -1);
18761544Seschrock 
18771544Seschrock 	mutex_enter(&arc_reclaim_thr_lock);
18781544Seschrock 	arc_do_user_evicts();
18791544Seschrock 	mutex_exit(&arc_reclaim_thr_lock);
18805642Smaybee 	ASSERT(spa || arc_eviction_list == NULL);
1881789Sahrens }
1882789Sahrens 
1883789Sahrens void
18843158Smaybee arc_shrink(void)
1885789Sahrens {
18863403Sbmc 	if (arc_c > arc_c_min) {
18873158Smaybee 		uint64_t to_free;
1888789Sahrens 
18892048Sstans #ifdef _KERNEL
18903403Sbmc 		to_free = MAX(arc_c >> arc_shrink_shift, ptob(needfree));
18912048Sstans #else
18923403Sbmc 		to_free = arc_c >> arc_shrink_shift;
18932048Sstans #endif
18943403Sbmc 		if (arc_c > arc_c_min + to_free)
18953403Sbmc 			atomic_add_64(&arc_c, -to_free);
18963158Smaybee 		else
18973403Sbmc 			arc_c = arc_c_min;
18982048Sstans 
18993403Sbmc 		atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
19003403Sbmc 		if (arc_c > arc_size)
19013403Sbmc 			arc_c = MAX(arc_size, arc_c_min);
19023403Sbmc 		if (arc_p > arc_c)
19033403Sbmc 			arc_p = (arc_c >> 1);
19043403Sbmc 		ASSERT(arc_c >= arc_c_min);
19053403Sbmc 		ASSERT((int64_t)arc_p >= 0);
19063158Smaybee 	}
1907789Sahrens 
19083403Sbmc 	if (arc_size > arc_c)
19093158Smaybee 		arc_adjust();
1910789Sahrens }
1911789Sahrens 
1912789Sahrens static int
1913789Sahrens arc_reclaim_needed(void)
1914789Sahrens {
1915789Sahrens 	uint64_t extra;
1916789Sahrens 
1917789Sahrens #ifdef _KERNEL
19182048Sstans 
19192048Sstans 	if (needfree)
19202048Sstans 		return (1);
19212048Sstans 
1922789Sahrens 	/*
1923789Sahrens 	 * take 'desfree' extra pages, so we reclaim sooner, rather than later
1924789Sahrens 	 */
1925789Sahrens 	extra = desfree;
1926789Sahrens 
1927789Sahrens 	/*
1928789Sahrens 	 * check that we're out of range of the pageout scanner.  It starts to
1929789Sahrens 	 * schedule paging if freemem is less than lotsfree and needfree.
1930789Sahrens 	 * lotsfree is the high-water mark for pageout, and needfree is the
1931789Sahrens 	 * number of needed free pages.  We add extra pages here to make sure
1932789Sahrens 	 * the scanner doesn't start up while we're freeing memory.
1933789Sahrens 	 */
1934789Sahrens 	if (freemem < lotsfree + needfree + extra)
1935789Sahrens 		return (1);
1936789Sahrens 
1937789Sahrens 	/*
1938789Sahrens 	 * check to make sure that swapfs has enough space so that anon
19395450Sbrendan 	 * reservations can still succeed. anon_resvmem() checks that the
1940789Sahrens 	 * availrmem is greater than swapfs_minfree, and the number of reserved
1941789Sahrens 	 * swap pages.  We also add a bit of extra here just to prevent
1942789Sahrens 	 * circumstances from getting really dire.
1943789Sahrens 	 */
1944789Sahrens 	if (availrmem < swapfs_minfree + swapfs_reserve + extra)
1945789Sahrens 		return (1);
1946789Sahrens 
19471936Smaybee #if defined(__i386)
1948789Sahrens 	/*
1949789Sahrens 	 * If we're on an i386 platform, it's possible that we'll exhaust the
1950789Sahrens 	 * kernel heap space before we ever run out of available physical
1951789Sahrens 	 * memory.  Most checks of the size of the heap_area compare against
1952789Sahrens 	 * tune.t_minarmem, which is the minimum available real memory that we
1953789Sahrens 	 * can have in the system.  However, this is generally fixed at 25 pages
1954789Sahrens 	 * which is so low that it's useless.  In this comparison, we seek to
1955789Sahrens 	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
19565450Sbrendan 	 * heap is allocated.  (Or, in the calculation, if less than 1/4th is
1957789Sahrens 	 * free)
1958789Sahrens 	 */
1959789Sahrens 	if (btop(vmem_size(heap_arena, VMEM_FREE)) <
1960789Sahrens 	    (btop(vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC)) >> 2))
1961789Sahrens 		return (1);
1962789Sahrens #endif
1963789Sahrens 
1964789Sahrens #else
1965789Sahrens 	if (spa_get_random(100) == 0)
1966789Sahrens 		return (1);
1967789Sahrens #endif
1968789Sahrens 	return (0);
1969789Sahrens }
1970789Sahrens 
1971789Sahrens static void
1972789Sahrens arc_kmem_reap_now(arc_reclaim_strategy_t strat)
1973789Sahrens {
1974789Sahrens 	size_t			i;
1975789Sahrens 	kmem_cache_t		*prev_cache = NULL;
19763290Sjohansen 	kmem_cache_t		*prev_data_cache = NULL;
1977789Sahrens 	extern kmem_cache_t	*zio_buf_cache[];
19783290Sjohansen 	extern kmem_cache_t	*zio_data_buf_cache[];
1979789Sahrens 
19801484Sek110237 #ifdef _KERNEL
19814309Smaybee 	if (arc_meta_used >= arc_meta_limit) {
19824309Smaybee 		/*
19834309Smaybee 		 * We are exceeding our meta-data cache limit.
19844309Smaybee 		 * Purge some DNLC entries to release holds on meta-data.
19854309Smaybee 		 */
19864309Smaybee 		dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
19874309Smaybee 	}
19881936Smaybee #if defined(__i386)
19891936Smaybee 	/*
19901936Smaybee 	 * Reclaim unused memory from all kmem caches.
19911936Smaybee 	 */
19921936Smaybee 	kmem_reap();
19931936Smaybee #endif
19941484Sek110237 #endif
19951484Sek110237 
1996789Sahrens 	/*
19975450Sbrendan 	 * An aggressive reclamation will shrink the cache size as well as
19981544Seschrock 	 * reap free buffers from the arc kmem caches.
1999789Sahrens 	 */
2000789Sahrens 	if (strat == ARC_RECLAIM_AGGR)
20013158Smaybee 		arc_shrink();
2002789Sahrens 
2003789Sahrens 	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
2004789Sahrens 		if (zio_buf_cache[i] != prev_cache) {
2005789Sahrens 			prev_cache = zio_buf_cache[i];
2006789Sahrens 			kmem_cache_reap_now(zio_buf_cache[i]);
2007789Sahrens 		}
20083290Sjohansen 		if (zio_data_buf_cache[i] != prev_data_cache) {
20093290Sjohansen 			prev_data_cache = zio_data_buf_cache[i];
20103290Sjohansen 			kmem_cache_reap_now(zio_data_buf_cache[i]);
20113290Sjohansen 		}
2012789Sahrens 	}
20131544Seschrock 	kmem_cache_reap_now(buf_cache);
20141544Seschrock 	kmem_cache_reap_now(hdr_cache);
2015789Sahrens }
2016789Sahrens 
2017789Sahrens static void
2018789Sahrens arc_reclaim_thread(void)
2019789Sahrens {
2020789Sahrens 	clock_t			growtime = 0;
2021789Sahrens 	arc_reclaim_strategy_t	last_reclaim = ARC_RECLAIM_CONS;
2022789Sahrens 	callb_cpr_t		cpr;
2023789Sahrens 
2024789Sahrens 	CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
2025789Sahrens 
2026789Sahrens 	mutex_enter(&arc_reclaim_thr_lock);
2027789Sahrens 	while (arc_thread_exit == 0) {
2028789Sahrens 		if (arc_reclaim_needed()) {
2029789Sahrens 
20303403Sbmc 			if (arc_no_grow) {
2031789Sahrens 				if (last_reclaim == ARC_RECLAIM_CONS) {
2032789Sahrens 					last_reclaim = ARC_RECLAIM_AGGR;
2033789Sahrens 				} else {
2034789Sahrens 					last_reclaim = ARC_RECLAIM_CONS;
2035789Sahrens 				}
2036789Sahrens 			} else {
20373403Sbmc 				arc_no_grow = TRUE;
2038789Sahrens 				last_reclaim = ARC_RECLAIM_AGGR;
2039789Sahrens 				membar_producer();
2040789Sahrens 			}
2041789Sahrens 
2042789Sahrens 			/* reset the growth delay for every reclaim */
2043789Sahrens 			growtime = lbolt + (arc_grow_retry * hz);
2044789Sahrens 
2045789Sahrens 			arc_kmem_reap_now(last_reclaim);
20466987Sbrendan 			arc_warm = B_TRUE;
2047789Sahrens 
20484309Smaybee 		} else if (arc_no_grow && lbolt >= growtime) {
20493403Sbmc 			arc_no_grow = FALSE;
2050789Sahrens 		}
2051789Sahrens 
20523403Sbmc 		if (2 * arc_c < arc_size +
20533403Sbmc 		    arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size)
20543298Smaybee 			arc_adjust();
20553298Smaybee 
20561544Seschrock 		if (arc_eviction_list != NULL)
20571544Seschrock 			arc_do_user_evicts();
20581544Seschrock 
2059789Sahrens 		/* block until needed, or one second, whichever is shorter */
2060789Sahrens 		CALLB_CPR_SAFE_BEGIN(&cpr);
2061789Sahrens 		(void) cv_timedwait(&arc_reclaim_thr_cv,
2062789Sahrens 		    &arc_reclaim_thr_lock, (lbolt + hz));
2063789Sahrens 		CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
2064789Sahrens 	}
2065789Sahrens 
2066789Sahrens 	arc_thread_exit = 0;
2067789Sahrens 	cv_broadcast(&arc_reclaim_thr_cv);
2068789Sahrens 	CALLB_CPR_EXIT(&cpr);		/* drops arc_reclaim_thr_lock */
2069789Sahrens 	thread_exit();
2070789Sahrens }
2071789Sahrens 
20721544Seschrock /*
20731544Seschrock  * Adapt arc info given the number of bytes we are trying to add and
20741544Seschrock  * the state that we are comming from.  This function is only called
20751544Seschrock  * when we are adding new content to the cache.
20761544Seschrock  */
2077789Sahrens static void
20781544Seschrock arc_adapt(int bytes, arc_state_t *state)
2079789Sahrens {
20801544Seschrock 	int mult;
20818582SBrendan.Gregg@Sun.COM 	uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
20821544Seschrock 
20835450Sbrendan 	if (state == arc_l2c_only)
20845450Sbrendan 		return;
20855450Sbrendan 
20861544Seschrock 	ASSERT(bytes > 0);
2087789Sahrens 	/*
20881544Seschrock 	 * Adapt the target size of the MRU list:
20891544Seschrock 	 *	- if we just hit in the MRU ghost list, then increase
20901544Seschrock 	 *	  the target size of the MRU list.
20911544Seschrock 	 *	- if we just hit in the MFU ghost list, then increase
20921544Seschrock 	 *	  the target size of the MFU list by decreasing the
20931544Seschrock 	 *	  target size of the MRU list.
2094789Sahrens 	 */
20953403Sbmc 	if (state == arc_mru_ghost) {
20963403Sbmc 		mult = ((arc_mru_ghost->arcs_size >= arc_mfu_ghost->arcs_size) ?
20973403Sbmc 		    1 : (arc_mfu_ghost->arcs_size/arc_mru_ghost->arcs_size));
20981544Seschrock 
20998582SBrendan.Gregg@Sun.COM 		arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
21003403Sbmc 	} else if (state == arc_mfu_ghost) {
21018582SBrendan.Gregg@Sun.COM 		uint64_t delta;
21028582SBrendan.Gregg@Sun.COM 
21033403Sbmc 		mult = ((arc_mfu_ghost->arcs_size >= arc_mru_ghost->arcs_size) ?
21043403Sbmc 		    1 : (arc_mru_ghost->arcs_size/arc_mfu_ghost->arcs_size));
21051544Seschrock 
21068582SBrendan.Gregg@Sun.COM 		delta = MIN(bytes * mult, arc_p);
21078582SBrendan.Gregg@Sun.COM 		arc_p = MAX(arc_p_min, arc_p - delta);
21081544Seschrock 	}
21093403Sbmc 	ASSERT((int64_t)arc_p >= 0);
2110789Sahrens 
2111789Sahrens 	if (arc_reclaim_needed()) {
2112789Sahrens 		cv_signal(&arc_reclaim_thr_cv);
2113789Sahrens 		return;
2114789Sahrens 	}
2115789Sahrens 
21163403Sbmc 	if (arc_no_grow)
2117789Sahrens 		return;
2118789Sahrens 
21193403Sbmc 	if (arc_c >= arc_c_max)
21201544Seschrock 		return;
21211544Seschrock 
2122789Sahrens 	/*
21231544Seschrock 	 * If we're within (2 * maxblocksize) bytes of the target
21241544Seschrock 	 * cache size, increment the target cache size
2125789Sahrens 	 */
21263403Sbmc 	if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
21273403Sbmc 		atomic_add_64(&arc_c, (int64_t)bytes);
21283403Sbmc 		if (arc_c > arc_c_max)
21293403Sbmc 			arc_c = arc_c_max;
21303403Sbmc 		else if (state == arc_anon)
21313403Sbmc 			atomic_add_64(&arc_p, (int64_t)bytes);
21323403Sbmc 		if (arc_p > arc_c)
21333403Sbmc 			arc_p = arc_c;
2134789Sahrens 	}
21353403Sbmc 	ASSERT((int64_t)arc_p >= 0);
2136789Sahrens }
2137789Sahrens 
2138789Sahrens /*
21391544Seschrock  * Check if the cache has reached its limits and eviction is required
21401544Seschrock  * prior to insert.
2141789Sahrens  */
2142789Sahrens static int
21434309Smaybee arc_evict_needed(arc_buf_contents_t type)
2144789Sahrens {
21454309Smaybee 	if (type == ARC_BUFC_METADATA && arc_meta_used >= arc_meta_limit)
21464309Smaybee 		return (1);
21474309Smaybee 
21484309Smaybee #ifdef _KERNEL
21494309Smaybee 	/*
21504309Smaybee 	 * If zio data pages are being allocated out of a separate heap segment,
21514309Smaybee 	 * then enforce that the size of available vmem for this area remains
21524309Smaybee 	 * above about 1/32nd free.
21534309Smaybee 	 */
21544309Smaybee 	if (type == ARC_BUFC_DATA && zio_arena != NULL &&
21554309Smaybee 	    vmem_size(zio_arena, VMEM_FREE) <
21564309Smaybee 	    (vmem_size(zio_arena, VMEM_ALLOC) >> 5))
21574309Smaybee 		return (1);
21584309Smaybee #endif
21594309Smaybee 
2160789Sahrens 	if (arc_reclaim_needed())
2161789Sahrens 		return (1);
2162789Sahrens 
21633403Sbmc 	return (arc_size > arc_c);
2164789Sahrens }
2165789Sahrens 
2166789Sahrens /*
21672688Smaybee  * The buffer, supplied as the first argument, needs a data block.
21682688Smaybee  * So, if we are at cache max, determine which cache should be victimized.
21692688Smaybee  * We have the following cases:
2170789Sahrens  *
21713403Sbmc  * 1. Insert for MRU, p > sizeof(arc_anon + arc_mru) ->
2172789Sahrens  * In this situation if we're out of space, but the resident size of the MFU is
2173789Sahrens  * under the limit, victimize the MFU cache to satisfy this insertion request.
2174789Sahrens  *
21753403Sbmc  * 2. Insert for MRU, p <= sizeof(arc_anon + arc_mru) ->
2176789Sahrens  * Here, we've used up all of the available space for the MRU, so we need to
2177789Sahrens  * evict from our own cache instead.  Evict from the set of resident MRU
2178789Sahrens  * entries.
2179789Sahrens  *
21803403Sbmc  * 3. Insert for MFU (c - p) > sizeof(arc_mfu) ->
2181789Sahrens  * c minus p represents the MFU space in the cache, since p is the size of the
2182789Sahrens  * cache that is dedicated to the MRU.  In this situation there's still space on
2183789Sahrens  * the MFU side, so the MRU side needs to be victimized.
2184789Sahrens  *
21853403Sbmc  * 4. Insert for MFU (c - p) < sizeof(arc_mfu) ->
2186789Sahrens  * MFU's resident set is consuming more space than it has been allotted.  In
2187789Sahrens  * this situation, we must victimize our own cache, the MFU, for this insertion.
2188789Sahrens  */
2189789Sahrens static void
21902688Smaybee arc_get_data_buf(arc_buf_t *buf)
2191789Sahrens {
21923290Sjohansen 	arc_state_t		*state = buf->b_hdr->b_state;
21933290Sjohansen 	uint64_t		size = buf->b_hdr->b_size;
21943290Sjohansen 	arc_buf_contents_t	type = buf->b_hdr->b_type;
21952688Smaybee 
21962688Smaybee 	arc_adapt(size, state);
2197789Sahrens 
21982688Smaybee 	/*
21992688Smaybee 	 * We have not yet reached cache maximum size,
22002688Smaybee 	 * just allocate a new buffer.
22012688Smaybee 	 */
22024309Smaybee 	if (!arc_evict_needed(type)) {
22033290Sjohansen 		if (type == ARC_BUFC_METADATA) {
22043290Sjohansen 			buf->b_data = zio_buf_alloc(size);
22058582SBrendan.Gregg@Sun.COM 			arc_space_consume(size, ARC_SPACE_DATA);
22063290Sjohansen 		} else {
22073290Sjohansen 			ASSERT(type == ARC_BUFC_DATA);
22083290Sjohansen 			buf->b_data = zio_data_buf_alloc(size);
22098582SBrendan.Gregg@Sun.COM 			ARCSTAT_INCR(arcstat_data_size, size);
22104309Smaybee 			atomic_add_64(&arc_size, size);
22113290Sjohansen 		}
22122688Smaybee 		goto out;
22132688Smaybee 	}
22142688Smaybee 
22152688Smaybee 	/*
22162688Smaybee 	 * If we are prefetching from the mfu ghost list, this buffer
22172688Smaybee 	 * will end up on the mru list; so steal space from there.
22182688Smaybee 	 */
22193403Sbmc 	if (state == arc_mfu_ghost)
22203403Sbmc 		state = buf->b_hdr->b_flags & ARC_PREFETCH ? arc_mru : arc_mfu;
22213403Sbmc 	else if (state == arc_mru_ghost)
22223403Sbmc 		state = arc_mru;
2223789Sahrens 
22243403Sbmc 	if (state == arc_mru || state == arc_anon) {
22253403Sbmc 		uint64_t mru_used = arc_anon->arcs_size + arc_mru->arcs_size;
22268582SBrendan.Gregg@Sun.COM 		state = (arc_mfu->arcs_lsize[type] >= size &&
22274309Smaybee 		    arc_p > mru_used) ? arc_mfu : arc_mru;
2228789Sahrens 	} else {
22292688Smaybee 		/* MFU cases */
22303403Sbmc 		uint64_t mfu_space = arc_c - arc_p;
22318582SBrendan.Gregg@Sun.COM 		state =  (arc_mru->arcs_lsize[type] >= size &&
22324309Smaybee 		    mfu_space > arc_mfu->arcs_size) ? arc_mru : arc_mfu;
22332688Smaybee 	}
22345642Smaybee 	if ((buf->b_data = arc_evict(state, NULL, size, TRUE, type)) == NULL) {
22353290Sjohansen 		if (type == ARC_BUFC_METADATA) {
22363290Sjohansen 			buf->b_data = zio_buf_alloc(size);
22378582SBrendan.Gregg@Sun.COM 			arc_space_consume(size, ARC_SPACE_DATA);
22383290Sjohansen 		} else {
22393290Sjohansen 			ASSERT(type == ARC_BUFC_DATA);
22403290Sjohansen 			buf->b_data = zio_data_buf_alloc(size);
22418582SBrendan.Gregg@Sun.COM 			ARCSTAT_INCR(arcstat_data_size, size);
22424309Smaybee 			atomic_add_64(&arc_size, size);
22433290Sjohansen 		}
22443403Sbmc 		ARCSTAT_BUMP(arcstat_recycle_miss);
22452688Smaybee 	}
22462688Smaybee 	ASSERT(buf->b_data != NULL);
22472688Smaybee out:
22482688Smaybee 	/*
22492688Smaybee 	 * Update the state size.  Note that ghost states have a
22502688Smaybee 	 * "ghost size" and so don't need to be updated.
22512688Smaybee 	 */
22522688Smaybee 	if (!GHOST_STATE(buf->b_hdr->b_state)) {
22532688Smaybee 		arc_buf_hdr_t *hdr = buf->b_hdr;
22542688Smaybee 
22553403Sbmc 		atomic_add_64(&hdr->b_state->arcs_size, size);
22562688Smaybee 		if (list_link_active(&hdr->b_arc_node)) {
22572688Smaybee 			ASSERT(refcount_is_zero(&hdr->b_refcnt));
22584309Smaybee 			atomic_add_64(&hdr->b_state->arcs_lsize[type], size);
2259789Sahrens 		}
22603298Smaybee 		/*
22613298Smaybee 		 * If we are growing the cache, and we are adding anonymous
22623403Sbmc 		 * data, and we have outgrown arc_p, update arc_p
22633298Smaybee 		 */
22643403Sbmc 		if (arc_size < arc_c && hdr->b_state == arc_anon &&
22653403Sbmc 		    arc_anon->arcs_size + arc_mru->arcs_size > arc_p)
22663403Sbmc 			arc_p = MIN(arc_c, arc_p + size);
2267789Sahrens 	}
2268789Sahrens }
2269789Sahrens 
2270789Sahrens /*
2271789Sahrens  * This routine is called whenever a buffer is accessed.
22721544Seschrock  * NOTE: the hash lock is dropped in this function.
2273789Sahrens  */
2274789Sahrens static void
22752688Smaybee arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock)
2276789Sahrens {
2277789Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
2278789Sahrens 
22793403Sbmc 	if (buf->b_state == arc_anon) {
2280789Sahrens 		/*
2281789Sahrens 		 * This buffer is not in the cache, and does not
2282789Sahrens 		 * appear in our "ghost" list.  Add the new buffer
2283789Sahrens 		 * to the MRU state.
2284789Sahrens 		 */
2285789Sahrens 
2286789Sahrens 		ASSERT(buf->b_arc_access == 0);
2287789Sahrens 		buf->b_arc_access = lbolt;
22881544Seschrock 		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
22893403Sbmc 		arc_change_state(arc_mru, buf, hash_lock);
2290789Sahrens 
22913403Sbmc 	} else if (buf->b_state == arc_mru) {
2292789Sahrens 		/*
22932391Smaybee 		 * If this buffer is here because of a prefetch, then either:
22942391Smaybee 		 * - clear the flag if this is a "referencing" read
22952391Smaybee 		 *   (any subsequent access will bump this into the MFU state).
22962391Smaybee 		 * or
22972391Smaybee 		 * - move the buffer to the head of the list if this is
22982391Smaybee 		 *   another prefetch (to make it less likely to be evicted).
2299789Sahrens 		 */
2300789Sahrens 		if ((buf->b_flags & ARC_PREFETCH) != 0) {
23012391Smaybee 			if (refcount_count(&buf->b_refcnt) == 0) {
23022391Smaybee 				ASSERT(list_link_active(&buf->b_arc_node));
23032391Smaybee 			} else {
23042391Smaybee 				buf->b_flags &= ~ARC_PREFETCH;
23053403Sbmc 				ARCSTAT_BUMP(arcstat_mru_hits);
23062391Smaybee 			}
23072391Smaybee 			buf->b_arc_access = lbolt;
2308789Sahrens 			return;
2309789Sahrens 		}
2310789Sahrens 
2311789Sahrens 		/*
2312789Sahrens 		 * This buffer has been "accessed" only once so far,
2313789Sahrens 		 * but it is still in the cache. Move it to the MFU
2314789Sahrens 		 * state.
2315789Sahrens 		 */
2316789Sahrens 		if (lbolt > buf->b_arc_access + ARC_MINTIME) {
2317789Sahrens 			/*
2318789Sahrens 			 * More than 125ms have passed since we
2319789Sahrens 			 * instantiated this buffer.  Move it to the
2320789Sahrens 			 * most frequently used state.
2321789Sahrens 			 */
2322789Sahrens 			buf->b_arc_access = lbolt;
23231544Seschrock 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
23243403Sbmc 			arc_change_state(arc_mfu, buf, hash_lock);
2325789Sahrens 		}
23263403Sbmc 		ARCSTAT_BUMP(arcstat_mru_hits);
23273403Sbmc 	} else if (buf->b_state == arc_mru_ghost) {
2328789Sahrens 		arc_state_t	*new_state;
2329789Sahrens 		/*
2330789Sahrens 		 * This buffer has been "accessed" recently, but
2331789Sahrens 		 * was evicted from the cache.  Move it to the
2332789Sahrens 		 * MFU state.
2333789Sahrens 		 */
2334789Sahrens 
2335789Sahrens 		if (buf->b_flags & ARC_PREFETCH) {
23363403Sbmc 			new_state = arc_mru;
23372391Smaybee 			if (refcount_count(&buf->b_refcnt) > 0)
23382391Smaybee 				buf->b_flags &= ~ARC_PREFETCH;
23391544Seschrock 			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2340789Sahrens 		} else {
23413403Sbmc 			new_state = arc_mfu;
23421544Seschrock 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2343789Sahrens 		}
2344789Sahrens 
2345789Sahrens 		buf->b_arc_access = lbolt;
2346789Sahrens 		arc_change_state(new_state, buf, hash_lock);
2347789Sahrens 
23483403Sbmc 		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
23493403Sbmc 	} else if (buf->b_state == arc_mfu) {
2350789Sahrens 		/*
2351789Sahrens 		 * This buffer has been accessed more than once and is
2352789Sahrens 		 * still in the cache.  Keep it in the MFU state.
2353789Sahrens 		 *
23542391Smaybee 		 * NOTE: an add_reference() that occurred when we did
23552391Smaybee 		 * the arc_read() will have kicked this off the list.
23562391Smaybee 		 * If it was a prefetch, we will explicitly move it to
23572391Smaybee 		 * the head of the list now.
2358789Sahrens 		 */
23592391Smaybee 		if ((buf->b_flags & ARC_PREFETCH) != 0) {
23602391Smaybee 			ASSERT(refcount_count(&buf->b_refcnt) == 0);
23612391Smaybee 			ASSERT(list_link_active(&buf->b_arc_node));
23622391Smaybee 		}
23633403Sbmc 		ARCSTAT_BUMP(arcstat_mfu_hits);
23642391Smaybee 		buf->b_arc_access = lbolt;
23653403Sbmc 	} else if (buf->b_state == arc_mfu_ghost) {
23663403Sbmc 		arc_state_t	*new_state = arc_mfu;
2367789Sahrens 		/*
2368789Sahrens 		 * This buffer has been accessed more than once but has
2369789Sahrens 		 * been evicted from the cache.  Move it back to the
2370789Sahrens 		 * MFU state.
2371789Sahrens 		 */
2372789Sahrens 
23732391Smaybee 		if (buf->b_flags & ARC_PREFETCH) {
23742391Smaybee 			/*
23752391Smaybee 			 * This is a prefetch access...
23762391Smaybee 			 * move this block back to the MRU state.
23772391Smaybee 			 */
23782391Smaybee 			ASSERT3U(refcount_count(&buf->b_refcnt), ==, 0);
23793403Sbmc 			new_state = arc_mru;
23802391Smaybee 		}
23812391Smaybee 
2382789Sahrens 		buf->b_arc_access = lbolt;
23831544Seschrock 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
23842391Smaybee 		arc_change_state(new_state, buf, hash_lock);
2385789Sahrens 
23863403Sbmc 		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
23875450Sbrendan 	} else if (buf->b_state == arc_l2c_only) {
23885450Sbrendan 		/*
23895450Sbrendan 		 * This buffer is on the 2nd Level ARC.
23905450Sbrendan 		 */
23915450Sbrendan 
23925450Sbrendan 		buf->b_arc_access = lbolt;
23935450Sbrendan 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
23945450Sbrendan 		arc_change_state(arc_mfu, buf, hash_lock);
2395789Sahrens 	} else {
2396789Sahrens 		ASSERT(!"invalid arc state");
2397789Sahrens 	}
2398789Sahrens }
2399789Sahrens 
2400789Sahrens /* a generic arc_done_func_t which you can use */
2401789Sahrens /* ARGSUSED */
2402789Sahrens void
2403789Sahrens arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
2404789Sahrens {
2405789Sahrens 	bcopy(buf->b_data, arg, buf->b_hdr->b_size);
24061544Seschrock 	VERIFY(arc_buf_remove_ref(buf, arg) == 1);
2407789Sahrens }
2408789Sahrens 
24094309Smaybee /* a generic arc_done_func_t */
2410789Sahrens void
2411789Sahrens arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
2412789Sahrens {
2413789Sahrens 	arc_buf_t **bufp = arg;
2414789Sahrens 	if (zio && zio->io_error) {
24151544Seschrock 		VERIFY(arc_buf_remove_ref(buf, arg) == 1);
2416789Sahrens 		*bufp = NULL;
2417789Sahrens 	} else {
2418789Sahrens 		*bufp = buf;
2419789Sahrens 	}
2420789Sahrens }
2421789Sahrens 
2422789Sahrens static void
2423789Sahrens arc_read_done(zio_t *zio)
2424789Sahrens {
24251589Smaybee 	arc_buf_hdr_t	*hdr, *found;
2426789Sahrens 	arc_buf_t	*buf;
2427789Sahrens 	arc_buf_t	*abuf;	/* buffer we're assigning to callback */
2428789Sahrens 	kmutex_t	*hash_lock;
2429789Sahrens 	arc_callback_t	*callback_list, *acb;
2430789Sahrens 	int		freeable = FALSE;
2431789Sahrens 
2432789Sahrens 	buf = zio->io_private;
2433789Sahrens 	hdr = buf->b_hdr;
2434789Sahrens 
24351589Smaybee 	/*
24361589Smaybee 	 * The hdr was inserted into hash-table and removed from lists
24371589Smaybee 	 * prior to starting I/O.  We should find this header, since
24381589Smaybee 	 * it's in the hash table, and it should be legit since it's
24391589Smaybee 	 * not possible to evict it during the I/O.  The only possible
24401589Smaybee 	 * reason for it not to be found is if we were freed during the
24411589Smaybee 	 * read.
24421589Smaybee 	 */
24438636SMark.Maybee@Sun.COM 	found = buf_hash_find(hdr->b_spa, &hdr->b_dva, hdr->b_birth,
24443093Sahrens 	    &hash_lock);
2445789Sahrens 
24461589Smaybee 	ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) && hash_lock == NULL) ||
24475450Sbrendan 	    (found == hdr && DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
24485450Sbrendan 	    (found == hdr && HDR_L2_READING(hdr)));
24495450Sbrendan 
24506987Sbrendan 	hdr->b_flags &= ~ARC_L2_EVICTED;
24515450Sbrendan 	if (l2arc_noprefetch && (hdr->b_flags & ARC_PREFETCH))
24527237Sek110237 		hdr->b_flags &= ~ARC_L2CACHE;
2453789Sahrens 
2454789Sahrens 	/* byteswap if necessary */
2455789Sahrens 	callback_list = hdr->b_acb;
2456789Sahrens 	ASSERT(callback_list != NULL);
2457*10839Swilliam.gorrell@sun.com 	if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
24587046Sahrens 		arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
24597046Sahrens 		    byteswap_uint64_array :
24607046Sahrens 		    dmu_ot[BP_GET_TYPE(zio->io_bp)].ot_byteswap;
24617046Sahrens 		func(buf->b_data, hdr->b_size);
24627046Sahrens 	}
2463789Sahrens 
24645450Sbrendan 	arc_cksum_compute(buf, B_FALSE);
24653093Sahrens 
2466789Sahrens 	/* create copies of the data buffer for the callers */
2467789Sahrens 	abuf = buf;
2468789Sahrens 	for (acb = callback_list; acb; acb = acb->acb_next) {
2469789Sahrens 		if (acb->acb_done) {
24702688Smaybee 			if (abuf == NULL)
24712688Smaybee 				abuf = arc_buf_clone(buf);
2472789Sahrens 			acb->acb_buf = abuf;
2473789Sahrens 			abuf = NULL;
2474789Sahrens 		}
2475789Sahrens 	}
2476789Sahrens 	hdr->b_acb = NULL;
2477789Sahrens 	hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
24781544Seschrock 	ASSERT(!HDR_BUF_AVAILABLE(hdr));
24791544Seschrock 	if (abuf == buf)
24801544Seschrock 		hdr->b_flags |= ARC_BUF_AVAILABLE;
2481789Sahrens 
2482789Sahrens 	ASSERT(refcount_is_zero(&hdr->b_refcnt) || callback_list != NULL);
2483789Sahrens 
2484789Sahrens 	if (zio->io_error != 0) {
2485789Sahrens 		hdr->b_flags |= ARC_IO_ERROR;
24863403Sbmc 		if (hdr->b_state != arc_anon)
24873403Sbmc 			arc_change_state(arc_anon, hdr, hash_lock);
24881544Seschrock 		if (HDR_IN_HASH_TABLE(hdr))
24891544Seschrock 			buf_hash_remove(hdr);
2490789Sahrens 		freeable = refcount_is_zero(&hdr->b_refcnt);
2491789Sahrens 	}
2492789Sahrens 
24931544Seschrock 	/*
24942391Smaybee 	 * Broadcast before we drop the hash_lock to avoid the possibility
24952391Smaybee 	 * that the hdr (and hence the cv) might be freed before we get to
24962391Smaybee 	 * the cv_broadcast().
24971544Seschrock 	 */
24981544Seschrock 	cv_broadcast(&hdr->b_cv);
24991544Seschrock 
25001589Smaybee 	if (hash_lock) {
2501789Sahrens 		/*
2502789Sahrens 		 * Only call arc_access on anonymous buffers.  This is because
2503789Sahrens 		 * if we've issued an I/O for an evicted buffer, we've already
2504789Sahrens 		 * called arc_access (to prevent any simultaneous readers from
2505789Sahrens 		 * getting confused).
2506789Sahrens 		 */
25073403Sbmc 		if (zio->io_error == 0 && hdr->b_state == arc_anon)
25082688Smaybee 			arc_access(hdr, hash_lock);
25092688Smaybee 		mutex_exit(hash_lock);
2510789Sahrens 	} else {
2511789Sahrens 		/*
2512789Sahrens 		 * This block was freed while we waited for the read to
2513789Sahrens 		 * complete.  It has been removed from the hash table and
2514789Sahrens 		 * moved to the anonymous state (so that it won't show up
2515789Sahrens 		 * in the cache).
2516789Sahrens 		 */
25173403Sbmc 		ASSERT3P(hdr->b_state, ==, arc_anon);
2518789Sahrens 		freeable = refcount_is_zero(&hdr->b_refcnt);
2519789Sahrens 	}
2520789Sahrens 
2521789Sahrens 	/* execute each callback and free its structure */
2522789Sahrens 	while ((acb = callback_list) != NULL) {
2523789Sahrens 		if (acb->acb_done)
2524789Sahrens 			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
2525789Sahrens 
2526789Sahrens 		if (acb->acb_zio_dummy != NULL) {
2527789Sahrens 			acb->acb_zio_dummy->io_error = zio->io_error;
2528789Sahrens 			zio_nowait(acb->acb_zio_dummy);
2529789Sahrens 		}
2530789Sahrens 
2531789Sahrens 		callback_list = acb->acb_next;
2532789Sahrens 		kmem_free(acb, sizeof (arc_callback_t));
2533789Sahrens 	}
2534789Sahrens 
2535789Sahrens 	if (freeable)
25361544Seschrock 		arc_hdr_destroy(hdr);
2537789Sahrens }
2538789Sahrens 
2539789Sahrens /*
2540789Sahrens  * "Read" the block block at the specified DVA (in bp) via the
2541789Sahrens  * cache.  If the block is found in the cache, invoke the provided
2542789Sahrens  * callback immediately and return.  Note that the `zio' parameter
2543789Sahrens  * in the callback will be NULL in this case, since no IO was
2544789Sahrens  * required.  If the block is not in the cache pass the read request
2545789Sahrens  * on to the spa with a substitute callback function, so that the
2546789Sahrens  * requested block will be added to the cache.
2547789Sahrens  *
2548789Sahrens  * If a read request arrives for a block that has a read in-progress,
2549789Sahrens  * either wait for the in-progress read to complete (and return the
2550789Sahrens  * results); or, if this is a read with a "done" func, add a record
2551789Sahrens  * to the read to invoke the "done" func when the read completes,
2552789Sahrens  * and return; or just return.
2553789Sahrens  *
2554789Sahrens  * arc_read_done() will invoke all the requested "done" functions
2555789Sahrens  * for readers of this block.
25567046Sahrens  *
25577046Sahrens  * Normal callers should use arc_read and pass the arc buffer and offset
25587046Sahrens  * for the bp.  But if you know you don't need locking, you can use
25598213SSuhasini.Peddada@Sun.COM  * arc_read_bp.
2560789Sahrens  */
2561789Sahrens int
25627046Sahrens arc_read(zio_t *pio, spa_t *spa, blkptr_t *bp, arc_buf_t *pbuf,
25637237Sek110237     arc_done_func_t *done, void *private, int priority, int zio_flags,
25647046Sahrens     uint32_t *arc_flags, const zbookmark_t *zb)
25657046Sahrens {
25667046Sahrens 	int err;
25677046Sahrens 
25687046Sahrens 	ASSERT(!refcount_is_zero(&pbuf->b_hdr->b_refcnt));
25697046Sahrens 	ASSERT3U((char *)bp - (char *)pbuf->b_data, <, pbuf->b_hdr->b_size);
25707545SMark.Maybee@Sun.COM 	rw_enter(&pbuf->b_lock, RW_READER);
25717046Sahrens 
25727046Sahrens 	err = arc_read_nolock(pio, spa, bp, done, private, priority,
25737237Sek110237 	    zio_flags, arc_flags, zb);
25747545SMark.Maybee@Sun.COM 	rw_exit(&pbuf->b_lock);
25759396SMatthew.Ahrens@Sun.COM 
25767046Sahrens 	return (err);
25777046Sahrens }
25787046Sahrens 
25797046Sahrens int
25807046Sahrens arc_read_nolock(zio_t *pio, spa_t *spa, blkptr_t *bp,
25817237Sek110237     arc_done_func_t *done, void *private, int priority, int zio_flags,
25827046Sahrens     uint32_t *arc_flags, const zbookmark_t *zb)
2583789Sahrens {
2584789Sahrens 	arc_buf_hdr_t *hdr;
2585789Sahrens 	arc_buf_t *buf;
2586789Sahrens 	kmutex_t *hash_lock;
25875450Sbrendan 	zio_t *rzio;
25888636SMark.Maybee@Sun.COM 	uint64_t guid = spa_guid(spa);
2589789Sahrens 
2590789Sahrens top:
25918636SMark.Maybee@Sun.COM 	hdr = buf_hash_find(guid, BP_IDENTITY(bp), bp->blk_birth, &hash_lock);
25921544Seschrock 	if (hdr && hdr->b_datacnt > 0) {
2593789Sahrens 
25942391Smaybee 		*arc_flags |= ARC_CACHED;
25952391Smaybee 
2596789Sahrens 		if (HDR_IO_IN_PROGRESS(hdr)) {
25972391Smaybee 
25982391Smaybee 			if (*arc_flags & ARC_WAIT) {
25992391Smaybee 				cv_wait(&hdr->b_cv, hash_lock);
26002391Smaybee 				mutex_exit(hash_lock);
26012391Smaybee 				goto top;
26022391Smaybee 			}
26032391Smaybee 			ASSERT(*arc_flags & ARC_NOWAIT);
26042391Smaybee 
26052391Smaybee 			if (done) {
2606789Sahrens 				arc_callback_t	*acb = NULL;
2607789Sahrens 
2608789Sahrens 				acb = kmem_zalloc(sizeof (arc_callback_t),
2609789Sahrens 				    KM_SLEEP);
2610789Sahrens 				acb->acb_done = done;
2611789Sahrens 				acb->acb_private = private;
2612789Sahrens 				if (pio != NULL)
2613789Sahrens 					acb->acb_zio_dummy = zio_null(pio,
26148632SBill.Moore@Sun.COM 					    spa, NULL, NULL, NULL, zio_flags);
2615789Sahrens 
2616789Sahrens 				ASSERT(acb->acb_done != NULL);
2617789Sahrens 				acb->acb_next = hdr->b_acb;
2618789Sahrens 				hdr->b_acb = acb;
2619789Sahrens 				add_reference(hdr, hash_lock, private);
2620789Sahrens 				mutex_exit(hash_lock);
2621789Sahrens 				return (0);
2622789Sahrens 			}
2623789Sahrens 			mutex_exit(hash_lock);
2624789Sahrens 			return (0);
2625789Sahrens 		}
2626789Sahrens 
26273403Sbmc 		ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
2628789Sahrens 
26291544Seschrock 		if (done) {
26302688Smaybee 			add_reference(hdr, hash_lock, private);
26311544Seschrock 			/*
26321544Seschrock 			 * If this block is already in use, create a new
26331544Seschrock 			 * copy of the data so that we will be guaranteed
26341544Seschrock 			 * that arc_release() will always succeed.
26351544Seschrock 			 */
26361544Seschrock 			buf = hdr->b_buf;
26371544Seschrock 			ASSERT(buf);
26381544Seschrock 			ASSERT(buf->b_data);
26392688Smaybee 			if (HDR_BUF_AVAILABLE(hdr)) {
26401544Seschrock 				ASSERT(buf->b_efunc == NULL);
26411544Seschrock 				hdr->b_flags &= ~ARC_BUF_AVAILABLE;
26422688Smaybee 			} else {
26432688Smaybee 				buf = arc_buf_clone(buf);
26441544Seschrock 			}
26452391Smaybee 		} else if (*arc_flags & ARC_PREFETCH &&
26462391Smaybee 		    refcount_count(&hdr->b_refcnt) == 0) {
26472391Smaybee 			hdr->b_flags |= ARC_PREFETCH;
2648789Sahrens 		}
2649789Sahrens 		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
26502688Smaybee 		arc_access(hdr, hash_lock);
26517237Sek110237 		if (*arc_flags & ARC_L2CACHE)
26527237Sek110237 			hdr->b_flags |= ARC_L2CACHE;
26532688Smaybee 		mutex_exit(hash_lock);
26543403Sbmc 		ARCSTAT_BUMP(arcstat_hits);
26553403Sbmc 		ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
26563403Sbmc 		    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
26573403Sbmc 		    data, metadata, hits);
26583403Sbmc 
2659789Sahrens 		if (done)
2660789Sahrens 			done(NULL, buf, private);
2661789Sahrens 	} else {
2662789Sahrens 		uint64_t size = BP_GET_LSIZE(bp);
2663789Sahrens 		arc_callback_t	*acb;
26646987Sbrendan 		vdev_t *vd = NULL;
26659215SGeorge.Wilson@Sun.COM 		uint64_t addr;
26668582SBrendan.Gregg@Sun.COM 		boolean_t devw = B_FALSE;
2667789Sahrens 
2668789Sahrens 		if (hdr == NULL) {
2669789Sahrens 			/* this block is not in the cache */
2670789Sahrens 			arc_buf_hdr_t	*exists;
26713290Sjohansen 			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
26723290Sjohansen 			buf = arc_buf_alloc(spa, size, private, type);
2673789Sahrens 			hdr = buf->b_hdr;
2674789Sahrens 			hdr->b_dva = *BP_IDENTITY(bp);
2675789Sahrens 			hdr->b_birth = bp->blk_birth;
2676789Sahrens 			hdr->b_cksum0 = bp->blk_cksum.zc_word[0];
2677789Sahrens 			exists = buf_hash_insert(hdr, &hash_lock);
2678789Sahrens 			if (exists) {
2679789Sahrens 				/* somebody beat us to the hash insert */
2680789Sahrens 				mutex_exit(hash_lock);
2681789Sahrens 				bzero(&hdr->b_dva, sizeof (dva_t));
2682789Sahrens 				hdr->b_birth = 0;
2683789Sahrens 				hdr->b_cksum0 = 0;
26841544Seschrock 				(void) arc_buf_remove_ref(buf, private);
2685789Sahrens 				goto top; /* restart the IO request */
2686789Sahrens 			}
26872391Smaybee 			/* if this is a prefetch, we don't have a reference */
26882391Smaybee 			if (*arc_flags & ARC_PREFETCH) {
26892391Smaybee 				(void) remove_reference(hdr, hash_lock,
26902391Smaybee 				    private);
26912391Smaybee 				hdr->b_flags |= ARC_PREFETCH;
26922391Smaybee 			}
26937237Sek110237 			if (*arc_flags & ARC_L2CACHE)
26947237Sek110237 				hdr->b_flags |= ARC_L2CACHE;
26952391Smaybee 			if (BP_GET_LEVEL(bp) > 0)
26962391Smaybee 				hdr->b_flags |= ARC_INDIRECT;
2697789Sahrens 		} else {
2698789Sahrens 			/* this block is in the ghost cache */
26991544Seschrock 			ASSERT(GHOST_STATE(hdr->b_state));
27001544Seschrock 			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
27012391Smaybee 			ASSERT3U(refcount_count(&hdr->b_refcnt), ==, 0);
27022391Smaybee 			ASSERT(hdr->b_buf == NULL);
2703789Sahrens 
27042391Smaybee 			/* if this is a prefetch, we don't have a reference */
27052391Smaybee 			if (*arc_flags & ARC_PREFETCH)
27062391Smaybee 				hdr->b_flags |= ARC_PREFETCH;
27072391Smaybee 			else
27082391Smaybee 				add_reference(hdr, hash_lock, private);
27097237Sek110237 			if (*arc_flags & ARC_L2CACHE)
27107237Sek110237 				hdr->b_flags |= ARC_L2CACHE;
27116245Smaybee 			buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
27121544Seschrock 			buf->b_hdr = hdr;
27132688Smaybee 			buf->b_data = NULL;
27141544Seschrock 			buf->b_efunc = NULL;
27151544Seschrock 			buf->b_private = NULL;
27161544Seschrock 			buf->b_next = NULL;
27171544Seschrock 			hdr->b_buf = buf;
27182688Smaybee 			arc_get_data_buf(buf);
27191544Seschrock 			ASSERT(hdr->b_datacnt == 0);
27201544Seschrock 			hdr->b_datacnt = 1;
27212391Smaybee 
2722789Sahrens 		}
2723789Sahrens 
2724789Sahrens 		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
2725789Sahrens 		acb->acb_done = done;
2726789Sahrens 		acb->acb_private = private;
2727789Sahrens 
2728789Sahrens 		ASSERT(hdr->b_acb == NULL);
2729789Sahrens 		hdr->b_acb = acb;
2730789Sahrens 		hdr->b_flags |= ARC_IO_IN_PROGRESS;
2731789Sahrens 
2732789Sahrens 		/*
2733789Sahrens 		 * If the buffer has been evicted, migrate it to a present state
2734789Sahrens 		 * before issuing the I/O.  Once we drop the hash-table lock,
2735789Sahrens 		 * the header will be marked as I/O in progress and have an
2736789Sahrens 		 * attached buffer.  At this point, anybody who finds this
2737789Sahrens 		 * buffer ought to notice that it's legit but has a pending I/O.
2738789Sahrens 		 */
2739789Sahrens 
27401544Seschrock 		if (GHOST_STATE(hdr->b_state))
27412688Smaybee 			arc_access(hdr, hash_lock);
2742789Sahrens 
27437754SJeff.Bonwick@Sun.COM 		if (HDR_L2CACHE(hdr) && hdr->b_l2hdr != NULL &&
27447754SJeff.Bonwick@Sun.COM 		    (vd = hdr->b_l2hdr->b_dev->l2ad_vdev) != NULL) {
27458582SBrendan.Gregg@Sun.COM 			devw = hdr->b_l2hdr->b_dev->l2ad_writing;
27466987Sbrendan 			addr = hdr->b_l2hdr->b_daddr;
27477754SJeff.Bonwick@Sun.COM 			/*
27487754SJeff.Bonwick@Sun.COM 			 * Lock out device removal.
27497754SJeff.Bonwick@Sun.COM 			 */
27507754SJeff.Bonwick@Sun.COM 			if (vdev_is_dead(vd) ||
27517754SJeff.Bonwick@Sun.COM 			    !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
27527754SJeff.Bonwick@Sun.COM 				vd = NULL;
27536987Sbrendan 		}
27546987Sbrendan 
27556987Sbrendan 		mutex_exit(hash_lock);
27566987Sbrendan 
2757789Sahrens 		ASSERT3U(hdr->b_size, ==, size);
275810409SBrendan.Gregg@Sun.COM 		DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
275910409SBrendan.Gregg@Sun.COM 		    uint64_t, size, zbookmark_t *, zb);
27603403Sbmc 		ARCSTAT_BUMP(arcstat_misses);
27613403Sbmc 		ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
27623403Sbmc 		    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
27633403Sbmc 		    data, metadata, misses);
27641544Seschrock 
27658582SBrendan.Gregg@Sun.COM 		if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
27666987Sbrendan 			/*
27676987Sbrendan 			 * Read from the L2ARC if the following are true:
27686987Sbrendan 			 * 1. The L2ARC vdev was previously cached.
27696987Sbrendan 			 * 2. This buffer still has L2ARC metadata.
27706987Sbrendan 			 * 3. This buffer isn't currently writing to the L2ARC.
27716987Sbrendan 			 * 4. The L2ARC entry wasn't evicted, which may
27726987Sbrendan 			 *    also have invalidated the vdev.
27738582SBrendan.Gregg@Sun.COM 			 * 5. This isn't prefetch and l2arc_noprefetch is set.
27746987Sbrendan 			 */
27757754SJeff.Bonwick@Sun.COM 			if (hdr->b_l2hdr != NULL &&
27768582SBrendan.Gregg@Sun.COM 			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
27778582SBrendan.Gregg@Sun.COM 			    !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
27785450Sbrendan 				l2arc_read_callback_t *cb;
27795450Sbrendan 
27806643Seschrock 				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
27816643Seschrock 				ARCSTAT_BUMP(arcstat_l2_hits);
27826643Seschrock 
27835450Sbrendan 				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
27845450Sbrendan 				    KM_SLEEP);
27855450Sbrendan 				cb->l2rcb_buf = buf;
27865450Sbrendan 				cb->l2rcb_spa = spa;
27875450Sbrendan 				cb->l2rcb_bp = *bp;
27885450Sbrendan 				cb->l2rcb_zb = *zb;
27897237Sek110237 				cb->l2rcb_flags = zio_flags;
27905450Sbrendan 
27915450Sbrendan 				/*
27927754SJeff.Bonwick@Sun.COM 				 * l2arc read.  The SCL_L2ARC lock will be
27937754SJeff.Bonwick@Sun.COM 				 * released by l2arc_read_done().
27945450Sbrendan 				 */
27955450Sbrendan 				rzio = zio_read_phys(pio, vd, addr, size,
27965450Sbrendan 				    buf->b_data, ZIO_CHECKSUM_OFF,
27977237Sek110237 				    l2arc_read_done, cb, priority, zio_flags |
27987361SBrendan.Gregg@Sun.COM 				    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_CANFAIL |
27997754SJeff.Bonwick@Sun.COM 				    ZIO_FLAG_DONT_PROPAGATE |
28007754SJeff.Bonwick@Sun.COM 				    ZIO_FLAG_DONT_RETRY, B_FALSE);
28015450Sbrendan 				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
28025450Sbrendan 				    zio_t *, rzio);
28038582SBrendan.Gregg@Sun.COM 				ARCSTAT_INCR(arcstat_l2_read_bytes, size);
28046987Sbrendan 
28056987Sbrendan 				if (*arc_flags & ARC_NOWAIT) {
28066987Sbrendan 					zio_nowait(rzio);
28076987Sbrendan 					return (0);
28086987Sbrendan 				}
28096987Sbrendan 
28106987Sbrendan 				ASSERT(*arc_flags & ARC_WAIT);
28116987Sbrendan 				if (zio_wait(rzio) == 0)
28126987Sbrendan 					return (0);
28136987Sbrendan 
28146987Sbrendan 				/* l2arc read error; goto zio_read() */
28155450Sbrendan 			} else {
28165450Sbrendan 				DTRACE_PROBE1(l2arc__miss,
28175450Sbrendan 				    arc_buf_hdr_t *, hdr);
28185450Sbrendan 				ARCSTAT_BUMP(arcstat_l2_misses);
28195450Sbrendan 				if (HDR_L2_WRITING(hdr))
28205450Sbrendan 					ARCSTAT_BUMP(arcstat_l2_rw_clash);
28217754SJeff.Bonwick@Sun.COM 				spa_config_exit(spa, SCL_L2ARC, vd);
28225450Sbrendan 			}
28238582SBrendan.Gregg@Sun.COM 		} else {
28248628SBill.Moore@Sun.COM 			if (vd != NULL)
28258628SBill.Moore@Sun.COM 				spa_config_exit(spa, SCL_L2ARC, vd);
28268582SBrendan.Gregg@Sun.COM 			if (l2arc_ndev != 0) {
28278582SBrendan.Gregg@Sun.COM 				DTRACE_PROBE1(l2arc__miss,
28288582SBrendan.Gregg@Sun.COM 				    arc_buf_hdr_t *, hdr);
28298582SBrendan.Gregg@Sun.COM 				ARCSTAT_BUMP(arcstat_l2_misses);
28308582SBrendan.Gregg@Sun.COM 			}
28315450Sbrendan 		}
28326643Seschrock 
2833789Sahrens 		rzio = zio_read(pio, spa, bp, buf->b_data, size,
28347237Sek110237 		    arc_read_done, buf, priority, zio_flags, zb);
2835789Sahrens 
28362391Smaybee 		if (*arc_flags & ARC_WAIT)
2837789Sahrens 			return (zio_wait(rzio));
2838789Sahrens 
28392391Smaybee 		ASSERT(*arc_flags & ARC_NOWAIT);
2840789Sahrens 		zio_nowait(rzio);
2841789Sahrens 	}
2842789Sahrens 	return (0);
2843789Sahrens }
2844789Sahrens 
28451544Seschrock void
28461544Seschrock arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
28471544Seschrock {
28481544Seschrock 	ASSERT(buf->b_hdr != NULL);
28493403Sbmc 	ASSERT(buf->b_hdr->b_state != arc_anon);
28501544Seschrock 	ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt) || func == NULL);
28511544Seschrock 	buf->b_efunc = func;
28521544Seschrock 	buf->b_private = private;
28531544Seschrock }
28541544Seschrock 
28551544Seschrock /*
28561544Seschrock  * This is used by the DMU to let the ARC know that a buffer is
28571544Seschrock  * being evicted, so the ARC should clean up.  If this arc buf
28581544Seschrock  * is not yet in the evicted state, it will be put there.
28591544Seschrock  */
28601544Seschrock int
28611544Seschrock arc_buf_evict(arc_buf_t *buf)
28621544Seschrock {
28632887Smaybee 	arc_buf_hdr_t *hdr;
28641544Seschrock 	kmutex_t *hash_lock;
28651544Seschrock 	arc_buf_t **bufp;
28661544Seschrock 
28677545SMark.Maybee@Sun.COM 	rw_enter(&buf->b_lock, RW_WRITER);
28682887Smaybee 	hdr = buf->b_hdr;
28691544Seschrock 	if (hdr == NULL) {
28701544Seschrock 		/*
28711544Seschrock 		 * We are in arc_do_user_evicts().
28721544Seschrock 		 */
28731544Seschrock 		ASSERT(buf->b_data == NULL);
28747545SMark.Maybee@Sun.COM 		rw_exit(&buf->b_lock);
28751544Seschrock 		return (0);
28767545SMark.Maybee@Sun.COM 	} else if (buf->b_data == NULL) {
28777545SMark.Maybee@Sun.COM 		arc_buf_t copy = *buf; /* structure assignment */
28787545SMark.Maybee@Sun.COM 		/*
28797545SMark.Maybee@Sun.COM 		 * We are on the eviction list; process this buffer now
28807545SMark.Maybee@Sun.COM 		 * but let arc_do_user_evicts() do the reaping.
28817545SMark.Maybee@Sun.COM 		 */
28827545SMark.Maybee@Sun.COM 		buf->b_efunc = NULL;
28837545SMark.Maybee@Sun.COM 		rw_exit(&buf->b_lock);
28847545SMark.Maybee@Sun.COM 		VERIFY(copy.b_efunc(&copy) == 0);
28857545SMark.Maybee@Sun.COM 		return (1);
28861544Seschrock 	}
28872887Smaybee 	hash_lock = HDR_LOCK(hdr);
28881544Seschrock 	mutex_enter(hash_lock);
28891544Seschrock 
28902724Smaybee 	ASSERT(buf->b_hdr == hdr);
28912724Smaybee 	ASSERT3U(refcount_count(&hdr->b_refcnt), <, hdr->b_datacnt);
28923403Sbmc 	ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
28931544Seschrock 
28941544Seschrock 	/*
28951544Seschrock 	 * Pull this buffer off of the hdr
28961544Seschrock 	 */
28971544Seschrock 	bufp = &hdr->b_buf;
28981544Seschrock 	while (*bufp != buf)
28991544Seschrock 		bufp = &(*bufp)->b_next;
29001544Seschrock 	*bufp = buf->b_next;
29011544Seschrock 
29021544Seschrock 	ASSERT(buf->b_data != NULL);
29032688Smaybee 	arc_buf_destroy(buf, FALSE, FALSE);
29041544Seschrock 
29051544Seschrock 	if (hdr->b_datacnt == 0) {
29061544Seschrock 		arc_state_t *old_state = hdr->b_state;
29071544Seschrock 		arc_state_t *evicted_state;
29081544Seschrock 
29091544Seschrock 		ASSERT(refcount_is_zero(&hdr->b_refcnt));
29101544Seschrock 
29111544Seschrock 		evicted_state =
29123403Sbmc 		    (old_state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
29131544Seschrock 
29143403Sbmc 		mutex_enter(&old_state->arcs_mtx);
29153403Sbmc 		mutex_enter(&evicted_state->arcs_mtx);
29161544Seschrock 
29171544Seschrock 		arc_change_state(evicted_state, hdr, hash_lock);
29181544Seschrock 		ASSERT(HDR_IN_HASH_TABLE(hdr));
29195450Sbrendan 		hdr->b_flags |= ARC_IN_HASH_TABLE;
29205450Sbrendan 		hdr->b_flags &= ~ARC_BUF_AVAILABLE;
29211544Seschrock 
29223403Sbmc 		mutex_exit(&evicted_state->arcs_mtx);
29233403Sbmc 		mutex_exit(&old_state->arcs_mtx);
29241544Seschrock 	}
29251544Seschrock 	mutex_exit(hash_lock);
29267545SMark.Maybee@Sun.COM 	rw_exit(&buf->b_lock);
29271819Smaybee 
29281544Seschrock 	VERIFY(buf->b_efunc(buf) == 0);
29291544Seschrock 	buf->b_efunc = NULL;
29301544Seschrock 	buf->b_private = NULL;
29311544Seschrock 	buf->b_hdr = NULL;
29321544Seschrock 	kmem_cache_free(buf_cache, buf);
29331544Seschrock 	return (1);
29341544Seschrock }
29351544Seschrock 
2936789Sahrens /*
2937789Sahrens  * Release this buffer from the cache.  This must be done
2938789Sahrens  * after a read and prior to modifying the buffer contents.
2939789Sahrens  * If the buffer has more than one reference, we must make
29407046Sahrens  * a new hdr for the buffer.
2941789Sahrens  */
2942789Sahrens void
2943789Sahrens arc_release(arc_buf_t *buf, void *tag)
2944789Sahrens {
29457545SMark.Maybee@Sun.COM 	arc_buf_hdr_t *hdr;
29467545SMark.Maybee@Sun.COM 	kmutex_t *hash_lock;
29477545SMark.Maybee@Sun.COM 	l2arc_buf_hdr_t *l2hdr;
29485450Sbrendan 	uint64_t buf_size;
29499274SBrendan.Gregg@Sun.COM 	boolean_t released = B_FALSE;
2950789Sahrens 
29517545SMark.Maybee@Sun.COM 	rw_enter(&buf->b_lock, RW_WRITER);
29527545SMark.Maybee@Sun.COM 	hdr = buf->b_hdr;
29537545SMark.Maybee@Sun.COM 
2954789Sahrens 	/* this buffer is not on any list */
2955789Sahrens 	ASSERT(refcount_count(&hdr->b_refcnt) > 0);
29567046Sahrens 	ASSERT(!(hdr->b_flags & ARC_STORED));
2957789Sahrens 
29583403Sbmc 	if (hdr->b_state == arc_anon) {
2959789Sahrens 		/* this buffer is already released */
2960789Sahrens 		ASSERT3U(refcount_count(&hdr->b_refcnt), ==, 1);
2961789Sahrens 		ASSERT(BUF_EMPTY(hdr));
29621544Seschrock 		ASSERT(buf->b_efunc == NULL);
29633093Sahrens 		arc_buf_thaw(buf);
29647545SMark.Maybee@Sun.COM 		rw_exit(&buf->b_lock);
29659274SBrendan.Gregg@Sun.COM 		released = B_TRUE;
29669274SBrendan.Gregg@Sun.COM 	} else {
29679274SBrendan.Gregg@Sun.COM 		hash_lock = HDR_LOCK(hdr);
29689274SBrendan.Gregg@Sun.COM 		mutex_enter(hash_lock);
2969789Sahrens 	}
2970789Sahrens 
29717545SMark.Maybee@Sun.COM 	l2hdr = hdr->b_l2hdr;
29727545SMark.Maybee@Sun.COM 	if (l2hdr) {
29737545SMark.Maybee@Sun.COM 		mutex_enter(&l2arc_buflist_mtx);
29747545SMark.Maybee@Sun.COM 		hdr->b_l2hdr = NULL;
29757545SMark.Maybee@Sun.COM 		buf_size = hdr->b_size;
29767545SMark.Maybee@Sun.COM 	}
29777545SMark.Maybee@Sun.COM 
29789274SBrendan.Gregg@Sun.COM 	if (released)
29799274SBrendan.Gregg@Sun.COM 		goto out;
29809274SBrendan.Gregg@Sun.COM 
29811544Seschrock 	/*
29821544Seschrock 	 * Do we have more than one buf?
29831544Seschrock 	 */
29847545SMark.Maybee@Sun.COM 	if (hdr->b_datacnt > 1) {
2985789Sahrens 		arc_buf_hdr_t *nhdr;
2986789Sahrens 		arc_buf_t **bufp;
2987789Sahrens 		uint64_t blksz = hdr->b_size;
29888636SMark.Maybee@Sun.COM 		uint64_t spa = hdr->b_spa;
29893290Sjohansen 		arc_buf_contents_t type = hdr->b_type;
29905450Sbrendan 		uint32_t flags = hdr->b_flags;
2991789Sahrens 
29927545SMark.Maybee@Sun.COM 		ASSERT(hdr->b_buf != buf || buf->b_next != NULL);
2993789Sahrens 		/*
2994789Sahrens 		 * Pull the data off of this buf and attach it to
2995789Sahrens 		 * a new anonymous buf.
2996789Sahrens 		 */
29971544Seschrock 		(void) remove_reference(hdr, hash_lock, tag);
2998789Sahrens 		bufp = &hdr->b_buf;
29991544Seschrock 		while (*bufp != buf)
3000789Sahrens 			bufp = &(*bufp)->b_next;
3001789Sahrens 		*bufp = (*bufp)->b_next;
30023897Smaybee 		buf->b_next = NULL;
30031544Seschrock 
30043403Sbmc 		ASSERT3U(hdr->b_state->arcs_size, >=, hdr->b_size);
30053403Sbmc 		atomic_add_64(&hdr->b_state->arcs_size, -hdr->b_size);
30061544Seschrock 		if (refcount_is_zero(&hdr->b_refcnt)) {
30074309Smaybee 			uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
30084309Smaybee 			ASSERT3U(*size, >=, hdr->b_size);
30094309Smaybee 			atomic_add_64(size, -hdr->b_size);
30101544Seschrock 		}
30111544Seschrock 		hdr->b_datacnt -= 1;
30123547Smaybee 		arc_cksum_verify(buf);
30131544Seschrock 
3014789Sahrens 		mutex_exit(hash_lock);
3015789Sahrens 
30166245Smaybee 		nhdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
3017789Sahrens 		nhdr->b_size = blksz;
3018789Sahrens 		nhdr->b_spa = spa;
30193290Sjohansen 		nhdr->b_type = type;
3020789Sahrens 		nhdr->b_buf = buf;
30213403Sbmc 		nhdr->b_state = arc_anon;
3022789Sahrens 		nhdr->b_arc_access = 0;
30235450Sbrendan 		nhdr->b_flags = flags & ARC_L2_WRITING;
30245450Sbrendan 		nhdr->b_l2hdr = NULL;
30251544Seschrock 		nhdr->b_datacnt = 1;
30263547Smaybee 		nhdr->b_freeze_cksum = NULL;
30273897Smaybee 		(void) refcount_add(&nhdr->b_refcnt, tag);
3028789Sahrens 		buf->b_hdr = nhdr;
30297545SMark.Maybee@Sun.COM 		rw_exit(&buf->b_lock);
30303403Sbmc 		atomic_add_64(&arc_anon->arcs_size, blksz);
3031789Sahrens 	} else {
30327545SMark.Maybee@Sun.COM 		rw_exit(&buf->b_lock);
30331544Seschrock 		ASSERT(refcount_count(&hdr->b_refcnt) == 1);
3034789Sahrens 		ASSERT(!list_link_active(&hdr->b_arc_node));
3035789Sahrens 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
30363403Sbmc 		arc_change_state(arc_anon, hdr, hash_lock);
3037789Sahrens 		hdr->b_arc_access = 0;
3038789Sahrens 		mutex_exit(hash_lock);
30395450Sbrendan 
3040789Sahrens 		bzero(&hdr->b_dva, sizeof (dva_t));
3041789Sahrens 		hdr->b_birth = 0;
3042789Sahrens 		hdr->b_cksum0 = 0;
30433547Smaybee 		arc_buf_thaw(buf);
3044789Sahrens 	}
30451544Seschrock 	buf->b_efunc = NULL;
30461544Seschrock 	buf->b_private = NULL;
30475450Sbrendan 
30489274SBrendan.Gregg@Sun.COM out:
30495450Sbrendan 	if (l2hdr) {
30505450Sbrendan 		list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
30515450Sbrendan 		kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
30525450Sbrendan 		ARCSTAT_INCR(arcstat_l2_size, -buf_size);
30537545SMark.Maybee@Sun.COM 		mutex_exit(&l2arc_buflist_mtx);
30545450Sbrendan 	}
3055789Sahrens }
3056789Sahrens 
3057789Sahrens int
3058789Sahrens arc_released(arc_buf_t *buf)
3059789Sahrens {
30607545SMark.Maybee@Sun.COM 	int released;
30617545SMark.Maybee@Sun.COM 
30627545SMark.Maybee@Sun.COM 	rw_enter(&buf->b_lock, RW_READER);
30637545SMark.Maybee@Sun.COM 	released = (buf->b_data != NULL && buf->b_hdr->b_state == arc_anon);
30647545SMark.Maybee@Sun.COM 	rw_exit(&buf->b_lock);
30657545SMark.Maybee@Sun.COM 	return (released);
30661544Seschrock }
30671544Seschrock 
30681544Seschrock int
30691544Seschrock arc_has_callback(arc_buf_t *buf)
30701544Seschrock {
30717545SMark.Maybee@Sun.COM 	int callback;
30727545SMark.Maybee@Sun.COM 
30737545SMark.Maybee@Sun.COM 	rw_enter(&buf->b_lock, RW_READER);
30747545SMark.Maybee@Sun.COM 	callback = (buf->b_efunc != NULL);
30757545SMark.Maybee@Sun.COM 	rw_exit(&buf->b_lock);
30767545SMark.Maybee@Sun.COM 	return (callback);
3077789Sahrens }
3078789Sahrens 
30791544Seschrock #ifdef ZFS_DEBUG
30801544Seschrock int
30811544Seschrock arc_referenced(arc_buf_t *buf)
30821544Seschrock {
30837545SMark.Maybee@Sun.COM 	int referenced;
30847545SMark.Maybee@Sun.COM 
30857545SMark.Maybee@Sun.COM 	rw_enter(&buf->b_lock, RW_READER);
30867545SMark.Maybee@Sun.COM 	referenced = (refcount_count(&buf->b_hdr->b_refcnt));
30877545SMark.Maybee@Sun.COM 	rw_exit(&buf->b_lock);
30887545SMark.Maybee@Sun.COM 	return (referenced);
30891544Seschrock }
30901544Seschrock #endif
30911544Seschrock 
3092789Sahrens static void
30933547Smaybee arc_write_ready(zio_t *zio)
30943547Smaybee {
30953547Smaybee 	arc_write_callback_t *callback = zio->io_private;
30963547Smaybee 	arc_buf_t *buf = callback->awcb_buf;
30975329Sgw25295 	arc_buf_hdr_t *hdr = buf->b_hdr;
30985329Sgw25295 
30997754SJeff.Bonwick@Sun.COM 	ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt));
31007754SJeff.Bonwick@Sun.COM 	callback->awcb_ready(zio, buf, callback->awcb_private);
31017754SJeff.Bonwick@Sun.COM 
31025329Sgw25295 	/*
31035329Sgw25295 	 * If the IO is already in progress, then this is a re-write
31047754SJeff.Bonwick@Sun.COM 	 * attempt, so we need to thaw and re-compute the cksum.
31057754SJeff.Bonwick@Sun.COM 	 * It is the responsibility of the callback to handle the
31067754SJeff.Bonwick@Sun.COM 	 * accounting for any re-write attempt.
31075329Sgw25295 	 */
31085329Sgw25295 	if (HDR_IO_IN_PROGRESS(hdr)) {
31095329Sgw25295 		mutex_enter(&hdr->b_freeze_lock);
31105329Sgw25295 		if (hdr->b_freeze_cksum != NULL) {
31115329Sgw25295 			kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
31125329Sgw25295 			hdr->b_freeze_cksum = NULL;
31135329Sgw25295 		}
31145329Sgw25295 		mutex_exit(&hdr->b_freeze_lock);
31155329Sgw25295 	}
31165450Sbrendan 	arc_cksum_compute(buf, B_FALSE);
31175329Sgw25295 	hdr->b_flags |= ARC_IO_IN_PROGRESS;
31183547Smaybee }
31193547Smaybee 
31203547Smaybee static void
3121789Sahrens arc_write_done(zio_t *zio)
3122789Sahrens {
31233547Smaybee 	arc_write_callback_t *callback = zio->io_private;
31243547Smaybee 	arc_buf_t *buf = callback->awcb_buf;
31253547Smaybee 	arc_buf_hdr_t *hdr = buf->b_hdr;
3126789Sahrens 
3127789Sahrens 	hdr->b_acb = NULL;
3128789Sahrens 
3129789Sahrens 	hdr->b_dva = *BP_IDENTITY(zio->io_bp);
3130789Sahrens 	hdr->b_birth = zio->io_bp->blk_birth;
3131789Sahrens 	hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
31321544Seschrock 	/*
31331544Seschrock 	 * If the block to be written was all-zero, we may have
31341544Seschrock 	 * compressed it away.  In this case no write was performed
31351544Seschrock 	 * so there will be no dva/birth-date/checksum.  The buffer
31361544Seschrock 	 * must therefor remain anonymous (and uncached).
31371544Seschrock 	 */
3138789Sahrens 	if (!BUF_EMPTY(hdr)) {
3139789Sahrens 		arc_buf_hdr_t *exists;
3140789Sahrens 		kmutex_t *hash_lock;
3141789Sahrens 
31423093Sahrens 		arc_cksum_verify(buf);
31433093Sahrens 
3144789Sahrens 		exists = buf_hash_insert(hdr, &hash_lock);
3145789Sahrens 		if (exists) {
3146789Sahrens 			/*
3147789Sahrens 			 * This can only happen if we overwrite for
3148789Sahrens 			 * sync-to-convergence, because we remove
3149789Sahrens 			 * buffers from the hash table when we arc_free().
3150789Sahrens 			 */
315110272SMatthew.Ahrens@Sun.COM 			if (!(zio->io_flags & ZIO_FLAG_IO_REWRITE) ||
315210272SMatthew.Ahrens@Sun.COM 			    !DVA_EQUAL(BP_IDENTITY(&zio->io_bp_orig),
315310272SMatthew.Ahrens@Sun.COM 			    BP_IDENTITY(zio->io_bp)) ||
315410272SMatthew.Ahrens@Sun.COM 			    zio->io_bp_orig.blk_birth !=
315510272SMatthew.Ahrens@Sun.COM 			    zio->io_bp->blk_birth) {
315610272SMatthew.Ahrens@Sun.COM 				panic("bad overwrite, hdr=%p exists=%p",
315710272SMatthew.Ahrens@Sun.COM 				    (void *)hdr, (void *)exists);
315810272SMatthew.Ahrens@Sun.COM 			}
3159789Sahrens 
3160789Sahrens 			ASSERT(refcount_is_zero(&exists->b_refcnt));
31613403Sbmc 			arc_change_state(arc_anon, exists, hash_lock);
3162789Sahrens 			mutex_exit(hash_lock);
31631544Seschrock 			arc_hdr_destroy(exists);
3164789Sahrens 			exists = buf_hash_insert(hdr, &hash_lock);
3165789Sahrens 			ASSERT3P(exists, ==, NULL);
3166789Sahrens 		}
31671544Seschrock 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
31687046Sahrens 		/* if it's not anon, we are doing a scrub */
31697046Sahrens 		if (hdr->b_state == arc_anon)
31707046Sahrens 			arc_access(hdr, hash_lock);
31712688Smaybee 		mutex_exit(hash_lock);
31723547Smaybee 	} else if (callback->awcb_done == NULL) {
31731544Seschrock 		int destroy_hdr;
31741544Seschrock 		/*
31751544Seschrock 		 * This is an anonymous buffer with no user callback,
31761544Seschrock 		 * destroy it if there are no active references.
31771544Seschrock 		 */
31781544Seschrock 		mutex_enter(&arc_eviction_mtx);
31791544Seschrock 		destroy_hdr = refcount_is_zero(&hdr->b_refcnt);
31801544Seschrock 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
31811544Seschrock 		mutex_exit(&arc_eviction_mtx);
31821544Seschrock 		if (destroy_hdr)
31831544Seschrock 			arc_hdr_destroy(hdr);
31841544Seschrock 	} else {
31851544Seschrock 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3186789Sahrens 	}
31877046Sahrens 	hdr->b_flags &= ~ARC_STORED;
31881544Seschrock 
31893547Smaybee 	if (callback->awcb_done) {
3190789Sahrens 		ASSERT(!refcount_is_zero(&hdr->b_refcnt));
31913547Smaybee 		callback->awcb_done(zio, buf, callback->awcb_private);
3192789Sahrens 	}
3193789Sahrens 
31943547Smaybee 	kmem_free(callback, sizeof (arc_write_callback_t));
3195789Sahrens }
3196789Sahrens 
31977872STim.Haley@Sun.COM void
31987754SJeff.Bonwick@Sun.COM write_policy(spa_t *spa, const writeprops_t *wp, zio_prop_t *zp)
31997046Sahrens {
32007046Sahrens 	boolean_t ismd = (wp->wp_level > 0 || dmu_ot[wp->wp_type].ot_metadata);
32017046Sahrens 
32027046Sahrens 	/* Determine checksum setting */
32037046Sahrens 	if (ismd) {
32047046Sahrens 		/*
32057046Sahrens 		 * Metadata always gets checksummed.  If the data
32067046Sahrens 		 * checksum is multi-bit correctable, and it's not a
32077046Sahrens 		 * ZBT-style checksum, then it's suitable for metadata
32087046Sahrens 		 * as well.  Otherwise, the metadata checksum defaults
32097046Sahrens 		 * to fletcher4.
32107046Sahrens 		 */
32117046Sahrens 		if (zio_checksum_table[wp->wp_oschecksum].ci_correctable &&
32127046Sahrens 		    !zio_checksum_table[wp->wp_oschecksum].ci_zbt)
32137754SJeff.Bonwick@Sun.COM 			zp->zp_checksum = wp->wp_oschecksum;
32147046Sahrens 		else
32157754SJeff.Bonwick@Sun.COM 			zp->zp_checksum = ZIO_CHECKSUM_FLETCHER_4;
32167046Sahrens 	} else {
32177754SJeff.Bonwick@Sun.COM 		zp->zp_checksum = zio_checksum_select(wp->wp_dnchecksum,
32187046Sahrens 		    wp->wp_oschecksum);
32197046Sahrens 	}
32207046Sahrens 
32217046Sahrens 	/* Determine compression setting */
32227046Sahrens 	if (ismd) {
32237046Sahrens 		/*
32247046Sahrens 		 * XXX -- we should design a compression algorithm
32257046Sahrens 		 * that specializes in arrays of bps.
32267046Sahrens 		 */
32277754SJeff.Bonwick@Sun.COM 		zp->zp_compress = zfs_mdcomp_disable ? ZIO_COMPRESS_EMPTY :
32287046Sahrens 		    ZIO_COMPRESS_LZJB;
32297046Sahrens 	} else {
32307754SJeff.Bonwick@Sun.COM 		zp->zp_compress = zio_compress_select(wp->wp_dncompress,
32317046Sahrens 		    wp->wp_oscompress);
32327046Sahrens 	}
32337754SJeff.Bonwick@Sun.COM 
32347754SJeff.Bonwick@Sun.COM 	zp->zp_type = wp->wp_type;
32357754SJeff.Bonwick@Sun.COM 	zp->zp_level = wp->wp_level;
32367754SJeff.Bonwick@Sun.COM 	zp->zp_ndvas = MIN(wp->wp_copies + ismd, spa_max_replication(spa));
32377046Sahrens }
32387046Sahrens 
32393547Smaybee zio_t *
32407046Sahrens arc_write(zio_t *pio, spa_t *spa, const writeprops_t *wp,
32417237Sek110237     boolean_t l2arc, uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
32423547Smaybee     arc_done_func_t *ready, arc_done_func_t *done, void *private, int priority,
32437237Sek110237     int zio_flags, const zbookmark_t *zb)
3244789Sahrens {
3245789Sahrens 	arc_buf_hdr_t *hdr = buf->b_hdr;
32463547Smaybee 	arc_write_callback_t *callback;
32477754SJeff.Bonwick@Sun.COM 	zio_t *zio;
32487754SJeff.Bonwick@Sun.COM 	zio_prop_t zp;
32497754SJeff.Bonwick@Sun.COM 
32507754SJeff.Bonwick@Sun.COM 	ASSERT(ready != NULL);
3251789Sahrens 	ASSERT(!HDR_IO_ERROR(hdr));
32522237Smaybee 	ASSERT((hdr->b_flags & ARC_IO_IN_PROGRESS) == 0);
32532237Smaybee 	ASSERT(hdr->b_acb == 0);
32547237Sek110237 	if (l2arc)
32557237Sek110237 		hdr->b_flags |= ARC_L2CACHE;
32563547Smaybee 	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
32573547Smaybee 	callback->awcb_ready = ready;
32583547Smaybee 	callback->awcb_done = done;
32593547Smaybee 	callback->awcb_private = private;
32603547Smaybee 	callback->awcb_buf = buf;
32617046Sahrens 
32627754SJeff.Bonwick@Sun.COM 	write_policy(spa, wp, &zp);
32637754SJeff.Bonwick@Sun.COM 	zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, &zp,
32647754SJeff.Bonwick@Sun.COM 	    arc_write_ready, arc_write_done, callback, priority, zio_flags, zb);
3265789Sahrens 
32663547Smaybee 	return (zio);
3267789Sahrens }
3268789Sahrens 
3269789Sahrens int
3270789Sahrens arc_free(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
3271789Sahrens     zio_done_func_t *done, void *private, uint32_t arc_flags)
3272789Sahrens {
3273789Sahrens 	arc_buf_hdr_t *ab;
3274789Sahrens 	kmutex_t *hash_lock;
3275789Sahrens 	zio_t	*zio;
32768636SMark.Maybee@Sun.COM 	uint64_t guid = spa_guid(spa);
3277789Sahrens 
3278789Sahrens 	/*
3279789Sahrens 	 * If this buffer is in the cache, release it, so it
3280789Sahrens 	 * can be re-used.
3281789Sahrens 	 */
32828636SMark.Maybee@Sun.COM 	ab = buf_hash_find(guid, BP_IDENTITY(bp), bp->blk_birth, &hash_lock);
3283789Sahrens 	if (ab != NULL) {
3284789Sahrens 		/*
3285789Sahrens 		 * The checksum of blocks to free is not always
3286789Sahrens 		 * preserved (eg. on the deadlist).  However, if it is
3287789Sahrens 		 * nonzero, it should match what we have in the cache.
3288789Sahrens 		 */
3289789Sahrens 		ASSERT(bp->blk_cksum.zc_word[0] == 0 ||
32907754SJeff.Bonwick@Sun.COM 		    bp->blk_cksum.zc_word[0] == ab->b_cksum0 ||
32917754SJeff.Bonwick@Sun.COM 		    bp->blk_fill == BLK_FILL_ALREADY_FREED);
32927754SJeff.Bonwick@Sun.COM 
32933403Sbmc 		if (ab->b_state != arc_anon)
32943403Sbmc 			arc_change_state(arc_anon, ab, hash_lock);
32952391Smaybee 		if (HDR_IO_IN_PROGRESS(ab)) {
32962391Smaybee 			/*
32972391Smaybee 			 * This should only happen when we prefetch.
32982391Smaybee 			 */
32992391Smaybee 			ASSERT(ab->b_flags & ARC_PREFETCH);
33002391Smaybee 			ASSERT3U(ab->b_datacnt, ==, 1);
33012391Smaybee 			ab->b_flags |= ARC_FREED_IN_READ;
33022391Smaybee 			if (HDR_IN_HASH_TABLE(ab))
33032391Smaybee 				buf_hash_remove(ab);
33042391Smaybee 			ab->b_arc_access = 0;
33052391Smaybee 			bzero(&ab->b_dva, sizeof (dva_t));
33062391Smaybee 			ab->b_birth = 0;
33072391Smaybee 			ab->b_cksum0 = 0;
33082391Smaybee 			ab->b_buf->b_efunc = NULL;
33092391Smaybee 			ab->b_buf->b_private = NULL;
33102391Smaybee 			mutex_exit(hash_lock);
33112391Smaybee 		} else if (refcount_is_zero(&ab->b_refcnt)) {
33125450Sbrendan 			ab->b_flags |= ARC_FREE_IN_PROGRESS;
3313789Sahrens 			mutex_exit(hash_lock);
33141544Seschrock 			arc_hdr_destroy(ab);
33153403Sbmc 			ARCSTAT_BUMP(arcstat_deleted);
3316789Sahrens 		} else {
33171589Smaybee 			/*
33182391Smaybee 			 * We still have an active reference on this
33192391Smaybee 			 * buffer.  This can happen, e.g., from
33202391Smaybee 			 * dbuf_unoverride().
33211589Smaybee 			 */
33222391Smaybee 			ASSERT(!HDR_IN_HASH_TABLE(ab));
3323789Sahrens 			ab->b_arc_access = 0;
3324789Sahrens 			bzero(&ab->b_dva, sizeof (dva_t));
3325789Sahrens 			ab->b_birth = 0;
3326789Sahrens 			ab->b_cksum0 = 0;
33271544Seschrock 			ab->b_buf->b_efunc = NULL;
33281544Seschrock 			ab->b_buf->b_private = NULL;
3329789Sahrens 			mutex_exit(hash_lock);
3330789Sahrens 		}
3331789Sahrens 	}
3332789Sahrens 
33337754SJeff.Bonwick@Sun.COM 	zio = zio_free(pio, spa, txg, bp, done, private, ZIO_FLAG_MUSTSUCCEED);
3334789Sahrens 
3335789Sahrens 	if (arc_flags & ARC_WAIT)
3336789Sahrens 		return (zio_wait(zio));
3337789Sahrens 
3338789Sahrens 	ASSERT(arc_flags & ARC_NOWAIT);
3339789Sahrens 	zio_nowait(zio);
3340789Sahrens 
3341789Sahrens 	return (0);
3342789Sahrens }
3343789Sahrens 
33446245Smaybee static int
33459412SAleksandr.Guzovskiy@Sun.COM arc_memory_throttle(uint64_t reserve, uint64_t inflight_data, uint64_t txg)
33466245Smaybee {
33476245Smaybee #ifdef _KERNEL
33486245Smaybee 	uint64_t available_memory = ptob(freemem);
33496245Smaybee 	static uint64_t page_load = 0;
33506245Smaybee 	static uint64_t last_txg = 0;
33516245Smaybee 
33526245Smaybee #if defined(__i386)
33536245Smaybee 	available_memory =
33546245Smaybee 	    MIN(available_memory, vmem_size(heap_arena, VMEM_FREE));
33556245Smaybee #endif
33566245Smaybee 	if (available_memory >= zfs_write_limit_max)
33576245Smaybee 		return (0);
33586245Smaybee 
33596245Smaybee 	if (txg > last_txg) {
33606245Smaybee 		last_txg = txg;
33616245Smaybee 		page_load = 0;
33626245Smaybee 	}
33636245Smaybee 	/*
33646245Smaybee 	 * If we are in pageout, we know that memory is already tight,
33656245Smaybee 	 * the arc is already going to be evicting, so we just want to
33666245Smaybee 	 * continue to let page writes occur as quickly as possible.
33676245Smaybee 	 */
33686245Smaybee 	if (curproc == proc_pageout) {
33696245Smaybee 		if (page_load > MAX(ptob(minfree), available_memory) / 4)
33706245Smaybee 			return (ERESTART);
33716245Smaybee 		/* Note: reserve is inflated, so we deflate */
33726245Smaybee 		page_load += reserve / 8;
33736245Smaybee 		return (0);
33746245Smaybee 	} else if (page_load > 0 && arc_reclaim_needed()) {
33756245Smaybee 		/* memory is low, delay before restarting */
33766245Smaybee 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
33776245Smaybee 		return (EAGAIN);
33786245Smaybee 	}
33796245Smaybee 	page_load = 0;
33806245Smaybee 
33816245Smaybee 	if (arc_size > arc_c_min) {
33826245Smaybee 		uint64_t evictable_memory =
33836245Smaybee 		    arc_mru->arcs_lsize[ARC_BUFC_DATA] +
33846245Smaybee 		    arc_mru->arcs_lsize[ARC_BUFC_METADATA] +
33856245Smaybee 		    arc_mfu->arcs_lsize[ARC_BUFC_DATA] +
33866245Smaybee 		    arc_mfu->arcs_lsize[ARC_BUFC_METADATA];
33876245Smaybee 		available_memory += MIN(evictable_memory, arc_size - arc_c_min);
33886245Smaybee 	}
33896245Smaybee 
33906245Smaybee 	if (inflight_data > available_memory / 4) {
33916245Smaybee 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
33926245Smaybee 		return (ERESTART);
33936245Smaybee 	}
33946245Smaybee #endif
33956245Smaybee 	return (0);
33966245Smaybee }
33976245Smaybee 
3398789Sahrens void
33996245Smaybee arc_tempreserve_clear(uint64_t reserve)
3400789Sahrens {
34016245Smaybee 	atomic_add_64(&arc_tempreserve, -reserve);
3402789Sahrens 	ASSERT((int64_t)arc_tempreserve >= 0);
3403789Sahrens }
3404789Sahrens 
3405789Sahrens int
34066245Smaybee arc_tempreserve_space(uint64_t reserve, uint64_t txg)
3407789Sahrens {
34086245Smaybee 	int error;
34099412SAleksandr.Guzovskiy@Sun.COM 	uint64_t anon_size;
34106245Smaybee 
3411789Sahrens #ifdef ZFS_DEBUG
3412789Sahrens 	/*
3413789Sahrens 	 * Once in a while, fail for no reason.  Everything should cope.
3414789Sahrens 	 */
3415789Sahrens 	if (spa_get_random(10000) == 0) {
3416789Sahrens 		dprintf("forcing random failure\n");
3417789Sahrens 		return (ERESTART);
3418789Sahrens 	}
3419789Sahrens #endif
34206245Smaybee 	if (reserve > arc_c/4 && !arc_no_grow)
34216245Smaybee 		arc_c = MIN(arc_c_max, reserve * 4);
34226245Smaybee 	if (reserve > arc_c)
3423982Smaybee 		return (ENOMEM);
3424982Smaybee 
3425789Sahrens 	/*
34269412SAleksandr.Guzovskiy@Sun.COM 	 * Don't count loaned bufs as in flight dirty data to prevent long
34279412SAleksandr.Guzovskiy@Sun.COM 	 * network delays from blocking transactions that are ready to be
34289412SAleksandr.Guzovskiy@Sun.COM 	 * assigned to a txg.
34299412SAleksandr.Guzovskiy@Sun.COM 	 */
34309412SAleksandr.Guzovskiy@Sun.COM 	anon_size = MAX((int64_t)(arc_anon->arcs_size - arc_loaned_bytes), 0);
34319412SAleksandr.Guzovskiy@Sun.COM 
34329412SAleksandr.Guzovskiy@Sun.COM 	/*
34336245Smaybee 	 * Writes will, almost always, require additional memory allocations
34346245Smaybee 	 * in order to compress/encrypt/etc the data.  We therefor need to
34356245Smaybee 	 * make sure that there is sufficient available memory for this.
34366245Smaybee 	 */
34379412SAleksandr.Guzovskiy@Sun.COM 	if (error = arc_memory_throttle(reserve, anon_size, txg))
34386245Smaybee 		return (error);
34396245Smaybee 
34406245Smaybee 	/*
3441982Smaybee 	 * Throttle writes when the amount of dirty data in the cache
3442982Smaybee 	 * gets too large.  We try to keep the cache less than half full
3443982Smaybee 	 * of dirty blocks so that our sync times don't grow too large.
3444982Smaybee 	 * Note: if two requests come in concurrently, we might let them
3445982Smaybee 	 * both succeed, when one of them should fail.  Not a huge deal.
3446789Sahrens 	 */
34479412SAleksandr.Guzovskiy@Sun.COM 
34489412SAleksandr.Guzovskiy@Sun.COM 	if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
34499412SAleksandr.Guzovskiy@Sun.COM 	    anon_size > arc_c / 4) {
34504309Smaybee 		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
34514309Smaybee 		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
34524309Smaybee 		    arc_tempreserve>>10,
34534309Smaybee 		    arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
34544309Smaybee 		    arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
34556245Smaybee 		    reserve>>10, arc_c>>10);
3456789Sahrens 		return (ERESTART);
3457789Sahrens 	}
34586245Smaybee 	atomic_add_64(&arc_tempreserve, reserve);
3459789Sahrens 	return (0);
3460789Sahrens }
3461789Sahrens 
3462789Sahrens void
3463789Sahrens arc_init(void)
3464789Sahrens {
3465789Sahrens 	mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
3466789Sahrens 	cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
3467789Sahrens 
34682391Smaybee 	/* Convert seconds to clock ticks */
34692638Sperrin 	arc_min_prefetch_lifespan = 1 * hz;
34702391Smaybee 
3471789Sahrens 	/* Start out with 1/8 of all memory */
34723403Sbmc 	arc_c = physmem * PAGESIZE / 8;
3473789Sahrens 
3474789Sahrens #ifdef _KERNEL
3475789Sahrens 	/*
3476789Sahrens 	 * On architectures where the physical memory can be larger
3477789Sahrens 	 * than the addressable space (intel in 32-bit mode), we may
3478789Sahrens 	 * need to limit the cache to 1/8 of VM size.
3479789Sahrens 	 */
34803403Sbmc 	arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
3481789Sahrens #endif
3482789Sahrens 
3483982Smaybee 	/* set min cache to 1/32 of all memory, or 64MB, whichever is more */
34843403Sbmc 	arc_c_min = MAX(arc_c / 4, 64<<20);
3485982Smaybee 	/* set max to 3/4 of all memory, or all but 1GB, whichever is more */
34863403Sbmc 	if (arc_c * 8 >= 1<<30)
34873403Sbmc 		arc_c_max = (arc_c * 8) - (1<<30);
3488789Sahrens 	else
34893403Sbmc 		arc_c_max = arc_c_min;
34903403Sbmc 	arc_c_max = MAX(arc_c * 6, arc_c_max);
34912885Sahrens 
34922885Sahrens 	/*
34932885Sahrens 	 * Allow the tunables to override our calculations if they are
34942885Sahrens 	 * reasonable (ie. over 64MB)
34952885Sahrens 	 */
34962885Sahrens 	if (zfs_arc_max > 64<<20 && zfs_arc_max < physmem * PAGESIZE)
34973403Sbmc 		arc_c_max = zfs_arc_max;
34983403Sbmc 	if (zfs_arc_min > 64<<20 && zfs_arc_min <= arc_c_max)
34993403Sbmc 		arc_c_min = zfs_arc_min;
35002885Sahrens 
35013403Sbmc 	arc_c = arc_c_max;
35023403Sbmc 	arc_p = (arc_c >> 1);
3503789Sahrens 
35044309Smaybee 	/* limit meta-data to 1/4 of the arc capacity */
35054309Smaybee 	arc_meta_limit = arc_c_max / 4;
35064645Sek110237 
35074645Sek110237 	/* Allow the tunable to override if it is reasonable */
35084645Sek110237 	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
35094645Sek110237 		arc_meta_limit = zfs_arc_meta_limit;
35104645Sek110237 
35114309Smaybee 	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
35124309Smaybee 		arc_c_min = arc_meta_limit / 2;
35134309Smaybee 
35148582SBrendan.Gregg@Sun.COM 	if (zfs_arc_grow_retry > 0)
35158582SBrendan.Gregg@Sun.COM 		arc_grow_retry = zfs_arc_grow_retry;
35168582SBrendan.Gregg@Sun.COM 
35178582SBrendan.Gregg@Sun.COM 	if (zfs_arc_shrink_shift > 0)
35188582SBrendan.Gregg@Sun.COM 		arc_shrink_shift = zfs_arc_shrink_shift;
35198582SBrendan.Gregg@Sun.COM 
35208582SBrendan.Gregg@Sun.COM 	if (zfs_arc_p_min_shift > 0)
35218582SBrendan.Gregg@Sun.COM 		arc_p_min_shift = zfs_arc_p_min_shift;
35228582SBrendan.Gregg@Sun.COM 
3523789Sahrens 	/* if kmem_flags are set, lets try to use less memory */
3524789Sahrens 	if (kmem_debugging())
35253403Sbmc 		arc_c = arc_c / 2;
35263403Sbmc 	if (arc_c < arc_c_min)
35273403Sbmc 		arc_c = arc_c_min;
3528789Sahrens 
35293403Sbmc 	arc_anon = &ARC_anon;
35303403Sbmc 	arc_mru = &ARC_mru;
35313403Sbmc 	arc_mru_ghost = &ARC_mru_ghost;
35323403Sbmc 	arc_mfu = &ARC_mfu;
35333403Sbmc 	arc_mfu_ghost = &ARC_mfu_ghost;
35345450Sbrendan 	arc_l2c_only = &ARC_l2c_only;
35353403Sbmc 	arc_size = 0;
3536789Sahrens 
35373403Sbmc 	mutex_init(&arc_anon->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
35383403Sbmc 	mutex_init(&arc_mru->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
35393403Sbmc 	mutex_init(&arc_mru_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
35403403Sbmc 	mutex_init(&arc_mfu->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
35413403Sbmc 	mutex_init(&arc_mfu_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
35425450Sbrendan 	mutex_init(&arc_l2c_only->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
35432688Smaybee 
35444309Smaybee 	list_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
35454309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35464309Smaybee 	list_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
35474309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35484309Smaybee 	list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
35494309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35504309Smaybee 	list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
35514309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35524309Smaybee 	list_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
35534309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35544309Smaybee 	list_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
35554309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35564309Smaybee 	list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
35574309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35584309Smaybee 	list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
35594309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35605450Sbrendan 	list_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
35615450Sbrendan 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35625450Sbrendan 	list_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
35635450Sbrendan 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3564789Sahrens 
3565789Sahrens 	buf_init();
3566789Sahrens 
3567789Sahrens 	arc_thread_exit = 0;
35681544Seschrock 	arc_eviction_list = NULL;
35691544Seschrock 	mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
35702887Smaybee 	bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
3571789Sahrens 
35723403Sbmc 	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
35733403Sbmc 	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
35743403Sbmc 
35753403Sbmc 	if (arc_ksp != NULL) {
35763403Sbmc 		arc_ksp->ks_data = &arc_stats;
35773403Sbmc 		kstat_install(arc_ksp);
35783403Sbmc 	}
35793403Sbmc 
3580789Sahrens 	(void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
3581789Sahrens 	    TS_RUN, minclsyspri);
35823158Smaybee 
35833158Smaybee 	arc_dead = FALSE;
35846987Sbrendan 	arc_warm = B_FALSE;
35856245Smaybee 
35866245Smaybee 	if (zfs_write_limit_max == 0)
35877468SMark.Maybee@Sun.COM 		zfs_write_limit_max = ptob(physmem) >> zfs_write_limit_shift;
35886245Smaybee 	else
35896245Smaybee 		zfs_write_limit_shift = 0;
35907468SMark.Maybee@Sun.COM 	mutex_init(&zfs_write_limit_lock, NULL, MUTEX_DEFAULT, NULL);
3591789Sahrens }
3592789Sahrens 
3593789Sahrens void
3594789Sahrens arc_fini(void)
3595789Sahrens {
3596789Sahrens 	mutex_enter(&arc_reclaim_thr_lock);
3597789Sahrens 	arc_thread_exit = 1;
3598789Sahrens 	while (arc_thread_exit != 0)
3599789Sahrens 		cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
3600789Sahrens 	mutex_exit(&arc_reclaim_thr_lock);
3601789Sahrens 
36025642Smaybee 	arc_flush(NULL);
3603789Sahrens 
3604789Sahrens 	arc_dead = TRUE;
3605789Sahrens 
36063403Sbmc 	if (arc_ksp != NULL) {
36073403Sbmc 		kstat_delete(arc_ksp);
36083403Sbmc 		arc_ksp = NULL;
36093403Sbmc 	}
36103403Sbmc 
36111544Seschrock 	mutex_destroy(&arc_eviction_mtx);
3612789Sahrens 	mutex_destroy(&arc_reclaim_thr_lock);
3613789Sahrens 	cv_destroy(&arc_reclaim_thr_cv);
3614789Sahrens 
36154309Smaybee 	list_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
36164309Smaybee 	list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
36174309Smaybee 	list_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
36184309Smaybee 	list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
36194309Smaybee 	list_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
36204309Smaybee 	list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
36214309Smaybee 	list_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
36224309Smaybee 	list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
3623789Sahrens 
36243403Sbmc 	mutex_destroy(&arc_anon->arcs_mtx);
36253403Sbmc 	mutex_destroy(&arc_mru->arcs_mtx);
36263403Sbmc 	mutex_destroy(&arc_mru_ghost->arcs_mtx);
36273403Sbmc 	mutex_destroy(&arc_mfu->arcs_mtx);
36283403Sbmc 	mutex_destroy(&arc_mfu_ghost->arcs_mtx);
36298214SRicardo.M.Correia@Sun.COM 	mutex_destroy(&arc_l2c_only->arcs_mtx);
36302856Snd150628 
36317468SMark.Maybee@Sun.COM 	mutex_destroy(&zfs_write_limit_lock);
36327468SMark.Maybee@Sun.COM 
3633789Sahrens 	buf_fini();
36349412SAleksandr.Guzovskiy@Sun.COM 
36359412SAleksandr.Guzovskiy@Sun.COM 	ASSERT(arc_loaned_bytes == 0);
3636789Sahrens }
36375450Sbrendan 
36385450Sbrendan /*
36395450Sbrendan  * Level 2 ARC
36405450Sbrendan  *
36415450Sbrendan  * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
36425450Sbrendan  * It uses dedicated storage devices to hold cached data, which are populated
36435450Sbrendan  * using large infrequent writes.  The main role of this cache is to boost
36445450Sbrendan  * the performance of random read workloads.  The intended L2ARC devices
36455450Sbrendan  * include short-stroked disks, solid state disks, and other media with
36465450Sbrendan  * substantially faster read latency than disk.
36475450Sbrendan  *
36485450Sbrendan  *                 +-----------------------+
36495450Sbrendan  *                 |         ARC           |
36505450Sbrendan  *                 +-----------------------+
36515450Sbrendan  *                    |         ^     ^
36525450Sbrendan  *                    |         |     |
36535450Sbrendan  *      l2arc_feed_thread()    arc_read()
36545450Sbrendan  *                    |         |     |
36555450Sbrendan  *                    |  l2arc read   |
36565450Sbrendan  *                    V         |     |
36575450Sbrendan  *               +---------------+    |
36585450Sbrendan  *               |     L2ARC     |    |
36595450Sbrendan  *               +---------------+    |
36605450Sbrendan  *                   |    ^           |
36615450Sbrendan  *          l2arc_write() |           |
36625450Sbrendan  *                   |    |           |
36635450Sbrendan  *                   V    |           |
36645450Sbrendan  *                 +-------+      +-------+
36655450Sbrendan  *                 | vdev  |      | vdev  |
36665450Sbrendan  *                 | cache |      | cache |
36675450Sbrendan  *                 +-------+      +-------+
36685450Sbrendan  *                 +=========+     .-----.
36695450Sbrendan  *                 :  L2ARC  :    |-_____-|
36705450Sbrendan  *                 : devices :    | Disks |
36715450Sbrendan  *                 +=========+    `-_____-'
36725450Sbrendan  *
36735450Sbrendan  * Read requests are satisfied from the following sources, in order:
36745450Sbrendan  *
36755450Sbrendan  *	1) ARC
36765450Sbrendan  *	2) vdev cache of L2ARC devices
36775450Sbrendan  *	3) L2ARC devices
36785450Sbrendan  *	4) vdev cache of disks
36795450Sbrendan  *	5) disks
36805450Sbrendan  *
36815450Sbrendan  * Some L2ARC device types exhibit extremely slow write performance.
36825450Sbrendan  * To accommodate for this there are some significant differences between
36835450Sbrendan  * the L2ARC and traditional cache design:
36845450Sbrendan  *
36855450Sbrendan  * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
36865450Sbrendan  * the ARC behave as usual, freeing buffers and placing headers on ghost
36875450Sbrendan  * lists.  The ARC does not send buffers to the L2ARC during eviction as
36885450Sbrendan  * this would add inflated write latencies for all ARC memory pressure.
36895450Sbrendan  *
36905450Sbrendan  * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
36915450Sbrendan  * It does this by periodically scanning buffers from the eviction-end of
36925450Sbrendan  * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
36935450Sbrendan  * not already there.  It scans until a headroom of buffers is satisfied,
36945450Sbrendan  * which itself is a buffer for ARC eviction.  The thread that does this is
36955450Sbrendan  * l2arc_feed_thread(), illustrated below; example sizes are included to
36965450Sbrendan  * provide a better sense of ratio than this diagram:
36975450Sbrendan  *
36985450Sbrendan  *	       head -->                        tail
36995450Sbrendan  *	        +---------------------+----------+
37005450Sbrendan  *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
37015450Sbrendan  *	        +---------------------+----------+   |   o L2ARC eligible
37025450Sbrendan  *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
37035450Sbrendan  *	        +---------------------+----------+   |
37045450Sbrendan  *	             15.9 Gbytes      ^ 32 Mbytes    |
37055450Sbrendan  *	                           headroom          |
37065450Sbrendan  *	                                      l2arc_feed_thread()
37075450Sbrendan  *	                                             |
37085450Sbrendan  *	                 l2arc write hand <--[oooo]--'
37095450Sbrendan  *	                         |           8 Mbyte
37105450Sbrendan  *	                         |          write max
37115450Sbrendan  *	                         V
37125450Sbrendan  *		  +==============================+
37135450Sbrendan  *	L2ARC dev |####|#|###|###|    |####| ... |
37145450Sbrendan  *	          +==============================+
37155450Sbrendan  *	                     32 Gbytes
37165450Sbrendan  *
37175450Sbrendan  * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
37185450Sbrendan  * evicted, then the L2ARC has cached a buffer much sooner than it probably
37195450Sbrendan  * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
37205450Sbrendan  * safe to say that this is an uncommon case, since buffers at the end of
37215450Sbrendan  * the ARC lists have moved there due to inactivity.
37225450Sbrendan  *
37235450Sbrendan  * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
37245450Sbrendan  * then the L2ARC simply misses copying some buffers.  This serves as a
37255450Sbrendan  * pressure valve to prevent heavy read workloads from both stalling the ARC
37265450Sbrendan  * with waits and clogging the L2ARC with writes.  This also helps prevent
37275450Sbrendan  * the potential for the L2ARC to churn if it attempts to cache content too
37285450Sbrendan  * quickly, such as during backups of the entire pool.
37295450Sbrendan  *
37306987Sbrendan  * 5. After system boot and before the ARC has filled main memory, there are
37316987Sbrendan  * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
37326987Sbrendan  * lists can remain mostly static.  Instead of searching from tail of these
37336987Sbrendan  * lists as pictured, the l2arc_feed_thread() will search from the list heads
37346987Sbrendan  * for eligible buffers, greatly increasing its chance of finding them.
37356987Sbrendan  *
37366987Sbrendan  * The L2ARC device write speed is also boosted during this time so that
37376987Sbrendan  * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
37386987Sbrendan  * there are no L2ARC reads, and no fear of degrading read performance
37396987Sbrendan  * through increased writes.
37406987Sbrendan  *
37416987Sbrendan  * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
37425450Sbrendan  * the vdev queue can aggregate them into larger and fewer writes.  Each
37435450Sbrendan  * device is written to in a rotor fashion, sweeping writes through
37445450Sbrendan  * available space then repeating.
37455450Sbrendan  *
37466987Sbrendan  * 7. The L2ARC does not store dirty content.  It never needs to flush
37475450Sbrendan  * write buffers back to disk based storage.
37485450Sbrendan  *
37496987Sbrendan  * 8. If an ARC buffer is written (and dirtied) which also exists in the
37505450Sbrendan  * L2ARC, the now stale L2ARC buffer is immediately dropped.
37515450Sbrendan  *
37525450Sbrendan  * The performance of the L2ARC can be tweaked by a number of tunables, which
37535450Sbrendan  * may be necessary for different workloads:
37545450Sbrendan  *
37555450Sbrendan  *	l2arc_write_max		max write bytes per interval
37566987Sbrendan  *	l2arc_write_boost	extra write bytes during device warmup
37575450Sbrendan  *	l2arc_noprefetch	skip caching prefetched buffers
37585450Sbrendan  *	l2arc_headroom		number of max device writes to precache
37595450Sbrendan  *	l2arc_feed_secs		seconds between L2ARC writing
37605450Sbrendan  *
37615450Sbrendan  * Tunables may be removed or added as future performance improvements are
37625450Sbrendan  * integrated, and also may become zpool properties.
37638582SBrendan.Gregg@Sun.COM  *
37648582SBrendan.Gregg@Sun.COM  * There are three key functions that control how the L2ARC warms up:
37658582SBrendan.Gregg@Sun.COM  *
37668582SBrendan.Gregg@Sun.COM  *	l2arc_write_eligible()	check if a buffer is eligible to cache
37678582SBrendan.Gregg@Sun.COM  *	l2arc_write_size()	calculate how much to write
37688582SBrendan.Gregg@Sun.COM  *	l2arc_write_interval()	calculate sleep delay between writes
37698582SBrendan.Gregg@Sun.COM  *
37708582SBrendan.Gregg@Sun.COM  * These three functions determine what to write, how much, and how quickly
37718582SBrendan.Gregg@Sun.COM  * to send writes.
37725450Sbrendan  */
37735450Sbrendan 
37748582SBrendan.Gregg@Sun.COM static boolean_t
37758636SMark.Maybee@Sun.COM l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *ab)
37768582SBrendan.Gregg@Sun.COM {
37778582SBrendan.Gregg@Sun.COM 	/*
37788582SBrendan.Gregg@Sun.COM 	 * A buffer is *not* eligible for the L2ARC if it:
37798582SBrendan.Gregg@Sun.COM 	 * 1. belongs to a different spa.
378010357SBrendan.Gregg@Sun.COM 	 * 2. is already cached on the L2ARC.
378110357SBrendan.Gregg@Sun.COM 	 * 3. has an I/O in progress (it may be an incomplete read).
378210357SBrendan.Gregg@Sun.COM 	 * 4. is flagged not eligible (zfs property).
37838582SBrendan.Gregg@Sun.COM 	 */
378410357SBrendan.Gregg@Sun.COM 	if (ab->b_spa != spa_guid || ab->b_l2hdr != NULL ||
37858582SBrendan.Gregg@Sun.COM 	    HDR_IO_IN_PROGRESS(ab) || !HDR_L2CACHE(ab))
37868582SBrendan.Gregg@Sun.COM 		return (B_FALSE);
37878582SBrendan.Gregg@Sun.COM 
37888582SBrendan.Gregg@Sun.COM 	return (B_TRUE);
37898582SBrendan.Gregg@Sun.COM }
37908582SBrendan.Gregg@Sun.COM 
37918582SBrendan.Gregg@Sun.COM static uint64_t
37928582SBrendan.Gregg@Sun.COM l2arc_write_size(l2arc_dev_t *dev)
37938582SBrendan.Gregg@Sun.COM {
37948582SBrendan.Gregg@Sun.COM 	uint64_t size;
37958582SBrendan.Gregg@Sun.COM 
37968582SBrendan.Gregg@Sun.COM 	size = dev->l2ad_write;
37978582SBrendan.Gregg@Sun.COM 
37988582SBrendan.Gregg@Sun.COM 	if (arc_warm == B_FALSE)
37998582SBrendan.Gregg@Sun.COM 		size += dev->l2ad_boost;
38008582SBrendan.Gregg@Sun.COM 
38018582SBrendan.Gregg@Sun.COM 	return (size);
38028582SBrendan.Gregg@Sun.COM 
38038582SBrendan.Gregg@Sun.COM }
38048582SBrendan.Gregg@Sun.COM 
38058582SBrendan.Gregg@Sun.COM static clock_t
38068582SBrendan.Gregg@Sun.COM l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
38078582SBrendan.Gregg@Sun.COM {
38088582SBrendan.Gregg@Sun.COM 	clock_t interval, next;
38098582SBrendan.Gregg@Sun.COM 
38108582SBrendan.Gregg@Sun.COM 	/*
38118582SBrendan.Gregg@Sun.COM 	 * If the ARC lists are busy, increase our write rate; if the
38128582SBrendan.Gregg@Sun.COM 	 * lists are stale, idle back.  This is achieved by checking
38138582SBrendan.Gregg@Sun.COM 	 * how much we previously wrote - if it was more than half of
38148582SBrendan.Gregg@Sun.COM 	 * what we wanted, schedule the next write much sooner.
38158582SBrendan.Gregg@Sun.COM 	 */
38168582SBrendan.Gregg@Sun.COM 	if (l2arc_feed_again && wrote > (wanted / 2))
38178582SBrendan.Gregg@Sun.COM 		interval = (hz * l2arc_feed_min_ms) / 1000;
38188582SBrendan.Gregg@Sun.COM 	else
38198582SBrendan.Gregg@Sun.COM 		interval = hz * l2arc_feed_secs;
38208582SBrendan.Gregg@Sun.COM 
38218582SBrendan.Gregg@Sun.COM 	next = MAX(lbolt, MIN(lbolt + interval, began + interval));
38228582SBrendan.Gregg@Sun.COM 
38238582SBrendan.Gregg@Sun.COM 	return (next);
38248582SBrendan.Gregg@Sun.COM }
38258582SBrendan.Gregg@Sun.COM 
38265450Sbrendan static void
38275450Sbrendan l2arc_hdr_stat_add(void)
38285450Sbrendan {
38296018Sbrendan 	ARCSTAT_INCR(arcstat_l2_hdr_size, HDR_SIZE + L2HDR_SIZE);
38306018Sbrendan 	ARCSTAT_INCR(arcstat_hdr_size, -HDR_SIZE);
38315450Sbrendan }
38325450Sbrendan 
38335450Sbrendan static void
38345450Sbrendan l2arc_hdr_stat_remove(void)
38355450Sbrendan {
38366018Sbrendan 	ARCSTAT_INCR(arcstat_l2_hdr_size, -(HDR_SIZE + L2HDR_SIZE));
38376018Sbrendan 	ARCSTAT_INCR(arcstat_hdr_size, HDR_SIZE);
38385450Sbrendan }
38395450Sbrendan 
38405450Sbrendan /*
38415450Sbrendan  * Cycle through L2ARC devices.  This is how L2ARC load balances.
38426987Sbrendan  * If a device is returned, this also returns holding the spa config lock.
38435450Sbrendan  */
38445450Sbrendan static l2arc_dev_t *
38455450Sbrendan l2arc_dev_get_next(void)
38465450Sbrendan {
38476987Sbrendan 	l2arc_dev_t *first, *next = NULL;
38486987Sbrendan 
38496987Sbrendan 	/*
38506987Sbrendan 	 * Lock out the removal of spas (spa_namespace_lock), then removal
38516987Sbrendan 	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
38526987Sbrendan 	 * both locks will be dropped and a spa config lock held instead.
38536987Sbrendan 	 */
38546987Sbrendan 	mutex_enter(&spa_namespace_lock);
38556987Sbrendan 	mutex_enter(&l2arc_dev_mtx);
38566643Seschrock 
38576643Seschrock 	/* if there are no vdevs, there is nothing to do */
38586643Seschrock 	if (l2arc_ndev == 0)
38596987Sbrendan 		goto out;
38606643Seschrock 
38616643Seschrock 	first = NULL;
38626643Seschrock 	next = l2arc_dev_last;
38636643Seschrock 	do {
38646643Seschrock 		/* loop around the list looking for a non-faulted vdev */
38656643Seschrock 		if (next == NULL) {
38665450Sbrendan 			next = list_head(l2arc_dev_list);
38676643Seschrock 		} else {
38686643Seschrock 			next = list_next(l2arc_dev_list, next);
38696643Seschrock 			if (next == NULL)
38706643Seschrock 				next = list_head(l2arc_dev_list);
38716643Seschrock 		}
38726643Seschrock 
38736643Seschrock 		/* if we have come back to the start, bail out */
38746643Seschrock 		if (first == NULL)
38756643Seschrock 			first = next;
38766643Seschrock 		else if (next == first)
38776643Seschrock 			break;
38786643Seschrock 
38796643Seschrock 	} while (vdev_is_dead(next->l2ad_vdev));
38806643Seschrock 
38816643Seschrock 	/* if we were unable to find any usable vdevs, return NULL */
38826643Seschrock 	if (vdev_is_dead(next->l2ad_vdev))
38836987Sbrendan 		next = NULL;
38845450Sbrendan 
38855450Sbrendan 	l2arc_dev_last = next;
38865450Sbrendan 
38876987Sbrendan out:
38886987Sbrendan 	mutex_exit(&l2arc_dev_mtx);
38896987Sbrendan 
38906987Sbrendan 	/*
38916987Sbrendan 	 * Grab the config lock to prevent the 'next' device from being
38926987Sbrendan 	 * removed while we are writing to it.
38936987Sbrendan 	 */
38946987Sbrendan 	if (next != NULL)
38957754SJeff.Bonwick@Sun.COM 		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
38966987Sbrendan 	mutex_exit(&spa_namespace_lock);
38976987Sbrendan 
38985450Sbrendan 	return (next);
38995450Sbrendan }
39005450Sbrendan 
39015450Sbrendan /*
39026987Sbrendan  * Free buffers that were tagged for destruction.
39036987Sbrendan  */
39046987Sbrendan static void
39056987Sbrendan l2arc_do_free_on_write()
39066987Sbrendan {
39076987Sbrendan 	list_t *buflist;
39086987Sbrendan 	l2arc_data_free_t *df, *df_prev;
39096987Sbrendan 
39106987Sbrendan 	mutex_enter(&l2arc_free_on_write_mtx);
39116987Sbrendan 	buflist = l2arc_free_on_write;
39126987Sbrendan 
39136987Sbrendan 	for (df = list_tail(buflist); df; df = df_prev) {
39146987Sbrendan 		df_prev = list_prev(buflist, df);
39156987Sbrendan 		ASSERT(df->l2df_data != NULL);
39166987Sbrendan 		ASSERT(df->l2df_func != NULL);
39176987Sbrendan 		df->l2df_func(df->l2df_data, df->l2df_size);
39186987Sbrendan 		list_remove(buflist, df);
39196987Sbrendan 		kmem_free(df, sizeof (l2arc_data_free_t));
39206987Sbrendan 	}
39216987Sbrendan 
39226987Sbrendan 	mutex_exit(&l2arc_free_on_write_mtx);
39236987Sbrendan }
39246987Sbrendan 
39256987Sbrendan /*
39265450Sbrendan  * A write to a cache device has completed.  Update all headers to allow
39275450Sbrendan  * reads from these buffers to begin.
39285450Sbrendan  */
39295450Sbrendan static void
39305450Sbrendan l2arc_write_done(zio_t *zio)
39315450Sbrendan {
39325450Sbrendan 	l2arc_write_callback_t *cb;
39335450Sbrendan 	l2arc_dev_t *dev;
39345450Sbrendan 	list_t *buflist;
39355450Sbrendan 	arc_buf_hdr_t *head, *ab, *ab_prev;
39366987Sbrendan 	l2arc_buf_hdr_t *abl2;
39375450Sbrendan 	kmutex_t *hash_lock;
39385450Sbrendan 
39395450Sbrendan 	cb = zio->io_private;
39405450Sbrendan 	ASSERT(cb != NULL);
39415450Sbrendan 	dev = cb->l2wcb_dev;
39425450Sbrendan 	ASSERT(dev != NULL);
39435450Sbrendan 	head = cb->l2wcb_head;
39445450Sbrendan 	ASSERT(head != NULL);
39455450Sbrendan 	buflist = dev->l2ad_buflist;
39465450Sbrendan 	ASSERT(buflist != NULL);
39475450Sbrendan 	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
39485450Sbrendan 	    l2arc_write_callback_t *, cb);
39495450Sbrendan 
39505450Sbrendan 	if (zio->io_error != 0)
39515450Sbrendan 		ARCSTAT_BUMP(arcstat_l2_writes_error);
39525450Sbrendan 
39535450Sbrendan 	mutex_enter(&l2arc_buflist_mtx);
39545450Sbrendan 
39555450Sbrendan 	/*
39565450Sbrendan 	 * All writes completed, or an error was hit.
39575450Sbrendan 	 */
39585450Sbrendan 	for (ab = list_prev(buflist, head); ab; ab = ab_prev) {
39595450Sbrendan 		ab_prev = list_prev(buflist, ab);
39605450Sbrendan 
39615450Sbrendan 		hash_lock = HDR_LOCK(ab);
39625450Sbrendan 		if (!mutex_tryenter(hash_lock)) {
39635450Sbrendan 			/*
39645450Sbrendan 			 * This buffer misses out.  It may be in a stage
39655450Sbrendan 			 * of eviction.  Its ARC_L2_WRITING flag will be
39665450Sbrendan 			 * left set, denying reads to this buffer.
39675450Sbrendan 			 */
39685450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_writes_hdr_miss);
39695450Sbrendan 			continue;
39705450Sbrendan 		}
39715450Sbrendan 
39725450Sbrendan 		if (zio->io_error != 0) {
39735450Sbrendan 			/*
39746987Sbrendan 			 * Error - drop L2ARC entry.
39755450Sbrendan 			 */
39766987Sbrendan 			list_remove(buflist, ab);
39776987Sbrendan 			abl2 = ab->b_l2hdr;
39785450Sbrendan 			ab->b_l2hdr = NULL;
39796987Sbrendan 			kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
39806987Sbrendan 			ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
39815450Sbrendan 		}
39825450Sbrendan 
39835450Sbrendan 		/*
39845450Sbrendan 		 * Allow ARC to begin reads to this L2ARC entry.
39855450Sbrendan 		 */
39865450Sbrendan 		ab->b_flags &= ~ARC_L2_WRITING;
39875450Sbrendan 
39885450Sbrendan 		mutex_exit(hash_lock);
39895450Sbrendan 	}
39905450Sbrendan 
39915450Sbrendan 	atomic_inc_64(&l2arc_writes_done);
39925450Sbrendan 	list_remove(buflist, head);
39935450Sbrendan 	kmem_cache_free(hdr_cache, head);
39945450Sbrendan 	mutex_exit(&l2arc_buflist_mtx);
39955450Sbrendan 
39966987Sbrendan 	l2arc_do_free_on_write();
39975450Sbrendan 
39985450Sbrendan 	kmem_free(cb, sizeof (l2arc_write_callback_t));
39995450Sbrendan }
40005450Sbrendan 
40015450Sbrendan /*
40025450Sbrendan  * A read to a cache device completed.  Validate buffer contents before
40035450Sbrendan  * handing over to the regular ARC routines.
40045450Sbrendan  */
40055450Sbrendan static void
40065450Sbrendan l2arc_read_done(zio_t *zio)
40075450Sbrendan {
40085450Sbrendan 	l2arc_read_callback_t *cb;
40095450Sbrendan 	arc_buf_hdr_t *hdr;
40105450Sbrendan 	arc_buf_t *buf;
40115450Sbrendan 	kmutex_t *hash_lock;
40126987Sbrendan 	int equal;
40135450Sbrendan 
40147754SJeff.Bonwick@Sun.COM 	ASSERT(zio->io_vd != NULL);
40157754SJeff.Bonwick@Sun.COM 	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
40167754SJeff.Bonwick@Sun.COM 
40177754SJeff.Bonwick@Sun.COM 	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
40187754SJeff.Bonwick@Sun.COM 
40195450Sbrendan 	cb = zio->io_private;
40205450Sbrendan 	ASSERT(cb != NULL);
40215450Sbrendan 	buf = cb->l2rcb_buf;
40225450Sbrendan 	ASSERT(buf != NULL);
40235450Sbrendan 	hdr = buf->b_hdr;
40245450Sbrendan 	ASSERT(hdr != NULL);
40255450Sbrendan 
40265450Sbrendan 	hash_lock = HDR_LOCK(hdr);
40275450Sbrendan 	mutex_enter(hash_lock);
40285450Sbrendan 
40295450Sbrendan 	/*
40305450Sbrendan 	 * Check this survived the L2ARC journey.
40315450Sbrendan 	 */
40325450Sbrendan 	equal = arc_cksum_equal(buf);
40335450Sbrendan 	if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
40345450Sbrendan 		mutex_exit(hash_lock);
40355450Sbrendan 		zio->io_private = buf;
40367754SJeff.Bonwick@Sun.COM 		zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
40377754SJeff.Bonwick@Sun.COM 		zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
40385450Sbrendan 		arc_read_done(zio);
40395450Sbrendan 	} else {
40405450Sbrendan 		mutex_exit(hash_lock);
40415450Sbrendan 		/*
40425450Sbrendan 		 * Buffer didn't survive caching.  Increment stats and
40435450Sbrendan 		 * reissue to the original storage device.
40445450Sbrendan 		 */
40456987Sbrendan 		if (zio->io_error != 0) {
40465450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_io_error);
40476987Sbrendan 		} else {
40486987Sbrendan 			zio->io_error = EIO;
40496987Sbrendan 		}
40505450Sbrendan 		if (!equal)
40515450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
40525450Sbrendan 
40537754SJeff.Bonwick@Sun.COM 		/*
40547754SJeff.Bonwick@Sun.COM 		 * If there's no waiter, issue an async i/o to the primary
40557754SJeff.Bonwick@Sun.COM 		 * storage now.  If there *is* a waiter, the caller must
40567754SJeff.Bonwick@Sun.COM 		 * issue the i/o in a context where it's OK to block.
40577754SJeff.Bonwick@Sun.COM 		 */
40588632SBill.Moore@Sun.COM 		if (zio->io_waiter == NULL) {
40598632SBill.Moore@Sun.COM 			zio_t *pio = zio_unique_parent(zio);
40608632SBill.Moore@Sun.COM 
40618632SBill.Moore@Sun.COM 			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
40628632SBill.Moore@Sun.COM 
40638632SBill.Moore@Sun.COM 			zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
40647754SJeff.Bonwick@Sun.COM 			    buf->b_data, zio->io_size, arc_read_done, buf,
40657754SJeff.Bonwick@Sun.COM 			    zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
40668632SBill.Moore@Sun.COM 		}
40675450Sbrendan 	}
40685450Sbrendan 
40695450Sbrendan 	kmem_free(cb, sizeof (l2arc_read_callback_t));
40705450Sbrendan }
40715450Sbrendan 
40725450Sbrendan /*
40735450Sbrendan  * This is the list priority from which the L2ARC will search for pages to
40745450Sbrendan  * cache.  This is used within loops (0..3) to cycle through lists in the
40755450Sbrendan  * desired order.  This order can have a significant effect on cache
40765450Sbrendan  * performance.
40775450Sbrendan  *
40785450Sbrendan  * Currently the metadata lists are hit first, MFU then MRU, followed by
40795450Sbrendan  * the data lists.  This function returns a locked list, and also returns
40805450Sbrendan  * the lock pointer.
40815450Sbrendan  */
40825450Sbrendan static list_t *
40835450Sbrendan l2arc_list_locked(int list_num, kmutex_t **lock)
40845450Sbrendan {
40855450Sbrendan 	list_t *list;
40865450Sbrendan 
40875450Sbrendan 	ASSERT(list_num >= 0 && list_num <= 3);
40885450Sbrendan 
40895450Sbrendan 	switch (list_num) {
40905450Sbrendan 	case 0:
40915450Sbrendan 		list = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
40925450Sbrendan 		*lock = &arc_mfu->arcs_mtx;
40935450Sbrendan 		break;
40945450Sbrendan 	case 1:
40955450Sbrendan 		list = &arc_mru->arcs_list[ARC_BUFC_METADATA];
40965450Sbrendan 		*lock = &arc_mru->arcs_mtx;
40975450Sbrendan 		break;
40985450Sbrendan 	case 2:
40995450Sbrendan 		list = &arc_mfu->arcs_list[ARC_BUFC_DATA];
41005450Sbrendan 		*lock = &arc_mfu->arcs_mtx;
41015450Sbrendan 		break;
41025450Sbrendan 	case 3:
41035450Sbrendan 		list = &arc_mru->arcs_list[ARC_BUFC_DATA];
41045450Sbrendan 		*lock = &arc_mru->arcs_mtx;
41055450Sbrendan 		break;
41065450Sbrendan 	}
41075450Sbrendan 
41085450Sbrendan 	ASSERT(!(MUTEX_HELD(*lock)));
41095450Sbrendan 	mutex_enter(*lock);
41105450Sbrendan 	return (list);
41115450Sbrendan }
41125450Sbrendan 
41135450Sbrendan /*
41145450Sbrendan  * Evict buffers from the device write hand to the distance specified in
41155450Sbrendan  * bytes.  This distance may span populated buffers, it may span nothing.
41165450Sbrendan  * This is clearing a region on the L2ARC device ready for writing.
41175450Sbrendan  * If the 'all' boolean is set, every buffer is evicted.
41185450Sbrendan  */
41195450Sbrendan static void
41205450Sbrendan l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
41215450Sbrendan {
41225450Sbrendan 	list_t *buflist;
41235450Sbrendan 	l2arc_buf_hdr_t *abl2;
41245450Sbrendan 	arc_buf_hdr_t *ab, *ab_prev;
41255450Sbrendan 	kmutex_t *hash_lock;
41265450Sbrendan 	uint64_t taddr;
41275450Sbrendan 
41285450Sbrendan 	buflist = dev->l2ad_buflist;
41295450Sbrendan 
41305450Sbrendan 	if (buflist == NULL)
41315450Sbrendan 		return;
41325450Sbrendan 
41335450Sbrendan 	if (!all && dev->l2ad_first) {
41345450Sbrendan 		/*
41355450Sbrendan 		 * This is the first sweep through the device.  There is
41365450Sbrendan 		 * nothing to evict.
41375450Sbrendan 		 */
41385450Sbrendan 		return;
41395450Sbrendan 	}
41405450Sbrendan 
41416987Sbrendan 	if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
41425450Sbrendan 		/*
41435450Sbrendan 		 * When nearing the end of the device, evict to the end
41445450Sbrendan 		 * before the device write hand jumps to the start.
41455450Sbrendan 		 */
41465450Sbrendan 		taddr = dev->l2ad_end;
41475450Sbrendan 	} else {
41485450Sbrendan 		taddr = dev->l2ad_hand + distance;
41495450Sbrendan 	}
41505450Sbrendan 	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
41515450Sbrendan 	    uint64_t, taddr, boolean_t, all);
41525450Sbrendan 
41535450Sbrendan top:
41545450Sbrendan 	mutex_enter(&l2arc_buflist_mtx);
41555450Sbrendan 	for (ab = list_tail(buflist); ab; ab = ab_prev) {
41565450Sbrendan 		ab_prev = list_prev(buflist, ab);
41575450Sbrendan 
41585450Sbrendan 		hash_lock = HDR_LOCK(ab);
41595450Sbrendan 		if (!mutex_tryenter(hash_lock)) {
41605450Sbrendan 			/*
41615450Sbrendan 			 * Missed the hash lock.  Retry.
41625450Sbrendan 			 */
41635450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
41645450Sbrendan 			mutex_exit(&l2arc_buflist_mtx);
41655450Sbrendan 			mutex_enter(hash_lock);
41665450Sbrendan 			mutex_exit(hash_lock);
41675450Sbrendan 			goto top;
41685450Sbrendan 		}
41695450Sbrendan 
41705450Sbrendan 		if (HDR_L2_WRITE_HEAD(ab)) {
41715450Sbrendan 			/*
41725450Sbrendan 			 * We hit a write head node.  Leave it for
41735450Sbrendan 			 * l2arc_write_done().
41745450Sbrendan 			 */
41755450Sbrendan 			list_remove(buflist, ab);
41765450Sbrendan 			mutex_exit(hash_lock);
41775450Sbrendan 			continue;
41785450Sbrendan 		}
41795450Sbrendan 
41805450Sbrendan 		if (!all && ab->b_l2hdr != NULL &&
41815450Sbrendan 		    (ab->b_l2hdr->b_daddr > taddr ||
41825450Sbrendan 		    ab->b_l2hdr->b_daddr < dev->l2ad_hand)) {
41835450Sbrendan 			/*
41845450Sbrendan 			 * We've evicted to the target address,
41855450Sbrendan 			 * or the end of the device.
41865450Sbrendan 			 */
41875450Sbrendan 			mutex_exit(hash_lock);
41885450Sbrendan 			break;
41895450Sbrendan 		}
41905450Sbrendan 
41915450Sbrendan 		if (HDR_FREE_IN_PROGRESS(ab)) {
41925450Sbrendan 			/*
41935450Sbrendan 			 * Already on the path to destruction.
41945450Sbrendan 			 */
41955450Sbrendan 			mutex_exit(hash_lock);
41965450Sbrendan 			continue;
41975450Sbrendan 		}
41985450Sbrendan 
41995450Sbrendan 		if (ab->b_state == arc_l2c_only) {
42005450Sbrendan 			ASSERT(!HDR_L2_READING(ab));
42015450Sbrendan 			/*
42025450Sbrendan 			 * This doesn't exist in the ARC.  Destroy.
42035450Sbrendan 			 * arc_hdr_destroy() will call list_remove()
42045450Sbrendan 			 * and decrement arcstat_l2_size.
42055450Sbrendan 			 */
42065450Sbrendan 			arc_change_state(arc_anon, ab, hash_lock);
42075450Sbrendan 			arc_hdr_destroy(ab);
42085450Sbrendan 		} else {
42095450Sbrendan 			/*
42106987Sbrendan 			 * Invalidate issued or about to be issued
42116987Sbrendan 			 * reads, since we may be about to write
42126987Sbrendan 			 * over this location.
42136987Sbrendan 			 */
42146987Sbrendan 			if (HDR_L2_READING(ab)) {
42156987Sbrendan 				ARCSTAT_BUMP(arcstat_l2_evict_reading);
42166987Sbrendan 				ab->b_flags |= ARC_L2_EVICTED;
42176987Sbrendan 			}
42186987Sbrendan 
42196987Sbrendan 			/*
42205450Sbrendan 			 * Tell ARC this no longer exists in L2ARC.
42215450Sbrendan 			 */
42225450Sbrendan 			if (ab->b_l2hdr != NULL) {
42235450Sbrendan 				abl2 = ab->b_l2hdr;
42245450Sbrendan 				ab->b_l2hdr = NULL;
42255450Sbrendan 				kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
42265450Sbrendan 				ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
42275450Sbrendan 			}
42285450Sbrendan 			list_remove(buflist, ab);
42295450Sbrendan 
42305450Sbrendan 			/*
42315450Sbrendan 			 * This may have been leftover after a
42325450Sbrendan 			 * failed write.
42335450Sbrendan 			 */
42345450Sbrendan 			ab->b_flags &= ~ARC_L2_WRITING;
42355450Sbrendan 		}
42365450Sbrendan 		mutex_exit(hash_lock);
42375450Sbrendan 	}
42385450Sbrendan 	mutex_exit(&l2arc_buflist_mtx);
42395450Sbrendan 
42405450Sbrendan 	spa_l2cache_space_update(dev->l2ad_vdev, 0, -(taddr - dev->l2ad_evict));
42415450Sbrendan 	dev->l2ad_evict = taddr;
42425450Sbrendan }
42435450Sbrendan 
42445450Sbrendan /*
42455450Sbrendan  * Find and write ARC buffers to the L2ARC device.
42465450Sbrendan  *
42475450Sbrendan  * An ARC_L2_WRITING flag is set so that the L2ARC buffers are not valid
42485450Sbrendan  * for reading until they have completed writing.
42495450Sbrendan  */
42508582SBrendan.Gregg@Sun.COM static uint64_t
42516987Sbrendan l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
42525450Sbrendan {
42535450Sbrendan 	arc_buf_hdr_t *ab, *ab_prev, *head;
42545450Sbrendan 	l2arc_buf_hdr_t *hdrl2;
42555450Sbrendan 	list_t *list;
42566987Sbrendan 	uint64_t passed_sz, write_sz, buf_sz, headroom;
42575450Sbrendan 	void *buf_data;
42585450Sbrendan 	kmutex_t *hash_lock, *list_lock;
42595450Sbrendan 	boolean_t have_lock, full;
42605450Sbrendan 	l2arc_write_callback_t *cb;
42615450Sbrendan 	zio_t *pio, *wzio;
42628636SMark.Maybee@Sun.COM 	uint64_t guid = spa_guid(spa);
42635450Sbrendan 
42645450Sbrendan 	ASSERT(dev->l2ad_vdev != NULL);
42655450Sbrendan 
42665450Sbrendan 	pio = NULL;
42675450Sbrendan 	write_sz = 0;
42685450Sbrendan 	full = B_FALSE;
42696245Smaybee 	head = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
42705450Sbrendan 	head->b_flags |= ARC_L2_WRITE_HEAD;
42715450Sbrendan 
42725450Sbrendan 	/*
42735450Sbrendan 	 * Copy buffers for L2ARC writing.
42745450Sbrendan 	 */
42755450Sbrendan 	mutex_enter(&l2arc_buflist_mtx);
42765450Sbrendan 	for (int try = 0; try <= 3; try++) {
42775450Sbrendan 		list = l2arc_list_locked(try, &list_lock);
42785450Sbrendan 		passed_sz = 0;
42795450Sbrendan 
42806987Sbrendan 		/*
42816987Sbrendan 		 * L2ARC fast warmup.
42826987Sbrendan 		 *
42836987Sbrendan 		 * Until the ARC is warm and starts to evict, read from the
42846987Sbrendan 		 * head of the ARC lists rather than the tail.
42856987Sbrendan 		 */
42866987Sbrendan 		headroom = target_sz * l2arc_headroom;
42876987Sbrendan 		if (arc_warm == B_FALSE)
42886987Sbrendan 			ab = list_head(list);
42896987Sbrendan 		else
42906987Sbrendan 			ab = list_tail(list);
42916987Sbrendan 
42926987Sbrendan 		for (; ab; ab = ab_prev) {
42936987Sbrendan 			if (arc_warm == B_FALSE)
42946987Sbrendan 				ab_prev = list_next(list, ab);
42956987Sbrendan 			else
42966987Sbrendan 				ab_prev = list_prev(list, ab);
42975450Sbrendan 
42985450Sbrendan 			hash_lock = HDR_LOCK(ab);
42995450Sbrendan 			have_lock = MUTEX_HELD(hash_lock);
43005450Sbrendan 			if (!have_lock && !mutex_tryenter(hash_lock)) {
43015450Sbrendan 				/*
43025450Sbrendan 				 * Skip this buffer rather than waiting.
43035450Sbrendan 				 */
43045450Sbrendan 				continue;
43055450Sbrendan 			}
43065450Sbrendan 
43075450Sbrendan 			passed_sz += ab->b_size;
43085450Sbrendan 			if (passed_sz > headroom) {
43095450Sbrendan 				/*
43105450Sbrendan 				 * Searched too far.
43115450Sbrendan 				 */
43125450Sbrendan 				mutex_exit(hash_lock);
43135450Sbrendan 				break;
43145450Sbrendan 			}
43155450Sbrendan 
43168636SMark.Maybee@Sun.COM 			if (!l2arc_write_eligible(guid, ab)) {
43175450Sbrendan 				mutex_exit(hash_lock);
43185450Sbrendan 				continue;
43195450Sbrendan 			}
43205450Sbrendan 
43215450Sbrendan 			if ((write_sz + ab->b_size) > target_sz) {
43225450Sbrendan 				full = B_TRUE;
43235450Sbrendan 				mutex_exit(hash_lock);
43245450Sbrendan 				break;
43255450Sbrendan 			}
43265450Sbrendan 
43275450Sbrendan 			if (pio == NULL) {
43285450Sbrendan 				/*
43295450Sbrendan 				 * Insert a dummy header on the buflist so
43305450Sbrendan 				 * l2arc_write_done() can find where the
43315450Sbrendan 				 * write buffers begin without searching.
43325450Sbrendan 				 */
43335450Sbrendan 				list_insert_head(dev->l2ad_buflist, head);
43345450Sbrendan 
43355450Sbrendan 				cb = kmem_alloc(
43365450Sbrendan 				    sizeof (l2arc_write_callback_t), KM_SLEEP);
43375450Sbrendan 				cb->l2wcb_dev = dev;
43385450Sbrendan 				cb->l2wcb_head = head;
43395450Sbrendan 				pio = zio_root(spa, l2arc_write_done, cb,
43405450Sbrendan 				    ZIO_FLAG_CANFAIL);
43415450Sbrendan 			}
43425450Sbrendan 
43435450Sbrendan 			/*
43445450Sbrendan 			 * Create and add a new L2ARC header.
43455450Sbrendan 			 */
43465450Sbrendan 			hdrl2 = kmem_zalloc(sizeof (l2arc_buf_hdr_t), KM_SLEEP);
43475450Sbrendan 			hdrl2->b_dev = dev;
43485450Sbrendan 			hdrl2->b_daddr = dev->l2ad_hand;
43495450Sbrendan 
43505450Sbrendan 			ab->b_flags |= ARC_L2_WRITING;
43515450Sbrendan 			ab->b_l2hdr = hdrl2;
43525450Sbrendan 			list_insert_head(dev->l2ad_buflist, ab);
43535450Sbrendan 			buf_data = ab->b_buf->b_data;
43545450Sbrendan 			buf_sz = ab->b_size;
43555450Sbrendan 
43565450Sbrendan 			/*
43575450Sbrendan 			 * Compute and store the buffer cksum before
43585450Sbrendan 			 * writing.  On debug the cksum is verified first.
43595450Sbrendan 			 */
43605450Sbrendan 			arc_cksum_verify(ab->b_buf);
43615450Sbrendan 			arc_cksum_compute(ab->b_buf, B_TRUE);
43625450Sbrendan 
43635450Sbrendan 			mutex_exit(hash_lock);
43645450Sbrendan 
43655450Sbrendan 			wzio = zio_write_phys(pio, dev->l2ad_vdev,
43665450Sbrendan 			    dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
43675450Sbrendan 			    NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
43685450Sbrendan 			    ZIO_FLAG_CANFAIL, B_FALSE);
43695450Sbrendan 
43705450Sbrendan 			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
43715450Sbrendan 			    zio_t *, wzio);
43725450Sbrendan 			(void) zio_nowait(wzio);
43735450Sbrendan 
43747754SJeff.Bonwick@Sun.COM 			/*
43757754SJeff.Bonwick@Sun.COM 			 * Keep the clock hand suitably device-aligned.
43767754SJeff.Bonwick@Sun.COM 			 */
43777754SJeff.Bonwick@Sun.COM 			buf_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
43787754SJeff.Bonwick@Sun.COM 
43795450Sbrendan 			write_sz += buf_sz;
43805450Sbrendan 			dev->l2ad_hand += buf_sz;
43815450Sbrendan 		}
43825450Sbrendan 
43835450Sbrendan 		mutex_exit(list_lock);
43845450Sbrendan 
43855450Sbrendan 		if (full == B_TRUE)
43865450Sbrendan 			break;
43875450Sbrendan 	}
43885450Sbrendan 	mutex_exit(&l2arc_buflist_mtx);
43895450Sbrendan 
43905450Sbrendan 	if (pio == NULL) {
43915450Sbrendan 		ASSERT3U(write_sz, ==, 0);
43925450Sbrendan 		kmem_cache_free(hdr_cache, head);
43938582SBrendan.Gregg@Sun.COM 		return (0);
43945450Sbrendan 	}
43955450Sbrendan 
43965450Sbrendan 	ASSERT3U(write_sz, <=, target_sz);
43975450Sbrendan 	ARCSTAT_BUMP(arcstat_l2_writes_sent);
43988582SBrendan.Gregg@Sun.COM 	ARCSTAT_INCR(arcstat_l2_write_bytes, write_sz);
43995450Sbrendan 	ARCSTAT_INCR(arcstat_l2_size, write_sz);
44005450Sbrendan 	spa_l2cache_space_update(dev->l2ad_vdev, 0, write_sz);
44015450Sbrendan 
44025450Sbrendan 	/*
44035450Sbrendan 	 * Bump device hand to the device start if it is approaching the end.
44045450Sbrendan 	 * l2arc_evict() will already have evicted ahead for this case.
44055450Sbrendan 	 */
44066987Sbrendan 	if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
44075450Sbrendan 		spa_l2cache_space_update(dev->l2ad_vdev, 0,
44085450Sbrendan 		    dev->l2ad_end - dev->l2ad_hand);
44095450Sbrendan 		dev->l2ad_hand = dev->l2ad_start;
44105450Sbrendan 		dev->l2ad_evict = dev->l2ad_start;
44115450Sbrendan 		dev->l2ad_first = B_FALSE;
44125450Sbrendan 	}
44135450Sbrendan 
44148582SBrendan.Gregg@Sun.COM 	dev->l2ad_writing = B_TRUE;
44155450Sbrendan 	(void) zio_wait(pio);
44168582SBrendan.Gregg@Sun.COM 	dev->l2ad_writing = B_FALSE;
44178582SBrendan.Gregg@Sun.COM 
44188582SBrendan.Gregg@Sun.COM 	return (write_sz);
44195450Sbrendan }
44205450Sbrendan 
44215450Sbrendan /*
44225450Sbrendan  * This thread feeds the L2ARC at regular intervals.  This is the beating
44235450Sbrendan  * heart of the L2ARC.
44245450Sbrendan  */
44255450Sbrendan static void
44265450Sbrendan l2arc_feed_thread(void)
44275450Sbrendan {
44285450Sbrendan 	callb_cpr_t cpr;
44295450Sbrendan 	l2arc_dev_t *dev;
44305450Sbrendan 	spa_t *spa;
44318582SBrendan.Gregg@Sun.COM 	uint64_t size, wrote;
44328582SBrendan.Gregg@Sun.COM 	clock_t begin, next = lbolt;
44335450Sbrendan 
44345450Sbrendan 	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
44355450Sbrendan 
44365450Sbrendan 	mutex_enter(&l2arc_feed_thr_lock);
44375450Sbrendan 
44385450Sbrendan 	while (l2arc_thread_exit == 0) {
44395450Sbrendan 		CALLB_CPR_SAFE_BEGIN(&cpr);
44406987Sbrendan 		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
44418582SBrendan.Gregg@Sun.COM 		    next);
44426987Sbrendan 		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
44438582SBrendan.Gregg@Sun.COM 		next = lbolt + hz;
44446987Sbrendan 
44456987Sbrendan 		/*
44466987Sbrendan 		 * Quick check for L2ARC devices.
44476987Sbrendan 		 */
44486987Sbrendan 		mutex_enter(&l2arc_dev_mtx);
44496987Sbrendan 		if (l2arc_ndev == 0) {
44506987Sbrendan 			mutex_exit(&l2arc_dev_mtx);
44516987Sbrendan 			continue;
44525450Sbrendan 		}
44536987Sbrendan 		mutex_exit(&l2arc_dev_mtx);
44548582SBrendan.Gregg@Sun.COM 		begin = lbolt;
44556643Seschrock 
44565450Sbrendan 		/*
44576643Seschrock 		 * This selects the next l2arc device to write to, and in
44586643Seschrock 		 * doing so the next spa to feed from: dev->l2ad_spa.   This
44596987Sbrendan 		 * will return NULL if there are now no l2arc devices or if
44606987Sbrendan 		 * they are all faulted.
44616987Sbrendan 		 *
44626987Sbrendan 		 * If a device is returned, its spa's config lock is also
44636987Sbrendan 		 * held to prevent device removal.  l2arc_dev_get_next()
44646987Sbrendan 		 * will grab and release l2arc_dev_mtx.
44655450Sbrendan 		 */
44666987Sbrendan 		if ((dev = l2arc_dev_get_next()) == NULL)
44675450Sbrendan 			continue;
44686987Sbrendan 
44696987Sbrendan 		spa = dev->l2ad_spa;
44706987Sbrendan 		ASSERT(spa != NULL);
44715450Sbrendan 
44725450Sbrendan 		/*
44735450Sbrendan 		 * Avoid contributing to memory pressure.
44745450Sbrendan 		 */
44755450Sbrendan 		if (arc_reclaim_needed()) {
44765450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
44777754SJeff.Bonwick@Sun.COM 			spa_config_exit(spa, SCL_L2ARC, dev);
44785450Sbrendan 			continue;
44795450Sbrendan 		}
44805450Sbrendan 
44815450Sbrendan 		ARCSTAT_BUMP(arcstat_l2_feeds);
44825450Sbrendan 
44838582SBrendan.Gregg@Sun.COM 		size = l2arc_write_size(dev);
44846987Sbrendan 
44855450Sbrendan 		/*
44865450Sbrendan 		 * Evict L2ARC buffers that will be overwritten.
44875450Sbrendan 		 */
44886987Sbrendan 		l2arc_evict(dev, size, B_FALSE);
44895450Sbrendan 
44905450Sbrendan 		/*
44915450Sbrendan 		 * Write ARC buffers.
44925450Sbrendan 		 */
44938582SBrendan.Gregg@Sun.COM 		wrote = l2arc_write_buffers(spa, dev, size);
44948582SBrendan.Gregg@Sun.COM 
44958582SBrendan.Gregg@Sun.COM 		/*
44968582SBrendan.Gregg@Sun.COM 		 * Calculate interval between writes.
44978582SBrendan.Gregg@Sun.COM 		 */
44988582SBrendan.Gregg@Sun.COM 		next = l2arc_write_interval(begin, size, wrote);
44997754SJeff.Bonwick@Sun.COM 		spa_config_exit(spa, SCL_L2ARC, dev);
45005450Sbrendan 	}
45015450Sbrendan 
45025450Sbrendan 	l2arc_thread_exit = 0;
45035450Sbrendan 	cv_broadcast(&l2arc_feed_thr_cv);
45045450Sbrendan 	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
45055450Sbrendan 	thread_exit();
45065450Sbrendan }
45075450Sbrendan 
45086643Seschrock boolean_t
45096643Seschrock l2arc_vdev_present(vdev_t *vd)
45106643Seschrock {
45116643Seschrock 	l2arc_dev_t *dev;
45126643Seschrock 
45136643Seschrock 	mutex_enter(&l2arc_dev_mtx);
45146643Seschrock 	for (dev = list_head(l2arc_dev_list); dev != NULL;
45156643Seschrock 	    dev = list_next(l2arc_dev_list, dev)) {
45166643Seschrock 		if (dev->l2ad_vdev == vd)
45176643Seschrock 			break;
45186643Seschrock 	}
45196643Seschrock 	mutex_exit(&l2arc_dev_mtx);
45206643Seschrock 
45216643Seschrock 	return (dev != NULL);
45226643Seschrock }
45236643Seschrock 
45245450Sbrendan /*
45255450Sbrendan  * Add a vdev for use by the L2ARC.  By this point the spa has already
45265450Sbrendan  * validated the vdev and opened it.
45275450Sbrendan  */
45285450Sbrendan void
45299816SGeorge.Wilson@Sun.COM l2arc_add_vdev(spa_t *spa, vdev_t *vd)
45305450Sbrendan {
45315450Sbrendan 	l2arc_dev_t *adddev;
45325450Sbrendan 
45336643Seschrock 	ASSERT(!l2arc_vdev_present(vd));
45346643Seschrock 
45355450Sbrendan 	/*
45365450Sbrendan 	 * Create a new l2arc device entry.
45375450Sbrendan 	 */
45385450Sbrendan 	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
45395450Sbrendan 	adddev->l2ad_spa = spa;
45405450Sbrendan 	adddev->l2ad_vdev = vd;
45415450Sbrendan 	adddev->l2ad_write = l2arc_write_max;
45426987Sbrendan 	adddev->l2ad_boost = l2arc_write_boost;
45439816SGeorge.Wilson@Sun.COM 	adddev->l2ad_start = VDEV_LABEL_START_SIZE;
45449816SGeorge.Wilson@Sun.COM 	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
45455450Sbrendan 	adddev->l2ad_hand = adddev->l2ad_start;
45465450Sbrendan 	adddev->l2ad_evict = adddev->l2ad_start;
45475450Sbrendan 	adddev->l2ad_first = B_TRUE;
45488582SBrendan.Gregg@Sun.COM 	adddev->l2ad_writing = B_FALSE;
45495450Sbrendan 	ASSERT3U(adddev->l2ad_write, >, 0);
45505450Sbrendan 
45515450Sbrendan 	/*
45525450Sbrendan 	 * This is a list of all ARC buffers that are still valid on the
45535450Sbrendan 	 * device.
45545450Sbrendan 	 */
45555450Sbrendan 	adddev->l2ad_buflist = kmem_zalloc(sizeof (list_t), KM_SLEEP);
45565450Sbrendan 	list_create(adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
45575450Sbrendan 	    offsetof(arc_buf_hdr_t, b_l2node));
45585450Sbrendan 
45595450Sbrendan 	spa_l2cache_space_update(vd, adddev->l2ad_end - adddev->l2ad_hand, 0);
45605450Sbrendan 
45615450Sbrendan 	/*
45625450Sbrendan 	 * Add device to global list
45635450Sbrendan 	 */
45645450Sbrendan 	mutex_enter(&l2arc_dev_mtx);
45655450Sbrendan 	list_insert_head(l2arc_dev_list, adddev);
45665450Sbrendan 	atomic_inc_64(&l2arc_ndev);
45675450Sbrendan 	mutex_exit(&l2arc_dev_mtx);
45685450Sbrendan }
45695450Sbrendan 
45705450Sbrendan /*
45715450Sbrendan  * Remove a vdev from the L2ARC.
45725450Sbrendan  */
45735450Sbrendan void
45745450Sbrendan l2arc_remove_vdev(vdev_t *vd)
45755450Sbrendan {
45765450Sbrendan 	l2arc_dev_t *dev, *nextdev, *remdev = NULL;
45775450Sbrendan 
45785450Sbrendan 	/*
45795450Sbrendan 	 * Find the device by vdev
45805450Sbrendan 	 */
45815450Sbrendan 	mutex_enter(&l2arc_dev_mtx);
45825450Sbrendan 	for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
45835450Sbrendan 		nextdev = list_next(l2arc_dev_list, dev);
45845450Sbrendan 		if (vd == dev->l2ad_vdev) {
45855450Sbrendan 			remdev = dev;
45865450Sbrendan 			break;
45875450Sbrendan 		}
45885450Sbrendan 	}
45895450Sbrendan 	ASSERT(remdev != NULL);
45905450Sbrendan 
45915450Sbrendan 	/*
45925450Sbrendan 	 * Remove device from global list
45935450Sbrendan 	 */
45945450Sbrendan 	list_remove(l2arc_dev_list, remdev);
45955450Sbrendan 	l2arc_dev_last = NULL;		/* may have been invalidated */
45966987Sbrendan 	atomic_dec_64(&l2arc_ndev);
45976987Sbrendan 	mutex_exit(&l2arc_dev_mtx);
45985450Sbrendan 
45995450Sbrendan 	/*
46005450Sbrendan 	 * Clear all buflists and ARC references.  L2ARC device flush.
46015450Sbrendan 	 */
46025450Sbrendan 	l2arc_evict(remdev, 0, B_TRUE);
46035450Sbrendan 	list_destroy(remdev->l2ad_buflist);
46045450Sbrendan 	kmem_free(remdev->l2ad_buflist, sizeof (list_t));
46055450Sbrendan 	kmem_free(remdev, sizeof (l2arc_dev_t));
46065450Sbrendan }
46075450Sbrendan 
46085450Sbrendan void
46097754SJeff.Bonwick@Sun.COM l2arc_init(void)
46105450Sbrendan {
46115450Sbrendan 	l2arc_thread_exit = 0;
46125450Sbrendan 	l2arc_ndev = 0;
46135450Sbrendan 	l2arc_writes_sent = 0;
46145450Sbrendan 	l2arc_writes_done = 0;
46155450Sbrendan 
46165450Sbrendan 	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
46175450Sbrendan 	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
46185450Sbrendan 	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
46195450Sbrendan 	mutex_init(&l2arc_buflist_mtx, NULL, MUTEX_DEFAULT, NULL);
46205450Sbrendan 	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
46215450Sbrendan 
46225450Sbrendan 	l2arc_dev_list = &L2ARC_dev_list;
46235450Sbrendan 	l2arc_free_on_write = &L2ARC_free_on_write;
46245450Sbrendan 	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
46255450Sbrendan 	    offsetof(l2arc_dev_t, l2ad_node));
46265450Sbrendan 	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
46275450Sbrendan 	    offsetof(l2arc_data_free_t, l2df_list_node));
46285450Sbrendan }
46295450Sbrendan 
46305450Sbrendan void
46317754SJeff.Bonwick@Sun.COM l2arc_fini(void)
46325450Sbrendan {
46336987Sbrendan 	/*
46346987Sbrendan 	 * This is called from dmu_fini(), which is called from spa_fini();
46356987Sbrendan 	 * Because of this, we can assume that all l2arc devices have
46366987Sbrendan 	 * already been removed when the pools themselves were removed.
46376987Sbrendan 	 */
46386987Sbrendan 
46396987Sbrendan 	l2arc_do_free_on_write();
46406987Sbrendan 
46415450Sbrendan 	mutex_destroy(&l2arc_feed_thr_lock);
46425450Sbrendan 	cv_destroy(&l2arc_feed_thr_cv);
46435450Sbrendan 	mutex_destroy(&l2arc_dev_mtx);
46445450Sbrendan 	mutex_destroy(&l2arc_buflist_mtx);
46455450Sbrendan 	mutex_destroy(&l2arc_free_on_write_mtx);
46465450Sbrendan 
46475450Sbrendan 	list_destroy(l2arc_dev_list);
46485450Sbrendan 	list_destroy(l2arc_free_on_write);
46495450Sbrendan }
46507754SJeff.Bonwick@Sun.COM 
46517754SJeff.Bonwick@Sun.COM void
46527754SJeff.Bonwick@Sun.COM l2arc_start(void)
46537754SJeff.Bonwick@Sun.COM {
46548241SJeff.Bonwick@Sun.COM 	if (!(spa_mode_global & FWRITE))
46557754SJeff.Bonwick@Sun.COM 		return;
46567754SJeff.Bonwick@Sun.COM 
46577754SJeff.Bonwick@Sun.COM 	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
46587754SJeff.Bonwick@Sun.COM 	    TS_RUN, minclsyspri);
46597754SJeff.Bonwick@Sun.COM }
46607754SJeff.Bonwick@Sun.COM 
46617754SJeff.Bonwick@Sun.COM void
46627754SJeff.Bonwick@Sun.COM l2arc_stop(void)
46637754SJeff.Bonwick@Sun.COM {
46648241SJeff.Bonwick@Sun.COM 	if (!(spa_mode_global & FWRITE))
46657754SJeff.Bonwick@Sun.COM 		return;
46667754SJeff.Bonwick@Sun.COM 
46677754SJeff.Bonwick@Sun.COM 	mutex_enter(&l2arc_feed_thr_lock);
46687754SJeff.Bonwick@Sun.COM 	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
46697754SJeff.Bonwick@Sun.COM 	l2arc_thread_exit = 1;
46707754SJeff.Bonwick@Sun.COM 	while (l2arc_thread_exit != 0)
46717754SJeff.Bonwick@Sun.COM 		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
46727754SJeff.Bonwick@Sun.COM 	mutex_exit(&l2arc_feed_thr_lock);
46737754SJeff.Bonwick@Sun.COM }
4674