xref: /titanic_51/usr/src/uts/common/fs/zfs/arc.c (revision 5f9925438d25a0e6d4a0e3582a12c92a7f4c29fb)
1fa9e4066Sahrens /*
2fa9e4066Sahrens  * CDDL HEADER START
3fa9e4066Sahrens  *
4fa9e4066Sahrens  * The contents of this file are subject to the terms of the
5033f9833Sek110237  * Common Development and Distribution License (the "License").
6033f9833Sek110237  * You may not use this file except in compliance with the License.
7fa9e4066Sahrens  *
8fa9e4066Sahrens  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9fa9e4066Sahrens  * or http://www.opensolaris.org/os/licensing.
10fa9e4066Sahrens  * See the License for the specific language governing permissions
11fa9e4066Sahrens  * and limitations under the License.
12fa9e4066Sahrens  *
13fa9e4066Sahrens  * When distributing Covered Code, include this CDDL HEADER in each
14fa9e4066Sahrens  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15fa9e4066Sahrens  * If applicable, add the following below this CDDL HEADER, with the
16fa9e4066Sahrens  * fields enclosed by brackets "[]" replaced with your own identifying
17fa9e4066Sahrens  * information: Portions Copyright [yyyy] [name of copyright owner]
18fa9e4066Sahrens  *
19fa9e4066Sahrens  * CDDL HEADER END
20fa9e4066Sahrens  */
21fa9e4066Sahrens /*
223f9d6ad7SLin Ling  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23cf746768SBryan Cantrill  * Copyright (c) 2012, Joyent, Inc. All rights reserved.
242fd872a7SPrakash Surya  * Copyright (c) 2011, 2015 by Delphix. All rights reserved.
2571cb1b74SSaso Kiselkov  * Copyright (c) 2014 by Saso Kiselkov. All rights reserved.
2631c46cf2SAlek Pinchuk  * Copyright 2015 Nexenta Systems, Inc.  All rights reserved.
27fa9e4066Sahrens  */
28fa9e4066Sahrens 
29fa9e4066Sahrens /*
3044cb6abcSbmc  * DVA-based Adjustable Replacement Cache
31fa9e4066Sahrens  *
32ea8dc4b6Seschrock  * While much of the theory of operation used here is
33ea8dc4b6Seschrock  * based on the self-tuning, low overhead replacement cache
34fa9e4066Sahrens  * presented by Megiddo and Modha at FAST 2003, there are some
35fa9e4066Sahrens  * significant differences:
36fa9e4066Sahrens  *
37fa9e4066Sahrens  * 1. The Megiddo and Modha model assumes any page is evictable.
38fa9e4066Sahrens  * Pages in its cache cannot be "locked" into memory.  This makes
39fa9e4066Sahrens  * the eviction algorithm simple: evict the last page in the list.
40fa9e4066Sahrens  * This also make the performance characteristics easy to reason
41fa9e4066Sahrens  * about.  Our cache is not so simple.  At any given moment, some
42fa9e4066Sahrens  * subset of the blocks in the cache are un-evictable because we
43fa9e4066Sahrens  * have handed out a reference to them.  Blocks are only evictable
44fa9e4066Sahrens  * when there are no external references active.  This makes
45fa9e4066Sahrens  * eviction far more problematic:  we choose to evict the evictable
46fa9e4066Sahrens  * blocks that are the "lowest" in the list.
47fa9e4066Sahrens  *
48fa9e4066Sahrens  * There are times when it is not possible to evict the requested
49fa9e4066Sahrens  * space.  In these circumstances we are unable to adjust the cache
50fa9e4066Sahrens  * size.  To prevent the cache growing unbounded at these times we
51fa94a07fSbrendan  * implement a "cache throttle" that slows the flow of new data
52fa94a07fSbrendan  * into the cache until we can make space available.
53fa9e4066Sahrens  *
54fa9e4066Sahrens  * 2. The Megiddo and Modha model assumes a fixed cache size.
55fa9e4066Sahrens  * Pages are evicted when the cache is full and there is a cache
56fa9e4066Sahrens  * miss.  Our model has a variable sized cache.  It grows with
57fa94a07fSbrendan  * high use, but also tries to react to memory pressure from the
58fa9e4066Sahrens  * operating system: decreasing its size when system memory is
59fa9e4066Sahrens  * tight.
60fa9e4066Sahrens  *
61fa9e4066Sahrens  * 3. The Megiddo and Modha model assumes a fixed page size. All
62f7170741SWill Andrews  * elements of the cache are therefore exactly the same size.  So
63fa9e4066Sahrens  * when adjusting the cache size following a cache miss, its simply
64fa9e4066Sahrens  * a matter of choosing a single page to evict.  In our model, we
65fa9e4066Sahrens  * have variable sized cache blocks (rangeing from 512 bytes to
66f7170741SWill Andrews  * 128K bytes).  We therefore choose a set of blocks to evict to make
67fa9e4066Sahrens  * space for a cache miss that approximates as closely as possible
68fa9e4066Sahrens  * the space used by the new block.
69fa9e4066Sahrens  *
70fa9e4066Sahrens  * See also:  "ARC: A Self-Tuning, Low Overhead Replacement Cache"
71fa9e4066Sahrens  * by N. Megiddo & D. Modha, FAST 2003
72fa9e4066Sahrens  */
73fa9e4066Sahrens 
74fa9e4066Sahrens /*
75fa9e4066Sahrens  * The locking model:
76fa9e4066Sahrens  *
77fa9e4066Sahrens  * A new reference to a cache buffer can be obtained in two
78fa9e4066Sahrens  * ways: 1) via a hash table lookup using the DVA as a key,
79fa94a07fSbrendan  * or 2) via one of the ARC lists.  The arc_read() interface
80fa9e4066Sahrens  * uses method 1, while the internal arc algorithms for
81f7170741SWill Andrews  * adjusting the cache use method 2.  We therefore provide two
82fa9e4066Sahrens  * types of locks: 1) the hash table lock array, and 2) the
83fa9e4066Sahrens  * arc list locks.
84fa9e4066Sahrens  *
85fc98fea5SBart Coddens  * Buffers do not have their own mutexes, rather they rely on the
86fc98fea5SBart Coddens  * hash table mutexes for the bulk of their protection (i.e. most
87fc98fea5SBart Coddens  * fields in the arc_buf_hdr_t are protected by these mutexes).
88fa9e4066Sahrens  *
89fa9e4066Sahrens  * buf_hash_find() returns the appropriate mutex (held) when it
90fa9e4066Sahrens  * locates the requested buffer in the hash table.  It returns
91fa9e4066Sahrens  * NULL for the mutex if the buffer was not in the table.
92fa9e4066Sahrens  *
93fa9e4066Sahrens  * buf_hash_remove() expects the appropriate hash mutex to be
94fa9e4066Sahrens  * already held before it is invoked.
95fa9e4066Sahrens  *
96fa9e4066Sahrens  * Each arc state also has a mutex which is used to protect the
97fa9e4066Sahrens  * buffer list associated with the state.  When attempting to
98fa9e4066Sahrens  * obtain a hash table lock while holding an arc list lock you
99fa9e4066Sahrens  * must use: mutex_tryenter() to avoid deadlock.  Also note that
10044eda4d7Smaybee  * the active state mutex must be held before the ghost state mutex.
101fa9e4066Sahrens  *
102ea8dc4b6Seschrock  * Arc buffers may have an associated eviction callback function.
103ea8dc4b6Seschrock  * This function will be invoked prior to removing the buffer (e.g.
104ea8dc4b6Seschrock  * in arc_do_user_evicts()).  Note however that the data associated
105ea8dc4b6Seschrock  * with the buffer may be evicted prior to the callback.  The callback
106ea8dc4b6Seschrock  * must be made with *no locks held* (to prevent deadlock).  Additionally,
107ea8dc4b6Seschrock  * the users of callbacks must ensure that their private data is
108bbfa8ea8SMatthew Ahrens  * protected from simultaneous callbacks from arc_clear_callback()
109ea8dc4b6Seschrock  * and arc_do_user_evicts().
110ea8dc4b6Seschrock  *
111fa9e4066Sahrens  * Note that the majority of the performance stats are manipulated
112fa9e4066Sahrens  * with atomic operations.
113fa94a07fSbrendan  *
11489c86e32SChris Williamson  * The L2ARC uses the l2ad_mtx on each vdev for the following:
115fa94a07fSbrendan  *
116fa94a07fSbrendan  *	- L2ARC buflist creation
117fa94a07fSbrendan  *	- L2ARC buflist eviction
118fa94a07fSbrendan  *	- L2ARC write completion, which walks L2ARC buflists
119fa94a07fSbrendan  *	- ARC header destruction, as it removes from L2ARC buflists
120fa94a07fSbrendan  *	- ARC header release, as it removes from L2ARC buflists
121fa9e4066Sahrens  */
122fa9e4066Sahrens 
123fa9e4066Sahrens #include <sys/spa.h>
124fa9e4066Sahrens #include <sys/zio.h>
125aad02571SSaso Kiselkov #include <sys/zio_compress.h>
126fa9e4066Sahrens #include <sys/zfs_context.h>
127fa9e4066Sahrens #include <sys/arc.h>
128fa9e4066Sahrens #include <sys/refcount.h>
129c5904d13Seschrock #include <sys/vdev.h>
130573ca77eSGeorge Wilson #include <sys/vdev_impl.h>
13169962b56SMatthew Ahrens #include <sys/dsl_pool.h>
132244781f1SPrakash Surya #include <sys/multilist.h>
133fa9e4066Sahrens #ifdef _KERNEL
134fa9e4066Sahrens #include <sys/vmsystm.h>
135fa9e4066Sahrens #include <vm/anon.h>
136fa9e4066Sahrens #include <sys/fs/swapnode.h>
137033f9833Sek110237 #include <sys/dnlc.h>
138fa9e4066Sahrens #endif
139fa9e4066Sahrens #include <sys/callb.h>
14044cb6abcSbmc #include <sys/kstat.h>
141b24ab676SJeff Bonwick #include <zfs_fletcher.h>
142ce0d9371SArne Jansen #include <sys/zfs_ioctl.h>
143fa9e4066Sahrens 
144cd1c8b85SMatthew Ahrens #ifndef _KERNEL
145cd1c8b85SMatthew Ahrens /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
146cd1c8b85SMatthew Ahrens boolean_t arc_watch = B_FALSE;
147cd1c8b85SMatthew Ahrens int arc_procfd;
148cd1c8b85SMatthew Ahrens #endif
149cd1c8b85SMatthew Ahrens 
150244781f1SPrakash Surya static kmutex_t		arc_reclaim_lock;
151244781f1SPrakash Surya static kcondvar_t	arc_reclaim_thread_cv;
152244781f1SPrakash Surya static boolean_t	arc_reclaim_thread_exit;
153244781f1SPrakash Surya static kcondvar_t	arc_reclaim_waiters_cv;
154244781f1SPrakash Surya 
155244781f1SPrakash Surya static kmutex_t		arc_user_evicts_lock;
156244781f1SPrakash Surya static kcondvar_t	arc_user_evicts_cv;
157244781f1SPrakash Surya static boolean_t	arc_user_evicts_thread_exit;
158fa9e4066Sahrens 
1592ec99e3eSMatthew Ahrens uint_t arc_reduce_dnlc_percent = 3;
160fa9e4066Sahrens 
16169962b56SMatthew Ahrens /*
162244781f1SPrakash Surya  * The number of headers to evict in arc_evict_state_impl() before
163244781f1SPrakash Surya  * dropping the sublist lock and evicting from another sublist. A lower
164244781f1SPrakash Surya  * value means we're more likely to evict the "correct" header (i.e. the
165244781f1SPrakash Surya  * oldest header in the arc state), but comes with higher overhead
166244781f1SPrakash Surya  * (i.e. more invocations of arc_evict_state_impl()).
16769962b56SMatthew Ahrens  */
168244781f1SPrakash Surya int zfs_arc_evict_batch_limit = 10;
169244781f1SPrakash Surya 
170244781f1SPrakash Surya /*
171244781f1SPrakash Surya  * The number of sublists used for each of the arc state lists. If this
172244781f1SPrakash Surya  * is not set to a suitable value by the user, it will be configured to
173244781f1SPrakash Surya  * the number of CPUs on the system in arc_init().
174244781f1SPrakash Surya  */
175244781f1SPrakash Surya int zfs_arc_num_sublists_per_state = 0;
17669962b56SMatthew Ahrens 
177fa9e4066Sahrens /* number of seconds before growing cache again */
178fa9e4066Sahrens static int		arc_grow_retry = 60;
179fa9e4066Sahrens 
180244781f1SPrakash Surya /* shift of arc_c for calculating overflow limit in arc_get_data_buf */
181244781f1SPrakash Surya int		zfs_arc_overflow_shift = 8;
182244781f1SPrakash Surya 
1835a98e54bSBrendan Gregg - Sun Microsystems /* shift of arc_c for calculating both min and max arc_p */
1845a98e54bSBrendan Gregg - Sun Microsystems static int		arc_p_min_shift = 4;
1855a98e54bSBrendan Gregg - Sun Microsystems 
1865a98e54bSBrendan Gregg - Sun Microsystems /* log2(fraction of arc to reclaim) */
1872ec99e3eSMatthew Ahrens static int		arc_shrink_shift = 7;
1882ec99e3eSMatthew Ahrens 
1892ec99e3eSMatthew Ahrens /*
1902ec99e3eSMatthew Ahrens  * log2(fraction of ARC which must be free to allow growing).
1912ec99e3eSMatthew Ahrens  * I.e. If there is less than arc_c >> arc_no_grow_shift free memory,
1922ec99e3eSMatthew Ahrens  * when reading a new block into the ARC, we will evict an equal-sized block
1932ec99e3eSMatthew Ahrens  * from the ARC.
1942ec99e3eSMatthew Ahrens  *
1952ec99e3eSMatthew Ahrens  * This must be less than arc_shrink_shift, so that when we shrink the ARC,
1962ec99e3eSMatthew Ahrens  * we will still not allow it to grow.
1972ec99e3eSMatthew Ahrens  */
1982ec99e3eSMatthew Ahrens int			arc_no_grow_shift = 5;
1992ec99e3eSMatthew Ahrens 
2005a98e54bSBrendan Gregg - Sun Microsystems 
20113506d1eSmaybee /*
202b19a79ecSperrin  * minimum lifespan of a prefetch block in clock ticks
203b19a79ecSperrin  * (initialized in arc_init())
20413506d1eSmaybee  */
205b19a79ecSperrin static int		arc_min_prefetch_lifespan;
20613506d1eSmaybee 
20769962b56SMatthew Ahrens /*
20869962b56SMatthew Ahrens  * If this percent of memory is free, don't throttle.
20969962b56SMatthew Ahrens  */
21069962b56SMatthew Ahrens int arc_lotsfree_percent = 10;
21169962b56SMatthew Ahrens 
212fa9e4066Sahrens static int arc_dead;
213fa9e4066Sahrens 
214fa9e4066Sahrens /*
2153a737e0dSbrendan  * The arc has filled available memory and has now warmed up.
2163a737e0dSbrendan  */
2173a737e0dSbrendan static boolean_t arc_warm;
2183a737e0dSbrendan 
2193a737e0dSbrendan /*
220a2eea2e1Sahrens  * These tunables are for performance analysis.
221a2eea2e1Sahrens  */
222a2eea2e1Sahrens uint64_t zfs_arc_max;
223a2eea2e1Sahrens uint64_t zfs_arc_min;
2241116048bSek110237 uint64_t zfs_arc_meta_limit = 0;
2253a5286a1SMatthew Ahrens uint64_t zfs_arc_meta_min = 0;
2265a98e54bSBrendan Gregg - Sun Microsystems int zfs_arc_grow_retry = 0;
2275a98e54bSBrendan Gregg - Sun Microsystems int zfs_arc_shrink_shift = 0;
2285a98e54bSBrendan Gregg - Sun Microsystems int zfs_arc_p_min_shift = 0;
2299253d63dSGeorge Wilson int zfs_disable_dup_eviction = 0;
23063e911b6SMatthew Ahrens int zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
231a2eea2e1Sahrens 
232a2eea2e1Sahrens /*
233fa94a07fSbrendan  * Note that buffers can be in one of 6 states:
234fa9e4066Sahrens  *	ARC_anon	- anonymous (discussed below)
235ea8dc4b6Seschrock  *	ARC_mru		- recently used, currently cached
236ea8dc4b6Seschrock  *	ARC_mru_ghost	- recentely used, no longer in cache
237ea8dc4b6Seschrock  *	ARC_mfu		- frequently used, currently cached
238ea8dc4b6Seschrock  *	ARC_mfu_ghost	- frequently used, no longer in cache
239fa94a07fSbrendan  *	ARC_l2c_only	- exists in L2ARC but not other states
2400e8c6158Smaybee  * When there are no active references to the buffer, they are
2410e8c6158Smaybee  * are linked onto a list in one of these arc states.  These are
2420e8c6158Smaybee  * the only buffers that can be evicted or deleted.  Within each
2430e8c6158Smaybee  * state there are multiple lists, one for meta-data and one for
2440e8c6158Smaybee  * non-meta-data.  Meta-data (indirect blocks, blocks of dnodes,
2450e8c6158Smaybee  * etc.) is tracked separately so that it can be managed more
246fa94a07fSbrendan  * explicitly: favored over data, limited explicitly.
247fa9e4066Sahrens  *
248fa9e4066Sahrens  * Anonymous buffers are buffers that are not associated with
249fa9e4066Sahrens  * a DVA.  These are buffers that hold dirty block copies
250fa9e4066Sahrens  * before they are written to stable storage.  By definition,
251ea8dc4b6Seschrock  * they are "ref'd" and are considered part of arc_mru
252fa9e4066Sahrens  * that cannot be freed.  Generally, they will aquire a DVA
253ea8dc4b6Seschrock  * as they are written and migrate onto the arc_mru list.
254fa94a07fSbrendan  *
255fa94a07fSbrendan  * The ARC_l2c_only state is for buffers that are in the second
256fa94a07fSbrendan  * level ARC but no longer in any of the ARC_m* lists.  The second
257fa94a07fSbrendan  * level ARC itself may also contain buffers that are in any of
258fa94a07fSbrendan  * the ARC_m* states - meaning that a buffer can exist in two
259fa94a07fSbrendan  * places.  The reason for the ARC_l2c_only state is to keep the
260fa94a07fSbrendan  * buffer header in the hash table, so that reads that hit the
261fa94a07fSbrendan  * second level ARC benefit from these fast lookups.
262fa9e4066Sahrens  */
263fa9e4066Sahrens 
264fa9e4066Sahrens typedef struct arc_state {
265244781f1SPrakash Surya 	/*
266244781f1SPrakash Surya 	 * list of evictable buffers
267244781f1SPrakash Surya 	 */
268244781f1SPrakash Surya 	multilist_t arcs_list[ARC_BUFC_NUMTYPES];
269244781f1SPrakash Surya 	/*
270244781f1SPrakash Surya 	 * total amount of evictable data in this state
271244781f1SPrakash Surya 	 */
272244781f1SPrakash Surya 	uint64_t arcs_lsize[ARC_BUFC_NUMTYPES];
273244781f1SPrakash Surya 	/*
274244781f1SPrakash Surya 	 * total amount of data in this state; this includes: evictable,
275244781f1SPrakash Surya 	 * non-evictable, ARC_BUFC_DATA, and ARC_BUFC_METADATA.
276244781f1SPrakash Surya 	 */
2772fd872a7SPrakash Surya 	refcount_t arcs_size;
278fa9e4066Sahrens } arc_state_t;
279fa9e4066Sahrens 
280fa94a07fSbrendan /* The 6 states: */
281fa9e4066Sahrens static arc_state_t ARC_anon;
282ea8dc4b6Seschrock static arc_state_t ARC_mru;
283ea8dc4b6Seschrock static arc_state_t ARC_mru_ghost;
284ea8dc4b6Seschrock static arc_state_t ARC_mfu;
285ea8dc4b6Seschrock static arc_state_t ARC_mfu_ghost;
286fa94a07fSbrendan static arc_state_t ARC_l2c_only;
287fa9e4066Sahrens 
28844cb6abcSbmc typedef struct arc_stats {
28944cb6abcSbmc 	kstat_named_t arcstat_hits;
29044cb6abcSbmc 	kstat_named_t arcstat_misses;
291*5f992543SArne Jansen 	kstat_named_t arcstat_demand_data_hits;
292*5f992543SArne Jansen 	kstat_named_t arcstat_demand_data_misses;
293*5f992543SArne Jansen 	kstat_named_t arcstat_demand_metadata_hits;
294*5f992543SArne Jansen 	kstat_named_t arcstat_demand_metadata_misses;
295*5f992543SArne Jansen 	kstat_named_t arcstat_prefetch_data_hits;
296*5f992543SArne Jansen 	kstat_named_t arcstat_prefetch_data_misses;
297*5f992543SArne Jansen 	kstat_named_t arcstat_prefetch_metadata_hits;
298*5f992543SArne Jansen 	kstat_named_t arcstat_prefetch_metadata_misses;
29944cb6abcSbmc 	kstat_named_t arcstat_mru_hits;
30044cb6abcSbmc 	kstat_named_t arcstat_mru_ghost_hits;
30144cb6abcSbmc 	kstat_named_t arcstat_mfu_hits;
30244cb6abcSbmc 	kstat_named_t arcstat_mfu_ghost_hits;
30344cb6abcSbmc 	kstat_named_t arcstat_deleted;
3043e30c24aSWill Andrews 	/*
3053e30c24aSWill Andrews 	 * Number of buffers that could not be evicted because the hash lock
3063e30c24aSWill Andrews 	 * was held by another thread.  The lock may not necessarily be held
3073e30c24aSWill Andrews 	 * by something using the same buffer, since hash locks are shared
3083e30c24aSWill Andrews 	 * by multiple buffers.
3093e30c24aSWill Andrews 	 */
31044cb6abcSbmc 	kstat_named_t arcstat_mutex_miss;
3113e30c24aSWill Andrews 	/*
3123e30c24aSWill Andrews 	 * Number of buffers skipped because they have I/O in progress, are
3133e30c24aSWill Andrews 	 * indrect prefetch buffers that have not lived long enough, or are
3143e30c24aSWill Andrews 	 * not from the spa we're trying to evict from.
3153e30c24aSWill Andrews 	 */
31644cb6abcSbmc 	kstat_named_t arcstat_evict_skip;
317244781f1SPrakash Surya 	/*
318244781f1SPrakash Surya 	 * Number of times arc_evict_state() was unable to evict enough
319244781f1SPrakash Surya 	 * buffers to reach it's target amount.
320244781f1SPrakash Surya 	 */
321244781f1SPrakash Surya 	kstat_named_t arcstat_evict_not_enough;
3225ea40c06SBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_evict_l2_cached;
3235ea40c06SBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_evict_l2_eligible;
3245ea40c06SBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_evict_l2_ineligible;
325244781f1SPrakash Surya 	kstat_named_t arcstat_evict_l2_skip;
32644cb6abcSbmc 	kstat_named_t arcstat_hash_elements;
32744cb6abcSbmc 	kstat_named_t arcstat_hash_elements_max;
32844cb6abcSbmc 	kstat_named_t arcstat_hash_collisions;
32944cb6abcSbmc 	kstat_named_t arcstat_hash_chains;
33044cb6abcSbmc 	kstat_named_t arcstat_hash_chain_max;
33144cb6abcSbmc 	kstat_named_t arcstat_p;
33244cb6abcSbmc 	kstat_named_t arcstat_c;
33344cb6abcSbmc 	kstat_named_t arcstat_c_min;
33444cb6abcSbmc 	kstat_named_t arcstat_c_max;
33544cb6abcSbmc 	kstat_named_t arcstat_size;
3364076b1bfSPrakash Surya 	/*
3374076b1bfSPrakash Surya 	 * Number of bytes consumed by internal ARC structures necessary
3384076b1bfSPrakash Surya 	 * for tracking purposes; these structures are not actually
3394076b1bfSPrakash Surya 	 * backed by ARC buffers. This includes arc_buf_hdr_t structures
3404076b1bfSPrakash Surya 	 * (allocated via arc_buf_hdr_t_full and arc_buf_hdr_t_l2only
3414076b1bfSPrakash Surya 	 * caches), and arc_buf_t structures (allocated via arc_buf_t
3424076b1bfSPrakash Surya 	 * cache).
3434076b1bfSPrakash Surya 	 */
344fa94a07fSbrendan 	kstat_named_t arcstat_hdr_size;
3454076b1bfSPrakash Surya 	/*
3464076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers of type equal to
3474076b1bfSPrakash Surya 	 * ARC_BUFC_DATA. This is generally consumed by buffers backing
3484076b1bfSPrakash Surya 	 * on disk user data (e.g. plain file contents).
3494076b1bfSPrakash Surya 	 */
3505a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_data_size;
3514076b1bfSPrakash Surya 	/*
3524076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers of type equal to
3534076b1bfSPrakash Surya 	 * ARC_BUFC_METADATA. This is generally consumed by buffers
3544076b1bfSPrakash Surya 	 * backing on disk data that is used for internal ZFS
3554076b1bfSPrakash Surya 	 * structures (e.g. ZAP, dnode, indirect blocks, etc).
3564076b1bfSPrakash Surya 	 */
3574076b1bfSPrakash Surya 	kstat_named_t arcstat_metadata_size;
3584076b1bfSPrakash Surya 	/*
3594076b1bfSPrakash Surya 	 * Number of bytes consumed by various buffers and structures
3604076b1bfSPrakash Surya 	 * not actually backed with ARC buffers. This includes bonus
3614076b1bfSPrakash Surya 	 * buffers (allocated directly via zio_buf_* functions),
3624076b1bfSPrakash Surya 	 * dmu_buf_impl_t structures (allocated via dmu_buf_impl_t
3634076b1bfSPrakash Surya 	 * cache), and dnode_t structures (allocated via dnode_t cache).
3644076b1bfSPrakash Surya 	 */
3655a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_other_size;
3664076b1bfSPrakash Surya 	/*
3674076b1bfSPrakash Surya 	 * Total number of bytes consumed by ARC buffers residing in the
3684076b1bfSPrakash Surya 	 * arc_anon state. This includes *all* buffers in the arc_anon
3694076b1bfSPrakash Surya 	 * state; e.g. data, metadata, evictable, and unevictable buffers
3704076b1bfSPrakash Surya 	 * are all included in this value.
3714076b1bfSPrakash Surya 	 */
3724076b1bfSPrakash Surya 	kstat_named_t arcstat_anon_size;
3734076b1bfSPrakash Surya 	/*
3744076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
3754076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_DATA,
3764076b1bfSPrakash Surya 	 * residing in the arc_anon state, and are eligible for eviction
3774076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
3784076b1bfSPrakash Surya 	 */
3794076b1bfSPrakash Surya 	kstat_named_t arcstat_anon_evictable_data;
3804076b1bfSPrakash Surya 	/*
3814076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
3824076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_METADATA,
3834076b1bfSPrakash Surya 	 * residing in the arc_anon state, and are eligible for eviction
3844076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
3854076b1bfSPrakash Surya 	 */
3864076b1bfSPrakash Surya 	kstat_named_t arcstat_anon_evictable_metadata;
3874076b1bfSPrakash Surya 	/*
3884076b1bfSPrakash Surya 	 * Total number of bytes consumed by ARC buffers residing in the
3894076b1bfSPrakash Surya 	 * arc_mru state. This includes *all* buffers in the arc_mru
3904076b1bfSPrakash Surya 	 * state; e.g. data, metadata, evictable, and unevictable buffers
3914076b1bfSPrakash Surya 	 * are all included in this value.
3924076b1bfSPrakash Surya 	 */
3934076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_size;
3944076b1bfSPrakash Surya 	/*
3954076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
3964076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_DATA,
3974076b1bfSPrakash Surya 	 * residing in the arc_mru state, and are eligible for eviction
3984076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
3994076b1bfSPrakash Surya 	 */
4004076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_evictable_data;
4014076b1bfSPrakash Surya 	/*
4024076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
4034076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_METADATA,
4044076b1bfSPrakash Surya 	 * residing in the arc_mru state, and are eligible for eviction
4054076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
4064076b1bfSPrakash Surya 	 */
4074076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_evictable_metadata;
4084076b1bfSPrakash Surya 	/*
4094076b1bfSPrakash Surya 	 * Total number of bytes that *would have been* consumed by ARC
4104076b1bfSPrakash Surya 	 * buffers in the arc_mru_ghost state. The key thing to note
4114076b1bfSPrakash Surya 	 * here, is the fact that this size doesn't actually indicate
4124076b1bfSPrakash Surya 	 * RAM consumption. The ghost lists only consist of headers and
4134076b1bfSPrakash Surya 	 * don't actually have ARC buffers linked off of these headers.
4144076b1bfSPrakash Surya 	 * Thus, *if* the headers had associated ARC buffers, these
4154076b1bfSPrakash Surya 	 * buffers *would have* consumed this number of bytes.
4164076b1bfSPrakash Surya 	 */
4174076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_ghost_size;
4184076b1bfSPrakash Surya 	/*
4194076b1bfSPrakash Surya 	 * Number of bytes that *would have been* consumed by ARC
4204076b1bfSPrakash Surya 	 * buffers that are eligible for eviction, of type
4214076b1bfSPrakash Surya 	 * ARC_BUFC_DATA, and linked off the arc_mru_ghost state.
4224076b1bfSPrakash Surya 	 */
4234076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_ghost_evictable_data;
4244076b1bfSPrakash Surya 	/*
4254076b1bfSPrakash Surya 	 * Number of bytes that *would have been* consumed by ARC
4264076b1bfSPrakash Surya 	 * buffers that are eligible for eviction, of type
4274076b1bfSPrakash Surya 	 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
4284076b1bfSPrakash Surya 	 */
4294076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_ghost_evictable_metadata;
4304076b1bfSPrakash Surya 	/*
4314076b1bfSPrakash Surya 	 * Total number of bytes consumed by ARC buffers residing in the
4324076b1bfSPrakash Surya 	 * arc_mfu state. This includes *all* buffers in the arc_mfu
4334076b1bfSPrakash Surya 	 * state; e.g. data, metadata, evictable, and unevictable buffers
4344076b1bfSPrakash Surya 	 * are all included in this value.
4354076b1bfSPrakash Surya 	 */
4364076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_size;
4374076b1bfSPrakash Surya 	/*
4384076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that are eligible for
4394076b1bfSPrakash Surya 	 * eviction, of type ARC_BUFC_DATA, and reside in the arc_mfu
4404076b1bfSPrakash Surya 	 * state.
4414076b1bfSPrakash Surya 	 */
4424076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_evictable_data;
4434076b1bfSPrakash Surya 	/*
4444076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that are eligible for
4454076b1bfSPrakash Surya 	 * eviction, of type ARC_BUFC_METADATA, and reside in the
4464076b1bfSPrakash Surya 	 * arc_mfu state.
4474076b1bfSPrakash Surya 	 */
4484076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_evictable_metadata;
4494076b1bfSPrakash Surya 	/*
4504076b1bfSPrakash Surya 	 * Total number of bytes that *would have been* consumed by ARC
4514076b1bfSPrakash Surya 	 * buffers in the arc_mfu_ghost state. See the comment above
4524076b1bfSPrakash Surya 	 * arcstat_mru_ghost_size for more details.
4534076b1bfSPrakash Surya 	 */
4544076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_ghost_size;
4554076b1bfSPrakash Surya 	/*
4564076b1bfSPrakash Surya 	 * Number of bytes that *would have been* consumed by ARC
4574076b1bfSPrakash Surya 	 * buffers that are eligible for eviction, of type
4584076b1bfSPrakash Surya 	 * ARC_BUFC_DATA, and linked off the arc_mfu_ghost state.
4594076b1bfSPrakash Surya 	 */
4604076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_ghost_evictable_data;
4614076b1bfSPrakash Surya 	/*
4624076b1bfSPrakash Surya 	 * Number of bytes that *would have been* consumed by ARC
4634076b1bfSPrakash Surya 	 * buffers that are eligible for eviction, of type
4644076b1bfSPrakash Surya 	 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
4654076b1bfSPrakash Surya 	 */
4664076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_ghost_evictable_metadata;
467fa94a07fSbrendan 	kstat_named_t arcstat_l2_hits;
468fa94a07fSbrendan 	kstat_named_t arcstat_l2_misses;
469fa94a07fSbrendan 	kstat_named_t arcstat_l2_feeds;
470fa94a07fSbrendan 	kstat_named_t arcstat_l2_rw_clash;
4715a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_l2_read_bytes;
4725a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_l2_write_bytes;
473fa94a07fSbrendan 	kstat_named_t arcstat_l2_writes_sent;
474fa94a07fSbrendan 	kstat_named_t arcstat_l2_writes_done;
475fa94a07fSbrendan 	kstat_named_t arcstat_l2_writes_error;
476244781f1SPrakash Surya 	kstat_named_t arcstat_l2_writes_lock_retry;
477fa94a07fSbrendan 	kstat_named_t arcstat_l2_evict_lock_retry;
478fa94a07fSbrendan 	kstat_named_t arcstat_l2_evict_reading;
47989c86e32SChris Williamson 	kstat_named_t arcstat_l2_evict_l1cached;
480fa94a07fSbrendan 	kstat_named_t arcstat_l2_free_on_write;
481244781f1SPrakash Surya 	kstat_named_t arcstat_l2_cdata_free_on_write;
482fa94a07fSbrendan 	kstat_named_t arcstat_l2_abort_lowmem;
483fa94a07fSbrendan 	kstat_named_t arcstat_l2_cksum_bad;
484fa94a07fSbrendan 	kstat_named_t arcstat_l2_io_error;
485fa94a07fSbrendan 	kstat_named_t arcstat_l2_size;
486aad02571SSaso Kiselkov 	kstat_named_t arcstat_l2_asize;
487fa94a07fSbrendan 	kstat_named_t arcstat_l2_hdr_size;
488aad02571SSaso Kiselkov 	kstat_named_t arcstat_l2_compress_successes;
489aad02571SSaso Kiselkov 	kstat_named_t arcstat_l2_compress_zeros;
490aad02571SSaso Kiselkov 	kstat_named_t arcstat_l2_compress_failures;
4911ab7f2deSmaybee 	kstat_named_t arcstat_memory_throttle_count;
4929253d63dSGeorge Wilson 	kstat_named_t arcstat_duplicate_buffers;
4939253d63dSGeorge Wilson 	kstat_named_t arcstat_duplicate_buffers_size;
4949253d63dSGeorge Wilson 	kstat_named_t arcstat_duplicate_reads;
49520128a08SGeorge Wilson 	kstat_named_t arcstat_meta_used;
49620128a08SGeorge Wilson 	kstat_named_t arcstat_meta_limit;
49720128a08SGeorge Wilson 	kstat_named_t arcstat_meta_max;
4983a5286a1SMatthew Ahrens 	kstat_named_t arcstat_meta_min;
499cf6106c8SMatthew Ahrens 	kstat_named_t arcstat_sync_wait_for_async;
500cf6106c8SMatthew Ahrens 	kstat_named_t arcstat_demand_hit_predictive_prefetch;
50144cb6abcSbmc } arc_stats_t;
502fa9e4066Sahrens 
50344cb6abcSbmc static arc_stats_t arc_stats = {
50444cb6abcSbmc 	{ "hits",			KSTAT_DATA_UINT64 },
50544cb6abcSbmc 	{ "misses",			KSTAT_DATA_UINT64 },
50644cb6abcSbmc 	{ "demand_data_hits",		KSTAT_DATA_UINT64 },
50744cb6abcSbmc 	{ "demand_data_misses",		KSTAT_DATA_UINT64 },
50844cb6abcSbmc 	{ "demand_metadata_hits",	KSTAT_DATA_UINT64 },
50944cb6abcSbmc 	{ "demand_metadata_misses",	KSTAT_DATA_UINT64 },
51044cb6abcSbmc 	{ "prefetch_data_hits",		KSTAT_DATA_UINT64 },
51144cb6abcSbmc 	{ "prefetch_data_misses",	KSTAT_DATA_UINT64 },
51244cb6abcSbmc 	{ "prefetch_metadata_hits",	KSTAT_DATA_UINT64 },
51344cb6abcSbmc 	{ "prefetch_metadata_misses",	KSTAT_DATA_UINT64 },
51444cb6abcSbmc 	{ "mru_hits",			KSTAT_DATA_UINT64 },
51544cb6abcSbmc 	{ "mru_ghost_hits",		KSTAT_DATA_UINT64 },
51644cb6abcSbmc 	{ "mfu_hits",			KSTAT_DATA_UINT64 },
51744cb6abcSbmc 	{ "mfu_ghost_hits",		KSTAT_DATA_UINT64 },
51844cb6abcSbmc 	{ "deleted",			KSTAT_DATA_UINT64 },
51944cb6abcSbmc 	{ "mutex_miss",			KSTAT_DATA_UINT64 },
52044cb6abcSbmc 	{ "evict_skip",			KSTAT_DATA_UINT64 },
521244781f1SPrakash Surya 	{ "evict_not_enough",		KSTAT_DATA_UINT64 },
5225ea40c06SBrendan Gregg - Sun Microsystems 	{ "evict_l2_cached",		KSTAT_DATA_UINT64 },
5235ea40c06SBrendan Gregg - Sun Microsystems 	{ "evict_l2_eligible",		KSTAT_DATA_UINT64 },
5245ea40c06SBrendan Gregg - Sun Microsystems 	{ "evict_l2_ineligible",	KSTAT_DATA_UINT64 },
525244781f1SPrakash Surya 	{ "evict_l2_skip",		KSTAT_DATA_UINT64 },
52644cb6abcSbmc 	{ "hash_elements",		KSTAT_DATA_UINT64 },
52744cb6abcSbmc 	{ "hash_elements_max",		KSTAT_DATA_UINT64 },
52844cb6abcSbmc 	{ "hash_collisions",		KSTAT_DATA_UINT64 },
52944cb6abcSbmc 	{ "hash_chains",		KSTAT_DATA_UINT64 },
53044cb6abcSbmc 	{ "hash_chain_max",		KSTAT_DATA_UINT64 },
53144cb6abcSbmc 	{ "p",				KSTAT_DATA_UINT64 },
53244cb6abcSbmc 	{ "c",				KSTAT_DATA_UINT64 },
53344cb6abcSbmc 	{ "c_min",			KSTAT_DATA_UINT64 },
53444cb6abcSbmc 	{ "c_max",			KSTAT_DATA_UINT64 },
535fa94a07fSbrendan 	{ "size",			KSTAT_DATA_UINT64 },
536fa94a07fSbrendan 	{ "hdr_size",			KSTAT_DATA_UINT64 },
5375a98e54bSBrendan Gregg - Sun Microsystems 	{ "data_size",			KSTAT_DATA_UINT64 },
5384076b1bfSPrakash Surya 	{ "metadata_size",		KSTAT_DATA_UINT64 },
5395a98e54bSBrendan Gregg - Sun Microsystems 	{ "other_size",			KSTAT_DATA_UINT64 },
5404076b1bfSPrakash Surya 	{ "anon_size",			KSTAT_DATA_UINT64 },
5414076b1bfSPrakash Surya 	{ "anon_evictable_data",	KSTAT_DATA_UINT64 },
5424076b1bfSPrakash Surya 	{ "anon_evictable_metadata",	KSTAT_DATA_UINT64 },
5434076b1bfSPrakash Surya 	{ "mru_size",			KSTAT_DATA_UINT64 },
5444076b1bfSPrakash Surya 	{ "mru_evictable_data",		KSTAT_DATA_UINT64 },
5454076b1bfSPrakash Surya 	{ "mru_evictable_metadata",	KSTAT_DATA_UINT64 },
5464076b1bfSPrakash Surya 	{ "mru_ghost_size",		KSTAT_DATA_UINT64 },
5474076b1bfSPrakash Surya 	{ "mru_ghost_evictable_data",	KSTAT_DATA_UINT64 },
5484076b1bfSPrakash Surya 	{ "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
5494076b1bfSPrakash Surya 	{ "mfu_size",			KSTAT_DATA_UINT64 },
5504076b1bfSPrakash Surya 	{ "mfu_evictable_data",		KSTAT_DATA_UINT64 },
5514076b1bfSPrakash Surya 	{ "mfu_evictable_metadata",	KSTAT_DATA_UINT64 },
5524076b1bfSPrakash Surya 	{ "mfu_ghost_size",		KSTAT_DATA_UINT64 },
5534076b1bfSPrakash Surya 	{ "mfu_ghost_evictable_data",	KSTAT_DATA_UINT64 },
5544076b1bfSPrakash Surya 	{ "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
555fa94a07fSbrendan 	{ "l2_hits",			KSTAT_DATA_UINT64 },
556fa94a07fSbrendan 	{ "l2_misses",			KSTAT_DATA_UINT64 },
557fa94a07fSbrendan 	{ "l2_feeds",			KSTAT_DATA_UINT64 },
558fa94a07fSbrendan 	{ "l2_rw_clash",		KSTAT_DATA_UINT64 },
5595a98e54bSBrendan Gregg - Sun Microsystems 	{ "l2_read_bytes",		KSTAT_DATA_UINT64 },
5605a98e54bSBrendan Gregg - Sun Microsystems 	{ "l2_write_bytes",		KSTAT_DATA_UINT64 },
561fa94a07fSbrendan 	{ "l2_writes_sent",		KSTAT_DATA_UINT64 },
562fa94a07fSbrendan 	{ "l2_writes_done",		KSTAT_DATA_UINT64 },
563fa94a07fSbrendan 	{ "l2_writes_error",		KSTAT_DATA_UINT64 },
564244781f1SPrakash Surya 	{ "l2_writes_lock_retry",	KSTAT_DATA_UINT64 },
565fa94a07fSbrendan 	{ "l2_evict_lock_retry",	KSTAT_DATA_UINT64 },
566fa94a07fSbrendan 	{ "l2_evict_reading",		KSTAT_DATA_UINT64 },
56789c86e32SChris Williamson 	{ "l2_evict_l1cached",		KSTAT_DATA_UINT64 },
568fa94a07fSbrendan 	{ "l2_free_on_write",		KSTAT_DATA_UINT64 },
569244781f1SPrakash Surya 	{ "l2_cdata_free_on_write",	KSTAT_DATA_UINT64 },
570fa94a07fSbrendan 	{ "l2_abort_lowmem",		KSTAT_DATA_UINT64 },
571fa94a07fSbrendan 	{ "l2_cksum_bad",		KSTAT_DATA_UINT64 },
572fa94a07fSbrendan 	{ "l2_io_error",		KSTAT_DATA_UINT64 },
573fa94a07fSbrendan 	{ "l2_size",			KSTAT_DATA_UINT64 },
574aad02571SSaso Kiselkov 	{ "l2_asize",			KSTAT_DATA_UINT64 },
5751ab7f2deSmaybee 	{ "l2_hdr_size",		KSTAT_DATA_UINT64 },
576aad02571SSaso Kiselkov 	{ "l2_compress_successes",	KSTAT_DATA_UINT64 },
577aad02571SSaso Kiselkov 	{ "l2_compress_zeros",		KSTAT_DATA_UINT64 },
578aad02571SSaso Kiselkov 	{ "l2_compress_failures",	KSTAT_DATA_UINT64 },
5799253d63dSGeorge Wilson 	{ "memory_throttle_count",	KSTAT_DATA_UINT64 },
5809253d63dSGeorge Wilson 	{ "duplicate_buffers",		KSTAT_DATA_UINT64 },
5819253d63dSGeorge Wilson 	{ "duplicate_buffers_size",	KSTAT_DATA_UINT64 },
58220128a08SGeorge Wilson 	{ "duplicate_reads",		KSTAT_DATA_UINT64 },
58320128a08SGeorge Wilson 	{ "arc_meta_used",		KSTAT_DATA_UINT64 },
58420128a08SGeorge Wilson 	{ "arc_meta_limit",		KSTAT_DATA_UINT64 },
5853a5286a1SMatthew Ahrens 	{ "arc_meta_max",		KSTAT_DATA_UINT64 },
586cf6106c8SMatthew Ahrens 	{ "arc_meta_min",		KSTAT_DATA_UINT64 },
587cf6106c8SMatthew Ahrens 	{ "sync_wait_for_async",	KSTAT_DATA_UINT64 },
588cf6106c8SMatthew Ahrens 	{ "demand_hit_predictive_prefetch", KSTAT_DATA_UINT64 },
58944cb6abcSbmc };
590fa9e4066Sahrens 
59144cb6abcSbmc #define	ARCSTAT(stat)	(arc_stats.stat.value.ui64)
592fa9e4066Sahrens 
59344cb6abcSbmc #define	ARCSTAT_INCR(stat, val) \
594f7170741SWill Andrews 	atomic_add_64(&arc_stats.stat.value.ui64, (val))
59544cb6abcSbmc 
59644cb6abcSbmc #define	ARCSTAT_BUMP(stat)	ARCSTAT_INCR(stat, 1)
59744cb6abcSbmc #define	ARCSTAT_BUMPDOWN(stat)	ARCSTAT_INCR(stat, -1)
59844cb6abcSbmc 
59944cb6abcSbmc #define	ARCSTAT_MAX(stat, val) {					\
60044cb6abcSbmc 	uint64_t m;							\
60144cb6abcSbmc 	while ((val) > (m = arc_stats.stat.value.ui64) &&		\
60244cb6abcSbmc 	    (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val))))	\
60344cb6abcSbmc 		continue;						\
60444cb6abcSbmc }
60544cb6abcSbmc 
60644cb6abcSbmc #define	ARCSTAT_MAXSTAT(stat) \
60744cb6abcSbmc 	ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
60844cb6abcSbmc 
60944cb6abcSbmc /*
61044cb6abcSbmc  * We define a macro to allow ARC hits/misses to be easily broken down by
61144cb6abcSbmc  * two separate conditions, giving a total of four different subtypes for
61244cb6abcSbmc  * each of hits and misses (so eight statistics total).
61344cb6abcSbmc  */
61444cb6abcSbmc #define	ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
61544cb6abcSbmc 	if (cond1) {							\
61644cb6abcSbmc 		if (cond2) {						\
61744cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
61844cb6abcSbmc 		} else {						\
61944cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
62044cb6abcSbmc 		}							\
62144cb6abcSbmc 	} else {							\
62244cb6abcSbmc 		if (cond2) {						\
62344cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
62444cb6abcSbmc 		} else {						\
62544cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
62644cb6abcSbmc 		}							\
62744cb6abcSbmc 	}
62844cb6abcSbmc 
62944cb6abcSbmc kstat_t			*arc_ksp;
63044cb6abcSbmc static arc_state_t	*arc_anon;
63144cb6abcSbmc static arc_state_t	*arc_mru;
63244cb6abcSbmc static arc_state_t	*arc_mru_ghost;
63344cb6abcSbmc static arc_state_t	*arc_mfu;
63444cb6abcSbmc static arc_state_t	*arc_mfu_ghost;
635fa94a07fSbrendan static arc_state_t	*arc_l2c_only;
63644cb6abcSbmc 
63744cb6abcSbmc /*
63844cb6abcSbmc  * There are several ARC variables that are critical to export as kstats --
63944cb6abcSbmc  * but we don't want to have to grovel around in the kstat whenever we wish to
64044cb6abcSbmc  * manipulate them.  For these variables, we therefore define them to be in
64144cb6abcSbmc  * terms of the statistic variable.  This assures that we are not introducing
64244cb6abcSbmc  * the possibility of inconsistency by having shadow copies of the variables,
64344cb6abcSbmc  * while still allowing the code to be readable.
64444cb6abcSbmc  */
64544cb6abcSbmc #define	arc_size	ARCSTAT(arcstat_size)	/* actual total arc size */
64644cb6abcSbmc #define	arc_p		ARCSTAT(arcstat_p)	/* target size of MRU */
64744cb6abcSbmc #define	arc_c		ARCSTAT(arcstat_c)	/* target size of cache */
64844cb6abcSbmc #define	arc_c_min	ARCSTAT(arcstat_c_min)	/* min target cache size */
64944cb6abcSbmc #define	arc_c_max	ARCSTAT(arcstat_c_max)	/* max target cache size */
65020128a08SGeorge Wilson #define	arc_meta_limit	ARCSTAT(arcstat_meta_limit) /* max size for metadata */
6513a5286a1SMatthew Ahrens #define	arc_meta_min	ARCSTAT(arcstat_meta_min) /* min size for metadata */
65220128a08SGeorge Wilson #define	arc_meta_used	ARCSTAT(arcstat_meta_used) /* size of metadata */
65320128a08SGeorge Wilson #define	arc_meta_max	ARCSTAT(arcstat_meta_max) /* max size of metadata */
65444cb6abcSbmc 
655aad02571SSaso Kiselkov #define	L2ARC_IS_VALID_COMPRESS(_c_) \
656aad02571SSaso Kiselkov 	((_c_) == ZIO_COMPRESS_LZ4 || (_c_) == ZIO_COMPRESS_EMPTY)
657aad02571SSaso Kiselkov 
65844cb6abcSbmc static int		arc_no_grow;	/* Don't try to grow cache size */
659fa9e4066Sahrens static uint64_t		arc_tempreserve;
6602fdbea25SAleksandr Guzovskiy static uint64_t		arc_loaned_bytes;
661fa9e4066Sahrens 
662fa9e4066Sahrens typedef struct arc_callback arc_callback_t;
663fa9e4066Sahrens 
664fa9e4066Sahrens struct arc_callback {
665fa9e4066Sahrens 	void			*acb_private;
666c717a561Smaybee 	arc_done_func_t		*acb_done;
667fa9e4066Sahrens 	arc_buf_t		*acb_buf;
668fa9e4066Sahrens 	zio_t			*acb_zio_dummy;
669fa9e4066Sahrens 	arc_callback_t		*acb_next;
670fa9e4066Sahrens };
671fa9e4066Sahrens 
672c717a561Smaybee typedef struct arc_write_callback arc_write_callback_t;
673c717a561Smaybee 
674c717a561Smaybee struct arc_write_callback {
675c717a561Smaybee 	void		*awcb_private;
676c717a561Smaybee 	arc_done_func_t	*awcb_ready;
67769962b56SMatthew Ahrens 	arc_done_func_t	*awcb_physdone;
678c717a561Smaybee 	arc_done_func_t	*awcb_done;
679c717a561Smaybee 	arc_buf_t	*awcb_buf;
680c717a561Smaybee };
681c717a561Smaybee 
68289c86e32SChris Williamson /*
68389c86e32SChris Williamson  * ARC buffers are separated into multiple structs as a memory saving measure:
68489c86e32SChris Williamson  *   - Common fields struct, always defined, and embedded within it:
68589c86e32SChris Williamson  *       - L2-only fields, always allocated but undefined when not in L2ARC
68689c86e32SChris Williamson  *       - L1-only fields, only allocated when in L1ARC
68789c86e32SChris Williamson  *
68889c86e32SChris Williamson  *           Buffer in L1                     Buffer only in L2
68989c86e32SChris Williamson  *    +------------------------+          +------------------------+
69089c86e32SChris Williamson  *    | arc_buf_hdr_t          |          | arc_buf_hdr_t          |
69189c86e32SChris Williamson  *    |                        |          |                        |
69289c86e32SChris Williamson  *    |                        |          |                        |
69389c86e32SChris Williamson  *    |                        |          |                        |
69489c86e32SChris Williamson  *    +------------------------+          +------------------------+
69589c86e32SChris Williamson  *    | l2arc_buf_hdr_t        |          | l2arc_buf_hdr_t        |
69689c86e32SChris Williamson  *    | (undefined if L1-only) |          |                        |
69789c86e32SChris Williamson  *    +------------------------+          +------------------------+
69889c86e32SChris Williamson  *    | l1arc_buf_hdr_t        |
69989c86e32SChris Williamson  *    |                        |
70089c86e32SChris Williamson  *    |                        |
70189c86e32SChris Williamson  *    |                        |
70289c86e32SChris Williamson  *    |                        |
70389c86e32SChris Williamson  *    +------------------------+
70489c86e32SChris Williamson  *
70589c86e32SChris Williamson  * Because it's possible for the L2ARC to become extremely large, we can wind
70689c86e32SChris Williamson  * up eating a lot of memory in L2ARC buffer headers, so the size of a header
70789c86e32SChris Williamson  * is minimized by only allocating the fields necessary for an L1-cached buffer
70889c86e32SChris Williamson  * when a header is actually in the L1 cache. The sub-headers (l1arc_buf_hdr and
70989c86e32SChris Williamson  * l2arc_buf_hdr) are embedded rather than allocated separately to save a couple
71089c86e32SChris Williamson  * words in pointers. arc_hdr_realloc() is used to switch a header between
71189c86e32SChris Williamson  * these two allocation states.
71289c86e32SChris Williamson  */
71389c86e32SChris Williamson typedef struct l1arc_buf_hdr {
7146b4acc8bSahrens 	kmutex_t		b_freeze_lock;
71589c86e32SChris Williamson #ifdef ZFS_DEBUG
71689c86e32SChris Williamson 	/*
71789c86e32SChris Williamson 	 * used for debugging wtih kmem_flags - by allocating and freeing
71889c86e32SChris Williamson 	 * b_thawed when the buffer is thawed, we get a record of the stack
71989c86e32SChris Williamson 	 * trace that thawed it.
72089c86e32SChris Williamson 	 */
7213f9d6ad7SLin Ling 	void			*b_thawed;
72289c86e32SChris Williamson #endif
7236b4acc8bSahrens 
724fa9e4066Sahrens 	arc_buf_t		*b_buf;
725ea8dc4b6Seschrock 	uint32_t		b_datacnt;
72689c86e32SChris Williamson 	/* for waiting on writes to complete */
727ad23a2dbSjohansen 	kcondvar_t		b_cv;
728ad23a2dbSjohansen 
729fa9e4066Sahrens 	/* protected by arc state mutex */
730fa9e4066Sahrens 	arc_state_t		*b_state;
731244781f1SPrakash Surya 	multilist_node_t	b_arc_node;
732fa9e4066Sahrens 
733fa9e4066Sahrens 	/* updated atomically */
734fa9e4066Sahrens 	clock_t			b_arc_access;
735fa9e4066Sahrens 
736fa9e4066Sahrens 	/* self protecting */
737fa9e4066Sahrens 	refcount_t		b_refcnt;
738fa94a07fSbrendan 
73989c86e32SChris Williamson 	arc_callback_t		*b_acb;
74089c86e32SChris Williamson 	/* temporary buffer holder for in-flight compressed data */
74189c86e32SChris Williamson 	void			*b_tmp_cdata;
74289c86e32SChris Williamson } l1arc_buf_hdr_t;
74389c86e32SChris Williamson 
74489c86e32SChris Williamson typedef struct l2arc_dev l2arc_dev_t;
74589c86e32SChris Williamson 
74689c86e32SChris Williamson typedef struct l2arc_buf_hdr {
74789c86e32SChris Williamson 	/* protected by arc_buf_hdr mutex */
74889c86e32SChris Williamson 	l2arc_dev_t		*b_dev;		/* L2ARC device */
74989c86e32SChris Williamson 	uint64_t		b_daddr;	/* disk address, offset byte */
75089c86e32SChris Williamson 	/* real alloc'd buffer size depending on b_compress applied */
75189c86e32SChris Williamson 	int32_t			b_asize;
752d4cd038cSArne Jansen 	uint8_t			b_compress;
75389c86e32SChris Williamson 
754fa94a07fSbrendan 	list_node_t		b_l2node;
75589c86e32SChris Williamson } l2arc_buf_hdr_t;
75689c86e32SChris Williamson 
75789c86e32SChris Williamson struct arc_buf_hdr {
75889c86e32SChris Williamson 	/* protected by hash lock */
75989c86e32SChris Williamson 	dva_t			b_dva;
76089c86e32SChris Williamson 	uint64_t		b_birth;
76189c86e32SChris Williamson 	/*
76289c86e32SChris Williamson 	 * Even though this checksum is only set/verified when a buffer is in
76389c86e32SChris Williamson 	 * the L1 cache, it needs to be in the set of common fields because it
76489c86e32SChris Williamson 	 * must be preserved from the time before a buffer is written out to
76589c86e32SChris Williamson 	 * L2ARC until after it is read back in.
76689c86e32SChris Williamson 	 */
76789c86e32SChris Williamson 	zio_cksum_t		*b_freeze_cksum;
76889c86e32SChris Williamson 
76989c86e32SChris Williamson 	arc_buf_hdr_t		*b_hash_next;
77089c86e32SChris Williamson 	arc_flags_t		b_flags;
77189c86e32SChris Williamson 
77289c86e32SChris Williamson 	/* immutable */
77389c86e32SChris Williamson 	int32_t			b_size;
77489c86e32SChris Williamson 	uint64_t		b_spa;
77589c86e32SChris Williamson 
77689c86e32SChris Williamson 	/* L2ARC fields. Undefined when not in L2ARC. */
77789c86e32SChris Williamson 	l2arc_buf_hdr_t		b_l2hdr;
77889c86e32SChris Williamson 	/* L1ARC fields. Undefined when in l2arc_only state */
77989c86e32SChris Williamson 	l1arc_buf_hdr_t		b_l1hdr;
780fa9e4066Sahrens };
781fa9e4066Sahrens 
782ea8dc4b6Seschrock static arc_buf_t *arc_eviction_list;
78340d7d650Smaybee static arc_buf_hdr_t arc_eviction_hdr;
7845ea40c06SBrendan Gregg - Sun Microsystems 
785ea8dc4b6Seschrock #define	GHOST_STATE(state)	\
786fa94a07fSbrendan 	((state) == arc_mru_ghost || (state) == arc_mfu_ghost ||	\
787fa94a07fSbrendan 	(state) == arc_l2c_only)
788ea8dc4b6Seschrock 
7897adb730bSGeorge Wilson #define	HDR_IN_HASH_TABLE(hdr)	((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
7907adb730bSGeorge Wilson #define	HDR_IO_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
7917adb730bSGeorge Wilson #define	HDR_IO_ERROR(hdr)	((hdr)->b_flags & ARC_FLAG_IO_ERROR)
7927adb730bSGeorge Wilson #define	HDR_PREFETCH(hdr)	((hdr)->b_flags & ARC_FLAG_PREFETCH)
7937adb730bSGeorge Wilson #define	HDR_FREED_IN_READ(hdr)	((hdr)->b_flags & ARC_FLAG_FREED_IN_READ)
7947adb730bSGeorge Wilson #define	HDR_BUF_AVAILABLE(hdr)	((hdr)->b_flags & ARC_FLAG_BUF_AVAILABLE)
79589c86e32SChris Williamson 
7967adb730bSGeorge Wilson #define	HDR_L2CACHE(hdr)	((hdr)->b_flags & ARC_FLAG_L2CACHE)
79789c86e32SChris Williamson #define	HDR_L2COMPRESS(hdr)	((hdr)->b_flags & ARC_FLAG_L2COMPRESS)
7987adb730bSGeorge Wilson #define	HDR_L2_READING(hdr)	\
79989c86e32SChris Williamson 	    (((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) &&	\
80089c86e32SChris Williamson 	    ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
8017adb730bSGeorge Wilson #define	HDR_L2_WRITING(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITING)
8027adb730bSGeorge Wilson #define	HDR_L2_EVICTED(hdr)	((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
8037adb730bSGeorge Wilson #define	HDR_L2_WRITE_HEAD(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
804fa9e4066Sahrens 
80589c86e32SChris Williamson #define	HDR_ISTYPE_METADATA(hdr)	\
80689c86e32SChris Williamson 	    ((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
80789c86e32SChris Williamson #define	HDR_ISTYPE_DATA(hdr)	(!HDR_ISTYPE_METADATA(hdr))
80889c86e32SChris Williamson 
80989c86e32SChris Williamson #define	HDR_HAS_L1HDR(hdr)	((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
81089c86e32SChris Williamson #define	HDR_HAS_L2HDR(hdr)	((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
81189c86e32SChris Williamson 
812fa9e4066Sahrens /*
813e6c728e1Sbrendan  * Other sizes
814e6c728e1Sbrendan  */
815e6c728e1Sbrendan 
81689c86e32SChris Williamson #define	HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
81789c86e32SChris Williamson #define	HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
818e6c728e1Sbrendan 
819e6c728e1Sbrendan /*
820fa9e4066Sahrens  * Hash table routines
821fa9e4066Sahrens  */
822fa9e4066Sahrens 
823fa9e4066Sahrens #define	HT_LOCK_PAD	64
824fa9e4066Sahrens 
825fa9e4066Sahrens struct ht_lock {
826fa9e4066Sahrens 	kmutex_t	ht_lock;
827fa9e4066Sahrens #ifdef _KERNEL
828fa9e4066Sahrens 	unsigned char	pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
829fa9e4066Sahrens #endif
830fa9e4066Sahrens };
831fa9e4066Sahrens 
832fa9e4066Sahrens #define	BUF_LOCKS 256
833fa9e4066Sahrens typedef struct buf_hash_table {
834fa9e4066Sahrens 	uint64_t ht_mask;
835fa9e4066Sahrens 	arc_buf_hdr_t **ht_table;
836fa9e4066Sahrens 	struct ht_lock ht_locks[BUF_LOCKS];
837fa9e4066Sahrens } buf_hash_table_t;
838fa9e4066Sahrens 
839fa9e4066Sahrens static buf_hash_table_t buf_hash_table;
840fa9e4066Sahrens 
841fa9e4066Sahrens #define	BUF_HASH_INDEX(spa, dva, birth) \
842fa9e4066Sahrens 	(buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
843fa9e4066Sahrens #define	BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
844fa9e4066Sahrens #define	BUF_HASH_LOCK(idx)	(&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
8453f9d6ad7SLin Ling #define	HDR_LOCK(hdr) \
8463f9d6ad7SLin Ling 	(BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
847fa9e4066Sahrens 
848fa9e4066Sahrens uint64_t zfs_crc64_table[256];
849fa9e4066Sahrens 
850fa94a07fSbrendan /*
851fa94a07fSbrendan  * Level 2 ARC
852fa94a07fSbrendan  */
853fa94a07fSbrendan 
854fa94a07fSbrendan #define	L2ARC_WRITE_SIZE	(8 * 1024 * 1024)	/* initial write max */
8555a98e54bSBrendan Gregg - Sun Microsystems #define	L2ARC_HEADROOM		2			/* num of writes */
856aad02571SSaso Kiselkov /*
857aad02571SSaso Kiselkov  * If we discover during ARC scan any buffers to be compressed, we boost
858aad02571SSaso Kiselkov  * our headroom for the next scanning cycle by this percentage multiple.
859aad02571SSaso Kiselkov  */
860aad02571SSaso Kiselkov #define	L2ARC_HEADROOM_BOOST	200
8615a98e54bSBrendan Gregg - Sun Microsystems #define	L2ARC_FEED_SECS		1		/* caching interval secs */
8625a98e54bSBrendan Gregg - Sun Microsystems #define	L2ARC_FEED_MIN_MS	200		/* min caching interval ms */
863fa94a07fSbrendan 
864a52fc310SPrakash Surya /*
865a52fc310SPrakash Surya  * Used to distinguish headers that are being process by
866a52fc310SPrakash Surya  * l2arc_write_buffers(), but have yet to be assigned to a l2arc disk
867a52fc310SPrakash Surya  * address. This can happen when the header is added to the l2arc's list
868a52fc310SPrakash Surya  * of buffers to write in the first stage of l2arc_write_buffers(), but
869a52fc310SPrakash Surya  * has not yet been written out which happens in the second stage of
870a52fc310SPrakash Surya  * l2arc_write_buffers().
871a52fc310SPrakash Surya  */
872a52fc310SPrakash Surya #define	L2ARC_ADDR_UNSET	((uint64_t)(-1))
873a52fc310SPrakash Surya 
874fa94a07fSbrendan #define	l2arc_writes_sent	ARCSTAT(arcstat_l2_writes_sent)
875fa94a07fSbrendan #define	l2arc_writes_done	ARCSTAT(arcstat_l2_writes_done)
876fa94a07fSbrendan 
877f7170741SWill Andrews /* L2ARC Performance Tunables */
878fa94a07fSbrendan uint64_t l2arc_write_max = L2ARC_WRITE_SIZE;	/* default max write size */
8793a737e0dSbrendan uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE;	/* extra write during warmup */
880fa94a07fSbrendan uint64_t l2arc_headroom = L2ARC_HEADROOM;	/* number of dev writes */
881aad02571SSaso Kiselkov uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
882fa94a07fSbrendan uint64_t l2arc_feed_secs = L2ARC_FEED_SECS;	/* interval seconds */
8835a98e54bSBrendan Gregg - Sun Microsystems uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS;	/* min interval milliseconds */
884fa94a07fSbrendan boolean_t l2arc_noprefetch = B_TRUE;		/* don't cache prefetch bufs */
8855a98e54bSBrendan Gregg - Sun Microsystems boolean_t l2arc_feed_again = B_TRUE;		/* turbo warmup */
8865a98e54bSBrendan Gregg - Sun Microsystems boolean_t l2arc_norw = B_TRUE;			/* no reads during writes */
887fa94a07fSbrendan 
888*5f992543SArne Jansen /*
889*5f992543SArne Jansen  * L2ARC Internals
890*5f992543SArne Jansen  */
891*5f992543SArne Jansen struct l2arc_dev {
892*5f992543SArne Jansen 	vdev_t			*l2ad_vdev;	/* vdev */
893*5f992543SArne Jansen 	spa_t			*l2ad_spa;	/* spa */
894*5f992543SArne Jansen 	uint64_t		l2ad_hand;	/* next write location */
895*5f992543SArne Jansen 	uint64_t		l2ad_start;	/* first addr on device */
896*5f992543SArne Jansen 	uint64_t		l2ad_end;	/* last addr on device */
897*5f992543SArne Jansen 	boolean_t		l2ad_first;	/* first sweep through */
898*5f992543SArne Jansen 	boolean_t		l2ad_writing;	/* currently writing */
899*5f992543SArne Jansen 	kmutex_t		l2ad_mtx;	/* lock for buffer list */
900*5f992543SArne Jansen 	list_t			l2ad_buflist;	/* buffer list */
901*5f992543SArne Jansen 	list_node_t		l2ad_node;	/* device list node */
902*5f992543SArne Jansen 	refcount_t		l2ad_alloc;	/* allocated bytes */
903*5f992543SArne Jansen };
904*5f992543SArne Jansen 
905fa94a07fSbrendan static list_t L2ARC_dev_list;			/* device list */
906fa94a07fSbrendan static list_t *l2arc_dev_list;			/* device list pointer */
907fa94a07fSbrendan static kmutex_t l2arc_dev_mtx;			/* device list mutex */
908fa94a07fSbrendan static l2arc_dev_t *l2arc_dev_last;		/* last device used */
909fa94a07fSbrendan static list_t L2ARC_free_on_write;		/* free after write buf list */
910fa94a07fSbrendan static list_t *l2arc_free_on_write;		/* free after write list ptr */
911fa94a07fSbrendan static kmutex_t l2arc_free_on_write_mtx;	/* mutex for list */
912fa94a07fSbrendan static uint64_t l2arc_ndev;			/* number of devices */
913fa94a07fSbrendan 
914fa94a07fSbrendan typedef struct l2arc_read_callback {
915fa94a07fSbrendan 	arc_buf_t		*l2rcb_buf;		/* read buffer */
916fa94a07fSbrendan 	spa_t			*l2rcb_spa;		/* spa */
917fa94a07fSbrendan 	blkptr_t		l2rcb_bp;		/* original blkptr */
9187802d7bfSMatthew Ahrens 	zbookmark_phys_t	l2rcb_zb;		/* original bookmark */
919fa94a07fSbrendan 	int			l2rcb_flags;		/* original flags */
920aad02571SSaso Kiselkov 	enum zio_compress	l2rcb_compress;		/* applied compress */
921fa94a07fSbrendan } l2arc_read_callback_t;
922fa94a07fSbrendan 
923fa94a07fSbrendan typedef struct l2arc_write_callback {
924fa94a07fSbrendan 	l2arc_dev_t	*l2wcb_dev;		/* device info */
925fa94a07fSbrendan 	arc_buf_hdr_t	*l2wcb_head;		/* head of write buflist */
926fa94a07fSbrendan } l2arc_write_callback_t;
927fa94a07fSbrendan 
928fa94a07fSbrendan typedef struct l2arc_data_free {
929fa94a07fSbrendan 	/* protected by l2arc_free_on_write_mtx */
930fa94a07fSbrendan 	void		*l2df_data;
931fa94a07fSbrendan 	size_t		l2df_size;
932fa94a07fSbrendan 	void		(*l2df_func)(void *, size_t);
933fa94a07fSbrendan 	list_node_t	l2df_list_node;
934fa94a07fSbrendan } l2arc_data_free_t;
935fa94a07fSbrendan 
936fa94a07fSbrendan static kmutex_t l2arc_feed_thr_lock;
937fa94a07fSbrendan static kcondvar_t l2arc_feed_thr_cv;
938fa94a07fSbrendan static uint8_t l2arc_thread_exit;
939fa94a07fSbrendan 
9407adb730bSGeorge Wilson static void arc_get_data_buf(arc_buf_t *);
9417adb730bSGeorge Wilson static void arc_access(arc_buf_hdr_t *, kmutex_t *);
942244781f1SPrakash Surya static boolean_t arc_is_overflowing();
9437adb730bSGeorge Wilson static void arc_buf_watch(arc_buf_t *);
9447adb730bSGeorge Wilson 
94589c86e32SChris Williamson static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
94689c86e32SChris Williamson static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
94789c86e32SChris Williamson 
948f5ca7025SSaso Kiselkov static boolean_t l2arc_write_eligible(uint64_t, uint64_t, arc_buf_hdr_t *);
9497adb730bSGeorge Wilson static void l2arc_read_done(zio_t *);
950fa94a07fSbrendan 
95189c86e32SChris Williamson static boolean_t l2arc_compress_buf(arc_buf_hdr_t *);
9527adb730bSGeorge Wilson static void l2arc_decompress_zio(zio_t *, arc_buf_hdr_t *, enum zio_compress);
9537adb730bSGeorge Wilson static void l2arc_release_cdata_buf(arc_buf_hdr_t *);
954aad02571SSaso Kiselkov 
955*5f992543SArne Jansen static uint64_t
956ac05c741SMark Maybee buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
957fa9e4066Sahrens {
958fa9e4066Sahrens 	uint8_t *vdva = (uint8_t *)dva;
959fa9e4066Sahrens 	uint64_t crc = -1ULL;
960fa9e4066Sahrens 	int i;
961fa9e4066Sahrens 
962fa9e4066Sahrens 	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
963fa9e4066Sahrens 
964fa9e4066Sahrens 	for (i = 0; i < sizeof (dva_t); i++)
965fa9e4066Sahrens 		crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
966fa9e4066Sahrens 
967ac05c741SMark Maybee 	crc ^= (spa>>8) ^ birth;
968fa9e4066Sahrens 
969fa9e4066Sahrens 	return (crc);
970fa9e4066Sahrens }
971fa9e4066Sahrens 
972fa9e4066Sahrens #define	BUF_EMPTY(buf)						\
973fa9e4066Sahrens 	((buf)->b_dva.dva_word[0] == 0 &&			\
97489c86e32SChris Williamson 	(buf)->b_dva.dva_word[1] == 0)
975fa9e4066Sahrens 
976fa9e4066Sahrens #define	BUF_EQUAL(spa, dva, birth, buf)				\
977fa9e4066Sahrens 	((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) &&	\
978fa9e4066Sahrens 	((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) &&	\
979fa9e4066Sahrens 	((buf)->b_birth == birth) && ((buf)->b_spa == spa)
980fa9e4066Sahrens 
9813f9d6ad7SLin Ling static void
9823f9d6ad7SLin Ling buf_discard_identity(arc_buf_hdr_t *hdr)
9833f9d6ad7SLin Ling {
9843f9d6ad7SLin Ling 	hdr->b_dva.dva_word[0] = 0;
9853f9d6ad7SLin Ling 	hdr->b_dva.dva_word[1] = 0;
9863f9d6ad7SLin Ling 	hdr->b_birth = 0;
9873f9d6ad7SLin Ling }
9883f9d6ad7SLin Ling 
989fa9e4066Sahrens static arc_buf_hdr_t *
9905d7b4d43SMatthew Ahrens buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
991fa9e4066Sahrens {
9925d7b4d43SMatthew Ahrens 	const dva_t *dva = BP_IDENTITY(bp);
9935d7b4d43SMatthew Ahrens 	uint64_t birth = BP_PHYSICAL_BIRTH(bp);
994fa9e4066Sahrens 	uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
995fa9e4066Sahrens 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
9967adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr;
997fa9e4066Sahrens 
998fa9e4066Sahrens 	mutex_enter(hash_lock);
9997adb730bSGeorge Wilson 	for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
10007adb730bSGeorge Wilson 	    hdr = hdr->b_hash_next) {
10017adb730bSGeorge Wilson 		if (BUF_EQUAL(spa, dva, birth, hdr)) {
1002fa9e4066Sahrens 			*lockp = hash_lock;
10037adb730bSGeorge Wilson 			return (hdr);
1004fa9e4066Sahrens 		}
1005fa9e4066Sahrens 	}
1006fa9e4066Sahrens 	mutex_exit(hash_lock);
1007fa9e4066Sahrens 	*lockp = NULL;
1008fa9e4066Sahrens 	return (NULL);
1009fa9e4066Sahrens }
1010fa9e4066Sahrens 
1011fa9e4066Sahrens /*
1012fa9e4066Sahrens  * Insert an entry into the hash table.  If there is already an element
1013fa9e4066Sahrens  * equal to elem in the hash table, then the already existing element
1014fa9e4066Sahrens  * will be returned and the new element will not be inserted.
1015fa9e4066Sahrens  * Otherwise returns NULL.
101689c86e32SChris Williamson  * If lockp == NULL, the caller is assumed to already hold the hash lock.
1017fa9e4066Sahrens  */
1018fa9e4066Sahrens static arc_buf_hdr_t *
10197adb730bSGeorge Wilson buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1020fa9e4066Sahrens {
10217adb730bSGeorge Wilson 	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1022fa9e4066Sahrens 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
10237adb730bSGeorge Wilson 	arc_buf_hdr_t *fhdr;
102444cb6abcSbmc 	uint32_t i;
1025fa9e4066Sahrens 
10267adb730bSGeorge Wilson 	ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
10277adb730bSGeorge Wilson 	ASSERT(hdr->b_birth != 0);
10287adb730bSGeorge Wilson 	ASSERT(!HDR_IN_HASH_TABLE(hdr));
102989c86e32SChris Williamson 
103089c86e32SChris Williamson 	if (lockp != NULL) {
1031fa9e4066Sahrens 		*lockp = hash_lock;
1032fa9e4066Sahrens 		mutex_enter(hash_lock);
103389c86e32SChris Williamson 	} else {
103489c86e32SChris Williamson 		ASSERT(MUTEX_HELD(hash_lock));
103589c86e32SChris Williamson 	}
103689c86e32SChris Williamson 
10377adb730bSGeorge Wilson 	for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
10387adb730bSGeorge Wilson 	    fhdr = fhdr->b_hash_next, i++) {
10397adb730bSGeorge Wilson 		if (BUF_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
10407adb730bSGeorge Wilson 			return (fhdr);
1041fa9e4066Sahrens 	}
1042fa9e4066Sahrens 
10437adb730bSGeorge Wilson 	hdr->b_hash_next = buf_hash_table.ht_table[idx];
10447adb730bSGeorge Wilson 	buf_hash_table.ht_table[idx] = hdr;
10457adb730bSGeorge Wilson 	hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
1046fa9e4066Sahrens 
1047fa9e4066Sahrens 	/* collect some hash table performance data */
1048fa9e4066Sahrens 	if (i > 0) {
104944cb6abcSbmc 		ARCSTAT_BUMP(arcstat_hash_collisions);
1050fa9e4066Sahrens 		if (i == 1)
105144cb6abcSbmc 			ARCSTAT_BUMP(arcstat_hash_chains);
105244cb6abcSbmc 
105344cb6abcSbmc 		ARCSTAT_MAX(arcstat_hash_chain_max, i);
1054fa9e4066Sahrens 	}
105544cb6abcSbmc 
105644cb6abcSbmc 	ARCSTAT_BUMP(arcstat_hash_elements);
105744cb6abcSbmc 	ARCSTAT_MAXSTAT(arcstat_hash_elements);
1058fa9e4066Sahrens 
1059fa9e4066Sahrens 	return (NULL);
1060fa9e4066Sahrens }
1061fa9e4066Sahrens 
1062fa9e4066Sahrens static void
10637adb730bSGeorge Wilson buf_hash_remove(arc_buf_hdr_t *hdr)
1064fa9e4066Sahrens {
10657adb730bSGeorge Wilson 	arc_buf_hdr_t *fhdr, **hdrp;
10667adb730bSGeorge Wilson 	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1067fa9e4066Sahrens 
1068fa9e4066Sahrens 	ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
10697adb730bSGeorge Wilson 	ASSERT(HDR_IN_HASH_TABLE(hdr));
1070fa9e4066Sahrens 
10717adb730bSGeorge Wilson 	hdrp = &buf_hash_table.ht_table[idx];
10727adb730bSGeorge Wilson 	while ((fhdr = *hdrp) != hdr) {
10737adb730bSGeorge Wilson 		ASSERT(fhdr != NULL);
10747adb730bSGeorge Wilson 		hdrp = &fhdr->b_hash_next;
1075fa9e4066Sahrens 	}
10767adb730bSGeorge Wilson 	*hdrp = hdr->b_hash_next;
10777adb730bSGeorge Wilson 	hdr->b_hash_next = NULL;
10787adb730bSGeorge Wilson 	hdr->b_flags &= ~ARC_FLAG_IN_HASH_TABLE;
1079fa9e4066Sahrens 
1080fa9e4066Sahrens 	/* collect some hash table performance data */
108144cb6abcSbmc 	ARCSTAT_BUMPDOWN(arcstat_hash_elements);
108244cb6abcSbmc 
1083fa9e4066Sahrens 	if (buf_hash_table.ht_table[idx] &&
1084fa9e4066Sahrens 	    buf_hash_table.ht_table[idx]->b_hash_next == NULL)
108544cb6abcSbmc 		ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1086fa9e4066Sahrens }
1087fa9e4066Sahrens 
1088fa9e4066Sahrens /*
1089fa9e4066Sahrens  * Global data structures and functions for the buf kmem cache.
1090fa9e4066Sahrens  */
109189c86e32SChris Williamson static kmem_cache_t *hdr_full_cache;
109289c86e32SChris Williamson static kmem_cache_t *hdr_l2only_cache;
1093fa9e4066Sahrens static kmem_cache_t *buf_cache;
1094fa9e4066Sahrens 
1095fa9e4066Sahrens static void
1096fa9e4066Sahrens buf_fini(void)
1097fa9e4066Sahrens {
1098fa9e4066Sahrens 	int i;
1099fa9e4066Sahrens 
1100fa9e4066Sahrens 	kmem_free(buf_hash_table.ht_table,
1101fa9e4066Sahrens 	    (buf_hash_table.ht_mask + 1) * sizeof (void *));
1102fa9e4066Sahrens 	for (i = 0; i < BUF_LOCKS; i++)
1103fa9e4066Sahrens 		mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
110489c86e32SChris Williamson 	kmem_cache_destroy(hdr_full_cache);
110589c86e32SChris Williamson 	kmem_cache_destroy(hdr_l2only_cache);
1106fa9e4066Sahrens 	kmem_cache_destroy(buf_cache);
1107fa9e4066Sahrens }
1108fa9e4066Sahrens 
1109fa9e4066Sahrens /*
1110fa9e4066Sahrens  * Constructor callback - called when the cache is empty
1111fa9e4066Sahrens  * and a new buf is requested.
1112fa9e4066Sahrens  */
1113fa9e4066Sahrens /* ARGSUSED */
1114fa9e4066Sahrens static int
111589c86e32SChris Williamson hdr_full_cons(void *vbuf, void *unused, int kmflag)
1116fa9e4066Sahrens {
11177adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr = vbuf;
1118fa9e4066Sahrens 
111989c86e32SChris Williamson 	bzero(hdr, HDR_FULL_SIZE);
112089c86e32SChris Williamson 	cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
112189c86e32SChris Williamson 	refcount_create(&hdr->b_l1hdr.b_refcnt);
112289c86e32SChris Williamson 	mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1123244781f1SPrakash Surya 	multilist_link_init(&hdr->b_l1hdr.b_arc_node);
112489c86e32SChris Williamson 	arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
112589c86e32SChris Williamson 
112689c86e32SChris Williamson 	return (0);
112789c86e32SChris Williamson }
112889c86e32SChris Williamson 
112989c86e32SChris Williamson /* ARGSUSED */
113089c86e32SChris Williamson static int
113189c86e32SChris Williamson hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
113289c86e32SChris Williamson {
113389c86e32SChris Williamson 	arc_buf_hdr_t *hdr = vbuf;
113489c86e32SChris Williamson 
113589c86e32SChris Williamson 	bzero(hdr, HDR_L2ONLY_SIZE);
113689c86e32SChris Williamson 	arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1137fa94a07fSbrendan 
1138fa9e4066Sahrens 	return (0);
1139fa9e4066Sahrens }
1140fa9e4066Sahrens 
11416f83844dSMark Maybee /* ARGSUSED */
11426f83844dSMark Maybee static int
11436f83844dSMark Maybee buf_cons(void *vbuf, void *unused, int kmflag)
11446f83844dSMark Maybee {
11456f83844dSMark Maybee 	arc_buf_t *buf = vbuf;
11466f83844dSMark Maybee 
11476f83844dSMark Maybee 	bzero(buf, sizeof (arc_buf_t));
11483f9d6ad7SLin Ling 	mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
11495a98e54bSBrendan Gregg - Sun Microsystems 	arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
11505a98e54bSBrendan Gregg - Sun Microsystems 
11516f83844dSMark Maybee 	return (0);
11526f83844dSMark Maybee }
11536f83844dSMark Maybee 
1154fa9e4066Sahrens /*
1155fa9e4066Sahrens  * Destructor callback - called when a cached buf is
1156fa9e4066Sahrens  * no longer required.
1157fa9e4066Sahrens  */
1158fa9e4066Sahrens /* ARGSUSED */
1159fa9e4066Sahrens static void
116089c86e32SChris Williamson hdr_full_dest(void *vbuf, void *unused)
1161fa9e4066Sahrens {
11627adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr = vbuf;
1163fa9e4066Sahrens 
11647adb730bSGeorge Wilson 	ASSERT(BUF_EMPTY(hdr));
116589c86e32SChris Williamson 	cv_destroy(&hdr->b_l1hdr.b_cv);
116689c86e32SChris Williamson 	refcount_destroy(&hdr->b_l1hdr.b_refcnt);
116789c86e32SChris Williamson 	mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1168244781f1SPrakash Surya 	ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
116989c86e32SChris Williamson 	arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
117089c86e32SChris Williamson }
117189c86e32SChris Williamson 
117289c86e32SChris Williamson /* ARGSUSED */
117389c86e32SChris Williamson static void
117489c86e32SChris Williamson hdr_l2only_dest(void *vbuf, void *unused)
117589c86e32SChris Williamson {
117689c86e32SChris Williamson 	arc_buf_hdr_t *hdr = vbuf;
117789c86e32SChris Williamson 
117889c86e32SChris Williamson 	ASSERT(BUF_EMPTY(hdr));
117989c86e32SChris Williamson 	arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1180fa9e4066Sahrens }
1181fa9e4066Sahrens 
11826f83844dSMark Maybee /* ARGSUSED */
11836f83844dSMark Maybee static void
11846f83844dSMark Maybee buf_dest(void *vbuf, void *unused)
11856f83844dSMark Maybee {
11866f83844dSMark Maybee 	arc_buf_t *buf = vbuf;
11876f83844dSMark Maybee 
11883f9d6ad7SLin Ling 	mutex_destroy(&buf->b_evict_lock);
11895a98e54bSBrendan Gregg - Sun Microsystems 	arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
11906f83844dSMark Maybee }
11916f83844dSMark Maybee 
1192fa9e4066Sahrens /*
1193fa9e4066Sahrens  * Reclaim callback -- invoked when memory is low.
1194fa9e4066Sahrens  */
1195fa9e4066Sahrens /* ARGSUSED */
1196fa9e4066Sahrens static void
1197fa9e4066Sahrens hdr_recl(void *unused)
1198fa9e4066Sahrens {
1199fa9e4066Sahrens 	dprintf("hdr_recl called\n");
120049e3519aSmaybee 	/*
120149e3519aSmaybee 	 * umem calls the reclaim func when we destroy the buf cache,
120249e3519aSmaybee 	 * which is after we do arc_fini().
120349e3519aSmaybee 	 */
120449e3519aSmaybee 	if (!arc_dead)
1205244781f1SPrakash Surya 		cv_signal(&arc_reclaim_thread_cv);
1206fa9e4066Sahrens }
1207fa9e4066Sahrens 
1208fa9e4066Sahrens static void
1209fa9e4066Sahrens buf_init(void)
1210fa9e4066Sahrens {
1211fa9e4066Sahrens 	uint64_t *ct;
1212ea8dc4b6Seschrock 	uint64_t hsize = 1ULL << 12;
1213fa9e4066Sahrens 	int i, j;
1214fa9e4066Sahrens 
1215fa9e4066Sahrens 	/*
1216fa9e4066Sahrens 	 * The hash table is big enough to fill all of physical memory
121763e911b6SMatthew Ahrens 	 * with an average block size of zfs_arc_average_blocksize (default 8K).
121863e911b6SMatthew Ahrens 	 * By default, the table will take up
121963e911b6SMatthew Ahrens 	 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1220fa9e4066Sahrens 	 */
122163e911b6SMatthew Ahrens 	while (hsize * zfs_arc_average_blocksize < physmem * PAGESIZE)
1222fa9e4066Sahrens 		hsize <<= 1;
1223ea8dc4b6Seschrock retry:
1224fa9e4066Sahrens 	buf_hash_table.ht_mask = hsize - 1;
1225ea8dc4b6Seschrock 	buf_hash_table.ht_table =
1226ea8dc4b6Seschrock 	    kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1227ea8dc4b6Seschrock 	if (buf_hash_table.ht_table == NULL) {
1228ea8dc4b6Seschrock 		ASSERT(hsize > (1ULL << 8));
1229ea8dc4b6Seschrock 		hsize >>= 1;
1230ea8dc4b6Seschrock 		goto retry;
1231ea8dc4b6Seschrock 	}
1232fa9e4066Sahrens 
123389c86e32SChris Williamson 	hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
123489c86e32SChris Williamson 	    0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
123589c86e32SChris Williamson 	hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
123689c86e32SChris Williamson 	    HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
123789c86e32SChris Williamson 	    NULL, NULL, 0);
1238fa9e4066Sahrens 	buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
12396f83844dSMark Maybee 	    0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1240fa9e4066Sahrens 
1241fa9e4066Sahrens 	for (i = 0; i < 256; i++)
1242fa9e4066Sahrens 		for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1243fa9e4066Sahrens 			*ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1244fa9e4066Sahrens 
1245fa9e4066Sahrens 	for (i = 0; i < BUF_LOCKS; i++) {
1246fa9e4066Sahrens 		mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1247fa9e4066Sahrens 		    NULL, MUTEX_DEFAULT, NULL);
1248fa9e4066Sahrens 	}
1249fa9e4066Sahrens }
1250fa9e4066Sahrens 
125189c86e32SChris Williamson /*
125289c86e32SChris Williamson  * Transition between the two allocation states for the arc_buf_hdr struct.
125389c86e32SChris Williamson  * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
125489c86e32SChris Williamson  * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
125589c86e32SChris Williamson  * version is used when a cache buffer is only in the L2ARC in order to reduce
125689c86e32SChris Williamson  * memory usage.
125789c86e32SChris Williamson  */
125889c86e32SChris Williamson static arc_buf_hdr_t *
125989c86e32SChris Williamson arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
126089c86e32SChris Williamson {
126189c86e32SChris Williamson 	ASSERT(HDR_HAS_L2HDR(hdr));
126289c86e32SChris Williamson 
126389c86e32SChris Williamson 	arc_buf_hdr_t *nhdr;
126489c86e32SChris Williamson 	l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
126589c86e32SChris Williamson 
126689c86e32SChris Williamson 	ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
126789c86e32SChris Williamson 	    (old == hdr_l2only_cache && new == hdr_full_cache));
126889c86e32SChris Williamson 
126989c86e32SChris Williamson 	nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
127089c86e32SChris Williamson 
127189c86e32SChris Williamson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
127289c86e32SChris Williamson 	buf_hash_remove(hdr);
127389c86e32SChris Williamson 
127489c86e32SChris Williamson 	bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
1275a52fc310SPrakash Surya 
127689c86e32SChris Williamson 	if (new == hdr_full_cache) {
127789c86e32SChris Williamson 		nhdr->b_flags |= ARC_FLAG_HAS_L1HDR;
127889c86e32SChris Williamson 		/*
127989c86e32SChris Williamson 		 * arc_access and arc_change_state need to be aware that a
128089c86e32SChris Williamson 		 * header has just come out of L2ARC, so we set its state to
128189c86e32SChris Williamson 		 * l2c_only even though it's about to change.
128289c86e32SChris Williamson 		 */
128389c86e32SChris Williamson 		nhdr->b_l1hdr.b_state = arc_l2c_only;
1284244781f1SPrakash Surya 
1285244781f1SPrakash Surya 		/* Verify previous threads set to NULL before freeing */
1286244781f1SPrakash Surya 		ASSERT3P(nhdr->b_l1hdr.b_tmp_cdata, ==, NULL);
128789c86e32SChris Williamson 	} else {
128889c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_buf == NULL);
128989c86e32SChris Williamson 		ASSERT0(hdr->b_l1hdr.b_datacnt);
1290244781f1SPrakash Surya 
129189c86e32SChris Williamson 		/*
1292244781f1SPrakash Surya 		 * If we've reached here, We must have been called from
1293244781f1SPrakash Surya 		 * arc_evict_hdr(), as such we should have already been
1294244781f1SPrakash Surya 		 * removed from any ghost list we were previously on
1295244781f1SPrakash Surya 		 * (which protects us from racing with arc_evict_state),
1296244781f1SPrakash Surya 		 * thus no locking is needed during this check.
129789c86e32SChris Williamson 		 */
1298244781f1SPrakash Surya 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1299244781f1SPrakash Surya 
1300244781f1SPrakash Surya 		/*
1301244781f1SPrakash Surya 		 * A buffer must not be moved into the arc_l2c_only
1302244781f1SPrakash Surya 		 * state if it's not finished being written out to the
1303244781f1SPrakash Surya 		 * l2arc device. Otherwise, the b_l1hdr.b_tmp_cdata field
1304244781f1SPrakash Surya 		 * might try to be accessed, even though it was removed.
1305244781f1SPrakash Surya 		 */
1306244781f1SPrakash Surya 		VERIFY(!HDR_L2_WRITING(hdr));
1307244781f1SPrakash Surya 		VERIFY3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
1308244781f1SPrakash Surya 
1309c546f36aSArne Jansen #ifdef ZFS_DEBUG
1310c546f36aSArne Jansen 		if (hdr->b_l1hdr.b_thawed != NULL) {
1311c546f36aSArne Jansen 			kmem_free(hdr->b_l1hdr.b_thawed, 1);
1312c546f36aSArne Jansen 			hdr->b_l1hdr.b_thawed = NULL;
1313c546f36aSArne Jansen 		}
1314c546f36aSArne Jansen #endif
1315c546f36aSArne Jansen 
131689c86e32SChris Williamson 		nhdr->b_flags &= ~ARC_FLAG_HAS_L1HDR;
131789c86e32SChris Williamson 	}
131889c86e32SChris Williamson 	/*
131989c86e32SChris Williamson 	 * The header has been reallocated so we need to re-insert it into any
132089c86e32SChris Williamson 	 * lists it was on.
132189c86e32SChris Williamson 	 */
132289c86e32SChris Williamson 	(void) buf_hash_insert(nhdr, NULL);
132389c86e32SChris Williamson 
132489c86e32SChris Williamson 	ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
132589c86e32SChris Williamson 
132689c86e32SChris Williamson 	mutex_enter(&dev->l2ad_mtx);
132789c86e32SChris Williamson 
132889c86e32SChris Williamson 	/*
132989c86e32SChris Williamson 	 * We must place the realloc'ed header back into the list at
133089c86e32SChris Williamson 	 * the same spot. Otherwise, if it's placed earlier in the list,
133189c86e32SChris Williamson 	 * l2arc_write_buffers() could find it during the function's
133289c86e32SChris Williamson 	 * write phase, and try to write it out to the l2arc.
133389c86e32SChris Williamson 	 */
133489c86e32SChris Williamson 	list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
133589c86e32SChris Williamson 	list_remove(&dev->l2ad_buflist, hdr);
133689c86e32SChris Williamson 
133789c86e32SChris Williamson 	mutex_exit(&dev->l2ad_mtx);
133889c86e32SChris Williamson 
1339a52fc310SPrakash Surya 	/*
1340a52fc310SPrakash Surya 	 * Since we're using the pointer address as the tag when
1341a52fc310SPrakash Surya 	 * incrementing and decrementing the l2ad_alloc refcount, we
1342a52fc310SPrakash Surya 	 * must remove the old pointer (that we're about to destroy) and
1343a52fc310SPrakash Surya 	 * add the new pointer to the refcount. Otherwise we'd remove
1344a52fc310SPrakash Surya 	 * the wrong pointer address when calling arc_hdr_destroy() later.
1345a52fc310SPrakash Surya 	 */
1346a52fc310SPrakash Surya 
1347a52fc310SPrakash Surya 	(void) refcount_remove_many(&dev->l2ad_alloc,
1348a52fc310SPrakash Surya 	    hdr->b_l2hdr.b_asize, hdr);
1349a52fc310SPrakash Surya 
1350a52fc310SPrakash Surya 	(void) refcount_add_many(&dev->l2ad_alloc,
1351a52fc310SPrakash Surya 	    nhdr->b_l2hdr.b_asize, nhdr);
1352a52fc310SPrakash Surya 
135389c86e32SChris Williamson 	buf_discard_identity(hdr);
135489c86e32SChris Williamson 	hdr->b_freeze_cksum = NULL;
135589c86e32SChris Williamson 	kmem_cache_free(old, hdr);
135689c86e32SChris Williamson 
135789c86e32SChris Williamson 	return (nhdr);
135889c86e32SChris Williamson }
135989c86e32SChris Williamson 
136089c86e32SChris Williamson 
1361fa9e4066Sahrens #define	ARC_MINTIME	(hz>>4) /* 62 ms */
1362fa9e4066Sahrens 
1363fa9e4066Sahrens static void
13646b4acc8bSahrens arc_cksum_verify(arc_buf_t *buf)
13656b4acc8bSahrens {
13666b4acc8bSahrens 	zio_cksum_t zc;
13676b4acc8bSahrens 
1368cc60fd72Sahrens 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
13696b4acc8bSahrens 		return;
13706b4acc8bSahrens 
137189c86e32SChris Williamson 	mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
137289c86e32SChris Williamson 	if (buf->b_hdr->b_freeze_cksum == NULL || HDR_IO_ERROR(buf->b_hdr)) {
137389c86e32SChris Williamson 		mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
13746b4acc8bSahrens 		return;
13756b4acc8bSahrens 	}
137645818ee1SMatthew Ahrens 	fletcher_2_native(buf->b_data, buf->b_hdr->b_size, NULL, &zc);
13776b4acc8bSahrens 	if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
13786b4acc8bSahrens 		panic("buffer modified while frozen!");
137989c86e32SChris Williamson 	mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
13806b4acc8bSahrens }
13816b4acc8bSahrens 
1382fa94a07fSbrendan static int
1383fa94a07fSbrendan arc_cksum_equal(arc_buf_t *buf)
13846b4acc8bSahrens {
1385fa94a07fSbrendan 	zio_cksum_t zc;
1386fa94a07fSbrendan 	int equal;
1387fa94a07fSbrendan 
138889c86e32SChris Williamson 	mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
138945818ee1SMatthew Ahrens 	fletcher_2_native(buf->b_data, buf->b_hdr->b_size, NULL, &zc);
1390fa94a07fSbrendan 	equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
139189c86e32SChris Williamson 	mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1392fa94a07fSbrendan 
1393fa94a07fSbrendan 	return (equal);
1394fa94a07fSbrendan }
1395fa94a07fSbrendan 
1396fa94a07fSbrendan static void
1397fa94a07fSbrendan arc_cksum_compute(arc_buf_t *buf, boolean_t force)
1398fa94a07fSbrendan {
1399fa94a07fSbrendan 	if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
14006b4acc8bSahrens 		return;
14016b4acc8bSahrens 
140289c86e32SChris Williamson 	mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
14036b4acc8bSahrens 	if (buf->b_hdr->b_freeze_cksum != NULL) {
140489c86e32SChris Williamson 		mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
14056b4acc8bSahrens 		return;
14066b4acc8bSahrens 	}
14076b4acc8bSahrens 	buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
14086b4acc8bSahrens 	fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
140945818ee1SMatthew Ahrens 	    NULL, buf->b_hdr->b_freeze_cksum);
141089c86e32SChris Williamson 	mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1411cd1c8b85SMatthew Ahrens 	arc_buf_watch(buf);
1412cd1c8b85SMatthew Ahrens }
1413cd1c8b85SMatthew Ahrens 
1414cd1c8b85SMatthew Ahrens #ifndef _KERNEL
1415cd1c8b85SMatthew Ahrens typedef struct procctl {
1416cd1c8b85SMatthew Ahrens 	long cmd;
1417cd1c8b85SMatthew Ahrens 	prwatch_t prwatch;
1418cd1c8b85SMatthew Ahrens } procctl_t;
1419cd1c8b85SMatthew Ahrens #endif
1420cd1c8b85SMatthew Ahrens 
1421cd1c8b85SMatthew Ahrens /* ARGSUSED */
1422cd1c8b85SMatthew Ahrens static void
1423cd1c8b85SMatthew Ahrens arc_buf_unwatch(arc_buf_t *buf)
1424cd1c8b85SMatthew Ahrens {
1425cd1c8b85SMatthew Ahrens #ifndef _KERNEL
1426cd1c8b85SMatthew Ahrens 	if (arc_watch) {
1427cd1c8b85SMatthew Ahrens 		int result;
1428cd1c8b85SMatthew Ahrens 		procctl_t ctl;
1429cd1c8b85SMatthew Ahrens 		ctl.cmd = PCWATCH;
1430cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1431cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_size = 0;
1432cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_wflags = 0;
1433cd1c8b85SMatthew Ahrens 		result = write(arc_procfd, &ctl, sizeof (ctl));
1434cd1c8b85SMatthew Ahrens 		ASSERT3U(result, ==, sizeof (ctl));
1435cd1c8b85SMatthew Ahrens 	}
1436cd1c8b85SMatthew Ahrens #endif
1437cd1c8b85SMatthew Ahrens }
1438cd1c8b85SMatthew Ahrens 
1439cd1c8b85SMatthew Ahrens /* ARGSUSED */
1440cd1c8b85SMatthew Ahrens static void
1441cd1c8b85SMatthew Ahrens arc_buf_watch(arc_buf_t *buf)
1442cd1c8b85SMatthew Ahrens {
1443cd1c8b85SMatthew Ahrens #ifndef _KERNEL
1444cd1c8b85SMatthew Ahrens 	if (arc_watch) {
1445cd1c8b85SMatthew Ahrens 		int result;
1446cd1c8b85SMatthew Ahrens 		procctl_t ctl;
1447cd1c8b85SMatthew Ahrens 		ctl.cmd = PCWATCH;
1448cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1449cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_size = buf->b_hdr->b_size;
1450cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_wflags = WA_WRITE;
1451cd1c8b85SMatthew Ahrens 		result = write(arc_procfd, &ctl, sizeof (ctl));
1452cd1c8b85SMatthew Ahrens 		ASSERT3U(result, ==, sizeof (ctl));
1453cd1c8b85SMatthew Ahrens 	}
1454cd1c8b85SMatthew Ahrens #endif
14556b4acc8bSahrens }
14566b4acc8bSahrens 
145789c86e32SChris Williamson static arc_buf_contents_t
145889c86e32SChris Williamson arc_buf_type(arc_buf_hdr_t *hdr)
145989c86e32SChris Williamson {
146089c86e32SChris Williamson 	if (HDR_ISTYPE_METADATA(hdr)) {
146189c86e32SChris Williamson 		return (ARC_BUFC_METADATA);
146289c86e32SChris Williamson 	} else {
146389c86e32SChris Williamson 		return (ARC_BUFC_DATA);
146489c86e32SChris Williamson 	}
146589c86e32SChris Williamson }
146689c86e32SChris Williamson 
146789c86e32SChris Williamson static uint32_t
146889c86e32SChris Williamson arc_bufc_to_flags(arc_buf_contents_t type)
146989c86e32SChris Williamson {
147089c86e32SChris Williamson 	switch (type) {
147189c86e32SChris Williamson 	case ARC_BUFC_DATA:
147289c86e32SChris Williamson 		/* metadata field is 0 if buffer contains normal data */
147389c86e32SChris Williamson 		return (0);
147489c86e32SChris Williamson 	case ARC_BUFC_METADATA:
147589c86e32SChris Williamson 		return (ARC_FLAG_BUFC_METADATA);
147689c86e32SChris Williamson 	default:
147789c86e32SChris Williamson 		break;
147889c86e32SChris Williamson 	}
147989c86e32SChris Williamson 	panic("undefined ARC buffer type!");
148089c86e32SChris Williamson 	return ((uint32_t)-1);
148189c86e32SChris Williamson }
148289c86e32SChris Williamson 
14836b4acc8bSahrens void
14846b4acc8bSahrens arc_buf_thaw(arc_buf_t *buf)
14856b4acc8bSahrens {
1486fa94a07fSbrendan 	if (zfs_flags & ZFS_DEBUG_MODIFY) {
148789c86e32SChris Williamson 		if (buf->b_hdr->b_l1hdr.b_state != arc_anon)
14886b4acc8bSahrens 			panic("modifying non-anon buffer!");
148989c86e32SChris Williamson 		if (HDR_IO_IN_PROGRESS(buf->b_hdr))
14906b4acc8bSahrens 			panic("modifying buffer while i/o in progress!");
14916b4acc8bSahrens 		arc_cksum_verify(buf);
1492fa94a07fSbrendan 	}
1493fa94a07fSbrendan 
149489c86e32SChris Williamson 	mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
14956b4acc8bSahrens 	if (buf->b_hdr->b_freeze_cksum != NULL) {
14966b4acc8bSahrens 		kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
14976b4acc8bSahrens 		buf->b_hdr->b_freeze_cksum = NULL;
14986b4acc8bSahrens 	}
14993f9d6ad7SLin Ling 
150089c86e32SChris Williamson #ifdef ZFS_DEBUG
15013f9d6ad7SLin Ling 	if (zfs_flags & ZFS_DEBUG_MODIFY) {
150289c86e32SChris Williamson 		if (buf->b_hdr->b_l1hdr.b_thawed != NULL)
150389c86e32SChris Williamson 			kmem_free(buf->b_hdr->b_l1hdr.b_thawed, 1);
150489c86e32SChris Williamson 		buf->b_hdr->b_l1hdr.b_thawed = kmem_alloc(1, KM_SLEEP);
15053f9d6ad7SLin Ling 	}
150689c86e32SChris Williamson #endif
15073f9d6ad7SLin Ling 
150889c86e32SChris Williamson 	mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1509cd1c8b85SMatthew Ahrens 
1510cd1c8b85SMatthew Ahrens 	arc_buf_unwatch(buf);
15116b4acc8bSahrens }
15126b4acc8bSahrens 
15136b4acc8bSahrens void
15146b4acc8bSahrens arc_buf_freeze(arc_buf_t *buf)
15156b4acc8bSahrens {
15163f9d6ad7SLin Ling 	kmutex_t *hash_lock;
15173f9d6ad7SLin Ling 
1518cc60fd72Sahrens 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1519cc60fd72Sahrens 		return;
1520cc60fd72Sahrens 
15213f9d6ad7SLin Ling 	hash_lock = HDR_LOCK(buf->b_hdr);
15223f9d6ad7SLin Ling 	mutex_enter(hash_lock);
15233f9d6ad7SLin Ling 
15246b4acc8bSahrens 	ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
152589c86e32SChris Williamson 	    buf->b_hdr->b_l1hdr.b_state == arc_anon);
1526fa94a07fSbrendan 	arc_cksum_compute(buf, B_FALSE);
15273f9d6ad7SLin Ling 	mutex_exit(hash_lock);
1528cd1c8b85SMatthew Ahrens 
15296b4acc8bSahrens }
15306b4acc8bSahrens 
15316b4acc8bSahrens static void
15327adb730bSGeorge Wilson add_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1533fa9e4066Sahrens {
153489c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
1535fa9e4066Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
153689c86e32SChris Williamson 	arc_state_t *state = hdr->b_l1hdr.b_state;
1537fa9e4066Sahrens 
153889c86e32SChris Williamson 	if ((refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
153989c86e32SChris Williamson 	    (state != arc_anon)) {
154089c86e32SChris Williamson 		/* We don't use the L2-only state list. */
154189c86e32SChris Williamson 		if (state != arc_l2c_only) {
1542244781f1SPrakash Surya 			arc_buf_contents_t type = arc_buf_type(hdr);
154389c86e32SChris Williamson 			uint64_t delta = hdr->b_size * hdr->b_l1hdr.b_datacnt;
1544244781f1SPrakash Surya 			multilist_t *list = &state->arcs_list[type];
1545244781f1SPrakash Surya 			uint64_t *size = &state->arcs_lsize[type];
1546fa9e4066Sahrens 
1547244781f1SPrakash Surya 			multilist_remove(list, hdr);
1548244781f1SPrakash Surya 
154989c86e32SChris Williamson 			if (GHOST_STATE(state)) {
155089c86e32SChris Williamson 				ASSERT0(hdr->b_l1hdr.b_datacnt);
155189c86e32SChris Williamson 				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
15527adb730bSGeorge Wilson 				delta = hdr->b_size;
1553ea8dc4b6Seschrock 			}
1554ea8dc4b6Seschrock 			ASSERT(delta > 0);
15550e8c6158Smaybee 			ASSERT3U(*size, >=, delta);
15560e8c6158Smaybee 			atomic_add_64(size, -delta);
155789c86e32SChris Williamson 		}
1558088f3894Sahrens 		/* remove the prefetch flag if we get a reference */
15597adb730bSGeorge Wilson 		hdr->b_flags &= ~ARC_FLAG_PREFETCH;
1560fa9e4066Sahrens 	}
1561fa9e4066Sahrens }
1562fa9e4066Sahrens 
1563fa9e4066Sahrens static int
15647adb730bSGeorge Wilson remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1565fa9e4066Sahrens {
1566fa9e4066Sahrens 	int cnt;
156789c86e32SChris Williamson 	arc_state_t *state = hdr->b_l1hdr.b_state;
1568fa9e4066Sahrens 
156989c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
157044cb6abcSbmc 	ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
157144cb6abcSbmc 	ASSERT(!GHOST_STATE(state));
1572fa9e4066Sahrens 
157389c86e32SChris Williamson 	/*
157489c86e32SChris Williamson 	 * arc_l2c_only counts as a ghost state so we don't need to explicitly
157589c86e32SChris Williamson 	 * check to prevent usage of the arc_l2c_only list.
157689c86e32SChris Williamson 	 */
157789c86e32SChris Williamson 	if (((cnt = refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
157844cb6abcSbmc 	    (state != arc_anon)) {
1579244781f1SPrakash Surya 		arc_buf_contents_t type = arc_buf_type(hdr);
1580244781f1SPrakash Surya 		multilist_t *list = &state->arcs_list[type];
1581244781f1SPrakash Surya 		uint64_t *size = &state->arcs_lsize[type];
15820e8c6158Smaybee 
1583244781f1SPrakash Surya 		multilist_insert(list, hdr);
1584244781f1SPrakash Surya 
158589c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_datacnt > 0);
158689c86e32SChris Williamson 		atomic_add_64(size, hdr->b_size *
158789c86e32SChris Williamson 		    hdr->b_l1hdr.b_datacnt);
1588fa9e4066Sahrens 	}
1589fa9e4066Sahrens 	return (cnt);
1590fa9e4066Sahrens }
1591fa9e4066Sahrens 
1592fa9e4066Sahrens /*
1593244781f1SPrakash Surya  * Move the supplied buffer to the indicated state. The hash lock
1594fa9e4066Sahrens  * for the buffer must be held by the caller.
1595fa9e4066Sahrens  */
1596fa9e4066Sahrens static void
15977adb730bSGeorge Wilson arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
15987adb730bSGeorge Wilson     kmutex_t *hash_lock)
1599fa9e4066Sahrens {
160089c86e32SChris Williamson 	arc_state_t *old_state;
160189c86e32SChris Williamson 	int64_t refcnt;
160289c86e32SChris Williamson 	uint32_t datacnt;
1603c0a81264Sek110237 	uint64_t from_delta, to_delta;
160489c86e32SChris Williamson 	arc_buf_contents_t buftype = arc_buf_type(hdr);
160589c86e32SChris Williamson 
160689c86e32SChris Williamson 	/*
160789c86e32SChris Williamson 	 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
160889c86e32SChris Williamson 	 * in arc_read() when bringing a buffer out of the L2ARC.  However, the
160989c86e32SChris Williamson 	 * L1 hdr doesn't always exist when we change state to arc_anon before
161089c86e32SChris Williamson 	 * destroying a header, in which case reallocating to add the L1 hdr is
161189c86e32SChris Williamson 	 * pointless.
161289c86e32SChris Williamson 	 */
161389c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr)) {
161489c86e32SChris Williamson 		old_state = hdr->b_l1hdr.b_state;
161589c86e32SChris Williamson 		refcnt = refcount_count(&hdr->b_l1hdr.b_refcnt);
161689c86e32SChris Williamson 		datacnt = hdr->b_l1hdr.b_datacnt;
161789c86e32SChris Williamson 	} else {
161889c86e32SChris Williamson 		old_state = arc_l2c_only;
161989c86e32SChris Williamson 		refcnt = 0;
162089c86e32SChris Williamson 		datacnt = 0;
162189c86e32SChris Williamson 	}
1622fa9e4066Sahrens 
1623fa9e4066Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
162469962b56SMatthew Ahrens 	ASSERT3P(new_state, !=, old_state);
162589c86e32SChris Williamson 	ASSERT(refcnt == 0 || datacnt > 0);
162689c86e32SChris Williamson 	ASSERT(!GHOST_STATE(new_state) || datacnt == 0);
162789c86e32SChris Williamson 	ASSERT(old_state != arc_anon || datacnt <= 1);
1628ea8dc4b6Seschrock 
162989c86e32SChris Williamson 	from_delta = to_delta = datacnt * hdr->b_size;
1630fa9e4066Sahrens 
1631fa9e4066Sahrens 	/*
1632fa9e4066Sahrens 	 * If this buffer is evictable, transfer it from the
1633fa9e4066Sahrens 	 * old state list to the new state list.
1634fa9e4066Sahrens 	 */
1635ea8dc4b6Seschrock 	if (refcnt == 0) {
163689c86e32SChris Williamson 		if (old_state != arc_anon && old_state != arc_l2c_only) {
163789c86e32SChris Williamson 			uint64_t *size = &old_state->arcs_lsize[buftype];
1638fa9e4066Sahrens 
163989c86e32SChris Williamson 			ASSERT(HDR_HAS_L1HDR(hdr));
1640244781f1SPrakash Surya 			multilist_remove(&old_state->arcs_list[buftype], hdr);
1641ea8dc4b6Seschrock 
164213506d1eSmaybee 			/*
164313506d1eSmaybee 			 * If prefetching out of the ghost cache,
16443f9d6ad7SLin Ling 			 * we will have a non-zero datacnt.
164513506d1eSmaybee 			 */
164689c86e32SChris Williamson 			if (GHOST_STATE(old_state) && datacnt == 0) {
1647ea8dc4b6Seschrock 				/* ghost elements have a ghost size */
164889c86e32SChris Williamson 				ASSERT(hdr->b_l1hdr.b_buf == NULL);
16497adb730bSGeorge Wilson 				from_delta = hdr->b_size;
1650ea8dc4b6Seschrock 			}
16510e8c6158Smaybee 			ASSERT3U(*size, >=, from_delta);
16520e8c6158Smaybee 			atomic_add_64(size, -from_delta);
1653fa9e4066Sahrens 		}
165489c86e32SChris Williamson 		if (new_state != arc_anon && new_state != arc_l2c_only) {
165589c86e32SChris Williamson 			uint64_t *size = &new_state->arcs_lsize[buftype];
1656fa9e4066Sahrens 
165789c86e32SChris Williamson 			/*
165889c86e32SChris Williamson 			 * An L1 header always exists here, since if we're
165989c86e32SChris Williamson 			 * moving to some L1-cached state (i.e. not l2c_only or
166089c86e32SChris Williamson 			 * anonymous), we realloc the header to add an L1hdr
166189c86e32SChris Williamson 			 * beforehand.
166289c86e32SChris Williamson 			 */
166389c86e32SChris Williamson 			ASSERT(HDR_HAS_L1HDR(hdr));
1664244781f1SPrakash Surya 			multilist_insert(&new_state->arcs_list[buftype], hdr);
1665ea8dc4b6Seschrock 
1666ea8dc4b6Seschrock 			/* ghost elements have a ghost size */
1667ea8dc4b6Seschrock 			if (GHOST_STATE(new_state)) {
166889c86e32SChris Williamson 				ASSERT0(datacnt);
166989c86e32SChris Williamson 				ASSERT(hdr->b_l1hdr.b_buf == NULL);
16707adb730bSGeorge Wilson 				to_delta = hdr->b_size;
1671ea8dc4b6Seschrock 			}
16720e8c6158Smaybee 			atomic_add_64(size, to_delta);
1673fa9e4066Sahrens 		}
1674fa9e4066Sahrens 	}
1675fa9e4066Sahrens 
16767adb730bSGeorge Wilson 	ASSERT(!BUF_EMPTY(hdr));
16777adb730bSGeorge Wilson 	if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
16787adb730bSGeorge Wilson 		buf_hash_remove(hdr);
1679fa9e4066Sahrens 
168089c86e32SChris Williamson 	/* adjust state sizes (ignore arc_l2c_only) */
16812fd872a7SPrakash Surya 
16822fd872a7SPrakash Surya 	if (to_delta && new_state != arc_l2c_only) {
16832fd872a7SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(hdr));
16842fd872a7SPrakash Surya 		if (GHOST_STATE(new_state)) {
16852fd872a7SPrakash Surya 			ASSERT0(datacnt);
16862fd872a7SPrakash Surya 
16872fd872a7SPrakash Surya 			/*
16882fd872a7SPrakash Surya 			 * We moving a header to a ghost state, we first
16892fd872a7SPrakash Surya 			 * remove all arc buffers. Thus, we'll have a
16902fd872a7SPrakash Surya 			 * datacnt of zero, and no arc buffer to use for
16912fd872a7SPrakash Surya 			 * the reference. As a result, we use the arc
16922fd872a7SPrakash Surya 			 * header pointer for the reference.
16932fd872a7SPrakash Surya 			 */
16942fd872a7SPrakash Surya 			(void) refcount_add_many(&new_state->arcs_size,
16952fd872a7SPrakash Surya 			    hdr->b_size, hdr);
16962fd872a7SPrakash Surya 		} else {
16972fd872a7SPrakash Surya 			ASSERT3U(datacnt, !=, 0);
16982fd872a7SPrakash Surya 
16992fd872a7SPrakash Surya 			/*
17002fd872a7SPrakash Surya 			 * Each individual buffer holds a unique reference,
17012fd872a7SPrakash Surya 			 * thus we must remove each of these references one
17022fd872a7SPrakash Surya 			 * at a time.
17032fd872a7SPrakash Surya 			 */
17042fd872a7SPrakash Surya 			for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
17052fd872a7SPrakash Surya 			    buf = buf->b_next) {
17062fd872a7SPrakash Surya 				(void) refcount_add_many(&new_state->arcs_size,
17072fd872a7SPrakash Surya 				    hdr->b_size, buf);
1708fa9e4066Sahrens 			}
17092fd872a7SPrakash Surya 		}
17102fd872a7SPrakash Surya 	}
17112fd872a7SPrakash Surya 
17122fd872a7SPrakash Surya 	if (from_delta && old_state != arc_l2c_only) {
17132fd872a7SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(hdr));
17142fd872a7SPrakash Surya 		if (GHOST_STATE(old_state)) {
17152fd872a7SPrakash Surya 			/*
17162fd872a7SPrakash Surya 			 * When moving a header off of a ghost state,
17172fd872a7SPrakash Surya 			 * there's the possibility for datacnt to be
17182fd872a7SPrakash Surya 			 * non-zero. This is because we first add the
17192fd872a7SPrakash Surya 			 * arc buffer to the header prior to changing
17202fd872a7SPrakash Surya 			 * the header's state. Since we used the header
17212fd872a7SPrakash Surya 			 * for the reference when putting the header on
17222fd872a7SPrakash Surya 			 * the ghost state, we must balance that and use
17232fd872a7SPrakash Surya 			 * the header when removing off the ghost state
17242fd872a7SPrakash Surya 			 * (even though datacnt is non zero).
17252fd872a7SPrakash Surya 			 */
17262fd872a7SPrakash Surya 
17272fd872a7SPrakash Surya 			IMPLY(datacnt == 0, new_state == arc_anon ||
17282fd872a7SPrakash Surya 			    new_state == arc_l2c_only);
17292fd872a7SPrakash Surya 
17302fd872a7SPrakash Surya 			(void) refcount_remove_many(&old_state->arcs_size,
17312fd872a7SPrakash Surya 			    hdr->b_size, hdr);
17322fd872a7SPrakash Surya 		} else {
17332fd872a7SPrakash Surya 			ASSERT3P(datacnt, !=, 0);
17342fd872a7SPrakash Surya 
17352fd872a7SPrakash Surya 			/*
17362fd872a7SPrakash Surya 			 * Each individual buffer holds a unique reference,
17372fd872a7SPrakash Surya 			 * thus we must remove each of these references one
17382fd872a7SPrakash Surya 			 * at a time.
17392fd872a7SPrakash Surya 			 */
17402fd872a7SPrakash Surya 			for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
17412fd872a7SPrakash Surya 			    buf = buf->b_next) {
17422fd872a7SPrakash Surya 				(void) refcount_remove_many(
17432fd872a7SPrakash Surya 				    &old_state->arcs_size, hdr->b_size, buf);
17442fd872a7SPrakash Surya 			}
17452fd872a7SPrakash Surya 		}
17462fd872a7SPrakash Surya 	}
17472fd872a7SPrakash Surya 
174889c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr))
174989c86e32SChris Williamson 		hdr->b_l1hdr.b_state = new_state;
1750fa94a07fSbrendan 
175189c86e32SChris Williamson 	/*
175289c86e32SChris Williamson 	 * L2 headers should never be on the L2 state list since they don't
175389c86e32SChris Williamson 	 * have L1 headers allocated.
175489c86e32SChris Williamson 	 */
1755244781f1SPrakash Surya 	ASSERT(multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
1756244781f1SPrakash Surya 	    multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
1757fa9e4066Sahrens }
1758fa9e4066Sahrens 
17590e8c6158Smaybee void
17605a98e54bSBrendan Gregg - Sun Microsystems arc_space_consume(uint64_t space, arc_space_type_t type)
17610e8c6158Smaybee {
17625a98e54bSBrendan Gregg - Sun Microsystems 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
17635a98e54bSBrendan Gregg - Sun Microsystems 
17645a98e54bSBrendan Gregg - Sun Microsystems 	switch (type) {
17655a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_DATA:
17665a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_data_size, space);
17675a98e54bSBrendan Gregg - Sun Microsystems 		break;
17684076b1bfSPrakash Surya 	case ARC_SPACE_META:
17694076b1bfSPrakash Surya 		ARCSTAT_INCR(arcstat_metadata_size, space);
17704076b1bfSPrakash Surya 		break;
17715a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_OTHER:
17725a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_other_size, space);
17735a98e54bSBrendan Gregg - Sun Microsystems 		break;
17745a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_HDRS:
17755a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_hdr_size, space);
17765a98e54bSBrendan Gregg - Sun Microsystems 		break;
17775a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_L2HDRS:
17785a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_l2_hdr_size, space);
17795a98e54bSBrendan Gregg - Sun Microsystems 		break;
17805a98e54bSBrendan Gregg - Sun Microsystems 	}
17815a98e54bSBrendan Gregg - Sun Microsystems 
17824076b1bfSPrakash Surya 	if (type != ARC_SPACE_DATA)
178320128a08SGeorge Wilson 		ARCSTAT_INCR(arcstat_meta_used, space);
17844076b1bfSPrakash Surya 
17850e8c6158Smaybee 	atomic_add_64(&arc_size, space);
17860e8c6158Smaybee }
17870e8c6158Smaybee 
17880e8c6158Smaybee void
17895a98e54bSBrendan Gregg - Sun Microsystems arc_space_return(uint64_t space, arc_space_type_t type)
17900e8c6158Smaybee {
17915a98e54bSBrendan Gregg - Sun Microsystems 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
17925a98e54bSBrendan Gregg - Sun Microsystems 
17935a98e54bSBrendan Gregg - Sun Microsystems 	switch (type) {
17945a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_DATA:
17955a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_data_size, -space);
17965a98e54bSBrendan Gregg - Sun Microsystems 		break;
17974076b1bfSPrakash Surya 	case ARC_SPACE_META:
17984076b1bfSPrakash Surya 		ARCSTAT_INCR(arcstat_metadata_size, -space);
17994076b1bfSPrakash Surya 		break;
18005a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_OTHER:
18015a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_other_size, -space);
18025a98e54bSBrendan Gregg - Sun Microsystems 		break;
18035a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_HDRS:
18045a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_hdr_size, -space);
18055a98e54bSBrendan Gregg - Sun Microsystems 		break;
18065a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_L2HDRS:
18075a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
18085a98e54bSBrendan Gregg - Sun Microsystems 		break;
18095a98e54bSBrendan Gregg - Sun Microsystems 	}
18105a98e54bSBrendan Gregg - Sun Microsystems 
18114076b1bfSPrakash Surya 	if (type != ARC_SPACE_DATA) {
18120e8c6158Smaybee 		ASSERT(arc_meta_used >= space);
18130e8c6158Smaybee 		if (arc_meta_max < arc_meta_used)
18140e8c6158Smaybee 			arc_meta_max = arc_meta_used;
181520128a08SGeorge Wilson 		ARCSTAT_INCR(arcstat_meta_used, -space);
18164076b1bfSPrakash Surya 	}
18174076b1bfSPrakash Surya 
18180e8c6158Smaybee 	ASSERT(arc_size >= space);
18190e8c6158Smaybee 	atomic_add_64(&arc_size, -space);
18200e8c6158Smaybee }
18210e8c6158Smaybee 
1822fa9e4066Sahrens arc_buf_t *
182389c86e32SChris Williamson arc_buf_alloc(spa_t *spa, int32_t size, void *tag, arc_buf_contents_t type)
1824fa9e4066Sahrens {
1825fa9e4066Sahrens 	arc_buf_hdr_t *hdr;
1826fa9e4066Sahrens 	arc_buf_t *buf;
1827fa9e4066Sahrens 
1828fa9e4066Sahrens 	ASSERT3U(size, >, 0);
182989c86e32SChris Williamson 	hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
1830fa9e4066Sahrens 	ASSERT(BUF_EMPTY(hdr));
183189c86e32SChris Williamson 	ASSERT3P(hdr->b_freeze_cksum, ==, NULL);
1832fa9e4066Sahrens 	hdr->b_size = size;
1833e9103aaeSGarrett D'Amore 	hdr->b_spa = spa_load_guid(spa);
183489c86e32SChris Williamson 
18351ab7f2deSmaybee 	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1836fa9e4066Sahrens 	buf->b_hdr = hdr;
183744eda4d7Smaybee 	buf->b_data = NULL;
1838ea8dc4b6Seschrock 	buf->b_efunc = NULL;
1839ea8dc4b6Seschrock 	buf->b_private = NULL;
1840fa9e4066Sahrens 	buf->b_next = NULL;
184189c86e32SChris Williamson 
184289c86e32SChris Williamson 	hdr->b_flags = arc_bufc_to_flags(type);
184389c86e32SChris Williamson 	hdr->b_flags |= ARC_FLAG_HAS_L1HDR;
184489c86e32SChris Williamson 
184589c86e32SChris Williamson 	hdr->b_l1hdr.b_buf = buf;
184689c86e32SChris Williamson 	hdr->b_l1hdr.b_state = arc_anon;
184789c86e32SChris Williamson 	hdr->b_l1hdr.b_arc_access = 0;
184889c86e32SChris Williamson 	hdr->b_l1hdr.b_datacnt = 1;
1849244781f1SPrakash Surya 	hdr->b_l1hdr.b_tmp_cdata = NULL;
185089c86e32SChris Williamson 
185144eda4d7Smaybee 	arc_get_data_buf(buf);
185289c86e32SChris Williamson 	ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
185389c86e32SChris Williamson 	(void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
1854fa9e4066Sahrens 
1855fa9e4066Sahrens 	return (buf);
1856fa9e4066Sahrens }
1857fa9e4066Sahrens 
18582fdbea25SAleksandr Guzovskiy static char *arc_onloan_tag = "onloan";
18592fdbea25SAleksandr Guzovskiy 
18602fdbea25SAleksandr Guzovskiy /*
18612fdbea25SAleksandr Guzovskiy  * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
18622fdbea25SAleksandr Guzovskiy  * flight data by arc_tempreserve_space() until they are "returned". Loaned
18632fdbea25SAleksandr Guzovskiy  * buffers must be returned to the arc before they can be used by the DMU or
18642fdbea25SAleksandr Guzovskiy  * freed.
18652fdbea25SAleksandr Guzovskiy  */
18662fdbea25SAleksandr Guzovskiy arc_buf_t *
18672fdbea25SAleksandr Guzovskiy arc_loan_buf(spa_t *spa, int size)
18682fdbea25SAleksandr Guzovskiy {
18692fdbea25SAleksandr Guzovskiy 	arc_buf_t *buf;
18702fdbea25SAleksandr Guzovskiy 
18712fdbea25SAleksandr Guzovskiy 	buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
18722fdbea25SAleksandr Guzovskiy 
18732fdbea25SAleksandr Guzovskiy 	atomic_add_64(&arc_loaned_bytes, size);
18742fdbea25SAleksandr Guzovskiy 	return (buf);
18752fdbea25SAleksandr Guzovskiy }
18762fdbea25SAleksandr Guzovskiy 
18772fdbea25SAleksandr Guzovskiy /*
18782fdbea25SAleksandr Guzovskiy  * Return a loaned arc buffer to the arc.
18792fdbea25SAleksandr Guzovskiy  */
18802fdbea25SAleksandr Guzovskiy void
18812fdbea25SAleksandr Guzovskiy arc_return_buf(arc_buf_t *buf, void *tag)
18822fdbea25SAleksandr Guzovskiy {
18832fdbea25SAleksandr Guzovskiy 	arc_buf_hdr_t *hdr = buf->b_hdr;
18842fdbea25SAleksandr Guzovskiy 
18852fdbea25SAleksandr Guzovskiy 	ASSERT(buf->b_data != NULL);
188689c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
188789c86e32SChris Williamson 	(void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
188889c86e32SChris Williamson 	(void) refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
18892fdbea25SAleksandr Guzovskiy 
18902fdbea25SAleksandr Guzovskiy 	atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
18912fdbea25SAleksandr Guzovskiy }
18922fdbea25SAleksandr Guzovskiy 
1893c242f9a0Schunli zhang - Sun Microsystems - Irvine United States /* Detach an arc_buf from a dbuf (tag) */
1894c242f9a0Schunli zhang - Sun Microsystems - Irvine United States void
1895c242f9a0Schunli zhang - Sun Microsystems - Irvine United States arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
1896c242f9a0Schunli zhang - Sun Microsystems - Irvine United States {
189789c86e32SChris Williamson 	arc_buf_hdr_t *hdr = buf->b_hdr;
1898c242f9a0Schunli zhang - Sun Microsystems - Irvine United States 
1899c242f9a0Schunli zhang - Sun Microsystems - Irvine United States 	ASSERT(buf->b_data != NULL);
190089c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
190189c86e32SChris Williamson 	(void) refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
190289c86e32SChris Williamson 	(void) refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
1903c242f9a0Schunli zhang - Sun Microsystems - Irvine United States 	buf->b_efunc = NULL;
1904c242f9a0Schunli zhang - Sun Microsystems - Irvine United States 	buf->b_private = NULL;
1905c242f9a0Schunli zhang - Sun Microsystems - Irvine United States 
1906c242f9a0Schunli zhang - Sun Microsystems - Irvine United States 	atomic_add_64(&arc_loaned_bytes, hdr->b_size);
1907c242f9a0Schunli zhang - Sun Microsystems - Irvine United States }
1908c242f9a0Schunli zhang - Sun Microsystems - Irvine United States 
190944eda4d7Smaybee static arc_buf_t *
191044eda4d7Smaybee arc_buf_clone(arc_buf_t *from)
1911ea8dc4b6Seschrock {
191244eda4d7Smaybee 	arc_buf_t *buf;
191344eda4d7Smaybee 	arc_buf_hdr_t *hdr = from->b_hdr;
191444eda4d7Smaybee 	uint64_t size = hdr->b_size;
1915ea8dc4b6Seschrock 
191689c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
191789c86e32SChris Williamson 	ASSERT(hdr->b_l1hdr.b_state != arc_anon);
1918b24ab676SJeff Bonwick 
19191ab7f2deSmaybee 	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
192044eda4d7Smaybee 	buf->b_hdr = hdr;
192144eda4d7Smaybee 	buf->b_data = NULL;
192244eda4d7Smaybee 	buf->b_efunc = NULL;
192344eda4d7Smaybee 	buf->b_private = NULL;
192489c86e32SChris Williamson 	buf->b_next = hdr->b_l1hdr.b_buf;
192589c86e32SChris Williamson 	hdr->b_l1hdr.b_buf = buf;
192644eda4d7Smaybee 	arc_get_data_buf(buf);
192744eda4d7Smaybee 	bcopy(from->b_data, buf->b_data, size);
19289253d63dSGeorge Wilson 
19299253d63dSGeorge Wilson 	/*
19309253d63dSGeorge Wilson 	 * This buffer already exists in the arc so create a duplicate
19319253d63dSGeorge Wilson 	 * copy for the caller.  If the buffer is associated with user data
19329253d63dSGeorge Wilson 	 * then track the size and number of duplicates.  These stats will be
19339253d63dSGeorge Wilson 	 * updated as duplicate buffers are created and destroyed.
19349253d63dSGeorge Wilson 	 */
193589c86e32SChris Williamson 	if (HDR_ISTYPE_DATA(hdr)) {
19369253d63dSGeorge Wilson 		ARCSTAT_BUMP(arcstat_duplicate_buffers);
19379253d63dSGeorge Wilson 		ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
19389253d63dSGeorge Wilson 	}
193989c86e32SChris Williamson 	hdr->b_l1hdr.b_datacnt += 1;
194044eda4d7Smaybee 	return (buf);
1941ea8dc4b6Seschrock }
1942ea8dc4b6Seschrock 
1943ea8dc4b6Seschrock void
1944ea8dc4b6Seschrock arc_buf_add_ref(arc_buf_t *buf, void* tag)
1945ea8dc4b6Seschrock {
194640d7d650Smaybee 	arc_buf_hdr_t *hdr;
1947ea8dc4b6Seschrock 	kmutex_t *hash_lock;
1948ea8dc4b6Seschrock 
19499b23f181Smaybee 	/*
19506f83844dSMark Maybee 	 * Check to see if this buffer is evicted.  Callers
19516f83844dSMark Maybee 	 * must verify b_data != NULL to know if the add_ref
19526f83844dSMark Maybee 	 * was successful.
19539b23f181Smaybee 	 */
19543f9d6ad7SLin Ling 	mutex_enter(&buf->b_evict_lock);
1955ea8dc4b6Seschrock 	if (buf->b_data == NULL) {
19563f9d6ad7SLin Ling 		mutex_exit(&buf->b_evict_lock);
1957ea8dc4b6Seschrock 		return;
1958ea8dc4b6Seschrock 	}
19593f9d6ad7SLin Ling 	hash_lock = HDR_LOCK(buf->b_hdr);
19606f83844dSMark Maybee 	mutex_enter(hash_lock);
19613f9d6ad7SLin Ling 	hdr = buf->b_hdr;
196289c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
19633f9d6ad7SLin Ling 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
19643f9d6ad7SLin Ling 	mutex_exit(&buf->b_evict_lock);
1965ea8dc4b6Seschrock 
196689c86e32SChris Williamson 	ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
196789c86e32SChris Williamson 	    hdr->b_l1hdr.b_state == arc_mfu);
196889c86e32SChris Williamson 
1969ea8dc4b6Seschrock 	add_reference(hdr, hash_lock, tag);
19705a98e54bSBrendan Gregg - Sun Microsystems 	DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
197144eda4d7Smaybee 	arc_access(hdr, hash_lock);
197244eda4d7Smaybee 	mutex_exit(hash_lock);
197344cb6abcSbmc 	ARCSTAT_BUMP(arcstat_hits);
1974*5f992543SArne Jansen 	ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
1975*5f992543SArne Jansen 	    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
1976*5f992543SArne Jansen 	    data, metadata, hits);
1977ea8dc4b6Seschrock }
1978ea8dc4b6Seschrock 
1979244781f1SPrakash Surya static void
1980244781f1SPrakash Surya arc_buf_free_on_write(void *data, size_t size,
1981244781f1SPrakash Surya     void (*free_func)(void *, size_t))
1982244781f1SPrakash Surya {
1983244781f1SPrakash Surya 	l2arc_data_free_t *df;
1984244781f1SPrakash Surya 
1985244781f1SPrakash Surya 	df = kmem_alloc(sizeof (*df), KM_SLEEP);
1986244781f1SPrakash Surya 	df->l2df_data = data;
1987244781f1SPrakash Surya 	df->l2df_size = size;
1988244781f1SPrakash Surya 	df->l2df_func = free_func;
1989244781f1SPrakash Surya 	mutex_enter(&l2arc_free_on_write_mtx);
1990244781f1SPrakash Surya 	list_insert_head(l2arc_free_on_write, df);
1991244781f1SPrakash Surya 	mutex_exit(&l2arc_free_on_write_mtx);
1992244781f1SPrakash Surya }
1993244781f1SPrakash Surya 
1994fa94a07fSbrendan /*
1995fa94a07fSbrendan  * Free the arc data buffer.  If it is an l2arc write in progress,
1996fa94a07fSbrendan  * the buffer is placed on l2arc_free_on_write to be freed later.
1997fa94a07fSbrendan  */
1998fa94a07fSbrendan static void
1999cd1c8b85SMatthew Ahrens arc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
2000fa94a07fSbrendan {
2001cd1c8b85SMatthew Ahrens 	arc_buf_hdr_t *hdr = buf->b_hdr;
2002cd1c8b85SMatthew Ahrens 
2003fa94a07fSbrendan 	if (HDR_L2_WRITING(hdr)) {
2004244781f1SPrakash Surya 		arc_buf_free_on_write(buf->b_data, hdr->b_size, free_func);
2005fa94a07fSbrendan 		ARCSTAT_BUMP(arcstat_l2_free_on_write);
2006fa94a07fSbrendan 	} else {
2007cd1c8b85SMatthew Ahrens 		free_func(buf->b_data, hdr->b_size);
2008fa94a07fSbrendan 	}
2009fa94a07fSbrendan }
2010fa94a07fSbrendan 
2011244781f1SPrakash Surya static void
2012244781f1SPrakash Surya arc_buf_l2_cdata_free(arc_buf_hdr_t *hdr)
2013244781f1SPrakash Surya {
2014244781f1SPrakash Surya 	ASSERT(HDR_HAS_L2HDR(hdr));
2015244781f1SPrakash Surya 	ASSERT(MUTEX_HELD(&hdr->b_l2hdr.b_dev->l2ad_mtx));
2016244781f1SPrakash Surya 
2017244781f1SPrakash Surya 	/*
2018244781f1SPrakash Surya 	 * The b_tmp_cdata field is linked off of the b_l1hdr, so if
2019244781f1SPrakash Surya 	 * that doesn't exist, the header is in the arc_l2c_only state,
2020244781f1SPrakash Surya 	 * and there isn't anything to free (it's already been freed).
2021244781f1SPrakash Surya 	 */
2022244781f1SPrakash Surya 	if (!HDR_HAS_L1HDR(hdr))
2023244781f1SPrakash Surya 		return;
2024244781f1SPrakash Surya 
2025244781f1SPrakash Surya 	/*
2026244781f1SPrakash Surya 	 * The header isn't being written to the l2arc device, thus it
2027244781f1SPrakash Surya 	 * shouldn't have a b_tmp_cdata to free.
2028244781f1SPrakash Surya 	 */
2029244781f1SPrakash Surya 	if (!HDR_L2_WRITING(hdr)) {
2030244781f1SPrakash Surya 		ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
2031244781f1SPrakash Surya 		return;
2032244781f1SPrakash Surya 	}
2033244781f1SPrakash Surya 
2034244781f1SPrakash Surya 	/*
2035244781f1SPrakash Surya 	 * The header does not have compression enabled. This can be due
2036244781f1SPrakash Surya 	 * to the buffer not being compressible, or because we're
2037244781f1SPrakash Surya 	 * freeing the buffer before the second phase of
2038244781f1SPrakash Surya 	 * l2arc_write_buffer() has started (which does the compression
2039244781f1SPrakash Surya 	 * step). In either case, b_tmp_cdata does not point to a
2040244781f1SPrakash Surya 	 * separately compressed buffer, so there's nothing to free (it
2041244781f1SPrakash Surya 	 * points to the same buffer as the arc_buf_t's b_data field).
2042244781f1SPrakash Surya 	 */
2043d4cd038cSArne Jansen 	if (hdr->b_l2hdr.b_compress == ZIO_COMPRESS_OFF) {
2044244781f1SPrakash Surya 		hdr->b_l1hdr.b_tmp_cdata = NULL;
2045244781f1SPrakash Surya 		return;
2046244781f1SPrakash Surya 	}
2047244781f1SPrakash Surya 
2048244781f1SPrakash Surya 	/*
2049244781f1SPrakash Surya 	 * There's nothing to free since the buffer was all zero's and
2050244781f1SPrakash Surya 	 * compressed to a zero length buffer.
2051244781f1SPrakash Surya 	 */
2052d4cd038cSArne Jansen 	if (hdr->b_l2hdr.b_compress == ZIO_COMPRESS_EMPTY) {
2053244781f1SPrakash Surya 		ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
2054244781f1SPrakash Surya 		return;
2055244781f1SPrakash Surya 	}
2056244781f1SPrakash Surya 
2057d4cd038cSArne Jansen 	ASSERT(L2ARC_IS_VALID_COMPRESS(hdr->b_l2hdr.b_compress));
2058244781f1SPrakash Surya 
2059244781f1SPrakash Surya 	arc_buf_free_on_write(hdr->b_l1hdr.b_tmp_cdata,
2060244781f1SPrakash Surya 	    hdr->b_size, zio_data_buf_free);
2061244781f1SPrakash Surya 
2062244781f1SPrakash Surya 	ARCSTAT_BUMP(arcstat_l2_cdata_free_on_write);
2063244781f1SPrakash Surya 	hdr->b_l1hdr.b_tmp_cdata = NULL;
2064244781f1SPrakash Surya }
2065244781f1SPrakash Surya 
2066bbfa8ea8SMatthew Ahrens /*
2067bbfa8ea8SMatthew Ahrens  * Free up buf->b_data and if 'remove' is set, then pull the
2068bbfa8ea8SMatthew Ahrens  * arc_buf_t off of the the arc_buf_hdr_t's list and free it.
2069bbfa8ea8SMatthew Ahrens  */
2070fa9e4066Sahrens static void
2071244781f1SPrakash Surya arc_buf_destroy(arc_buf_t *buf, boolean_t remove)
2072ea8dc4b6Seschrock {
2073ea8dc4b6Seschrock 	arc_buf_t **bufp;
2074ea8dc4b6Seschrock 
2075ea8dc4b6Seschrock 	/* free up data associated with the buf */
207689c86e32SChris Williamson 	if (buf->b_data != NULL) {
207789c86e32SChris Williamson 		arc_state_t *state = buf->b_hdr->b_l1hdr.b_state;
2078ea8dc4b6Seschrock 		uint64_t size = buf->b_hdr->b_size;
207989c86e32SChris Williamson 		arc_buf_contents_t type = arc_buf_type(buf->b_hdr);
2080ea8dc4b6Seschrock 
20816b4acc8bSahrens 		arc_cksum_verify(buf);
2082cd1c8b85SMatthew Ahrens 		arc_buf_unwatch(buf);
2083b24ab676SJeff Bonwick 
2084ad23a2dbSjohansen 		if (type == ARC_BUFC_METADATA) {
2085cd1c8b85SMatthew Ahrens 			arc_buf_data_free(buf, zio_buf_free);
20864076b1bfSPrakash Surya 			arc_space_return(size, ARC_SPACE_META);
2087ad23a2dbSjohansen 		} else {
2088ad23a2dbSjohansen 			ASSERT(type == ARC_BUFC_DATA);
2089cd1c8b85SMatthew Ahrens 			arc_buf_data_free(buf, zio_data_buf_free);
20904076b1bfSPrakash Surya 			arc_space_return(size, ARC_SPACE_DATA);
209144eda4d7Smaybee 		}
2092244781f1SPrakash Surya 
2093244781f1SPrakash Surya 		/* protected by hash lock, if in the hash table */
2094244781f1SPrakash Surya 		if (multilist_link_active(&buf->b_hdr->b_l1hdr.b_arc_node)) {
20950e8c6158Smaybee 			uint64_t *cnt = &state->arcs_lsize[type];
20960e8c6158Smaybee 
209789c86e32SChris Williamson 			ASSERT(refcount_is_zero(
209889c86e32SChris Williamson 			    &buf->b_hdr->b_l1hdr.b_refcnt));
209989c86e32SChris Williamson 			ASSERT(state != arc_anon && state != arc_l2c_only);
21000e8c6158Smaybee 
21010e8c6158Smaybee 			ASSERT3U(*cnt, >=, size);
21020e8c6158Smaybee 			atomic_add_64(cnt, -size);
2103ea8dc4b6Seschrock 		}
21042fd872a7SPrakash Surya 
21052fd872a7SPrakash Surya 		(void) refcount_remove_many(&state->arcs_size, size, buf);
2106ea8dc4b6Seschrock 		buf->b_data = NULL;
21079253d63dSGeorge Wilson 
21089253d63dSGeorge Wilson 		/*
21099253d63dSGeorge Wilson 		 * If we're destroying a duplicate buffer make sure
21109253d63dSGeorge Wilson 		 * that the appropriate statistics are updated.
21119253d63dSGeorge Wilson 		 */
211289c86e32SChris Williamson 		if (buf->b_hdr->b_l1hdr.b_datacnt > 1 &&
211389c86e32SChris Williamson 		    HDR_ISTYPE_DATA(buf->b_hdr)) {
21149253d63dSGeorge Wilson 			ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
21159253d63dSGeorge Wilson 			ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
21169253d63dSGeorge Wilson 		}
211789c86e32SChris Williamson 		ASSERT(buf->b_hdr->b_l1hdr.b_datacnt > 0);
211889c86e32SChris Williamson 		buf->b_hdr->b_l1hdr.b_datacnt -= 1;
2119ea8dc4b6Seschrock 	}
2120ea8dc4b6Seschrock 
2121ea8dc4b6Seschrock 	/* only remove the buf if requested */
2122bbfa8ea8SMatthew Ahrens 	if (!remove)
2123ea8dc4b6Seschrock 		return;
2124ea8dc4b6Seschrock 
2125ea8dc4b6Seschrock 	/* remove the buf from the hdr list */
212689c86e32SChris Williamson 	for (bufp = &buf->b_hdr->b_l1hdr.b_buf; *bufp != buf;
212789c86e32SChris Williamson 	    bufp = &(*bufp)->b_next)
2128ea8dc4b6Seschrock 		continue;
2129ea8dc4b6Seschrock 	*bufp = buf->b_next;
21303f9d6ad7SLin Ling 	buf->b_next = NULL;
2131ea8dc4b6Seschrock 
2132ea8dc4b6Seschrock 	ASSERT(buf->b_efunc == NULL);
2133ea8dc4b6Seschrock 
2134ea8dc4b6Seschrock 	/* clean up the buf */
2135ea8dc4b6Seschrock 	buf->b_hdr = NULL;
2136ea8dc4b6Seschrock 	kmem_cache_free(buf_cache, buf);
2137ea8dc4b6Seschrock }
2138ea8dc4b6Seschrock 
2139ea8dc4b6Seschrock static void
2140a52fc310SPrakash Surya arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
2141a52fc310SPrakash Surya {
2142a52fc310SPrakash Surya 	l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
2143a52fc310SPrakash Surya 	l2arc_dev_t *dev = l2hdr->b_dev;
2144a52fc310SPrakash Surya 
2145a52fc310SPrakash Surya 	ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
2146a52fc310SPrakash Surya 	ASSERT(HDR_HAS_L2HDR(hdr));
2147a52fc310SPrakash Surya 
2148a52fc310SPrakash Surya 	list_remove(&dev->l2ad_buflist, hdr);
2149a52fc310SPrakash Surya 
2150a52fc310SPrakash Surya 	/*
2151a52fc310SPrakash Surya 	 * We don't want to leak the b_tmp_cdata buffer that was
2152a52fc310SPrakash Surya 	 * allocated in l2arc_write_buffers()
2153a52fc310SPrakash Surya 	 */
2154a52fc310SPrakash Surya 	arc_buf_l2_cdata_free(hdr);
2155a52fc310SPrakash Surya 
2156a52fc310SPrakash Surya 	/*
2157a52fc310SPrakash Surya 	 * If the l2hdr's b_daddr is equal to L2ARC_ADDR_UNSET, then
2158a52fc310SPrakash Surya 	 * this header is being processed by l2arc_write_buffers() (i.e.
2159a52fc310SPrakash Surya 	 * it's in the first stage of l2arc_write_buffers()).
2160a52fc310SPrakash Surya 	 * Re-affirming that truth here, just to serve as a reminder. If
2161a52fc310SPrakash Surya 	 * b_daddr does not equal L2ARC_ADDR_UNSET, then the header may or
2162a52fc310SPrakash Surya 	 * may not have its HDR_L2_WRITING flag set. (the write may have
2163a52fc310SPrakash Surya 	 * completed, in which case HDR_L2_WRITING will be false and the
2164a52fc310SPrakash Surya 	 * b_daddr field will point to the address of the buffer on disk).
2165a52fc310SPrakash Surya 	 */
2166a52fc310SPrakash Surya 	IMPLY(l2hdr->b_daddr == L2ARC_ADDR_UNSET, HDR_L2_WRITING(hdr));
2167a52fc310SPrakash Surya 
2168a52fc310SPrakash Surya 	/*
2169a52fc310SPrakash Surya 	 * If b_daddr is equal to L2ARC_ADDR_UNSET, we're racing with
2170a52fc310SPrakash Surya 	 * l2arc_write_buffers(). Since we've just removed this header
2171a52fc310SPrakash Surya 	 * from the l2arc buffer list, this header will never reach the
2172a52fc310SPrakash Surya 	 * second stage of l2arc_write_buffers(), which increments the
2173a52fc310SPrakash Surya 	 * accounting stats for this header. Thus, we must be careful
2174a52fc310SPrakash Surya 	 * not to decrement them for this header either.
2175a52fc310SPrakash Surya 	 */
2176a52fc310SPrakash Surya 	if (l2hdr->b_daddr != L2ARC_ADDR_UNSET) {
2177a52fc310SPrakash Surya 		ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
2178a52fc310SPrakash Surya 		ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
2179a52fc310SPrakash Surya 
2180a52fc310SPrakash Surya 		vdev_space_update(dev->l2ad_vdev,
2181a52fc310SPrakash Surya 		    -l2hdr->b_asize, 0, 0);
2182a52fc310SPrakash Surya 
2183a52fc310SPrakash Surya 		(void) refcount_remove_many(&dev->l2ad_alloc,
2184a52fc310SPrakash Surya 		    l2hdr->b_asize, hdr);
2185a52fc310SPrakash Surya 	}
2186a52fc310SPrakash Surya 
2187a52fc310SPrakash Surya 	hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
2188a52fc310SPrakash Surya }
2189a52fc310SPrakash Surya 
2190a52fc310SPrakash Surya static void
2191ea8dc4b6Seschrock arc_hdr_destroy(arc_buf_hdr_t *hdr)
2192fa9e4066Sahrens {
219389c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr)) {
219489c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_buf == NULL ||
219589c86e32SChris Williamson 		    hdr->b_l1hdr.b_datacnt > 0);
219689c86e32SChris Williamson 		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
219789c86e32SChris Williamson 		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
219889c86e32SChris Williamson 	}
2199ea8dc4b6Seschrock 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
220089c86e32SChris Williamson 	ASSERT(!HDR_IN_HASH_TABLE(hdr));
2201fa9e4066Sahrens 
220289c86e32SChris Williamson 	if (HDR_HAS_L2HDR(hdr)) {
2203a52fc310SPrakash Surya 		l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
2204a52fc310SPrakash Surya 		boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
2205fa94a07fSbrendan 
2206b24ab676SJeff Bonwick 		if (!buflist_held)
2207a52fc310SPrakash Surya 			mutex_enter(&dev->l2ad_mtx);
220889c86e32SChris Williamson 
2209a52fc310SPrakash Surya 		/*
2210a52fc310SPrakash Surya 		 * Even though we checked this conditional above, we
2211a52fc310SPrakash Surya 		 * need to check this again now that we have the
2212a52fc310SPrakash Surya 		 * l2ad_mtx. This is because we could be racing with
2213a52fc310SPrakash Surya 		 * another thread calling l2arc_evict() which might have
2214a52fc310SPrakash Surya 		 * destroyed this header's L2 portion as we were waiting
2215a52fc310SPrakash Surya 		 * to acquire the l2ad_mtx. If that happens, we don't
2216a52fc310SPrakash Surya 		 * want to re-destroy the header's L2 portion.
2217a52fc310SPrakash Surya 		 */
2218a52fc310SPrakash Surya 		if (HDR_HAS_L2HDR(hdr))
2219a52fc310SPrakash Surya 			arc_hdr_l2hdr_destroy(hdr);
2220a52fc310SPrakash Surya 
2221a52fc310SPrakash Surya 		if (!buflist_held)
2222a52fc310SPrakash Surya 			mutex_exit(&dev->l2ad_mtx);
2223b24ab676SJeff Bonwick 	}
2224b24ab676SJeff Bonwick 
222589c86e32SChris Williamson 	if (!BUF_EMPTY(hdr))
22263f9d6ad7SLin Ling 		buf_discard_identity(hdr);
2227fa9e4066Sahrens 
222889c86e32SChris Williamson 	if (hdr->b_freeze_cksum != NULL) {
222989c86e32SChris Williamson 		kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
223089c86e32SChris Williamson 		hdr->b_freeze_cksum = NULL;
223189c86e32SChris Williamson 	}
223289c86e32SChris Williamson 
223389c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr)) {
223489c86e32SChris Williamson 		while (hdr->b_l1hdr.b_buf) {
223589c86e32SChris Williamson 			arc_buf_t *buf = hdr->b_l1hdr.b_buf;
223689c86e32SChris Williamson 
223789c86e32SChris Williamson 			if (buf->b_efunc != NULL) {
2238244781f1SPrakash Surya 				mutex_enter(&arc_user_evicts_lock);
22393f9d6ad7SLin Ling 				mutex_enter(&buf->b_evict_lock);
2240ea8dc4b6Seschrock 				ASSERT(buf->b_hdr != NULL);
2241244781f1SPrakash Surya 				arc_buf_destroy(hdr->b_l1hdr.b_buf, FALSE);
224289c86e32SChris Williamson 				hdr->b_l1hdr.b_buf = buf->b_next;
224340d7d650Smaybee 				buf->b_hdr = &arc_eviction_hdr;
2244ea8dc4b6Seschrock 				buf->b_next = arc_eviction_list;
2245ea8dc4b6Seschrock 				arc_eviction_list = buf;
22463f9d6ad7SLin Ling 				mutex_exit(&buf->b_evict_lock);
2247244781f1SPrakash Surya 				cv_signal(&arc_user_evicts_cv);
2248244781f1SPrakash Surya 				mutex_exit(&arc_user_evicts_lock);
2249ea8dc4b6Seschrock 			} else {
2250244781f1SPrakash Surya 				arc_buf_destroy(hdr->b_l1hdr.b_buf, TRUE);
2251fa9e4066Sahrens 			}
2252ea8dc4b6Seschrock 		}
225389c86e32SChris Williamson #ifdef ZFS_DEBUG
225489c86e32SChris Williamson 		if (hdr->b_l1hdr.b_thawed != NULL) {
225589c86e32SChris Williamson 			kmem_free(hdr->b_l1hdr.b_thawed, 1);
225689c86e32SChris Williamson 			hdr->b_l1hdr.b_thawed = NULL;
22576b4acc8bSahrens 		}
225889c86e32SChris Williamson #endif
22593f9d6ad7SLin Ling 	}
2260ea8dc4b6Seschrock 
2261fa9e4066Sahrens 	ASSERT3P(hdr->b_hash_next, ==, NULL);
226289c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr)) {
2263244781f1SPrakash Surya 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
226489c86e32SChris Williamson 		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
226589c86e32SChris Williamson 		kmem_cache_free(hdr_full_cache, hdr);
226689c86e32SChris Williamson 	} else {
226789c86e32SChris Williamson 		kmem_cache_free(hdr_l2only_cache, hdr);
226889c86e32SChris Williamson 	}
2269fa9e4066Sahrens }
2270fa9e4066Sahrens 
2271fa9e4066Sahrens void
2272fa9e4066Sahrens arc_buf_free(arc_buf_t *buf, void *tag)
2273fa9e4066Sahrens {
2274fa9e4066Sahrens 	arc_buf_hdr_t *hdr = buf->b_hdr;
227589c86e32SChris Williamson 	int hashed = hdr->b_l1hdr.b_state != arc_anon;
2276ea8dc4b6Seschrock 
2277ea8dc4b6Seschrock 	ASSERT(buf->b_efunc == NULL);
2278ea8dc4b6Seschrock 	ASSERT(buf->b_data != NULL);
2279ea8dc4b6Seschrock 
2280ea8dc4b6Seschrock 	if (hashed) {
2281fa9e4066Sahrens 		kmutex_t *hash_lock = HDR_LOCK(hdr);
2282fa9e4066Sahrens 
2283fa9e4066Sahrens 		mutex_enter(hash_lock);
22843f9d6ad7SLin Ling 		hdr = buf->b_hdr;
22853f9d6ad7SLin Ling 		ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
22863f9d6ad7SLin Ling 
2287ea8dc4b6Seschrock 		(void) remove_reference(hdr, hash_lock, tag);
228889c86e32SChris Williamson 		if (hdr->b_l1hdr.b_datacnt > 1) {
2289244781f1SPrakash Surya 			arc_buf_destroy(buf, TRUE);
2290b24ab676SJeff Bonwick 		} else {
229189c86e32SChris Williamson 			ASSERT(buf == hdr->b_l1hdr.b_buf);
2292b24ab676SJeff Bonwick 			ASSERT(buf->b_efunc == NULL);
22937adb730bSGeorge Wilson 			hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
2294b24ab676SJeff Bonwick 		}
2295fa9e4066Sahrens 		mutex_exit(hash_lock);
2296ea8dc4b6Seschrock 	} else if (HDR_IO_IN_PROGRESS(hdr)) {
2297ea8dc4b6Seschrock 		int destroy_hdr;
2298ea8dc4b6Seschrock 		/*
2299ea8dc4b6Seschrock 		 * We are in the middle of an async write.  Don't destroy
2300ea8dc4b6Seschrock 		 * this buffer unless the write completes before we finish
2301ea8dc4b6Seschrock 		 * decrementing the reference count.
2302ea8dc4b6Seschrock 		 */
2303244781f1SPrakash Surya 		mutex_enter(&arc_user_evicts_lock);
2304ea8dc4b6Seschrock 		(void) remove_reference(hdr, NULL, tag);
230589c86e32SChris Williamson 		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2306ea8dc4b6Seschrock 		destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
2307244781f1SPrakash Surya 		mutex_exit(&arc_user_evicts_lock);
2308ea8dc4b6Seschrock 		if (destroy_hdr)
2309ea8dc4b6Seschrock 			arc_hdr_destroy(hdr);
2310ea8dc4b6Seschrock 	} else {
23113f9d6ad7SLin Ling 		if (remove_reference(hdr, NULL, tag) > 0)
2312244781f1SPrakash Surya 			arc_buf_destroy(buf, TRUE);
23133f9d6ad7SLin Ling 		else
2314ea8dc4b6Seschrock 			arc_hdr_destroy(hdr);
2315ea8dc4b6Seschrock 	}
2316ea8dc4b6Seschrock }
2317fa9e4066Sahrens 
23183b2aab18SMatthew Ahrens boolean_t
2319ea8dc4b6Seschrock arc_buf_remove_ref(arc_buf_t *buf, void* tag)
2320ea8dc4b6Seschrock {
2321ea8dc4b6Seschrock 	arc_buf_hdr_t *hdr = buf->b_hdr;
2322ea8dc4b6Seschrock 	kmutex_t *hash_lock = HDR_LOCK(hdr);
23233b2aab18SMatthew Ahrens 	boolean_t no_callback = (buf->b_efunc == NULL);
2324fa9e4066Sahrens 
232589c86e32SChris Williamson 	if (hdr->b_l1hdr.b_state == arc_anon) {
232689c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_datacnt == 1);
2327ea8dc4b6Seschrock 		arc_buf_free(buf, tag);
2328ea8dc4b6Seschrock 		return (no_callback);
2329ea8dc4b6Seschrock 	}
2330ea8dc4b6Seschrock 
2331ea8dc4b6Seschrock 	mutex_enter(hash_lock);
23323f9d6ad7SLin Ling 	hdr = buf->b_hdr;
233389c86e32SChris Williamson 	ASSERT(hdr->b_l1hdr.b_datacnt > 0);
23343f9d6ad7SLin Ling 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
233589c86e32SChris Williamson 	ASSERT(hdr->b_l1hdr.b_state != arc_anon);
2336ea8dc4b6Seschrock 	ASSERT(buf->b_data != NULL);
2337ea8dc4b6Seschrock 
2338ea8dc4b6Seschrock 	(void) remove_reference(hdr, hash_lock, tag);
233989c86e32SChris Williamson 	if (hdr->b_l1hdr.b_datacnt > 1) {
2340ea8dc4b6Seschrock 		if (no_callback)
2341244781f1SPrakash Surya 			arc_buf_destroy(buf, TRUE);
2342ea8dc4b6Seschrock 	} else if (no_callback) {
234389c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_buf == buf && buf->b_next == NULL);
2344b24ab676SJeff Bonwick 		ASSERT(buf->b_efunc == NULL);
23457adb730bSGeorge Wilson 		hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
2346ea8dc4b6Seschrock 	}
234789c86e32SChris Williamson 	ASSERT(no_callback || hdr->b_l1hdr.b_datacnt > 1 ||
234889c86e32SChris Williamson 	    refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2349ea8dc4b6Seschrock 	mutex_exit(hash_lock);
2350ea8dc4b6Seschrock 	return (no_callback);
2351fa9e4066Sahrens }
2352fa9e4066Sahrens 
235389c86e32SChris Williamson int32_t
2354fa9e4066Sahrens arc_buf_size(arc_buf_t *buf)
2355fa9e4066Sahrens {
2356fa9e4066Sahrens 	return (buf->b_hdr->b_size);
2357fa9e4066Sahrens }
2358fa9e4066Sahrens 
2359fa9e4066Sahrens /*
23609253d63dSGeorge Wilson  * Called from the DMU to determine if the current buffer should be
23619253d63dSGeorge Wilson  * evicted. In order to ensure proper locking, the eviction must be initiated
23629253d63dSGeorge Wilson  * from the DMU. Return true if the buffer is associated with user data and
23639253d63dSGeorge Wilson  * duplicate buffers still exist.
23649253d63dSGeorge Wilson  */
23659253d63dSGeorge Wilson boolean_t
23669253d63dSGeorge Wilson arc_buf_eviction_needed(arc_buf_t *buf)
23679253d63dSGeorge Wilson {
23689253d63dSGeorge Wilson 	arc_buf_hdr_t *hdr;
23699253d63dSGeorge Wilson 	boolean_t evict_needed = B_FALSE;
23709253d63dSGeorge Wilson 
23719253d63dSGeorge Wilson 	if (zfs_disable_dup_eviction)
23729253d63dSGeorge Wilson 		return (B_FALSE);
23739253d63dSGeorge Wilson 
23749253d63dSGeorge Wilson 	mutex_enter(&buf->b_evict_lock);
23759253d63dSGeorge Wilson 	hdr = buf->b_hdr;
23769253d63dSGeorge Wilson 	if (hdr == NULL) {
23779253d63dSGeorge Wilson 		/*
23789253d63dSGeorge Wilson 		 * We are in arc_do_user_evicts(); let that function
23799253d63dSGeorge Wilson 		 * perform the eviction.
23809253d63dSGeorge Wilson 		 */
23819253d63dSGeorge Wilson 		ASSERT(buf->b_data == NULL);
23829253d63dSGeorge Wilson 		mutex_exit(&buf->b_evict_lock);
23839253d63dSGeorge Wilson 		return (B_FALSE);
23849253d63dSGeorge Wilson 	} else if (buf->b_data == NULL) {
23859253d63dSGeorge Wilson 		/*
23869253d63dSGeorge Wilson 		 * We have already been added to the arc eviction list;
23879253d63dSGeorge Wilson 		 * recommend eviction.
23889253d63dSGeorge Wilson 		 */
23899253d63dSGeorge Wilson 		ASSERT3P(hdr, ==, &arc_eviction_hdr);
23909253d63dSGeorge Wilson 		mutex_exit(&buf->b_evict_lock);
23919253d63dSGeorge Wilson 		return (B_TRUE);
23929253d63dSGeorge Wilson 	}
23939253d63dSGeorge Wilson 
239489c86e32SChris Williamson 	if (hdr->b_l1hdr.b_datacnt > 1 && HDR_ISTYPE_DATA(hdr))
23959253d63dSGeorge Wilson 		evict_needed = B_TRUE;
23969253d63dSGeorge Wilson 
23979253d63dSGeorge Wilson 	mutex_exit(&buf->b_evict_lock);
23989253d63dSGeorge Wilson 	return (evict_needed);
23999253d63dSGeorge Wilson }
24009253d63dSGeorge Wilson 
24019253d63dSGeorge Wilson /*
2402244781f1SPrakash Surya  * Evict the arc_buf_hdr that is provided as a parameter. The resultant
2403244781f1SPrakash Surya  * state of the header is dependent on it's state prior to entering this
2404244781f1SPrakash Surya  * function. The following transitions are possible:
2405874395d5Smaybee  *
2406244781f1SPrakash Surya  *    - arc_mru -> arc_mru_ghost
2407244781f1SPrakash Surya  *    - arc_mfu -> arc_mfu_ghost
2408244781f1SPrakash Surya  *    - arc_mru_ghost -> arc_l2c_only
2409244781f1SPrakash Surya  *    - arc_mru_ghost -> deleted
2410244781f1SPrakash Surya  *    - arc_mfu_ghost -> arc_l2c_only
2411244781f1SPrakash Surya  *    - arc_mfu_ghost -> deleted
2412fa9e4066Sahrens  */
2413244781f1SPrakash Surya static int64_t
2414244781f1SPrakash Surya arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
2415fa9e4066Sahrens {
2416244781f1SPrakash Surya 	arc_state_t *evicted_state, *state;
2417244781f1SPrakash Surya 	int64_t bytes_evicted = 0;
2418fa9e4066Sahrens 
2419244781f1SPrakash Surya 	ASSERT(MUTEX_HELD(hash_lock));
2420244781f1SPrakash Surya 	ASSERT(HDR_HAS_L1HDR(hdr));
2421fa9e4066Sahrens 
2422244781f1SPrakash Surya 	state = hdr->b_l1hdr.b_state;
2423244781f1SPrakash Surya 	if (GHOST_STATE(state)) {
24247adb730bSGeorge Wilson 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2425244781f1SPrakash Surya 		ASSERT(hdr->b_l1hdr.b_buf == NULL);
2426244781f1SPrakash Surya 
2427244781f1SPrakash Surya 		/*
2428244781f1SPrakash Surya 		 * l2arc_write_buffers() relies on a header's L1 portion
2429244781f1SPrakash Surya 		 * (i.e. it's b_tmp_cdata field) during it's write phase.
2430244781f1SPrakash Surya 		 * Thus, we cannot push a header onto the arc_l2c_only
2431244781f1SPrakash Surya 		 * state (removing it's L1 piece) until the header is
2432244781f1SPrakash Surya 		 * done being written to the l2arc.
2433244781f1SPrakash Surya 		 */
2434244781f1SPrakash Surya 		if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
2435244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_evict_l2_skip);
2436244781f1SPrakash Surya 			return (bytes_evicted);
2437244781f1SPrakash Surya 		}
2438244781f1SPrakash Surya 
243944cb6abcSbmc 		ARCSTAT_BUMP(arcstat_deleted);
2440244781f1SPrakash Surya 		bytes_evicted += hdr->b_size;
2441244781f1SPrakash Surya 
2442244781f1SPrakash Surya 		DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
2443fa94a07fSbrendan 
244489c86e32SChris Williamson 		if (HDR_HAS_L2HDR(hdr)) {
2445fa94a07fSbrendan 			/*
2446fa94a07fSbrendan 			 * This buffer is cached on the 2nd Level ARC;
2447fa94a07fSbrendan 			 * don't destroy the header.
2448fa94a07fSbrendan 			 */
24497adb730bSGeorge Wilson 			arc_change_state(arc_l2c_only, hdr, hash_lock);
245089c86e32SChris Williamson 			/*
245189c86e32SChris Williamson 			 * dropping from L1+L2 cached to L2-only,
245289c86e32SChris Williamson 			 * realloc to remove the L1 header.
245389c86e32SChris Williamson 			 */
245489c86e32SChris Williamson 			hdr = arc_hdr_realloc(hdr, hdr_full_cache,
245589c86e32SChris Williamson 			    hdr_l2only_cache);
2456fa94a07fSbrendan 		} else {
24577adb730bSGeorge Wilson 			arc_change_state(arc_anon, hdr, hash_lock);
24587adb730bSGeorge Wilson 			arc_hdr_destroy(hdr);
2459fa94a07fSbrendan 		}
2460244781f1SPrakash Surya 		return (bytes_evicted);
2461244781f1SPrakash Surya 	}
2462fa94a07fSbrendan 
2463244781f1SPrakash Surya 	ASSERT(state == arc_mru || state == arc_mfu);
2464244781f1SPrakash Surya 	evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
2465244781f1SPrakash Surya 
2466244781f1SPrakash Surya 	/* prefetch buffers have a minimum lifespan */
2467244781f1SPrakash Surya 	if (HDR_IO_IN_PROGRESS(hdr) ||
2468244781f1SPrakash Surya 	    ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
2469244781f1SPrakash Surya 	    ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
2470244781f1SPrakash Surya 	    arc_min_prefetch_lifespan)) {
2471244781f1SPrakash Surya 		ARCSTAT_BUMP(arcstat_evict_skip);
2472244781f1SPrakash Surya 		return (bytes_evicted);
2473244781f1SPrakash Surya 	}
2474244781f1SPrakash Surya 
2475244781f1SPrakash Surya 	ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
2476244781f1SPrakash Surya 	ASSERT3U(hdr->b_l1hdr.b_datacnt, >, 0);
2477244781f1SPrakash Surya 	while (hdr->b_l1hdr.b_buf) {
2478244781f1SPrakash Surya 		arc_buf_t *buf = hdr->b_l1hdr.b_buf;
2479244781f1SPrakash Surya 		if (!mutex_tryenter(&buf->b_evict_lock)) {
2480244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_mutex_miss);
2481fa9e4066Sahrens 			break;
2482244781f1SPrakash Surya 		}
2483244781f1SPrakash Surya 		if (buf->b_data != NULL)
2484244781f1SPrakash Surya 			bytes_evicted += hdr->b_size;
2485244781f1SPrakash Surya 		if (buf->b_efunc != NULL) {
2486244781f1SPrakash Surya 			mutex_enter(&arc_user_evicts_lock);
2487244781f1SPrakash Surya 			arc_buf_destroy(buf, FALSE);
2488244781f1SPrakash Surya 			hdr->b_l1hdr.b_buf = buf->b_next;
2489244781f1SPrakash Surya 			buf->b_hdr = &arc_eviction_hdr;
2490244781f1SPrakash Surya 			buf->b_next = arc_eviction_list;
2491244781f1SPrakash Surya 			arc_eviction_list = buf;
2492244781f1SPrakash Surya 			cv_signal(&arc_user_evicts_cv);
2493244781f1SPrakash Surya 			mutex_exit(&arc_user_evicts_lock);
2494244781f1SPrakash Surya 			mutex_exit(&buf->b_evict_lock);
249569962b56SMatthew Ahrens 		} else {
2496244781f1SPrakash Surya 			mutex_exit(&buf->b_evict_lock);
2497244781f1SPrakash Surya 			arc_buf_destroy(buf, TRUE);
2498244781f1SPrakash Surya 		}
2499fa9e4066Sahrens 	}
250069962b56SMatthew Ahrens 
2501244781f1SPrakash Surya 	if (HDR_HAS_L2HDR(hdr)) {
2502244781f1SPrakash Surya 		ARCSTAT_INCR(arcstat_evict_l2_cached, hdr->b_size);
2503244781f1SPrakash Surya 	} else {
2504f5ca7025SSaso Kiselkov 		if (l2arc_write_eligible(hdr->b_spa, UINT64_MAX, hdr))
2505244781f1SPrakash Surya 			ARCSTAT_INCR(arcstat_evict_l2_eligible, hdr->b_size);
2506244781f1SPrakash Surya 		else
2507244781f1SPrakash Surya 			ARCSTAT_INCR(arcstat_evict_l2_ineligible, hdr->b_size);
25080e8c6158Smaybee 	}
25090e8c6158Smaybee 
2510244781f1SPrakash Surya 	if (hdr->b_l1hdr.b_datacnt == 0) {
2511244781f1SPrakash Surya 		arc_change_state(evicted_state, hdr, hash_lock);
2512244781f1SPrakash Surya 		ASSERT(HDR_IN_HASH_TABLE(hdr));
2513244781f1SPrakash Surya 		hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
2514244781f1SPrakash Surya 		hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
2515244781f1SPrakash Surya 		DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
2516fa9e4066Sahrens 	}
2517fa9e4066Sahrens 
2518244781f1SPrakash Surya 	return (bytes_evicted);
2519fa9e4066Sahrens }
2520fa9e4066Sahrens 
2521244781f1SPrakash Surya static uint64_t
2522244781f1SPrakash Surya arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
2523244781f1SPrakash Surya     uint64_t spa, int64_t bytes)
2524244781f1SPrakash Surya {
2525244781f1SPrakash Surya 	multilist_sublist_t *mls;
2526244781f1SPrakash Surya 	uint64_t bytes_evicted = 0;
2527244781f1SPrakash Surya 	arc_buf_hdr_t *hdr;
2528244781f1SPrakash Surya 	kmutex_t *hash_lock;
2529244781f1SPrakash Surya 	int evict_count = 0;
2530244781f1SPrakash Surya 
2531244781f1SPrakash Surya 	ASSERT3P(marker, !=, NULL);
2532244781f1SPrakash Surya 	IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
2533244781f1SPrakash Surya 
2534244781f1SPrakash Surya 	mls = multilist_sublist_lock(ml, idx);
2535244781f1SPrakash Surya 
2536244781f1SPrakash Surya 	for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
2537244781f1SPrakash Surya 	    hdr = multilist_sublist_prev(mls, marker)) {
2538244781f1SPrakash Surya 		if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
2539244781f1SPrakash Surya 		    (evict_count >= zfs_arc_evict_batch_limit))
2540244781f1SPrakash Surya 			break;
2541244781f1SPrakash Surya 
2542244781f1SPrakash Surya 		/*
2543244781f1SPrakash Surya 		 * To keep our iteration location, move the marker
2544244781f1SPrakash Surya 		 * forward. Since we're not holding hdr's hash lock, we
2545244781f1SPrakash Surya 		 * must be very careful and not remove 'hdr' from the
2546244781f1SPrakash Surya 		 * sublist. Otherwise, other consumers might mistake the
2547244781f1SPrakash Surya 		 * 'hdr' as not being on a sublist when they call the
2548244781f1SPrakash Surya 		 * multilist_link_active() function (they all rely on
2549244781f1SPrakash Surya 		 * the hash lock protecting concurrent insertions and
2550244781f1SPrakash Surya 		 * removals). multilist_sublist_move_forward() was
2551244781f1SPrakash Surya 		 * specifically implemented to ensure this is the case
2552244781f1SPrakash Surya 		 * (only 'marker' will be removed and re-inserted).
2553244781f1SPrakash Surya 		 */
2554244781f1SPrakash Surya 		multilist_sublist_move_forward(mls, marker);
2555244781f1SPrakash Surya 
2556244781f1SPrakash Surya 		/*
2557244781f1SPrakash Surya 		 * The only case where the b_spa field should ever be
2558244781f1SPrakash Surya 		 * zero, is the marker headers inserted by
2559244781f1SPrakash Surya 		 * arc_evict_state(). It's possible for multiple threads
2560244781f1SPrakash Surya 		 * to be calling arc_evict_state() concurrently (e.g.
2561244781f1SPrakash Surya 		 * dsl_pool_close() and zio_inject_fault()), so we must
2562244781f1SPrakash Surya 		 * skip any markers we see from these other threads.
2563244781f1SPrakash Surya 		 */
2564244781f1SPrakash Surya 		if (hdr->b_spa == 0)
2565244781f1SPrakash Surya 			continue;
2566244781f1SPrakash Surya 
2567244781f1SPrakash Surya 		/* we're only interested in evicting buffers of a certain spa */
2568244781f1SPrakash Surya 		if (spa != 0 && hdr->b_spa != spa) {
2569244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_evict_skip);
2570244781f1SPrakash Surya 			continue;
2571244781f1SPrakash Surya 		}
2572244781f1SPrakash Surya 
2573244781f1SPrakash Surya 		hash_lock = HDR_LOCK(hdr);
2574244781f1SPrakash Surya 
2575244781f1SPrakash Surya 		/*
2576244781f1SPrakash Surya 		 * We aren't calling this function from any code path
2577244781f1SPrakash Surya 		 * that would already be holding a hash lock, so we're
2578244781f1SPrakash Surya 		 * asserting on this assumption to be defensive in case
2579244781f1SPrakash Surya 		 * this ever changes. Without this check, it would be
2580244781f1SPrakash Surya 		 * possible to incorrectly increment arcstat_mutex_miss
2581244781f1SPrakash Surya 		 * below (e.g. if the code changed such that we called
2582244781f1SPrakash Surya 		 * this function with a hash lock held).
2583244781f1SPrakash Surya 		 */
2584244781f1SPrakash Surya 		ASSERT(!MUTEX_HELD(hash_lock));
2585244781f1SPrakash Surya 
2586244781f1SPrakash Surya 		if (mutex_tryenter(hash_lock)) {
2587244781f1SPrakash Surya 			uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
2588244781f1SPrakash Surya 			mutex_exit(hash_lock);
2589244781f1SPrakash Surya 
2590244781f1SPrakash Surya 			bytes_evicted += evicted;
2591244781f1SPrakash Surya 
2592244781f1SPrakash Surya 			/*
2593244781f1SPrakash Surya 			 * If evicted is zero, arc_evict_hdr() must have
2594244781f1SPrakash Surya 			 * decided to skip this header, don't increment
2595244781f1SPrakash Surya 			 * evict_count in this case.
2596244781f1SPrakash Surya 			 */
2597244781f1SPrakash Surya 			if (evicted != 0)
2598244781f1SPrakash Surya 				evict_count++;
2599244781f1SPrakash Surya 
2600244781f1SPrakash Surya 			/*
2601244781f1SPrakash Surya 			 * If arc_size isn't overflowing, signal any
2602244781f1SPrakash Surya 			 * threads that might happen to be waiting.
2603244781f1SPrakash Surya 			 *
2604244781f1SPrakash Surya 			 * For each header evicted, we wake up a single
2605244781f1SPrakash Surya 			 * thread. If we used cv_broadcast, we could
2606244781f1SPrakash Surya 			 * wake up "too many" threads causing arc_size
2607244781f1SPrakash Surya 			 * to significantly overflow arc_c; since
2608244781f1SPrakash Surya 			 * arc_get_data_buf() doesn't check for overflow
2609244781f1SPrakash Surya 			 * when it's woken up (it doesn't because it's
2610244781f1SPrakash Surya 			 * possible for the ARC to be overflowing while
2611244781f1SPrakash Surya 			 * full of un-evictable buffers, and the
2612244781f1SPrakash Surya 			 * function should proceed in this case).
2613244781f1SPrakash Surya 			 *
2614244781f1SPrakash Surya 			 * If threads are left sleeping, due to not
2615244781f1SPrakash Surya 			 * using cv_broadcast, they will be woken up
2616244781f1SPrakash Surya 			 * just before arc_reclaim_thread() sleeps.
2617244781f1SPrakash Surya 			 */
2618244781f1SPrakash Surya 			mutex_enter(&arc_reclaim_lock);
2619244781f1SPrakash Surya 			if (!arc_is_overflowing())
2620244781f1SPrakash Surya 				cv_signal(&arc_reclaim_waiters_cv);
2621244781f1SPrakash Surya 			mutex_exit(&arc_reclaim_lock);
2622244781f1SPrakash Surya 		} else {
2623244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_mutex_miss);
2624244781f1SPrakash Surya 		}
2625244781f1SPrakash Surya 	}
2626244781f1SPrakash Surya 
2627244781f1SPrakash Surya 	multilist_sublist_unlock(mls);
2628244781f1SPrakash Surya 
2629244781f1SPrakash Surya 	return (bytes_evicted);
2630244781f1SPrakash Surya }
2631244781f1SPrakash Surya 
2632244781f1SPrakash Surya /*
2633244781f1SPrakash Surya  * Evict buffers from the given arc state, until we've removed the
2634244781f1SPrakash Surya  * specified number of bytes. Move the removed buffers to the
2635244781f1SPrakash Surya  * appropriate evict state.
2636244781f1SPrakash Surya  *
2637244781f1SPrakash Surya  * This function makes a "best effort". It skips over any buffers
2638244781f1SPrakash Surya  * it can't get a hash_lock on, and so, may not catch all candidates.
2639244781f1SPrakash Surya  * It may also return without evicting as much space as requested.
2640244781f1SPrakash Surya  *
2641244781f1SPrakash Surya  * If bytes is specified using the special value ARC_EVICT_ALL, this
2642244781f1SPrakash Surya  * will evict all available (i.e. unlocked and evictable) buffers from
2643244781f1SPrakash Surya  * the given arc state; which is used by arc_flush().
2644244781f1SPrakash Surya  */
2645244781f1SPrakash Surya static uint64_t
2646244781f1SPrakash Surya arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
2647244781f1SPrakash Surya     arc_buf_contents_t type)
2648244781f1SPrakash Surya {
2649244781f1SPrakash Surya 	uint64_t total_evicted = 0;
2650244781f1SPrakash Surya 	multilist_t *ml = &state->arcs_list[type];
2651244781f1SPrakash Surya 	int num_sublists;
2652244781f1SPrakash Surya 	arc_buf_hdr_t **markers;
2653244781f1SPrakash Surya 
2654244781f1SPrakash Surya 	IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
2655244781f1SPrakash Surya 
2656244781f1SPrakash Surya 	num_sublists = multilist_get_num_sublists(ml);
2657244781f1SPrakash Surya 
2658244781f1SPrakash Surya 	/*
2659244781f1SPrakash Surya 	 * If we've tried to evict from each sublist, made some
2660244781f1SPrakash Surya 	 * progress, but still have not hit the target number of bytes
2661244781f1SPrakash Surya 	 * to evict, we want to keep trying. The markers allow us to
2662244781f1SPrakash Surya 	 * pick up where we left off for each individual sublist, rather
2663244781f1SPrakash Surya 	 * than starting from the tail each time.
2664244781f1SPrakash Surya 	 */
2665244781f1SPrakash Surya 	markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
2666244781f1SPrakash Surya 	for (int i = 0; i < num_sublists; i++) {
2667244781f1SPrakash Surya 		markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
2668244781f1SPrakash Surya 
2669244781f1SPrakash Surya 		/*
2670244781f1SPrakash Surya 		 * A b_spa of 0 is used to indicate that this header is
2671244781f1SPrakash Surya 		 * a marker. This fact is used in arc_adjust_type() and
2672244781f1SPrakash Surya 		 * arc_evict_state_impl().
2673244781f1SPrakash Surya 		 */
2674244781f1SPrakash Surya 		markers[i]->b_spa = 0;
2675244781f1SPrakash Surya 
2676244781f1SPrakash Surya 		multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
2677244781f1SPrakash Surya 		multilist_sublist_insert_tail(mls, markers[i]);
2678244781f1SPrakash Surya 		multilist_sublist_unlock(mls);
2679244781f1SPrakash Surya 	}
2680244781f1SPrakash Surya 
2681244781f1SPrakash Surya 	/*
2682244781f1SPrakash Surya 	 * While we haven't hit our target number of bytes to evict, or
2683244781f1SPrakash Surya 	 * we're evicting all available buffers.
2684244781f1SPrakash Surya 	 */
2685244781f1SPrakash Surya 	while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
2686244781f1SPrakash Surya 		/*
2687244781f1SPrakash Surya 		 * Start eviction using a randomly selected sublist,
2688244781f1SPrakash Surya 		 * this is to try and evenly balance eviction across all
2689244781f1SPrakash Surya 		 * sublists. Always starting at the same sublist
2690244781f1SPrakash Surya 		 * (e.g. index 0) would cause evictions to favor certain
2691244781f1SPrakash Surya 		 * sublists over others.
2692244781f1SPrakash Surya 		 */
2693244781f1SPrakash Surya 		int sublist_idx = multilist_get_random_index(ml);
2694244781f1SPrakash Surya 		uint64_t scan_evicted = 0;
2695244781f1SPrakash Surya 
2696244781f1SPrakash Surya 		for (int i = 0; i < num_sublists; i++) {
2697244781f1SPrakash Surya 			uint64_t bytes_remaining;
2698244781f1SPrakash Surya 			uint64_t bytes_evicted;
2699244781f1SPrakash Surya 
2700244781f1SPrakash Surya 			if (bytes == ARC_EVICT_ALL)
2701244781f1SPrakash Surya 				bytes_remaining = ARC_EVICT_ALL;
2702244781f1SPrakash Surya 			else if (total_evicted < bytes)
2703244781f1SPrakash Surya 				bytes_remaining = bytes - total_evicted;
2704244781f1SPrakash Surya 			else
2705244781f1SPrakash Surya 				break;
2706244781f1SPrakash Surya 
2707244781f1SPrakash Surya 			bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
2708244781f1SPrakash Surya 			    markers[sublist_idx], spa, bytes_remaining);
2709244781f1SPrakash Surya 
2710244781f1SPrakash Surya 			scan_evicted += bytes_evicted;
2711244781f1SPrakash Surya 			total_evicted += bytes_evicted;
2712244781f1SPrakash Surya 
2713244781f1SPrakash Surya 			/* we've reached the end, wrap to the beginning */
2714244781f1SPrakash Surya 			if (++sublist_idx >= num_sublists)
2715244781f1SPrakash Surya 				sublist_idx = 0;
2716244781f1SPrakash Surya 		}
2717244781f1SPrakash Surya 
2718244781f1SPrakash Surya 		/*
2719244781f1SPrakash Surya 		 * If we didn't evict anything during this scan, we have
2720244781f1SPrakash Surya 		 * no reason to believe we'll evict more during another
2721244781f1SPrakash Surya 		 * scan, so break the loop.
2722244781f1SPrakash Surya 		 */
2723244781f1SPrakash Surya 		if (scan_evicted == 0) {
2724244781f1SPrakash Surya 			/* This isn't possible, let's make that obvious */
2725244781f1SPrakash Surya 			ASSERT3S(bytes, !=, 0);
2726244781f1SPrakash Surya 
2727244781f1SPrakash Surya 			/*
2728244781f1SPrakash Surya 			 * When bytes is ARC_EVICT_ALL, the only way to
2729244781f1SPrakash Surya 			 * break the loop is when scan_evicted is zero.
2730244781f1SPrakash Surya 			 * In that case, we actually have evicted enough,
2731244781f1SPrakash Surya 			 * so we don't want to increment the kstat.
2732244781f1SPrakash Surya 			 */
2733244781f1SPrakash Surya 			if (bytes != ARC_EVICT_ALL) {
2734244781f1SPrakash Surya 				ASSERT3S(total_evicted, <, bytes);
2735244781f1SPrakash Surya 				ARCSTAT_BUMP(arcstat_evict_not_enough);
2736244781f1SPrakash Surya 			}
2737244781f1SPrakash Surya 
2738244781f1SPrakash Surya 			break;
2739244781f1SPrakash Surya 		}
2740244781f1SPrakash Surya 	}
2741244781f1SPrakash Surya 
2742244781f1SPrakash Surya 	for (int i = 0; i < num_sublists; i++) {
2743244781f1SPrakash Surya 		multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
2744244781f1SPrakash Surya 		multilist_sublist_remove(mls, markers[i]);
2745244781f1SPrakash Surya 		multilist_sublist_unlock(mls);
2746244781f1SPrakash Surya 
2747244781f1SPrakash Surya 		kmem_cache_free(hdr_full_cache, markers[i]);
2748244781f1SPrakash Surya 	}
2749244781f1SPrakash Surya 	kmem_free(markers, sizeof (*markers) * num_sublists);
2750244781f1SPrakash Surya 
2751244781f1SPrakash Surya 	return (total_evicted);
2752244781f1SPrakash Surya }
2753244781f1SPrakash Surya 
2754244781f1SPrakash Surya /*
2755244781f1SPrakash Surya  * Flush all "evictable" data of the given type from the arc state
2756244781f1SPrakash Surya  * specified. This will not evict any "active" buffers (i.e. referenced).
2757244781f1SPrakash Surya  *
2758244781f1SPrakash Surya  * When 'retry' is set to FALSE, the function will make a single pass
2759244781f1SPrakash Surya  * over the state and evict any buffers that it can. Since it doesn't
2760244781f1SPrakash Surya  * continually retry the eviction, it might end up leaving some buffers
2761244781f1SPrakash Surya  * in the ARC due to lock misses.
2762244781f1SPrakash Surya  *
2763244781f1SPrakash Surya  * When 'retry' is set to TRUE, the function will continually retry the
2764244781f1SPrakash Surya  * eviction until *all* evictable buffers have been removed from the
2765244781f1SPrakash Surya  * state. As a result, if concurrent insertions into the state are
2766244781f1SPrakash Surya  * allowed (e.g. if the ARC isn't shutting down), this function might
2767244781f1SPrakash Surya  * wind up in an infinite loop, continually trying to evict buffers.
2768244781f1SPrakash Surya  */
2769244781f1SPrakash Surya static uint64_t
2770244781f1SPrakash Surya arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
2771244781f1SPrakash Surya     boolean_t retry)
2772244781f1SPrakash Surya {
2773244781f1SPrakash Surya 	uint64_t evicted = 0;
2774244781f1SPrakash Surya 
2775244781f1SPrakash Surya 	while (state->arcs_lsize[type] != 0) {
2776244781f1SPrakash Surya 		evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
2777244781f1SPrakash Surya 
2778244781f1SPrakash Surya 		if (!retry)
2779244781f1SPrakash Surya 			break;
2780244781f1SPrakash Surya 	}
2781244781f1SPrakash Surya 
2782244781f1SPrakash Surya 	return (evicted);
2783244781f1SPrakash Surya }
2784244781f1SPrakash Surya 
2785244781f1SPrakash Surya /*
2786244781f1SPrakash Surya  * Evict the specified number of bytes from the state specified,
2787244781f1SPrakash Surya  * restricting eviction to the spa and type given. This function
2788244781f1SPrakash Surya  * prevents us from trying to evict more from a state's list than
2789244781f1SPrakash Surya  * is "evictable", and to skip evicting altogether when passed a
2790244781f1SPrakash Surya  * negative value for "bytes". In contrast, arc_evict_state() will
2791244781f1SPrakash Surya  * evict everything it can, when passed a negative value for "bytes".
2792244781f1SPrakash Surya  */
2793244781f1SPrakash Surya static uint64_t
2794244781f1SPrakash Surya arc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
2795244781f1SPrakash Surya     arc_buf_contents_t type)
2796244781f1SPrakash Surya {
2797244781f1SPrakash Surya 	int64_t delta;
2798244781f1SPrakash Surya 
2799244781f1SPrakash Surya 	if (bytes > 0 && state->arcs_lsize[type] > 0) {
2800244781f1SPrakash Surya 		delta = MIN(state->arcs_lsize[type], bytes);
2801244781f1SPrakash Surya 		return (arc_evict_state(state, spa, delta, type));
2802244781f1SPrakash Surya 	}
2803244781f1SPrakash Surya 
2804244781f1SPrakash Surya 	return (0);
2805244781f1SPrakash Surya }
2806244781f1SPrakash Surya 
2807244781f1SPrakash Surya /*
2808244781f1SPrakash Surya  * Evict metadata buffers from the cache, such that arc_meta_used is
2809244781f1SPrakash Surya  * capped by the arc_meta_limit tunable.
2810244781f1SPrakash Surya  */
2811244781f1SPrakash Surya static uint64_t
2812244781f1SPrakash Surya arc_adjust_meta(void)
2813244781f1SPrakash Surya {
2814244781f1SPrakash Surya 	uint64_t total_evicted = 0;
2815244781f1SPrakash Surya 	int64_t target;
2816244781f1SPrakash Surya 
2817244781f1SPrakash Surya 	/*
2818244781f1SPrakash Surya 	 * If we're over the meta limit, we want to evict enough
2819244781f1SPrakash Surya 	 * metadata to get back under the meta limit. We don't want to
2820244781f1SPrakash Surya 	 * evict so much that we drop the MRU below arc_p, though. If
2821244781f1SPrakash Surya 	 * we're over the meta limit more than we're over arc_p, we
2822244781f1SPrakash Surya 	 * evict some from the MRU here, and some from the MFU below.
2823244781f1SPrakash Surya 	 */
2824244781f1SPrakash Surya 	target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
28252fd872a7SPrakash Surya 	    (int64_t)(refcount_count(&arc_anon->arcs_size) +
28262fd872a7SPrakash Surya 	    refcount_count(&arc_mru->arcs_size) - arc_p));
2827244781f1SPrakash Surya 
2828244781f1SPrakash Surya 	total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
2829244781f1SPrakash Surya 
2830244781f1SPrakash Surya 	/*
2831244781f1SPrakash Surya 	 * Similar to the above, we want to evict enough bytes to get us
2832244781f1SPrakash Surya 	 * below the meta limit, but not so much as to drop us below the
2833244781f1SPrakash Surya 	 * space alloted to the MFU (which is defined as arc_c - arc_p).
2834244781f1SPrakash Surya 	 */
2835244781f1SPrakash Surya 	target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
28362fd872a7SPrakash Surya 	    (int64_t)(refcount_count(&arc_mfu->arcs_size) - (arc_c - arc_p)));
2837244781f1SPrakash Surya 
2838244781f1SPrakash Surya 	total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
2839244781f1SPrakash Surya 
2840244781f1SPrakash Surya 	return (total_evicted);
2841244781f1SPrakash Surya }
2842244781f1SPrakash Surya 
2843244781f1SPrakash Surya /*
2844244781f1SPrakash Surya  * Return the type of the oldest buffer in the given arc state
2845244781f1SPrakash Surya  *
2846244781f1SPrakash Surya  * This function will select a random sublist of type ARC_BUFC_DATA and
2847244781f1SPrakash Surya  * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
2848244781f1SPrakash Surya  * is compared, and the type which contains the "older" buffer will be
2849244781f1SPrakash Surya  * returned.
2850244781f1SPrakash Surya  */
2851244781f1SPrakash Surya static arc_buf_contents_t
2852244781f1SPrakash Surya arc_adjust_type(arc_state_t *state)
2853244781f1SPrakash Surya {
2854244781f1SPrakash Surya 	multilist_t *data_ml = &state->arcs_list[ARC_BUFC_DATA];
2855244781f1SPrakash Surya 	multilist_t *meta_ml = &state->arcs_list[ARC_BUFC_METADATA];
2856244781f1SPrakash Surya 	int data_idx = multilist_get_random_index(data_ml);
2857244781f1SPrakash Surya 	int meta_idx = multilist_get_random_index(meta_ml);
2858244781f1SPrakash Surya 	multilist_sublist_t *data_mls;
2859244781f1SPrakash Surya 	multilist_sublist_t *meta_mls;
2860244781f1SPrakash Surya 	arc_buf_contents_t type;
2861244781f1SPrakash Surya 	arc_buf_hdr_t *data_hdr;
2862244781f1SPrakash Surya 	arc_buf_hdr_t *meta_hdr;
2863244781f1SPrakash Surya 
2864244781f1SPrakash Surya 	/*
2865244781f1SPrakash Surya 	 * We keep the sublist lock until we're finished, to prevent
2866244781f1SPrakash Surya 	 * the headers from being destroyed via arc_evict_state().
2867244781f1SPrakash Surya 	 */
2868244781f1SPrakash Surya 	data_mls = multilist_sublist_lock(data_ml, data_idx);
2869244781f1SPrakash Surya 	meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
2870244781f1SPrakash Surya 
2871244781f1SPrakash Surya 	/*
2872244781f1SPrakash Surya 	 * These two loops are to ensure we skip any markers that
2873244781f1SPrakash Surya 	 * might be at the tail of the lists due to arc_evict_state().
2874244781f1SPrakash Surya 	 */
2875244781f1SPrakash Surya 
2876244781f1SPrakash Surya 	for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
2877244781f1SPrakash Surya 	    data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
2878244781f1SPrakash Surya 		if (data_hdr->b_spa != 0)
2879244781f1SPrakash Surya 			break;
2880244781f1SPrakash Surya 	}
2881244781f1SPrakash Surya 
2882244781f1SPrakash Surya 	for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
2883244781f1SPrakash Surya 	    meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
2884244781f1SPrakash Surya 		if (meta_hdr->b_spa != 0)
2885244781f1SPrakash Surya 			break;
2886244781f1SPrakash Surya 	}
2887244781f1SPrakash Surya 
2888244781f1SPrakash Surya 	if (data_hdr == NULL && meta_hdr == NULL) {
2889244781f1SPrakash Surya 		type = ARC_BUFC_DATA;
2890244781f1SPrakash Surya 	} else if (data_hdr == NULL) {
2891244781f1SPrakash Surya 		ASSERT3P(meta_hdr, !=, NULL);
2892244781f1SPrakash Surya 		type = ARC_BUFC_METADATA;
2893244781f1SPrakash Surya 	} else if (meta_hdr == NULL) {
2894244781f1SPrakash Surya 		ASSERT3P(data_hdr, !=, NULL);
2895244781f1SPrakash Surya 		type = ARC_BUFC_DATA;
2896244781f1SPrakash Surya 	} else {
2897244781f1SPrakash Surya 		ASSERT3P(data_hdr, !=, NULL);
2898244781f1SPrakash Surya 		ASSERT3P(meta_hdr, !=, NULL);
2899244781f1SPrakash Surya 
2900244781f1SPrakash Surya 		/* The headers can't be on the sublist without an L1 header */
2901244781f1SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(data_hdr));
2902244781f1SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(meta_hdr));
2903244781f1SPrakash Surya 
2904244781f1SPrakash Surya 		if (data_hdr->b_l1hdr.b_arc_access <
2905244781f1SPrakash Surya 		    meta_hdr->b_l1hdr.b_arc_access) {
2906244781f1SPrakash Surya 			type = ARC_BUFC_DATA;
2907244781f1SPrakash Surya 		} else {
2908244781f1SPrakash Surya 			type = ARC_BUFC_METADATA;
2909244781f1SPrakash Surya 		}
2910244781f1SPrakash Surya 	}
2911244781f1SPrakash Surya 
2912244781f1SPrakash Surya 	multilist_sublist_unlock(meta_mls);
2913244781f1SPrakash Surya 	multilist_sublist_unlock(data_mls);
2914244781f1SPrakash Surya 
2915244781f1SPrakash Surya 	return (type);
2916244781f1SPrakash Surya }
2917244781f1SPrakash Surya 
2918244781f1SPrakash Surya /*
2919244781f1SPrakash Surya  * Evict buffers from the cache, such that arc_size is capped by arc_c.
2920244781f1SPrakash Surya  */
2921244781f1SPrakash Surya static uint64_t
2922fa9e4066Sahrens arc_adjust(void)
2923fa9e4066Sahrens {
2924244781f1SPrakash Surya 	uint64_t total_evicted = 0;
2925244781f1SPrakash Surya 	uint64_t bytes;
2926244781f1SPrakash Surya 	int64_t target;
2927244781f1SPrakash Surya 
2928244781f1SPrakash Surya 	/*
2929244781f1SPrakash Surya 	 * If we're over arc_meta_limit, we want to correct that before
2930244781f1SPrakash Surya 	 * potentially evicting data buffers below.
2931244781f1SPrakash Surya 	 */
2932244781f1SPrakash Surya 	total_evicted += arc_adjust_meta();
2933fa9e4066Sahrens 
29345a98e54bSBrendan Gregg - Sun Microsystems 	/*
29355a98e54bSBrendan Gregg - Sun Microsystems 	 * Adjust MRU size
2936244781f1SPrakash Surya 	 *
2937244781f1SPrakash Surya 	 * If we're over the target cache size, we want to evict enough
2938244781f1SPrakash Surya 	 * from the list to get back to our target size. We don't want
2939244781f1SPrakash Surya 	 * to evict too much from the MRU, such that it drops below
2940244781f1SPrakash Surya 	 * arc_p. So, if we're over our target cache size more than
2941244781f1SPrakash Surya 	 * the MRU is over arc_p, we'll evict enough to get back to
2942244781f1SPrakash Surya 	 * arc_p here, and then evict more from the MFU below.
29435a98e54bSBrendan Gregg - Sun Microsystems 	 */
2944244781f1SPrakash Surya 	target = MIN((int64_t)(arc_size - arc_c),
29452fd872a7SPrakash Surya 	    (int64_t)(refcount_count(&arc_anon->arcs_size) +
29462fd872a7SPrakash Surya 	    refcount_count(&arc_mru->arcs_size) + arc_meta_used - arc_p));
29475a98e54bSBrendan Gregg - Sun Microsystems 
2948244781f1SPrakash Surya 	/*
2949244781f1SPrakash Surya 	 * If we're below arc_meta_min, always prefer to evict data.
2950244781f1SPrakash Surya 	 * Otherwise, try to satisfy the requested number of bytes to
2951244781f1SPrakash Surya 	 * evict from the type which contains older buffers; in an
2952244781f1SPrakash Surya 	 * effort to keep newer buffers in the cache regardless of their
2953244781f1SPrakash Surya 	 * type. If we cannot satisfy the number of bytes from this
2954244781f1SPrakash Surya 	 * type, spill over into the next type.
2955244781f1SPrakash Surya 	 */
2956244781f1SPrakash Surya 	if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
2957244781f1SPrakash Surya 	    arc_meta_used > arc_meta_min) {
2958244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
2959244781f1SPrakash Surya 		total_evicted += bytes;
29600e8c6158Smaybee 
2961244781f1SPrakash Surya 		/*
2962244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
2963244781f1SPrakash Surya 		 * metadata, we try to get the rest from data.
2964244781f1SPrakash Surya 		 */
2965244781f1SPrakash Surya 		target -= bytes;
2966244781f1SPrakash Surya 
2967244781f1SPrakash Surya 		total_evicted +=
2968244781f1SPrakash Surya 		    arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
2969244781f1SPrakash Surya 	} else {
2970244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
2971244781f1SPrakash Surya 		total_evicted += bytes;
2972244781f1SPrakash Surya 
2973244781f1SPrakash Surya 		/*
2974244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
2975244781f1SPrakash Surya 		 * data, we try to get the rest from metadata.
2976244781f1SPrakash Surya 		 */
2977244781f1SPrakash Surya 		target -= bytes;
2978244781f1SPrakash Surya 
2979244781f1SPrakash Surya 		total_evicted +=
2980244781f1SPrakash Surya 		    arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
29810e8c6158Smaybee 	}
2982fa9e4066Sahrens 
29835a98e54bSBrendan Gregg - Sun Microsystems 	/*
29845a98e54bSBrendan Gregg - Sun Microsystems 	 * Adjust MFU size
2985244781f1SPrakash Surya 	 *
2986244781f1SPrakash Surya 	 * Now that we've tried to evict enough from the MRU to get its
2987244781f1SPrakash Surya 	 * size back to arc_p, if we're still above the target cache
2988244781f1SPrakash Surya 	 * size, we evict the rest from the MFU.
29895a98e54bSBrendan Gregg - Sun Microsystems 	 */
2990244781f1SPrakash Surya 	target = arc_size - arc_c;
29910e8c6158Smaybee 
299231c46cf2SAlek Pinchuk 	if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
2993244781f1SPrakash Surya 	    arc_meta_used > arc_meta_min) {
2994244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
2995244781f1SPrakash Surya 		total_evicted += bytes;
29965a98e54bSBrendan Gregg - Sun Microsystems 
2997244781f1SPrakash Surya 		/*
2998244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
2999244781f1SPrakash Surya 		 * metadata, we try to get the rest from data.
3000244781f1SPrakash Surya 		 */
3001244781f1SPrakash Surya 		target -= bytes;
30025a98e54bSBrendan Gregg - Sun Microsystems 
3003244781f1SPrakash Surya 		total_evicted +=
3004244781f1SPrakash Surya 		    arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3005244781f1SPrakash Surya 	} else {
3006244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3007244781f1SPrakash Surya 		total_evicted += bytes;
3008244781f1SPrakash Surya 
3009244781f1SPrakash Surya 		/*
3010244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
3011244781f1SPrakash Surya 		 * data, we try to get the rest from data.
3012244781f1SPrakash Surya 		 */
3013244781f1SPrakash Surya 		target -= bytes;
3014244781f1SPrakash Surya 
3015244781f1SPrakash Surya 		total_evicted +=
3016244781f1SPrakash Surya 		    arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
30175a98e54bSBrendan Gregg - Sun Microsystems 	}
30185a98e54bSBrendan Gregg - Sun Microsystems 
30195a98e54bSBrendan Gregg - Sun Microsystems 	/*
30205a98e54bSBrendan Gregg - Sun Microsystems 	 * Adjust ghost lists
3021244781f1SPrakash Surya 	 *
3022244781f1SPrakash Surya 	 * In addition to the above, the ARC also defines target values
3023244781f1SPrakash Surya 	 * for the ghost lists. The sum of the mru list and mru ghost
3024244781f1SPrakash Surya 	 * list should never exceed the target size of the cache, and
3025244781f1SPrakash Surya 	 * the sum of the mru list, mfu list, mru ghost list, and mfu
3026244781f1SPrakash Surya 	 * ghost list should never exceed twice the target size of the
3027244781f1SPrakash Surya 	 * cache. The following logic enforces these limits on the ghost
3028244781f1SPrakash Surya 	 * caches, and evicts from them as needed.
30295a98e54bSBrendan Gregg - Sun Microsystems 	 */
30302fd872a7SPrakash Surya 	target = refcount_count(&arc_mru->arcs_size) +
30312fd872a7SPrakash Surya 	    refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
30325a98e54bSBrendan Gregg - Sun Microsystems 
3033244781f1SPrakash Surya 	bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
3034244781f1SPrakash Surya 	total_evicted += bytes;
30355a98e54bSBrendan Gregg - Sun Microsystems 
3036244781f1SPrakash Surya 	target -= bytes;
30375a98e54bSBrendan Gregg - Sun Microsystems 
3038244781f1SPrakash Surya 	total_evicted +=
3039244781f1SPrakash Surya 	    arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
30405a98e54bSBrendan Gregg - Sun Microsystems 
3041244781f1SPrakash Surya 	/*
3042244781f1SPrakash Surya 	 * We assume the sum of the mru list and mfu list is less than
3043244781f1SPrakash Surya 	 * or equal to arc_c (we enforced this above), which means we
3044244781f1SPrakash Surya 	 * can use the simpler of the two equations below:
3045244781f1SPrakash Surya 	 *
3046244781f1SPrakash Surya 	 *	mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
3047244781f1SPrakash Surya 	 *		    mru ghost + mfu ghost <= arc_c
3048244781f1SPrakash Surya 	 */
30492fd872a7SPrakash Surya 	target = refcount_count(&arc_mru_ghost->arcs_size) +
30502fd872a7SPrakash Surya 	    refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
3051244781f1SPrakash Surya 
3052244781f1SPrakash Surya 	bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
3053244781f1SPrakash Surya 	total_evicted += bytes;
3054244781f1SPrakash Surya 
3055244781f1SPrakash Surya 	target -= bytes;
3056244781f1SPrakash Surya 
3057244781f1SPrakash Surya 	total_evicted +=
3058244781f1SPrakash Surya 	    arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
3059244781f1SPrakash Surya 
3060244781f1SPrakash Surya 	return (total_evicted);
3061fa9e4066Sahrens }
3062fa9e4066Sahrens 
3063ea8dc4b6Seschrock static void
3064ea8dc4b6Seschrock arc_do_user_evicts(void)
3065ea8dc4b6Seschrock {
3066244781f1SPrakash Surya 	mutex_enter(&arc_user_evicts_lock);
3067ea8dc4b6Seschrock 	while (arc_eviction_list != NULL) {
3068ea8dc4b6Seschrock 		arc_buf_t *buf = arc_eviction_list;
3069ea8dc4b6Seschrock 		arc_eviction_list = buf->b_next;
30703f9d6ad7SLin Ling 		mutex_enter(&buf->b_evict_lock);
3071ea8dc4b6Seschrock 		buf->b_hdr = NULL;
30723f9d6ad7SLin Ling 		mutex_exit(&buf->b_evict_lock);
3073244781f1SPrakash Surya 		mutex_exit(&arc_user_evicts_lock);
3074ea8dc4b6Seschrock 
3075dd6ef538Smaybee 		if (buf->b_efunc != NULL)
3076bbfa8ea8SMatthew Ahrens 			VERIFY0(buf->b_efunc(buf->b_private));
3077ea8dc4b6Seschrock 
3078ea8dc4b6Seschrock 		buf->b_efunc = NULL;
3079ea8dc4b6Seschrock 		buf->b_private = NULL;
3080ea8dc4b6Seschrock 		kmem_cache_free(buf_cache, buf);
3081244781f1SPrakash Surya 		mutex_enter(&arc_user_evicts_lock);
3082ea8dc4b6Seschrock 	}
3083244781f1SPrakash Surya 	mutex_exit(&arc_user_evicts_lock);
3084ea8dc4b6Seschrock }
3085ea8dc4b6Seschrock 
3086fa9e4066Sahrens void
3087244781f1SPrakash Surya arc_flush(spa_t *spa, boolean_t retry)
3088fa9e4066Sahrens {
3089ac05c741SMark Maybee 	uint64_t guid = 0;
3090ac05c741SMark Maybee 
3091244781f1SPrakash Surya 	/*
3092244781f1SPrakash Surya 	 * If retry is TRUE, a spa must not be specified since we have
3093244781f1SPrakash Surya 	 * no good way to determine if all of a spa's buffers have been
3094244781f1SPrakash Surya 	 * evicted from an arc state.
3095244781f1SPrakash Surya 	 */
3096244781f1SPrakash Surya 	ASSERT(!retry || spa == 0);
3097244781f1SPrakash Surya 
309889c86e32SChris Williamson 	if (spa != NULL)
3099e9103aaeSGarrett D'Amore 		guid = spa_load_guid(spa);
3100ac05c741SMark Maybee 
3101244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
3102244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
3103fa9e4066Sahrens 
3104244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
3105244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
3106ea8dc4b6Seschrock 
3107244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
3108244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
3109244781f1SPrakash Surya 
3110244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
3111244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
3112244781f1SPrakash Surya 
3113ea8dc4b6Seschrock 	arc_do_user_evicts();
3114874395d5Smaybee 	ASSERT(spa || arc_eviction_list == NULL);
3115fa9e4066Sahrens }
3116fa9e4066Sahrens 
3117fa9e4066Sahrens void
31182ec99e3eSMatthew Ahrens arc_shrink(int64_t to_free)
3119fa9e4066Sahrens {
312044cb6abcSbmc 	if (arc_c > arc_c_min) {
31213cff2f43Sstans 
312244cb6abcSbmc 		if (arc_c > arc_c_min + to_free)
312344cb6abcSbmc 			atomic_add_64(&arc_c, -to_free);
31243cff2f43Sstans 		else
312544cb6abcSbmc 			arc_c = arc_c_min;
31263cff2f43Sstans 
312744cb6abcSbmc 		atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
312844cb6abcSbmc 		if (arc_c > arc_size)
312944cb6abcSbmc 			arc_c = MAX(arc_size, arc_c_min);
313044cb6abcSbmc 		if (arc_p > arc_c)
313144cb6abcSbmc 			arc_p = (arc_c >> 1);
313244cb6abcSbmc 		ASSERT(arc_c >= arc_c_min);
313344cb6abcSbmc 		ASSERT((int64_t)arc_p >= 0);
313449e3519aSmaybee 	}
3135fa9e4066Sahrens 
313644cb6abcSbmc 	if (arc_size > arc_c)
3137244781f1SPrakash Surya 		(void) arc_adjust();
3138fa9e4066Sahrens }
3139fa9e4066Sahrens 
31402ec99e3eSMatthew Ahrens typedef enum free_memory_reason_t {
31412ec99e3eSMatthew Ahrens 	FMR_UNKNOWN,
31422ec99e3eSMatthew Ahrens 	FMR_NEEDFREE,
31432ec99e3eSMatthew Ahrens 	FMR_LOTSFREE,
31442ec99e3eSMatthew Ahrens 	FMR_SWAPFS_MINFREE,
31452ec99e3eSMatthew Ahrens 	FMR_PAGES_PP_MAXIMUM,
31462ec99e3eSMatthew Ahrens 	FMR_HEAP_ARENA,
31472ec99e3eSMatthew Ahrens 	FMR_ZIO_ARENA,
31482ec99e3eSMatthew Ahrens } free_memory_reason_t;
31492ec99e3eSMatthew Ahrens 
31502ec99e3eSMatthew Ahrens int64_t last_free_memory;
31512ec99e3eSMatthew Ahrens free_memory_reason_t last_free_reason;
31522ec99e3eSMatthew Ahrens 
315394dd93aeSGeorge Wilson /*
31542ec99e3eSMatthew Ahrens  * Additional reserve of pages for pp_reserve.
315594dd93aeSGeorge Wilson  */
31562ec99e3eSMatthew Ahrens int64_t arc_pages_pp_reserve = 64;
31572ec99e3eSMatthew Ahrens 
31582ec99e3eSMatthew Ahrens /*
31592ec99e3eSMatthew Ahrens  * Additional reserve of pages for swapfs.
31602ec99e3eSMatthew Ahrens  */
31612ec99e3eSMatthew Ahrens int64_t arc_swapfs_reserve = 64;
31622ec99e3eSMatthew Ahrens 
31632ec99e3eSMatthew Ahrens /*
31642ec99e3eSMatthew Ahrens  * Return the amount of memory that can be consumed before reclaim will be
31652ec99e3eSMatthew Ahrens  * needed.  Positive if there is sufficient free memory, negative indicates
31662ec99e3eSMatthew Ahrens  * the amount of memory that needs to be freed up.
31672ec99e3eSMatthew Ahrens  */
31682ec99e3eSMatthew Ahrens static int64_t
31692ec99e3eSMatthew Ahrens arc_available_memory(void)
3170fa9e4066Sahrens {
31712ec99e3eSMatthew Ahrens 	int64_t lowest = INT64_MAX;
31722ec99e3eSMatthew Ahrens 	int64_t n;
31732ec99e3eSMatthew Ahrens 	free_memory_reason_t r = FMR_UNKNOWN;
3174fa9e4066Sahrens 
3175fa9e4066Sahrens #ifdef _KERNEL
31762ec99e3eSMatthew Ahrens 	if (needfree > 0) {
31772ec99e3eSMatthew Ahrens 		n = PAGESIZE * (-needfree);
31782ec99e3eSMatthew Ahrens 		if (n < lowest) {
31792ec99e3eSMatthew Ahrens 			lowest = n;
31802ec99e3eSMatthew Ahrens 			r = FMR_NEEDFREE;
31812ec99e3eSMatthew Ahrens 		}
31822ec99e3eSMatthew Ahrens 	}
3183fa9e4066Sahrens 
3184fa9e4066Sahrens 	/*
3185fa9e4066Sahrens 	 * check that we're out of range of the pageout scanner.  It starts to
3186fa9e4066Sahrens 	 * schedule paging if freemem is less than lotsfree and needfree.
3187fa9e4066Sahrens 	 * lotsfree is the high-water mark for pageout, and needfree is the
3188fa9e4066Sahrens 	 * number of needed free pages.  We add extra pages here to make sure
3189fa9e4066Sahrens 	 * the scanner doesn't start up while we're freeing memory.
3190fa9e4066Sahrens 	 */
31912ec99e3eSMatthew Ahrens 	n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
31922ec99e3eSMatthew Ahrens 	if (n < lowest) {
31932ec99e3eSMatthew Ahrens 		lowest = n;
31942ec99e3eSMatthew Ahrens 		r = FMR_LOTSFREE;
31952ec99e3eSMatthew Ahrens 	}
3196fa9e4066Sahrens 
3197fa9e4066Sahrens 	/*
3198fa9e4066Sahrens 	 * check to make sure that swapfs has enough space so that anon
3199fa94a07fSbrendan 	 * reservations can still succeed. anon_resvmem() checks that the
3200fa9e4066Sahrens 	 * availrmem is greater than swapfs_minfree, and the number of reserved
3201fa9e4066Sahrens 	 * swap pages.  We also add a bit of extra here just to prevent
3202fa9e4066Sahrens 	 * circumstances from getting really dire.
3203fa9e4066Sahrens 	 */
32042ec99e3eSMatthew Ahrens 	n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
32052ec99e3eSMatthew Ahrens 	    desfree - arc_swapfs_reserve);
32062ec99e3eSMatthew Ahrens 	if (n < lowest) {
32072ec99e3eSMatthew Ahrens 		lowest = n;
32082ec99e3eSMatthew Ahrens 		r = FMR_SWAPFS_MINFREE;
32092ec99e3eSMatthew Ahrens 	}
32102ec99e3eSMatthew Ahrens 
3211fa9e4066Sahrens 
3212cf746768SBryan Cantrill 	/*
3213cf746768SBryan Cantrill 	 * Check that we have enough availrmem that memory locking (e.g., via
3214cf746768SBryan Cantrill 	 * mlock(3C) or memcntl(2)) can still succeed.  (pages_pp_maximum
3215cf746768SBryan Cantrill 	 * stores the number of pages that cannot be locked; when availrmem
3216cf746768SBryan Cantrill 	 * drops below pages_pp_maximum, page locking mechanisms such as
3217cf746768SBryan Cantrill 	 * page_pp_lock() will fail.)
3218cf746768SBryan Cantrill 	 */
32192ec99e3eSMatthew Ahrens 	n = PAGESIZE * (availrmem - pages_pp_maximum -
32202ec99e3eSMatthew Ahrens 	    arc_pages_pp_reserve);
32212ec99e3eSMatthew Ahrens 	if (n < lowest) {
32222ec99e3eSMatthew Ahrens 		lowest = n;
32232ec99e3eSMatthew Ahrens 		r = FMR_PAGES_PP_MAXIMUM;
32242ec99e3eSMatthew Ahrens 	}
3225cf746768SBryan Cantrill 
32265dc8af33Smaybee #if defined(__i386)
3227fa9e4066Sahrens 	/*
3228fa9e4066Sahrens 	 * If we're on an i386 platform, it's possible that we'll exhaust the
3229fa9e4066Sahrens 	 * kernel heap space before we ever run out of available physical
3230fa9e4066Sahrens 	 * memory.  Most checks of the size of the heap_area compare against
3231fa9e4066Sahrens 	 * tune.t_minarmem, which is the minimum available real memory that we
3232fa9e4066Sahrens 	 * can have in the system.  However, this is generally fixed at 25 pages
3233fa9e4066Sahrens 	 * which is so low that it's useless.  In this comparison, we seek to
3234fa9e4066Sahrens 	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
3235fa94a07fSbrendan 	 * heap is allocated.  (Or, in the calculation, if less than 1/4th is
3236fa9e4066Sahrens 	 * free)
3237fa9e4066Sahrens 	 */
32382ec99e3eSMatthew Ahrens 	n = vmem_size(heap_arena, VMEM_FREE) -
32392ec99e3eSMatthew Ahrens 	    (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2);
32402ec99e3eSMatthew Ahrens 	if (n < lowest) {
32412ec99e3eSMatthew Ahrens 		lowest = n;
32422ec99e3eSMatthew Ahrens 		r = FMR_HEAP_ARENA;
32432ec99e3eSMatthew Ahrens 	}
3244fa9e4066Sahrens #endif
3245fa9e4066Sahrens 
324694dd93aeSGeorge Wilson 	/*
324794dd93aeSGeorge Wilson 	 * If zio data pages are being allocated out of a separate heap segment,
324894dd93aeSGeorge Wilson 	 * then enforce that the size of available vmem for this arena remains
324994dd93aeSGeorge Wilson 	 * above about 1/16th free.
325094dd93aeSGeorge Wilson 	 *
325194dd93aeSGeorge Wilson 	 * Note: The 1/16th arena free requirement was put in place
325294dd93aeSGeorge Wilson 	 * to aggressively evict memory from the arc in order to avoid
325394dd93aeSGeorge Wilson 	 * memory fragmentation issues.
325494dd93aeSGeorge Wilson 	 */
32552ec99e3eSMatthew Ahrens 	if (zio_arena != NULL) {
32562ec99e3eSMatthew Ahrens 		n = vmem_size(zio_arena, VMEM_FREE) -
32572ec99e3eSMatthew Ahrens 		    (vmem_size(zio_arena, VMEM_ALLOC) >> 4);
32582ec99e3eSMatthew Ahrens 		if (n < lowest) {
32592ec99e3eSMatthew Ahrens 			lowest = n;
32602ec99e3eSMatthew Ahrens 			r = FMR_ZIO_ARENA;
32612ec99e3eSMatthew Ahrens 		}
32622ec99e3eSMatthew Ahrens 	}
3263fa9e4066Sahrens #else
32642ec99e3eSMatthew Ahrens 	/* Every 100 calls, free a small amount */
3265fa9e4066Sahrens 	if (spa_get_random(100) == 0)
32662ec99e3eSMatthew Ahrens 		lowest = -1024;
3267fa9e4066Sahrens #endif
32682ec99e3eSMatthew Ahrens 
32692ec99e3eSMatthew Ahrens 	last_free_memory = lowest;
32702ec99e3eSMatthew Ahrens 	last_free_reason = r;
32712ec99e3eSMatthew Ahrens 
32722ec99e3eSMatthew Ahrens 	return (lowest);
32732ec99e3eSMatthew Ahrens }
32742ec99e3eSMatthew Ahrens 
32752ec99e3eSMatthew Ahrens 
32762ec99e3eSMatthew Ahrens /*
32772ec99e3eSMatthew Ahrens  * Determine if the system is under memory pressure and is asking
32782ec99e3eSMatthew Ahrens  * to reclaim memory. A return value of TRUE indicates that the system
32792ec99e3eSMatthew Ahrens  * is under memory pressure and that the arc should adjust accordingly.
32802ec99e3eSMatthew Ahrens  */
32812ec99e3eSMatthew Ahrens static boolean_t
32822ec99e3eSMatthew Ahrens arc_reclaim_needed(void)
32832ec99e3eSMatthew Ahrens {
32842ec99e3eSMatthew Ahrens 	return (arc_available_memory() < 0);
3285fa9e4066Sahrens }
3286fa9e4066Sahrens 
3287fa9e4066Sahrens static void
32882ec99e3eSMatthew Ahrens arc_kmem_reap_now(void)
3289fa9e4066Sahrens {
3290fa9e4066Sahrens 	size_t			i;
3291fa9e4066Sahrens 	kmem_cache_t		*prev_cache = NULL;
3292ad23a2dbSjohansen 	kmem_cache_t		*prev_data_cache = NULL;
3293fa9e4066Sahrens 	extern kmem_cache_t	*zio_buf_cache[];
3294ad23a2dbSjohansen 	extern kmem_cache_t	*zio_data_buf_cache[];
329583803b51SGeorge Wilson 	extern kmem_cache_t	*range_seg_cache;
3296fa9e4066Sahrens 
3297033f9833Sek110237 #ifdef _KERNEL
32980e8c6158Smaybee 	if (arc_meta_used >= arc_meta_limit) {
3299033f9833Sek110237 		/*
33000e8c6158Smaybee 		 * We are exceeding our meta-data cache limit.
33010e8c6158Smaybee 		 * Purge some DNLC entries to release holds on meta-data.
3302033f9833Sek110237 		 */
3303cee972f8Sek110237 		dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
33040e8c6158Smaybee 	}
33055dc8af33Smaybee #if defined(__i386)
33065dc8af33Smaybee 	/*
33075dc8af33Smaybee 	 * Reclaim unused memory from all kmem caches.
33085dc8af33Smaybee 	 */
33095dc8af33Smaybee 	kmem_reap();
33105dc8af33Smaybee #endif
3311033f9833Sek110237 #endif
3312033f9833Sek110237 
3313fa9e4066Sahrens 	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
3314fa9e4066Sahrens 		if (zio_buf_cache[i] != prev_cache) {
3315fa9e4066Sahrens 			prev_cache = zio_buf_cache[i];
3316fa9e4066Sahrens 			kmem_cache_reap_now(zio_buf_cache[i]);
3317fa9e4066Sahrens 		}
3318ad23a2dbSjohansen 		if (zio_data_buf_cache[i] != prev_data_cache) {
3319ad23a2dbSjohansen 			prev_data_cache = zio_data_buf_cache[i];
3320ad23a2dbSjohansen 			kmem_cache_reap_now(zio_data_buf_cache[i]);
3321ad23a2dbSjohansen 		}
3322fa9e4066Sahrens 	}
3323ea8dc4b6Seschrock 	kmem_cache_reap_now(buf_cache);
332489c86e32SChris Williamson 	kmem_cache_reap_now(hdr_full_cache);
332589c86e32SChris Williamson 	kmem_cache_reap_now(hdr_l2only_cache);
332683803b51SGeorge Wilson 	kmem_cache_reap_now(range_seg_cache);
332794dd93aeSGeorge Wilson 
33282ec99e3eSMatthew Ahrens 	if (zio_arena != NULL) {
332994dd93aeSGeorge Wilson 		/*
33302ec99e3eSMatthew Ahrens 		 * Ask the vmem arena to reclaim unused memory from its
333194dd93aeSGeorge Wilson 		 * quantum caches.
333294dd93aeSGeorge Wilson 		 */
333394dd93aeSGeorge Wilson 		vmem_qcache_reap(zio_arena);
3334fa9e4066Sahrens 	}
33352ec99e3eSMatthew Ahrens }
3336fa9e4066Sahrens 
3337244781f1SPrakash Surya /*
3338244781f1SPrakash Surya  * Threads can block in arc_get_data_buf() waiting for this thread to evict
3339244781f1SPrakash Surya  * enough data and signal them to proceed. When this happens, the threads in
3340244781f1SPrakash Surya  * arc_get_data_buf() are sleeping while holding the hash lock for their
3341244781f1SPrakash Surya  * particular arc header. Thus, we must be careful to never sleep on a
3342244781f1SPrakash Surya  * hash lock in this thread. This is to prevent the following deadlock:
3343244781f1SPrakash Surya  *
3344244781f1SPrakash Surya  *  - Thread A sleeps on CV in arc_get_data_buf() holding hash lock "L",
3345244781f1SPrakash Surya  *    waiting for the reclaim thread to signal it.
3346244781f1SPrakash Surya  *
3347244781f1SPrakash Surya  *  - arc_reclaim_thread() tries to acquire hash lock "L" using mutex_enter,
3348244781f1SPrakash Surya  *    fails, and goes to sleep forever.
3349244781f1SPrakash Surya  *
3350244781f1SPrakash Surya  * This possible deadlock is avoided by always acquiring a hash lock
3351244781f1SPrakash Surya  * using mutex_tryenter() from arc_reclaim_thread().
3352244781f1SPrakash Surya  */
3353fa9e4066Sahrens static void
3354fa9e4066Sahrens arc_reclaim_thread(void)
3355fa9e4066Sahrens {
3356a8f6344fSEli Rosenthal 	hrtime_t		growtime = 0;
3357fa9e4066Sahrens 	callb_cpr_t		cpr;
3358fa9e4066Sahrens 
3359244781f1SPrakash Surya 	CALLB_CPR_INIT(&cpr, &arc_reclaim_lock, callb_generic_cpr, FTAG);
3360fa9e4066Sahrens 
3361244781f1SPrakash Surya 	mutex_enter(&arc_reclaim_lock);
3362244781f1SPrakash Surya 	while (!arc_reclaim_thread_exit) {
33632ec99e3eSMatthew Ahrens 		int64_t free_memory = arc_available_memory();
3364244781f1SPrakash Surya 		uint64_t evicted = 0;
3365244781f1SPrakash Surya 
3366244781f1SPrakash Surya 		mutex_exit(&arc_reclaim_lock);
3367244781f1SPrakash Surya 
33682ec99e3eSMatthew Ahrens 		if (free_memory < 0) {
3369fa9e4066Sahrens 
33702ec99e3eSMatthew Ahrens 			arc_no_grow = B_TRUE;
33713a737e0dSbrendan 			arc_warm = B_TRUE;
3372fa9e4066Sahrens 
33732ec99e3eSMatthew Ahrens 			/*
33742ec99e3eSMatthew Ahrens 			 * Wait at least zfs_grow_retry (default 60) seconds
33752ec99e3eSMatthew Ahrens 			 * before considering growing.
33762ec99e3eSMatthew Ahrens 			 */
3377a8f6344fSEli Rosenthal 			growtime = gethrtime() + SEC2NSEC(arc_grow_retry);
33782ec99e3eSMatthew Ahrens 
33792ec99e3eSMatthew Ahrens 			arc_kmem_reap_now();
33802ec99e3eSMatthew Ahrens 
33812ec99e3eSMatthew Ahrens 			/*
33822ec99e3eSMatthew Ahrens 			 * If we are still low on memory, shrink the ARC
33832ec99e3eSMatthew Ahrens 			 * so that we have arc_shrink_min free space.
33842ec99e3eSMatthew Ahrens 			 */
33852ec99e3eSMatthew Ahrens 			free_memory = arc_available_memory();
33862ec99e3eSMatthew Ahrens 
33872ec99e3eSMatthew Ahrens 			int64_t to_free =
33882ec99e3eSMatthew Ahrens 			    (arc_c >> arc_shrink_shift) - free_memory;
33892ec99e3eSMatthew Ahrens 			if (to_free > 0) {
33902ec99e3eSMatthew Ahrens #ifdef _KERNEL
33912ec99e3eSMatthew Ahrens 				to_free = MAX(to_free, ptob(needfree));
33922ec99e3eSMatthew Ahrens #endif
33932ec99e3eSMatthew Ahrens 				arc_shrink(to_free);
33942ec99e3eSMatthew Ahrens 			}
33952ec99e3eSMatthew Ahrens 		} else if (free_memory < arc_c >> arc_no_grow_shift) {
33962ec99e3eSMatthew Ahrens 			arc_no_grow = B_TRUE;
3397a8f6344fSEli Rosenthal 		} else if (gethrtime() >= growtime) {
33982ec99e3eSMatthew Ahrens 			arc_no_grow = B_FALSE;
3399fa9e4066Sahrens 		}
3400fa9e4066Sahrens 
3401244781f1SPrakash Surya 		evicted = arc_adjust();
3402641fbdaeSmaybee 
3403244781f1SPrakash Surya 		mutex_enter(&arc_reclaim_lock);
3404244781f1SPrakash Surya 
3405244781f1SPrakash Surya 		/*
3406244781f1SPrakash Surya 		 * If evicted is zero, we couldn't evict anything via
3407244781f1SPrakash Surya 		 * arc_adjust(). This could be due to hash lock
3408244781f1SPrakash Surya 		 * collisions, but more likely due to the majority of
3409244781f1SPrakash Surya 		 * arc buffers being unevictable. Therefore, even if
3410244781f1SPrakash Surya 		 * arc_size is above arc_c, another pass is unlikely to
3411244781f1SPrakash Surya 		 * be helpful and could potentially cause us to enter an
3412244781f1SPrakash Surya 		 * infinite loop.
3413244781f1SPrakash Surya 		 */
3414244781f1SPrakash Surya 		if (arc_size <= arc_c || evicted == 0) {
3415244781f1SPrakash Surya 			/*
3416244781f1SPrakash Surya 			 * We're either no longer overflowing, or we
3417244781f1SPrakash Surya 			 * can't evict anything more, so we should wake
3418244781f1SPrakash Surya 			 * up any threads before we go to sleep.
3419244781f1SPrakash Surya 			 */
3420244781f1SPrakash Surya 			cv_broadcast(&arc_reclaim_waiters_cv);
3421244781f1SPrakash Surya 
3422244781f1SPrakash Surya 			/*
3423244781f1SPrakash Surya 			 * Block until signaled, or after one second (we
3424244781f1SPrakash Surya 			 * might need to perform arc_kmem_reap_now()
3425244781f1SPrakash Surya 			 * even if we aren't being signalled)
3426244781f1SPrakash Surya 			 */
3427244781f1SPrakash Surya 			CALLB_CPR_SAFE_BEGIN(&cpr);
3428a8f6344fSEli Rosenthal 			(void) cv_timedwait_hires(&arc_reclaim_thread_cv,
3429a8f6344fSEli Rosenthal 			    &arc_reclaim_lock, SEC2NSEC(1), MSEC2NSEC(1), 0);
3430244781f1SPrakash Surya 			CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_lock);
3431244781f1SPrakash Surya 		}
3432244781f1SPrakash Surya 	}
3433244781f1SPrakash Surya 
3434244781f1SPrakash Surya 	arc_reclaim_thread_exit = FALSE;
3435244781f1SPrakash Surya 	cv_broadcast(&arc_reclaim_thread_cv);
3436244781f1SPrakash Surya 	CALLB_CPR_EXIT(&cpr);		/* drops arc_reclaim_lock */
3437244781f1SPrakash Surya 	thread_exit();
3438244781f1SPrakash Surya }
3439244781f1SPrakash Surya 
3440244781f1SPrakash Surya static void
3441244781f1SPrakash Surya arc_user_evicts_thread(void)
3442244781f1SPrakash Surya {
3443244781f1SPrakash Surya 	callb_cpr_t cpr;
3444244781f1SPrakash Surya 
3445244781f1SPrakash Surya 	CALLB_CPR_INIT(&cpr, &arc_user_evicts_lock, callb_generic_cpr, FTAG);
3446244781f1SPrakash Surya 
3447244781f1SPrakash Surya 	mutex_enter(&arc_user_evicts_lock);
3448244781f1SPrakash Surya 	while (!arc_user_evicts_thread_exit) {
3449244781f1SPrakash Surya 		mutex_exit(&arc_user_evicts_lock);
3450244781f1SPrakash Surya 
3451ea8dc4b6Seschrock 		arc_do_user_evicts();
3452ea8dc4b6Seschrock 
34534076b1bfSPrakash Surya 		/*
34544076b1bfSPrakash Surya 		 * This is necessary in order for the mdb ::arc dcmd to
34554076b1bfSPrakash Surya 		 * show up to date information. Since the ::arc command
34564076b1bfSPrakash Surya 		 * does not call the kstat's update function, without
34574076b1bfSPrakash Surya 		 * this call, the command may show stale stats for the
34584076b1bfSPrakash Surya 		 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
34594076b1bfSPrakash Surya 		 * with this change, the data might be up to 1 second
34604076b1bfSPrakash Surya 		 * out of date; but that should suffice. The arc_state_t
34614076b1bfSPrakash Surya 		 * structures can be queried directly if more accurate
34624076b1bfSPrakash Surya 		 * information is needed.
34634076b1bfSPrakash Surya 		 */
34644076b1bfSPrakash Surya 		if (arc_ksp != NULL)
34654076b1bfSPrakash Surya 			arc_ksp->ks_update(arc_ksp, KSTAT_READ);
34664076b1bfSPrakash Surya 
3467244781f1SPrakash Surya 		mutex_enter(&arc_user_evicts_lock);
3468244781f1SPrakash Surya 
3469244781f1SPrakash Surya 		/*
3470244781f1SPrakash Surya 		 * Block until signaled, or after one second (we need to
3471244781f1SPrakash Surya 		 * call the arc's kstat update function regularly).
3472244781f1SPrakash Surya 		 */
3473fa9e4066Sahrens 		CALLB_CPR_SAFE_BEGIN(&cpr);
3474244781f1SPrakash Surya 		(void) cv_timedwait(&arc_user_evicts_cv,
3475244781f1SPrakash Surya 		    &arc_user_evicts_lock, ddi_get_lbolt() + hz);
3476244781f1SPrakash Surya 		CALLB_CPR_SAFE_END(&cpr, &arc_user_evicts_lock);
3477fa9e4066Sahrens 	}
3478fa9e4066Sahrens 
3479244781f1SPrakash Surya 	arc_user_evicts_thread_exit = FALSE;
3480244781f1SPrakash Surya 	cv_broadcast(&arc_user_evicts_cv);
3481244781f1SPrakash Surya 	CALLB_CPR_EXIT(&cpr);		/* drops arc_user_evicts_lock */
3482fa9e4066Sahrens 	thread_exit();
3483fa9e4066Sahrens }
3484fa9e4066Sahrens 
3485fa9e4066Sahrens /*
3486ea8dc4b6Seschrock  * Adapt arc info given the number of bytes we are trying to add and
3487ea8dc4b6Seschrock  * the state that we are comming from.  This function is only called
3488ea8dc4b6Seschrock  * when we are adding new content to the cache.
3489fa9e4066Sahrens  */
3490ea8dc4b6Seschrock static void
3491ea8dc4b6Seschrock arc_adapt(int bytes, arc_state_t *state)
3492ea8dc4b6Seschrock {
3493ea8dc4b6Seschrock 	int mult;
34945a98e54bSBrendan Gregg - Sun Microsystems 	uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
34952fd872a7SPrakash Surya 	int64_t mrug_size = refcount_count(&arc_mru_ghost->arcs_size);
34962fd872a7SPrakash Surya 	int64_t mfug_size = refcount_count(&arc_mfu_ghost->arcs_size);
3497ea8dc4b6Seschrock 
3498fa94a07fSbrendan 	if (state == arc_l2c_only)
3499fa94a07fSbrendan 		return;
3500fa94a07fSbrendan 
3501ea8dc4b6Seschrock 	ASSERT(bytes > 0);
3502ea8dc4b6Seschrock 	/*
3503ea8dc4b6Seschrock 	 * Adapt the target size of the MRU list:
3504ea8dc4b6Seschrock 	 *	- if we just hit in the MRU ghost list, then increase
3505ea8dc4b6Seschrock 	 *	  the target size of the MRU list.
3506ea8dc4b6Seschrock 	 *	- if we just hit in the MFU ghost list, then increase
3507ea8dc4b6Seschrock 	 *	  the target size of the MFU list by decreasing the
3508ea8dc4b6Seschrock 	 *	  target size of the MRU list.
3509ea8dc4b6Seschrock 	 */
351044cb6abcSbmc 	if (state == arc_mru_ghost) {
35112fd872a7SPrakash Surya 		mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
35123e4e8481STom Erickson 		mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
3513ea8dc4b6Seschrock 
35145a98e54bSBrendan Gregg - Sun Microsystems 		arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
351544cb6abcSbmc 	} else if (state == arc_mfu_ghost) {
35165a98e54bSBrendan Gregg - Sun Microsystems 		uint64_t delta;
35175a98e54bSBrendan Gregg - Sun Microsystems 
35182fd872a7SPrakash Surya 		mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
35193e4e8481STom Erickson 		mult = MIN(mult, 10);
3520ea8dc4b6Seschrock 
35215a98e54bSBrendan Gregg - Sun Microsystems 		delta = MIN(bytes * mult, arc_p);
35225a98e54bSBrendan Gregg - Sun Microsystems 		arc_p = MAX(arc_p_min, arc_p - delta);
3523ea8dc4b6Seschrock 	}
352444cb6abcSbmc 	ASSERT((int64_t)arc_p >= 0);
3525fa9e4066Sahrens 
3526fa9e4066Sahrens 	if (arc_reclaim_needed()) {
3527244781f1SPrakash Surya 		cv_signal(&arc_reclaim_thread_cv);
3528fa9e4066Sahrens 		return;
3529fa9e4066Sahrens 	}
3530fa9e4066Sahrens 
353144cb6abcSbmc 	if (arc_no_grow)
3532fa9e4066Sahrens 		return;
3533fa9e4066Sahrens 
353444cb6abcSbmc 	if (arc_c >= arc_c_max)
3535ea8dc4b6Seschrock 		return;
3536ea8dc4b6Seschrock 
3537fa9e4066Sahrens 	/*
3538ea8dc4b6Seschrock 	 * If we're within (2 * maxblocksize) bytes of the target
3539ea8dc4b6Seschrock 	 * cache size, increment the target cache size
3540fa9e4066Sahrens 	 */
354144cb6abcSbmc 	if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
354244cb6abcSbmc 		atomic_add_64(&arc_c, (int64_t)bytes);
354344cb6abcSbmc 		if (arc_c > arc_c_max)
354444cb6abcSbmc 			arc_c = arc_c_max;
354544cb6abcSbmc 		else if (state == arc_anon)
354644cb6abcSbmc 			atomic_add_64(&arc_p, (int64_t)bytes);
354744cb6abcSbmc 		if (arc_p > arc_c)
354844cb6abcSbmc 			arc_p = arc_c;
3549fa9e4066Sahrens 	}
355044cb6abcSbmc 	ASSERT((int64_t)arc_p >= 0);
3551fa9e4066Sahrens }
3552fa9e4066Sahrens 
3553fa9e4066Sahrens /*
3554244781f1SPrakash Surya  * Check if arc_size has grown past our upper threshold, determined by
3555244781f1SPrakash Surya  * zfs_arc_overflow_shift.
3556fa9e4066Sahrens  */
3557244781f1SPrakash Surya static boolean_t
3558244781f1SPrakash Surya arc_is_overflowing(void)
3559fa9e4066Sahrens {
3560244781f1SPrakash Surya 	/* Always allow at least one block of overflow */
3561244781f1SPrakash Surya 	uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
3562244781f1SPrakash Surya 	    arc_c >> zfs_arc_overflow_shift);
35630e8c6158Smaybee 
3564244781f1SPrakash Surya 	return (arc_size >= arc_c + overflow);
3565fa9e4066Sahrens }
3566fa9e4066Sahrens 
3567fa9e4066Sahrens /*
3568244781f1SPrakash Surya  * The buffer, supplied as the first argument, needs a data block. If we
3569244781f1SPrakash Surya  * are hitting the hard limit for the cache size, we must sleep, waiting
3570244781f1SPrakash Surya  * for the eviction thread to catch up. If we're past the target size
3571244781f1SPrakash Surya  * but below the hard limit, we'll only signal the reclaim thread and
3572244781f1SPrakash Surya  * continue on.
3573fa9e4066Sahrens  */
3574fa9e4066Sahrens static void
357544eda4d7Smaybee arc_get_data_buf(arc_buf_t *buf)
3576fa9e4066Sahrens {
357789c86e32SChris Williamson 	arc_state_t		*state = buf->b_hdr->b_l1hdr.b_state;
357844eda4d7Smaybee 	uint64_t		size = buf->b_hdr->b_size;
357989c86e32SChris Williamson 	arc_buf_contents_t	type = arc_buf_type(buf->b_hdr);
3580fa9e4066Sahrens 
358144eda4d7Smaybee 	arc_adapt(size, state);
3582fa9e4066Sahrens 
358344eda4d7Smaybee 	/*
3584244781f1SPrakash Surya 	 * If arc_size is currently overflowing, and has grown past our
3585244781f1SPrakash Surya 	 * upper limit, we must be adding data faster than the evict
3586244781f1SPrakash Surya 	 * thread can evict. Thus, to ensure we don't compound the
3587244781f1SPrakash Surya 	 * problem by adding more data and forcing arc_size to grow even
3588244781f1SPrakash Surya 	 * further past it's target size, we halt and wait for the
3589244781f1SPrakash Surya 	 * eviction thread to catch up.
3590244781f1SPrakash Surya 	 *
3591244781f1SPrakash Surya 	 * It's also possible that the reclaim thread is unable to evict
3592244781f1SPrakash Surya 	 * enough buffers to get arc_size below the overflow limit (e.g.
3593244781f1SPrakash Surya 	 * due to buffers being un-evictable, or hash lock collisions).
3594244781f1SPrakash Surya 	 * In this case, we want to proceed regardless if we're
3595244781f1SPrakash Surya 	 * overflowing; thus we don't use a while loop here.
359644eda4d7Smaybee 	 */
3597244781f1SPrakash Surya 	if (arc_is_overflowing()) {
3598244781f1SPrakash Surya 		mutex_enter(&arc_reclaim_lock);
359944eda4d7Smaybee 
360044eda4d7Smaybee 		/*
3601244781f1SPrakash Surya 		 * Now that we've acquired the lock, we may no longer be
3602244781f1SPrakash Surya 		 * over the overflow limit, lets check.
3603244781f1SPrakash Surya 		 *
3604244781f1SPrakash Surya 		 * We're ignoring the case of spurious wake ups. If that
3605244781f1SPrakash Surya 		 * were to happen, it'd let this thread consume an ARC
3606244781f1SPrakash Surya 		 * buffer before it should have (i.e. before we're under
3607244781f1SPrakash Surya 		 * the overflow limit and were signalled by the reclaim
3608244781f1SPrakash Surya 		 * thread). As long as that is a rare occurrence, it
3609244781f1SPrakash Surya 		 * shouldn't cause any harm.
361044eda4d7Smaybee 		 */
3611244781f1SPrakash Surya 		if (arc_is_overflowing()) {
3612244781f1SPrakash Surya 			cv_signal(&arc_reclaim_thread_cv);
3613244781f1SPrakash Surya 			cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
361444eda4d7Smaybee 		}
3615244781f1SPrakash Surya 
3616244781f1SPrakash Surya 		mutex_exit(&arc_reclaim_lock);
3617244781f1SPrakash Surya 	}
3618244781f1SPrakash Surya 
3619ad23a2dbSjohansen 	if (type == ARC_BUFC_METADATA) {
362044eda4d7Smaybee 		buf->b_data = zio_buf_alloc(size);
36214076b1bfSPrakash Surya 		arc_space_consume(size, ARC_SPACE_META);
3622ad23a2dbSjohansen 	} else {
3623ad23a2dbSjohansen 		ASSERT(type == ARC_BUFC_DATA);
3624ad23a2dbSjohansen 		buf->b_data = zio_data_buf_alloc(size);
36254076b1bfSPrakash Surya 		arc_space_consume(size, ARC_SPACE_DATA);
36260e8c6158Smaybee 	}
3627244781f1SPrakash Surya 
362844eda4d7Smaybee 	/*
362944eda4d7Smaybee 	 * Update the state size.  Note that ghost states have a
363044eda4d7Smaybee 	 * "ghost size" and so don't need to be updated.
363144eda4d7Smaybee 	 */
363289c86e32SChris Williamson 	if (!GHOST_STATE(buf->b_hdr->b_l1hdr.b_state)) {
363344eda4d7Smaybee 		arc_buf_hdr_t *hdr = buf->b_hdr;
36342fd872a7SPrakash Surya 		arc_state_t *state = hdr->b_l1hdr.b_state;
363544eda4d7Smaybee 
36362fd872a7SPrakash Surya 		(void) refcount_add_many(&state->arcs_size, size, buf);
3637244781f1SPrakash Surya 
3638244781f1SPrakash Surya 		/*
3639244781f1SPrakash Surya 		 * If this is reached via arc_read, the link is
3640244781f1SPrakash Surya 		 * protected by the hash lock. If reached via
3641244781f1SPrakash Surya 		 * arc_buf_alloc, the header should not be accessed by
3642244781f1SPrakash Surya 		 * any other thread. And, if reached via arc_read_done,
3643244781f1SPrakash Surya 		 * the hash lock will protect it if it's found in the
3644244781f1SPrakash Surya 		 * hash table; otherwise no other thread should be
3645244781f1SPrakash Surya 		 * trying to [add|remove]_reference it.
3646244781f1SPrakash Surya 		 */
3647244781f1SPrakash Surya 		if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
364889c86e32SChris Williamson 			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
364989c86e32SChris Williamson 			atomic_add_64(&hdr->b_l1hdr.b_state->arcs_lsize[type],
365089c86e32SChris Williamson 			    size);
3651fa9e4066Sahrens 		}
3652641fbdaeSmaybee 		/*
3653641fbdaeSmaybee 		 * If we are growing the cache, and we are adding anonymous
365444cb6abcSbmc 		 * data, and we have outgrown arc_p, update arc_p
3655641fbdaeSmaybee 		 */
365689c86e32SChris Williamson 		if (arc_size < arc_c && hdr->b_l1hdr.b_state == arc_anon &&
36572fd872a7SPrakash Surya 		    (refcount_count(&arc_anon->arcs_size) +
36582fd872a7SPrakash Surya 		    refcount_count(&arc_mru->arcs_size) > arc_p))
365944cb6abcSbmc 			arc_p = MIN(arc_c, arc_p + size);
3660fa9e4066Sahrens 	}
3661fa9e4066Sahrens }
3662fa9e4066Sahrens 
3663fa9e4066Sahrens /*
3664fa9e4066Sahrens  * This routine is called whenever a buffer is accessed.
3665ea8dc4b6Seschrock  * NOTE: the hash lock is dropped in this function.
3666fa9e4066Sahrens  */
3667fa9e4066Sahrens static void
36687adb730bSGeorge Wilson arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3669fa9e4066Sahrens {
3670d3d50737SRafael Vanoni 	clock_t now;
3671d3d50737SRafael Vanoni 
3672fa9e4066Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
367389c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
3674fa9e4066Sahrens 
367589c86e32SChris Williamson 	if (hdr->b_l1hdr.b_state == arc_anon) {
3676fa9e4066Sahrens 		/*
3677fa9e4066Sahrens 		 * This buffer is not in the cache, and does not
3678fa9e4066Sahrens 		 * appear in our "ghost" list.  Add the new buffer
3679fa9e4066Sahrens 		 * to the MRU state.
3680fa9e4066Sahrens 		 */
3681fa9e4066Sahrens 
368289c86e32SChris Williamson 		ASSERT0(hdr->b_l1hdr.b_arc_access);
368389c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
36847adb730bSGeorge Wilson 		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
36857adb730bSGeorge Wilson 		arc_change_state(arc_mru, hdr, hash_lock);
3686fa9e4066Sahrens 
368789c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mru) {
3688d3d50737SRafael Vanoni 		now = ddi_get_lbolt();
3689d3d50737SRafael Vanoni 
3690fa9e4066Sahrens 		/*
369113506d1eSmaybee 		 * If this buffer is here because of a prefetch, then either:
369213506d1eSmaybee 		 * - clear the flag if this is a "referencing" read
369313506d1eSmaybee 		 *   (any subsequent access will bump this into the MFU state).
369413506d1eSmaybee 		 * or
369513506d1eSmaybee 		 * - move the buffer to the head of the list if this is
369613506d1eSmaybee 		 *   another prefetch (to make it less likely to be evicted).
3697fa9e4066Sahrens 		 */
369889c86e32SChris Williamson 		if (HDR_PREFETCH(hdr)) {
369989c86e32SChris Williamson 			if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
3700244781f1SPrakash Surya 				/* link protected by hash lock */
3701244781f1SPrakash Surya 				ASSERT(multilist_link_active(
370289c86e32SChris Williamson 				    &hdr->b_l1hdr.b_arc_node));
370313506d1eSmaybee 			} else {
37047adb730bSGeorge Wilson 				hdr->b_flags &= ~ARC_FLAG_PREFETCH;
370544cb6abcSbmc 				ARCSTAT_BUMP(arcstat_mru_hits);
370613506d1eSmaybee 			}
370789c86e32SChris Williamson 			hdr->b_l1hdr.b_arc_access = now;
3708fa9e4066Sahrens 			return;
3709fa9e4066Sahrens 		}
3710fa9e4066Sahrens 
3711fa9e4066Sahrens 		/*
3712fa9e4066Sahrens 		 * This buffer has been "accessed" only once so far,
3713fa9e4066Sahrens 		 * but it is still in the cache. Move it to the MFU
3714fa9e4066Sahrens 		 * state.
3715fa9e4066Sahrens 		 */
371689c86e32SChris Williamson 		if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
3717fa9e4066Sahrens 			/*
3718fa9e4066Sahrens 			 * More than 125ms have passed since we
3719fa9e4066Sahrens 			 * instantiated this buffer.  Move it to the
3720fa9e4066Sahrens 			 * most frequently used state.
3721fa9e4066Sahrens 			 */
372289c86e32SChris Williamson 			hdr->b_l1hdr.b_arc_access = now;
37237adb730bSGeorge Wilson 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
37247adb730bSGeorge Wilson 			arc_change_state(arc_mfu, hdr, hash_lock);
3725fa9e4066Sahrens 		}
372644cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mru_hits);
372789c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
3728fa9e4066Sahrens 		arc_state_t	*new_state;
3729fa9e4066Sahrens 		/*
3730fa9e4066Sahrens 		 * This buffer has been "accessed" recently, but
3731fa9e4066Sahrens 		 * was evicted from the cache.  Move it to the
3732fa9e4066Sahrens 		 * MFU state.
3733fa9e4066Sahrens 		 */
3734fa9e4066Sahrens 
373589c86e32SChris Williamson 		if (HDR_PREFETCH(hdr)) {
373644cb6abcSbmc 			new_state = arc_mru;
373789c86e32SChris Williamson 			if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0)
37387adb730bSGeorge Wilson 				hdr->b_flags &= ~ARC_FLAG_PREFETCH;
37397adb730bSGeorge Wilson 			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3740fa9e4066Sahrens 		} else {
374144cb6abcSbmc 			new_state = arc_mfu;
37427adb730bSGeorge Wilson 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3743fa9e4066Sahrens 		}
3744fa9e4066Sahrens 
374589c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
37467adb730bSGeorge Wilson 		arc_change_state(new_state, hdr, hash_lock);
3747fa9e4066Sahrens 
374844cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
374989c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mfu) {
3750fa9e4066Sahrens 		/*
3751fa9e4066Sahrens 		 * This buffer has been accessed more than once and is
3752fa9e4066Sahrens 		 * still in the cache.  Keep it in the MFU state.
3753fa9e4066Sahrens 		 *
375413506d1eSmaybee 		 * NOTE: an add_reference() that occurred when we did
375513506d1eSmaybee 		 * the arc_read() will have kicked this off the list.
375613506d1eSmaybee 		 * If it was a prefetch, we will explicitly move it to
375713506d1eSmaybee 		 * the head of the list now.
3758fa9e4066Sahrens 		 */
375989c86e32SChris Williamson 		if ((HDR_PREFETCH(hdr)) != 0) {
376089c86e32SChris Williamson 			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3761244781f1SPrakash Surya 			/* link protected by hash_lock */
3762244781f1SPrakash Surya 			ASSERT(multilist_link_active(&hdr->b_l1hdr.b_arc_node));
376313506d1eSmaybee 		}
376444cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mfu_hits);
376589c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
376689c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
376744cb6abcSbmc 		arc_state_t	*new_state = arc_mfu;
3768fa9e4066Sahrens 		/*
3769fa9e4066Sahrens 		 * This buffer has been accessed more than once but has
3770fa9e4066Sahrens 		 * been evicted from the cache.  Move it back to the
3771fa9e4066Sahrens 		 * MFU state.
3772fa9e4066Sahrens 		 */
3773fa9e4066Sahrens 
377489c86e32SChris Williamson 		if (HDR_PREFETCH(hdr)) {
377513506d1eSmaybee 			/*
377613506d1eSmaybee 			 * This is a prefetch access...
377713506d1eSmaybee 			 * move this block back to the MRU state.
377813506d1eSmaybee 			 */
377989c86e32SChris Williamson 			ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
378044cb6abcSbmc 			new_state = arc_mru;
378113506d1eSmaybee 		}
378213506d1eSmaybee 
378389c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
37847adb730bSGeorge Wilson 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
37857adb730bSGeorge Wilson 		arc_change_state(new_state, hdr, hash_lock);
3786fa9e4066Sahrens 
378744cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
378889c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
3789fa94a07fSbrendan 		/*
3790fa94a07fSbrendan 		 * This buffer is on the 2nd Level ARC.
3791fa94a07fSbrendan 		 */
3792fa94a07fSbrendan 
379389c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
37947adb730bSGeorge Wilson 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
37957adb730bSGeorge Wilson 		arc_change_state(arc_mfu, hdr, hash_lock);
3796fa9e4066Sahrens 	} else {
3797fa9e4066Sahrens 		ASSERT(!"invalid arc state");
3798fa9e4066Sahrens 	}
3799fa9e4066Sahrens }
3800fa9e4066Sahrens 
3801fa9e4066Sahrens /* a generic arc_done_func_t which you can use */
3802fa9e4066Sahrens /* ARGSUSED */
3803fa9e4066Sahrens void
3804fa9e4066Sahrens arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
3805fa9e4066Sahrens {
38063f9d6ad7SLin Ling 	if (zio == NULL || zio->io_error == 0)
3807fa9e4066Sahrens 		bcopy(buf->b_data, arg, buf->b_hdr->b_size);
38083b2aab18SMatthew Ahrens 	VERIFY(arc_buf_remove_ref(buf, arg));
3809fa9e4066Sahrens }
3810fa9e4066Sahrens 
38110e8c6158Smaybee /* a generic arc_done_func_t */
3812fa9e4066Sahrens void
3813fa9e4066Sahrens arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
3814fa9e4066Sahrens {
3815fa9e4066Sahrens 	arc_buf_t **bufp = arg;
3816fa9e4066Sahrens 	if (zio && zio->io_error) {
38173b2aab18SMatthew Ahrens 		VERIFY(arc_buf_remove_ref(buf, arg));
3818fa9e4066Sahrens 		*bufp = NULL;
3819fa9e4066Sahrens 	} else {
3820fa9e4066Sahrens 		*bufp = buf;
38213f9d6ad7SLin Ling 		ASSERT(buf->b_data);
3822fa9e4066Sahrens 	}
3823fa9e4066Sahrens }
3824fa9e4066Sahrens 
3825fa9e4066Sahrens static void
3826fa9e4066Sahrens arc_read_done(zio_t *zio)
3827fa9e4066Sahrens {
38285d7b4d43SMatthew Ahrens 	arc_buf_hdr_t	*hdr;
3829fa9e4066Sahrens 	arc_buf_t	*buf;
3830fa9e4066Sahrens 	arc_buf_t	*abuf;	/* buffer we're assigning to callback */
38315d7b4d43SMatthew Ahrens 	kmutex_t	*hash_lock = NULL;
3832fa9e4066Sahrens 	arc_callback_t	*callback_list, *acb;
3833fa9e4066Sahrens 	int		freeable = FALSE;
3834fa9e4066Sahrens 
3835fa9e4066Sahrens 	buf = zio->io_private;
3836fa9e4066Sahrens 	hdr = buf->b_hdr;
3837fa9e4066Sahrens 
3838bbf4a8dfSmaybee 	/*
3839bbf4a8dfSmaybee 	 * The hdr was inserted into hash-table and removed from lists
3840bbf4a8dfSmaybee 	 * prior to starting I/O.  We should find this header, since
3841bbf4a8dfSmaybee 	 * it's in the hash table, and it should be legit since it's
3842bbf4a8dfSmaybee 	 * not possible to evict it during the I/O.  The only possible
3843bbf4a8dfSmaybee 	 * reason for it not to be found is if we were freed during the
3844bbf4a8dfSmaybee 	 * read.
3845bbf4a8dfSmaybee 	 */
38465d7b4d43SMatthew Ahrens 	if (HDR_IN_HASH_TABLE(hdr)) {
38475d7b4d43SMatthew Ahrens 		ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
38485d7b4d43SMatthew Ahrens 		ASSERT3U(hdr->b_dva.dva_word[0], ==,
38495d7b4d43SMatthew Ahrens 		    BP_IDENTITY(zio->io_bp)->dva_word[0]);
38505d7b4d43SMatthew Ahrens 		ASSERT3U(hdr->b_dva.dva_word[1], ==,
38515d7b4d43SMatthew Ahrens 		    BP_IDENTITY(zio->io_bp)->dva_word[1]);
38525d7b4d43SMatthew Ahrens 
38535d7b4d43SMatthew Ahrens 		arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
3854fa9e4066Sahrens 		    &hash_lock);
3855fa9e4066Sahrens 
38565d7b4d43SMatthew Ahrens 		ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) &&
38575d7b4d43SMatthew Ahrens 		    hash_lock == NULL) ||
38585d7b4d43SMatthew Ahrens 		    (found == hdr &&
38595d7b4d43SMatthew Ahrens 		    DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
3860fa94a07fSbrendan 		    (found == hdr && HDR_L2_READING(hdr)));
38615d7b4d43SMatthew Ahrens 	}
3862fa94a07fSbrendan 
38637adb730bSGeorge Wilson 	hdr->b_flags &= ~ARC_FLAG_L2_EVICTED;
386489c86e32SChris Williamson 	if (l2arc_noprefetch && HDR_PREFETCH(hdr))
38657adb730bSGeorge Wilson 		hdr->b_flags &= ~ARC_FLAG_L2CACHE;
3866fa9e4066Sahrens 
3867fa9e4066Sahrens 	/* byteswap if necessary */
386889c86e32SChris Williamson 	callback_list = hdr->b_l1hdr.b_acb;
3869fa9e4066Sahrens 	ASSERT(callback_list != NULL);
38708e0f0d3dSWilliam Gorrell 	if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
3871ad135b5dSChristopher Siden 		dmu_object_byteswap_t bswap =
3872ad135b5dSChristopher Siden 		    DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
3873088f3894Sahrens 		arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
3874088f3894Sahrens 		    byteswap_uint64_array :
3875ad135b5dSChristopher Siden 		    dmu_ot_byteswap[bswap].ob_func;
3876088f3894Sahrens 		func(buf->b_data, hdr->b_size);
3877088f3894Sahrens 	}
3878fa9e4066Sahrens 
3879fa94a07fSbrendan 	arc_cksum_compute(buf, B_FALSE);
3880cd1c8b85SMatthew Ahrens 	arc_buf_watch(buf);
38816b4acc8bSahrens 
388289c86e32SChris Williamson 	if (hash_lock && zio->io_error == 0 &&
388389c86e32SChris Williamson 	    hdr->b_l1hdr.b_state == arc_anon) {
3884b24ab676SJeff Bonwick 		/*
3885b24ab676SJeff Bonwick 		 * Only call arc_access on anonymous buffers.  This is because
3886b24ab676SJeff Bonwick 		 * if we've issued an I/O for an evicted buffer, we've already
3887b24ab676SJeff Bonwick 		 * called arc_access (to prevent any simultaneous readers from
3888b24ab676SJeff Bonwick 		 * getting confused).
3889b24ab676SJeff Bonwick 		 */
3890b24ab676SJeff Bonwick 		arc_access(hdr, hash_lock);
3891b24ab676SJeff Bonwick 	}
3892b24ab676SJeff Bonwick 
3893fa9e4066Sahrens 	/* create copies of the data buffer for the callers */
3894fa9e4066Sahrens 	abuf = buf;
3895fa9e4066Sahrens 	for (acb = callback_list; acb; acb = acb->acb_next) {
3896fa9e4066Sahrens 		if (acb->acb_done) {
38979253d63dSGeorge Wilson 			if (abuf == NULL) {
38989253d63dSGeorge Wilson 				ARCSTAT_BUMP(arcstat_duplicate_reads);
389944eda4d7Smaybee 				abuf = arc_buf_clone(buf);
39009253d63dSGeorge Wilson 			}
3901fa9e4066Sahrens 			acb->acb_buf = abuf;
3902fa9e4066Sahrens 			abuf = NULL;
3903fa9e4066Sahrens 		}
3904fa9e4066Sahrens 	}
390589c86e32SChris Williamson 	hdr->b_l1hdr.b_acb = NULL;
39067adb730bSGeorge Wilson 	hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
3907ea8dc4b6Seschrock 	ASSERT(!HDR_BUF_AVAILABLE(hdr));
3908b24ab676SJeff Bonwick 	if (abuf == buf) {
3909b24ab676SJeff Bonwick 		ASSERT(buf->b_efunc == NULL);
391089c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_datacnt == 1);
39117adb730bSGeorge Wilson 		hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
3912b24ab676SJeff Bonwick 	}
3913fa9e4066Sahrens 
391489c86e32SChris Williamson 	ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
391589c86e32SChris Williamson 	    callback_list != NULL);
3916fa9e4066Sahrens 
3917fa9e4066Sahrens 	if (zio->io_error != 0) {
39187adb730bSGeorge Wilson 		hdr->b_flags |= ARC_FLAG_IO_ERROR;
391989c86e32SChris Williamson 		if (hdr->b_l1hdr.b_state != arc_anon)
392044cb6abcSbmc 			arc_change_state(arc_anon, hdr, hash_lock);
3921ea8dc4b6Seschrock 		if (HDR_IN_HASH_TABLE(hdr))
3922ea8dc4b6Seschrock 			buf_hash_remove(hdr);
392389c86e32SChris Williamson 		freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
3924fa9e4066Sahrens 	}
3925fa9e4066Sahrens 
3926ea8dc4b6Seschrock 	/*
392713506d1eSmaybee 	 * Broadcast before we drop the hash_lock to avoid the possibility
392813506d1eSmaybee 	 * that the hdr (and hence the cv) might be freed before we get to
392913506d1eSmaybee 	 * the cv_broadcast().
3930ea8dc4b6Seschrock 	 */
393189c86e32SChris Williamson 	cv_broadcast(&hdr->b_l1hdr.b_cv);
3932ea8dc4b6Seschrock 
393389c86e32SChris Williamson 	if (hash_lock != NULL) {
3934fa9e4066Sahrens 		mutex_exit(hash_lock);
3935fa9e4066Sahrens 	} else {
3936fa9e4066Sahrens 		/*
3937fa9e4066Sahrens 		 * This block was freed while we waited for the read to
3938fa9e4066Sahrens 		 * complete.  It has been removed from the hash table and
3939fa9e4066Sahrens 		 * moved to the anonymous state (so that it won't show up
3940fa9e4066Sahrens 		 * in the cache).
3941fa9e4066Sahrens 		 */
394289c86e32SChris Williamson 		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
394389c86e32SChris Williamson 		freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
3944fa9e4066Sahrens 	}
3945fa9e4066Sahrens 
3946fa9e4066Sahrens 	/* execute each callback and free its structure */
3947fa9e4066Sahrens 	while ((acb = callback_list) != NULL) {
3948fa9e4066Sahrens 		if (acb->acb_done)
3949fa9e4066Sahrens 			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
3950fa9e4066Sahrens 
3951fa9e4066Sahrens 		if (acb->acb_zio_dummy != NULL) {
3952fa9e4066Sahrens 			acb->acb_zio_dummy->io_error = zio->io_error;
3953fa9e4066Sahrens 			zio_nowait(acb->acb_zio_dummy);
3954fa9e4066Sahrens 		}
3955fa9e4066Sahrens 
3956fa9e4066Sahrens 		callback_list = acb->acb_next;
3957fa9e4066Sahrens 		kmem_free(acb, sizeof (arc_callback_t));
3958fa9e4066Sahrens 	}
3959fa9e4066Sahrens 
3960fa9e4066Sahrens 	if (freeable)
3961ea8dc4b6Seschrock 		arc_hdr_destroy(hdr);
3962fa9e4066Sahrens }
3963fa9e4066Sahrens 
3964fa9e4066Sahrens /*
3965fc98fea5SBart Coddens  * "Read" the block at the specified DVA (in bp) via the
3966fa9e4066Sahrens  * cache.  If the block is found in the cache, invoke the provided
3967fa9e4066Sahrens  * callback immediately and return.  Note that the `zio' parameter
3968fa9e4066Sahrens  * in the callback will be NULL in this case, since no IO was
3969fa9e4066Sahrens  * required.  If the block is not in the cache pass the read request
3970fa9e4066Sahrens  * on to the spa with a substitute callback function, so that the
3971fa9e4066Sahrens  * requested block will be added to the cache.
3972fa9e4066Sahrens  *
3973fa9e4066Sahrens  * If a read request arrives for a block that has a read in-progress,
3974fa9e4066Sahrens  * either wait for the in-progress read to complete (and return the
3975fa9e4066Sahrens  * results); or, if this is a read with a "done" func, add a record
3976fa9e4066Sahrens  * to the read to invoke the "done" func when the read completes,
3977fa9e4066Sahrens  * and return; or just return.
3978fa9e4066Sahrens  *
3979fa9e4066Sahrens  * arc_read_done() will invoke all the requested "done" functions
3980fa9e4066Sahrens  * for readers of this block.
3981fa9e4066Sahrens  */
3982fa9e4066Sahrens int
39831b912ec7SGeorge Wilson arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
39847adb730bSGeorge Wilson     void *private, zio_priority_t priority, int zio_flags,
39857adb730bSGeorge Wilson     arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
3986fa9e4066Sahrens {
39875d7b4d43SMatthew Ahrens 	arc_buf_hdr_t *hdr = NULL;
3988d5285caeSGeorge Wilson 	arc_buf_t *buf = NULL;
39895d7b4d43SMatthew Ahrens 	kmutex_t *hash_lock = NULL;
3990fa9e4066Sahrens 	zio_t *rzio;
3991e9103aaeSGarrett D'Amore 	uint64_t guid = spa_load_guid(spa);
3992fa9e4066Sahrens 
39935d7b4d43SMatthew Ahrens 	ASSERT(!BP_IS_EMBEDDED(bp) ||
39945d7b4d43SMatthew Ahrens 	    BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
39955d7b4d43SMatthew Ahrens 
3996fa9e4066Sahrens top:
39975d7b4d43SMatthew Ahrens 	if (!BP_IS_EMBEDDED(bp)) {
39985d7b4d43SMatthew Ahrens 		/*
39995d7b4d43SMatthew Ahrens 		 * Embedded BP's have no DVA and require no I/O to "read".
40005d7b4d43SMatthew Ahrens 		 * Create an anonymous arc buf to back it.
40015d7b4d43SMatthew Ahrens 		 */
40025d7b4d43SMatthew Ahrens 		hdr = buf_hash_find(guid, bp, &hash_lock);
40035d7b4d43SMatthew Ahrens 	}
40045d7b4d43SMatthew Ahrens 
400589c86e32SChris Williamson 	if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_datacnt > 0) {
4006fa9e4066Sahrens 
40077adb730bSGeorge Wilson 		*arc_flags |= ARC_FLAG_CACHED;
400813506d1eSmaybee 
4009fa9e4066Sahrens 		if (HDR_IO_IN_PROGRESS(hdr)) {
401013506d1eSmaybee 
4011cf6106c8SMatthew Ahrens 			if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
4012cf6106c8SMatthew Ahrens 			    priority == ZIO_PRIORITY_SYNC_READ) {
4013cf6106c8SMatthew Ahrens 				/*
4014cf6106c8SMatthew Ahrens 				 * This sync read must wait for an
4015cf6106c8SMatthew Ahrens 				 * in-progress async read (e.g. a predictive
4016cf6106c8SMatthew Ahrens 				 * prefetch).  Async reads are queued
4017cf6106c8SMatthew Ahrens 				 * separately at the vdev_queue layer, so
4018cf6106c8SMatthew Ahrens 				 * this is a form of priority inversion.
4019cf6106c8SMatthew Ahrens 				 * Ideally, we would "inherit" the demand
4020cf6106c8SMatthew Ahrens 				 * i/o's priority by moving the i/o from
4021cf6106c8SMatthew Ahrens 				 * the async queue to the synchronous queue,
4022cf6106c8SMatthew Ahrens 				 * but there is currently no mechanism to do
4023cf6106c8SMatthew Ahrens 				 * so.  Track this so that we can evaluate
4024cf6106c8SMatthew Ahrens 				 * the magnitude of this potential performance
4025cf6106c8SMatthew Ahrens 				 * problem.
4026cf6106c8SMatthew Ahrens 				 *
4027cf6106c8SMatthew Ahrens 				 * Note that if the prefetch i/o is already
4028cf6106c8SMatthew Ahrens 				 * active (has been issued to the device),
4029cf6106c8SMatthew Ahrens 				 * the prefetch improved performance, because
4030cf6106c8SMatthew Ahrens 				 * we issued it sooner than we would have
4031cf6106c8SMatthew Ahrens 				 * without the prefetch.
4032cf6106c8SMatthew Ahrens 				 */
4033cf6106c8SMatthew Ahrens 				DTRACE_PROBE1(arc__sync__wait__for__async,
4034cf6106c8SMatthew Ahrens 				    arc_buf_hdr_t *, hdr);
4035cf6106c8SMatthew Ahrens 				ARCSTAT_BUMP(arcstat_sync_wait_for_async);
4036cf6106c8SMatthew Ahrens 			}
4037cf6106c8SMatthew Ahrens 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
4038cf6106c8SMatthew Ahrens 				hdr->b_flags &= ~ARC_FLAG_PREDICTIVE_PREFETCH;
4039cf6106c8SMatthew Ahrens 			}
4040cf6106c8SMatthew Ahrens 
40417adb730bSGeorge Wilson 			if (*arc_flags & ARC_FLAG_WAIT) {
404289c86e32SChris Williamson 				cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
404313506d1eSmaybee 				mutex_exit(hash_lock);
404413506d1eSmaybee 				goto top;
404513506d1eSmaybee 			}
40467adb730bSGeorge Wilson 			ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
404713506d1eSmaybee 
404813506d1eSmaybee 			if (done) {
4049fa9e4066Sahrens 				arc_callback_t *acb = NULL;
4050fa9e4066Sahrens 
4051fa9e4066Sahrens 				acb = kmem_zalloc(sizeof (arc_callback_t),
4052fa9e4066Sahrens 				    KM_SLEEP);
4053fa9e4066Sahrens 				acb->acb_done = done;
4054fa9e4066Sahrens 				acb->acb_private = private;
4055fa9e4066Sahrens 				if (pio != NULL)
4056fa9e4066Sahrens 					acb->acb_zio_dummy = zio_null(pio,
4057a3f829aeSBill Moore 					    spa, NULL, NULL, NULL, zio_flags);
4058fa9e4066Sahrens 
4059fa9e4066Sahrens 				ASSERT(acb->acb_done != NULL);
406089c86e32SChris Williamson 				acb->acb_next = hdr->b_l1hdr.b_acb;
406189c86e32SChris Williamson 				hdr->b_l1hdr.b_acb = acb;
4062fa9e4066Sahrens 				add_reference(hdr, hash_lock, private);
4063fa9e4066Sahrens 				mutex_exit(hash_lock);
4064fa9e4066Sahrens 				return (0);
4065fa9e4066Sahrens 			}
4066fa9e4066Sahrens 			mutex_exit(hash_lock);
4067fa9e4066Sahrens 			return (0);
4068fa9e4066Sahrens 		}
4069fa9e4066Sahrens 
407089c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
407189c86e32SChris Williamson 		    hdr->b_l1hdr.b_state == arc_mfu);
4072ea8dc4b6Seschrock 
4073ea8dc4b6Seschrock 		if (done) {
4074cf6106c8SMatthew Ahrens 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
4075cf6106c8SMatthew Ahrens 				/*
4076cf6106c8SMatthew Ahrens 				 * This is a demand read which does not have to
4077cf6106c8SMatthew Ahrens 				 * wait for i/o because we did a predictive
4078cf6106c8SMatthew Ahrens 				 * prefetch i/o for it, which has completed.
4079cf6106c8SMatthew Ahrens 				 */
4080cf6106c8SMatthew Ahrens 				DTRACE_PROBE1(
4081cf6106c8SMatthew Ahrens 				    arc__demand__hit__predictive__prefetch,
4082cf6106c8SMatthew Ahrens 				    arc_buf_hdr_t *, hdr);
4083cf6106c8SMatthew Ahrens 				ARCSTAT_BUMP(
4084cf6106c8SMatthew Ahrens 				    arcstat_demand_hit_predictive_prefetch);
4085cf6106c8SMatthew Ahrens 				hdr->b_flags &= ~ARC_FLAG_PREDICTIVE_PREFETCH;
4086cf6106c8SMatthew Ahrens 			}
408744eda4d7Smaybee 			add_reference(hdr, hash_lock, private);
4088fa9e4066Sahrens 			/*
4089ea8dc4b6Seschrock 			 * If this block is already in use, create a new
4090ea8dc4b6Seschrock 			 * copy of the data so that we will be guaranteed
4091fa9e4066Sahrens 			 * that arc_release() will always succeed.
4092fa9e4066Sahrens 			 */
409389c86e32SChris Williamson 			buf = hdr->b_l1hdr.b_buf;
4094ea8dc4b6Seschrock 			ASSERT(buf);
4095ea8dc4b6Seschrock 			ASSERT(buf->b_data);
409644eda4d7Smaybee 			if (HDR_BUF_AVAILABLE(hdr)) {
4097ea8dc4b6Seschrock 				ASSERT(buf->b_efunc == NULL);
40987adb730bSGeorge Wilson 				hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
409944eda4d7Smaybee 			} else {
410044eda4d7Smaybee 				buf = arc_buf_clone(buf);
4101ea8dc4b6Seschrock 			}
4102b24ab676SJeff Bonwick 
41037adb730bSGeorge Wilson 		} else if (*arc_flags & ARC_FLAG_PREFETCH &&
410489c86e32SChris Williamson 		    refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
41057adb730bSGeorge Wilson 			hdr->b_flags |= ARC_FLAG_PREFETCH;
4106fa9e4066Sahrens 		}
4107fa9e4066Sahrens 		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
410844eda4d7Smaybee 		arc_access(hdr, hash_lock);
41097adb730bSGeorge Wilson 		if (*arc_flags & ARC_FLAG_L2CACHE)
41107adb730bSGeorge Wilson 			hdr->b_flags |= ARC_FLAG_L2CACHE;
41117adb730bSGeorge Wilson 		if (*arc_flags & ARC_FLAG_L2COMPRESS)
41127adb730bSGeorge Wilson 			hdr->b_flags |= ARC_FLAG_L2COMPRESS;
411344eda4d7Smaybee 		mutex_exit(hash_lock);
411444cb6abcSbmc 		ARCSTAT_BUMP(arcstat_hits);
4115*5f992543SArne Jansen 		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4116*5f992543SArne Jansen 		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
4117*5f992543SArne Jansen 		    data, metadata, hits);
411844cb6abcSbmc 
4119fa9e4066Sahrens 		if (done)
4120fa9e4066Sahrens 			done(NULL, buf, private);
4121fa9e4066Sahrens 	} else {
4122fa9e4066Sahrens 		uint64_t size = BP_GET_LSIZE(bp);
4123fa9e4066Sahrens 		arc_callback_t *acb;
41243a737e0dSbrendan 		vdev_t *vd = NULL;
4125d5285caeSGeorge Wilson 		uint64_t addr = 0;
41265a98e54bSBrendan Gregg - Sun Microsystems 		boolean_t devw = B_FALSE;
412757815f6bSBoris Protopopov 		enum zio_compress b_compress = ZIO_COMPRESS_OFF;
412889c86e32SChris Williamson 		int32_t b_asize = 0;
4129fa9e4066Sahrens 
4130fa9e4066Sahrens 		if (hdr == NULL) {
4131fa9e4066Sahrens 			/* this block is not in the cache */
41325d7b4d43SMatthew Ahrens 			arc_buf_hdr_t *exists = NULL;
4133ad23a2dbSjohansen 			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
4134ad23a2dbSjohansen 			buf = arc_buf_alloc(spa, size, private, type);
4135fa9e4066Sahrens 			hdr = buf->b_hdr;
41365d7b4d43SMatthew Ahrens 			if (!BP_IS_EMBEDDED(bp)) {
4137fa9e4066Sahrens 				hdr->b_dva = *BP_IDENTITY(bp);
4138b24ab676SJeff Bonwick 				hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
4139fa9e4066Sahrens 				exists = buf_hash_insert(hdr, &hash_lock);
41405d7b4d43SMatthew Ahrens 			}
41415d7b4d43SMatthew Ahrens 			if (exists != NULL) {
4142fa9e4066Sahrens 				/* somebody beat us to the hash insert */
4143fa9e4066Sahrens 				mutex_exit(hash_lock);
41443f9d6ad7SLin Ling 				buf_discard_identity(hdr);
4145ea8dc4b6Seschrock 				(void) arc_buf_remove_ref(buf, private);
4146fa9e4066Sahrens 				goto top; /* restart the IO request */
4147fa9e4066Sahrens 			}
41487adb730bSGeorge Wilson 
4149cf6106c8SMatthew Ahrens 			/*
4150cf6106c8SMatthew Ahrens 			 * If there is a callback, we pass our reference to
4151cf6106c8SMatthew Ahrens 			 * it; otherwise we remove our reference.
4152cf6106c8SMatthew Ahrens 			 */
4153cf6106c8SMatthew Ahrens 			if (done == NULL) {
415413506d1eSmaybee 				(void) remove_reference(hdr, hash_lock,
415513506d1eSmaybee 				    private);
415613506d1eSmaybee 			}
4157cf6106c8SMatthew Ahrens 			if (*arc_flags & ARC_FLAG_PREFETCH)
4158cf6106c8SMatthew Ahrens 				hdr->b_flags |= ARC_FLAG_PREFETCH;
41597adb730bSGeorge Wilson 			if (*arc_flags & ARC_FLAG_L2CACHE)
41607adb730bSGeorge Wilson 				hdr->b_flags |= ARC_FLAG_L2CACHE;
41617adb730bSGeorge Wilson 			if (*arc_flags & ARC_FLAG_L2COMPRESS)
41627adb730bSGeorge Wilson 				hdr->b_flags |= ARC_FLAG_L2COMPRESS;
416313506d1eSmaybee 			if (BP_GET_LEVEL(bp) > 0)
41647adb730bSGeorge Wilson 				hdr->b_flags |= ARC_FLAG_INDIRECT;
4165fa9e4066Sahrens 		} else {
416689c86e32SChris Williamson 			/*
416789c86e32SChris Williamson 			 * This block is in the ghost cache. If it was L2-only
416889c86e32SChris Williamson 			 * (and thus didn't have an L1 hdr), we realloc the
416989c86e32SChris Williamson 			 * header to add an L1 hdr.
417089c86e32SChris Williamson 			 */
417189c86e32SChris Williamson 			if (!HDR_HAS_L1HDR(hdr)) {
417289c86e32SChris Williamson 				hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
417389c86e32SChris Williamson 				    hdr_full_cache);
417489c86e32SChris Williamson 			}
417589c86e32SChris Williamson 
417689c86e32SChris Williamson 			ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
4177fa9e4066Sahrens 			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
417889c86e32SChris Williamson 			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4179244781f1SPrakash Surya 			ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
418013506d1eSmaybee 
4181cf6106c8SMatthew Ahrens 			/*
4182cf6106c8SMatthew Ahrens 			 * If there is a callback, we pass a reference to it.
4183cf6106c8SMatthew Ahrens 			 */
4184cf6106c8SMatthew Ahrens 			if (done != NULL)
4185cf6106c8SMatthew Ahrens 				add_reference(hdr, hash_lock, private);
41867adb730bSGeorge Wilson 			if (*arc_flags & ARC_FLAG_PREFETCH)
41877adb730bSGeorge Wilson 				hdr->b_flags |= ARC_FLAG_PREFETCH;
41887adb730bSGeorge Wilson 			if (*arc_flags & ARC_FLAG_L2CACHE)
41897adb730bSGeorge Wilson 				hdr->b_flags |= ARC_FLAG_L2CACHE;
41907adb730bSGeorge Wilson 			if (*arc_flags & ARC_FLAG_L2COMPRESS)
41917adb730bSGeorge Wilson 				hdr->b_flags |= ARC_FLAG_L2COMPRESS;
41921ab7f2deSmaybee 			buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
4193fa9e4066Sahrens 			buf->b_hdr = hdr;
419444eda4d7Smaybee 			buf->b_data = NULL;
4195ea8dc4b6Seschrock 			buf->b_efunc = NULL;
4196ea8dc4b6Seschrock 			buf->b_private = NULL;
4197fa9e4066Sahrens 			buf->b_next = NULL;
419889c86e32SChris Williamson 			hdr->b_l1hdr.b_buf = buf;
419989c86e32SChris Williamson 			ASSERT0(hdr->b_l1hdr.b_datacnt);
420089c86e32SChris Williamson 			hdr->b_l1hdr.b_datacnt = 1;
42015614b00aSWilliam Gorrell 			arc_get_data_buf(buf);
42027e453561SWilliam Gorrell 			arc_access(hdr, hash_lock);
4203fa9e4066Sahrens 		}
4204fa9e4066Sahrens 
4205cf6106c8SMatthew Ahrens 		if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
4206cf6106c8SMatthew Ahrens 			hdr->b_flags |= ARC_FLAG_PREDICTIVE_PREFETCH;
420789c86e32SChris Williamson 		ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
42085614b00aSWilliam Gorrell 
4209fa9e4066Sahrens 		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
4210fa9e4066Sahrens 		acb->acb_done = done;
4211fa9e4066Sahrens 		acb->acb_private = private;
4212fa9e4066Sahrens 
421389c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_acb == NULL);
421489c86e32SChris Williamson 		hdr->b_l1hdr.b_acb = acb;
42157adb730bSGeorge Wilson 		hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
4216fa9e4066Sahrens 
421789c86e32SChris Williamson 		if (HDR_HAS_L2HDR(hdr) &&
421889c86e32SChris Williamson 		    (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
421989c86e32SChris Williamson 			devw = hdr->b_l2hdr.b_dev->l2ad_writing;
422089c86e32SChris Williamson 			addr = hdr->b_l2hdr.b_daddr;
4221d4cd038cSArne Jansen 			b_compress = hdr->b_l2hdr.b_compress;
422289c86e32SChris Williamson 			b_asize = hdr->b_l2hdr.b_asize;
4223e14bb325SJeff Bonwick 			/*
4224e14bb325SJeff Bonwick 			 * Lock out device removal.
4225e14bb325SJeff Bonwick 			 */
4226e14bb325SJeff Bonwick 			if (vdev_is_dead(vd) ||
4227e14bb325SJeff Bonwick 			    !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
4228e14bb325SJeff Bonwick 				vd = NULL;
42293a737e0dSbrendan 		}
42303a737e0dSbrendan 
42315d7b4d43SMatthew Ahrens 		if (hash_lock != NULL)
42323a737e0dSbrendan 			mutex_exit(hash_lock);
42333a737e0dSbrendan 
42343e30c24aSWill Andrews 		/*
42353e30c24aSWill Andrews 		 * At this point, we have a level 1 cache miss.  Try again in
42363e30c24aSWill Andrews 		 * L2ARC if possible.
42373e30c24aSWill Andrews 		 */
4238fa9e4066Sahrens 		ASSERT3U(hdr->b_size, ==, size);
42395c28183bSBrendan Gregg - Sun Microsystems 		DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
42407802d7bfSMatthew Ahrens 		    uint64_t, size, zbookmark_phys_t *, zb);
424144cb6abcSbmc 		ARCSTAT_BUMP(arcstat_misses);
4242*5f992543SArne Jansen 		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4243*5f992543SArne Jansen 		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
4244*5f992543SArne Jansen 		    data, metadata, misses);
4245ea8dc4b6Seschrock 
4246cf6106c8SMatthew Ahrens 		if (priority == ZIO_PRIORITY_ASYNC_READ)
4247cf6106c8SMatthew Ahrens 			hdr->b_flags |= ARC_FLAG_PRIO_ASYNC_READ;
4248cf6106c8SMatthew Ahrens 		else
4249cf6106c8SMatthew Ahrens 			hdr->b_flags &= ~ARC_FLAG_PRIO_ASYNC_READ;
4250cf6106c8SMatthew Ahrens 
42515a98e54bSBrendan Gregg - Sun Microsystems 		if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
42523a737e0dSbrendan 			/*
42533a737e0dSbrendan 			 * Read from the L2ARC if the following are true:
42543a737e0dSbrendan 			 * 1. The L2ARC vdev was previously cached.
42553a737e0dSbrendan 			 * 2. This buffer still has L2ARC metadata.
42563a737e0dSbrendan 			 * 3. This buffer isn't currently writing to the L2ARC.
42573a737e0dSbrendan 			 * 4. The L2ARC entry wasn't evicted, which may
42583a737e0dSbrendan 			 *    also have invalidated the vdev.
42595a98e54bSBrendan Gregg - Sun Microsystems 			 * 5. This isn't prefetch and l2arc_noprefetch is set.
42603a737e0dSbrendan 			 */
426189c86e32SChris Williamson 			if (HDR_HAS_L2HDR(hdr) &&
42625a98e54bSBrendan Gregg - Sun Microsystems 			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
42635a98e54bSBrendan Gregg - Sun Microsystems 			    !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
4264fa94a07fSbrendan 				l2arc_read_callback_t *cb;
4265fa94a07fSbrendan 
4266c5904d13Seschrock 				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
4267c5904d13Seschrock 				ARCSTAT_BUMP(arcstat_l2_hits);
4268c5904d13Seschrock 
4269fa94a07fSbrendan 				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
4270fa94a07fSbrendan 				    KM_SLEEP);
4271fa94a07fSbrendan 				cb->l2rcb_buf = buf;
4272fa94a07fSbrendan 				cb->l2rcb_spa = spa;
4273fa94a07fSbrendan 				cb->l2rcb_bp = *bp;
4274fa94a07fSbrendan 				cb->l2rcb_zb = *zb;
42753baa08fcSek110237 				cb->l2rcb_flags = zio_flags;
427657815f6bSBoris Protopopov 				cb->l2rcb_compress = b_compress;
4277fa94a07fSbrendan 
4278d5285caeSGeorge Wilson 				ASSERT(addr >= VDEV_LABEL_START_SIZE &&
4279d5285caeSGeorge Wilson 				    addr + size < vd->vdev_psize -
4280d5285caeSGeorge Wilson 				    VDEV_LABEL_END_SIZE);
4281d5285caeSGeorge Wilson 
4282fa94a07fSbrendan 				/*
4283e14bb325SJeff Bonwick 				 * l2arc read.  The SCL_L2ARC lock will be
4284e14bb325SJeff Bonwick 				 * released by l2arc_read_done().
4285aad02571SSaso Kiselkov 				 * Issue a null zio if the underlying buffer
4286aad02571SSaso Kiselkov 				 * was squashed to zero size by compression.
4287fa94a07fSbrendan 				 */
428857815f6bSBoris Protopopov 				if (b_compress == ZIO_COMPRESS_EMPTY) {
4289aad02571SSaso Kiselkov 					rzio = zio_null(pio, spa, vd,
4290aad02571SSaso Kiselkov 					    l2arc_read_done, cb,
4291aad02571SSaso Kiselkov 					    zio_flags | ZIO_FLAG_DONT_CACHE |
4292aad02571SSaso Kiselkov 					    ZIO_FLAG_CANFAIL |
4293aad02571SSaso Kiselkov 					    ZIO_FLAG_DONT_PROPAGATE |
4294aad02571SSaso Kiselkov 					    ZIO_FLAG_DONT_RETRY);
4295aad02571SSaso Kiselkov 				} else {
4296aad02571SSaso Kiselkov 					rzio = zio_read_phys(pio, vd, addr,
429757815f6bSBoris Protopopov 					    b_asize, buf->b_data,
429857815f6bSBoris Protopopov 					    ZIO_CHECKSUM_OFF,
4299aad02571SSaso Kiselkov 					    l2arc_read_done, cb, priority,
4300aad02571SSaso Kiselkov 					    zio_flags | ZIO_FLAG_DONT_CACHE |
4301aad02571SSaso Kiselkov 					    ZIO_FLAG_CANFAIL |
4302e14bb325SJeff Bonwick 					    ZIO_FLAG_DONT_PROPAGATE |
4303e14bb325SJeff Bonwick 					    ZIO_FLAG_DONT_RETRY, B_FALSE);
4304aad02571SSaso Kiselkov 				}
4305fa94a07fSbrendan 				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
4306fa94a07fSbrendan 				    zio_t *, rzio);
430757815f6bSBoris Protopopov 				ARCSTAT_INCR(arcstat_l2_read_bytes, b_asize);
4308fa94a07fSbrendan 
43097adb730bSGeorge Wilson 				if (*arc_flags & ARC_FLAG_NOWAIT) {
4310fa94a07fSbrendan 					zio_nowait(rzio);
4311fa94a07fSbrendan 					return (0);
43123a737e0dSbrendan 				}
43133a737e0dSbrendan 
43147adb730bSGeorge Wilson 				ASSERT(*arc_flags & ARC_FLAG_WAIT);
43153a737e0dSbrendan 				if (zio_wait(rzio) == 0)
43163a737e0dSbrendan 					return (0);
43173a737e0dSbrendan 
43183a737e0dSbrendan 				/* l2arc read error; goto zio_read() */
4319fa94a07fSbrendan 			} else {
4320fa94a07fSbrendan 				DTRACE_PROBE1(l2arc__miss,
4321fa94a07fSbrendan 				    arc_buf_hdr_t *, hdr);
4322fa94a07fSbrendan 				ARCSTAT_BUMP(arcstat_l2_misses);
4323fa94a07fSbrendan 				if (HDR_L2_WRITING(hdr))
4324fa94a07fSbrendan 					ARCSTAT_BUMP(arcstat_l2_rw_clash);
4325e14bb325SJeff Bonwick 				spa_config_exit(spa, SCL_L2ARC, vd);
4326fa94a07fSbrendan 			}
43275a98e54bSBrendan Gregg - Sun Microsystems 		} else {
432876a25fafSBill Moore 			if (vd != NULL)
432976a25fafSBill Moore 				spa_config_exit(spa, SCL_L2ARC, vd);
43305a98e54bSBrendan Gregg - Sun Microsystems 			if (l2arc_ndev != 0) {
43315a98e54bSBrendan Gregg - Sun Microsystems 				DTRACE_PROBE1(l2arc__miss,
43325a98e54bSBrendan Gregg - Sun Microsystems 				    arc_buf_hdr_t *, hdr);
43335a98e54bSBrendan Gregg - Sun Microsystems 				ARCSTAT_BUMP(arcstat_l2_misses);
43345a98e54bSBrendan Gregg - Sun Microsystems 			}
4335fa94a07fSbrendan 		}
4336c5904d13Seschrock 
4337fa9e4066Sahrens 		rzio = zio_read(pio, spa, bp, buf->b_data, size,
43383baa08fcSek110237 		    arc_read_done, buf, priority, zio_flags, zb);
4339fa9e4066Sahrens 
43407adb730bSGeorge Wilson 		if (*arc_flags & ARC_FLAG_WAIT)
4341fa9e4066Sahrens 			return (zio_wait(rzio));
4342fa9e4066Sahrens 
43437adb730bSGeorge Wilson 		ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
4344fa9e4066Sahrens 		zio_nowait(rzio);
4345fa9e4066Sahrens 	}
4346fa9e4066Sahrens 	return (0);
4347fa9e4066Sahrens }
4348fa9e4066Sahrens 
4349ea8dc4b6Seschrock void
4350ea8dc4b6Seschrock arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
4351ea8dc4b6Seschrock {
4352ea8dc4b6Seschrock 	ASSERT(buf->b_hdr != NULL);
435389c86e32SChris Williamson 	ASSERT(buf->b_hdr->b_l1hdr.b_state != arc_anon);
435489c86e32SChris Williamson 	ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt) ||
435589c86e32SChris Williamson 	    func == NULL);
4356b24ab676SJeff Bonwick 	ASSERT(buf->b_efunc == NULL);
4357b24ab676SJeff Bonwick 	ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
4358b24ab676SJeff Bonwick 
4359ea8dc4b6Seschrock 	buf->b_efunc = func;
4360ea8dc4b6Seschrock 	buf->b_private = private;
4361ea8dc4b6Seschrock }
4362ea8dc4b6Seschrock 
4363ea8dc4b6Seschrock /*
43646e6d5868SMatthew Ahrens  * Notify the arc that a block was freed, and thus will never be used again.
43656e6d5868SMatthew Ahrens  */
43666e6d5868SMatthew Ahrens void
43676e6d5868SMatthew Ahrens arc_freed(spa_t *spa, const blkptr_t *bp)
43686e6d5868SMatthew Ahrens {
43696e6d5868SMatthew Ahrens 	arc_buf_hdr_t *hdr;
43706e6d5868SMatthew Ahrens 	kmutex_t *hash_lock;
43716e6d5868SMatthew Ahrens 	uint64_t guid = spa_load_guid(spa);
43726e6d5868SMatthew Ahrens 
43735d7b4d43SMatthew Ahrens 	ASSERT(!BP_IS_EMBEDDED(bp));
43745d7b4d43SMatthew Ahrens 
43755d7b4d43SMatthew Ahrens 	hdr = buf_hash_find(guid, bp, &hash_lock);
43766e6d5868SMatthew Ahrens 	if (hdr == NULL)
43776e6d5868SMatthew Ahrens 		return;
43786e6d5868SMatthew Ahrens 	if (HDR_BUF_AVAILABLE(hdr)) {
437989c86e32SChris Williamson 		arc_buf_t *buf = hdr->b_l1hdr.b_buf;
43806e6d5868SMatthew Ahrens 		add_reference(hdr, hash_lock, FTAG);
43817adb730bSGeorge Wilson 		hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
43826e6d5868SMatthew Ahrens 		mutex_exit(hash_lock);
43836e6d5868SMatthew Ahrens 
43846e6d5868SMatthew Ahrens 		arc_release(buf, FTAG);
43856e6d5868SMatthew Ahrens 		(void) arc_buf_remove_ref(buf, FTAG);
43866e6d5868SMatthew Ahrens 	} else {
43876e6d5868SMatthew Ahrens 		mutex_exit(hash_lock);
43886e6d5868SMatthew Ahrens 	}
43896e6d5868SMatthew Ahrens 
43906e6d5868SMatthew Ahrens }
43916e6d5868SMatthew Ahrens 
43926e6d5868SMatthew Ahrens /*
4393bbfa8ea8SMatthew Ahrens  * Clear the user eviction callback set by arc_set_callback(), first calling
4394bbfa8ea8SMatthew Ahrens  * it if it exists.  Because the presence of a callback keeps an arc_buf cached
4395bbfa8ea8SMatthew Ahrens  * clearing the callback may result in the arc_buf being destroyed.  However,
4396bbfa8ea8SMatthew Ahrens  * it will not result in the *last* arc_buf being destroyed, hence the data
4397bbfa8ea8SMatthew Ahrens  * will remain cached in the ARC. We make a copy of the arc buffer here so
4398bbfa8ea8SMatthew Ahrens  * that we can process the callback without holding any locks.
4399bbfa8ea8SMatthew Ahrens  *
4400bbfa8ea8SMatthew Ahrens  * It's possible that the callback is already in the process of being cleared
4401bbfa8ea8SMatthew Ahrens  * by another thread.  In this case we can not clear the callback.
4402bbfa8ea8SMatthew Ahrens  *
4403bbfa8ea8SMatthew Ahrens  * Returns B_TRUE if the callback was successfully called and cleared.
4404ea8dc4b6Seschrock  */
4405bbfa8ea8SMatthew Ahrens boolean_t
4406bbfa8ea8SMatthew Ahrens arc_clear_callback(arc_buf_t *buf)
4407ea8dc4b6Seschrock {
440840d7d650Smaybee 	arc_buf_hdr_t *hdr;
4409ea8dc4b6Seschrock 	kmutex_t *hash_lock;
4410bbfa8ea8SMatthew Ahrens 	arc_evict_func_t *efunc = buf->b_efunc;
4411bbfa8ea8SMatthew Ahrens 	void *private = buf->b_private;
4412ea8dc4b6Seschrock 
44133f9d6ad7SLin Ling 	mutex_enter(&buf->b_evict_lock);
441440d7d650Smaybee 	hdr = buf->b_hdr;
4415ea8dc4b6Seschrock 	if (hdr == NULL) {
4416ea8dc4b6Seschrock 		/*
4417ea8dc4b6Seschrock 		 * We are in arc_do_user_evicts().
4418ea8dc4b6Seschrock 		 */
4419ea8dc4b6Seschrock 		ASSERT(buf->b_data == NULL);
44203f9d6ad7SLin Ling 		mutex_exit(&buf->b_evict_lock);
4421bbfa8ea8SMatthew Ahrens 		return (B_FALSE);
44226f83844dSMark Maybee 	} else if (buf->b_data == NULL) {
44239b23f181Smaybee 		/*
44246f83844dSMark Maybee 		 * We are on the eviction list; process this buffer now
44259b23f181Smaybee 		 * but let arc_do_user_evicts() do the reaping.
44269b23f181Smaybee 		 */
44279b23f181Smaybee 		buf->b_efunc = NULL;
44283f9d6ad7SLin Ling 		mutex_exit(&buf->b_evict_lock);
4429bbfa8ea8SMatthew Ahrens 		VERIFY0(efunc(private));
4430bbfa8ea8SMatthew Ahrens 		return (B_TRUE);
44319b23f181Smaybee 	}
44326f83844dSMark Maybee 	hash_lock = HDR_LOCK(hdr);
44336f83844dSMark Maybee 	mutex_enter(hash_lock);
44343f9d6ad7SLin Ling 	hdr = buf->b_hdr;
44353f9d6ad7SLin Ling 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
44369b23f181Smaybee 
443789c86e32SChris Williamson 	ASSERT3U(refcount_count(&hdr->b_l1hdr.b_refcnt), <,
443889c86e32SChris Williamson 	    hdr->b_l1hdr.b_datacnt);
443989c86e32SChris Williamson 	ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
444089c86e32SChris Williamson 	    hdr->b_l1hdr.b_state == arc_mfu);
4441ea8dc4b6Seschrock 
4442ea8dc4b6Seschrock 	buf->b_efunc = NULL;
4443ea8dc4b6Seschrock 	buf->b_private = NULL;
4444bbfa8ea8SMatthew Ahrens 
444589c86e32SChris Williamson 	if (hdr->b_l1hdr.b_datacnt > 1) {
4446bbfa8ea8SMatthew Ahrens 		mutex_exit(&buf->b_evict_lock);
4447244781f1SPrakash Surya 		arc_buf_destroy(buf, TRUE);
4448bbfa8ea8SMatthew Ahrens 	} else {
444989c86e32SChris Williamson 		ASSERT(buf == hdr->b_l1hdr.b_buf);
44507adb730bSGeorge Wilson 		hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
4451bbfa8ea8SMatthew Ahrens 		mutex_exit(&buf->b_evict_lock);
4452bbfa8ea8SMatthew Ahrens 	}
4453bbfa8ea8SMatthew Ahrens 
4454bbfa8ea8SMatthew Ahrens 	mutex_exit(hash_lock);
4455bbfa8ea8SMatthew Ahrens 	VERIFY0(efunc(private));
4456bbfa8ea8SMatthew Ahrens 	return (B_TRUE);
4457ea8dc4b6Seschrock }
4458ea8dc4b6Seschrock 
4459fa9e4066Sahrens /*
44603e30c24aSWill Andrews  * Release this buffer from the cache, making it an anonymous buffer.  This
44613e30c24aSWill Andrews  * must be done after a read and prior to modifying the buffer contents.
4462fa9e4066Sahrens  * If the buffer has more than one reference, we must make
4463088f3894Sahrens  * a new hdr for the buffer.
4464fa9e4066Sahrens  */
4465fa9e4066Sahrens void
4466fa9e4066Sahrens arc_release(arc_buf_t *buf, void *tag)
4467fa9e4066Sahrens {
446889c86e32SChris Williamson 	arc_buf_hdr_t *hdr = buf->b_hdr;
4469fa9e4066Sahrens 
44703f9d6ad7SLin Ling 	/*
44713f9d6ad7SLin Ling 	 * It would be nice to assert that if it's DMU metadata (level >
44723f9d6ad7SLin Ling 	 * 0 || it's the dnode file), then it must be syncing context.
44733f9d6ad7SLin Ling 	 * But we don't know that information at this level.
44743f9d6ad7SLin Ling 	 */
44753f9d6ad7SLin Ling 
44763f9d6ad7SLin Ling 	mutex_enter(&buf->b_evict_lock);
447789c86e32SChris Williamson 
4478244781f1SPrakash Surya 	ASSERT(HDR_HAS_L1HDR(hdr));
4479244781f1SPrakash Surya 
448089c86e32SChris Williamson 	/*
448189c86e32SChris Williamson 	 * We don't grab the hash lock prior to this check, because if
448289c86e32SChris Williamson 	 * the buffer's header is in the arc_anon state, it won't be
448389c86e32SChris Williamson 	 * linked into the hash table.
448489c86e32SChris Williamson 	 */
448589c86e32SChris Williamson 	if (hdr->b_l1hdr.b_state == arc_anon) {
448689c86e32SChris Williamson 		mutex_exit(&buf->b_evict_lock);
448789c86e32SChris Williamson 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
448889c86e32SChris Williamson 		ASSERT(!HDR_IN_HASH_TABLE(hdr));
448989c86e32SChris Williamson 		ASSERT(!HDR_HAS_L2HDR(hdr));
449089c86e32SChris Williamson 		ASSERT(BUF_EMPTY(hdr));
449189c86e32SChris Williamson 
449289c86e32SChris Williamson 		ASSERT3U(hdr->b_l1hdr.b_datacnt, ==, 1);
449389c86e32SChris Williamson 		ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
449489c86e32SChris Williamson 		ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
449589c86e32SChris Williamson 
449689c86e32SChris Williamson 		ASSERT3P(buf->b_efunc, ==, NULL);
449789c86e32SChris Williamson 		ASSERT3P(buf->b_private, ==, NULL);
449889c86e32SChris Williamson 
449989c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = 0;
450089c86e32SChris Williamson 		arc_buf_thaw(buf);
450189c86e32SChris Williamson 
450289c86e32SChris Williamson 		return;
450389c86e32SChris Williamson 	}
450489c86e32SChris Williamson 
450589c86e32SChris Williamson 	kmutex_t *hash_lock = HDR_LOCK(hdr);
450689c86e32SChris Williamson 	mutex_enter(hash_lock);
450789c86e32SChris Williamson 
450889c86e32SChris Williamson 	/*
450989c86e32SChris Williamson 	 * This assignment is only valid as long as the hash_lock is
451089c86e32SChris Williamson 	 * held, we must be careful not to reference state or the
451189c86e32SChris Williamson 	 * b_state field after dropping the lock.
451289c86e32SChris Williamson 	 */
451389c86e32SChris Williamson 	arc_state_t *state = hdr->b_l1hdr.b_state;
451489c86e32SChris Williamson 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
451589c86e32SChris Williamson 	ASSERT3P(state, !=, arc_anon);
45166f83844dSMark Maybee 
4517fa9e4066Sahrens 	/* this buffer is not on any list */
451889c86e32SChris Williamson 	ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) > 0);
4519fa9e4066Sahrens 
452089c86e32SChris Williamson 	if (HDR_HAS_L2HDR(hdr)) {
452189c86e32SChris Williamson 		mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
4522244781f1SPrakash Surya 
4523244781f1SPrakash Surya 		/*
4524a52fc310SPrakash Surya 		 * We have to recheck this conditional again now that
4525a52fc310SPrakash Surya 		 * we're holding the l2ad_mtx to prevent a race with
4526a52fc310SPrakash Surya 		 * another thread which might be concurrently calling
4527a52fc310SPrakash Surya 		 * l2arc_evict(). In that case, l2arc_evict() might have
4528a52fc310SPrakash Surya 		 * destroyed the header's L2 portion as we were waiting
4529a52fc310SPrakash Surya 		 * to acquire the l2ad_mtx.
4530244781f1SPrakash Surya 		 */
4531a52fc310SPrakash Surya 		if (HDR_HAS_L2HDR(hdr))
4532a52fc310SPrakash Surya 			arc_hdr_l2hdr_destroy(hdr);
4533244781f1SPrakash Surya 
453489c86e32SChris Williamson 		mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
45356f83844dSMark Maybee 	}
45366f83844dSMark Maybee 
4537ea8dc4b6Seschrock 	/*
4538ea8dc4b6Seschrock 	 * Do we have more than one buf?
4539ea8dc4b6Seschrock 	 */
454089c86e32SChris Williamson 	if (hdr->b_l1hdr.b_datacnt > 1) {
4541fa9e4066Sahrens 		arc_buf_hdr_t *nhdr;
4542fa9e4066Sahrens 		arc_buf_t **bufp;
4543fa9e4066Sahrens 		uint64_t blksz = hdr->b_size;
4544ac05c741SMark Maybee 		uint64_t spa = hdr->b_spa;
454589c86e32SChris Williamson 		arc_buf_contents_t type = arc_buf_type(hdr);
4546fa94a07fSbrendan 		uint32_t flags = hdr->b_flags;
4547fa9e4066Sahrens 
454889c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
4549fa9e4066Sahrens 		/*
45503f9d6ad7SLin Ling 		 * Pull the data off of this hdr and attach it to
45513f9d6ad7SLin Ling 		 * a new anonymous hdr.
4552fa9e4066Sahrens 		 */
4553ea8dc4b6Seschrock 		(void) remove_reference(hdr, hash_lock, tag);
455489c86e32SChris Williamson 		bufp = &hdr->b_l1hdr.b_buf;
4555ea8dc4b6Seschrock 		while (*bufp != buf)
4556fa9e4066Sahrens 			bufp = &(*bufp)->b_next;
45573f9d6ad7SLin Ling 		*bufp = buf->b_next;
4558af2c4821Smaybee 		buf->b_next = NULL;
4559ea8dc4b6Seschrock 
456089c86e32SChris Williamson 		ASSERT3P(state, !=, arc_l2c_only);
45612fd872a7SPrakash Surya 
45622fd872a7SPrakash Surya 		(void) refcount_remove_many(
45632fd872a7SPrakash Surya 		    &state->arcs_size, hdr->b_size, buf);
45642fd872a7SPrakash Surya 
456589c86e32SChris Williamson 		if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
456689c86e32SChris Williamson 			ASSERT3P(state, !=, arc_l2c_only);
456789c86e32SChris Williamson 			uint64_t *size = &state->arcs_lsize[type];
45680e8c6158Smaybee 			ASSERT3U(*size, >=, hdr->b_size);
45690e8c6158Smaybee 			atomic_add_64(size, -hdr->b_size);
4570ea8dc4b6Seschrock 		}
45719253d63dSGeorge Wilson 
45729253d63dSGeorge Wilson 		/*
45739253d63dSGeorge Wilson 		 * We're releasing a duplicate user data buffer, update
45749253d63dSGeorge Wilson 		 * our statistics accordingly.
45759253d63dSGeorge Wilson 		 */
457689c86e32SChris Williamson 		if (HDR_ISTYPE_DATA(hdr)) {
45779253d63dSGeorge Wilson 			ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
45789253d63dSGeorge Wilson 			ARCSTAT_INCR(arcstat_duplicate_buffers_size,
45799253d63dSGeorge Wilson 			    -hdr->b_size);
45809253d63dSGeorge Wilson 		}
458189c86e32SChris Williamson 		hdr->b_l1hdr.b_datacnt -= 1;
4582c717a561Smaybee 		arc_cksum_verify(buf);
4583cd1c8b85SMatthew Ahrens 		arc_buf_unwatch(buf);
4584ea8dc4b6Seschrock 
4585fa9e4066Sahrens 		mutex_exit(hash_lock);
4586fa9e4066Sahrens 
458789c86e32SChris Williamson 		nhdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
4588fa9e4066Sahrens 		nhdr->b_size = blksz;
4589fa9e4066Sahrens 		nhdr->b_spa = spa;
459089c86e32SChris Williamson 
45917adb730bSGeorge Wilson 		nhdr->b_flags = flags & ARC_FLAG_L2_WRITING;
459289c86e32SChris Williamson 		nhdr->b_flags |= arc_bufc_to_flags(type);
459389c86e32SChris Williamson 		nhdr->b_flags |= ARC_FLAG_HAS_L1HDR;
459489c86e32SChris Williamson 
459589c86e32SChris Williamson 		nhdr->b_l1hdr.b_buf = buf;
459689c86e32SChris Williamson 		nhdr->b_l1hdr.b_datacnt = 1;
459789c86e32SChris Williamson 		nhdr->b_l1hdr.b_state = arc_anon;
459889c86e32SChris Williamson 		nhdr->b_l1hdr.b_arc_access = 0;
4599244781f1SPrakash Surya 		nhdr->b_l1hdr.b_tmp_cdata = NULL;
4600c717a561Smaybee 		nhdr->b_freeze_cksum = NULL;
460189c86e32SChris Williamson 
460289c86e32SChris Williamson 		(void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
4603af2c4821Smaybee 		buf->b_hdr = nhdr;
46043f9d6ad7SLin Ling 		mutex_exit(&buf->b_evict_lock);
46052fd872a7SPrakash Surya 		(void) refcount_add_many(&arc_anon->arcs_size, blksz, buf);
4606fa9e4066Sahrens 	} else {
46073f9d6ad7SLin Ling 		mutex_exit(&buf->b_evict_lock);
460889c86e32SChris Williamson 		ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
4609244781f1SPrakash Surya 		/* protected by hash lock, or hdr is on arc_anon */
4610244781f1SPrakash Surya 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
4611fa9e4066Sahrens 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
461244cb6abcSbmc 		arc_change_state(arc_anon, hdr, hash_lock);
461389c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = 0;
4614fa9e4066Sahrens 		mutex_exit(hash_lock);
4615fa94a07fSbrendan 
46163f9d6ad7SLin Ling 		buf_discard_identity(hdr);
4617c717a561Smaybee 		arc_buf_thaw(buf);
4618fa9e4066Sahrens 	}
4619ea8dc4b6Seschrock 	buf->b_efunc = NULL;
4620ea8dc4b6Seschrock 	buf->b_private = NULL;
46216f83844dSMark Maybee }
4622fa9e4066Sahrens 
4623fa9e4066Sahrens int
4624fa9e4066Sahrens arc_released(arc_buf_t *buf)
4625fa9e4066Sahrens {
46266f83844dSMark Maybee 	int released;
46276f83844dSMark Maybee 
46283f9d6ad7SLin Ling 	mutex_enter(&buf->b_evict_lock);
462989c86e32SChris Williamson 	released = (buf->b_data != NULL &&
463089c86e32SChris Williamson 	    buf->b_hdr->b_l1hdr.b_state == arc_anon);
46313f9d6ad7SLin Ling 	mutex_exit(&buf->b_evict_lock);
46326f83844dSMark Maybee 	return (released);
4633fa9e4066Sahrens }
4634fa9e4066Sahrens 
4635ea8dc4b6Seschrock #ifdef ZFS_DEBUG
4636ea8dc4b6Seschrock int
4637ea8dc4b6Seschrock arc_referenced(arc_buf_t *buf)
4638ea8dc4b6Seschrock {
46396f83844dSMark Maybee 	int referenced;
46406f83844dSMark Maybee 
46413f9d6ad7SLin Ling 	mutex_enter(&buf->b_evict_lock);
464289c86e32SChris Williamson 	referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
46433f9d6ad7SLin Ling 	mutex_exit(&buf->b_evict_lock);
46446f83844dSMark Maybee 	return (referenced);
4645ea8dc4b6Seschrock }
4646ea8dc4b6Seschrock #endif
4647ea8dc4b6Seschrock 
4648fa9e4066Sahrens static void
4649c717a561Smaybee arc_write_ready(zio_t *zio)
4650c717a561Smaybee {
4651c717a561Smaybee 	arc_write_callback_t *callback = zio->io_private;
4652c717a561Smaybee 	arc_buf_t *buf = callback->awcb_buf;
46530a4e9518Sgw25295 	arc_buf_hdr_t *hdr = buf->b_hdr;
4654c717a561Smaybee 
465589c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
465689c86e32SChris Williamson 	ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
465789c86e32SChris Williamson 	ASSERT(hdr->b_l1hdr.b_datacnt > 0);
4658c717a561Smaybee 	callback->awcb_ready(zio, buf, callback->awcb_private);
4659e14bb325SJeff Bonwick 
46600a4e9518Sgw25295 	/*
46610a4e9518Sgw25295 	 * If the IO is already in progress, then this is a re-write
4662e14bb325SJeff Bonwick 	 * attempt, so we need to thaw and re-compute the cksum.
4663e14bb325SJeff Bonwick 	 * It is the responsibility of the callback to handle the
4664e14bb325SJeff Bonwick 	 * accounting for any re-write attempt.
46650a4e9518Sgw25295 	 */
46660a4e9518Sgw25295 	if (HDR_IO_IN_PROGRESS(hdr)) {
466789c86e32SChris Williamson 		mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
46680a4e9518Sgw25295 		if (hdr->b_freeze_cksum != NULL) {
46690a4e9518Sgw25295 			kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
46700a4e9518Sgw25295 			hdr->b_freeze_cksum = NULL;
46710a4e9518Sgw25295 		}
467289c86e32SChris Williamson 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
46730a4e9518Sgw25295 	}
4674fa94a07fSbrendan 	arc_cksum_compute(buf, B_FALSE);
46757adb730bSGeorge Wilson 	hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
4676c717a561Smaybee }
4677c717a561Smaybee 
467869962b56SMatthew Ahrens /*
467969962b56SMatthew Ahrens  * The SPA calls this callback for each physical write that happens on behalf
468069962b56SMatthew Ahrens  * of a logical write.  See the comment in dbuf_write_physdone() for details.
468169962b56SMatthew Ahrens  */
468269962b56SMatthew Ahrens static void
468369962b56SMatthew Ahrens arc_write_physdone(zio_t *zio)
468469962b56SMatthew Ahrens {
468569962b56SMatthew Ahrens 	arc_write_callback_t *cb = zio->io_private;
468669962b56SMatthew Ahrens 	if (cb->awcb_physdone != NULL)
468769962b56SMatthew Ahrens 		cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
468869962b56SMatthew Ahrens }
468969962b56SMatthew Ahrens 
4690c717a561Smaybee static void
4691fa9e4066Sahrens arc_write_done(zio_t *zio)
4692fa9e4066Sahrens {
4693c717a561Smaybee 	arc_write_callback_t *callback = zio->io_private;
4694c717a561Smaybee 	arc_buf_t *buf = callback->awcb_buf;
4695c717a561Smaybee 	arc_buf_hdr_t *hdr = buf->b_hdr;
4696fa9e4066Sahrens 
469789c86e32SChris Williamson 	ASSERT(hdr->b_l1hdr.b_acb == NULL);
4698fa9e4066Sahrens 
4699b24ab676SJeff Bonwick 	if (zio->io_error == 0) {
47005d7b4d43SMatthew Ahrens 		if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
470143466aaeSMax Grossman 			buf_discard_identity(hdr);
470243466aaeSMax Grossman 		} else {
4703fa9e4066Sahrens 			hdr->b_dva = *BP_IDENTITY(zio->io_bp);
4704b24ab676SJeff Bonwick 			hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
470543466aaeSMax Grossman 		}
4706b24ab676SJeff Bonwick 	} else {
4707b24ab676SJeff Bonwick 		ASSERT(BUF_EMPTY(hdr));
4708b24ab676SJeff Bonwick 	}
4709b24ab676SJeff Bonwick 
4710ea8dc4b6Seschrock 	/*
47115d7b4d43SMatthew Ahrens 	 * If the block to be written was all-zero or compressed enough to be
47125d7b4d43SMatthew Ahrens 	 * embedded in the BP, no write was performed so there will be no
47135d7b4d43SMatthew Ahrens 	 * dva/birth/checksum.  The buffer must therefore remain anonymous
47145d7b4d43SMatthew Ahrens 	 * (and uncached).
4715ea8dc4b6Seschrock 	 */
4716fa9e4066Sahrens 	if (!BUF_EMPTY(hdr)) {
4717fa9e4066Sahrens 		arc_buf_hdr_t *exists;
4718fa9e4066Sahrens 		kmutex_t *hash_lock;
4719fa9e4066Sahrens 
4720b24ab676SJeff Bonwick 		ASSERT(zio->io_error == 0);
4721b24ab676SJeff Bonwick 
47226b4acc8bSahrens 		arc_cksum_verify(buf);
47236b4acc8bSahrens 
4724fa9e4066Sahrens 		exists = buf_hash_insert(hdr, &hash_lock);
472589c86e32SChris Williamson 		if (exists != NULL) {
4726fa9e4066Sahrens 			/*
4727fa9e4066Sahrens 			 * This can only happen if we overwrite for
4728fa9e4066Sahrens 			 * sync-to-convergence, because we remove
4729fa9e4066Sahrens 			 * buffers from the hash table when we arc_free().
4730fa9e4066Sahrens 			 */
4731b24ab676SJeff Bonwick 			if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
4732b24ab676SJeff Bonwick 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
4733ae46e4c7SMatthew Ahrens 					panic("bad overwrite, hdr=%p exists=%p",
4734ae46e4c7SMatthew Ahrens 					    (void *)hdr, (void *)exists);
473589c86e32SChris Williamson 				ASSERT(refcount_is_zero(
473689c86e32SChris Williamson 				    &exists->b_l1hdr.b_refcnt));
473744cb6abcSbmc 				arc_change_state(arc_anon, exists, hash_lock);
4738fa9e4066Sahrens 				mutex_exit(hash_lock);
4739ea8dc4b6Seschrock 				arc_hdr_destroy(exists);
4740fa9e4066Sahrens 				exists = buf_hash_insert(hdr, &hash_lock);
4741fa9e4066Sahrens 				ASSERT3P(exists, ==, NULL);
474280901aeaSGeorge Wilson 			} else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
474380901aeaSGeorge Wilson 				/* nopwrite */
474480901aeaSGeorge Wilson 				ASSERT(zio->io_prop.zp_nopwrite);
474580901aeaSGeorge Wilson 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
474680901aeaSGeorge Wilson 					panic("bad nopwrite, hdr=%p exists=%p",
474780901aeaSGeorge Wilson 					    (void *)hdr, (void *)exists);
4748b24ab676SJeff Bonwick 			} else {
4749b24ab676SJeff Bonwick 				/* Dedup */
475089c86e32SChris Williamson 				ASSERT(hdr->b_l1hdr.b_datacnt == 1);
475189c86e32SChris Williamson 				ASSERT(hdr->b_l1hdr.b_state == arc_anon);
4752b24ab676SJeff Bonwick 				ASSERT(BP_GET_DEDUP(zio->io_bp));
4753b24ab676SJeff Bonwick 				ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
4754b24ab676SJeff Bonwick 			}
4755fa9e4066Sahrens 		}
47567adb730bSGeorge Wilson 		hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
4757088f3894Sahrens 		/* if it's not anon, we are doing a scrub */
475889c86e32SChris Williamson 		if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
475944eda4d7Smaybee 			arc_access(hdr, hash_lock);
476044eda4d7Smaybee 		mutex_exit(hash_lock);
4761ea8dc4b6Seschrock 	} else {
47627adb730bSGeorge Wilson 		hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
4763fa9e4066Sahrens 	}
4764ea8dc4b6Seschrock 
476589c86e32SChris Williamson 	ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4766c717a561Smaybee 	callback->awcb_done(zio, buf, callback->awcb_private);
4767fa9e4066Sahrens 
4768c717a561Smaybee 	kmem_free(callback, sizeof (arc_write_callback_t));
4769fa9e4066Sahrens }
4770fa9e4066Sahrens 
4771c717a561Smaybee zio_t *
4772b24ab676SJeff Bonwick arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
4773aad02571SSaso Kiselkov     blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
477469962b56SMatthew Ahrens     const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *physdone,
477569962b56SMatthew Ahrens     arc_done_func_t *done, void *private, zio_priority_t priority,
47767802d7bfSMatthew Ahrens     int zio_flags, const zbookmark_phys_t *zb)
4777fa9e4066Sahrens {
4778fa9e4066Sahrens 	arc_buf_hdr_t *hdr = buf->b_hdr;
4779c717a561Smaybee 	arc_write_callback_t *callback;
4780c717a561Smaybee 	zio_t *zio;
4781fa9e4066Sahrens 
4782e14bb325SJeff Bonwick 	ASSERT(ready != NULL);
4783b24ab676SJeff Bonwick 	ASSERT(done != NULL);
4784fa9e4066Sahrens 	ASSERT(!HDR_IO_ERROR(hdr));
478589c86e32SChris Williamson 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
478689c86e32SChris Williamson 	ASSERT(hdr->b_l1hdr.b_acb == NULL);
478789c86e32SChris Williamson 	ASSERT(hdr->b_l1hdr.b_datacnt > 0);
47883baa08fcSek110237 	if (l2arc)
47897adb730bSGeorge Wilson 		hdr->b_flags |= ARC_FLAG_L2CACHE;
4790aad02571SSaso Kiselkov 	if (l2arc_compress)
47917adb730bSGeorge Wilson 		hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4792c717a561Smaybee 	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
4793c717a561Smaybee 	callback->awcb_ready = ready;
479469962b56SMatthew Ahrens 	callback->awcb_physdone = physdone;
4795c717a561Smaybee 	callback->awcb_done = done;
4796c717a561Smaybee 	callback->awcb_private = private;
4797c717a561Smaybee 	callback->awcb_buf = buf;
4798088f3894Sahrens 
4799b24ab676SJeff Bonwick 	zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
480069962b56SMatthew Ahrens 	    arc_write_ready, arc_write_physdone, arc_write_done, callback,
480169962b56SMatthew Ahrens 	    priority, zio_flags, zb);
4802fa9e4066Sahrens 
4803c717a561Smaybee 	return (zio);
4804fa9e4066Sahrens }
4805fa9e4066Sahrens 
48061ab7f2deSmaybee static int
480769962b56SMatthew Ahrens arc_memory_throttle(uint64_t reserve, uint64_t txg)
4808fa9e4066Sahrens {
48091ab7f2deSmaybee #ifdef _KERNEL
48101ab7f2deSmaybee 	uint64_t available_memory = ptob(freemem);
48111ab7f2deSmaybee 	static uint64_t page_load = 0;
48121ab7f2deSmaybee 	static uint64_t last_txg = 0;
48131ab7f2deSmaybee 
48141ab7f2deSmaybee #if defined(__i386)
48151ab7f2deSmaybee 	available_memory =
48161ab7f2deSmaybee 	    MIN(available_memory, vmem_size(heap_arena, VMEM_FREE));
48171ab7f2deSmaybee #endif
481869962b56SMatthew Ahrens 
481969962b56SMatthew Ahrens 	if (freemem > physmem * arc_lotsfree_percent / 100)
48201ab7f2deSmaybee 		return (0);
48211ab7f2deSmaybee 
48221ab7f2deSmaybee 	if (txg > last_txg) {
48231ab7f2deSmaybee 		last_txg = txg;
48241ab7f2deSmaybee 		page_load = 0;
48251ab7f2deSmaybee 	}
48261ab7f2deSmaybee 	/*
48271ab7f2deSmaybee 	 * If we are in pageout, we know that memory is already tight,
48281ab7f2deSmaybee 	 * the arc is already going to be evicting, so we just want to
48291ab7f2deSmaybee 	 * continue to let page writes occur as quickly as possible.
48301ab7f2deSmaybee 	 */
48311ab7f2deSmaybee 	if (curproc == proc_pageout) {
48321ab7f2deSmaybee 		if (page_load > MAX(ptob(minfree), available_memory) / 4)
4833be6fd75aSMatthew Ahrens 			return (SET_ERROR(ERESTART));
48341ab7f2deSmaybee 		/* Note: reserve is inflated, so we deflate */
48351ab7f2deSmaybee 		page_load += reserve / 8;
48361ab7f2deSmaybee 		return (0);
48371ab7f2deSmaybee 	} else if (page_load > 0 && arc_reclaim_needed()) {
48381ab7f2deSmaybee 		/* memory is low, delay before restarting */
48391ab7f2deSmaybee 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
4840be6fd75aSMatthew Ahrens 		return (SET_ERROR(EAGAIN));
48411ab7f2deSmaybee 	}
48421ab7f2deSmaybee 	page_load = 0;
48431ab7f2deSmaybee #endif
48441ab7f2deSmaybee 	return (0);
48451ab7f2deSmaybee }
48461ab7f2deSmaybee 
48471ab7f2deSmaybee void
48481ab7f2deSmaybee arc_tempreserve_clear(uint64_t reserve)
48491ab7f2deSmaybee {
48501ab7f2deSmaybee 	atomic_add_64(&arc_tempreserve, -reserve);
4851fa9e4066Sahrens 	ASSERT((int64_t)arc_tempreserve >= 0);
4852fa9e4066Sahrens }
4853fa9e4066Sahrens 
4854fa9e4066Sahrens int
48551ab7f2deSmaybee arc_tempreserve_space(uint64_t reserve, uint64_t txg)
4856fa9e4066Sahrens {
48571ab7f2deSmaybee 	int error;
48582fdbea25SAleksandr Guzovskiy 	uint64_t anon_size;
48591ab7f2deSmaybee 
48601ab7f2deSmaybee 	if (reserve > arc_c/4 && !arc_no_grow)
48611ab7f2deSmaybee 		arc_c = MIN(arc_c_max, reserve * 4);
48621ab7f2deSmaybee 	if (reserve > arc_c)
4863be6fd75aSMatthew Ahrens 		return (SET_ERROR(ENOMEM));
4864112fe045Smaybee 
4865fa9e4066Sahrens 	/*
48662fdbea25SAleksandr Guzovskiy 	 * Don't count loaned bufs as in flight dirty data to prevent long
48672fdbea25SAleksandr Guzovskiy 	 * network delays from blocking transactions that are ready to be
48682fdbea25SAleksandr Guzovskiy 	 * assigned to a txg.
48692fdbea25SAleksandr Guzovskiy 	 */
48702fd872a7SPrakash Surya 	anon_size = MAX((int64_t)(refcount_count(&arc_anon->arcs_size) -
48712fd872a7SPrakash Surya 	    arc_loaned_bytes), 0);
48722fdbea25SAleksandr Guzovskiy 
48732fdbea25SAleksandr Guzovskiy 	/*
48741ab7f2deSmaybee 	 * Writes will, almost always, require additional memory allocations
4875f7170741SWill Andrews 	 * in order to compress/encrypt/etc the data.  We therefore need to
48761ab7f2deSmaybee 	 * make sure that there is sufficient available memory for this.
48771ab7f2deSmaybee 	 */
487869962b56SMatthew Ahrens 	error = arc_memory_throttle(reserve, txg);
487969962b56SMatthew Ahrens 	if (error != 0)
48801ab7f2deSmaybee 		return (error);
48811ab7f2deSmaybee 
48821ab7f2deSmaybee 	/*
4883112fe045Smaybee 	 * Throttle writes when the amount of dirty data in the cache
4884112fe045Smaybee 	 * gets too large.  We try to keep the cache less than half full
4885112fe045Smaybee 	 * of dirty blocks so that our sync times don't grow too large.
4886112fe045Smaybee 	 * Note: if two requests come in concurrently, we might let them
4887112fe045Smaybee 	 * both succeed, when one of them should fail.  Not a huge deal.
4888fa9e4066Sahrens 	 */
48892fdbea25SAleksandr Guzovskiy 
48902fdbea25SAleksandr Guzovskiy 	if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
48912fdbea25SAleksandr Guzovskiy 	    anon_size > arc_c / 4) {
48920e8c6158Smaybee 		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
48930e8c6158Smaybee 		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
48940e8c6158Smaybee 		    arc_tempreserve>>10,
48950e8c6158Smaybee 		    arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
48960e8c6158Smaybee 		    arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
48971ab7f2deSmaybee 		    reserve>>10, arc_c>>10);
4898be6fd75aSMatthew Ahrens 		return (SET_ERROR(ERESTART));
4899fa9e4066Sahrens 	}
49001ab7f2deSmaybee 	atomic_add_64(&arc_tempreserve, reserve);
4901fa9e4066Sahrens 	return (0);
4902fa9e4066Sahrens }
4903fa9e4066Sahrens 
49044076b1bfSPrakash Surya static void
49054076b1bfSPrakash Surya arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
49064076b1bfSPrakash Surya     kstat_named_t *evict_data, kstat_named_t *evict_metadata)
49074076b1bfSPrakash Surya {
49082fd872a7SPrakash Surya 	size->value.ui64 = refcount_count(&state->arcs_size);
49094076b1bfSPrakash Surya 	evict_data->value.ui64 = state->arcs_lsize[ARC_BUFC_DATA];
49104076b1bfSPrakash Surya 	evict_metadata->value.ui64 = state->arcs_lsize[ARC_BUFC_METADATA];
49114076b1bfSPrakash Surya }
49124076b1bfSPrakash Surya 
49134076b1bfSPrakash Surya static int
49144076b1bfSPrakash Surya arc_kstat_update(kstat_t *ksp, int rw)
49154076b1bfSPrakash Surya {
49164076b1bfSPrakash Surya 	arc_stats_t *as = ksp->ks_data;
49174076b1bfSPrakash Surya 
49184076b1bfSPrakash Surya 	if (rw == KSTAT_WRITE) {
49194076b1bfSPrakash Surya 		return (EACCES);
49204076b1bfSPrakash Surya 	} else {
49214076b1bfSPrakash Surya 		arc_kstat_update_state(arc_anon,
49224076b1bfSPrakash Surya 		    &as->arcstat_anon_size,
49234076b1bfSPrakash Surya 		    &as->arcstat_anon_evictable_data,
49244076b1bfSPrakash Surya 		    &as->arcstat_anon_evictable_metadata);
49254076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mru,
49264076b1bfSPrakash Surya 		    &as->arcstat_mru_size,
49274076b1bfSPrakash Surya 		    &as->arcstat_mru_evictable_data,
49284076b1bfSPrakash Surya 		    &as->arcstat_mru_evictable_metadata);
49294076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mru_ghost,
49304076b1bfSPrakash Surya 		    &as->arcstat_mru_ghost_size,
49314076b1bfSPrakash Surya 		    &as->arcstat_mru_ghost_evictable_data,
49324076b1bfSPrakash Surya 		    &as->arcstat_mru_ghost_evictable_metadata);
49334076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mfu,
49344076b1bfSPrakash Surya 		    &as->arcstat_mfu_size,
49354076b1bfSPrakash Surya 		    &as->arcstat_mfu_evictable_data,
49364076b1bfSPrakash Surya 		    &as->arcstat_mfu_evictable_metadata);
49374076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mfu_ghost,
49384076b1bfSPrakash Surya 		    &as->arcstat_mfu_ghost_size,
49394076b1bfSPrakash Surya 		    &as->arcstat_mfu_ghost_evictable_data,
49404076b1bfSPrakash Surya 		    &as->arcstat_mfu_ghost_evictable_metadata);
49414076b1bfSPrakash Surya 	}
49424076b1bfSPrakash Surya 
49434076b1bfSPrakash Surya 	return (0);
49444076b1bfSPrakash Surya }
49454076b1bfSPrakash Surya 
4946244781f1SPrakash Surya /*
4947244781f1SPrakash Surya  * This function *must* return indices evenly distributed between all
4948244781f1SPrakash Surya  * sublists of the multilist. This is needed due to how the ARC eviction
4949244781f1SPrakash Surya  * code is laid out; arc_evict_state() assumes ARC buffers are evenly
4950244781f1SPrakash Surya  * distributed between all sublists and uses this assumption when
4951244781f1SPrakash Surya  * deciding which sublist to evict from and how much to evict from it.
4952244781f1SPrakash Surya  */
4953244781f1SPrakash Surya unsigned int
4954244781f1SPrakash Surya arc_state_multilist_index_func(multilist_t *ml, void *obj)
4955244781f1SPrakash Surya {
4956244781f1SPrakash Surya 	arc_buf_hdr_t *hdr = obj;
4957244781f1SPrakash Surya 
4958244781f1SPrakash Surya 	/*
4959244781f1SPrakash Surya 	 * We rely on b_dva to generate evenly distributed index
4960244781f1SPrakash Surya 	 * numbers using buf_hash below. So, as an added precaution,
4961244781f1SPrakash Surya 	 * let's make sure we never add empty buffers to the arc lists.
4962244781f1SPrakash Surya 	 */
4963244781f1SPrakash Surya 	ASSERT(!BUF_EMPTY(hdr));
4964244781f1SPrakash Surya 
4965244781f1SPrakash Surya 	/*
4966244781f1SPrakash Surya 	 * The assumption here, is the hash value for a given
4967244781f1SPrakash Surya 	 * arc_buf_hdr_t will remain constant throughout it's lifetime
4968244781f1SPrakash Surya 	 * (i.e. it's b_spa, b_dva, and b_birth fields don't change).
4969244781f1SPrakash Surya 	 * Thus, we don't need to store the header's sublist index
4970244781f1SPrakash Surya 	 * on insertion, as this index can be recalculated on removal.
4971244781f1SPrakash Surya 	 *
4972244781f1SPrakash Surya 	 * Also, the low order bits of the hash value are thought to be
4973244781f1SPrakash Surya 	 * distributed evenly. Otherwise, in the case that the multilist
4974244781f1SPrakash Surya 	 * has a power of two number of sublists, each sublists' usage
4975244781f1SPrakash Surya 	 * would not be evenly distributed.
4976244781f1SPrakash Surya 	 */
4977244781f1SPrakash Surya 	return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
4978244781f1SPrakash Surya 	    multilist_get_num_sublists(ml));
4979244781f1SPrakash Surya }
4980244781f1SPrakash Surya 
4981fa9e4066Sahrens void
4982fa9e4066Sahrens arc_init(void)
4983fa9e4066Sahrens {
49842ec99e3eSMatthew Ahrens 	/*
49852ec99e3eSMatthew Ahrens 	 * allmem is "all memory that we could possibly use".
49862ec99e3eSMatthew Ahrens 	 */
49872ec99e3eSMatthew Ahrens #ifdef _KERNEL
49882ec99e3eSMatthew Ahrens 	uint64_t allmem = ptob(physmem - swapfs_minfree);
49892ec99e3eSMatthew Ahrens #else
49902ec99e3eSMatthew Ahrens 	uint64_t allmem = (physmem * PAGESIZE) / 2;
49912ec99e3eSMatthew Ahrens #endif
49922ec99e3eSMatthew Ahrens 
4993244781f1SPrakash Surya 	mutex_init(&arc_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
4994244781f1SPrakash Surya 	cv_init(&arc_reclaim_thread_cv, NULL, CV_DEFAULT, NULL);
4995244781f1SPrakash Surya 	cv_init(&arc_reclaim_waiters_cv, NULL, CV_DEFAULT, NULL);
4996244781f1SPrakash Surya 
4997244781f1SPrakash Surya 	mutex_init(&arc_user_evicts_lock, NULL, MUTEX_DEFAULT, NULL);
4998244781f1SPrakash Surya 	cv_init(&arc_user_evicts_cv, NULL, CV_DEFAULT, NULL);
4999fa9e4066Sahrens 
500013506d1eSmaybee 	/* Convert seconds to clock ticks */
5001b19a79ecSperrin 	arc_min_prefetch_lifespan = 1 * hz;
500213506d1eSmaybee 
5003fa9e4066Sahrens 	/* Start out with 1/8 of all memory */
50042ec99e3eSMatthew Ahrens 	arc_c = allmem / 8;
5005fa9e4066Sahrens 
5006fa9e4066Sahrens #ifdef _KERNEL
5007fa9e4066Sahrens 	/*
5008fa9e4066Sahrens 	 * On architectures where the physical memory can be larger
5009fa9e4066Sahrens 	 * than the addressable space (intel in 32-bit mode), we may
5010fa9e4066Sahrens 	 * need to limit the cache to 1/8 of VM size.
5011fa9e4066Sahrens 	 */
501244cb6abcSbmc 	arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
5013fa9e4066Sahrens #endif
5014fa9e4066Sahrens 
5015112fe045Smaybee 	/* set min cache to 1/32 of all memory, or 64MB, whichever is more */
50162ec99e3eSMatthew Ahrens 	arc_c_min = MAX(allmem / 32, 64 << 20);
5017112fe045Smaybee 	/* set max to 3/4 of all memory, or all but 1GB, whichever is more */
50182ec99e3eSMatthew Ahrens 	if (allmem >= 1 << 30)
50192ec99e3eSMatthew Ahrens 		arc_c_max = allmem - (1 << 30);
5020fa9e4066Sahrens 	else
502144cb6abcSbmc 		arc_c_max = arc_c_min;
50222ec99e3eSMatthew Ahrens 	arc_c_max = MAX(allmem * 3 / 4, arc_c_max);
5023a2eea2e1Sahrens 
5024a2eea2e1Sahrens 	/*
50258fe00bfbSMatthew Ahrens 	 * In userland, there's only the memory pressure that we artificially
50268fe00bfbSMatthew Ahrens 	 * create (see arc_available_memory()).  Don't let arc_c get too
50278fe00bfbSMatthew Ahrens 	 * small, because it can cause transactions to be larger than
50288fe00bfbSMatthew Ahrens 	 * arc_c, causing arc_tempreserve_space() to fail.
50298fe00bfbSMatthew Ahrens 	 */
50308fe00bfbSMatthew Ahrens #ifndef _KERNEL
50318fe00bfbSMatthew Ahrens 	arc_c_min = arc_c_max / 2;
50328fe00bfbSMatthew Ahrens #endif
50338fe00bfbSMatthew Ahrens 
50348fe00bfbSMatthew Ahrens 	/*
5035a2eea2e1Sahrens 	 * Allow the tunables to override our calculations if they are
5036a2eea2e1Sahrens 	 * reasonable (ie. over 64MB)
5037a2eea2e1Sahrens 	 */
50382ec99e3eSMatthew Ahrens 	if (zfs_arc_max > 64 << 20 && zfs_arc_max < allmem)
503944cb6abcSbmc 		arc_c_max = zfs_arc_max;
504044cb6abcSbmc 	if (zfs_arc_min > 64 << 20 && zfs_arc_min <= arc_c_max)
504144cb6abcSbmc 		arc_c_min = zfs_arc_min;
5042a2eea2e1Sahrens 
504344cb6abcSbmc 	arc_c = arc_c_max;
504444cb6abcSbmc 	arc_p = (arc_c >> 1);
5045fa9e4066Sahrens 
50460e8c6158Smaybee 	/* limit meta-data to 1/4 of the arc capacity */
50470e8c6158Smaybee 	arc_meta_limit = arc_c_max / 4;
50481116048bSek110237 
50491116048bSek110237 	/* Allow the tunable to override if it is reasonable */
50501116048bSek110237 	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
50511116048bSek110237 		arc_meta_limit = zfs_arc_meta_limit;
50521116048bSek110237 
50530e8c6158Smaybee 	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
50540e8c6158Smaybee 		arc_c_min = arc_meta_limit / 2;
50550e8c6158Smaybee 
50563a5286a1SMatthew Ahrens 	if (zfs_arc_meta_min > 0) {
50573a5286a1SMatthew Ahrens 		arc_meta_min = zfs_arc_meta_min;
50583a5286a1SMatthew Ahrens 	} else {
50593a5286a1SMatthew Ahrens 		arc_meta_min = arc_c_min / 2;
50603a5286a1SMatthew Ahrens 	}
50613a5286a1SMatthew Ahrens 
50625a98e54bSBrendan Gregg - Sun Microsystems 	if (zfs_arc_grow_retry > 0)
50635a98e54bSBrendan Gregg - Sun Microsystems 		arc_grow_retry = zfs_arc_grow_retry;
50645a98e54bSBrendan Gregg - Sun Microsystems 
50655a98e54bSBrendan Gregg - Sun Microsystems 	if (zfs_arc_shrink_shift > 0)
50665a98e54bSBrendan Gregg - Sun Microsystems 		arc_shrink_shift = zfs_arc_shrink_shift;
50675a98e54bSBrendan Gregg - Sun Microsystems 
50682ec99e3eSMatthew Ahrens 	/*
50692ec99e3eSMatthew Ahrens 	 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
50702ec99e3eSMatthew Ahrens 	 */
50712ec99e3eSMatthew Ahrens 	if (arc_no_grow_shift >= arc_shrink_shift)
50722ec99e3eSMatthew Ahrens 		arc_no_grow_shift = arc_shrink_shift - 1;
50732ec99e3eSMatthew Ahrens 
50745a98e54bSBrendan Gregg - Sun Microsystems 	if (zfs_arc_p_min_shift > 0)
50755a98e54bSBrendan Gregg - Sun Microsystems 		arc_p_min_shift = zfs_arc_p_min_shift;
50765a98e54bSBrendan Gregg - Sun Microsystems 
5077244781f1SPrakash Surya 	if (zfs_arc_num_sublists_per_state < 1)
5078244781f1SPrakash Surya 		zfs_arc_num_sublists_per_state = MAX(boot_ncpus, 1);
5079244781f1SPrakash Surya 
5080fa9e4066Sahrens 	/* if kmem_flags are set, lets try to use less memory */
5081fa9e4066Sahrens 	if (kmem_debugging())
508244cb6abcSbmc 		arc_c = arc_c / 2;
508344cb6abcSbmc 	if (arc_c < arc_c_min)
508444cb6abcSbmc 		arc_c = arc_c_min;
5085fa9e4066Sahrens 
508644cb6abcSbmc 	arc_anon = &ARC_anon;
508744cb6abcSbmc 	arc_mru = &ARC_mru;
508844cb6abcSbmc 	arc_mru_ghost = &ARC_mru_ghost;
508944cb6abcSbmc 	arc_mfu = &ARC_mfu;
509044cb6abcSbmc 	arc_mfu_ghost = &ARC_mfu_ghost;
5091fa94a07fSbrendan 	arc_l2c_only = &ARC_l2c_only;
509244cb6abcSbmc 	arc_size = 0;
5093fa9e4066Sahrens 
5094244781f1SPrakash Surya 	multilist_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
509589c86e32SChris Williamson 	    sizeof (arc_buf_hdr_t),
5096244781f1SPrakash Surya 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5097244781f1SPrakash Surya 	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5098244781f1SPrakash Surya 	multilist_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
509989c86e32SChris Williamson 	    sizeof (arc_buf_hdr_t),
5100244781f1SPrakash Surya 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5101244781f1SPrakash Surya 	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5102244781f1SPrakash Surya 	multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
510389c86e32SChris Williamson 	    sizeof (arc_buf_hdr_t),
5104244781f1SPrakash Surya 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5105244781f1SPrakash Surya 	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5106244781f1SPrakash Surya 	multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
510789c86e32SChris Williamson 	    sizeof (arc_buf_hdr_t),
5108244781f1SPrakash Surya 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5109244781f1SPrakash Surya 	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5110244781f1SPrakash Surya 	multilist_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
511189c86e32SChris Williamson 	    sizeof (arc_buf_hdr_t),
5112244781f1SPrakash Surya 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5113244781f1SPrakash Surya 	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5114244781f1SPrakash Surya 	multilist_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
511589c86e32SChris Williamson 	    sizeof (arc_buf_hdr_t),
5116244781f1SPrakash Surya 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5117244781f1SPrakash Surya 	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5118244781f1SPrakash Surya 	multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
511989c86e32SChris Williamson 	    sizeof (arc_buf_hdr_t),
5120244781f1SPrakash Surya 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5121244781f1SPrakash Surya 	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5122244781f1SPrakash Surya 	multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
512389c86e32SChris Williamson 	    sizeof (arc_buf_hdr_t),
5124244781f1SPrakash Surya 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5125244781f1SPrakash Surya 	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5126244781f1SPrakash Surya 	multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
512789c86e32SChris Williamson 	    sizeof (arc_buf_hdr_t),
5128244781f1SPrakash Surya 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5129244781f1SPrakash Surya 	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5130244781f1SPrakash Surya 	multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
513189c86e32SChris Williamson 	    sizeof (arc_buf_hdr_t),
5132244781f1SPrakash Surya 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5133244781f1SPrakash Surya 	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5134fa9e4066Sahrens 
51352fd872a7SPrakash Surya 	refcount_create(&arc_anon->arcs_size);
51362fd872a7SPrakash Surya 	refcount_create(&arc_mru->arcs_size);
51372fd872a7SPrakash Surya 	refcount_create(&arc_mru_ghost->arcs_size);
51382fd872a7SPrakash Surya 	refcount_create(&arc_mfu->arcs_size);
51392fd872a7SPrakash Surya 	refcount_create(&arc_mfu_ghost->arcs_size);
51402fd872a7SPrakash Surya 	refcount_create(&arc_l2c_only->arcs_size);
51412fd872a7SPrakash Surya 
5142fa9e4066Sahrens 	buf_init();
5143fa9e4066Sahrens 
5144244781f1SPrakash Surya 	arc_reclaim_thread_exit = FALSE;
5145244781f1SPrakash Surya 	arc_user_evicts_thread_exit = FALSE;
5146ea8dc4b6Seschrock 	arc_eviction_list = NULL;
514740d7d650Smaybee 	bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
5148fa9e4066Sahrens 
514944cb6abcSbmc 	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
515044cb6abcSbmc 	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
515144cb6abcSbmc 
515244cb6abcSbmc 	if (arc_ksp != NULL) {
515344cb6abcSbmc 		arc_ksp->ks_data = &arc_stats;
51544076b1bfSPrakash Surya 		arc_ksp->ks_update = arc_kstat_update;
515544cb6abcSbmc 		kstat_install(arc_ksp);
515644cb6abcSbmc 	}
515744cb6abcSbmc 
5158fa9e4066Sahrens 	(void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
5159fa9e4066Sahrens 	    TS_RUN, minclsyspri);
516049e3519aSmaybee 
5161244781f1SPrakash Surya 	(void) thread_create(NULL, 0, arc_user_evicts_thread, NULL, 0, &p0,
5162244781f1SPrakash Surya 	    TS_RUN, minclsyspri);
5163244781f1SPrakash Surya 
516449e3519aSmaybee 	arc_dead = FALSE;
51653a737e0dSbrendan 	arc_warm = B_FALSE;
51661ab7f2deSmaybee 
516769962b56SMatthew Ahrens 	/*
516869962b56SMatthew Ahrens 	 * Calculate maximum amount of dirty data per pool.
516969962b56SMatthew Ahrens 	 *
517069962b56SMatthew Ahrens 	 * If it has been set by /etc/system, take that.
517169962b56SMatthew Ahrens 	 * Otherwise, use a percentage of physical memory defined by
517269962b56SMatthew Ahrens 	 * zfs_dirty_data_max_percent (default 10%) with a cap at
517369962b56SMatthew Ahrens 	 * zfs_dirty_data_max_max (default 4GB).
517469962b56SMatthew Ahrens 	 */
517569962b56SMatthew Ahrens 	if (zfs_dirty_data_max == 0) {
517669962b56SMatthew Ahrens 		zfs_dirty_data_max = physmem * PAGESIZE *
517769962b56SMatthew Ahrens 		    zfs_dirty_data_max_percent / 100;
517869962b56SMatthew Ahrens 		zfs_dirty_data_max = MIN(zfs_dirty_data_max,
517969962b56SMatthew Ahrens 		    zfs_dirty_data_max_max);
518069962b56SMatthew Ahrens 	}
5181fa9e4066Sahrens }
5182fa9e4066Sahrens 
5183fa9e4066Sahrens void
5184fa9e4066Sahrens arc_fini(void)
5185fa9e4066Sahrens {
5186244781f1SPrakash Surya 	mutex_enter(&arc_reclaim_lock);
5187244781f1SPrakash Surya 	arc_reclaim_thread_exit = TRUE;
5188244781f1SPrakash Surya 	/*
5189244781f1SPrakash Surya 	 * The reclaim thread will set arc_reclaim_thread_exit back to
5190244781f1SPrakash Surya 	 * FALSE when it is finished exiting; we're waiting for that.
5191244781f1SPrakash Surya 	 */
5192244781f1SPrakash Surya 	while (arc_reclaim_thread_exit) {
5193244781f1SPrakash Surya 		cv_signal(&arc_reclaim_thread_cv);
5194244781f1SPrakash Surya 		cv_wait(&arc_reclaim_thread_cv, &arc_reclaim_lock);
5195244781f1SPrakash Surya 	}
5196244781f1SPrakash Surya 	mutex_exit(&arc_reclaim_lock);
5197fa9e4066Sahrens 
5198244781f1SPrakash Surya 	mutex_enter(&arc_user_evicts_lock);
5199244781f1SPrakash Surya 	arc_user_evicts_thread_exit = TRUE;
5200244781f1SPrakash Surya 	/*
5201244781f1SPrakash Surya 	 * The user evicts thread will set arc_user_evicts_thread_exit
5202244781f1SPrakash Surya 	 * to FALSE when it is finished exiting; we're waiting for that.
5203244781f1SPrakash Surya 	 */
5204244781f1SPrakash Surya 	while (arc_user_evicts_thread_exit) {
5205244781f1SPrakash Surya 		cv_signal(&arc_user_evicts_cv);
5206244781f1SPrakash Surya 		cv_wait(&arc_user_evicts_cv, &arc_user_evicts_lock);
5207244781f1SPrakash Surya 	}
5208244781f1SPrakash Surya 	mutex_exit(&arc_user_evicts_lock);
5209244781f1SPrakash Surya 
5210244781f1SPrakash Surya 	/* Use TRUE to ensure *all* buffers are evicted */
5211244781f1SPrakash Surya 	arc_flush(NULL, TRUE);
5212fa9e4066Sahrens 
5213fa9e4066Sahrens 	arc_dead = TRUE;
5214fa9e4066Sahrens 
521544cb6abcSbmc 	if (arc_ksp != NULL) {
521644cb6abcSbmc 		kstat_delete(arc_ksp);
521744cb6abcSbmc 		arc_ksp = NULL;
521844cb6abcSbmc 	}
521944cb6abcSbmc 
5220244781f1SPrakash Surya 	mutex_destroy(&arc_reclaim_lock);
5221244781f1SPrakash Surya 	cv_destroy(&arc_reclaim_thread_cv);
5222244781f1SPrakash Surya 	cv_destroy(&arc_reclaim_waiters_cv);
5223fa9e4066Sahrens 
5224244781f1SPrakash Surya 	mutex_destroy(&arc_user_evicts_lock);
5225244781f1SPrakash Surya 	cv_destroy(&arc_user_evicts_cv);
5226fa9e4066Sahrens 
52272fd872a7SPrakash Surya 	refcount_destroy(&arc_anon->arcs_size);
52282fd872a7SPrakash Surya 	refcount_destroy(&arc_mru->arcs_size);
52292fd872a7SPrakash Surya 	refcount_destroy(&arc_mru_ghost->arcs_size);
52302fd872a7SPrakash Surya 	refcount_destroy(&arc_mfu->arcs_size);
52312fd872a7SPrakash Surya 	refcount_destroy(&arc_mfu_ghost->arcs_size);
52322fd872a7SPrakash Surya 	refcount_destroy(&arc_l2c_only->arcs_size);
52332fd872a7SPrakash Surya 
5234244781f1SPrakash Surya 	multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
5235244781f1SPrakash Surya 	multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
5236244781f1SPrakash Surya 	multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
5237244781f1SPrakash Surya 	multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
523857deb232SPrakash Surya 	multilist_destroy(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA]);
5239244781f1SPrakash Surya 	multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
5240244781f1SPrakash Surya 	multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
5241244781f1SPrakash Surya 	multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
5242244781f1SPrakash Surya 	multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
524357deb232SPrakash Surya 	multilist_destroy(&arc_l2c_only->arcs_list[ARC_BUFC_DATA]);
52445ad82045Snd150628 
5245fa9e4066Sahrens 	buf_fini();
52462fdbea25SAleksandr Guzovskiy 
524789c86e32SChris Williamson 	ASSERT0(arc_loaned_bytes);
5248fa9e4066Sahrens }
5249fa94a07fSbrendan 
5250fa94a07fSbrendan /*
5251fa94a07fSbrendan  * Level 2 ARC
5252fa94a07fSbrendan  *
5253fa94a07fSbrendan  * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
5254fa94a07fSbrendan  * It uses dedicated storage devices to hold cached data, which are populated
5255fa94a07fSbrendan  * using large infrequent writes.  The main role of this cache is to boost
5256fa94a07fSbrendan  * the performance of random read workloads.  The intended L2ARC devices
5257fa94a07fSbrendan  * include short-stroked disks, solid state disks, and other media with
5258fa94a07fSbrendan  * substantially faster read latency than disk.
5259fa94a07fSbrendan  *
5260fa94a07fSbrendan  *                 +-----------------------+
5261fa94a07fSbrendan  *                 |         ARC           |
5262fa94a07fSbrendan  *                 +-----------------------+
5263fa94a07fSbrendan  *                    |         ^     ^
5264fa94a07fSbrendan  *                    |         |     |
5265fa94a07fSbrendan  *      l2arc_feed_thread()    arc_read()
5266fa94a07fSbrendan  *                    |         |     |
5267fa94a07fSbrendan  *                    |  l2arc read   |
5268fa94a07fSbrendan  *                    V         |     |
5269fa94a07fSbrendan  *               +---------------+    |
5270fa94a07fSbrendan  *               |     L2ARC     |    |
5271fa94a07fSbrendan  *               +---------------+    |
5272fa94a07fSbrendan  *                   |    ^           |
5273fa94a07fSbrendan  *          l2arc_write() |           |
5274fa94a07fSbrendan  *                   |    |           |
5275fa94a07fSbrendan  *                   V    |           |
5276fa94a07fSbrendan  *                 +-------+      +-------+
5277fa94a07fSbrendan  *                 | vdev  |      | vdev  |
5278fa94a07fSbrendan  *                 | cache |      | cache |
5279fa94a07fSbrendan  *                 +-------+      +-------+
5280fa94a07fSbrendan  *                 +=========+     .-----.
5281fa94a07fSbrendan  *                 :  L2ARC  :    |-_____-|
5282fa94a07fSbrendan  *                 : devices :    | Disks |
5283fa94a07fSbrendan  *                 +=========+    `-_____-'
5284fa94a07fSbrendan  *
5285fa94a07fSbrendan  * Read requests are satisfied from the following sources, in order:
5286fa94a07fSbrendan  *
5287fa94a07fSbrendan  *	1) ARC
5288fa94a07fSbrendan  *	2) vdev cache of L2ARC devices
5289fa94a07fSbrendan  *	3) L2ARC devices
5290fa94a07fSbrendan  *	4) vdev cache of disks
5291fa94a07fSbrendan  *	5) disks
5292fa94a07fSbrendan  *
5293fa94a07fSbrendan  * Some L2ARC device types exhibit extremely slow write performance.
5294fa94a07fSbrendan  * To accommodate for this there are some significant differences between
5295fa94a07fSbrendan  * the L2ARC and traditional cache design:
5296fa94a07fSbrendan  *
5297fa94a07fSbrendan  * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
5298fa94a07fSbrendan  * the ARC behave as usual, freeing buffers and placing headers on ghost
5299fa94a07fSbrendan  * lists.  The ARC does not send buffers to the L2ARC during eviction as
5300fa94a07fSbrendan  * this would add inflated write latencies for all ARC memory pressure.
5301fa94a07fSbrendan  *
5302fa94a07fSbrendan  * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
5303fa94a07fSbrendan  * It does this by periodically scanning buffers from the eviction-end of
5304fa94a07fSbrendan  * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
5305fa94a07fSbrendan  * not already there. It scans until a headroom of buffers is satisfied,
5306aad02571SSaso Kiselkov  * which itself is a buffer for ARC eviction. If a compressible buffer is
5307aad02571SSaso Kiselkov  * found during scanning and selected for writing to an L2ARC device, we
5308aad02571SSaso Kiselkov  * temporarily boost scanning headroom during the next scan cycle to make
5309aad02571SSaso Kiselkov  * sure we adapt to compression effects (which might significantly reduce
5310aad02571SSaso Kiselkov  * the data volume we write to L2ARC). The thread that does this is
5311fa94a07fSbrendan  * l2arc_feed_thread(), illustrated below; example sizes are included to
5312fa94a07fSbrendan  * provide a better sense of ratio than this diagram:
5313fa94a07fSbrendan  *
5314fa94a07fSbrendan  *	       head -->                        tail
5315fa94a07fSbrendan  *	        +---------------------+----------+
5316fa94a07fSbrendan  *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
5317fa94a07fSbrendan  *	        +---------------------+----------+   |   o L2ARC eligible
5318fa94a07fSbrendan  *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
5319fa94a07fSbrendan  *	        +---------------------+----------+   |
5320fa94a07fSbrendan  *	             15.9 Gbytes      ^ 32 Mbytes    |
5321fa94a07fSbrendan  *	                           headroom          |
5322fa94a07fSbrendan  *	                                      l2arc_feed_thread()
5323fa94a07fSbrendan  *	                                             |
5324fa94a07fSbrendan  *	                 l2arc write hand <--[oooo]--'
5325fa94a07fSbrendan  *	                         |           8 Mbyte
5326fa94a07fSbrendan  *	                         |          write max
5327fa94a07fSbrendan  *	                         V
5328fa94a07fSbrendan  *		  +==============================+
5329fa94a07fSbrendan  *	L2ARC dev |####|#|###|###|    |####| ... |
5330fa94a07fSbrendan  *	          +==============================+
5331fa94a07fSbrendan  *	                     32 Gbytes
5332fa94a07fSbrendan  *
5333fa94a07fSbrendan  * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
5334fa94a07fSbrendan  * evicted, then the L2ARC has cached a buffer much sooner than it probably
5335fa94a07fSbrendan  * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
5336fa94a07fSbrendan  * safe to say that this is an uncommon case, since buffers at the end of
5337fa94a07fSbrendan  * the ARC lists have moved there due to inactivity.
5338fa94a07fSbrendan  *
5339fa94a07fSbrendan  * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
5340fa94a07fSbrendan  * then the L2ARC simply misses copying some buffers.  This serves as a
5341fa94a07fSbrendan  * pressure valve to prevent heavy read workloads from both stalling the ARC
5342fa94a07fSbrendan  * with waits and clogging the L2ARC with writes.  This also helps prevent
5343fa94a07fSbrendan  * the potential for the L2ARC to churn if it attempts to cache content too
5344fa94a07fSbrendan  * quickly, such as during backups of the entire pool.
5345fa94a07fSbrendan  *
53463a737e0dSbrendan  * 5. After system boot and before the ARC has filled main memory, there are
53473a737e0dSbrendan  * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
53483a737e0dSbrendan  * lists can remain mostly static.  Instead of searching from tail of these
53493a737e0dSbrendan  * lists as pictured, the l2arc_feed_thread() will search from the list heads
53503a737e0dSbrendan  * for eligible buffers, greatly increasing its chance of finding them.
53513a737e0dSbrendan  *
53523a737e0dSbrendan  * The L2ARC device write speed is also boosted during this time so that
53533a737e0dSbrendan  * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
53543a737e0dSbrendan  * there are no L2ARC reads, and no fear of degrading read performance
53553a737e0dSbrendan  * through increased writes.
53563a737e0dSbrendan  *
53573a737e0dSbrendan  * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
5358fa94a07fSbrendan  * the vdev queue can aggregate them into larger and fewer writes.  Each
5359fa94a07fSbrendan  * device is written to in a rotor fashion, sweeping writes through
5360fa94a07fSbrendan  * available space then repeating.
5361fa94a07fSbrendan  *
53623a737e0dSbrendan  * 7. The L2ARC does not store dirty content.  It never needs to flush
5363fa94a07fSbrendan  * write buffers back to disk based storage.
5364fa94a07fSbrendan  *
53653a737e0dSbrendan  * 8. If an ARC buffer is written (and dirtied) which also exists in the
5366fa94a07fSbrendan  * L2ARC, the now stale L2ARC buffer is immediately dropped.
5367fa94a07fSbrendan  *
5368fa94a07fSbrendan  * The performance of the L2ARC can be tweaked by a number of tunables, which
5369fa94a07fSbrendan  * may be necessary for different workloads:
5370fa94a07fSbrendan  *
5371fa94a07fSbrendan  *	l2arc_write_max		max write bytes per interval
53723a737e0dSbrendan  *	l2arc_write_boost	extra write bytes during device warmup
5373fa94a07fSbrendan  *	l2arc_noprefetch	skip caching prefetched buffers
5374fa94a07fSbrendan  *	l2arc_headroom		number of max device writes to precache
5375aad02571SSaso Kiselkov  *	l2arc_headroom_boost	when we find compressed buffers during ARC
5376aad02571SSaso Kiselkov  *				scanning, we multiply headroom by this
5377aad02571SSaso Kiselkov  *				percentage factor for the next scan cycle,
5378aad02571SSaso Kiselkov  *				since more compressed buffers are likely to
5379aad02571SSaso Kiselkov  *				be present
5380fa94a07fSbrendan  *	l2arc_feed_secs		seconds between L2ARC writing
5381fa94a07fSbrendan  *
5382fa94a07fSbrendan  * Tunables may be removed or added as future performance improvements are
5383fa94a07fSbrendan  * integrated, and also may become zpool properties.
53845a98e54bSBrendan Gregg - Sun Microsystems  *
53855a98e54bSBrendan Gregg - Sun Microsystems  * There are three key functions that control how the L2ARC warms up:
53865a98e54bSBrendan Gregg - Sun Microsystems  *
53875a98e54bSBrendan Gregg - Sun Microsystems  *	l2arc_write_eligible()	check if a buffer is eligible to cache
53885a98e54bSBrendan Gregg - Sun Microsystems  *	l2arc_write_size()	calculate how much to write
53895a98e54bSBrendan Gregg - Sun Microsystems  *	l2arc_write_interval()	calculate sleep delay between writes
53905a98e54bSBrendan Gregg - Sun Microsystems  *
53915a98e54bSBrendan Gregg - Sun Microsystems  * These three functions determine what to write, how much, and how quickly
53925a98e54bSBrendan Gregg - Sun Microsystems  * to send writes.
5393fa94a07fSbrendan  */
5394fa94a07fSbrendan 
53955a98e54bSBrendan Gregg - Sun Microsystems static boolean_t
5396f5ca7025SSaso Kiselkov l2arc_write_eligible(uint64_t spa_guid, uint64_t sync_txg, arc_buf_hdr_t *hdr)
53975a98e54bSBrendan Gregg - Sun Microsystems {
53985a98e54bSBrendan Gregg - Sun Microsystems 	/*
53995a98e54bSBrendan Gregg - Sun Microsystems 	 * A buffer is *not* eligible for the L2ARC if it:
54005a98e54bSBrendan Gregg - Sun Microsystems 	 * 1. belongs to a different spa.
54015ea40c06SBrendan Gregg - Sun Microsystems 	 * 2. is already cached on the L2ARC.
54025ea40c06SBrendan Gregg - Sun Microsystems 	 * 3. has an I/O in progress (it may be an incomplete read).
54035ea40c06SBrendan Gregg - Sun Microsystems 	 * 4. is flagged not eligible (zfs property).
5404f5ca7025SSaso Kiselkov 	 * 5. is part of the syncing txg (and thus subject to change).
54055a98e54bSBrendan Gregg - Sun Microsystems 	 */
540689c86e32SChris Williamson 	if (hdr->b_spa != spa_guid || HDR_HAS_L2HDR(hdr) ||
5407f5ca7025SSaso Kiselkov 	    HDR_IO_IN_PROGRESS(hdr) || !HDR_L2CACHE(hdr) ||
5408f5ca7025SSaso Kiselkov 	    hdr->b_birth >= sync_txg)
54095a98e54bSBrendan Gregg - Sun Microsystems 		return (B_FALSE);
54105a98e54bSBrendan Gregg - Sun Microsystems 
54115a98e54bSBrendan Gregg - Sun Microsystems 	return (B_TRUE);
54125a98e54bSBrendan Gregg - Sun Microsystems }
54135a98e54bSBrendan Gregg - Sun Microsystems 
54145a98e54bSBrendan Gregg - Sun Microsystems static uint64_t
5415aad02571SSaso Kiselkov l2arc_write_size(void)
54165a98e54bSBrendan Gregg - Sun Microsystems {
54175a98e54bSBrendan Gregg - Sun Microsystems 	uint64_t size;
54185a98e54bSBrendan Gregg - Sun Microsystems 
5419aad02571SSaso Kiselkov 	/*
5420aad02571SSaso Kiselkov 	 * Make sure our globals have meaningful values in case the user
5421aad02571SSaso Kiselkov 	 * altered them.
5422aad02571SSaso Kiselkov 	 */
5423aad02571SSaso Kiselkov 	size = l2arc_write_max;
5424aad02571SSaso Kiselkov 	if (size == 0) {
5425aad02571SSaso Kiselkov 		cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
5426aad02571SSaso Kiselkov 		    "be greater than zero, resetting it to the default (%d)",
5427aad02571SSaso Kiselkov 		    L2ARC_WRITE_SIZE);
5428aad02571SSaso Kiselkov 		size = l2arc_write_max = L2ARC_WRITE_SIZE;
5429aad02571SSaso Kiselkov 	}
54305a98e54bSBrendan Gregg - Sun Microsystems 
54315a98e54bSBrendan Gregg - Sun Microsystems 	if (arc_warm == B_FALSE)
5432aad02571SSaso Kiselkov 		size += l2arc_write_boost;
54335a98e54bSBrendan Gregg - Sun Microsystems 
54345a98e54bSBrendan Gregg - Sun Microsystems 	return (size);
54355a98e54bSBrendan Gregg - Sun Microsystems 
54365a98e54bSBrendan Gregg - Sun Microsystems }
54375a98e54bSBrendan Gregg - Sun Microsystems 
54385a98e54bSBrendan Gregg - Sun Microsystems static clock_t
54395a98e54bSBrendan Gregg - Sun Microsystems l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
54405a98e54bSBrendan Gregg - Sun Microsystems {
5441d3d50737SRafael Vanoni 	clock_t interval, next, now;
54425a98e54bSBrendan Gregg - Sun Microsystems 
54435a98e54bSBrendan Gregg - Sun Microsystems 	/*
54445a98e54bSBrendan Gregg - Sun Microsystems 	 * If the ARC lists are busy, increase our write rate; if the
54455a98e54bSBrendan Gregg - Sun Microsystems 	 * lists are stale, idle back.  This is achieved by checking
54465a98e54bSBrendan Gregg - Sun Microsystems 	 * how much we previously wrote - if it was more than half of
54475a98e54bSBrendan Gregg - Sun Microsystems 	 * what we wanted, schedule the next write much sooner.
54485a98e54bSBrendan Gregg - Sun Microsystems 	 */
54495a98e54bSBrendan Gregg - Sun Microsystems 	if (l2arc_feed_again && wrote > (wanted / 2))
54505a98e54bSBrendan Gregg - Sun Microsystems 		interval = (hz * l2arc_feed_min_ms) / 1000;
54515a98e54bSBrendan Gregg - Sun Microsystems 	else
54525a98e54bSBrendan Gregg - Sun Microsystems 		interval = hz * l2arc_feed_secs;
54535a98e54bSBrendan Gregg - Sun Microsystems 
5454d3d50737SRafael Vanoni 	now = ddi_get_lbolt();
5455d3d50737SRafael Vanoni 	next = MAX(now, MIN(now + interval, began + interval));
54565a98e54bSBrendan Gregg - Sun Microsystems 
54575a98e54bSBrendan Gregg - Sun Microsystems 	return (next);
54585a98e54bSBrendan Gregg - Sun Microsystems }
54595a98e54bSBrendan Gregg - Sun Microsystems 
5460fa94a07fSbrendan /*
5461fa94a07fSbrendan  * Cycle through L2ARC devices.  This is how L2ARC load balances.
54623a737e0dSbrendan  * If a device is returned, this also returns holding the spa config lock.
5463fa94a07fSbrendan  */
5464fa94a07fSbrendan static l2arc_dev_t *
5465fa94a07fSbrendan l2arc_dev_get_next(void)
5466fa94a07fSbrendan {
54673a737e0dSbrendan 	l2arc_dev_t *first, *next = NULL;
54683a737e0dSbrendan 
54693a737e0dSbrendan 	/*
54703a737e0dSbrendan 	 * Lock out the removal of spas (spa_namespace_lock), then removal
54713a737e0dSbrendan 	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
54723a737e0dSbrendan 	 * both locks will be dropped and a spa config lock held instead.
54733a737e0dSbrendan 	 */
54743a737e0dSbrendan 	mutex_enter(&spa_namespace_lock);
54753a737e0dSbrendan 	mutex_enter(&l2arc_dev_mtx);
5476fa94a07fSbrendan 
5477c5904d13Seschrock 	/* if there are no vdevs, there is nothing to do */
5478c5904d13Seschrock 	if (l2arc_ndev == 0)
54793a737e0dSbrendan 		goto out;
5480c5904d13Seschrock 
5481c5904d13Seschrock 	first = NULL;
5482c5904d13Seschrock 	next = l2arc_dev_last;
5483c5904d13Seschrock 	do {
5484c5904d13Seschrock 		/* loop around the list looking for a non-faulted vdev */
5485c5904d13Seschrock 		if (next == NULL) {
5486fa94a07fSbrendan 			next = list_head(l2arc_dev_list);
5487fa94a07fSbrendan 		} else {
5488c5904d13Seschrock 			next = list_next(l2arc_dev_list, next);
5489fa94a07fSbrendan 			if (next == NULL)
5490fa94a07fSbrendan 				next = list_head(l2arc_dev_list);
5491fa94a07fSbrendan 		}
5492fa94a07fSbrendan 
5493c5904d13Seschrock 		/* if we have come back to the start, bail out */
5494c5904d13Seschrock 		if (first == NULL)
5495c5904d13Seschrock 			first = next;
5496c5904d13Seschrock 		else if (next == first)
5497c5904d13Seschrock 			break;
5498c5904d13Seschrock 
5499*5f992543SArne Jansen 	} while (vdev_is_dead(next->l2ad_vdev));
5500c5904d13Seschrock 
5501c5904d13Seschrock 	/* if we were unable to find any usable vdevs, return NULL */
5502*5f992543SArne Jansen 	if (vdev_is_dead(next->l2ad_vdev))
55033a737e0dSbrendan 		next = NULL;
5504c5904d13Seschrock 
5505fa94a07fSbrendan 	l2arc_dev_last = next;
5506fa94a07fSbrendan 
55073a737e0dSbrendan out:
55083a737e0dSbrendan 	mutex_exit(&l2arc_dev_mtx);
55093a737e0dSbrendan 
55103a737e0dSbrendan 	/*
55113a737e0dSbrendan 	 * Grab the config lock to prevent the 'next' device from being
55123a737e0dSbrendan 	 * removed while we are writing to it.
55133a737e0dSbrendan 	 */
55143a737e0dSbrendan 	if (next != NULL)
5515e14bb325SJeff Bonwick 		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
55163a737e0dSbrendan 	mutex_exit(&spa_namespace_lock);
55173a737e0dSbrendan 
5518fa94a07fSbrendan 	return (next);
5519fa94a07fSbrendan }
5520fa94a07fSbrendan 
5521fa94a07fSbrendan /*
55223a737e0dSbrendan  * Free buffers that were tagged for destruction.
55233a737e0dSbrendan  */
55243a737e0dSbrendan static void
55253a737e0dSbrendan l2arc_do_free_on_write()
55263a737e0dSbrendan {
55273a737e0dSbrendan 	list_t *buflist;
55283a737e0dSbrendan 	l2arc_data_free_t *df, *df_prev;
55293a737e0dSbrendan 
55303a737e0dSbrendan 	mutex_enter(&l2arc_free_on_write_mtx);
55313a737e0dSbrendan 	buflist = l2arc_free_on_write;
55323a737e0dSbrendan 
55333a737e0dSbrendan 	for (df = list_tail(buflist); df; df = df_prev) {
55343a737e0dSbrendan 		df_prev = list_prev(buflist, df);
55353a737e0dSbrendan 		ASSERT(df->l2df_data != NULL);
55363a737e0dSbrendan 		ASSERT(df->l2df_func != NULL);
55373a737e0dSbrendan 		df->l2df_func(df->l2df_data, df->l2df_size);
55383a737e0dSbrendan 		list_remove(buflist, df);
55393a737e0dSbrendan 		kmem_free(df, sizeof (l2arc_data_free_t));
55403a737e0dSbrendan 	}
55413a737e0dSbrendan 
55423a737e0dSbrendan 	mutex_exit(&l2arc_free_on_write_mtx);
55433a737e0dSbrendan }
55443a737e0dSbrendan 
55453a737e0dSbrendan /*
5546fa94a07fSbrendan  * A write to a cache device has completed.  Update all headers to allow
5547fa94a07fSbrendan  * reads from these buffers to begin.
5548fa94a07fSbrendan  */
5549fa94a07fSbrendan static void
5550fa94a07fSbrendan l2arc_write_done(zio_t *zio)
5551fa94a07fSbrendan {
5552fa94a07fSbrendan 	l2arc_write_callback_t *cb;
5553fa94a07fSbrendan 	l2arc_dev_t *dev;
5554fa94a07fSbrendan 	list_t *buflist;
55557adb730bSGeorge Wilson 	arc_buf_hdr_t *head, *hdr, *hdr_prev;
5556fa94a07fSbrendan 	kmutex_t *hash_lock;
55573038a2b4SSaso Kiselkov 	int64_t bytes_dropped = 0;
5558fa94a07fSbrendan 
5559fa94a07fSbrendan 	cb = zio->io_private;
5560fa94a07fSbrendan 	ASSERT(cb != NULL);
5561fa94a07fSbrendan 	dev = cb->l2wcb_dev;
5562fa94a07fSbrendan 	ASSERT(dev != NULL);
5563fa94a07fSbrendan 	head = cb->l2wcb_head;
5564fa94a07fSbrendan 	ASSERT(head != NULL);
556589c86e32SChris Williamson 	buflist = &dev->l2ad_buflist;
5566fa94a07fSbrendan 	ASSERT(buflist != NULL);
5567fa94a07fSbrendan 	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
5568fa94a07fSbrendan 	    l2arc_write_callback_t *, cb);
5569fa94a07fSbrendan 
5570fa94a07fSbrendan 	if (zio->io_error != 0)
5571fa94a07fSbrendan 		ARCSTAT_BUMP(arcstat_l2_writes_error);
5572fa94a07fSbrendan 
5573fa94a07fSbrendan 	/*
5574fa94a07fSbrendan 	 * All writes completed, or an error was hit.
5575fa94a07fSbrendan 	 */
5576244781f1SPrakash Surya top:
5577244781f1SPrakash Surya 	mutex_enter(&dev->l2ad_mtx);
55787adb730bSGeorge Wilson 	for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
55797adb730bSGeorge Wilson 		hdr_prev = list_prev(buflist, hdr);
5580fa94a07fSbrendan 
55817adb730bSGeorge Wilson 		hash_lock = HDR_LOCK(hdr);
5582244781f1SPrakash Surya 
5583244781f1SPrakash Surya 		/*
5584244781f1SPrakash Surya 		 * We cannot use mutex_enter or else we can deadlock
5585244781f1SPrakash Surya 		 * with l2arc_write_buffers (due to swapping the order
5586244781f1SPrakash Surya 		 * the hash lock and l2ad_mtx are taken).
5587244781f1SPrakash Surya 		 */
5588fa94a07fSbrendan 		if (!mutex_tryenter(hash_lock)) {
5589fa94a07fSbrendan 			/*
5590244781f1SPrakash Surya 			 * Missed the hash lock. We must retry so we
5591244781f1SPrakash Surya 			 * don't leave the ARC_FLAG_L2_WRITING bit set.
5592fa94a07fSbrendan 			 */
5593244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
5594244781f1SPrakash Surya 
5595244781f1SPrakash Surya 			/*
5596244781f1SPrakash Surya 			 * We don't want to rescan the headers we've
5597244781f1SPrakash Surya 			 * already marked as having been written out, so
5598244781f1SPrakash Surya 			 * we reinsert the head node so we can pick up
5599244781f1SPrakash Surya 			 * where we left off.
5600244781f1SPrakash Surya 			 */
5601244781f1SPrakash Surya 			list_remove(buflist, head);
5602244781f1SPrakash Surya 			list_insert_after(buflist, hdr, head);
5603244781f1SPrakash Surya 
5604244781f1SPrakash Surya 			mutex_exit(&dev->l2ad_mtx);
5605244781f1SPrakash Surya 
5606244781f1SPrakash Surya 			/*
5607244781f1SPrakash Surya 			 * We wait for the hash lock to become available
5608244781f1SPrakash Surya 			 * to try and prevent busy waiting, and increase
5609244781f1SPrakash Surya 			 * the chance we'll be able to acquire the lock
5610244781f1SPrakash Surya 			 * the next time around.
5611244781f1SPrakash Surya 			 */
5612244781f1SPrakash Surya 			mutex_enter(hash_lock);
5613244781f1SPrakash Surya 			mutex_exit(hash_lock);
5614244781f1SPrakash Surya 			goto top;
5615fa94a07fSbrendan 		}
5616fa94a07fSbrendan 
561789c86e32SChris Williamson 		/*
5618244781f1SPrakash Surya 		 * We could not have been moved into the arc_l2c_only
5619244781f1SPrakash Surya 		 * state while in-flight due to our ARC_FLAG_L2_WRITING
5620244781f1SPrakash Surya 		 * bit being set. Let's just ensure that's being enforced.
562189c86e32SChris Williamson 		 */
5622244781f1SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(hdr));
5623244781f1SPrakash Surya 
5624244781f1SPrakash Surya 		/*
5625244781f1SPrakash Surya 		 * We may have allocated a buffer for L2ARC compression,
5626244781f1SPrakash Surya 		 * we must release it to avoid leaking this data.
5627244781f1SPrakash Surya 		 */
562889c86e32SChris Williamson 		l2arc_release_cdata_buf(hdr);
562989c86e32SChris Williamson 
5630fa94a07fSbrendan 		if (zio->io_error != 0) {
5631fa94a07fSbrendan 			/*
56323a737e0dSbrendan 			 * Error - drop L2ARC entry.
5633fa94a07fSbrendan 			 */
56347adb730bSGeorge Wilson 			list_remove(buflist, hdr);
563589c86e32SChris Williamson 			hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
563689c86e32SChris Williamson 
563789c86e32SChris Williamson 			ARCSTAT_INCR(arcstat_l2_asize, -hdr->b_l2hdr.b_asize);
56387adb730bSGeorge Wilson 			ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
5639a52fc310SPrakash Surya 
5640a52fc310SPrakash Surya 			bytes_dropped += hdr->b_l2hdr.b_asize;
5641a52fc310SPrakash Surya 			(void) refcount_remove_many(&dev->l2ad_alloc,
5642a52fc310SPrakash Surya 			    hdr->b_l2hdr.b_asize, hdr);
5643fa94a07fSbrendan 		}
5644fa94a07fSbrendan 
5645fa94a07fSbrendan 		/*
5646244781f1SPrakash Surya 		 * Allow ARC to begin reads and ghost list evictions to
5647244781f1SPrakash Surya 		 * this L2ARC entry.
5648fa94a07fSbrendan 		 */
56497adb730bSGeorge Wilson 		hdr->b_flags &= ~ARC_FLAG_L2_WRITING;
5650fa94a07fSbrendan 
5651fa94a07fSbrendan 		mutex_exit(hash_lock);
5652fa94a07fSbrendan 	}
5653fa94a07fSbrendan 
5654fa94a07fSbrendan 	atomic_inc_64(&l2arc_writes_done);
5655fa94a07fSbrendan 	list_remove(buflist, head);
565689c86e32SChris Williamson 	ASSERT(!HDR_HAS_L1HDR(head));
565789c86e32SChris Williamson 	kmem_cache_free(hdr_l2only_cache, head);
565889c86e32SChris Williamson 	mutex_exit(&dev->l2ad_mtx);
5659fa94a07fSbrendan 
56603038a2b4SSaso Kiselkov 	vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
56613038a2b4SSaso Kiselkov 
56623a737e0dSbrendan 	l2arc_do_free_on_write();
5663fa94a07fSbrendan 
5664fa94a07fSbrendan 	kmem_free(cb, sizeof (l2arc_write_callback_t));
5665fa94a07fSbrendan }
5666fa94a07fSbrendan 
5667fa94a07fSbrendan /*
5668fa94a07fSbrendan  * A read to a cache device completed.  Validate buffer contents before
5669fa94a07fSbrendan  * handing over to the regular ARC routines.
5670fa94a07fSbrendan  */
5671fa94a07fSbrendan static void
5672fa94a07fSbrendan l2arc_read_done(zio_t *zio)
5673fa94a07fSbrendan {
5674fa94a07fSbrendan 	l2arc_read_callback_t *cb;
5675fa94a07fSbrendan 	arc_buf_hdr_t *hdr;
5676fa94a07fSbrendan 	arc_buf_t *buf;
5677fa94a07fSbrendan 	kmutex_t *hash_lock;
56783a737e0dSbrendan 	int equal;
5679fa94a07fSbrendan 
5680e14bb325SJeff Bonwick 	ASSERT(zio->io_vd != NULL);
5681e14bb325SJeff Bonwick 	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
5682e14bb325SJeff Bonwick 
5683e14bb325SJeff Bonwick 	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
5684e14bb325SJeff Bonwick 
5685fa94a07fSbrendan 	cb = zio->io_private;
5686fa94a07fSbrendan 	ASSERT(cb != NULL);
5687fa94a07fSbrendan 	buf = cb->l2rcb_buf;
5688fa94a07fSbrendan 	ASSERT(buf != NULL);
5689fa94a07fSbrendan 
56903f9d6ad7SLin Ling 	hash_lock = HDR_LOCK(buf->b_hdr);
5691fa94a07fSbrendan 	mutex_enter(hash_lock);
56923f9d6ad7SLin Ling 	hdr = buf->b_hdr;
56933f9d6ad7SLin Ling 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
5694fa94a07fSbrendan 
5695fa94a07fSbrendan 	/*
5696aad02571SSaso Kiselkov 	 * If the buffer was compressed, decompress it first.
5697aad02571SSaso Kiselkov 	 */
5698aad02571SSaso Kiselkov 	if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
5699aad02571SSaso Kiselkov 		l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
5700aad02571SSaso Kiselkov 	ASSERT(zio->io_data != NULL);
5701d4cd038cSArne Jansen 	ASSERT3U(zio->io_size, ==, hdr->b_size);
5702d4cd038cSArne Jansen 	ASSERT3U(BP_GET_LSIZE(&cb->l2rcb_bp), ==, hdr->b_size);
5703aad02571SSaso Kiselkov 
5704aad02571SSaso Kiselkov 	/*
5705fa94a07fSbrendan 	 * Check this survived the L2ARC journey.
5706fa94a07fSbrendan 	 */
5707fa94a07fSbrendan 	equal = arc_cksum_equal(buf);
5708fa94a07fSbrendan 	if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
5709fa94a07fSbrendan 		mutex_exit(hash_lock);
5710fa94a07fSbrendan 		zio->io_private = buf;
5711e14bb325SJeff Bonwick 		zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
5712e14bb325SJeff Bonwick 		zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
5713fa94a07fSbrendan 		arc_read_done(zio);
5714fa94a07fSbrendan 	} else {
5715fa94a07fSbrendan 		mutex_exit(hash_lock);
5716fa94a07fSbrendan 		/*
5717fa94a07fSbrendan 		 * Buffer didn't survive caching.  Increment stats and
5718fa94a07fSbrendan 		 * reissue to the original storage device.
5719fa94a07fSbrendan 		 */
57203a737e0dSbrendan 		if (zio->io_error != 0) {
5721fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_io_error);
57223a737e0dSbrendan 		} else {
5723be6fd75aSMatthew Ahrens 			zio->io_error = SET_ERROR(EIO);
57243a737e0dSbrendan 		}
5725fa94a07fSbrendan 		if (!equal)
5726fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
5727fa94a07fSbrendan 
57283a737e0dSbrendan 		/*
5729e14bb325SJeff Bonwick 		 * If there's no waiter, issue an async i/o to the primary
5730e14bb325SJeff Bonwick 		 * storage now.  If there *is* a waiter, the caller must
5731e14bb325SJeff Bonwick 		 * issue the i/o in a context where it's OK to block.
57323a737e0dSbrendan 		 */
5733a3f829aeSBill Moore 		if (zio->io_waiter == NULL) {
5734a3f829aeSBill Moore 			zio_t *pio = zio_unique_parent(zio);
5735a3f829aeSBill Moore 
5736a3f829aeSBill Moore 			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
5737a3f829aeSBill Moore 
5738a3f829aeSBill Moore 			zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
5739d4cd038cSArne Jansen 			    buf->b_data, hdr->b_size, arc_read_done, buf,
5740e14bb325SJeff Bonwick 			    zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
5741fa94a07fSbrendan 		}
5742a3f829aeSBill Moore 	}
5743fa94a07fSbrendan 
5744fa94a07fSbrendan 	kmem_free(cb, sizeof (l2arc_read_callback_t));
5745fa94a07fSbrendan }
5746fa94a07fSbrendan 
5747fa94a07fSbrendan /*
5748fa94a07fSbrendan  * This is the list priority from which the L2ARC will search for pages to
5749fa94a07fSbrendan  * cache.  This is used within loops (0..3) to cycle through lists in the
5750fa94a07fSbrendan  * desired order.  This order can have a significant effect on cache
5751fa94a07fSbrendan  * performance.
5752fa94a07fSbrendan  *
5753fa94a07fSbrendan  * Currently the metadata lists are hit first, MFU then MRU, followed by
5754fa94a07fSbrendan  * the data lists.  This function returns a locked list, and also returns
5755fa94a07fSbrendan  * the lock pointer.
5756fa94a07fSbrendan  */
5757244781f1SPrakash Surya static multilist_sublist_t *
5758244781f1SPrakash Surya l2arc_sublist_lock(int list_num)
5759fa94a07fSbrendan {
5760244781f1SPrakash Surya 	multilist_t *ml = NULL;
5761244781f1SPrakash Surya 	unsigned int idx;
5762fa94a07fSbrendan 
5763fa94a07fSbrendan 	ASSERT(list_num >= 0 && list_num <= 3);
5764fa94a07fSbrendan 
5765fa94a07fSbrendan 	switch (list_num) {
5766fa94a07fSbrendan 	case 0:
5767244781f1SPrakash Surya 		ml = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
5768fa94a07fSbrendan 		break;
5769fa94a07fSbrendan 	case 1:
5770244781f1SPrakash Surya 		ml = &arc_mru->arcs_list[ARC_BUFC_METADATA];
5771fa94a07fSbrendan 		break;
5772fa94a07fSbrendan 	case 2:
5773244781f1SPrakash Surya 		ml = &arc_mfu->arcs_list[ARC_BUFC_DATA];
5774fa94a07fSbrendan 		break;
5775fa94a07fSbrendan 	case 3:
5776244781f1SPrakash Surya 		ml = &arc_mru->arcs_list[ARC_BUFC_DATA];
5777fa94a07fSbrendan 		break;
5778fa94a07fSbrendan 	}
5779fa94a07fSbrendan 
5780244781f1SPrakash Surya 	/*
5781244781f1SPrakash Surya 	 * Return a randomly-selected sublist. This is acceptable
5782244781f1SPrakash Surya 	 * because the caller feeds only a little bit of data for each
5783244781f1SPrakash Surya 	 * call (8MB). Subsequent calls will result in different
5784244781f1SPrakash Surya 	 * sublists being selected.
5785244781f1SPrakash Surya 	 */
5786244781f1SPrakash Surya 	idx = multilist_get_random_index(ml);
5787244781f1SPrakash Surya 	return (multilist_sublist_lock(ml, idx));
5788fa94a07fSbrendan }
5789fa94a07fSbrendan 
5790fa94a07fSbrendan /*
5791fa94a07fSbrendan  * Evict buffers from the device write hand to the distance specified in
5792fa94a07fSbrendan  * bytes.  This distance may span populated buffers, it may span nothing.
5793fa94a07fSbrendan  * This is clearing a region on the L2ARC device ready for writing.
5794fa94a07fSbrendan  * If the 'all' boolean is set, every buffer is evicted.
5795fa94a07fSbrendan  */
5796fa94a07fSbrendan static void
5797fa94a07fSbrendan l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
5798fa94a07fSbrendan {
5799fa94a07fSbrendan 	list_t *buflist;
58007adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr, *hdr_prev;
5801fa94a07fSbrendan 	kmutex_t *hash_lock;
5802fa94a07fSbrendan 	uint64_t taddr;
5803fa94a07fSbrendan 
580489c86e32SChris Williamson 	buflist = &dev->l2ad_buflist;
5805fa94a07fSbrendan 
5806fa94a07fSbrendan 	if (!all && dev->l2ad_first) {
5807fa94a07fSbrendan 		/*
5808fa94a07fSbrendan 		 * This is the first sweep through the device.  There is
5809fa94a07fSbrendan 		 * nothing to evict.
5810fa94a07fSbrendan 		 */
5811fa94a07fSbrendan 		return;
5812fa94a07fSbrendan 	}
5813fa94a07fSbrendan 
58143a737e0dSbrendan 	if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
5815fa94a07fSbrendan 		/*
5816fa94a07fSbrendan 		 * When nearing the end of the device, evict to the end
5817fa94a07fSbrendan 		 * before the device write hand jumps to the start.
5818fa94a07fSbrendan 		 */
5819fa94a07fSbrendan 		taddr = dev->l2ad_end;
5820fa94a07fSbrendan 	} else {
5821fa94a07fSbrendan 		taddr = dev->l2ad_hand + distance;
5822fa94a07fSbrendan 	}
5823fa94a07fSbrendan 	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
5824fa94a07fSbrendan 	    uint64_t, taddr, boolean_t, all);
5825fa94a07fSbrendan 
5826fa94a07fSbrendan top:
582789c86e32SChris Williamson 	mutex_enter(&dev->l2ad_mtx);
58287adb730bSGeorge Wilson 	for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
58297adb730bSGeorge Wilson 		hdr_prev = list_prev(buflist, hdr);
5830fa94a07fSbrendan 
58317adb730bSGeorge Wilson 		hash_lock = HDR_LOCK(hdr);
5832244781f1SPrakash Surya 
5833244781f1SPrakash Surya 		/*
5834244781f1SPrakash Surya 		 * We cannot use mutex_enter or else we can deadlock
5835244781f1SPrakash Surya 		 * with l2arc_write_buffers (due to swapping the order
5836244781f1SPrakash Surya 		 * the hash lock and l2ad_mtx are taken).
5837244781f1SPrakash Surya 		 */
5838fa94a07fSbrendan 		if (!mutex_tryenter(hash_lock)) {
5839fa94a07fSbrendan 			/*
5840fa94a07fSbrendan 			 * Missed the hash lock.  Retry.
5841fa94a07fSbrendan 			 */
5842fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
584389c86e32SChris Williamson 			mutex_exit(&dev->l2ad_mtx);
5844fa94a07fSbrendan 			mutex_enter(hash_lock);
5845fa94a07fSbrendan 			mutex_exit(hash_lock);
5846fa94a07fSbrendan 			goto top;
5847fa94a07fSbrendan 		}
5848fa94a07fSbrendan 
58497adb730bSGeorge Wilson 		if (HDR_L2_WRITE_HEAD(hdr)) {
5850fa94a07fSbrendan 			/*
5851fa94a07fSbrendan 			 * We hit a write head node.  Leave it for
5852fa94a07fSbrendan 			 * l2arc_write_done().
5853fa94a07fSbrendan 			 */
58547adb730bSGeorge Wilson 			list_remove(buflist, hdr);
5855fa94a07fSbrendan 			mutex_exit(hash_lock);
5856fa94a07fSbrendan 			continue;
5857fa94a07fSbrendan 		}
5858fa94a07fSbrendan 
585989c86e32SChris Williamson 		if (!all && HDR_HAS_L2HDR(hdr) &&
586089c86e32SChris Williamson 		    (hdr->b_l2hdr.b_daddr > taddr ||
586189c86e32SChris Williamson 		    hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
5862fa94a07fSbrendan 			/*
5863fa94a07fSbrendan 			 * We've evicted to the target address,
5864fa94a07fSbrendan 			 * or the end of the device.
5865fa94a07fSbrendan 			 */
5866fa94a07fSbrendan 			mutex_exit(hash_lock);
5867fa94a07fSbrendan 			break;
5868fa94a07fSbrendan 		}
5869fa94a07fSbrendan 
587089c86e32SChris Williamson 		ASSERT(HDR_HAS_L2HDR(hdr));
587189c86e32SChris Williamson 		if (!HDR_HAS_L1HDR(hdr)) {
58727adb730bSGeorge Wilson 			ASSERT(!HDR_L2_READING(hdr));
5873fa94a07fSbrendan 			/*
5874fa94a07fSbrendan 			 * This doesn't exist in the ARC.  Destroy.
5875fa94a07fSbrendan 			 * arc_hdr_destroy() will call list_remove()
5876fa94a07fSbrendan 			 * and decrement arcstat_l2_size.
5877fa94a07fSbrendan 			 */
58787adb730bSGeorge Wilson 			arc_change_state(arc_anon, hdr, hash_lock);
58797adb730bSGeorge Wilson 			arc_hdr_destroy(hdr);
5880fa94a07fSbrendan 		} else {
588189c86e32SChris Williamson 			ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
588289c86e32SChris Williamson 			ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
5883fa94a07fSbrendan 			/*
58843a737e0dSbrendan 			 * Invalidate issued or about to be issued
58853a737e0dSbrendan 			 * reads, since we may be about to write
58863a737e0dSbrendan 			 * over this location.
58873a737e0dSbrendan 			 */
58887adb730bSGeorge Wilson 			if (HDR_L2_READING(hdr)) {
58893a737e0dSbrendan 				ARCSTAT_BUMP(arcstat_l2_evict_reading);
58907adb730bSGeorge Wilson 				hdr->b_flags |= ARC_FLAG_L2_EVICTED;
58913a737e0dSbrendan 			}
58923a737e0dSbrendan 
5893244781f1SPrakash Surya 			/* Ensure this header has finished being written */
5894244781f1SPrakash Surya 			ASSERT(!HDR_L2_WRITING(hdr));
5895244781f1SPrakash Surya 			ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
5896a52fc310SPrakash Surya 
5897a52fc310SPrakash Surya 			arc_hdr_l2hdr_destroy(hdr);
5898fa94a07fSbrendan 		}
5899fa94a07fSbrendan 		mutex_exit(hash_lock);
5900fa94a07fSbrendan 	}
590189c86e32SChris Williamson 	mutex_exit(&dev->l2ad_mtx);
5902fa94a07fSbrendan }
5903fa94a07fSbrendan 
5904fa94a07fSbrendan /*
5905fa94a07fSbrendan  * Find and write ARC buffers to the L2ARC device.
5906fa94a07fSbrendan  *
59077adb730bSGeorge Wilson  * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
5908fa94a07fSbrendan  * for reading until they have completed writing.
5909aad02571SSaso Kiselkov  * The headroom_boost is an in-out parameter used to maintain headroom boost
5910aad02571SSaso Kiselkov  * state between calls to this function.
5911aad02571SSaso Kiselkov  *
5912aad02571SSaso Kiselkov  * Returns the number of bytes actually written (which may be smaller than
5913aad02571SSaso Kiselkov  * the delta by which the device hand has changed due to alignment).
5914fa94a07fSbrendan  */
59155a98e54bSBrendan Gregg - Sun Microsystems static uint64_t
5916aad02571SSaso Kiselkov l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
5917aad02571SSaso Kiselkov     boolean_t *headroom_boost)
5918fa94a07fSbrendan {
59197adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr, *hdr_prev, *head;
5920d7d9a6d9SAndriy Gapon 	uint64_t write_asize, write_sz, headroom,
5921aad02571SSaso Kiselkov 	    buf_compress_minsz;
5922fa94a07fSbrendan 	void *buf_data;
5923aad02571SSaso Kiselkov 	boolean_t full;
5924fa94a07fSbrendan 	l2arc_write_callback_t *cb;
5925fa94a07fSbrendan 	zio_t *pio, *wzio;
5926e9103aaeSGarrett D'Amore 	uint64_t guid = spa_load_guid(spa);
5927f5ca7025SSaso Kiselkov 	uint64_t sync_txg = spa_syncing_txg(spa);
5928aad02571SSaso Kiselkov 	const boolean_t do_headroom_boost = *headroom_boost;
5929fa94a07fSbrendan 
5930fa94a07fSbrendan 	ASSERT(dev->l2ad_vdev != NULL);
5931fa94a07fSbrendan 
5932aad02571SSaso Kiselkov 	/* Lower the flag now, we might want to raise it again later. */
5933aad02571SSaso Kiselkov 	*headroom_boost = B_FALSE;
5934aad02571SSaso Kiselkov 
5935fa94a07fSbrendan 	pio = NULL;
5936d7d9a6d9SAndriy Gapon 	write_sz = write_asize = 0;
5937fa94a07fSbrendan 	full = B_FALSE;
593889c86e32SChris Williamson 	head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
59397adb730bSGeorge Wilson 	head->b_flags |= ARC_FLAG_L2_WRITE_HEAD;
594089c86e32SChris Williamson 	head->b_flags |= ARC_FLAG_HAS_L2HDR;
5941fa94a07fSbrendan 
5942fa94a07fSbrendan 	/*
5943aad02571SSaso Kiselkov 	 * We will want to try to compress buffers that are at least 2x the
5944aad02571SSaso Kiselkov 	 * device sector size.
5945aad02571SSaso Kiselkov 	 */
5946aad02571SSaso Kiselkov 	buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
5947aad02571SSaso Kiselkov 
5948aad02571SSaso Kiselkov 	/*
5949fa94a07fSbrendan 	 * Copy buffers for L2ARC writing.
5950fa94a07fSbrendan 	 */
5951fa94a07fSbrendan 	for (int try = 0; try <= 3; try++) {
5952244781f1SPrakash Surya 		multilist_sublist_t *mls = l2arc_sublist_lock(try);
5953aad02571SSaso Kiselkov 		uint64_t passed_sz = 0;
5954aad02571SSaso Kiselkov 
59553a737e0dSbrendan 		/*
59563a737e0dSbrendan 		 * L2ARC fast warmup.
59573a737e0dSbrendan 		 *
59583a737e0dSbrendan 		 * Until the ARC is warm and starts to evict, read from the
59593a737e0dSbrendan 		 * head of the ARC lists rather than the tail.
59603a737e0dSbrendan 		 */
59613a737e0dSbrendan 		if (arc_warm == B_FALSE)
5962244781f1SPrakash Surya 			hdr = multilist_sublist_head(mls);
59633a737e0dSbrendan 		else
5964244781f1SPrakash Surya 			hdr = multilist_sublist_tail(mls);
59653a737e0dSbrendan 
5966aad02571SSaso Kiselkov 		headroom = target_sz * l2arc_headroom;
5967aad02571SSaso Kiselkov 		if (do_headroom_boost)
5968aad02571SSaso Kiselkov 			headroom = (headroom * l2arc_headroom_boost) / 100;
5969aad02571SSaso Kiselkov 
59707adb730bSGeorge Wilson 		for (; hdr; hdr = hdr_prev) {
5971aad02571SSaso Kiselkov 			kmutex_t *hash_lock;
5972aad02571SSaso Kiselkov 			uint64_t buf_sz;
5973d7d9a6d9SAndriy Gapon 			uint64_t buf_a_sz;
5974aad02571SSaso Kiselkov 
59753a737e0dSbrendan 			if (arc_warm == B_FALSE)
5976244781f1SPrakash Surya 				hdr_prev = multilist_sublist_next(mls, hdr);
59773a737e0dSbrendan 			else
5978244781f1SPrakash Surya 				hdr_prev = multilist_sublist_prev(mls, hdr);
5979fa94a07fSbrendan 
59807adb730bSGeorge Wilson 			hash_lock = HDR_LOCK(hdr);
5981aad02571SSaso Kiselkov 			if (!mutex_tryenter(hash_lock)) {
5982fa94a07fSbrendan 				/*
5983fa94a07fSbrendan 				 * Skip this buffer rather than waiting.
5984fa94a07fSbrendan 				 */
5985fa94a07fSbrendan 				continue;
5986fa94a07fSbrendan 			}
5987fa94a07fSbrendan 
59887adb730bSGeorge Wilson 			passed_sz += hdr->b_size;
5989fa94a07fSbrendan 			if (passed_sz > headroom) {
5990fa94a07fSbrendan 				/*
5991fa94a07fSbrendan 				 * Searched too far.
5992fa94a07fSbrendan 				 */
5993fa94a07fSbrendan 				mutex_exit(hash_lock);
5994fa94a07fSbrendan 				break;
5995fa94a07fSbrendan 			}
5996fa94a07fSbrendan 
5997f5ca7025SSaso Kiselkov 			if (!l2arc_write_eligible(guid, sync_txg, hdr)) {
5998fa94a07fSbrendan 				mutex_exit(hash_lock);
5999fa94a07fSbrendan 				continue;
6000fa94a07fSbrendan 			}
6001fa94a07fSbrendan 
6002d7d9a6d9SAndriy Gapon 			/*
6003d7d9a6d9SAndriy Gapon 			 * Assume that the buffer is not going to be compressed
6004d7d9a6d9SAndriy Gapon 			 * and could take more space on disk because of a larger
6005d7d9a6d9SAndriy Gapon 			 * disk block size.
6006d7d9a6d9SAndriy Gapon 			 */
6007d7d9a6d9SAndriy Gapon 			buf_sz = hdr->b_size;
6008d7d9a6d9SAndriy Gapon 			buf_a_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
6009d7d9a6d9SAndriy Gapon 
6010d7d9a6d9SAndriy Gapon 			if ((write_asize + buf_a_sz) > target_sz) {
6011fa94a07fSbrendan 				full = B_TRUE;
6012fa94a07fSbrendan 				mutex_exit(hash_lock);
6013fa94a07fSbrendan 				break;
6014fa94a07fSbrendan 			}
6015fa94a07fSbrendan 
6016fa94a07fSbrendan 			if (pio == NULL) {
6017fa94a07fSbrendan 				/*
6018fa94a07fSbrendan 				 * Insert a dummy header on the buflist so
6019fa94a07fSbrendan 				 * l2arc_write_done() can find where the
6020fa94a07fSbrendan 				 * write buffers begin without searching.
6021fa94a07fSbrendan 				 */
6022244781f1SPrakash Surya 				mutex_enter(&dev->l2ad_mtx);
602389c86e32SChris Williamson 				list_insert_head(&dev->l2ad_buflist, head);
6024244781f1SPrakash Surya 				mutex_exit(&dev->l2ad_mtx);
6025fa94a07fSbrendan 
6026*5f992543SArne Jansen 				cb = kmem_alloc(
6027fa94a07fSbrendan 				    sizeof (l2arc_write_callback_t), KM_SLEEP);
6028fa94a07fSbrendan 				cb->l2wcb_dev = dev;
6029fa94a07fSbrendan 				cb->l2wcb_head = head;
6030fa94a07fSbrendan 				pio = zio_root(spa, l2arc_write_done, cb,
6031fa94a07fSbrendan 				    ZIO_FLAG_CANFAIL);
6032fa94a07fSbrendan 			}
6033fa94a07fSbrendan 
6034fa94a07fSbrendan 			/*
6035fa94a07fSbrendan 			 * Create and add a new L2ARC header.
6036fa94a07fSbrendan 			 */
603789c86e32SChris Williamson 			hdr->b_l2hdr.b_dev = dev;
60387adb730bSGeorge Wilson 			hdr->b_flags |= ARC_FLAG_L2_WRITING;
6039aad02571SSaso Kiselkov 			/*
6040aad02571SSaso Kiselkov 			 * Temporarily stash the data buffer in b_tmp_cdata.
6041aad02571SSaso Kiselkov 			 * The subsequent write step will pick it up from
604289c86e32SChris Williamson 			 * there. This is because can't access b_l1hdr.b_buf
6043aad02571SSaso Kiselkov 			 * without holding the hash_lock, which we in turn
6044aad02571SSaso Kiselkov 			 * can't access without holding the ARC list locks
6045aad02571SSaso Kiselkov 			 * (which we want to avoid during compression/writing).
6046aad02571SSaso Kiselkov 			 */
6047d4cd038cSArne Jansen 			hdr->b_l2hdr.b_compress = ZIO_COMPRESS_OFF;
604889c86e32SChris Williamson 			hdr->b_l2hdr.b_asize = hdr->b_size;
604989c86e32SChris Williamson 			hdr->b_l1hdr.b_tmp_cdata = hdr->b_l1hdr.b_buf->b_data;
6050aad02571SSaso Kiselkov 
6051a52fc310SPrakash Surya 			/*
6052a52fc310SPrakash Surya 			 * Explicitly set the b_daddr field to a known
6053a52fc310SPrakash Surya 			 * value which means "invalid address". This
6054a52fc310SPrakash Surya 			 * enables us to differentiate which stage of
6055a52fc310SPrakash Surya 			 * l2arc_write_buffers() the particular header
6056a52fc310SPrakash Surya 			 * is in (e.g. this loop, or the one below).
6057a52fc310SPrakash Surya 			 * ARC_FLAG_L2_WRITING is not enough to make
6058a52fc310SPrakash Surya 			 * this distinction, and we need to know in
6059a52fc310SPrakash Surya 			 * order to do proper l2arc vdev accounting in
6060a52fc310SPrakash Surya 			 * arc_release() and arc_hdr_destroy().
6061a52fc310SPrakash Surya 			 *
6062a52fc310SPrakash Surya 			 * Note, we can't use a new flag to distinguish
6063a52fc310SPrakash Surya 			 * the two stages because we don't hold the
6064a52fc310SPrakash Surya 			 * header's hash_lock below, in the second stage
6065a52fc310SPrakash Surya 			 * of this function. Thus, we can't simply
6066a52fc310SPrakash Surya 			 * change the b_flags field to denote that the
6067a52fc310SPrakash Surya 			 * IO has been sent. We can change the b_daddr
6068a52fc310SPrakash Surya 			 * field of the L2 portion, though, since we'll
6069a52fc310SPrakash Surya 			 * be holding the l2ad_mtx; which is why we're
6070a52fc310SPrakash Surya 			 * using it to denote the header's state change.
6071a52fc310SPrakash Surya 			 */
6072a52fc310SPrakash Surya 			hdr->b_l2hdr.b_daddr = L2ARC_ADDR_UNSET;
6073a52fc310SPrakash Surya 
607489c86e32SChris Williamson 			hdr->b_flags |= ARC_FLAG_HAS_L2HDR;
6075aad02571SSaso Kiselkov 
6076244781f1SPrakash Surya 			mutex_enter(&dev->l2ad_mtx);
607789c86e32SChris Williamson 			list_insert_head(&dev->l2ad_buflist, hdr);
6078244781f1SPrakash Surya 			mutex_exit(&dev->l2ad_mtx);
6079fa94a07fSbrendan 
6080fa94a07fSbrendan 			/*
6081fa94a07fSbrendan 			 * Compute and store the buffer cksum before
6082fa94a07fSbrendan 			 * writing.  On debug the cksum is verified first.
6083fa94a07fSbrendan 			 */
608489c86e32SChris Williamson 			arc_cksum_verify(hdr->b_l1hdr.b_buf);
608589c86e32SChris Williamson 			arc_cksum_compute(hdr->b_l1hdr.b_buf, B_TRUE);
6086fa94a07fSbrendan 
6087fa94a07fSbrendan 			mutex_exit(hash_lock);
6088fa94a07fSbrendan 
6089aad02571SSaso Kiselkov 			write_sz += buf_sz;
6090d7d9a6d9SAndriy Gapon 			write_asize += buf_a_sz;
6091aad02571SSaso Kiselkov 		}
6092aad02571SSaso Kiselkov 
6093244781f1SPrakash Surya 		multilist_sublist_unlock(mls);
6094aad02571SSaso Kiselkov 
6095aad02571SSaso Kiselkov 		if (full == B_TRUE)
6096aad02571SSaso Kiselkov 			break;
6097aad02571SSaso Kiselkov 	}
6098aad02571SSaso Kiselkov 
6099aad02571SSaso Kiselkov 	/* No buffers selected for writing? */
6100aad02571SSaso Kiselkov 	if (pio == NULL) {
6101aad02571SSaso Kiselkov 		ASSERT0(write_sz);
610289c86e32SChris Williamson 		ASSERT(!HDR_HAS_L1HDR(head));
610389c86e32SChris Williamson 		kmem_cache_free(hdr_l2only_cache, head);
6104aad02571SSaso Kiselkov 		return (0);
6105aad02571SSaso Kiselkov 	}
6106aad02571SSaso Kiselkov 
6107244781f1SPrakash Surya 	mutex_enter(&dev->l2ad_mtx);
6108244781f1SPrakash Surya 
6109aad02571SSaso Kiselkov 	/*
6110d7d9a6d9SAndriy Gapon 	 * Note that elsewhere in this file arcstat_l2_asize
6111d7d9a6d9SAndriy Gapon 	 * and the used space on l2ad_vdev are updated using b_asize,
6112d7d9a6d9SAndriy Gapon 	 * which is not necessarily rounded up to the device block size.
6113d7d9a6d9SAndriy Gapon 	 * Too keep accounting consistent we do the same here as well:
6114d7d9a6d9SAndriy Gapon 	 * stats_size accumulates the sum of b_asize of the written buffers,
6115d7d9a6d9SAndriy Gapon 	 * while write_asize accumulates the sum of b_asize rounded up
6116d7d9a6d9SAndriy Gapon 	 * to the device block size.
6117d7d9a6d9SAndriy Gapon 	 * The latter sum is used only to validate the corectness of the code.
6118d7d9a6d9SAndriy Gapon 	 */
6119d7d9a6d9SAndriy Gapon 	uint64_t stats_size = 0;
6120d7d9a6d9SAndriy Gapon 	write_asize = 0;
6121d7d9a6d9SAndriy Gapon 
6122d7d9a6d9SAndriy Gapon 	/*
6123aad02571SSaso Kiselkov 	 * Now start writing the buffers. We're starting at the write head
6124aad02571SSaso Kiselkov 	 * and work backwards, retracing the course of the buffer selector
6125aad02571SSaso Kiselkov 	 * loop above.
6126aad02571SSaso Kiselkov 	 */
612789c86e32SChris Williamson 	for (hdr = list_prev(&dev->l2ad_buflist, head); hdr;
612889c86e32SChris Williamson 	    hdr = list_prev(&dev->l2ad_buflist, hdr)) {
6129aad02571SSaso Kiselkov 		uint64_t buf_sz;
6130aad02571SSaso Kiselkov 
6131aad02571SSaso Kiselkov 		/*
6132244781f1SPrakash Surya 		 * We rely on the L1 portion of the header below, so
6133244781f1SPrakash Surya 		 * it's invalid for this header to have been evicted out
6134244781f1SPrakash Surya 		 * of the ghost cache, prior to being written out. The
6135244781f1SPrakash Surya 		 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
6136244781f1SPrakash Surya 		 */
6137244781f1SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(hdr));
6138244781f1SPrakash Surya 
6139244781f1SPrakash Surya 		/*
6140aad02571SSaso Kiselkov 		 * We shouldn't need to lock the buffer here, since we flagged
61417adb730bSGeorge Wilson 		 * it as ARC_FLAG_L2_WRITING in the previous step, but we must
61427adb730bSGeorge Wilson 		 * take care to only access its L2 cache parameters. In
614389c86e32SChris Williamson 		 * particular, hdr->l1hdr.b_buf may be invalid by now due to
61447adb730bSGeorge Wilson 		 * ARC eviction.
6145aad02571SSaso Kiselkov 		 */
614689c86e32SChris Williamson 		hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
6147aad02571SSaso Kiselkov 
614889c86e32SChris Williamson 		if ((HDR_L2COMPRESS(hdr)) &&
614989c86e32SChris Williamson 		    hdr->b_l2hdr.b_asize >= buf_compress_minsz) {
615089c86e32SChris Williamson 			if (l2arc_compress_buf(hdr)) {
6151aad02571SSaso Kiselkov 				/*
6152aad02571SSaso Kiselkov 				 * If compression succeeded, enable headroom
6153aad02571SSaso Kiselkov 				 * boost on the next scan cycle.
6154aad02571SSaso Kiselkov 				 */
6155aad02571SSaso Kiselkov 				*headroom_boost = B_TRUE;
6156aad02571SSaso Kiselkov 			}
6157aad02571SSaso Kiselkov 		}
6158aad02571SSaso Kiselkov 
6159aad02571SSaso Kiselkov 		/*
6160aad02571SSaso Kiselkov 		 * Pick up the buffer data we had previously stashed away
6161aad02571SSaso Kiselkov 		 * (and now potentially also compressed).
6162aad02571SSaso Kiselkov 		 */
616389c86e32SChris Williamson 		buf_data = hdr->b_l1hdr.b_tmp_cdata;
616489c86e32SChris Williamson 		buf_sz = hdr->b_l2hdr.b_asize;
6165aad02571SSaso Kiselkov 
6166a52fc310SPrakash Surya 		/*
6167a52fc310SPrakash Surya 		 * We need to do this regardless if buf_sz is zero or
6168a52fc310SPrakash Surya 		 * not, otherwise, when this l2hdr is evicted we'll
6169a52fc310SPrakash Surya 		 * remove a reference that was never added.
6170a52fc310SPrakash Surya 		 */
6171a52fc310SPrakash Surya 		(void) refcount_add_many(&dev->l2ad_alloc, buf_sz, hdr);
6172a52fc310SPrakash Surya 
6173aad02571SSaso Kiselkov 		/* Compression may have squashed the buffer to zero length. */
6174aad02571SSaso Kiselkov 		if (buf_sz != 0) {
6175d7d9a6d9SAndriy Gapon 			uint64_t buf_a_sz;
6176aad02571SSaso Kiselkov 
6177fa94a07fSbrendan 			wzio = zio_write_phys(pio, dev->l2ad_vdev,
6178fa94a07fSbrendan 			    dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
6179fa94a07fSbrendan 			    NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
6180fa94a07fSbrendan 			    ZIO_FLAG_CANFAIL, B_FALSE);
6181fa94a07fSbrendan 
6182fa94a07fSbrendan 			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
6183fa94a07fSbrendan 			    zio_t *, wzio);
6184fa94a07fSbrendan 			(void) zio_nowait(wzio);
6185fa94a07fSbrendan 
6186d7d9a6d9SAndriy Gapon 			stats_size += buf_sz;
6187a52fc310SPrakash Surya 
6188e14bb325SJeff Bonwick 			/*
6189e14bb325SJeff Bonwick 			 * Keep the clock hand suitably device-aligned.
6190e14bb325SJeff Bonwick 			 */
6191d7d9a6d9SAndriy Gapon 			buf_a_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
6192d7d9a6d9SAndriy Gapon 			write_asize += buf_a_sz;
6193d7d9a6d9SAndriy Gapon 			dev->l2ad_hand += buf_a_sz;
6194aad02571SSaso Kiselkov 		}
6195fa94a07fSbrendan 	}
6196fa94a07fSbrendan 
619789c86e32SChris Williamson 	mutex_exit(&dev->l2ad_mtx);
6198fa94a07fSbrendan 
6199*5f992543SArne Jansen 	ASSERT3U(write_asize, <=, target_sz);
6200fa94a07fSbrendan 	ARCSTAT_BUMP(arcstat_l2_writes_sent);
6201*5f992543SArne Jansen 	ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
6202fa94a07fSbrendan 	ARCSTAT_INCR(arcstat_l2_size, write_sz);
6203d7d9a6d9SAndriy Gapon 	ARCSTAT_INCR(arcstat_l2_asize, stats_size);
6204*5f992543SArne Jansen 	vdev_space_update(dev->l2ad_vdev, stats_size, 0, 0);
6205fa94a07fSbrendan 
6206fa94a07fSbrendan 	/*
6207fa94a07fSbrendan 	 * Bump device hand to the device start if it is approaching the end.
6208fa94a07fSbrendan 	 * l2arc_evict() will already have evicted ahead for this case.
6209fa94a07fSbrendan 	 */
6210*5f992543SArne Jansen 	if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
6211fa94a07fSbrendan 		dev->l2ad_hand = dev->l2ad_start;
6212fa94a07fSbrendan 		dev->l2ad_first = B_FALSE;
6213fa94a07fSbrendan 	}
6214fa94a07fSbrendan 
62155a98e54bSBrendan Gregg - Sun Microsystems 	dev->l2ad_writing = B_TRUE;
6216fa94a07fSbrendan 	(void) zio_wait(pio);
62175a98e54bSBrendan Gregg - Sun Microsystems 	dev->l2ad_writing = B_FALSE;
62185a98e54bSBrendan Gregg - Sun Microsystems 
6219*5f992543SArne Jansen 	return (write_asize);
6220aad02571SSaso Kiselkov }
6221aad02571SSaso Kiselkov 
6222aad02571SSaso Kiselkov /*
6223aad02571SSaso Kiselkov  * Compresses an L2ARC buffer.
622489c86e32SChris Williamson  * The data to be compressed must be prefilled in l1hdr.b_tmp_cdata and its
6225aad02571SSaso Kiselkov  * size in l2hdr->b_asize. This routine tries to compress the data and
6226aad02571SSaso Kiselkov  * depending on the compression result there are three possible outcomes:
6227aad02571SSaso Kiselkov  * *) The buffer was incompressible. The original l2hdr contents were left
6228aad02571SSaso Kiselkov  *    untouched and are ready for writing to an L2 device.
6229aad02571SSaso Kiselkov  * *) The buffer was all-zeros, so there is no need to write it to an L2
6230aad02571SSaso Kiselkov  *    device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
6231aad02571SSaso Kiselkov  *    set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
6232aad02571SSaso Kiselkov  * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
6233aad02571SSaso Kiselkov  *    data buffer which holds the compressed data to be written, and b_asize
6234aad02571SSaso Kiselkov  *    tells us how much data there is. b_compress is set to the appropriate
6235aad02571SSaso Kiselkov  *    compression algorithm. Once writing is done, invoke
6236aad02571SSaso Kiselkov  *    l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
6237aad02571SSaso Kiselkov  *
6238aad02571SSaso Kiselkov  * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
6239aad02571SSaso Kiselkov  * buffer was incompressible).
6240aad02571SSaso Kiselkov  */
6241aad02571SSaso Kiselkov static boolean_t
624289c86e32SChris Williamson l2arc_compress_buf(arc_buf_hdr_t *hdr)
6243aad02571SSaso Kiselkov {
6244aad02571SSaso Kiselkov 	void *cdata;
62455d7b4d43SMatthew Ahrens 	size_t csize, len, rounded;
624689c86e32SChris Williamson 	ASSERT(HDR_HAS_L2HDR(hdr));
624789c86e32SChris Williamson 	l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
6248aad02571SSaso Kiselkov 
624989c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
6250d4cd038cSArne Jansen 	ASSERT3S(l2hdr->b_compress, ==, ZIO_COMPRESS_OFF);
625189c86e32SChris Williamson 	ASSERT(hdr->b_l1hdr.b_tmp_cdata != NULL);
6252aad02571SSaso Kiselkov 
6253aad02571SSaso Kiselkov 	len = l2hdr->b_asize;
6254aad02571SSaso Kiselkov 	cdata = zio_data_buf_alloc(len);
625589c86e32SChris Williamson 	ASSERT3P(cdata, !=, NULL);
625689c86e32SChris Williamson 	csize = zio_compress_data(ZIO_COMPRESS_LZ4, hdr->b_l1hdr.b_tmp_cdata,
6257aad02571SSaso Kiselkov 	    cdata, l2hdr->b_asize);
6258aad02571SSaso Kiselkov 
62595d7b4d43SMatthew Ahrens 	rounded = P2ROUNDUP(csize, (size_t)SPA_MINBLOCKSIZE);
62605d7b4d43SMatthew Ahrens 	if (rounded > csize) {
62615d7b4d43SMatthew Ahrens 		bzero((char *)cdata + csize, rounded - csize);
62625d7b4d43SMatthew Ahrens 		csize = rounded;
62635d7b4d43SMatthew Ahrens 	}
62645d7b4d43SMatthew Ahrens 
6265aad02571SSaso Kiselkov 	if (csize == 0) {
6266aad02571SSaso Kiselkov 		/* zero block, indicate that there's nothing to write */
6267aad02571SSaso Kiselkov 		zio_data_buf_free(cdata, len);
6268d4cd038cSArne Jansen 		l2hdr->b_compress = ZIO_COMPRESS_EMPTY;
6269aad02571SSaso Kiselkov 		l2hdr->b_asize = 0;
627089c86e32SChris Williamson 		hdr->b_l1hdr.b_tmp_cdata = NULL;
6271aad02571SSaso Kiselkov 		ARCSTAT_BUMP(arcstat_l2_compress_zeros);
6272aad02571SSaso Kiselkov 		return (B_TRUE);
6273aad02571SSaso Kiselkov 	} else if (csize > 0 && csize < len) {
6274aad02571SSaso Kiselkov 		/*
6275aad02571SSaso Kiselkov 		 * Compression succeeded, we'll keep the cdata around for
6276aad02571SSaso Kiselkov 		 * writing and release it afterwards.
6277aad02571SSaso Kiselkov 		 */
6278d4cd038cSArne Jansen 		l2hdr->b_compress = ZIO_COMPRESS_LZ4;
6279aad02571SSaso Kiselkov 		l2hdr->b_asize = csize;
628089c86e32SChris Williamson 		hdr->b_l1hdr.b_tmp_cdata = cdata;
6281aad02571SSaso Kiselkov 		ARCSTAT_BUMP(arcstat_l2_compress_successes);
6282aad02571SSaso Kiselkov 		return (B_TRUE);
6283aad02571SSaso Kiselkov 	} else {
6284aad02571SSaso Kiselkov 		/*
6285aad02571SSaso Kiselkov 		 * Compression failed, release the compressed buffer.
6286aad02571SSaso Kiselkov 		 * l2hdr will be left unmodified.
6287aad02571SSaso Kiselkov 		 */
6288aad02571SSaso Kiselkov 		zio_data_buf_free(cdata, len);
6289aad02571SSaso Kiselkov 		ARCSTAT_BUMP(arcstat_l2_compress_failures);
6290aad02571SSaso Kiselkov 		return (B_FALSE);
6291aad02571SSaso Kiselkov 	}
6292aad02571SSaso Kiselkov }
6293aad02571SSaso Kiselkov 
6294aad02571SSaso Kiselkov /*
6295aad02571SSaso Kiselkov  * Decompresses a zio read back from an l2arc device. On success, the
6296aad02571SSaso Kiselkov  * underlying zio's io_data buffer is overwritten by the uncompressed
6297aad02571SSaso Kiselkov  * version. On decompression error (corrupt compressed stream), the
6298aad02571SSaso Kiselkov  * zio->io_error value is set to signal an I/O error.
6299aad02571SSaso Kiselkov  *
6300aad02571SSaso Kiselkov  * Please note that the compressed data stream is not checksummed, so
6301aad02571SSaso Kiselkov  * if the underlying device is experiencing data corruption, we may feed
6302aad02571SSaso Kiselkov  * corrupt data to the decompressor, so the decompressor needs to be
6303aad02571SSaso Kiselkov  * able to handle this situation (LZ4 does).
6304aad02571SSaso Kiselkov  */
6305aad02571SSaso Kiselkov static void
6306aad02571SSaso Kiselkov l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
6307aad02571SSaso Kiselkov {
6308aad02571SSaso Kiselkov 	ASSERT(L2ARC_IS_VALID_COMPRESS(c));
6309aad02571SSaso Kiselkov 
6310aad02571SSaso Kiselkov 	if (zio->io_error != 0) {
6311aad02571SSaso Kiselkov 		/*
6312aad02571SSaso Kiselkov 		 * An io error has occured, just restore the original io
6313aad02571SSaso Kiselkov 		 * size in preparation for a main pool read.
6314aad02571SSaso Kiselkov 		 */
6315aad02571SSaso Kiselkov 		zio->io_orig_size = zio->io_size = hdr->b_size;
6316aad02571SSaso Kiselkov 		return;
6317aad02571SSaso Kiselkov 	}
6318aad02571SSaso Kiselkov 
6319aad02571SSaso Kiselkov 	if (c == ZIO_COMPRESS_EMPTY) {
6320aad02571SSaso Kiselkov 		/*
6321aad02571SSaso Kiselkov 		 * An empty buffer results in a null zio, which means we
6322aad02571SSaso Kiselkov 		 * need to fill its io_data after we're done restoring the
6323aad02571SSaso Kiselkov 		 * buffer's contents.
6324aad02571SSaso Kiselkov 		 */
632589c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_buf != NULL);
632689c86e32SChris Williamson 		bzero(hdr->b_l1hdr.b_buf->b_data, hdr->b_size);
632789c86e32SChris Williamson 		zio->io_data = zio->io_orig_data = hdr->b_l1hdr.b_buf->b_data;
6328aad02571SSaso Kiselkov 	} else {
6329aad02571SSaso Kiselkov 		ASSERT(zio->io_data != NULL);
6330aad02571SSaso Kiselkov 		/*
6331aad02571SSaso Kiselkov 		 * We copy the compressed data from the start of the arc buffer
6332aad02571SSaso Kiselkov 		 * (the zio_read will have pulled in only what we need, the
6333aad02571SSaso Kiselkov 		 * rest is garbage which we will overwrite at decompression)
6334aad02571SSaso Kiselkov 		 * and then decompress back to the ARC data buffer. This way we
6335aad02571SSaso Kiselkov 		 * can minimize copying by simply decompressing back over the
6336aad02571SSaso Kiselkov 		 * original compressed data (rather than decompressing to an
6337aad02571SSaso Kiselkov 		 * aux buffer and then copying back the uncompressed buffer,
6338aad02571SSaso Kiselkov 		 * which is likely to be much larger).
6339aad02571SSaso Kiselkov 		 */
6340aad02571SSaso Kiselkov 		uint64_t csize;
6341aad02571SSaso Kiselkov 		void *cdata;
6342aad02571SSaso Kiselkov 
6343aad02571SSaso Kiselkov 		csize = zio->io_size;
6344aad02571SSaso Kiselkov 		cdata = zio_data_buf_alloc(csize);
6345aad02571SSaso Kiselkov 		bcopy(zio->io_data, cdata, csize);
6346aad02571SSaso Kiselkov 		if (zio_decompress_data(c, cdata, zio->io_data, csize,
6347aad02571SSaso Kiselkov 		    hdr->b_size) != 0)
6348aad02571SSaso Kiselkov 			zio->io_error = EIO;
6349aad02571SSaso Kiselkov 		zio_data_buf_free(cdata, csize);
6350aad02571SSaso Kiselkov 	}
6351aad02571SSaso Kiselkov 
6352aad02571SSaso Kiselkov 	/* Restore the expected uncompressed IO size. */
6353aad02571SSaso Kiselkov 	zio->io_orig_size = zio->io_size = hdr->b_size;
6354aad02571SSaso Kiselkov }
6355aad02571SSaso Kiselkov 
6356aad02571SSaso Kiselkov /*
6357aad02571SSaso Kiselkov  * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
6358aad02571SSaso Kiselkov  * This buffer serves as a temporary holder of compressed data while
6359aad02571SSaso Kiselkov  * the buffer entry is being written to an l2arc device. Once that is
6360aad02571SSaso Kiselkov  * done, we can dispose of it.
6361aad02571SSaso Kiselkov  */
6362aad02571SSaso Kiselkov static void
63637adb730bSGeorge Wilson l2arc_release_cdata_buf(arc_buf_hdr_t *hdr)
6364aad02571SSaso Kiselkov {
6365d4cd038cSArne Jansen 	ASSERT(HDR_HAS_L2HDR(hdr));
6366d4cd038cSArne Jansen 	enum zio_compress comp = hdr->b_l2hdr.b_compress;
6367244781f1SPrakash Surya 
636889c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
6369244781f1SPrakash Surya 	ASSERT(comp == ZIO_COMPRESS_OFF || L2ARC_IS_VALID_COMPRESS(comp));
6370244781f1SPrakash Surya 
6371244781f1SPrakash Surya 	if (comp == ZIO_COMPRESS_OFF) {
6372244781f1SPrakash Surya 		/*
6373244781f1SPrakash Surya 		 * In this case, b_tmp_cdata points to the same buffer
6374244781f1SPrakash Surya 		 * as the arc_buf_t's b_data field. We don't want to
6375244781f1SPrakash Surya 		 * free it, since the arc_buf_t will handle that.
6376244781f1SPrakash Surya 		 */
6377244781f1SPrakash Surya 		hdr->b_l1hdr.b_tmp_cdata = NULL;
6378244781f1SPrakash Surya 	} else if (comp == ZIO_COMPRESS_EMPTY) {
6379244781f1SPrakash Surya 		/*
6380244781f1SPrakash Surya 		 * In this case, b_tmp_cdata was compressed to an empty
6381244781f1SPrakash Surya 		 * buffer, thus there's nothing to free and b_tmp_cdata
6382244781f1SPrakash Surya 		 * should have been set to NULL in l2arc_write_buffers().
6383244781f1SPrakash Surya 		 */
6384244781f1SPrakash Surya 		ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
6385244781f1SPrakash Surya 	} else {
6386aad02571SSaso Kiselkov 		/*
6387aad02571SSaso Kiselkov 		 * If the data was compressed, then we've allocated a
6388aad02571SSaso Kiselkov 		 * temporary buffer for it, so now we need to release it.
6389aad02571SSaso Kiselkov 		 */
639089c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_tmp_cdata != NULL);
639189c86e32SChris Williamson 		zio_data_buf_free(hdr->b_l1hdr.b_tmp_cdata,
639289c86e32SChris Williamson 		    hdr->b_size);
639389c86e32SChris Williamson 		hdr->b_l1hdr.b_tmp_cdata = NULL;
6394fa94a07fSbrendan 	}
6395fa94a07fSbrendan 
6396244781f1SPrakash Surya }
6397244781f1SPrakash Surya 
6398fa94a07fSbrendan /*
6399fa94a07fSbrendan  * This thread feeds the L2ARC at regular intervals.  This is the beating
6400fa94a07fSbrendan  * heart of the L2ARC.
6401fa94a07fSbrendan  */
6402fa94a07fSbrendan static void
6403fa94a07fSbrendan l2arc_feed_thread(void)
6404fa94a07fSbrendan {
6405fa94a07fSbrendan 	callb_cpr_t cpr;
6406fa94a07fSbrendan 	l2arc_dev_t *dev;
6407fa94a07fSbrendan 	spa_t *spa;
64085a98e54bSBrendan Gregg - Sun Microsystems 	uint64_t size, wrote;
6409d3d50737SRafael Vanoni 	clock_t begin, next = ddi_get_lbolt();
6410aad02571SSaso Kiselkov 	boolean_t headroom_boost = B_FALSE;
6411fa94a07fSbrendan 
6412fa94a07fSbrendan 	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
6413fa94a07fSbrendan 
6414fa94a07fSbrendan 	mutex_enter(&l2arc_feed_thr_lock);
6415fa94a07fSbrendan 
6416fa94a07fSbrendan 	while (l2arc_thread_exit == 0) {
6417fa94a07fSbrendan 		CALLB_CPR_SAFE_BEGIN(&cpr);
6418fa94a07fSbrendan 		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
64195a98e54bSBrendan Gregg - Sun Microsystems 		    next);
6420fa94a07fSbrendan 		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
6421d3d50737SRafael Vanoni 		next = ddi_get_lbolt() + hz;
6422fa94a07fSbrendan 
64233a737e0dSbrendan 		/*
64243a737e0dSbrendan 		 * Quick check for L2ARC devices.
64253a737e0dSbrendan 		 */
6426fa94a07fSbrendan 		mutex_enter(&l2arc_dev_mtx);
64273a737e0dSbrendan 		if (l2arc_ndev == 0) {
64283a737e0dSbrendan 			mutex_exit(&l2arc_dev_mtx);
64293a737e0dSbrendan 			continue;
64303a737e0dSbrendan 		}
64313a737e0dSbrendan 		mutex_exit(&l2arc_dev_mtx);
6432d3d50737SRafael Vanoni 		begin = ddi_get_lbolt();
6433c5904d13Seschrock 
6434c5904d13Seschrock 		/*
6435c5904d13Seschrock 		 * This selects the next l2arc device to write to, and in
6436c5904d13Seschrock 		 * doing so the next spa to feed from: dev->l2ad_spa.   This
64373a737e0dSbrendan 		 * will return NULL if there are now no l2arc devices or if
64383a737e0dSbrendan 		 * they are all faulted.
64393a737e0dSbrendan 		 *
64403a737e0dSbrendan 		 * If a device is returned, its spa's config lock is also
64413a737e0dSbrendan 		 * held to prevent device removal.  l2arc_dev_get_next()
64423a737e0dSbrendan 		 * will grab and release l2arc_dev_mtx.
6443c5904d13Seschrock 		 */
64443a737e0dSbrendan 		if ((dev = l2arc_dev_get_next()) == NULL)
6445fa94a07fSbrendan 			continue;
64463a737e0dSbrendan 
64473a737e0dSbrendan 		spa = dev->l2ad_spa;
64483a737e0dSbrendan 		ASSERT(spa != NULL);
6449fa94a07fSbrendan 
6450fa94a07fSbrendan 		/*
6451f9af39baSGeorge Wilson 		 * If the pool is read-only then force the feed thread to
6452f9af39baSGeorge Wilson 		 * sleep a little longer.
6453f9af39baSGeorge Wilson 		 */
6454f9af39baSGeorge Wilson 		if (!spa_writeable(spa)) {
6455f9af39baSGeorge Wilson 			next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
6456f9af39baSGeorge Wilson 			spa_config_exit(spa, SCL_L2ARC, dev);
6457f9af39baSGeorge Wilson 			continue;
6458f9af39baSGeorge Wilson 		}
6459f9af39baSGeorge Wilson 
6460f9af39baSGeorge Wilson 		/*
6461fa94a07fSbrendan 		 * Avoid contributing to memory pressure.
6462fa94a07fSbrendan 		 */
6463fa94a07fSbrendan 		if (arc_reclaim_needed()) {
6464fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
6465e14bb325SJeff Bonwick 			spa_config_exit(spa, SCL_L2ARC, dev);
6466fa94a07fSbrendan 			continue;
6467fa94a07fSbrendan 		}
6468fa94a07fSbrendan 
6469fa94a07fSbrendan 		ARCSTAT_BUMP(arcstat_l2_feeds);
6470fa94a07fSbrendan 
6471aad02571SSaso Kiselkov 		size = l2arc_write_size();
64723a737e0dSbrendan 
6473fa94a07fSbrendan 		/*
6474fa94a07fSbrendan 		 * Evict L2ARC buffers that will be overwritten.
6475fa94a07fSbrendan 		 */
64763a737e0dSbrendan 		l2arc_evict(dev, size, B_FALSE);
6477fa94a07fSbrendan 
6478fa94a07fSbrendan 		/*
6479fa94a07fSbrendan 		 * Write ARC buffers.
6480fa94a07fSbrendan 		 */
6481aad02571SSaso Kiselkov 		wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
64825a98e54bSBrendan Gregg - Sun Microsystems 
64835a98e54bSBrendan Gregg - Sun Microsystems 		/*
64845a98e54bSBrendan Gregg - Sun Microsystems 		 * Calculate interval between writes.
64855a98e54bSBrendan Gregg - Sun Microsystems 		 */
64865a98e54bSBrendan Gregg - Sun Microsystems 		next = l2arc_write_interval(begin, size, wrote);
6487e14bb325SJeff Bonwick 		spa_config_exit(spa, SCL_L2ARC, dev);
6488fa94a07fSbrendan 	}
6489fa94a07fSbrendan 
6490fa94a07fSbrendan 	l2arc_thread_exit = 0;
6491fa94a07fSbrendan 	cv_broadcast(&l2arc_feed_thr_cv);
6492fa94a07fSbrendan 	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
6493fa94a07fSbrendan 	thread_exit();
6494fa94a07fSbrendan }
6495fa94a07fSbrendan 
6496c5904d13Seschrock boolean_t
6497c5904d13Seschrock l2arc_vdev_present(vdev_t *vd)
6498c5904d13Seschrock {
6499c9e5c7a7SSaso Kiselkov 	l2arc_dev_t *dev;
6500c9e5c7a7SSaso Kiselkov 
6501c5904d13Seschrock 	mutex_enter(&l2arc_dev_mtx);
6502c5904d13Seschrock 	for (dev = list_head(l2arc_dev_list); dev != NULL;
6503c5904d13Seschrock 	    dev = list_next(l2arc_dev_list, dev)) {
6504c5904d13Seschrock 		if (dev->l2ad_vdev == vd)
6505c5904d13Seschrock 			break;
6506c5904d13Seschrock 	}
6507c5904d13Seschrock 	mutex_exit(&l2arc_dev_mtx);
6508c5904d13Seschrock 
6509*5f992543SArne Jansen 	return (dev != NULL);
6510c5904d13Seschrock }
6511c5904d13Seschrock 
6512fa94a07fSbrendan /*
6513fa94a07fSbrendan  * Add a vdev for use by the L2ARC.  By this point the spa has already
6514*5f992543SArne Jansen  * validated the vdev and opened it.
6515fa94a07fSbrendan  */
6516fa94a07fSbrendan void
6517*5f992543SArne Jansen l2arc_add_vdev(spa_t *spa, vdev_t *vd)
6518fa94a07fSbrendan {
6519fa94a07fSbrendan 	l2arc_dev_t *adddev;
6520fa94a07fSbrendan 
6521c5904d13Seschrock 	ASSERT(!l2arc_vdev_present(vd));
6522c5904d13Seschrock 
6523fa94a07fSbrendan 	/*
6524fa94a07fSbrendan 	 * Create a new l2arc device entry.
6525fa94a07fSbrendan 	 */
6526fa94a07fSbrendan 	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
6527fa94a07fSbrendan 	adddev->l2ad_spa = spa;
6528fa94a07fSbrendan 	adddev->l2ad_vdev = vd;
6529*5f992543SArne Jansen 	adddev->l2ad_start = VDEV_LABEL_START_SIZE;
6530573ca77eSGeorge Wilson 	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
6531fa94a07fSbrendan 	adddev->l2ad_hand = adddev->l2ad_start;
6532fa94a07fSbrendan 	adddev->l2ad_first = B_TRUE;
65335a98e54bSBrendan Gregg - Sun Microsystems 	adddev->l2ad_writing = B_FALSE;
6534fa94a07fSbrendan 
653589c86e32SChris Williamson 	mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
6536fa94a07fSbrendan 	/*
6537fa94a07fSbrendan 	 * This is a list of all ARC buffers that are still valid on the
6538fa94a07fSbrendan 	 * device.
6539fa94a07fSbrendan 	 */
654089c86e32SChris Williamson 	list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
654189c86e32SChris Williamson 	    offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
6542fa94a07fSbrendan 
6543b24ab676SJeff Bonwick 	vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
6544a52fc310SPrakash Surya 	refcount_create(&adddev->l2ad_alloc);
6545fa94a07fSbrendan 
6546fa94a07fSbrendan 	/*
6547fa94a07fSbrendan 	 * Add device to global list
6548fa94a07fSbrendan 	 */
6549fa94a07fSbrendan 	mutex_enter(&l2arc_dev_mtx);
6550fa94a07fSbrendan 	list_insert_head(l2arc_dev_list, adddev);
6551fa94a07fSbrendan 	atomic_inc_64(&l2arc_ndev);
6552fa94a07fSbrendan 	mutex_exit(&l2arc_dev_mtx);
6553fa94a07fSbrendan }
6554fa94a07fSbrendan 
6555fa94a07fSbrendan /*
6556fa94a07fSbrendan  * Remove a vdev from the L2ARC.
6557fa94a07fSbrendan  */
6558fa94a07fSbrendan void
6559fa94a07fSbrendan l2arc_remove_vdev(vdev_t *vd)
6560fa94a07fSbrendan {
6561fa94a07fSbrendan 	l2arc_dev_t *dev, *nextdev, *remdev = NULL;
6562fa94a07fSbrendan 
6563fa94a07fSbrendan 	/*
6564fa94a07fSbrendan 	 * Find the device by vdev
6565fa94a07fSbrendan 	 */
6566fa94a07fSbrendan 	mutex_enter(&l2arc_dev_mtx);
6567fa94a07fSbrendan 	for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
6568fa94a07fSbrendan 		nextdev = list_next(l2arc_dev_list, dev);
6569fa94a07fSbrendan 		if (vd == dev->l2ad_vdev) {
6570fa94a07fSbrendan 			remdev = dev;
6571fa94a07fSbrendan 			break;
6572fa94a07fSbrendan 		}
6573fa94a07fSbrendan 	}
6574fa94a07fSbrendan 	ASSERT(remdev != NULL);
6575fa94a07fSbrendan 
6576fa94a07fSbrendan 	/*
6577fa94a07fSbrendan 	 * Remove device from global list
6578fa94a07fSbrendan 	 */
6579fa94a07fSbrendan 	list_remove(l2arc_dev_list, remdev);
6580fa94a07fSbrendan 	l2arc_dev_last = NULL;		/* may have been invalidated */
65813a737e0dSbrendan 	atomic_dec_64(&l2arc_ndev);
65823a737e0dSbrendan 	mutex_exit(&l2arc_dev_mtx);
6583fa94a07fSbrendan 
6584fa94a07fSbrendan 	/*
6585fa94a07fSbrendan 	 * Clear all buflists and ARC references.  L2ARC device flush.
6586fa94a07fSbrendan 	 */
6587fa94a07fSbrendan 	l2arc_evict(remdev, 0, B_TRUE);
658889c86e32SChris Williamson 	list_destroy(&remdev->l2ad_buflist);
658989c86e32SChris Williamson 	mutex_destroy(&remdev->l2ad_mtx);
6590a52fc310SPrakash Surya 	refcount_destroy(&remdev->l2ad_alloc);
6591fa94a07fSbrendan 	kmem_free(remdev, sizeof (l2arc_dev_t));
6592fa94a07fSbrendan }
6593fa94a07fSbrendan 
6594fa94a07fSbrendan void
6595e14bb325SJeff Bonwick l2arc_init(void)
6596fa94a07fSbrendan {
6597fa94a07fSbrendan 	l2arc_thread_exit = 0;
6598fa94a07fSbrendan 	l2arc_ndev = 0;
6599fa94a07fSbrendan 	l2arc_writes_sent = 0;
6600fa94a07fSbrendan 	l2arc_writes_done = 0;
6601fa94a07fSbrendan 
6602fa94a07fSbrendan 	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
6603fa94a07fSbrendan 	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
6604fa94a07fSbrendan 	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
6605fa94a07fSbrendan 	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
6606fa94a07fSbrendan 
6607fa94a07fSbrendan 	l2arc_dev_list = &L2ARC_dev_list;
6608fa94a07fSbrendan 	l2arc_free_on_write = &L2ARC_free_on_write;
6609fa94a07fSbrendan 	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
6610fa94a07fSbrendan 	    offsetof(l2arc_dev_t, l2ad_node));
6611fa94a07fSbrendan 	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
6612fa94a07fSbrendan 	    offsetof(l2arc_data_free_t, l2df_list_node));
6613fa94a07fSbrendan }
6614fa94a07fSbrendan 
6615fa94a07fSbrendan void
6616e14bb325SJeff Bonwick l2arc_fini(void)
6617fa94a07fSbrendan {
66183a737e0dSbrendan 	/*
66193a737e0dSbrendan 	 * This is called from dmu_fini(), which is called from spa_fini();
66203a737e0dSbrendan 	 * Because of this, we can assume that all l2arc devices have
66213a737e0dSbrendan 	 * already been removed when the pools themselves were removed.
66223a737e0dSbrendan 	 */
66233a737e0dSbrendan 
66243a737e0dSbrendan 	l2arc_do_free_on_write();
66253a737e0dSbrendan 
6626fa94a07fSbrendan 	mutex_destroy(&l2arc_feed_thr_lock);
6627fa94a07fSbrendan 	cv_destroy(&l2arc_feed_thr_cv);
6628fa94a07fSbrendan 	mutex_destroy(&l2arc_dev_mtx);
6629fa94a07fSbrendan 	mutex_destroy(&l2arc_free_on_write_mtx);
6630fa94a07fSbrendan 
6631fa94a07fSbrendan 	list_destroy(l2arc_dev_list);
6632fa94a07fSbrendan 	list_destroy(l2arc_free_on_write);
6633fa94a07fSbrendan }
6634e14bb325SJeff Bonwick 
6635e14bb325SJeff Bonwick void
6636e14bb325SJeff Bonwick l2arc_start(void)
6637e14bb325SJeff Bonwick {
66388ad4d6ddSJeff Bonwick 	if (!(spa_mode_global & FWRITE))
6639e14bb325SJeff Bonwick 		return;
6640e14bb325SJeff Bonwick 
6641e14bb325SJeff Bonwick 	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
6642e14bb325SJeff Bonwick 	    TS_RUN, minclsyspri);
6643e14bb325SJeff Bonwick }
6644e14bb325SJeff Bonwick 
6645e14bb325SJeff Bonwick void
6646e14bb325SJeff Bonwick l2arc_stop(void)
6647e14bb325SJeff Bonwick {
66488ad4d6ddSJeff Bonwick 	if (!(spa_mode_global & FWRITE))
6649e14bb325SJeff Bonwick 		return;
6650e14bb325SJeff Bonwick 
6651e14bb325SJeff Bonwick 	mutex_enter(&l2arc_feed_thr_lock);
6652e14bb325SJeff Bonwick 	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
6653e14bb325SJeff Bonwick 	l2arc_thread_exit = 1;
6654e14bb325SJeff Bonwick 	while (l2arc_thread_exit != 0)
6655e14bb325SJeff Bonwick 		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
6656e14bb325SJeff Bonwick 	mutex_exit(&l2arc_feed_thr_lock);
6657e14bb325SJeff Bonwick }
6658c9e5c7a7SSaso Kiselkov 
6659c9e5c7a7SSaso Kiselkov /*
6660ce0d9371SArne Jansen  * dump arc cache to user mode for debugging purposes
6661ce0d9371SArne Jansen  */
6662ce0d9371SArne Jansen static void
6663ce0d9371SArne Jansen arc_dump_entry(arc_buf_hdr_t *entry, arc_info_t *outp)
6664ce0d9371SArne Jansen {
6665ce0d9371SArne Jansen 	outp->ai_dva = entry->b_dva;
6666ce0d9371SArne Jansen 	outp->ai_birth = entry->b_birth;
6667ce0d9371SArne Jansen 	outp->ai_flags = entry->b_flags;
6668ce0d9371SArne Jansen 	outp->ai_spa = entry->b_spa;
6669ce0d9371SArne Jansen 	outp->ai_size = entry->b_size;
6670ce0d9371SArne Jansen 	if (HDR_HAS_L1HDR(entry)) {
6671ce0d9371SArne Jansen 		arc_state_t *state = entry->b_l1hdr.b_state;
6672ce0d9371SArne Jansen 		if (state == arc_anon)
6673ce0d9371SArne Jansen 			outp->ai_state = AIS_ANON;
6674ce0d9371SArne Jansen 		else if (state == arc_mru)
6675ce0d9371SArne Jansen 			outp->ai_state = AIS_MRU;
6676ce0d9371SArne Jansen 		else if (state == arc_mru_ghost)
6677ce0d9371SArne Jansen 			outp->ai_state = AIS_MRU_GHOST;
6678ce0d9371SArne Jansen 		else if (state == arc_mfu)
6679ce0d9371SArne Jansen 			outp->ai_state = AIS_MFU;
6680ce0d9371SArne Jansen 		else if (state == arc_mfu_ghost)
6681ce0d9371SArne Jansen 			outp->ai_state = AIS_MFU_GHOST;
6682ce0d9371SArne Jansen 		else if (state == arc_l2c_only)
6683ce0d9371SArne Jansen 			outp->ai_state = AIS_L2C_ONLY;
6684ce0d9371SArne Jansen 		else
6685ce0d9371SArne Jansen 			outp->ai_state = AIS_UNKNOWN;
6686ce0d9371SArne Jansen 	} else {
6687ce0d9371SArne Jansen 		outp->ai_state = AIS_NO_L1HDR;
6688ce0d9371SArne Jansen 	}
6689ce0d9371SArne Jansen }
6690ce0d9371SArne Jansen 
6691ce0d9371SArne Jansen int
6692ce0d9371SArne Jansen arc_dump(int start_bucket, void *buf, size_t bufsize, size_t *returned_bytes)
6693ce0d9371SArne Jansen {
6694ce0d9371SArne Jansen 	int i;
6695ce0d9371SArne Jansen 	arc_info_t *outp = buf + sizeof(arc_info_hdr_t);
6696ce0d9371SArne Jansen 	arc_info_t *maxp = buf + bufsize;
6697ce0d9371SArne Jansen 	arc_info_hdr_t *aih = buf;
6698ce0d9371SArne Jansen 	size_t nbuckets = buf_hash_table.ht_mask + 1;
6699ce0d9371SArne Jansen 	size_t bph = nbuckets / BUF_LOCKS;	/* buckets per hash */
6700ce0d9371SArne Jansen 	kmutex_t *last_lock = NULL;
6701ce0d9371SArne Jansen 
6702ce0d9371SArne Jansen 	if (bufsize < sizeof(arc_info_hdr_t))
6703ce0d9371SArne Jansen 		return (ENOMEM);
6704ce0d9371SArne Jansen 
6705ce0d9371SArne Jansen 	aih->aih_buckets = nbuckets;
6706ce0d9371SArne Jansen 	aih->aih_buf_locks = BUF_LOCKS;
6707ce0d9371SArne Jansen 
6708ce0d9371SArne Jansen 	ASSERT(start_bucket >= 0);
6709ce0d9371SArne Jansen 	ASSERT(start_bucket < nbuckets);
6710ce0d9371SArne Jansen 
6711ce0d9371SArne Jansen 	for (i = start_bucket; i < nbuckets; ++i) {
6712ce0d9371SArne Jansen 		kmutex_t *hash_lock;
6713ce0d9371SArne Jansen 		arc_buf_hdr_t *entry;
6714ce0d9371SArne Jansen 		arc_info_t *dryrun = outp;
6715ce0d9371SArne Jansen 		int bucket;
6716ce0d9371SArne Jansen 
6717ce0d9371SArne Jansen 		/*
6718ce0d9371SArne Jansen 		 * transform index. We want to enumerate the buckets in an
6719ce0d9371SArne Jansen 		 * order that allows us to keep the mutex as long as possible
6720ce0d9371SArne Jansen 		 */
6721ce0d9371SArne Jansen 		bucket = (i / bph) + (i % bph) * BUF_LOCKS;
6722ce0d9371SArne Jansen 
6723ce0d9371SArne Jansen 		hash_lock = BUF_HASH_LOCK(bucket);
6724ce0d9371SArne Jansen 		if (hash_lock != last_lock) {
6725ce0d9371SArne Jansen 			if (last_lock)
6726ce0d9371SArne Jansen 				mutex_exit(last_lock);
6727ce0d9371SArne Jansen 			mutex_enter(hash_lock);
6728ce0d9371SArne Jansen 		}
6729ce0d9371SArne Jansen 		last_lock = hash_lock;
6730ce0d9371SArne Jansen 		/* count entries to see if they will fit */
6731ce0d9371SArne Jansen 		entry = buf_hash_table.ht_table[bucket];
6732ce0d9371SArne Jansen 		while (entry != NULL) {
6733ce0d9371SArne Jansen 			++dryrun;
6734ce0d9371SArne Jansen 			entry = entry->b_hash_next;
6735ce0d9371SArne Jansen 		}
6736ce0d9371SArne Jansen 		if (dryrun > maxp) {
6737ce0d9371SArne Jansen 			break;
6738ce0d9371SArne Jansen 		}
6739ce0d9371SArne Jansen 		/* actually copy entries */
6740ce0d9371SArne Jansen 		entry = buf_hash_table.ht_table[bucket];
6741ce0d9371SArne Jansen 		while (entry != NULL) {
6742ce0d9371SArne Jansen 			arc_dump_entry(entry, outp);
6743ce0d9371SArne Jansen 			++outp;
6744ce0d9371SArne Jansen 			entry = entry->b_hash_next;
6745ce0d9371SArne Jansen 		}
6746ce0d9371SArne Jansen 	}
6747ce0d9371SArne Jansen 	if (last_lock)
6748ce0d9371SArne Jansen 		mutex_exit(last_lock);
6749ce0d9371SArne Jansen 
6750ce0d9371SArne Jansen 	*returned_bytes = (void *)outp - buf;
6751ce0d9371SArne Jansen 	aih->aih_entries = (*returned_bytes - sizeof(*aih)) / sizeof(*outp);
6752ce0d9371SArne Jansen 
6753ce0d9371SArne Jansen 	if (i <= buf_hash_table.ht_mask)
6754ce0d9371SArne Jansen 		aih->aih_next = i;
6755ce0d9371SArne Jansen 	else
6756ce0d9371SArne Jansen 		aih->aih_next = 0;
6757ce0d9371SArne Jansen 
6758ce0d9371SArne Jansen 	return (0);
6759ce0d9371SArne Jansen }
6760