xref: /onnv-gate/usr/src/uts/common/fs/zfs/arc.c (revision 10357)
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;
252*10357SBrendan.Gregg@Sun.COM 	kstat_named_t arcstat_evict_l2_cached;
253*10357SBrendan.Gregg@Sun.COM 	kstat_named_t arcstat_evict_l2_eligible;
254*10357SBrendan.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 },
308*10357SBrendan.Gregg@Sun.COM 	{ "evict_l2_cached",		KSTAT_DATA_UINT64 },
309*10357SBrendan.Gregg@Sun.COM 	{ "evict_l2_eligible",		KSTAT_DATA_UINT64 },
310*10357SBrendan.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 
477*10357SBrendan.Gregg@Sun.COM static boolean_t l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *ab);
478*10357SBrendan.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 			}
1616*10357SBrendan.Gregg@Sun.COM 
1617*10357SBrendan.Gregg@Sun.COM 			if (ab->b_l2hdr) {
1618*10357SBrendan.Gregg@Sun.COM 				ARCSTAT_INCR(arcstat_evict_l2_cached,
1619*10357SBrendan.Gregg@Sun.COM 				    ab->b_size);
1620*10357SBrendan.Gregg@Sun.COM 			} else {
1621*10357SBrendan.Gregg@Sun.COM 				if (l2arc_write_eligible(ab->b_spa, ab)) {
1622*10357SBrendan.Gregg@Sun.COM 					ARCSTAT_INCR(arcstat_evict_l2_eligible,
1623*10357SBrendan.Gregg@Sun.COM 					    ab->b_size);
1624*10357SBrendan.Gregg@Sun.COM 				} else {
1625*10357SBrendan.Gregg@Sun.COM 					ARCSTAT_INCR(
1626*10357SBrendan.Gregg@Sun.COM 					    arcstat_evict_l2_ineligible,
1627*10357SBrendan.Gregg@Sun.COM 					    ab->b_size);
1628*10357SBrendan.Gregg@Sun.COM 				}
1629*10357SBrendan.Gregg@Sun.COM 			}
1630*10357SBrendan.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);
24577046Sahrens 	if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
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);
27581596Sahrens 		DTRACE_PROBE3(arc__miss, blkptr_t *, bp, uint64_t, size,
27591596Sahrens 		    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 
2845789Sahrens /*
2846789Sahrens  * arc_read() variant to support pool traversal.  If the block is already
2847789Sahrens  * in the ARC, make a copy of it; otherwise, the caller will do the I/O.
2848789Sahrens  * The idea is that we don't want pool traversal filling up memory, but
2849789Sahrens  * if the ARC already has the data anyway, we shouldn't pay for the I/O.
2850789Sahrens  */
2851789Sahrens int
2852789Sahrens arc_tryread(spa_t *spa, blkptr_t *bp, void *data)
2853789Sahrens {
2854789Sahrens 	arc_buf_hdr_t *hdr;
2855789Sahrens 	kmutex_t *hash_mtx;
28568636SMark.Maybee@Sun.COM 	uint64_t guid = spa_guid(spa);
2857789Sahrens 	int rc = 0;
2858789Sahrens 
28598636SMark.Maybee@Sun.COM 	hdr = buf_hash_find(guid, BP_IDENTITY(bp), bp->blk_birth, &hash_mtx);
2860789Sahrens 
28611544Seschrock 	if (hdr && hdr->b_datacnt > 0 && !HDR_IO_IN_PROGRESS(hdr)) {
28621544Seschrock 		arc_buf_t *buf = hdr->b_buf;
28631544Seschrock 
28641544Seschrock 		ASSERT(buf);
28651544Seschrock 		while (buf->b_data == NULL) {
28661544Seschrock 			buf = buf->b_next;
28671544Seschrock 			ASSERT(buf);
28681544Seschrock 		}
28691544Seschrock 		bcopy(buf->b_data, data, hdr->b_size);
28701544Seschrock 	} else {
2871789Sahrens 		rc = ENOENT;
28721544Seschrock 	}
2873789Sahrens 
2874789Sahrens 	if (hash_mtx)
2875789Sahrens 		mutex_exit(hash_mtx);
2876789Sahrens 
2877789Sahrens 	return (rc);
2878789Sahrens }
2879789Sahrens 
28801544Seschrock void
28811544Seschrock arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
28821544Seschrock {
28831544Seschrock 	ASSERT(buf->b_hdr != NULL);
28843403Sbmc 	ASSERT(buf->b_hdr->b_state != arc_anon);
28851544Seschrock 	ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt) || func == NULL);
28861544Seschrock 	buf->b_efunc = func;
28871544Seschrock 	buf->b_private = private;
28881544Seschrock }
28891544Seschrock 
28901544Seschrock /*
28911544Seschrock  * This is used by the DMU to let the ARC know that a buffer is
28921544Seschrock  * being evicted, so the ARC should clean up.  If this arc buf
28931544Seschrock  * is not yet in the evicted state, it will be put there.
28941544Seschrock  */
28951544Seschrock int
28961544Seschrock arc_buf_evict(arc_buf_t *buf)
28971544Seschrock {
28982887Smaybee 	arc_buf_hdr_t *hdr;
28991544Seschrock 	kmutex_t *hash_lock;
29001544Seschrock 	arc_buf_t **bufp;
29011544Seschrock 
29027545SMark.Maybee@Sun.COM 	rw_enter(&buf->b_lock, RW_WRITER);
29032887Smaybee 	hdr = buf->b_hdr;
29041544Seschrock 	if (hdr == NULL) {
29051544Seschrock 		/*
29061544Seschrock 		 * We are in arc_do_user_evicts().
29071544Seschrock 		 */
29081544Seschrock 		ASSERT(buf->b_data == NULL);
29097545SMark.Maybee@Sun.COM 		rw_exit(&buf->b_lock);
29101544Seschrock 		return (0);
29117545SMark.Maybee@Sun.COM 	} else if (buf->b_data == NULL) {
29127545SMark.Maybee@Sun.COM 		arc_buf_t copy = *buf; /* structure assignment */
29137545SMark.Maybee@Sun.COM 		/*
29147545SMark.Maybee@Sun.COM 		 * We are on the eviction list; process this buffer now
29157545SMark.Maybee@Sun.COM 		 * but let arc_do_user_evicts() do the reaping.
29167545SMark.Maybee@Sun.COM 		 */
29177545SMark.Maybee@Sun.COM 		buf->b_efunc = NULL;
29187545SMark.Maybee@Sun.COM 		rw_exit(&buf->b_lock);
29197545SMark.Maybee@Sun.COM 		VERIFY(copy.b_efunc(&copy) == 0);
29207545SMark.Maybee@Sun.COM 		return (1);
29211544Seschrock 	}
29222887Smaybee 	hash_lock = HDR_LOCK(hdr);
29231544Seschrock 	mutex_enter(hash_lock);
29241544Seschrock 
29252724Smaybee 	ASSERT(buf->b_hdr == hdr);
29262724Smaybee 	ASSERT3U(refcount_count(&hdr->b_refcnt), <, hdr->b_datacnt);
29273403Sbmc 	ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
29281544Seschrock 
29291544Seschrock 	/*
29301544Seschrock 	 * Pull this buffer off of the hdr
29311544Seschrock 	 */
29321544Seschrock 	bufp = &hdr->b_buf;
29331544Seschrock 	while (*bufp != buf)
29341544Seschrock 		bufp = &(*bufp)->b_next;
29351544Seschrock 	*bufp = buf->b_next;
29361544Seschrock 
29371544Seschrock 	ASSERT(buf->b_data != NULL);
29382688Smaybee 	arc_buf_destroy(buf, FALSE, FALSE);
29391544Seschrock 
29401544Seschrock 	if (hdr->b_datacnt == 0) {
29411544Seschrock 		arc_state_t *old_state = hdr->b_state;
29421544Seschrock 		arc_state_t *evicted_state;
29431544Seschrock 
29441544Seschrock 		ASSERT(refcount_is_zero(&hdr->b_refcnt));
29451544Seschrock 
29461544Seschrock 		evicted_state =
29473403Sbmc 		    (old_state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
29481544Seschrock 
29493403Sbmc 		mutex_enter(&old_state->arcs_mtx);
29503403Sbmc 		mutex_enter(&evicted_state->arcs_mtx);
29511544Seschrock 
29521544Seschrock 		arc_change_state(evicted_state, hdr, hash_lock);
29531544Seschrock 		ASSERT(HDR_IN_HASH_TABLE(hdr));
29545450Sbrendan 		hdr->b_flags |= ARC_IN_HASH_TABLE;
29555450Sbrendan 		hdr->b_flags &= ~ARC_BUF_AVAILABLE;
29561544Seschrock 
29573403Sbmc 		mutex_exit(&evicted_state->arcs_mtx);
29583403Sbmc 		mutex_exit(&old_state->arcs_mtx);
29591544Seschrock 	}
29601544Seschrock 	mutex_exit(hash_lock);
29617545SMark.Maybee@Sun.COM 	rw_exit(&buf->b_lock);
29621819Smaybee 
29631544Seschrock 	VERIFY(buf->b_efunc(buf) == 0);
29641544Seschrock 	buf->b_efunc = NULL;
29651544Seschrock 	buf->b_private = NULL;
29661544Seschrock 	buf->b_hdr = NULL;
29671544Seschrock 	kmem_cache_free(buf_cache, buf);
29681544Seschrock 	return (1);
29691544Seschrock }
29701544Seschrock 
2971789Sahrens /*
2972789Sahrens  * Release this buffer from the cache.  This must be done
2973789Sahrens  * after a read and prior to modifying the buffer contents.
2974789Sahrens  * If the buffer has more than one reference, we must make
29757046Sahrens  * a new hdr for the buffer.
2976789Sahrens  */
2977789Sahrens void
2978789Sahrens arc_release(arc_buf_t *buf, void *tag)
2979789Sahrens {
29807545SMark.Maybee@Sun.COM 	arc_buf_hdr_t *hdr;
29817545SMark.Maybee@Sun.COM 	kmutex_t *hash_lock;
29827545SMark.Maybee@Sun.COM 	l2arc_buf_hdr_t *l2hdr;
29835450Sbrendan 	uint64_t buf_size;
29849274SBrendan.Gregg@Sun.COM 	boolean_t released = B_FALSE;
2985789Sahrens 
29867545SMark.Maybee@Sun.COM 	rw_enter(&buf->b_lock, RW_WRITER);
29877545SMark.Maybee@Sun.COM 	hdr = buf->b_hdr;
29887545SMark.Maybee@Sun.COM 
2989789Sahrens 	/* this buffer is not on any list */
2990789Sahrens 	ASSERT(refcount_count(&hdr->b_refcnt) > 0);
29917046Sahrens 	ASSERT(!(hdr->b_flags & ARC_STORED));
2992789Sahrens 
29933403Sbmc 	if (hdr->b_state == arc_anon) {
2994789Sahrens 		/* this buffer is already released */
2995789Sahrens 		ASSERT3U(refcount_count(&hdr->b_refcnt), ==, 1);
2996789Sahrens 		ASSERT(BUF_EMPTY(hdr));
29971544Seschrock 		ASSERT(buf->b_efunc == NULL);
29983093Sahrens 		arc_buf_thaw(buf);
29997545SMark.Maybee@Sun.COM 		rw_exit(&buf->b_lock);
30009274SBrendan.Gregg@Sun.COM 		released = B_TRUE;
30019274SBrendan.Gregg@Sun.COM 	} else {
30029274SBrendan.Gregg@Sun.COM 		hash_lock = HDR_LOCK(hdr);
30039274SBrendan.Gregg@Sun.COM 		mutex_enter(hash_lock);
3004789Sahrens 	}
3005789Sahrens 
30067545SMark.Maybee@Sun.COM 	l2hdr = hdr->b_l2hdr;
30077545SMark.Maybee@Sun.COM 	if (l2hdr) {
30087545SMark.Maybee@Sun.COM 		mutex_enter(&l2arc_buflist_mtx);
30097545SMark.Maybee@Sun.COM 		hdr->b_l2hdr = NULL;
30107545SMark.Maybee@Sun.COM 		buf_size = hdr->b_size;
30117545SMark.Maybee@Sun.COM 	}
30127545SMark.Maybee@Sun.COM 
30139274SBrendan.Gregg@Sun.COM 	if (released)
30149274SBrendan.Gregg@Sun.COM 		goto out;
30159274SBrendan.Gregg@Sun.COM 
30161544Seschrock 	/*
30171544Seschrock 	 * Do we have more than one buf?
30181544Seschrock 	 */
30197545SMark.Maybee@Sun.COM 	if (hdr->b_datacnt > 1) {
3020789Sahrens 		arc_buf_hdr_t *nhdr;
3021789Sahrens 		arc_buf_t **bufp;
3022789Sahrens 		uint64_t blksz = hdr->b_size;
30238636SMark.Maybee@Sun.COM 		uint64_t spa = hdr->b_spa;
30243290Sjohansen 		arc_buf_contents_t type = hdr->b_type;
30255450Sbrendan 		uint32_t flags = hdr->b_flags;
3026789Sahrens 
30277545SMark.Maybee@Sun.COM 		ASSERT(hdr->b_buf != buf || buf->b_next != NULL);
3028789Sahrens 		/*
3029789Sahrens 		 * Pull the data off of this buf and attach it to
3030789Sahrens 		 * a new anonymous buf.
3031789Sahrens 		 */
30321544Seschrock 		(void) remove_reference(hdr, hash_lock, tag);
3033789Sahrens 		bufp = &hdr->b_buf;
30341544Seschrock 		while (*bufp != buf)
3035789Sahrens 			bufp = &(*bufp)->b_next;
3036789Sahrens 		*bufp = (*bufp)->b_next;
30373897Smaybee 		buf->b_next = NULL;
30381544Seschrock 
30393403Sbmc 		ASSERT3U(hdr->b_state->arcs_size, >=, hdr->b_size);
30403403Sbmc 		atomic_add_64(&hdr->b_state->arcs_size, -hdr->b_size);
30411544Seschrock 		if (refcount_is_zero(&hdr->b_refcnt)) {
30424309Smaybee 			uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
30434309Smaybee 			ASSERT3U(*size, >=, hdr->b_size);
30444309Smaybee 			atomic_add_64(size, -hdr->b_size);
30451544Seschrock 		}
30461544Seschrock 		hdr->b_datacnt -= 1;
30473547Smaybee 		arc_cksum_verify(buf);
30481544Seschrock 
3049789Sahrens 		mutex_exit(hash_lock);
3050789Sahrens 
30516245Smaybee 		nhdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
3052789Sahrens 		nhdr->b_size = blksz;
3053789Sahrens 		nhdr->b_spa = spa;
30543290Sjohansen 		nhdr->b_type = type;
3055789Sahrens 		nhdr->b_buf = buf;
30563403Sbmc 		nhdr->b_state = arc_anon;
3057789Sahrens 		nhdr->b_arc_access = 0;
30585450Sbrendan 		nhdr->b_flags = flags & ARC_L2_WRITING;
30595450Sbrendan 		nhdr->b_l2hdr = NULL;
30601544Seschrock 		nhdr->b_datacnt = 1;
30613547Smaybee 		nhdr->b_freeze_cksum = NULL;
30623897Smaybee 		(void) refcount_add(&nhdr->b_refcnt, tag);
3063789Sahrens 		buf->b_hdr = nhdr;
30647545SMark.Maybee@Sun.COM 		rw_exit(&buf->b_lock);
30653403Sbmc 		atomic_add_64(&arc_anon->arcs_size, blksz);
3066789Sahrens 	} else {
30677545SMark.Maybee@Sun.COM 		rw_exit(&buf->b_lock);
30681544Seschrock 		ASSERT(refcount_count(&hdr->b_refcnt) == 1);
3069789Sahrens 		ASSERT(!list_link_active(&hdr->b_arc_node));
3070789Sahrens 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
30713403Sbmc 		arc_change_state(arc_anon, hdr, hash_lock);
3072789Sahrens 		hdr->b_arc_access = 0;
3073789Sahrens 		mutex_exit(hash_lock);
30745450Sbrendan 
3075789Sahrens 		bzero(&hdr->b_dva, sizeof (dva_t));
3076789Sahrens 		hdr->b_birth = 0;
3077789Sahrens 		hdr->b_cksum0 = 0;
30783547Smaybee 		arc_buf_thaw(buf);
3079789Sahrens 	}
30801544Seschrock 	buf->b_efunc = NULL;
30811544Seschrock 	buf->b_private = NULL;
30825450Sbrendan 
30839274SBrendan.Gregg@Sun.COM out:
30845450Sbrendan 	if (l2hdr) {
30855450Sbrendan 		list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
30865450Sbrendan 		kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
30875450Sbrendan 		ARCSTAT_INCR(arcstat_l2_size, -buf_size);
30887545SMark.Maybee@Sun.COM 		mutex_exit(&l2arc_buflist_mtx);
30895450Sbrendan 	}
3090789Sahrens }
3091789Sahrens 
3092789Sahrens int
3093789Sahrens arc_released(arc_buf_t *buf)
3094789Sahrens {
30957545SMark.Maybee@Sun.COM 	int released;
30967545SMark.Maybee@Sun.COM 
30977545SMark.Maybee@Sun.COM 	rw_enter(&buf->b_lock, RW_READER);
30987545SMark.Maybee@Sun.COM 	released = (buf->b_data != NULL && buf->b_hdr->b_state == arc_anon);
30997545SMark.Maybee@Sun.COM 	rw_exit(&buf->b_lock);
31007545SMark.Maybee@Sun.COM 	return (released);
31011544Seschrock }
31021544Seschrock 
31031544Seschrock int
31041544Seschrock arc_has_callback(arc_buf_t *buf)
31051544Seschrock {
31067545SMark.Maybee@Sun.COM 	int callback;
31077545SMark.Maybee@Sun.COM 
31087545SMark.Maybee@Sun.COM 	rw_enter(&buf->b_lock, RW_READER);
31097545SMark.Maybee@Sun.COM 	callback = (buf->b_efunc != NULL);
31107545SMark.Maybee@Sun.COM 	rw_exit(&buf->b_lock);
31117545SMark.Maybee@Sun.COM 	return (callback);
3112789Sahrens }
3113789Sahrens 
31141544Seschrock #ifdef ZFS_DEBUG
31151544Seschrock int
31161544Seschrock arc_referenced(arc_buf_t *buf)
31171544Seschrock {
31187545SMark.Maybee@Sun.COM 	int referenced;
31197545SMark.Maybee@Sun.COM 
31207545SMark.Maybee@Sun.COM 	rw_enter(&buf->b_lock, RW_READER);
31217545SMark.Maybee@Sun.COM 	referenced = (refcount_count(&buf->b_hdr->b_refcnt));
31227545SMark.Maybee@Sun.COM 	rw_exit(&buf->b_lock);
31237545SMark.Maybee@Sun.COM 	return (referenced);
31241544Seschrock }
31251544Seschrock #endif
31261544Seschrock 
3127789Sahrens static void
31283547Smaybee arc_write_ready(zio_t *zio)
31293547Smaybee {
31303547Smaybee 	arc_write_callback_t *callback = zio->io_private;
31313547Smaybee 	arc_buf_t *buf = callback->awcb_buf;
31325329Sgw25295 	arc_buf_hdr_t *hdr = buf->b_hdr;
31335329Sgw25295 
31347754SJeff.Bonwick@Sun.COM 	ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt));
31357754SJeff.Bonwick@Sun.COM 	callback->awcb_ready(zio, buf, callback->awcb_private);
31367754SJeff.Bonwick@Sun.COM 
31375329Sgw25295 	/*
31385329Sgw25295 	 * If the IO is already in progress, then this is a re-write
31397754SJeff.Bonwick@Sun.COM 	 * attempt, so we need to thaw and re-compute the cksum.
31407754SJeff.Bonwick@Sun.COM 	 * It is the responsibility of the callback to handle the
31417754SJeff.Bonwick@Sun.COM 	 * accounting for any re-write attempt.
31425329Sgw25295 	 */
31435329Sgw25295 	if (HDR_IO_IN_PROGRESS(hdr)) {
31445329Sgw25295 		mutex_enter(&hdr->b_freeze_lock);
31455329Sgw25295 		if (hdr->b_freeze_cksum != NULL) {
31465329Sgw25295 			kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
31475329Sgw25295 			hdr->b_freeze_cksum = NULL;
31485329Sgw25295 		}
31495329Sgw25295 		mutex_exit(&hdr->b_freeze_lock);
31505329Sgw25295 	}
31515450Sbrendan 	arc_cksum_compute(buf, B_FALSE);
31525329Sgw25295 	hdr->b_flags |= ARC_IO_IN_PROGRESS;
31533547Smaybee }
31543547Smaybee 
31553547Smaybee static void
3156789Sahrens arc_write_done(zio_t *zio)
3157789Sahrens {
31583547Smaybee 	arc_write_callback_t *callback = zio->io_private;
31593547Smaybee 	arc_buf_t *buf = callback->awcb_buf;
31603547Smaybee 	arc_buf_hdr_t *hdr = buf->b_hdr;
3161789Sahrens 
3162789Sahrens 	hdr->b_acb = NULL;
3163789Sahrens 
3164789Sahrens 	hdr->b_dva = *BP_IDENTITY(zio->io_bp);
3165789Sahrens 	hdr->b_birth = zio->io_bp->blk_birth;
3166789Sahrens 	hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
31671544Seschrock 	/*
31681544Seschrock 	 * If the block to be written was all-zero, we may have
31691544Seschrock 	 * compressed it away.  In this case no write was performed
31701544Seschrock 	 * so there will be no dva/birth-date/checksum.  The buffer
31711544Seschrock 	 * must therefor remain anonymous (and uncached).
31721544Seschrock 	 */
3173789Sahrens 	if (!BUF_EMPTY(hdr)) {
3174789Sahrens 		arc_buf_hdr_t *exists;
3175789Sahrens 		kmutex_t *hash_lock;
3176789Sahrens 
31773093Sahrens 		arc_cksum_verify(buf);
31783093Sahrens 
3179789Sahrens 		exists = buf_hash_insert(hdr, &hash_lock);
3180789Sahrens 		if (exists) {
3181789Sahrens 			/*
3182789Sahrens 			 * This can only happen if we overwrite for
3183789Sahrens 			 * sync-to-convergence, because we remove
3184789Sahrens 			 * buffers from the hash table when we arc_free().
3185789Sahrens 			 */
318610272SMatthew.Ahrens@Sun.COM 			if (!(zio->io_flags & ZIO_FLAG_IO_REWRITE) ||
318710272SMatthew.Ahrens@Sun.COM 			    !DVA_EQUAL(BP_IDENTITY(&zio->io_bp_orig),
318810272SMatthew.Ahrens@Sun.COM 			    BP_IDENTITY(zio->io_bp)) ||
318910272SMatthew.Ahrens@Sun.COM 			    zio->io_bp_orig.blk_birth !=
319010272SMatthew.Ahrens@Sun.COM 			    zio->io_bp->blk_birth) {
319110272SMatthew.Ahrens@Sun.COM 				panic("bad overwrite, hdr=%p exists=%p",
319210272SMatthew.Ahrens@Sun.COM 				    (void *)hdr, (void *)exists);
319310272SMatthew.Ahrens@Sun.COM 			}
3194789Sahrens 
3195789Sahrens 			ASSERT(refcount_is_zero(&exists->b_refcnt));
31963403Sbmc 			arc_change_state(arc_anon, exists, hash_lock);
3197789Sahrens 			mutex_exit(hash_lock);
31981544Seschrock 			arc_hdr_destroy(exists);
3199789Sahrens 			exists = buf_hash_insert(hdr, &hash_lock);
3200789Sahrens 			ASSERT3P(exists, ==, NULL);
3201789Sahrens 		}
32021544Seschrock 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
32037046Sahrens 		/* if it's not anon, we are doing a scrub */
32047046Sahrens 		if (hdr->b_state == arc_anon)
32057046Sahrens 			arc_access(hdr, hash_lock);
32062688Smaybee 		mutex_exit(hash_lock);
32073547Smaybee 	} else if (callback->awcb_done == NULL) {
32081544Seschrock 		int destroy_hdr;
32091544Seschrock 		/*
32101544Seschrock 		 * This is an anonymous buffer with no user callback,
32111544Seschrock 		 * destroy it if there are no active references.
32121544Seschrock 		 */
32131544Seschrock 		mutex_enter(&arc_eviction_mtx);
32141544Seschrock 		destroy_hdr = refcount_is_zero(&hdr->b_refcnt);
32151544Seschrock 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
32161544Seschrock 		mutex_exit(&arc_eviction_mtx);
32171544Seschrock 		if (destroy_hdr)
32181544Seschrock 			arc_hdr_destroy(hdr);
32191544Seschrock 	} else {
32201544Seschrock 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3221789Sahrens 	}
32227046Sahrens 	hdr->b_flags &= ~ARC_STORED;
32231544Seschrock 
32243547Smaybee 	if (callback->awcb_done) {
3225789Sahrens 		ASSERT(!refcount_is_zero(&hdr->b_refcnt));
32263547Smaybee 		callback->awcb_done(zio, buf, callback->awcb_private);
3227789Sahrens 	}
3228789Sahrens 
32293547Smaybee 	kmem_free(callback, sizeof (arc_write_callback_t));
3230789Sahrens }
3231789Sahrens 
32327872STim.Haley@Sun.COM void
32337754SJeff.Bonwick@Sun.COM write_policy(spa_t *spa, const writeprops_t *wp, zio_prop_t *zp)
32347046Sahrens {
32357046Sahrens 	boolean_t ismd = (wp->wp_level > 0 || dmu_ot[wp->wp_type].ot_metadata);
32367046Sahrens 
32377046Sahrens 	/* Determine checksum setting */
32387046Sahrens 	if (ismd) {
32397046Sahrens 		/*
32407046Sahrens 		 * Metadata always gets checksummed.  If the data
32417046Sahrens 		 * checksum is multi-bit correctable, and it's not a
32427046Sahrens 		 * ZBT-style checksum, then it's suitable for metadata
32437046Sahrens 		 * as well.  Otherwise, the metadata checksum defaults
32447046Sahrens 		 * to fletcher4.
32457046Sahrens 		 */
32467046Sahrens 		if (zio_checksum_table[wp->wp_oschecksum].ci_correctable &&
32477046Sahrens 		    !zio_checksum_table[wp->wp_oschecksum].ci_zbt)
32487754SJeff.Bonwick@Sun.COM 			zp->zp_checksum = wp->wp_oschecksum;
32497046Sahrens 		else
32507754SJeff.Bonwick@Sun.COM 			zp->zp_checksum = ZIO_CHECKSUM_FLETCHER_4;
32517046Sahrens 	} else {
32527754SJeff.Bonwick@Sun.COM 		zp->zp_checksum = zio_checksum_select(wp->wp_dnchecksum,
32537046Sahrens 		    wp->wp_oschecksum);
32547046Sahrens 	}
32557046Sahrens 
32567046Sahrens 	/* Determine compression setting */
32577046Sahrens 	if (ismd) {
32587046Sahrens 		/*
32597046Sahrens 		 * XXX -- we should design a compression algorithm
32607046Sahrens 		 * that specializes in arrays of bps.
32617046Sahrens 		 */
32627754SJeff.Bonwick@Sun.COM 		zp->zp_compress = zfs_mdcomp_disable ? ZIO_COMPRESS_EMPTY :
32637046Sahrens 		    ZIO_COMPRESS_LZJB;
32647046Sahrens 	} else {
32657754SJeff.Bonwick@Sun.COM 		zp->zp_compress = zio_compress_select(wp->wp_dncompress,
32667046Sahrens 		    wp->wp_oscompress);
32677046Sahrens 	}
32687754SJeff.Bonwick@Sun.COM 
32697754SJeff.Bonwick@Sun.COM 	zp->zp_type = wp->wp_type;
32707754SJeff.Bonwick@Sun.COM 	zp->zp_level = wp->wp_level;
32717754SJeff.Bonwick@Sun.COM 	zp->zp_ndvas = MIN(wp->wp_copies + ismd, spa_max_replication(spa));
32727046Sahrens }
32737046Sahrens 
32743547Smaybee zio_t *
32757046Sahrens arc_write(zio_t *pio, spa_t *spa, const writeprops_t *wp,
32767237Sek110237     boolean_t l2arc, uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
32773547Smaybee     arc_done_func_t *ready, arc_done_func_t *done, void *private, int priority,
32787237Sek110237     int zio_flags, const zbookmark_t *zb)
3279789Sahrens {
3280789Sahrens 	arc_buf_hdr_t *hdr = buf->b_hdr;
32813547Smaybee 	arc_write_callback_t *callback;
32827754SJeff.Bonwick@Sun.COM 	zio_t *zio;
32837754SJeff.Bonwick@Sun.COM 	zio_prop_t zp;
32847754SJeff.Bonwick@Sun.COM 
32857754SJeff.Bonwick@Sun.COM 	ASSERT(ready != NULL);
3286789Sahrens 	ASSERT(!HDR_IO_ERROR(hdr));
32872237Smaybee 	ASSERT((hdr->b_flags & ARC_IO_IN_PROGRESS) == 0);
32882237Smaybee 	ASSERT(hdr->b_acb == 0);
32897237Sek110237 	if (l2arc)
32907237Sek110237 		hdr->b_flags |= ARC_L2CACHE;
32913547Smaybee 	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
32923547Smaybee 	callback->awcb_ready = ready;
32933547Smaybee 	callback->awcb_done = done;
32943547Smaybee 	callback->awcb_private = private;
32953547Smaybee 	callback->awcb_buf = buf;
32967046Sahrens 
32977754SJeff.Bonwick@Sun.COM 	write_policy(spa, wp, &zp);
32987754SJeff.Bonwick@Sun.COM 	zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, &zp,
32997754SJeff.Bonwick@Sun.COM 	    arc_write_ready, arc_write_done, callback, priority, zio_flags, zb);
3300789Sahrens 
33013547Smaybee 	return (zio);
3302789Sahrens }
3303789Sahrens 
3304789Sahrens int
3305789Sahrens arc_free(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
3306789Sahrens     zio_done_func_t *done, void *private, uint32_t arc_flags)
3307789Sahrens {
3308789Sahrens 	arc_buf_hdr_t *ab;
3309789Sahrens 	kmutex_t *hash_lock;
3310789Sahrens 	zio_t	*zio;
33118636SMark.Maybee@Sun.COM 	uint64_t guid = spa_guid(spa);
3312789Sahrens 
3313789Sahrens 	/*
3314789Sahrens 	 * If this buffer is in the cache, release it, so it
3315789Sahrens 	 * can be re-used.
3316789Sahrens 	 */
33178636SMark.Maybee@Sun.COM 	ab = buf_hash_find(guid, BP_IDENTITY(bp), bp->blk_birth, &hash_lock);
3318789Sahrens 	if (ab != NULL) {
3319789Sahrens 		/*
3320789Sahrens 		 * The checksum of blocks to free is not always
3321789Sahrens 		 * preserved (eg. on the deadlist).  However, if it is
3322789Sahrens 		 * nonzero, it should match what we have in the cache.
3323789Sahrens 		 */
3324789Sahrens 		ASSERT(bp->blk_cksum.zc_word[0] == 0 ||
33257754SJeff.Bonwick@Sun.COM 		    bp->blk_cksum.zc_word[0] == ab->b_cksum0 ||
33267754SJeff.Bonwick@Sun.COM 		    bp->blk_fill == BLK_FILL_ALREADY_FREED);
33277754SJeff.Bonwick@Sun.COM 
33283403Sbmc 		if (ab->b_state != arc_anon)
33293403Sbmc 			arc_change_state(arc_anon, ab, hash_lock);
33302391Smaybee 		if (HDR_IO_IN_PROGRESS(ab)) {
33312391Smaybee 			/*
33322391Smaybee 			 * This should only happen when we prefetch.
33332391Smaybee 			 */
33342391Smaybee 			ASSERT(ab->b_flags & ARC_PREFETCH);
33352391Smaybee 			ASSERT3U(ab->b_datacnt, ==, 1);
33362391Smaybee 			ab->b_flags |= ARC_FREED_IN_READ;
33372391Smaybee 			if (HDR_IN_HASH_TABLE(ab))
33382391Smaybee 				buf_hash_remove(ab);
33392391Smaybee 			ab->b_arc_access = 0;
33402391Smaybee 			bzero(&ab->b_dva, sizeof (dva_t));
33412391Smaybee 			ab->b_birth = 0;
33422391Smaybee 			ab->b_cksum0 = 0;
33432391Smaybee 			ab->b_buf->b_efunc = NULL;
33442391Smaybee 			ab->b_buf->b_private = NULL;
33452391Smaybee 			mutex_exit(hash_lock);
33462391Smaybee 		} else if (refcount_is_zero(&ab->b_refcnt)) {
33475450Sbrendan 			ab->b_flags |= ARC_FREE_IN_PROGRESS;
3348789Sahrens 			mutex_exit(hash_lock);
33491544Seschrock 			arc_hdr_destroy(ab);
33503403Sbmc 			ARCSTAT_BUMP(arcstat_deleted);
3351789Sahrens 		} else {
33521589Smaybee 			/*
33532391Smaybee 			 * We still have an active reference on this
33542391Smaybee 			 * buffer.  This can happen, e.g., from
33552391Smaybee 			 * dbuf_unoverride().
33561589Smaybee 			 */
33572391Smaybee 			ASSERT(!HDR_IN_HASH_TABLE(ab));
3358789Sahrens 			ab->b_arc_access = 0;
3359789Sahrens 			bzero(&ab->b_dva, sizeof (dva_t));
3360789Sahrens 			ab->b_birth = 0;
3361789Sahrens 			ab->b_cksum0 = 0;
33621544Seschrock 			ab->b_buf->b_efunc = NULL;
33631544Seschrock 			ab->b_buf->b_private = NULL;
3364789Sahrens 			mutex_exit(hash_lock);
3365789Sahrens 		}
3366789Sahrens 	}
3367789Sahrens 
33687754SJeff.Bonwick@Sun.COM 	zio = zio_free(pio, spa, txg, bp, done, private, ZIO_FLAG_MUSTSUCCEED);
3369789Sahrens 
3370789Sahrens 	if (arc_flags & ARC_WAIT)
3371789Sahrens 		return (zio_wait(zio));
3372789Sahrens 
3373789Sahrens 	ASSERT(arc_flags & ARC_NOWAIT);
3374789Sahrens 	zio_nowait(zio);
3375789Sahrens 
3376789Sahrens 	return (0);
3377789Sahrens }
3378789Sahrens 
33796245Smaybee static int
33809412SAleksandr.Guzovskiy@Sun.COM arc_memory_throttle(uint64_t reserve, uint64_t inflight_data, uint64_t txg)
33816245Smaybee {
33826245Smaybee #ifdef _KERNEL
33836245Smaybee 	uint64_t available_memory = ptob(freemem);
33846245Smaybee 	static uint64_t page_load = 0;
33856245Smaybee 	static uint64_t last_txg = 0;
33866245Smaybee 
33876245Smaybee #if defined(__i386)
33886245Smaybee 	available_memory =
33896245Smaybee 	    MIN(available_memory, vmem_size(heap_arena, VMEM_FREE));
33906245Smaybee #endif
33916245Smaybee 	if (available_memory >= zfs_write_limit_max)
33926245Smaybee 		return (0);
33936245Smaybee 
33946245Smaybee 	if (txg > last_txg) {
33956245Smaybee 		last_txg = txg;
33966245Smaybee 		page_load = 0;
33976245Smaybee 	}
33986245Smaybee 	/*
33996245Smaybee 	 * If we are in pageout, we know that memory is already tight,
34006245Smaybee 	 * the arc is already going to be evicting, so we just want to
34016245Smaybee 	 * continue to let page writes occur as quickly as possible.
34026245Smaybee 	 */
34036245Smaybee 	if (curproc == proc_pageout) {
34046245Smaybee 		if (page_load > MAX(ptob(minfree), available_memory) / 4)
34056245Smaybee 			return (ERESTART);
34066245Smaybee 		/* Note: reserve is inflated, so we deflate */
34076245Smaybee 		page_load += reserve / 8;
34086245Smaybee 		return (0);
34096245Smaybee 	} else if (page_load > 0 && arc_reclaim_needed()) {
34106245Smaybee 		/* memory is low, delay before restarting */
34116245Smaybee 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
34126245Smaybee 		return (EAGAIN);
34136245Smaybee 	}
34146245Smaybee 	page_load = 0;
34156245Smaybee 
34166245Smaybee 	if (arc_size > arc_c_min) {
34176245Smaybee 		uint64_t evictable_memory =
34186245Smaybee 		    arc_mru->arcs_lsize[ARC_BUFC_DATA] +
34196245Smaybee 		    arc_mru->arcs_lsize[ARC_BUFC_METADATA] +
34206245Smaybee 		    arc_mfu->arcs_lsize[ARC_BUFC_DATA] +
34216245Smaybee 		    arc_mfu->arcs_lsize[ARC_BUFC_METADATA];
34226245Smaybee 		available_memory += MIN(evictable_memory, arc_size - arc_c_min);
34236245Smaybee 	}
34246245Smaybee 
34256245Smaybee 	if (inflight_data > available_memory / 4) {
34266245Smaybee 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
34276245Smaybee 		return (ERESTART);
34286245Smaybee 	}
34296245Smaybee #endif
34306245Smaybee 	return (0);
34316245Smaybee }
34326245Smaybee 
3433789Sahrens void
34346245Smaybee arc_tempreserve_clear(uint64_t reserve)
3435789Sahrens {
34366245Smaybee 	atomic_add_64(&arc_tempreserve, -reserve);
3437789Sahrens 	ASSERT((int64_t)arc_tempreserve >= 0);
3438789Sahrens }
3439789Sahrens 
3440789Sahrens int
34416245Smaybee arc_tempreserve_space(uint64_t reserve, uint64_t txg)
3442789Sahrens {
34436245Smaybee 	int error;
34449412SAleksandr.Guzovskiy@Sun.COM 	uint64_t anon_size;
34456245Smaybee 
3446789Sahrens #ifdef ZFS_DEBUG
3447789Sahrens 	/*
3448789Sahrens 	 * Once in a while, fail for no reason.  Everything should cope.
3449789Sahrens 	 */
3450789Sahrens 	if (spa_get_random(10000) == 0) {
3451789Sahrens 		dprintf("forcing random failure\n");
3452789Sahrens 		return (ERESTART);
3453789Sahrens 	}
3454789Sahrens #endif
34556245Smaybee 	if (reserve > arc_c/4 && !arc_no_grow)
34566245Smaybee 		arc_c = MIN(arc_c_max, reserve * 4);
34576245Smaybee 	if (reserve > arc_c)
3458982Smaybee 		return (ENOMEM);
3459982Smaybee 
3460789Sahrens 	/*
34619412SAleksandr.Guzovskiy@Sun.COM 	 * Don't count loaned bufs as in flight dirty data to prevent long
34629412SAleksandr.Guzovskiy@Sun.COM 	 * network delays from blocking transactions that are ready to be
34639412SAleksandr.Guzovskiy@Sun.COM 	 * assigned to a txg.
34649412SAleksandr.Guzovskiy@Sun.COM 	 */
34659412SAleksandr.Guzovskiy@Sun.COM 	anon_size = MAX((int64_t)(arc_anon->arcs_size - arc_loaned_bytes), 0);
34669412SAleksandr.Guzovskiy@Sun.COM 
34679412SAleksandr.Guzovskiy@Sun.COM 	/*
34686245Smaybee 	 * Writes will, almost always, require additional memory allocations
34696245Smaybee 	 * in order to compress/encrypt/etc the data.  We therefor need to
34706245Smaybee 	 * make sure that there is sufficient available memory for this.
34716245Smaybee 	 */
34729412SAleksandr.Guzovskiy@Sun.COM 	if (error = arc_memory_throttle(reserve, anon_size, txg))
34736245Smaybee 		return (error);
34746245Smaybee 
34756245Smaybee 	/*
3476982Smaybee 	 * Throttle writes when the amount of dirty data in the cache
3477982Smaybee 	 * gets too large.  We try to keep the cache less than half full
3478982Smaybee 	 * of dirty blocks so that our sync times don't grow too large.
3479982Smaybee 	 * Note: if two requests come in concurrently, we might let them
3480982Smaybee 	 * both succeed, when one of them should fail.  Not a huge deal.
3481789Sahrens 	 */
34829412SAleksandr.Guzovskiy@Sun.COM 
34839412SAleksandr.Guzovskiy@Sun.COM 	if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
34849412SAleksandr.Guzovskiy@Sun.COM 	    anon_size > arc_c / 4) {
34854309Smaybee 		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
34864309Smaybee 		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
34874309Smaybee 		    arc_tempreserve>>10,
34884309Smaybee 		    arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
34894309Smaybee 		    arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
34906245Smaybee 		    reserve>>10, arc_c>>10);
3491789Sahrens 		return (ERESTART);
3492789Sahrens 	}
34936245Smaybee 	atomic_add_64(&arc_tempreserve, reserve);
3494789Sahrens 	return (0);
3495789Sahrens }
3496789Sahrens 
3497789Sahrens void
3498789Sahrens arc_init(void)
3499789Sahrens {
3500789Sahrens 	mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
3501789Sahrens 	cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
3502789Sahrens 
35032391Smaybee 	/* Convert seconds to clock ticks */
35042638Sperrin 	arc_min_prefetch_lifespan = 1 * hz;
35052391Smaybee 
3506789Sahrens 	/* Start out with 1/8 of all memory */
35073403Sbmc 	arc_c = physmem * PAGESIZE / 8;
3508789Sahrens 
3509789Sahrens #ifdef _KERNEL
3510789Sahrens 	/*
3511789Sahrens 	 * On architectures where the physical memory can be larger
3512789Sahrens 	 * than the addressable space (intel in 32-bit mode), we may
3513789Sahrens 	 * need to limit the cache to 1/8 of VM size.
3514789Sahrens 	 */
35153403Sbmc 	arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
3516789Sahrens #endif
3517789Sahrens 
3518982Smaybee 	/* set min cache to 1/32 of all memory, or 64MB, whichever is more */
35193403Sbmc 	arc_c_min = MAX(arc_c / 4, 64<<20);
3520982Smaybee 	/* set max to 3/4 of all memory, or all but 1GB, whichever is more */
35213403Sbmc 	if (arc_c * 8 >= 1<<30)
35223403Sbmc 		arc_c_max = (arc_c * 8) - (1<<30);
3523789Sahrens 	else
35243403Sbmc 		arc_c_max = arc_c_min;
35253403Sbmc 	arc_c_max = MAX(arc_c * 6, arc_c_max);
35262885Sahrens 
35272885Sahrens 	/*
35282885Sahrens 	 * Allow the tunables to override our calculations if they are
35292885Sahrens 	 * reasonable (ie. over 64MB)
35302885Sahrens 	 */
35312885Sahrens 	if (zfs_arc_max > 64<<20 && zfs_arc_max < physmem * PAGESIZE)
35323403Sbmc 		arc_c_max = zfs_arc_max;
35333403Sbmc 	if (zfs_arc_min > 64<<20 && zfs_arc_min <= arc_c_max)
35343403Sbmc 		arc_c_min = zfs_arc_min;
35352885Sahrens 
35363403Sbmc 	arc_c = arc_c_max;
35373403Sbmc 	arc_p = (arc_c >> 1);
3538789Sahrens 
35394309Smaybee 	/* limit meta-data to 1/4 of the arc capacity */
35404309Smaybee 	arc_meta_limit = arc_c_max / 4;
35414645Sek110237 
35424645Sek110237 	/* Allow the tunable to override if it is reasonable */
35434645Sek110237 	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
35444645Sek110237 		arc_meta_limit = zfs_arc_meta_limit;
35454645Sek110237 
35464309Smaybee 	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
35474309Smaybee 		arc_c_min = arc_meta_limit / 2;
35484309Smaybee 
35498582SBrendan.Gregg@Sun.COM 	if (zfs_arc_grow_retry > 0)
35508582SBrendan.Gregg@Sun.COM 		arc_grow_retry = zfs_arc_grow_retry;
35518582SBrendan.Gregg@Sun.COM 
35528582SBrendan.Gregg@Sun.COM 	if (zfs_arc_shrink_shift > 0)
35538582SBrendan.Gregg@Sun.COM 		arc_shrink_shift = zfs_arc_shrink_shift;
35548582SBrendan.Gregg@Sun.COM 
35558582SBrendan.Gregg@Sun.COM 	if (zfs_arc_p_min_shift > 0)
35568582SBrendan.Gregg@Sun.COM 		arc_p_min_shift = zfs_arc_p_min_shift;
35578582SBrendan.Gregg@Sun.COM 
3558789Sahrens 	/* if kmem_flags are set, lets try to use less memory */
3559789Sahrens 	if (kmem_debugging())
35603403Sbmc 		arc_c = arc_c / 2;
35613403Sbmc 	if (arc_c < arc_c_min)
35623403Sbmc 		arc_c = arc_c_min;
3563789Sahrens 
35643403Sbmc 	arc_anon = &ARC_anon;
35653403Sbmc 	arc_mru = &ARC_mru;
35663403Sbmc 	arc_mru_ghost = &ARC_mru_ghost;
35673403Sbmc 	arc_mfu = &ARC_mfu;
35683403Sbmc 	arc_mfu_ghost = &ARC_mfu_ghost;
35695450Sbrendan 	arc_l2c_only = &ARC_l2c_only;
35703403Sbmc 	arc_size = 0;
3571789Sahrens 
35723403Sbmc 	mutex_init(&arc_anon->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
35733403Sbmc 	mutex_init(&arc_mru->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
35743403Sbmc 	mutex_init(&arc_mru_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
35753403Sbmc 	mutex_init(&arc_mfu->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
35763403Sbmc 	mutex_init(&arc_mfu_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
35775450Sbrendan 	mutex_init(&arc_l2c_only->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
35782688Smaybee 
35794309Smaybee 	list_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
35804309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35814309Smaybee 	list_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
35824309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35834309Smaybee 	list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
35844309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35854309Smaybee 	list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
35864309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35874309Smaybee 	list_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
35884309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35894309Smaybee 	list_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
35904309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35914309Smaybee 	list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
35924309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35934309Smaybee 	list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
35944309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35955450Sbrendan 	list_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
35965450Sbrendan 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35975450Sbrendan 	list_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
35985450Sbrendan 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3599789Sahrens 
3600789Sahrens 	buf_init();
3601789Sahrens 
3602789Sahrens 	arc_thread_exit = 0;
36031544Seschrock 	arc_eviction_list = NULL;
36041544Seschrock 	mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
36052887Smaybee 	bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
3606789Sahrens 
36073403Sbmc 	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
36083403Sbmc 	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
36093403Sbmc 
36103403Sbmc 	if (arc_ksp != NULL) {
36113403Sbmc 		arc_ksp->ks_data = &arc_stats;
36123403Sbmc 		kstat_install(arc_ksp);
36133403Sbmc 	}
36143403Sbmc 
3615789Sahrens 	(void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
3616789Sahrens 	    TS_RUN, minclsyspri);
36173158Smaybee 
36183158Smaybee 	arc_dead = FALSE;
36196987Sbrendan 	arc_warm = B_FALSE;
36206245Smaybee 
36216245Smaybee 	if (zfs_write_limit_max == 0)
36227468SMark.Maybee@Sun.COM 		zfs_write_limit_max = ptob(physmem) >> zfs_write_limit_shift;
36236245Smaybee 	else
36246245Smaybee 		zfs_write_limit_shift = 0;
36257468SMark.Maybee@Sun.COM 	mutex_init(&zfs_write_limit_lock, NULL, MUTEX_DEFAULT, NULL);
3626789Sahrens }
3627789Sahrens 
3628789Sahrens void
3629789Sahrens arc_fini(void)
3630789Sahrens {
3631789Sahrens 	mutex_enter(&arc_reclaim_thr_lock);
3632789Sahrens 	arc_thread_exit = 1;
3633789Sahrens 	while (arc_thread_exit != 0)
3634789Sahrens 		cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
3635789Sahrens 	mutex_exit(&arc_reclaim_thr_lock);
3636789Sahrens 
36375642Smaybee 	arc_flush(NULL);
3638789Sahrens 
3639789Sahrens 	arc_dead = TRUE;
3640789Sahrens 
36413403Sbmc 	if (arc_ksp != NULL) {
36423403Sbmc 		kstat_delete(arc_ksp);
36433403Sbmc 		arc_ksp = NULL;
36443403Sbmc 	}
36453403Sbmc 
36461544Seschrock 	mutex_destroy(&arc_eviction_mtx);
3647789Sahrens 	mutex_destroy(&arc_reclaim_thr_lock);
3648789Sahrens 	cv_destroy(&arc_reclaim_thr_cv);
3649789Sahrens 
36504309Smaybee 	list_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
36514309Smaybee 	list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
36524309Smaybee 	list_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
36534309Smaybee 	list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
36544309Smaybee 	list_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
36554309Smaybee 	list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
36564309Smaybee 	list_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
36574309Smaybee 	list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
3658789Sahrens 
36593403Sbmc 	mutex_destroy(&arc_anon->arcs_mtx);
36603403Sbmc 	mutex_destroy(&arc_mru->arcs_mtx);
36613403Sbmc 	mutex_destroy(&arc_mru_ghost->arcs_mtx);
36623403Sbmc 	mutex_destroy(&arc_mfu->arcs_mtx);
36633403Sbmc 	mutex_destroy(&arc_mfu_ghost->arcs_mtx);
36648214SRicardo.M.Correia@Sun.COM 	mutex_destroy(&arc_l2c_only->arcs_mtx);
36652856Snd150628 
36667468SMark.Maybee@Sun.COM 	mutex_destroy(&zfs_write_limit_lock);
36677468SMark.Maybee@Sun.COM 
3668789Sahrens 	buf_fini();
36699412SAleksandr.Guzovskiy@Sun.COM 
36709412SAleksandr.Guzovskiy@Sun.COM 	ASSERT(arc_loaned_bytes == 0);
3671789Sahrens }
36725450Sbrendan 
36735450Sbrendan /*
36745450Sbrendan  * Level 2 ARC
36755450Sbrendan  *
36765450Sbrendan  * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
36775450Sbrendan  * It uses dedicated storage devices to hold cached data, which are populated
36785450Sbrendan  * using large infrequent writes.  The main role of this cache is to boost
36795450Sbrendan  * the performance of random read workloads.  The intended L2ARC devices
36805450Sbrendan  * include short-stroked disks, solid state disks, and other media with
36815450Sbrendan  * substantially faster read latency than disk.
36825450Sbrendan  *
36835450Sbrendan  *                 +-----------------------+
36845450Sbrendan  *                 |         ARC           |
36855450Sbrendan  *                 +-----------------------+
36865450Sbrendan  *                    |         ^     ^
36875450Sbrendan  *                    |         |     |
36885450Sbrendan  *      l2arc_feed_thread()    arc_read()
36895450Sbrendan  *                    |         |     |
36905450Sbrendan  *                    |  l2arc read   |
36915450Sbrendan  *                    V         |     |
36925450Sbrendan  *               +---------------+    |
36935450Sbrendan  *               |     L2ARC     |    |
36945450Sbrendan  *               +---------------+    |
36955450Sbrendan  *                   |    ^           |
36965450Sbrendan  *          l2arc_write() |           |
36975450Sbrendan  *                   |    |           |
36985450Sbrendan  *                   V    |           |
36995450Sbrendan  *                 +-------+      +-------+
37005450Sbrendan  *                 | vdev  |      | vdev  |
37015450Sbrendan  *                 | cache |      | cache |
37025450Sbrendan  *                 +-------+      +-------+
37035450Sbrendan  *                 +=========+     .-----.
37045450Sbrendan  *                 :  L2ARC  :    |-_____-|
37055450Sbrendan  *                 : devices :    | Disks |
37065450Sbrendan  *                 +=========+    `-_____-'
37075450Sbrendan  *
37085450Sbrendan  * Read requests are satisfied from the following sources, in order:
37095450Sbrendan  *
37105450Sbrendan  *	1) ARC
37115450Sbrendan  *	2) vdev cache of L2ARC devices
37125450Sbrendan  *	3) L2ARC devices
37135450Sbrendan  *	4) vdev cache of disks
37145450Sbrendan  *	5) disks
37155450Sbrendan  *
37165450Sbrendan  * Some L2ARC device types exhibit extremely slow write performance.
37175450Sbrendan  * To accommodate for this there are some significant differences between
37185450Sbrendan  * the L2ARC and traditional cache design:
37195450Sbrendan  *
37205450Sbrendan  * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
37215450Sbrendan  * the ARC behave as usual, freeing buffers and placing headers on ghost
37225450Sbrendan  * lists.  The ARC does not send buffers to the L2ARC during eviction as
37235450Sbrendan  * this would add inflated write latencies for all ARC memory pressure.
37245450Sbrendan  *
37255450Sbrendan  * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
37265450Sbrendan  * It does this by periodically scanning buffers from the eviction-end of
37275450Sbrendan  * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
37285450Sbrendan  * not already there.  It scans until a headroom of buffers is satisfied,
37295450Sbrendan  * which itself is a buffer for ARC eviction.  The thread that does this is
37305450Sbrendan  * l2arc_feed_thread(), illustrated below; example sizes are included to
37315450Sbrendan  * provide a better sense of ratio than this diagram:
37325450Sbrendan  *
37335450Sbrendan  *	       head -->                        tail
37345450Sbrendan  *	        +---------------------+----------+
37355450Sbrendan  *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
37365450Sbrendan  *	        +---------------------+----------+   |   o L2ARC eligible
37375450Sbrendan  *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
37385450Sbrendan  *	        +---------------------+----------+   |
37395450Sbrendan  *	             15.9 Gbytes      ^ 32 Mbytes    |
37405450Sbrendan  *	                           headroom          |
37415450Sbrendan  *	                                      l2arc_feed_thread()
37425450Sbrendan  *	                                             |
37435450Sbrendan  *	                 l2arc write hand <--[oooo]--'
37445450Sbrendan  *	                         |           8 Mbyte
37455450Sbrendan  *	                         |          write max
37465450Sbrendan  *	                         V
37475450Sbrendan  *		  +==============================+
37485450Sbrendan  *	L2ARC dev |####|#|###|###|    |####| ... |
37495450Sbrendan  *	          +==============================+
37505450Sbrendan  *	                     32 Gbytes
37515450Sbrendan  *
37525450Sbrendan  * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
37535450Sbrendan  * evicted, then the L2ARC has cached a buffer much sooner than it probably
37545450Sbrendan  * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
37555450Sbrendan  * safe to say that this is an uncommon case, since buffers at the end of
37565450Sbrendan  * the ARC lists have moved there due to inactivity.
37575450Sbrendan  *
37585450Sbrendan  * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
37595450Sbrendan  * then the L2ARC simply misses copying some buffers.  This serves as a
37605450Sbrendan  * pressure valve to prevent heavy read workloads from both stalling the ARC
37615450Sbrendan  * with waits and clogging the L2ARC with writes.  This also helps prevent
37625450Sbrendan  * the potential for the L2ARC to churn if it attempts to cache content too
37635450Sbrendan  * quickly, such as during backups of the entire pool.
37645450Sbrendan  *
37656987Sbrendan  * 5. After system boot and before the ARC has filled main memory, there are
37666987Sbrendan  * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
37676987Sbrendan  * lists can remain mostly static.  Instead of searching from tail of these
37686987Sbrendan  * lists as pictured, the l2arc_feed_thread() will search from the list heads
37696987Sbrendan  * for eligible buffers, greatly increasing its chance of finding them.
37706987Sbrendan  *
37716987Sbrendan  * The L2ARC device write speed is also boosted during this time so that
37726987Sbrendan  * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
37736987Sbrendan  * there are no L2ARC reads, and no fear of degrading read performance
37746987Sbrendan  * through increased writes.
37756987Sbrendan  *
37766987Sbrendan  * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
37775450Sbrendan  * the vdev queue can aggregate them into larger and fewer writes.  Each
37785450Sbrendan  * device is written to in a rotor fashion, sweeping writes through
37795450Sbrendan  * available space then repeating.
37805450Sbrendan  *
37816987Sbrendan  * 7. The L2ARC does not store dirty content.  It never needs to flush
37825450Sbrendan  * write buffers back to disk based storage.
37835450Sbrendan  *
37846987Sbrendan  * 8. If an ARC buffer is written (and dirtied) which also exists in the
37855450Sbrendan  * L2ARC, the now stale L2ARC buffer is immediately dropped.
37865450Sbrendan  *
37875450Sbrendan  * The performance of the L2ARC can be tweaked by a number of tunables, which
37885450Sbrendan  * may be necessary for different workloads:
37895450Sbrendan  *
37905450Sbrendan  *	l2arc_write_max		max write bytes per interval
37916987Sbrendan  *	l2arc_write_boost	extra write bytes during device warmup
37925450Sbrendan  *	l2arc_noprefetch	skip caching prefetched buffers
37935450Sbrendan  *	l2arc_headroom		number of max device writes to precache
37945450Sbrendan  *	l2arc_feed_secs		seconds between L2ARC writing
37955450Sbrendan  *
37965450Sbrendan  * Tunables may be removed or added as future performance improvements are
37975450Sbrendan  * integrated, and also may become zpool properties.
37988582SBrendan.Gregg@Sun.COM  *
37998582SBrendan.Gregg@Sun.COM  * There are three key functions that control how the L2ARC warms up:
38008582SBrendan.Gregg@Sun.COM  *
38018582SBrendan.Gregg@Sun.COM  *	l2arc_write_eligible()	check if a buffer is eligible to cache
38028582SBrendan.Gregg@Sun.COM  *	l2arc_write_size()	calculate how much to write
38038582SBrendan.Gregg@Sun.COM  *	l2arc_write_interval()	calculate sleep delay between writes
38048582SBrendan.Gregg@Sun.COM  *
38058582SBrendan.Gregg@Sun.COM  * These three functions determine what to write, how much, and how quickly
38068582SBrendan.Gregg@Sun.COM  * to send writes.
38075450Sbrendan  */
38085450Sbrendan 
38098582SBrendan.Gregg@Sun.COM static boolean_t
38108636SMark.Maybee@Sun.COM l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *ab)
38118582SBrendan.Gregg@Sun.COM {
38128582SBrendan.Gregg@Sun.COM 	/*
38138582SBrendan.Gregg@Sun.COM 	 * A buffer is *not* eligible for the L2ARC if it:
38148582SBrendan.Gregg@Sun.COM 	 * 1. belongs to a different spa.
3815*10357SBrendan.Gregg@Sun.COM 	 * 2. is already cached on the L2ARC.
3816*10357SBrendan.Gregg@Sun.COM 	 * 3. has an I/O in progress (it may be an incomplete read).
3817*10357SBrendan.Gregg@Sun.COM 	 * 4. is flagged not eligible (zfs property).
38188582SBrendan.Gregg@Sun.COM 	 */
3819*10357SBrendan.Gregg@Sun.COM 	if (ab->b_spa != spa_guid || ab->b_l2hdr != NULL ||
38208582SBrendan.Gregg@Sun.COM 	    HDR_IO_IN_PROGRESS(ab) || !HDR_L2CACHE(ab))
38218582SBrendan.Gregg@Sun.COM 		return (B_FALSE);
38228582SBrendan.Gregg@Sun.COM 
38238582SBrendan.Gregg@Sun.COM 	return (B_TRUE);
38248582SBrendan.Gregg@Sun.COM }
38258582SBrendan.Gregg@Sun.COM 
38268582SBrendan.Gregg@Sun.COM static uint64_t
38278582SBrendan.Gregg@Sun.COM l2arc_write_size(l2arc_dev_t *dev)
38288582SBrendan.Gregg@Sun.COM {
38298582SBrendan.Gregg@Sun.COM 	uint64_t size;
38308582SBrendan.Gregg@Sun.COM 
38318582SBrendan.Gregg@Sun.COM 	size = dev->l2ad_write;
38328582SBrendan.Gregg@Sun.COM 
38338582SBrendan.Gregg@Sun.COM 	if (arc_warm == B_FALSE)
38348582SBrendan.Gregg@Sun.COM 		size += dev->l2ad_boost;
38358582SBrendan.Gregg@Sun.COM 
38368582SBrendan.Gregg@Sun.COM 	return (size);
38378582SBrendan.Gregg@Sun.COM 
38388582SBrendan.Gregg@Sun.COM }
38398582SBrendan.Gregg@Sun.COM 
38408582SBrendan.Gregg@Sun.COM static clock_t
38418582SBrendan.Gregg@Sun.COM l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
38428582SBrendan.Gregg@Sun.COM {
38438582SBrendan.Gregg@Sun.COM 	clock_t interval, next;
38448582SBrendan.Gregg@Sun.COM 
38458582SBrendan.Gregg@Sun.COM 	/*
38468582SBrendan.Gregg@Sun.COM 	 * If the ARC lists are busy, increase our write rate; if the
38478582SBrendan.Gregg@Sun.COM 	 * lists are stale, idle back.  This is achieved by checking
38488582SBrendan.Gregg@Sun.COM 	 * how much we previously wrote - if it was more than half of
38498582SBrendan.Gregg@Sun.COM 	 * what we wanted, schedule the next write much sooner.
38508582SBrendan.Gregg@Sun.COM 	 */
38518582SBrendan.Gregg@Sun.COM 	if (l2arc_feed_again && wrote > (wanted / 2))
38528582SBrendan.Gregg@Sun.COM 		interval = (hz * l2arc_feed_min_ms) / 1000;
38538582SBrendan.Gregg@Sun.COM 	else
38548582SBrendan.Gregg@Sun.COM 		interval = hz * l2arc_feed_secs;
38558582SBrendan.Gregg@Sun.COM 
38568582SBrendan.Gregg@Sun.COM 	next = MAX(lbolt, MIN(lbolt + interval, began + interval));
38578582SBrendan.Gregg@Sun.COM 
38588582SBrendan.Gregg@Sun.COM 	return (next);
38598582SBrendan.Gregg@Sun.COM }
38608582SBrendan.Gregg@Sun.COM 
38615450Sbrendan static void
38625450Sbrendan l2arc_hdr_stat_add(void)
38635450Sbrendan {
38646018Sbrendan 	ARCSTAT_INCR(arcstat_l2_hdr_size, HDR_SIZE + L2HDR_SIZE);
38656018Sbrendan 	ARCSTAT_INCR(arcstat_hdr_size, -HDR_SIZE);
38665450Sbrendan }
38675450Sbrendan 
38685450Sbrendan static void
38695450Sbrendan l2arc_hdr_stat_remove(void)
38705450Sbrendan {
38716018Sbrendan 	ARCSTAT_INCR(arcstat_l2_hdr_size, -(HDR_SIZE + L2HDR_SIZE));
38726018Sbrendan 	ARCSTAT_INCR(arcstat_hdr_size, HDR_SIZE);
38735450Sbrendan }
38745450Sbrendan 
38755450Sbrendan /*
38765450Sbrendan  * Cycle through L2ARC devices.  This is how L2ARC load balances.
38776987Sbrendan  * If a device is returned, this also returns holding the spa config lock.
38785450Sbrendan  */
38795450Sbrendan static l2arc_dev_t *
38805450Sbrendan l2arc_dev_get_next(void)
38815450Sbrendan {
38826987Sbrendan 	l2arc_dev_t *first, *next = NULL;
38836987Sbrendan 
38846987Sbrendan 	/*
38856987Sbrendan 	 * Lock out the removal of spas (spa_namespace_lock), then removal
38866987Sbrendan 	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
38876987Sbrendan 	 * both locks will be dropped and a spa config lock held instead.
38886987Sbrendan 	 */
38896987Sbrendan 	mutex_enter(&spa_namespace_lock);
38906987Sbrendan 	mutex_enter(&l2arc_dev_mtx);
38916643Seschrock 
38926643Seschrock 	/* if there are no vdevs, there is nothing to do */
38936643Seschrock 	if (l2arc_ndev == 0)
38946987Sbrendan 		goto out;
38956643Seschrock 
38966643Seschrock 	first = NULL;
38976643Seschrock 	next = l2arc_dev_last;
38986643Seschrock 	do {
38996643Seschrock 		/* loop around the list looking for a non-faulted vdev */
39006643Seschrock 		if (next == NULL) {
39015450Sbrendan 			next = list_head(l2arc_dev_list);
39026643Seschrock 		} else {
39036643Seschrock 			next = list_next(l2arc_dev_list, next);
39046643Seschrock 			if (next == NULL)
39056643Seschrock 				next = list_head(l2arc_dev_list);
39066643Seschrock 		}
39076643Seschrock 
39086643Seschrock 		/* if we have come back to the start, bail out */
39096643Seschrock 		if (first == NULL)
39106643Seschrock 			first = next;
39116643Seschrock 		else if (next == first)
39126643Seschrock 			break;
39136643Seschrock 
39146643Seschrock 	} while (vdev_is_dead(next->l2ad_vdev));
39156643Seschrock 
39166643Seschrock 	/* if we were unable to find any usable vdevs, return NULL */
39176643Seschrock 	if (vdev_is_dead(next->l2ad_vdev))
39186987Sbrendan 		next = NULL;
39195450Sbrendan 
39205450Sbrendan 	l2arc_dev_last = next;
39215450Sbrendan 
39226987Sbrendan out:
39236987Sbrendan 	mutex_exit(&l2arc_dev_mtx);
39246987Sbrendan 
39256987Sbrendan 	/*
39266987Sbrendan 	 * Grab the config lock to prevent the 'next' device from being
39276987Sbrendan 	 * removed while we are writing to it.
39286987Sbrendan 	 */
39296987Sbrendan 	if (next != NULL)
39307754SJeff.Bonwick@Sun.COM 		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
39316987Sbrendan 	mutex_exit(&spa_namespace_lock);
39326987Sbrendan 
39335450Sbrendan 	return (next);
39345450Sbrendan }
39355450Sbrendan 
39365450Sbrendan /*
39376987Sbrendan  * Free buffers that were tagged for destruction.
39386987Sbrendan  */
39396987Sbrendan static void
39406987Sbrendan l2arc_do_free_on_write()
39416987Sbrendan {
39426987Sbrendan 	list_t *buflist;
39436987Sbrendan 	l2arc_data_free_t *df, *df_prev;
39446987Sbrendan 
39456987Sbrendan 	mutex_enter(&l2arc_free_on_write_mtx);
39466987Sbrendan 	buflist = l2arc_free_on_write;
39476987Sbrendan 
39486987Sbrendan 	for (df = list_tail(buflist); df; df = df_prev) {
39496987Sbrendan 		df_prev = list_prev(buflist, df);
39506987Sbrendan 		ASSERT(df->l2df_data != NULL);
39516987Sbrendan 		ASSERT(df->l2df_func != NULL);
39526987Sbrendan 		df->l2df_func(df->l2df_data, df->l2df_size);
39536987Sbrendan 		list_remove(buflist, df);
39546987Sbrendan 		kmem_free(df, sizeof (l2arc_data_free_t));
39556987Sbrendan 	}
39566987Sbrendan 
39576987Sbrendan 	mutex_exit(&l2arc_free_on_write_mtx);
39586987Sbrendan }
39596987Sbrendan 
39606987Sbrendan /*
39615450Sbrendan  * A write to a cache device has completed.  Update all headers to allow
39625450Sbrendan  * reads from these buffers to begin.
39635450Sbrendan  */
39645450Sbrendan static void
39655450Sbrendan l2arc_write_done(zio_t *zio)
39665450Sbrendan {
39675450Sbrendan 	l2arc_write_callback_t *cb;
39685450Sbrendan 	l2arc_dev_t *dev;
39695450Sbrendan 	list_t *buflist;
39705450Sbrendan 	arc_buf_hdr_t *head, *ab, *ab_prev;
39716987Sbrendan 	l2arc_buf_hdr_t *abl2;
39725450Sbrendan 	kmutex_t *hash_lock;
39735450Sbrendan 
39745450Sbrendan 	cb = zio->io_private;
39755450Sbrendan 	ASSERT(cb != NULL);
39765450Sbrendan 	dev = cb->l2wcb_dev;
39775450Sbrendan 	ASSERT(dev != NULL);
39785450Sbrendan 	head = cb->l2wcb_head;
39795450Sbrendan 	ASSERT(head != NULL);
39805450Sbrendan 	buflist = dev->l2ad_buflist;
39815450Sbrendan 	ASSERT(buflist != NULL);
39825450Sbrendan 	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
39835450Sbrendan 	    l2arc_write_callback_t *, cb);
39845450Sbrendan 
39855450Sbrendan 	if (zio->io_error != 0)
39865450Sbrendan 		ARCSTAT_BUMP(arcstat_l2_writes_error);
39875450Sbrendan 
39885450Sbrendan 	mutex_enter(&l2arc_buflist_mtx);
39895450Sbrendan 
39905450Sbrendan 	/*
39915450Sbrendan 	 * All writes completed, or an error was hit.
39925450Sbrendan 	 */
39935450Sbrendan 	for (ab = list_prev(buflist, head); ab; ab = ab_prev) {
39945450Sbrendan 		ab_prev = list_prev(buflist, ab);
39955450Sbrendan 
39965450Sbrendan 		hash_lock = HDR_LOCK(ab);
39975450Sbrendan 		if (!mutex_tryenter(hash_lock)) {
39985450Sbrendan 			/*
39995450Sbrendan 			 * This buffer misses out.  It may be in a stage
40005450Sbrendan 			 * of eviction.  Its ARC_L2_WRITING flag will be
40015450Sbrendan 			 * left set, denying reads to this buffer.
40025450Sbrendan 			 */
40035450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_writes_hdr_miss);
40045450Sbrendan 			continue;
40055450Sbrendan 		}
40065450Sbrendan 
40075450Sbrendan 		if (zio->io_error != 0) {
40085450Sbrendan 			/*
40096987Sbrendan 			 * Error - drop L2ARC entry.
40105450Sbrendan 			 */
40116987Sbrendan 			list_remove(buflist, ab);
40126987Sbrendan 			abl2 = ab->b_l2hdr;
40135450Sbrendan 			ab->b_l2hdr = NULL;
40146987Sbrendan 			kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
40156987Sbrendan 			ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
40165450Sbrendan 		}
40175450Sbrendan 
40185450Sbrendan 		/*
40195450Sbrendan 		 * Allow ARC to begin reads to this L2ARC entry.
40205450Sbrendan 		 */
40215450Sbrendan 		ab->b_flags &= ~ARC_L2_WRITING;
40225450Sbrendan 
40235450Sbrendan 		mutex_exit(hash_lock);
40245450Sbrendan 	}
40255450Sbrendan 
40265450Sbrendan 	atomic_inc_64(&l2arc_writes_done);
40275450Sbrendan 	list_remove(buflist, head);
40285450Sbrendan 	kmem_cache_free(hdr_cache, head);
40295450Sbrendan 	mutex_exit(&l2arc_buflist_mtx);
40305450Sbrendan 
40316987Sbrendan 	l2arc_do_free_on_write();
40325450Sbrendan 
40335450Sbrendan 	kmem_free(cb, sizeof (l2arc_write_callback_t));
40345450Sbrendan }
40355450Sbrendan 
40365450Sbrendan /*
40375450Sbrendan  * A read to a cache device completed.  Validate buffer contents before
40385450Sbrendan  * handing over to the regular ARC routines.
40395450Sbrendan  */
40405450Sbrendan static void
40415450Sbrendan l2arc_read_done(zio_t *zio)
40425450Sbrendan {
40435450Sbrendan 	l2arc_read_callback_t *cb;
40445450Sbrendan 	arc_buf_hdr_t *hdr;
40455450Sbrendan 	arc_buf_t *buf;
40465450Sbrendan 	kmutex_t *hash_lock;
40476987Sbrendan 	int equal;
40485450Sbrendan 
40497754SJeff.Bonwick@Sun.COM 	ASSERT(zio->io_vd != NULL);
40507754SJeff.Bonwick@Sun.COM 	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
40517754SJeff.Bonwick@Sun.COM 
40527754SJeff.Bonwick@Sun.COM 	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
40537754SJeff.Bonwick@Sun.COM 
40545450Sbrendan 	cb = zio->io_private;
40555450Sbrendan 	ASSERT(cb != NULL);
40565450Sbrendan 	buf = cb->l2rcb_buf;
40575450Sbrendan 	ASSERT(buf != NULL);
40585450Sbrendan 	hdr = buf->b_hdr;
40595450Sbrendan 	ASSERT(hdr != NULL);
40605450Sbrendan 
40615450Sbrendan 	hash_lock = HDR_LOCK(hdr);
40625450Sbrendan 	mutex_enter(hash_lock);
40635450Sbrendan 
40645450Sbrendan 	/*
40655450Sbrendan 	 * Check this survived the L2ARC journey.
40665450Sbrendan 	 */
40675450Sbrendan 	equal = arc_cksum_equal(buf);
40685450Sbrendan 	if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
40695450Sbrendan 		mutex_exit(hash_lock);
40705450Sbrendan 		zio->io_private = buf;
40717754SJeff.Bonwick@Sun.COM 		zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
40727754SJeff.Bonwick@Sun.COM 		zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
40735450Sbrendan 		arc_read_done(zio);
40745450Sbrendan 	} else {
40755450Sbrendan 		mutex_exit(hash_lock);
40765450Sbrendan 		/*
40775450Sbrendan 		 * Buffer didn't survive caching.  Increment stats and
40785450Sbrendan 		 * reissue to the original storage device.
40795450Sbrendan 		 */
40806987Sbrendan 		if (zio->io_error != 0) {
40815450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_io_error);
40826987Sbrendan 		} else {
40836987Sbrendan 			zio->io_error = EIO;
40846987Sbrendan 		}
40855450Sbrendan 		if (!equal)
40865450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
40875450Sbrendan 
40887754SJeff.Bonwick@Sun.COM 		/*
40897754SJeff.Bonwick@Sun.COM 		 * If there's no waiter, issue an async i/o to the primary
40907754SJeff.Bonwick@Sun.COM 		 * storage now.  If there *is* a waiter, the caller must
40917754SJeff.Bonwick@Sun.COM 		 * issue the i/o in a context where it's OK to block.
40927754SJeff.Bonwick@Sun.COM 		 */
40938632SBill.Moore@Sun.COM 		if (zio->io_waiter == NULL) {
40948632SBill.Moore@Sun.COM 			zio_t *pio = zio_unique_parent(zio);
40958632SBill.Moore@Sun.COM 
40968632SBill.Moore@Sun.COM 			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
40978632SBill.Moore@Sun.COM 
40988632SBill.Moore@Sun.COM 			zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
40997754SJeff.Bonwick@Sun.COM 			    buf->b_data, zio->io_size, arc_read_done, buf,
41007754SJeff.Bonwick@Sun.COM 			    zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
41018632SBill.Moore@Sun.COM 		}
41025450Sbrendan 	}
41035450Sbrendan 
41045450Sbrendan 	kmem_free(cb, sizeof (l2arc_read_callback_t));
41055450Sbrendan }
41065450Sbrendan 
41075450Sbrendan /*
41085450Sbrendan  * This is the list priority from which the L2ARC will search for pages to
41095450Sbrendan  * cache.  This is used within loops (0..3) to cycle through lists in the
41105450Sbrendan  * desired order.  This order can have a significant effect on cache
41115450Sbrendan  * performance.
41125450Sbrendan  *
41135450Sbrendan  * Currently the metadata lists are hit first, MFU then MRU, followed by
41145450Sbrendan  * the data lists.  This function returns a locked list, and also returns
41155450Sbrendan  * the lock pointer.
41165450Sbrendan  */
41175450Sbrendan static list_t *
41185450Sbrendan l2arc_list_locked(int list_num, kmutex_t **lock)
41195450Sbrendan {
41205450Sbrendan 	list_t *list;
41215450Sbrendan 
41225450Sbrendan 	ASSERT(list_num >= 0 && list_num <= 3);
41235450Sbrendan 
41245450Sbrendan 	switch (list_num) {
41255450Sbrendan 	case 0:
41265450Sbrendan 		list = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
41275450Sbrendan 		*lock = &arc_mfu->arcs_mtx;
41285450Sbrendan 		break;
41295450Sbrendan 	case 1:
41305450Sbrendan 		list = &arc_mru->arcs_list[ARC_BUFC_METADATA];
41315450Sbrendan 		*lock = &arc_mru->arcs_mtx;
41325450Sbrendan 		break;
41335450Sbrendan 	case 2:
41345450Sbrendan 		list = &arc_mfu->arcs_list[ARC_BUFC_DATA];
41355450Sbrendan 		*lock = &arc_mfu->arcs_mtx;
41365450Sbrendan 		break;
41375450Sbrendan 	case 3:
41385450Sbrendan 		list = &arc_mru->arcs_list[ARC_BUFC_DATA];
41395450Sbrendan 		*lock = &arc_mru->arcs_mtx;
41405450Sbrendan 		break;
41415450Sbrendan 	}
41425450Sbrendan 
41435450Sbrendan 	ASSERT(!(MUTEX_HELD(*lock)));
41445450Sbrendan 	mutex_enter(*lock);
41455450Sbrendan 	return (list);
41465450Sbrendan }
41475450Sbrendan 
41485450Sbrendan /*
41495450Sbrendan  * Evict buffers from the device write hand to the distance specified in
41505450Sbrendan  * bytes.  This distance may span populated buffers, it may span nothing.
41515450Sbrendan  * This is clearing a region on the L2ARC device ready for writing.
41525450Sbrendan  * If the 'all' boolean is set, every buffer is evicted.
41535450Sbrendan  */
41545450Sbrendan static void
41555450Sbrendan l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
41565450Sbrendan {
41575450Sbrendan 	list_t *buflist;
41585450Sbrendan 	l2arc_buf_hdr_t *abl2;
41595450Sbrendan 	arc_buf_hdr_t *ab, *ab_prev;
41605450Sbrendan 	kmutex_t *hash_lock;
41615450Sbrendan 	uint64_t taddr;
41625450Sbrendan 
41635450Sbrendan 	buflist = dev->l2ad_buflist;
41645450Sbrendan 
41655450Sbrendan 	if (buflist == NULL)
41665450Sbrendan 		return;
41675450Sbrendan 
41685450Sbrendan 	if (!all && dev->l2ad_first) {
41695450Sbrendan 		/*
41705450Sbrendan 		 * This is the first sweep through the device.  There is
41715450Sbrendan 		 * nothing to evict.
41725450Sbrendan 		 */
41735450Sbrendan 		return;
41745450Sbrendan 	}
41755450Sbrendan 
41766987Sbrendan 	if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
41775450Sbrendan 		/*
41785450Sbrendan 		 * When nearing the end of the device, evict to the end
41795450Sbrendan 		 * before the device write hand jumps to the start.
41805450Sbrendan 		 */
41815450Sbrendan 		taddr = dev->l2ad_end;
41825450Sbrendan 	} else {
41835450Sbrendan 		taddr = dev->l2ad_hand + distance;
41845450Sbrendan 	}
41855450Sbrendan 	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
41865450Sbrendan 	    uint64_t, taddr, boolean_t, all);
41875450Sbrendan 
41885450Sbrendan top:
41895450Sbrendan 	mutex_enter(&l2arc_buflist_mtx);
41905450Sbrendan 	for (ab = list_tail(buflist); ab; ab = ab_prev) {
41915450Sbrendan 		ab_prev = list_prev(buflist, ab);
41925450Sbrendan 
41935450Sbrendan 		hash_lock = HDR_LOCK(ab);
41945450Sbrendan 		if (!mutex_tryenter(hash_lock)) {
41955450Sbrendan 			/*
41965450Sbrendan 			 * Missed the hash lock.  Retry.
41975450Sbrendan 			 */
41985450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
41995450Sbrendan 			mutex_exit(&l2arc_buflist_mtx);
42005450Sbrendan 			mutex_enter(hash_lock);
42015450Sbrendan 			mutex_exit(hash_lock);
42025450Sbrendan 			goto top;
42035450Sbrendan 		}
42045450Sbrendan 
42055450Sbrendan 		if (HDR_L2_WRITE_HEAD(ab)) {
42065450Sbrendan 			/*
42075450Sbrendan 			 * We hit a write head node.  Leave it for
42085450Sbrendan 			 * l2arc_write_done().
42095450Sbrendan 			 */
42105450Sbrendan 			list_remove(buflist, ab);
42115450Sbrendan 			mutex_exit(hash_lock);
42125450Sbrendan 			continue;
42135450Sbrendan 		}
42145450Sbrendan 
42155450Sbrendan 		if (!all && ab->b_l2hdr != NULL &&
42165450Sbrendan 		    (ab->b_l2hdr->b_daddr > taddr ||
42175450Sbrendan 		    ab->b_l2hdr->b_daddr < dev->l2ad_hand)) {
42185450Sbrendan 			/*
42195450Sbrendan 			 * We've evicted to the target address,
42205450Sbrendan 			 * or the end of the device.
42215450Sbrendan 			 */
42225450Sbrendan 			mutex_exit(hash_lock);
42235450Sbrendan 			break;
42245450Sbrendan 		}
42255450Sbrendan 
42265450Sbrendan 		if (HDR_FREE_IN_PROGRESS(ab)) {
42275450Sbrendan 			/*
42285450Sbrendan 			 * Already on the path to destruction.
42295450Sbrendan 			 */
42305450Sbrendan 			mutex_exit(hash_lock);
42315450Sbrendan 			continue;
42325450Sbrendan 		}
42335450Sbrendan 
42345450Sbrendan 		if (ab->b_state == arc_l2c_only) {
42355450Sbrendan 			ASSERT(!HDR_L2_READING(ab));
42365450Sbrendan 			/*
42375450Sbrendan 			 * This doesn't exist in the ARC.  Destroy.
42385450Sbrendan 			 * arc_hdr_destroy() will call list_remove()
42395450Sbrendan 			 * and decrement arcstat_l2_size.
42405450Sbrendan 			 */
42415450Sbrendan 			arc_change_state(arc_anon, ab, hash_lock);
42425450Sbrendan 			arc_hdr_destroy(ab);
42435450Sbrendan 		} else {
42445450Sbrendan 			/*
42456987Sbrendan 			 * Invalidate issued or about to be issued
42466987Sbrendan 			 * reads, since we may be about to write
42476987Sbrendan 			 * over this location.
42486987Sbrendan 			 */
42496987Sbrendan 			if (HDR_L2_READING(ab)) {
42506987Sbrendan 				ARCSTAT_BUMP(arcstat_l2_evict_reading);
42516987Sbrendan 				ab->b_flags |= ARC_L2_EVICTED;
42526987Sbrendan 			}
42536987Sbrendan 
42546987Sbrendan 			/*
42555450Sbrendan 			 * Tell ARC this no longer exists in L2ARC.
42565450Sbrendan 			 */
42575450Sbrendan 			if (ab->b_l2hdr != NULL) {
42585450Sbrendan 				abl2 = ab->b_l2hdr;
42595450Sbrendan 				ab->b_l2hdr = NULL;
42605450Sbrendan 				kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
42615450Sbrendan 				ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
42625450Sbrendan 			}
42635450Sbrendan 			list_remove(buflist, ab);
42645450Sbrendan 
42655450Sbrendan 			/*
42665450Sbrendan 			 * This may have been leftover after a
42675450Sbrendan 			 * failed write.
42685450Sbrendan 			 */
42695450Sbrendan 			ab->b_flags &= ~ARC_L2_WRITING;
42705450Sbrendan 		}
42715450Sbrendan 		mutex_exit(hash_lock);
42725450Sbrendan 	}
42735450Sbrendan 	mutex_exit(&l2arc_buflist_mtx);
42745450Sbrendan 
42755450Sbrendan 	spa_l2cache_space_update(dev->l2ad_vdev, 0, -(taddr - dev->l2ad_evict));
42765450Sbrendan 	dev->l2ad_evict = taddr;
42775450Sbrendan }
42785450Sbrendan 
42795450Sbrendan /*
42805450Sbrendan  * Find and write ARC buffers to the L2ARC device.
42815450Sbrendan  *
42825450Sbrendan  * An ARC_L2_WRITING flag is set so that the L2ARC buffers are not valid
42835450Sbrendan  * for reading until they have completed writing.
42845450Sbrendan  */
42858582SBrendan.Gregg@Sun.COM static uint64_t
42866987Sbrendan l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
42875450Sbrendan {
42885450Sbrendan 	arc_buf_hdr_t *ab, *ab_prev, *head;
42895450Sbrendan 	l2arc_buf_hdr_t *hdrl2;
42905450Sbrendan 	list_t *list;
42916987Sbrendan 	uint64_t passed_sz, write_sz, buf_sz, headroom;
42925450Sbrendan 	void *buf_data;
42935450Sbrendan 	kmutex_t *hash_lock, *list_lock;
42945450Sbrendan 	boolean_t have_lock, full;
42955450Sbrendan 	l2arc_write_callback_t *cb;
42965450Sbrendan 	zio_t *pio, *wzio;
42978636SMark.Maybee@Sun.COM 	uint64_t guid = spa_guid(spa);
42985450Sbrendan 
42995450Sbrendan 	ASSERT(dev->l2ad_vdev != NULL);
43005450Sbrendan 
43015450Sbrendan 	pio = NULL;
43025450Sbrendan 	write_sz = 0;
43035450Sbrendan 	full = B_FALSE;
43046245Smaybee 	head = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
43055450Sbrendan 	head->b_flags |= ARC_L2_WRITE_HEAD;
43065450Sbrendan 
43075450Sbrendan 	/*
43085450Sbrendan 	 * Copy buffers for L2ARC writing.
43095450Sbrendan 	 */
43105450Sbrendan 	mutex_enter(&l2arc_buflist_mtx);
43115450Sbrendan 	for (int try = 0; try <= 3; try++) {
43125450Sbrendan 		list = l2arc_list_locked(try, &list_lock);
43135450Sbrendan 		passed_sz = 0;
43145450Sbrendan 
43156987Sbrendan 		/*
43166987Sbrendan 		 * L2ARC fast warmup.
43176987Sbrendan 		 *
43186987Sbrendan 		 * Until the ARC is warm and starts to evict, read from the
43196987Sbrendan 		 * head of the ARC lists rather than the tail.
43206987Sbrendan 		 */
43216987Sbrendan 		headroom = target_sz * l2arc_headroom;
43226987Sbrendan 		if (arc_warm == B_FALSE)
43236987Sbrendan 			ab = list_head(list);
43246987Sbrendan 		else
43256987Sbrendan 			ab = list_tail(list);
43266987Sbrendan 
43276987Sbrendan 		for (; ab; ab = ab_prev) {
43286987Sbrendan 			if (arc_warm == B_FALSE)
43296987Sbrendan 				ab_prev = list_next(list, ab);
43306987Sbrendan 			else
43316987Sbrendan 				ab_prev = list_prev(list, ab);
43325450Sbrendan 
43335450Sbrendan 			hash_lock = HDR_LOCK(ab);
43345450Sbrendan 			have_lock = MUTEX_HELD(hash_lock);
43355450Sbrendan 			if (!have_lock && !mutex_tryenter(hash_lock)) {
43365450Sbrendan 				/*
43375450Sbrendan 				 * Skip this buffer rather than waiting.
43385450Sbrendan 				 */
43395450Sbrendan 				continue;
43405450Sbrendan 			}
43415450Sbrendan 
43425450Sbrendan 			passed_sz += ab->b_size;
43435450Sbrendan 			if (passed_sz > headroom) {
43445450Sbrendan 				/*
43455450Sbrendan 				 * Searched too far.
43465450Sbrendan 				 */
43475450Sbrendan 				mutex_exit(hash_lock);
43485450Sbrendan 				break;
43495450Sbrendan 			}
43505450Sbrendan 
43518636SMark.Maybee@Sun.COM 			if (!l2arc_write_eligible(guid, ab)) {
43525450Sbrendan 				mutex_exit(hash_lock);
43535450Sbrendan 				continue;
43545450Sbrendan 			}
43555450Sbrendan 
43565450Sbrendan 			if ((write_sz + ab->b_size) > target_sz) {
43575450Sbrendan 				full = B_TRUE;
43585450Sbrendan 				mutex_exit(hash_lock);
43595450Sbrendan 				break;
43605450Sbrendan 			}
43615450Sbrendan 
43625450Sbrendan 			if (pio == NULL) {
43635450Sbrendan 				/*
43645450Sbrendan 				 * Insert a dummy header on the buflist so
43655450Sbrendan 				 * l2arc_write_done() can find where the
43665450Sbrendan 				 * write buffers begin without searching.
43675450Sbrendan 				 */
43685450Sbrendan 				list_insert_head(dev->l2ad_buflist, head);
43695450Sbrendan 
43705450Sbrendan 				cb = kmem_alloc(
43715450Sbrendan 				    sizeof (l2arc_write_callback_t), KM_SLEEP);
43725450Sbrendan 				cb->l2wcb_dev = dev;
43735450Sbrendan 				cb->l2wcb_head = head;
43745450Sbrendan 				pio = zio_root(spa, l2arc_write_done, cb,
43755450Sbrendan 				    ZIO_FLAG_CANFAIL);
43765450Sbrendan 			}
43775450Sbrendan 
43785450Sbrendan 			/*
43795450Sbrendan 			 * Create and add a new L2ARC header.
43805450Sbrendan 			 */
43815450Sbrendan 			hdrl2 = kmem_zalloc(sizeof (l2arc_buf_hdr_t), KM_SLEEP);
43825450Sbrendan 			hdrl2->b_dev = dev;
43835450Sbrendan 			hdrl2->b_daddr = dev->l2ad_hand;
43845450Sbrendan 
43855450Sbrendan 			ab->b_flags |= ARC_L2_WRITING;
43865450Sbrendan 			ab->b_l2hdr = hdrl2;
43875450Sbrendan 			list_insert_head(dev->l2ad_buflist, ab);
43885450Sbrendan 			buf_data = ab->b_buf->b_data;
43895450Sbrendan 			buf_sz = ab->b_size;
43905450Sbrendan 
43915450Sbrendan 			/*
43925450Sbrendan 			 * Compute and store the buffer cksum before
43935450Sbrendan 			 * writing.  On debug the cksum is verified first.
43945450Sbrendan 			 */
43955450Sbrendan 			arc_cksum_verify(ab->b_buf);
43965450Sbrendan 			arc_cksum_compute(ab->b_buf, B_TRUE);
43975450Sbrendan 
43985450Sbrendan 			mutex_exit(hash_lock);
43995450Sbrendan 
44005450Sbrendan 			wzio = zio_write_phys(pio, dev->l2ad_vdev,
44015450Sbrendan 			    dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
44025450Sbrendan 			    NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
44035450Sbrendan 			    ZIO_FLAG_CANFAIL, B_FALSE);
44045450Sbrendan 
44055450Sbrendan 			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
44065450Sbrendan 			    zio_t *, wzio);
44075450Sbrendan 			(void) zio_nowait(wzio);
44085450Sbrendan 
44097754SJeff.Bonwick@Sun.COM 			/*
44107754SJeff.Bonwick@Sun.COM 			 * Keep the clock hand suitably device-aligned.
44117754SJeff.Bonwick@Sun.COM 			 */
44127754SJeff.Bonwick@Sun.COM 			buf_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
44137754SJeff.Bonwick@Sun.COM 
44145450Sbrendan 			write_sz += buf_sz;
44155450Sbrendan 			dev->l2ad_hand += buf_sz;
44165450Sbrendan 		}
44175450Sbrendan 
44185450Sbrendan 		mutex_exit(list_lock);
44195450Sbrendan 
44205450Sbrendan 		if (full == B_TRUE)
44215450Sbrendan 			break;
44225450Sbrendan 	}
44235450Sbrendan 	mutex_exit(&l2arc_buflist_mtx);
44245450Sbrendan 
44255450Sbrendan 	if (pio == NULL) {
44265450Sbrendan 		ASSERT3U(write_sz, ==, 0);
44275450Sbrendan 		kmem_cache_free(hdr_cache, head);
44288582SBrendan.Gregg@Sun.COM 		return (0);
44295450Sbrendan 	}
44305450Sbrendan 
44315450Sbrendan 	ASSERT3U(write_sz, <=, target_sz);
44325450Sbrendan 	ARCSTAT_BUMP(arcstat_l2_writes_sent);
44338582SBrendan.Gregg@Sun.COM 	ARCSTAT_INCR(arcstat_l2_write_bytes, write_sz);
44345450Sbrendan 	ARCSTAT_INCR(arcstat_l2_size, write_sz);
44355450Sbrendan 	spa_l2cache_space_update(dev->l2ad_vdev, 0, write_sz);
44365450Sbrendan 
44375450Sbrendan 	/*
44385450Sbrendan 	 * Bump device hand to the device start if it is approaching the end.
44395450Sbrendan 	 * l2arc_evict() will already have evicted ahead for this case.
44405450Sbrendan 	 */
44416987Sbrendan 	if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
44425450Sbrendan 		spa_l2cache_space_update(dev->l2ad_vdev, 0,
44435450Sbrendan 		    dev->l2ad_end - dev->l2ad_hand);
44445450Sbrendan 		dev->l2ad_hand = dev->l2ad_start;
44455450Sbrendan 		dev->l2ad_evict = dev->l2ad_start;
44465450Sbrendan 		dev->l2ad_first = B_FALSE;
44475450Sbrendan 	}
44485450Sbrendan 
44498582SBrendan.Gregg@Sun.COM 	dev->l2ad_writing = B_TRUE;
44505450Sbrendan 	(void) zio_wait(pio);
44518582SBrendan.Gregg@Sun.COM 	dev->l2ad_writing = B_FALSE;
44528582SBrendan.Gregg@Sun.COM 
44538582SBrendan.Gregg@Sun.COM 	return (write_sz);
44545450Sbrendan }
44555450Sbrendan 
44565450Sbrendan /*
44575450Sbrendan  * This thread feeds the L2ARC at regular intervals.  This is the beating
44585450Sbrendan  * heart of the L2ARC.
44595450Sbrendan  */
44605450Sbrendan static void
44615450Sbrendan l2arc_feed_thread(void)
44625450Sbrendan {
44635450Sbrendan 	callb_cpr_t cpr;
44645450Sbrendan 	l2arc_dev_t *dev;
44655450Sbrendan 	spa_t *spa;
44668582SBrendan.Gregg@Sun.COM 	uint64_t size, wrote;
44678582SBrendan.Gregg@Sun.COM 	clock_t begin, next = lbolt;
44685450Sbrendan 
44695450Sbrendan 	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
44705450Sbrendan 
44715450Sbrendan 	mutex_enter(&l2arc_feed_thr_lock);
44725450Sbrendan 
44735450Sbrendan 	while (l2arc_thread_exit == 0) {
44745450Sbrendan 		CALLB_CPR_SAFE_BEGIN(&cpr);
44756987Sbrendan 		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
44768582SBrendan.Gregg@Sun.COM 		    next);
44776987Sbrendan 		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
44788582SBrendan.Gregg@Sun.COM 		next = lbolt + hz;
44796987Sbrendan 
44806987Sbrendan 		/*
44816987Sbrendan 		 * Quick check for L2ARC devices.
44826987Sbrendan 		 */
44836987Sbrendan 		mutex_enter(&l2arc_dev_mtx);
44846987Sbrendan 		if (l2arc_ndev == 0) {
44856987Sbrendan 			mutex_exit(&l2arc_dev_mtx);
44866987Sbrendan 			continue;
44875450Sbrendan 		}
44886987Sbrendan 		mutex_exit(&l2arc_dev_mtx);
44898582SBrendan.Gregg@Sun.COM 		begin = lbolt;
44906643Seschrock 
44915450Sbrendan 		/*
44926643Seschrock 		 * This selects the next l2arc device to write to, and in
44936643Seschrock 		 * doing so the next spa to feed from: dev->l2ad_spa.   This
44946987Sbrendan 		 * will return NULL if there are now no l2arc devices or if
44956987Sbrendan 		 * they are all faulted.
44966987Sbrendan 		 *
44976987Sbrendan 		 * If a device is returned, its spa's config lock is also
44986987Sbrendan 		 * held to prevent device removal.  l2arc_dev_get_next()
44996987Sbrendan 		 * will grab and release l2arc_dev_mtx.
45005450Sbrendan 		 */
45016987Sbrendan 		if ((dev = l2arc_dev_get_next()) == NULL)
45025450Sbrendan 			continue;
45036987Sbrendan 
45046987Sbrendan 		spa = dev->l2ad_spa;
45056987Sbrendan 		ASSERT(spa != NULL);
45065450Sbrendan 
45075450Sbrendan 		/*
45085450Sbrendan 		 * Avoid contributing to memory pressure.
45095450Sbrendan 		 */
45105450Sbrendan 		if (arc_reclaim_needed()) {
45115450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
45127754SJeff.Bonwick@Sun.COM 			spa_config_exit(spa, SCL_L2ARC, dev);
45135450Sbrendan 			continue;
45145450Sbrendan 		}
45155450Sbrendan 
45165450Sbrendan 		ARCSTAT_BUMP(arcstat_l2_feeds);
45175450Sbrendan 
45188582SBrendan.Gregg@Sun.COM 		size = l2arc_write_size(dev);
45196987Sbrendan 
45205450Sbrendan 		/*
45215450Sbrendan 		 * Evict L2ARC buffers that will be overwritten.
45225450Sbrendan 		 */
45236987Sbrendan 		l2arc_evict(dev, size, B_FALSE);
45245450Sbrendan 
45255450Sbrendan 		/*
45265450Sbrendan 		 * Write ARC buffers.
45275450Sbrendan 		 */
45288582SBrendan.Gregg@Sun.COM 		wrote = l2arc_write_buffers(spa, dev, size);
45298582SBrendan.Gregg@Sun.COM 
45308582SBrendan.Gregg@Sun.COM 		/*
45318582SBrendan.Gregg@Sun.COM 		 * Calculate interval between writes.
45328582SBrendan.Gregg@Sun.COM 		 */
45338582SBrendan.Gregg@Sun.COM 		next = l2arc_write_interval(begin, size, wrote);
45347754SJeff.Bonwick@Sun.COM 		spa_config_exit(spa, SCL_L2ARC, dev);
45355450Sbrendan 	}
45365450Sbrendan 
45375450Sbrendan 	l2arc_thread_exit = 0;
45385450Sbrendan 	cv_broadcast(&l2arc_feed_thr_cv);
45395450Sbrendan 	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
45405450Sbrendan 	thread_exit();
45415450Sbrendan }
45425450Sbrendan 
45436643Seschrock boolean_t
45446643Seschrock l2arc_vdev_present(vdev_t *vd)
45456643Seschrock {
45466643Seschrock 	l2arc_dev_t *dev;
45476643Seschrock 
45486643Seschrock 	mutex_enter(&l2arc_dev_mtx);
45496643Seschrock 	for (dev = list_head(l2arc_dev_list); dev != NULL;
45506643Seschrock 	    dev = list_next(l2arc_dev_list, dev)) {
45516643Seschrock 		if (dev->l2ad_vdev == vd)
45526643Seschrock 			break;
45536643Seschrock 	}
45546643Seschrock 	mutex_exit(&l2arc_dev_mtx);
45556643Seschrock 
45566643Seschrock 	return (dev != NULL);
45576643Seschrock }
45586643Seschrock 
45595450Sbrendan /*
45605450Sbrendan  * Add a vdev for use by the L2ARC.  By this point the spa has already
45615450Sbrendan  * validated the vdev and opened it.
45625450Sbrendan  */
45635450Sbrendan void
45649816SGeorge.Wilson@Sun.COM l2arc_add_vdev(spa_t *spa, vdev_t *vd)
45655450Sbrendan {
45665450Sbrendan 	l2arc_dev_t *adddev;
45675450Sbrendan 
45686643Seschrock 	ASSERT(!l2arc_vdev_present(vd));
45696643Seschrock 
45705450Sbrendan 	/*
45715450Sbrendan 	 * Create a new l2arc device entry.
45725450Sbrendan 	 */
45735450Sbrendan 	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
45745450Sbrendan 	adddev->l2ad_spa = spa;
45755450Sbrendan 	adddev->l2ad_vdev = vd;
45765450Sbrendan 	adddev->l2ad_write = l2arc_write_max;
45776987Sbrendan 	adddev->l2ad_boost = l2arc_write_boost;
45789816SGeorge.Wilson@Sun.COM 	adddev->l2ad_start = VDEV_LABEL_START_SIZE;
45799816SGeorge.Wilson@Sun.COM 	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
45805450Sbrendan 	adddev->l2ad_hand = adddev->l2ad_start;
45815450Sbrendan 	adddev->l2ad_evict = adddev->l2ad_start;
45825450Sbrendan 	adddev->l2ad_first = B_TRUE;
45838582SBrendan.Gregg@Sun.COM 	adddev->l2ad_writing = B_FALSE;
45845450Sbrendan 	ASSERT3U(adddev->l2ad_write, >, 0);
45855450Sbrendan 
45865450Sbrendan 	/*
45875450Sbrendan 	 * This is a list of all ARC buffers that are still valid on the
45885450Sbrendan 	 * device.
45895450Sbrendan 	 */
45905450Sbrendan 	adddev->l2ad_buflist = kmem_zalloc(sizeof (list_t), KM_SLEEP);
45915450Sbrendan 	list_create(adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
45925450Sbrendan 	    offsetof(arc_buf_hdr_t, b_l2node));
45935450Sbrendan 
45945450Sbrendan 	spa_l2cache_space_update(vd, adddev->l2ad_end - adddev->l2ad_hand, 0);
45955450Sbrendan 
45965450Sbrendan 	/*
45975450Sbrendan 	 * Add device to global list
45985450Sbrendan 	 */
45995450Sbrendan 	mutex_enter(&l2arc_dev_mtx);
46005450Sbrendan 	list_insert_head(l2arc_dev_list, adddev);
46015450Sbrendan 	atomic_inc_64(&l2arc_ndev);
46025450Sbrendan 	mutex_exit(&l2arc_dev_mtx);
46035450Sbrendan }
46045450Sbrendan 
46055450Sbrendan /*
46065450Sbrendan  * Remove a vdev from the L2ARC.
46075450Sbrendan  */
46085450Sbrendan void
46095450Sbrendan l2arc_remove_vdev(vdev_t *vd)
46105450Sbrendan {
46115450Sbrendan 	l2arc_dev_t *dev, *nextdev, *remdev = NULL;
46125450Sbrendan 
46135450Sbrendan 	/*
46145450Sbrendan 	 * Find the device by vdev
46155450Sbrendan 	 */
46165450Sbrendan 	mutex_enter(&l2arc_dev_mtx);
46175450Sbrendan 	for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
46185450Sbrendan 		nextdev = list_next(l2arc_dev_list, dev);
46195450Sbrendan 		if (vd == dev->l2ad_vdev) {
46205450Sbrendan 			remdev = dev;
46215450Sbrendan 			break;
46225450Sbrendan 		}
46235450Sbrendan 	}
46245450Sbrendan 	ASSERT(remdev != NULL);
46255450Sbrendan 
46265450Sbrendan 	/*
46275450Sbrendan 	 * Remove device from global list
46285450Sbrendan 	 */
46295450Sbrendan 	list_remove(l2arc_dev_list, remdev);
46305450Sbrendan 	l2arc_dev_last = NULL;		/* may have been invalidated */
46316987Sbrendan 	atomic_dec_64(&l2arc_ndev);
46326987Sbrendan 	mutex_exit(&l2arc_dev_mtx);
46335450Sbrendan 
46345450Sbrendan 	/*
46355450Sbrendan 	 * Clear all buflists and ARC references.  L2ARC device flush.
46365450Sbrendan 	 */
46375450Sbrendan 	l2arc_evict(remdev, 0, B_TRUE);
46385450Sbrendan 	list_destroy(remdev->l2ad_buflist);
46395450Sbrendan 	kmem_free(remdev->l2ad_buflist, sizeof (list_t));
46405450Sbrendan 	kmem_free(remdev, sizeof (l2arc_dev_t));
46415450Sbrendan }
46425450Sbrendan 
46435450Sbrendan void
46447754SJeff.Bonwick@Sun.COM l2arc_init(void)
46455450Sbrendan {
46465450Sbrendan 	l2arc_thread_exit = 0;
46475450Sbrendan 	l2arc_ndev = 0;
46485450Sbrendan 	l2arc_writes_sent = 0;
46495450Sbrendan 	l2arc_writes_done = 0;
46505450Sbrendan 
46515450Sbrendan 	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
46525450Sbrendan 	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
46535450Sbrendan 	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
46545450Sbrendan 	mutex_init(&l2arc_buflist_mtx, NULL, MUTEX_DEFAULT, NULL);
46555450Sbrendan 	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
46565450Sbrendan 
46575450Sbrendan 	l2arc_dev_list = &L2ARC_dev_list;
46585450Sbrendan 	l2arc_free_on_write = &L2ARC_free_on_write;
46595450Sbrendan 	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
46605450Sbrendan 	    offsetof(l2arc_dev_t, l2ad_node));
46615450Sbrendan 	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
46625450Sbrendan 	    offsetof(l2arc_data_free_t, l2df_list_node));
46635450Sbrendan }
46645450Sbrendan 
46655450Sbrendan void
46667754SJeff.Bonwick@Sun.COM l2arc_fini(void)
46675450Sbrendan {
46686987Sbrendan 	/*
46696987Sbrendan 	 * This is called from dmu_fini(), which is called from spa_fini();
46706987Sbrendan 	 * Because of this, we can assume that all l2arc devices have
46716987Sbrendan 	 * already been removed when the pools themselves were removed.
46726987Sbrendan 	 */
46736987Sbrendan 
46746987Sbrendan 	l2arc_do_free_on_write();
46756987Sbrendan 
46765450Sbrendan 	mutex_destroy(&l2arc_feed_thr_lock);
46775450Sbrendan 	cv_destroy(&l2arc_feed_thr_cv);
46785450Sbrendan 	mutex_destroy(&l2arc_dev_mtx);
46795450Sbrendan 	mutex_destroy(&l2arc_buflist_mtx);
46805450Sbrendan 	mutex_destroy(&l2arc_free_on_write_mtx);
46815450Sbrendan 
46825450Sbrendan 	list_destroy(l2arc_dev_list);
46835450Sbrendan 	list_destroy(l2arc_free_on_write);
46845450Sbrendan }
46857754SJeff.Bonwick@Sun.COM 
46867754SJeff.Bonwick@Sun.COM void
46877754SJeff.Bonwick@Sun.COM l2arc_start(void)
46887754SJeff.Bonwick@Sun.COM {
46898241SJeff.Bonwick@Sun.COM 	if (!(spa_mode_global & FWRITE))
46907754SJeff.Bonwick@Sun.COM 		return;
46917754SJeff.Bonwick@Sun.COM 
46927754SJeff.Bonwick@Sun.COM 	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
46937754SJeff.Bonwick@Sun.COM 	    TS_RUN, minclsyspri);
46947754SJeff.Bonwick@Sun.COM }
46957754SJeff.Bonwick@Sun.COM 
46967754SJeff.Bonwick@Sun.COM void
46977754SJeff.Bonwick@Sun.COM l2arc_stop(void)
46987754SJeff.Bonwick@Sun.COM {
46998241SJeff.Bonwick@Sun.COM 	if (!(spa_mode_global & FWRITE))
47007754SJeff.Bonwick@Sun.COM 		return;
47017754SJeff.Bonwick@Sun.COM 
47027754SJeff.Bonwick@Sun.COM 	mutex_enter(&l2arc_feed_thr_lock);
47037754SJeff.Bonwick@Sun.COM 	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
47047754SJeff.Bonwick@Sun.COM 	l2arc_thread_exit = 1;
47057754SJeff.Bonwick@Sun.COM 	while (l2arc_thread_exit != 0)
47067754SJeff.Bonwick@Sun.COM 		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
47077754SJeff.Bonwick@Sun.COM 	mutex_exit(&l2arc_feed_thr_lock);
47087754SJeff.Bonwick@Sun.COM }
4709