xref: /onnv-gate/usr/src/uts/common/fs/zfs/arc.c (revision 6987)
1789Sahrens /*
2789Sahrens  * CDDL HEADER START
3789Sahrens  *
4789Sahrens  * The contents of this file are subject to the terms of the
51484Sek110237  * Common Development and Distribution License (the "License").
61484Sek110237  * You may not use this file except in compliance with the License.
7789Sahrens  *
8789Sahrens  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9789Sahrens  * or http://www.opensolaris.org/os/licensing.
10789Sahrens  * See the License for the specific language governing permissions
11789Sahrens  * and limitations under the License.
12789Sahrens  *
13789Sahrens  * When distributing Covered Code, include this CDDL HEADER in each
14789Sahrens  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15789Sahrens  * If applicable, add the following below this CDDL HEADER, with the
16789Sahrens  * fields enclosed by brackets "[]" replaced with your own identifying
17789Sahrens  * information: Portions Copyright [yyyy] [name of copyright owner]
18789Sahrens  *
19789Sahrens  * CDDL HEADER END
20789Sahrens  */
21789Sahrens /*
226018Sbrendan  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23789Sahrens  * Use is subject to license terms.
24789Sahrens  */
25789Sahrens 
26789Sahrens #pragma ident	"%Z%%M%	%I%	%E% SMI"
27789Sahrens 
28789Sahrens /*
293403Sbmc  * DVA-based Adjustable Replacement Cache
30789Sahrens  *
311544Seschrock  * While much of the theory of operation used here is
321544Seschrock  * based on the self-tuning, low overhead replacement cache
33789Sahrens  * presented by Megiddo and Modha at FAST 2003, there are some
34789Sahrens  * significant differences:
35789Sahrens  *
36789Sahrens  * 1. The Megiddo and Modha model assumes any page is evictable.
37789Sahrens  * Pages in its cache cannot be "locked" into memory.  This makes
38789Sahrens  * the eviction algorithm simple: evict the last page in the list.
39789Sahrens  * This also make the performance characteristics easy to reason
40789Sahrens  * about.  Our cache is not so simple.  At any given moment, some
41789Sahrens  * subset of the blocks in the cache are un-evictable because we
42789Sahrens  * have handed out a reference to them.  Blocks are only evictable
43789Sahrens  * when there are no external references active.  This makes
44789Sahrens  * eviction far more problematic:  we choose to evict the evictable
45789Sahrens  * blocks that are the "lowest" in the list.
46789Sahrens  *
47789Sahrens  * There are times when it is not possible to evict the requested
48789Sahrens  * space.  In these circumstances we are unable to adjust the cache
49789Sahrens  * size.  To prevent the cache growing unbounded at these times we
505450Sbrendan  * implement a "cache throttle" that slows the flow of new data
515450Sbrendan  * into the cache until we can make space available.
52789Sahrens  *
53789Sahrens  * 2. The Megiddo and Modha model assumes a fixed cache size.
54789Sahrens  * Pages are evicted when the cache is full and there is a cache
55789Sahrens  * miss.  Our model has a variable sized cache.  It grows with
565450Sbrendan  * high use, but also tries to react to memory pressure from the
57789Sahrens  * operating system: decreasing its size when system memory is
58789Sahrens  * tight.
59789Sahrens  *
60789Sahrens  * 3. The Megiddo and Modha model assumes a fixed page size. All
61789Sahrens  * elements of the cache are therefor exactly the same size.  So
62789Sahrens  * when adjusting the cache size following a cache miss, its simply
63789Sahrens  * a matter of choosing a single page to evict.  In our model, we
64789Sahrens  * have variable sized cache blocks (rangeing from 512 bytes to
65789Sahrens  * 128K bytes).  We therefor choose a set of blocks to evict to make
66789Sahrens  * space for a cache miss that approximates as closely as possible
67789Sahrens  * the space used by the new block.
68789Sahrens  *
69789Sahrens  * See also:  "ARC: A Self-Tuning, Low Overhead Replacement Cache"
70789Sahrens  * by N. Megiddo & D. Modha, FAST 2003
71789Sahrens  */
72789Sahrens 
73789Sahrens /*
74789Sahrens  * The locking model:
75789Sahrens  *
76789Sahrens  * A new reference to a cache buffer can be obtained in two
77789Sahrens  * ways: 1) via a hash table lookup using the DVA as a key,
785450Sbrendan  * or 2) via one of the ARC lists.  The arc_read() interface
79789Sahrens  * uses method 1, while the internal arc algorithms for
80789Sahrens  * adjusting the cache use method 2.  We therefor provide two
81789Sahrens  * types of locks: 1) the hash table lock array, and 2) the
82789Sahrens  * arc list locks.
83789Sahrens  *
84789Sahrens  * Buffers do not have their own mutexs, rather they rely on the
85789Sahrens  * hash table mutexs for the bulk of their protection (i.e. most
86789Sahrens  * fields in the arc_buf_hdr_t are protected by these mutexs).
87789Sahrens  *
88789Sahrens  * buf_hash_find() returns the appropriate mutex (held) when it
89789Sahrens  * locates the requested buffer in the hash table.  It returns
90789Sahrens  * NULL for the mutex if the buffer was not in the table.
91789Sahrens  *
92789Sahrens  * buf_hash_remove() expects the appropriate hash mutex to be
93789Sahrens  * already held before it is invoked.
94789Sahrens  *
95789Sahrens  * Each arc state also has a mutex which is used to protect the
96789Sahrens  * buffer list associated with the state.  When attempting to
97789Sahrens  * obtain a hash table lock while holding an arc list lock you
98789Sahrens  * must use: mutex_tryenter() to avoid deadlock.  Also note that
992688Smaybee  * the active state mutex must be held before the ghost state mutex.
100789Sahrens  *
1011544Seschrock  * Arc buffers may have an associated eviction callback function.
1021544Seschrock  * This function will be invoked prior to removing the buffer (e.g.
1031544Seschrock  * in arc_do_user_evicts()).  Note however that the data associated
1041544Seschrock  * with the buffer may be evicted prior to the callback.  The callback
1051544Seschrock  * must be made with *no locks held* (to prevent deadlock).  Additionally,
1061544Seschrock  * the users of callbacks must ensure that their private data is
1071544Seschrock  * protected from simultaneous callbacks from arc_buf_evict()
1081544Seschrock  * and arc_do_user_evicts().
1091544Seschrock  *
110789Sahrens  * Note that the majority of the performance stats are manipulated
111789Sahrens  * with atomic operations.
1125450Sbrendan  *
1135450Sbrendan  * The L2ARC uses the l2arc_buflist_mtx global mutex for the following:
1145450Sbrendan  *
1155450Sbrendan  *	- L2ARC buflist creation
1165450Sbrendan  *	- L2ARC buflist eviction
1175450Sbrendan  *	- L2ARC write completion, which walks L2ARC buflists
1185450Sbrendan  *	- ARC header destruction, as it removes from L2ARC buflists
1195450Sbrendan  *	- ARC header release, as it removes from L2ARC buflists
120789Sahrens  */
121789Sahrens 
122789Sahrens #include <sys/spa.h>
123789Sahrens #include <sys/zio.h>
1243093Sahrens #include <sys/zio_checksum.h>
125789Sahrens #include <sys/zfs_context.h>
126789Sahrens #include <sys/arc.h>
127789Sahrens #include <sys/refcount.h>
1286643Seschrock #include <sys/vdev.h>
129789Sahrens #ifdef _KERNEL
130789Sahrens #include <sys/vmsystm.h>
131789Sahrens #include <vm/anon.h>
132789Sahrens #include <sys/fs/swapnode.h>
1331484Sek110237 #include <sys/dnlc.h>
134789Sahrens #endif
135789Sahrens #include <sys/callb.h>
1363403Sbmc #include <sys/kstat.h>
137789Sahrens 
138789Sahrens static kmutex_t		arc_reclaim_thr_lock;
139789Sahrens static kcondvar_t	arc_reclaim_thr_cv;	/* used to signal reclaim thr */
140789Sahrens static uint8_t		arc_thread_exit;
141789Sahrens 
1426245Smaybee extern int zfs_write_limit_shift;
1436245Smaybee extern uint64_t zfs_write_limit_max;
1446245Smaybee extern uint64_t zfs_write_limit_inflated;
1456245Smaybee 
1461484Sek110237 #define	ARC_REDUCE_DNLC_PERCENT	3
1471484Sek110237 uint_t arc_reduce_dnlc_percent = ARC_REDUCE_DNLC_PERCENT;
1481484Sek110237 
149789Sahrens typedef enum arc_reclaim_strategy {
150789Sahrens 	ARC_RECLAIM_AGGR,		/* Aggressive reclaim strategy */
151789Sahrens 	ARC_RECLAIM_CONS		/* Conservative reclaim strategy */
152789Sahrens } arc_reclaim_strategy_t;
153789Sahrens 
154789Sahrens /* number of seconds before growing cache again */
155789Sahrens static int		arc_grow_retry = 60;
156789Sahrens 
1572391Smaybee /*
1582638Sperrin  * minimum lifespan of a prefetch block in clock ticks
1592638Sperrin  * (initialized in arc_init())
1602391Smaybee  */
1612638Sperrin static int		arc_min_prefetch_lifespan;
1622391Smaybee 
163789Sahrens static int arc_dead;
164789Sahrens 
165789Sahrens /*
166*6987Sbrendan  * The arc has filled available memory and has now warmed up.
167*6987Sbrendan  */
168*6987Sbrendan static boolean_t arc_warm;
169*6987Sbrendan 
170*6987Sbrendan /*
1712885Sahrens  * These tunables are for performance analysis.
1722885Sahrens  */
1732885Sahrens uint64_t zfs_arc_max;
1742885Sahrens uint64_t zfs_arc_min;
1754645Sek110237 uint64_t zfs_arc_meta_limit = 0;
1762885Sahrens 
1772885Sahrens /*
1785450Sbrendan  * Note that buffers can be in one of 6 states:
179789Sahrens  *	ARC_anon	- anonymous (discussed below)
1801544Seschrock  *	ARC_mru		- recently used, currently cached
1811544Seschrock  *	ARC_mru_ghost	- recentely used, no longer in cache
1821544Seschrock  *	ARC_mfu		- frequently used, currently cached
1831544Seschrock  *	ARC_mfu_ghost	- frequently used, no longer in cache
1845450Sbrendan  *	ARC_l2c_only	- exists in L2ARC but not other states
1854309Smaybee  * When there are no active references to the buffer, they are
1864309Smaybee  * are linked onto a list in one of these arc states.  These are
1874309Smaybee  * the only buffers that can be evicted or deleted.  Within each
1884309Smaybee  * state there are multiple lists, one for meta-data and one for
1894309Smaybee  * non-meta-data.  Meta-data (indirect blocks, blocks of dnodes,
1904309Smaybee  * etc.) is tracked separately so that it can be managed more
1915450Sbrendan  * explicitly: favored over data, limited explicitly.
192789Sahrens  *
193789Sahrens  * Anonymous buffers are buffers that are not associated with
194789Sahrens  * a DVA.  These are buffers that hold dirty block copies
195789Sahrens  * before they are written to stable storage.  By definition,
1961544Seschrock  * they are "ref'd" and are considered part of arc_mru
197789Sahrens  * that cannot be freed.  Generally, they will aquire a DVA
1981544Seschrock  * as they are written and migrate onto the arc_mru list.
1995450Sbrendan  *
2005450Sbrendan  * The ARC_l2c_only state is for buffers that are in the second
2015450Sbrendan  * level ARC but no longer in any of the ARC_m* lists.  The second
2025450Sbrendan  * level ARC itself may also contain buffers that are in any of
2035450Sbrendan  * the ARC_m* states - meaning that a buffer can exist in two
2045450Sbrendan  * places.  The reason for the ARC_l2c_only state is to keep the
2055450Sbrendan  * buffer header in the hash table, so that reads that hit the
2065450Sbrendan  * second level ARC benefit from these fast lookups.
207789Sahrens  */
208789Sahrens 
209789Sahrens typedef struct arc_state {
2104309Smaybee 	list_t	arcs_list[ARC_BUFC_NUMTYPES];	/* list of evictable buffers */
2114309Smaybee 	uint64_t arcs_lsize[ARC_BUFC_NUMTYPES];	/* amount of evictable data */
2124309Smaybee 	uint64_t arcs_size;	/* total amount of data in this state */
2133403Sbmc 	kmutex_t arcs_mtx;
214789Sahrens } arc_state_t;
215789Sahrens 
2165450Sbrendan /* The 6 states: */
217789Sahrens static arc_state_t ARC_anon;
2181544Seschrock static arc_state_t ARC_mru;
2191544Seschrock static arc_state_t ARC_mru_ghost;
2201544Seschrock static arc_state_t ARC_mfu;
2211544Seschrock static arc_state_t ARC_mfu_ghost;
2225450Sbrendan static arc_state_t ARC_l2c_only;
223789Sahrens 
2243403Sbmc typedef struct arc_stats {
2253403Sbmc 	kstat_named_t arcstat_hits;
2263403Sbmc 	kstat_named_t arcstat_misses;
2273403Sbmc 	kstat_named_t arcstat_demand_data_hits;
2283403Sbmc 	kstat_named_t arcstat_demand_data_misses;
2293403Sbmc 	kstat_named_t arcstat_demand_metadata_hits;
2303403Sbmc 	kstat_named_t arcstat_demand_metadata_misses;
2313403Sbmc 	kstat_named_t arcstat_prefetch_data_hits;
2323403Sbmc 	kstat_named_t arcstat_prefetch_data_misses;
2333403Sbmc 	kstat_named_t arcstat_prefetch_metadata_hits;
2343403Sbmc 	kstat_named_t arcstat_prefetch_metadata_misses;
2353403Sbmc 	kstat_named_t arcstat_mru_hits;
2363403Sbmc 	kstat_named_t arcstat_mru_ghost_hits;
2373403Sbmc 	kstat_named_t arcstat_mfu_hits;
2383403Sbmc 	kstat_named_t arcstat_mfu_ghost_hits;
2393403Sbmc 	kstat_named_t arcstat_deleted;
2403403Sbmc 	kstat_named_t arcstat_recycle_miss;
2413403Sbmc 	kstat_named_t arcstat_mutex_miss;
2423403Sbmc 	kstat_named_t arcstat_evict_skip;
2433403Sbmc 	kstat_named_t arcstat_hash_elements;
2443403Sbmc 	kstat_named_t arcstat_hash_elements_max;
2453403Sbmc 	kstat_named_t arcstat_hash_collisions;
2463403Sbmc 	kstat_named_t arcstat_hash_chains;
2473403Sbmc 	kstat_named_t arcstat_hash_chain_max;
2483403Sbmc 	kstat_named_t arcstat_p;
2493403Sbmc 	kstat_named_t arcstat_c;
2503403Sbmc 	kstat_named_t arcstat_c_min;
2513403Sbmc 	kstat_named_t arcstat_c_max;
2523403Sbmc 	kstat_named_t arcstat_size;
2535450Sbrendan 	kstat_named_t arcstat_hdr_size;
2545450Sbrendan 	kstat_named_t arcstat_l2_hits;
2555450Sbrendan 	kstat_named_t arcstat_l2_misses;
2565450Sbrendan 	kstat_named_t arcstat_l2_feeds;
2575450Sbrendan 	kstat_named_t arcstat_l2_rw_clash;
2585450Sbrendan 	kstat_named_t arcstat_l2_writes_sent;
2595450Sbrendan 	kstat_named_t arcstat_l2_writes_done;
2605450Sbrendan 	kstat_named_t arcstat_l2_writes_error;
2615450Sbrendan 	kstat_named_t arcstat_l2_writes_hdr_miss;
2625450Sbrendan 	kstat_named_t arcstat_l2_evict_lock_retry;
2635450Sbrendan 	kstat_named_t arcstat_l2_evict_reading;
2645450Sbrendan 	kstat_named_t arcstat_l2_free_on_write;
2655450Sbrendan 	kstat_named_t arcstat_l2_abort_lowmem;
2665450Sbrendan 	kstat_named_t arcstat_l2_cksum_bad;
2675450Sbrendan 	kstat_named_t arcstat_l2_io_error;
2685450Sbrendan 	kstat_named_t arcstat_l2_size;
2695450Sbrendan 	kstat_named_t arcstat_l2_hdr_size;
2706245Smaybee 	kstat_named_t arcstat_memory_throttle_count;
2713403Sbmc } arc_stats_t;
2723403Sbmc 
2733403Sbmc static arc_stats_t arc_stats = {
2743403Sbmc 	{ "hits",			KSTAT_DATA_UINT64 },
2753403Sbmc 	{ "misses",			KSTAT_DATA_UINT64 },
2763403Sbmc 	{ "demand_data_hits",		KSTAT_DATA_UINT64 },
2773403Sbmc 	{ "demand_data_misses",		KSTAT_DATA_UINT64 },
2783403Sbmc 	{ "demand_metadata_hits",	KSTAT_DATA_UINT64 },
2793403Sbmc 	{ "demand_metadata_misses",	KSTAT_DATA_UINT64 },
2803403Sbmc 	{ "prefetch_data_hits",		KSTAT_DATA_UINT64 },
2813403Sbmc 	{ "prefetch_data_misses",	KSTAT_DATA_UINT64 },
2823403Sbmc 	{ "prefetch_metadata_hits",	KSTAT_DATA_UINT64 },
2833403Sbmc 	{ "prefetch_metadata_misses",	KSTAT_DATA_UINT64 },
2843403Sbmc 	{ "mru_hits",			KSTAT_DATA_UINT64 },
2853403Sbmc 	{ "mru_ghost_hits",		KSTAT_DATA_UINT64 },
2863403Sbmc 	{ "mfu_hits",			KSTAT_DATA_UINT64 },
2873403Sbmc 	{ "mfu_ghost_hits",		KSTAT_DATA_UINT64 },
2883403Sbmc 	{ "deleted",			KSTAT_DATA_UINT64 },
2893403Sbmc 	{ "recycle_miss",		KSTAT_DATA_UINT64 },
2903403Sbmc 	{ "mutex_miss",			KSTAT_DATA_UINT64 },
2913403Sbmc 	{ "evict_skip",			KSTAT_DATA_UINT64 },
2923403Sbmc 	{ "hash_elements",		KSTAT_DATA_UINT64 },
2933403Sbmc 	{ "hash_elements_max",		KSTAT_DATA_UINT64 },
2943403Sbmc 	{ "hash_collisions",		KSTAT_DATA_UINT64 },
2953403Sbmc 	{ "hash_chains",		KSTAT_DATA_UINT64 },
2963403Sbmc 	{ "hash_chain_max",		KSTAT_DATA_UINT64 },
2973403Sbmc 	{ "p",				KSTAT_DATA_UINT64 },
2983403Sbmc 	{ "c",				KSTAT_DATA_UINT64 },
2993403Sbmc 	{ "c_min",			KSTAT_DATA_UINT64 },
3003403Sbmc 	{ "c_max",			KSTAT_DATA_UINT64 },
3015450Sbrendan 	{ "size",			KSTAT_DATA_UINT64 },
3025450Sbrendan 	{ "hdr_size",			KSTAT_DATA_UINT64 },
3035450Sbrendan 	{ "l2_hits",			KSTAT_DATA_UINT64 },
3045450Sbrendan 	{ "l2_misses",			KSTAT_DATA_UINT64 },
3055450Sbrendan 	{ "l2_feeds",			KSTAT_DATA_UINT64 },
3065450Sbrendan 	{ "l2_rw_clash",		KSTAT_DATA_UINT64 },
3075450Sbrendan 	{ "l2_writes_sent",		KSTAT_DATA_UINT64 },
3085450Sbrendan 	{ "l2_writes_done",		KSTAT_DATA_UINT64 },
3095450Sbrendan 	{ "l2_writes_error",		KSTAT_DATA_UINT64 },
3105450Sbrendan 	{ "l2_writes_hdr_miss",		KSTAT_DATA_UINT64 },
3115450Sbrendan 	{ "l2_evict_lock_retry",	KSTAT_DATA_UINT64 },
3125450Sbrendan 	{ "l2_evict_reading",		KSTAT_DATA_UINT64 },
3135450Sbrendan 	{ "l2_free_on_write",		KSTAT_DATA_UINT64 },
3145450Sbrendan 	{ "l2_abort_lowmem",		KSTAT_DATA_UINT64 },
3155450Sbrendan 	{ "l2_cksum_bad",		KSTAT_DATA_UINT64 },
3165450Sbrendan 	{ "l2_io_error",		KSTAT_DATA_UINT64 },
3175450Sbrendan 	{ "l2_size",			KSTAT_DATA_UINT64 },
3186245Smaybee 	{ "l2_hdr_size",		KSTAT_DATA_UINT64 },
3196245Smaybee 	{ "memory_throttle_count",	KSTAT_DATA_UINT64 }
3203403Sbmc };
321789Sahrens 
3223403Sbmc #define	ARCSTAT(stat)	(arc_stats.stat.value.ui64)
3233403Sbmc 
3243403Sbmc #define	ARCSTAT_INCR(stat, val) \
3253403Sbmc 	atomic_add_64(&arc_stats.stat.value.ui64, (val));
3263403Sbmc 
3273403Sbmc #define	ARCSTAT_BUMP(stat) 	ARCSTAT_INCR(stat, 1)
3283403Sbmc #define	ARCSTAT_BUMPDOWN(stat)	ARCSTAT_INCR(stat, -1)
3293403Sbmc 
3303403Sbmc #define	ARCSTAT_MAX(stat, val) {					\
3313403Sbmc 	uint64_t m;							\
3323403Sbmc 	while ((val) > (m = arc_stats.stat.value.ui64) &&		\
3333403Sbmc 	    (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val))))	\
3343403Sbmc 		continue;						\
3353403Sbmc }
3363403Sbmc 
3373403Sbmc #define	ARCSTAT_MAXSTAT(stat) \
3383403Sbmc 	ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
339789Sahrens 
3403403Sbmc /*
3413403Sbmc  * We define a macro to allow ARC hits/misses to be easily broken down by
3423403Sbmc  * two separate conditions, giving a total of four different subtypes for
3433403Sbmc  * each of hits and misses (so eight statistics total).
3443403Sbmc  */
3453403Sbmc #define	ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
3463403Sbmc 	if (cond1) {							\
3473403Sbmc 		if (cond2) {						\
3483403Sbmc 			ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
3493403Sbmc 		} else {						\
3503403Sbmc 			ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
3513403Sbmc 		}							\
3523403Sbmc 	} else {							\
3533403Sbmc 		if (cond2) {						\
3543403Sbmc 			ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
3553403Sbmc 		} else {						\
3563403Sbmc 			ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
3573403Sbmc 		}							\
3583403Sbmc 	}
359789Sahrens 
3603403Sbmc kstat_t			*arc_ksp;
3613403Sbmc static arc_state_t 	*arc_anon;
3623403Sbmc static arc_state_t	*arc_mru;
3633403Sbmc static arc_state_t	*arc_mru_ghost;
3643403Sbmc static arc_state_t	*arc_mfu;
3653403Sbmc static arc_state_t	*arc_mfu_ghost;
3665450Sbrendan static arc_state_t	*arc_l2c_only;
3673403Sbmc 
3683403Sbmc /*
3693403Sbmc  * There are several ARC variables that are critical to export as kstats --
3703403Sbmc  * but we don't want to have to grovel around in the kstat whenever we wish to
3713403Sbmc  * manipulate them.  For these variables, we therefore define them to be in
3723403Sbmc  * terms of the statistic variable.  This assures that we are not introducing
3733403Sbmc  * the possibility of inconsistency by having shadow copies of the variables,
3743403Sbmc  * while still allowing the code to be readable.
3753403Sbmc  */
3763403Sbmc #define	arc_size	ARCSTAT(arcstat_size)	/* actual total arc size */
3773403Sbmc #define	arc_p		ARCSTAT(arcstat_p)	/* target size of MRU */
3783403Sbmc #define	arc_c		ARCSTAT(arcstat_c)	/* target size of cache */
3793403Sbmc #define	arc_c_min	ARCSTAT(arcstat_c_min)	/* min target cache size */
3803403Sbmc #define	arc_c_max	ARCSTAT(arcstat_c_max)	/* max target cache size */
3813403Sbmc 
3823403Sbmc static int		arc_no_grow;	/* Don't try to grow cache size */
3833403Sbmc static uint64_t		arc_tempreserve;
3844309Smaybee static uint64_t		arc_meta_used;
3854309Smaybee static uint64_t		arc_meta_limit;
3864309Smaybee static uint64_t		arc_meta_max = 0;
387789Sahrens 
3885450Sbrendan typedef struct l2arc_buf_hdr l2arc_buf_hdr_t;
3895450Sbrendan 
390789Sahrens typedef struct arc_callback arc_callback_t;
391789Sahrens 
392789Sahrens struct arc_callback {
3933547Smaybee 	void			*acb_private;
394789Sahrens 	arc_done_func_t		*acb_done;
395789Sahrens 	arc_byteswap_func_t	*acb_byteswap;
396789Sahrens 	arc_buf_t		*acb_buf;
397789Sahrens 	zio_t			*acb_zio_dummy;
398789Sahrens 	arc_callback_t		*acb_next;
399789Sahrens };
400789Sahrens 
4013547Smaybee typedef struct arc_write_callback arc_write_callback_t;
4023547Smaybee 
4033547Smaybee struct arc_write_callback {
4043547Smaybee 	void		*awcb_private;
4053547Smaybee 	arc_done_func_t	*awcb_ready;
4063547Smaybee 	arc_done_func_t	*awcb_done;
4073547Smaybee 	arc_buf_t	*awcb_buf;
4083547Smaybee };
4093547Smaybee 
410789Sahrens struct arc_buf_hdr {
411789Sahrens 	/* protected by hash lock */
412789Sahrens 	dva_t			b_dva;
413789Sahrens 	uint64_t		b_birth;
414789Sahrens 	uint64_t		b_cksum0;
415789Sahrens 
4163093Sahrens 	kmutex_t		b_freeze_lock;
4173093Sahrens 	zio_cksum_t		*b_freeze_cksum;
4183093Sahrens 
419789Sahrens 	arc_buf_hdr_t		*b_hash_next;
420789Sahrens 	arc_buf_t		*b_buf;
421789Sahrens 	uint32_t		b_flags;
4221544Seschrock 	uint32_t		b_datacnt;
423789Sahrens 
4243290Sjohansen 	arc_callback_t		*b_acb;
425789Sahrens 	kcondvar_t		b_cv;
4263290Sjohansen 
4273290Sjohansen 	/* immutable */
4283290Sjohansen 	arc_buf_contents_t	b_type;
4293290Sjohansen 	uint64_t		b_size;
4303290Sjohansen 	spa_t			*b_spa;
431789Sahrens 
432789Sahrens 	/* protected by arc state mutex */
433789Sahrens 	arc_state_t		*b_state;
434789Sahrens 	list_node_t		b_arc_node;
435789Sahrens 
436789Sahrens 	/* updated atomically */
437789Sahrens 	clock_t			b_arc_access;
438789Sahrens 
439789Sahrens 	/* self protecting */
440789Sahrens 	refcount_t		b_refcnt;
4415450Sbrendan 
4425450Sbrendan 	l2arc_buf_hdr_t		*b_l2hdr;
4435450Sbrendan 	list_node_t		b_l2node;
444789Sahrens };
445789Sahrens 
4461544Seschrock static arc_buf_t *arc_eviction_list;
4471544Seschrock static kmutex_t arc_eviction_mtx;
4482887Smaybee static arc_buf_hdr_t arc_eviction_hdr;
4492688Smaybee static void arc_get_data_buf(arc_buf_t *buf);
4502688Smaybee static void arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock);
4514309Smaybee static int arc_evict_needed(arc_buf_contents_t type);
4525642Smaybee static void arc_evict_ghost(arc_state_t *state, spa_t *spa, int64_t bytes);
4531544Seschrock 
4541544Seschrock #define	GHOST_STATE(state)	\
4555450Sbrendan 	((state) == arc_mru_ghost || (state) == arc_mfu_ghost ||	\
4565450Sbrendan 	(state) == arc_l2c_only)
4571544Seschrock 
458789Sahrens /*
459789Sahrens  * Private ARC flags.  These flags are private ARC only flags that will show up
460789Sahrens  * in b_flags in the arc_hdr_buf_t.  Some flags are publicly declared, and can
461789Sahrens  * be passed in as arc_flags in things like arc_read.  However, these flags
462789Sahrens  * should never be passed and should only be set by ARC code.  When adding new
463789Sahrens  * public flags, make sure not to smash the private ones.
464789Sahrens  */
465789Sahrens 
4661544Seschrock #define	ARC_IN_HASH_TABLE	(1 << 9)	/* this buffer is hashed */
467789Sahrens #define	ARC_IO_IN_PROGRESS	(1 << 10)	/* I/O in progress for buf */
468789Sahrens #define	ARC_IO_ERROR		(1 << 11)	/* I/O failed for buf */
469789Sahrens #define	ARC_FREED_IN_READ	(1 << 12)	/* buf freed while in read */
4701544Seschrock #define	ARC_BUF_AVAILABLE	(1 << 13)	/* block not in active use */
4712391Smaybee #define	ARC_INDIRECT		(1 << 14)	/* this is an indirect block */
4725450Sbrendan #define	ARC_FREE_IN_PROGRESS	(1 << 15)	/* hdr about to be freed */
4735450Sbrendan #define	ARC_DONT_L2CACHE	(1 << 16)	/* originated by prefetch */
474*6987Sbrendan #define	ARC_L2_WRITING		(1 << 17)	/* L2ARC write in progress */
475*6987Sbrendan #define	ARC_L2_EVICTED		(1 << 18)	/* evicted during I/O */
476*6987Sbrendan #define	ARC_L2_WRITE_HEAD	(1 << 19)	/* head of write list */
477789Sahrens 
4781544Seschrock #define	HDR_IN_HASH_TABLE(hdr)	((hdr)->b_flags & ARC_IN_HASH_TABLE)
479789Sahrens #define	HDR_IO_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_IO_IN_PROGRESS)
480789Sahrens #define	HDR_IO_ERROR(hdr)	((hdr)->b_flags & ARC_IO_ERROR)
481789Sahrens #define	HDR_FREED_IN_READ(hdr)	((hdr)->b_flags & ARC_FREED_IN_READ)
4821544Seschrock #define	HDR_BUF_AVAILABLE(hdr)	((hdr)->b_flags & ARC_BUF_AVAILABLE)
4835450Sbrendan #define	HDR_FREE_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_FREE_IN_PROGRESS)
4845450Sbrendan #define	HDR_DONT_L2CACHE(hdr)	((hdr)->b_flags & ARC_DONT_L2CACHE)
485*6987Sbrendan #define	HDR_L2_READING(hdr)	((hdr)->b_flags & ARC_IO_IN_PROGRESS &&	\
486*6987Sbrendan 				    (hdr)->b_l2hdr != NULL)
4875450Sbrendan #define	HDR_L2_WRITING(hdr)	((hdr)->b_flags & ARC_L2_WRITING)
4885450Sbrendan #define	HDR_L2_EVICTED(hdr)	((hdr)->b_flags & ARC_L2_EVICTED)
4895450Sbrendan #define	HDR_L2_WRITE_HEAD(hdr)	((hdr)->b_flags & ARC_L2_WRITE_HEAD)
490789Sahrens 
491789Sahrens /*
4926018Sbrendan  * Other sizes
4936018Sbrendan  */
4946018Sbrendan 
4956018Sbrendan #define	HDR_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
4966018Sbrendan #define	L2HDR_SIZE ((int64_t)sizeof (l2arc_buf_hdr_t))
4976018Sbrendan 
4986018Sbrendan /*
499789Sahrens  * Hash table routines
500789Sahrens  */
501789Sahrens 
502789Sahrens #define	HT_LOCK_PAD	64
503789Sahrens 
504789Sahrens struct ht_lock {
505789Sahrens 	kmutex_t	ht_lock;
506789Sahrens #ifdef _KERNEL
507789Sahrens 	unsigned char	pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
508789Sahrens #endif
509789Sahrens };
510789Sahrens 
511789Sahrens #define	BUF_LOCKS 256
512789Sahrens typedef struct buf_hash_table {
513789Sahrens 	uint64_t ht_mask;
514789Sahrens 	arc_buf_hdr_t **ht_table;
515789Sahrens 	struct ht_lock ht_locks[BUF_LOCKS];
516789Sahrens } buf_hash_table_t;
517789Sahrens 
518789Sahrens static buf_hash_table_t buf_hash_table;
519789Sahrens 
520789Sahrens #define	BUF_HASH_INDEX(spa, dva, birth) \
521789Sahrens 	(buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
522789Sahrens #define	BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
523789Sahrens #define	BUF_HASH_LOCK(idx)	(&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
524789Sahrens #define	HDR_LOCK(buf) \
525789Sahrens 	(BUF_HASH_LOCK(BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth)))
526789Sahrens 
527789Sahrens uint64_t zfs_crc64_table[256];
528789Sahrens 
5295450Sbrendan /*
5305450Sbrendan  * Level 2 ARC
5315450Sbrendan  */
5325450Sbrendan 
5335450Sbrendan #define	L2ARC_WRITE_SIZE	(8 * 1024 * 1024)	/* initial write max */
5345450Sbrendan #define	L2ARC_HEADROOM		4		/* num of writes */
5355450Sbrendan #define	L2ARC_FEED_SECS		1		/* caching interval */
5365450Sbrendan 
5375450Sbrendan #define	l2arc_writes_sent	ARCSTAT(arcstat_l2_writes_sent)
5385450Sbrendan #define	l2arc_writes_done	ARCSTAT(arcstat_l2_writes_done)
5395450Sbrendan 
5405450Sbrendan /*
5415450Sbrendan  * L2ARC Performance Tunables
5425450Sbrendan  */
5435450Sbrendan uint64_t l2arc_write_max = L2ARC_WRITE_SIZE;	/* default max write size */
544*6987Sbrendan uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE;	/* extra write during warmup */
5455450Sbrendan uint64_t l2arc_headroom = L2ARC_HEADROOM;	/* number of dev writes */
5465450Sbrendan uint64_t l2arc_feed_secs = L2ARC_FEED_SECS;	/* interval seconds */
5475450Sbrendan boolean_t l2arc_noprefetch = B_TRUE;		/* don't cache prefetch bufs */
5485450Sbrendan 
5495450Sbrendan /*
5505450Sbrendan  * L2ARC Internals
5515450Sbrendan  */
5525450Sbrendan typedef struct l2arc_dev {
5535450Sbrendan 	vdev_t			*l2ad_vdev;	/* vdev */
5545450Sbrendan 	spa_t			*l2ad_spa;	/* spa */
5555450Sbrendan 	uint64_t		l2ad_hand;	/* next write location */
5565450Sbrendan 	uint64_t		l2ad_write;	/* desired write size, bytes */
557*6987Sbrendan 	uint64_t		l2ad_boost;	/* warmup write boost, bytes */
5585450Sbrendan 	uint64_t		l2ad_start;	/* first addr on device */
5595450Sbrendan 	uint64_t		l2ad_end;	/* last addr on device */
5605450Sbrendan 	uint64_t		l2ad_evict;	/* last addr eviction reached */
5615450Sbrendan 	boolean_t		l2ad_first;	/* first sweep through */
5625450Sbrendan 	list_t			*l2ad_buflist;	/* buffer list */
5635450Sbrendan 	list_node_t		l2ad_node;	/* device list node */
5645450Sbrendan } l2arc_dev_t;
5655450Sbrendan 
5665450Sbrendan static list_t L2ARC_dev_list;			/* device list */
5675450Sbrendan static list_t *l2arc_dev_list;			/* device list pointer */
5685450Sbrendan static kmutex_t l2arc_dev_mtx;			/* device list mutex */
5695450Sbrendan static l2arc_dev_t *l2arc_dev_last;		/* last device used */
5705450Sbrendan static kmutex_t l2arc_buflist_mtx;		/* mutex for all buflists */
5715450Sbrendan static list_t L2ARC_free_on_write;		/* free after write buf list */
5725450Sbrendan static list_t *l2arc_free_on_write;		/* free after write list ptr */
5735450Sbrendan static kmutex_t l2arc_free_on_write_mtx;	/* mutex for list */
5745450Sbrendan static uint64_t l2arc_ndev;			/* number of devices */
5755450Sbrendan 
5765450Sbrendan typedef struct l2arc_read_callback {
5775450Sbrendan 	arc_buf_t	*l2rcb_buf;		/* read buffer */
5785450Sbrendan 	spa_t		*l2rcb_spa;		/* spa */
5795450Sbrendan 	blkptr_t	l2rcb_bp;		/* original blkptr */
5805450Sbrendan 	zbookmark_t	l2rcb_zb;		/* original bookmark */
5815450Sbrendan 	int		l2rcb_flags;		/* original flags */
5825450Sbrendan } l2arc_read_callback_t;
5835450Sbrendan 
5845450Sbrendan typedef struct l2arc_write_callback {
5855450Sbrendan 	l2arc_dev_t	*l2wcb_dev;		/* device info */
5865450Sbrendan 	arc_buf_hdr_t	*l2wcb_head;		/* head of write buflist */
5875450Sbrendan } l2arc_write_callback_t;
5885450Sbrendan 
5895450Sbrendan struct l2arc_buf_hdr {
5905450Sbrendan 	/* protected by arc_buf_hdr  mutex */
5915450Sbrendan 	l2arc_dev_t	*b_dev;			/* L2ARC device */
5925450Sbrendan 	daddr_t		b_daddr;		/* disk address, offset byte */
5935450Sbrendan };
5945450Sbrendan 
5955450Sbrendan typedef struct l2arc_data_free {
5965450Sbrendan 	/* protected by l2arc_free_on_write_mtx */
5975450Sbrendan 	void		*l2df_data;
5985450Sbrendan 	size_t		l2df_size;
5995450Sbrendan 	void		(*l2df_func)(void *, size_t);
6005450Sbrendan 	list_node_t	l2df_list_node;
6015450Sbrendan } l2arc_data_free_t;
6025450Sbrendan 
6035450Sbrendan static kmutex_t l2arc_feed_thr_lock;
6045450Sbrendan static kcondvar_t l2arc_feed_thr_cv;
6055450Sbrendan static uint8_t l2arc_thread_exit;
6065450Sbrendan 
6075450Sbrendan static void l2arc_read_done(zio_t *zio);
6085450Sbrendan static void l2arc_hdr_stat_add(void);
6095450Sbrendan static void l2arc_hdr_stat_remove(void);
6105450Sbrendan 
611789Sahrens static uint64_t
612789Sahrens buf_hash(spa_t *spa, dva_t *dva, uint64_t birth)
613789Sahrens {
614789Sahrens 	uintptr_t spav = (uintptr_t)spa;
615789Sahrens 	uint8_t *vdva = (uint8_t *)dva;
616789Sahrens 	uint64_t crc = -1ULL;
617789Sahrens 	int i;
618789Sahrens 
619789Sahrens 	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
620789Sahrens 
621789Sahrens 	for (i = 0; i < sizeof (dva_t); i++)
622789Sahrens 		crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
623789Sahrens 
624789Sahrens 	crc ^= (spav>>8) ^ birth;
625789Sahrens 
626789Sahrens 	return (crc);
627789Sahrens }
628789Sahrens 
629789Sahrens #define	BUF_EMPTY(buf)						\
630789Sahrens 	((buf)->b_dva.dva_word[0] == 0 &&			\
631789Sahrens 	(buf)->b_dva.dva_word[1] == 0 &&			\
632789Sahrens 	(buf)->b_birth == 0)
633789Sahrens 
634789Sahrens #define	BUF_EQUAL(spa, dva, birth, buf)				\
635789Sahrens 	((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) &&	\
636789Sahrens 	((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) &&	\
637789Sahrens 	((buf)->b_birth == birth) && ((buf)->b_spa == spa)
638789Sahrens 
639789Sahrens static arc_buf_hdr_t *
640789Sahrens buf_hash_find(spa_t *spa, dva_t *dva, uint64_t birth, kmutex_t **lockp)
641789Sahrens {
642789Sahrens 	uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
643789Sahrens 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
644789Sahrens 	arc_buf_hdr_t *buf;
645789Sahrens 
646789Sahrens 	mutex_enter(hash_lock);
647789Sahrens 	for (buf = buf_hash_table.ht_table[idx]; buf != NULL;
648789Sahrens 	    buf = buf->b_hash_next) {
649789Sahrens 		if (BUF_EQUAL(spa, dva, birth, buf)) {
650789Sahrens 			*lockp = hash_lock;
651789Sahrens 			return (buf);
652789Sahrens 		}
653789Sahrens 	}
654789Sahrens 	mutex_exit(hash_lock);
655789Sahrens 	*lockp = NULL;
656789Sahrens 	return (NULL);
657789Sahrens }
658789Sahrens 
659789Sahrens /*
660789Sahrens  * Insert an entry into the hash table.  If there is already an element
661789Sahrens  * equal to elem in the hash table, then the already existing element
662789Sahrens  * will be returned and the new element will not be inserted.
663789Sahrens  * Otherwise returns NULL.
664789Sahrens  */
665789Sahrens static arc_buf_hdr_t *
666789Sahrens buf_hash_insert(arc_buf_hdr_t *buf, kmutex_t **lockp)
667789Sahrens {
668789Sahrens 	uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
669789Sahrens 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
670789Sahrens 	arc_buf_hdr_t *fbuf;
6713403Sbmc 	uint32_t i;
672789Sahrens 
6731544Seschrock 	ASSERT(!HDR_IN_HASH_TABLE(buf));
674789Sahrens 	*lockp = hash_lock;
675789Sahrens 	mutex_enter(hash_lock);
676789Sahrens 	for (fbuf = buf_hash_table.ht_table[idx], i = 0; fbuf != NULL;
677789Sahrens 	    fbuf = fbuf->b_hash_next, i++) {
678789Sahrens 		if (BUF_EQUAL(buf->b_spa, &buf->b_dva, buf->b_birth, fbuf))
679789Sahrens 			return (fbuf);
680789Sahrens 	}
681789Sahrens 
682789Sahrens 	buf->b_hash_next = buf_hash_table.ht_table[idx];
683789Sahrens 	buf_hash_table.ht_table[idx] = buf;
6841544Seschrock 	buf->b_flags |= ARC_IN_HASH_TABLE;
685789Sahrens 
686789Sahrens 	/* collect some hash table performance data */
687789Sahrens 	if (i > 0) {
6883403Sbmc 		ARCSTAT_BUMP(arcstat_hash_collisions);
689789Sahrens 		if (i == 1)
6903403Sbmc 			ARCSTAT_BUMP(arcstat_hash_chains);
6913403Sbmc 
6923403Sbmc 		ARCSTAT_MAX(arcstat_hash_chain_max, i);
693789Sahrens 	}
6943403Sbmc 
6953403Sbmc 	ARCSTAT_BUMP(arcstat_hash_elements);
6963403Sbmc 	ARCSTAT_MAXSTAT(arcstat_hash_elements);
697789Sahrens 
698789Sahrens 	return (NULL);
699789Sahrens }
700789Sahrens 
701789Sahrens static void
702789Sahrens buf_hash_remove(arc_buf_hdr_t *buf)
703789Sahrens {
704789Sahrens 	arc_buf_hdr_t *fbuf, **bufp;
705789Sahrens 	uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
706789Sahrens 
707789Sahrens 	ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
7081544Seschrock 	ASSERT(HDR_IN_HASH_TABLE(buf));
709789Sahrens 
710789Sahrens 	bufp = &buf_hash_table.ht_table[idx];
711789Sahrens 	while ((fbuf = *bufp) != buf) {
712789Sahrens 		ASSERT(fbuf != NULL);
713789Sahrens 		bufp = &fbuf->b_hash_next;
714789Sahrens 	}
715789Sahrens 	*bufp = buf->b_hash_next;
716789Sahrens 	buf->b_hash_next = NULL;
7171544Seschrock 	buf->b_flags &= ~ARC_IN_HASH_TABLE;
718789Sahrens 
719789Sahrens 	/* collect some hash table performance data */
7203403Sbmc 	ARCSTAT_BUMPDOWN(arcstat_hash_elements);
7213403Sbmc 
722789Sahrens 	if (buf_hash_table.ht_table[idx] &&
723789Sahrens 	    buf_hash_table.ht_table[idx]->b_hash_next == NULL)
7243403Sbmc 		ARCSTAT_BUMPDOWN(arcstat_hash_chains);
725789Sahrens }
726789Sahrens 
727789Sahrens /*
728789Sahrens  * Global data structures and functions for the buf kmem cache.
729789Sahrens  */
730789Sahrens static kmem_cache_t *hdr_cache;
731789Sahrens static kmem_cache_t *buf_cache;
732789Sahrens 
733789Sahrens static void
734789Sahrens buf_fini(void)
735789Sahrens {
736789Sahrens 	int i;
737789Sahrens 
738789Sahrens 	kmem_free(buf_hash_table.ht_table,
739789Sahrens 	    (buf_hash_table.ht_mask + 1) * sizeof (void *));
740789Sahrens 	for (i = 0; i < BUF_LOCKS; i++)
741789Sahrens 		mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
742789Sahrens 	kmem_cache_destroy(hdr_cache);
743789Sahrens 	kmem_cache_destroy(buf_cache);
744789Sahrens }
745789Sahrens 
746789Sahrens /*
747789Sahrens  * Constructor callback - called when the cache is empty
748789Sahrens  * and a new buf is requested.
749789Sahrens  */
750789Sahrens /* ARGSUSED */
751789Sahrens static int
752789Sahrens hdr_cons(void *vbuf, void *unused, int kmflag)
753789Sahrens {
754789Sahrens 	arc_buf_hdr_t *buf = vbuf;
755789Sahrens 
756789Sahrens 	bzero(buf, sizeof (arc_buf_hdr_t));
757789Sahrens 	refcount_create(&buf->b_refcnt);
758789Sahrens 	cv_init(&buf->b_cv, NULL, CV_DEFAULT, NULL);
7594831Sgw25295 	mutex_init(&buf->b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
7605450Sbrendan 
7616018Sbrendan 	ARCSTAT_INCR(arcstat_hdr_size, HDR_SIZE);
762789Sahrens 	return (0);
763789Sahrens }
764789Sahrens 
765789Sahrens /*
766789Sahrens  * Destructor callback - called when a cached buf is
767789Sahrens  * no longer required.
768789Sahrens  */
769789Sahrens /* ARGSUSED */
770789Sahrens static void
771789Sahrens hdr_dest(void *vbuf, void *unused)
772789Sahrens {
773789Sahrens 	arc_buf_hdr_t *buf = vbuf;
774789Sahrens 
775789Sahrens 	refcount_destroy(&buf->b_refcnt);
776789Sahrens 	cv_destroy(&buf->b_cv);
7774831Sgw25295 	mutex_destroy(&buf->b_freeze_lock);
7785450Sbrendan 
7796018Sbrendan 	ARCSTAT_INCR(arcstat_hdr_size, -HDR_SIZE);
780789Sahrens }
781789Sahrens 
782789Sahrens /*
783789Sahrens  * Reclaim callback -- invoked when memory is low.
784789Sahrens  */
785789Sahrens /* ARGSUSED */
786789Sahrens static void
787789Sahrens hdr_recl(void *unused)
788789Sahrens {
789789Sahrens 	dprintf("hdr_recl called\n");
7903158Smaybee 	/*
7913158Smaybee 	 * umem calls the reclaim func when we destroy the buf cache,
7923158Smaybee 	 * which is after we do arc_fini().
7933158Smaybee 	 */
7943158Smaybee 	if (!arc_dead)
7953158Smaybee 		cv_signal(&arc_reclaim_thr_cv);
796789Sahrens }
797789Sahrens 
798789Sahrens static void
799789Sahrens buf_init(void)
800789Sahrens {
801789Sahrens 	uint64_t *ct;
8021544Seschrock 	uint64_t hsize = 1ULL << 12;
803789Sahrens 	int i, j;
804789Sahrens 
805789Sahrens 	/*
806789Sahrens 	 * The hash table is big enough to fill all of physical memory
8071544Seschrock 	 * with an average 64K block size.  The table will take up
8081544Seschrock 	 * totalmem*sizeof(void*)/64K (eg. 128KB/GB with 8-byte pointers).
809789Sahrens 	 */
8101544Seschrock 	while (hsize * 65536 < physmem * PAGESIZE)
811789Sahrens 		hsize <<= 1;
8121544Seschrock retry:
813789Sahrens 	buf_hash_table.ht_mask = hsize - 1;
8141544Seschrock 	buf_hash_table.ht_table =
8151544Seschrock 	    kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
8161544Seschrock 	if (buf_hash_table.ht_table == NULL) {
8171544Seschrock 		ASSERT(hsize > (1ULL << 8));
8181544Seschrock 		hsize >>= 1;
8191544Seschrock 		goto retry;
8201544Seschrock 	}
821789Sahrens 
822789Sahrens 	hdr_cache = kmem_cache_create("arc_buf_hdr_t", sizeof (arc_buf_hdr_t),
823789Sahrens 	    0, hdr_cons, hdr_dest, hdr_recl, NULL, NULL, 0);
824789Sahrens 	buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
825789Sahrens 	    0, NULL, NULL, NULL, NULL, NULL, 0);
826789Sahrens 
827789Sahrens 	for (i = 0; i < 256; i++)
828789Sahrens 		for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
829789Sahrens 			*ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
830789Sahrens 
831789Sahrens 	for (i = 0; i < BUF_LOCKS; i++) {
832789Sahrens 		mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
833789Sahrens 		    NULL, MUTEX_DEFAULT, NULL);
834789Sahrens 	}
835789Sahrens }
836789Sahrens 
837789Sahrens #define	ARC_MINTIME	(hz>>4) /* 62 ms */
838789Sahrens 
839789Sahrens static void
8403093Sahrens arc_cksum_verify(arc_buf_t *buf)
8413093Sahrens {
8423093Sahrens 	zio_cksum_t zc;
8433093Sahrens 
8443312Sahrens 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
8453093Sahrens 		return;
8463093Sahrens 
8473093Sahrens 	mutex_enter(&buf->b_hdr->b_freeze_lock);
8483265Sahrens 	if (buf->b_hdr->b_freeze_cksum == NULL ||
8493265Sahrens 	    (buf->b_hdr->b_flags & ARC_IO_ERROR)) {
8503093Sahrens 		mutex_exit(&buf->b_hdr->b_freeze_lock);
8513093Sahrens 		return;
8523093Sahrens 	}
8533093Sahrens 	fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
8543093Sahrens 	if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
8553093Sahrens 		panic("buffer modified while frozen!");
8563093Sahrens 	mutex_exit(&buf->b_hdr->b_freeze_lock);
8573093Sahrens }
8583093Sahrens 
8595450Sbrendan static int
8605450Sbrendan arc_cksum_equal(arc_buf_t *buf)
8615450Sbrendan {
8625450Sbrendan 	zio_cksum_t zc;
8635450Sbrendan 	int equal;
8645450Sbrendan 
8655450Sbrendan 	mutex_enter(&buf->b_hdr->b_freeze_lock);
8665450Sbrendan 	fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
8675450Sbrendan 	equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
8685450Sbrendan 	mutex_exit(&buf->b_hdr->b_freeze_lock);
8695450Sbrendan 
8705450Sbrendan 	return (equal);
8715450Sbrendan }
8725450Sbrendan 
8733093Sahrens static void
8745450Sbrendan arc_cksum_compute(arc_buf_t *buf, boolean_t force)
8753093Sahrens {
8765450Sbrendan 	if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
8773093Sahrens 		return;
8783093Sahrens 
8793093Sahrens 	mutex_enter(&buf->b_hdr->b_freeze_lock);
8803093Sahrens 	if (buf->b_hdr->b_freeze_cksum != NULL) {
8813093Sahrens 		mutex_exit(&buf->b_hdr->b_freeze_lock);
8823093Sahrens 		return;
8833093Sahrens 	}
8843093Sahrens 	buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
8853093Sahrens 	fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
8863093Sahrens 	    buf->b_hdr->b_freeze_cksum);
8873093Sahrens 	mutex_exit(&buf->b_hdr->b_freeze_lock);
8883093Sahrens }
8893093Sahrens 
8903093Sahrens void
8913093Sahrens arc_buf_thaw(arc_buf_t *buf)
8923093Sahrens {
8935450Sbrendan 	if (zfs_flags & ZFS_DEBUG_MODIFY) {
8945450Sbrendan 		if (buf->b_hdr->b_state != arc_anon)
8955450Sbrendan 			panic("modifying non-anon buffer!");
8965450Sbrendan 		if (buf->b_hdr->b_flags & ARC_IO_IN_PROGRESS)
8975450Sbrendan 			panic("modifying buffer while i/o in progress!");
8985450Sbrendan 		arc_cksum_verify(buf);
8995450Sbrendan 	}
9005450Sbrendan 
9013093Sahrens 	mutex_enter(&buf->b_hdr->b_freeze_lock);
9023093Sahrens 	if (buf->b_hdr->b_freeze_cksum != NULL) {
9033093Sahrens 		kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
9043093Sahrens 		buf->b_hdr->b_freeze_cksum = NULL;
9053093Sahrens 	}
9063093Sahrens 	mutex_exit(&buf->b_hdr->b_freeze_lock);
9073093Sahrens }
9083093Sahrens 
9093093Sahrens void
9103093Sahrens arc_buf_freeze(arc_buf_t *buf)
9113093Sahrens {
9123312Sahrens 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
9133312Sahrens 		return;
9143312Sahrens 
9153093Sahrens 	ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
9163403Sbmc 	    buf->b_hdr->b_state == arc_anon);
9175450Sbrendan 	arc_cksum_compute(buf, B_FALSE);
9183093Sahrens }
9193093Sahrens 
9203093Sahrens static void
921789Sahrens add_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
922789Sahrens {
923789Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
924789Sahrens 
925789Sahrens 	if ((refcount_add(&ab->b_refcnt, tag) == 1) &&
9263403Sbmc 	    (ab->b_state != arc_anon)) {
9273700Sek110237 		uint64_t delta = ab->b_size * ab->b_datacnt;
9284309Smaybee 		list_t *list = &ab->b_state->arcs_list[ab->b_type];
9294309Smaybee 		uint64_t *size = &ab->b_state->arcs_lsize[ab->b_type];
930789Sahrens 
9313403Sbmc 		ASSERT(!MUTEX_HELD(&ab->b_state->arcs_mtx));
9323403Sbmc 		mutex_enter(&ab->b_state->arcs_mtx);
933789Sahrens 		ASSERT(list_link_active(&ab->b_arc_node));
9344309Smaybee 		list_remove(list, ab);
9351544Seschrock 		if (GHOST_STATE(ab->b_state)) {
9361544Seschrock 			ASSERT3U(ab->b_datacnt, ==, 0);
9371544Seschrock 			ASSERT3P(ab->b_buf, ==, NULL);
9381544Seschrock 			delta = ab->b_size;
9391544Seschrock 		}
9401544Seschrock 		ASSERT(delta > 0);
9414309Smaybee 		ASSERT3U(*size, >=, delta);
9424309Smaybee 		atomic_add_64(size, -delta);
9433403Sbmc 		mutex_exit(&ab->b_state->arcs_mtx);
9442391Smaybee 		/* remove the prefetch flag is we get a reference */
9452391Smaybee 		if (ab->b_flags & ARC_PREFETCH)
9462391Smaybee 			ab->b_flags &= ~ARC_PREFETCH;
947789Sahrens 	}
948789Sahrens }
949789Sahrens 
950789Sahrens static int
951789Sahrens remove_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
952789Sahrens {
953789Sahrens 	int cnt;
9543403Sbmc 	arc_state_t *state = ab->b_state;
955789Sahrens 
9563403Sbmc 	ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
9573403Sbmc 	ASSERT(!GHOST_STATE(state));
958789Sahrens 
959789Sahrens 	if (((cnt = refcount_remove(&ab->b_refcnt, tag)) == 0) &&
9603403Sbmc 	    (state != arc_anon)) {
9614309Smaybee 		uint64_t *size = &state->arcs_lsize[ab->b_type];
9624309Smaybee 
9633403Sbmc 		ASSERT(!MUTEX_HELD(&state->arcs_mtx));
9643403Sbmc 		mutex_enter(&state->arcs_mtx);
965789Sahrens 		ASSERT(!list_link_active(&ab->b_arc_node));
9664309Smaybee 		list_insert_head(&state->arcs_list[ab->b_type], ab);
9671544Seschrock 		ASSERT(ab->b_datacnt > 0);
9684309Smaybee 		atomic_add_64(size, ab->b_size * ab->b_datacnt);
9693403Sbmc 		mutex_exit(&state->arcs_mtx);
970789Sahrens 	}
971789Sahrens 	return (cnt);
972789Sahrens }
973789Sahrens 
974789Sahrens /*
975789Sahrens  * Move the supplied buffer to the indicated state.  The mutex
976789Sahrens  * for the buffer must be held by the caller.
977789Sahrens  */
978789Sahrens static void
9791544Seschrock arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *ab, kmutex_t *hash_lock)
980789Sahrens {
9811544Seschrock 	arc_state_t *old_state = ab->b_state;
9823700Sek110237 	int64_t refcnt = refcount_count(&ab->b_refcnt);
9833700Sek110237 	uint64_t from_delta, to_delta;
984789Sahrens 
985789Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
9861544Seschrock 	ASSERT(new_state != old_state);
9871544Seschrock 	ASSERT(refcnt == 0 || ab->b_datacnt > 0);
9881544Seschrock 	ASSERT(ab->b_datacnt == 0 || !GHOST_STATE(new_state));
9891544Seschrock 
9901544Seschrock 	from_delta = to_delta = ab->b_datacnt * ab->b_size;
991789Sahrens 
992789Sahrens 	/*
993789Sahrens 	 * If this buffer is evictable, transfer it from the
994789Sahrens 	 * old state list to the new state list.
995789Sahrens 	 */
9961544Seschrock 	if (refcnt == 0) {
9973403Sbmc 		if (old_state != arc_anon) {
9983403Sbmc 			int use_mutex = !MUTEX_HELD(&old_state->arcs_mtx);
9994309Smaybee 			uint64_t *size = &old_state->arcs_lsize[ab->b_type];
10001544Seschrock 
10011544Seschrock 			if (use_mutex)
10023403Sbmc 				mutex_enter(&old_state->arcs_mtx);
10031544Seschrock 
10041544Seschrock 			ASSERT(list_link_active(&ab->b_arc_node));
10054309Smaybee 			list_remove(&old_state->arcs_list[ab->b_type], ab);
1006789Sahrens 
10072391Smaybee 			/*
10082391Smaybee 			 * If prefetching out of the ghost cache,
10092391Smaybee 			 * we will have a non-null datacnt.
10102391Smaybee 			 */
10112391Smaybee 			if (GHOST_STATE(old_state) && ab->b_datacnt == 0) {
10122391Smaybee 				/* ghost elements have a ghost size */
10131544Seschrock 				ASSERT(ab->b_buf == NULL);
10141544Seschrock 				from_delta = ab->b_size;
1015789Sahrens 			}
10164309Smaybee 			ASSERT3U(*size, >=, from_delta);
10174309Smaybee 			atomic_add_64(size, -from_delta);
10181544Seschrock 
10191544Seschrock 			if (use_mutex)
10203403Sbmc 				mutex_exit(&old_state->arcs_mtx);
1021789Sahrens 		}
10223403Sbmc 		if (new_state != arc_anon) {
10233403Sbmc 			int use_mutex = !MUTEX_HELD(&new_state->arcs_mtx);
10244309Smaybee 			uint64_t *size = &new_state->arcs_lsize[ab->b_type];
1025789Sahrens 
10261544Seschrock 			if (use_mutex)
10273403Sbmc 				mutex_enter(&new_state->arcs_mtx);
10281544Seschrock 
10294309Smaybee 			list_insert_head(&new_state->arcs_list[ab->b_type], ab);
10301544Seschrock 
10311544Seschrock 			/* ghost elements have a ghost size */
10321544Seschrock 			if (GHOST_STATE(new_state)) {
10331544Seschrock 				ASSERT(ab->b_datacnt == 0);
10341544Seschrock 				ASSERT(ab->b_buf == NULL);
10351544Seschrock 				to_delta = ab->b_size;
10361544Seschrock 			}
10374309Smaybee 			atomic_add_64(size, to_delta);
10381544Seschrock 
10391544Seschrock 			if (use_mutex)
10403403Sbmc 				mutex_exit(&new_state->arcs_mtx);
1041789Sahrens 		}
1042789Sahrens 	}
1043789Sahrens 
1044789Sahrens 	ASSERT(!BUF_EMPTY(ab));
10455450Sbrendan 	if (new_state == arc_anon) {
1046789Sahrens 		buf_hash_remove(ab);
1047789Sahrens 	}
1048789Sahrens 
10491544Seschrock 	/* adjust state sizes */
10501544Seschrock 	if (to_delta)
10513403Sbmc 		atomic_add_64(&new_state->arcs_size, to_delta);
10521544Seschrock 	if (from_delta) {
10533403Sbmc 		ASSERT3U(old_state->arcs_size, >=, from_delta);
10543403Sbmc 		atomic_add_64(&old_state->arcs_size, -from_delta);
1055789Sahrens 	}
1056789Sahrens 	ab->b_state = new_state;
10575450Sbrendan 
10585450Sbrendan 	/* adjust l2arc hdr stats */
10595450Sbrendan 	if (new_state == arc_l2c_only)
10605450Sbrendan 		l2arc_hdr_stat_add();
10615450Sbrendan 	else if (old_state == arc_l2c_only)
10625450Sbrendan 		l2arc_hdr_stat_remove();
1063789Sahrens }
1064789Sahrens 
10654309Smaybee void
10664309Smaybee arc_space_consume(uint64_t space)
10674309Smaybee {
10684309Smaybee 	atomic_add_64(&arc_meta_used, space);
10694309Smaybee 	atomic_add_64(&arc_size, space);
10704309Smaybee }
10714309Smaybee 
10724309Smaybee void
10734309Smaybee arc_space_return(uint64_t space)
10744309Smaybee {
10754309Smaybee 	ASSERT(arc_meta_used >= space);
10764309Smaybee 	if (arc_meta_max < arc_meta_used)
10774309Smaybee 		arc_meta_max = arc_meta_used;
10784309Smaybee 	atomic_add_64(&arc_meta_used, -space);
10794309Smaybee 	ASSERT(arc_size >= space);
10804309Smaybee 	atomic_add_64(&arc_size, -space);
10814309Smaybee }
10824309Smaybee 
10834309Smaybee void *
10844309Smaybee arc_data_buf_alloc(uint64_t size)
10854309Smaybee {
10864309Smaybee 	if (arc_evict_needed(ARC_BUFC_DATA))
10874309Smaybee 		cv_signal(&arc_reclaim_thr_cv);
10884309Smaybee 	atomic_add_64(&arc_size, size);
10894309Smaybee 	return (zio_data_buf_alloc(size));
10904309Smaybee }
10914309Smaybee 
10924309Smaybee void
10934309Smaybee arc_data_buf_free(void *buf, uint64_t size)
10944309Smaybee {
10954309Smaybee 	zio_data_buf_free(buf, size);
10964309Smaybee 	ASSERT(arc_size >= size);
10974309Smaybee 	atomic_add_64(&arc_size, -size);
10984309Smaybee }
10994309Smaybee 
1100789Sahrens arc_buf_t *
11013290Sjohansen arc_buf_alloc(spa_t *spa, int size, void *tag, arc_buf_contents_t type)
1102789Sahrens {
1103789Sahrens 	arc_buf_hdr_t *hdr;
1104789Sahrens 	arc_buf_t *buf;
1105789Sahrens 
1106789Sahrens 	ASSERT3U(size, >, 0);
11076245Smaybee 	hdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
1108789Sahrens 	ASSERT(BUF_EMPTY(hdr));
1109789Sahrens 	hdr->b_size = size;
11103290Sjohansen 	hdr->b_type = type;
1111789Sahrens 	hdr->b_spa = spa;
11123403Sbmc 	hdr->b_state = arc_anon;
1113789Sahrens 	hdr->b_arc_access = 0;
11146245Smaybee 	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1115789Sahrens 	buf->b_hdr = hdr;
11162688Smaybee 	buf->b_data = NULL;
11171544Seschrock 	buf->b_efunc = NULL;
11181544Seschrock 	buf->b_private = NULL;
1119789Sahrens 	buf->b_next = NULL;
1120789Sahrens 	hdr->b_buf = buf;
11212688Smaybee 	arc_get_data_buf(buf);
11221544Seschrock 	hdr->b_datacnt = 1;
1123789Sahrens 	hdr->b_flags = 0;
1124789Sahrens 	ASSERT(refcount_is_zero(&hdr->b_refcnt));
1125789Sahrens 	(void) refcount_add(&hdr->b_refcnt, tag);
1126789Sahrens 
1127789Sahrens 	return (buf);
1128789Sahrens }
1129789Sahrens 
11302688Smaybee static arc_buf_t *
11312688Smaybee arc_buf_clone(arc_buf_t *from)
11321544Seschrock {
11332688Smaybee 	arc_buf_t *buf;
11342688Smaybee 	arc_buf_hdr_t *hdr = from->b_hdr;
11352688Smaybee 	uint64_t size = hdr->b_size;
11361544Seschrock 
11376245Smaybee 	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
11382688Smaybee 	buf->b_hdr = hdr;
11392688Smaybee 	buf->b_data = NULL;
11402688Smaybee 	buf->b_efunc = NULL;
11412688Smaybee 	buf->b_private = NULL;
11422688Smaybee 	buf->b_next = hdr->b_buf;
11432688Smaybee 	hdr->b_buf = buf;
11442688Smaybee 	arc_get_data_buf(buf);
11452688Smaybee 	bcopy(from->b_data, buf->b_data, size);
11462688Smaybee 	hdr->b_datacnt += 1;
11472688Smaybee 	return (buf);
11481544Seschrock }
11491544Seschrock 
11501544Seschrock void
11511544Seschrock arc_buf_add_ref(arc_buf_t *buf, void* tag)
11521544Seschrock {
11532887Smaybee 	arc_buf_hdr_t *hdr;
11541544Seschrock 	kmutex_t *hash_lock;
11551544Seschrock 
11562724Smaybee 	/*
11572724Smaybee 	 * Check to see if this buffer is currently being evicted via
11582887Smaybee 	 * arc_do_user_evicts().
11592724Smaybee 	 */
11602887Smaybee 	mutex_enter(&arc_eviction_mtx);
11612887Smaybee 	hdr = buf->b_hdr;
11622887Smaybee 	if (hdr == NULL) {
11632887Smaybee 		mutex_exit(&arc_eviction_mtx);
11642724Smaybee 		return;
11652887Smaybee 	}
11662887Smaybee 	hash_lock = HDR_LOCK(hdr);
11672887Smaybee 	mutex_exit(&arc_eviction_mtx);
11682724Smaybee 
11692724Smaybee 	mutex_enter(hash_lock);
11701544Seschrock 	if (buf->b_data == NULL) {
11711544Seschrock 		/*
11721544Seschrock 		 * This buffer is evicted.
11731544Seschrock 		 */
11742724Smaybee 		mutex_exit(hash_lock);
11751544Seschrock 		return;
11761544Seschrock 	}
11771544Seschrock 
11782724Smaybee 	ASSERT(buf->b_hdr == hdr);
11793403Sbmc 	ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
11801544Seschrock 	add_reference(hdr, hash_lock, tag);
11812688Smaybee 	arc_access(hdr, hash_lock);
11822688Smaybee 	mutex_exit(hash_lock);
11833403Sbmc 	ARCSTAT_BUMP(arcstat_hits);
11843403Sbmc 	ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
11853403Sbmc 	    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
11863403Sbmc 	    data, metadata, hits);
11871544Seschrock }
11881544Seschrock 
11895450Sbrendan /*
11905450Sbrendan  * Free the arc data buffer.  If it is an l2arc write in progress,
11915450Sbrendan  * the buffer is placed on l2arc_free_on_write to be freed later.
11925450Sbrendan  */
11935450Sbrendan static void
11945450Sbrendan arc_buf_data_free(arc_buf_hdr_t *hdr, void (*free_func)(void *, size_t),
11955450Sbrendan     void *data, size_t size)
11965450Sbrendan {
11975450Sbrendan 	if (HDR_L2_WRITING(hdr)) {
11985450Sbrendan 		l2arc_data_free_t *df;
11995450Sbrendan 		df = kmem_alloc(sizeof (l2arc_data_free_t), KM_SLEEP);
12005450Sbrendan 		df->l2df_data = data;
12015450Sbrendan 		df->l2df_size = size;
12025450Sbrendan 		df->l2df_func = free_func;
12035450Sbrendan 		mutex_enter(&l2arc_free_on_write_mtx);
12045450Sbrendan 		list_insert_head(l2arc_free_on_write, df);
12055450Sbrendan 		mutex_exit(&l2arc_free_on_write_mtx);
12065450Sbrendan 		ARCSTAT_BUMP(arcstat_l2_free_on_write);
12075450Sbrendan 	} else {
12085450Sbrendan 		free_func(data, size);
12095450Sbrendan 	}
12105450Sbrendan }
12115450Sbrendan 
1212789Sahrens static void
12132688Smaybee arc_buf_destroy(arc_buf_t *buf, boolean_t recycle, boolean_t all)
12141544Seschrock {
12151544Seschrock 	arc_buf_t **bufp;
12161544Seschrock 
12171544Seschrock 	/* free up data associated with the buf */
12181544Seschrock 	if (buf->b_data) {
12191544Seschrock 		arc_state_t *state = buf->b_hdr->b_state;
12201544Seschrock 		uint64_t size = buf->b_hdr->b_size;
12213290Sjohansen 		arc_buf_contents_t type = buf->b_hdr->b_type;
12221544Seschrock 
12233093Sahrens 		arc_cksum_verify(buf);
12242688Smaybee 		if (!recycle) {
12253290Sjohansen 			if (type == ARC_BUFC_METADATA) {
12265450Sbrendan 				arc_buf_data_free(buf->b_hdr, zio_buf_free,
12275450Sbrendan 				    buf->b_data, size);
12284309Smaybee 				arc_space_return(size);
12293290Sjohansen 			} else {
12303290Sjohansen 				ASSERT(type == ARC_BUFC_DATA);
12315450Sbrendan 				arc_buf_data_free(buf->b_hdr,
12325450Sbrendan 				    zio_data_buf_free, buf->b_data, size);
12334309Smaybee 				atomic_add_64(&arc_size, -size);
12343290Sjohansen 			}
12352688Smaybee 		}
12361544Seschrock 		if (list_link_active(&buf->b_hdr->b_arc_node)) {
12374309Smaybee 			uint64_t *cnt = &state->arcs_lsize[type];
12384309Smaybee 
12391544Seschrock 			ASSERT(refcount_is_zero(&buf->b_hdr->b_refcnt));
12403403Sbmc 			ASSERT(state != arc_anon);
12414309Smaybee 
12424309Smaybee 			ASSERT3U(*cnt, >=, size);
12434309Smaybee 			atomic_add_64(cnt, -size);
12441544Seschrock 		}
12453403Sbmc 		ASSERT3U(state->arcs_size, >=, size);
12463403Sbmc 		atomic_add_64(&state->arcs_size, -size);
12471544Seschrock 		buf->b_data = NULL;
12481544Seschrock 		ASSERT(buf->b_hdr->b_datacnt > 0);
12491544Seschrock 		buf->b_hdr->b_datacnt -= 1;
12501544Seschrock 	}
12511544Seschrock 
12521544Seschrock 	/* only remove the buf if requested */
12531544Seschrock 	if (!all)
12541544Seschrock 		return;
12551544Seschrock 
12561544Seschrock 	/* remove the buf from the hdr list */
12571544Seschrock 	for (bufp = &buf->b_hdr->b_buf; *bufp != buf; bufp = &(*bufp)->b_next)
12581544Seschrock 		continue;
12591544Seschrock 	*bufp = buf->b_next;
12601544Seschrock 
12611544Seschrock 	ASSERT(buf->b_efunc == NULL);
12621544Seschrock 
12631544Seschrock 	/* clean up the buf */
12641544Seschrock 	buf->b_hdr = NULL;
12651544Seschrock 	kmem_cache_free(buf_cache, buf);
12661544Seschrock }
12671544Seschrock 
12681544Seschrock static void
12691544Seschrock arc_hdr_destroy(arc_buf_hdr_t *hdr)
1270789Sahrens {
1271789Sahrens 	ASSERT(refcount_is_zero(&hdr->b_refcnt));
12723403Sbmc 	ASSERT3P(hdr->b_state, ==, arc_anon);
12731544Seschrock 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1274789Sahrens 
12755450Sbrendan 	if (hdr->b_l2hdr != NULL) {
12765450Sbrendan 		if (!MUTEX_HELD(&l2arc_buflist_mtx)) {
12775450Sbrendan 			/*
12785450Sbrendan 			 * To prevent arc_free() and l2arc_evict() from
12795450Sbrendan 			 * attempting to free the same buffer at the same time,
12805450Sbrendan 			 * a FREE_IN_PROGRESS flag is given to arc_free() to
12815450Sbrendan 			 * give it priority.  l2arc_evict() can't destroy this
12825450Sbrendan 			 * header while we are waiting on l2arc_buflist_mtx.
12835450Sbrendan 			 */
12845450Sbrendan 			mutex_enter(&l2arc_buflist_mtx);
12855450Sbrendan 			ASSERT(hdr->b_l2hdr != NULL);
12865450Sbrendan 
12875450Sbrendan 			list_remove(hdr->b_l2hdr->b_dev->l2ad_buflist, hdr);
12885450Sbrendan 			mutex_exit(&l2arc_buflist_mtx);
12895450Sbrendan 		} else {
12905450Sbrendan 			list_remove(hdr->b_l2hdr->b_dev->l2ad_buflist, hdr);
12915450Sbrendan 		}
12925450Sbrendan 		ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
12935450Sbrendan 		kmem_free(hdr->b_l2hdr, sizeof (l2arc_buf_hdr_t));
12945450Sbrendan 		if (hdr->b_state == arc_l2c_only)
12955450Sbrendan 			l2arc_hdr_stat_remove();
12965450Sbrendan 		hdr->b_l2hdr = NULL;
12975450Sbrendan 	}
12985450Sbrendan 
1299789Sahrens 	if (!BUF_EMPTY(hdr)) {
13001544Seschrock 		ASSERT(!HDR_IN_HASH_TABLE(hdr));
1301789Sahrens 		bzero(&hdr->b_dva, sizeof (dva_t));
1302789Sahrens 		hdr->b_birth = 0;
1303789Sahrens 		hdr->b_cksum0 = 0;
1304789Sahrens 	}
13051544Seschrock 	while (hdr->b_buf) {
1306789Sahrens 		arc_buf_t *buf = hdr->b_buf;
1307789Sahrens 
13081544Seschrock 		if (buf->b_efunc) {
13091544Seschrock 			mutex_enter(&arc_eviction_mtx);
13101544Seschrock 			ASSERT(buf->b_hdr != NULL);
13112688Smaybee 			arc_buf_destroy(hdr->b_buf, FALSE, FALSE);
13121544Seschrock 			hdr->b_buf = buf->b_next;
13132887Smaybee 			buf->b_hdr = &arc_eviction_hdr;
13141544Seschrock 			buf->b_next = arc_eviction_list;
13151544Seschrock 			arc_eviction_list = buf;
13161544Seschrock 			mutex_exit(&arc_eviction_mtx);
13171544Seschrock 		} else {
13182688Smaybee 			arc_buf_destroy(hdr->b_buf, FALSE, TRUE);
13191544Seschrock 		}
1320789Sahrens 	}
13213093Sahrens 	if (hdr->b_freeze_cksum != NULL) {
13223093Sahrens 		kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
13233093Sahrens 		hdr->b_freeze_cksum = NULL;
13243093Sahrens 	}
13251544Seschrock 
1326789Sahrens 	ASSERT(!list_link_active(&hdr->b_arc_node));
1327789Sahrens 	ASSERT3P(hdr->b_hash_next, ==, NULL);
1328789Sahrens 	ASSERT3P(hdr->b_acb, ==, NULL);
1329789Sahrens 	kmem_cache_free(hdr_cache, hdr);
1330789Sahrens }
1331789Sahrens 
1332789Sahrens void
1333789Sahrens arc_buf_free(arc_buf_t *buf, void *tag)
1334789Sahrens {
1335789Sahrens 	arc_buf_hdr_t *hdr = buf->b_hdr;
13363403Sbmc 	int hashed = hdr->b_state != arc_anon;
13371544Seschrock 
13381544Seschrock 	ASSERT(buf->b_efunc == NULL);
13391544Seschrock 	ASSERT(buf->b_data != NULL);
13401544Seschrock 
13411544Seschrock 	if (hashed) {
13421544Seschrock 		kmutex_t *hash_lock = HDR_LOCK(hdr);
13431544Seschrock 
13441544Seschrock 		mutex_enter(hash_lock);
13451544Seschrock 		(void) remove_reference(hdr, hash_lock, tag);
13461544Seschrock 		if (hdr->b_datacnt > 1)
13472688Smaybee 			arc_buf_destroy(buf, FALSE, TRUE);
13481544Seschrock 		else
13491544Seschrock 			hdr->b_flags |= ARC_BUF_AVAILABLE;
13501544Seschrock 		mutex_exit(hash_lock);
13511544Seschrock 	} else if (HDR_IO_IN_PROGRESS(hdr)) {
13521544Seschrock 		int destroy_hdr;
13531544Seschrock 		/*
13541544Seschrock 		 * We are in the middle of an async write.  Don't destroy
13551544Seschrock 		 * this buffer unless the write completes before we finish
13561544Seschrock 		 * decrementing the reference count.
13571544Seschrock 		 */
13581544Seschrock 		mutex_enter(&arc_eviction_mtx);
13591544Seschrock 		(void) remove_reference(hdr, NULL, tag);
13601544Seschrock 		ASSERT(refcount_is_zero(&hdr->b_refcnt));
13611544Seschrock 		destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
13621544Seschrock 		mutex_exit(&arc_eviction_mtx);
13631544Seschrock 		if (destroy_hdr)
13641544Seschrock 			arc_hdr_destroy(hdr);
13651544Seschrock 	} else {
13661544Seschrock 		if (remove_reference(hdr, NULL, tag) > 0) {
13671544Seschrock 			ASSERT(HDR_IO_ERROR(hdr));
13682688Smaybee 			arc_buf_destroy(buf, FALSE, TRUE);
13691544Seschrock 		} else {
13701544Seschrock 			arc_hdr_destroy(hdr);
13711544Seschrock 		}
13721544Seschrock 	}
13731544Seschrock }
13741544Seschrock 
13751544Seschrock int
13761544Seschrock arc_buf_remove_ref(arc_buf_t *buf, void* tag)
13771544Seschrock {
13781544Seschrock 	arc_buf_hdr_t *hdr = buf->b_hdr;
1379789Sahrens 	kmutex_t *hash_lock = HDR_LOCK(hdr);
13801544Seschrock 	int no_callback = (buf->b_efunc == NULL);
13811544Seschrock 
13823403Sbmc 	if (hdr->b_state == arc_anon) {
13831544Seschrock 		arc_buf_free(buf, tag);
13841544Seschrock 		return (no_callback);
13851544Seschrock 	}
1386789Sahrens 
1387789Sahrens 	mutex_enter(hash_lock);
13883403Sbmc 	ASSERT(hdr->b_state != arc_anon);
13891544Seschrock 	ASSERT(buf->b_data != NULL);
1390789Sahrens 
13911544Seschrock 	(void) remove_reference(hdr, hash_lock, tag);
13921544Seschrock 	if (hdr->b_datacnt > 1) {
13931544Seschrock 		if (no_callback)
13942688Smaybee 			arc_buf_destroy(buf, FALSE, TRUE);
13951544Seschrock 	} else if (no_callback) {
13961544Seschrock 		ASSERT(hdr->b_buf == buf && buf->b_next == NULL);
13971544Seschrock 		hdr->b_flags |= ARC_BUF_AVAILABLE;
1398789Sahrens 	}
13991544Seschrock 	ASSERT(no_callback || hdr->b_datacnt > 1 ||
14001544Seschrock 	    refcount_is_zero(&hdr->b_refcnt));
1401789Sahrens 	mutex_exit(hash_lock);
14021544Seschrock 	return (no_callback);
1403789Sahrens }
1404789Sahrens 
1405789Sahrens int
1406789Sahrens arc_buf_size(arc_buf_t *buf)
1407789Sahrens {
1408789Sahrens 	return (buf->b_hdr->b_size);
1409789Sahrens }
1410789Sahrens 
1411789Sahrens /*
1412789Sahrens  * Evict buffers from list until we've removed the specified number of
1413789Sahrens  * bytes.  Move the removed buffers to the appropriate evict state.
14142688Smaybee  * If the recycle flag is set, then attempt to "recycle" a buffer:
14152688Smaybee  * - look for a buffer to evict that is `bytes' long.
14162688Smaybee  * - return the data block from this buffer rather than freeing it.
14172688Smaybee  * This flag is used by callers that are trying to make space for a
14182688Smaybee  * new buffer in a full arc cache.
14195642Smaybee  *
14205642Smaybee  * This function makes a "best effort".  It skips over any buffers
14215642Smaybee  * it can't get a hash_lock on, and so may not catch all candidates.
14225642Smaybee  * It may also return without evicting as much space as requested.
1423789Sahrens  */
14242688Smaybee static void *
14255642Smaybee arc_evict(arc_state_t *state, spa_t *spa, int64_t bytes, boolean_t recycle,
14263290Sjohansen     arc_buf_contents_t type)
1427789Sahrens {
1428789Sahrens 	arc_state_t *evicted_state;
14292688Smaybee 	uint64_t bytes_evicted = 0, skipped = 0, missed = 0;
14302918Smaybee 	arc_buf_hdr_t *ab, *ab_prev = NULL;
14314309Smaybee 	list_t *list = &state->arcs_list[type];
1432789Sahrens 	kmutex_t *hash_lock;
14332688Smaybee 	boolean_t have_lock;
14342918Smaybee 	void *stolen = NULL;
1435789Sahrens 
14363403Sbmc 	ASSERT(state == arc_mru || state == arc_mfu);
1437789Sahrens 
14383403Sbmc 	evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
1439789Sahrens 
14403403Sbmc 	mutex_enter(&state->arcs_mtx);
14413403Sbmc 	mutex_enter(&evicted_state->arcs_mtx);
1442789Sahrens 
14434309Smaybee 	for (ab = list_tail(list); ab; ab = ab_prev) {
14444309Smaybee 		ab_prev = list_prev(list, ab);
14452391Smaybee 		/* prefetch buffers have a minimum lifespan */
14462688Smaybee 		if (HDR_IO_IN_PROGRESS(ab) ||
14475642Smaybee 		    (spa && ab->b_spa != spa) ||
14482688Smaybee 		    (ab->b_flags & (ARC_PREFETCH|ARC_INDIRECT) &&
14492688Smaybee 		    lbolt - ab->b_arc_access < arc_min_prefetch_lifespan)) {
14502391Smaybee 			skipped++;
14512391Smaybee 			continue;
14522391Smaybee 		}
14532918Smaybee 		/* "lookahead" for better eviction candidate */
14542918Smaybee 		if (recycle && ab->b_size != bytes &&
14552918Smaybee 		    ab_prev && ab_prev->b_size == bytes)
14562688Smaybee 			continue;
1457789Sahrens 		hash_lock = HDR_LOCK(ab);
14582688Smaybee 		have_lock = MUTEX_HELD(hash_lock);
14592688Smaybee 		if (have_lock || mutex_tryenter(hash_lock)) {
1460789Sahrens 			ASSERT3U(refcount_count(&ab->b_refcnt), ==, 0);
14611544Seschrock 			ASSERT(ab->b_datacnt > 0);
14621544Seschrock 			while (ab->b_buf) {
14631544Seschrock 				arc_buf_t *buf = ab->b_buf;
14642688Smaybee 				if (buf->b_data) {
14651544Seschrock 					bytes_evicted += ab->b_size;
14663290Sjohansen 					if (recycle && ab->b_type == type &&
14675450Sbrendan 					    ab->b_size == bytes &&
14685450Sbrendan 					    !HDR_L2_WRITING(ab)) {
14692918Smaybee 						stolen = buf->b_data;
14702918Smaybee 						recycle = FALSE;
14712918Smaybee 					}
14722688Smaybee 				}
14731544Seschrock 				if (buf->b_efunc) {
14741544Seschrock 					mutex_enter(&arc_eviction_mtx);
14752918Smaybee 					arc_buf_destroy(buf,
14762918Smaybee 					    buf->b_data == stolen, FALSE);
14771544Seschrock 					ab->b_buf = buf->b_next;
14782887Smaybee 					buf->b_hdr = &arc_eviction_hdr;
14791544Seschrock 					buf->b_next = arc_eviction_list;
14801544Seschrock 					arc_eviction_list = buf;
14811544Seschrock 					mutex_exit(&arc_eviction_mtx);
14821544Seschrock 				} else {
14832918Smaybee 					arc_buf_destroy(buf,
14842918Smaybee 					    buf->b_data == stolen, TRUE);
14851544Seschrock 				}
14861544Seschrock 			}
14871544Seschrock 			ASSERT(ab->b_datacnt == 0);
1488789Sahrens 			arc_change_state(evicted_state, ab, hash_lock);
14891544Seschrock 			ASSERT(HDR_IN_HASH_TABLE(ab));
14905450Sbrendan 			ab->b_flags |= ARC_IN_HASH_TABLE;
14915450Sbrendan 			ab->b_flags &= ~ARC_BUF_AVAILABLE;
1492789Sahrens 			DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, ab);
14932688Smaybee 			if (!have_lock)
14942688Smaybee 				mutex_exit(hash_lock);
14951544Seschrock 			if (bytes >= 0 && bytes_evicted >= bytes)
1496789Sahrens 				break;
1497789Sahrens 		} else {
14982688Smaybee 			missed += 1;
1499789Sahrens 		}
1500789Sahrens 	}
15013403Sbmc 
15023403Sbmc 	mutex_exit(&evicted_state->arcs_mtx);
15033403Sbmc 	mutex_exit(&state->arcs_mtx);
1504789Sahrens 
1505789Sahrens 	if (bytes_evicted < bytes)
1506789Sahrens 		dprintf("only evicted %lld bytes from %x",
1507789Sahrens 		    (longlong_t)bytes_evicted, state);
1508789Sahrens 
15092688Smaybee 	if (skipped)
15103403Sbmc 		ARCSTAT_INCR(arcstat_evict_skip, skipped);
15113403Sbmc 
15122688Smaybee 	if (missed)
15133403Sbmc 		ARCSTAT_INCR(arcstat_mutex_miss, missed);
15143403Sbmc 
15154709Smaybee 	/*
15164709Smaybee 	 * We have just evicted some date into the ghost state, make
15174709Smaybee 	 * sure we also adjust the ghost state size if necessary.
15184709Smaybee 	 */
15194709Smaybee 	if (arc_no_grow &&
15204709Smaybee 	    arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size > arc_c) {
15214709Smaybee 		int64_t mru_over = arc_anon->arcs_size + arc_mru->arcs_size +
15224709Smaybee 		    arc_mru_ghost->arcs_size - arc_c;
15234709Smaybee 
15244709Smaybee 		if (mru_over > 0 && arc_mru_ghost->arcs_lsize[type] > 0) {
15254709Smaybee 			int64_t todelete =
15264709Smaybee 			    MIN(arc_mru_ghost->arcs_lsize[type], mru_over);
15275642Smaybee 			arc_evict_ghost(arc_mru_ghost, NULL, todelete);
15284709Smaybee 		} else if (arc_mfu_ghost->arcs_lsize[type] > 0) {
15294709Smaybee 			int64_t todelete = MIN(arc_mfu_ghost->arcs_lsize[type],
15304709Smaybee 			    arc_mru_ghost->arcs_size +
15314709Smaybee 			    arc_mfu_ghost->arcs_size - arc_c);
15325642Smaybee 			arc_evict_ghost(arc_mfu_ghost, NULL, todelete);
15334709Smaybee 		}
15344709Smaybee 	}
15354709Smaybee 
15362918Smaybee 	return (stolen);
1537789Sahrens }
1538789Sahrens 
1539789Sahrens /*
1540789Sahrens  * Remove buffers from list until we've removed the specified number of
1541789Sahrens  * bytes.  Destroy the buffers that are removed.
1542789Sahrens  */
1543789Sahrens static void
15445642Smaybee arc_evict_ghost(arc_state_t *state, spa_t *spa, int64_t bytes)
1545789Sahrens {
1546789Sahrens 	arc_buf_hdr_t *ab, *ab_prev;
15474309Smaybee 	list_t *list = &state->arcs_list[ARC_BUFC_DATA];
1548789Sahrens 	kmutex_t *hash_lock;
15491544Seschrock 	uint64_t bytes_deleted = 0;
15503700Sek110237 	uint64_t bufs_skipped = 0;
1551789Sahrens 
15521544Seschrock 	ASSERT(GHOST_STATE(state));
1553789Sahrens top:
15543403Sbmc 	mutex_enter(&state->arcs_mtx);
15554309Smaybee 	for (ab = list_tail(list); ab; ab = ab_prev) {
15564309Smaybee 		ab_prev = list_prev(list, ab);
15575642Smaybee 		if (spa && ab->b_spa != spa)
15585642Smaybee 			continue;
1559789Sahrens 		hash_lock = HDR_LOCK(ab);
1560789Sahrens 		if (mutex_tryenter(hash_lock)) {
15612391Smaybee 			ASSERT(!HDR_IO_IN_PROGRESS(ab));
15621544Seschrock 			ASSERT(ab->b_buf == NULL);
15633403Sbmc 			ARCSTAT_BUMP(arcstat_deleted);
15641544Seschrock 			bytes_deleted += ab->b_size;
15655450Sbrendan 
15665450Sbrendan 			if (ab->b_l2hdr != NULL) {
15675450Sbrendan 				/*
15685450Sbrendan 				 * This buffer is cached on the 2nd Level ARC;
15695450Sbrendan 				 * don't destroy the header.
15705450Sbrendan 				 */
15715450Sbrendan 				arc_change_state(arc_l2c_only, ab, hash_lock);
15725450Sbrendan 				mutex_exit(hash_lock);
15735450Sbrendan 			} else {
15745450Sbrendan 				arc_change_state(arc_anon, ab, hash_lock);
15755450Sbrendan 				mutex_exit(hash_lock);
15765450Sbrendan 				arc_hdr_destroy(ab);
15775450Sbrendan 			}
15785450Sbrendan 
1579789Sahrens 			DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, ab);
1580789Sahrens 			if (bytes >= 0 && bytes_deleted >= bytes)
1581789Sahrens 				break;
1582789Sahrens 		} else {
1583789Sahrens 			if (bytes < 0) {
15843403Sbmc 				mutex_exit(&state->arcs_mtx);
1585789Sahrens 				mutex_enter(hash_lock);
1586789Sahrens 				mutex_exit(hash_lock);
1587789Sahrens 				goto top;
1588789Sahrens 			}
1589789Sahrens 			bufs_skipped += 1;
1590789Sahrens 		}
1591789Sahrens 	}
15923403Sbmc 	mutex_exit(&state->arcs_mtx);
1593789Sahrens 
15944309Smaybee 	if (list == &state->arcs_list[ARC_BUFC_DATA] &&
15954309Smaybee 	    (bytes < 0 || bytes_deleted < bytes)) {
15964309Smaybee 		list = &state->arcs_list[ARC_BUFC_METADATA];
15974309Smaybee 		goto top;
15984309Smaybee 	}
15994309Smaybee 
1600789Sahrens 	if (bufs_skipped) {
16013403Sbmc 		ARCSTAT_INCR(arcstat_mutex_miss, bufs_skipped);
1602789Sahrens 		ASSERT(bytes >= 0);
1603789Sahrens 	}
1604789Sahrens 
1605789Sahrens 	if (bytes_deleted < bytes)
1606789Sahrens 		dprintf("only deleted %lld bytes from %p",
1607789Sahrens 		    (longlong_t)bytes_deleted, state);
1608789Sahrens }
1609789Sahrens 
1610789Sahrens static void
1611789Sahrens arc_adjust(void)
1612789Sahrens {
16133403Sbmc 	int64_t top_sz, mru_over, arc_over, todelete;
1614789Sahrens 
16155642Smaybee 	top_sz = arc_anon->arcs_size + arc_mru->arcs_size + arc_meta_used;
1616789Sahrens 
16174309Smaybee 	if (top_sz > arc_p && arc_mru->arcs_lsize[ARC_BUFC_DATA] > 0) {
16184309Smaybee 		int64_t toevict =
16194309Smaybee 		    MIN(arc_mru->arcs_lsize[ARC_BUFC_DATA], top_sz - arc_p);
16205642Smaybee 		(void) arc_evict(arc_mru, NULL, toevict, FALSE, ARC_BUFC_DATA);
16214309Smaybee 		top_sz = arc_anon->arcs_size + arc_mru->arcs_size;
16224309Smaybee 	}
16234309Smaybee 
16244309Smaybee 	if (top_sz > arc_p && arc_mru->arcs_lsize[ARC_BUFC_METADATA] > 0) {
16254309Smaybee 		int64_t toevict =
16264309Smaybee 		    MIN(arc_mru->arcs_lsize[ARC_BUFC_METADATA], top_sz - arc_p);
16275642Smaybee 		(void) arc_evict(arc_mru, NULL, toevict, FALSE,
16285642Smaybee 		    ARC_BUFC_METADATA);
16293403Sbmc 		top_sz = arc_anon->arcs_size + arc_mru->arcs_size;
1630789Sahrens 	}
1631789Sahrens 
16323403Sbmc 	mru_over = top_sz + arc_mru_ghost->arcs_size - arc_c;
1633789Sahrens 
1634789Sahrens 	if (mru_over > 0) {
16354309Smaybee 		if (arc_mru_ghost->arcs_size > 0) {
16364309Smaybee 			todelete = MIN(arc_mru_ghost->arcs_size, mru_over);
16375642Smaybee 			arc_evict_ghost(arc_mru_ghost, NULL, todelete);
1638789Sahrens 		}
1639789Sahrens 	}
1640789Sahrens 
16413403Sbmc 	if ((arc_over = arc_size - arc_c) > 0) {
16421544Seschrock 		int64_t tbl_over;
1643789Sahrens 
16444309Smaybee 		if (arc_mfu->arcs_lsize[ARC_BUFC_DATA] > 0) {
16454309Smaybee 			int64_t toevict =
16464309Smaybee 			    MIN(arc_mfu->arcs_lsize[ARC_BUFC_DATA], arc_over);
16475642Smaybee 			(void) arc_evict(arc_mfu, NULL, toevict, FALSE,
16484309Smaybee 			    ARC_BUFC_DATA);
16494309Smaybee 			arc_over = arc_size - arc_c;
1650789Sahrens 		}
1651789Sahrens 
16524309Smaybee 		if (arc_over > 0 &&
16534309Smaybee 		    arc_mfu->arcs_lsize[ARC_BUFC_METADATA] > 0) {
16544309Smaybee 			int64_t toevict =
16554309Smaybee 			    MIN(arc_mfu->arcs_lsize[ARC_BUFC_METADATA],
16564309Smaybee 			    arc_over);
16575642Smaybee 			(void) arc_evict(arc_mfu, NULL, toevict, FALSE,
16584309Smaybee 			    ARC_BUFC_METADATA);
16594309Smaybee 		}
16604309Smaybee 
16614309Smaybee 		tbl_over = arc_size + arc_mru_ghost->arcs_size +
16624309Smaybee 		    arc_mfu_ghost->arcs_size - arc_c * 2;
16634309Smaybee 
16644309Smaybee 		if (tbl_over > 0 && arc_mfu_ghost->arcs_size > 0) {
16654309Smaybee 			todelete = MIN(arc_mfu_ghost->arcs_size, tbl_over);
16665642Smaybee 			arc_evict_ghost(arc_mfu_ghost, NULL, todelete);
1667789Sahrens 		}
1668789Sahrens 	}
1669789Sahrens }
1670789Sahrens 
16711544Seschrock static void
16721544Seschrock arc_do_user_evicts(void)
16731544Seschrock {
16741544Seschrock 	mutex_enter(&arc_eviction_mtx);
16751544Seschrock 	while (arc_eviction_list != NULL) {
16761544Seschrock 		arc_buf_t *buf = arc_eviction_list;
16771544Seschrock 		arc_eviction_list = buf->b_next;
16781544Seschrock 		buf->b_hdr = NULL;
16791544Seschrock 		mutex_exit(&arc_eviction_mtx);
16801544Seschrock 
16811819Smaybee 		if (buf->b_efunc != NULL)
16821819Smaybee 			VERIFY(buf->b_efunc(buf) == 0);
16831544Seschrock 
16841544Seschrock 		buf->b_efunc = NULL;
16851544Seschrock 		buf->b_private = NULL;
16861544Seschrock 		kmem_cache_free(buf_cache, buf);
16871544Seschrock 		mutex_enter(&arc_eviction_mtx);
16881544Seschrock 	}
16891544Seschrock 	mutex_exit(&arc_eviction_mtx);
16901544Seschrock }
16911544Seschrock 
1692789Sahrens /*
16935642Smaybee  * Flush all *evictable* data from the cache for the given spa.
1694789Sahrens  * NOTE: this will not touch "active" (i.e. referenced) data.
1695789Sahrens  */
1696789Sahrens void
16975642Smaybee arc_flush(spa_t *spa)
1698789Sahrens {
16995642Smaybee 	while (list_head(&arc_mru->arcs_list[ARC_BUFC_DATA])) {
17005642Smaybee 		(void) arc_evict(arc_mru, spa, -1, FALSE, ARC_BUFC_DATA);
17015642Smaybee 		if (spa)
17025642Smaybee 			break;
17035642Smaybee 	}
17045642Smaybee 	while (list_head(&arc_mru->arcs_list[ARC_BUFC_METADATA])) {
17055642Smaybee 		(void) arc_evict(arc_mru, spa, -1, FALSE, ARC_BUFC_METADATA);
17065642Smaybee 		if (spa)
17075642Smaybee 			break;
17085642Smaybee 	}
17095642Smaybee 	while (list_head(&arc_mfu->arcs_list[ARC_BUFC_DATA])) {
17105642Smaybee 		(void) arc_evict(arc_mfu, spa, -1, FALSE, ARC_BUFC_DATA);
17115642Smaybee 		if (spa)
17125642Smaybee 			break;
17135642Smaybee 	}
17145642Smaybee 	while (list_head(&arc_mfu->arcs_list[ARC_BUFC_METADATA])) {
17155642Smaybee 		(void) arc_evict(arc_mfu, spa, -1, FALSE, ARC_BUFC_METADATA);
17165642Smaybee 		if (spa)
17175642Smaybee 			break;
17185642Smaybee 	}
17195642Smaybee 
17205642Smaybee 	arc_evict_ghost(arc_mru_ghost, spa, -1);
17215642Smaybee 	arc_evict_ghost(arc_mfu_ghost, spa, -1);
17221544Seschrock 
17231544Seschrock 	mutex_enter(&arc_reclaim_thr_lock);
17241544Seschrock 	arc_do_user_evicts();
17251544Seschrock 	mutex_exit(&arc_reclaim_thr_lock);
17265642Smaybee 	ASSERT(spa || arc_eviction_list == NULL);
1727789Sahrens }
1728789Sahrens 
17293158Smaybee int arc_shrink_shift = 5;		/* log2(fraction of arc to reclaim) */
17302391Smaybee 
1731789Sahrens void
17323158Smaybee arc_shrink(void)
1733789Sahrens {
17343403Sbmc 	if (arc_c > arc_c_min) {
17353158Smaybee 		uint64_t to_free;
1736789Sahrens 
17372048Sstans #ifdef _KERNEL
17383403Sbmc 		to_free = MAX(arc_c >> arc_shrink_shift, ptob(needfree));
17392048Sstans #else
17403403Sbmc 		to_free = arc_c >> arc_shrink_shift;
17412048Sstans #endif
17423403Sbmc 		if (arc_c > arc_c_min + to_free)
17433403Sbmc 			atomic_add_64(&arc_c, -to_free);
17443158Smaybee 		else
17453403Sbmc 			arc_c = arc_c_min;
17462048Sstans 
17473403Sbmc 		atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
17483403Sbmc 		if (arc_c > arc_size)
17493403Sbmc 			arc_c = MAX(arc_size, arc_c_min);
17503403Sbmc 		if (arc_p > arc_c)
17513403Sbmc 			arc_p = (arc_c >> 1);
17523403Sbmc 		ASSERT(arc_c >= arc_c_min);
17533403Sbmc 		ASSERT((int64_t)arc_p >= 0);
17543158Smaybee 	}
1755789Sahrens 
17563403Sbmc 	if (arc_size > arc_c)
17573158Smaybee 		arc_adjust();
1758789Sahrens }
1759789Sahrens 
1760789Sahrens static int
1761789Sahrens arc_reclaim_needed(void)
1762789Sahrens {
1763789Sahrens 	uint64_t extra;
1764789Sahrens 
1765789Sahrens #ifdef _KERNEL
17662048Sstans 
17672048Sstans 	if (needfree)
17682048Sstans 		return (1);
17692048Sstans 
1770789Sahrens 	/*
1771789Sahrens 	 * take 'desfree' extra pages, so we reclaim sooner, rather than later
1772789Sahrens 	 */
1773789Sahrens 	extra = desfree;
1774789Sahrens 
1775789Sahrens 	/*
1776789Sahrens 	 * check that we're out of range of the pageout scanner.  It starts to
1777789Sahrens 	 * schedule paging if freemem is less than lotsfree and needfree.
1778789Sahrens 	 * lotsfree is the high-water mark for pageout, and needfree is the
1779789Sahrens 	 * number of needed free pages.  We add extra pages here to make sure
1780789Sahrens 	 * the scanner doesn't start up while we're freeing memory.
1781789Sahrens 	 */
1782789Sahrens 	if (freemem < lotsfree + needfree + extra)
1783789Sahrens 		return (1);
1784789Sahrens 
1785789Sahrens 	/*
1786789Sahrens 	 * check to make sure that swapfs has enough space so that anon
17875450Sbrendan 	 * reservations can still succeed. anon_resvmem() checks that the
1788789Sahrens 	 * availrmem is greater than swapfs_minfree, and the number of reserved
1789789Sahrens 	 * swap pages.  We also add a bit of extra here just to prevent
1790789Sahrens 	 * circumstances from getting really dire.
1791789Sahrens 	 */
1792789Sahrens 	if (availrmem < swapfs_minfree + swapfs_reserve + extra)
1793789Sahrens 		return (1);
1794789Sahrens 
17951936Smaybee #if defined(__i386)
1796789Sahrens 	/*
1797789Sahrens 	 * If we're on an i386 platform, it's possible that we'll exhaust the
1798789Sahrens 	 * kernel heap space before we ever run out of available physical
1799789Sahrens 	 * memory.  Most checks of the size of the heap_area compare against
1800789Sahrens 	 * tune.t_minarmem, which is the minimum available real memory that we
1801789Sahrens 	 * can have in the system.  However, this is generally fixed at 25 pages
1802789Sahrens 	 * which is so low that it's useless.  In this comparison, we seek to
1803789Sahrens 	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
18045450Sbrendan 	 * heap is allocated.  (Or, in the calculation, if less than 1/4th is
1805789Sahrens 	 * free)
1806789Sahrens 	 */
1807789Sahrens 	if (btop(vmem_size(heap_arena, VMEM_FREE)) <
1808789Sahrens 	    (btop(vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC)) >> 2))
1809789Sahrens 		return (1);
1810789Sahrens #endif
1811789Sahrens 
1812789Sahrens #else
1813789Sahrens 	if (spa_get_random(100) == 0)
1814789Sahrens 		return (1);
1815789Sahrens #endif
1816789Sahrens 	return (0);
1817789Sahrens }
1818789Sahrens 
1819789Sahrens static void
1820789Sahrens arc_kmem_reap_now(arc_reclaim_strategy_t strat)
1821789Sahrens {
1822789Sahrens 	size_t			i;
1823789Sahrens 	kmem_cache_t		*prev_cache = NULL;
18243290Sjohansen 	kmem_cache_t		*prev_data_cache = NULL;
1825789Sahrens 	extern kmem_cache_t	*zio_buf_cache[];
18263290Sjohansen 	extern kmem_cache_t	*zio_data_buf_cache[];
1827789Sahrens 
18281484Sek110237 #ifdef _KERNEL
18294309Smaybee 	if (arc_meta_used >= arc_meta_limit) {
18304309Smaybee 		/*
18314309Smaybee 		 * We are exceeding our meta-data cache limit.
18324309Smaybee 		 * Purge some DNLC entries to release holds on meta-data.
18334309Smaybee 		 */
18344309Smaybee 		dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
18354309Smaybee 	}
18361936Smaybee #if defined(__i386)
18371936Smaybee 	/*
18381936Smaybee 	 * Reclaim unused memory from all kmem caches.
18391936Smaybee 	 */
18401936Smaybee 	kmem_reap();
18411936Smaybee #endif
18421484Sek110237 #endif
18431484Sek110237 
1844789Sahrens 	/*
18455450Sbrendan 	 * An aggressive reclamation will shrink the cache size as well as
18461544Seschrock 	 * reap free buffers from the arc kmem caches.
1847789Sahrens 	 */
1848789Sahrens 	if (strat == ARC_RECLAIM_AGGR)
18493158Smaybee 		arc_shrink();
1850789Sahrens 
1851789Sahrens 	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
1852789Sahrens 		if (zio_buf_cache[i] != prev_cache) {
1853789Sahrens 			prev_cache = zio_buf_cache[i];
1854789Sahrens 			kmem_cache_reap_now(zio_buf_cache[i]);
1855789Sahrens 		}
18563290Sjohansen 		if (zio_data_buf_cache[i] != prev_data_cache) {
18573290Sjohansen 			prev_data_cache = zio_data_buf_cache[i];
18583290Sjohansen 			kmem_cache_reap_now(zio_data_buf_cache[i]);
18593290Sjohansen 		}
1860789Sahrens 	}
18611544Seschrock 	kmem_cache_reap_now(buf_cache);
18621544Seschrock 	kmem_cache_reap_now(hdr_cache);
1863789Sahrens }
1864789Sahrens 
1865789Sahrens static void
1866789Sahrens arc_reclaim_thread(void)
1867789Sahrens {
1868789Sahrens 	clock_t			growtime = 0;
1869789Sahrens 	arc_reclaim_strategy_t	last_reclaim = ARC_RECLAIM_CONS;
1870789Sahrens 	callb_cpr_t		cpr;
1871789Sahrens 
1872789Sahrens 	CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
1873789Sahrens 
1874789Sahrens 	mutex_enter(&arc_reclaim_thr_lock);
1875789Sahrens 	while (arc_thread_exit == 0) {
1876789Sahrens 		if (arc_reclaim_needed()) {
1877789Sahrens 
18783403Sbmc 			if (arc_no_grow) {
1879789Sahrens 				if (last_reclaim == ARC_RECLAIM_CONS) {
1880789Sahrens 					last_reclaim = ARC_RECLAIM_AGGR;
1881789Sahrens 				} else {
1882789Sahrens 					last_reclaim = ARC_RECLAIM_CONS;
1883789Sahrens 				}
1884789Sahrens 			} else {
18853403Sbmc 				arc_no_grow = TRUE;
1886789Sahrens 				last_reclaim = ARC_RECLAIM_AGGR;
1887789Sahrens 				membar_producer();
1888789Sahrens 			}
1889789Sahrens 
1890789Sahrens 			/* reset the growth delay for every reclaim */
1891789Sahrens 			growtime = lbolt + (arc_grow_retry * hz);
1892789Sahrens 
1893789Sahrens 			arc_kmem_reap_now(last_reclaim);
1894*6987Sbrendan 			arc_warm = B_TRUE;
1895789Sahrens 
18964309Smaybee 		} else if (arc_no_grow && lbolt >= growtime) {
18973403Sbmc 			arc_no_grow = FALSE;
1898789Sahrens 		}
1899789Sahrens 
19003403Sbmc 		if (2 * arc_c < arc_size +
19013403Sbmc 		    arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size)
19023298Smaybee 			arc_adjust();
19033298Smaybee 
19041544Seschrock 		if (arc_eviction_list != NULL)
19051544Seschrock 			arc_do_user_evicts();
19061544Seschrock 
1907789Sahrens 		/* block until needed, or one second, whichever is shorter */
1908789Sahrens 		CALLB_CPR_SAFE_BEGIN(&cpr);
1909789Sahrens 		(void) cv_timedwait(&arc_reclaim_thr_cv,
1910789Sahrens 		    &arc_reclaim_thr_lock, (lbolt + hz));
1911789Sahrens 		CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
1912789Sahrens 	}
1913789Sahrens 
1914789Sahrens 	arc_thread_exit = 0;
1915789Sahrens 	cv_broadcast(&arc_reclaim_thr_cv);
1916789Sahrens 	CALLB_CPR_EXIT(&cpr);		/* drops arc_reclaim_thr_lock */
1917789Sahrens 	thread_exit();
1918789Sahrens }
1919789Sahrens 
19201544Seschrock /*
19211544Seschrock  * Adapt arc info given the number of bytes we are trying to add and
19221544Seschrock  * the state that we are comming from.  This function is only called
19231544Seschrock  * when we are adding new content to the cache.
19241544Seschrock  */
1925789Sahrens static void
19261544Seschrock arc_adapt(int bytes, arc_state_t *state)
1927789Sahrens {
19281544Seschrock 	int mult;
19291544Seschrock 
19305450Sbrendan 	if (state == arc_l2c_only)
19315450Sbrendan 		return;
19325450Sbrendan 
19331544Seschrock 	ASSERT(bytes > 0);
1934789Sahrens 	/*
19351544Seschrock 	 * Adapt the target size of the MRU list:
19361544Seschrock 	 *	- if we just hit in the MRU ghost list, then increase
19371544Seschrock 	 *	  the target size of the MRU list.
19381544Seschrock 	 *	- if we just hit in the MFU ghost list, then increase
19391544Seschrock 	 *	  the target size of the MFU list by decreasing the
19401544Seschrock 	 *	  target size of the MRU list.
1941789Sahrens 	 */
19423403Sbmc 	if (state == arc_mru_ghost) {
19433403Sbmc 		mult = ((arc_mru_ghost->arcs_size >= arc_mfu_ghost->arcs_size) ?
19443403Sbmc 		    1 : (arc_mfu_ghost->arcs_size/arc_mru_ghost->arcs_size));
19451544Seschrock 
19463403Sbmc 		arc_p = MIN(arc_c, arc_p + bytes * mult);
19473403Sbmc 	} else if (state == arc_mfu_ghost) {
19483403Sbmc 		mult = ((arc_mfu_ghost->arcs_size >= arc_mru_ghost->arcs_size) ?
19493403Sbmc 		    1 : (arc_mru_ghost->arcs_size/arc_mfu_ghost->arcs_size));
19501544Seschrock 
19513403Sbmc 		arc_p = MAX(0, (int64_t)arc_p - bytes * mult);
19521544Seschrock 	}
19533403Sbmc 	ASSERT((int64_t)arc_p >= 0);
1954789Sahrens 
1955789Sahrens 	if (arc_reclaim_needed()) {
1956789Sahrens 		cv_signal(&arc_reclaim_thr_cv);
1957789Sahrens 		return;
1958789Sahrens 	}
1959789Sahrens 
19603403Sbmc 	if (arc_no_grow)
1961789Sahrens 		return;
1962789Sahrens 
19633403Sbmc 	if (arc_c >= arc_c_max)
19641544Seschrock 		return;
19651544Seschrock 
1966789Sahrens 	/*
19671544Seschrock 	 * If we're within (2 * maxblocksize) bytes of the target
19681544Seschrock 	 * cache size, increment the target cache size
1969789Sahrens 	 */
19703403Sbmc 	if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
19713403Sbmc 		atomic_add_64(&arc_c, (int64_t)bytes);
19723403Sbmc 		if (arc_c > arc_c_max)
19733403Sbmc 			arc_c = arc_c_max;
19743403Sbmc 		else if (state == arc_anon)
19753403Sbmc 			atomic_add_64(&arc_p, (int64_t)bytes);
19763403Sbmc 		if (arc_p > arc_c)
19773403Sbmc 			arc_p = arc_c;
1978789Sahrens 	}
19793403Sbmc 	ASSERT((int64_t)arc_p >= 0);
1980789Sahrens }
1981789Sahrens 
1982789Sahrens /*
19831544Seschrock  * Check if the cache has reached its limits and eviction is required
19841544Seschrock  * prior to insert.
1985789Sahrens  */
1986789Sahrens static int
19874309Smaybee arc_evict_needed(arc_buf_contents_t type)
1988789Sahrens {
19894309Smaybee 	if (type == ARC_BUFC_METADATA && arc_meta_used >= arc_meta_limit)
19904309Smaybee 		return (1);
19914309Smaybee 
19924309Smaybee #ifdef _KERNEL
19934309Smaybee 	/*
19944309Smaybee 	 * If zio data pages are being allocated out of a separate heap segment,
19954309Smaybee 	 * then enforce that the size of available vmem for this area remains
19964309Smaybee 	 * above about 1/32nd free.
19974309Smaybee 	 */
19984309Smaybee 	if (type == ARC_BUFC_DATA && zio_arena != NULL &&
19994309Smaybee 	    vmem_size(zio_arena, VMEM_FREE) <
20004309Smaybee 	    (vmem_size(zio_arena, VMEM_ALLOC) >> 5))
20014309Smaybee 		return (1);
20024309Smaybee #endif
20034309Smaybee 
2004789Sahrens 	if (arc_reclaim_needed())
2005789Sahrens 		return (1);
2006789Sahrens 
20073403Sbmc 	return (arc_size > arc_c);
2008789Sahrens }
2009789Sahrens 
2010789Sahrens /*
20112688Smaybee  * The buffer, supplied as the first argument, needs a data block.
20122688Smaybee  * So, if we are at cache max, determine which cache should be victimized.
20132688Smaybee  * We have the following cases:
2014789Sahrens  *
20153403Sbmc  * 1. Insert for MRU, p > sizeof(arc_anon + arc_mru) ->
2016789Sahrens  * In this situation if we're out of space, but the resident size of the MFU is
2017789Sahrens  * under the limit, victimize the MFU cache to satisfy this insertion request.
2018789Sahrens  *
20193403Sbmc  * 2. Insert for MRU, p <= sizeof(arc_anon + arc_mru) ->
2020789Sahrens  * Here, we've used up all of the available space for the MRU, so we need to
2021789Sahrens  * evict from our own cache instead.  Evict from the set of resident MRU
2022789Sahrens  * entries.
2023789Sahrens  *
20243403Sbmc  * 3. Insert for MFU (c - p) > sizeof(arc_mfu) ->
2025789Sahrens  * c minus p represents the MFU space in the cache, since p is the size of the
2026789Sahrens  * cache that is dedicated to the MRU.  In this situation there's still space on
2027789Sahrens  * the MFU side, so the MRU side needs to be victimized.
2028789Sahrens  *
20293403Sbmc  * 4. Insert for MFU (c - p) < sizeof(arc_mfu) ->
2030789Sahrens  * MFU's resident set is consuming more space than it has been allotted.  In
2031789Sahrens  * this situation, we must victimize our own cache, the MFU, for this insertion.
2032789Sahrens  */
2033789Sahrens static void
20342688Smaybee arc_get_data_buf(arc_buf_t *buf)
2035789Sahrens {
20363290Sjohansen 	arc_state_t		*state = buf->b_hdr->b_state;
20373290Sjohansen 	uint64_t		size = buf->b_hdr->b_size;
20383290Sjohansen 	arc_buf_contents_t	type = buf->b_hdr->b_type;
20392688Smaybee 
20402688Smaybee 	arc_adapt(size, state);
2041789Sahrens 
20422688Smaybee 	/*
20432688Smaybee 	 * We have not yet reached cache maximum size,
20442688Smaybee 	 * just allocate a new buffer.
20452688Smaybee 	 */
20464309Smaybee 	if (!arc_evict_needed(type)) {
20473290Sjohansen 		if (type == ARC_BUFC_METADATA) {
20483290Sjohansen 			buf->b_data = zio_buf_alloc(size);
20494309Smaybee 			arc_space_consume(size);
20503290Sjohansen 		} else {
20513290Sjohansen 			ASSERT(type == ARC_BUFC_DATA);
20523290Sjohansen 			buf->b_data = zio_data_buf_alloc(size);
20534309Smaybee 			atomic_add_64(&arc_size, size);
20543290Sjohansen 		}
20552688Smaybee 		goto out;
20562688Smaybee 	}
20572688Smaybee 
20582688Smaybee 	/*
20592688Smaybee 	 * If we are prefetching from the mfu ghost list, this buffer
20602688Smaybee 	 * will end up on the mru list; so steal space from there.
20612688Smaybee 	 */
20623403Sbmc 	if (state == arc_mfu_ghost)
20633403Sbmc 		state = buf->b_hdr->b_flags & ARC_PREFETCH ? arc_mru : arc_mfu;
20643403Sbmc 	else if (state == arc_mru_ghost)
20653403Sbmc 		state = arc_mru;
2066789Sahrens 
20673403Sbmc 	if (state == arc_mru || state == arc_anon) {
20683403Sbmc 		uint64_t mru_used = arc_anon->arcs_size + arc_mru->arcs_size;
20694309Smaybee 		state = (arc_mfu->arcs_lsize[type] > 0 &&
20704309Smaybee 		    arc_p > mru_used) ? arc_mfu : arc_mru;
2071789Sahrens 	} else {
20722688Smaybee 		/* MFU cases */
20733403Sbmc 		uint64_t mfu_space = arc_c - arc_p;
20744309Smaybee 		state =  (arc_mru->arcs_lsize[type] > 0 &&
20754309Smaybee 		    mfu_space > arc_mfu->arcs_size) ? arc_mru : arc_mfu;
20762688Smaybee 	}
20775642Smaybee 	if ((buf->b_data = arc_evict(state, NULL, size, TRUE, type)) == NULL) {
20783290Sjohansen 		if (type == ARC_BUFC_METADATA) {
20793290Sjohansen 			buf->b_data = zio_buf_alloc(size);
20804309Smaybee 			arc_space_consume(size);
20813290Sjohansen 		} else {
20823290Sjohansen 			ASSERT(type == ARC_BUFC_DATA);
20833290Sjohansen 			buf->b_data = zio_data_buf_alloc(size);
20844309Smaybee 			atomic_add_64(&arc_size, size);
20853290Sjohansen 		}
20863403Sbmc 		ARCSTAT_BUMP(arcstat_recycle_miss);
20872688Smaybee 	}
20882688Smaybee 	ASSERT(buf->b_data != NULL);
20892688Smaybee out:
20902688Smaybee 	/*
20912688Smaybee 	 * Update the state size.  Note that ghost states have a
20922688Smaybee 	 * "ghost size" and so don't need to be updated.
20932688Smaybee 	 */
20942688Smaybee 	if (!GHOST_STATE(buf->b_hdr->b_state)) {
20952688Smaybee 		arc_buf_hdr_t *hdr = buf->b_hdr;
20962688Smaybee 
20973403Sbmc 		atomic_add_64(&hdr->b_state->arcs_size, size);
20982688Smaybee 		if (list_link_active(&hdr->b_arc_node)) {
20992688Smaybee 			ASSERT(refcount_is_zero(&hdr->b_refcnt));
21004309Smaybee 			atomic_add_64(&hdr->b_state->arcs_lsize[type], size);
2101789Sahrens 		}
21023298Smaybee 		/*
21033298Smaybee 		 * If we are growing the cache, and we are adding anonymous
21043403Sbmc 		 * data, and we have outgrown arc_p, update arc_p
21053298Smaybee 		 */
21063403Sbmc 		if (arc_size < arc_c && hdr->b_state == arc_anon &&
21073403Sbmc 		    arc_anon->arcs_size + arc_mru->arcs_size > arc_p)
21083403Sbmc 			arc_p = MIN(arc_c, arc_p + size);
2109789Sahrens 	}
2110789Sahrens }
2111789Sahrens 
2112789Sahrens /*
2113789Sahrens  * This routine is called whenever a buffer is accessed.
21141544Seschrock  * NOTE: the hash lock is dropped in this function.
2115789Sahrens  */
2116789Sahrens static void
21172688Smaybee arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock)
2118789Sahrens {
2119789Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
2120789Sahrens 
21213403Sbmc 	if (buf->b_state == arc_anon) {
2122789Sahrens 		/*
2123789Sahrens 		 * This buffer is not in the cache, and does not
2124789Sahrens 		 * appear in our "ghost" list.  Add the new buffer
2125789Sahrens 		 * to the MRU state.
2126789Sahrens 		 */
2127789Sahrens 
2128789Sahrens 		ASSERT(buf->b_arc_access == 0);
2129789Sahrens 		buf->b_arc_access = lbolt;
21301544Seschrock 		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
21313403Sbmc 		arc_change_state(arc_mru, buf, hash_lock);
2132789Sahrens 
21333403Sbmc 	} else if (buf->b_state == arc_mru) {
2134789Sahrens 		/*
21352391Smaybee 		 * If this buffer is here because of a prefetch, then either:
21362391Smaybee 		 * - clear the flag if this is a "referencing" read
21372391Smaybee 		 *   (any subsequent access will bump this into the MFU state).
21382391Smaybee 		 * or
21392391Smaybee 		 * - move the buffer to the head of the list if this is
21402391Smaybee 		 *   another prefetch (to make it less likely to be evicted).
2141789Sahrens 		 */
2142789Sahrens 		if ((buf->b_flags & ARC_PREFETCH) != 0) {
21432391Smaybee 			if (refcount_count(&buf->b_refcnt) == 0) {
21442391Smaybee 				ASSERT(list_link_active(&buf->b_arc_node));
21452391Smaybee 			} else {
21462391Smaybee 				buf->b_flags &= ~ARC_PREFETCH;
21473403Sbmc 				ARCSTAT_BUMP(arcstat_mru_hits);
21482391Smaybee 			}
21492391Smaybee 			buf->b_arc_access = lbolt;
2150789Sahrens 			return;
2151789Sahrens 		}
2152789Sahrens 
2153789Sahrens 		/*
2154789Sahrens 		 * This buffer has been "accessed" only once so far,
2155789Sahrens 		 * but it is still in the cache. Move it to the MFU
2156789Sahrens 		 * state.
2157789Sahrens 		 */
2158789Sahrens 		if (lbolt > buf->b_arc_access + ARC_MINTIME) {
2159789Sahrens 			/*
2160789Sahrens 			 * More than 125ms have passed since we
2161789Sahrens 			 * instantiated this buffer.  Move it to the
2162789Sahrens 			 * most frequently used state.
2163789Sahrens 			 */
2164789Sahrens 			buf->b_arc_access = lbolt;
21651544Seschrock 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
21663403Sbmc 			arc_change_state(arc_mfu, buf, hash_lock);
2167789Sahrens 		}
21683403Sbmc 		ARCSTAT_BUMP(arcstat_mru_hits);
21693403Sbmc 	} else if (buf->b_state == arc_mru_ghost) {
2170789Sahrens 		arc_state_t	*new_state;
2171789Sahrens 		/*
2172789Sahrens 		 * This buffer has been "accessed" recently, but
2173789Sahrens 		 * was evicted from the cache.  Move it to the
2174789Sahrens 		 * MFU state.
2175789Sahrens 		 */
2176789Sahrens 
2177789Sahrens 		if (buf->b_flags & ARC_PREFETCH) {
21783403Sbmc 			new_state = arc_mru;
21792391Smaybee 			if (refcount_count(&buf->b_refcnt) > 0)
21802391Smaybee 				buf->b_flags &= ~ARC_PREFETCH;
21811544Seschrock 			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2182789Sahrens 		} else {
21833403Sbmc 			new_state = arc_mfu;
21841544Seschrock 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2185789Sahrens 		}
2186789Sahrens 
2187789Sahrens 		buf->b_arc_access = lbolt;
2188789Sahrens 		arc_change_state(new_state, buf, hash_lock);
2189789Sahrens 
21903403Sbmc 		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
21913403Sbmc 	} else if (buf->b_state == arc_mfu) {
2192789Sahrens 		/*
2193789Sahrens 		 * This buffer has been accessed more than once and is
2194789Sahrens 		 * still in the cache.  Keep it in the MFU state.
2195789Sahrens 		 *
21962391Smaybee 		 * NOTE: an add_reference() that occurred when we did
21972391Smaybee 		 * the arc_read() will have kicked this off the list.
21982391Smaybee 		 * If it was a prefetch, we will explicitly move it to
21992391Smaybee 		 * the head of the list now.
2200789Sahrens 		 */
22012391Smaybee 		if ((buf->b_flags & ARC_PREFETCH) != 0) {
22022391Smaybee 			ASSERT(refcount_count(&buf->b_refcnt) == 0);
22032391Smaybee 			ASSERT(list_link_active(&buf->b_arc_node));
22042391Smaybee 		}
22053403Sbmc 		ARCSTAT_BUMP(arcstat_mfu_hits);
22062391Smaybee 		buf->b_arc_access = lbolt;
22073403Sbmc 	} else if (buf->b_state == arc_mfu_ghost) {
22083403Sbmc 		arc_state_t	*new_state = arc_mfu;
2209789Sahrens 		/*
2210789Sahrens 		 * This buffer has been accessed more than once but has
2211789Sahrens 		 * been evicted from the cache.  Move it back to the
2212789Sahrens 		 * MFU state.
2213789Sahrens 		 */
2214789Sahrens 
22152391Smaybee 		if (buf->b_flags & ARC_PREFETCH) {
22162391Smaybee 			/*
22172391Smaybee 			 * This is a prefetch access...
22182391Smaybee 			 * move this block back to the MRU state.
22192391Smaybee 			 */
22202391Smaybee 			ASSERT3U(refcount_count(&buf->b_refcnt), ==, 0);
22213403Sbmc 			new_state = arc_mru;
22222391Smaybee 		}
22232391Smaybee 
2224789Sahrens 		buf->b_arc_access = lbolt;
22251544Seschrock 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
22262391Smaybee 		arc_change_state(new_state, buf, hash_lock);
2227789Sahrens 
22283403Sbmc 		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
22295450Sbrendan 	} else if (buf->b_state == arc_l2c_only) {
22305450Sbrendan 		/*
22315450Sbrendan 		 * This buffer is on the 2nd Level ARC.
22325450Sbrendan 		 */
22335450Sbrendan 
22345450Sbrendan 		buf->b_arc_access = lbolt;
22355450Sbrendan 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
22365450Sbrendan 		arc_change_state(arc_mfu, buf, hash_lock);
2237789Sahrens 	} else {
2238789Sahrens 		ASSERT(!"invalid arc state");
2239789Sahrens 	}
2240789Sahrens }
2241789Sahrens 
2242789Sahrens /* a generic arc_done_func_t which you can use */
2243789Sahrens /* ARGSUSED */
2244789Sahrens void
2245789Sahrens arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
2246789Sahrens {
2247789Sahrens 	bcopy(buf->b_data, arg, buf->b_hdr->b_size);
22481544Seschrock 	VERIFY(arc_buf_remove_ref(buf, arg) == 1);
2249789Sahrens }
2250789Sahrens 
22514309Smaybee /* a generic arc_done_func_t */
2252789Sahrens void
2253789Sahrens arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
2254789Sahrens {
2255789Sahrens 	arc_buf_t **bufp = arg;
2256789Sahrens 	if (zio && zio->io_error) {
22571544Seschrock 		VERIFY(arc_buf_remove_ref(buf, arg) == 1);
2258789Sahrens 		*bufp = NULL;
2259789Sahrens 	} else {
2260789Sahrens 		*bufp = buf;
2261789Sahrens 	}
2262789Sahrens }
2263789Sahrens 
2264789Sahrens static void
2265789Sahrens arc_read_done(zio_t *zio)
2266789Sahrens {
22671589Smaybee 	arc_buf_hdr_t	*hdr, *found;
2268789Sahrens 	arc_buf_t	*buf;
2269789Sahrens 	arc_buf_t	*abuf;	/* buffer we're assigning to callback */
2270789Sahrens 	kmutex_t	*hash_lock;
2271789Sahrens 	arc_callback_t	*callback_list, *acb;
2272789Sahrens 	int		freeable = FALSE;
2273789Sahrens 
2274789Sahrens 	buf = zio->io_private;
2275789Sahrens 	hdr = buf->b_hdr;
2276789Sahrens 
22771589Smaybee 	/*
22781589Smaybee 	 * The hdr was inserted into hash-table and removed from lists
22791589Smaybee 	 * prior to starting I/O.  We should find this header, since
22801589Smaybee 	 * it's in the hash table, and it should be legit since it's
22811589Smaybee 	 * not possible to evict it during the I/O.  The only possible
22821589Smaybee 	 * reason for it not to be found is if we were freed during the
22831589Smaybee 	 * read.
22841589Smaybee 	 */
22851589Smaybee 	found = buf_hash_find(zio->io_spa, &hdr->b_dva, hdr->b_birth,
22863093Sahrens 	    &hash_lock);
2287789Sahrens 
22881589Smaybee 	ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) && hash_lock == NULL) ||
22895450Sbrendan 	    (found == hdr && DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
22905450Sbrendan 	    (found == hdr && HDR_L2_READING(hdr)));
22915450Sbrendan 
2292*6987Sbrendan 	hdr->b_flags &= ~ARC_L2_EVICTED;
22935450Sbrendan 	if (l2arc_noprefetch && (hdr->b_flags & ARC_PREFETCH))
22945450Sbrendan 		hdr->b_flags |= ARC_DONT_L2CACHE;
2295789Sahrens 
2296789Sahrens 	/* byteswap if necessary */
2297789Sahrens 	callback_list = hdr->b_acb;
2298789Sahrens 	ASSERT(callback_list != NULL);
2299789Sahrens 	if (BP_SHOULD_BYTESWAP(zio->io_bp) && callback_list->acb_byteswap)
2300789Sahrens 		callback_list->acb_byteswap(buf->b_data, hdr->b_size);
2301789Sahrens 
23025450Sbrendan 	arc_cksum_compute(buf, B_FALSE);
23033093Sahrens 
2304789Sahrens 	/* create copies of the data buffer for the callers */
2305789Sahrens 	abuf = buf;
2306789Sahrens 	for (acb = callback_list; acb; acb = acb->acb_next) {
2307789Sahrens 		if (acb->acb_done) {
23082688Smaybee 			if (abuf == NULL)
23092688Smaybee 				abuf = arc_buf_clone(buf);
2310789Sahrens 			acb->acb_buf = abuf;
2311789Sahrens 			abuf = NULL;
2312789Sahrens 		}
2313789Sahrens 	}
2314789Sahrens 	hdr->b_acb = NULL;
2315789Sahrens 	hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
23161544Seschrock 	ASSERT(!HDR_BUF_AVAILABLE(hdr));
23171544Seschrock 	if (abuf == buf)
23181544Seschrock 		hdr->b_flags |= ARC_BUF_AVAILABLE;
2319789Sahrens 
2320789Sahrens 	ASSERT(refcount_is_zero(&hdr->b_refcnt) || callback_list != NULL);
2321789Sahrens 
2322789Sahrens 	if (zio->io_error != 0) {
2323789Sahrens 		hdr->b_flags |= ARC_IO_ERROR;
23243403Sbmc 		if (hdr->b_state != arc_anon)
23253403Sbmc 			arc_change_state(arc_anon, hdr, hash_lock);
23261544Seschrock 		if (HDR_IN_HASH_TABLE(hdr))
23271544Seschrock 			buf_hash_remove(hdr);
2328789Sahrens 		freeable = refcount_is_zero(&hdr->b_refcnt);
23292391Smaybee 		/* convert checksum errors into IO errors */
23301544Seschrock 		if (zio->io_error == ECKSUM)
23311544Seschrock 			zio->io_error = EIO;
2332789Sahrens 	}
2333789Sahrens 
23341544Seschrock 	/*
23352391Smaybee 	 * Broadcast before we drop the hash_lock to avoid the possibility
23362391Smaybee 	 * that the hdr (and hence the cv) might be freed before we get to
23372391Smaybee 	 * the cv_broadcast().
23381544Seschrock 	 */
23391544Seschrock 	cv_broadcast(&hdr->b_cv);
23401544Seschrock 
23411589Smaybee 	if (hash_lock) {
2342789Sahrens 		/*
2343789Sahrens 		 * Only call arc_access on anonymous buffers.  This is because
2344789Sahrens 		 * if we've issued an I/O for an evicted buffer, we've already
2345789Sahrens 		 * called arc_access (to prevent any simultaneous readers from
2346789Sahrens 		 * getting confused).
2347789Sahrens 		 */
23483403Sbmc 		if (zio->io_error == 0 && hdr->b_state == arc_anon)
23492688Smaybee 			arc_access(hdr, hash_lock);
23502688Smaybee 		mutex_exit(hash_lock);
2351789Sahrens 	} else {
2352789Sahrens 		/*
2353789Sahrens 		 * This block was freed while we waited for the read to
2354789Sahrens 		 * complete.  It has been removed from the hash table and
2355789Sahrens 		 * moved to the anonymous state (so that it won't show up
2356789Sahrens 		 * in the cache).
2357789Sahrens 		 */
23583403Sbmc 		ASSERT3P(hdr->b_state, ==, arc_anon);
2359789Sahrens 		freeable = refcount_is_zero(&hdr->b_refcnt);
2360789Sahrens 	}
2361789Sahrens 
2362789Sahrens 	/* execute each callback and free its structure */
2363789Sahrens 	while ((acb = callback_list) != NULL) {
2364789Sahrens 		if (acb->acb_done)
2365789Sahrens 			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
2366789Sahrens 
2367789Sahrens 		if (acb->acb_zio_dummy != NULL) {
2368789Sahrens 			acb->acb_zio_dummy->io_error = zio->io_error;
2369789Sahrens 			zio_nowait(acb->acb_zio_dummy);
2370789Sahrens 		}
2371789Sahrens 
2372789Sahrens 		callback_list = acb->acb_next;
2373789Sahrens 		kmem_free(acb, sizeof (arc_callback_t));
2374789Sahrens 	}
2375789Sahrens 
2376789Sahrens 	if (freeable)
23771544Seschrock 		arc_hdr_destroy(hdr);
2378789Sahrens }
2379789Sahrens 
2380789Sahrens /*
2381789Sahrens  * "Read" the block block at the specified DVA (in bp) via the
2382789Sahrens  * cache.  If the block is found in the cache, invoke the provided
2383789Sahrens  * callback immediately and return.  Note that the `zio' parameter
2384789Sahrens  * in the callback will be NULL in this case, since no IO was
2385789Sahrens  * required.  If the block is not in the cache pass the read request
2386789Sahrens  * on to the spa with a substitute callback function, so that the
2387789Sahrens  * requested block will be added to the cache.
2388789Sahrens  *
2389789Sahrens  * If a read request arrives for a block that has a read in-progress,
2390789Sahrens  * either wait for the in-progress read to complete (and return the
2391789Sahrens  * results); or, if this is a read with a "done" func, add a record
2392789Sahrens  * to the read to invoke the "done" func when the read completes,
2393789Sahrens  * and return; or just return.
2394789Sahrens  *
2395789Sahrens  * arc_read_done() will invoke all the requested "done" functions
2396789Sahrens  * for readers of this block.
2397789Sahrens  */
2398789Sahrens int
2399789Sahrens arc_read(zio_t *pio, spa_t *spa, blkptr_t *bp, arc_byteswap_func_t *swap,
2400789Sahrens     arc_done_func_t *done, void *private, int priority, int flags,
24012391Smaybee     uint32_t *arc_flags, zbookmark_t *zb)
2402789Sahrens {
2403789Sahrens 	arc_buf_hdr_t *hdr;
2404789Sahrens 	arc_buf_t *buf;
2405789Sahrens 	kmutex_t *hash_lock;
24065450Sbrendan 	zio_t *rzio;
2407789Sahrens 
2408789Sahrens top:
2409789Sahrens 	hdr = buf_hash_find(spa, BP_IDENTITY(bp), bp->blk_birth, &hash_lock);
24101544Seschrock 	if (hdr && hdr->b_datacnt > 0) {
2411789Sahrens 
24122391Smaybee 		*arc_flags |= ARC_CACHED;
24132391Smaybee 
2414789Sahrens 		if (HDR_IO_IN_PROGRESS(hdr)) {
24152391Smaybee 
24162391Smaybee 			if (*arc_flags & ARC_WAIT) {
24172391Smaybee 				cv_wait(&hdr->b_cv, hash_lock);
24182391Smaybee 				mutex_exit(hash_lock);
24192391Smaybee 				goto top;
24202391Smaybee 			}
24212391Smaybee 			ASSERT(*arc_flags & ARC_NOWAIT);
24222391Smaybee 
24232391Smaybee 			if (done) {
2424789Sahrens 				arc_callback_t	*acb = NULL;
2425789Sahrens 
2426789Sahrens 				acb = kmem_zalloc(sizeof (arc_callback_t),
2427789Sahrens 				    KM_SLEEP);
2428789Sahrens 				acb->acb_done = done;
2429789Sahrens 				acb->acb_private = private;
2430789Sahrens 				acb->acb_byteswap = swap;
2431789Sahrens 				if (pio != NULL)
2432789Sahrens 					acb->acb_zio_dummy = zio_null(pio,
2433789Sahrens 					    spa, NULL, NULL, flags);
2434789Sahrens 
2435789Sahrens 				ASSERT(acb->acb_done != NULL);
2436789Sahrens 				acb->acb_next = hdr->b_acb;
2437789Sahrens 				hdr->b_acb = acb;
2438789Sahrens 				add_reference(hdr, hash_lock, private);
2439789Sahrens 				mutex_exit(hash_lock);
2440789Sahrens 				return (0);
2441789Sahrens 			}
2442789Sahrens 			mutex_exit(hash_lock);
2443789Sahrens 			return (0);
2444789Sahrens 		}
2445789Sahrens 
24463403Sbmc 		ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
2447789Sahrens 
24481544Seschrock 		if (done) {
24492688Smaybee 			add_reference(hdr, hash_lock, private);
24501544Seschrock 			/*
24511544Seschrock 			 * If this block is already in use, create a new
24521544Seschrock 			 * copy of the data so that we will be guaranteed
24531544Seschrock 			 * that arc_release() will always succeed.
24541544Seschrock 			 */
24551544Seschrock 			buf = hdr->b_buf;
24561544Seschrock 			ASSERT(buf);
24571544Seschrock 			ASSERT(buf->b_data);
24582688Smaybee 			if (HDR_BUF_AVAILABLE(hdr)) {
24591544Seschrock 				ASSERT(buf->b_efunc == NULL);
24601544Seschrock 				hdr->b_flags &= ~ARC_BUF_AVAILABLE;
24612688Smaybee 			} else {
24622688Smaybee 				buf = arc_buf_clone(buf);
24631544Seschrock 			}
24642391Smaybee 		} else if (*arc_flags & ARC_PREFETCH &&
24652391Smaybee 		    refcount_count(&hdr->b_refcnt) == 0) {
24662391Smaybee 			hdr->b_flags |= ARC_PREFETCH;
2467789Sahrens 		}
2468789Sahrens 		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
24692688Smaybee 		arc_access(hdr, hash_lock);
24702688Smaybee 		mutex_exit(hash_lock);
24713403Sbmc 		ARCSTAT_BUMP(arcstat_hits);
24723403Sbmc 		ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
24733403Sbmc 		    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
24743403Sbmc 		    data, metadata, hits);
24753403Sbmc 
2476789Sahrens 		if (done)
2477789Sahrens 			done(NULL, buf, private);
2478789Sahrens 	} else {
2479789Sahrens 		uint64_t size = BP_GET_LSIZE(bp);
2480789Sahrens 		arc_callback_t	*acb;
2481*6987Sbrendan 		vdev_t *vd = NULL;
2482*6987Sbrendan 		daddr_t addr;
2483789Sahrens 
2484789Sahrens 		if (hdr == NULL) {
2485789Sahrens 			/* this block is not in the cache */
2486789Sahrens 			arc_buf_hdr_t	*exists;
24873290Sjohansen 			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
24883290Sjohansen 			buf = arc_buf_alloc(spa, size, private, type);
2489789Sahrens 			hdr = buf->b_hdr;
2490789Sahrens 			hdr->b_dva = *BP_IDENTITY(bp);
2491789Sahrens 			hdr->b_birth = bp->blk_birth;
2492789Sahrens 			hdr->b_cksum0 = bp->blk_cksum.zc_word[0];
2493789Sahrens 			exists = buf_hash_insert(hdr, &hash_lock);
2494789Sahrens 			if (exists) {
2495789Sahrens 				/* somebody beat us to the hash insert */
2496789Sahrens 				mutex_exit(hash_lock);
2497789Sahrens 				bzero(&hdr->b_dva, sizeof (dva_t));
2498789Sahrens 				hdr->b_birth = 0;
2499789Sahrens 				hdr->b_cksum0 = 0;
25001544Seschrock 				(void) arc_buf_remove_ref(buf, private);
2501789Sahrens 				goto top; /* restart the IO request */
2502789Sahrens 			}
25032391Smaybee 			/* if this is a prefetch, we don't have a reference */
25042391Smaybee 			if (*arc_flags & ARC_PREFETCH) {
25052391Smaybee 				(void) remove_reference(hdr, hash_lock,
25062391Smaybee 				    private);
25072391Smaybee 				hdr->b_flags |= ARC_PREFETCH;
25082391Smaybee 			}
25092391Smaybee 			if (BP_GET_LEVEL(bp) > 0)
25102391Smaybee 				hdr->b_flags |= ARC_INDIRECT;
2511789Sahrens 		} else {
2512789Sahrens 			/* this block is in the ghost cache */
25131544Seschrock 			ASSERT(GHOST_STATE(hdr->b_state));
25141544Seschrock 			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
25152391Smaybee 			ASSERT3U(refcount_count(&hdr->b_refcnt), ==, 0);
25162391Smaybee 			ASSERT(hdr->b_buf == NULL);
2517789Sahrens 
25182391Smaybee 			/* if this is a prefetch, we don't have a reference */
25192391Smaybee 			if (*arc_flags & ARC_PREFETCH)
25202391Smaybee 				hdr->b_flags |= ARC_PREFETCH;
25212391Smaybee 			else
25222391Smaybee 				add_reference(hdr, hash_lock, private);
25236245Smaybee 			buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
25241544Seschrock 			buf->b_hdr = hdr;
25252688Smaybee 			buf->b_data = NULL;
25261544Seschrock 			buf->b_efunc = NULL;
25271544Seschrock 			buf->b_private = NULL;
25281544Seschrock 			buf->b_next = NULL;
25291544Seschrock 			hdr->b_buf = buf;
25302688Smaybee 			arc_get_data_buf(buf);
25311544Seschrock 			ASSERT(hdr->b_datacnt == 0);
25321544Seschrock 			hdr->b_datacnt = 1;
25332391Smaybee 
2534789Sahrens 		}
2535789Sahrens 
2536789Sahrens 		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
2537789Sahrens 		acb->acb_done = done;
2538789Sahrens 		acb->acb_private = private;
2539789Sahrens 		acb->acb_byteswap = swap;
2540789Sahrens 
2541789Sahrens 		ASSERT(hdr->b_acb == NULL);
2542789Sahrens 		hdr->b_acb = acb;
2543789Sahrens 		hdr->b_flags |= ARC_IO_IN_PROGRESS;
2544789Sahrens 
2545789Sahrens 		/*
2546789Sahrens 		 * If the buffer has been evicted, migrate it to a present state
2547789Sahrens 		 * before issuing the I/O.  Once we drop the hash-table lock,
2548789Sahrens 		 * the header will be marked as I/O in progress and have an
2549789Sahrens 		 * attached buffer.  At this point, anybody who finds this
2550789Sahrens 		 * buffer ought to notice that it's legit but has a pending I/O.
2551789Sahrens 		 */
2552789Sahrens 
25531544Seschrock 		if (GHOST_STATE(hdr->b_state))
25542688Smaybee 			arc_access(hdr, hash_lock);
2555789Sahrens 
2556*6987Sbrendan 		if (hdr->b_l2hdr != NULL) {
2557*6987Sbrendan 			vd = hdr->b_l2hdr->b_dev->l2ad_vdev;
2558*6987Sbrendan 			addr = hdr->b_l2hdr->b_daddr;
2559*6987Sbrendan 		}
2560*6987Sbrendan 
2561*6987Sbrendan 		mutex_exit(hash_lock);
2562*6987Sbrendan 
2563789Sahrens 		ASSERT3U(hdr->b_size, ==, size);
25641596Sahrens 		DTRACE_PROBE3(arc__miss, blkptr_t *, bp, uint64_t, size,
25651596Sahrens 		    zbookmark_t *, zb);
25663403Sbmc 		ARCSTAT_BUMP(arcstat_misses);
25673403Sbmc 		ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
25683403Sbmc 		    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
25693403Sbmc 		    data, metadata, misses);
25701544Seschrock 
25715450Sbrendan 		if (l2arc_ndev != 0) {
25725450Sbrendan 			/*
2573*6987Sbrendan 			 * Lock out device removal.
25745450Sbrendan 			 */
2575*6987Sbrendan 			spa_config_enter(spa, RW_READER, FTAG);
2576*6987Sbrendan 
2577*6987Sbrendan 			/*
2578*6987Sbrendan 			 * Read from the L2ARC if the following are true:
2579*6987Sbrendan 			 * 1. The L2ARC vdev was previously cached.
2580*6987Sbrendan 			 * 2. This buffer still has L2ARC metadata.
2581*6987Sbrendan 			 * 3. This buffer isn't currently writing to the L2ARC.
2582*6987Sbrendan 			 * 4. The L2ARC entry wasn't evicted, which may
2583*6987Sbrendan 			 *    also have invalidated the vdev.
2584*6987Sbrendan 			 */
2585*6987Sbrendan 			if (vd != NULL && hdr->b_l2hdr != NULL &&
2586*6987Sbrendan 			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr)) {
25875450Sbrendan 				l2arc_read_callback_t *cb;
25885450Sbrendan 
25896643Seschrock 				if (vdev_is_dead(vd))
2590*6987Sbrendan 					goto l2skip;
25915450Sbrendan 
25926643Seschrock 				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
25936643Seschrock 				ARCSTAT_BUMP(arcstat_l2_hits);
25946643Seschrock 
25955450Sbrendan 				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
25965450Sbrendan 				    KM_SLEEP);
25975450Sbrendan 				cb->l2rcb_buf = buf;
25985450Sbrendan 				cb->l2rcb_spa = spa;
25995450Sbrendan 				cb->l2rcb_bp = *bp;
26005450Sbrendan 				cb->l2rcb_zb = *zb;
26015450Sbrendan 				cb->l2rcb_flags = flags;
26025450Sbrendan 
26035450Sbrendan 				/*
26045450Sbrendan 				 * l2arc read.
26055450Sbrendan 				 */
26065450Sbrendan 				rzio = zio_read_phys(pio, vd, addr, size,
26075450Sbrendan 				    buf->b_data, ZIO_CHECKSUM_OFF,
2608*6987Sbrendan 				    l2arc_read_done, cb, priority, flags |
2609*6987Sbrendan 				    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_CANFAIL,
2610*6987Sbrendan 				    B_FALSE);
26115450Sbrendan 				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
26125450Sbrendan 				    zio_t *, rzio);
2613*6987Sbrendan 				spa_config_exit(spa, FTAG);
2614*6987Sbrendan 
2615*6987Sbrendan 				if (*arc_flags & ARC_NOWAIT) {
2616*6987Sbrendan 					zio_nowait(rzio);
2617*6987Sbrendan 					return (0);
2618*6987Sbrendan 				}
2619*6987Sbrendan 
2620*6987Sbrendan 				ASSERT(*arc_flags & ARC_WAIT);
2621*6987Sbrendan 				if (zio_wait(rzio) == 0)
2622*6987Sbrendan 					return (0);
2623*6987Sbrendan 
2624*6987Sbrendan 				/* l2arc read error; goto zio_read() */
26255450Sbrendan 			} else {
26265450Sbrendan 				DTRACE_PROBE1(l2arc__miss,
26275450Sbrendan 				    arc_buf_hdr_t *, hdr);
26285450Sbrendan 				ARCSTAT_BUMP(arcstat_l2_misses);
26295450Sbrendan 				if (HDR_L2_WRITING(hdr))
26305450Sbrendan 					ARCSTAT_BUMP(arcstat_l2_rw_clash);
2631*6987Sbrendan l2skip:
2632*6987Sbrendan 				spa_config_exit(spa, FTAG);
26335450Sbrendan 			}
26345450Sbrendan 		}
26356643Seschrock 
2636789Sahrens 		rzio = zio_read(pio, spa, bp, buf->b_data, size,
26371544Seschrock 		    arc_read_done, buf, priority, flags, zb);
2638789Sahrens 
26392391Smaybee 		if (*arc_flags & ARC_WAIT)
2640789Sahrens 			return (zio_wait(rzio));
2641789Sahrens 
26422391Smaybee 		ASSERT(*arc_flags & ARC_NOWAIT);
2643789Sahrens 		zio_nowait(rzio);
2644789Sahrens 	}
2645789Sahrens 	return (0);
2646789Sahrens }
2647789Sahrens 
2648789Sahrens /*
2649789Sahrens  * arc_read() variant to support pool traversal.  If the block is already
2650789Sahrens  * in the ARC, make a copy of it; otherwise, the caller will do the I/O.
2651789Sahrens  * The idea is that we don't want pool traversal filling up memory, but
2652789Sahrens  * if the ARC already has the data anyway, we shouldn't pay for the I/O.
2653789Sahrens  */
2654789Sahrens int
2655789Sahrens arc_tryread(spa_t *spa, blkptr_t *bp, void *data)
2656789Sahrens {
2657789Sahrens 	arc_buf_hdr_t *hdr;
2658789Sahrens 	kmutex_t *hash_mtx;
2659789Sahrens 	int rc = 0;
2660789Sahrens 
2661789Sahrens 	hdr = buf_hash_find(spa, BP_IDENTITY(bp), bp->blk_birth, &hash_mtx);
2662789Sahrens 
26631544Seschrock 	if (hdr && hdr->b_datacnt > 0 && !HDR_IO_IN_PROGRESS(hdr)) {
26641544Seschrock 		arc_buf_t *buf = hdr->b_buf;
26651544Seschrock 
26661544Seschrock 		ASSERT(buf);
26671544Seschrock 		while (buf->b_data == NULL) {
26681544Seschrock 			buf = buf->b_next;
26691544Seschrock 			ASSERT(buf);
26701544Seschrock 		}
26711544Seschrock 		bcopy(buf->b_data, data, hdr->b_size);
26721544Seschrock 	} else {
2673789Sahrens 		rc = ENOENT;
26741544Seschrock 	}
2675789Sahrens 
2676789Sahrens 	if (hash_mtx)
2677789Sahrens 		mutex_exit(hash_mtx);
2678789Sahrens 
2679789Sahrens 	return (rc);
2680789Sahrens }
2681789Sahrens 
26821544Seschrock void
26831544Seschrock arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
26841544Seschrock {
26851544Seschrock 	ASSERT(buf->b_hdr != NULL);
26863403Sbmc 	ASSERT(buf->b_hdr->b_state != arc_anon);
26871544Seschrock 	ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt) || func == NULL);
26881544Seschrock 	buf->b_efunc = func;
26891544Seschrock 	buf->b_private = private;
26901544Seschrock }
26911544Seschrock 
26921544Seschrock /*
26931544Seschrock  * This is used by the DMU to let the ARC know that a buffer is
26941544Seschrock  * being evicted, so the ARC should clean up.  If this arc buf
26951544Seschrock  * is not yet in the evicted state, it will be put there.
26961544Seschrock  */
26971544Seschrock int
26981544Seschrock arc_buf_evict(arc_buf_t *buf)
26991544Seschrock {
27002887Smaybee 	arc_buf_hdr_t *hdr;
27011544Seschrock 	kmutex_t *hash_lock;
27021544Seschrock 	arc_buf_t **bufp;
27031544Seschrock 
27042887Smaybee 	mutex_enter(&arc_eviction_mtx);
27052887Smaybee 	hdr = buf->b_hdr;
27061544Seschrock 	if (hdr == NULL) {
27071544Seschrock 		/*
27081544Seschrock 		 * We are in arc_do_user_evicts().
27091544Seschrock 		 */
27101544Seschrock 		ASSERT(buf->b_data == NULL);
27112887Smaybee 		mutex_exit(&arc_eviction_mtx);
27121544Seschrock 		return (0);
27131544Seschrock 	}
27142887Smaybee 	hash_lock = HDR_LOCK(hdr);
27152887Smaybee 	mutex_exit(&arc_eviction_mtx);
27161544Seschrock 
27171544Seschrock 	mutex_enter(hash_lock);
27181544Seschrock 
27192724Smaybee 	if (buf->b_data == NULL) {
27202724Smaybee 		/*
27212724Smaybee 		 * We are on the eviction list.
27222724Smaybee 		 */
27232724Smaybee 		mutex_exit(hash_lock);
27242724Smaybee 		mutex_enter(&arc_eviction_mtx);
27252724Smaybee 		if (buf->b_hdr == NULL) {
27262724Smaybee 			/*
27272724Smaybee 			 * We are already in arc_do_user_evicts().
27282724Smaybee 			 */
27292724Smaybee 			mutex_exit(&arc_eviction_mtx);
27302724Smaybee 			return (0);
27312724Smaybee 		} else {
27322724Smaybee 			arc_buf_t copy = *buf; /* structure assignment */
27332724Smaybee 			/*
27342724Smaybee 			 * Process this buffer now
27352724Smaybee 			 * but let arc_do_user_evicts() do the reaping.
27362724Smaybee 			 */
27372724Smaybee 			buf->b_efunc = NULL;
27382724Smaybee 			mutex_exit(&arc_eviction_mtx);
27392724Smaybee 			VERIFY(copy.b_efunc(&copy) == 0);
27402724Smaybee 			return (1);
27412724Smaybee 		}
27422724Smaybee 	}
27432724Smaybee 
27442724Smaybee 	ASSERT(buf->b_hdr == hdr);
27452724Smaybee 	ASSERT3U(refcount_count(&hdr->b_refcnt), <, hdr->b_datacnt);
27463403Sbmc 	ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
27471544Seschrock 
27481544Seschrock 	/*
27491544Seschrock 	 * Pull this buffer off of the hdr
27501544Seschrock 	 */
27511544Seschrock 	bufp = &hdr->b_buf;
27521544Seschrock 	while (*bufp != buf)
27531544Seschrock 		bufp = &(*bufp)->b_next;
27541544Seschrock 	*bufp = buf->b_next;
27551544Seschrock 
27561544Seschrock 	ASSERT(buf->b_data != NULL);
27572688Smaybee 	arc_buf_destroy(buf, FALSE, FALSE);
27581544Seschrock 
27591544Seschrock 	if (hdr->b_datacnt == 0) {
27601544Seschrock 		arc_state_t *old_state = hdr->b_state;
27611544Seschrock 		arc_state_t *evicted_state;
27621544Seschrock 
27631544Seschrock 		ASSERT(refcount_is_zero(&hdr->b_refcnt));
27641544Seschrock 
27651544Seschrock 		evicted_state =
27663403Sbmc 		    (old_state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
27671544Seschrock 
27683403Sbmc 		mutex_enter(&old_state->arcs_mtx);
27693403Sbmc 		mutex_enter(&evicted_state->arcs_mtx);
27701544Seschrock 
27711544Seschrock 		arc_change_state(evicted_state, hdr, hash_lock);
27721544Seschrock 		ASSERT(HDR_IN_HASH_TABLE(hdr));
27735450Sbrendan 		hdr->b_flags |= ARC_IN_HASH_TABLE;
27745450Sbrendan 		hdr->b_flags &= ~ARC_BUF_AVAILABLE;
27751544Seschrock 
27763403Sbmc 		mutex_exit(&evicted_state->arcs_mtx);
27773403Sbmc 		mutex_exit(&old_state->arcs_mtx);
27781544Seschrock 	}
27791544Seschrock 	mutex_exit(hash_lock);
27801819Smaybee 
27811544Seschrock 	VERIFY(buf->b_efunc(buf) == 0);
27821544Seschrock 	buf->b_efunc = NULL;
27831544Seschrock 	buf->b_private = NULL;
27841544Seschrock 	buf->b_hdr = NULL;
27851544Seschrock 	kmem_cache_free(buf_cache, buf);
27861544Seschrock 	return (1);
27871544Seschrock }
27881544Seschrock 
2789789Sahrens /*
2790789Sahrens  * Release this buffer from the cache.  This must be done
2791789Sahrens  * after a read and prior to modifying the buffer contents.
2792789Sahrens  * If the buffer has more than one reference, we must make
2793789Sahrens  * make a new hdr for the buffer.
2794789Sahrens  */
2795789Sahrens void
2796789Sahrens arc_release(arc_buf_t *buf, void *tag)
2797789Sahrens {
2798789Sahrens 	arc_buf_hdr_t *hdr = buf->b_hdr;
2799789Sahrens 	kmutex_t *hash_lock = HDR_LOCK(hdr);
28005450Sbrendan 	l2arc_buf_hdr_t *l2hdr = NULL;
28015450Sbrendan 	uint64_t buf_size;
2802789Sahrens 
2803789Sahrens 	/* this buffer is not on any list */
2804789Sahrens 	ASSERT(refcount_count(&hdr->b_refcnt) > 0);
2805789Sahrens 
28063403Sbmc 	if (hdr->b_state == arc_anon) {
2807789Sahrens 		/* this buffer is already released */
2808789Sahrens 		ASSERT3U(refcount_count(&hdr->b_refcnt), ==, 1);
2809789Sahrens 		ASSERT(BUF_EMPTY(hdr));
28101544Seschrock 		ASSERT(buf->b_efunc == NULL);
28113093Sahrens 		arc_buf_thaw(buf);
2812789Sahrens 		return;
2813789Sahrens 	}
2814789Sahrens 
2815789Sahrens 	mutex_enter(hash_lock);
2816789Sahrens 
28171544Seschrock 	/*
28181544Seschrock 	 * Do we have more than one buf?
28191544Seschrock 	 */
28201544Seschrock 	if (hdr->b_buf != buf || buf->b_next != NULL) {
2821789Sahrens 		arc_buf_hdr_t *nhdr;
2822789Sahrens 		arc_buf_t **bufp;
2823789Sahrens 		uint64_t blksz = hdr->b_size;
2824789Sahrens 		spa_t *spa = hdr->b_spa;
28253290Sjohansen 		arc_buf_contents_t type = hdr->b_type;
28265450Sbrendan 		uint32_t flags = hdr->b_flags;
2827789Sahrens 
28281544Seschrock 		ASSERT(hdr->b_datacnt > 1);
2829789Sahrens 		/*
2830789Sahrens 		 * Pull the data off of this buf and attach it to
2831789Sahrens 		 * a new anonymous buf.
2832789Sahrens 		 */
28331544Seschrock 		(void) remove_reference(hdr, hash_lock, tag);
2834789Sahrens 		bufp = &hdr->b_buf;
28351544Seschrock 		while (*bufp != buf)
2836789Sahrens 			bufp = &(*bufp)->b_next;
2837789Sahrens 		*bufp = (*bufp)->b_next;
28383897Smaybee 		buf->b_next = NULL;
28391544Seschrock 
28403403Sbmc 		ASSERT3U(hdr->b_state->arcs_size, >=, hdr->b_size);
28413403Sbmc 		atomic_add_64(&hdr->b_state->arcs_size, -hdr->b_size);
28421544Seschrock 		if (refcount_is_zero(&hdr->b_refcnt)) {
28434309Smaybee 			uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
28444309Smaybee 			ASSERT3U(*size, >=, hdr->b_size);
28454309Smaybee 			atomic_add_64(size, -hdr->b_size);
28461544Seschrock 		}
28471544Seschrock 		hdr->b_datacnt -= 1;
28485450Sbrendan 		if (hdr->b_l2hdr != NULL) {
28495450Sbrendan 			mutex_enter(&l2arc_buflist_mtx);
28505450Sbrendan 			l2hdr = hdr->b_l2hdr;
28515450Sbrendan 			hdr->b_l2hdr = NULL;
28525450Sbrendan 			buf_size = hdr->b_size;
28535450Sbrendan 		}
28543547Smaybee 		arc_cksum_verify(buf);
28551544Seschrock 
2856789Sahrens 		mutex_exit(hash_lock);
2857789Sahrens 
28586245Smaybee 		nhdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
2859789Sahrens 		nhdr->b_size = blksz;
2860789Sahrens 		nhdr->b_spa = spa;
28613290Sjohansen 		nhdr->b_type = type;
2862789Sahrens 		nhdr->b_buf = buf;
28633403Sbmc 		nhdr->b_state = arc_anon;
2864789Sahrens 		nhdr->b_arc_access = 0;
28655450Sbrendan 		nhdr->b_flags = flags & ARC_L2_WRITING;
28665450Sbrendan 		nhdr->b_l2hdr = NULL;
28671544Seschrock 		nhdr->b_datacnt = 1;
28683547Smaybee 		nhdr->b_freeze_cksum = NULL;
28693897Smaybee 		(void) refcount_add(&nhdr->b_refcnt, tag);
2870789Sahrens 		buf->b_hdr = nhdr;
28713403Sbmc 		atomic_add_64(&arc_anon->arcs_size, blksz);
2872789Sahrens 	} else {
28731544Seschrock 		ASSERT(refcount_count(&hdr->b_refcnt) == 1);
2874789Sahrens 		ASSERT(!list_link_active(&hdr->b_arc_node));
2875789Sahrens 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
28763403Sbmc 		arc_change_state(arc_anon, hdr, hash_lock);
2877789Sahrens 		hdr->b_arc_access = 0;
28785450Sbrendan 		if (hdr->b_l2hdr != NULL) {
28795450Sbrendan 			mutex_enter(&l2arc_buflist_mtx);
28805450Sbrendan 			l2hdr = hdr->b_l2hdr;
28815450Sbrendan 			hdr->b_l2hdr = NULL;
28825450Sbrendan 			buf_size = hdr->b_size;
28835450Sbrendan 		}
2884789Sahrens 		mutex_exit(hash_lock);
28855450Sbrendan 
2886789Sahrens 		bzero(&hdr->b_dva, sizeof (dva_t));
2887789Sahrens 		hdr->b_birth = 0;
2888789Sahrens 		hdr->b_cksum0 = 0;
28893547Smaybee 		arc_buf_thaw(buf);
2890789Sahrens 	}
28911544Seschrock 	buf->b_efunc = NULL;
28921544Seschrock 	buf->b_private = NULL;
28935450Sbrendan 
28945450Sbrendan 	if (l2hdr) {
28955450Sbrendan 		list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
28965450Sbrendan 		kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
28975450Sbrendan 		ARCSTAT_INCR(arcstat_l2_size, -buf_size);
28985450Sbrendan 	}
28995450Sbrendan 	if (MUTEX_HELD(&l2arc_buflist_mtx))
29005450Sbrendan 		mutex_exit(&l2arc_buflist_mtx);
2901789Sahrens }
2902789Sahrens 
2903789Sahrens int
2904789Sahrens arc_released(arc_buf_t *buf)
2905789Sahrens {
29063403Sbmc 	return (buf->b_data != NULL && buf->b_hdr->b_state == arc_anon);
29071544Seschrock }
29081544Seschrock 
29091544Seschrock int
29101544Seschrock arc_has_callback(arc_buf_t *buf)
29111544Seschrock {
29121544Seschrock 	return (buf->b_efunc != NULL);
2913789Sahrens }
2914789Sahrens 
29151544Seschrock #ifdef ZFS_DEBUG
29161544Seschrock int
29171544Seschrock arc_referenced(arc_buf_t *buf)
29181544Seschrock {
29191544Seschrock 	return (refcount_count(&buf->b_hdr->b_refcnt));
29201544Seschrock }
29211544Seschrock #endif
29221544Seschrock 
2923789Sahrens static void
29243547Smaybee arc_write_ready(zio_t *zio)
29253547Smaybee {
29263547Smaybee 	arc_write_callback_t *callback = zio->io_private;
29273547Smaybee 	arc_buf_t *buf = callback->awcb_buf;
29285329Sgw25295 	arc_buf_hdr_t *hdr = buf->b_hdr;
29295329Sgw25295 
29305329Sgw25295 	if (zio->io_error == 0 && callback->awcb_ready) {
29313547Smaybee 		ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt));
29323547Smaybee 		callback->awcb_ready(zio, buf, callback->awcb_private);
29333547Smaybee 	}
29345329Sgw25295 	/*
29355329Sgw25295 	 * If the IO is already in progress, then this is a re-write
29365329Sgw25295 	 * attempt, so we need to thaw and re-compute the cksum. It is
29375329Sgw25295 	 * the responsibility of the callback to handle the freeing
29385329Sgw25295 	 * and accounting for any re-write attempt. If we don't have a
29395329Sgw25295 	 * callback registered then simply free the block here.
29405329Sgw25295 	 */
29415329Sgw25295 	if (HDR_IO_IN_PROGRESS(hdr)) {
29425329Sgw25295 		if (!BP_IS_HOLE(&zio->io_bp_orig) &&
29435329Sgw25295 		    callback->awcb_ready == NULL) {
29445329Sgw25295 			zio_nowait(zio_free(zio, zio->io_spa, zio->io_txg,
29455329Sgw25295 			    &zio->io_bp_orig, NULL, NULL));
29465329Sgw25295 		}
29475329Sgw25295 		mutex_enter(&hdr->b_freeze_lock);
29485329Sgw25295 		if (hdr->b_freeze_cksum != NULL) {
29495329Sgw25295 			kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
29505329Sgw25295 			hdr->b_freeze_cksum = NULL;
29515329Sgw25295 		}
29525329Sgw25295 		mutex_exit(&hdr->b_freeze_lock);
29535329Sgw25295 	}
29545450Sbrendan 	arc_cksum_compute(buf, B_FALSE);
29555329Sgw25295 	hdr->b_flags |= ARC_IO_IN_PROGRESS;
29563547Smaybee }
29573547Smaybee 
29583547Smaybee static void
2959789Sahrens arc_write_done(zio_t *zio)
2960789Sahrens {
29613547Smaybee 	arc_write_callback_t *callback = zio->io_private;
29623547Smaybee 	arc_buf_t *buf = callback->awcb_buf;
29633547Smaybee 	arc_buf_hdr_t *hdr = buf->b_hdr;
2964789Sahrens 
2965789Sahrens 	hdr->b_acb = NULL;
2966789Sahrens 
2967789Sahrens 	/* this buffer is on no lists and is not in the hash table */
29683403Sbmc 	ASSERT3P(hdr->b_state, ==, arc_anon);
2969789Sahrens 
2970789Sahrens 	hdr->b_dva = *BP_IDENTITY(zio->io_bp);
2971789Sahrens 	hdr->b_birth = zio->io_bp->blk_birth;
2972789Sahrens 	hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
29731544Seschrock 	/*
29741544Seschrock 	 * If the block to be written was all-zero, we may have
29751544Seschrock 	 * compressed it away.  In this case no write was performed
29761544Seschrock 	 * so there will be no dva/birth-date/checksum.  The buffer
29771544Seschrock 	 * must therefor remain anonymous (and uncached).
29781544Seschrock 	 */
2979789Sahrens 	if (!BUF_EMPTY(hdr)) {
2980789Sahrens 		arc_buf_hdr_t *exists;
2981789Sahrens 		kmutex_t *hash_lock;
2982789Sahrens 
29833093Sahrens 		arc_cksum_verify(buf);
29843093Sahrens 
2985789Sahrens 		exists = buf_hash_insert(hdr, &hash_lock);
2986789Sahrens 		if (exists) {
2987789Sahrens 			/*
2988789Sahrens 			 * This can only happen if we overwrite for
2989789Sahrens 			 * sync-to-convergence, because we remove
2990789Sahrens 			 * buffers from the hash table when we arc_free().
2991789Sahrens 			 */
2992789Sahrens 			ASSERT(DVA_EQUAL(BP_IDENTITY(&zio->io_bp_orig),
2993789Sahrens 			    BP_IDENTITY(zio->io_bp)));
2994789Sahrens 			ASSERT3U(zio->io_bp_orig.blk_birth, ==,
2995789Sahrens 			    zio->io_bp->blk_birth);
2996789Sahrens 
2997789Sahrens 			ASSERT(refcount_is_zero(&exists->b_refcnt));
29983403Sbmc 			arc_change_state(arc_anon, exists, hash_lock);
2999789Sahrens 			mutex_exit(hash_lock);
30001544Seschrock 			arc_hdr_destroy(exists);
3001789Sahrens 			exists = buf_hash_insert(hdr, &hash_lock);
3002789Sahrens 			ASSERT3P(exists, ==, NULL);
3003789Sahrens 		}
30041544Seschrock 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
30052688Smaybee 		arc_access(hdr, hash_lock);
30062688Smaybee 		mutex_exit(hash_lock);
30073547Smaybee 	} else if (callback->awcb_done == NULL) {
30081544Seschrock 		int destroy_hdr;
30091544Seschrock 		/*
30101544Seschrock 		 * This is an anonymous buffer with no user callback,
30111544Seschrock 		 * destroy it if there are no active references.
30121544Seschrock 		 */
30131544Seschrock 		mutex_enter(&arc_eviction_mtx);
30141544Seschrock 		destroy_hdr = refcount_is_zero(&hdr->b_refcnt);
30151544Seschrock 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
30161544Seschrock 		mutex_exit(&arc_eviction_mtx);
30171544Seschrock 		if (destroy_hdr)
30181544Seschrock 			arc_hdr_destroy(hdr);
30191544Seschrock 	} else {
30201544Seschrock 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3021789Sahrens 	}
30221544Seschrock 
30233547Smaybee 	if (callback->awcb_done) {
3024789Sahrens 		ASSERT(!refcount_is_zero(&hdr->b_refcnt));
30253547Smaybee 		callback->awcb_done(zio, buf, callback->awcb_private);
3026789Sahrens 	}
3027789Sahrens 
30283547Smaybee 	kmem_free(callback, sizeof (arc_write_callback_t));
3029789Sahrens }
3030789Sahrens 
30313547Smaybee zio_t *
30321775Sbillm arc_write(zio_t *pio, spa_t *spa, int checksum, int compress, int ncopies,
3033789Sahrens     uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
30343547Smaybee     arc_done_func_t *ready, arc_done_func_t *done, void *private, int priority,
30353547Smaybee     int flags, zbookmark_t *zb)
3036789Sahrens {
3037789Sahrens 	arc_buf_hdr_t *hdr = buf->b_hdr;
30383547Smaybee 	arc_write_callback_t *callback;
30393547Smaybee 	zio_t	*zio;
3040789Sahrens 
3041789Sahrens 	/* this is a private buffer - no locking required */
30423403Sbmc 	ASSERT3P(hdr->b_state, ==, arc_anon);
3043789Sahrens 	ASSERT(BUF_EMPTY(hdr));
3044789Sahrens 	ASSERT(!HDR_IO_ERROR(hdr));
30452237Smaybee 	ASSERT((hdr->b_flags & ARC_IO_IN_PROGRESS) == 0);
30462237Smaybee 	ASSERT(hdr->b_acb == 0);
30473547Smaybee 	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
30483547Smaybee 	callback->awcb_ready = ready;
30493547Smaybee 	callback->awcb_done = done;
30503547Smaybee 	callback->awcb_private = private;
30513547Smaybee 	callback->awcb_buf = buf;
30523547Smaybee 	zio = zio_write(pio, spa, checksum, compress, ncopies, txg, bp,
30533547Smaybee 	    buf->b_data, hdr->b_size, arc_write_ready, arc_write_done, callback,
30543547Smaybee 	    priority, flags, zb);
3055789Sahrens 
30563547Smaybee 	return (zio);
3057789Sahrens }
3058789Sahrens 
3059789Sahrens int
3060789Sahrens arc_free(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
3061789Sahrens     zio_done_func_t *done, void *private, uint32_t arc_flags)
3062789Sahrens {
3063789Sahrens 	arc_buf_hdr_t *ab;
3064789Sahrens 	kmutex_t *hash_lock;
3065789Sahrens 	zio_t	*zio;
3066789Sahrens 
3067789Sahrens 	/*
3068789Sahrens 	 * If this buffer is in the cache, release it, so it
3069789Sahrens 	 * can be re-used.
3070789Sahrens 	 */
3071789Sahrens 	ab = buf_hash_find(spa, BP_IDENTITY(bp), bp->blk_birth, &hash_lock);
3072789Sahrens 	if (ab != NULL) {
3073789Sahrens 		/*
3074789Sahrens 		 * The checksum of blocks to free is not always
3075789Sahrens 		 * preserved (eg. on the deadlist).  However, if it is
3076789Sahrens 		 * nonzero, it should match what we have in the cache.
3077789Sahrens 		 */
3078789Sahrens 		ASSERT(bp->blk_cksum.zc_word[0] == 0 ||
3079789Sahrens 		    ab->b_cksum0 == bp->blk_cksum.zc_word[0]);
30803403Sbmc 		if (ab->b_state != arc_anon)
30813403Sbmc 			arc_change_state(arc_anon, ab, hash_lock);
30822391Smaybee 		if (HDR_IO_IN_PROGRESS(ab)) {
30832391Smaybee 			/*
30842391Smaybee 			 * This should only happen when we prefetch.
30852391Smaybee 			 */
30862391Smaybee 			ASSERT(ab->b_flags & ARC_PREFETCH);
30872391Smaybee 			ASSERT3U(ab->b_datacnt, ==, 1);
30882391Smaybee 			ab->b_flags |= ARC_FREED_IN_READ;
30892391Smaybee 			if (HDR_IN_HASH_TABLE(ab))
30902391Smaybee 				buf_hash_remove(ab);
30912391Smaybee 			ab->b_arc_access = 0;
30922391Smaybee 			bzero(&ab->b_dva, sizeof (dva_t));
30932391Smaybee 			ab->b_birth = 0;
30942391Smaybee 			ab->b_cksum0 = 0;
30952391Smaybee 			ab->b_buf->b_efunc = NULL;
30962391Smaybee 			ab->b_buf->b_private = NULL;
30972391Smaybee 			mutex_exit(hash_lock);
30982391Smaybee 		} else if (refcount_is_zero(&ab->b_refcnt)) {
30995450Sbrendan 			ab->b_flags |= ARC_FREE_IN_PROGRESS;
3100789Sahrens 			mutex_exit(hash_lock);
31011544Seschrock 			arc_hdr_destroy(ab);
31023403Sbmc 			ARCSTAT_BUMP(arcstat_deleted);
3103789Sahrens 		} else {
31041589Smaybee 			/*
31052391Smaybee 			 * We still have an active reference on this
31062391Smaybee 			 * buffer.  This can happen, e.g., from
31072391Smaybee 			 * dbuf_unoverride().
31081589Smaybee 			 */
31092391Smaybee 			ASSERT(!HDR_IN_HASH_TABLE(ab));
3110789Sahrens 			ab->b_arc_access = 0;
3111789Sahrens 			bzero(&ab->b_dva, sizeof (dva_t));
3112789Sahrens 			ab->b_birth = 0;
3113789Sahrens 			ab->b_cksum0 = 0;
31141544Seschrock 			ab->b_buf->b_efunc = NULL;
31151544Seschrock 			ab->b_buf->b_private = NULL;
3116789Sahrens 			mutex_exit(hash_lock);
3117789Sahrens 		}
3118789Sahrens 	}
3119789Sahrens 
3120789Sahrens 	zio = zio_free(pio, spa, txg, bp, done, private);
3121789Sahrens 
3122789Sahrens 	if (arc_flags & ARC_WAIT)
3123789Sahrens 		return (zio_wait(zio));
3124789Sahrens 
3125789Sahrens 	ASSERT(arc_flags & ARC_NOWAIT);
3126789Sahrens 	zio_nowait(zio);
3127789Sahrens 
3128789Sahrens 	return (0);
3129789Sahrens }
3130789Sahrens 
31316245Smaybee static int
31326245Smaybee arc_memory_throttle(uint64_t reserve, uint64_t txg)
31336245Smaybee {
31346245Smaybee #ifdef _KERNEL
31356245Smaybee 	uint64_t inflight_data = arc_anon->arcs_size;
31366245Smaybee 	uint64_t available_memory = ptob(freemem);
31376245Smaybee 	static uint64_t page_load = 0;
31386245Smaybee 	static uint64_t last_txg = 0;
31396245Smaybee 
31406245Smaybee #if defined(__i386)
31416245Smaybee 	available_memory =
31426245Smaybee 	    MIN(available_memory, vmem_size(heap_arena, VMEM_FREE));
31436245Smaybee #endif
31446245Smaybee 	if (available_memory >= zfs_write_limit_max)
31456245Smaybee 		return (0);
31466245Smaybee 
31476245Smaybee 	if (txg > last_txg) {
31486245Smaybee 		last_txg = txg;
31496245Smaybee 		page_load = 0;
31506245Smaybee 	}
31516245Smaybee 	/*
31526245Smaybee 	 * If we are in pageout, we know that memory is already tight,
31536245Smaybee 	 * the arc is already going to be evicting, so we just want to
31546245Smaybee 	 * continue to let page writes occur as quickly as possible.
31556245Smaybee 	 */
31566245Smaybee 	if (curproc == proc_pageout) {
31576245Smaybee 		if (page_load > MAX(ptob(minfree), available_memory) / 4)
31586245Smaybee 			return (ERESTART);
31596245Smaybee 		/* Note: reserve is inflated, so we deflate */
31606245Smaybee 		page_load += reserve / 8;
31616245Smaybee 		return (0);
31626245Smaybee 	} else if (page_load > 0 && arc_reclaim_needed()) {
31636245Smaybee 		/* memory is low, delay before restarting */
31646245Smaybee 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
31656245Smaybee 		return (EAGAIN);
31666245Smaybee 	}
31676245Smaybee 	page_load = 0;
31686245Smaybee 
31696245Smaybee 	if (arc_size > arc_c_min) {
31706245Smaybee 		uint64_t evictable_memory =
31716245Smaybee 		    arc_mru->arcs_lsize[ARC_BUFC_DATA] +
31726245Smaybee 		    arc_mru->arcs_lsize[ARC_BUFC_METADATA] +
31736245Smaybee 		    arc_mfu->arcs_lsize[ARC_BUFC_DATA] +
31746245Smaybee 		    arc_mfu->arcs_lsize[ARC_BUFC_METADATA];
31756245Smaybee 		available_memory += MIN(evictable_memory, arc_size - arc_c_min);
31766245Smaybee 	}
31776245Smaybee 
31786245Smaybee 	if (inflight_data > available_memory / 4) {
31796245Smaybee 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
31806245Smaybee 		return (ERESTART);
31816245Smaybee 	}
31826245Smaybee #endif
31836245Smaybee 	return (0);
31846245Smaybee }
31856245Smaybee 
3186789Sahrens void
31876245Smaybee arc_tempreserve_clear(uint64_t reserve)
3188789Sahrens {
31896245Smaybee 	atomic_add_64(&arc_tempreserve, -reserve);
3190789Sahrens 	ASSERT((int64_t)arc_tempreserve >= 0);
3191789Sahrens }
3192789Sahrens 
3193789Sahrens int
31946245Smaybee arc_tempreserve_space(uint64_t reserve, uint64_t txg)
3195789Sahrens {
31966245Smaybee 	int error;
31976245Smaybee 
3198789Sahrens #ifdef ZFS_DEBUG
3199789Sahrens 	/*
3200789Sahrens 	 * Once in a while, fail for no reason.  Everything should cope.
3201789Sahrens 	 */
3202789Sahrens 	if (spa_get_random(10000) == 0) {
3203789Sahrens 		dprintf("forcing random failure\n");
3204789Sahrens 		return (ERESTART);
3205789Sahrens 	}
3206789Sahrens #endif
32076245Smaybee 	if (reserve > arc_c/4 && !arc_no_grow)
32086245Smaybee 		arc_c = MIN(arc_c_max, reserve * 4);
32096245Smaybee 	if (reserve > arc_c)
3210982Smaybee 		return (ENOMEM);
3211982Smaybee 
3212789Sahrens 	/*
32136245Smaybee 	 * Writes will, almost always, require additional memory allocations
32146245Smaybee 	 * in order to compress/encrypt/etc the data.  We therefor need to
32156245Smaybee 	 * make sure that there is sufficient available memory for this.
32166245Smaybee 	 */
32176245Smaybee 	if (error = arc_memory_throttle(reserve, txg))
32186245Smaybee 		return (error);
32196245Smaybee 
32206245Smaybee 	/*
3221982Smaybee 	 * Throttle writes when the amount of dirty data in the cache
3222982Smaybee 	 * gets too large.  We try to keep the cache less than half full
3223982Smaybee 	 * of dirty blocks so that our sync times don't grow too large.
3224982Smaybee 	 * Note: if two requests come in concurrently, we might let them
3225982Smaybee 	 * both succeed, when one of them should fail.  Not a huge deal.
3226789Sahrens 	 */
32276245Smaybee 	if (reserve + arc_tempreserve + arc_anon->arcs_size > arc_c / 2 &&
32286245Smaybee 	    arc_anon->arcs_size > arc_c / 4) {
32294309Smaybee 		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
32304309Smaybee 		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
32314309Smaybee 		    arc_tempreserve>>10,
32324309Smaybee 		    arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
32334309Smaybee 		    arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
32346245Smaybee 		    reserve>>10, arc_c>>10);
3235789Sahrens 		return (ERESTART);
3236789Sahrens 	}
32376245Smaybee 	atomic_add_64(&arc_tempreserve, reserve);
3238789Sahrens 	return (0);
3239789Sahrens }
3240789Sahrens 
3241789Sahrens void
3242789Sahrens arc_init(void)
3243789Sahrens {
3244789Sahrens 	mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
3245789Sahrens 	cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
3246789Sahrens 
32472391Smaybee 	/* Convert seconds to clock ticks */
32482638Sperrin 	arc_min_prefetch_lifespan = 1 * hz;
32492391Smaybee 
3250789Sahrens 	/* Start out with 1/8 of all memory */
32513403Sbmc 	arc_c = physmem * PAGESIZE / 8;
3252789Sahrens 
3253789Sahrens #ifdef _KERNEL
3254789Sahrens 	/*
3255789Sahrens 	 * On architectures where the physical memory can be larger
3256789Sahrens 	 * than the addressable space (intel in 32-bit mode), we may
3257789Sahrens 	 * need to limit the cache to 1/8 of VM size.
3258789Sahrens 	 */
32593403Sbmc 	arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
3260789Sahrens #endif
3261789Sahrens 
3262982Smaybee 	/* set min cache to 1/32 of all memory, or 64MB, whichever is more */
32633403Sbmc 	arc_c_min = MAX(arc_c / 4, 64<<20);
3264982Smaybee 	/* set max to 3/4 of all memory, or all but 1GB, whichever is more */
32653403Sbmc 	if (arc_c * 8 >= 1<<30)
32663403Sbmc 		arc_c_max = (arc_c * 8) - (1<<30);
3267789Sahrens 	else
32683403Sbmc 		arc_c_max = arc_c_min;
32693403Sbmc 	arc_c_max = MAX(arc_c * 6, arc_c_max);
32702885Sahrens 
32712885Sahrens 	/*
32722885Sahrens 	 * Allow the tunables to override our calculations if they are
32732885Sahrens 	 * reasonable (ie. over 64MB)
32742885Sahrens 	 */
32752885Sahrens 	if (zfs_arc_max > 64<<20 && zfs_arc_max < physmem * PAGESIZE)
32763403Sbmc 		arc_c_max = zfs_arc_max;
32773403Sbmc 	if (zfs_arc_min > 64<<20 && zfs_arc_min <= arc_c_max)
32783403Sbmc 		arc_c_min = zfs_arc_min;
32792885Sahrens 
32803403Sbmc 	arc_c = arc_c_max;
32813403Sbmc 	arc_p = (arc_c >> 1);
3282789Sahrens 
32834309Smaybee 	/* limit meta-data to 1/4 of the arc capacity */
32844309Smaybee 	arc_meta_limit = arc_c_max / 4;
32854645Sek110237 
32864645Sek110237 	/* Allow the tunable to override if it is reasonable */
32874645Sek110237 	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
32884645Sek110237 		arc_meta_limit = zfs_arc_meta_limit;
32894645Sek110237 
32904309Smaybee 	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
32914309Smaybee 		arc_c_min = arc_meta_limit / 2;
32924309Smaybee 
3293789Sahrens 	/* if kmem_flags are set, lets try to use less memory */
3294789Sahrens 	if (kmem_debugging())
32953403Sbmc 		arc_c = arc_c / 2;
32963403Sbmc 	if (arc_c < arc_c_min)
32973403Sbmc 		arc_c = arc_c_min;
3298789Sahrens 
32993403Sbmc 	arc_anon = &ARC_anon;
33003403Sbmc 	arc_mru = &ARC_mru;
33013403Sbmc 	arc_mru_ghost = &ARC_mru_ghost;
33023403Sbmc 	arc_mfu = &ARC_mfu;
33033403Sbmc 	arc_mfu_ghost = &ARC_mfu_ghost;
33045450Sbrendan 	arc_l2c_only = &ARC_l2c_only;
33053403Sbmc 	arc_size = 0;
3306789Sahrens 
33073403Sbmc 	mutex_init(&arc_anon->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
33083403Sbmc 	mutex_init(&arc_mru->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
33093403Sbmc 	mutex_init(&arc_mru_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
33103403Sbmc 	mutex_init(&arc_mfu->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
33113403Sbmc 	mutex_init(&arc_mfu_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
33125450Sbrendan 	mutex_init(&arc_l2c_only->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
33132688Smaybee 
33144309Smaybee 	list_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
33154309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
33164309Smaybee 	list_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
33174309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
33184309Smaybee 	list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
33194309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
33204309Smaybee 	list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
33214309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
33224309Smaybee 	list_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
33234309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
33244309Smaybee 	list_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
33254309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
33264309Smaybee 	list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
33274309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
33284309Smaybee 	list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
33294309Smaybee 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
33305450Sbrendan 	list_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
33315450Sbrendan 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
33325450Sbrendan 	list_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
33335450Sbrendan 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3334789Sahrens 
3335789Sahrens 	buf_init();
3336789Sahrens 
3337789Sahrens 	arc_thread_exit = 0;
33381544Seschrock 	arc_eviction_list = NULL;
33391544Seschrock 	mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
33402887Smaybee 	bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
3341789Sahrens 
33423403Sbmc 	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
33433403Sbmc 	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
33443403Sbmc 
33453403Sbmc 	if (arc_ksp != NULL) {
33463403Sbmc 		arc_ksp->ks_data = &arc_stats;
33473403Sbmc 		kstat_install(arc_ksp);
33483403Sbmc 	}
33493403Sbmc 
3350789Sahrens 	(void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
3351789Sahrens 	    TS_RUN, minclsyspri);
33523158Smaybee 
33533158Smaybee 	arc_dead = FALSE;
3354*6987Sbrendan 	arc_warm = B_FALSE;
33556245Smaybee 
33566245Smaybee 	if (zfs_write_limit_max == 0)
33576245Smaybee 		zfs_write_limit_max = physmem * PAGESIZE >>
33586245Smaybee 		    zfs_write_limit_shift;
33596245Smaybee 	else
33606245Smaybee 		zfs_write_limit_shift = 0;
3361789Sahrens }
3362789Sahrens 
3363789Sahrens void
3364789Sahrens arc_fini(void)
3365789Sahrens {
3366789Sahrens 	mutex_enter(&arc_reclaim_thr_lock);
3367789Sahrens 	arc_thread_exit = 1;
3368789Sahrens 	while (arc_thread_exit != 0)
3369789Sahrens 		cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
3370789Sahrens 	mutex_exit(&arc_reclaim_thr_lock);
3371789Sahrens 
33725642Smaybee 	arc_flush(NULL);
3373789Sahrens 
3374789Sahrens 	arc_dead = TRUE;
3375789Sahrens 
33763403Sbmc 	if (arc_ksp != NULL) {
33773403Sbmc 		kstat_delete(arc_ksp);
33783403Sbmc 		arc_ksp = NULL;
33793403Sbmc 	}
33803403Sbmc 
33811544Seschrock 	mutex_destroy(&arc_eviction_mtx);
3382789Sahrens 	mutex_destroy(&arc_reclaim_thr_lock);
3383789Sahrens 	cv_destroy(&arc_reclaim_thr_cv);
3384789Sahrens 
33854309Smaybee 	list_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
33864309Smaybee 	list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
33874309Smaybee 	list_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
33884309Smaybee 	list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
33894309Smaybee 	list_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
33904309Smaybee 	list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
33914309Smaybee 	list_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
33924309Smaybee 	list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
3393789Sahrens 
33943403Sbmc 	mutex_destroy(&arc_anon->arcs_mtx);
33953403Sbmc 	mutex_destroy(&arc_mru->arcs_mtx);
33963403Sbmc 	mutex_destroy(&arc_mru_ghost->arcs_mtx);
33973403Sbmc 	mutex_destroy(&arc_mfu->arcs_mtx);
33983403Sbmc 	mutex_destroy(&arc_mfu_ghost->arcs_mtx);
33992856Snd150628 
3400789Sahrens 	buf_fini();
3401789Sahrens }
34025450Sbrendan 
34035450Sbrendan /*
34045450Sbrendan  * Level 2 ARC
34055450Sbrendan  *
34065450Sbrendan  * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
34075450Sbrendan  * It uses dedicated storage devices to hold cached data, which are populated
34085450Sbrendan  * using large infrequent writes.  The main role of this cache is to boost
34095450Sbrendan  * the performance of random read workloads.  The intended L2ARC devices
34105450Sbrendan  * include short-stroked disks, solid state disks, and other media with
34115450Sbrendan  * substantially faster read latency than disk.
34125450Sbrendan  *
34135450Sbrendan  *                 +-----------------------+
34145450Sbrendan  *                 |         ARC           |
34155450Sbrendan  *                 +-----------------------+
34165450Sbrendan  *                    |         ^     ^
34175450Sbrendan  *                    |         |     |
34185450Sbrendan  *      l2arc_feed_thread()    arc_read()
34195450Sbrendan  *                    |         |     |
34205450Sbrendan  *                    |  l2arc read   |
34215450Sbrendan  *                    V         |     |
34225450Sbrendan  *               +---------------+    |
34235450Sbrendan  *               |     L2ARC     |    |
34245450Sbrendan  *               +---------------+    |
34255450Sbrendan  *                   |    ^           |
34265450Sbrendan  *          l2arc_write() |           |
34275450Sbrendan  *                   |    |           |
34285450Sbrendan  *                   V    |           |
34295450Sbrendan  *                 +-------+      +-------+
34305450Sbrendan  *                 | vdev  |      | vdev  |
34315450Sbrendan  *                 | cache |      | cache |
34325450Sbrendan  *                 +-------+      +-------+
34335450Sbrendan  *                 +=========+     .-----.
34345450Sbrendan  *                 :  L2ARC  :    |-_____-|
34355450Sbrendan  *                 : devices :    | Disks |
34365450Sbrendan  *                 +=========+    `-_____-'
34375450Sbrendan  *
34385450Sbrendan  * Read requests are satisfied from the following sources, in order:
34395450Sbrendan  *
34405450Sbrendan  *	1) ARC
34415450Sbrendan  *	2) vdev cache of L2ARC devices
34425450Sbrendan  *	3) L2ARC devices
34435450Sbrendan  *	4) vdev cache of disks
34445450Sbrendan  *	5) disks
34455450Sbrendan  *
34465450Sbrendan  * Some L2ARC device types exhibit extremely slow write performance.
34475450Sbrendan  * To accommodate for this there are some significant differences between
34485450Sbrendan  * the L2ARC and traditional cache design:
34495450Sbrendan  *
34505450Sbrendan  * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
34515450Sbrendan  * the ARC behave as usual, freeing buffers and placing headers on ghost
34525450Sbrendan  * lists.  The ARC does not send buffers to the L2ARC during eviction as
34535450Sbrendan  * this would add inflated write latencies for all ARC memory pressure.
34545450Sbrendan  *
34555450Sbrendan  * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
34565450Sbrendan  * It does this by periodically scanning buffers from the eviction-end of
34575450Sbrendan  * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
34585450Sbrendan  * not already there.  It scans until a headroom of buffers is satisfied,
34595450Sbrendan  * which itself is a buffer for ARC eviction.  The thread that does this is
34605450Sbrendan  * l2arc_feed_thread(), illustrated below; example sizes are included to
34615450Sbrendan  * provide a better sense of ratio than this diagram:
34625450Sbrendan  *
34635450Sbrendan  *	       head -->                        tail
34645450Sbrendan  *	        +---------------------+----------+
34655450Sbrendan  *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
34665450Sbrendan  *	        +---------------------+----------+   |   o L2ARC eligible
34675450Sbrendan  *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
34685450Sbrendan  *	        +---------------------+----------+   |
34695450Sbrendan  *	             15.9 Gbytes      ^ 32 Mbytes    |
34705450Sbrendan  *	                           headroom          |
34715450Sbrendan  *	                                      l2arc_feed_thread()
34725450Sbrendan  *	                                             |
34735450Sbrendan  *	                 l2arc write hand <--[oooo]--'
34745450Sbrendan  *	                         |           8 Mbyte
34755450Sbrendan  *	                         |          write max
34765450Sbrendan  *	                         V
34775450Sbrendan  *		  +==============================+
34785450Sbrendan  *	L2ARC dev |####|#|###|###|    |####| ... |
34795450Sbrendan  *	          +==============================+
34805450Sbrendan  *	                     32 Gbytes
34815450Sbrendan  *
34825450Sbrendan  * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
34835450Sbrendan  * evicted, then the L2ARC has cached a buffer much sooner than it probably
34845450Sbrendan  * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
34855450Sbrendan  * safe to say that this is an uncommon case, since buffers at the end of
34865450Sbrendan  * the ARC lists have moved there due to inactivity.
34875450Sbrendan  *
34885450Sbrendan  * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
34895450Sbrendan  * then the L2ARC simply misses copying some buffers.  This serves as a
34905450Sbrendan  * pressure valve to prevent heavy read workloads from both stalling the ARC
34915450Sbrendan  * with waits and clogging the L2ARC with writes.  This also helps prevent
34925450Sbrendan  * the potential for the L2ARC to churn if it attempts to cache content too
34935450Sbrendan  * quickly, such as during backups of the entire pool.
34945450Sbrendan  *
3495*6987Sbrendan  * 5. After system boot and before the ARC has filled main memory, there are
3496*6987Sbrendan  * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
3497*6987Sbrendan  * lists can remain mostly static.  Instead of searching from tail of these
3498*6987Sbrendan  * lists as pictured, the l2arc_feed_thread() will search from the list heads
3499*6987Sbrendan  * for eligible buffers, greatly increasing its chance of finding them.
3500*6987Sbrendan  *
3501*6987Sbrendan  * The L2ARC device write speed is also boosted during this time so that
3502*6987Sbrendan  * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
3503*6987Sbrendan  * there are no L2ARC reads, and no fear of degrading read performance
3504*6987Sbrendan  * through increased writes.
3505*6987Sbrendan  *
3506*6987Sbrendan  * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
35075450Sbrendan  * the vdev queue can aggregate them into larger and fewer writes.  Each
35085450Sbrendan  * device is written to in a rotor fashion, sweeping writes through
35095450Sbrendan  * available space then repeating.
35105450Sbrendan  *
3511*6987Sbrendan  * 7. The L2ARC does not store dirty content.  It never needs to flush
35125450Sbrendan  * write buffers back to disk based storage.
35135450Sbrendan  *
3514*6987Sbrendan  * 8. If an ARC buffer is written (and dirtied) which also exists in the
35155450Sbrendan  * L2ARC, the now stale L2ARC buffer is immediately dropped.
35165450Sbrendan  *
35175450Sbrendan  * The performance of the L2ARC can be tweaked by a number of tunables, which
35185450Sbrendan  * may be necessary for different workloads:
35195450Sbrendan  *
35205450Sbrendan  *	l2arc_write_max		max write bytes per interval
3521*6987Sbrendan  *	l2arc_write_boost	extra write bytes during device warmup
35225450Sbrendan  *	l2arc_noprefetch	skip caching prefetched buffers
35235450Sbrendan  *	l2arc_headroom		number of max device writes to precache
35245450Sbrendan  *	l2arc_feed_secs		seconds between L2ARC writing
35255450Sbrendan  *
35265450Sbrendan  * Tunables may be removed or added as future performance improvements are
35275450Sbrendan  * integrated, and also may become zpool properties.
35285450Sbrendan  */
35295450Sbrendan 
35305450Sbrendan static void
35315450Sbrendan l2arc_hdr_stat_add(void)
35325450Sbrendan {
35336018Sbrendan 	ARCSTAT_INCR(arcstat_l2_hdr_size, HDR_SIZE + L2HDR_SIZE);
35346018Sbrendan 	ARCSTAT_INCR(arcstat_hdr_size, -HDR_SIZE);
35355450Sbrendan }
35365450Sbrendan 
35375450Sbrendan static void
35385450Sbrendan l2arc_hdr_stat_remove(void)
35395450Sbrendan {
35406018Sbrendan 	ARCSTAT_INCR(arcstat_l2_hdr_size, -(HDR_SIZE + L2HDR_SIZE));
35416018Sbrendan 	ARCSTAT_INCR(arcstat_hdr_size, HDR_SIZE);
35425450Sbrendan }
35435450Sbrendan 
35445450Sbrendan /*
35455450Sbrendan  * Cycle through L2ARC devices.  This is how L2ARC load balances.
3546*6987Sbrendan  * If a device is returned, this also returns holding the spa config lock.
35475450Sbrendan  */
35485450Sbrendan static l2arc_dev_t *
35495450Sbrendan l2arc_dev_get_next(void)
35505450Sbrendan {
3551*6987Sbrendan 	l2arc_dev_t *first, *next = NULL;
3552*6987Sbrendan 
3553*6987Sbrendan 	/*
3554*6987Sbrendan 	 * Lock out the removal of spas (spa_namespace_lock), then removal
3555*6987Sbrendan 	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
3556*6987Sbrendan 	 * both locks will be dropped and a spa config lock held instead.
3557*6987Sbrendan 	 */
3558*6987Sbrendan 	mutex_enter(&spa_namespace_lock);
3559*6987Sbrendan 	mutex_enter(&l2arc_dev_mtx);
35606643Seschrock 
35616643Seschrock 	/* if there are no vdevs, there is nothing to do */
35626643Seschrock 	if (l2arc_ndev == 0)
3563*6987Sbrendan 		goto out;
35646643Seschrock 
35656643Seschrock 	first = NULL;
35666643Seschrock 	next = l2arc_dev_last;
35676643Seschrock 	do {
35686643Seschrock 		/* loop around the list looking for a non-faulted vdev */
35696643Seschrock 		if (next == NULL) {
35705450Sbrendan 			next = list_head(l2arc_dev_list);
35716643Seschrock 		} else {
35726643Seschrock 			next = list_next(l2arc_dev_list, next);
35736643Seschrock 			if (next == NULL)
35746643Seschrock 				next = list_head(l2arc_dev_list);
35756643Seschrock 		}
35766643Seschrock 
35776643Seschrock 		/* if we have come back to the start, bail out */
35786643Seschrock 		if (first == NULL)
35796643Seschrock 			first = next;
35806643Seschrock 		else if (next == first)
35816643Seschrock 			break;
35826643Seschrock 
35836643Seschrock 	} while (vdev_is_dead(next->l2ad_vdev));
35846643Seschrock 
35856643Seschrock 	/* if we were unable to find any usable vdevs, return NULL */
35866643Seschrock 	if (vdev_is_dead(next->l2ad_vdev))
3587*6987Sbrendan 		next = NULL;
35885450Sbrendan 
35895450Sbrendan 	l2arc_dev_last = next;
35905450Sbrendan 
3591*6987Sbrendan out:
3592*6987Sbrendan 	mutex_exit(&l2arc_dev_mtx);
3593*6987Sbrendan 
3594*6987Sbrendan 	/*
3595*6987Sbrendan 	 * Grab the config lock to prevent the 'next' device from being
3596*6987Sbrendan 	 * removed while we are writing to it.
3597*6987Sbrendan 	 */
3598*6987Sbrendan 	if (next != NULL)
3599*6987Sbrendan 		spa_config_enter(next->l2ad_spa, RW_READER, next);
3600*6987Sbrendan 	mutex_exit(&spa_namespace_lock);
3601*6987Sbrendan 
36025450Sbrendan 	return (next);
36035450Sbrendan }
36045450Sbrendan 
36055450Sbrendan /*
3606*6987Sbrendan  * Free buffers that were tagged for destruction.
3607*6987Sbrendan  */
3608*6987Sbrendan static void
3609*6987Sbrendan l2arc_do_free_on_write()
3610*6987Sbrendan {
3611*6987Sbrendan 	list_t *buflist;
3612*6987Sbrendan 	l2arc_data_free_t *df, *df_prev;
3613*6987Sbrendan 
3614*6987Sbrendan 	mutex_enter(&l2arc_free_on_write_mtx);
3615*6987Sbrendan 	buflist = l2arc_free_on_write;
3616*6987Sbrendan 
3617*6987Sbrendan 	for (df = list_tail(buflist); df; df = df_prev) {
3618*6987Sbrendan 		df_prev = list_prev(buflist, df);
3619*6987Sbrendan 		ASSERT(df->l2df_data != NULL);
3620*6987Sbrendan 		ASSERT(df->l2df_func != NULL);
3621*6987Sbrendan 		df->l2df_func(df->l2df_data, df->l2df_size);
3622*6987Sbrendan 		list_remove(buflist, df);
3623*6987Sbrendan 		kmem_free(df, sizeof (l2arc_data_free_t));
3624*6987Sbrendan 	}
3625*6987Sbrendan 
3626*6987Sbrendan 	mutex_exit(&l2arc_free_on_write_mtx);
3627*6987Sbrendan }
3628*6987Sbrendan 
3629*6987Sbrendan /*
36305450Sbrendan  * A write to a cache device has completed.  Update all headers to allow
36315450Sbrendan  * reads from these buffers to begin.
36325450Sbrendan  */
36335450Sbrendan static void
36345450Sbrendan l2arc_write_done(zio_t *zio)
36355450Sbrendan {
36365450Sbrendan 	l2arc_write_callback_t *cb;
36375450Sbrendan 	l2arc_dev_t *dev;
36385450Sbrendan 	list_t *buflist;
36395450Sbrendan 	arc_buf_hdr_t *head, *ab, *ab_prev;
3640*6987Sbrendan 	l2arc_buf_hdr_t *abl2;
36415450Sbrendan 	kmutex_t *hash_lock;
36425450Sbrendan 
36435450Sbrendan 	cb = zio->io_private;
36445450Sbrendan 	ASSERT(cb != NULL);
36455450Sbrendan 	dev = cb->l2wcb_dev;
36465450Sbrendan 	ASSERT(dev != NULL);
36475450Sbrendan 	head = cb->l2wcb_head;
36485450Sbrendan 	ASSERT(head != NULL);
36495450Sbrendan 	buflist = dev->l2ad_buflist;
36505450Sbrendan 	ASSERT(buflist != NULL);
36515450Sbrendan 	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
36525450Sbrendan 	    l2arc_write_callback_t *, cb);
36535450Sbrendan 
36545450Sbrendan 	if (zio->io_error != 0)
36555450Sbrendan 		ARCSTAT_BUMP(arcstat_l2_writes_error);
36565450Sbrendan 
36575450Sbrendan 	mutex_enter(&l2arc_buflist_mtx);
36585450Sbrendan 
36595450Sbrendan 	/*
36605450Sbrendan 	 * All writes completed, or an error was hit.
36615450Sbrendan 	 */
36625450Sbrendan 	for (ab = list_prev(buflist, head); ab; ab = ab_prev) {
36635450Sbrendan 		ab_prev = list_prev(buflist, ab);
36645450Sbrendan 
36655450Sbrendan 		hash_lock = HDR_LOCK(ab);
36665450Sbrendan 		if (!mutex_tryenter(hash_lock)) {
36675450Sbrendan 			/*
36685450Sbrendan 			 * This buffer misses out.  It may be in a stage
36695450Sbrendan 			 * of eviction.  Its ARC_L2_WRITING flag will be
36705450Sbrendan 			 * left set, denying reads to this buffer.
36715450Sbrendan 			 */
36725450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_writes_hdr_miss);
36735450Sbrendan 			continue;
36745450Sbrendan 		}
36755450Sbrendan 
36765450Sbrendan 		if (zio->io_error != 0) {
36775450Sbrendan 			/*
3678*6987Sbrendan 			 * Error - drop L2ARC entry.
36795450Sbrendan 			 */
3680*6987Sbrendan 			list_remove(buflist, ab);
3681*6987Sbrendan 			abl2 = ab->b_l2hdr;
36825450Sbrendan 			ab->b_l2hdr = NULL;
3683*6987Sbrendan 			kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
3684*6987Sbrendan 			ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
36855450Sbrendan 		}
36865450Sbrendan 
36875450Sbrendan 		/*
36885450Sbrendan 		 * Allow ARC to begin reads to this L2ARC entry.
36895450Sbrendan 		 */
36905450Sbrendan 		ab->b_flags &= ~ARC_L2_WRITING;
36915450Sbrendan 
36925450Sbrendan 		mutex_exit(hash_lock);
36935450Sbrendan 	}
36945450Sbrendan 
36955450Sbrendan 	atomic_inc_64(&l2arc_writes_done);
36965450Sbrendan 	list_remove(buflist, head);
36975450Sbrendan 	kmem_cache_free(hdr_cache, head);
36985450Sbrendan 	mutex_exit(&l2arc_buflist_mtx);
36995450Sbrendan 
3700*6987Sbrendan 	l2arc_do_free_on_write();
37015450Sbrendan 
37025450Sbrendan 	kmem_free(cb, sizeof (l2arc_write_callback_t));
37035450Sbrendan }
37045450Sbrendan 
37055450Sbrendan /*
37065450Sbrendan  * A read to a cache device completed.  Validate buffer contents before
37075450Sbrendan  * handing over to the regular ARC routines.
37085450Sbrendan  */
37095450Sbrendan static void
37105450Sbrendan l2arc_read_done(zio_t *zio)
37115450Sbrendan {
37125450Sbrendan 	l2arc_read_callback_t *cb;
37135450Sbrendan 	arc_buf_hdr_t *hdr;
37145450Sbrendan 	arc_buf_t *buf;
37155450Sbrendan 	zio_t *rzio;
37165450Sbrendan 	kmutex_t *hash_lock;
3717*6987Sbrendan 	int equal;
37185450Sbrendan 
37195450Sbrendan 	cb = zio->io_private;
37205450Sbrendan 	ASSERT(cb != NULL);
37215450Sbrendan 	buf = cb->l2rcb_buf;
37225450Sbrendan 	ASSERT(buf != NULL);
37235450Sbrendan 	hdr = buf->b_hdr;
37245450Sbrendan 	ASSERT(hdr != NULL);
37255450Sbrendan 
37265450Sbrendan 	hash_lock = HDR_LOCK(hdr);
37275450Sbrendan 	mutex_enter(hash_lock);
37285450Sbrendan 
37295450Sbrendan 	/*
37305450Sbrendan 	 * Check this survived the L2ARC journey.
37315450Sbrendan 	 */
37325450Sbrendan 	equal = arc_cksum_equal(buf);
37335450Sbrendan 	if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
37345450Sbrendan 		mutex_exit(hash_lock);
37355450Sbrendan 		zio->io_private = buf;
37365450Sbrendan 		arc_read_done(zio);
37375450Sbrendan 	} else {
37385450Sbrendan 		mutex_exit(hash_lock);
37395450Sbrendan 		/*
37405450Sbrendan 		 * Buffer didn't survive caching.  Increment stats and
37415450Sbrendan 		 * reissue to the original storage device.
37425450Sbrendan 		 */
3743*6987Sbrendan 		if (zio->io_error != 0) {
37445450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_io_error);
3745*6987Sbrendan 		} else {
3746*6987Sbrendan 			zio->io_error = EIO;
3747*6987Sbrendan 		}
37485450Sbrendan 		if (!equal)
37495450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
37505450Sbrendan 
3751*6987Sbrendan 		if (zio->io_waiter == NULL) {
3752*6987Sbrendan 			/*
3753*6987Sbrendan 			 * Let the resent I/O call arc_read_done() instead.
3754*6987Sbrendan 			 */
3755*6987Sbrendan 			zio->io_done = NULL;
3756*6987Sbrendan 			zio->io_flags &= ~ZIO_FLAG_DONT_CACHE;
3757*6987Sbrendan 
3758*6987Sbrendan 			rzio = zio_read(NULL, cb->l2rcb_spa, &cb->l2rcb_bp,
3759*6987Sbrendan 			    buf->b_data, zio->io_size, arc_read_done, buf,
3760*6987Sbrendan 			    zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb);
3761*6987Sbrendan 
3762*6987Sbrendan 			(void) zio_nowait(rzio);
3763*6987Sbrendan 		}
37645450Sbrendan 	}
37655450Sbrendan 
37665450Sbrendan 	kmem_free(cb, sizeof (l2arc_read_callback_t));
37675450Sbrendan }
37685450Sbrendan 
37695450Sbrendan /*
37705450Sbrendan  * This is the list priority from which the L2ARC will search for pages to
37715450Sbrendan  * cache.  This is used within loops (0..3) to cycle through lists in the
37725450Sbrendan  * desired order.  This order can have a significant effect on cache
37735450Sbrendan  * performance.
37745450Sbrendan  *
37755450Sbrendan  * Currently the metadata lists are hit first, MFU then MRU, followed by
37765450Sbrendan  * the data lists.  This function returns a locked list, and also returns
37775450Sbrendan  * the lock pointer.
37785450Sbrendan  */
37795450Sbrendan static list_t *
37805450Sbrendan l2arc_list_locked(int list_num, kmutex_t **lock)
37815450Sbrendan {
37825450Sbrendan 	list_t *list;
37835450Sbrendan 
37845450Sbrendan 	ASSERT(list_num >= 0 && list_num <= 3);
37855450Sbrendan 
37865450Sbrendan 	switch (list_num) {
37875450Sbrendan 	case 0:
37885450Sbrendan 		list = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
37895450Sbrendan 		*lock = &arc_mfu->arcs_mtx;
37905450Sbrendan 		break;
37915450Sbrendan 	case 1:
37925450Sbrendan 		list = &arc_mru->arcs_list[ARC_BUFC_METADATA];
37935450Sbrendan 		*lock = &arc_mru->arcs_mtx;
37945450Sbrendan 		break;
37955450Sbrendan 	case 2:
37965450Sbrendan 		list = &arc_mfu->arcs_list[ARC_BUFC_DATA];
37975450Sbrendan 		*lock = &arc_mfu->arcs_mtx;
37985450Sbrendan 		break;
37995450Sbrendan 	case 3:
38005450Sbrendan 		list = &arc_mru->arcs_list[ARC_BUFC_DATA];
38015450Sbrendan 		*lock = &arc_mru->arcs_mtx;
38025450Sbrendan 		break;
38035450Sbrendan 	}
38045450Sbrendan 
38055450Sbrendan 	ASSERT(!(MUTEX_HELD(*lock)));
38065450Sbrendan 	mutex_enter(*lock);
38075450Sbrendan 	return (list);
38085450Sbrendan }
38095450Sbrendan 
38105450Sbrendan /*
38115450Sbrendan  * Evict buffers from the device write hand to the distance specified in
38125450Sbrendan  * bytes.  This distance may span populated buffers, it may span nothing.
38135450Sbrendan  * This is clearing a region on the L2ARC device ready for writing.
38145450Sbrendan  * If the 'all' boolean is set, every buffer is evicted.
38155450Sbrendan  */
38165450Sbrendan static void
38175450Sbrendan l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
38185450Sbrendan {
38195450Sbrendan 	list_t *buflist;
38205450Sbrendan 	l2arc_buf_hdr_t *abl2;
38215450Sbrendan 	arc_buf_hdr_t *ab, *ab_prev;
38225450Sbrendan 	kmutex_t *hash_lock;
38235450Sbrendan 	uint64_t taddr;
38245450Sbrendan 
38255450Sbrendan 	buflist = dev->l2ad_buflist;
38265450Sbrendan 
38275450Sbrendan 	if (buflist == NULL)
38285450Sbrendan 		return;
38295450Sbrendan 
38305450Sbrendan 	if (!all && dev->l2ad_first) {
38315450Sbrendan 		/*
38325450Sbrendan 		 * This is the first sweep through the device.  There is
38335450Sbrendan 		 * nothing to evict.
38345450Sbrendan 		 */
38355450Sbrendan 		return;
38365450Sbrendan 	}
38375450Sbrendan 
3838*6987Sbrendan 	if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
38395450Sbrendan 		/*
38405450Sbrendan 		 * When nearing the end of the device, evict to the end
38415450Sbrendan 		 * before the device write hand jumps to the start.
38425450Sbrendan 		 */
38435450Sbrendan 		taddr = dev->l2ad_end;
38445450Sbrendan 	} else {
38455450Sbrendan 		taddr = dev->l2ad_hand + distance;
38465450Sbrendan 	}
38475450Sbrendan 	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
38485450Sbrendan 	    uint64_t, taddr, boolean_t, all);
38495450Sbrendan 
38505450Sbrendan top:
38515450Sbrendan 	mutex_enter(&l2arc_buflist_mtx);
38525450Sbrendan 	for (ab = list_tail(buflist); ab; ab = ab_prev) {
38535450Sbrendan 		ab_prev = list_prev(buflist, ab);
38545450Sbrendan 
38555450Sbrendan 		hash_lock = HDR_LOCK(ab);
38565450Sbrendan 		if (!mutex_tryenter(hash_lock)) {
38575450Sbrendan 			/*
38585450Sbrendan 			 * Missed the hash lock.  Retry.
38595450Sbrendan 			 */
38605450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
38615450Sbrendan 			mutex_exit(&l2arc_buflist_mtx);
38625450Sbrendan 			mutex_enter(hash_lock);
38635450Sbrendan 			mutex_exit(hash_lock);
38645450Sbrendan 			goto top;
38655450Sbrendan 		}
38665450Sbrendan 
38675450Sbrendan 		if (HDR_L2_WRITE_HEAD(ab)) {
38685450Sbrendan 			/*
38695450Sbrendan 			 * We hit a write head node.  Leave it for
38705450Sbrendan 			 * l2arc_write_done().
38715450Sbrendan 			 */
38725450Sbrendan 			list_remove(buflist, ab);
38735450Sbrendan 			mutex_exit(hash_lock);
38745450Sbrendan 			continue;
38755450Sbrendan 		}
38765450Sbrendan 
38775450Sbrendan 		if (!all && ab->b_l2hdr != NULL &&
38785450Sbrendan 		    (ab->b_l2hdr->b_daddr > taddr ||
38795450Sbrendan 		    ab->b_l2hdr->b_daddr < dev->l2ad_hand)) {
38805450Sbrendan 			/*
38815450Sbrendan 			 * We've evicted to the target address,
38825450Sbrendan 			 * or the end of the device.
38835450Sbrendan 			 */
38845450Sbrendan 			mutex_exit(hash_lock);
38855450Sbrendan 			break;
38865450Sbrendan 		}
38875450Sbrendan 
38885450Sbrendan 		if (HDR_FREE_IN_PROGRESS(ab)) {
38895450Sbrendan 			/*
38905450Sbrendan 			 * Already on the path to destruction.
38915450Sbrendan 			 */
38925450Sbrendan 			mutex_exit(hash_lock);
38935450Sbrendan 			continue;
38945450Sbrendan 		}
38955450Sbrendan 
38965450Sbrendan 		if (ab->b_state == arc_l2c_only) {
38975450Sbrendan 			ASSERT(!HDR_L2_READING(ab));
38985450Sbrendan 			/*
38995450Sbrendan 			 * This doesn't exist in the ARC.  Destroy.
39005450Sbrendan 			 * arc_hdr_destroy() will call list_remove()
39015450Sbrendan 			 * and decrement arcstat_l2_size.
39025450Sbrendan 			 */
39035450Sbrendan 			arc_change_state(arc_anon, ab, hash_lock);
39045450Sbrendan 			arc_hdr_destroy(ab);
39055450Sbrendan 		} else {
39065450Sbrendan 			/*
3907*6987Sbrendan 			 * Invalidate issued or about to be issued
3908*6987Sbrendan 			 * reads, since we may be about to write
3909*6987Sbrendan 			 * over this location.
3910*6987Sbrendan 			 */
3911*6987Sbrendan 			if (HDR_L2_READING(ab)) {
3912*6987Sbrendan 				ARCSTAT_BUMP(arcstat_l2_evict_reading);
3913*6987Sbrendan 				ab->b_flags |= ARC_L2_EVICTED;
3914*6987Sbrendan 			}
3915*6987Sbrendan 
3916*6987Sbrendan 			/*
39175450Sbrendan 			 * Tell ARC this no longer exists in L2ARC.
39185450Sbrendan 			 */
39195450Sbrendan 			if (ab->b_l2hdr != NULL) {
39205450Sbrendan 				abl2 = ab->b_l2hdr;
39215450Sbrendan 				ab->b_l2hdr = NULL;
39225450Sbrendan 				kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
39235450Sbrendan 				ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
39245450Sbrendan 			}
39255450Sbrendan 			list_remove(buflist, ab);
39265450Sbrendan 
39275450Sbrendan 			/*
39285450Sbrendan 			 * This may have been leftover after a
39295450Sbrendan 			 * failed write.
39305450Sbrendan 			 */
39315450Sbrendan 			ab->b_flags &= ~ARC_L2_WRITING;
39325450Sbrendan 		}
39335450Sbrendan 		mutex_exit(hash_lock);
39345450Sbrendan 	}
39355450Sbrendan 	mutex_exit(&l2arc_buflist_mtx);
39365450Sbrendan 
39375450Sbrendan 	spa_l2cache_space_update(dev->l2ad_vdev, 0, -(taddr - dev->l2ad_evict));
39385450Sbrendan 	dev->l2ad_evict = taddr;
39395450Sbrendan }
39405450Sbrendan 
39415450Sbrendan /*
39425450Sbrendan  * Find and write ARC buffers to the L2ARC device.
39435450Sbrendan  *
39445450Sbrendan  * An ARC_L2_WRITING flag is set so that the L2ARC buffers are not valid
39455450Sbrendan  * for reading until they have completed writing.
39465450Sbrendan  */
39475450Sbrendan static void
3948*6987Sbrendan l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
39495450Sbrendan {
39505450Sbrendan 	arc_buf_hdr_t *ab, *ab_prev, *head;
39515450Sbrendan 	l2arc_buf_hdr_t *hdrl2;
39525450Sbrendan 	list_t *list;
3953*6987Sbrendan 	uint64_t passed_sz, write_sz, buf_sz, headroom;
39545450Sbrendan 	void *buf_data;
39555450Sbrendan 	kmutex_t *hash_lock, *list_lock;
39565450Sbrendan 	boolean_t have_lock, full;
39575450Sbrendan 	l2arc_write_callback_t *cb;
39585450Sbrendan 	zio_t *pio, *wzio;
39595450Sbrendan 
39605450Sbrendan 	ASSERT(dev->l2ad_vdev != NULL);
39615450Sbrendan 
39625450Sbrendan 	pio = NULL;
39635450Sbrendan 	write_sz = 0;
39645450Sbrendan 	full = B_FALSE;
39656245Smaybee 	head = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
39665450Sbrendan 	head->b_flags |= ARC_L2_WRITE_HEAD;
39675450Sbrendan 
39685450Sbrendan 	/*
39695450Sbrendan 	 * Copy buffers for L2ARC writing.
39705450Sbrendan 	 */
39715450Sbrendan 	mutex_enter(&l2arc_buflist_mtx);
39725450Sbrendan 	for (int try = 0; try <= 3; try++) {
39735450Sbrendan 		list = l2arc_list_locked(try, &list_lock);
39745450Sbrendan 		passed_sz = 0;
39755450Sbrendan 
3976*6987Sbrendan 		/*
3977*6987Sbrendan 		 * L2ARC fast warmup.
3978*6987Sbrendan 		 *
3979*6987Sbrendan 		 * Until the ARC is warm and starts to evict, read from the
3980*6987Sbrendan 		 * head of the ARC lists rather than the tail.
3981*6987Sbrendan 		 */
3982*6987Sbrendan 		headroom = target_sz * l2arc_headroom;
3983*6987Sbrendan 		if (arc_warm == B_FALSE)
3984*6987Sbrendan 			ab = list_head(list);
3985*6987Sbrendan 		else
3986*6987Sbrendan 			ab = list_tail(list);
3987*6987Sbrendan 
3988*6987Sbrendan 		for (; ab; ab = ab_prev) {
3989*6987Sbrendan 			if (arc_warm == B_FALSE)
3990*6987Sbrendan 				ab_prev = list_next(list, ab);
3991*6987Sbrendan 			else
3992*6987Sbrendan 				ab_prev = list_prev(list, ab);
39935450Sbrendan 
39945450Sbrendan 			hash_lock = HDR_LOCK(ab);
39955450Sbrendan 			have_lock = MUTEX_HELD(hash_lock);
39965450Sbrendan 			if (!have_lock && !mutex_tryenter(hash_lock)) {
39975450Sbrendan 				/*
39985450Sbrendan 				 * Skip this buffer rather than waiting.
39995450Sbrendan 				 */
40005450Sbrendan 				continue;
40015450Sbrendan 			}
40025450Sbrendan 
40035450Sbrendan 			passed_sz += ab->b_size;
40045450Sbrendan 			if (passed_sz > headroom) {
40055450Sbrendan 				/*
40065450Sbrendan 				 * Searched too far.
40075450Sbrendan 				 */
40085450Sbrendan 				mutex_exit(hash_lock);
40095450Sbrendan 				break;
40105450Sbrendan 			}
40115450Sbrendan 
40125450Sbrendan 			if (ab->b_spa != spa) {
40135450Sbrendan 				mutex_exit(hash_lock);
40145450Sbrendan 				continue;
40155450Sbrendan 			}
40165450Sbrendan 
40175450Sbrendan 			if (ab->b_l2hdr != NULL) {
40185450Sbrendan 				/*
40195450Sbrendan 				 * Already in L2ARC.
40205450Sbrendan 				 */
40215450Sbrendan 				mutex_exit(hash_lock);
40225450Sbrendan 				continue;
40235450Sbrendan 			}
40245450Sbrendan 
40255450Sbrendan 			if (HDR_IO_IN_PROGRESS(ab) || HDR_DONT_L2CACHE(ab)) {
40265450Sbrendan 				mutex_exit(hash_lock);
40275450Sbrendan 				continue;
40285450Sbrendan 			}
40295450Sbrendan 
40305450Sbrendan 			if ((write_sz + ab->b_size) > target_sz) {
40315450Sbrendan 				full = B_TRUE;
40325450Sbrendan 				mutex_exit(hash_lock);
40335450Sbrendan 				break;
40345450Sbrendan 			}
40355450Sbrendan 
40365450Sbrendan 			if (ab->b_buf == NULL) {
40375450Sbrendan 				DTRACE_PROBE1(l2arc__buf__null, void *, ab);
40385450Sbrendan 				mutex_exit(hash_lock);
40395450Sbrendan 				continue;
40405450Sbrendan 			}
40415450Sbrendan 
40425450Sbrendan 			if (pio == NULL) {
40435450Sbrendan 				/*
40445450Sbrendan 				 * Insert a dummy header on the buflist so
40455450Sbrendan 				 * l2arc_write_done() can find where the
40465450Sbrendan 				 * write buffers begin without searching.
40475450Sbrendan 				 */
40485450Sbrendan 				list_insert_head(dev->l2ad_buflist, head);
40495450Sbrendan 
40505450Sbrendan 				cb = kmem_alloc(
40515450Sbrendan 				    sizeof (l2arc_write_callback_t), KM_SLEEP);
40525450Sbrendan 				cb->l2wcb_dev = dev;
40535450Sbrendan 				cb->l2wcb_head = head;
40545450Sbrendan 				pio = zio_root(spa, l2arc_write_done, cb,
40555450Sbrendan 				    ZIO_FLAG_CANFAIL);
40565450Sbrendan 			}
40575450Sbrendan 
40585450Sbrendan 			/*
40595450Sbrendan 			 * Create and add a new L2ARC header.
40605450Sbrendan 			 */
40615450Sbrendan 			hdrl2 = kmem_zalloc(sizeof (l2arc_buf_hdr_t), KM_SLEEP);
40625450Sbrendan 			hdrl2->b_dev = dev;
40635450Sbrendan 			hdrl2->b_daddr = dev->l2ad_hand;
40645450Sbrendan 
40655450Sbrendan 			ab->b_flags |= ARC_L2_WRITING;
40665450Sbrendan 			ab->b_l2hdr = hdrl2;
40675450Sbrendan 			list_insert_head(dev->l2ad_buflist, ab);
40685450Sbrendan 			buf_data = ab->b_buf->b_data;
40695450Sbrendan 			buf_sz = ab->b_size;
40705450Sbrendan 
40715450Sbrendan 			/*
40725450Sbrendan 			 * Compute and store the buffer cksum before
40735450Sbrendan 			 * writing.  On debug the cksum is verified first.
40745450Sbrendan 			 */
40755450Sbrendan 			arc_cksum_verify(ab->b_buf);
40765450Sbrendan 			arc_cksum_compute(ab->b_buf, B_TRUE);
40775450Sbrendan 
40785450Sbrendan 			mutex_exit(hash_lock);
40795450Sbrendan 
40805450Sbrendan 			wzio = zio_write_phys(pio, dev->l2ad_vdev,
40815450Sbrendan 			    dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
40825450Sbrendan 			    NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
40835450Sbrendan 			    ZIO_FLAG_CANFAIL, B_FALSE);
40845450Sbrendan 
40855450Sbrendan 			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
40865450Sbrendan 			    zio_t *, wzio);
40875450Sbrendan 			(void) zio_nowait(wzio);
40885450Sbrendan 
40895450Sbrendan 			write_sz += buf_sz;
40905450Sbrendan 			dev->l2ad_hand += buf_sz;
40915450Sbrendan 		}
40925450Sbrendan 
40935450Sbrendan 		mutex_exit(list_lock);
40945450Sbrendan 
40955450Sbrendan 		if (full == B_TRUE)
40965450Sbrendan 			break;
40975450Sbrendan 	}
40985450Sbrendan 	mutex_exit(&l2arc_buflist_mtx);
40995450Sbrendan 
41005450Sbrendan 	if (pio == NULL) {
41015450Sbrendan 		ASSERT3U(write_sz, ==, 0);
41025450Sbrendan 		kmem_cache_free(hdr_cache, head);
41035450Sbrendan 		return;
41045450Sbrendan 	}
41055450Sbrendan 
41065450Sbrendan 	ASSERT3U(write_sz, <=, target_sz);
41075450Sbrendan 	ARCSTAT_BUMP(arcstat_l2_writes_sent);
41085450Sbrendan 	ARCSTAT_INCR(arcstat_l2_size, write_sz);
41095450Sbrendan 	spa_l2cache_space_update(dev->l2ad_vdev, 0, write_sz);
41105450Sbrendan 
41115450Sbrendan 	/*
41125450Sbrendan 	 * Bump device hand to the device start if it is approaching the end.
41135450Sbrendan 	 * l2arc_evict() will already have evicted ahead for this case.
41145450Sbrendan 	 */
4115*6987Sbrendan 	if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
41165450Sbrendan 		spa_l2cache_space_update(dev->l2ad_vdev, 0,
41175450Sbrendan 		    dev->l2ad_end - dev->l2ad_hand);
41185450Sbrendan 		dev->l2ad_hand = dev->l2ad_start;
41195450Sbrendan 		dev->l2ad_evict = dev->l2ad_start;
41205450Sbrendan 		dev->l2ad_first = B_FALSE;
41215450Sbrendan 	}
41225450Sbrendan 
41235450Sbrendan 	(void) zio_wait(pio);
41245450Sbrendan }
41255450Sbrendan 
41265450Sbrendan /*
41275450Sbrendan  * This thread feeds the L2ARC at regular intervals.  This is the beating
41285450Sbrendan  * heart of the L2ARC.
41295450Sbrendan  */
41305450Sbrendan static void
41315450Sbrendan l2arc_feed_thread(void)
41325450Sbrendan {
41335450Sbrendan 	callb_cpr_t cpr;
41345450Sbrendan 	l2arc_dev_t *dev;
41355450Sbrendan 	spa_t *spa;
4136*6987Sbrendan 	uint64_t size;
41375450Sbrendan 
41385450Sbrendan 	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
41395450Sbrendan 
41405450Sbrendan 	mutex_enter(&l2arc_feed_thr_lock);
41415450Sbrendan 
41425450Sbrendan 	while (l2arc_thread_exit == 0) {
41435450Sbrendan 		/*
4144*6987Sbrendan 		 * Pause for l2arc_feed_secs seconds between writes.
41455450Sbrendan 		 */
41465450Sbrendan 		CALLB_CPR_SAFE_BEGIN(&cpr);
4147*6987Sbrendan 		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
4148*6987Sbrendan 		    lbolt + (hz * l2arc_feed_secs));
4149*6987Sbrendan 		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
4150*6987Sbrendan 
4151*6987Sbrendan 		/*
4152*6987Sbrendan 		 * Quick check for L2ARC devices.
4153*6987Sbrendan 		 */
4154*6987Sbrendan 		mutex_enter(&l2arc_dev_mtx);
4155*6987Sbrendan 		if (l2arc_ndev == 0) {
4156*6987Sbrendan 			mutex_exit(&l2arc_dev_mtx);
4157*6987Sbrendan 			continue;
41585450Sbrendan 		}
4159*6987Sbrendan 		mutex_exit(&l2arc_dev_mtx);
41606643Seschrock 
41615450Sbrendan 		/*
41626643Seschrock 		 * This selects the next l2arc device to write to, and in
41636643Seschrock 		 * doing so the next spa to feed from: dev->l2ad_spa.   This
4164*6987Sbrendan 		 * will return NULL if there are now no l2arc devices or if
4165*6987Sbrendan 		 * they are all faulted.
4166*6987Sbrendan 		 *
4167*6987Sbrendan 		 * If a device is returned, its spa's config lock is also
4168*6987Sbrendan 		 * held to prevent device removal.  l2arc_dev_get_next()
4169*6987Sbrendan 		 * will grab and release l2arc_dev_mtx.
41705450Sbrendan 		 */
4171*6987Sbrendan 		if ((dev = l2arc_dev_get_next()) == NULL)
41725450Sbrendan 			continue;
4173*6987Sbrendan 
4174*6987Sbrendan 		spa = dev->l2ad_spa;
4175*6987Sbrendan 		ASSERT(spa != NULL);
41765450Sbrendan 
41775450Sbrendan 		/*
41785450Sbrendan 		 * Avoid contributing to memory pressure.
41795450Sbrendan 		 */
41805450Sbrendan 		if (arc_reclaim_needed()) {
41815450Sbrendan 			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
4182*6987Sbrendan 			spa_config_exit(spa, dev);
41835450Sbrendan 			continue;
41845450Sbrendan 		}
41855450Sbrendan 
41865450Sbrendan 		ARCSTAT_BUMP(arcstat_l2_feeds);
41875450Sbrendan 
4188*6987Sbrendan 		size = dev->l2ad_write;
4189*6987Sbrendan 		if (arc_warm == B_FALSE)
4190*6987Sbrendan 			size += dev->l2ad_boost;
4191*6987Sbrendan 
41925450Sbrendan 		/*
41935450Sbrendan 		 * Evict L2ARC buffers that will be overwritten.
41945450Sbrendan 		 */
4195*6987Sbrendan 		l2arc_evict(dev, size, B_FALSE);
41965450Sbrendan 
41975450Sbrendan 		/*
41985450Sbrendan 		 * Write ARC buffers.
41995450Sbrendan 		 */
4200*6987Sbrendan 		l2arc_write_buffers(spa, dev, size);
4201*6987Sbrendan 		spa_config_exit(spa, dev);
42025450Sbrendan 	}
42035450Sbrendan 
42045450Sbrendan 	l2arc_thread_exit = 0;
42055450Sbrendan 	cv_broadcast(&l2arc_feed_thr_cv);
42065450Sbrendan 	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
42075450Sbrendan 	thread_exit();
42085450Sbrendan }
42095450Sbrendan 
42106643Seschrock boolean_t
42116643Seschrock l2arc_vdev_present(vdev_t *vd)
42126643Seschrock {
42136643Seschrock 	l2arc_dev_t *dev;
42146643Seschrock 
42156643Seschrock 	mutex_enter(&l2arc_dev_mtx);
42166643Seschrock 	for (dev = list_head(l2arc_dev_list); dev != NULL;
42176643Seschrock 	    dev = list_next(l2arc_dev_list, dev)) {
42186643Seschrock 		if (dev->l2ad_vdev == vd)
42196643Seschrock 			break;
42206643Seschrock 	}
42216643Seschrock 	mutex_exit(&l2arc_dev_mtx);
42226643Seschrock 
42236643Seschrock 	return (dev != NULL);
42246643Seschrock }
42256643Seschrock 
42265450Sbrendan /*
42275450Sbrendan  * Add a vdev for use by the L2ARC.  By this point the spa has already
42285450Sbrendan  * validated the vdev and opened it.
42295450Sbrendan  */
42305450Sbrendan void
42315450Sbrendan l2arc_add_vdev(spa_t *spa, vdev_t *vd, uint64_t start, uint64_t end)
42325450Sbrendan {
42335450Sbrendan 	l2arc_dev_t *adddev;
42345450Sbrendan 
42356643Seschrock 	ASSERT(!l2arc_vdev_present(vd));
42366643Seschrock 
42375450Sbrendan 	/*
42385450Sbrendan 	 * Create a new l2arc device entry.
42395450Sbrendan 	 */
42405450Sbrendan 	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
42415450Sbrendan 	adddev->l2ad_spa = spa;
42425450Sbrendan 	adddev->l2ad_vdev = vd;
42435450Sbrendan 	adddev->l2ad_write = l2arc_write_max;
4244*6987Sbrendan 	adddev->l2ad_boost = l2arc_write_boost;
42455450Sbrendan 	adddev->l2ad_start = start;
42465450Sbrendan 	adddev->l2ad_end = end;
42475450Sbrendan 	adddev->l2ad_hand = adddev->l2ad_start;
42485450Sbrendan 	adddev->l2ad_evict = adddev->l2ad_start;
42495450Sbrendan 	adddev->l2ad_first = B_TRUE;
42505450Sbrendan 	ASSERT3U(adddev->l2ad_write, >, 0);
42515450Sbrendan 
42525450Sbrendan 	/*
42535450Sbrendan 	 * This is a list of all ARC buffers that are still valid on the
42545450Sbrendan 	 * device.
42555450Sbrendan 	 */
42565450Sbrendan 	adddev->l2ad_buflist = kmem_zalloc(sizeof (list_t), KM_SLEEP);
42575450Sbrendan 	list_create(adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
42585450Sbrendan 	    offsetof(arc_buf_hdr_t, b_l2node));
42595450Sbrendan 
42605450Sbrendan 	spa_l2cache_space_update(vd, adddev->l2ad_end - adddev->l2ad_hand, 0);
42615450Sbrendan 
42625450Sbrendan 	/*
42635450Sbrendan 	 * Add device to global list
42645450Sbrendan 	 */
42655450Sbrendan 	mutex_enter(&l2arc_dev_mtx);
42665450Sbrendan 	list_insert_head(l2arc_dev_list, adddev);
42675450Sbrendan 	atomic_inc_64(&l2arc_ndev);
42685450Sbrendan 	mutex_exit(&l2arc_dev_mtx);
42695450Sbrendan }
42705450Sbrendan 
42715450Sbrendan /*
42725450Sbrendan  * Remove a vdev from the L2ARC.
42735450Sbrendan  */
42745450Sbrendan void
42755450Sbrendan l2arc_remove_vdev(vdev_t *vd)
42765450Sbrendan {
42775450Sbrendan 	l2arc_dev_t *dev, *nextdev, *remdev = NULL;
42785450Sbrendan 
42795450Sbrendan 	/*
42805450Sbrendan 	 * Find the device by vdev
42815450Sbrendan 	 */
42825450Sbrendan 	mutex_enter(&l2arc_dev_mtx);
42835450Sbrendan 	for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
42845450Sbrendan 		nextdev = list_next(l2arc_dev_list, dev);
42855450Sbrendan 		if (vd == dev->l2ad_vdev) {
42865450Sbrendan 			remdev = dev;
42875450Sbrendan 			break;
42885450Sbrendan 		}
42895450Sbrendan 	}
42905450Sbrendan 	ASSERT(remdev != NULL);
42915450Sbrendan 
42925450Sbrendan 	/*
42935450Sbrendan 	 * Remove device from global list
42945450Sbrendan 	 */
42955450Sbrendan 	list_remove(l2arc_dev_list, remdev);
42965450Sbrendan 	l2arc_dev_last = NULL;		/* may have been invalidated */
4297*6987Sbrendan 	atomic_dec_64(&l2arc_ndev);
4298*6987Sbrendan 	mutex_exit(&l2arc_dev_mtx);
42995450Sbrendan 
43005450Sbrendan 	/*
43015450Sbrendan 	 * Clear all buflists and ARC references.  L2ARC device flush.
43025450Sbrendan 	 */
43035450Sbrendan 	l2arc_evict(remdev, 0, B_TRUE);
43045450Sbrendan 	list_destroy(remdev->l2ad_buflist);
43055450Sbrendan 	kmem_free(remdev->l2ad_buflist, sizeof (list_t));
43065450Sbrendan 	kmem_free(remdev, sizeof (l2arc_dev_t));
43075450Sbrendan }
43085450Sbrendan 
43095450Sbrendan void
43105450Sbrendan l2arc_init()
43115450Sbrendan {
43125450Sbrendan 	l2arc_thread_exit = 0;
43135450Sbrendan 	l2arc_ndev = 0;
43145450Sbrendan 	l2arc_writes_sent = 0;
43155450Sbrendan 	l2arc_writes_done = 0;
43165450Sbrendan 
43175450Sbrendan 	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
43185450Sbrendan 	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
43195450Sbrendan 	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
43205450Sbrendan 	mutex_init(&l2arc_buflist_mtx, NULL, MUTEX_DEFAULT, NULL);
43215450Sbrendan 	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
43225450Sbrendan 
43235450Sbrendan 	l2arc_dev_list = &L2ARC_dev_list;
43245450Sbrendan 	l2arc_free_on_write = &L2ARC_free_on_write;
43255450Sbrendan 	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
43265450Sbrendan 	    offsetof(l2arc_dev_t, l2ad_node));
43275450Sbrendan 	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
43285450Sbrendan 	    offsetof(l2arc_data_free_t, l2df_list_node));
43295450Sbrendan 
43305450Sbrendan 	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
43315450Sbrendan 	    TS_RUN, minclsyspri);
43325450Sbrendan }
43335450Sbrendan 
43345450Sbrendan void
43355450Sbrendan l2arc_fini()
43365450Sbrendan {
4337*6987Sbrendan 	/*
4338*6987Sbrendan 	 * This is called from dmu_fini(), which is called from spa_fini();
4339*6987Sbrendan 	 * Because of this, we can assume that all l2arc devices have
4340*6987Sbrendan 	 * already been removed when the pools themselves were removed.
4341*6987Sbrendan 	 */
4342*6987Sbrendan 
43435450Sbrendan 	mutex_enter(&l2arc_feed_thr_lock);
43445450Sbrendan 	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
43455450Sbrendan 	l2arc_thread_exit = 1;
43465450Sbrendan 	while (l2arc_thread_exit != 0)
43475450Sbrendan 		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
43485450Sbrendan 	mutex_exit(&l2arc_feed_thr_lock);
43495450Sbrendan 
4350*6987Sbrendan 	l2arc_do_free_on_write();
4351*6987Sbrendan 
43525450Sbrendan 	mutex_destroy(&l2arc_feed_thr_lock);
43535450Sbrendan 	cv_destroy(&l2arc_feed_thr_cv);
43545450Sbrendan 	mutex_destroy(&l2arc_dev_mtx);
43555450Sbrendan 	mutex_destroy(&l2arc_buflist_mtx);
43565450Sbrendan 	mutex_destroy(&l2arc_free_on_write_mtx);
43575450Sbrendan 
43585450Sbrendan 	list_destroy(l2arc_dev_list);
43595450Sbrendan 	list_destroy(l2arc_free_on_write);
43605450Sbrendan }
4361