xref: /onnv-gate/usr/src/uts/common/fs/zfs/arc.c (revision 9412)
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>
127789Sahrens #ifdef _KERNEL
128789Sahrens #include <sys/vmsystm.h>
129789Sahrens #include <vm/anon.h>
130789Sahrens #include <sys/fs/swapnode.h>
1311484Sek110237 #include <sys/dnlc.h>
132789Sahrens #endif
133789Sahrens #include <sys/callb.h>
1343403Sbmc #include <sys/kstat.h>
135789Sahrens 
136789Sahrens static kmutex_t		arc_reclaim_thr_lock;
137789Sahrens static kcondvar_t	arc_reclaim_thr_cv;	/* used to signal reclaim thr */
138789Sahrens static uint8_t		arc_thread_exit;
139789Sahrens 
1406245Smaybee extern int zfs_write_limit_shift;
1416245Smaybee extern uint64_t zfs_write_limit_max;
1427468SMark.Maybee@Sun.COM extern kmutex_t zfs_write_limit_lock;
1436245Smaybee 
1441484Sek110237 #define	ARC_REDUCE_DNLC_PERCENT	3
1451484Sek110237 uint_t arc_reduce_dnlc_percent = ARC_REDUCE_DNLC_PERCENT;
1461484Sek110237 
147789Sahrens typedef enum arc_reclaim_strategy {
148789Sahrens 	ARC_RECLAIM_AGGR,		/* Aggressive reclaim strategy */
149789Sahrens 	ARC_RECLAIM_CONS		/* Conservative reclaim strategy */
150789Sahrens } arc_reclaim_strategy_t;
151789Sahrens 
152789Sahrens /* number of seconds before growing cache again */
153789Sahrens static int		arc_grow_retry = 60;
154789Sahrens 
1558582SBrendan.Gregg@Sun.COM /* shift of arc_c for calculating both min and max arc_p */
1568582SBrendan.Gregg@Sun.COM static int		arc_p_min_shift = 4;
1578582SBrendan.Gregg@Sun.COM 
1588582SBrendan.Gregg@Sun.COM /* log2(fraction of arc to reclaim) */
1598582SBrendan.Gregg@Sun.COM static int		arc_shrink_shift = 5;
1608582SBrendan.Gregg@Sun.COM 
1612391Smaybee /*
1622638Sperrin  * minimum lifespan of a prefetch block in clock ticks
1632638Sperrin  * (initialized in arc_init())
1642391Smaybee  */
1652638Sperrin static int		arc_min_prefetch_lifespan;
1662391Smaybee 
167789Sahrens static int arc_dead;
168789Sahrens 
169789Sahrens /*
1706987Sbrendan  * The arc has filled available memory and has now warmed up.
1716987Sbrendan  */
1726987Sbrendan static boolean_t arc_warm;
1736987Sbrendan 
1746987Sbrendan /*
1752885Sahrens  * These tunables are for performance analysis.
1762885Sahrens  */
1772885Sahrens uint64_t zfs_arc_max;
1782885Sahrens uint64_t zfs_arc_min;
1794645Sek110237 uint64_t zfs_arc_meta_limit = 0;
1807046Sahrens int zfs_mdcomp_disable = 0;
1818582SBrendan.Gregg@Sun.COM int zfs_arc_grow_retry = 0;
1828582SBrendan.Gregg@Sun.COM int zfs_arc_shrink_shift = 0;
1838582SBrendan.Gregg@Sun.COM int zfs_arc_p_min_shift = 0;
1842885Sahrens 
1852885Sahrens /*
1865450Sbrendan  * Note that buffers can be in one of 6 states:
187789Sahrens  *	ARC_anon	- anonymous (discussed below)
1881544Seschrock  *	ARC_mru		- recently used, currently cached
1891544Seschrock  *	ARC_mru_ghost	- recentely used, no longer in cache
1901544Seschrock  *	ARC_mfu		- frequently used, currently cached
1911544Seschrock  *	ARC_mfu_ghost	- frequently used, no longer in cache
1925450Sbrendan  *	ARC_l2c_only	- exists in L2ARC but not other states
1934309Smaybee  * When there are no active references to the buffer, they are
1944309Smaybee  * are linked onto a list in one of these arc states.  These are
1954309Smaybee  * the only buffers that can be evicted or deleted.  Within each
1964309Smaybee  * state there are multiple lists, one for meta-data and one for
1974309Smaybee  * non-meta-data.  Meta-data (indirect blocks, blocks of dnodes,
1984309Smaybee  * etc.) is tracked separately so that it can be managed more
1995450Sbrendan  * explicitly: favored over data, limited explicitly.
200789Sahrens  *
201789Sahrens  * Anonymous buffers are buffers that are not associated with
202789Sahrens  * a DVA.  These are buffers that hold dirty block copies
203789Sahrens  * before they are written to stable storage.  By definition,
2041544Seschrock  * they are "ref'd" and are considered part of arc_mru
205789Sahrens  * that cannot be freed.  Generally, they will aquire a DVA
2061544Seschrock  * as they are written and migrate onto the arc_mru list.
2075450Sbrendan  *
2085450Sbrendan  * The ARC_l2c_only state is for buffers that are in the second
2095450Sbrendan  * level ARC but no longer in any of the ARC_m* lists.  The second
2105450Sbrendan  * level ARC itself may also contain buffers that are in any of
2115450Sbrendan  * the ARC_m* states - meaning that a buffer can exist in two
2125450Sbrendan  * places.  The reason for the ARC_l2c_only state is to keep the
2135450Sbrendan  * buffer header in the hash table, so that reads that hit the
2145450Sbrendan  * second level ARC benefit from these fast lookups.
215789Sahrens  */
216789Sahrens 
217789Sahrens typedef struct arc_state {
2184309Smaybee 	list_t	arcs_list[ARC_BUFC_NUMTYPES];	/* list of evictable buffers */
2194309Smaybee 	uint64_t arcs_lsize[ARC_BUFC_NUMTYPES];	/* amount of evictable data */
2204309Smaybee 	uint64_t arcs_size;	/* total amount of data in this state */
2213403Sbmc 	kmutex_t arcs_mtx;
222789Sahrens } arc_state_t;
223789Sahrens 
2245450Sbrendan /* The 6 states: */
225789Sahrens static arc_state_t ARC_anon;
2261544Seschrock static arc_state_t ARC_mru;
2271544Seschrock static arc_state_t ARC_mru_ghost;
2281544Seschrock static arc_state_t ARC_mfu;
2291544Seschrock static arc_state_t ARC_mfu_ghost;
2305450Sbrendan static arc_state_t ARC_l2c_only;
231789Sahrens 
2323403Sbmc typedef struct arc_stats {
2333403Sbmc 	kstat_named_t arcstat_hits;
2343403Sbmc 	kstat_named_t arcstat_misses;
2353403Sbmc 	kstat_named_t arcstat_demand_data_hits;
2363403Sbmc 	kstat_named_t arcstat_demand_data_misses;
2373403Sbmc 	kstat_named_t arcstat_demand_metadata_hits;
2383403Sbmc 	kstat_named_t arcstat_demand_metadata_misses;
2393403Sbmc 	kstat_named_t arcstat_prefetch_data_hits;
2403403Sbmc 	kstat_named_t arcstat_prefetch_data_misses;
2413403Sbmc 	kstat_named_t arcstat_prefetch_metadata_hits;
2423403Sbmc 	kstat_named_t arcstat_prefetch_metadata_misses;
2433403Sbmc 	kstat_named_t arcstat_mru_hits;
2443403Sbmc 	kstat_named_t arcstat_mru_ghost_hits;
2453403Sbmc 	kstat_named_t arcstat_mfu_hits;
2463403Sbmc 	kstat_named_t arcstat_mfu_ghost_hits;
2473403Sbmc 	kstat_named_t arcstat_deleted;
2483403Sbmc 	kstat_named_t arcstat_recycle_miss;
2493403Sbmc 	kstat_named_t arcstat_mutex_miss;
2503403Sbmc 	kstat_named_t arcstat_evict_skip;
2513403Sbmc 	kstat_named_t arcstat_hash_elements;
2523403Sbmc 	kstat_named_t arcstat_hash_elements_max;
2533403Sbmc 	kstat_named_t arcstat_hash_collisions;
2543403Sbmc 	kstat_named_t arcstat_hash_chains;
2553403Sbmc 	kstat_named_t arcstat_hash_chain_max;
2563403Sbmc 	kstat_named_t arcstat_p;
2573403Sbmc 	kstat_named_t arcstat_c;
2583403Sbmc 	kstat_named_t arcstat_c_min;
2593403Sbmc 	kstat_named_t arcstat_c_max;
2603403Sbmc 	kstat_named_t arcstat_size;
2615450Sbrendan 	kstat_named_t arcstat_hdr_size;
2628582SBrendan.Gregg@Sun.COM 	kstat_named_t arcstat_data_size;
2638582SBrendan.Gregg@Sun.COM 	kstat_named_t arcstat_other_size;
2645450Sbrendan 	kstat_named_t arcstat_l2_hits;
2655450Sbrendan 	kstat_named_t arcstat_l2_misses;
2665450Sbrendan 	kstat_named_t arcstat_l2_feeds;
2675450Sbrendan 	kstat_named_t arcstat_l2_rw_clash;
2688582SBrendan.Gregg@Sun.COM 	kstat_named_t arcstat_l2_read_bytes;
2698582SBrendan.Gregg@Sun.COM 	kstat_named_t arcstat_l2_write_bytes;
2705450Sbrendan 	kstat_named_t arcstat_l2_writes_sent;
2715450Sbrendan 	kstat_named_t arcstat_l2_writes_done;
2725450Sbrendan 	kstat_named_t arcstat_l2_writes_error;
2735450Sbrendan 	kstat_named_t arcstat_l2_writes_hdr_miss;
2745450Sbrendan 	kstat_named_t arcstat_l2_evict_lock_retry;
2755450Sbrendan 	kstat_named_t arcstat_l2_evict_reading;
2765450Sbrendan 	kstat_named_t arcstat_l2_free_on_write;
2775450Sbrendan 	kstat_named_t arcstat_l2_abort_lowmem;
2785450Sbrendan 	kstat_named_t arcstat_l2_cksum_bad;
2795450Sbrendan 	kstat_named_t arcstat_l2_io_error;
2805450Sbrendan 	kstat_named_t arcstat_l2_size;
2815450Sbrendan 	kstat_named_t arcstat_l2_hdr_size;
2826245Smaybee 	kstat_named_t arcstat_memory_throttle_count;
2833403Sbmc } arc_stats_t;
2843403Sbmc 
2853403Sbmc static arc_stats_t arc_stats = {
2863403Sbmc 	{ "hits",			KSTAT_DATA_UINT64 },
2873403Sbmc 	{ "misses",			KSTAT_DATA_UINT64 },
2883403Sbmc 	{ "demand_data_hits",		KSTAT_DATA_UINT64 },
2893403Sbmc 	{ "demand_data_misses",		KSTAT_DATA_UINT64 },
2903403Sbmc 	{ "demand_metadata_hits",	KSTAT_DATA_UINT64 },
2913403Sbmc 	{ "demand_metadata_misses",	KSTAT_DATA_UINT64 },
2923403Sbmc 	{ "prefetch_data_hits",		KSTAT_DATA_UINT64 },
2933403Sbmc 	{ "prefetch_data_misses",	KSTAT_DATA_UINT64 },
2943403Sbmc 	{ "prefetch_metadata_hits",	KSTAT_DATA_UINT64 },
2953403Sbmc 	{ "prefetch_metadata_misses",	KSTAT_DATA_UINT64 },
2963403Sbmc 	{ "mru_hits",			KSTAT_DATA_UINT64 },
2973403Sbmc 	{ "mru_ghost_hits",		KSTAT_DATA_UINT64 },
2983403Sbmc 	{ "mfu_hits",			KSTAT_DATA_UINT64 },
2993403Sbmc 	{ "mfu_ghost_hits",		KSTAT_DATA_UINT64 },
3003403Sbmc 	{ "deleted",			KSTAT_DATA_UINT64 },
3013403Sbmc 	{ "recycle_miss",		KSTAT_DATA_UINT64 },
3023403Sbmc 	{ "mutex_miss",			KSTAT_DATA_UINT64 },
3033403Sbmc 	{ "evict_skip",			KSTAT_DATA_UINT64 },
3043403Sbmc 	{ "hash_elements",		KSTAT_DATA_UINT64 },
3053403Sbmc 	{ "hash_elements_max",		KSTAT_DATA_UINT64 },
3063403Sbmc 	{ "hash_collisions",		KSTAT_DATA_UINT64 },
3073403Sbmc 	{ "hash_chains",		KSTAT_DATA_UINT64 },
3083403Sbmc 	{ "hash_chain_max",		KSTAT_DATA_UINT64 },
3093403Sbmc 	{ "p",				KSTAT_DATA_UINT64 },
3103403Sbmc 	{ "c",				KSTAT_DATA_UINT64 },
3113403Sbmc 	{ "c_min",			KSTAT_DATA_UINT64 },
3123403Sbmc 	{ "c_max",			KSTAT_DATA_UINT64 },
3135450Sbrendan 	{ "size",			KSTAT_DATA_UINT64 },
3145450Sbrendan 	{ "hdr_size",			KSTAT_DATA_UINT64 },
3158582SBrendan.Gregg@Sun.COM 	{ "data_size",			KSTAT_DATA_UINT64 },
3168582SBrendan.Gregg@Sun.COM 	{ "other_size",			KSTAT_DATA_UINT64 },
3175450Sbrendan 	{ "l2_hits",			KSTAT_DATA_UINT64 },
3185450Sbrendan 	{ "l2_misses",			KSTAT_DATA_UINT64 },
3195450Sbrendan 	{ "l2_feeds",			KSTAT_DATA_UINT64 },
3205450Sbrendan 	{ "l2_rw_clash",		KSTAT_DATA_UINT64 },
3218582SBrendan.Gregg@Sun.COM 	{ "l2_read_bytes",		KSTAT_DATA_UINT64 },
3228582SBrendan.Gregg@Sun.COM 	{ "l2_write_bytes",		KSTAT_DATA_UINT64 },
3235450Sbrendan 	{ "l2_writes_sent",		KSTAT_DATA_UINT64 },
3245450Sbrendan 	{ "l2_writes_done",		KSTAT_DATA_UINT64 },
3255450Sbrendan 	{ "l2_writes_error",		KSTAT_DATA_UINT64 },
3265450Sbrendan 	{ "l2_writes_hdr_miss",		KSTAT_DATA_UINT64 },
3275450Sbrendan 	{ "l2_evict_lock_retry",	KSTAT_DATA_UINT64 },
3285450Sbrendan 	{ "l2_evict_reading",		KSTAT_DATA_UINT64 },
3295450Sbrendan 	{ "l2_free_on_write",		KSTAT_DATA_UINT64 },
3305450Sbrendan 	{ "l2_abort_lowmem",		KSTAT_DATA_UINT64 },
3315450Sbrendan 	{ "l2_cksum_bad",		KSTAT_DATA_UINT64 },
3325450Sbrendan 	{ "l2_io_error",		KSTAT_DATA_UINT64 },
3335450Sbrendan 	{ "l2_size",			KSTAT_DATA_UINT64 },
3346245Smaybee 	{ "l2_hdr_size",		KSTAT_DATA_UINT64 },
3356245Smaybee 	{ "memory_throttle_count",	KSTAT_DATA_UINT64 }
3363403Sbmc };
337789Sahrens 
3383403Sbmc #define	ARCSTAT(stat)	(arc_stats.stat.value.ui64)
3393403Sbmc 
3403403Sbmc #define	ARCSTAT_INCR(stat, val) \
3413403Sbmc 	atomic_add_64(&arc_stats.stat.value.ui64, (val));
3423403Sbmc 
3433403Sbmc #define	ARCSTAT_BUMP(stat) 	ARCSTAT_INCR(stat, 1)
3443403Sbmc #define	ARCSTAT_BUMPDOWN(stat)	ARCSTAT_INCR(stat, -1)
3453403Sbmc 
3463403Sbmc #define	ARCSTAT_MAX(stat, val) {					\
3473403Sbmc 	uint64_t m;							\
3483403Sbmc 	while ((val) > (m = arc_stats.stat.value.ui64) &&		\
3493403Sbmc 	    (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val))))	\
3503403Sbmc 		continue;						\
3513403Sbmc }
3523403Sbmc 
3533403Sbmc #define	ARCSTAT_MAXSTAT(stat) \
3543403Sbmc 	ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
355789Sahrens 
3563403Sbmc /*
3573403Sbmc  * We define a macro to allow ARC hits/misses to be easily broken down by
3583403Sbmc  * two separate conditions, giving a total of four different subtypes for
3593403Sbmc  * each of hits and misses (so eight statistics total).
3603403Sbmc  */
3613403Sbmc #define	ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
3623403Sbmc 	if (cond1) {							\
3633403Sbmc 		if (cond2) {						\
3643403Sbmc 			ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
3653403Sbmc 		} else {						\
3663403Sbmc 			ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
3673403Sbmc 		}							\
3683403Sbmc 	} else {							\
3693403Sbmc 		if (cond2) {						\
3703403Sbmc 			ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
3713403Sbmc 		} else {						\
3723403Sbmc 			ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
3733403Sbmc 		}							\
3743403Sbmc 	}
375789Sahrens 
3763403Sbmc kstat_t			*arc_ksp;
3773403Sbmc static arc_state_t 	*arc_anon;
3783403Sbmc static arc_state_t	*arc_mru;
3793403Sbmc static arc_state_t	*arc_mru_ghost;
3803403Sbmc static arc_state_t	*arc_mfu;
3813403Sbmc static arc_state_t	*arc_mfu_ghost;
3825450Sbrendan static arc_state_t	*arc_l2c_only;
3833403Sbmc 
3843403Sbmc /*
3853403Sbmc  * There are several ARC variables that are critical to export as kstats --
3863403Sbmc  * but we don't want to have to grovel around in the kstat whenever we wish to
3873403Sbmc  * manipulate them.  For these variables, we therefore define them to be in
3883403Sbmc  * terms of the statistic variable.  This assures that we are not introducing
3893403Sbmc  * the possibility of inconsistency by having shadow copies of the variables,
3903403Sbmc  * while still allowing the code to be readable.
3913403Sbmc  */
3923403Sbmc #define	arc_size	ARCSTAT(arcstat_size)	/* actual total arc size */
3933403Sbmc #define	arc_p		ARCSTAT(arcstat_p)	/* target size of MRU */
3943403Sbmc #define	arc_c		ARCSTAT(arcstat_c)	/* target size of cache */
3953403Sbmc #define	arc_c_min	ARCSTAT(arcstat_c_min)	/* min target cache size */
3963403Sbmc #define	arc_c_max	ARCSTAT(arcstat_c_max)	/* max target cache size */
3973403Sbmc 
3983403Sbmc static int		arc_no_grow;	/* Don't try to grow cache size */
3993403Sbmc static uint64_t		arc_tempreserve;
400*9412SAleksandr.Guzovskiy@Sun.COM static uint64_t		arc_loaned_bytes;
4014309Smaybee static uint64_t		arc_meta_used;
4024309Smaybee static uint64_t		arc_meta_limit;
4034309Smaybee static uint64_t		arc_meta_max = 0;
404789Sahrens 
4055450Sbrendan typedef struct l2arc_buf_hdr l2arc_buf_hdr_t;
4065450Sbrendan 
407789Sahrens typedef struct arc_callback arc_callback_t;
408789Sahrens 
409789Sahrens struct arc_callback {
4103547Smaybee 	void			*acb_private;
411789Sahrens 	arc_done_func_t		*acb_done;
412789Sahrens 	arc_buf_t		*acb_buf;
413789Sahrens 	zio_t			*acb_zio_dummy;
414789Sahrens 	arc_callback_t		*acb_next;
415789Sahrens };
416789Sahrens 
4173547Smaybee typedef struct arc_write_callback arc_write_callback_t;
4183547Smaybee 
4193547Smaybee struct arc_write_callback {
4203547Smaybee 	void		*awcb_private;
4213547Smaybee 	arc_done_func_t	*awcb_ready;
4223547Smaybee 	arc_done_func_t	*awcb_done;
4233547Smaybee 	arc_buf_t	*awcb_buf;
4243547Smaybee };
4253547Smaybee 
426789Sahrens struct arc_buf_hdr {
427789Sahrens 	/* protected by hash lock */
428789Sahrens 	dva_t			b_dva;
429789Sahrens 	uint64_t		b_birth;
430789Sahrens 	uint64_t		b_cksum0;
431789Sahrens 
4323093Sahrens 	kmutex_t		b_freeze_lock;
4333093Sahrens 	zio_cksum_t		*b_freeze_cksum;
4343093Sahrens 
435789Sahrens 	arc_buf_hdr_t		*b_hash_next;
436789Sahrens 	arc_buf_t		*b_buf;
437789Sahrens 	uint32_t		b_flags;
4381544Seschrock 	uint32_t		b_datacnt;
439789Sahrens 
4403290Sjohansen 	arc_callback_t		*b_acb;
441789Sahrens 	kcondvar_t		b_cv;
4423290Sjohansen 
4433290Sjohansen 	/* immutable */
4443290Sjohansen 	arc_buf_contents_t	b_type;
4453290Sjohansen 	uint64_t		b_size;
4468636SMark.Maybee@Sun.COM 	uint64_t		b_spa;
447789Sahrens 
448789Sahrens 	/* protected by arc state mutex */
449789Sahrens 	arc_state_t		*b_state;
450789Sahrens 	list_node_t		b_arc_node;
451789Sahrens 
452789Sahrens 	/* updated atomically */
453789Sahrens 	clock_t			b_arc_access;
454789Sahrens 
455789Sahrens 	/* self protecting */
456789Sahrens 	refcount_t		b_refcnt;
4575450Sbrendan 
4585450Sbrendan 	l2arc_buf_hdr_t		*b_l2hdr;
4595450Sbrendan 	list_node_t		b_l2node;
460789Sahrens };
461789Sahrens 
4621544Seschrock static arc_buf_t *arc_eviction_list;
4631544Seschrock static kmutex_t arc_eviction_mtx;
4642887Smaybee static arc_buf_hdr_t arc_eviction_hdr;
4652688Smaybee static void arc_get_data_buf(arc_buf_t *buf);
4662688Smaybee static void arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock);
4674309Smaybee static int arc_evict_needed(arc_buf_contents_t type);
4688636SMark.Maybee@Sun.COM static void arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes);
4691544Seschrock 
4701544Seschrock #define	GHOST_STATE(state)	\
4715450Sbrendan 	((state) == arc_mru_ghost || (state) == arc_mfu_ghost ||	\
4725450Sbrendan 	(state) == arc_l2c_only)
4731544Seschrock 
474789Sahrens /*
475789Sahrens  * Private ARC flags.  These flags are private ARC only flags that will show up
476789Sahrens  * in b_flags in the arc_hdr_buf_t.  Some flags are publicly declared, and can
477789Sahrens  * be passed in as arc_flags in things like arc_read.  However, these flags
478789Sahrens  * should never be passed and should only be set by ARC code.  When adding new
479789Sahrens  * public flags, make sure not to smash the private ones.
480789Sahrens  */
481789Sahrens 
4821544Seschrock #define	ARC_IN_HASH_TABLE	(1 << 9)	/* this buffer is hashed */
483789Sahrens #define	ARC_IO_IN_PROGRESS	(1 << 10)	/* I/O in progress for buf */
484789Sahrens #define	ARC_IO_ERROR		(1 << 11)	/* I/O failed for buf */
485789Sahrens #define	ARC_FREED_IN_READ	(1 << 12)	/* buf freed while in read */
4861544Seschrock #define	ARC_BUF_AVAILABLE	(1 << 13)	/* block not in active use */
4872391Smaybee #define	ARC_INDIRECT		(1 << 14)	/* this is an indirect block */
4885450Sbrendan #define	ARC_FREE_IN_PROGRESS	(1 << 15)	/* hdr about to be freed */
4897237Sek110237 #define	ARC_L2_WRITING		(1 << 16)	/* L2ARC write in progress */
4907237Sek110237 #define	ARC_L2_EVICTED		(1 << 17)	/* evicted during I/O */
4917237Sek110237 #define	ARC_L2_WRITE_HEAD	(1 << 18)	/* head of write list */
4927237Sek110237 #define	ARC_STORED		(1 << 19)	/* has been store()d to */
493789Sahrens 
4941544Seschrock #define	HDR_IN_HASH_TABLE(hdr)	((hdr)->b_flags & ARC_IN_HASH_TABLE)
495789Sahrens #define	HDR_IO_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_IO_IN_PROGRESS)
496789Sahrens #define	HDR_IO_ERROR(hdr)	((hdr)->b_flags & ARC_IO_ERROR)
4978582SBrendan.Gregg@Sun.COM #define	HDR_PREFETCH(hdr)	((hdr)->b_flags & ARC_PREFETCH)
498789Sahrens #define	HDR_FREED_IN_READ(hdr)	((hdr)->b_flags & ARC_FREED_IN_READ)
4991544Seschrock #define	HDR_BUF_AVAILABLE(hdr)	((hdr)->b_flags & ARC_BUF_AVAILABLE)
5005450Sbrendan #define	HDR_FREE_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_FREE_IN_PROGRESS)
5017237Sek110237 #define	HDR_L2CACHE(hdr)	((hdr)->b_flags & ARC_L2CACHE)
5026987Sbrendan #define	HDR_L2_READING(hdr)	((hdr)->b_flags & ARC_IO_IN_PROGRESS &&	\
5036987Sbrendan 				    (hdr)->b_l2hdr != NULL)
5045450Sbrendan #define	HDR_L2_WRITING(hdr)	((hdr)->b_flags & ARC_L2_WRITING)
5055450Sbrendan #define	HDR_L2_EVICTED(hdr)	((hdr)->b_flags & ARC_L2_EVICTED)
5065450Sbrendan #define	HDR_L2_WRITE_HEAD(hdr)	((hdr)->b_flags & ARC_L2_WRITE_HEAD)
507789Sahrens 
508789Sahrens /*
5096018Sbrendan  * Other sizes
5106018Sbrendan  */
5116018Sbrendan 
5126018Sbrendan #define	HDR_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
5136018Sbrendan #define	L2HDR_SIZE ((int64_t)sizeof (l2arc_buf_hdr_t))
5146018Sbrendan 
5156018Sbrendan /*
516789Sahrens  * Hash table routines
517789Sahrens  */
518789Sahrens 
519789Sahrens #define	HT_LOCK_PAD	64
520789Sahrens 
521789Sahrens struct ht_lock {
522789Sahrens 	kmutex_t	ht_lock;
523789Sahrens #ifdef _KERNEL
524789Sahrens 	unsigned char	pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
525789Sahrens #endif
526789Sahrens };
527789Sahrens 
528789Sahrens #define	BUF_LOCKS 256
529789Sahrens typedef struct buf_hash_table {
530789Sahrens 	uint64_t ht_mask;
531789Sahrens 	arc_buf_hdr_t **ht_table;
532789Sahrens 	struct ht_lock ht_locks[BUF_LOCKS];
533789Sahrens } buf_hash_table_t;
534789Sahrens 
535789Sahrens static buf_hash_table_t buf_hash_table;
536789Sahrens 
537789Sahrens #define	BUF_HASH_INDEX(spa, dva, birth) \
538789Sahrens 	(buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
539789Sahrens #define	BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
540789Sahrens #define	BUF_HASH_LOCK(idx)	(&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
541789Sahrens #define	HDR_LOCK(buf) \
542789Sahrens 	(BUF_HASH_LOCK(BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth)))
543789Sahrens 
544789Sahrens uint64_t zfs_crc64_table[256];
545789Sahrens 
5465450Sbrendan /*
5475450Sbrendan  * Level 2 ARC
5485450Sbrendan  */
5495450Sbrendan 
5505450Sbrendan #define	L2ARC_WRITE_SIZE	(8 * 1024 * 1024)	/* initial write max */
5518582SBrendan.Gregg@Sun.COM #define	L2ARC_HEADROOM		2		/* num of writes */
5528582SBrendan.Gregg@Sun.COM #define	L2ARC_FEED_SECS		1		/* caching interval secs */
5538582SBrendan.Gregg@Sun.COM #define	L2ARC_FEED_MIN_MS	200		/* min caching interval ms */
5545450Sbrendan 
5555450Sbrendan #define	l2arc_writes_sent	ARCSTAT(arcstat_l2_writes_sent)
5565450Sbrendan #define	l2arc_writes_done	ARCSTAT(arcstat_l2_writes_done)
5575450Sbrendan 
5585450Sbrendan /*
5595450Sbrendan  * L2ARC Performance Tunables
5605450Sbrendan  */
5615450Sbrendan uint64_t l2arc_write_max = L2ARC_WRITE_SIZE;	/* default max write size */
5626987Sbrendan uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE;	/* extra write during warmup */
5635450Sbrendan uint64_t l2arc_headroom = L2ARC_HEADROOM;	/* number of dev writes */
5645450Sbrendan uint64_t l2arc_feed_secs = L2ARC_FEED_SECS;	/* interval seconds */
5658582SBrendan.Gregg@Sun.COM uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS;	/* min interval milliseconds */
5665450Sbrendan boolean_t l2arc_noprefetch = B_TRUE;		/* don't cache prefetch bufs */
5678582SBrendan.Gregg@Sun.COM boolean_t l2arc_feed_again = B_TRUE;		/* turbo warmup */
5688582SBrendan.Gregg@Sun.COM boolean_t l2arc_norw = B_TRUE;			/* no reads during writes */
5695450Sbrendan 
5705450Sbrendan /*
5715450Sbrendan  * L2ARC Internals
5725450Sbrendan  */
5735450Sbrendan typedef struct l2arc_dev {
5745450Sbrendan 	vdev_t			*l2ad_vdev;	/* vdev */
5755450Sbrendan 	spa_t			*l2ad_spa;	/* spa */
5765450Sbrendan 	uint64_t		l2ad_hand;	/* next write location */
5775450Sbrendan 	uint64_t		l2ad_write;	/* desired write size, bytes */
5786987Sbrendan 	uint64_t		l2ad_boost;	/* warmup write boost, bytes */
5795450Sbrendan 	uint64_t		l2ad_start;	/* first addr on device */
5805450Sbrendan 	uint64_t		l2ad_end;	/* last addr on device */
5815450Sbrendan 	uint64_t		l2ad_evict;	/* last addr eviction reached */
5825450Sbrendan 	boolean_t		l2ad_first;	/* first sweep through */
5838582SBrendan.Gregg@Sun.COM 	boolean_t		l2ad_writing;	/* currently writing */
5845450Sbrendan 	list_t			*l2ad_buflist;	/* buffer list */
5855450Sbrendan 	list_node_t		l2ad_node;	/* device list node */
5865450Sbrendan } l2arc_dev_t;
5875450Sbrendan 
5885450Sbrendan static list_t L2ARC_dev_list;			/* device list */
5895450Sbrendan static list_t *l2arc_dev_list;			/* device list pointer */
5905450Sbrendan static kmutex_t l2arc_dev_mtx;			/* device list mutex */
5915450Sbrendan static l2arc_dev_t *l2arc_dev_last;		/* last device used */
5925450Sbrendan static kmutex_t l2arc_buflist_mtx;		/* mutex for all buflists */
5935450Sbrendan static list_t L2ARC_free_on_write;		/* free after write buf list */
5945450Sbrendan static list_t *l2arc_free_on_write;		/* free after write list ptr */
5955450Sbrendan static kmutex_t l2arc_free_on_write_mtx;	/* mutex for list */
5965450Sbrendan static uint64_t l2arc_ndev;			/* number of devices */
5975450Sbrendan 
5985450Sbrendan typedef struct l2arc_read_callback {
5995450Sbrendan 	arc_buf_t	*l2rcb_buf;		/* read buffer */
6005450Sbrendan 	spa_t		*l2rcb_spa;		/* spa */
6015450Sbrendan 	blkptr_t	l2rcb_bp;		/* original blkptr */
6025450Sbrendan 	zbookmark_t	l2rcb_zb;		/* original bookmark */
6035450Sbrendan 	int		l2rcb_flags;		/* original flags */
6045450Sbrendan } l2arc_read_callback_t;
6055450Sbrendan 
6065450Sbrendan typedef struct l2arc_write_callback {
6075450Sbrendan 	l2arc_dev_t	*l2wcb_dev;		/* device info */
6085450Sbrendan 	arc_buf_hdr_t	*l2wcb_head;		/* head of write buflist */
6095450Sbrendan } l2arc_write_callback_t;
6105450Sbrendan 
6115450Sbrendan struct l2arc_buf_hdr {
6125450Sbrendan 	/* protected by arc_buf_hdr  mutex */
6135450Sbrendan 	l2arc_dev_t	*b_dev;			/* L2ARC device */
6149215SGeorge.Wilson@Sun.COM 	uint64_t	b_daddr;		/* disk address, offset byte */
6155450Sbrendan };
6165450Sbrendan 
6175450Sbrendan typedef struct l2arc_data_free {
6185450Sbrendan 	/* protected by l2arc_free_on_write_mtx */
6195450Sbrendan 	void		*l2df_data;
6205450Sbrendan 	size_t		l2df_size;
6215450Sbrendan 	void		(*l2df_func)(void *, size_t);
6225450Sbrendan 	list_node_t	l2df_list_node;
6235450Sbrendan } l2arc_data_free_t;
6245450Sbrendan 
6255450Sbrendan static kmutex_t l2arc_feed_thr_lock;
6265450Sbrendan static kcondvar_t l2arc_feed_thr_cv;
6275450Sbrendan static uint8_t l2arc_thread_exit;
6285450Sbrendan 
6295450Sbrendan static void l2arc_read_done(zio_t *zio);
6305450Sbrendan static void l2arc_hdr_stat_add(void);
6315450Sbrendan static void l2arc_hdr_stat_remove(void);
6325450Sbrendan 
633789Sahrens static uint64_t
6348636SMark.Maybee@Sun.COM buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
635789Sahrens {
636789Sahrens 	uint8_t *vdva = (uint8_t *)dva;
637789Sahrens 	uint64_t crc = -1ULL;
638789Sahrens 	int i;
639789Sahrens 
640789Sahrens 	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
641789Sahrens 
642789Sahrens 	for (i = 0; i < sizeof (dva_t); i++)
643789Sahrens 		crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
644789Sahrens 
6458636SMark.Maybee@Sun.COM 	crc ^= (spa>>8) ^ birth;
646789Sahrens 
647789Sahrens 	return (crc);
648789Sahrens }
649789Sahrens 
650789Sahrens #define	BUF_EMPTY(buf)						\
651789Sahrens 	((buf)->b_dva.dva_word[0] == 0 &&			\
652789Sahrens 	(buf)->b_dva.dva_word[1] == 0 &&			\
653789Sahrens 	(buf)->b_birth == 0)
654789Sahrens 
655789Sahrens #define	BUF_EQUAL(spa, dva, birth, buf)				\
656789Sahrens 	((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) &&	\
657789Sahrens 	((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) &&	\
658789Sahrens 	((buf)->b_birth == birth) && ((buf)->b_spa == spa)
659789Sahrens 
660789Sahrens static arc_buf_hdr_t *
6618636SMark.Maybee@Sun.COM buf_hash_find(uint64_t spa, const dva_t *dva, uint64_t birth, kmutex_t **lockp)
662789Sahrens {
663789Sahrens 	uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
664789Sahrens 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
665789Sahrens 	arc_buf_hdr_t *buf;
666789Sahrens 
667789Sahrens 	mutex_enter(hash_lock);
668789Sahrens 	for (buf = buf_hash_table.ht_table[idx]; buf != NULL;
669789Sahrens 	    buf = buf->b_hash_next) {
670789Sahrens 		if (BUF_EQUAL(spa, dva, birth, buf)) {
671789Sahrens 			*lockp = hash_lock;
672789Sahrens 			return (buf);
673789Sahrens 		}
674789Sahrens 	}
675789Sahrens 	mutex_exit(hash_lock);
676789Sahrens 	*lockp = NULL;
677789Sahrens 	return (NULL);
678789Sahrens }
679789Sahrens 
680789Sahrens /*
681789Sahrens  * Insert an entry into the hash table.  If there is already an element
682789Sahrens  * equal to elem in the hash table, then the already existing element
683789Sahrens  * will be returned and the new element will not be inserted.
684789Sahrens  * Otherwise returns NULL.
685789Sahrens  */
686789Sahrens static arc_buf_hdr_t *
687789Sahrens buf_hash_insert(arc_buf_hdr_t *buf, kmutex_t **lockp)
688789Sahrens {
689789Sahrens 	uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
690789Sahrens 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
691789Sahrens 	arc_buf_hdr_t *fbuf;
6923403Sbmc 	uint32_t i;
693789Sahrens 
6941544Seschrock 	ASSERT(!HDR_IN_HASH_TABLE(buf));
695789Sahrens 	*lockp = hash_lock;
696789Sahrens 	mutex_enter(hash_lock);
697789Sahrens 	for (fbuf = buf_hash_table.ht_table[idx], i = 0; fbuf != NULL;
698789Sahrens 	    fbuf = fbuf->b_hash_next, i++) {
699789Sahrens 		if (BUF_EQUAL(buf->b_spa, &buf->b_dva, buf->b_birth, fbuf))
700789Sahrens 			return (fbuf);
701789Sahrens 	}
702789Sahrens 
703789Sahrens 	buf->b_hash_next = buf_hash_table.ht_table[idx];
704789Sahrens 	buf_hash_table.ht_table[idx] = buf;
7051544Seschrock 	buf->b_flags |= ARC_IN_HASH_TABLE;
706789Sahrens 
707789Sahrens 	/* collect some hash table performance data */
708789Sahrens 	if (i > 0) {
7093403Sbmc 		ARCSTAT_BUMP(arcstat_hash_collisions);
710789Sahrens 		if (i == 1)
7113403Sbmc 			ARCSTAT_BUMP(arcstat_hash_chains);
7123403Sbmc 
7133403Sbmc 		ARCSTAT_MAX(arcstat_hash_chain_max, i);
714789Sahrens 	}
7153403Sbmc 
7163403Sbmc 	ARCSTAT_BUMP(arcstat_hash_elements);
7173403Sbmc 	ARCSTAT_MAXSTAT(arcstat_hash_elements);
718789Sahrens 
719789Sahrens 	return (NULL);
720789Sahrens }
721789Sahrens 
722789Sahrens static void
723789Sahrens buf_hash_remove(arc_buf_hdr_t *buf)
724789Sahrens {
725789Sahrens 	arc_buf_hdr_t *fbuf, **bufp;
726789Sahrens 	uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
727789Sahrens 
728789Sahrens 	ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
7291544Seschrock 	ASSERT(HDR_IN_HASH_TABLE(buf));
730789Sahrens 
731789Sahrens 	bufp = &buf_hash_table.ht_table[idx];
732789Sahrens 	while ((fbuf = *bufp) != buf) {
733789Sahrens 		ASSERT(fbuf != NULL);
734789Sahrens 		bufp = &fbuf->b_hash_next;
735789Sahrens 	}
736789Sahrens 	*bufp = buf->b_hash_next;
737789Sahrens 	buf->b_hash_next = NULL;
7381544Seschrock 	buf->b_flags &= ~ARC_IN_HASH_TABLE;
739789Sahrens 
740789Sahrens 	/* collect some hash table performance data */
7413403Sbmc 	ARCSTAT_BUMPDOWN(arcstat_hash_elements);
7423403Sbmc 
743789Sahrens 	if (buf_hash_table.ht_table[idx] &&
744789Sahrens 	    buf_hash_table.ht_table[idx]->b_hash_next == NULL)
7453403Sbmc 		ARCSTAT_BUMPDOWN(arcstat_hash_chains);
746789Sahrens }
747789Sahrens 
748789Sahrens /*
749789Sahrens  * Global data structures and functions for the buf kmem cache.
750789Sahrens  */
751789Sahrens static kmem_cache_t *hdr_cache;
752789Sahrens static kmem_cache_t *buf_cache;
753789Sahrens 
754789Sahrens static void
755789Sahrens buf_fini(void)
756789Sahrens {
757789Sahrens 	int i;
758789Sahrens 
759789Sahrens 	kmem_free(buf_hash_table.ht_table,
760789Sahrens 	    (buf_hash_table.ht_mask + 1) * sizeof (void *));
761789Sahrens 	for (i = 0; i < BUF_LOCKS; i++)
762789Sahrens 		mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
763789Sahrens 	kmem_cache_destroy(hdr_cache);
764789Sahrens 	kmem_cache_destroy(buf_cache);
765789Sahrens }
766789Sahrens 
767789Sahrens /*
768789Sahrens  * Constructor callback - called when the cache is empty
769789Sahrens  * and a new buf is requested.
770789Sahrens  */
771789Sahrens /* ARGSUSED */
772789Sahrens static int
773789Sahrens hdr_cons(void *vbuf, void *unused, int kmflag)
774789Sahrens {
775789Sahrens 	arc_buf_hdr_t *buf = vbuf;
776789Sahrens 
777789Sahrens 	bzero(buf, sizeof (arc_buf_hdr_t));
778789Sahrens 	refcount_create(&buf->b_refcnt);
779789Sahrens 	cv_init(&buf->b_cv, NULL, CV_DEFAULT, NULL);
7804831Sgw25295 	mutex_init(&buf->b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
7818582SBrendan.Gregg@Sun.COM 	arc_space_consume(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
7828582SBrendan.Gregg@Sun.COM 
783789Sahrens 	return (0);
784789Sahrens }
785789Sahrens 
7867545SMark.Maybee@Sun.COM /* ARGSUSED */
7877545SMark.Maybee@Sun.COM static int
7887545SMark.Maybee@Sun.COM buf_cons(void *vbuf, void *unused, int kmflag)
7897545SMark.Maybee@Sun.COM {
7907545SMark.Maybee@Sun.COM 	arc_buf_t *buf = vbuf;
7917545SMark.Maybee@Sun.COM 
7927545SMark.Maybee@Sun.COM 	bzero(buf, sizeof (arc_buf_t));
7937545SMark.Maybee@Sun.COM 	rw_init(&buf->b_lock, NULL, RW_DEFAULT, NULL);
7948582SBrendan.Gregg@Sun.COM 	arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
7958582SBrendan.Gregg@Sun.COM 
7967545SMark.Maybee@Sun.COM 	return (0);
7977545SMark.Maybee@Sun.COM }
7987545SMark.Maybee@Sun.COM 
799789Sahrens /*
800789Sahrens  * Destructor callback - called when a cached buf is
801789Sahrens  * no longer required.
802789Sahrens  */
803789Sahrens /* ARGSUSED */
804789Sahrens static void
805789Sahrens hdr_dest(void *vbuf, void *unused)
806789Sahrens {
807789Sahrens 	arc_buf_hdr_t *buf = vbuf;
808789Sahrens 
809789Sahrens 	refcount_destroy(&buf->b_refcnt);
810789Sahrens 	cv_destroy(&buf->b_cv);
8114831Sgw25295 	mutex_destroy(&buf->b_freeze_lock);
8128582SBrendan.Gregg@Sun.COM 	arc_space_return(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
813789Sahrens }
814789Sahrens 
8157545SMark.Maybee@Sun.COM /* ARGSUSED */
8167545SMark.Maybee@Sun.COM static void
8177545SMark.Maybee@Sun.COM buf_dest(void *vbuf, void *unused)
8187545SMark.Maybee@Sun.COM {
8197545SMark.Maybee@Sun.COM 	arc_buf_t *buf = vbuf;
8207545SMark.Maybee@Sun.COM 
8217545SMark.Maybee@Sun.COM 	rw_destroy(&buf->b_lock);
8228582SBrendan.Gregg@Sun.COM 	arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
8237545SMark.Maybee@Sun.COM }
8247545SMark.Maybee@Sun.COM 
825789Sahrens /*
826789Sahrens  * Reclaim callback -- invoked when memory is low.
827789Sahrens  */
828789Sahrens /* ARGSUSED */
829789Sahrens static void
830789Sahrens hdr_recl(void *unused)
831789Sahrens {
832789Sahrens 	dprintf("hdr_recl called\n");
8333158Smaybee 	/*
8343158Smaybee 	 * umem calls the reclaim func when we destroy the buf cache,
8353158Smaybee 	 * which is after we do arc_fini().
8363158Smaybee 	 */
8373158Smaybee 	if (!arc_dead)
8383158Smaybee 		cv_signal(&arc_reclaim_thr_cv);
839789Sahrens }
840789Sahrens 
841789Sahrens static void
842789Sahrens buf_init(void)
843789Sahrens {
844789Sahrens 	uint64_t *ct;
8451544Seschrock 	uint64_t hsize = 1ULL << 12;
846789Sahrens 	int i, j;
847789Sahrens 
848789Sahrens 	/*
849789Sahrens 	 * The hash table is big enough to fill all of physical memory
8501544Seschrock 	 * with an average 64K block size.  The table will take up
8511544Seschrock 	 * totalmem*sizeof(void*)/64K (eg. 128KB/GB with 8-byte pointers).
852789Sahrens 	 */
8531544Seschrock 	while (hsize * 65536 < physmem * PAGESIZE)
854789Sahrens 		hsize <<= 1;
8551544Seschrock retry:
856789Sahrens 	buf_hash_table.ht_mask = hsize - 1;
8571544Seschrock 	buf_hash_table.ht_table =
8581544Seschrock 	    kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
8591544Seschrock 	if (buf_hash_table.ht_table == NULL) {
8601544Seschrock 		ASSERT(hsize > (1ULL << 8));
8611544Seschrock 		hsize >>= 1;
8621544Seschrock 		goto retry;
8631544Seschrock 	}
864789Sahrens 
865789Sahrens 	hdr_cache = kmem_cache_create("arc_buf_hdr_t", sizeof (arc_buf_hdr_t),
866789Sahrens 	    0, hdr_cons, hdr_dest, hdr_recl, NULL, NULL, 0);
867789Sahrens 	buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
8687545SMark.Maybee@Sun.COM 	    0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
869789Sahrens 
870789Sahrens 	for (i = 0; i < 256; i++)
871789Sahrens 		for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
872789Sahrens 			*ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
873789Sahrens 
874789Sahrens 	for (i = 0; i < BUF_LOCKS; i++) {
875789Sahrens 		mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
876789Sahrens 		    NULL, MUTEX_DEFAULT, NULL);
877789Sahrens 	}
878789Sahrens }
879789Sahrens 
880789Sahrens #define	ARC_MINTIME	(hz>>4) /* 62 ms */
881789Sahrens 
882789Sahrens static void
8833093Sahrens arc_cksum_verify(arc_buf_t *buf)
8843093Sahrens {
8853093Sahrens 	zio_cksum_t zc;
8863093Sahrens 
8873312Sahrens 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
8883093Sahrens 		return;
8893093Sahrens 
8903093Sahrens 	mutex_enter(&buf->b_hdr->b_freeze_lock);
8913265Sahrens 	if (buf->b_hdr->b_freeze_cksum == NULL ||
8923265Sahrens 	    (buf->b_hdr->b_flags & ARC_IO_ERROR)) {
8933093Sahrens 		mutex_exit(&buf->b_hdr->b_freeze_lock);
8943093Sahrens 		return;
8953093Sahrens 	}
8963093Sahrens 	fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
8973093Sahrens 	if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
8983093Sahrens 		panic("buffer modified while frozen!");
8993093Sahrens 	mutex_exit(&buf->b_hdr->b_freeze_lock);
9003093Sahrens }
9013093Sahrens 
9025450Sbrendan static int
9035450Sbrendan arc_cksum_equal(arc_buf_t *buf)
9045450Sbrendan {
9055450Sbrendan 	zio_cksum_t zc;
9065450Sbrendan 	int equal;
9075450Sbrendan 
9085450Sbrendan 	mutex_enter(&buf->b_hdr->b_freeze_lock);
9095450Sbrendan 	fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
9105450Sbrendan 	equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
9115450Sbrendan 	mutex_exit(&buf->b_hdr->b_freeze_lock);
9125450Sbrendan 
9135450Sbrendan 	return (equal);
9145450Sbrendan }
9155450Sbrendan 
9163093Sahrens static void
9175450Sbrendan arc_cksum_compute(arc_buf_t *buf, boolean_t force)
9183093Sahrens {
9195450Sbrendan 	if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
9203093Sahrens 		return;
9213093Sahrens 
9223093Sahrens 	mutex_enter(&buf->b_hdr->b_freeze_lock);
9233093Sahrens 	if (buf->b_hdr->b_freeze_cksum != NULL) {
9243093Sahrens 		mutex_exit(&buf->b_hdr->b_freeze_lock);
9253093Sahrens 		return;
9263093Sahrens 	}
9273093Sahrens 	buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
9283093Sahrens 	fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
9293093Sahrens 	    buf->b_hdr->b_freeze_cksum);
9303093Sahrens 	mutex_exit(&buf->b_hdr->b_freeze_lock);
9313093Sahrens }
9323093Sahrens 
9333093Sahrens void
9343093Sahrens arc_buf_thaw(arc_buf_t *buf)
9353093Sahrens {
9365450Sbrendan 	if (zfs_flags & ZFS_DEBUG_MODIFY) {
9375450Sbrendan 		if (buf->b_hdr->b_state != arc_anon)
9385450Sbrendan 			panic("modifying non-anon buffer!");
9395450Sbrendan 		if (buf->b_hdr->b_flags & ARC_IO_IN_PROGRESS)
9405450Sbrendan 			panic("modifying buffer while i/o in progress!");
9415450Sbrendan 		arc_cksum_verify(buf);
9425450Sbrendan 	}
9435450Sbrendan 
9443093Sahrens 	mutex_enter(&buf->b_hdr->b_freeze_lock);
9453093Sahrens 	if (buf->b_hdr->b_freeze_cksum != NULL) {
9463093Sahrens 		kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
9473093Sahrens 		buf->b_hdr->b_freeze_cksum = NULL;
9483093Sahrens 	}
9493093Sahrens 	mutex_exit(&buf->b_hdr->b_freeze_lock);
9503093Sahrens }
9513093Sahrens 
9523093Sahrens void
9533093Sahrens arc_buf_freeze(arc_buf_t *buf)
9543093Sahrens {
9553312Sahrens 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
9563312Sahrens 		return;
9573312Sahrens 
9583093Sahrens 	ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
9593403Sbmc 	    buf->b_hdr->b_state == arc_anon);
9605450Sbrendan 	arc_cksum_compute(buf, B_FALSE);
9613093Sahrens }
9623093Sahrens 
9633093Sahrens static void
964789Sahrens add_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
965789Sahrens {
966789Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
967789Sahrens 
968789Sahrens 	if ((refcount_add(&ab->b_refcnt, tag) == 1) &&
9693403Sbmc 	    (ab->b_state != arc_anon)) {
9703700Sek110237 		uint64_t delta = ab->b_size * ab->b_datacnt;
9714309Smaybee 		list_t *list = &ab->b_state->arcs_list[ab->b_type];
9724309Smaybee 		uint64_t *size = &ab->b_state->arcs_lsize[ab->b_type];
973789Sahrens 
9743403Sbmc 		ASSERT(!MUTEX_HELD(&ab->b_state->arcs_mtx));
9753403Sbmc 		mutex_enter(&ab->b_state->arcs_mtx);
976789Sahrens 		ASSERT(list_link_active(&ab->b_arc_node));
9774309Smaybee 		list_remove(list, ab);
9781544Seschrock 		if (GHOST_STATE(ab->b_state)) {
9791544Seschrock 			ASSERT3U(ab->b_datacnt, ==, 0);
9801544Seschrock 			ASSERT3P(ab->b_buf, ==, NULL);
9811544Seschrock 			delta = ab->b_size;
9821544Seschrock 		}
9831544Seschrock 		ASSERT(delta > 0);
9844309Smaybee 		ASSERT3U(*size, >=, delta);
9854309Smaybee 		atomic_add_64(size, -delta);
9863403Sbmc 		mutex_exit(&ab->b_state->arcs_mtx);
9877046Sahrens 		/* remove the prefetch flag if we get a reference */
9882391Smaybee 		if (ab->b_flags & ARC_PREFETCH)
9892391Smaybee 			ab->b_flags &= ~ARC_PREFETCH;
990789Sahrens 	}
991789Sahrens }
992789Sahrens 
993789Sahrens static int
994789Sahrens remove_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
995789Sahrens {
996789Sahrens 	int cnt;
9973403Sbmc 	arc_state_t *state = ab->b_state;
998789Sahrens 
9993403Sbmc 	ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
10003403Sbmc 	ASSERT(!GHOST_STATE(state));
1001789Sahrens 
1002789Sahrens 	if (((cnt = refcount_remove(&ab->b_refcnt, tag)) == 0) &&
10033403Sbmc 	    (state != arc_anon)) {
10044309Smaybee 		uint64_t *size = &state->arcs_lsize[ab->b_type];
10054309Smaybee 
10063403Sbmc 		ASSERT(!MUTEX_HELD(&state->arcs_mtx));
10073403Sbmc 		mutex_enter(&state->arcs_mtx);
1008789Sahrens 		ASSERT(!list_link_active(&ab->b_arc_node));
10094309Smaybee 		list_insert_head(&state->arcs_list[ab->b_type], ab);
10101544Seschrock 		ASSERT(ab->b_datacnt > 0);
10114309Smaybee 		atomic_add_64(size, ab->b_size * ab->b_datacnt);
10123403Sbmc 		mutex_exit(&state->arcs_mtx);
1013789Sahrens 	}
1014789Sahrens 	return (cnt);
1015789Sahrens }
1016789Sahrens 
1017789Sahrens /*
1018789Sahrens  * Move the supplied buffer to the indicated state.  The mutex
1019789Sahrens  * for the buffer must be held by the caller.
1020789Sahrens  */
1021789Sahrens static void
10221544Seschrock arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *ab, kmutex_t *hash_lock)
1023789Sahrens {
10241544Seschrock 	arc_state_t *old_state = ab->b_state;
10253700Sek110237 	int64_t refcnt = refcount_count(&ab->b_refcnt);
10263700Sek110237 	uint64_t from_delta, to_delta;
1027789Sahrens 
1028789Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
10291544Seschrock 	ASSERT(new_state != old_state);
10301544Seschrock 	ASSERT(refcnt == 0 || ab->b_datacnt > 0);
10311544Seschrock 	ASSERT(ab->b_datacnt == 0 || !GHOST_STATE(new_state));
10321544Seschrock 
10331544Seschrock 	from_delta = to_delta = ab->b_datacnt * ab->b_size;
1034789Sahrens 
1035789Sahrens 	/*
1036789Sahrens 	 * If this buffer is evictable, transfer it from the
1037789Sahrens 	 * old state list to the new state list.
1038789Sahrens 	 */
10391544Seschrock 	if (refcnt == 0) {
10403403Sbmc 		if (old_state != arc_anon) {
10413403Sbmc 			int use_mutex = !MUTEX_HELD(&old_state->arcs_mtx);
10424309Smaybee 			uint64_t *size = &old_state->arcs_lsize[ab->b_type];
10431544Seschrock 
10441544Seschrock 			if (use_mutex)
10453403Sbmc 				mutex_enter(&old_state->arcs_mtx);
10461544Seschrock 
10471544Seschrock 			ASSERT(list_link_active(&ab->b_arc_node));
10484309Smaybee 			list_remove(&old_state->arcs_list[ab->b_type], ab);
1049789Sahrens 
10502391Smaybee 			/*
10512391Smaybee 			 * If prefetching out of the ghost cache,
10522391Smaybee 			 * we will have a non-null datacnt.
10532391Smaybee 			 */
10542391Smaybee 			if (GHOST_STATE(old_state) && ab->b_datacnt == 0) {
10552391Smaybee 				/* ghost elements have a ghost size */
10561544Seschrock 				ASSERT(ab->b_buf == NULL);
10571544Seschrock 				from_delta = ab->b_size;
1058789Sahrens 			}
10594309Smaybee 			ASSERT3U(*size, >=, from_delta);
10604309Smaybee 			atomic_add_64(size, -from_delta);
10611544Seschrock 
10621544Seschrock 			if (use_mutex)
10633403Sbmc 				mutex_exit(&old_state->arcs_mtx);
1064789Sahrens 		}
10653403Sbmc 		if (new_state != arc_anon) {
10663403Sbmc 			int use_mutex = !MUTEX_HELD(&new_state->arcs_mtx);
10674309Smaybee 			uint64_t *size = &new_state->arcs_lsize[ab->b_type];
1068789Sahrens 
10691544Seschrock 			if (use_mutex)
10703403Sbmc 				mutex_enter(&new_state->arcs_mtx);
10711544Seschrock 
10724309Smaybee 			list_insert_head(&new_state->arcs_list[ab->b_type], ab);
10731544Seschrock 
10741544Seschrock 			/* ghost elements have a ghost size */
10751544Seschrock 			if (GHOST_STATE(new_state)) {
10761544Seschrock 				ASSERT(ab->b_datacnt == 0);
10771544Seschrock 				ASSERT(ab->b_buf == NULL);
10781544Seschrock 				to_delta = ab->b_size;
10791544Seschrock 			}
10804309Smaybee 			atomic_add_64(size, to_delta);
10811544Seschrock 
10821544Seschrock 			if (use_mutex)
10833403Sbmc 				mutex_exit(&new_state->arcs_mtx);
1084789Sahrens 		}
1085789Sahrens 	}
1086789Sahrens 
1087789Sahrens 	ASSERT(!BUF_EMPTY(ab));
10885450Sbrendan 	if (new_state == arc_anon) {
1089789Sahrens 		buf_hash_remove(ab);
1090789Sahrens 	}
1091789Sahrens 
10921544Seschrock 	/* adjust state sizes */
10931544Seschrock 	if (to_delta)
10943403Sbmc 		atomic_add_64(&new_state->arcs_size, to_delta);
10951544Seschrock 	if (from_delta) {
10963403Sbmc 		ASSERT3U(old_state->arcs_size, >=, from_delta);
10973403Sbmc 		atomic_add_64(&old_state->arcs_size, -from_delta);
1098789Sahrens 	}
1099789Sahrens 	ab->b_state = new_state;
11005450Sbrendan 
11015450Sbrendan 	/* adjust l2arc hdr stats */
11025450Sbrendan 	if (new_state == arc_l2c_only)
11035450Sbrendan 		l2arc_hdr_stat_add();
11045450Sbrendan 	else if (old_state == arc_l2c_only)
11055450Sbrendan 		l2arc_hdr_stat_remove();
1106789Sahrens }
1107789Sahrens 
11084309Smaybee void
11098582SBrendan.Gregg@Sun.COM arc_space_consume(uint64_t space, arc_space_type_t type)
11104309Smaybee {
11118582SBrendan.Gregg@Sun.COM 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
11128582SBrendan.Gregg@Sun.COM 
11138582SBrendan.Gregg@Sun.COM 	switch (type) {
11148582SBrendan.Gregg@Sun.COM 	case ARC_SPACE_DATA:
11158582SBrendan.Gregg@Sun.COM 		ARCSTAT_INCR(arcstat_data_size, space);
11168582SBrendan.Gregg@Sun.COM 		break;
11178582SBrendan.Gregg@Sun.COM 	case ARC_SPACE_OTHER:
11188582SBrendan.Gregg@Sun.COM 		ARCSTAT_INCR(arcstat_other_size, space);
11198582SBrendan.Gregg@Sun.COM 		break;
11208582SBrendan.Gregg@Sun.COM 	case ARC_SPACE_HDRS:
11218582SBrendan.Gregg@Sun.COM 		ARCSTAT_INCR(arcstat_hdr_size, space);
11228582SBrendan.Gregg@Sun.COM 		break;
11238582SBrendan.Gregg@Sun.COM 	case ARC_SPACE_L2HDRS:
11248582SBrendan.Gregg@Sun.COM 		ARCSTAT_INCR(arcstat_l2_hdr_size, space);
11258582SBrendan.Gregg@Sun.COM 		break;
11268582SBrendan.Gregg@Sun.COM 	}
11278582SBrendan.Gregg@Sun.COM 
11284309Smaybee 	atomic_add_64(&arc_meta_used, space);
11294309Smaybee 	atomic_add_64(&arc_size, space);
11304309Smaybee }
11314309Smaybee 
11324309Smaybee void
11338582SBrendan.Gregg@Sun.COM arc_space_return(uint64_t space, arc_space_type_t type)
11344309Smaybee {
11358582SBrendan.Gregg@Sun.COM 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
11368582SBrendan.Gregg@Sun.COM 
11378582SBrendan.Gregg@Sun.COM 	switch (type) {
11388582SBrendan.Gregg@Sun.COM 	case ARC_SPACE_DATA:
11398582SBrendan.Gregg@Sun.COM 		ARCSTAT_INCR(arcstat_data_size, -space);
11408582SBrendan.Gregg@Sun.COM 		break;
11418582SBrendan.Gregg@Sun.COM 	case ARC_SPACE_OTHER:
11428582SBrendan.Gregg@Sun.COM 		ARCSTAT_INCR(arcstat_other_size, -space);
11438582SBrendan.Gregg@Sun.COM 		break;
11448582SBrendan.Gregg@Sun.COM 	case ARC_SPACE_HDRS:
11458582SBrendan.Gregg@Sun.COM 		ARCSTAT_INCR(arcstat_hdr_size, -space);
11468582SBrendan.Gregg@Sun.COM 		break;
11478582SBrendan.Gregg@Sun.COM 	case ARC_SPACE_L2HDRS:
11488582SBrendan.Gregg@Sun.COM 		ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
11498582SBrendan.Gregg@Sun.COM 		break;
11508582SBrendan.Gregg@Sun.COM 	}
11518582SBrendan.Gregg@Sun.COM 
11524309Smaybee 	ASSERT(arc_meta_used >= space);
11534309Smaybee 	if (arc_meta_max < arc_meta_used)
11544309Smaybee 		arc_meta_max = arc_meta_used;
11554309Smaybee 	atomic_add_64(&arc_meta_used, -space);
11564309Smaybee 	ASSERT(arc_size >= space);
11574309Smaybee 	atomic_add_64(&arc_size, -space);
11584309Smaybee }
11594309Smaybee 
11604309Smaybee void *
11614309Smaybee arc_data_buf_alloc(uint64_t size)
11624309Smaybee {
11634309Smaybee 	if (arc_evict_needed(ARC_BUFC_DATA))
11644309Smaybee 		cv_signal(&arc_reclaim_thr_cv);
11654309Smaybee 	atomic_add_64(&arc_size, size);
11664309Smaybee 	return (zio_data_buf_alloc(size));
11674309Smaybee }
11684309Smaybee 
11694309Smaybee void
11704309Smaybee arc_data_buf_free(void *buf, uint64_t size)
11714309Smaybee {
11724309Smaybee 	zio_data_buf_free(buf, size);
11734309Smaybee 	ASSERT(arc_size >= size);
11744309Smaybee 	atomic_add_64(&arc_size, -size);
11754309Smaybee }
11764309Smaybee 
1177789Sahrens arc_buf_t *
11783290Sjohansen arc_buf_alloc(spa_t *spa, int size, void *tag, arc_buf_contents_t type)
1179789Sahrens {
1180789Sahrens 	arc_buf_hdr_t *hdr;
1181789Sahrens 	arc_buf_t *buf;
1182789Sahrens 
1183789Sahrens 	ASSERT3U(size, >, 0);
11846245Smaybee 	hdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
1185789Sahrens 	ASSERT(BUF_EMPTY(hdr));
1186789Sahrens 	hdr->b_size = size;
11873290Sjohansen 	hdr->b_type = type;
11888636SMark.Maybee@Sun.COM 	hdr->b_spa = spa_guid(spa);
11893403Sbmc 	hdr->b_state = arc_anon;
1190789Sahrens 	hdr->b_arc_access = 0;
11916245Smaybee 	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1192789Sahrens 	buf->b_hdr = hdr;
11932688Smaybee 	buf->b_data = NULL;
11941544Seschrock 	buf->b_efunc = NULL;
11951544Seschrock 	buf->b_private = NULL;
1196789Sahrens 	buf->b_next = NULL;
1197789Sahrens 	hdr->b_buf = buf;
11982688Smaybee 	arc_get_data_buf(buf);
11991544Seschrock 	hdr->b_datacnt = 1;
1200789Sahrens 	hdr->b_flags = 0;
1201789Sahrens 	ASSERT(refcount_is_zero(&hdr->b_refcnt));
1202789Sahrens 	(void) refcount_add(&hdr->b_refcnt, tag);
1203789Sahrens 
1204789Sahrens 	return (buf);
1205789Sahrens }
1206789Sahrens 
1207*9412SAleksandr.Guzovskiy@Sun.COM static char *arc_onloan_tag = "onloan";
1208*9412SAleksandr.Guzovskiy@Sun.COM 
1209*9412SAleksandr.Guzovskiy@Sun.COM /*
1210*9412SAleksandr.Guzovskiy@Sun.COM  * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
1211*9412SAleksandr.Guzovskiy@Sun.COM  * flight data by arc_tempreserve_space() until they are "returned". Loaned
1212*9412SAleksandr.Guzovskiy@Sun.COM  * buffers must be returned to the arc before they can be used by the DMU or
1213*9412SAleksandr.Guzovskiy@Sun.COM  * freed.
1214*9412SAleksandr.Guzovskiy@Sun.COM  */
1215*9412SAleksandr.Guzovskiy@Sun.COM arc_buf_t *
1216*9412SAleksandr.Guzovskiy@Sun.COM arc_loan_buf(spa_t *spa, int size)
1217*9412SAleksandr.Guzovskiy@Sun.COM {
1218*9412SAleksandr.Guzovskiy@Sun.COM 	arc_buf_t *buf;
1219*9412SAleksandr.Guzovskiy@Sun.COM 
1220*9412SAleksandr.Guzovskiy@Sun.COM 	buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
1221*9412SAleksandr.Guzovskiy@Sun.COM 
1222*9412SAleksandr.Guzovskiy@Sun.COM 	atomic_add_64(&arc_loaned_bytes, size);
1223*9412SAleksandr.Guzovskiy@Sun.COM 	return (buf);
1224*9412SAleksandr.Guzovskiy@Sun.COM }
1225*9412SAleksandr.Guzovskiy@Sun.COM 
1226*9412SAleksandr.Guzovskiy@Sun.COM /*
1227*9412SAleksandr.Guzovskiy@Sun.COM  * Return a loaned arc buffer to the arc.
1228*9412SAleksandr.Guzovskiy@Sun.COM  */
1229*9412SAleksandr.Guzovskiy@Sun.COM void
1230*9412SAleksandr.Guzovskiy@Sun.COM arc_return_buf(arc_buf_t *buf, void *tag)
1231*9412SAleksandr.Guzovskiy@Sun.COM {
1232*9412SAleksandr.Guzovskiy@Sun.COM 	arc_buf_hdr_t *hdr = buf->b_hdr;
1233*9412SAleksandr.Guzovskiy@Sun.COM 
1234*9412SAleksandr.Guzovskiy@Sun.COM 	ASSERT(hdr->b_state == arc_anon);
1235*9412SAleksandr.Guzovskiy@Sun.COM 	ASSERT(buf->b_data != NULL);
1236*9412SAleksandr.Guzovskiy@Sun.COM 	VERIFY(refcount_remove(&hdr->b_refcnt, arc_onloan_tag) == 0);
1237*9412SAleksandr.Guzovskiy@Sun.COM 	VERIFY(refcount_add(&hdr->b_refcnt, tag) == 1);
1238*9412SAleksandr.Guzovskiy@Sun.COM 
1239*9412SAleksandr.Guzovskiy@Sun.COM 	atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
1240*9412SAleksandr.Guzovskiy@Sun.COM }
1241*9412SAleksandr.Guzovskiy@Sun.COM 
12422688Smaybee static arc_buf_t *
12432688Smaybee arc_buf_clone(arc_buf_t *from)
12441544Seschrock {
12452688Smaybee 	arc_buf_t *buf;
12462688Smaybee 	arc_buf_hdr_t *hdr = from->b_hdr;
12472688Smaybee 	uint64_t size = hdr->b_size;
12481544Seschrock 
12496245Smaybee 	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
12502688Smaybee 	buf->b_hdr = hdr;
12512688Smaybee 	buf->b_data = NULL;
12522688Smaybee 	buf->b_efunc = NULL;
12532688Smaybee 	buf->b_private = NULL;
12542688Smaybee 	buf->b_next = hdr->b_buf;
12552688Smaybee 	hdr->b_buf = buf;
12562688Smaybee 	arc_get_data_buf(buf);
12572688Smaybee 	bcopy(from->b_data, buf->b_data, size);
12582688Smaybee 	hdr->b_datacnt += 1;
12592688Smaybee 	return (buf);
12601544Seschrock }
12611544Seschrock 
12621544Seschrock void
12631544Seschrock arc_buf_add_ref(arc_buf_t *buf, void* tag)
12641544Seschrock {
12652887Smaybee 	arc_buf_hdr_t *hdr;
12661544Seschrock 	kmutex_t *hash_lock;
12671544Seschrock 
12682724Smaybee 	/*
12697545SMark.Maybee@Sun.COM 	 * Check to see if this buffer is evicted.  Callers
12707545SMark.Maybee@Sun.COM 	 * must verify b_data != NULL to know if the add_ref
12717545SMark.Maybee@Sun.COM 	 * was successful.
12722724Smaybee 	 */
12737545SMark.Maybee@Sun.COM 	rw_enter(&buf->b_lock, RW_READER);
12747545SMark.Maybee@Sun.COM 	if (buf->b_data == NULL) {
12757545SMark.Maybee@Sun.COM 		rw_exit(&buf->b_lock);
12762724Smaybee 		return;
12772887Smaybee 	}
12787545SMark.Maybee@Sun.COM 	hdr = buf->b_hdr;
12797545SMark.Maybee@Sun.COM 	ASSERT(hdr != NULL);
12802887Smaybee 	hash_lock = HDR_LOCK(hdr);
12812724Smaybee 	mutex_enter(hash_lock);
12827545SMark.Maybee@Sun.COM 	rw_exit(&buf->b_lock);
12837545SMark.Maybee@Sun.COM 
12843403Sbmc 	ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
12851544Seschrock 	add_reference(hdr, hash_lock, tag);
12868582SBrendan.Gregg@Sun.COM 	DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
12872688Smaybee 	arc_access(hdr, hash_lock);
12882688Smaybee 	mutex_exit(hash_lock);
12893403Sbmc 	ARCSTAT_BUMP(arcstat_hits);
12903403Sbmc 	ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
12913403Sbmc 	    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
12923403Sbmc 	    data, metadata, hits);
12931544Seschrock }
12941544Seschrock 
12955450Sbrendan /*
12965450Sbrendan  * Free the arc data buffer.  If it is an l2arc write in progress,
12975450Sbrendan  * the buffer is placed on l2arc_free_on_write to be freed later.
12985450Sbrendan  */
12995450Sbrendan static void
13005450Sbrendan arc_buf_data_free(arc_buf_hdr_t *hdr, void (*free_func)(void *, size_t),
13015450Sbrendan     void *data, size_t size)
13025450Sbrendan {
13035450Sbrendan 	if (HDR_L2_WRITING(hdr)) {
13045450Sbrendan 		l2arc_data_free_t *df;
13055450Sbrendan 		df = kmem_alloc(sizeof (l2arc_data_free_t), KM_SLEEP);
13065450Sbrendan 		df->l2df_data = data;
13075450Sbrendan 		df->l2df_size = size;
13085450Sbrendan 		df->l2df_func = free_func;
13095450Sbrendan 		mutex_enter(&l2arc_free_on_write_mtx);
13105450Sbrendan 		list_insert_head(l2arc_free_on_write, df);
13115450Sbrendan 		mutex_exit(&l2arc_free_on_write_mtx);
13125450Sbrendan 		ARCSTAT_BUMP(arcstat_l2_free_on_write);
13135450Sbrendan 	} else {
13145450Sbrendan 		free_func(data, size);
13155450Sbrendan 	}
13165450Sbrendan }
13175450Sbrendan 
1318789Sahrens static void
13192688Smaybee arc_buf_destroy(arc_buf_t *buf, boolean_t recycle, boolean_t all)
13201544Seschrock {
13211544Seschrock 	arc_buf_t **bufp;
13221544Seschrock 
13231544Seschrock 	/* free up data associated with the buf */
13241544Seschrock 	if (buf->b_data) {
13251544Seschrock 		arc_state_t *state = buf->b_hdr->b_state;
13261544Seschrock 		uint64_t size = buf->b_hdr->b_size;
13273290Sjohansen 		arc_buf_contents_t type = buf->b_hdr->b_type;
13281544Seschrock 
13293093Sahrens 		arc_cksum_verify(buf);
13302688Smaybee 		if (!recycle) {
13313290Sjohansen 			if (type == ARC_BUFC_METADATA) {
13325450Sbrendan 				arc_buf_data_free(buf->b_hdr, zio_buf_free,
13335450Sbrendan 				    buf->b_data, size);
13348582SBrendan.Gregg@Sun.COM 				arc_space_return(size, ARC_SPACE_DATA);
13353290Sjohansen 			} else {
13363290Sjohansen 				ASSERT(type == ARC_BUFC_DATA);
13375450Sbrendan 				arc_buf_data_free(buf->b_hdr,
13385450Sbrendan 				    zio_data_buf_free, buf->b_data, size);
13398582SBrendan.Gregg@Sun.COM 				ARCSTAT_INCR(arcstat_data_size, -size);
13404309Smaybee 				atomic_add_64(&arc_size, -size);
13413290Sjohansen 			}
13422688Smaybee 		}
13431544Seschrock 		if (list_link_active(&buf->b_hdr->b_arc_node)) {
13444309Smaybee 			uint64_t *cnt = &state->arcs_lsize[type];
13454309Smaybee 
13461544Seschrock 			ASSERT(refcount_is_zero(&buf->b_hdr->b_refcnt));
13473403Sbmc 			ASSERT(state != arc_anon);
13484309Smaybee 
13494309Smaybee 			ASSERT3U(*cnt, >=, size);
13504309Smaybee 			atomic_add_64(cnt, -size);
13511544Seschrock 		}
13523403Sbmc 		ASSERT3U(state->arcs_size, >=, size);
13533403Sbmc 		atomic_add_64(&state->arcs_size, -size);
13541544Seschrock 		buf->b_data = NULL;
13551544Seschrock 		ASSERT(buf->b_hdr->b_datacnt > 0);
13561544Seschrock 		buf->b_hdr->b_datacnt -= 1;
13571544Seschrock 	}
13581544Seschrock 
13591544Seschrock 	/* only remove the buf if requested */
13601544Seschrock 	if (!all)
13611544Seschrock 		return;
13621544Seschrock 
13631544Seschrock 	/* remove the buf from the hdr list */
13641544Seschrock 	for (bufp = &buf->b_hdr->b_buf; *bufp != buf; bufp = &(*bufp)->b_next)
13651544Seschrock 		continue;
13661544Seschrock 	*bufp = buf->b_next;
13671544Seschrock 
13681544Seschrock 	ASSERT(buf->b_efunc == NULL);
13691544Seschrock 
13701544Seschrock 	/* clean up the buf */
13711544Seschrock 	buf->b_hdr = NULL;
13721544Seschrock 	kmem_cache_free(buf_cache, buf);
13731544Seschrock }
13741544Seschrock 
13751544Seschrock static void
13761544Seschrock arc_hdr_destroy(arc_buf_hdr_t *hdr)
1377789Sahrens {
1378789Sahrens 	ASSERT(refcount_is_zero(&hdr->b_refcnt));
13793403Sbmc 	ASSERT3P(hdr->b_state, ==, arc_anon);
13801544Seschrock 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
13817046Sahrens 	ASSERT(!(hdr->b_flags & ARC_STORED));
1382789Sahrens 
13835450Sbrendan 	if (hdr->b_l2hdr != NULL) {
13845450Sbrendan 		if (!MUTEX_HELD(&l2arc_buflist_mtx)) {
13855450Sbrendan 			/*
13865450Sbrendan 			 * To prevent arc_free() and l2arc_evict() from
13875450Sbrendan 			 * attempting to free the same buffer at the same time,
13885450Sbrendan 			 * a FREE_IN_PROGRESS flag is given to arc_free() to
13895450Sbrendan 			 * give it priority.  l2arc_evict() can't destroy this
13905450Sbrendan 			 * header while we are waiting on l2arc_buflist_mtx.
13917361SBrendan.Gregg@Sun.COM 			 *
13927361SBrendan.Gregg@Sun.COM 			 * The hdr may be removed from l2ad_buflist before we
13937361SBrendan.Gregg@Sun.COM 			 * grab l2arc_buflist_mtx, so b_l2hdr is rechecked.
13945450Sbrendan 			 */
13955450Sbrendan 			mutex_enter(&l2arc_buflist_mtx);
13967361SBrendan.Gregg@Sun.COM 			if (hdr->b_l2hdr != NULL) {
13977361SBrendan.Gregg@Sun.COM 				list_remove(hdr->b_l2hdr->b_dev->l2ad_buflist,
13987361SBrendan.Gregg@Sun.COM 				    hdr);
13997361SBrendan.Gregg@Sun.COM 			}
14005450Sbrendan 			mutex_exit(&l2arc_buflist_mtx);
14015450Sbrendan 		} else {
14025450Sbrendan 			list_remove(hdr->b_l2hdr->b_dev->l2ad_buflist, hdr);
14035450Sbrendan 		}
14045450Sbrendan 		ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
14055450Sbrendan 		kmem_free(hdr->b_l2hdr, sizeof (l2arc_buf_hdr_t));
14065450Sbrendan 		if (hdr->b_state == arc_l2c_only)
14075450Sbrendan 			l2arc_hdr_stat_remove();
14085450Sbrendan 		hdr->b_l2hdr = NULL;
14095450Sbrendan 	}
14105450Sbrendan 
1411789Sahrens 	if (!BUF_EMPTY(hdr)) {
14121544Seschrock 		ASSERT(!HDR_IN_HASH_TABLE(hdr));
1413789Sahrens 		bzero(&hdr->b_dva, sizeof (dva_t));
1414789Sahrens 		hdr->b_birth = 0;
1415789Sahrens 		hdr->b_cksum0 = 0;
1416789Sahrens 	}
14171544Seschrock 	while (hdr->b_buf) {
1418789Sahrens 		arc_buf_t *buf = hdr->b_buf;
1419789Sahrens 
14201544Seschrock 		if (buf->b_efunc) {
14211544Seschrock 			mutex_enter(&arc_eviction_mtx);
14227545SMark.Maybee@Sun.COM 			rw_enter(&buf->b_lock, RW_WRITER);
14231544Seschrock 			ASSERT(buf->b_hdr != NULL);
14242688Smaybee 			arc_buf_destroy(hdr->b_buf, FALSE, FALSE);
14251544Seschrock 			hdr->b_buf = buf->b_next;
14262887Smaybee 			buf->b_hdr = &arc_eviction_hdr;
14271544Seschrock 			buf->b_next = arc_eviction_list;
14281544Seschrock 			arc_eviction_list = buf;
14297545SMark.Maybee@Sun.COM 			rw_exit(&buf->b_lock);
14301544Seschrock 			mutex_exit(&arc_eviction_mtx);
14311544Seschrock 		} else {
14322688Smaybee 			arc_buf_destroy(hdr->b_buf, FALSE, TRUE);
14331544Seschrock 		}
1434789Sahrens 	}
14353093Sahrens 	if (hdr->b_freeze_cksum != NULL) {
14363093Sahrens 		kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
14373093Sahrens 		hdr->b_freeze_cksum = NULL;
14383093Sahrens 	}
14391544Seschrock 
1440789Sahrens 	ASSERT(!list_link_active(&hdr->b_arc_node));
1441789Sahrens 	ASSERT3P(hdr->b_hash_next, ==, NULL);
1442789Sahrens 	ASSERT3P(hdr->b_acb, ==, NULL);
1443789Sahrens 	kmem_cache_free(hdr_cache, hdr);
1444789Sahrens }
1445789Sahrens 
1446789Sahrens void
1447789Sahrens arc_buf_free(arc_buf_t *buf, void *tag)
1448789Sahrens {
1449789Sahrens 	arc_buf_hdr_t *hdr = buf->b_hdr;
14503403Sbmc 	int hashed = hdr->b_state != arc_anon;
14511544Seschrock 
14521544Seschrock 	ASSERT(buf->b_efunc == NULL);
14531544Seschrock 	ASSERT(buf->b_data != NULL);
14541544Seschrock 
14551544Seschrock 	if (hashed) {
14561544Seschrock 		kmutex_t *hash_lock = HDR_LOCK(hdr);
14571544Seschrock 
14581544Seschrock 		mutex_enter(hash_lock);
14591544Seschrock 		(void) remove_reference(hdr, hash_lock, tag);
14601544Seschrock 		if (hdr->b_datacnt > 1)
14612688Smaybee 			arc_buf_destroy(buf, FALSE, TRUE);
14621544Seschrock 		else
14631544Seschrock 			hdr->b_flags |= ARC_BUF_AVAILABLE;
14641544Seschrock 		mutex_exit(hash_lock);
14651544Seschrock 	} else if (HDR_IO_IN_PROGRESS(hdr)) {
14661544Seschrock 		int destroy_hdr;
14671544Seschrock 		/*
14681544Seschrock 		 * We are in the middle of an async write.  Don't destroy
14691544Seschrock 		 * this buffer unless the write completes before we finish
14701544Seschrock 		 * decrementing the reference count.
14711544Seschrock 		 */
14721544Seschrock 		mutex_enter(&arc_eviction_mtx);
14731544Seschrock 		(void) remove_reference(hdr, NULL, tag);
14741544Seschrock 		ASSERT(refcount_is_zero(&hdr->b_refcnt));
14751544Seschrock 		destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
14761544Seschrock 		mutex_exit(&arc_eviction_mtx);
14771544Seschrock 		if (destroy_hdr)
14781544Seschrock 			arc_hdr_destroy(hdr);
14791544Seschrock 	} else {
14801544Seschrock 		if (remove_reference(hdr, NULL, tag) > 0) {
14811544Seschrock 			ASSERT(HDR_IO_ERROR(hdr));
14822688Smaybee 			arc_buf_destroy(buf, FALSE, TRUE);
14831544Seschrock 		} else {
14841544Seschrock 			arc_hdr_destroy(hdr);
14851544Seschrock 		}
14861544Seschrock 	}
14871544Seschrock }
14881544Seschrock 
14891544Seschrock int
14901544Seschrock arc_buf_remove_ref(arc_buf_t *buf, void* tag)
14911544Seschrock {
14921544Seschrock 	arc_buf_hdr_t *hdr = buf->b_hdr;
1493789Sahrens 	kmutex_t *hash_lock = HDR_LOCK(hdr);
14941544Seschrock 	int no_callback = (buf->b_efunc == NULL);
14951544Seschrock 
14963403Sbmc 	if (hdr->b_state == arc_anon) {
14971544Seschrock 		arc_buf_free(buf, tag);
14981544Seschrock 		return (no_callback);
14991544Seschrock 	}
1500789Sahrens 
1501789Sahrens 	mutex_enter(hash_lock);
15023403Sbmc 	ASSERT(hdr->b_state != arc_anon);
15031544Seschrock 	ASSERT(buf->b_data != NULL);
1504789Sahrens 
15051544Seschrock 	(void) remove_reference(hdr, hash_lock, tag);
15061544Seschrock 	if (hdr->b_datacnt > 1) {
15071544Seschrock 		if (no_callback)
15082688Smaybee 			arc_buf_destroy(buf, FALSE, TRUE);
15091544Seschrock 	} else if (no_callback) {
15101544Seschrock 		ASSERT(hdr->b_buf == buf && buf->b_next == NULL);
15111544Seschrock 		hdr->b_flags |= ARC_BUF_AVAILABLE;
1512789Sahrens 	}
15131544Seschrock 	ASSERT(no_callback || hdr->b_datacnt > 1 ||
15141544Seschrock 	    refcount_is_zero(&hdr->b_refcnt));
1515789Sahrens 	mutex_exit(hash_lock);
15161544Seschrock 	return (no_callback);
1517789Sahrens }
1518789Sahrens 
1519789Sahrens int
1520789Sahrens arc_buf_size(arc_buf_t *buf)
1521789Sahrens {
1522789Sahrens 	return (buf->b_hdr->b_size);
1523789Sahrens }
1524789Sahrens 
1525789Sahrens /*
1526789Sahrens  * Evict buffers from list until we've removed the specified number of
1527789Sahrens  * bytes.  Move the removed buffers to the appropriate evict state.
15282688Smaybee  * If the recycle flag is set, then attempt to "recycle" a buffer:
15292688Smaybee  * - look for a buffer to evict that is `bytes' long.
15302688Smaybee  * - return the data block from this buffer rather than freeing it.
15312688Smaybee  * This flag is used by callers that are trying to make space for a
15322688Smaybee  * new buffer in a full arc cache.
15335642Smaybee  *
15345642Smaybee  * This function makes a "best effort".  It skips over any buffers
15355642Smaybee  * it can't get a hash_lock on, and so may not catch all candidates.
15365642Smaybee  * It may also return without evicting as much space as requested.
1537789Sahrens  */
15382688Smaybee static void *
15398636SMark.Maybee@Sun.COM arc_evict(arc_state_t *state, uint64_t spa, int64_t bytes, boolean_t recycle,
15403290Sjohansen     arc_buf_contents_t type)
1541789Sahrens {
1542789Sahrens 	arc_state_t *evicted_state;
15432688Smaybee 	uint64_t bytes_evicted = 0, skipped = 0, missed = 0;
15442918Smaybee 	arc_buf_hdr_t *ab, *ab_prev = NULL;
15454309Smaybee 	list_t *list = &state->arcs_list[type];
1546789Sahrens 	kmutex_t *hash_lock;
15472688Smaybee 	boolean_t have_lock;
15482918Smaybee 	void *stolen = NULL;
1549789Sahrens 
15503403Sbmc 	ASSERT(state == arc_mru || state == arc_mfu);
1551789Sahrens 
15523403Sbmc 	evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
1553789Sahrens 
15543403Sbmc 	mutex_enter(&state->arcs_mtx);
15553403Sbmc 	mutex_enter(&evicted_state->arcs_mtx);
1556789Sahrens 
15574309Smaybee 	for (ab = list_tail(list); ab; ab = ab_prev) {
15584309Smaybee 		ab_prev = list_prev(list, ab);
15592391Smaybee 		/* prefetch buffers have a minimum lifespan */
15602688Smaybee 		if (HDR_IO_IN_PROGRESS(ab) ||
15615642Smaybee 		    (spa && ab->b_spa != spa) ||
15622688Smaybee 		    (ab->b_flags & (ARC_PREFETCH|ARC_INDIRECT) &&
15632688Smaybee 		    lbolt - ab->b_arc_access < arc_min_prefetch_lifespan)) {
15642391Smaybee 			skipped++;
15652391Smaybee 			continue;
15662391Smaybee 		}
15672918Smaybee 		/* "lookahead" for better eviction candidate */
15682918Smaybee 		if (recycle && ab->b_size != bytes &&
15692918Smaybee 		    ab_prev && ab_prev->b_size == bytes)
15702688Smaybee 			continue;
1571789Sahrens 		hash_lock = HDR_LOCK(ab);
15722688Smaybee 		have_lock = MUTEX_HELD(hash_lock);
15732688Smaybee 		if (have_lock || mutex_tryenter(hash_lock)) {
1574789Sahrens 			ASSERT3U(refcount_count(&ab->b_refcnt), ==, 0);
15751544Seschrock 			ASSERT(ab->b_datacnt > 0);
15761544Seschrock 			while (ab->b_buf) {
15771544Seschrock 				arc_buf_t *buf = ab->b_buf;
15787545SMark.Maybee@Sun.COM 				if (!rw_tryenter(&buf->b_lock, RW_WRITER)) {
15797545SMark.Maybee@Sun.COM 					missed += 1;
15807545SMark.Maybee@Sun.COM 					break;
15817545SMark.Maybee@Sun.COM 				}
15822688Smaybee 				if (buf->b_data) {
15831544Seschrock 					bytes_evicted += ab->b_size;
15843290Sjohansen 					if (recycle && ab->b_type == type &&
15855450Sbrendan 					    ab->b_size == bytes &&
15865450Sbrendan 					    !HDR_L2_WRITING(ab)) {
15872918Smaybee 						stolen = buf->b_data;
15882918Smaybee 						recycle = FALSE;
15892918Smaybee 					}
15902688Smaybee 				}
15911544Seschrock 				if (buf->b_efunc) {
15921544Seschrock 					mutex_enter(&arc_eviction_mtx);
15932918Smaybee 					arc_buf_destroy(buf,
15942918Smaybee 					    buf->b_data == stolen, FALSE);
15951544Seschrock 					ab->b_buf = buf->b_next;
15962887Smaybee 					buf->b_hdr = &arc_eviction_hdr;
15971544Seschrock 					buf->b_next = arc_eviction_list;
15981544Seschrock 					arc_eviction_list = buf;
15991544Seschrock 					mutex_exit(&arc_eviction_mtx);
16007545SMark.Maybee@Sun.COM 					rw_exit(&buf->b_lock);
16011544Seschrock 				} else {
16027545SMark.Maybee@Sun.COM 					rw_exit(&buf->b_lock);
16032918Smaybee 					arc_buf_destroy(buf,
16042918Smaybee 					    buf->b_data == stolen, TRUE);
16051544Seschrock 				}
16061544Seschrock 			}
16077545SMark.Maybee@Sun.COM 			if (ab->b_datacnt == 0) {
16087545SMark.Maybee@Sun.COM 				arc_change_state(evicted_state, ab, hash_lock);
16097545SMark.Maybee@Sun.COM 				ASSERT(HDR_IN_HASH_TABLE(ab));
16107545SMark.Maybee@Sun.COM 				ab->b_flags |= ARC_IN_HASH_TABLE;
16117545SMark.Maybee@Sun.COM 				ab->b_flags &= ~ARC_BUF_AVAILABLE;
16127545SMark.Maybee@Sun.COM 				DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, ab);
16137545SMark.Maybee@Sun.COM 			}
16142688Smaybee 			if (!have_lock)
16152688Smaybee 				mutex_exit(hash_lock);
16161544Seschrock 			if (bytes >= 0 && bytes_evicted >= bytes)
1617789Sahrens 				break;
1618789Sahrens 		} else {
16192688Smaybee 			missed += 1;
1620789Sahrens 		}
1621789Sahrens 	}
16223403Sbmc 
16233403Sbmc 	mutex_exit(&evicted_state->arcs_mtx);
16243403Sbmc 	mutex_exit(&state->arcs_mtx);
1625789Sahrens 
1626789Sahrens 	if (bytes_evicted < bytes)
1627789Sahrens 		dprintf("only evicted %lld bytes from %x",
1628789Sahrens 		    (longlong_t)bytes_evicted, state);
1629789Sahrens 
16302688Smaybee 	if (skipped)
16313403Sbmc 		ARCSTAT_INCR(arcstat_evict_skip, skipped);
16323403Sbmc 
16332688Smaybee 	if (missed)
16343403Sbmc 		ARCSTAT_INCR(arcstat_mutex_miss, missed);
16353403Sbmc 
16364709Smaybee 	/*
16374709Smaybee 	 * We have just evicted some date into the ghost state, make
16384709Smaybee 	 * sure we also adjust the ghost state size if necessary.
16394709Smaybee 	 */
16404709Smaybee 	if (arc_no_grow &&
16414709Smaybee 	    arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size > arc_c) {
16424709Smaybee 		int64_t mru_over = arc_anon->arcs_size + arc_mru->arcs_size +
16434709Smaybee 		    arc_mru_ghost->arcs_size - arc_c;
16444709Smaybee 
16454709Smaybee 		if (mru_over > 0 && arc_mru_ghost->arcs_lsize[type] > 0) {
16464709Smaybee 			int64_t todelete =
16474709Smaybee 			    MIN(arc_mru_ghost->arcs_lsize[type], mru_over);
16485642Smaybee 			arc_evict_ghost(arc_mru_ghost, NULL, todelete);
16494709Smaybee 		} else if (arc_mfu_ghost->arcs_lsize[type] > 0) {
16504709Smaybee 			int64_t todelete = MIN(arc_mfu_ghost->arcs_lsize[type],
16514709Smaybee 			    arc_mru_ghost->arcs_size +
16524709Smaybee 			    arc_mfu_ghost->arcs_size - arc_c);
16535642Smaybee 			arc_evict_ghost(arc_mfu_ghost, NULL, todelete);
16544709Smaybee 		}
16554709Smaybee 	}
16564709Smaybee 
16572918Smaybee 	return (stolen);
1658789Sahrens }
1659789Sahrens 
1660789Sahrens /*
1661789Sahrens  * Remove buffers from list until we've removed the specified number of
1662789Sahrens  * bytes.  Destroy the buffers that are removed.
1663789Sahrens  */
1664789Sahrens static void
16658636SMark.Maybee@Sun.COM arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes)
1666789Sahrens {
1667789Sahrens 	arc_buf_hdr_t *ab, *ab_prev;
16684309Smaybee 	list_t *list = &state->arcs_list[ARC_BUFC_DATA];
1669789Sahrens 	kmutex_t *hash_lock;
16701544Seschrock 	uint64_t bytes_deleted = 0;
16713700Sek110237 	uint64_t bufs_skipped = 0;
1672789Sahrens 
16731544Seschrock 	ASSERT(GHOST_STATE(state));
1674789Sahrens top:
16753403Sbmc 	mutex_enter(&state->arcs_mtx);
16764309Smaybee 	for (ab = list_tail(list); ab; ab = ab_prev) {
16774309Smaybee 		ab_prev = list_prev(list, ab);
16785642Smaybee 		if (spa && ab->b_spa != spa)
16795642Smaybee 			continue;
1680789Sahrens 		hash_lock = HDR_LOCK(ab);
1681789Sahrens 		if (mutex_tryenter(hash_lock)) {
16822391Smaybee 			ASSERT(!HDR_IO_IN_PROGRESS(ab));
16831544Seschrock 			ASSERT(ab->b_buf == NULL);
16843403Sbmc 			ARCSTAT_BUMP(arcstat_deleted);
16851544Seschrock 			bytes_deleted += ab->b_size;
16865450Sbrendan 
16875450Sbrendan 			if (ab->b_l2hdr != NULL) {
16885450Sbrendan 				/*
16895450Sbrendan 				 * This buffer is cached on the 2nd Level ARC;
16905450Sbrendan 				 * don't destroy the header.
16915450Sbrendan 				 */
16925450Sbrendan 				arc_change_state(arc_l2c_only, ab, hash_lock);
16935450Sbrendan 				mutex_exit(hash_lock);
16945450Sbrendan 			} else {
16955450Sbrendan 				arc_change_state(arc_anon, ab, hash_lock);
16965450Sbrendan 				mutex_exit(hash_lock);
16975450Sbrendan 				arc_hdr_destroy(ab);
16985450Sbrendan 			}
16995450Sbrendan 
1700789Sahrens 			DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, ab);
1701789Sahrens 			if (bytes >= 0 && bytes_deleted >= bytes)
1702789Sahrens 				break;
1703789Sahrens 		} else {
1704789Sahrens 			if (bytes < 0) {
17053403Sbmc 				mutex_exit(&state->arcs_mtx);
1706789Sahrens 				mutex_enter(hash_lock);
1707789Sahrens 				mutex_exit(hash_lock);
1708789Sahrens 				goto top;
1709789Sahrens 			}
1710789Sahrens 			bufs_skipped += 1;
1711789Sahrens 		}
1712789Sahrens 	}
17133403Sbmc 	mutex_exit(&state->arcs_mtx);
1714789Sahrens 
17154309Smaybee 	if (list == &state->arcs_list[ARC_BUFC_DATA] &&
17164309Smaybee 	    (bytes < 0 || bytes_deleted < bytes)) {
17174309Smaybee 		list = &state->arcs_list[ARC_BUFC_METADATA];
17184309Smaybee 		goto top;
17194309Smaybee 	}
17204309Smaybee 
1721789Sahrens 	if (bufs_skipped) {
17223403Sbmc 		ARCSTAT_INCR(arcstat_mutex_miss, bufs_skipped);
1723789Sahrens 		ASSERT(bytes >= 0);
1724789Sahrens 	}
1725789Sahrens 
1726789Sahrens 	if (bytes_deleted < bytes)
1727789Sahrens 		dprintf("only deleted %lld bytes from %p",
1728789Sahrens 		    (longlong_t)bytes_deleted, state);
1729789Sahrens }
1730789Sahrens 
1731789Sahrens static void
1732789Sahrens arc_adjust(void)
1733789Sahrens {
17348582SBrendan.Gregg@Sun.COM 	int64_t adjustment, delta;
17358582SBrendan.Gregg@Sun.COM 
17368582SBrendan.Gregg@Sun.COM 	/*
17378582SBrendan.Gregg@Sun.COM 	 * Adjust MRU size
17388582SBrendan.Gregg@Sun.COM 	 */
17398582SBrendan.Gregg@Sun.COM 
17408582SBrendan.Gregg@Sun.COM 	adjustment = MIN(arc_size - arc_c,
17418582SBrendan.Gregg@Sun.COM 	    arc_anon->arcs_size + arc_mru->arcs_size + arc_meta_used - arc_p);
17428582SBrendan.Gregg@Sun.COM 
17438582SBrendan.Gregg@Sun.COM 	if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_DATA] > 0) {
17448582SBrendan.Gregg@Sun.COM 		delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_DATA], adjustment);
17458582SBrendan.Gregg@Sun.COM 		(void) arc_evict(arc_mru, NULL, delta, FALSE, ARC_BUFC_DATA);
17468582SBrendan.Gregg@Sun.COM 		adjustment -= delta;
17474309Smaybee 	}
17484309Smaybee 
17498582SBrendan.Gregg@Sun.COM 	if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_METADATA] > 0) {
17508582SBrendan.Gregg@Sun.COM 		delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_METADATA], adjustment);
17518582SBrendan.Gregg@Sun.COM 		(void) arc_evict(arc_mru, NULL, delta, FALSE,
17525642Smaybee 		    ARC_BUFC_METADATA);
1753789Sahrens 	}
1754789Sahrens 
17558582SBrendan.Gregg@Sun.COM 	/*
17568582SBrendan.Gregg@Sun.COM 	 * Adjust MFU size
17578582SBrendan.Gregg@Sun.COM 	 */
17588582SBrendan.Gregg@Sun.COM 
17598582SBrendan.Gregg@Sun.COM 	adjustment = arc_size - arc_c;
17608582SBrendan.Gregg@Sun.COM 
17618582SBrendan.Gregg@Sun.COM 	if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_DATA] > 0) {
17628582SBrendan.Gregg@Sun.COM 		delta = MIN(adjustment, arc_mfu->arcs_lsize[ARC_BUFC_DATA]);
17638582SBrendan.Gregg@Sun.COM 		(void) arc_evict(arc_mfu, NULL, delta, FALSE, ARC_BUFC_DATA);
17648582SBrendan.Gregg@Sun.COM 		adjustment -= delta;
17658582SBrendan.Gregg@Sun.COM 	}
17668582SBrendan.Gregg@Sun.COM 
17678582SBrendan.Gregg@Sun.COM 	if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_METADATA] > 0) {
17688582SBrendan.Gregg@Sun.COM 		int64_t delta = MIN(adjustment,
17698582SBrendan.Gregg@Sun.COM 		    arc_mfu->arcs_lsize[ARC_BUFC_METADATA]);
17708582SBrendan.Gregg@Sun.COM 		(void) arc_evict(arc_mfu, NULL, delta, FALSE,
17718582SBrendan.Gregg@Sun.COM 		    ARC_BUFC_METADATA);
17728582SBrendan.Gregg@Sun.COM 	}
17738582SBrendan.Gregg@Sun.COM 
17748582SBrendan.Gregg@Sun.COM 	/*
17758582SBrendan.Gregg@Sun.COM 	 * Adjust ghost lists
17768582SBrendan.Gregg@Sun.COM 	 */
17778582SBrendan.Gregg@Sun.COM 
17788582SBrendan.Gregg@Sun.COM 	adjustment = arc_mru->arcs_size + arc_mru_ghost->arcs_size - arc_c;
17798582SBrendan.Gregg@Sun.COM 
17808582SBrendan.Gregg@Sun.COM 	if (adjustment > 0 && arc_mru_ghost->arcs_size > 0) {
17818582SBrendan.Gregg@Sun.COM 		delta = MIN(arc_mru_ghost->arcs_size, adjustment);
17828582SBrendan.Gregg@Sun.COM 		arc_evict_ghost(arc_mru_ghost, NULL, delta);
17838582SBrendan.Gregg@Sun.COM 	}
17848582SBrendan.Gregg@Sun.COM 
17858582SBrendan.Gregg@Sun.COM 	adjustment =
17868582SBrendan.Gregg@Sun.COM 	    arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size - arc_c;
17878582SBrendan.Gregg@Sun.COM 
17888582SBrendan.Gregg@Sun.COM 	if (adjustment > 0 && arc_mfu_ghost->arcs_size > 0) {
17898582SBrendan.Gregg@Sun.COM 		delta = MIN(arc_mfu_ghost->arcs_size, adjustment);
17908582SBrendan.Gregg@Sun.COM 		arc_evict_ghost(arc_mfu_ghost, NULL, delta);
1791789Sahrens 	}
1792789Sahrens }
1793789Sahrens 
17941544Seschrock static void
17951544Seschrock arc_do_user_evicts(void)
17961544Seschrock {
17971544Seschrock 	mutex_enter(&arc_eviction_mtx);
17981544Seschrock 	while (arc_eviction_list != NULL) {
17991544Seschrock 		arc_buf_t *buf = arc_eviction_list;
18001544Seschrock 		arc_eviction_list = buf->b_next;
18017545SMark.Maybee@Sun.COM 		rw_enter(&buf->b_lock, RW_WRITER);
18021544Seschrock 		buf->b_hdr = NULL;
18037545SMark.Maybee@Sun.COM 		rw_exit(&buf->b_lock);
18041544Seschrock 		mutex_exit(&arc_eviction_mtx);
18051544Seschrock 
18061819Smaybee 		if (buf->b_efunc != NULL)
18071819Smaybee 			VERIFY(buf->b_efunc(buf) == 0);
18081544Seschrock 
18091544Seschrock 		buf->b_efunc = NULL;
18101544Seschrock 		buf->b_private = NULL;
18111544Seschrock 		kmem_cache_free(buf_cache, buf);
18121544Seschrock 		mutex_enter(&arc_eviction_mtx);
18131544Seschrock 	}
18141544Seschrock 	mutex_exit(&arc_eviction_mtx);
18151544Seschrock }
18161544Seschrock 
1817789Sahrens /*
18185642Smaybee  * Flush all *evictable* data from the cache for the given spa.
1819789Sahrens  * NOTE: this will not touch "active" (i.e. referenced) data.
1820789Sahrens  */
1821789Sahrens void
18225642Smaybee arc_flush(spa_t *spa)
1823789Sahrens {
18248636SMark.Maybee@Sun.COM 	uint64_t guid = 0;
18258636SMark.Maybee@Sun.COM 
18268636SMark.Maybee@Sun.COM 	if (spa)
18278636SMark.Maybee@Sun.COM 		guid = spa_guid(spa);
18288636SMark.Maybee@Sun.COM 
18295642Smaybee 	while (list_head(&arc_mru->arcs_list[ARC_BUFC_DATA])) {
18308636SMark.Maybee@Sun.COM 		(void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_DATA);
18315642Smaybee 		if (spa)
18325642Smaybee 			break;
18335642Smaybee 	}
18345642Smaybee 	while (list_head(&arc_mru->arcs_list[ARC_BUFC_METADATA])) {
18358636SMark.Maybee@Sun.COM 		(void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_METADATA);
18365642Smaybee 		if (spa)
18375642Smaybee 			break;
18385642Smaybee 	}
18395642Smaybee 	while (list_head(&arc_mfu->arcs_list[ARC_BUFC_DATA])) {
18408636SMark.Maybee@Sun.COM 		(void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_DATA);
18415642Smaybee 		if (spa)
18425642Smaybee 			break;
18435642Smaybee 	}
18445642Smaybee 	while (list_head(&arc_mfu->arcs_list[ARC_BUFC_METADATA])) {
18458636SMark.Maybee@Sun.COM 		(void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_METADATA);
18465642Smaybee 		if (spa)
18475642Smaybee 			break;
18485642Smaybee 	}
18495642Smaybee 
18508636SMark.Maybee@Sun.COM 	arc_evict_ghost(arc_mru_ghost, guid, -1);
18518636SMark.Maybee@Sun.COM 	arc_evict_ghost(arc_mfu_ghost, guid, -1);
18521544Seschrock 
18531544Seschrock 	mutex_enter(&arc_reclaim_thr_lock);
18541544Seschrock 	arc_do_user_evicts();
18551544Seschrock 	mutex_exit(&arc_reclaim_thr_lock);
18565642Smaybee 	ASSERT(spa || arc_eviction_list == NULL);
1857789Sahrens }
1858789Sahrens 
1859789Sahrens void
18603158Smaybee arc_shrink(void)
1861789Sahrens {
18623403Sbmc 	if (arc_c > arc_c_min) {
18633158Smaybee 		uint64_t to_free;
1864789Sahrens 
18652048Sstans #ifdef _KERNEL
18663403Sbmc 		to_free = MAX(arc_c >> arc_shrink_shift, ptob(needfree));
18672048Sstans #else
18683403Sbmc 		to_free = arc_c >> arc_shrink_shift;
18692048Sstans #endif
18703403Sbmc 		if (arc_c > arc_c_min + to_free)
18713403Sbmc 			atomic_add_64(&arc_c, -to_free);
18723158Smaybee 		else
18733403Sbmc 			arc_c = arc_c_min;
18742048Sstans 
18753403Sbmc 		atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
18763403Sbmc 		if (arc_c > arc_size)
18773403Sbmc 			arc_c = MAX(arc_size, arc_c_min);
18783403Sbmc 		if (arc_p > arc_c)
18793403Sbmc 			arc_p = (arc_c >> 1);
18803403Sbmc 		ASSERT(arc_c >= arc_c_min);
18813403Sbmc 		ASSERT((int64_t)arc_p >= 0);
18823158Smaybee 	}
1883789Sahrens 
18843403Sbmc 	if (arc_size > arc_c)
18853158Smaybee 		arc_adjust();
1886789Sahrens }
1887789Sahrens 
1888789Sahrens static int
1889789Sahrens arc_reclaim_needed(void)
1890789Sahrens {
1891789Sahrens 	uint64_t extra;
1892789Sahrens 
1893789Sahrens #ifdef _KERNEL
18942048Sstans 
18952048Sstans 	if (needfree)
18962048Sstans 		return (1);
18972048Sstans 
1898789Sahrens 	/*
1899789Sahrens 	 * take 'desfree' extra pages, so we reclaim sooner, rather than later
1900789Sahrens 	 */
1901789Sahrens 	extra = desfree;
1902789Sahrens 
1903789Sahrens 	/*
1904789Sahrens 	 * check that we're out of range of the pageout scanner.  It starts to
1905789Sahrens 	 * schedule paging if freemem is less than lotsfree and needfree.
1906789Sahrens 	 * lotsfree is the high-water mark for pageout, and needfree is the
1907789Sahrens 	 * number of needed free pages.  We add extra pages here to make sure
1908789Sahrens 	 * the scanner doesn't start up while we're freeing memory.
1909789Sahrens 	 */
1910789Sahrens 	if (freemem < lotsfree + needfree + extra)
1911789Sahrens 		return (1);
1912789Sahrens 
1913789Sahrens 	/*
1914789Sahrens 	 * check to make sure that swapfs has enough space so that anon
19155450Sbrendan 	 * reservations can still succeed. anon_resvmem() checks that the
1916789Sahrens 	 * availrmem is greater than swapfs_minfree, and the number of reserved
1917789Sahrens 	 * swap pages.  We also add a bit of extra here just to prevent
1918789Sahrens 	 * circumstances from getting really dire.
1919789Sahrens 	 */
1920789Sahrens 	if (availrmem < swapfs_minfree + swapfs_reserve + extra)
1921789Sahrens 		return (1);
1922789Sahrens 
19231936Smaybee #if defined(__i386)
1924789Sahrens 	/*
1925789Sahrens 	 * If we're on an i386 platform, it's possible that we'll exhaust the
1926789Sahrens 	 * kernel heap space before we ever run out of available physical
1927789Sahrens 	 * memory.  Most checks of the size of the heap_area compare against
1928789Sahrens 	 * tune.t_minarmem, which is the minimum available real memory that we
1929789Sahrens 	 * can have in the system.  However, this is generally fixed at 25 pages
1930789Sahrens 	 * which is so low that it's useless.  In this comparison, we seek to
1931789Sahrens 	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
19325450Sbrendan 	 * heap is allocated.  (Or, in the calculation, if less than 1/4th is
1933789Sahrens 	 * free)
1934789Sahrens 	 */
1935789Sahrens 	if (btop(vmem_size(heap_arena, VMEM_FREE)) <
1936789Sahrens 	    (btop(vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC)) >> 2))
1937789Sahrens 		return (1);
1938789Sahrens #endif
1939789Sahrens 
1940789Sahrens #else
1941789Sahrens 	if (spa_get_random(100) == 0)
1942789Sahrens 		return (1);
1943789Sahrens #endif
1944789Sahrens 	return (0);
1945789Sahrens }
1946789Sahrens 
1947789Sahrens static void
1948789Sahrens arc_kmem_reap_now(arc_reclaim_strategy_t strat)
1949789Sahrens {
1950789Sahrens 	size_t			i;
1951789Sahrens 	kmem_cache_t		*prev_cache = NULL;
19523290Sjohansen 	kmem_cache_t		*prev_data_cache = NULL;
1953789Sahrens 	extern kmem_cache_t	*zio_buf_cache[];
19543290Sjohansen 	extern kmem_cache_t	*zio_data_buf_cache[];
1955789Sahrens 
19561484Sek110237 #ifdef _KERNEL
19574309Smaybee 	if (arc_meta_used >= arc_meta_limit) {
19584309Smaybee 		/*
19594309Smaybee 		 * We are exceeding our meta-data cache limit.
19604309Smaybee 		 * Purge some DNLC entries to release holds on meta-data.
19614309Smaybee 		 */
19624309Smaybee 		dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
19634309Smaybee 	}
19641936Smaybee #if defined(__i386)
19651936Smaybee 	/*
19661936Smaybee 	 * Reclaim unused memory from all kmem caches.
19671936Smaybee 	 */
19681936Smaybee 	kmem_reap();
19691936Smaybee #endif
19701484Sek110237 #endif
19711484Sek110237 
1972789Sahrens 	/*
19735450Sbrendan 	 * An aggressive reclamation will shrink the cache size as well as
19741544Seschrock 	 * reap free buffers from the arc kmem caches.
1975789Sahrens 	 */
1976789Sahrens 	if (strat == ARC_RECLAIM_AGGR)
19773158Smaybee 		arc_shrink();
1978789Sahrens 
1979789Sahrens 	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
1980789Sahrens 		if (zio_buf_cache[i] != prev_cache) {
1981789Sahrens 			prev_cache = zio_buf_cache[i];
1982789Sahrens 			kmem_cache_reap_now(zio_buf_cache[i]);
1983789Sahrens 		}
19843290Sjohansen 		if (zio_data_buf_cache[i] != prev_data_cache) {
19853290Sjohansen 			prev_data_cache = zio_data_buf_cache[i];
19863290Sjohansen 			kmem_cache_reap_now(zio_data_buf_cache[i]);
19873290Sjohansen 		}
1988789Sahrens 	}
19891544Seschrock 	kmem_cache_reap_now(buf_cache);
19901544Seschrock 	kmem_cache_reap_now(hdr_cache);
1991789Sahrens }
1992789Sahrens 
1993789Sahrens static void
1994789Sahrens arc_reclaim_thread(void)
1995789Sahrens {
1996789Sahrens 	clock_t			growtime = 0;
1997789Sahrens 	arc_reclaim_strategy_t	last_reclaim = ARC_RECLAIM_CONS;
1998789Sahrens 	callb_cpr_t		cpr;
1999789Sahrens 
2000789Sahrens 	CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
2001789Sahrens 
2002789Sahrens 	mutex_enter(&arc_reclaim_thr_lock);
2003789Sahrens 	while (arc_thread_exit == 0) {
2004789Sahrens 		if (arc_reclaim_needed()) {
2005789Sahrens 
20063403Sbmc 			if (arc_no_grow) {
2007789Sahrens 				if (last_reclaim == ARC_RECLAIM_CONS) {
2008789Sahrens 					last_reclaim = ARC_RECLAIM_AGGR;
2009789Sahrens 				} else {
2010789Sahrens 					last_reclaim = ARC_RECLAIM_CONS;
2011789Sahrens 				}
2012789Sahrens 			} else {
20133403Sbmc 				arc_no_grow = TRUE;
2014789Sahrens 				last_reclaim = ARC_RECLAIM_AGGR;
2015789Sahrens 				membar_producer();
2016789Sahrens 			}
2017789Sahrens 
2018789Sahrens 			/* reset the growth delay for every reclaim */
2019789Sahrens 			growtime = lbolt + (arc_grow_retry * hz);
2020789Sahrens 
2021789Sahrens 			arc_kmem_reap_now(last_reclaim);
20226987Sbrendan 			arc_warm = B_TRUE;
2023789Sahrens 
20244309Smaybee 		} else if (arc_no_grow && lbolt >= growtime) {
20253403Sbmc 			arc_no_grow = FALSE;
2026789Sahrens 		}
2027789Sahrens 
20283403Sbmc 		if (2 * arc_c < arc_size +
20293403Sbmc 		    arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size)
20303298Smaybee 			arc_adjust();
20313298Smaybee 
20321544Seschrock 		if (arc_eviction_list != NULL)
20331544Seschrock 			arc_do_user_evicts();
20341544Seschrock 
2035789Sahrens 		/* block until needed, or one second, whichever is shorter */
2036789Sahrens 		CALLB_CPR_SAFE_BEGIN(&cpr);
2037789Sahrens 		(void) cv_timedwait(&arc_reclaim_thr_cv,
2038789Sahrens 		    &arc_reclaim_thr_lock, (lbolt + hz));
2039789Sahrens 		CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
2040789Sahrens 	}
2041789Sahrens 
2042789Sahrens 	arc_thread_exit = 0;
2043789Sahrens 	cv_broadcast(&arc_reclaim_thr_cv);
2044789Sahrens 	CALLB_CPR_EXIT(&cpr);		/* drops arc_reclaim_thr_lock */
2045789Sahrens 	thread_exit();
2046789Sahrens }
2047789Sahrens 
20481544Seschrock /*
20491544Seschrock  * Adapt arc info given the number of bytes we are trying to add and
20501544Seschrock  * the state that we are comming from.  This function is only called
20511544Seschrock  * when we are adding new content to the cache.
20521544Seschrock  */
2053789Sahrens static void
20541544Seschrock arc_adapt(int bytes, arc_state_t *state)
2055789Sahrens {
20561544Seschrock 	int mult;
20578582SBrendan.Gregg@Sun.COM 	uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
20581544Seschrock 
20595450Sbrendan 	if (state == arc_l2c_only)
20605450Sbrendan 		return;
20615450Sbrendan 
20621544Seschrock 	ASSERT(bytes > 0);
2063789Sahrens 	/*
20641544Seschrock 	 * Adapt the target size of the MRU list:
20651544Seschrock 	 *	- if we just hit in the MRU ghost list, then increase
20661544Seschrock 	 *	  the target size of the MRU list.
20671544Seschrock 	 *	- if we just hit in the MFU ghost list, then increase
20681544Seschrock 	 *	  the target size of the MFU list by decreasing the
20691544Seschrock 	 *	  target size of the MRU list.
2070789Sahrens 	 */
20713403Sbmc 	if (state == arc_mru_ghost) {
20723403Sbmc 		mult = ((arc_mru_ghost->arcs_size >= arc_mfu_ghost->arcs_size) ?
20733403Sbmc 		    1 : (arc_mfu_ghost->arcs_size/arc_mru_ghost->arcs_size));
20741544Seschrock 
20758582SBrendan.Gregg@Sun.COM 		arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
20763403Sbmc 	} else if (state == arc_mfu_ghost) {
20778582SBrendan.Gregg@Sun.COM 		uint64_t delta;
20788582SBrendan.Gregg@Sun.COM 
20793403Sbmc 		mult = ((arc_mfu_ghost->arcs_size >= arc_mru_ghost->arcs_size) ?
20803403Sbmc 		    1 : (arc_mru_ghost->arcs_size/arc_mfu_ghost->arcs_size));
20811544Seschrock 
20828582SBrendan.Gregg@Sun.COM 		delta = MIN(bytes * mult, arc_p);
20838582SBrendan.Gregg@Sun.COM 		arc_p = MAX(arc_p_min, arc_p - delta);
20841544Seschrock 	}
20853403Sbmc 	ASSERT((int64_t)arc_p >= 0);
2086789Sahrens 
2087789Sahrens 	if (arc_reclaim_needed()) {
2088789Sahrens 		cv_signal(&arc_reclaim_thr_cv);
2089789Sahrens 		return;
2090789Sahrens 	}
2091789Sahrens 
20923403Sbmc 	if (arc_no_grow)
2093789Sahrens 		return;
2094789Sahrens 
20953403Sbmc 	if (arc_c >= arc_c_max)
20961544Seschrock 		return;
20971544Seschrock 
2098789Sahrens 	/*
20991544Seschrock 	 * If we're within (2 * maxblocksize) bytes of the target
21001544Seschrock 	 * cache size, increment the target cache size
2101789Sahrens 	 */
21023403Sbmc 	if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
21033403Sbmc 		atomic_add_64(&arc_c, (int64_t)bytes);
21043403Sbmc 		if (arc_c > arc_c_max)
21053403Sbmc 			arc_c = arc_c_max;
21063403Sbmc 		else if (state == arc_anon)
21073403Sbmc 			atomic_add_64(&arc_p, (int64_t)bytes);
21083403Sbmc 		if (arc_p > arc_c)
21093403Sbmc 			arc_p = arc_c;
2110789Sahrens 	}
21113403Sbmc 	ASSERT((int64_t)arc_p >= 0);
2112789Sahrens }
2113789Sahrens 
2114789Sahrens /*
21151544Seschrock  * Check if the cache has reached its limits and eviction is required
21161544Seschrock  * prior to insert.
2117789Sahrens  */
2118789Sahrens static int
21194309Smaybee arc_evict_needed(arc_buf_contents_t type)
2120789Sahrens {
21214309Smaybee 	if (type == ARC_BUFC_METADATA && arc_meta_used >= arc_meta_limit)
21224309Smaybee 		return (1);
21234309Smaybee 
21244309Smaybee #ifdef _KERNEL
21254309Smaybee 	/*
21264309Smaybee 	 * If zio data pages are being allocated out of a separate heap segment,
21274309Smaybee 	 * then enforce that the size of available vmem for this area remains
21284309Smaybee 	 * above about 1/32nd free.
21294309Smaybee 	 */
21304309Smaybee 	if (type == ARC_BUFC_DATA && zio_arena != NULL &&
21314309Smaybee 	    vmem_size(zio_arena, VMEM_FREE) <
21324309Smaybee 	    (vmem_size(zio_arena, VMEM_ALLOC) >> 5))
21334309Smaybee 		return (1);
21344309Smaybee #endif
21354309Smaybee 
2136789Sahrens 	if (arc_reclaim_needed())
2137789Sahrens 		return (1);
2138789Sahrens 
21393403Sbmc 	return (arc_size > arc_c);
2140789Sahrens }
2141789Sahrens 
2142789Sahrens /*
21432688Smaybee  * The buffer, supplied as the first argument, needs a data block.
21442688Smaybee  * So, if we are at cache max, determine which cache should be victimized.
21452688Smaybee  * We have the following cases:
2146789Sahrens  *
21473403Sbmc  * 1. Insert for MRU, p > sizeof(arc_anon + arc_mru) ->
2148789Sahrens  * In this situation if we're out of space, but the resident size of the MFU is
2149789Sahrens  * under the limit, victimize the MFU cache to satisfy this insertion request.
2150789Sahrens  *
21513403Sbmc  * 2. Insert for MRU, p <= sizeof(arc_anon + arc_mru) ->
2152789Sahrens  * Here, we've used up all of the available space for the MRU, so we need to
2153789Sahrens  * evict from our own cache instead.  Evict from the set of resident MRU
2154789Sahrens  * entries.
2155789Sahrens  *
21563403Sbmc  * 3. Insert for MFU (c - p) > sizeof(arc_mfu) ->
2157789Sahrens  * c minus p represents the MFU space in the cache, since p is the size of the
2158789Sahrens  * cache that is dedicated to the MRU.  In this situation there's still space on
2159789Sahrens  * the MFU side, so the MRU side needs to be victimized.
2160789Sahrens  *
21613403Sbmc  * 4. Insert for MFU (c - p) < sizeof(arc_mfu) ->
2162789Sahrens  * MFU's resident set is consuming more space than it has been allotted.  In
2163789Sahrens  * this situation, we must victimize our own cache, the MFU, for this insertion.
2164789Sahrens  */
2165789Sahrens static void
21662688Smaybee arc_get_data_buf(arc_buf_t *buf)
2167789Sahrens {
21683290Sjohansen 	arc_state_t		*state = buf->b_hdr->b_state;
21693290Sjohansen 	uint64_t		size = buf->b_hdr->b_size;
21703290Sjohansen 	arc_buf_contents_t	type = buf->b_hdr->b_type;
21712688Smaybee 
21722688Smaybee 	arc_adapt(size, state);
2173789Sahrens 
21742688Smaybee 	/*
21752688Smaybee 	 * We have not yet reached cache maximum size,
21762688Smaybee 	 * just allocate a new buffer.
21772688Smaybee 	 */
21784309Smaybee 	if (!arc_evict_needed(type)) {
21793290Sjohansen 		if (type == ARC_BUFC_METADATA) {
21803290Sjohansen 			buf->b_data = zio_buf_alloc(size);
21818582SBrendan.Gregg@Sun.COM 			arc_space_consume(size, ARC_SPACE_DATA);
21823290Sjohansen 		} else {
21833290Sjohansen 			ASSERT(type == ARC_BUFC_DATA);
21843290Sjohansen 			buf->b_data = zio_data_buf_alloc(size);
21858582SBrendan.Gregg@Sun.COM 			ARCSTAT_INCR(arcstat_data_size, size);
21864309Smaybee 			atomic_add_64(&arc_size, size);
21873290Sjohansen 		}
21882688Smaybee 		goto out;
21892688Smaybee 	}
21902688Smaybee 
21912688Smaybee 	/*
21922688Smaybee 	 * If we are prefetching from the mfu ghost list, this buffer
21932688Smaybee 	 * will end up on the mru list; so steal space from there.
21942688Smaybee 	 */
21953403Sbmc 	if (state == arc_mfu_ghost)
21963403Sbmc 		state = buf->b_hdr->b_flags & ARC_PREFETCH ? arc_mru : arc_mfu;
21973403Sbmc 	else if (state == arc_mru_ghost)
21983403Sbmc 		state = arc_mru;
2199789Sahrens 
22003403Sbmc 	if (state == arc_mru || state == arc_anon) {
22013403Sbmc 		uint64_t mru_used = arc_anon->arcs_size + arc_mru->arcs_size;
22028582SBrendan.Gregg@Sun.COM 		state = (arc_mfu->arcs_lsize[type] >= size &&
22034309Smaybee 		    arc_p > mru_used) ? arc_mfu : arc_mru;
2204789Sahrens 	} else {
22052688Smaybee 		/* MFU cases */
22063403Sbmc 		uint64_t mfu_space = arc_c - arc_p;
22078582SBrendan.Gregg@Sun.COM 		state =  (arc_mru->arcs_lsize[type] >= size &&
22084309Smaybee 		    mfu_space > arc_mfu->arcs_size) ? arc_mru : arc_mfu;
22092688Smaybee 	}
22105642Smaybee 	if ((buf->b_data = arc_evict(state, NULL, size, TRUE, type)) == NULL) {
22113290Sjohansen 		if (type == ARC_BUFC_METADATA) {
22123290Sjohansen 			buf->b_data = zio_buf_alloc(size);
22138582SBrendan.Gregg@Sun.COM 			arc_space_consume(size, ARC_SPACE_DATA);
22143290Sjohansen 		} else {
22153290Sjohansen 			ASSERT(type == ARC_BUFC_DATA);
22163290Sjohansen 			buf->b_data = zio_data_buf_alloc(size);
22178582SBrendan.Gregg@Sun.COM 			ARCSTAT_INCR(arcstat_data_size, size);
22184309Smaybee 			atomic_add_64(&arc_size, size);
22193290Sjohansen 		}
22203403Sbmc 		ARCSTAT_BUMP(arcstat_recycle_miss);
22212688Smaybee 	}
22222688Smaybee 	ASSERT(buf->b_data != NULL);
22232688Smaybee out:
22242688Smaybee 	/*
22252688Smaybee 	 * Update the state size.  Note that ghost states have a
22262688Smaybee 	 * "ghost size" and so don't need to be updated.
22272688Smaybee 	 */
22282688Smaybee 	if (!GHOST_STATE(buf->b_hdr->b_state)) {
22292688Smaybee 		arc_buf_hdr_t *hdr = buf->b_hdr;
22302688Smaybee 
22313403Sbmc 		atomic_add_64(&hdr->b_state->arcs_size, size);
22322688Smaybee 		if (list_link_active(&hdr->b_arc_node)) {
22332688Smaybee 			ASSERT(refcount_is_zero(&hdr->b_refcnt));
22344309Smaybee 			atomic_add_64(&hdr->b_state->arcs_lsize[type], size);
2235789Sahrens 		}
22363298Smaybee 		/*
22373298Smaybee 		 * If we are growing the cache, and we are adding anonymous
22383403Sbmc 		 * data, and we have outgrown arc_p, update arc_p
22393298Smaybee 		 */
22403403Sbmc 		if (arc_size < arc_c && hdr->b_state == arc_anon &&
22413403Sbmc 		    arc_anon->arcs_size + arc_mru->arcs_size > arc_p)
22423403Sbmc 			arc_p = MIN(arc_c, arc_p + size);
2243789Sahrens 	}
2244789Sahrens }
2245789Sahrens 
2246789Sahrens /*
2247789Sahrens  * This routine is called whenever a buffer is accessed.
22481544Seschrock  * NOTE: the hash lock is dropped in this function.
2249789Sahrens  */
2250789Sahrens static void
22512688Smaybee arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock)
2252789Sahrens {
2253789Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
2254789Sahrens 
22553403Sbmc 	if (buf->b_state == arc_anon) {
2256789Sahrens 		/*
2257789Sahrens 		 * This buffer is not in the cache, and does not
2258789Sahrens 		 * appear in our "ghost" list.  Add the new buffer
2259789Sahrens 		 * to the MRU state.
2260789Sahrens 		 */
2261789Sahrens 
2262789Sahrens 		ASSERT(buf->b_arc_access == 0);
2263789Sahrens 		buf->b_arc_access = lbolt;
22641544Seschrock 		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
22653403Sbmc 		arc_change_state(arc_mru, buf, hash_lock);
2266789Sahrens 
22673403Sbmc 	} else if (buf->b_state == arc_mru) {
2268789Sahrens 		/*
22692391Smaybee 		 * If this buffer is here because of a prefetch, then either:
22702391Smaybee 		 * - clear the flag if this is a "referencing" read
22712391Smaybee 		 *   (any subsequent access will bump this into the MFU state).
22722391Smaybee 		 * or
22732391Smaybee 		 * - move the buffer to the head of the list if this is
22742391Smaybee 		 *   another prefetch (to make it less likely to be evicted).
2275789Sahrens 		 */
2276789Sahrens 		if ((buf->b_flags & ARC_PREFETCH) != 0) {
22772391Smaybee 			if (refcount_count(&buf->b_refcnt) == 0) {
22782391Smaybee 				ASSERT(list_link_active(&buf->b_arc_node));
22792391Smaybee 			} else {
22802391Smaybee 				buf->b_flags &= ~ARC_PREFETCH;
22813403Sbmc 				ARCSTAT_BUMP(arcstat_mru_hits);
22822391Smaybee 			}
22832391Smaybee 			buf->b_arc_access = lbolt;
2284789Sahrens 			return;
2285789Sahrens 		}
2286789Sahrens 
2287789Sahrens 		/*
2288789Sahrens 		 * This buffer has been "accessed" only once so far,
2289789Sahrens 		 * but it is still in the cache. Move it to the MFU
2290789Sahrens 		 * state.
2291789Sahrens 		 */
2292789Sahrens 		if (lbolt > buf->b_arc_access + ARC_MINTIME) {
2293789Sahrens 			/*
2294789Sahrens 			 * More than 125ms have passed since we
2295789Sahrens 			 * instantiated this buffer.  Move it to the
2296789Sahrens 			 * most frequently used state.
2297789Sahrens 			 */
2298789Sahrens 			buf->b_arc_access = lbolt;
22991544Seschrock 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
23003403Sbmc 			arc_change_state(arc_mfu, buf, hash_lock);
2301789Sahrens 		}
23023403Sbmc 		ARCSTAT_BUMP(arcstat_mru_hits);
23033403Sbmc 	} else if (buf->b_state == arc_mru_ghost) {
2304789Sahrens 		arc_state_t	*new_state;
2305789Sahrens 		/*
2306789Sahrens 		 * This buffer has been "accessed" recently, but
2307789Sahrens 		 * was evicted from the cache.  Move it to the
2308789Sahrens 		 * MFU state.
2309789Sahrens 		 */
2310789Sahrens 
2311789Sahrens 		if (buf->b_flags & ARC_PREFETCH) {
23123403Sbmc 			new_state = arc_mru;
23132391Smaybee 			if (refcount_count(&buf->b_refcnt) > 0)
23142391Smaybee 				buf->b_flags &= ~ARC_PREFETCH;
23151544Seschrock 			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2316789Sahrens 		} else {
23173403Sbmc 			new_state = arc_mfu;
23181544Seschrock 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2319789Sahrens 		}
2320789Sahrens 
2321789Sahrens 		buf->b_arc_access = lbolt;
2322789Sahrens 		arc_change_state(new_state, buf, hash_lock);
2323789Sahrens 
23243403Sbmc 		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
23253403Sbmc 	} else if (buf->b_state == arc_mfu) {
2326789Sahrens 		/*
2327789Sahrens 		 * This buffer has been accessed more than once and is
2328789Sahrens 		 * still in the cache.  Keep it in the MFU state.
2329789Sahrens 		 *
23302391Smaybee 		 * NOTE: an add_reference() that occurred when we did
23312391Smaybee 		 * the arc_read() will have kicked this off the list.
23322391Smaybee 		 * If it was a prefetch, we will explicitly move it to
23332391Smaybee 		 * the head of the list now.
2334789Sahrens 		 */
23352391Smaybee 		if ((buf->b_flags & ARC_PREFETCH) != 0) {
23362391Smaybee 			ASSERT(refcount_count(&buf->b_refcnt) == 0);
23372391Smaybee 			ASSERT(list_link_active(&buf->b_arc_node));
23382391Smaybee 		}
23393403Sbmc 		ARCSTAT_BUMP(arcstat_mfu_hits);
23402391Smaybee 		buf->b_arc_access = lbolt;
23413403Sbmc 	} else if (buf->b_state == arc_mfu_ghost) {
23423403Sbmc 		arc_state_t	*new_state = arc_mfu;
2343789Sahrens 		/*
2344789Sahrens 		 * This buffer has been accessed more than once but has
2345789Sahrens 		 * been evicted from the cache.  Move it back to the
2346789Sahrens 		 * MFU state.
2347789Sahrens 		 */
2348789Sahrens 
23492391Smaybee 		if (buf->b_flags & ARC_PREFETCH) {
23502391Smaybee 			/*
23512391Smaybee 			 * This is a prefetch access...
23522391Smaybee 			 * move this block back to the MRU state.
23532391Smaybee 			 */
23542391Smaybee 			ASSERT3U(refcount_count(&buf->b_refcnt), ==, 0);
23553403Sbmc 			new_state = arc_mru;
23562391Smaybee 		}
23572391Smaybee 
2358789Sahrens 		buf->b_arc_access = lbolt;
23591544Seschrock 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
23602391Smaybee 		arc_change_state(new_state, buf, hash_lock);
2361789Sahrens 
23623403Sbmc 		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
23635450Sbrendan 	} else if (buf->b_state == arc_l2c_only) {
23645450Sbrendan 		/*
23655450Sbrendan 		 * This buffer is on the 2nd Level ARC.
23665450Sbrendan 		 */
23675450Sbrendan 
23685450Sbrendan 		buf->b_arc_access = lbolt;
23695450Sbrendan 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
23705450Sbrendan 		arc_change_state(arc_mfu, buf, hash_lock);
2371789Sahrens 	} else {
2372789Sahrens 		ASSERT(!"invalid arc state");
2373789Sahrens 	}
2374789Sahrens }
2375789Sahrens 
2376789Sahrens /* a generic arc_done_func_t which you can use */
2377789Sahrens /* ARGSUSED */
2378789Sahrens void
2379789Sahrens arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
2380789Sahrens {
2381789Sahrens 	bcopy(buf->b_data, arg, buf->b_hdr->b_size);
23821544Seschrock 	VERIFY(arc_buf_remove_ref(buf, arg) == 1);
2383789Sahrens }
2384789Sahrens 
23854309Smaybee /* a generic arc_done_func_t */
2386789Sahrens void
2387789Sahrens arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
2388789Sahrens {
2389789Sahrens 	arc_buf_t **bufp = arg;
2390789Sahrens 	if (zio && zio->io_error) {
23911544Seschrock 		VERIFY(arc_buf_remove_ref(buf, arg) == 1);
2392789Sahrens 		*bufp = NULL;
2393789Sahrens 	} else {
2394789Sahrens 		*bufp = buf;
2395789Sahrens 	}
2396789Sahrens }
2397789Sahrens 
2398789Sahrens static void
2399789Sahrens arc_read_done(zio_t *zio)
2400789Sahrens {
24011589Smaybee 	arc_buf_hdr_t	*hdr, *found;
2402789Sahrens 	arc_buf_t	*buf;
2403789Sahrens 	arc_buf_t	*abuf;	/* buffer we're assigning to callback */
2404789Sahrens 	kmutex_t	*hash_lock;
2405789Sahrens 	arc_callback_t	*callback_list, *acb;
2406789Sahrens 	int		freeable = FALSE;
2407789Sahrens 
2408789Sahrens 	buf = zio->io_private;
2409789Sahrens 	hdr = buf->b_hdr;
2410789Sahrens 
24111589Smaybee 	/*
24121589Smaybee 	 * The hdr was inserted into hash-table and removed from lists
24131589Smaybee 	 * prior to starting I/O.  We should find this header, since
24141589Smaybee 	 * it's in the hash table, and it should be legit since it's
24151589Smaybee 	 * not possible to evict it during the I/O.  The only possible
24161589Smaybee 	 * reason for it not to be found is if we were freed during the
24171589Smaybee 	 * read.
24181589Smaybee 	 */
24198636SMark.Maybee@Sun.COM 	found = buf_hash_find(hdr->b_spa, &hdr->b_dva, hdr->b_birth,
24203093Sahrens 	    &hash_lock);
2421789Sahrens 
24221589Smaybee 	ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) && hash_lock == NULL) ||
24235450Sbrendan 	    (found == hdr && DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
24245450Sbrendan 	    (found == hdr && HDR_L2_READING(hdr)));
24255450Sbrendan 
24266987Sbrendan 	hdr->b_flags &= ~ARC_L2_EVICTED;
24275450Sbrendan 	if (l2arc_noprefetch && (hdr->b_flags & ARC_PREFETCH))
24287237Sek110237 		hdr->b_flags &= ~ARC_L2CACHE;
2429789Sahrens 
2430789Sahrens 	/* byteswap if necessary */
2431789Sahrens 	callback_list = hdr->b_acb;
2432789Sahrens 	ASSERT(callback_list != NULL);
24337046Sahrens 	if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
24347046Sahrens 		arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
24357046Sahrens 		    byteswap_uint64_array :
24367046Sahrens 		    dmu_ot[BP_GET_TYPE(zio->io_bp)].ot_byteswap;
24377046Sahrens 		func(buf->b_data, hdr->b_size);
24387046Sahrens 	}
2439789Sahrens 
24405450Sbrendan 	arc_cksum_compute(buf, B_FALSE);
24413093Sahrens 
2442789Sahrens 	/* create copies of the data buffer for the callers */
2443789Sahrens 	abuf = buf;
2444789Sahrens 	for (acb = callback_list; acb; acb = acb->acb_next) {
2445789Sahrens 		if (acb->acb_done) {
24462688Smaybee 			if (abuf == NULL)
24472688Smaybee 				abuf = arc_buf_clone(buf);
2448789Sahrens 			acb->acb_buf = abuf;
2449789Sahrens 			abuf = NULL;
2450789Sahrens 		}
2451789Sahrens 	}
2452789Sahrens 	hdr->b_acb = NULL;
2453789Sahrens 	hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
24541544Seschrock 	ASSERT(!HDR_BUF_AVAILABLE(hdr));
24551544Seschrock 	if (abuf == buf)
24561544Seschrock 		hdr->b_flags |= ARC_BUF_AVAILABLE;
2457789Sahrens 
2458789Sahrens 	ASSERT(refcount_is_zero(&hdr->b_refcnt) || callback_list != NULL);
2459789Sahrens 
2460789Sahrens 	if (zio->io_error != 0) {
2461789Sahrens 		hdr->b_flags |= ARC_IO_ERROR;
24623403Sbmc 		if (hdr->b_state != arc_anon)
24633403Sbmc 			arc_change_state(arc_anon, hdr, hash_lock);
24641544Seschrock 		if (HDR_IN_HASH_TABLE(hdr))
24651544Seschrock 			buf_hash_remove(hdr);
2466789Sahrens 		freeable = refcount_is_zero(&hdr->b_refcnt);
2467789Sahrens 	}
2468789Sahrens 
24691544Seschrock 	/*
24702391Smaybee 	 * Broadcast before we drop the hash_lock to avoid the possibility
24712391Smaybee 	 * that the hdr (and hence the cv) might be freed before we get to
24722391Smaybee 	 * the cv_broadcast().
24731544Seschrock 	 */
24741544Seschrock 	cv_broadcast(&hdr->b_cv);
24751544Seschrock 
24761589Smaybee 	if (hash_lock) {
2477789Sahrens 		/*
2478789Sahrens 		 * Only call arc_access on anonymous buffers.  This is because
2479789Sahrens 		 * if we've issued an I/O for an evicted buffer, we've already
2480789Sahrens 		 * called arc_access (to prevent any simultaneous readers from
2481789Sahrens 		 * getting confused).
2482789Sahrens 		 */
24833403Sbmc 		if (zio->io_error == 0 && hdr->b_state == arc_anon)
24842688Smaybee 			arc_access(hdr, hash_lock);
24852688Smaybee 		mutex_exit(hash_lock);
2486789Sahrens 	} else {
2487789Sahrens 		/*
2488789Sahrens 		 * This block was freed while we waited for the read to
2489789Sahrens 		 * complete.  It has been removed from the hash table and
2490789Sahrens 		 * moved to the anonymous state (so that it won't show up
2491789Sahrens 		 * in the cache).
2492789Sahrens 		 */
24933403Sbmc 		ASSERT3P(hdr->b_state, ==, arc_anon);
2494789Sahrens 		freeable = refcount_is_zero(&hdr->b_refcnt);
2495789Sahrens 	}
2496789Sahrens 
2497789Sahrens 	/* execute each callback and free its structure */
2498789Sahrens 	while ((acb = callback_list) != NULL) {
2499789Sahrens 		if (acb->acb_done)
2500789Sahrens 			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
2501789Sahrens 
2502789Sahrens 		if (acb->acb_zio_dummy != NULL) {
2503789Sahrens 			acb->acb_zio_dummy->io_error = zio->io_error;
2504789Sahrens 			zio_nowait(acb->acb_zio_dummy);
2505789Sahrens 		}
2506789Sahrens 
2507789Sahrens 		callback_list = acb->acb_next;
2508789Sahrens 		kmem_free(acb, sizeof (arc_callback_t));
2509789Sahrens 	}
2510789Sahrens 
2511789Sahrens 	if (freeable)
25121544Seschrock 		arc_hdr_destroy(hdr);
2513789Sahrens }
2514789Sahrens 
2515789Sahrens /*
2516789Sahrens  * "Read" the block block at the specified DVA (in bp) via the
2517789Sahrens  * cache.  If the block is found in the cache, invoke the provided
2518789Sahrens  * callback immediately and return.  Note that the `zio' parameter
2519789Sahrens  * in the callback will be NULL in this case, since no IO was
2520789Sahrens  * required.  If the block is not in the cache pass the read request
2521789Sahrens  * on to the spa with a substitute callback function, so that the
2522789Sahrens  * requested block will be added to the cache.
2523789Sahrens  *
2524789Sahrens  * If a read request arrives for a block that has a read in-progress,
2525789Sahrens  * either wait for the in-progress read to complete (and return the
2526789Sahrens  * results); or, if this is a read with a "done" func, add a record
2527789Sahrens  * to the read to invoke the "done" func when the read completes,
2528789Sahrens  * and return; or just return.
2529789Sahrens  *
2530789Sahrens  * arc_read_done() will invoke all the requested "done" functions
2531789Sahrens  * for readers of this block.
25327046Sahrens  *
25337046Sahrens  * Normal callers should use arc_read and pass the arc buffer and offset
25347046Sahrens  * for the bp.  But if you know you don't need locking, you can use
25358213SSuhasini.Peddada@Sun.COM  * arc_read_bp.
2536789Sahrens  */
2537789Sahrens int
25387046Sahrens arc_read(zio_t *pio, spa_t *spa, blkptr_t *bp, arc_buf_t *pbuf,
25397237Sek110237     arc_done_func_t *done, void *private, int priority, int zio_flags,
25407046Sahrens     uint32_t *arc_flags, const zbookmark_t *zb)
25417046Sahrens {
25427046Sahrens 	int err;
25437046Sahrens 
25447046Sahrens 	ASSERT(!refcount_is_zero(&pbuf->b_hdr->b_refcnt));
25457046Sahrens 	ASSERT3U((char *)bp - (char *)pbuf->b_data, <, pbuf->b_hdr->b_size);
25467545SMark.Maybee@Sun.COM 	rw_enter(&pbuf->b_lock, RW_READER);
25477046Sahrens 
25487046Sahrens 	err = arc_read_nolock(pio, spa, bp, done, private, priority,
25497237Sek110237 	    zio_flags, arc_flags, zb);
25507545SMark.Maybee@Sun.COM 	rw_exit(&pbuf->b_lock);
25519396SMatthew.Ahrens@Sun.COM 
25527046Sahrens 	return (err);
25537046Sahrens }
25547046Sahrens 
25557046Sahrens int
25567046Sahrens arc_read_nolock(zio_t *pio, spa_t *spa, blkptr_t *bp,
25577237Sek110237     arc_done_func_t *done, void *private, int priority, int zio_flags,
25587046Sahrens     uint32_t *arc_flags, const zbookmark_t *zb)
2559789Sahrens {
2560789Sahrens 	arc_buf_hdr_t *hdr;
2561789Sahrens 	arc_buf_t *buf;
2562789Sahrens 	kmutex_t *hash_lock;
25635450Sbrendan 	zio_t *rzio;
25648636SMark.Maybee@Sun.COM 	uint64_t guid = spa_guid(spa);
2565789Sahrens 
2566789Sahrens top:
25678636SMark.Maybee@Sun.COM 	hdr = buf_hash_find(guid, BP_IDENTITY(bp), bp->blk_birth, &hash_lock);
25681544Seschrock 	if (hdr && hdr->b_datacnt > 0) {
2569789Sahrens 
25702391Smaybee 		*arc_flags |= ARC_CACHED;
25712391Smaybee 
2572789Sahrens 		if (HDR_IO_IN_PROGRESS(hdr)) {
25732391Smaybee 
25742391Smaybee 			if (*arc_flags & ARC_WAIT) {
25752391Smaybee 				cv_wait(&hdr->b_cv, hash_lock);
25762391Smaybee 				mutex_exit(hash_lock);
25772391Smaybee 				goto top;
25782391Smaybee 			}
25792391Smaybee 			ASSERT(*arc_flags & ARC_NOWAIT);
25802391Smaybee 
25812391Smaybee 			if (done) {
2582789Sahrens 				arc_callback_t	*acb = NULL;
2583789Sahrens 
2584789Sahrens 				acb = kmem_zalloc(sizeof (arc_callback_t),
2585789Sahrens 				    KM_SLEEP);
2586789Sahrens 				acb->acb_done = done;
2587789Sahrens 				acb->acb_private = private;
2588789Sahrens 				if (pio != NULL)
2589789Sahrens 					acb->acb_zio_dummy = zio_null(pio,
25908632SBill.Moore@Sun.COM 					    spa, NULL, NULL, NULL, zio_flags);
2591789Sahrens 
2592789Sahrens 				ASSERT(acb->acb_done != NULL);
2593789Sahrens 				acb->acb_next = hdr->b_acb;
2594789Sahrens 				hdr->b_acb = acb;
2595789Sahrens 				add_reference(hdr, hash_lock, private);
2596789Sahrens 				mutex_exit(hash_lock);
2597789Sahrens 				return (0);
2598789Sahrens 			}
2599789Sahrens 			mutex_exit(hash_lock);
2600789Sahrens 			return (0);
2601789Sahrens 		}
2602789Sahrens 
26033403Sbmc 		ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
2604789Sahrens 
26051544Seschrock 		if (done) {
26062688Smaybee 			add_reference(hdr, hash_lock, private);
26071544Seschrock 			/*
26081544Seschrock 			 * If this block is already in use, create a new
26091544Seschrock 			 * copy of the data so that we will be guaranteed
26101544Seschrock 			 * that arc_release() will always succeed.
26111544Seschrock 			 */
26121544Seschrock 			buf = hdr->b_buf;
26131544Seschrock 			ASSERT(buf);
26141544Seschrock 			ASSERT(buf->b_data);
26152688Smaybee 			if (HDR_BUF_AVAILABLE(hdr)) {
26161544Seschrock 				ASSERT(buf->b_efunc == NULL);
26171544Seschrock 				hdr->b_flags &= ~ARC_BUF_AVAILABLE;
26182688Smaybee 			} else {
26192688Smaybee 				buf = arc_buf_clone(buf);
26201544Seschrock 			}
26212391Smaybee 		} else if (*arc_flags & ARC_PREFETCH &&
26222391Smaybee 		    refcount_count(&hdr->b_refcnt) == 0) {
26232391Smaybee 			hdr->b_flags |= ARC_PREFETCH;
2624789Sahrens 		}
2625789Sahrens 		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
26262688Smaybee 		arc_access(hdr, hash_lock);
26277237Sek110237 		if (*arc_flags & ARC_L2CACHE)
26287237Sek110237 			hdr->b_flags |= ARC_L2CACHE;
26292688Smaybee 		mutex_exit(hash_lock);
26303403Sbmc 		ARCSTAT_BUMP(arcstat_hits);
26313403Sbmc 		ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
26323403Sbmc 		    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
26333403Sbmc 		    data, metadata, hits);
26343403Sbmc 
2635789Sahrens 		if (done)
2636789Sahrens 			done(NULL, buf, private);
2637789Sahrens 	} else {
2638789Sahrens 		uint64_t size = BP_GET_LSIZE(bp);
2639789Sahrens 		arc_callback_t	*acb;
26406987Sbrendan 		vdev_t *vd = NULL;
26419215SGeorge.Wilson@Sun.COM 		uint64_t addr;
26428582SBrendan.Gregg@Sun.COM 		boolean_t devw = B_FALSE;
2643789Sahrens 
2644789Sahrens 		if (hdr == NULL) {
2645789Sahrens 			/* this block is not in the cache */
2646789Sahrens 			arc_buf_hdr_t	*exists;
26473290Sjohansen 			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
26483290Sjohansen 			buf = arc_buf_alloc(spa, size, private, type);
2649789Sahrens 			hdr = buf->b_hdr;
2650789Sahrens 			hdr->b_dva = *BP_IDENTITY(bp);
2651789Sahrens 			hdr->b_birth = bp->blk_birth;
2652789Sahrens 			hdr->b_cksum0 = bp->blk_cksum.zc_word[0];
2653789Sahrens 			exists = buf_hash_insert(hdr, &hash_lock);
2654789Sahrens 			if (exists) {
2655789Sahrens 				/* somebody beat us to the hash insert */
2656789Sahrens 				mutex_exit(hash_lock);
2657789Sahrens 				bzero(&hdr->b_dva, sizeof (dva_t));
2658789Sahrens 				hdr->b_birth = 0;
2659789Sahrens 				hdr->b_cksum0 = 0;
26601544Seschrock 				(void) arc_buf_remove_ref(buf, private);
2661789Sahrens 				goto top; /* restart the IO request */
2662789Sahrens 			}
26632391Smaybee 			/* if this is a prefetch, we don't have a reference */
26642391Smaybee 			if (*arc_flags & ARC_PREFETCH) {
26652391Smaybee 				(void) remove_reference(hdr, hash_lock,
26662391Smaybee 				    private);
26672391Smaybee 				hdr->b_flags |= ARC_PREFETCH;
26682391Smaybee 			}
26697237Sek110237 			if (*arc_flags & ARC_L2CACHE)
26707237Sek110237 				hdr->b_flags |= ARC_L2CACHE;
26712391Smaybee 			if (BP_GET_LEVEL(bp) > 0)
26722391Smaybee 				hdr->b_flags |= ARC_INDIRECT;
2673789Sahrens 		} else {
2674789Sahrens 			/* this block is in the ghost cache */
26751544Seschrock 			ASSERT(GHOST_STATE(hdr->b_state));
26761544Seschrock 			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
26772391Smaybee 			ASSERT3U(refcount_count(&hdr->b_refcnt), ==, 0);
26782391Smaybee 			ASSERT(hdr->b_buf == NULL);
2679789Sahrens 
26802391Smaybee 			/* if this is a prefetch, we don't have a reference */
26812391Smaybee 			if (*arc_flags & ARC_PREFETCH)
26822391Smaybee 				hdr->b_flags |= ARC_PREFETCH;
26832391Smaybee 			else
26842391Smaybee 				add_reference(hdr, hash_lock, private);
26857237Sek110237 			if (*arc_flags & ARC_L2CACHE)
26867237Sek110237 				hdr->b_flags |= ARC_L2CACHE;
26876245Smaybee 			buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
26881544Seschrock 			buf->b_hdr = hdr;
26892688Smaybee 			buf->b_data = NULL;
26901544Seschrock 			buf->b_efunc = NULL;
26911544Seschrock 			buf->b_private = NULL;
26921544Seschrock 			buf->b_next = NULL;
26931544Seschrock 			hdr->b_buf = buf;
26942688Smaybee 			arc_get_data_buf(buf);
26951544Seschrock 			ASSERT(hdr->b_datacnt == 0);
26961544Seschrock 			hdr->b_datacnt = 1;
26972391Smaybee 
2698789Sahrens 		}
2699789Sahrens 
2700789Sahrens 		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
2701789Sahrens 		acb->acb_done = done;
2702789Sahrens 		acb->acb_private = private;
2703789Sahrens 
2704789Sahrens 		ASSERT(hdr->b_acb == NULL);
2705789Sahrens 		hdr->b_acb = acb;
2706789Sahrens 		hdr->b_flags |= ARC_IO_IN_PROGRESS;
2707789Sahrens 
2708789Sahrens 		/*
2709789Sahrens 		 * If the buffer has been evicted, migrate it to a present state
2710789Sahrens 		 * before issuing the I/O.  Once we drop the hash-table lock,
2711789Sahrens 		 * the header will be marked as I/O in progress and have an
2712789Sahrens 		 * attached buffer.  At this point, anybody who finds this
2713789Sahrens 		 * buffer ought to notice that it's legit but has a pending I/O.
2714789Sahrens 		 */
2715789Sahrens 
27161544Seschrock 		if (GHOST_STATE(hdr->b_state))
27172688Smaybee 			arc_access(hdr, hash_lock);
2718789Sahrens 
27197754SJeff.Bonwick@Sun.COM 		if (HDR_L2CACHE(hdr) && hdr->b_l2hdr != NULL &&
27207754SJeff.Bonwick@Sun.COM 		    (vd = hdr->b_l2hdr->b_dev->l2ad_vdev) != NULL) {
27218582SBrendan.Gregg@Sun.COM 			devw = hdr->b_l2hdr->b_dev->l2ad_writing;
27226987Sbrendan 			addr = hdr->b_l2hdr->b_daddr;
27237754SJeff.Bonwick@Sun.COM 			/*
27247754SJeff.Bonwick@Sun.COM 			 * Lock out device removal.
27257754SJeff.Bonwick@Sun.COM 			 */
27267754SJeff.Bonwick@Sun.COM 			if (vdev_is_dead(vd) ||
27277754SJeff.Bonwick@Sun.COM 			    !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
27287754SJeff.Bonwick@Sun.COM 				vd = NULL;
27296987Sbrendan 		}
27306987Sbrendan 
27316987Sbrendan 		mutex_exit(hash_lock);
27326987Sbrendan 
2733789Sahrens 		ASSERT3U(hdr->b_size, ==, size);
27341596Sahrens 		DTRACE_PROBE3(arc__miss, blkptr_t *, bp, uint64_t, size,
27351596Sahrens 		    zbookmark_t *, zb);
27363403Sbmc 		ARCSTAT_BUMP(arcstat_misses);
27373403Sbmc 		ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
27383403Sbmc 		    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
27393403Sbmc 		    data, metadata, misses);
27401544Seschrock 
27418582SBrendan.Gregg@Sun.COM 		if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
27426987Sbrendan 			/*
27436987Sbrendan 			 * Read from the L2ARC if the following are true:
27446987Sbrendan 			 * 1. The L2ARC vdev was previously cached.
27456987Sbrendan 			 * 2. This buffer still has L2ARC metadata.
27466987Sbrendan 			 * 3. This buffer isn't currently writing to the L2ARC.
27476987Sbrendan 			 * 4. The L2ARC entry wasn't evicted, which may
27486987Sbrendan 			 *    also have invalidated the vdev.
27498582SBrendan.Gregg@Sun.COM 			 * 5. This isn't prefetch and l2arc_noprefetch is set.
27506987Sbrendan 			 */
27517754SJeff.Bonwick@Sun.COM 			if (hdr->b_l2hdr != NULL &&
27528582SBrendan.Gregg@Sun.COM 			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
27538582SBrendan.Gregg@Sun.COM 			    !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
27545450Sbrendan 				l2arc_read_callback_t *cb;
27555450Sbrendan 
27566643Seschrock 				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
27576643Seschrock 				ARCSTAT_BUMP(arcstat_l2_hits);
27586643Seschrock 
27595450Sbrendan 				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
27605450Sbrendan 				    KM_SLEEP);
27615450Sbrendan 				cb->l2rcb_buf = buf;
27625450Sbrendan 				cb->l2rcb_spa = spa;
27635450Sbrendan 				cb->l2rcb_bp = *bp;
27645450Sbrendan 				cb->l2rcb_zb = *zb;
27657237Sek110237 				cb->l2rcb_flags = zio_flags;
27665450Sbrendan 
27675450Sbrendan 				/*
27687754SJeff.Bonwick@Sun.COM 				 * l2arc read.  The SCL_L2ARC lock will be
27697754SJeff.Bonwick@Sun.COM 				 * released by l2arc_read_done().
27705450Sbrendan 				 */
27715450Sbrendan 				rzio = zio_read_phys(pio, vd, addr, size,
27725450Sbrendan 				    buf->b_data, ZIO_CHECKSUM_OFF,
27737237Sek110237 				    l2arc_read_done, cb, priority, zio_flags |
27747361SBrendan.Gregg@Sun.COM 				    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_CANFAIL |
27757754SJeff.Bonwick@Sun.COM 				    ZIO_FLAG_DONT_PROPAGATE |
27767754SJeff.Bonwick@Sun.COM 				    ZIO_FLAG_DONT_RETRY, B_FALSE);
27775450Sbrendan 				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
27785450Sbrendan 				    zio_t *, rzio);
27798582SBrendan.Gregg@Sun.COM 				ARCSTAT_INCR(arcstat_l2_read_bytes, size);
27806987Sbrendan 
27816987Sbrendan 				if (*arc_flags & ARC_NOWAIT) {
27826987Sbrendan 					zio_nowait(rzio);
27836987Sbrendan 					return (0);
27846987Sbrendan 				}
27856987Sbrendan 
27866987Sbrendan 				ASSERT(*arc_flags & ARC_WAIT);
27876987Sbrendan 				if (zio_wait(rzio) == 0)
27886987Sbrendan 					return (0);
27896987Sbrendan 
27906987Sbrendan 				/* l2arc read error; goto zio_read() */
27915450Sbrendan 			} else {
27925450Sbrendan 				DTRACE_PROBE1(l2arc__miss,
27935450Sbrendan 				    arc_buf_hdr_t *, hdr);
27945450Sbrendan 				ARCSTAT_BUMP(arcstat_l2_misses);
27955450Sbrendan 				if (HDR_L2_WRITING(hdr))
27965450Sbrendan 					ARCSTAT_BUMP(arcstat_l2_rw_clash);
27977754SJeff.Bonwick@Sun.COM 				spa_config_exit(spa, SCL_L2ARC, vd);
27985450Sbrendan 			}
27998582SBrendan.Gregg@Sun.COM 		} else {
28008628SBill.Moore@Sun.COM 			if (vd != NULL)
28018628SBill.Moore@Sun.COM 				spa_config_exit(spa, SCL_L2ARC, vd);
28028582SBrendan.Gregg@Sun.COM 			if (l2arc_ndev != 0) {
28038582SBrendan.Gregg@Sun.COM 				DTRACE_PROBE1(l2arc__miss,
28048582SBrendan.Gregg@Sun.COM 				    arc_buf_hdr_t *, hdr);
28058582SBrendan.Gregg@Sun.COM 				ARCSTAT_BUMP(arcstat_l2_misses);
28068582SBrendan.Gregg@Sun.COM 			}
28075450Sbrendan 		}
28086643Seschrock 
2809789Sahrens 		rzio = zio_read(pio, spa, bp, buf->b_data, size,
28107237Sek110237 		    arc_read_done, buf, priority, zio_flags, zb);
2811789Sahrens 
28122391Smaybee 		if (*arc_flags & ARC_WAIT)
2813789Sahrens 			return (zio_wait(rzio));
2814789Sahrens 
28152391Smaybee 		ASSERT(*arc_flags & ARC_NOWAIT);
2816789Sahrens 		zio_nowait(rzio);
2817789Sahrens 	}
2818789Sahrens 	return (0);
2819789Sahrens }
2820789Sahrens 
2821789Sahrens /*
2822789Sahrens  * arc_read() variant to support pool traversal.  If the block is already
2823789Sahrens  * in the ARC, make a copy of it; otherwise, the caller will do the I/O.
2824789Sahrens  * The idea is that we don't want pool traversal filling up memory, but
2825789Sahrens  * if the ARC already has the data anyway, we shouldn't pay for the I/O.
2826789Sahrens  */
2827789Sahrens int
2828789Sahrens arc_tryread(spa_t *spa, blkptr_t *bp, void *data)
2829789Sahrens {
2830789Sahrens 	arc_buf_hdr_t *hdr;
2831789Sahrens 	kmutex_t *hash_mtx;
28328636SMark.Maybee@Sun.COM 	uint64_t guid = spa_guid(spa);
2833789Sahrens 	int rc = 0;
2834789Sahrens 
28358636SMark.Maybee@Sun.COM 	hdr = buf_hash_find(guid, BP_IDENTITY(bp), bp->blk_birth, &hash_mtx);
2836789Sahrens 
28371544Seschrock 	if (hdr && hdr->b_datacnt > 0 && !HDR_IO_IN_PROGRESS(hdr)) {
28381544Seschrock 		arc_buf_t *buf = hdr->b_buf;
28391544Seschrock 
28401544Seschrock 		ASSERT(buf);
28411544Seschrock 		while (buf->b_data == NULL) {
28421544Seschrock 			buf = buf->b_next;
28431544Seschrock 			ASSERT(buf);
28441544Seschrock 		}
28451544Seschrock 		bcopy(buf->b_data, data, hdr->b_size);
28461544Seschrock 	} else {
2847789Sahrens 		rc = ENOENT;
28481544Seschrock 	}
2849789Sahrens 
2850789Sahrens 	if (hash_mtx)
2851789Sahrens 		mutex_exit(hash_mtx);
2852789Sahrens 
2853789Sahrens 	return (rc);
2854789Sahrens }
2855789Sahrens 
28561544Seschrock void
28571544Seschrock arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
28581544Seschrock {
28591544Seschrock 	ASSERT(buf->b_hdr != NULL);
28603403Sbmc 	ASSERT(buf->b_hdr->b_state != arc_anon);
28611544Seschrock 	ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt) || func == NULL);
28621544Seschrock 	buf->b_efunc = func;
28631544Seschrock 	buf->b_private = private;
28641544Seschrock }
28651544Seschrock 
28661544Seschrock /*
28671544Seschrock  * This is used by the DMU to let the ARC know that a buffer is
28681544Seschrock  * being evicted, so the ARC should clean up.  If this arc buf
28691544Seschrock  * is not yet in the evicted state, it will be put there.
28701544Seschrock  */
28711544Seschrock int
28721544Seschrock arc_buf_evict(arc_buf_t *buf)
28731544Seschrock {
28742887Smaybee 	arc_buf_hdr_t *hdr;
28751544Seschrock 	kmutex_t *hash_lock;
28761544Seschrock 	arc_buf_t **bufp;
28771544Seschrock 
28787545SMark.Maybee@Sun.COM 	rw_enter(&buf->b_lock, RW_WRITER);
28792887Smaybee 	hdr = buf->b_hdr;
28801544Seschrock 	if (hdr == NULL) {
28811544Seschrock 		/*
28821544Seschrock 		 * We are in arc_do_user_evicts().
28831544Seschrock 		 */
28841544Seschrock 		ASSERT(buf->b_data == NULL);
28857545SMark.Maybee@Sun.COM 		rw_exit(&buf->b_lock);
28861544Seschrock 		return (0);
28877545SMark.Maybee@Sun.COM 	} else if (buf->b_data == NULL) {
28887545SMark.Maybee@Sun.COM 		arc_buf_t copy = *buf; /* structure assignment */
28897545SMark.Maybee@Sun.COM 		/*
28907545SMark.Maybee@Sun.COM 		 * We are on the eviction list; process this buffer now
28917545SMark.Maybee@Sun.COM 		 * but let arc_do_user_evicts() do the reaping.
28927545SMark.Maybee@Sun.COM 		 */
28937545SMark.Maybee@Sun.COM 		buf->b_efunc = NULL;
28947545SMark.Maybee@Sun.COM 		rw_exit(&buf->b_lock);
28957545SMark.Maybee@Sun.COM 		VERIFY(copy.b_efunc(&copy) == 0);
28967545SMark.Maybee@Sun.COM 		return (1);
28971544Seschrock 	}
28982887Smaybee 	hash_lock = HDR_LOCK(hdr);
28991544Seschrock 	mutex_enter(hash_lock);
29001544Seschrock 
29012724Smaybee 	ASSERT(buf->b_hdr == hdr);
29022724Smaybee 	ASSERT3U(refcount_count(&hdr->b_refcnt), <, hdr->b_datacnt);
29033403Sbmc 	ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
29041544Seschrock 
29051544Seschrock 	/*
29061544Seschrock 	 * Pull this buffer off of the hdr
29071544Seschrock 	 */
29081544Seschrock 	bufp = &hdr->b_buf;
29091544Seschrock 	while (*bufp != buf)
29101544Seschrock 		bufp = &(*bufp)->b_next;
29111544Seschrock 	*bufp = buf->b_next;
29121544Seschrock 
29131544Seschrock 	ASSERT(buf->b_data != NULL);
29142688Smaybee 	arc_buf_destroy(buf, FALSE, FALSE);
29151544Seschrock 
29161544Seschrock 	if (hdr->b_datacnt == 0) {
29171544Seschrock 		arc_state_t *old_state = hdr->b_state;
29181544Seschrock 		arc_state_t *evicted_state;
29191544Seschrock 
29201544Seschrock 		ASSERT(refcount_is_zero(&hdr->b_refcnt));
29211544Seschrock 
29221544Seschrock 		evicted_state =
29233403Sbmc 		    (old_state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
29241544Seschrock 
29253403Sbmc 		mutex_enter(&old_state->arcs_mtx);
29263403Sbmc 		mutex_enter(&evicted_state->arcs_mtx);
29271544Seschrock 
29281544Seschrock 		arc_change_state(evicted_state, hdr, hash_lock);
29291544Seschrock 		ASSERT(HDR_IN_HASH_TABLE(hdr));
29305450Sbrendan 		hdr->b_flags |= ARC_IN_HASH_TABLE;
29315450Sbrendan 		hdr->b_flags &= ~ARC_BUF_AVAILABLE;
29321544Seschrock 
29333403Sbmc 		mutex_exit(&evicted_state->arcs_mtx);
29343403Sbmc 		mutex_exit(&old_state->arcs_mtx);
29351544Seschrock 	}
29361544Seschrock 	mutex_exit(hash_lock);
29377545SMark.Maybee@Sun.COM 	rw_exit(&buf->b_lock);
29381819Smaybee 
29391544Seschrock 	VERIFY(buf->b_efunc(buf) == 0);
29401544Seschrock 	buf->b_efunc = NULL;
29411544Seschrock 	buf->b_private = NULL;
29421544Seschrock 	buf->b_hdr = NULL;
29431544Seschrock 	kmem_cache_free(buf_cache, buf);
29441544Seschrock 	return (1);
29451544Seschrock }
29461544Seschrock 
2947789Sahrens /*
2948789Sahrens  * Release this buffer from the cache.  This must be done
2949789Sahrens  * after a read and prior to modifying the buffer contents.
2950789Sahrens  * If the buffer has more than one reference, we must make
29517046Sahrens  * a new hdr for the buffer.
2952789Sahrens  */
2953789Sahrens void
2954789Sahrens arc_release(arc_buf_t *buf, void *tag)
2955789Sahrens {
29567545SMark.Maybee@Sun.COM 	arc_buf_hdr_t *hdr;
29577545SMark.Maybee@Sun.COM 	kmutex_t *hash_lock;
29587545SMark.Maybee@Sun.COM 	l2arc_buf_hdr_t *l2hdr;
29595450Sbrendan 	uint64_t buf_size;
29609274SBrendan.Gregg@Sun.COM 	boolean_t released = B_FALSE;
2961789Sahrens 
29627545SMark.Maybee@Sun.COM 	rw_enter(&buf->b_lock, RW_WRITER);
29637545SMark.Maybee@Sun.COM 	hdr = buf->b_hdr;
29647545SMark.Maybee@Sun.COM 
2965789Sahrens 	/* this buffer is not on any list */
2966789Sahrens 	ASSERT(refcount_count(&hdr->b_refcnt) > 0);
29677046Sahrens 	ASSERT(!(hdr->b_flags & ARC_STORED));
2968789Sahrens 
29693403Sbmc 	if (hdr->b_state == arc_anon) {
2970789Sahrens 		/* this buffer is already released */
2971789Sahrens 		ASSERT3U(refcount_count(&hdr->b_refcnt), ==, 1);
2972789Sahrens 		ASSERT(BUF_EMPTY(hdr));
29731544Seschrock 		ASSERT(buf->b_efunc == NULL);
29743093Sahrens 		arc_buf_thaw(buf);
29757545SMark.Maybee@Sun.COM 		rw_exit(&buf->b_lock);
29769274SBrendan.Gregg@Sun.COM 		released = B_TRUE;
29779274SBrendan.Gregg@Sun.COM 	} else {
29789274SBrendan.Gregg@Sun.COM 		hash_lock = HDR_LOCK(hdr);
29799274SBrendan.Gregg@Sun.COM 		mutex_enter(hash_lock);
2980789Sahrens 	}
2981789Sahrens 
29827545SMark.Maybee@Sun.COM 	l2hdr = hdr->b_l2hdr;
29837545SMark.Maybee@Sun.COM 	if (l2hdr) {
29847545SMark.Maybee@Sun.COM 		mutex_enter(&l2arc_buflist_mtx);
29857545SMark.Maybee@Sun.COM 		hdr->b_l2hdr = NULL;
29867545SMark.Maybee@Sun.COM 		buf_size = hdr->b_size;
29877545SMark.Maybee@Sun.COM 	}
29887545SMark.Maybee@Sun.COM 
29899274SBrendan.Gregg@Sun.COM 	if (released)
29909274SBrendan.Gregg@Sun.COM 		goto out;
29919274SBrendan.Gregg@Sun.COM 
29921544Seschrock 	/*
29931544Seschrock 	 * Do we have more than one buf?
29941544Seschrock 	 */
29957545SMark.Maybee@Sun.COM 	if (hdr->b_datacnt > 1) {
2996789Sahrens 		arc_buf_hdr_t *nhdr;
2997789Sahrens 		arc_buf_t **bufp;
2998789Sahrens 		uint64_t blksz = hdr->b_size;
29998636SMark.Maybee@Sun.COM 		uint64_t spa = hdr->b_spa;
30003290Sjohansen 		arc_buf_contents_t type = hdr->b_type;
30015450Sbrendan 		uint32_t flags = hdr->b_flags;
3002789Sahrens 
30037545SMark.Maybee@Sun.COM 		ASSERT(hdr->b_buf != buf || buf->b_next != NULL);
3004789Sahrens 		/*
3005789Sahrens 		 * Pull the data off of this buf and attach it to
3006789Sahrens 		 * a new anonymous buf.
3007789Sahrens 		 */
30081544Seschrock 		(void) remove_reference(hdr, hash_lock, tag);
3009789Sahrens 		bufp = &hdr->b_buf;
30101544Seschrock 		while (*bufp != buf)
3011789Sahrens 			bufp = &(*bufp)->b_next;
3012789Sahrens 		*bufp = (*bufp)->b_next;
30133897Smaybee 		buf->b_next = NULL;
30141544Seschrock 
30153403Sbmc 		ASSERT3U(hdr->b_state->arcs_size, >=, hdr->b_size);
30163403Sbmc 		atomic_add_64(&hdr->b_state->arcs_size, -hdr->b_size);
30171544Seschrock 		if (refcount_is_zero(&hdr->b_refcnt)) {
30184309Smaybee 			uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
30194309Smaybee 			ASSERT3U(*size, >=, hdr->b_size);
30204309Smaybee 			atomic_add_64(size, -hdr->b_size);
30211544Seschrock 		}
30221544Seschrock 		hdr->b_datacnt -= 1;
30233547Smaybee 		arc_cksum_verify(buf);
30241544Seschrock 
3025789Sahrens 		mutex_exit(hash_lock);
3026789Sahrens 
30276245Smaybee 		nhdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
3028789Sahrens 		nhdr->b_size = blksz;
3029789Sahrens 		nhdr->b_spa = spa;
30303290Sjohansen 		nhdr->b_type = type;
3031789Sahrens 		nhdr->b_buf = buf;
30323403Sbmc 		nhdr->b_state = arc_anon;
3033789Sahrens 		nhdr->b_arc_access = 0;
30345450Sbrendan 		nhdr->b_flags = flags & ARC_L2_WRITING;
30355450Sbrendan 		nhdr->b_l2hdr = NULL;
30361544Seschrock 		nhdr->b_datacnt = 1;
30373547Smaybee 		nhdr->b_freeze_cksum = NULL;
30383897Smaybee 		(void) refcount_add(&nhdr->b_refcnt, tag);
3039789Sahrens 		buf->b_hdr = nhdr;
30407545SMark.Maybee@Sun.COM 		rw_exit(&buf->b_lock);
30413403Sbmc 		atomic_add_64(&arc_anon->arcs_size, blksz);
3042789Sahrens 	} else {
30437545SMark.Maybee@Sun.COM 		rw_exit(&buf->b_lock);
30441544Seschrock 		ASSERT(refcount_count(&hdr->b_refcnt) == 1);
3045789Sahrens 		ASSERT(!list_link_active(&hdr->b_arc_node));
3046789Sahrens 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
30473403Sbmc 		arc_change_state(arc_anon, hdr, hash_lock);
3048789Sahrens 		hdr->b_arc_access = 0;
3049789Sahrens 		mutex_exit(hash_lock);
30505450Sbrendan 
3051789Sahrens 		bzero(&hdr->b_dva, sizeof (dva_t));
3052789Sahrens 		hdr->b_birth = 0;
3053789Sahrens 		hdr->b_cksum0 = 0;
30543547Smaybee 		arc_buf_thaw(buf);
3055789Sahrens 	}
30561544Seschrock 	buf->b_efunc = NULL;
30571544Seschrock 	buf->b_private = NULL;
30585450Sbrendan 
30599274SBrendan.Gregg@Sun.COM out:
30605450Sbrendan 	if (l2hdr) {
30615450Sbrendan 		list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
30625450Sbrendan 		kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
30635450Sbrendan 		ARCSTAT_INCR(arcstat_l2_size, -buf_size);
30647545SMark.Maybee@Sun.COM 		mutex_exit(&l2arc_buflist_mtx);
30655450Sbrendan 	}
3066789Sahrens }
3067789Sahrens 
3068789Sahrens int
3069789Sahrens arc_released(arc_buf_t *buf)
3070789Sahrens {
30717545SMark.Maybee@Sun.COM 	int released;
30727545SMark.Maybee@Sun.COM 
30737545SMark.Maybee@Sun.COM 	rw_enter(&buf->b_lock, RW_READER);
30747545SMark.Maybee@Sun.COM 	released = (buf->b_data != NULL && buf->b_hdr->b_state == arc_anon);
30757545SMark.Maybee@Sun.COM 	rw_exit(&buf->b_lock);
30767545SMark.Maybee@Sun.COM 	return (released);
30771544Seschrock }
30781544Seschrock 
30791544Seschrock int
30801544Seschrock arc_has_callback(arc_buf_t *buf)
30811544Seschrock {
30827545SMark.Maybee@Sun.COM 	int callback;
30837545SMark.Maybee@Sun.COM 
30847545SMark.Maybee@Sun.COM 	rw_enter(&buf->b_lock, RW_READER);
30857545SMark.Maybee@Sun.COM 	callback = (buf->b_efunc != NULL);
30867545SMark.Maybee@Sun.COM 	rw_exit(&buf->b_lock);
30877545SMark.Maybee@Sun.COM 	return (callback);
3088789Sahrens }
3089789Sahrens 
30901544Seschrock #ifdef ZFS_DEBUG
30911544Seschrock int
30921544Seschrock arc_referenced(arc_buf_t *buf)
30931544Seschrock {
30947545SMark.Maybee@Sun.COM 	int referenced;
30957545SMark.Maybee@Sun.COM 
30967545SMark.Maybee@Sun.COM 	rw_enter(&buf->b_lock, RW_READER);
30977545SMark.Maybee@Sun.COM 	referenced = (refcount_count(&buf->b_hdr->b_refcnt));
30987545SMark.Maybee@Sun.COM 	rw_exit(&buf->b_lock);
30997545SMark.Maybee@Sun.COM 	return (referenced);
31001544Seschrock }
31011544Seschrock #endif
31021544Seschrock 
3103789Sahrens static void
31043547Smaybee arc_write_ready(zio_t *zio)
31053547Smaybee {
31063547Smaybee 	arc_write_callback_t *callback = zio->io_private;
31073547Smaybee 	arc_buf_t *buf = callback->awcb_buf;
31085329Sgw25295 	arc_buf_hdr_t *hdr = buf->b_hdr;
31095329Sgw25295 
31107754SJeff.Bonwick@Sun.COM 	ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt));
31117754SJeff.Bonwick@Sun.COM 	callback->awcb_ready(zio, buf, callback->awcb_private);
31127754SJeff.Bonwick@Sun.COM 
31135329Sgw25295 	/*
31145329Sgw25295 	 * If the IO is already in progress, then this is a re-write
31157754SJeff.Bonwick@Sun.COM 	 * attempt, so we need to thaw and re-compute the cksum.
31167754SJeff.Bonwick@Sun.COM 	 * It is the responsibility of the callback to handle the
31177754SJeff.Bonwick@Sun.COM 	 * accounting for any re-write attempt.
31185329Sgw25295 	 */
31195329Sgw25295 	if (HDR_IO_IN_PROGRESS(hdr)) {
31205329Sgw25295 		mutex_enter(&hdr->b_freeze_lock);
31215329Sgw25295 		if (hdr->b_freeze_cksum != NULL) {
31225329Sgw25295 			kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
31235329Sgw25295 			hdr->b_freeze_cksum = NULL;
31245329Sgw25295 		}
31255329Sgw25295 		mutex_exit(&hdr->b_freeze_lock);
31265329Sgw25295 	}
31275450Sbrendan 	arc_cksum_compute(buf, B_FALSE);
31285329Sgw25295 	hdr->b_flags |= ARC_IO_IN_PROGRESS;
31293547Smaybee }
31303547Smaybee 
31313547Smaybee static void
3132789Sahrens arc_write_done(zio_t *zio)
3133789Sahrens {
31343547Smaybee 	arc_write_callback_t *callback = zio->io_private;
31353547Smaybee 	arc_buf_t *buf = callback->awcb_buf;
31363547Smaybee 	arc_buf_hdr_t *hdr = buf->b_hdr;
3137789Sahrens 
3138789Sahrens 	hdr->b_acb = NULL;
3139789Sahrens 
3140789Sahrens 	hdr->b_dva = *BP_IDENTITY(zio->io_bp);
3141789Sahrens 	hdr->b_birth = zio->io_bp->blk_birth;
3142789Sahrens 	hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
31431544Seschrock 	/*
31441544Seschrock 	 * If the block to be written was all-zero, we may have
31451544Seschrock 	 * compressed it away.  In this case no write was performed
31461544Seschrock 	 * so there will be no dva/birth-date/checksum.  The buffer
31471544Seschrock 	 * must therefor remain anonymous (and uncached).
31481544Seschrock 	 */
3149789Sahrens 	if (!BUF_EMPTY(hdr)) {
3150789Sahrens 		arc_buf_hdr_t *exists;
3151789Sahrens 		kmutex_t *hash_lock;
3152789Sahrens 
31533093Sahrens 		arc_cksum_verify(buf);
31543093Sahrens 
3155789Sahrens 		exists = buf_hash_insert(hdr, &hash_lock);
3156789Sahrens 		if (exists) {
3157789Sahrens 			/*
3158789Sahrens 			 * This can only happen if we overwrite for
3159789Sahrens 			 * sync-to-convergence, because we remove
3160789Sahrens 			 * buffers from the hash table when we arc_free().
3161789Sahrens 			 */
31627754SJeff.Bonwick@Sun.COM 			ASSERT(zio->io_flags & ZIO_FLAG_IO_REWRITE);
3163789Sahrens 			ASSERT(DVA_EQUAL(BP_IDENTITY(&zio->io_bp_orig),
3164789Sahrens 			    BP_IDENTITY(zio->io_bp)));
3165789Sahrens 			ASSERT3U(zio->io_bp_orig.blk_birth, ==,
3166789Sahrens 			    zio->io_bp->blk_birth);
3167789Sahrens 
3168789Sahrens 			ASSERT(refcount_is_zero(&exists->b_refcnt));
31693403Sbmc 			arc_change_state(arc_anon, exists, hash_lock);
3170789Sahrens 			mutex_exit(hash_lock);
31711544Seschrock 			arc_hdr_destroy(exists);
3172789Sahrens 			exists = buf_hash_insert(hdr, &hash_lock);
3173789Sahrens 			ASSERT3P(exists, ==, NULL);
3174789Sahrens 		}
31751544Seschrock 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
31767046Sahrens 		/* if it's not anon, we are doing a scrub */
31777046Sahrens 		if (hdr->b_state == arc_anon)
31787046Sahrens 			arc_access(hdr, hash_lock);
31792688Smaybee 		mutex_exit(hash_lock);
31803547Smaybee 	} else if (callback->awcb_done == NULL) {
31811544Seschrock 		int destroy_hdr;
31821544Seschrock 		/*
31831544Seschrock 		 * This is an anonymous buffer with no user callback,
31841544Seschrock 		 * destroy it if there are no active references.
31851544Seschrock 		 */
31861544Seschrock 		mutex_enter(&arc_eviction_mtx);
31871544Seschrock 		destroy_hdr = refcount_is_zero(&hdr->b_refcnt);
31881544Seschrock 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
31891544Seschrock 		mutex_exit(&arc_eviction_mtx);
31901544Seschrock 		if (destroy_hdr)
31911544Seschrock 			arc_hdr_destroy(hdr);
31921544Seschrock 	} else {
31931544Seschrock 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3194789Sahrens 	}
31957046Sahrens 	hdr->b_flags &= ~ARC_STORED;
31961544Seschrock 
31973547Smaybee 	if (callback->awcb_done) {
3198789Sahrens 		ASSERT(!refcount_is_zero(&hdr->b_refcnt));
31993547Smaybee 		callback->awcb_done(zio, buf, callback->awcb_private);
3200789Sahrens 	}
3201789Sahrens 
32023547Smaybee 	kmem_free(callback, sizeof (arc_write_callback_t));
3203789Sahrens }
3204789Sahrens 
32057872STim.Haley@Sun.COM void
32067754SJeff.Bonwick@Sun.COM write_policy(spa_t *spa, const writeprops_t *wp, zio_prop_t *zp)
32077046Sahrens {
32087046Sahrens 	boolean_t ismd = (wp->wp_level > 0 || dmu_ot[wp->wp_type].ot_metadata);
32097046Sahrens 
32107046Sahrens 	/* Determine checksum setting */
32117046Sahrens 	if (ismd) {
32127046Sahrens 		/*
32137046Sahrens 		 * Metadata always gets checksummed.  If the data
32147046Sahrens 		 * checksum is multi-bit correctable, and it's not a
32157046Sahrens 		 * ZBT-style checksum, then it's suitable for metadata
32167046Sahrens 		 * as well.  Otherwise, the metadata checksum defaults
32177046Sahrens 		 * to fletcher4.
32187046Sahrens 		 */
32197046Sahrens 		if (zio_checksum_table[wp->wp_oschecksum].ci_correctable &&
32207046Sahrens 		    !zio_checksum_table[wp->wp_oschecksum].ci_zbt)
32217754SJeff.Bonwick@Sun.COM 			zp->zp_checksum = wp->wp_oschecksum;
32227046Sahrens 		else
32237754SJeff.Bonwick@Sun.COM 			zp->zp_checksum = ZIO_CHECKSUM_FLETCHER_4;
32247046Sahrens 	} else {
32257754SJeff.Bonwick@Sun.COM 		zp->zp_checksum = zio_checksum_select(wp->wp_dnchecksum,
32267046Sahrens 		    wp->wp_oschecksum);
32277046Sahrens 	}
32287046Sahrens 
32297046Sahrens 	/* Determine compression setting */
32307046Sahrens 	if (ismd) {
32317046Sahrens 		/*
32327046Sahrens 		 * XXX -- we should design a compression algorithm
32337046Sahrens 		 * that specializes in arrays of bps.
32347046Sahrens 		 */
32357754SJeff.Bonwick@Sun.COM 		zp->zp_compress = zfs_mdcomp_disable ? ZIO_COMPRESS_EMPTY :
32367046Sahrens 		    ZIO_COMPRESS_LZJB;
32377046Sahrens 	} else {
32387754SJeff.Bonwick@Sun.COM 		zp->zp_compress = zio_compress_select(wp->wp_dncompress,
32397046Sahrens 		    wp->wp_oscompress);
32407046Sahrens 	}
32417754SJeff.Bonwick@Sun.COM 
32427754SJeff.Bonwick@Sun.COM 	zp->zp_type = wp->wp_type;
32437754SJeff.Bonwick@Sun.COM 	zp->zp_level = wp->wp_level;
32447754SJeff.Bonwick@Sun.COM 	zp->zp_ndvas = MIN(wp->wp_copies + ismd, spa_max_replication(spa));
32457046Sahrens }
32467046Sahrens 
32473547Smaybee zio_t *
32487046Sahrens arc_write(zio_t *pio, spa_t *spa, const writeprops_t *wp,
32497237Sek110237     boolean_t l2arc, uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
32503547Smaybee     arc_done_func_t *ready, arc_done_func_t *done, void *private, int priority,
32517237Sek110237     int zio_flags, const zbookmark_t *zb)
3252789Sahrens {
3253789Sahrens 	arc_buf_hdr_t *hdr = buf->b_hdr;
32543547Smaybee 	arc_write_callback_t *callback;
32557754SJeff.Bonwick@Sun.COM 	zio_t *zio;
32567754SJeff.Bonwick@Sun.COM 	zio_prop_t zp;
32577754SJeff.Bonwick@Sun.COM 
32587754SJeff.Bonwick@Sun.COM 	ASSERT(ready != NULL);
3259789Sahrens 	ASSERT(!HDR_IO_ERROR(hdr));
32602237Smaybee 	ASSERT((hdr->b_flags & ARC_IO_IN_PROGRESS) == 0);
32612237Smaybee 	ASSERT(hdr->b_acb == 0);
32627237Sek110237 	if (l2arc)
32637237Sek110237 		hdr->b_flags |= ARC_L2CACHE;
32643547Smaybee 	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
32653547Smaybee 	callback->awcb_ready = ready;
32663547Smaybee 	callback->awcb_done = done;
32673547Smaybee 	callback->awcb_private = private;
32683547Smaybee 	callback->awcb_buf = buf;
32697046Sahrens 
32707754SJeff.Bonwick@Sun.COM 	write_policy(spa, wp, &zp);
32717754SJeff.Bonwick@Sun.COM 	zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, &zp,
32727754SJeff.Bonwick@Sun.COM 	    arc_write_ready, arc_write_done, callback, priority, zio_flags, zb);
3273789Sahrens 
32743547Smaybee 	return (zio);
3275789Sahrens }
3276789Sahrens 
3277789Sahrens int
3278789Sahrens arc_free(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
3279789Sahrens     zio_done_func_t *done, void *private, uint32_t arc_flags)
3280789Sahrens {
3281789Sahrens 	arc_buf_hdr_t *ab;
3282789Sahrens 	kmutex_t *hash_lock;
3283789Sahrens 	zio_t	*zio;
32848636SMark.Maybee@Sun.COM 	uint64_t guid = spa_guid(spa);
3285789Sahrens 
3286789Sahrens 	/*
3287789Sahrens 	 * If this buffer is in the cache, release it, so it
3288789Sahrens 	 * can be re-used.
3289789Sahrens 	 */
32908636SMark.Maybee@Sun.COM 	ab = buf_hash_find(guid, BP_IDENTITY(bp), bp->blk_birth, &hash_lock);
3291789Sahrens 	if (ab != NULL) {
3292789Sahrens 		/*
3293789Sahrens 		 * The checksum of blocks to free is not always
3294789Sahrens 		 * preserved (eg. on the deadlist).  However, if it is
3295789Sahrens 		 * nonzero, it should match what we have in the cache.
3296789Sahrens 		 */
3297789Sahrens 		ASSERT(bp->blk_cksum.zc_word[0] == 0 ||
32987754SJeff.Bonwick@Sun.COM 		    bp->blk_cksum.zc_word[0] == ab->b_cksum0 ||
32997754SJeff.Bonwick@Sun.COM 		    bp->blk_fill == BLK_FILL_ALREADY_FREED);
33007754SJeff.Bonwick@Sun.COM 
33013403Sbmc 		if (ab->b_state != arc_anon)
33023403Sbmc 			arc_change_state(arc_anon, ab, hash_lock);
33032391Smaybee 		if (HDR_IO_IN_PROGRESS(ab)) {
33042391Smaybee 			/*
33052391Smaybee 			 * This should only happen when we prefetch.
33062391Smaybee 			 */
33072391Smaybee 			ASSERT(ab->b_flags & ARC_PREFETCH);
33082391Smaybee 			ASSERT3U(ab->b_datacnt, ==, 1);
33092391Smaybee 			ab->b_flags |= ARC_FREED_IN_READ;
33102391Smaybee 			if (HDR_IN_HASH_TABLE(ab))
33112391Smaybee 				buf_hash_remove(ab);
33122391Smaybee 			ab->b_arc_access = 0;
33132391Smaybee 			bzero(&ab->b_dva, sizeof (dva_t));
33142391Smaybee 			ab->b_birth = 0;
33152391Smaybee 			ab->b_cksum0 = 0;
33162391Smaybee 			ab->b_buf->b_efunc = NULL;
33172391Smaybee 			ab->b_buf->b_private = NULL;
33182391Smaybee 			mutex_exit(hash_lock);
33192391Smaybee 		} else if (refcount_is_zero(&ab->b_refcnt)) {
33205450Sbrendan 			ab->b_flags |= ARC_FREE_IN_PROGRESS;
3321789Sahrens 			mutex_exit(hash_lock);
33221544Seschrock 			arc_hdr_destroy(ab);
33233403Sbmc 			ARCSTAT_BUMP(arcstat_deleted);
3324789Sahrens 		} else {
33251589Smaybee 			/*
33262391Smaybee 			 * We still have an active reference on this
33272391Smaybee 			 * buffer.  This can happen, e.g., from
33282391Smaybee 			 * dbuf_unoverride().
33291589Smaybee 			 */
33302391Smaybee 			ASSERT(!HDR_IN_HASH_TABLE(ab));
3331789Sahrens 			ab->b_arc_access = 0;
3332789Sahrens 			bzero(&ab->b_dva, sizeof (dva_t));
3333789Sahrens 			ab->b_birth = 0;
3334789Sahrens 			ab->b_cksum0 = 0;
33351544Seschrock 			ab->b_buf->b_efunc = NULL;
33361544Seschrock 			ab->b_buf->b_private = NULL;
3337789Sahrens 			mutex_exit(hash_lock);
3338789Sahrens 		}
3339789Sahrens 	}
3340789Sahrens 
33417754SJeff.Bonwick@Sun.COM 	zio = zio_free(pio, spa, txg, bp, done, private, ZIO_FLAG_MUSTSUCCEED);
3342789Sahrens 
3343789Sahrens 	if (arc_flags & ARC_WAIT)
3344789Sahrens 		return (zio_wait(zio));
3345789Sahrens 
3346789Sahrens 	ASSERT(arc_flags & ARC_NOWAIT);
3347789Sahrens 	zio_nowait(zio);
3348789Sahrens 
3349789Sahrens 	return (0);
3350789Sahrens }
3351789Sahrens 
33526245Smaybee static int
3353*9412SAleksandr.Guzovskiy@Sun.COM arc_memory_throttle(uint64_t reserve, uint64_t inflight_data, uint64_t txg)
33546245Smaybee {
33556245Smaybee #ifdef _KERNEL
33566245Smaybee 	uint64_t available_memory = ptob(freemem);
33576245Smaybee 	static uint64_t page_load = 0;
33586245Smaybee 	static uint64_t last_txg = 0;
33596245Smaybee 
33606245Smaybee #if defined(__i386)
33616245Smaybee 	available_memory =
33626245Smaybee 	    MIN(available_memory, vmem_size(heap_arena, VMEM_FREE));
33636245Smaybee #endif
33646245Smaybee 	if (available_memory >= zfs_write_limit_max)
33656245Smaybee 		return (0);
33666245Smaybee 
33676245Smaybee 	if (txg > last_txg) {
33686245Smaybee 		last_txg = txg;
33696245Smaybee 		page_load = 0;
33706245Smaybee 	}
33716245Smaybee 	/*
33726245Smaybee 	 * If we are in pageout, we know that memory is already tight,
33736245Smaybee 	 * the arc is already going to be evicting, so we just want to
33746245Smaybee 	 * continue to let page writes occur as quickly as possible.
33756245Smaybee 	 */
33766245Smaybee 	if (curproc == proc_pageout) {
33776245Smaybee 		if (page_load > MAX(ptob(minfree), available_memory) / 4)
33786245Smaybee 			return (ERESTART);
33796245Smaybee 		/* Note: reserve is inflated, so we deflate */
33806245Smaybee 		page_load += reserve / 8;
33816245Smaybee 		return (0);
33826245Smaybee 	} else if (page_load > 0 && arc_reclaim_needed()) {
33836245Smaybee 		/* memory is low, delay before restarting */
33846245Smaybee 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
33856245Smaybee 		return (EAGAIN);
33866245Smaybee 	}
33876245Smaybee 	page_load = 0;
33886245Smaybee 
33896245Smaybee 	if (arc_size > arc_c_min) {
33906245Smaybee 		uint64_t evictable_memory =
33916245Smaybee 		    arc_mru->arcs_lsize[ARC_BUFC_DATA] +
33926245Smaybee 		    arc_mru->arcs_lsize[ARC_BUFC_METADATA] +
33936245Smaybee 		    arc_mfu->arcs_lsize[ARC_BUFC_DATA] +
33946245Smaybee 		    arc_mfu->arcs_lsize[ARC_BUFC_METADATA];
33956245Smaybee 		available_memory += MIN(evictable_memory, arc_size - arc_c_min);
33966245Smaybee 	}
33976245Smaybee 
33986245Smaybee 	if (inflight_data > available_memory / 4) {
33996245Smaybee 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
34006245Smaybee 		return (ERESTART);
34016245Smaybee 	}
34026245Smaybee #endif
34036245Smaybee 	return (0);
34046245Smaybee }
34056245Smaybee 
3406789Sahrens void
34076245Smaybee arc_tempreserve_clear(uint64_t reserve)
3408789Sahrens {
34096245Smaybee 	atomic_add_64(&arc_tempreserve, -reserve);
3410789Sahrens 	ASSERT((int64_t)arc_tempreserve >= 0);
3411789Sahrens }
3412789Sahrens 
3413789Sahrens int
34146245Smaybee arc_tempreserve_space(uint64_t reserve, uint64_t txg)
3415789Sahrens {
34166245Smaybee 	int error;
3417*9412SAleksandr.Guzovskiy@Sun.COM 	uint64_t anon_size;
34186245Smaybee 
3419789Sahrens #ifdef ZFS_DEBUG
3420789Sahrens 	/*
3421789Sahrens 	 * Once in a while, fail for no reason.  Everything should cope.
3422789Sahrens 	 */
3423789Sahrens 	if (spa_get_random(10000) == 0) {
3424789Sahrens 		dprintf("forcing random failure\n");
3425789Sahrens 		return (ERESTART);
3426789Sahrens 	}
3427789Sahrens #endif
34286245Smaybee 	if (reserve > arc_c/4 && !arc_no_grow)
34296245Smaybee 		arc_c = MIN(arc_c_max, reserve * 4);
34306245Smaybee 	if (reserve > arc_c)
3431982Smaybee 		return (ENOMEM);
3432982Smaybee 
3433789Sahrens 	/*
3434*9412SAleksandr.Guzovskiy@Sun.COM 	 * Don't count loaned bufs as in flight dirty data to prevent long
3435*9412SAleksandr.Guzovskiy@Sun.COM 	 * network delays from blocking transactions that are ready to be
3436*9412SAleksandr.Guzovskiy@Sun.COM 	 * assigned to a txg.
3437*9412SAleksandr.Guzovskiy@Sun.COM 	 */
3438*9412SAleksandr.Guzovskiy@Sun.COM 	anon_size = MAX((int64_t)(arc_anon->arcs_size - arc_loaned_bytes), 0);
3439*9412SAleksandr.Guzovskiy@Sun.COM 
3440*9412SAleksandr.Guzovskiy@Sun.COM 	/*
34416245Smaybee 	 * Writes will, almost always, require additional memory allocations
34426245Smaybee 	 * in order to compress/encrypt/etc the data.  We therefor need to
34436245Smaybee 	 * make sure that there is sufficient available memory for this.
34446245Smaybee 	 */
3445*9412SAleksandr.Guzovskiy@Sun.COM 	if (error = arc_memory_throttle(reserve, anon_size, txg))
34466245Smaybee 		return (error);
34476245Smaybee 
34486245Smaybee 	/*
3449982Smaybee 	 * Throttle writes when the amount of dirty data in the cache
3450982Smaybee 	 * gets too large.  We try to keep the cache less than half full
3451982Smaybee 	 * of dirty blocks so that our sync times don't grow too large.
3452982Smaybee 	 * Note: if two requests come in concurrently, we might let them
3453982Smaybee 	 * both succeed, when one of them should fail.  Not a huge deal.
3454789Sahrens 	 */
3455*9412SAleksandr.Guzovskiy@Sun.COM 
3456*9412SAleksandr.Guzovskiy@Sun.COM 	if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
3457*9412SAleksandr.Guzovskiy@Sun.COM 	    anon_size > arc_c / 4) {
34584309Smaybee 		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
34594309Smaybee 		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
34604309Smaybee 		    arc_tempreserve>>10,
34614309Smaybee 		    arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
34624309Smaybee 		    arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
34636245Smaybee 		    reserve>>10, arc_c>>10);
3464789Sahrens 		return (ERESTART);
3465789Sahrens 	}
34666245Smaybee 	atomic_add_64(&arc_tempreserve, reserve);
3467789Sahrens 	return (0);
3468789Sahrens }
3469789Sahrens 
3470789Sahrens void
3471789Sahrens arc_init(void)
3472789Sahrens {
3473789Sahrens 	mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
3474789Sahrens 	cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
3475789Sahrens 
34762391Smaybee 	/* Convert seconds to clock ticks */
34772638Sperrin 	arc_min_prefetch_lifespan = 1 * hz;
34782391Smaybee 
3479789Sahrens 	/* Start out with 1/8 of all memory */
34803403Sbmc 	arc_c = physmem * PAGESIZE / 8;
3481789Sahrens 
3482789Sahrens #ifdef _KERNEL
3483789Sahrens 	/*
3484789Sahrens 	 * On architectures where the physical memory can be larger
3485789Sahrens 	 * than the addressable space (intel in 32-bit mode), we may
3486789Sahrens 	 * need to limit the cache to 1/8 of VM size.
3487789Sahrens 	 */
34883403Sbmc 	arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
3489789Sahrens #endif
3490789Sahrens 
3491982Smaybee 	/* set min cache to 1/32 of all memory, or 64MB, whichever is more */
34923403Sbmc 	arc_c_min = MAX(arc_c / 4, 64<<20);
3493982Smaybee 	/* set max to 3/4 of all memory, or all but 1GB, whichever is more */
34943403Sbmc 	if (arc_c * 8 >= 1<<30)
34953403Sbmc 		arc_c_max = (arc_c * 8) - (1<<30);
3496789Sahrens 	else
34973403Sbmc 		arc_c_max = arc_c_min;
34983403Sbmc 	arc_c_max = MAX(arc_c * 6, arc_c_max);
34992885Sahrens 
35002885Sahrens 	/*
35012885Sahrens 	 * Allow the tunables to override our calculations if they are
35022885Sahrens 	 * reasonable (ie. over 64MB)
35032885Sahrens 	 */
35042885Sahrens 	if (zfs_arc_max > 64<<20 && zfs_arc_max < physmem * PAGESIZE)
35053403Sbmc 		arc_c_max = zfs_arc_max;
35063403Sbmc 	if (zfs_arc_min > 64<<20 && zfs_arc_min <= arc_c_max)
35073403Sbmc 		arc_c_min = zfs_arc_min;
35082885Sahrens 
35093403Sbmc 	arc_c = arc_c_max;
35103403Sbmc 	arc_p = (arc_c >> 1);
3511789Sahrens 
35124309Smaybee 	/* limit meta-data to 1/4 of the arc capacity */
35134309Smaybee 	arc_meta_limit = arc_c_max / 4;
35144645Sek110237 
35154645Sek110237 	/* Allow the tunable to override if it is reasonable */
35164645Sek110237 	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
35174645Sek110237 		arc_meta_limit = zfs_arc_meta_limit;
35184645Sek110237 
35194309Smaybee 	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
35204309Smaybee 		arc_c_min = arc_meta_limit / 2;
35214309Smaybee 
35228582SBrendan.Gregg@Sun.COM 	if (zfs_arc_grow_retry > 0)
35238582SBrendan.Gregg@Sun.COM 		arc_grow_retry = zfs_arc_grow_retry;
35248582SBrendan.Gregg@Sun.COM 
35258582SBrendan.Gregg@Sun.COM 	if (zfs_arc_shrink_shift > 0)
35268582SBrendan.Gregg@Sun.COM 		arc_shrink_shift = zfs_arc_shrink_shift;
35278582SBrendan.Gregg@Sun.COM 
35288582SBrendan.Gregg@Sun.COM 	if (zfs_arc_p_min_shift > 0)
35298582SBrendan.Gregg@Sun.COM 		arc_p_min_shift = zfs_arc_p_min_shift;
35308582SBrendan.Gregg@Sun.COM 
3531789Sahrens 	/* if kmem_flags are set, lets try to use less memory */
3532789Sahrens 	if (kmem_debugging())
35333403Sbmc 		arc_c = arc_c / 2;
35343403Sbmc 	if (arc_c < arc_c_min)
35353403Sbmc 		arc_c = arc_c_min;
3536789Sahrens 
35373403Sbmc 	arc_anon = &ARC_anon;
35383403Sbmc 	arc_mru = &ARC_mru;
35393403Sbmc 	arc_mru_ghost = &ARC_mru_ghost;
35403403Sbmc 	arc_mfu = &ARC_mfu;
35413403Sbmc 	arc_mfu_ghost = &ARC_mfu_ghost;
35425450Sbrendan 	arc_l2c_only = &ARC_l2c_only;
35433403Sbmc 	arc_size = 0;
3544789Sahrens 
35453403Sbmc 	mutex_init(&arc_anon->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
35463403Sbmc 	mutex_init(&arc_mru->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
35473403Sbmc 	mutex_init(&arc_mru_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
35483403Sbmc 	mutex_init(&arc_mfu->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
35493403Sbmc 	mutex_init(&arc_mfu_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
35505450Sbrendan 	mutex_init(&arc_l2c_only->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
35512688Smaybee 
35524309Smaybee 	list_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
35534309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35544309Smaybee 	list_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
35554309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35564309Smaybee 	list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
35574309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35584309Smaybee 	list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
35594309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35604309Smaybee 	list_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
35614309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35624309Smaybee 	list_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
35634309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35644309Smaybee 	list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
35654309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35664309Smaybee 	list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
35674309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35685450Sbrendan 	list_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
35695450Sbrendan 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
35705450Sbrendan 	list_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
35715450Sbrendan 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3572789Sahrens 
3573789Sahrens 	buf_init();
3574789Sahrens 
3575789Sahrens 	arc_thread_exit = 0;
35761544Seschrock 	arc_eviction_list = NULL;
35771544Seschrock 	mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
35782887Smaybee 	bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
3579789Sahrens 
35803403Sbmc 	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
35813403Sbmc 	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
35823403Sbmc 
35833403Sbmc 	if (arc_ksp != NULL) {
35843403Sbmc 		arc_ksp->ks_data = &arc_stats;
35853403Sbmc 		kstat_install(arc_ksp);
35863403Sbmc 	}
35873403Sbmc 
3588789Sahrens 	(void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
3589789Sahrens 	    TS_RUN, minclsyspri);
35903158Smaybee 
35913158Smaybee 	arc_dead = FALSE;
35926987Sbrendan 	arc_warm = B_FALSE;
35936245Smaybee 
35946245Smaybee 	if (zfs_write_limit_max == 0)
35957468SMark.Maybee@Sun.COM 		zfs_write_limit_max = ptob(physmem) >> zfs_write_limit_shift;
35966245Smaybee 	else
35976245Smaybee 		zfs_write_limit_shift = 0;
35987468SMark.Maybee@Sun.COM 	mutex_init(&zfs_write_limit_lock, NULL, MUTEX_DEFAULT, NULL);
3599789Sahrens }
3600789Sahrens 
3601789Sahrens void
3602789Sahrens arc_fini(void)
3603789Sahrens {
3604789Sahrens 	mutex_enter(&arc_reclaim_thr_lock);
3605789Sahrens 	arc_thread_exit = 1;
3606789Sahrens 	while (arc_thread_exit != 0)
3607789Sahrens 		cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
3608789Sahrens 	mutex_exit(&arc_reclaim_thr_lock);
3609789Sahrens 
36105642Smaybee 	arc_flush(NULL);
3611789Sahrens 
3612789Sahrens 	arc_dead = TRUE;
3613789Sahrens 
36143403Sbmc 	if (arc_ksp != NULL) {
36153403Sbmc 		kstat_delete(arc_ksp);
36163403Sbmc 		arc_ksp = NULL;
36173403Sbmc 	}
36183403Sbmc 
36191544Seschrock 	mutex_destroy(&arc_eviction_mtx);
3620789Sahrens 	mutex_destroy(&arc_reclaim_thr_lock);
3621789Sahrens 	cv_destroy(&arc_reclaim_thr_cv);
3622789Sahrens 
36234309Smaybee 	list_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
36244309Smaybee 	list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
36254309Smaybee 	list_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
36264309Smaybee 	list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
36274309Smaybee 	list_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
36284309Smaybee 	list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
36294309Smaybee 	list_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
36304309Smaybee 	list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
3631789Sahrens 
36323403Sbmc 	mutex_destroy(&arc_anon->arcs_mtx);
36333403Sbmc 	mutex_destroy(&arc_mru->arcs_mtx);
36343403Sbmc 	mutex_destroy(&arc_mru_ghost->arcs_mtx);
36353403Sbmc 	mutex_destroy(&arc_mfu->arcs_mtx);
36363403Sbmc 	mutex_destroy(&arc_mfu_ghost->arcs_mtx);
36378214SRicardo.M.Correia@Sun.COM 	mutex_destroy(&arc_l2c_only->arcs_mtx);
36382856Snd150628 
36397468SMark.Maybee@Sun.COM 	mutex_destroy(&zfs_write_limit_lock);
36407468SMark.Maybee@Sun.COM 
3641789Sahrens 	buf_fini();
3642*9412SAleksandr.Guzovskiy@Sun.COM 
3643*9412SAleksandr.Guzovskiy@Sun.COM 	ASSERT(arc_loaned_bytes == 0);
3644789Sahrens }
36455450Sbrendan 
36465450Sbrendan /*
36475450Sbrendan  * Level 2 ARC
36485450Sbrendan  *
36495450Sbrendan  * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
36505450Sbrendan  * It uses dedicated storage devices to hold cached data, which are populated
36515450Sbrendan  * using large infrequent writes.  The main role of this cache is to boost
36525450Sbrendan  * the performance of random read workloads.  The intended L2ARC devices
36535450Sbrendan  * include short-stroked disks, solid state disks, and other media with
36545450Sbrendan  * substantially faster read latency than disk.
36555450Sbrendan  *
36565450Sbrendan  *                 +-----------------------+
36575450Sbrendan  *                 |         ARC           |
36585450Sbrendan  *                 +-----------------------+
36595450Sbrendan  *                    |         ^     ^
36605450Sbrendan  *                    |         |     |
36615450Sbrendan  *      l2arc_feed_thread()    arc_read()
36625450Sbrendan  *                    |         |     |
36635450Sbrendan  *                    |  l2arc read   |
36645450Sbrendan  *                    V         |     |
36655450Sbrendan  *               +---------------+    |
36665450Sbrendan  *               |     L2ARC     |    |
36675450Sbrendan  *               +---------------+    |
36685450Sbrendan  *                   |    ^           |
36695450Sbrendan  *          l2arc_write() |           |
36705450Sbrendan  *                   |    |           |
36715450Sbrendan  *                   V    |           |
36725450Sbrendan  *                 +-------+      +-------+
36735450Sbrendan  *                 | vdev  |      | vdev  |
36745450Sbrendan  *                 | cache |      | cache |
36755450Sbrendan  *                 +-------+      +-------+
36765450Sbrendan  *                 +=========+     .-----.
36775450Sbrendan  *                 :  L2ARC  :    |-_____-|
36785450Sbrendan  *                 : devices :    | Disks |
36795450Sbrendan  *                 +=========+    `-_____-'
36805450Sbrendan  *
36815450Sbrendan  * Read requests are satisfied from the following sources, in order:
36825450Sbrendan  *
36835450Sbrendan  *	1) ARC
36845450Sbrendan  *	2) vdev cache of L2ARC devices
36855450Sbrendan  *	3) L2ARC devices
36865450Sbrendan  *	4) vdev cache of disks
36875450Sbrendan  *	5) disks
36885450Sbrendan  *
36895450Sbrendan  * Some L2ARC device types exhibit extremely slow write performance.
36905450Sbrendan  * To accommodate for this there are some significant differences between
36915450Sbrendan  * the L2ARC and traditional cache design:
36925450Sbrendan  *
36935450Sbrendan  * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
36945450Sbrendan  * the ARC behave as usual, freeing buffers and placing headers on ghost
36955450Sbrendan  * lists.  The ARC does not send buffers to the L2ARC during eviction as
36965450Sbrendan  * this would add inflated write latencies for all ARC memory pressure.
36975450Sbrendan  *
36985450Sbrendan  * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
36995450Sbrendan  * It does this by periodically scanning buffers from the eviction-end of
37005450Sbrendan  * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
37015450Sbrendan  * not already there.  It scans until a headroom of buffers is satisfied,
37025450Sbrendan  * which itself is a buffer for ARC eviction.  The thread that does this is
37035450Sbrendan  * l2arc_feed_thread(), illustrated below; example sizes are included to
37045450Sbrendan  * provide a better sense of ratio than this diagram:
37055450Sbrendan  *
37065450Sbrendan  *	       head -->                        tail
37075450Sbrendan  *	        +---------------------+----------+
37085450Sbrendan  *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
37095450Sbrendan  *	        +---------------------+----------+   |   o L2ARC eligible
37105450Sbrendan  *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
37115450Sbrendan  *	        +---------------------+----------+   |
37125450Sbrendan  *	             15.9 Gbytes      ^ 32 Mbytes    |
37135450Sbrendan  *	                           headroom          |
37145450Sbrendan  *	                                      l2arc_feed_thread()
37155450Sbrendan  *	                                             |
37165450Sbrendan  *	                 l2arc write hand <--[oooo]--'
37175450Sbrendan  *	                         |           8 Mbyte
37185450Sbrendan  *	                         |          write max
37195450Sbrendan  *	                         V
37205450Sbrendan  *		  +==============================+
37215450Sbrendan  *	L2ARC dev |####|#|###|###|    |####| ... |
37225450Sbrendan  *	          +==============================+
37235450Sbrendan  *	                     32 Gbytes
37245450Sbrendan  *
37255450Sbrendan  * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
37265450Sbrendan  * evicted, then the L2ARC has cached a buffer much sooner than it probably
37275450Sbrendan  * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
37285450Sbrendan  * safe to say that this is an uncommon case, since buffers at the end of
37295450Sbrendan  * the ARC lists have moved there due to inactivity.
37305450Sbrendan  *
37315450Sbrendan  * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
37325450Sbrendan  * then the L2ARC simply misses copying some buffers.  This serves as a
37335450Sbrendan  * pressure valve to prevent heavy read workloads from both stalling the ARC
37345450Sbrendan  * with waits and clogging the L2ARC with writes.  This also helps prevent
37355450Sbrendan  * the potential for the L2ARC to churn if it attempts to cache content too
37365450Sbrendan  * quickly, such as during backups of the entire pool.
37375450Sbrendan  *
37386987Sbrendan  * 5. After system boot and before the ARC has filled main memory, there are
37396987Sbrendan  * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
37406987Sbrendan  * lists can remain mostly static.  Instead of searching from tail of these
37416987Sbrendan  * lists as pictured, the l2arc_feed_thread() will search from the list heads
37426987Sbrendan  * for eligible buffers, greatly increasing its chance of finding them.
37436987Sbrendan  *
37446987Sbrendan  * The L2ARC device write speed is also boosted during this time so that
37456987Sbrendan  * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
37466987Sbrendan  * there are no L2ARC reads, and no fear of degrading read performance
37476987Sbrendan  * through increased writes.
37486987Sbrendan  *
37496987Sbrendan  * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
37505450Sbrendan  * the vdev queue can aggregate them into larger and fewer writes.  Each
37515450Sbrendan  * device is written to in a rotor fashion, sweeping writes through
37525450Sbrendan  * available space then repeating.
37535450Sbrendan  *
37546987Sbrendan  * 7. The L2ARC does not store dirty content.  It never needs to flush
37555450Sbrendan  * write buffers back to disk based storage.
37565450Sbrendan  *
37576987Sbrendan  * 8. If an ARC buffer is written (and dirtied) which also exists in the
37585450Sbrendan  * L2ARC, the now stale L2ARC buffer is immediately dropped.
37595450Sbrendan  *
37605450Sbrendan  * The performance of the L2ARC can be tweaked by a number of tunables, which
37615450Sbrendan  * may be necessary for different workloads:
37625450Sbrendan  *
37635450Sbrendan  *	l2arc_write_max		max write bytes per interval
37646987Sbrendan  *	l2arc_write_boost	extra write bytes during device warmup
37655450Sbrendan  *	l2arc_noprefetch	skip caching prefetched buffers
37665450Sbrendan  *	l2arc_headroom		number of max device writes to precache
37675450Sbrendan  *	l2arc_feed_secs		seconds between L2ARC writing
37685450Sbrendan  *
37695450Sbrendan  * Tunables may be removed or added as future performance improvements are
37705450Sbrendan  * integrated, and also may become zpool properties.
37718582SBrendan.Gregg@Sun.COM  *
37728582SBrendan.Gregg@Sun.COM  * There are three key functions that control how the L2ARC warms up:
37738582SBrendan.Gregg@Sun.COM  *
37748582SBrendan.Gregg@Sun.COM  *	l2arc_write_eligible()	check if a buffer is eligible to cache
37758582SBrendan.Gregg@Sun.COM  *	l2arc_write_size()	calculate how much to write
37768582SBrendan.Gregg@Sun.COM  *	l2arc_write_interval()	calculate sleep delay between writes
37778582SBrendan.Gregg@Sun.COM  *
37788582SBrendan.Gregg@Sun.COM  * These three functions determine what to write, how much, and how quickly
37798582SBrendan.Gregg@Sun.COM  * to send writes.
37805450Sbrendan  */
37815450Sbrendan 
37828582SBrendan.Gregg@Sun.COM static boolean_t
37838636SMark.Maybee@Sun.COM l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *ab)
37848582SBrendan.Gregg@Sun.COM {
37858582SBrendan.Gregg@Sun.COM 	/*
37868582SBrendan.Gregg@Sun.COM 	 * A buffer is *not* eligible for the L2ARC if it:
37878582SBrendan.Gregg@Sun.COM 	 * 1. belongs to a different spa.
37888582SBrendan.Gregg@Sun.COM 	 * 2. has no attached buffer.
37898582SBrendan.Gregg@Sun.COM 	 * 3. is already cached on the L2ARC.
37908582SBrendan.Gregg@Sun.COM 	 * 4. has an I/O in progress (it may be an incomplete read).
37918582SBrendan.Gregg@Sun.COM 	 * 5. is flagged not eligible (zfs property).
37928582SBrendan.Gregg@Sun.COM 	 */
37938636SMark.Maybee@Sun.COM 	if (ab->b_spa != spa_guid || ab->b_buf == NULL || ab->b_l2hdr != NULL ||
37948582SBrendan.Gregg@Sun.COM 	    HDR_IO_IN_PROGRESS(ab) || !HDR_L2CACHE(ab))
37958582SBrendan.Gregg@Sun.COM 		return (B_FALSE);
37968582SBrendan.Gregg@Sun.COM 
37978582SBrendan.Gregg@Sun.COM 	return (B_TRUE);
37988582SBrendan.Gregg@Sun.COM }
37998582SBrendan.Gregg@Sun.COM 
38008582SBrendan.Gregg@Sun.COM static uint64_t
38018582SBrendan.Gregg@Sun.COM l2arc_write_size(l2arc_dev_t *dev)
38028582SBrendan.Gregg@Sun.COM {
38038582SBrendan.Gregg@Sun.COM 	uint64_t size;
38048582SBrendan.Gregg@Sun.COM 
38058582SBrendan.Gregg@Sun.COM 	size = dev->l2ad_write;
38068582SBrendan.Gregg@Sun.COM 
38078582SBrendan.Gregg@Sun.COM 	if (arc_warm == B_FALSE)
38088582SBrendan.Gregg@Sun.COM 		size += dev->l2ad_boost;
38098582SBrendan.Gregg@Sun.COM 
38108582SBrendan.Gregg@Sun.COM 	return (size);
38118582SBrendan.Gregg@Sun.COM 
38128582SBrendan.Gregg@Sun.COM }
38138582SBrendan.Gregg@Sun.COM 
38148582SBrendan.Gregg@Sun.COM static clock_t
38158582SBrendan.Gregg@Sun.COM l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
38168582SBrendan.Gregg@Sun.COM {
38178582SBrendan.Gregg@Sun.COM 	clock_t interval, next;
38188582SBrendan.Gregg@Sun.COM 
38198582SBrendan.Gregg@Sun.COM 	/*
38208582SBrendan.Gregg@Sun.COM 	 * If the ARC lists are busy, increase our write rate; if the
38218582SBrendan.Gregg@Sun.COM 	 * lists are stale, idle back.  This is achieved by checking
38228582SBrendan.Gregg@Sun.COM 	 * how much we previously wrote - if it was more than half of
38238582SBrendan.Gregg@Sun.COM 	 * what we wanted, schedule the next write much sooner.
38248582SBrendan.Gregg@Sun.COM 	 */
38258582SBrendan.Gregg@Sun.COM 	if (l2arc_feed_again && wrote > (wanted / 2))
38268582SBrendan.Gregg@Sun.COM 		interval = (hz * l2arc_feed_min_ms) / 1000;
38278582SBrendan.Gregg@Sun.COM 	else
38288582SBrendan.Gregg@Sun.COM 		interval = hz * l2arc_feed_secs;
38298582SBrendan.Gregg@Sun.COM 
38308582SBrendan.Gregg@Sun.COM 	next = MAX(lbolt, MIN(lbolt + interval, began + interval));
38318582SBrendan.Gregg@Sun.COM 
38328582SBrendan.Gregg@Sun.COM 	return (next);
38338582SBrendan.Gregg@Sun.COM }
38348582SBrendan.Gregg@Sun.COM 
38355450Sbrendan static void
38365450Sbrendan l2arc_hdr_stat_add(void)
38375450Sbrendan {
38386018Sbrendan 	ARCSTAT_INCR(arcstat_l2_hdr_size, HDR_SIZE + L2HDR_SIZE);
38396018Sbrendan 	ARCSTAT_INCR(arcstat_hdr_size, -HDR_SIZE);
38405450Sbrendan }
38415450Sbrendan 
38425450Sbrendan static void
38435450Sbrendan l2arc_hdr_stat_remove(void)
38445450Sbrendan {
38456018Sbrendan 	ARCSTAT_INCR(arcstat_l2_hdr_size, -(HDR_SIZE + L2HDR_SIZE));
38466018Sbrendan 	ARCSTAT_INCR(arcstat_hdr_size, HDR_SIZE);
38475450Sbrendan }
38485450Sbrendan 
38495450Sbrendan /*
38505450Sbrendan  * Cycle through L2ARC devices.  This is how L2ARC load balances.
38516987Sbrendan  * If a device is returned, this also returns holding the spa config lock.
38525450Sbrendan  */
38535450Sbrendan static l2arc_dev_t *
38545450Sbrendan l2arc_dev_get_next(void)
38555450Sbrendan {
38566987Sbrendan 	l2arc_dev_t *first, *next = NULL;
38576987Sbrendan 
38586987Sbrendan 	/*
38596987Sbrendan 	 * Lock out the removal of spas (spa_namespace_lock), then removal
38606987Sbrendan 	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
38616987Sbrendan 	 * both locks will be dropped and a spa config lock held instead.
38626987Sbrendan 	 */
38636987Sbrendan 	mutex_enter(&spa_namespace_lock);
38646987Sbrendan 	mutex_enter(&l2arc_dev_mtx);
38656643Seschrock 
38666643Seschrock 	/* if there are no vdevs, there is nothing to do */
38676643Seschrock 	if (l2arc_ndev == 0)
38686987Sbrendan 		goto out;
38696643Seschrock 
38706643Seschrock 	first = NULL;
38716643Seschrock 	next = l2arc_dev_last;
38726643Seschrock 	do {
38736643Seschrock 		/* loop around the list looking for a non-faulted vdev */
38746643Seschrock 		if (next == NULL) {
38755450Sbrendan 			next = list_head(l2arc_dev_list);
38766643Seschrock 		} else {
38776643Seschrock 			next = list_next(l2arc_dev_list, next);
38786643Seschrock 			if (next == NULL)
38796643Seschrock 				next = list_head(l2arc_dev_list);
38806643Seschrock 		}
38816643Seschrock 
38826643Seschrock 		/* if we have come back to the start, bail out */
38836643Seschrock 		if (first == NULL)
38846643Seschrock 			first = next;
38856643Seschrock 		else if (next == first)
38866643Seschrock 			break;
38876643Seschrock 
38886643Seschrock 	} while (vdev_is_dead(next->l2ad_vdev));
38896643Seschrock 
38906643Seschrock 	/* if we were unable to find any usable vdevs, return NULL */
38916643Seschrock 	if (vdev_is_dead(next->l2ad_vdev))
38926987Sbrendan 		next = NULL;
38935450Sbrendan 
38945450Sbrendan 	l2arc_dev_last = next;
38955450Sbrendan 
38966987Sbrendan out:
38976987Sbrendan 	mutex_exit(&l2arc_dev_mtx);
38986987Sbrendan 
38996987Sbrendan 	/*
39006987Sbrendan 	 * Grab the config lock to prevent the 'next' device from being
39016987Sbrendan 	 * removed while we are writing to it.
39026987Sbrendan 	 */
39036987Sbrendan 	if (next != NULL)
39047754SJeff.Bonwick@Sun.COM 		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
39056987Sbrendan 	mutex_exit(&spa_namespace_lock);
39066987Sbrendan 
39075450Sbrendan 	return (next);
39085450Sbrendan }
39095450Sbrendan 
39105450Sbrendan /*
39116987Sbrendan  * Free buffers that were tagged for destruction.
39126987Sbrendan  */
39136987Sbrendan static void
39146987Sbrendan l2arc_do_free_on_write()
39156987Sbrendan {
39166987Sbrendan 	list_t *buflist;
39176987Sbrendan 	l2arc_data_free_t *df, *df_prev;
39186987Sbrendan 
39196987Sbrendan 	mutex_enter(&l2arc_free_on_write_mtx);
39206987Sbrendan 	buflist = l2arc_free_on_write;
39216987Sbrendan 
39226987Sbrendan 	for (df = list_tail(buflist); df; df = df_prev) {
39236987Sbrendan 		df_prev = list_prev(buflist, df);
39246987Sbrendan 		ASSERT(df->l2df_data != NULL);
39256987Sbrendan 		ASSERT(df->l2df_func != NULL);
39266987Sbrendan 		df->l2df_func(df->l2df_data, df->l2df_size);
39276987Sbrendan 		list_remove(buflist, df);
39286987Sbrendan 		kmem_free(df, sizeof (l2arc_data_free_t));
39296987Sbrendan 	}
39306987Sbrendan 
39316987Sbrendan 	mutex_exit(&l2arc_free_on_write_mtx);
39326987Sbrendan }
39336987Sbrendan 
39346987Sbrendan /*
39355450Sbrendan  * A write to a cache device has completed.  Update all headers to allow
39365450Sbrendan  * reads from these buffers to begin.
39375450Sbrendan  */
39385450Sbrendan static void
39395450Sbrendan l2arc_write_done(zio_t *zio)
39405450Sbrendan {
39415450Sbrendan 	l2arc_write_callback_t *cb;
39425450Sbrendan 	l2arc_dev_t *dev;
39435450Sbrendan 	list_t *buflist;
39445450Sbrendan 	arc_buf_hdr_t *head, *ab, *ab_prev;
39456987Sbrendan 	l2arc_buf_hdr_t *abl2;
39465450Sbrendan 	kmutex_t *hash_lock;
39475450Sbrendan 
39485450Sbrendan 	cb = zio->io_private;
39495450Sbrendan 	ASSERT(cb != NULL);
39505450Sbrendan 	dev = cb->l2wcb_dev;
39515450Sbrendan 	ASSERT(dev != NULL);
39525450Sbrendan 	head = cb->l2wcb_head;
39535450Sbrendan 	ASSERT(head != NULL);
39545450Sbrendan 	buflist = dev->l2ad_buflist;
39555450Sbrendan 	ASSERT(buflist != NULL);
39565450Sbrendan 	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
39575450Sbrendan 	    l2arc_write_callback_t *, cb);
39585450Sbrendan 
39595450Sbrendan 	if (zio->io_error != 0)
39605450Sbrendan 		ARCSTAT_BUMP(arcstat_l2_writes_error);
39615450Sbrendan 
39625450Sbrendan 	mutex_enter(&l2arc_buflist_mtx);
39635450Sbrendan 
39645450Sbrendan 	/*
39655450Sbrendan 	 * All writes completed, or an error was hit.
39665450Sbrendan 	 */
39675450Sbrendan 	for (ab = list_prev(buflist, head); ab; ab = ab_prev) {
39685450Sbrendan 		ab_prev = list_prev(buflist, ab);
39695450Sbrendan 
39705450Sbrendan 		hash_lock = HDR_LOCK(ab);
39715450Sbrendan 		if (!mutex_tryenter(hash_lock)) {
39725450Sbrendan 			/*
39735450Sbrendan 			 * This buffer misses out.  It may be in a stage
39745450Sbrendan 			 * of eviction.  Its ARC_L2_WRITING flag will be
39755450Sbrendan 			 * left set, denying reads to this buffer.
39765450Sbrendan 			 */
39775450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_writes_hdr_miss);
39785450Sbrendan 			continue;
39795450Sbrendan 		}
39805450Sbrendan 
39815450Sbrendan 		if (zio->io_error != 0) {
39825450Sbrendan 			/*
39836987Sbrendan 			 * Error - drop L2ARC entry.
39845450Sbrendan 			 */
39856987Sbrendan 			list_remove(buflist, ab);
39866987Sbrendan 			abl2 = ab->b_l2hdr;
39875450Sbrendan 			ab->b_l2hdr = NULL;
39886987Sbrendan 			kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
39896987Sbrendan 			ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
39905450Sbrendan 		}
39915450Sbrendan 
39925450Sbrendan 		/*
39935450Sbrendan 		 * Allow ARC to begin reads to this L2ARC entry.
39945450Sbrendan 		 */
39955450Sbrendan 		ab->b_flags &= ~ARC_L2_WRITING;
39965450Sbrendan 
39975450Sbrendan 		mutex_exit(hash_lock);
39985450Sbrendan 	}
39995450Sbrendan 
40005450Sbrendan 	atomic_inc_64(&l2arc_writes_done);
40015450Sbrendan 	list_remove(buflist, head);
40025450Sbrendan 	kmem_cache_free(hdr_cache, head);
40035450Sbrendan 	mutex_exit(&l2arc_buflist_mtx);
40045450Sbrendan 
40056987Sbrendan 	l2arc_do_free_on_write();
40065450Sbrendan 
40075450Sbrendan 	kmem_free(cb, sizeof (l2arc_write_callback_t));
40085450Sbrendan }
40095450Sbrendan 
40105450Sbrendan /*
40115450Sbrendan  * A read to a cache device completed.  Validate buffer contents before
40125450Sbrendan  * handing over to the regular ARC routines.
40135450Sbrendan  */
40145450Sbrendan static void
40155450Sbrendan l2arc_read_done(zio_t *zio)
40165450Sbrendan {
40175450Sbrendan 	l2arc_read_callback_t *cb;
40185450Sbrendan 	arc_buf_hdr_t *hdr;
40195450Sbrendan 	arc_buf_t *buf;
40205450Sbrendan 	kmutex_t *hash_lock;
40216987Sbrendan 	int equal;
40225450Sbrendan 
40237754SJeff.Bonwick@Sun.COM 	ASSERT(zio->io_vd != NULL);
40247754SJeff.Bonwick@Sun.COM 	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
40257754SJeff.Bonwick@Sun.COM 
40267754SJeff.Bonwick@Sun.COM 	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
40277754SJeff.Bonwick@Sun.COM 
40285450Sbrendan 	cb = zio->io_private;
40295450Sbrendan 	ASSERT(cb != NULL);
40305450Sbrendan 	buf = cb->l2rcb_buf;
40315450Sbrendan 	ASSERT(buf != NULL);
40325450Sbrendan 	hdr = buf->b_hdr;
40335450Sbrendan 	ASSERT(hdr != NULL);
40345450Sbrendan 
40355450Sbrendan 	hash_lock = HDR_LOCK(hdr);
40365450Sbrendan 	mutex_enter(hash_lock);
40375450Sbrendan 
40385450Sbrendan 	/*
40395450Sbrendan 	 * Check this survived the L2ARC journey.
40405450Sbrendan 	 */
40415450Sbrendan 	equal = arc_cksum_equal(buf);
40425450Sbrendan 	if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
40435450Sbrendan 		mutex_exit(hash_lock);
40445450Sbrendan 		zio->io_private = buf;
40457754SJeff.Bonwick@Sun.COM 		zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
40467754SJeff.Bonwick@Sun.COM 		zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
40475450Sbrendan 		arc_read_done(zio);
40485450Sbrendan 	} else {
40495450Sbrendan 		mutex_exit(hash_lock);
40505450Sbrendan 		/*
40515450Sbrendan 		 * Buffer didn't survive caching.  Increment stats and
40525450Sbrendan 		 * reissue to the original storage device.
40535450Sbrendan 		 */
40546987Sbrendan 		if (zio->io_error != 0) {
40555450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_io_error);
40566987Sbrendan 		} else {
40576987Sbrendan 			zio->io_error = EIO;
40586987Sbrendan 		}
40595450Sbrendan 		if (!equal)
40605450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
40615450Sbrendan 
40627754SJeff.Bonwick@Sun.COM 		/*
40637754SJeff.Bonwick@Sun.COM 		 * If there's no waiter, issue an async i/o to the primary
40647754SJeff.Bonwick@Sun.COM 		 * storage now.  If there *is* a waiter, the caller must
40657754SJeff.Bonwick@Sun.COM 		 * issue the i/o in a context where it's OK to block.
40667754SJeff.Bonwick@Sun.COM 		 */
40678632SBill.Moore@Sun.COM 		if (zio->io_waiter == NULL) {
40688632SBill.Moore@Sun.COM 			zio_t *pio = zio_unique_parent(zio);
40698632SBill.Moore@Sun.COM 
40708632SBill.Moore@Sun.COM 			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
40718632SBill.Moore@Sun.COM 
40728632SBill.Moore@Sun.COM 			zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
40737754SJeff.Bonwick@Sun.COM 			    buf->b_data, zio->io_size, arc_read_done, buf,
40747754SJeff.Bonwick@Sun.COM 			    zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
40758632SBill.Moore@Sun.COM 		}
40765450Sbrendan 	}
40775450Sbrendan 
40785450Sbrendan 	kmem_free(cb, sizeof (l2arc_read_callback_t));
40795450Sbrendan }
40805450Sbrendan 
40815450Sbrendan /*
40825450Sbrendan  * This is the list priority from which the L2ARC will search for pages to
40835450Sbrendan  * cache.  This is used within loops (0..3) to cycle through lists in the
40845450Sbrendan  * desired order.  This order can have a significant effect on cache
40855450Sbrendan  * performance.
40865450Sbrendan  *
40875450Sbrendan  * Currently the metadata lists are hit first, MFU then MRU, followed by
40885450Sbrendan  * the data lists.  This function returns a locked list, and also returns
40895450Sbrendan  * the lock pointer.
40905450Sbrendan  */
40915450Sbrendan static list_t *
40925450Sbrendan l2arc_list_locked(int list_num, kmutex_t **lock)
40935450Sbrendan {
40945450Sbrendan 	list_t *list;
40955450Sbrendan 
40965450Sbrendan 	ASSERT(list_num >= 0 && list_num <= 3);
40975450Sbrendan 
40985450Sbrendan 	switch (list_num) {
40995450Sbrendan 	case 0:
41005450Sbrendan 		list = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
41015450Sbrendan 		*lock = &arc_mfu->arcs_mtx;
41025450Sbrendan 		break;
41035450Sbrendan 	case 1:
41045450Sbrendan 		list = &arc_mru->arcs_list[ARC_BUFC_METADATA];
41055450Sbrendan 		*lock = &arc_mru->arcs_mtx;
41065450Sbrendan 		break;
41075450Sbrendan 	case 2:
41085450Sbrendan 		list = &arc_mfu->arcs_list[ARC_BUFC_DATA];
41095450Sbrendan 		*lock = &arc_mfu->arcs_mtx;
41105450Sbrendan 		break;
41115450Sbrendan 	case 3:
41125450Sbrendan 		list = &arc_mru->arcs_list[ARC_BUFC_DATA];
41135450Sbrendan 		*lock = &arc_mru->arcs_mtx;
41145450Sbrendan 		break;
41155450Sbrendan 	}
41165450Sbrendan 
41175450Sbrendan 	ASSERT(!(MUTEX_HELD(*lock)));
41185450Sbrendan 	mutex_enter(*lock);
41195450Sbrendan 	return (list);
41205450Sbrendan }
41215450Sbrendan 
41225450Sbrendan /*
41235450Sbrendan  * Evict buffers from the device write hand to the distance specified in
41245450Sbrendan  * bytes.  This distance may span populated buffers, it may span nothing.
41255450Sbrendan  * This is clearing a region on the L2ARC device ready for writing.
41265450Sbrendan  * If the 'all' boolean is set, every buffer is evicted.
41275450Sbrendan  */
41285450Sbrendan static void
41295450Sbrendan l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
41305450Sbrendan {
41315450Sbrendan 	list_t *buflist;
41325450Sbrendan 	l2arc_buf_hdr_t *abl2;
41335450Sbrendan 	arc_buf_hdr_t *ab, *ab_prev;
41345450Sbrendan 	kmutex_t *hash_lock;
41355450Sbrendan 	uint64_t taddr;
41365450Sbrendan 
41375450Sbrendan 	buflist = dev->l2ad_buflist;
41385450Sbrendan 
41395450Sbrendan 	if (buflist == NULL)
41405450Sbrendan 		return;
41415450Sbrendan 
41425450Sbrendan 	if (!all && dev->l2ad_first) {
41435450Sbrendan 		/*
41445450Sbrendan 		 * This is the first sweep through the device.  There is
41455450Sbrendan 		 * nothing to evict.
41465450Sbrendan 		 */
41475450Sbrendan 		return;
41485450Sbrendan 	}
41495450Sbrendan 
41506987Sbrendan 	if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
41515450Sbrendan 		/*
41525450Sbrendan 		 * When nearing the end of the device, evict to the end
41535450Sbrendan 		 * before the device write hand jumps to the start.
41545450Sbrendan 		 */
41555450Sbrendan 		taddr = dev->l2ad_end;
41565450Sbrendan 	} else {
41575450Sbrendan 		taddr = dev->l2ad_hand + distance;
41585450Sbrendan 	}
41595450Sbrendan 	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
41605450Sbrendan 	    uint64_t, taddr, boolean_t, all);
41615450Sbrendan 
41625450Sbrendan top:
41635450Sbrendan 	mutex_enter(&l2arc_buflist_mtx);
41645450Sbrendan 	for (ab = list_tail(buflist); ab; ab = ab_prev) {
41655450Sbrendan 		ab_prev = list_prev(buflist, ab);
41665450Sbrendan 
41675450Sbrendan 		hash_lock = HDR_LOCK(ab);
41685450Sbrendan 		if (!mutex_tryenter(hash_lock)) {
41695450Sbrendan 			/*
41705450Sbrendan 			 * Missed the hash lock.  Retry.
41715450Sbrendan 			 */
41725450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
41735450Sbrendan 			mutex_exit(&l2arc_buflist_mtx);
41745450Sbrendan 			mutex_enter(hash_lock);
41755450Sbrendan 			mutex_exit(hash_lock);
41765450Sbrendan 			goto top;
41775450Sbrendan 		}
41785450Sbrendan 
41795450Sbrendan 		if (HDR_L2_WRITE_HEAD(ab)) {
41805450Sbrendan 			/*
41815450Sbrendan 			 * We hit a write head node.  Leave it for
41825450Sbrendan 			 * l2arc_write_done().
41835450Sbrendan 			 */
41845450Sbrendan 			list_remove(buflist, ab);
41855450Sbrendan 			mutex_exit(hash_lock);
41865450Sbrendan 			continue;
41875450Sbrendan 		}
41885450Sbrendan 
41895450Sbrendan 		if (!all && ab->b_l2hdr != NULL &&
41905450Sbrendan 		    (ab->b_l2hdr->b_daddr > taddr ||
41915450Sbrendan 		    ab->b_l2hdr->b_daddr < dev->l2ad_hand)) {
41925450Sbrendan 			/*
41935450Sbrendan 			 * We've evicted to the target address,
41945450Sbrendan 			 * or the end of the device.
41955450Sbrendan 			 */
41965450Sbrendan 			mutex_exit(hash_lock);
41975450Sbrendan 			break;
41985450Sbrendan 		}
41995450Sbrendan 
42005450Sbrendan 		if (HDR_FREE_IN_PROGRESS(ab)) {
42015450Sbrendan 			/*
42025450Sbrendan 			 * Already on the path to destruction.
42035450Sbrendan 			 */
42045450Sbrendan 			mutex_exit(hash_lock);
42055450Sbrendan 			continue;
42065450Sbrendan 		}
42075450Sbrendan 
42085450Sbrendan 		if (ab->b_state == arc_l2c_only) {
42095450Sbrendan 			ASSERT(!HDR_L2_READING(ab));
42105450Sbrendan 			/*
42115450Sbrendan 			 * This doesn't exist in the ARC.  Destroy.
42125450Sbrendan 			 * arc_hdr_destroy() will call list_remove()
42135450Sbrendan 			 * and decrement arcstat_l2_size.
42145450Sbrendan 			 */
42155450Sbrendan 			arc_change_state(arc_anon, ab, hash_lock);
42165450Sbrendan 			arc_hdr_destroy(ab);
42175450Sbrendan 		} else {
42185450Sbrendan 			/*
42196987Sbrendan 			 * Invalidate issued or about to be issued
42206987Sbrendan 			 * reads, since we may be about to write
42216987Sbrendan 			 * over this location.
42226987Sbrendan 			 */
42236987Sbrendan 			if (HDR_L2_READING(ab)) {
42246987Sbrendan 				ARCSTAT_BUMP(arcstat_l2_evict_reading);
42256987Sbrendan 				ab->b_flags |= ARC_L2_EVICTED;
42266987Sbrendan 			}
42276987Sbrendan 
42286987Sbrendan 			/*
42295450Sbrendan 			 * Tell ARC this no longer exists in L2ARC.
42305450Sbrendan 			 */
42315450Sbrendan 			if (ab->b_l2hdr != NULL) {
42325450Sbrendan 				abl2 = ab->b_l2hdr;
42335450Sbrendan 				ab->b_l2hdr = NULL;
42345450Sbrendan 				kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
42355450Sbrendan 				ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
42365450Sbrendan 			}
42375450Sbrendan 			list_remove(buflist, ab);
42385450Sbrendan 
42395450Sbrendan 			/*
42405450Sbrendan 			 * This may have been leftover after a
42415450Sbrendan 			 * failed write.
42425450Sbrendan 			 */
42435450Sbrendan 			ab->b_flags &= ~ARC_L2_WRITING;
42445450Sbrendan 		}
42455450Sbrendan 		mutex_exit(hash_lock);
42465450Sbrendan 	}
42475450Sbrendan 	mutex_exit(&l2arc_buflist_mtx);
42485450Sbrendan 
42495450Sbrendan 	spa_l2cache_space_update(dev->l2ad_vdev, 0, -(taddr - dev->l2ad_evict));
42505450Sbrendan 	dev->l2ad_evict = taddr;
42515450Sbrendan }
42525450Sbrendan 
42535450Sbrendan /*
42545450Sbrendan  * Find and write ARC buffers to the L2ARC device.
42555450Sbrendan  *
42565450Sbrendan  * An ARC_L2_WRITING flag is set so that the L2ARC buffers are not valid
42575450Sbrendan  * for reading until they have completed writing.
42585450Sbrendan  */
42598582SBrendan.Gregg@Sun.COM static uint64_t
42606987Sbrendan l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
42615450Sbrendan {
42625450Sbrendan 	arc_buf_hdr_t *ab, *ab_prev, *head;
42635450Sbrendan 	l2arc_buf_hdr_t *hdrl2;
42645450Sbrendan 	list_t *list;
42656987Sbrendan 	uint64_t passed_sz, write_sz, buf_sz, headroom;
42665450Sbrendan 	void *buf_data;
42675450Sbrendan 	kmutex_t *hash_lock, *list_lock;
42685450Sbrendan 	boolean_t have_lock, full;
42695450Sbrendan 	l2arc_write_callback_t *cb;
42705450Sbrendan 	zio_t *pio, *wzio;
42718636SMark.Maybee@Sun.COM 	uint64_t guid = spa_guid(spa);
42725450Sbrendan 
42735450Sbrendan 	ASSERT(dev->l2ad_vdev != NULL);
42745450Sbrendan 
42755450Sbrendan 	pio = NULL;
42765450Sbrendan 	write_sz = 0;
42775450Sbrendan 	full = B_FALSE;
42786245Smaybee 	head = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
42795450Sbrendan 	head->b_flags |= ARC_L2_WRITE_HEAD;
42805450Sbrendan 
42815450Sbrendan 	/*
42825450Sbrendan 	 * Copy buffers for L2ARC writing.
42835450Sbrendan 	 */
42845450Sbrendan 	mutex_enter(&l2arc_buflist_mtx);
42855450Sbrendan 	for (int try = 0; try <= 3; try++) {
42865450Sbrendan 		list = l2arc_list_locked(try, &list_lock);
42875450Sbrendan 		passed_sz = 0;
42885450Sbrendan 
42896987Sbrendan 		/*
42906987Sbrendan 		 * L2ARC fast warmup.
42916987Sbrendan 		 *
42926987Sbrendan 		 * Until the ARC is warm and starts to evict, read from the
42936987Sbrendan 		 * head of the ARC lists rather than the tail.
42946987Sbrendan 		 */
42956987Sbrendan 		headroom = target_sz * l2arc_headroom;
42966987Sbrendan 		if (arc_warm == B_FALSE)
42976987Sbrendan 			ab = list_head(list);
42986987Sbrendan 		else
42996987Sbrendan 			ab = list_tail(list);
43006987Sbrendan 
43016987Sbrendan 		for (; ab; ab = ab_prev) {
43026987Sbrendan 			if (arc_warm == B_FALSE)
43036987Sbrendan 				ab_prev = list_next(list, ab);
43046987Sbrendan 			else
43056987Sbrendan 				ab_prev = list_prev(list, ab);
43065450Sbrendan 
43075450Sbrendan 			hash_lock = HDR_LOCK(ab);
43085450Sbrendan 			have_lock = MUTEX_HELD(hash_lock);
43095450Sbrendan 			if (!have_lock && !mutex_tryenter(hash_lock)) {
43105450Sbrendan 				/*
43115450Sbrendan 				 * Skip this buffer rather than waiting.
43125450Sbrendan 				 */
43135450Sbrendan 				continue;
43145450Sbrendan 			}
43155450Sbrendan 
43165450Sbrendan 			passed_sz += ab->b_size;
43175450Sbrendan 			if (passed_sz > headroom) {
43185450Sbrendan 				/*
43195450Sbrendan 				 * Searched too far.
43205450Sbrendan 				 */
43215450Sbrendan 				mutex_exit(hash_lock);
43225450Sbrendan 				break;
43235450Sbrendan 			}
43245450Sbrendan 
43258636SMark.Maybee@Sun.COM 			if (!l2arc_write_eligible(guid, ab)) {
43265450Sbrendan 				mutex_exit(hash_lock);
43275450Sbrendan 				continue;
43285450Sbrendan 			}
43295450Sbrendan 
43305450Sbrendan 			if ((write_sz + ab->b_size) > target_sz) {
43315450Sbrendan 				full = B_TRUE;
43325450Sbrendan 				mutex_exit(hash_lock);
43335450Sbrendan 				break;
43345450Sbrendan 			}
43355450Sbrendan 
43365450Sbrendan 			if (pio == NULL) {
43375450Sbrendan 				/*
43385450Sbrendan 				 * Insert a dummy header on the buflist so
43395450Sbrendan 				 * l2arc_write_done() can find where the
43405450Sbrendan 				 * write buffers begin without searching.
43415450Sbrendan 				 */
43425450Sbrendan 				list_insert_head(dev->l2ad_buflist, head);
43435450Sbrendan 
43445450Sbrendan 				cb = kmem_alloc(
43455450Sbrendan 				    sizeof (l2arc_write_callback_t), KM_SLEEP);
43465450Sbrendan 				cb->l2wcb_dev = dev;
43475450Sbrendan 				cb->l2wcb_head = head;
43485450Sbrendan 				pio = zio_root(spa, l2arc_write_done, cb,
43495450Sbrendan 				    ZIO_FLAG_CANFAIL);
43505450Sbrendan 			}
43515450Sbrendan 
43525450Sbrendan 			/*
43535450Sbrendan 			 * Create and add a new L2ARC header.
43545450Sbrendan 			 */
43555450Sbrendan 			hdrl2 = kmem_zalloc(sizeof (l2arc_buf_hdr_t), KM_SLEEP);
43565450Sbrendan 			hdrl2->b_dev = dev;
43575450Sbrendan 			hdrl2->b_daddr = dev->l2ad_hand;
43585450Sbrendan 
43595450Sbrendan 			ab->b_flags |= ARC_L2_WRITING;
43605450Sbrendan 			ab->b_l2hdr = hdrl2;
43615450Sbrendan 			list_insert_head(dev->l2ad_buflist, ab);
43625450Sbrendan 			buf_data = ab->b_buf->b_data;
43635450Sbrendan 			buf_sz = ab->b_size;
43645450Sbrendan 
43655450Sbrendan 			/*
43665450Sbrendan 			 * Compute and store the buffer cksum before
43675450Sbrendan 			 * writing.  On debug the cksum is verified first.
43685450Sbrendan 			 */
43695450Sbrendan 			arc_cksum_verify(ab->b_buf);
43705450Sbrendan 			arc_cksum_compute(ab->b_buf, B_TRUE);
43715450Sbrendan 
43725450Sbrendan 			mutex_exit(hash_lock);
43735450Sbrendan 
43745450Sbrendan 			wzio = zio_write_phys(pio, dev->l2ad_vdev,
43755450Sbrendan 			    dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
43765450Sbrendan 			    NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
43775450Sbrendan 			    ZIO_FLAG_CANFAIL, B_FALSE);
43785450Sbrendan 
43795450Sbrendan 			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
43805450Sbrendan 			    zio_t *, wzio);
43815450Sbrendan 			(void) zio_nowait(wzio);
43825450Sbrendan 
43837754SJeff.Bonwick@Sun.COM 			/*
43847754SJeff.Bonwick@Sun.COM 			 * Keep the clock hand suitably device-aligned.
43857754SJeff.Bonwick@Sun.COM 			 */
43867754SJeff.Bonwick@Sun.COM 			buf_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
43877754SJeff.Bonwick@Sun.COM 
43885450Sbrendan 			write_sz += buf_sz;
43895450Sbrendan 			dev->l2ad_hand += buf_sz;
43905450Sbrendan 		}
43915450Sbrendan 
43925450Sbrendan 		mutex_exit(list_lock);
43935450Sbrendan 
43945450Sbrendan 		if (full == B_TRUE)
43955450Sbrendan 			break;
43965450Sbrendan 	}
43975450Sbrendan 	mutex_exit(&l2arc_buflist_mtx);
43985450Sbrendan 
43995450Sbrendan 	if (pio == NULL) {
44005450Sbrendan 		ASSERT3U(write_sz, ==, 0);
44015450Sbrendan 		kmem_cache_free(hdr_cache, head);
44028582SBrendan.Gregg@Sun.COM 		return (0);
44035450Sbrendan 	}
44045450Sbrendan 
44055450Sbrendan 	ASSERT3U(write_sz, <=, target_sz);
44065450Sbrendan 	ARCSTAT_BUMP(arcstat_l2_writes_sent);
44078582SBrendan.Gregg@Sun.COM 	ARCSTAT_INCR(arcstat_l2_write_bytes, write_sz);
44085450Sbrendan 	ARCSTAT_INCR(arcstat_l2_size, write_sz);
44095450Sbrendan 	spa_l2cache_space_update(dev->l2ad_vdev, 0, write_sz);
44105450Sbrendan 
44115450Sbrendan 	/*
44125450Sbrendan 	 * Bump device hand to the device start if it is approaching the end.
44135450Sbrendan 	 * l2arc_evict() will already have evicted ahead for this case.
44145450Sbrendan 	 */
44156987Sbrendan 	if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
44165450Sbrendan 		spa_l2cache_space_update(dev->l2ad_vdev, 0,
44175450Sbrendan 		    dev->l2ad_end - dev->l2ad_hand);
44185450Sbrendan 		dev->l2ad_hand = dev->l2ad_start;
44195450Sbrendan 		dev->l2ad_evict = dev->l2ad_start;
44205450Sbrendan 		dev->l2ad_first = B_FALSE;
44215450Sbrendan 	}
44225450Sbrendan 
44238582SBrendan.Gregg@Sun.COM 	dev->l2ad_writing = B_TRUE;
44245450Sbrendan 	(void) zio_wait(pio);
44258582SBrendan.Gregg@Sun.COM 	dev->l2ad_writing = B_FALSE;
44268582SBrendan.Gregg@Sun.COM 
44278582SBrendan.Gregg@Sun.COM 	return (write_sz);
44285450Sbrendan }
44295450Sbrendan 
44305450Sbrendan /*
44315450Sbrendan  * This thread feeds the L2ARC at regular intervals.  This is the beating
44325450Sbrendan  * heart of the L2ARC.
44335450Sbrendan  */
44345450Sbrendan static void
44355450Sbrendan l2arc_feed_thread(void)
44365450Sbrendan {
44375450Sbrendan 	callb_cpr_t cpr;
44385450Sbrendan 	l2arc_dev_t *dev;
44395450Sbrendan 	spa_t *spa;
44408582SBrendan.Gregg@Sun.COM 	uint64_t size, wrote;
44418582SBrendan.Gregg@Sun.COM 	clock_t begin, next = lbolt;
44425450Sbrendan 
44435450Sbrendan 	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
44445450Sbrendan 
44455450Sbrendan 	mutex_enter(&l2arc_feed_thr_lock);
44465450Sbrendan 
44475450Sbrendan 	while (l2arc_thread_exit == 0) {
44485450Sbrendan 		CALLB_CPR_SAFE_BEGIN(&cpr);
44496987Sbrendan 		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
44508582SBrendan.Gregg@Sun.COM 		    next);
44516987Sbrendan 		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
44528582SBrendan.Gregg@Sun.COM 		next = lbolt + hz;
44536987Sbrendan 
44546987Sbrendan 		/*
44556987Sbrendan 		 * Quick check for L2ARC devices.
44566987Sbrendan 		 */
44576987Sbrendan 		mutex_enter(&l2arc_dev_mtx);
44586987Sbrendan 		if (l2arc_ndev == 0) {
44596987Sbrendan 			mutex_exit(&l2arc_dev_mtx);
44606987Sbrendan 			continue;
44615450Sbrendan 		}
44626987Sbrendan 		mutex_exit(&l2arc_dev_mtx);
44638582SBrendan.Gregg@Sun.COM 		begin = lbolt;
44646643Seschrock 
44655450Sbrendan 		/*
44666643Seschrock 		 * This selects the next l2arc device to write to, and in
44676643Seschrock 		 * doing so the next spa to feed from: dev->l2ad_spa.   This
44686987Sbrendan 		 * will return NULL if there are now no l2arc devices or if
44696987Sbrendan 		 * they are all faulted.
44706987Sbrendan 		 *
44716987Sbrendan 		 * If a device is returned, its spa's config lock is also
44726987Sbrendan 		 * held to prevent device removal.  l2arc_dev_get_next()
44736987Sbrendan 		 * will grab and release l2arc_dev_mtx.
44745450Sbrendan 		 */
44756987Sbrendan 		if ((dev = l2arc_dev_get_next()) == NULL)
44765450Sbrendan 			continue;
44776987Sbrendan 
44786987Sbrendan 		spa = dev->l2ad_spa;
44796987Sbrendan 		ASSERT(spa != NULL);
44805450Sbrendan 
44815450Sbrendan 		/*
44825450Sbrendan 		 * Avoid contributing to memory pressure.
44835450Sbrendan 		 */
44845450Sbrendan 		if (arc_reclaim_needed()) {
44855450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
44867754SJeff.Bonwick@Sun.COM 			spa_config_exit(spa, SCL_L2ARC, dev);
44875450Sbrendan 			continue;
44885450Sbrendan 		}
44895450Sbrendan 
44905450Sbrendan 		ARCSTAT_BUMP(arcstat_l2_feeds);
44915450Sbrendan 
44928582SBrendan.Gregg@Sun.COM 		size = l2arc_write_size(dev);
44936987Sbrendan 
44945450Sbrendan 		/*
44955450Sbrendan 		 * Evict L2ARC buffers that will be overwritten.
44965450Sbrendan 		 */
44976987Sbrendan 		l2arc_evict(dev, size, B_FALSE);
44985450Sbrendan 
44995450Sbrendan 		/*
45005450Sbrendan 		 * Write ARC buffers.
45015450Sbrendan 		 */
45028582SBrendan.Gregg@Sun.COM 		wrote = l2arc_write_buffers(spa, dev, size);
45038582SBrendan.Gregg@Sun.COM 
45048582SBrendan.Gregg@Sun.COM 		/*
45058582SBrendan.Gregg@Sun.COM 		 * Calculate interval between writes.
45068582SBrendan.Gregg@Sun.COM 		 */
45078582SBrendan.Gregg@Sun.COM 		next = l2arc_write_interval(begin, size, wrote);
45087754SJeff.Bonwick@Sun.COM 		spa_config_exit(spa, SCL_L2ARC, dev);
45095450Sbrendan 	}
45105450Sbrendan 
45115450Sbrendan 	l2arc_thread_exit = 0;
45125450Sbrendan 	cv_broadcast(&l2arc_feed_thr_cv);
45135450Sbrendan 	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
45145450Sbrendan 	thread_exit();
45155450Sbrendan }
45165450Sbrendan 
45176643Seschrock boolean_t
45186643Seschrock l2arc_vdev_present(vdev_t *vd)
45196643Seschrock {
45206643Seschrock 	l2arc_dev_t *dev;
45216643Seschrock 
45226643Seschrock 	mutex_enter(&l2arc_dev_mtx);
45236643Seschrock 	for (dev = list_head(l2arc_dev_list); dev != NULL;
45246643Seschrock 	    dev = list_next(l2arc_dev_list, dev)) {
45256643Seschrock 		if (dev->l2ad_vdev == vd)
45266643Seschrock 			break;
45276643Seschrock 	}
45286643Seschrock 	mutex_exit(&l2arc_dev_mtx);
45296643Seschrock 
45306643Seschrock 	return (dev != NULL);
45316643Seschrock }
45326643Seschrock 
45335450Sbrendan /*
45345450Sbrendan  * Add a vdev for use by the L2ARC.  By this point the spa has already
45355450Sbrendan  * validated the vdev and opened it.
45365450Sbrendan  */
45375450Sbrendan void
45385450Sbrendan l2arc_add_vdev(spa_t *spa, vdev_t *vd, uint64_t start, uint64_t end)
45395450Sbrendan {
45405450Sbrendan 	l2arc_dev_t *adddev;
45415450Sbrendan 
45426643Seschrock 	ASSERT(!l2arc_vdev_present(vd));
45436643Seschrock 
45445450Sbrendan 	/*
45455450Sbrendan 	 * Create a new l2arc device entry.
45465450Sbrendan 	 */
45475450Sbrendan 	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
45485450Sbrendan 	adddev->l2ad_spa = spa;
45495450Sbrendan 	adddev->l2ad_vdev = vd;
45505450Sbrendan 	adddev->l2ad_write = l2arc_write_max;
45516987Sbrendan 	adddev->l2ad_boost = l2arc_write_boost;
45525450Sbrendan 	adddev->l2ad_start = start;
45535450Sbrendan 	adddev->l2ad_end = end;
45545450Sbrendan 	adddev->l2ad_hand = adddev->l2ad_start;
45555450Sbrendan 	adddev->l2ad_evict = adddev->l2ad_start;
45565450Sbrendan 	adddev->l2ad_first = B_TRUE;
45578582SBrendan.Gregg@Sun.COM 	adddev->l2ad_writing = B_FALSE;
45585450Sbrendan 	ASSERT3U(adddev->l2ad_write, >, 0);
45595450Sbrendan 
45605450Sbrendan 	/*
45615450Sbrendan 	 * This is a list of all ARC buffers that are still valid on the
45625450Sbrendan 	 * device.
45635450Sbrendan 	 */
45645450Sbrendan 	adddev->l2ad_buflist = kmem_zalloc(sizeof (list_t), KM_SLEEP);
45655450Sbrendan 	list_create(adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
45665450Sbrendan 	    offsetof(arc_buf_hdr_t, b_l2node));
45675450Sbrendan 
45685450Sbrendan 	spa_l2cache_space_update(vd, adddev->l2ad_end - adddev->l2ad_hand, 0);
45695450Sbrendan 
45705450Sbrendan 	/*
45715450Sbrendan 	 * Add device to global list
45725450Sbrendan 	 */
45735450Sbrendan 	mutex_enter(&l2arc_dev_mtx);
45745450Sbrendan 	list_insert_head(l2arc_dev_list, adddev);
45755450Sbrendan 	atomic_inc_64(&l2arc_ndev);
45765450Sbrendan 	mutex_exit(&l2arc_dev_mtx);
45775450Sbrendan }
45785450Sbrendan 
45795450Sbrendan /*
45805450Sbrendan  * Remove a vdev from the L2ARC.
45815450Sbrendan  */
45825450Sbrendan void
45835450Sbrendan l2arc_remove_vdev(vdev_t *vd)
45845450Sbrendan {
45855450Sbrendan 	l2arc_dev_t *dev, *nextdev, *remdev = NULL;
45865450Sbrendan 
45875450Sbrendan 	/*
45885450Sbrendan 	 * Find the device by vdev
45895450Sbrendan 	 */
45905450Sbrendan 	mutex_enter(&l2arc_dev_mtx);
45915450Sbrendan 	for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
45925450Sbrendan 		nextdev = list_next(l2arc_dev_list, dev);
45935450Sbrendan 		if (vd == dev->l2ad_vdev) {
45945450Sbrendan 			remdev = dev;
45955450Sbrendan 			break;
45965450Sbrendan 		}
45975450Sbrendan 	}
45985450Sbrendan 	ASSERT(remdev != NULL);
45995450Sbrendan 
46005450Sbrendan 	/*
46015450Sbrendan 	 * Remove device from global list
46025450Sbrendan 	 */
46035450Sbrendan 	list_remove(l2arc_dev_list, remdev);
46045450Sbrendan 	l2arc_dev_last = NULL;		/* may have been invalidated */
46056987Sbrendan 	atomic_dec_64(&l2arc_ndev);
46066987Sbrendan 	mutex_exit(&l2arc_dev_mtx);
46075450Sbrendan 
46085450Sbrendan 	/*
46095450Sbrendan 	 * Clear all buflists and ARC references.  L2ARC device flush.
46105450Sbrendan 	 */
46115450Sbrendan 	l2arc_evict(remdev, 0, B_TRUE);
46125450Sbrendan 	list_destroy(remdev->l2ad_buflist);
46135450Sbrendan 	kmem_free(remdev->l2ad_buflist, sizeof (list_t));
46145450Sbrendan 	kmem_free(remdev, sizeof (l2arc_dev_t));
46155450Sbrendan }
46165450Sbrendan 
46175450Sbrendan void
46187754SJeff.Bonwick@Sun.COM l2arc_init(void)
46195450Sbrendan {
46205450Sbrendan 	l2arc_thread_exit = 0;
46215450Sbrendan 	l2arc_ndev = 0;
46225450Sbrendan 	l2arc_writes_sent = 0;
46235450Sbrendan 	l2arc_writes_done = 0;
46245450Sbrendan 
46255450Sbrendan 	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
46265450Sbrendan 	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
46275450Sbrendan 	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
46285450Sbrendan 	mutex_init(&l2arc_buflist_mtx, NULL, MUTEX_DEFAULT, NULL);
46295450Sbrendan 	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
46305450Sbrendan 
46315450Sbrendan 	l2arc_dev_list = &L2ARC_dev_list;
46325450Sbrendan 	l2arc_free_on_write = &L2ARC_free_on_write;
46335450Sbrendan 	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
46345450Sbrendan 	    offsetof(l2arc_dev_t, l2ad_node));
46355450Sbrendan 	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
46365450Sbrendan 	    offsetof(l2arc_data_free_t, l2df_list_node));
46375450Sbrendan }
46385450Sbrendan 
46395450Sbrendan void
46407754SJeff.Bonwick@Sun.COM l2arc_fini(void)
46415450Sbrendan {
46426987Sbrendan 	/*
46436987Sbrendan 	 * This is called from dmu_fini(), which is called from spa_fini();
46446987Sbrendan 	 * Because of this, we can assume that all l2arc devices have
46456987Sbrendan 	 * already been removed when the pools themselves were removed.
46466987Sbrendan 	 */
46476987Sbrendan 
46486987Sbrendan 	l2arc_do_free_on_write();
46496987Sbrendan 
46505450Sbrendan 	mutex_destroy(&l2arc_feed_thr_lock);
46515450Sbrendan 	cv_destroy(&l2arc_feed_thr_cv);
46525450Sbrendan 	mutex_destroy(&l2arc_dev_mtx);
46535450Sbrendan 	mutex_destroy(&l2arc_buflist_mtx);
46545450Sbrendan 	mutex_destroy(&l2arc_free_on_write_mtx);
46555450Sbrendan 
46565450Sbrendan 	list_destroy(l2arc_dev_list);
46575450Sbrendan 	list_destroy(l2arc_free_on_write);
46585450Sbrendan }
46597754SJeff.Bonwick@Sun.COM 
46607754SJeff.Bonwick@Sun.COM void
46617754SJeff.Bonwick@Sun.COM l2arc_start(void)
46627754SJeff.Bonwick@Sun.COM {
46638241SJeff.Bonwick@Sun.COM 	if (!(spa_mode_global & FWRITE))
46647754SJeff.Bonwick@Sun.COM 		return;
46657754SJeff.Bonwick@Sun.COM 
46667754SJeff.Bonwick@Sun.COM 	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
46677754SJeff.Bonwick@Sun.COM 	    TS_RUN, minclsyspri);
46687754SJeff.Bonwick@Sun.COM }
46697754SJeff.Bonwick@Sun.COM 
46707754SJeff.Bonwick@Sun.COM void
46717754SJeff.Bonwick@Sun.COM l2arc_stop(void)
46727754SJeff.Bonwick@Sun.COM {
46738241SJeff.Bonwick@Sun.COM 	if (!(spa_mode_global & FWRITE))
46747754SJeff.Bonwick@Sun.COM 		return;
46757754SJeff.Bonwick@Sun.COM 
46767754SJeff.Bonwick@Sun.COM 	mutex_enter(&l2arc_feed_thr_lock);
46777754SJeff.Bonwick@Sun.COM 	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
46787754SJeff.Bonwick@Sun.COM 	l2arc_thread_exit = 1;
46797754SJeff.Bonwick@Sun.COM 	while (l2arc_thread_exit != 0)
46807754SJeff.Bonwick@Sun.COM 		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
46817754SJeff.Bonwick@Sun.COM 	mutex_exit(&l2arc_feed_thr_lock);
46827754SJeff.Bonwick@Sun.COM }
4683