xref: /illumos-gate/usr/src/uts/common/fs/zfs/arc.c (revision 770499e1)
1fa9e4066Sahrens /*
2fa9e4066Sahrens  * CDDL HEADER START
3fa9e4066Sahrens  *
4fa9e4066Sahrens  * The contents of this file are subject to the terms of the
5033f9833Sek  * Common Development and Distribution License (the "License").
6033f9833Sek  * 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.
2410fbdecbSMatthew Ahrens  * Copyright (c) 2011, 2017 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
805602294fSDan Kimmel  * 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
835602294fSDan Kimmel  * 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  *
965602294fSDan Kimmel  * Each ARC state also has a mutex which is used to protect the
97fa9e4066Sahrens  * buffer list associated with the state.  When attempting to
985602294fSDan Kimmel  * 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  *
102fa9e4066Sahrens  * Note that the majority of the performance stats are manipulated
103fa9e4066Sahrens  * with atomic operations.
104fa94a07fSbrendan  *
10589c86e32SChris Williamson  * The L2ARC uses the l2ad_mtx on each vdev for the following:
106fa94a07fSbrendan  *
107fa94a07fSbrendan  *	- L2ARC buflist creation
108fa94a07fSbrendan  *	- L2ARC buflist eviction
109fa94a07fSbrendan  *	- L2ARC write completion, which walks L2ARC buflists
110fa94a07fSbrendan  *	- ARC header destruction, as it removes from L2ARC buflists
111fa94a07fSbrendan  *	- ARC header release, as it removes from L2ARC buflists
112fa9e4066Sahrens  */
113fa9e4066Sahrens 
114dcbf3bd6SGeorge Wilson /*
115dcbf3bd6SGeorge Wilson  * ARC operation:
116dcbf3bd6SGeorge Wilson  *
117dcbf3bd6SGeorge Wilson  * Every block that is in the ARC is tracked by an arc_buf_hdr_t structure.
118dcbf3bd6SGeorge Wilson  * This structure can point either to a block that is still in the cache or to
119dcbf3bd6SGeorge Wilson  * one that is only accessible in an L2 ARC device, or it can provide
120dcbf3bd6SGeorge Wilson  * information about a block that was recently evicted. If a block is
121dcbf3bd6SGeorge Wilson  * only accessible in the L2ARC, then the arc_buf_hdr_t only has enough
122dcbf3bd6SGeorge Wilson  * information to retrieve it from the L2ARC device. This information is
123dcbf3bd6SGeorge Wilson  * stored in the l2arc_buf_hdr_t sub-structure of the arc_buf_hdr_t. A block
124dcbf3bd6SGeorge Wilson  * that is in this state cannot access the data directly.
125dcbf3bd6SGeorge Wilson  *
126dcbf3bd6SGeorge Wilson  * Blocks that are actively being referenced or have not been evicted
127dcbf3bd6SGeorge Wilson  * are cached in the L1ARC. The L1ARC (l1arc_buf_hdr_t) is a structure within
128dcbf3bd6SGeorge Wilson  * the arc_buf_hdr_t that will point to the data block in memory. A block can
129dcbf3bd6SGeorge Wilson  * only be read by a consumer if it has an l1arc_buf_hdr_t. The L1ARC
1305602294fSDan Kimmel  * caches data in two ways -- in a list of ARC buffers (arc_buf_t) and
131*770499e1SDan Kimmel  * also in the arc_buf_hdr_t's private physical data block pointer (b_pabd).
1325602294fSDan Kimmel  *
1335602294fSDan Kimmel  * The L1ARC's data pointer may or may not be uncompressed. The ARC has the
134*770499e1SDan Kimmel  * ability to store the physical data (b_pabd) associated with the DVA of the
135*770499e1SDan Kimmel  * arc_buf_hdr_t. Since the b_pabd is a copy of the on-disk physical block,
1365602294fSDan Kimmel  * it will match its on-disk compression characteristics. This behavior can be
1375602294fSDan Kimmel  * disabled by setting 'zfs_compressed_arc_enabled' to B_FALSE. When the
138*770499e1SDan Kimmel  * compressed ARC functionality is disabled, the b_pabd will point to an
1395602294fSDan Kimmel  * uncompressed version of the on-disk data.
1405602294fSDan Kimmel  *
1415602294fSDan Kimmel  * Data in the L1ARC is not accessed by consumers of the ARC directly. Each
1425602294fSDan Kimmel  * arc_buf_hdr_t can have multiple ARC buffers (arc_buf_t) which reference it.
1435602294fSDan Kimmel  * Each ARC buffer (arc_buf_t) is being actively accessed by a specific ARC
1445602294fSDan Kimmel  * consumer. The ARC will provide references to this data and will keep it
1455602294fSDan Kimmel  * cached until it is no longer in use. The ARC caches only the L1ARC's physical
1465602294fSDan Kimmel  * data block and will evict any arc_buf_t that is no longer referenced. The
1475602294fSDan Kimmel  * amount of memory consumed by the arc_buf_ts' data buffers can be seen via the
148dcbf3bd6SGeorge Wilson  * "overhead_size" kstat.
149dcbf3bd6SGeorge Wilson  *
1505602294fSDan Kimmel  * Depending on the consumer, an arc_buf_t can be requested in uncompressed or
1515602294fSDan Kimmel  * compressed form. The typical case is that consumers will want uncompressed
1525602294fSDan Kimmel  * data, and when that happens a new data buffer is allocated where the data is
1535602294fSDan Kimmel  * decompressed for them to use. Currently the only consumer who wants
1545602294fSDan Kimmel  * compressed arc_buf_t's is "zfs send", when it streams data exactly as it
1555602294fSDan Kimmel  * exists on disk. When this happens, the arc_buf_t's data buffer is shared
1565602294fSDan Kimmel  * with the arc_buf_hdr_t.
157dcbf3bd6SGeorge Wilson  *
1585602294fSDan Kimmel  * Here is a diagram showing an arc_buf_hdr_t referenced by two arc_buf_t's. The
1595602294fSDan Kimmel  * first one is owned by a compressed send consumer (and therefore references
1605602294fSDan Kimmel  * the same compressed data buffer as the arc_buf_hdr_t) and the second could be
1615602294fSDan Kimmel  * used by any other consumer (and has its own uncompressed copy of the data
1625602294fSDan Kimmel  * buffer).
163dcbf3bd6SGeorge Wilson  *
1645602294fSDan Kimmel  *   arc_buf_hdr_t
1655602294fSDan Kimmel  *   +-----------+
1665602294fSDan Kimmel  *   | fields    |
1675602294fSDan Kimmel  *   | common to |
1685602294fSDan Kimmel  *   | L1- and   |
1695602294fSDan Kimmel  *   | L2ARC     |
1705602294fSDan Kimmel  *   +-----------+
1715602294fSDan Kimmel  *   | l2arc_buf_hdr_t
1725602294fSDan Kimmel  *   |           |
1735602294fSDan Kimmel  *   +-----------+
1745602294fSDan Kimmel  *   | l1arc_buf_hdr_t
1755602294fSDan Kimmel  *   |           |              arc_buf_t
1765602294fSDan Kimmel  *   | b_buf     +------------>+-----------+      arc_buf_t
177*770499e1SDan Kimmel  *   | b_pabd    +-+           |b_next     +---->+-----------+
1785602294fSDan Kimmel  *   +-----------+ |           |-----------|     |b_next     +-->NULL
1795602294fSDan Kimmel  *                 |           |b_comp = T |     +-----------+
1805602294fSDan Kimmel  *                 |           |b_data     +-+   |b_comp = F |
1815602294fSDan Kimmel  *                 |           +-----------+ |   |b_data     +-+
1825602294fSDan Kimmel  *                 +->+------+               |   +-----------+ |
1835602294fSDan Kimmel  *        compressed  |      |               |                 |
1845602294fSDan Kimmel  *           data     |      |<--------------+                 | uncompressed
1855602294fSDan Kimmel  *                    +------+          compressed,            |     data
1865602294fSDan Kimmel  *                                        shared               +-->+------+
1875602294fSDan Kimmel  *                                         data                    |      |
1885602294fSDan Kimmel  *                                                                 |      |
1895602294fSDan Kimmel  *                                                                 +------+
190dcbf3bd6SGeorge Wilson  *
191dcbf3bd6SGeorge Wilson  * When a consumer reads a block, the ARC must first look to see if the
1925602294fSDan Kimmel  * arc_buf_hdr_t is cached. If the hdr is cached then the ARC allocates a new
1935602294fSDan Kimmel  * arc_buf_t and either copies uncompressed data into a new data buffer from an
194*770499e1SDan Kimmel  * existing uncompressed arc_buf_t, decompresses the hdr's b_pabd buffer into a
195*770499e1SDan Kimmel  * new data buffer, or shares the hdr's b_pabd buffer, depending on whether the
1965602294fSDan Kimmel  * hdr is compressed and the desired compression characteristics of the
1975602294fSDan Kimmel  * arc_buf_t consumer. If the arc_buf_t ends up sharing data with the
1985602294fSDan Kimmel  * arc_buf_hdr_t and both of them are uncompressed then the arc_buf_t must be
1995602294fSDan Kimmel  * the last buffer in the hdr's b_buf list, however a shared compressed buf can
2005602294fSDan Kimmel  * be anywhere in the hdr's list.
201dcbf3bd6SGeorge Wilson  *
202dcbf3bd6SGeorge Wilson  * The diagram below shows an example of an uncompressed ARC hdr that is
2035602294fSDan Kimmel  * sharing its data with an arc_buf_t (note that the shared uncompressed buf is
2045602294fSDan Kimmel  * the last element in the buf list):
205dcbf3bd6SGeorge Wilson  *
206dcbf3bd6SGeorge Wilson  *                arc_buf_hdr_t
207dcbf3bd6SGeorge Wilson  *                +-----------+
208dcbf3bd6SGeorge Wilson  *                |           |
209dcbf3bd6SGeorge Wilson  *                |           |
210dcbf3bd6SGeorge Wilson  *                |           |
211dcbf3bd6SGeorge Wilson  *                +-----------+
212dcbf3bd6SGeorge Wilson  * l2arc_buf_hdr_t|           |
213dcbf3bd6SGeorge Wilson  *                |           |
214dcbf3bd6SGeorge Wilson  *                +-----------+
215dcbf3bd6SGeorge Wilson  * l1arc_buf_hdr_t|           |
216dcbf3bd6SGeorge Wilson  *                |           |                 arc_buf_t    (shared)
217dcbf3bd6SGeorge Wilson  *                |    b_buf  +------------>+---------+      arc_buf_t
218dcbf3bd6SGeorge Wilson  *                |           |             |b_next   +---->+---------+
219*770499e1SDan Kimmel  *                |  b_pabd   +-+           |---------|     |b_next   +-->NULL
220dcbf3bd6SGeorge Wilson  *                +-----------+ |           |         |     +---------+
221dcbf3bd6SGeorge Wilson  *                              |           |b_data   +-+   |         |
222dcbf3bd6SGeorge Wilson  *                              |           +---------+ |   |b_data   +-+
223dcbf3bd6SGeorge Wilson  *                              +->+------+             |   +---------+ |
224dcbf3bd6SGeorge Wilson  *                                 |      |             |               |
225dcbf3bd6SGeorge Wilson  *                   uncompressed  |      |             |               |
226dcbf3bd6SGeorge Wilson  *                        data     +------+             |               |
227dcbf3bd6SGeorge Wilson  *                                    ^                 +->+------+     |
228dcbf3bd6SGeorge Wilson  *                                    |       uncompressed |      |     |
229dcbf3bd6SGeorge Wilson  *                                    |           data     |      |     |
230dcbf3bd6SGeorge Wilson  *                                    |                    +------+     |
231dcbf3bd6SGeorge Wilson  *                                    +---------------------------------+
232dcbf3bd6SGeorge Wilson  *
233*770499e1SDan Kimmel  * Writing to the ARC requires that the ARC first discard the hdr's b_pabd
234dcbf3bd6SGeorge Wilson  * since the physical block is about to be rewritten. The new data contents
2355602294fSDan Kimmel  * will be contained in the arc_buf_t. As the I/O pipeline performs the write,
2365602294fSDan Kimmel  * it may compress the data before writing it to disk. The ARC will be called
2375602294fSDan Kimmel  * with the transformed data and will bcopy the transformed on-disk block into
238*770499e1SDan Kimmel  * a newly allocated b_pabd. Writes are always done into buffers which have
2395602294fSDan Kimmel  * either been loaned (and hence are new and don't have other readers) or
2405602294fSDan Kimmel  * buffers which have been released (and hence have their own hdr, if there
2415602294fSDan Kimmel  * were originally other readers of the buf's original hdr). This ensures that
2425602294fSDan Kimmel  * the ARC only needs to update a single buf and its hdr after a write occurs.
243dcbf3bd6SGeorge Wilson  *
244*770499e1SDan Kimmel  * When the L2ARC is in use, it will also take advantage of the b_pabd. The
245*770499e1SDan Kimmel  * L2ARC will always write the contents of b_pabd to the L2ARC. This means
2465602294fSDan Kimmel  * that when compressed ARC is enabled that the L2ARC blocks are identical
247dcbf3bd6SGeorge Wilson  * to the on-disk block in the main data pool. This provides a significant
248dcbf3bd6SGeorge Wilson  * advantage since the ARC can leverage the bp's checksum when reading from the
249dcbf3bd6SGeorge Wilson  * L2ARC to determine if the contents are valid. However, if the compressed
2505602294fSDan Kimmel  * ARC is disabled, then the L2ARC's block must be transformed to look
251dcbf3bd6SGeorge Wilson  * like the physical block in the main data pool before comparing the
252dcbf3bd6SGeorge Wilson  * checksum and determining its validity.
253dcbf3bd6SGeorge Wilson  */
254dcbf3bd6SGeorge Wilson 
255fa9e4066Sahrens #include <sys/spa.h>
256fa9e4066Sahrens #include <sys/zio.h>
257dcbf3bd6SGeorge Wilson #include <sys/spa_impl.h>
258aad02571SSaso Kiselkov #include <sys/zio_compress.h>
259dcbf3bd6SGeorge Wilson #include <sys/zio_checksum.h>
260fa9e4066Sahrens #include <sys/zfs_context.h>
261fa9e4066Sahrens #include <sys/arc.h>
262fa9e4066Sahrens #include <sys/refcount.h>
263c5904d13Seschrock #include <sys/vdev.h>
264573ca77eSGeorge Wilson #include <sys/vdev_impl.h>
26569962b56SMatthew Ahrens #include <sys/dsl_pool.h>
266*770499e1SDan Kimmel #include <sys/zio_checksum.h>
267244781f1SPrakash Surya #include <sys/multilist.h>
268*770499e1SDan Kimmel #include <sys/abd.h>
269fa9e4066Sahrens #ifdef _KERNEL
270fa9e4066Sahrens #include <sys/vmsystm.h>
271fa9e4066Sahrens #include <vm/anon.h>
272fa9e4066Sahrens #include <sys/fs/swapnode.h>
273033f9833Sek #include <sys/dnlc.h>
274fa9e4066Sahrens #endif
275fa9e4066Sahrens #include <sys/callb.h>
27644cb6abcSbmc #include <sys/kstat.h>
277b24ab676SJeff Bonwick #include <zfs_fletcher.h>
278fa9e4066Sahrens 
279cd1c8b85SMatthew Ahrens #ifndef _KERNEL
280cd1c8b85SMatthew Ahrens /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
281cd1c8b85SMatthew Ahrens boolean_t arc_watch = B_FALSE;
282cd1c8b85SMatthew Ahrens int arc_procfd;
283cd1c8b85SMatthew Ahrens #endif
284cd1c8b85SMatthew Ahrens 
285244781f1SPrakash Surya static kmutex_t		arc_reclaim_lock;
286244781f1SPrakash Surya static kcondvar_t	arc_reclaim_thread_cv;
287244781f1SPrakash Surya static boolean_t	arc_reclaim_thread_exit;
288244781f1SPrakash Surya static kcondvar_t	arc_reclaim_waiters_cv;
289244781f1SPrakash Surya 
2902ec99e3eSMatthew Ahrens uint_t arc_reduce_dnlc_percent = 3;
291fa9e4066Sahrens 
29269962b56SMatthew Ahrens /*
293244781f1SPrakash Surya  * The number of headers to evict in arc_evict_state_impl() before
294244781f1SPrakash Surya  * dropping the sublist lock and evicting from another sublist. A lower
295244781f1SPrakash Surya  * value means we're more likely to evict the "correct" header (i.e. the
296244781f1SPrakash Surya  * oldest header in the arc state), but comes with higher overhead
297244781f1SPrakash Surya  * (i.e. more invocations of arc_evict_state_impl()).
298244781f1SPrakash Surya  */
299244781f1SPrakash Surya int zfs_arc_evict_batch_limit = 10;
300244781f1SPrakash Surya 
301fa9e4066Sahrens /* number of seconds before growing cache again */
302fa9e4066Sahrens static int		arc_grow_retry = 60;
303fa9e4066Sahrens 
304*770499e1SDan Kimmel /* shift of arc_c for calculating overflow limit in arc_get_data_impl */
305244781f1SPrakash Surya int		zfs_arc_overflow_shift = 8;
306244781f1SPrakash Surya 
3075a98e54bSBrendan Gregg - Sun Microsystems /* shift of arc_c for calculating both min and max arc_p */
3085a98e54bSBrendan Gregg - Sun Microsystems static int		arc_p_min_shift = 4;
3095a98e54bSBrendan Gregg - Sun Microsystems 
3105a98e54bSBrendan Gregg - Sun Microsystems /* log2(fraction of arc to reclaim) */
3112ec99e3eSMatthew Ahrens static int		arc_shrink_shift = 7;
3122ec99e3eSMatthew Ahrens 
3132ec99e3eSMatthew Ahrens /*
3142ec99e3eSMatthew Ahrens  * log2(fraction of ARC which must be free to allow growing).
3152ec99e3eSMatthew Ahrens  * I.e. If there is less than arc_c >> arc_no_grow_shift free memory,
3162ec99e3eSMatthew Ahrens  * when reading a new block into the ARC, we will evict an equal-sized block
3172ec99e3eSMatthew Ahrens  * from the ARC.
3182ec99e3eSMatthew Ahrens  *
3192ec99e3eSMatthew Ahrens  * This must be less than arc_shrink_shift, so that when we shrink the ARC,
3202ec99e3eSMatthew Ahrens  * we will still not allow it to grow.
3212ec99e3eSMatthew Ahrens  */
3222ec99e3eSMatthew Ahrens int			arc_no_grow_shift = 5;
3232ec99e3eSMatthew Ahrens 
3245a98e54bSBrendan Gregg - Sun Microsystems 
32513506d1eSmaybee /*
326b19a79ecSperrin  * minimum lifespan of a prefetch block in clock ticks
327b19a79ecSperrin  * (initialized in arc_init())
32813506d1eSmaybee  */
329b19a79ecSperrin static int		arc_min_prefetch_lifespan;
33013506d1eSmaybee 
33169962b56SMatthew Ahrens /*
33269962b56SMatthew Ahrens  * If this percent of memory is free, don't throttle.
33369962b56SMatthew Ahrens  */
33469962b56SMatthew Ahrens int arc_lotsfree_percent = 10;
33569962b56SMatthew Ahrens 
336fa9e4066Sahrens static int arc_dead;
337fa9e4066Sahrens 
3383a737e0dSbrendan /*
3393a737e0dSbrendan  * The arc has filled available memory and has now warmed up.
3403a737e0dSbrendan  */
3413a737e0dSbrendan static boolean_t arc_warm;
3423a737e0dSbrendan 
3430dd053d7SPrakash Surya /*
3440dd053d7SPrakash Surya  * log2 fraction of the zio arena to keep free.
3450dd053d7SPrakash Surya  */
3460dd053d7SPrakash Surya int arc_zio_arena_free_shift = 2;
3470dd053d7SPrakash Surya 
348a2eea2e1Sahrens /*
349a2eea2e1Sahrens  * These tunables are for performance analysis.
350a2eea2e1Sahrens  */
351a2eea2e1Sahrens uint64_t zfs_arc_max;
352a2eea2e1Sahrens uint64_t zfs_arc_min;
3531116048bSek uint64_t zfs_arc_meta_limit = 0;
3543a5286a1SMatthew Ahrens uint64_t zfs_arc_meta_min = 0;
3555a98e54bSBrendan Gregg - Sun Microsystems int zfs_arc_grow_retry = 0;
3565a98e54bSBrendan Gregg - Sun Microsystems int zfs_arc_shrink_shift = 0;
3575a98e54bSBrendan Gregg - Sun Microsystems int zfs_arc_p_min_shift = 0;
35863e911b6SMatthew Ahrens int zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
359a2eea2e1Sahrens 
360dcbf3bd6SGeorge Wilson boolean_t zfs_compressed_arc_enabled = B_TRUE;
361dcbf3bd6SGeorge Wilson 
362fa9e4066Sahrens /*
363fa94a07fSbrendan  * Note that buffers can be in one of 6 states:
364fa9e4066Sahrens  *	ARC_anon	- anonymous (discussed below)
365ea8dc4b6Seschrock  *	ARC_mru		- recently used, currently cached
366ea8dc4b6Seschrock  *	ARC_mru_ghost	- recentely used, no longer in cache
367ea8dc4b6Seschrock  *	ARC_mfu		- frequently used, currently cached
368ea8dc4b6Seschrock  *	ARC_mfu_ghost	- frequently used, no longer in cache
369fa94a07fSbrendan  *	ARC_l2c_only	- exists in L2ARC but not other states
3700e8c6158Smaybee  * When there are no active references to the buffer, they are
3710e8c6158Smaybee  * are linked onto a list in one of these arc states.  These are
3720e8c6158Smaybee  * the only buffers that can be evicted or deleted.  Within each
3730e8c6158Smaybee  * state there are multiple lists, one for meta-data and one for
3740e8c6158Smaybee  * non-meta-data.  Meta-data (indirect blocks, blocks of dnodes,
3750e8c6158Smaybee  * etc.) is tracked separately so that it can be managed more
376fa94a07fSbrendan  * explicitly: favored over data, limited explicitly.
377fa9e4066Sahrens  *
378fa9e4066Sahrens  * Anonymous buffers are buffers that are not associated with
379fa9e4066Sahrens  * a DVA.  These are buffers that hold dirty block copies
380fa9e4066Sahrens  * before they are written to stable storage.  By definition,
381ea8dc4b6Seschrock  * they are "ref'd" and are considered part of arc_mru
382fa9e4066Sahrens  * that cannot be freed.  Generally, they will aquire a DVA
383ea8dc4b6Seschrock  * as they are written and migrate onto the arc_mru list.
384fa94a07fSbrendan  *
385fa94a07fSbrendan  * The ARC_l2c_only state is for buffers that are in the second
386fa94a07fSbrendan  * level ARC but no longer in any of the ARC_m* lists.  The second
387fa94a07fSbrendan  * level ARC itself may also contain buffers that are in any of
388fa94a07fSbrendan  * the ARC_m* states - meaning that a buffer can exist in two
389fa94a07fSbrendan  * places.  The reason for the ARC_l2c_only state is to keep the
390fa94a07fSbrendan  * buffer header in the hash table, so that reads that hit the
391fa94a07fSbrendan  * second level ARC benefit from these fast lookups.
392fa9e4066Sahrens  */
393fa9e4066Sahrens 
394fa9e4066Sahrens typedef struct arc_state {
395244781f1SPrakash Surya 	/*
396244781f1SPrakash Surya 	 * list of evictable buffers
397244781f1SPrakash Surya 	 */
39894c2d0ebSMatthew Ahrens 	multilist_t *arcs_list[ARC_BUFC_NUMTYPES];
399244781f1SPrakash Surya 	/*
400244781f1SPrakash Surya 	 * total amount of evictable data in this state
401244781f1SPrakash Surya 	 */
402dcbf3bd6SGeorge Wilson 	refcount_t arcs_esize[ARC_BUFC_NUMTYPES];
403244781f1SPrakash Surya 	/*
404244781f1SPrakash Surya 	 * total amount of data in this state; this includes: evictable,
405244781f1SPrakash Surya 	 * non-evictable, ARC_BUFC_DATA, and ARC_BUFC_METADATA.
406244781f1SPrakash Surya 	 */
4072fd872a7SPrakash Surya 	refcount_t arcs_size;
408fa9e4066Sahrens } arc_state_t;
409fa9e4066Sahrens 
410fa94a07fSbrendan /* The 6 states: */
411fa9e4066Sahrens static arc_state_t ARC_anon;
412ea8dc4b6Seschrock static arc_state_t ARC_mru;
413ea8dc4b6Seschrock static arc_state_t ARC_mru_ghost;
414ea8dc4b6Seschrock static arc_state_t ARC_mfu;
415ea8dc4b6Seschrock static arc_state_t ARC_mfu_ghost;
416fa94a07fSbrendan static arc_state_t ARC_l2c_only;
417fa9e4066Sahrens 
41844cb6abcSbmc typedef struct arc_stats {
41944cb6abcSbmc 	kstat_named_t arcstat_hits;
42044cb6abcSbmc 	kstat_named_t arcstat_misses;
42144cb6abcSbmc 	kstat_named_t arcstat_demand_data_hits;
42244cb6abcSbmc 	kstat_named_t arcstat_demand_data_misses;
42344cb6abcSbmc 	kstat_named_t arcstat_demand_metadata_hits;
42444cb6abcSbmc 	kstat_named_t arcstat_demand_metadata_misses;
42544cb6abcSbmc 	kstat_named_t arcstat_prefetch_data_hits;
42644cb6abcSbmc 	kstat_named_t arcstat_prefetch_data_misses;
42744cb6abcSbmc 	kstat_named_t arcstat_prefetch_metadata_hits;
42844cb6abcSbmc 	kstat_named_t arcstat_prefetch_metadata_misses;
42944cb6abcSbmc 	kstat_named_t arcstat_mru_hits;
43044cb6abcSbmc 	kstat_named_t arcstat_mru_ghost_hits;
43144cb6abcSbmc 	kstat_named_t arcstat_mfu_hits;
43244cb6abcSbmc 	kstat_named_t arcstat_mfu_ghost_hits;
43344cb6abcSbmc 	kstat_named_t arcstat_deleted;
4343e30c24aSWill Andrews 	/*
4353e30c24aSWill Andrews 	 * Number of buffers that could not be evicted because the hash lock
4363e30c24aSWill Andrews 	 * was held by another thread.  The lock may not necessarily be held
4373e30c24aSWill Andrews 	 * by something using the same buffer, since hash locks are shared
4383e30c24aSWill Andrews 	 * by multiple buffers.
4393e30c24aSWill Andrews 	 */
44044cb6abcSbmc 	kstat_named_t arcstat_mutex_miss;
4413e30c24aSWill Andrews 	/*
4423e30c24aSWill Andrews 	 * Number of buffers skipped because they have I/O in progress, are
4433e30c24aSWill Andrews 	 * indrect prefetch buffers that have not lived long enough, or are
4443e30c24aSWill Andrews 	 * not from the spa we're trying to evict from.
4453e30c24aSWill Andrews 	 */
44644cb6abcSbmc 	kstat_named_t arcstat_evict_skip;
447244781f1SPrakash Surya 	/*
448244781f1SPrakash Surya 	 * Number of times arc_evict_state() was unable to evict enough
449244781f1SPrakash Surya 	 * buffers to reach it's target amount.
450244781f1SPrakash Surya 	 */
451244781f1SPrakash Surya 	kstat_named_t arcstat_evict_not_enough;
4525ea40c06SBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_evict_l2_cached;
4535ea40c06SBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_evict_l2_eligible;
4545ea40c06SBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_evict_l2_ineligible;
455244781f1SPrakash Surya 	kstat_named_t arcstat_evict_l2_skip;
45644cb6abcSbmc 	kstat_named_t arcstat_hash_elements;
45744cb6abcSbmc 	kstat_named_t arcstat_hash_elements_max;
45844cb6abcSbmc 	kstat_named_t arcstat_hash_collisions;
45944cb6abcSbmc 	kstat_named_t arcstat_hash_chains;
46044cb6abcSbmc 	kstat_named_t arcstat_hash_chain_max;
46144cb6abcSbmc 	kstat_named_t arcstat_p;
46244cb6abcSbmc 	kstat_named_t arcstat_c;
46344cb6abcSbmc 	kstat_named_t arcstat_c_min;
46444cb6abcSbmc 	kstat_named_t arcstat_c_max;
46544cb6abcSbmc 	kstat_named_t arcstat_size;
466dcbf3bd6SGeorge Wilson 	/*
467*770499e1SDan Kimmel 	 * Number of compressed bytes stored in the arc_buf_hdr_t's b_pabd.
468dcbf3bd6SGeorge Wilson 	 * Note that the compressed bytes may match the uncompressed bytes
469dcbf3bd6SGeorge Wilson 	 * if the block is either not compressed or compressed arc is disabled.
470dcbf3bd6SGeorge Wilson 	 */
471dcbf3bd6SGeorge Wilson 	kstat_named_t arcstat_compressed_size;
472dcbf3bd6SGeorge Wilson 	/*
473*770499e1SDan Kimmel 	 * Uncompressed size of the data stored in b_pabd. If compressed
474dcbf3bd6SGeorge Wilson 	 * arc is disabled then this value will be identical to the stat
475dcbf3bd6SGeorge Wilson 	 * above.
476dcbf3bd6SGeorge Wilson 	 */
477dcbf3bd6SGeorge Wilson 	kstat_named_t arcstat_uncompressed_size;
478dcbf3bd6SGeorge Wilson 	/*
479dcbf3bd6SGeorge Wilson 	 * Number of bytes stored in all the arc_buf_t's. This is classified
480dcbf3bd6SGeorge Wilson 	 * as "overhead" since this data is typically short-lived and will
481dcbf3bd6SGeorge Wilson 	 * be evicted from the arc when it becomes unreferenced unless the
482dcbf3bd6SGeorge Wilson 	 * zfs_keep_uncompressed_metadata or zfs_keep_uncompressed_level
483dcbf3bd6SGeorge Wilson 	 * values have been set (see comment in dbuf.c for more information).
484dcbf3bd6SGeorge Wilson 	 */
485dcbf3bd6SGeorge Wilson 	kstat_named_t arcstat_overhead_size;
4864076b1bfSPrakash Surya 	/*
4874076b1bfSPrakash Surya 	 * Number of bytes consumed by internal ARC structures necessary
4884076b1bfSPrakash Surya 	 * for tracking purposes; these structures are not actually
4894076b1bfSPrakash Surya 	 * backed by ARC buffers. This includes arc_buf_hdr_t structures
4904076b1bfSPrakash Surya 	 * (allocated via arc_buf_hdr_t_full and arc_buf_hdr_t_l2only
4914076b1bfSPrakash Surya 	 * caches), and arc_buf_t structures (allocated via arc_buf_t
4924076b1bfSPrakash Surya 	 * cache).
4934076b1bfSPrakash Surya 	 */
494fa94a07fSbrendan 	kstat_named_t arcstat_hdr_size;
4954076b1bfSPrakash Surya 	/*
4964076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers of type equal to
4974076b1bfSPrakash Surya 	 * ARC_BUFC_DATA. This is generally consumed by buffers backing
4984076b1bfSPrakash Surya 	 * on disk user data (e.g. plain file contents).
4994076b1bfSPrakash Surya 	 */
5005a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_data_size;
5014076b1bfSPrakash Surya 	/*
5024076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers of type equal to
5034076b1bfSPrakash Surya 	 * ARC_BUFC_METADATA. This is generally consumed by buffers
5044076b1bfSPrakash Surya 	 * backing on disk data that is used for internal ZFS
5054076b1bfSPrakash Surya 	 * structures (e.g. ZAP, dnode, indirect blocks, etc).
5064076b1bfSPrakash Surya 	 */
5074076b1bfSPrakash Surya 	kstat_named_t arcstat_metadata_size;
5084076b1bfSPrakash Surya 	/*
5094076b1bfSPrakash Surya 	 * Number of bytes consumed by various buffers and structures
5104076b1bfSPrakash Surya 	 * not actually backed with ARC buffers. This includes bonus
5114076b1bfSPrakash Surya 	 * buffers (allocated directly via zio_buf_* functions),
5124076b1bfSPrakash Surya 	 * dmu_buf_impl_t structures (allocated via dmu_buf_impl_t
5134076b1bfSPrakash Surya 	 * cache), and dnode_t structures (allocated via dnode_t cache).
5144076b1bfSPrakash Surya 	 */
5155a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_other_size;
5164076b1bfSPrakash Surya 	/*
5174076b1bfSPrakash Surya 	 * Total number of bytes consumed by ARC buffers residing in the
5184076b1bfSPrakash Surya 	 * arc_anon state. This includes *all* buffers in the arc_anon
5194076b1bfSPrakash Surya 	 * state; e.g. data, metadata, evictable, and unevictable buffers
5204076b1bfSPrakash Surya 	 * are all included in this value.
5214076b1bfSPrakash Surya 	 */
5224076b1bfSPrakash Surya 	kstat_named_t arcstat_anon_size;
5234076b1bfSPrakash Surya 	/*
5244076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
5254076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_DATA,
5264076b1bfSPrakash Surya 	 * residing in the arc_anon state, and are eligible for eviction
5274076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
5284076b1bfSPrakash Surya 	 */
5294076b1bfSPrakash Surya 	kstat_named_t arcstat_anon_evictable_data;
5304076b1bfSPrakash Surya 	/*
5314076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
5324076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_METADATA,
5334076b1bfSPrakash Surya 	 * residing in the arc_anon state, and are eligible for eviction
5344076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
5354076b1bfSPrakash Surya 	 */
5364076b1bfSPrakash Surya 	kstat_named_t arcstat_anon_evictable_metadata;
5374076b1bfSPrakash Surya 	/*
5384076b1bfSPrakash Surya 	 * Total number of bytes consumed by ARC buffers residing in the
5394076b1bfSPrakash Surya 	 * arc_mru state. This includes *all* buffers in the arc_mru
5404076b1bfSPrakash Surya 	 * state; e.g. data, metadata, evictable, and unevictable buffers
5414076b1bfSPrakash Surya 	 * are all included in this value.
5424076b1bfSPrakash Surya 	 */
5434076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_size;
5444076b1bfSPrakash Surya 	/*
5454076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
5464076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_DATA,
5474076b1bfSPrakash Surya 	 * residing in the arc_mru state, and are eligible for eviction
5484076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
5494076b1bfSPrakash Surya 	 */
5504076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_evictable_data;
5514076b1bfSPrakash Surya 	/*
5524076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
5534076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_METADATA,
5544076b1bfSPrakash Surya 	 * residing in the arc_mru state, and are eligible for eviction
5554076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
5564076b1bfSPrakash Surya 	 */
5574076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_evictable_metadata;
5584076b1bfSPrakash Surya 	/*
5594076b1bfSPrakash Surya 	 * Total number of bytes that *would have been* consumed by ARC
5604076b1bfSPrakash Surya 	 * buffers in the arc_mru_ghost state. The key thing to note
5614076b1bfSPrakash Surya 	 * here, is the fact that this size doesn't actually indicate
5624076b1bfSPrakash Surya 	 * RAM consumption. The ghost lists only consist of headers and
5634076b1bfSPrakash Surya 	 * don't actually have ARC buffers linked off of these headers.
5644076b1bfSPrakash Surya 	 * Thus, *if* the headers had associated ARC buffers, these
5654076b1bfSPrakash Surya 	 * buffers *would have* consumed this number of bytes.
5664076b1bfSPrakash Surya 	 */
5674076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_ghost_size;
5684076b1bfSPrakash Surya 	/*
5694076b1bfSPrakash Surya 	 * Number of bytes that *would have been* consumed by ARC
5704076b1bfSPrakash Surya 	 * buffers that are eligible for eviction, of type
5714076b1bfSPrakash Surya 	 * ARC_BUFC_DATA, and linked off the arc_mru_ghost state.
5724076b1bfSPrakash Surya 	 */
5734076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_ghost_evictable_data;
5744076b1bfSPrakash Surya 	/*
5754076b1bfSPrakash Surya 	 * Number of bytes that *would have been* consumed by ARC
5764076b1bfSPrakash Surya 	 * buffers that are eligible for eviction, of type
5774076b1bfSPrakash Surya 	 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
5784076b1bfSPrakash Surya 	 */
5794076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_ghost_evictable_metadata;
5804076b1bfSPrakash Surya 	/*
5814076b1bfSPrakash Surya 	 * Total number of bytes consumed by ARC buffers residing in the
5824076b1bfSPrakash Surya 	 * arc_mfu state. This includes *all* buffers in the arc_mfu
5834076b1bfSPrakash Surya 	 * state; e.g. data, metadata, evictable, and unevictable buffers
5844076b1bfSPrakash Surya 	 * are all included in this value.
5854076b1bfSPrakash Surya 	 */
5864076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_size;
5874076b1bfSPrakash Surya 	/*
5884076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that are eligible for
5894076b1bfSPrakash Surya 	 * eviction, of type ARC_BUFC_DATA, and reside in the arc_mfu
5904076b1bfSPrakash Surya 	 * state.
5914076b1bfSPrakash Surya 	 */
5924076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_evictable_data;
5934076b1bfSPrakash Surya 	/*
5944076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that are eligible for
5954076b1bfSPrakash Surya 	 * eviction, of type ARC_BUFC_METADATA, and reside in the
5964076b1bfSPrakash Surya 	 * arc_mfu state.
5974076b1bfSPrakash Surya 	 */
5984076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_evictable_metadata;
5994076b1bfSPrakash Surya 	/*
6004076b1bfSPrakash Surya 	 * Total number of bytes that *would have been* consumed by ARC
6014076b1bfSPrakash Surya 	 * buffers in the arc_mfu_ghost state. See the comment above
6024076b1bfSPrakash Surya 	 * arcstat_mru_ghost_size for more details.
6034076b1bfSPrakash Surya 	 */
6044076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_ghost_size;
6054076b1bfSPrakash Surya 	/*
6064076b1bfSPrakash Surya 	 * Number of bytes that *would have been* consumed by ARC
6074076b1bfSPrakash Surya 	 * buffers that are eligible for eviction, of type
6084076b1bfSPrakash Surya 	 * ARC_BUFC_DATA, and linked off the arc_mfu_ghost state.
6094076b1bfSPrakash Surya 	 */
6104076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_ghost_evictable_data;
6114076b1bfSPrakash Surya 	/*
6124076b1bfSPrakash Surya 	 * Number of bytes that *would have been* consumed by ARC
6134076b1bfSPrakash Surya 	 * buffers that are eligible for eviction, of type
6144076b1bfSPrakash Surya 	 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
6154076b1bfSPrakash Surya 	 */
6164076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_ghost_evictable_metadata;
617fa94a07fSbrendan 	kstat_named_t arcstat_l2_hits;
618fa94a07fSbrendan 	kstat_named_t arcstat_l2_misses;
619fa94a07fSbrendan 	kstat_named_t arcstat_l2_feeds;
620fa94a07fSbrendan 	kstat_named_t arcstat_l2_rw_clash;
6215a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_l2_read_bytes;
6225a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_l2_write_bytes;
623fa94a07fSbrendan 	kstat_named_t arcstat_l2_writes_sent;
624fa94a07fSbrendan 	kstat_named_t arcstat_l2_writes_done;
625fa94a07fSbrendan 	kstat_named_t arcstat_l2_writes_error;
626244781f1SPrakash Surya 	kstat_named_t arcstat_l2_writes_lock_retry;
627fa94a07fSbrendan 	kstat_named_t arcstat_l2_evict_lock_retry;
628fa94a07fSbrendan 	kstat_named_t arcstat_l2_evict_reading;
62989c86e32SChris Williamson 	kstat_named_t arcstat_l2_evict_l1cached;
630fa94a07fSbrendan 	kstat_named_t arcstat_l2_free_on_write;
631fa94a07fSbrendan 	kstat_named_t arcstat_l2_abort_lowmem;
632fa94a07fSbrendan 	kstat_named_t arcstat_l2_cksum_bad;
633fa94a07fSbrendan 	kstat_named_t arcstat_l2_io_error;
634fa94a07fSbrendan 	kstat_named_t arcstat_l2_size;
635aad02571SSaso Kiselkov 	kstat_named_t arcstat_l2_asize;
636fa94a07fSbrendan 	kstat_named_t arcstat_l2_hdr_size;
6371ab7f2deSmaybee 	kstat_named_t arcstat_memory_throttle_count;
63820128a08SGeorge Wilson 	kstat_named_t arcstat_meta_used;
63920128a08SGeorge Wilson 	kstat_named_t arcstat_meta_limit;
64020128a08SGeorge Wilson 	kstat_named_t arcstat_meta_max;
6413a5286a1SMatthew Ahrens 	kstat_named_t arcstat_meta_min;
642cf6106c8SMatthew Ahrens 	kstat_named_t arcstat_sync_wait_for_async;
643cf6106c8SMatthew Ahrens 	kstat_named_t arcstat_demand_hit_predictive_prefetch;
64444cb6abcSbmc } arc_stats_t;
64544cb6abcSbmc 
64644cb6abcSbmc static arc_stats_t arc_stats = {
64744cb6abcSbmc 	{ "hits",			KSTAT_DATA_UINT64 },
64844cb6abcSbmc 	{ "misses",			KSTAT_DATA_UINT64 },
64944cb6abcSbmc 	{ "demand_data_hits",		KSTAT_DATA_UINT64 },
65044cb6abcSbmc 	{ "demand_data_misses",		KSTAT_DATA_UINT64 },
65144cb6abcSbmc 	{ "demand_metadata_hits",	KSTAT_DATA_UINT64 },
65244cb6abcSbmc 	{ "demand_metadata_misses",	KSTAT_DATA_UINT64 },
65344cb6abcSbmc 	{ "prefetch_data_hits",		KSTAT_DATA_UINT64 },
65444cb6abcSbmc 	{ "prefetch_data_misses",	KSTAT_DATA_UINT64 },
65544cb6abcSbmc 	{ "prefetch_metadata_hits",	KSTAT_DATA_UINT64 },
65644cb6abcSbmc 	{ "prefetch_metadata_misses",	KSTAT_DATA_UINT64 },
65744cb6abcSbmc 	{ "mru_hits",			KSTAT_DATA_UINT64 },
65844cb6abcSbmc 	{ "mru_ghost_hits",		KSTAT_DATA_UINT64 },
65944cb6abcSbmc 	{ "mfu_hits",			KSTAT_DATA_UINT64 },
66044cb6abcSbmc 	{ "mfu_ghost_hits",		KSTAT_DATA_UINT64 },
66144cb6abcSbmc 	{ "deleted",			KSTAT_DATA_UINT64 },
66244cb6abcSbmc 	{ "mutex_miss",			KSTAT_DATA_UINT64 },
66344cb6abcSbmc 	{ "evict_skip",			KSTAT_DATA_UINT64 },
664244781f1SPrakash Surya 	{ "evict_not_enough",		KSTAT_DATA_UINT64 },
6655ea40c06SBrendan Gregg - Sun Microsystems 	{ "evict_l2_cached",		KSTAT_DATA_UINT64 },
6665ea40c06SBrendan Gregg - Sun Microsystems 	{ "evict_l2_eligible",		KSTAT_DATA_UINT64 },
6675ea40c06SBrendan Gregg - Sun Microsystems 	{ "evict_l2_ineligible",	KSTAT_DATA_UINT64 },
668244781f1SPrakash Surya 	{ "evict_l2_skip",		KSTAT_DATA_UINT64 },
66944cb6abcSbmc 	{ "hash_elements",		KSTAT_DATA_UINT64 },
67044cb6abcSbmc 	{ "hash_elements_max",		KSTAT_DATA_UINT64 },
67144cb6abcSbmc 	{ "hash_collisions",		KSTAT_DATA_UINT64 },
67244cb6abcSbmc 	{ "hash_chains",		KSTAT_DATA_UINT64 },
67344cb6abcSbmc 	{ "hash_chain_max",		KSTAT_DATA_UINT64 },
67444cb6abcSbmc 	{ "p",				KSTAT_DATA_UINT64 },
67544cb6abcSbmc 	{ "c",				KSTAT_DATA_UINT64 },
67644cb6abcSbmc 	{ "c_min",			KSTAT_DATA_UINT64 },
67744cb6abcSbmc 	{ "c_max",			KSTAT_DATA_UINT64 },
678fa94a07fSbrendan 	{ "size",			KSTAT_DATA_UINT64 },
679dcbf3bd6SGeorge Wilson 	{ "compressed_size",		KSTAT_DATA_UINT64 },
680dcbf3bd6SGeorge Wilson 	{ "uncompressed_size",		KSTAT_DATA_UINT64 },
681dcbf3bd6SGeorge Wilson 	{ "overhead_size",		KSTAT_DATA_UINT64 },
682fa94a07fSbrendan 	{ "hdr_size",			KSTAT_DATA_UINT64 },
6835a98e54bSBrendan Gregg - Sun Microsystems 	{ "data_size",			KSTAT_DATA_UINT64 },
6844076b1bfSPrakash Surya 	{ "metadata_size",		KSTAT_DATA_UINT64 },
6855a98e54bSBrendan Gregg - Sun Microsystems 	{ "other_size",			KSTAT_DATA_UINT64 },
6864076b1bfSPrakash Surya 	{ "anon_size",			KSTAT_DATA_UINT64 },
6874076b1bfSPrakash Surya 	{ "anon_evictable_data",	KSTAT_DATA_UINT64 },
6884076b1bfSPrakash Surya 	{ "anon_evictable_metadata",	KSTAT_DATA_UINT64 },
6894076b1bfSPrakash Surya 	{ "mru_size",			KSTAT_DATA_UINT64 },
6904076b1bfSPrakash Surya 	{ "mru_evictable_data",		KSTAT_DATA_UINT64 },
6914076b1bfSPrakash Surya 	{ "mru_evictable_metadata",	KSTAT_DATA_UINT64 },
6924076b1bfSPrakash Surya 	{ "mru_ghost_size",		KSTAT_DATA_UINT64 },
6934076b1bfSPrakash Surya 	{ "mru_ghost_evictable_data",	KSTAT_DATA_UINT64 },
6944076b1bfSPrakash Surya 	{ "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
6954076b1bfSPrakash Surya 	{ "mfu_size",			KSTAT_DATA_UINT64 },
6964076b1bfSPrakash Surya 	{ "mfu_evictable_data",		KSTAT_DATA_UINT64 },
6974076b1bfSPrakash Surya 	{ "mfu_evictable_metadata",	KSTAT_DATA_UINT64 },
6984076b1bfSPrakash Surya 	{ "mfu_ghost_size",		KSTAT_DATA_UINT64 },
6994076b1bfSPrakash Surya 	{ "mfu_ghost_evictable_data",	KSTAT_DATA_UINT64 },
7004076b1bfSPrakash Surya 	{ "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
701fa94a07fSbrendan 	{ "l2_hits",			KSTAT_DATA_UINT64 },
702fa94a07fSbrendan 	{ "l2_misses",			KSTAT_DATA_UINT64 },
703fa94a07fSbrendan 	{ "l2_feeds",			KSTAT_DATA_UINT64 },
704fa94a07fSbrendan 	{ "l2_rw_clash",		KSTAT_DATA_UINT64 },
7055a98e54bSBrendan Gregg - Sun Microsystems 	{ "l2_read_bytes",		KSTAT_DATA_UINT64 },
7065a98e54bSBrendan Gregg - Sun Microsystems 	{ "l2_write_bytes",		KSTAT_DATA_UINT64 },
707fa94a07fSbrendan 	{ "l2_writes_sent",		KSTAT_DATA_UINT64 },
708fa94a07fSbrendan 	{ "l2_writes_done",		KSTAT_DATA_UINT64 },
709fa94a07fSbrendan 	{ "l2_writes_error",		KSTAT_DATA_UINT64 },
710244781f1SPrakash Surya 	{ "l2_writes_lock_retry",	KSTAT_DATA_UINT64 },
711fa94a07fSbrendan 	{ "l2_evict_lock_retry",	KSTAT_DATA_UINT64 },
712fa94a07fSbrendan 	{ "l2_evict_reading",		KSTAT_DATA_UINT64 },
71389c86e32SChris Williamson 	{ "l2_evict_l1cached",		KSTAT_DATA_UINT64 },
714fa94a07fSbrendan 	{ "l2_free_on_write",		KSTAT_DATA_UINT64 },
715fa94a07fSbrendan 	{ "l2_abort_lowmem",		KSTAT_DATA_UINT64 },
716fa94a07fSbrendan 	{ "l2_cksum_bad",		KSTAT_DATA_UINT64 },
717fa94a07fSbrendan 	{ "l2_io_error",		KSTAT_DATA_UINT64 },
718fa94a07fSbrendan 	{ "l2_size",			KSTAT_DATA_UINT64 },
719aad02571SSaso Kiselkov 	{ "l2_asize",			KSTAT_DATA_UINT64 },
7201ab7f2deSmaybee 	{ "l2_hdr_size",		KSTAT_DATA_UINT64 },
7219253d63dSGeorge Wilson 	{ "memory_throttle_count",	KSTAT_DATA_UINT64 },
72220128a08SGeorge Wilson 	{ "arc_meta_used",		KSTAT_DATA_UINT64 },
72320128a08SGeorge Wilson 	{ "arc_meta_limit",		KSTAT_DATA_UINT64 },
7243a5286a1SMatthew Ahrens 	{ "arc_meta_max",		KSTAT_DATA_UINT64 },
725cf6106c8SMatthew Ahrens 	{ "arc_meta_min",		KSTAT_DATA_UINT64 },
726cf6106c8SMatthew Ahrens 	{ "sync_wait_for_async",	KSTAT_DATA_UINT64 },
727cf6106c8SMatthew Ahrens 	{ "demand_hit_predictive_prefetch", KSTAT_DATA_UINT64 },
72844cb6abcSbmc };
72944cb6abcSbmc 
73044cb6abcSbmc #define	ARCSTAT(stat)	(arc_stats.stat.value.ui64)
73144cb6abcSbmc 
73244cb6abcSbmc #define	ARCSTAT_INCR(stat, val) \
733f7170741SWill Andrews 	atomic_add_64(&arc_stats.stat.value.ui64, (val))
73444cb6abcSbmc 
735b24ab676SJeff Bonwick #define	ARCSTAT_BUMP(stat)	ARCSTAT_INCR(stat, 1)
73644cb6abcSbmc #define	ARCSTAT_BUMPDOWN(stat)	ARCSTAT_INCR(stat, -1)
73744cb6abcSbmc 
73844cb6abcSbmc #define	ARCSTAT_MAX(stat, val) {					\
73944cb6abcSbmc 	uint64_t m;							\
74044cb6abcSbmc 	while ((val) > (m = arc_stats.stat.value.ui64) &&		\
74144cb6abcSbmc 	    (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val))))	\
74244cb6abcSbmc 		continue;						\
74344cb6abcSbmc }
74444cb6abcSbmc 
74544cb6abcSbmc #define	ARCSTAT_MAXSTAT(stat) \
74644cb6abcSbmc 	ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
74744cb6abcSbmc 
74844cb6abcSbmc /*
74944cb6abcSbmc  * We define a macro to allow ARC hits/misses to be easily broken down by
75044cb6abcSbmc  * two separate conditions, giving a total of four different subtypes for
75144cb6abcSbmc  * each of hits and misses (so eight statistics total).
75244cb6abcSbmc  */
75344cb6abcSbmc #define	ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
75444cb6abcSbmc 	if (cond1) {							\
75544cb6abcSbmc 		if (cond2) {						\
75644cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
75744cb6abcSbmc 		} else {						\
75844cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
75944cb6abcSbmc 		}							\
76044cb6abcSbmc 	} else {							\
76144cb6abcSbmc 		if (cond2) {						\
76244cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
76344cb6abcSbmc 		} else {						\
76444cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
76544cb6abcSbmc 		}							\
76644cb6abcSbmc 	}
76744cb6abcSbmc 
76844cb6abcSbmc kstat_t			*arc_ksp;
769b24ab676SJeff Bonwick static arc_state_t	*arc_anon;
77044cb6abcSbmc static arc_state_t	*arc_mru;
77144cb6abcSbmc static arc_state_t	*arc_mru_ghost;
77244cb6abcSbmc static arc_state_t	*arc_mfu;
77344cb6abcSbmc static arc_state_t	*arc_mfu_ghost;
774fa94a07fSbrendan static arc_state_t	*arc_l2c_only;
77544cb6abcSbmc 
77644cb6abcSbmc /*
77744cb6abcSbmc  * There are several ARC variables that are critical to export as kstats --
77844cb6abcSbmc  * but we don't want to have to grovel around in the kstat whenever we wish to
77944cb6abcSbmc  * manipulate them.  For these variables, we therefore define them to be in
78044cb6abcSbmc  * terms of the statistic variable.  This assures that we are not introducing
78144cb6abcSbmc  * the possibility of inconsistency by having shadow copies of the variables,
78244cb6abcSbmc  * while still allowing the code to be readable.
78344cb6abcSbmc  */
78444cb6abcSbmc #define	arc_size	ARCSTAT(arcstat_size)	/* actual total arc size */
78544cb6abcSbmc #define	arc_p		ARCSTAT(arcstat_p)	/* target size of MRU */
78644cb6abcSbmc #define	arc_c		ARCSTAT(arcstat_c)	/* target size of cache */
78744cb6abcSbmc #define	arc_c_min	ARCSTAT(arcstat_c_min)	/* min target cache size */
78844cb6abcSbmc #define	arc_c_max	ARCSTAT(arcstat_c_max)	/* max target cache size */
78920128a08SGeorge Wilson #define	arc_meta_limit	ARCSTAT(arcstat_meta_limit) /* max size for metadata */
7903a5286a1SMatthew Ahrens #define	arc_meta_min	ARCSTAT(arcstat_meta_min) /* min size for metadata */
79120128a08SGeorge Wilson #define	arc_meta_used	ARCSTAT(arcstat_meta_used) /* size of metadata */
79220128a08SGeorge Wilson #define	arc_meta_max	ARCSTAT(arcstat_meta_max) /* max size of metadata */
79344cb6abcSbmc 
794dcbf3bd6SGeorge Wilson /* compressed size of entire arc */
795dcbf3bd6SGeorge Wilson #define	arc_compressed_size	ARCSTAT(arcstat_compressed_size)
796dcbf3bd6SGeorge Wilson /* uncompressed size of entire arc */
797dcbf3bd6SGeorge Wilson #define	arc_uncompressed_size	ARCSTAT(arcstat_uncompressed_size)
798dcbf3bd6SGeorge Wilson /* number of bytes in the arc from arc_buf_t's */
799dcbf3bd6SGeorge Wilson #define	arc_overhead_size	ARCSTAT(arcstat_overhead_size)
800aad02571SSaso Kiselkov 
80144cb6abcSbmc static int		arc_no_grow;	/* Don't try to grow cache size */
80244cb6abcSbmc static uint64_t		arc_tempreserve;
8032fdbea25SAleksandr Guzovskiy static uint64_t		arc_loaned_bytes;
804fa9e4066Sahrens 
805fa9e4066Sahrens typedef struct arc_callback arc_callback_t;
806fa9e4066Sahrens 
807fa9e4066Sahrens struct arc_callback {
808fa9e4066Sahrens 	void			*acb_private;
809c717a561Smaybee 	arc_done_func_t		*acb_done;
810fa9e4066Sahrens 	arc_buf_t		*acb_buf;
8115602294fSDan Kimmel 	boolean_t		acb_compressed;
812fa9e4066Sahrens 	zio_t			*acb_zio_dummy;
813fa9e4066Sahrens 	arc_callback_t		*acb_next;
814fa9e4066Sahrens };
815fa9e4066Sahrens 
816c717a561Smaybee typedef struct arc_write_callback arc_write_callback_t;
817c717a561Smaybee 
818c717a561Smaybee struct arc_write_callback {
819c717a561Smaybee 	void		*awcb_private;
820c717a561Smaybee 	arc_done_func_t	*awcb_ready;
8218df0bcf0SPaul Dagnelie 	arc_done_func_t	*awcb_children_ready;
82269962b56SMatthew Ahrens 	arc_done_func_t	*awcb_physdone;
823c717a561Smaybee 	arc_done_func_t	*awcb_done;
824c717a561Smaybee 	arc_buf_t	*awcb_buf;
825c717a561Smaybee };
826c717a561Smaybee 
82789c86e32SChris Williamson /*
82889c86e32SChris Williamson  * ARC buffers are separated into multiple structs as a memory saving measure:
82989c86e32SChris Williamson  *   - Common fields struct, always defined, and embedded within it:
83089c86e32SChris Williamson  *       - L2-only fields, always allocated but undefined when not in L2ARC
83189c86e32SChris Williamson  *       - L1-only fields, only allocated when in L1ARC
83289c86e32SChris Williamson  *
83389c86e32SChris Williamson  *           Buffer in L1                     Buffer only in L2
83489c86e32SChris Williamson  *    +------------------------+          +------------------------+
83589c86e32SChris Williamson  *    | arc_buf_hdr_t          |          | arc_buf_hdr_t          |
83689c86e32SChris Williamson  *    |                        |          |                        |
83789c86e32SChris Williamson  *    |                        |          |                        |
83889c86e32SChris Williamson  *    |                        |          |                        |
83989c86e32SChris Williamson  *    +------------------------+          +------------------------+
84089c86e32SChris Williamson  *    | l2arc_buf_hdr_t        |          | l2arc_buf_hdr_t        |
84189c86e32SChris Williamson  *    | (undefined if L1-only) |          |                        |
84289c86e32SChris Williamson  *    +------------------------+          +------------------------+
84389c86e32SChris Williamson  *    | l1arc_buf_hdr_t        |
84489c86e32SChris Williamson  *    |                        |
84589c86e32SChris Williamson  *    |                        |
84689c86e32SChris Williamson  *    |                        |
84789c86e32SChris Williamson  *    |                        |
84889c86e32SChris Williamson  *    +------------------------+
84989c86e32SChris Williamson  *
85089c86e32SChris Williamson  * Because it's possible for the L2ARC to become extremely large, we can wind
85189c86e32SChris Williamson  * up eating a lot of memory in L2ARC buffer headers, so the size of a header
85289c86e32SChris Williamson  * is minimized by only allocating the fields necessary for an L1-cached buffer
85389c86e32SChris Williamson  * when a header is actually in the L1 cache. The sub-headers (l1arc_buf_hdr and
85489c86e32SChris Williamson  * l2arc_buf_hdr) are embedded rather than allocated separately to save a couple
85589c86e32SChris Williamson  * words in pointers. arc_hdr_realloc() is used to switch a header between
85689c86e32SChris Williamson  * these two allocation states.
85789c86e32SChris Williamson  */
85889c86e32SChris Williamson typedef struct l1arc_buf_hdr {
8596b4acc8bSahrens 	kmutex_t		b_freeze_lock;
860dcbf3bd6SGeorge Wilson 	zio_cksum_t		*b_freeze_cksum;
86189c86e32SChris Williamson #ifdef ZFS_DEBUG
86289c86e32SChris Williamson 	/*
8635602294fSDan Kimmel 	 * Used for debugging with kmem_flags - by allocating and freeing
86489c86e32SChris Williamson 	 * b_thawed when the buffer is thawed, we get a record of the stack
86589c86e32SChris Williamson 	 * trace that thawed it.
86689c86e32SChris Williamson 	 */
8673f9d6ad7SLin Ling 	void			*b_thawed;
86889c86e32SChris Williamson #endif
8696b4acc8bSahrens 
870fa9e4066Sahrens 	arc_buf_t		*b_buf;
871dcbf3bd6SGeorge Wilson 	uint32_t		b_bufcnt;
87289c86e32SChris Williamson 	/* for waiting on writes to complete */
873ad23a2dbSjohansen 	kcondvar_t		b_cv;
874dcbf3bd6SGeorge Wilson 	uint8_t			b_byteswap;
875ad23a2dbSjohansen 
876fa9e4066Sahrens 	/* protected by arc state mutex */
877fa9e4066Sahrens 	arc_state_t		*b_state;
878244781f1SPrakash Surya 	multilist_node_t	b_arc_node;
879fa9e4066Sahrens 
880fa9e4066Sahrens 	/* updated atomically */
881fa9e4066Sahrens 	clock_t			b_arc_access;
882fa9e4066Sahrens 
883fa9e4066Sahrens 	/* self protecting */
884fa9e4066Sahrens 	refcount_t		b_refcnt;
885fa94a07fSbrendan 
88689c86e32SChris Williamson 	arc_callback_t		*b_acb;
887*770499e1SDan Kimmel 	abd_t			*b_pabd;
88889c86e32SChris Williamson } l1arc_buf_hdr_t;
88989c86e32SChris Williamson 
89089c86e32SChris Williamson typedef struct l2arc_dev l2arc_dev_t;
89189c86e32SChris Williamson 
89289c86e32SChris Williamson typedef struct l2arc_buf_hdr {
89389c86e32SChris Williamson 	/* protected by arc_buf_hdr mutex */
89489c86e32SChris Williamson 	l2arc_dev_t		*b_dev;		/* L2ARC device */
89589c86e32SChris Williamson 	uint64_t		b_daddr;	/* disk address, offset byte */
89689c86e32SChris Williamson 
897fa94a07fSbrendan 	list_node_t		b_l2node;
89889c86e32SChris Williamson } l2arc_buf_hdr_t;
89989c86e32SChris Williamson 
90089c86e32SChris Williamson struct arc_buf_hdr {
90189c86e32SChris Williamson 	/* protected by hash lock */
90289c86e32SChris Williamson 	dva_t			b_dva;
90389c86e32SChris Williamson 	uint64_t		b_birth;
90489c86e32SChris Williamson 
905dcbf3bd6SGeorge Wilson 	arc_buf_contents_t	b_type;
90689c86e32SChris Williamson 	arc_buf_hdr_t		*b_hash_next;
90789c86e32SChris Williamson 	arc_flags_t		b_flags;
90889c86e32SChris Williamson 
909dcbf3bd6SGeorge Wilson 	/*
910dcbf3bd6SGeorge Wilson 	 * This field stores the size of the data buffer after
911dcbf3bd6SGeorge Wilson 	 * compression, and is set in the arc's zio completion handlers.
912dcbf3bd6SGeorge Wilson 	 * It is in units of SPA_MINBLOCKSIZE (e.g. 1 == 512 bytes).
913dcbf3bd6SGeorge Wilson 	 *
914dcbf3bd6SGeorge Wilson 	 * While the block pointers can store up to 32MB in their psize
915dcbf3bd6SGeorge Wilson 	 * field, we can only store up to 32MB minus 512B. This is due
916dcbf3bd6SGeorge Wilson 	 * to the bp using a bias of 1, whereas we use a bias of 0 (i.e.
917dcbf3bd6SGeorge Wilson 	 * a field of zeros represents 512B in the bp). We can't use a
918dcbf3bd6SGeorge Wilson 	 * bias of 1 since we need to reserve a psize of zero, here, to
919dcbf3bd6SGeorge Wilson 	 * represent holes and embedded blocks.
920dcbf3bd6SGeorge Wilson 	 *
921dcbf3bd6SGeorge Wilson 	 * This isn't a problem in practice, since the maximum size of a
922dcbf3bd6SGeorge Wilson 	 * buffer is limited to 16MB, so we never need to store 32MB in
923dcbf3bd6SGeorge Wilson 	 * this field. Even in the upstream illumos code base, the
924dcbf3bd6SGeorge Wilson 	 * maximum size of a buffer is limited to 16MB.
925dcbf3bd6SGeorge Wilson 	 */
926dcbf3bd6SGeorge Wilson 	uint16_t		b_psize;
927dcbf3bd6SGeorge Wilson 
928dcbf3bd6SGeorge Wilson 	/*
929dcbf3bd6SGeorge Wilson 	 * This field stores the size of the data buffer before
930dcbf3bd6SGeorge Wilson 	 * compression, and cannot change once set. It is in units
931dcbf3bd6SGeorge Wilson 	 * of SPA_MINBLOCKSIZE (e.g. 2 == 1024 bytes)
932dcbf3bd6SGeorge Wilson 	 */
933dcbf3bd6SGeorge Wilson 	uint16_t		b_lsize;	/* immutable */
934dcbf3bd6SGeorge Wilson 	uint64_t		b_spa;		/* immutable */
93589c86e32SChris Williamson 
93689c86e32SChris Williamson 	/* L2ARC fields. Undefined when not in L2ARC. */
93789c86e32SChris Williamson 	l2arc_buf_hdr_t		b_l2hdr;
93889c86e32SChris Williamson 	/* L1ARC fields. Undefined when in l2arc_only state */
93989c86e32SChris Williamson 	l1arc_buf_hdr_t		b_l1hdr;
940fa9e4066Sahrens };
941fa9e4066Sahrens 
942ea8dc4b6Seschrock #define	GHOST_STATE(state)	\
943fa94a07fSbrendan 	((state) == arc_mru_ghost || (state) == arc_mfu_ghost ||	\
944fa94a07fSbrendan 	(state) == arc_l2c_only)
945ea8dc4b6Seschrock 
9467adb730bSGeorge Wilson #define	HDR_IN_HASH_TABLE(hdr)	((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
9477adb730bSGeorge Wilson #define	HDR_IO_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
9487adb730bSGeorge Wilson #define	HDR_IO_ERROR(hdr)	((hdr)->b_flags & ARC_FLAG_IO_ERROR)
9497adb730bSGeorge Wilson #define	HDR_PREFETCH(hdr)	((hdr)->b_flags & ARC_FLAG_PREFETCH)
950dcbf3bd6SGeorge Wilson #define	HDR_COMPRESSION_ENABLED(hdr)	\
951dcbf3bd6SGeorge Wilson 	((hdr)->b_flags & ARC_FLAG_COMPRESSED_ARC)
95289c86e32SChris Williamson 
9537adb730bSGeorge Wilson #define	HDR_L2CACHE(hdr)	((hdr)->b_flags & ARC_FLAG_L2CACHE)
9547adb730bSGeorge Wilson #define	HDR_L2_READING(hdr)	\
955dcbf3bd6SGeorge Wilson 	(((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) &&	\
956dcbf3bd6SGeorge Wilson 	((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
9577adb730bSGeorge Wilson #define	HDR_L2_WRITING(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITING)
9587adb730bSGeorge Wilson #define	HDR_L2_EVICTED(hdr)	((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
9597adb730bSGeorge Wilson #define	HDR_L2_WRITE_HEAD(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
960dcbf3bd6SGeorge Wilson #define	HDR_SHARED_DATA(hdr)	((hdr)->b_flags & ARC_FLAG_SHARED_DATA)
961fa9e4066Sahrens 
96289c86e32SChris Williamson #define	HDR_ISTYPE_METADATA(hdr)	\
963dcbf3bd6SGeorge Wilson 	((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
96489c86e32SChris Williamson #define	HDR_ISTYPE_DATA(hdr)	(!HDR_ISTYPE_METADATA(hdr))
96589c86e32SChris Williamson 
96689c86e32SChris Williamson #define	HDR_HAS_L1HDR(hdr)	((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
96789c86e32SChris Williamson #define	HDR_HAS_L2HDR(hdr)	((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
96889c86e32SChris Williamson 
969dcbf3bd6SGeorge Wilson /* For storing compression mode in b_flags */
970dcbf3bd6SGeorge Wilson #define	HDR_COMPRESS_OFFSET	(highbit64(ARC_FLAG_COMPRESS_0) - 1)
971dcbf3bd6SGeorge Wilson 
972dcbf3bd6SGeorge Wilson #define	HDR_GET_COMPRESS(hdr)	((enum zio_compress)BF32_GET((hdr)->b_flags, \
973dcbf3bd6SGeorge Wilson 	HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS))
974dcbf3bd6SGeorge Wilson #define	HDR_SET_COMPRESS(hdr, cmp) BF32_SET((hdr)->b_flags, \
975dcbf3bd6SGeorge Wilson 	HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS, (cmp));
976dcbf3bd6SGeorge Wilson 
977dcbf3bd6SGeorge Wilson #define	ARC_BUF_LAST(buf)	((buf)->b_next == NULL)
9785602294fSDan Kimmel #define	ARC_BUF_SHARED(buf)	((buf)->b_flags & ARC_BUF_FLAG_SHARED)
9795602294fSDan Kimmel #define	ARC_BUF_COMPRESSED(buf)	((buf)->b_flags & ARC_BUF_FLAG_COMPRESSED)
980dcbf3bd6SGeorge Wilson 
981e6c728e1Sbrendan /*
982e6c728e1Sbrendan  * Other sizes
983e6c728e1Sbrendan  */
984e6c728e1Sbrendan 
98589c86e32SChris Williamson #define	HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
98689c86e32SChris Williamson #define	HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
987e6c728e1Sbrendan 
988fa9e4066Sahrens /*
989fa9e4066Sahrens  * Hash table routines
990fa9e4066Sahrens  */
991fa9e4066Sahrens 
992fa9e4066Sahrens #define	HT_LOCK_PAD	64
993fa9e4066Sahrens 
994fa9e4066Sahrens struct ht_lock {
995fa9e4066Sahrens 	kmutex_t	ht_lock;
996fa9e4066Sahrens #ifdef _KERNEL
997fa9e4066Sahrens 	unsigned char	pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
998fa9e4066Sahrens #endif
999fa9e4066Sahrens };
1000fa9e4066Sahrens 
1001fa9e4066Sahrens #define	BUF_LOCKS 256
1002fa9e4066Sahrens typedef struct buf_hash_table {
1003fa9e4066Sahrens 	uint64_t ht_mask;
1004fa9e4066Sahrens 	arc_buf_hdr_t **ht_table;
1005fa9e4066Sahrens 	struct ht_lock ht_locks[BUF_LOCKS];
1006fa9e4066Sahrens } buf_hash_table_t;
1007fa9e4066Sahrens 
1008fa9e4066Sahrens static buf_hash_table_t buf_hash_table;
1009fa9e4066Sahrens 
1010fa9e4066Sahrens #define	BUF_HASH_INDEX(spa, dva, birth) \
1011fa9e4066Sahrens 	(buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
1012fa9e4066Sahrens #define	BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
1013fa9e4066Sahrens #define	BUF_HASH_LOCK(idx)	(&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
10143f9d6ad7SLin Ling #define	HDR_LOCK(hdr) \
10153f9d6ad7SLin Ling 	(BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
1016fa9e4066Sahrens 
1017fa9e4066Sahrens uint64_t zfs_crc64_table[256];
1018fa9e4066Sahrens 
1019fa94a07fSbrendan /*
1020fa94a07fSbrendan  * Level 2 ARC
1021fa94a07fSbrendan  */
1022fa94a07fSbrendan 
1023fa94a07fSbrendan #define	L2ARC_WRITE_SIZE	(8 * 1024 * 1024)	/* initial write max */
1024aad02571SSaso Kiselkov #define	L2ARC_HEADROOM		2			/* num of writes */
1025aad02571SSaso Kiselkov /*
1026aad02571SSaso Kiselkov  * If we discover during ARC scan any buffers to be compressed, we boost
1027aad02571SSaso Kiselkov  * our headroom for the next scanning cycle by this percentage multiple.
1028aad02571SSaso Kiselkov  */
1029aad02571SSaso Kiselkov #define	L2ARC_HEADROOM_BOOST	200
10305a98e54bSBrendan Gregg - Sun Microsystems #define	L2ARC_FEED_SECS		1		/* caching interval secs */
10315a98e54bSBrendan Gregg - Sun Microsystems #define	L2ARC_FEED_MIN_MS	200		/* min caching interval ms */
1032fa94a07fSbrendan 
1033fa94a07fSbrendan #define	l2arc_writes_sent	ARCSTAT(arcstat_l2_writes_sent)
1034fa94a07fSbrendan #define	l2arc_writes_done	ARCSTAT(arcstat_l2_writes_done)
1035fa94a07fSbrendan 
1036f7170741SWill Andrews /* L2ARC Performance Tunables */
1037fa94a07fSbrendan uint64_t l2arc_write_max = L2ARC_WRITE_SIZE;	/* default max write size */
10383a737e0dSbrendan uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE;	/* extra write during warmup */
1039fa94a07fSbrendan uint64_t l2arc_headroom = L2ARC_HEADROOM;	/* number of dev writes */
1040aad02571SSaso Kiselkov uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
1041fa94a07fSbrendan uint64_t l2arc_feed_secs = L2ARC_FEED_SECS;	/* interval seconds */
10425a98e54bSBrendan Gregg - Sun Microsystems uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS;	/* min interval milliseconds */
1043fa94a07fSbrendan boolean_t l2arc_noprefetch = B_TRUE;		/* don't cache prefetch bufs */
10445a98e54bSBrendan Gregg - Sun Microsystems boolean_t l2arc_feed_again = B_TRUE;		/* turbo warmup */
10455a98e54bSBrendan Gregg - Sun Microsystems boolean_t l2arc_norw = B_TRUE;			/* no reads during writes */
1046fa94a07fSbrendan 
1047fa94a07fSbrendan /*
1048fa94a07fSbrendan  * L2ARC Internals
1049fa94a07fSbrendan  */
105089c86e32SChris Williamson struct l2arc_dev {
1051fa94a07fSbrendan 	vdev_t			*l2ad_vdev;	/* vdev */
1052fa94a07fSbrendan 	spa_t			*l2ad_spa;	/* spa */
1053fa94a07fSbrendan 	uint64_t		l2ad_hand;	/* next write location */
1054fa94a07fSbrendan 	uint64_t		l2ad_start;	/* first addr on device */
1055fa94a07fSbrendan 	uint64_t		l2ad_end;	/* last addr on device */
1056fa94a07fSbrendan 	boolean_t		l2ad_first;	/* first sweep through */
10575a98e54bSBrendan Gregg - Sun Microsystems 	boolean_t		l2ad_writing;	/* currently writing */
105889c86e32SChris Williamson 	kmutex_t		l2ad_mtx;	/* lock for buffer list */
105989c86e32SChris Williamson 	list_t			l2ad_buflist;	/* buffer list */
1060fa94a07fSbrendan 	list_node_t		l2ad_node;	/* device list node */
1061a52fc310SPrakash Surya 	refcount_t		l2ad_alloc;	/* allocated bytes */
106289c86e32SChris Williamson };
1063fa94a07fSbrendan 
1064fa94a07fSbrendan static list_t L2ARC_dev_list;			/* device list */
1065fa94a07fSbrendan static list_t *l2arc_dev_list;			/* device list pointer */
1066fa94a07fSbrendan static kmutex_t l2arc_dev_mtx;			/* device list mutex */
1067fa94a07fSbrendan static l2arc_dev_t *l2arc_dev_last;		/* last device used */
1068fa94a07fSbrendan static list_t L2ARC_free_on_write;		/* free after write buf list */
1069fa94a07fSbrendan static list_t *l2arc_free_on_write;		/* free after write list ptr */
1070fa94a07fSbrendan static kmutex_t l2arc_free_on_write_mtx;	/* mutex for list */
1071fa94a07fSbrendan static uint64_t l2arc_ndev;			/* number of devices */
1072fa94a07fSbrendan 
1073fa94a07fSbrendan typedef struct l2arc_read_callback {
10745602294fSDan Kimmel 	arc_buf_hdr_t		*l2rcb_hdr;		/* read header */
1075aad02571SSaso Kiselkov 	blkptr_t		l2rcb_bp;		/* original blkptr */
10767802d7bfSMatthew Ahrens 	zbookmark_phys_t	l2rcb_zb;		/* original bookmark */
1077aad02571SSaso Kiselkov 	int			l2rcb_flags;		/* original flags */
1078fa94a07fSbrendan } l2arc_read_callback_t;
1079fa94a07fSbrendan 
1080fa94a07fSbrendan typedef struct l2arc_write_callback {
1081fa94a07fSbrendan 	l2arc_dev_t	*l2wcb_dev;		/* device info */
1082fa94a07fSbrendan 	arc_buf_hdr_t	*l2wcb_head;		/* head of write buflist */
1083fa94a07fSbrendan } l2arc_write_callback_t;
1084fa94a07fSbrendan 
1085fa94a07fSbrendan typedef struct l2arc_data_free {
1086fa94a07fSbrendan 	/* protected by l2arc_free_on_write_mtx */
1087*770499e1SDan Kimmel 	abd_t		*l2df_abd;
1088fa94a07fSbrendan 	size_t		l2df_size;
1089dcbf3bd6SGeorge Wilson 	arc_buf_contents_t l2df_type;
1090fa94a07fSbrendan 	list_node_t	l2df_list_node;
1091fa94a07fSbrendan } l2arc_data_free_t;
1092fa94a07fSbrendan 
1093fa94a07fSbrendan static kmutex_t l2arc_feed_thr_lock;
1094fa94a07fSbrendan static kcondvar_t l2arc_feed_thr_cv;
1095fa94a07fSbrendan static uint8_t l2arc_thread_exit;
1096fa94a07fSbrendan 
1097*770499e1SDan Kimmel static abd_t *arc_get_data_abd(arc_buf_hdr_t *, uint64_t, void *);
1098dcbf3bd6SGeorge Wilson static void *arc_get_data_buf(arc_buf_hdr_t *, uint64_t, void *);
1099*770499e1SDan Kimmel static void arc_get_data_impl(arc_buf_hdr_t *, uint64_t, void *);
1100*770499e1SDan Kimmel static void arc_free_data_abd(arc_buf_hdr_t *, abd_t *, uint64_t, void *);
1101dcbf3bd6SGeorge Wilson static void arc_free_data_buf(arc_buf_hdr_t *, void *, uint64_t, void *);
1102*770499e1SDan Kimmel static void arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag);
1103*770499e1SDan Kimmel static void arc_hdr_free_pabd(arc_buf_hdr_t *);
1104*770499e1SDan Kimmel static void arc_hdr_alloc_pabd(arc_buf_hdr_t *);
11057adb730bSGeorge Wilson static void arc_access(arc_buf_hdr_t *, kmutex_t *);
1106244781f1SPrakash Surya static boolean_t arc_is_overflowing();
11077adb730bSGeorge Wilson static void arc_buf_watch(arc_buf_t *);
11087adb730bSGeorge Wilson 
110989c86e32SChris Williamson static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
111089c86e32SChris Williamson static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
1111dcbf3bd6SGeorge Wilson static inline void arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
1112dcbf3bd6SGeorge Wilson static inline void arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
111389c86e32SChris Williamson 
11147adb730bSGeorge Wilson static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
11157adb730bSGeorge Wilson static void l2arc_read_done(zio_t *);
1116fa94a07fSbrendan 
1117fa9e4066Sahrens static uint64_t
1118ac05c741SMark Maybee buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
1119fa9e4066Sahrens {
1120fa9e4066Sahrens 	uint8_t *vdva = (uint8_t *)dva;
1121fa9e4066Sahrens 	uint64_t crc = -1ULL;
1122fa9e4066Sahrens 	int i;
1123fa9e4066Sahrens 
1124fa9e4066Sahrens 	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
1125fa9e4066Sahrens 
1126fa9e4066Sahrens 	for (i = 0; i < sizeof (dva_t); i++)
1127fa9e4066Sahrens 		crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
1128fa9e4066Sahrens 
1129ac05c741SMark Maybee 	crc ^= (spa>>8) ^ birth;
1130fa9e4066Sahrens 
1131fa9e4066Sahrens 	return (crc);
1132fa9e4066Sahrens }
1133fa9e4066Sahrens 
1134dcbf3bd6SGeorge Wilson #define	HDR_EMPTY(hdr)						\
1135dcbf3bd6SGeorge Wilson 	((hdr)->b_dva.dva_word[0] == 0 &&			\
1136dcbf3bd6SGeorge Wilson 	(hdr)->b_dva.dva_word[1] == 0)
1137fa9e4066Sahrens 
1138dcbf3bd6SGeorge Wilson #define	HDR_EQUAL(spa, dva, birth, hdr)				\
1139dcbf3bd6SGeorge Wilson 	((hdr)->b_dva.dva_word[0] == (dva)->dva_word[0]) &&	\
1140dcbf3bd6SGeorge Wilson 	((hdr)->b_dva.dva_word[1] == (dva)->dva_word[1]) &&	\
1141dcbf3bd6SGeorge Wilson 	((hdr)->b_birth == birth) && ((hdr)->b_spa == spa)
1142fa9e4066Sahrens 
11433f9d6ad7SLin Ling static void
11443f9d6ad7SLin Ling buf_discard_identity(arc_buf_hdr_t *hdr)
11453f9d6ad7SLin Ling {
11463f9d6ad7SLin Ling 	hdr->b_dva.dva_word[0] = 0;
11473f9d6ad7SLin Ling 	hdr->b_dva.dva_word[1] = 0;
11483f9d6ad7SLin Ling 	hdr->b_birth = 0;
11493f9d6ad7SLin Ling }
11503f9d6ad7SLin Ling 
1151fa9e4066Sahrens static arc_buf_hdr_t *
11525d7b4d43SMatthew Ahrens buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
1153fa9e4066Sahrens {
11545d7b4d43SMatthew Ahrens 	const dva_t *dva = BP_IDENTITY(bp);
11555d7b4d43SMatthew Ahrens 	uint64_t birth = BP_PHYSICAL_BIRTH(bp);
1156fa9e4066Sahrens 	uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1157fa9e4066Sahrens 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
11587adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr;
1159fa9e4066Sahrens 
1160fa9e4066Sahrens 	mutex_enter(hash_lock);
11617adb730bSGeorge Wilson 	for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
11627adb730bSGeorge Wilson 	    hdr = hdr->b_hash_next) {
1163dcbf3bd6SGeorge Wilson 		if (HDR_EQUAL(spa, dva, birth, hdr)) {
1164fa9e4066Sahrens 			*lockp = hash_lock;
11657adb730bSGeorge Wilson 			return (hdr);
1166fa9e4066Sahrens 		}
1167fa9e4066Sahrens 	}
1168fa9e4066Sahrens 	mutex_exit(hash_lock);
1169fa9e4066Sahrens 	*lockp = NULL;
1170fa9e4066Sahrens 	return (NULL);
1171fa9e4066Sahrens }
1172fa9e4066Sahrens 
1173fa9e4066Sahrens /*
1174fa9e4066Sahrens  * Insert an entry into the hash table.  If there is already an element
1175fa9e4066Sahrens  * equal to elem in the hash table, then the already existing element
1176fa9e4066Sahrens  * will be returned and the new element will not be inserted.
1177fa9e4066Sahrens  * Otherwise returns NULL.
117889c86e32SChris Williamson  * If lockp == NULL, the caller is assumed to already hold the hash lock.
1179fa9e4066Sahrens  */
1180fa9e4066Sahrens static arc_buf_hdr_t *
11817adb730bSGeorge Wilson buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1182fa9e4066Sahrens {
11837adb730bSGeorge Wilson 	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1184fa9e4066Sahrens 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
11857adb730bSGeorge Wilson 	arc_buf_hdr_t *fhdr;
118644cb6abcSbmc 	uint32_t i;
1187fa9e4066Sahrens 
11887adb730bSGeorge Wilson 	ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
11897adb730bSGeorge Wilson 	ASSERT(hdr->b_birth != 0);
11907adb730bSGeorge Wilson 	ASSERT(!HDR_IN_HASH_TABLE(hdr));
119189c86e32SChris Williamson 
119289c86e32SChris Williamson 	if (lockp != NULL) {
119389c86e32SChris Williamson 		*lockp = hash_lock;
119489c86e32SChris Williamson 		mutex_enter(hash_lock);
119589c86e32SChris Williamson 	} else {
119689c86e32SChris Williamson 		ASSERT(MUTEX_HELD(hash_lock));
119789c86e32SChris Williamson 	}
119889c86e32SChris Williamson 
11997adb730bSGeorge Wilson 	for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
12007adb730bSGeorge Wilson 	    fhdr = fhdr->b_hash_next, i++) {
1201dcbf3bd6SGeorge Wilson 		if (HDR_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
12027adb730bSGeorge Wilson 			return (fhdr);
1203fa9e4066Sahrens 	}
1204fa9e4066Sahrens 
12057adb730bSGeorge Wilson 	hdr->b_hash_next = buf_hash_table.ht_table[idx];
12067adb730bSGeorge Wilson 	buf_hash_table.ht_table[idx] = hdr;
1207dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1208fa9e4066Sahrens 
1209fa9e4066Sahrens 	/* collect some hash table performance data */
1210fa9e4066Sahrens 	if (i > 0) {
121144cb6abcSbmc 		ARCSTAT_BUMP(arcstat_hash_collisions);
1212fa9e4066Sahrens 		if (i == 1)
121344cb6abcSbmc 			ARCSTAT_BUMP(arcstat_hash_chains);
121444cb6abcSbmc 
121544cb6abcSbmc 		ARCSTAT_MAX(arcstat_hash_chain_max, i);
1216fa9e4066Sahrens 	}
121744cb6abcSbmc 
121844cb6abcSbmc 	ARCSTAT_BUMP(arcstat_hash_elements);
121944cb6abcSbmc 	ARCSTAT_MAXSTAT(arcstat_hash_elements);
1220fa9e4066Sahrens 
1221fa9e4066Sahrens 	return (NULL);
1222fa9e4066Sahrens }
1223fa9e4066Sahrens 
1224fa9e4066Sahrens static void
12257adb730bSGeorge Wilson buf_hash_remove(arc_buf_hdr_t *hdr)
1226fa9e4066Sahrens {
12277adb730bSGeorge Wilson 	arc_buf_hdr_t *fhdr, **hdrp;
12287adb730bSGeorge Wilson 	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1229fa9e4066Sahrens 
1230fa9e4066Sahrens 	ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
12317adb730bSGeorge Wilson 	ASSERT(HDR_IN_HASH_TABLE(hdr));
1232fa9e4066Sahrens 
12337adb730bSGeorge Wilson 	hdrp = &buf_hash_table.ht_table[idx];
12347adb730bSGeorge Wilson 	while ((fhdr = *hdrp) != hdr) {
1235dcbf3bd6SGeorge Wilson 		ASSERT3P(fhdr, !=, NULL);
12367adb730bSGeorge Wilson 		hdrp = &fhdr->b_hash_next;
1237fa9e4066Sahrens 	}
12387adb730bSGeorge Wilson 	*hdrp = hdr->b_hash_next;
12397adb730bSGeorge Wilson 	hdr->b_hash_next = NULL;
1240dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1241fa9e4066Sahrens 
1242fa9e4066Sahrens 	/* collect some hash table performance data */
124344cb6abcSbmc 	ARCSTAT_BUMPDOWN(arcstat_hash_elements);
124444cb6abcSbmc 
1245fa9e4066Sahrens 	if (buf_hash_table.ht_table[idx] &&
1246fa9e4066Sahrens 	    buf_hash_table.ht_table[idx]->b_hash_next == NULL)
124744cb6abcSbmc 		ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1248fa9e4066Sahrens }
1249fa9e4066Sahrens 
1250fa9e4066Sahrens /*
1251fa9e4066Sahrens  * Global data structures and functions for the buf kmem cache.
1252fa9e4066Sahrens  */
125389c86e32SChris Williamson static kmem_cache_t *hdr_full_cache;
125489c86e32SChris Williamson static kmem_cache_t *hdr_l2only_cache;
1255fa9e4066Sahrens static kmem_cache_t *buf_cache;
1256fa9e4066Sahrens 
1257fa9e4066Sahrens static void
1258fa9e4066Sahrens buf_fini(void)
1259fa9e4066Sahrens {
1260fa9e4066Sahrens 	int i;
1261fa9e4066Sahrens 
1262fa9e4066Sahrens 	kmem_free(buf_hash_table.ht_table,
1263fa9e4066Sahrens 	    (buf_hash_table.ht_mask + 1) * sizeof (void *));
1264fa9e4066Sahrens 	for (i = 0; i < BUF_LOCKS; i++)
1265fa9e4066Sahrens 		mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
126689c86e32SChris Williamson 	kmem_cache_destroy(hdr_full_cache);
126789c86e32SChris Williamson 	kmem_cache_destroy(hdr_l2only_cache);
1268fa9e4066Sahrens 	kmem_cache_destroy(buf_cache);
1269fa9e4066Sahrens }
1270fa9e4066Sahrens 
1271fa9e4066Sahrens /*
1272fa9e4066Sahrens  * Constructor callback - called when the cache is empty
1273fa9e4066Sahrens  * and a new buf is requested.
1274fa9e4066Sahrens  */
1275fa9e4066Sahrens /* ARGSUSED */
1276fa9e4066Sahrens static int
127789c86e32SChris Williamson hdr_full_cons(void *vbuf, void *unused, int kmflag)
1278fa9e4066Sahrens {
12797adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr = vbuf;
1280fa9e4066Sahrens 
128189c86e32SChris Williamson 	bzero(hdr, HDR_FULL_SIZE);
128289c86e32SChris Williamson 	cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
128389c86e32SChris Williamson 	refcount_create(&hdr->b_l1hdr.b_refcnt);
128489c86e32SChris Williamson 	mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1285244781f1SPrakash Surya 	multilist_link_init(&hdr->b_l1hdr.b_arc_node);
128689c86e32SChris Williamson 	arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
128789c86e32SChris Williamson 
128889c86e32SChris Williamson 	return (0);
128989c86e32SChris Williamson }
129089c86e32SChris Williamson 
129189c86e32SChris Williamson /* ARGSUSED */
129289c86e32SChris Williamson static int
129389c86e32SChris Williamson hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
129489c86e32SChris Williamson {
129589c86e32SChris Williamson 	arc_buf_hdr_t *hdr = vbuf;
129689c86e32SChris Williamson 
129789c86e32SChris Williamson 	bzero(hdr, HDR_L2ONLY_SIZE);
129889c86e32SChris Williamson 	arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1299fa94a07fSbrendan 
1300fa9e4066Sahrens 	return (0);
1301fa9e4066Sahrens }
1302fa9e4066Sahrens 
13036f83844dSMark Maybee /* ARGSUSED */
13046f83844dSMark Maybee static int
13056f83844dSMark Maybee buf_cons(void *vbuf, void *unused, int kmflag)
13066f83844dSMark Maybee {
13076f83844dSMark Maybee 	arc_buf_t *buf = vbuf;
13086f83844dSMark Maybee 
13096f83844dSMark Maybee 	bzero(buf, sizeof (arc_buf_t));
13103f9d6ad7SLin Ling 	mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
13115a98e54bSBrendan Gregg - Sun Microsystems 	arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
13125a98e54bSBrendan Gregg - Sun Microsystems 
13136f83844dSMark Maybee 	return (0);
13146f83844dSMark Maybee }
13156f83844dSMark Maybee 
1316fa9e4066Sahrens /*
1317fa9e4066Sahrens  * Destructor callback - called when a cached buf is
1318fa9e4066Sahrens  * no longer required.
1319fa9e4066Sahrens  */
1320fa9e4066Sahrens /* ARGSUSED */
1321fa9e4066Sahrens static void
132289c86e32SChris Williamson hdr_full_dest(void *vbuf, void *unused)
132389c86e32SChris Williamson {
132489c86e32SChris Williamson 	arc_buf_hdr_t *hdr = vbuf;
132589c86e32SChris Williamson 
1326dcbf3bd6SGeorge Wilson 	ASSERT(HDR_EMPTY(hdr));
132789c86e32SChris Williamson 	cv_destroy(&hdr->b_l1hdr.b_cv);
132889c86e32SChris Williamson 	refcount_destroy(&hdr->b_l1hdr.b_refcnt);
132989c86e32SChris Williamson 	mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1330244781f1SPrakash Surya 	ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
133189c86e32SChris Williamson 	arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
133289c86e32SChris Williamson }
133389c86e32SChris Williamson 
133489c86e32SChris Williamson /* ARGSUSED */
133589c86e32SChris Williamson static void
133689c86e32SChris Williamson hdr_l2only_dest(void *vbuf, void *unused)
1337fa9e4066Sahrens {
13387adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr = vbuf;
1339fa9e4066Sahrens 
1340dcbf3bd6SGeorge Wilson 	ASSERT(HDR_EMPTY(hdr));
134189c86e32SChris Williamson 	arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1342fa9e4066Sahrens }
1343fa9e4066Sahrens 
13446f83844dSMark Maybee /* ARGSUSED */
13456f83844dSMark Maybee static void
13466f83844dSMark Maybee buf_dest(void *vbuf, void *unused)
13476f83844dSMark Maybee {
13486f83844dSMark Maybee 	arc_buf_t *buf = vbuf;
13496f83844dSMark Maybee 
13503f9d6ad7SLin Ling 	mutex_destroy(&buf->b_evict_lock);
13515a98e54bSBrendan Gregg - Sun Microsystems 	arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
13526f83844dSMark Maybee }
13536f83844dSMark Maybee 
1354fa9e4066Sahrens /*
1355fa9e4066Sahrens  * Reclaim callback -- invoked when memory is low.
1356fa9e4066Sahrens  */
1357fa9e4066Sahrens /* ARGSUSED */
1358fa9e4066Sahrens static void
1359fa9e4066Sahrens hdr_recl(void *unused)
1360fa9e4066Sahrens {
1361fa9e4066Sahrens 	dprintf("hdr_recl called\n");
136249e3519aSmaybee 	/*
136349e3519aSmaybee 	 * umem calls the reclaim func when we destroy the buf cache,
136449e3519aSmaybee 	 * which is after we do arc_fini().
136549e3519aSmaybee 	 */
136649e3519aSmaybee 	if (!arc_dead)
1367244781f1SPrakash Surya 		cv_signal(&arc_reclaim_thread_cv);
1368fa9e4066Sahrens }
1369fa9e4066Sahrens 
1370fa9e4066Sahrens static void
1371fa9e4066Sahrens buf_init(void)
1372fa9e4066Sahrens {
1373fa9e4066Sahrens 	uint64_t *ct;
1374ea8dc4b6Seschrock 	uint64_t hsize = 1ULL << 12;
1375fa9e4066Sahrens 	int i, j;
1376fa9e4066Sahrens 
1377fa9e4066Sahrens 	/*
1378fa9e4066Sahrens 	 * The hash table is big enough to fill all of physical memory
137963e911b6SMatthew Ahrens 	 * with an average block size of zfs_arc_average_blocksize (default 8K).
138063e911b6SMatthew Ahrens 	 * By default, the table will take up
138163e911b6SMatthew Ahrens 	 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1382fa9e4066Sahrens 	 */
138363e911b6SMatthew Ahrens 	while (hsize * zfs_arc_average_blocksize < physmem * PAGESIZE)
1384fa9e4066Sahrens 		hsize <<= 1;
1385ea8dc4b6Seschrock retry:
1386fa9e4066Sahrens 	buf_hash_table.ht_mask = hsize - 1;
1387ea8dc4b6Seschrock 	buf_hash_table.ht_table =
1388ea8dc4b6Seschrock 	    kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1389ea8dc4b6Seschrock 	if (buf_hash_table.ht_table == NULL) {
1390ea8dc4b6Seschrock 		ASSERT(hsize > (1ULL << 8));
1391ea8dc4b6Seschrock 		hsize >>= 1;
1392ea8dc4b6Seschrock 		goto retry;
1393ea8dc4b6Seschrock 	}
1394fa9e4066Sahrens 
139589c86e32SChris Williamson 	hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
139689c86e32SChris Williamson 	    0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
139789c86e32SChris Williamson 	hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
139889c86e32SChris Williamson 	    HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
139989c86e32SChris Williamson 	    NULL, NULL, 0);
1400fa9e4066Sahrens 	buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
14016f83844dSMark Maybee 	    0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1402fa9e4066Sahrens 
1403fa9e4066Sahrens 	for (i = 0; i < 256; i++)
1404fa9e4066Sahrens 		for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1405fa9e4066Sahrens 			*ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1406fa9e4066Sahrens 
1407fa9e4066Sahrens 	for (i = 0; i < BUF_LOCKS; i++) {
1408fa9e4066Sahrens 		mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1409fa9e4066Sahrens 		    NULL, MUTEX_DEFAULT, NULL);
1410fa9e4066Sahrens 	}
1411fa9e4066Sahrens }
1412fa9e4066Sahrens 
14135602294fSDan Kimmel /*
14145602294fSDan Kimmel  * This is the size that the buf occupies in memory. If the buf is compressed,
14155602294fSDan Kimmel  * it will correspond to the compressed size. You should use this method of
14165602294fSDan Kimmel  * getting the buf size unless you explicitly need the logical size.
14175602294fSDan Kimmel  */
14185602294fSDan Kimmel int32_t
14195602294fSDan Kimmel arc_buf_size(arc_buf_t *buf)
14205602294fSDan Kimmel {
14215602294fSDan Kimmel 	return (ARC_BUF_COMPRESSED(buf) ?
14225602294fSDan Kimmel 	    HDR_GET_PSIZE(buf->b_hdr) : HDR_GET_LSIZE(buf->b_hdr));
14235602294fSDan Kimmel }
14245602294fSDan Kimmel 
14255602294fSDan Kimmel int32_t
14265602294fSDan Kimmel arc_buf_lsize(arc_buf_t *buf)
14275602294fSDan Kimmel {
14285602294fSDan Kimmel 	return (HDR_GET_LSIZE(buf->b_hdr));
14295602294fSDan Kimmel }
14305602294fSDan Kimmel 
14315602294fSDan Kimmel enum zio_compress
14325602294fSDan Kimmel arc_get_compression(arc_buf_t *buf)
14335602294fSDan Kimmel {
14345602294fSDan Kimmel 	return (ARC_BUF_COMPRESSED(buf) ?
14355602294fSDan Kimmel 	    HDR_GET_COMPRESS(buf->b_hdr) : ZIO_COMPRESS_OFF);
14365602294fSDan Kimmel }
14375602294fSDan Kimmel 
1438dcbf3bd6SGeorge Wilson #define	ARC_MINTIME	(hz>>4) /* 62 ms */
1439244781f1SPrakash Surya 
1440dcbf3bd6SGeorge Wilson static inline boolean_t
1441dcbf3bd6SGeorge Wilson arc_buf_is_shared(arc_buf_t *buf)
1442dcbf3bd6SGeorge Wilson {
1443dcbf3bd6SGeorge Wilson 	boolean_t shared = (buf->b_data != NULL &&
1444*770499e1SDan Kimmel 	    buf->b_hdr->b_l1hdr.b_pabd != NULL &&
1445*770499e1SDan Kimmel 	    abd_is_linear(buf->b_hdr->b_l1hdr.b_pabd) &&
1446*770499e1SDan Kimmel 	    buf->b_data == abd_to_buf(buf->b_hdr->b_l1hdr.b_pabd));
1447dcbf3bd6SGeorge Wilson 	IMPLY(shared, HDR_SHARED_DATA(buf->b_hdr));
14485602294fSDan Kimmel 	IMPLY(shared, ARC_BUF_SHARED(buf));
14495602294fSDan Kimmel 	IMPLY(shared, ARC_BUF_COMPRESSED(buf) || ARC_BUF_LAST(buf));
14505602294fSDan Kimmel 
14515602294fSDan Kimmel 	/*
14525602294fSDan Kimmel 	 * It would be nice to assert arc_can_share() too, but the "hdr isn't
14535602294fSDan Kimmel 	 * already being shared" requirement prevents us from doing that.
14545602294fSDan Kimmel 	 */
14555602294fSDan Kimmel 
1456dcbf3bd6SGeorge Wilson 	return (shared);
1457dcbf3bd6SGeorge Wilson }
1458c546f36aSArne Jansen 
14595602294fSDan Kimmel /*
14605602294fSDan Kimmel  * Free the checksum associated with this header. If there is no checksum, this
14615602294fSDan Kimmel  * is a no-op.
14625602294fSDan Kimmel  */
1463dcbf3bd6SGeorge Wilson static inline void
1464dcbf3bd6SGeorge Wilson arc_cksum_free(arc_buf_hdr_t *hdr)
1465dcbf3bd6SGeorge Wilson {
1466dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
1467dcbf3bd6SGeorge Wilson 	mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1468dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
1469dcbf3bd6SGeorge Wilson 		kmem_free(hdr->b_l1hdr.b_freeze_cksum, sizeof (zio_cksum_t));
1470dcbf3bd6SGeorge Wilson 		hdr->b_l1hdr.b_freeze_cksum = NULL;
147189c86e32SChris Williamson 	}
1472dcbf3bd6SGeorge Wilson 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
147389c86e32SChris Williamson }
147489c86e32SChris Williamson 
14755602294fSDan Kimmel /*
14765602294fSDan Kimmel  * Return true iff at least one of the bufs on hdr is not compressed.
14775602294fSDan Kimmel  */
14785602294fSDan Kimmel static boolean_t
14795602294fSDan Kimmel arc_hdr_has_uncompressed_buf(arc_buf_hdr_t *hdr)
14805602294fSDan Kimmel {
14815602294fSDan Kimmel 	for (arc_buf_t *b = hdr->b_l1hdr.b_buf; b != NULL; b = b->b_next) {
14825602294fSDan Kimmel 		if (!ARC_BUF_COMPRESSED(b)) {
14835602294fSDan Kimmel 			return (B_TRUE);
14845602294fSDan Kimmel 		}
14855602294fSDan Kimmel 	}
14865602294fSDan Kimmel 	return (B_FALSE);
14875602294fSDan Kimmel }
14885602294fSDan Kimmel 
14895602294fSDan Kimmel /*
14905602294fSDan Kimmel  * If we've turned on the ZFS_DEBUG_MODIFY flag, verify that the buf's data
14915602294fSDan Kimmel  * matches the checksum that is stored in the hdr. If there is no checksum,
14925602294fSDan Kimmel  * or if the buf is compressed, this is a no-op.
14935602294fSDan Kimmel  */
14946b4acc8bSahrens static void
14956b4acc8bSahrens arc_cksum_verify(arc_buf_t *buf)
14966b4acc8bSahrens {
1497dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
14986b4acc8bSahrens 	zio_cksum_t zc;
14996b4acc8bSahrens 
1500cc60fd72Sahrens 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
15016b4acc8bSahrens 		return;
15026b4acc8bSahrens 
15035602294fSDan Kimmel 	if (ARC_BUF_COMPRESSED(buf)) {
15045602294fSDan Kimmel 		ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
15055602294fSDan Kimmel 		    arc_hdr_has_uncompressed_buf(hdr));
15065602294fSDan Kimmel 		return;
15075602294fSDan Kimmel 	}
15085602294fSDan Kimmel 
1509dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
1510dcbf3bd6SGeorge Wilson 
1511dcbf3bd6SGeorge Wilson 	mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1512dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_freeze_cksum == NULL || HDR_IO_ERROR(hdr)) {
1513dcbf3bd6SGeorge Wilson 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
15146b4acc8bSahrens 		return;
15156b4acc8bSahrens 	}
15165602294fSDan Kimmel 
15175602294fSDan Kimmel 	fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL, &zc);
1518dcbf3bd6SGeorge Wilson 	if (!ZIO_CHECKSUM_EQUAL(*hdr->b_l1hdr.b_freeze_cksum, zc))
15196b4acc8bSahrens 		panic("buffer modified while frozen!");
1520dcbf3bd6SGeorge Wilson 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
15216b4acc8bSahrens }
15226b4acc8bSahrens 
1523dcbf3bd6SGeorge Wilson static boolean_t
1524dcbf3bd6SGeorge Wilson arc_cksum_is_equal(arc_buf_hdr_t *hdr, zio_t *zio)
1525fa94a07fSbrendan {
1526dcbf3bd6SGeorge Wilson 	enum zio_compress compress = BP_GET_COMPRESS(zio->io_bp);
1527dcbf3bd6SGeorge Wilson 	boolean_t valid_cksum;
1528fa94a07fSbrendan 
1529dcbf3bd6SGeorge Wilson 	ASSERT(!BP_IS_EMBEDDED(zio->io_bp));
1530dcbf3bd6SGeorge Wilson 	VERIFY3U(BP_GET_PSIZE(zio->io_bp), ==, HDR_GET_PSIZE(hdr));
1531dcbf3bd6SGeorge Wilson 
1532dcbf3bd6SGeorge Wilson 	/*
1533dcbf3bd6SGeorge Wilson 	 * We rely on the blkptr's checksum to determine if the block
1534dcbf3bd6SGeorge Wilson 	 * is valid or not. When compressed arc is enabled, the l2arc
1535dcbf3bd6SGeorge Wilson 	 * writes the block to the l2arc just as it appears in the pool.
1536dcbf3bd6SGeorge Wilson 	 * This allows us to use the blkptr's checksum to validate the
1537dcbf3bd6SGeorge Wilson 	 * data that we just read off of the l2arc without having to store
1538dcbf3bd6SGeorge Wilson 	 * a separate checksum in the arc_buf_hdr_t. However, if compressed
1539dcbf3bd6SGeorge Wilson 	 * arc is disabled, then the data written to the l2arc is always
1540dcbf3bd6SGeorge Wilson 	 * uncompressed and won't match the block as it exists in the main
1541dcbf3bd6SGeorge Wilson 	 * pool. When this is the case, we must first compress it if it is
1542dcbf3bd6SGeorge Wilson 	 * compressed on the main pool before we can validate the checksum.
1543dcbf3bd6SGeorge Wilson 	 */
1544dcbf3bd6SGeorge Wilson 	if (!HDR_COMPRESSION_ENABLED(hdr) && compress != ZIO_COMPRESS_OFF) {
1545dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
1546dcbf3bd6SGeorge Wilson 		uint64_t lsize = HDR_GET_LSIZE(hdr);
1547dcbf3bd6SGeorge Wilson 		uint64_t csize;
1548dcbf3bd6SGeorge Wilson 
1549dcbf3bd6SGeorge Wilson 		void *cbuf = zio_buf_alloc(HDR_GET_PSIZE(hdr));
1550*770499e1SDan Kimmel 		csize = zio_compress_data(compress, zio->io_abd, cbuf, lsize);
1551*770499e1SDan Kimmel 
1552dcbf3bd6SGeorge Wilson 		ASSERT3U(csize, <=, HDR_GET_PSIZE(hdr));
1553dcbf3bd6SGeorge Wilson 		if (csize < HDR_GET_PSIZE(hdr)) {
1554dcbf3bd6SGeorge Wilson 			/*
1555dcbf3bd6SGeorge Wilson 			 * Compressed blocks are always a multiple of the
1556dcbf3bd6SGeorge Wilson 			 * smallest ashift in the pool. Ideally, we would
1557dcbf3bd6SGeorge Wilson 			 * like to round up the csize to the next
1558dcbf3bd6SGeorge Wilson 			 * spa_min_ashift but that value may have changed
1559dcbf3bd6SGeorge Wilson 			 * since the block was last written. Instead,
1560dcbf3bd6SGeorge Wilson 			 * we rely on the fact that the hdr's psize
1561dcbf3bd6SGeorge Wilson 			 * was set to the psize of the block when it was
1562dcbf3bd6SGeorge Wilson 			 * last written. We set the csize to that value
1563dcbf3bd6SGeorge Wilson 			 * and zero out any part that should not contain
1564dcbf3bd6SGeorge Wilson 			 * data.
1565dcbf3bd6SGeorge Wilson 			 */
1566dcbf3bd6SGeorge Wilson 			bzero((char *)cbuf + csize, HDR_GET_PSIZE(hdr) - csize);
1567dcbf3bd6SGeorge Wilson 			csize = HDR_GET_PSIZE(hdr);
1568dcbf3bd6SGeorge Wilson 		}
1569dcbf3bd6SGeorge Wilson 		zio_push_transform(zio, cbuf, csize, HDR_GET_PSIZE(hdr), NULL);
1570dcbf3bd6SGeorge Wilson 	}
1571fa94a07fSbrendan 
1572dcbf3bd6SGeorge Wilson 	/*
1573dcbf3bd6SGeorge Wilson 	 * Block pointers always store the checksum for the logical data.
1574dcbf3bd6SGeorge Wilson 	 * If the block pointer has the gang bit set, then the checksum
1575dcbf3bd6SGeorge Wilson 	 * it represents is for the reconstituted data and not for an
1576dcbf3bd6SGeorge Wilson 	 * individual gang member. The zio pipeline, however, must be able to
1577dcbf3bd6SGeorge Wilson 	 * determine the checksum of each of the gang constituents so it
1578dcbf3bd6SGeorge Wilson 	 * treats the checksum comparison differently than what we need
1579dcbf3bd6SGeorge Wilson 	 * for l2arc blocks. This prevents us from using the
1580dcbf3bd6SGeorge Wilson 	 * zio_checksum_error() interface directly. Instead we must call the
1581dcbf3bd6SGeorge Wilson 	 * zio_checksum_error_impl() so that we can ensure the checksum is
1582dcbf3bd6SGeorge Wilson 	 * generated using the correct checksum algorithm and accounts for the
1583dcbf3bd6SGeorge Wilson 	 * logical I/O size and not just a gang fragment.
1584dcbf3bd6SGeorge Wilson 	 */
1585dcbf3bd6SGeorge Wilson 	valid_cksum = (zio_checksum_error_impl(zio->io_spa, zio->io_bp,
1586*770499e1SDan Kimmel 	    BP_GET_CHECKSUM(zio->io_bp), zio->io_abd, zio->io_size,
1587dcbf3bd6SGeorge Wilson 	    zio->io_offset, NULL) == 0);
1588dcbf3bd6SGeorge Wilson 	zio_pop_transforms(zio);
1589dcbf3bd6SGeorge Wilson 	return (valid_cksum);
1590fa94a07fSbrendan }
1591fa94a07fSbrendan 
15925602294fSDan Kimmel /*
15935602294fSDan Kimmel  * Given a buf full of data, if ZFS_DEBUG_MODIFY is enabled this computes a
15945602294fSDan Kimmel  * checksum and attaches it to the buf's hdr so that we can ensure that the buf
15955602294fSDan Kimmel  * isn't modified later on. If buf is compressed or there is already a checksum
15965602294fSDan Kimmel  * on the hdr, this is a no-op (we only checksum uncompressed bufs).
15975602294fSDan Kimmel  */
15986b4acc8bSahrens static void
1599dcbf3bd6SGeorge Wilson arc_cksum_compute(arc_buf_t *buf)
16006b4acc8bSahrens {
1601dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
1602dcbf3bd6SGeorge Wilson 
1603dcbf3bd6SGeorge Wilson 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
16046b4acc8bSahrens 		return;
16056b4acc8bSahrens 
1606dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
16075602294fSDan Kimmel 
160889c86e32SChris Williamson 	mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1609dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
16105602294fSDan Kimmel 		ASSERT(arc_hdr_has_uncompressed_buf(hdr));
16115602294fSDan Kimmel 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
16125602294fSDan Kimmel 		return;
16135602294fSDan Kimmel 	} else if (ARC_BUF_COMPRESSED(buf)) {
1614dcbf3bd6SGeorge Wilson 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
16156b4acc8bSahrens 		return;
16166b4acc8bSahrens 	}
16175602294fSDan Kimmel 
16185602294fSDan Kimmel 	ASSERT(!ARC_BUF_COMPRESSED(buf));
1619dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t),
1620dcbf3bd6SGeorge Wilson 	    KM_SLEEP);
16215602294fSDan Kimmel 	fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL,
1622dcbf3bd6SGeorge Wilson 	    hdr->b_l1hdr.b_freeze_cksum);
1623dcbf3bd6SGeorge Wilson 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1624cd1c8b85SMatthew Ahrens 	arc_buf_watch(buf);
1625cd1c8b85SMatthew Ahrens }
1626cd1c8b85SMatthew Ahrens 
1627cd1c8b85SMatthew Ahrens #ifndef _KERNEL
1628cd1c8b85SMatthew Ahrens typedef struct procctl {
1629cd1c8b85SMatthew Ahrens 	long cmd;
1630cd1c8b85SMatthew Ahrens 	prwatch_t prwatch;
1631cd1c8b85SMatthew Ahrens } procctl_t;
1632cd1c8b85SMatthew Ahrens #endif
1633cd1c8b85SMatthew Ahrens 
1634cd1c8b85SMatthew Ahrens /* ARGSUSED */
1635cd1c8b85SMatthew Ahrens static void
1636cd1c8b85SMatthew Ahrens arc_buf_unwatch(arc_buf_t *buf)
1637cd1c8b85SMatthew Ahrens {
1638cd1c8b85SMatthew Ahrens #ifndef _KERNEL
1639cd1c8b85SMatthew Ahrens 	if (arc_watch) {
1640cd1c8b85SMatthew Ahrens 		int result;
1641cd1c8b85SMatthew Ahrens 		procctl_t ctl;
1642cd1c8b85SMatthew Ahrens 		ctl.cmd = PCWATCH;
1643cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1644cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_size = 0;
1645cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_wflags = 0;
1646cd1c8b85SMatthew Ahrens 		result = write(arc_procfd, &ctl, sizeof (ctl));
1647cd1c8b85SMatthew Ahrens 		ASSERT3U(result, ==, sizeof (ctl));
1648cd1c8b85SMatthew Ahrens 	}
1649cd1c8b85SMatthew Ahrens #endif
1650cd1c8b85SMatthew Ahrens }
1651cd1c8b85SMatthew Ahrens 
1652cd1c8b85SMatthew Ahrens /* ARGSUSED */
1653cd1c8b85SMatthew Ahrens static void
1654cd1c8b85SMatthew Ahrens arc_buf_watch(arc_buf_t *buf)
1655cd1c8b85SMatthew Ahrens {
1656cd1c8b85SMatthew Ahrens #ifndef _KERNEL
1657cd1c8b85SMatthew Ahrens 	if (arc_watch) {
1658cd1c8b85SMatthew Ahrens 		int result;
1659cd1c8b85SMatthew Ahrens 		procctl_t ctl;
1660cd1c8b85SMatthew Ahrens 		ctl.cmd = PCWATCH;
1661cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
16625602294fSDan Kimmel 		ctl.prwatch.pr_size = arc_buf_size(buf);
1663cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_wflags = WA_WRITE;
1664cd1c8b85SMatthew Ahrens 		result = write(arc_procfd, &ctl, sizeof (ctl));
1665cd1c8b85SMatthew Ahrens 		ASSERT3U(result, ==, sizeof (ctl));
1666cd1c8b85SMatthew Ahrens 	}
1667cd1c8b85SMatthew Ahrens #endif
16686b4acc8bSahrens }
16696b4acc8bSahrens 
167089c86e32SChris Williamson static arc_buf_contents_t
167189c86e32SChris Williamson arc_buf_type(arc_buf_hdr_t *hdr)
167289c86e32SChris Williamson {
1673dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type;
167489c86e32SChris Williamson 	if (HDR_ISTYPE_METADATA(hdr)) {
1675dcbf3bd6SGeorge Wilson 		type = ARC_BUFC_METADATA;
167689c86e32SChris Williamson 	} else {
1677dcbf3bd6SGeorge Wilson 		type = ARC_BUFC_DATA;
167889c86e32SChris Williamson 	}
1679dcbf3bd6SGeorge Wilson 	VERIFY3U(hdr->b_type, ==, type);
1680dcbf3bd6SGeorge Wilson 	return (type);
168189c86e32SChris Williamson }
168289c86e32SChris Williamson 
16835602294fSDan Kimmel boolean_t
16845602294fSDan Kimmel arc_is_metadata(arc_buf_t *buf)
16855602294fSDan Kimmel {
16865602294fSDan Kimmel 	return (HDR_ISTYPE_METADATA(buf->b_hdr) != 0);
16875602294fSDan Kimmel }
16885602294fSDan Kimmel 
168989c86e32SChris Williamson static uint32_t
169089c86e32SChris Williamson arc_bufc_to_flags(arc_buf_contents_t type)
169189c86e32SChris Williamson {
169289c86e32SChris Williamson 	switch (type) {
169389c86e32SChris Williamson 	case ARC_BUFC_DATA:
169489c86e32SChris Williamson 		/* metadata field is 0 if buffer contains normal data */
169589c86e32SChris Williamson 		return (0);
169689c86e32SChris Williamson 	case ARC_BUFC_METADATA:
169789c86e32SChris Williamson 		return (ARC_FLAG_BUFC_METADATA);
169889c86e32SChris Williamson 	default:
169989c86e32SChris Williamson 		break;
170089c86e32SChris Williamson 	}
170189c86e32SChris Williamson 	panic("undefined ARC buffer type!");
170289c86e32SChris Williamson 	return ((uint32_t)-1);
170389c86e32SChris Williamson }
170489c86e32SChris Williamson 
17056b4acc8bSahrens void
17066b4acc8bSahrens arc_buf_thaw(arc_buf_t *buf)
17076b4acc8bSahrens {
1708dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
1709dcbf3bd6SGeorge Wilson 
17105602294fSDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
17115602294fSDan Kimmel 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
17125602294fSDan Kimmel 
17135602294fSDan Kimmel 	arc_cksum_verify(buf);
17145602294fSDan Kimmel 
17155602294fSDan Kimmel 	/*
17165602294fSDan Kimmel 	 * Compressed buffers do not manipulate the b_freeze_cksum or
17175602294fSDan Kimmel 	 * allocate b_thawed.
17185602294fSDan Kimmel 	 */
17195602294fSDan Kimmel 	if (ARC_BUF_COMPRESSED(buf)) {
17205602294fSDan Kimmel 		ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
17215602294fSDan Kimmel 		    arc_hdr_has_uncompressed_buf(hdr));
17225602294fSDan Kimmel 		return;
1723fa94a07fSbrendan 	}
17246b4acc8bSahrens 
1725dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
1726dcbf3bd6SGeorge Wilson 	arc_cksum_free(hdr);
17273f9d6ad7SLin Ling 
1728dcbf3bd6SGeorge Wilson 	mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
172989c86e32SChris Williamson #ifdef ZFS_DEBUG
17303f9d6ad7SLin Ling 	if (zfs_flags & ZFS_DEBUG_MODIFY) {
1731dcbf3bd6SGeorge Wilson 		if (hdr->b_l1hdr.b_thawed != NULL)
1732dcbf3bd6SGeorge Wilson 			kmem_free(hdr->b_l1hdr.b_thawed, 1);
1733dcbf3bd6SGeorge Wilson 		hdr->b_l1hdr.b_thawed = kmem_alloc(1, KM_SLEEP);
17343f9d6ad7SLin Ling 	}
173589c86e32SChris Williamson #endif
17363f9d6ad7SLin Ling 
1737dcbf3bd6SGeorge Wilson 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1738cd1c8b85SMatthew Ahrens 
1739cd1c8b85SMatthew Ahrens 	arc_buf_unwatch(buf);
17406b4acc8bSahrens }
17416b4acc8bSahrens 
17426b4acc8bSahrens void
17436b4acc8bSahrens arc_buf_freeze(arc_buf_t *buf)
17446b4acc8bSahrens {
1745dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
17463f9d6ad7SLin Ling 	kmutex_t *hash_lock;
17473f9d6ad7SLin Ling 
1748cc60fd72Sahrens 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1749cc60fd72Sahrens 		return;
1750cc60fd72Sahrens 
17515602294fSDan Kimmel 	if (ARC_BUF_COMPRESSED(buf)) {
17525602294fSDan Kimmel 		ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
17535602294fSDan Kimmel 		    arc_hdr_has_uncompressed_buf(hdr));
17545602294fSDan Kimmel 		return;
17555602294fSDan Kimmel 	}
17565602294fSDan Kimmel 
1757dcbf3bd6SGeorge Wilson 	hash_lock = HDR_LOCK(hdr);
17583f9d6ad7SLin Ling 	mutex_enter(hash_lock);
17593f9d6ad7SLin Ling 
1760dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
1761dcbf3bd6SGeorge Wilson 	ASSERT(hdr->b_l1hdr.b_freeze_cksum != NULL ||
1762dcbf3bd6SGeorge Wilson 	    hdr->b_l1hdr.b_state == arc_anon);
1763dcbf3bd6SGeorge Wilson 	arc_cksum_compute(buf);
17643f9d6ad7SLin Ling 	mutex_exit(hash_lock);
17656b4acc8bSahrens }
17666b4acc8bSahrens 
1767dcbf3bd6SGeorge Wilson /*
1768dcbf3bd6SGeorge Wilson  * The arc_buf_hdr_t's b_flags should never be modified directly. Instead,
1769dcbf3bd6SGeorge Wilson  * the following functions should be used to ensure that the flags are
1770dcbf3bd6SGeorge Wilson  * updated in a thread-safe way. When manipulating the flags either
1771dcbf3bd6SGeorge Wilson  * the hash_lock must be held or the hdr must be undiscoverable. This
1772dcbf3bd6SGeorge Wilson  * ensures that we're not racing with any other threads when updating
1773dcbf3bd6SGeorge Wilson  * the flags.
1774dcbf3bd6SGeorge Wilson  */
1775dcbf3bd6SGeorge Wilson static inline void
1776dcbf3bd6SGeorge Wilson arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
1777dcbf3bd6SGeorge Wilson {
1778dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
1779dcbf3bd6SGeorge Wilson 	hdr->b_flags |= flags;
1780dcbf3bd6SGeorge Wilson }
1781dcbf3bd6SGeorge Wilson 
1782dcbf3bd6SGeorge Wilson static inline void
1783dcbf3bd6SGeorge Wilson arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
1784dcbf3bd6SGeorge Wilson {
1785dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
1786dcbf3bd6SGeorge Wilson 	hdr->b_flags &= ~flags;
1787dcbf3bd6SGeorge Wilson }
1788dcbf3bd6SGeorge Wilson 
1789dcbf3bd6SGeorge Wilson /*
1790dcbf3bd6SGeorge Wilson  * Setting the compression bits in the arc_buf_hdr_t's b_flags is
1791dcbf3bd6SGeorge Wilson  * done in a special way since we have to clear and set bits
1792dcbf3bd6SGeorge Wilson  * at the same time. Consumers that wish to set the compression bits
1793dcbf3bd6SGeorge Wilson  * must use this function to ensure that the flags are updated in
1794dcbf3bd6SGeorge Wilson  * thread-safe manner.
1795dcbf3bd6SGeorge Wilson  */
1796fa9e4066Sahrens static void
1797dcbf3bd6SGeorge Wilson arc_hdr_set_compress(arc_buf_hdr_t *hdr, enum zio_compress cmp)
1798fa9e4066Sahrens {
1799dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
1800fa9e4066Sahrens 
1801dcbf3bd6SGeorge Wilson 	/*
1802dcbf3bd6SGeorge Wilson 	 * Holes and embedded blocks will always have a psize = 0 so
1803dcbf3bd6SGeorge Wilson 	 * we ignore the compression of the blkptr and set the
1804dcbf3bd6SGeorge Wilson 	 * arc_buf_hdr_t's compression to ZIO_COMPRESS_OFF.
1805dcbf3bd6SGeorge Wilson 	 * Holes and embedded blocks remain anonymous so we don't
1806dcbf3bd6SGeorge Wilson 	 * want to uncompress them. Mark them as uncompressed.
1807dcbf3bd6SGeorge Wilson 	 */
1808dcbf3bd6SGeorge Wilson 	if (!zfs_compressed_arc_enabled || HDR_GET_PSIZE(hdr) == 0) {
1809dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
1810dcbf3bd6SGeorge Wilson 		HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_OFF);
1811dcbf3bd6SGeorge Wilson 		ASSERT(!HDR_COMPRESSION_ENABLED(hdr));
1812dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
1813dcbf3bd6SGeorge Wilson 	} else {
1814dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
1815dcbf3bd6SGeorge Wilson 		HDR_SET_COMPRESS(hdr, cmp);
1816dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, cmp);
1817dcbf3bd6SGeorge Wilson 		ASSERT(HDR_COMPRESSION_ENABLED(hdr));
1818dcbf3bd6SGeorge Wilson 	}
1819dcbf3bd6SGeorge Wilson }
1820244781f1SPrakash Surya 
18215602294fSDan Kimmel /*
18225602294fSDan Kimmel  * Looks for another buf on the same hdr which has the data decompressed, copies
18235602294fSDan Kimmel  * from it, and returns true. If no such buf exists, returns false.
18245602294fSDan Kimmel  */
18255602294fSDan Kimmel static boolean_t
18265602294fSDan Kimmel arc_buf_try_copy_decompressed_data(arc_buf_t *buf)
18275602294fSDan Kimmel {
18285602294fSDan Kimmel 	arc_buf_hdr_t *hdr = buf->b_hdr;
18295602294fSDan Kimmel 	boolean_t copied = B_FALSE;
18305602294fSDan Kimmel 
18315602294fSDan Kimmel 	ASSERT(HDR_HAS_L1HDR(hdr));
18325602294fSDan Kimmel 	ASSERT3P(buf->b_data, !=, NULL);
18335602294fSDan Kimmel 	ASSERT(!ARC_BUF_COMPRESSED(buf));
18345602294fSDan Kimmel 
18355602294fSDan Kimmel 	for (arc_buf_t *from = hdr->b_l1hdr.b_buf; from != NULL;
18365602294fSDan Kimmel 	    from = from->b_next) {
18375602294fSDan Kimmel 		/* can't use our own data buffer */
18385602294fSDan Kimmel 		if (from == buf) {
18395602294fSDan Kimmel 			continue;
18405602294fSDan Kimmel 		}
18415602294fSDan Kimmel 
18425602294fSDan Kimmel 		if (!ARC_BUF_COMPRESSED(from)) {
18435602294fSDan Kimmel 			bcopy(from->b_data, buf->b_data, arc_buf_size(buf));
18445602294fSDan Kimmel 			copied = B_TRUE;
18455602294fSDan Kimmel 			break;
18465602294fSDan Kimmel 		}
18475602294fSDan Kimmel 	}
18485602294fSDan Kimmel 
18495602294fSDan Kimmel 	/*
18505602294fSDan Kimmel 	 * There were no decompressed bufs, so there should not be a
18515602294fSDan Kimmel 	 * checksum on the hdr either.
18525602294fSDan Kimmel 	 */
18535602294fSDan Kimmel 	EQUIV(!copied, hdr->b_l1hdr.b_freeze_cksum == NULL);
18545602294fSDan Kimmel 
18555602294fSDan Kimmel 	return (copied);
18565602294fSDan Kimmel }
18575602294fSDan Kimmel 
18585602294fSDan Kimmel /*
18595602294fSDan Kimmel  * Given a buf that has a data buffer attached to it, this function will
18605602294fSDan Kimmel  * efficiently fill the buf with data of the specified compression setting from
18615602294fSDan Kimmel  * the hdr and update the hdr's b_freeze_cksum if necessary. If the buf and hdr
18625602294fSDan Kimmel  * are already sharing a data buf, no copy is performed.
18635602294fSDan Kimmel  *
18645602294fSDan Kimmel  * If the buf is marked as compressed but uncompressed data was requested, this
18655602294fSDan Kimmel  * will allocate a new data buffer for the buf, remove that flag, and fill the
18665602294fSDan Kimmel  * buf with uncompressed data. You can't request a compressed buf on a hdr with
18675602294fSDan Kimmel  * uncompressed data, and (since we haven't added support for it yet) if you
18685602294fSDan Kimmel  * want compressed data your buf must already be marked as compressed and have
18695602294fSDan Kimmel  * the correct-sized data buffer.
18705602294fSDan Kimmel  */
1871dcbf3bd6SGeorge Wilson static int
18725602294fSDan Kimmel arc_buf_fill(arc_buf_t *buf, boolean_t compressed)
1873dcbf3bd6SGeorge Wilson {
1874dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
18755602294fSDan Kimmel 	boolean_t hdr_compressed = (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
1876dcbf3bd6SGeorge Wilson 	dmu_object_byteswap_t bswap = hdr->b_l1hdr.b_byteswap;
187789c86e32SChris Williamson 
18785602294fSDan Kimmel 	ASSERT3P(buf->b_data, !=, NULL);
18795602294fSDan Kimmel 	IMPLY(compressed, hdr_compressed);
18805602294fSDan Kimmel 	IMPLY(compressed, ARC_BUF_COMPRESSED(buf));
18815602294fSDan Kimmel 
18825602294fSDan Kimmel 	if (hdr_compressed == compressed) {
18835602294fSDan Kimmel 		if (!arc_buf_is_shared(buf)) {
1884*770499e1SDan Kimmel 			abd_copy_to_buf(buf->b_data, hdr->b_l1hdr.b_pabd,
18855602294fSDan Kimmel 			    arc_buf_size(buf));
18865602294fSDan Kimmel 		}
1887dcbf3bd6SGeorge Wilson 	} else {
18885602294fSDan Kimmel 		ASSERT(hdr_compressed);
18895602294fSDan Kimmel 		ASSERT(!compressed);
1890dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, HDR_GET_PSIZE(hdr));
18915602294fSDan Kimmel 
18925602294fSDan Kimmel 		/*
18935602294fSDan Kimmel 		 * If the buf is sharing its data with the hdr, unlink it and
18945602294fSDan Kimmel 		 * allocate a new data buffer for the buf.
18955602294fSDan Kimmel 		 */
18965602294fSDan Kimmel 		if (arc_buf_is_shared(buf)) {
18975602294fSDan Kimmel 			ASSERT(ARC_BUF_COMPRESSED(buf));
18985602294fSDan Kimmel 
18995602294fSDan Kimmel 			/* We need to give the buf it's own b_data */
19005602294fSDan Kimmel 			buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
19015602294fSDan Kimmel 			buf->b_data =
19025602294fSDan Kimmel 			    arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
19035602294fSDan Kimmel 			arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
19045602294fSDan Kimmel 
19055602294fSDan Kimmel 			/* Previously overhead was 0; just add new overhead */
19065602294fSDan Kimmel 			ARCSTAT_INCR(arcstat_overhead_size, HDR_GET_LSIZE(hdr));
19075602294fSDan Kimmel 		} else if (ARC_BUF_COMPRESSED(buf)) {
19085602294fSDan Kimmel 			/* We need to reallocate the buf's b_data */
19095602294fSDan Kimmel 			arc_free_data_buf(hdr, buf->b_data, HDR_GET_PSIZE(hdr),
19105602294fSDan Kimmel 			    buf);
19115602294fSDan Kimmel 			buf->b_data =
19125602294fSDan Kimmel 			    arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
19135602294fSDan Kimmel 
19145602294fSDan Kimmel 			/* We increased the size of b_data; update overhead */
19155602294fSDan Kimmel 			ARCSTAT_INCR(arcstat_overhead_size,
19165602294fSDan Kimmel 			    HDR_GET_LSIZE(hdr) - HDR_GET_PSIZE(hdr));
19175602294fSDan Kimmel 		}
19185602294fSDan Kimmel 
19195602294fSDan Kimmel 		/*
19205602294fSDan Kimmel 		 * Regardless of the buf's previous compression settings, it
19215602294fSDan Kimmel 		 * should not be compressed at the end of this function.
19225602294fSDan Kimmel 		 */
19235602294fSDan Kimmel 		buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
19245602294fSDan Kimmel 
19255602294fSDan Kimmel 		/*
19265602294fSDan Kimmel 		 * Try copying the data from another buf which already has a
19275602294fSDan Kimmel 		 * decompressed version. If that's not possible, it's time to
19285602294fSDan Kimmel 		 * bite the bullet and decompress the data from the hdr.
19295602294fSDan Kimmel 		 */
19305602294fSDan Kimmel 		if (arc_buf_try_copy_decompressed_data(buf)) {
19315602294fSDan Kimmel 			/* Skip byteswapping and checksumming (already done) */
19325602294fSDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, !=, NULL);
19335602294fSDan Kimmel 			return (0);
19345602294fSDan Kimmel 		} else {
19355602294fSDan Kimmel 			int error = zio_decompress_data(HDR_GET_COMPRESS(hdr),
1936*770499e1SDan Kimmel 			    hdr->b_l1hdr.b_pabd, buf->b_data,
19375602294fSDan Kimmel 			    HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
19385602294fSDan Kimmel 
19395602294fSDan Kimmel 			/*
19405602294fSDan Kimmel 			 * Absent hardware errors or software bugs, this should
19415602294fSDan Kimmel 			 * be impossible, but log it anyway so we can debug it.
19425602294fSDan Kimmel 			 */
19435602294fSDan Kimmel 			if (error != 0) {
19445602294fSDan Kimmel 				zfs_dbgmsg(
19455602294fSDan Kimmel 				    "hdr %p, compress %d, psize %d, lsize %d",
19465602294fSDan Kimmel 				    hdr, HDR_GET_COMPRESS(hdr),
19475602294fSDan Kimmel 				    HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
19485602294fSDan Kimmel 				return (SET_ERROR(EIO));
19495602294fSDan Kimmel 			}
1950ea8dc4b6Seschrock 		}
1951fa9e4066Sahrens 	}
19525602294fSDan Kimmel 
19535602294fSDan Kimmel 	/* Byteswap the buf's data if necessary */
1954dcbf3bd6SGeorge Wilson 	if (bswap != DMU_BSWAP_NUMFUNCS) {
1955dcbf3bd6SGeorge Wilson 		ASSERT(!HDR_SHARED_DATA(hdr));
1956dcbf3bd6SGeorge Wilson 		ASSERT3U(bswap, <, DMU_BSWAP_NUMFUNCS);
1957dcbf3bd6SGeorge Wilson 		dmu_ot_byteswap[bswap].ob_func(buf->b_data, HDR_GET_LSIZE(hdr));
1958dcbf3bd6SGeorge Wilson 	}
19595602294fSDan Kimmel 
19605602294fSDan Kimmel 	/* Compute the hdr's checksum if necessary */
1961dcbf3bd6SGeorge Wilson 	arc_cksum_compute(buf);
19625602294fSDan Kimmel 
1963dcbf3bd6SGeorge Wilson 	return (0);
1964fa9e4066Sahrens }
1965fa9e4066Sahrens 
19665602294fSDan Kimmel int
19675602294fSDan Kimmel arc_decompress(arc_buf_t *buf)
19685602294fSDan Kimmel {
19695602294fSDan Kimmel 	return (arc_buf_fill(buf, B_FALSE));
19705602294fSDan Kimmel }
19715602294fSDan Kimmel 
1972dcbf3bd6SGeorge Wilson /*
1973*770499e1SDan Kimmel  * Return the size of the block, b_pabd, that is stored in the arc_buf_hdr_t.
1974dcbf3bd6SGeorge Wilson  */
1975dcbf3bd6SGeorge Wilson static uint64_t
1976dcbf3bd6SGeorge Wilson arc_hdr_size(arc_buf_hdr_t *hdr)
1977fa9e4066Sahrens {
1978dcbf3bd6SGeorge Wilson 	uint64_t size;
1979fa9e4066Sahrens 
1980dcbf3bd6SGeorge Wilson 	if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
1981dcbf3bd6SGeorge Wilson 	    HDR_GET_PSIZE(hdr) > 0) {
1982dcbf3bd6SGeorge Wilson 		size = HDR_GET_PSIZE(hdr);
1983dcbf3bd6SGeorge Wilson 	} else {
1984dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, 0);
1985dcbf3bd6SGeorge Wilson 		size = HDR_GET_LSIZE(hdr);
1986dcbf3bd6SGeorge Wilson 	}
1987dcbf3bd6SGeorge Wilson 	return (size);
1988dcbf3bd6SGeorge Wilson }
1989fa9e4066Sahrens 
1990dcbf3bd6SGeorge Wilson /*
1991dcbf3bd6SGeorge Wilson  * Increment the amount of evictable space in the arc_state_t's refcount.
1992dcbf3bd6SGeorge Wilson  * We account for the space used by the hdr and the arc buf individually
1993dcbf3bd6SGeorge Wilson  * so that we can add and remove them from the refcount individually.
1994dcbf3bd6SGeorge Wilson  */
1995dcbf3bd6SGeorge Wilson static void
1996dcbf3bd6SGeorge Wilson arc_evictable_space_increment(arc_buf_hdr_t *hdr, arc_state_t *state)
1997dcbf3bd6SGeorge Wilson {
1998dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type = arc_buf_type(hdr);
1999244781f1SPrakash Surya 
2000dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
20010e8c6158Smaybee 
2002dcbf3bd6SGeorge Wilson 	if (GHOST_STATE(state)) {
2003dcbf3bd6SGeorge Wilson 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
2004dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2005*770499e1SDan Kimmel 		ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
20065602294fSDan Kimmel 		(void) refcount_add_many(&state->arcs_esize[type],
20075602294fSDan Kimmel 		    HDR_GET_LSIZE(hdr), hdr);
2008dcbf3bd6SGeorge Wilson 		return;
2009dcbf3bd6SGeorge Wilson 	}
2010dcbf3bd6SGeorge Wilson 
2011dcbf3bd6SGeorge Wilson 	ASSERT(!GHOST_STATE(state));
2012*770499e1SDan Kimmel 	if (hdr->b_l1hdr.b_pabd != NULL) {
2013dcbf3bd6SGeorge Wilson 		(void) refcount_add_many(&state->arcs_esize[type],
2014dcbf3bd6SGeorge Wilson 		    arc_hdr_size(hdr), hdr);
2015dcbf3bd6SGeorge Wilson 	}
2016dcbf3bd6SGeorge Wilson 	for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2017dcbf3bd6SGeorge Wilson 	    buf = buf->b_next) {
20185602294fSDan Kimmel 		if (arc_buf_is_shared(buf))
2019dcbf3bd6SGeorge Wilson 			continue;
20205602294fSDan Kimmel 		(void) refcount_add_many(&state->arcs_esize[type],
20215602294fSDan Kimmel 		    arc_buf_size(buf), buf);
2022fa9e4066Sahrens 	}
2023fa9e4066Sahrens }
2024fa9e4066Sahrens 
2025fa9e4066Sahrens /*
2026dcbf3bd6SGeorge Wilson  * Decrement the amount of evictable space in the arc_state_t's refcount.
2027dcbf3bd6SGeorge Wilson  * We account for the space used by the hdr and the arc buf individually
2028dcbf3bd6SGeorge Wilson  * so that we can add and remove them from the refcount individually.
2029fa9e4066Sahrens  */
2030fa9e4066Sahrens static void
20315602294fSDan Kimmel arc_evictable_space_decrement(arc_buf_hdr_t *hdr, arc_state_t *state)
2032fa9e4066Sahrens {
2033dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type = arc_buf_type(hdr);
2034dcbf3bd6SGeorge Wilson 
2035dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2036dcbf3bd6SGeorge Wilson 
2037dcbf3bd6SGeorge Wilson 	if (GHOST_STATE(state)) {
2038dcbf3bd6SGeorge Wilson 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
2039dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2040*770499e1SDan Kimmel 		ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2041dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_esize[type],
20425602294fSDan Kimmel 		    HDR_GET_LSIZE(hdr), hdr);
2043dcbf3bd6SGeorge Wilson 		return;
2044dcbf3bd6SGeorge Wilson 	}
2045dcbf3bd6SGeorge Wilson 
2046dcbf3bd6SGeorge Wilson 	ASSERT(!GHOST_STATE(state));
2047*770499e1SDan Kimmel 	if (hdr->b_l1hdr.b_pabd != NULL) {
2048dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_esize[type],
2049dcbf3bd6SGeorge Wilson 		    arc_hdr_size(hdr), hdr);
2050dcbf3bd6SGeorge Wilson 	}
2051dcbf3bd6SGeorge Wilson 	for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2052dcbf3bd6SGeorge Wilson 	    buf = buf->b_next) {
20535602294fSDan Kimmel 		if (arc_buf_is_shared(buf))
2054dcbf3bd6SGeorge Wilson 			continue;
2055dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_esize[type],
20565602294fSDan Kimmel 		    arc_buf_size(buf), buf);
2057dcbf3bd6SGeorge Wilson 	}
2058dcbf3bd6SGeorge Wilson }
2059dcbf3bd6SGeorge Wilson 
2060dcbf3bd6SGeorge Wilson /*
2061dcbf3bd6SGeorge Wilson  * Add a reference to this hdr indicating that someone is actively
2062dcbf3bd6SGeorge Wilson  * referencing that memory. When the refcount transitions from 0 to 1,
2063dcbf3bd6SGeorge Wilson  * we remove it from the respective arc_state_t list to indicate that
2064dcbf3bd6SGeorge Wilson  * it is not evictable.
2065dcbf3bd6SGeorge Wilson  */
2066dcbf3bd6SGeorge Wilson static void
2067dcbf3bd6SGeorge Wilson add_reference(arc_buf_hdr_t *hdr, void *tag)
2068dcbf3bd6SGeorge Wilson {
2069dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2070dcbf3bd6SGeorge Wilson 	if (!MUTEX_HELD(HDR_LOCK(hdr))) {
2071dcbf3bd6SGeorge Wilson 		ASSERT(hdr->b_l1hdr.b_state == arc_anon);
2072dcbf3bd6SGeorge Wilson 		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2073dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2074dcbf3bd6SGeorge Wilson 	}
2075dcbf3bd6SGeorge Wilson 
2076dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
2077dcbf3bd6SGeorge Wilson 
2078dcbf3bd6SGeorge Wilson 	if ((refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
2079dcbf3bd6SGeorge Wilson 	    (state != arc_anon)) {
2080dcbf3bd6SGeorge Wilson 		/* We don't use the L2-only state list. */
2081dcbf3bd6SGeorge Wilson 		if (state != arc_l2c_only) {
208294c2d0ebSMatthew Ahrens 			multilist_remove(state->arcs_list[arc_buf_type(hdr)],
2083dcbf3bd6SGeorge Wilson 			    hdr);
20845602294fSDan Kimmel 			arc_evictable_space_decrement(hdr, state);
2085dcbf3bd6SGeorge Wilson 		}
2086dcbf3bd6SGeorge Wilson 		/* remove the prefetch flag if we get a reference */
2087dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
2088dcbf3bd6SGeorge Wilson 	}
2089dcbf3bd6SGeorge Wilson }
2090dcbf3bd6SGeorge Wilson 
2091dcbf3bd6SGeorge Wilson /*
2092dcbf3bd6SGeorge Wilson  * Remove a reference from this hdr. When the reference transitions from
2093dcbf3bd6SGeorge Wilson  * 1 to 0 and we're not anonymous, then we add this hdr to the arc_state_t's
2094dcbf3bd6SGeorge Wilson  * list making it eligible for eviction.
2095dcbf3bd6SGeorge Wilson  */
2096dcbf3bd6SGeorge Wilson static int
2097dcbf3bd6SGeorge Wilson remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
2098dcbf3bd6SGeorge Wilson {
2099dcbf3bd6SGeorge Wilson 	int cnt;
2100dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
2101dcbf3bd6SGeorge Wilson 
2102dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2103dcbf3bd6SGeorge Wilson 	ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
2104dcbf3bd6SGeorge Wilson 	ASSERT(!GHOST_STATE(state));
2105dcbf3bd6SGeorge Wilson 
2106dcbf3bd6SGeorge Wilson 	/*
2107dcbf3bd6SGeorge Wilson 	 * arc_l2c_only counts as a ghost state so we don't need to explicitly
2108dcbf3bd6SGeorge Wilson 	 * check to prevent usage of the arc_l2c_only list.
2109dcbf3bd6SGeorge Wilson 	 */
2110dcbf3bd6SGeorge Wilson 	if (((cnt = refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
2111dcbf3bd6SGeorge Wilson 	    (state != arc_anon)) {
211294c2d0ebSMatthew Ahrens 		multilist_insert(state->arcs_list[arc_buf_type(hdr)], hdr);
2113dcbf3bd6SGeorge Wilson 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
2114dcbf3bd6SGeorge Wilson 		arc_evictable_space_increment(hdr, state);
2115dcbf3bd6SGeorge Wilson 	}
2116dcbf3bd6SGeorge Wilson 	return (cnt);
2117dcbf3bd6SGeorge Wilson }
2118dcbf3bd6SGeorge Wilson 
2119dcbf3bd6SGeorge Wilson /*
2120dcbf3bd6SGeorge Wilson  * Move the supplied buffer to the indicated state. The hash lock
2121dcbf3bd6SGeorge Wilson  * for the buffer must be held by the caller.
2122dcbf3bd6SGeorge Wilson  */
2123dcbf3bd6SGeorge Wilson static void
2124dcbf3bd6SGeorge Wilson arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
2125dcbf3bd6SGeorge Wilson     kmutex_t *hash_lock)
2126dcbf3bd6SGeorge Wilson {
2127dcbf3bd6SGeorge Wilson 	arc_state_t *old_state;
2128dcbf3bd6SGeorge Wilson 	int64_t refcnt;
2129dcbf3bd6SGeorge Wilson 	uint32_t bufcnt;
2130dcbf3bd6SGeorge Wilson 	boolean_t update_old, update_new;
2131dcbf3bd6SGeorge Wilson 	arc_buf_contents_t buftype = arc_buf_type(hdr);
213289c86e32SChris Williamson 
213389c86e32SChris Williamson 	/*
213489c86e32SChris Williamson 	 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
213589c86e32SChris Williamson 	 * in arc_read() when bringing a buffer out of the L2ARC.  However, the
213689c86e32SChris Williamson 	 * L1 hdr doesn't always exist when we change state to arc_anon before
213789c86e32SChris Williamson 	 * destroying a header, in which case reallocating to add the L1 hdr is
213889c86e32SChris Williamson 	 * pointless.
213989c86e32SChris Williamson 	 */
214089c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr)) {
214189c86e32SChris Williamson 		old_state = hdr->b_l1hdr.b_state;
214289c86e32SChris Williamson 		refcnt = refcount_count(&hdr->b_l1hdr.b_refcnt);
2143dcbf3bd6SGeorge Wilson 		bufcnt = hdr->b_l1hdr.b_bufcnt;
2144*770499e1SDan Kimmel 		update_old = (bufcnt > 0 || hdr->b_l1hdr.b_pabd != NULL);
214589c86e32SChris Williamson 	} else {
214689c86e32SChris Williamson 		old_state = arc_l2c_only;
214789c86e32SChris Williamson 		refcnt = 0;
2148dcbf3bd6SGeorge Wilson 		bufcnt = 0;
2149dcbf3bd6SGeorge Wilson 		update_old = B_FALSE;
215089c86e32SChris Williamson 	}
2151dcbf3bd6SGeorge Wilson 	update_new = update_old;
2152fa9e4066Sahrens 
2153fa9e4066Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
215469962b56SMatthew Ahrens 	ASSERT3P(new_state, !=, old_state);
2155dcbf3bd6SGeorge Wilson 	ASSERT(!GHOST_STATE(new_state) || bufcnt == 0);
2156dcbf3bd6SGeorge Wilson 	ASSERT(old_state != arc_anon || bufcnt <= 1);
2157fa9e4066Sahrens 
2158fa9e4066Sahrens 	/*
2159fa9e4066Sahrens 	 * If this buffer is evictable, transfer it from the
2160fa9e4066Sahrens 	 * old state list to the new state list.
2161fa9e4066Sahrens 	 */
2162ea8dc4b6Seschrock 	if (refcnt == 0) {
216389c86e32SChris Williamson 		if (old_state != arc_anon && old_state != arc_l2c_only) {
216489c86e32SChris Williamson 			ASSERT(HDR_HAS_L1HDR(hdr));
216594c2d0ebSMatthew Ahrens 			multilist_remove(old_state->arcs_list[buftype], hdr);
2166ea8dc4b6Seschrock 
2167dcbf3bd6SGeorge Wilson 			if (GHOST_STATE(old_state)) {
2168dcbf3bd6SGeorge Wilson 				ASSERT0(bufcnt);
2169dcbf3bd6SGeorge Wilson 				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2170dcbf3bd6SGeorge Wilson 				update_old = B_TRUE;
2171ea8dc4b6Seschrock 			}
21725602294fSDan Kimmel 			arc_evictable_space_decrement(hdr, old_state);
2173fa9e4066Sahrens 		}
217489c86e32SChris Williamson 		if (new_state != arc_anon && new_state != arc_l2c_only) {
2175fa9e4066Sahrens 
217689c86e32SChris Williamson 			/*
217789c86e32SChris Williamson 			 * An L1 header always exists here, since if we're
217889c86e32SChris Williamson 			 * moving to some L1-cached state (i.e. not l2c_only or
217989c86e32SChris Williamson 			 * anonymous), we realloc the header to add an L1hdr
218089c86e32SChris Williamson 			 * beforehand.
218189c86e32SChris Williamson 			 */
218289c86e32SChris Williamson 			ASSERT(HDR_HAS_L1HDR(hdr));
218394c2d0ebSMatthew Ahrens 			multilist_insert(new_state->arcs_list[buftype], hdr);
2184ea8dc4b6Seschrock 
2185ea8dc4b6Seschrock 			if (GHOST_STATE(new_state)) {
2186dcbf3bd6SGeorge Wilson 				ASSERT0(bufcnt);
2187dcbf3bd6SGeorge Wilson 				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2188dcbf3bd6SGeorge Wilson 				update_new = B_TRUE;
2189ea8dc4b6Seschrock 			}
2190dcbf3bd6SGeorge Wilson 			arc_evictable_space_increment(hdr, new_state);
2191fa9e4066Sahrens 		}
2192fa9e4066Sahrens 	}
2193fa9e4066Sahrens 
2194dcbf3bd6SGeorge Wilson 	ASSERT(!HDR_EMPTY(hdr));
21957adb730bSGeorge Wilson 	if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
21967adb730bSGeorge Wilson 		buf_hash_remove(hdr);
2197fa9e4066Sahrens 
219889c86e32SChris Williamson 	/* adjust state sizes (ignore arc_l2c_only) */
21992fd872a7SPrakash Surya 
2200dcbf3bd6SGeorge Wilson 	if (update_new && new_state != arc_l2c_only) {
22012fd872a7SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(hdr));
22022fd872a7SPrakash Surya 		if (GHOST_STATE(new_state)) {
2203dcbf3bd6SGeorge Wilson 			ASSERT0(bufcnt);
22042fd872a7SPrakash Surya 
22052fd872a7SPrakash Surya 			/*
2206dcbf3bd6SGeorge Wilson 			 * When moving a header to a ghost state, we first
22072fd872a7SPrakash Surya 			 * remove all arc buffers. Thus, we'll have a
2208dcbf3bd6SGeorge Wilson 			 * bufcnt of zero, and no arc buffer to use for
22092fd872a7SPrakash Surya 			 * the reference. As a result, we use the arc
22102fd872a7SPrakash Surya 			 * header pointer for the reference.
22112fd872a7SPrakash Surya 			 */
22122fd872a7SPrakash Surya 			(void) refcount_add_many(&new_state->arcs_size,
2213dcbf3bd6SGeorge Wilson 			    HDR_GET_LSIZE(hdr), hdr);
2214*770499e1SDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
22152fd872a7SPrakash Surya 		} else {
2216dcbf3bd6SGeorge Wilson 			uint32_t buffers = 0;
22172fd872a7SPrakash Surya 
22182fd872a7SPrakash Surya 			/*
22192fd872a7SPrakash Surya 			 * Each individual buffer holds a unique reference,
22202fd872a7SPrakash Surya 			 * thus we must remove each of these references one
22212fd872a7SPrakash Surya 			 * at a time.
22222fd872a7SPrakash Surya 			 */
22232fd872a7SPrakash Surya 			for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
22242fd872a7SPrakash Surya 			    buf = buf->b_next) {
2225dcbf3bd6SGeorge Wilson 				ASSERT3U(bufcnt, !=, 0);
2226dcbf3bd6SGeorge Wilson 				buffers++;
2227dcbf3bd6SGeorge Wilson 
2228dcbf3bd6SGeorge Wilson 				/*
2229dcbf3bd6SGeorge Wilson 				 * When the arc_buf_t is sharing the data
2230dcbf3bd6SGeorge Wilson 				 * block with the hdr, the owner of the
2231dcbf3bd6SGeorge Wilson 				 * reference belongs to the hdr. Only
2232dcbf3bd6SGeorge Wilson 				 * add to the refcount if the arc_buf_t is
2233dcbf3bd6SGeorge Wilson 				 * not shared.
2234dcbf3bd6SGeorge Wilson 				 */
22355602294fSDan Kimmel 				if (arc_buf_is_shared(buf))
2236dcbf3bd6SGeorge Wilson 					continue;
2237dcbf3bd6SGeorge Wilson 
22382fd872a7SPrakash Surya 				(void) refcount_add_many(&new_state->arcs_size,
22395602294fSDan Kimmel 				    arc_buf_size(buf), buf);
2240dcbf3bd6SGeorge Wilson 			}
2241dcbf3bd6SGeorge Wilson 			ASSERT3U(bufcnt, ==, buffers);
2242dcbf3bd6SGeorge Wilson 
2243*770499e1SDan Kimmel 			if (hdr->b_l1hdr.b_pabd != NULL) {
2244dcbf3bd6SGeorge Wilson 				(void) refcount_add_many(&new_state->arcs_size,
2245dcbf3bd6SGeorge Wilson 				    arc_hdr_size(hdr), hdr);
2246dcbf3bd6SGeorge Wilson 			} else {
2247dcbf3bd6SGeorge Wilson 				ASSERT(GHOST_STATE(old_state));
22482fd872a7SPrakash Surya 			}
22492fd872a7SPrakash Surya 		}
22502fd872a7SPrakash Surya 	}
22512fd872a7SPrakash Surya 
2252dcbf3bd6SGeorge Wilson 	if (update_old && old_state != arc_l2c_only) {
22532fd872a7SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(hdr));
22542fd872a7SPrakash Surya 		if (GHOST_STATE(old_state)) {
2255dcbf3bd6SGeorge Wilson 			ASSERT0(bufcnt);
2256*770499e1SDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2257dcbf3bd6SGeorge Wilson 
22582fd872a7SPrakash Surya 			/*
22592fd872a7SPrakash Surya 			 * When moving a header off of a ghost state,
2260dcbf3bd6SGeorge Wilson 			 * the header will not contain any arc buffers.
2261dcbf3bd6SGeorge Wilson 			 * We use the arc header pointer for the reference
2262dcbf3bd6SGeorge Wilson 			 * which is exactly what we did when we put the
2263dcbf3bd6SGeorge Wilson 			 * header on the ghost state.
22642fd872a7SPrakash Surya 			 */
22652fd872a7SPrakash Surya 
22662fd872a7SPrakash Surya 			(void) refcount_remove_many(&old_state->arcs_size,
2267dcbf3bd6SGeorge Wilson 			    HDR_GET_LSIZE(hdr), hdr);
22682fd872a7SPrakash Surya 		} else {
2269dcbf3bd6SGeorge Wilson 			uint32_t buffers = 0;
22702fd872a7SPrakash Surya 
22712fd872a7SPrakash Surya 			/*
22722fd872a7SPrakash Surya 			 * Each individual buffer holds a unique reference,
22732fd872a7SPrakash Surya 			 * thus we must remove each of these references one
22742fd872a7SPrakash Surya 			 * at a time.
22752fd872a7SPrakash Surya 			 */
22762fd872a7SPrakash Surya 			for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
22772fd872a7SPrakash Surya 			    buf = buf->b_next) {
22785602294fSDan Kimmel 				ASSERT3U(bufcnt, !=, 0);
2279dcbf3bd6SGeorge Wilson 				buffers++;
2280dcbf3bd6SGeorge Wilson 
2281dcbf3bd6SGeorge Wilson 				/*
2282dcbf3bd6SGeorge Wilson 				 * When the arc_buf_t is sharing the data
2283dcbf3bd6SGeorge Wilson 				 * block with the hdr, the owner of the
2284dcbf3bd6SGeorge Wilson 				 * reference belongs to the hdr. Only
2285dcbf3bd6SGeorge Wilson 				 * add to the refcount if the arc_buf_t is
2286dcbf3bd6SGeorge Wilson 				 * not shared.
2287dcbf3bd6SGeorge Wilson 				 */
22885602294fSDan Kimmel 				if (arc_buf_is_shared(buf))
2289dcbf3bd6SGeorge Wilson 					continue;
2290dcbf3bd6SGeorge Wilson 
22912fd872a7SPrakash Surya 				(void) refcount_remove_many(
22925602294fSDan Kimmel 				    &old_state->arcs_size, arc_buf_size(buf),
2293dcbf3bd6SGeorge Wilson 				    buf);
22942fd872a7SPrakash Surya 			}
2295dcbf3bd6SGeorge Wilson 			ASSERT3U(bufcnt, ==, buffers);
2296*770499e1SDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2297dcbf3bd6SGeorge Wilson 			(void) refcount_remove_many(
2298dcbf3bd6SGeorge Wilson 			    &old_state->arcs_size, arc_hdr_size(hdr), hdr);
22992fd872a7SPrakash Surya 		}
2300fa9e4066Sahrens 	}
23012fd872a7SPrakash Surya 
230289c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr))
230389c86e32SChris Williamson 		hdr->b_l1hdr.b_state = new_state;
2304fa94a07fSbrendan 
230589c86e32SChris Williamson 	/*
230689c86e32SChris Williamson 	 * L2 headers should never be on the L2 state list since they don't
230789c86e32SChris Williamson 	 * have L1 headers allocated.
230889c86e32SChris Williamson 	 */
230994c2d0ebSMatthew Ahrens 	ASSERT(multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
231094c2d0ebSMatthew Ahrens 	    multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
2311fa9e4066Sahrens }
2312fa9e4066Sahrens 
23130e8c6158Smaybee void
23145a98e54bSBrendan Gregg - Sun Microsystems arc_space_consume(uint64_t space, arc_space_type_t type)
23150e8c6158Smaybee {
23165a98e54bSBrendan Gregg - Sun Microsystems 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
23175a98e54bSBrendan Gregg - Sun Microsystems 
23185a98e54bSBrendan Gregg - Sun Microsystems 	switch (type) {
23195a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_DATA:
23205a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_data_size, space);
23215a98e54bSBrendan Gregg - Sun Microsystems 		break;
23224076b1bfSPrakash Surya 	case ARC_SPACE_META:
23234076b1bfSPrakash Surya 		ARCSTAT_INCR(arcstat_metadata_size, space);
23244076b1bfSPrakash Surya 		break;
23255a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_OTHER:
23265a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_other_size, space);
23275a98e54bSBrendan Gregg - Sun Microsystems 		break;
23285a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_HDRS:
23295a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_hdr_size, space);
23305a98e54bSBrendan Gregg - Sun Microsystems 		break;
23315a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_L2HDRS:
23325a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_l2_hdr_size, space);
23335a98e54bSBrendan Gregg - Sun Microsystems 		break;
23345a98e54bSBrendan Gregg - Sun Microsystems 	}
23355a98e54bSBrendan Gregg - Sun Microsystems 
23364076b1bfSPrakash Surya 	if (type != ARC_SPACE_DATA)
23374076b1bfSPrakash Surya 		ARCSTAT_INCR(arcstat_meta_used, space);
23384076b1bfSPrakash Surya 
23390e8c6158Smaybee 	atomic_add_64(&arc_size, space);
23400e8c6158Smaybee }
23410e8c6158Smaybee 
23420e8c6158Smaybee void
23435a98e54bSBrendan Gregg - Sun Microsystems arc_space_return(uint64_t space, arc_space_type_t type)
23440e8c6158Smaybee {
23455a98e54bSBrendan Gregg - Sun Microsystems 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
23465a98e54bSBrendan Gregg - Sun Microsystems 
23475a98e54bSBrendan Gregg - Sun Microsystems 	switch (type) {
23485a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_DATA:
23495a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_data_size, -space);
23505a98e54bSBrendan Gregg - Sun Microsystems 		break;
23514076b1bfSPrakash Surya 	case ARC_SPACE_META:
23524076b1bfSPrakash Surya 		ARCSTAT_INCR(arcstat_metadata_size, -space);
23534076b1bfSPrakash Surya 		break;
23545a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_OTHER:
23555a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_other_size, -space);
23565a98e54bSBrendan Gregg - Sun Microsystems 		break;
23575a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_HDRS:
23585a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_hdr_size, -space);
23595a98e54bSBrendan Gregg - Sun Microsystems 		break;
23605a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_L2HDRS:
23615a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
23625a98e54bSBrendan Gregg - Sun Microsystems 		break;
23635a98e54bSBrendan Gregg - Sun Microsystems 	}
23645a98e54bSBrendan Gregg - Sun Microsystems 
23654076b1bfSPrakash Surya 	if (type != ARC_SPACE_DATA) {
23664076b1bfSPrakash Surya 		ASSERT(arc_meta_used >= space);
23674076b1bfSPrakash Surya 		if (arc_meta_max < arc_meta_used)
23684076b1bfSPrakash Surya 			arc_meta_max = arc_meta_used;
23694076b1bfSPrakash Surya 		ARCSTAT_INCR(arcstat_meta_used, -space);
23704076b1bfSPrakash Surya 	}
23714076b1bfSPrakash Surya 
23720e8c6158Smaybee 	ASSERT(arc_size >= space);
23730e8c6158Smaybee 	atomic_add_64(&arc_size, -space);
23740e8c6158Smaybee }
23750e8c6158Smaybee 
2376dcbf3bd6SGeorge Wilson /*
23775602294fSDan Kimmel  * Given a hdr and a buf, returns whether that buf can share its b_data buffer
2378*770499e1SDan Kimmel  * with the hdr's b_pabd.
2379dcbf3bd6SGeorge Wilson  */
23805602294fSDan Kimmel static boolean_t
23815602294fSDan Kimmel arc_can_share(arc_buf_hdr_t *hdr, arc_buf_t *buf)
23825602294fSDan Kimmel {
23835602294fSDan Kimmel 	/*
23845602294fSDan Kimmel 	 * The criteria for sharing a hdr's data are:
23855602294fSDan Kimmel 	 * 1. the hdr's compression matches the buf's compression
23865602294fSDan Kimmel 	 * 2. the hdr doesn't need to be byteswapped
23875602294fSDan Kimmel 	 * 3. the hdr isn't already being shared
23885602294fSDan Kimmel 	 * 4. the buf is either compressed or it is the last buf in the hdr list
23895602294fSDan Kimmel 	 *
23905602294fSDan Kimmel 	 * Criterion #4 maintains the invariant that shared uncompressed
23915602294fSDan Kimmel 	 * bufs must be the final buf in the hdr's b_buf list. Reading this, you
23925602294fSDan Kimmel 	 * might ask, "if a compressed buf is allocated first, won't that be the
23935602294fSDan Kimmel 	 * last thing in the list?", but in that case it's impossible to create
23945602294fSDan Kimmel 	 * a shared uncompressed buf anyway (because the hdr must be compressed
23955602294fSDan Kimmel 	 * to have the compressed buf). You might also think that #3 is
23965602294fSDan Kimmel 	 * sufficient to make this guarantee, however it's possible
23975602294fSDan Kimmel 	 * (specifically in the rare L2ARC write race mentioned in
23985602294fSDan Kimmel 	 * arc_buf_alloc_impl()) there will be an existing uncompressed buf that
23995602294fSDan Kimmel 	 * is sharable, but wasn't at the time of its allocation. Rather than
24005602294fSDan Kimmel 	 * allow a new shared uncompressed buf to be created and then shuffle
24015602294fSDan Kimmel 	 * the list around to make it the last element, this simply disallows
24025602294fSDan Kimmel 	 * sharing if the new buf isn't the first to be added.
24035602294fSDan Kimmel 	 */
24045602294fSDan Kimmel 	ASSERT3P(buf->b_hdr, ==, hdr);
24055602294fSDan Kimmel 	boolean_t hdr_compressed = HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF;
24065602294fSDan Kimmel 	boolean_t buf_compressed = ARC_BUF_COMPRESSED(buf) != 0;
24075602294fSDan Kimmel 	return (buf_compressed == hdr_compressed &&
24085602294fSDan Kimmel 	    hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS &&
24095602294fSDan Kimmel 	    !HDR_SHARED_DATA(hdr) &&
24105602294fSDan Kimmel 	    (ARC_BUF_LAST(buf) || ARC_BUF_COMPRESSED(buf)));
24115602294fSDan Kimmel }
24125602294fSDan Kimmel 
24135602294fSDan Kimmel /*
24145602294fSDan Kimmel  * Allocate a buf for this hdr. If you care about the data that's in the hdr,
24155602294fSDan Kimmel  * or if you want a compressed buffer, pass those flags in. Returns 0 if the
24165602294fSDan Kimmel  * copy was made successfully, or an error code otherwise.
24175602294fSDan Kimmel  */
24185602294fSDan Kimmel static int
24195602294fSDan Kimmel arc_buf_alloc_impl(arc_buf_hdr_t *hdr, void *tag, boolean_t compressed,
24205602294fSDan Kimmel     boolean_t fill, arc_buf_t **ret)
2421fa9e4066Sahrens {
2422fa9e4066Sahrens 	arc_buf_t *buf;
2423fa9e4066Sahrens 
2424dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2425dcbf3bd6SGeorge Wilson 	ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
2426dcbf3bd6SGeorge Wilson 	VERIFY(hdr->b_type == ARC_BUFC_DATA ||
2427dcbf3bd6SGeorge Wilson 	    hdr->b_type == ARC_BUFC_METADATA);
24285602294fSDan Kimmel 	ASSERT3P(ret, !=, NULL);
24295602294fSDan Kimmel 	ASSERT3P(*ret, ==, NULL);
2430dcbf3bd6SGeorge Wilson 
24315602294fSDan Kimmel 	buf = *ret = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2432fa9e4066Sahrens 	buf->b_hdr = hdr;
243344eda4d7Smaybee 	buf->b_data = NULL;
24345602294fSDan Kimmel 	buf->b_next = hdr->b_l1hdr.b_buf;
24355602294fSDan Kimmel 	buf->b_flags = 0;
243689c86e32SChris Williamson 
2437dcbf3bd6SGeorge Wilson 	add_reference(hdr, tag);
2438dcbf3bd6SGeorge Wilson 
2439dcbf3bd6SGeorge Wilson 	/*
2440dcbf3bd6SGeorge Wilson 	 * We're about to change the hdr's b_flags. We must either
2441dcbf3bd6SGeorge Wilson 	 * hold the hash_lock or be undiscoverable.
2442dcbf3bd6SGeorge Wilson 	 */
2443dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2444dcbf3bd6SGeorge Wilson 
2445dcbf3bd6SGeorge Wilson 	/*
24465602294fSDan Kimmel 	 * Only honor requests for compressed bufs if the hdr is actually
24475602294fSDan Kimmel 	 * compressed.
24485602294fSDan Kimmel 	 */
24495602294fSDan Kimmel 	if (compressed && HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF)
24505602294fSDan Kimmel 		buf->b_flags |= ARC_BUF_FLAG_COMPRESSED;
24515602294fSDan Kimmel 
24525602294fSDan Kimmel 	/*
24535602294fSDan Kimmel 	 * If the hdr's data can be shared then we share the data buffer and
24545602294fSDan Kimmel 	 * set the appropriate bit in the hdr's b_flags to indicate the hdr is
2455*770499e1SDan Kimmel 	 * sharing it's b_pabd with the arc_buf_t. Otherwise, we allocate a new
24565602294fSDan Kimmel 	 * buffer to store the buf's data.
24575602294fSDan Kimmel 	 *
2458*770499e1SDan Kimmel 	 * There are two additional restrictions here because we're sharing
2459*770499e1SDan Kimmel 	 * hdr -> buf instead of the usual buf -> hdr. First, the hdr can't be
2460*770499e1SDan Kimmel 	 * actively involved in an L2ARC write, because if this buf is used by
2461*770499e1SDan Kimmel 	 * an arc_write() then the hdr's data buffer will be released when the
24625602294fSDan Kimmel 	 * write completes, even though the L2ARC write might still be using it.
2463*770499e1SDan Kimmel 	 * Second, the hdr's ABD must be linear so that the buf's user doesn't
2464*770499e1SDan Kimmel 	 * need to be ABD-aware.
2465dcbf3bd6SGeorge Wilson 	 */
2466*770499e1SDan Kimmel 	boolean_t can_share = arc_can_share(hdr, buf) && !HDR_L2_WRITING(hdr) &&
2467*770499e1SDan Kimmel 	    abd_is_linear(hdr->b_l1hdr.b_pabd);
24685602294fSDan Kimmel 
24695602294fSDan Kimmel 	/* Set up b_data and sharing */
24705602294fSDan Kimmel 	if (can_share) {
2471*770499e1SDan Kimmel 		buf->b_data = abd_to_buf(hdr->b_l1hdr.b_pabd);
24725602294fSDan Kimmel 		buf->b_flags |= ARC_BUF_FLAG_SHARED;
2473dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
2474dcbf3bd6SGeorge Wilson 	} else {
24755602294fSDan Kimmel 		buf->b_data =
24765602294fSDan Kimmel 		    arc_get_data_buf(hdr, arc_buf_size(buf), buf);
24775602294fSDan Kimmel 		ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
2478dcbf3bd6SGeorge Wilson 	}
2479dcbf3bd6SGeorge Wilson 	VERIFY3P(buf->b_data, !=, NULL);
248089c86e32SChris Williamson 
248189c86e32SChris Williamson 	hdr->b_l1hdr.b_buf = buf;
2482dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_bufcnt += 1;
248389c86e32SChris Williamson 
24845602294fSDan Kimmel 	/*
24855602294fSDan Kimmel 	 * If the user wants the data from the hdr, we need to either copy or
24865602294fSDan Kimmel 	 * decompress the data.
24875602294fSDan Kimmel 	 */
24885602294fSDan Kimmel 	if (fill) {
24895602294fSDan Kimmel 		return (arc_buf_fill(buf, ARC_BUF_COMPRESSED(buf) != 0));
24905602294fSDan Kimmel 	}
2491dcbf3bd6SGeorge Wilson 
24925602294fSDan Kimmel 	return (0);
24935602294fSDan Kimmel }
2494dcbf3bd6SGeorge Wilson 
24955602294fSDan Kimmel static char *arc_onloan_tag = "onloan";
2496fa9e4066Sahrens 
24975602294fSDan Kimmel static inline void
24985602294fSDan Kimmel arc_loaned_bytes_update(int64_t delta)
24995602294fSDan Kimmel {
25005602294fSDan Kimmel 	atomic_add_64(&arc_loaned_bytes, delta);
2501dcbf3bd6SGeorge Wilson 
25025602294fSDan Kimmel 	/* assert that it did not wrap around */
25035602294fSDan Kimmel 	ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
2504fa9e4066Sahrens }
2505fa9e4066Sahrens 
25062fdbea25SAleksandr Guzovskiy /*
25072fdbea25SAleksandr Guzovskiy  * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
25082fdbea25SAleksandr Guzovskiy  * flight data by arc_tempreserve_space() until they are "returned". Loaned
25092fdbea25SAleksandr Guzovskiy  * buffers must be returned to the arc before they can be used by the DMU or
25102fdbea25SAleksandr Guzovskiy  * freed.
25112fdbea25SAleksandr Guzovskiy  */
25122fdbea25SAleksandr Guzovskiy arc_buf_t *
25135602294fSDan Kimmel arc_loan_buf(spa_t *spa, boolean_t is_metadata, int size)
25142fdbea25SAleksandr Guzovskiy {
25155602294fSDan Kimmel 	arc_buf_t *buf = arc_alloc_buf(spa, arc_onloan_tag,
25165602294fSDan Kimmel 	    is_metadata ? ARC_BUFC_METADATA : ARC_BUFC_DATA, size);
25175602294fSDan Kimmel 
25185602294fSDan Kimmel 	arc_loaned_bytes_update(size);
25195602294fSDan Kimmel 
25205602294fSDan Kimmel 	return (buf);
25215602294fSDan Kimmel }
25222fdbea25SAleksandr Guzovskiy 
25235602294fSDan Kimmel arc_buf_t *
25245602294fSDan Kimmel arc_loan_compressed_buf(spa_t *spa, uint64_t psize, uint64_t lsize,
25255602294fSDan Kimmel     enum zio_compress compression_type)
25265602294fSDan Kimmel {
25275602294fSDan Kimmel 	arc_buf_t *buf = arc_alloc_compressed_buf(spa, arc_onloan_tag,
25285602294fSDan Kimmel 	    psize, lsize, compression_type);
25295602294fSDan Kimmel 
25305602294fSDan Kimmel 	arc_loaned_bytes_update(psize);
25312fdbea25SAleksandr Guzovskiy 
25322fdbea25SAleksandr Guzovskiy 	return (buf);
25332fdbea25SAleksandr Guzovskiy }
25342fdbea25SAleksandr Guzovskiy 
25355602294fSDan Kimmel 
25362fdbea25SAleksandr Guzovskiy /*
25372fdbea25SAleksandr Guzovskiy  * Return a loaned arc buffer to the arc.
25382fdbea25SAleksandr Guzovskiy  */
25392fdbea25SAleksandr Guzovskiy void
25402fdbea25SAleksandr Guzovskiy arc_return_buf(arc_buf_t *buf, void *tag)
25412fdbea25SAleksandr Guzovskiy {
25422fdbea25SAleksandr Guzovskiy 	arc_buf_hdr_t *hdr = buf->b_hdr;
25432fdbea25SAleksandr Guzovskiy 
2544dcbf3bd6SGeorge Wilson 	ASSERT3P(buf->b_data, !=, NULL);
254589c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
254689c86e32SChris Williamson 	(void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
254789c86e32SChris Williamson 	(void) refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
25482fdbea25SAleksandr Guzovskiy 
25495602294fSDan Kimmel 	arc_loaned_bytes_update(-arc_buf_size(buf));
25502fdbea25SAleksandr Guzovskiy }
25512fdbea25SAleksandr Guzovskiy 
2552c242f9a0Schunli zhang - Sun Microsystems - Irvine United States /* Detach an arc_buf from a dbuf (tag) */
2553c242f9a0Schunli zhang - Sun Microsystems - Irvine United States void
2554c242f9a0Schunli zhang - Sun Microsystems - Irvine United States arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
2555c242f9a0Schunli zhang - Sun Microsystems - Irvine United States {
255689c86e32SChris Williamson 	arc_buf_hdr_t *hdr = buf->b_hdr;
2557c242f9a0Schunli zhang - Sun Microsystems - Irvine United States 
2558dcbf3bd6SGeorge Wilson 	ASSERT3P(buf->b_data, !=, NULL);
255989c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
256089c86e32SChris Williamson 	(void) refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
256189c86e32SChris Williamson 	(void) refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
2562c242f9a0Schunli zhang - Sun Microsystems - Irvine United States 
25635602294fSDan Kimmel 	arc_loaned_bytes_update(arc_buf_size(buf));
2564c242f9a0Schunli zhang - Sun Microsystems - Irvine United States }
2565c242f9a0Schunli zhang - Sun Microsystems - Irvine United States 
2566dcbf3bd6SGeorge Wilson static void
2567*770499e1SDan Kimmel l2arc_free_abd_on_write(abd_t *abd, size_t size, arc_buf_contents_t type)
2568ea8dc4b6Seschrock {
2569dcbf3bd6SGeorge Wilson 	l2arc_data_free_t *df = kmem_alloc(sizeof (*df), KM_SLEEP);
2570ea8dc4b6Seschrock 
2571*770499e1SDan Kimmel 	df->l2df_abd = abd;
2572dcbf3bd6SGeorge Wilson 	df->l2df_size = size;
2573dcbf3bd6SGeorge Wilson 	df->l2df_type = type;
2574dcbf3bd6SGeorge Wilson 	mutex_enter(&l2arc_free_on_write_mtx);
2575dcbf3bd6SGeorge Wilson 	list_insert_head(l2arc_free_on_write, df);
2576dcbf3bd6SGeorge Wilson 	mutex_exit(&l2arc_free_on_write_mtx);
2577dcbf3bd6SGeorge Wilson }
2578b24ab676SJeff Bonwick 
2579dcbf3bd6SGeorge Wilson static void
2580dcbf3bd6SGeorge Wilson arc_hdr_free_on_write(arc_buf_hdr_t *hdr)
2581dcbf3bd6SGeorge Wilson {
2582dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
2583dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type = arc_buf_type(hdr);
2584dcbf3bd6SGeorge Wilson 	uint64_t size = arc_hdr_size(hdr);
2585dcbf3bd6SGeorge Wilson 
2586dcbf3bd6SGeorge Wilson 	/* protected by hash lock, if in the hash table */
2587dcbf3bd6SGeorge Wilson 	if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
2588dcbf3bd6SGeorge Wilson 		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2589dcbf3bd6SGeorge Wilson 		ASSERT(state != arc_anon && state != arc_l2c_only);
2590dcbf3bd6SGeorge Wilson 
2591dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_esize[type],
2592dcbf3bd6SGeorge Wilson 		    size, hdr);
2593dcbf3bd6SGeorge Wilson 	}
2594dcbf3bd6SGeorge Wilson 	(void) refcount_remove_many(&state->arcs_size, size, hdr);
25956de76ce2SAndriy Gapon 	if (type == ARC_BUFC_METADATA) {
25966de76ce2SAndriy Gapon 		arc_space_return(size, ARC_SPACE_META);
25976de76ce2SAndriy Gapon 	} else {
25986de76ce2SAndriy Gapon 		ASSERT(type == ARC_BUFC_DATA);
25996de76ce2SAndriy Gapon 		arc_space_return(size, ARC_SPACE_DATA);
26006de76ce2SAndriy Gapon 	}
2601dcbf3bd6SGeorge Wilson 
2602*770499e1SDan Kimmel 	l2arc_free_abd_on_write(hdr->b_l1hdr.b_pabd, size, type);
2603dcbf3bd6SGeorge Wilson }
2604dcbf3bd6SGeorge Wilson 
2605dcbf3bd6SGeorge Wilson /*
2606dcbf3bd6SGeorge Wilson  * Share the arc_buf_t's data with the hdr. Whenever we are sharing the
2607dcbf3bd6SGeorge Wilson  * data buffer, we transfer the refcount ownership to the hdr and update
2608dcbf3bd6SGeorge Wilson  * the appropriate kstats.
2609dcbf3bd6SGeorge Wilson  */
2610dcbf3bd6SGeorge Wilson static void
2611dcbf3bd6SGeorge Wilson arc_share_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2612dcbf3bd6SGeorge Wilson {
2613dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
2614dcbf3bd6SGeorge Wilson 
26155602294fSDan Kimmel 	ASSERT(arc_can_share(hdr, buf));
2616*770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2617dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
26189253d63dSGeorge Wilson 
26199253d63dSGeorge Wilson 	/*
2620dcbf3bd6SGeorge Wilson 	 * Start sharing the data buffer. We transfer the
2621dcbf3bd6SGeorge Wilson 	 * refcount ownership to the hdr since it always owns
2622dcbf3bd6SGeorge Wilson 	 * the refcount whenever an arc_buf_t is shared.
26239253d63dSGeorge Wilson 	 */
2624dcbf3bd6SGeorge Wilson 	refcount_transfer_ownership(&state->arcs_size, buf, hdr);
2625*770499e1SDan Kimmel 	hdr->b_l1hdr.b_pabd = abd_get_from_buf(buf->b_data, arc_buf_size(buf));
2626*770499e1SDan Kimmel 	abd_take_ownership_of_buf(hdr->b_l1hdr.b_pabd,
2627*770499e1SDan Kimmel 	    HDR_ISTYPE_METADATA(hdr));
2628dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
26295602294fSDan Kimmel 	buf->b_flags |= ARC_BUF_FLAG_SHARED;
2630dcbf3bd6SGeorge Wilson 
2631dcbf3bd6SGeorge Wilson 	/*
2632dcbf3bd6SGeorge Wilson 	 * Since we've transferred ownership to the hdr we need
2633dcbf3bd6SGeorge Wilson 	 * to increment its compressed and uncompressed kstats and
2634dcbf3bd6SGeorge Wilson 	 * decrement the overhead size.
2635dcbf3bd6SGeorge Wilson 	 */
2636dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
2637dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
26385602294fSDan Kimmel 	ARCSTAT_INCR(arcstat_overhead_size, -arc_buf_size(buf));
2639ea8dc4b6Seschrock }
2640ea8dc4b6Seschrock 
2641dcbf3bd6SGeorge Wilson static void
2642dcbf3bd6SGeorge Wilson arc_unshare_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2643ea8dc4b6Seschrock {
2644dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
2645dcbf3bd6SGeorge Wilson 
2646dcbf3bd6SGeorge Wilson 	ASSERT(arc_buf_is_shared(buf));
2647*770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2648dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2649ea8dc4b6Seschrock 
26509b23f181Smaybee 	/*
2651dcbf3bd6SGeorge Wilson 	 * We are no longer sharing this buffer so we need
2652dcbf3bd6SGeorge Wilson 	 * to transfer its ownership to the rightful owner.
26539b23f181Smaybee 	 */
2654dcbf3bd6SGeorge Wilson 	refcount_transfer_ownership(&state->arcs_size, hdr, buf);
2655dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2656*770499e1SDan Kimmel 	abd_release_ownership_of_buf(hdr->b_l1hdr.b_pabd);
2657*770499e1SDan Kimmel 	abd_put(hdr->b_l1hdr.b_pabd);
2658*770499e1SDan Kimmel 	hdr->b_l1hdr.b_pabd = NULL;
26595602294fSDan Kimmel 	buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
2660dcbf3bd6SGeorge Wilson 
2661dcbf3bd6SGeorge Wilson 	/*
2662dcbf3bd6SGeorge Wilson 	 * Since the buffer is no longer shared between
2663dcbf3bd6SGeorge Wilson 	 * the arc buf and the hdr, count it as overhead.
2664dcbf3bd6SGeorge Wilson 	 */
2665dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
2666dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
26675602294fSDan Kimmel 	ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
2668dcbf3bd6SGeorge Wilson }
2669dcbf3bd6SGeorge Wilson 
2670dcbf3bd6SGeorge Wilson /*
26715602294fSDan Kimmel  * Remove an arc_buf_t from the hdr's buf list and return the last
26725602294fSDan Kimmel  * arc_buf_t on the list. If no buffers remain on the list then return
26735602294fSDan Kimmel  * NULL.
26745602294fSDan Kimmel  */
26755602294fSDan Kimmel static arc_buf_t *
26765602294fSDan Kimmel arc_buf_remove(arc_buf_hdr_t *hdr, arc_buf_t *buf)
26775602294fSDan Kimmel {
26785602294fSDan Kimmel 	ASSERT(HDR_HAS_L1HDR(hdr));
26795602294fSDan Kimmel 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
26805602294fSDan Kimmel 
26815602294fSDan Kimmel 	arc_buf_t **bufp = &hdr->b_l1hdr.b_buf;
26825602294fSDan Kimmel 	arc_buf_t *lastbuf = NULL;
26835602294fSDan Kimmel 
26845602294fSDan Kimmel 	/*
26855602294fSDan Kimmel 	 * Remove the buf from the hdr list and locate the last
26865602294fSDan Kimmel 	 * remaining buffer on the list.
26875602294fSDan Kimmel 	 */
26885602294fSDan Kimmel 	while (*bufp != NULL) {
26895602294fSDan Kimmel 		if (*bufp == buf)
26905602294fSDan Kimmel 			*bufp = buf->b_next;
26915602294fSDan Kimmel 
26925602294fSDan Kimmel 		/*
26935602294fSDan Kimmel 		 * If we've removed a buffer in the middle of
26945602294fSDan Kimmel 		 * the list then update the lastbuf and update
26955602294fSDan Kimmel 		 * bufp.
26965602294fSDan Kimmel 		 */
26975602294fSDan Kimmel 		if (*bufp != NULL) {
26985602294fSDan Kimmel 			lastbuf = *bufp;
26995602294fSDan Kimmel 			bufp = &(*bufp)->b_next;
27005602294fSDan Kimmel 		}
27015602294fSDan Kimmel 	}
27025602294fSDan Kimmel 	buf->b_next = NULL;
27035602294fSDan Kimmel 	ASSERT3P(lastbuf, !=, buf);
27045602294fSDan Kimmel 	IMPLY(hdr->b_l1hdr.b_bufcnt > 0, lastbuf != NULL);
27055602294fSDan Kimmel 	IMPLY(hdr->b_l1hdr.b_bufcnt > 0, hdr->b_l1hdr.b_buf != NULL);
27065602294fSDan Kimmel 	IMPLY(lastbuf != NULL, ARC_BUF_LAST(lastbuf));
27075602294fSDan Kimmel 
27085602294fSDan Kimmel 	return (lastbuf);
27095602294fSDan Kimmel }
27105602294fSDan Kimmel 
27115602294fSDan Kimmel /*
27125602294fSDan Kimmel  * Free up buf->b_data and pull the arc_buf_t off of the the arc_buf_hdr_t's
27135602294fSDan Kimmel  * list and free it.
2714dcbf3bd6SGeorge Wilson  */
2715dcbf3bd6SGeorge Wilson static void
27165602294fSDan Kimmel arc_buf_destroy_impl(arc_buf_t *buf)
2717dcbf3bd6SGeorge Wilson {
2718dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
2719dcbf3bd6SGeorge Wilson 
2720dcbf3bd6SGeorge Wilson 	/*
27215602294fSDan Kimmel 	 * Free up the data associated with the buf but only if we're not
27225602294fSDan Kimmel 	 * sharing this with the hdr. If we are sharing it with the hdr, the
27235602294fSDan Kimmel 	 * hdr is responsible for doing the free.
2724dcbf3bd6SGeorge Wilson 	 */
2725dcbf3bd6SGeorge Wilson 	if (buf->b_data != NULL) {
2726dcbf3bd6SGeorge Wilson 		/*
2727dcbf3bd6SGeorge Wilson 		 * We're about to change the hdr's b_flags. We must either
2728dcbf3bd6SGeorge Wilson 		 * hold the hash_lock or be undiscoverable.
2729dcbf3bd6SGeorge Wilson 		 */
2730dcbf3bd6SGeorge Wilson 		ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2731dcbf3bd6SGeorge Wilson 
2732dcbf3bd6SGeorge Wilson 		arc_cksum_verify(buf);
2733dcbf3bd6SGeorge Wilson 		arc_buf_unwatch(buf);
2734dcbf3bd6SGeorge Wilson 
27355602294fSDan Kimmel 		if (arc_buf_is_shared(buf)) {
2736dcbf3bd6SGeorge Wilson 			arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2737dcbf3bd6SGeorge Wilson 		} else {
27385602294fSDan Kimmel 			uint64_t size = arc_buf_size(buf);
2739dcbf3bd6SGeorge Wilson 			arc_free_data_buf(hdr, buf->b_data, size, buf);
2740dcbf3bd6SGeorge Wilson 			ARCSTAT_INCR(arcstat_overhead_size, -size);
2741dcbf3bd6SGeorge Wilson 		}
2742dcbf3bd6SGeorge Wilson 		buf->b_data = NULL;
2743dcbf3bd6SGeorge Wilson 
2744dcbf3bd6SGeorge Wilson 		ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
2745dcbf3bd6SGeorge Wilson 		hdr->b_l1hdr.b_bufcnt -= 1;
2746dcbf3bd6SGeorge Wilson 	}
2747dcbf3bd6SGeorge Wilson 
27485602294fSDan Kimmel 	arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
2749dcbf3bd6SGeorge Wilson 
27505602294fSDan Kimmel 	if (ARC_BUF_SHARED(buf) && !ARC_BUF_COMPRESSED(buf)) {
2751dcbf3bd6SGeorge Wilson 		/*
27525602294fSDan Kimmel 		 * If the current arc_buf_t is sharing its data buffer with the
2753*770499e1SDan Kimmel 		 * hdr, then reassign the hdr's b_pabd to share it with the new
27545602294fSDan Kimmel 		 * buffer at the end of the list. The shared buffer is always
27555602294fSDan Kimmel 		 * the last one on the hdr's buffer list.
27565602294fSDan Kimmel 		 *
27575602294fSDan Kimmel 		 * There is an equivalent case for compressed bufs, but since
27585602294fSDan Kimmel 		 * they aren't guaranteed to be the last buf in the list and
27595602294fSDan Kimmel 		 * that is an exceedingly rare case, we just allow that space be
27605602294fSDan Kimmel 		 * wasted temporarily.
2761dcbf3bd6SGeorge Wilson 		 */
27625602294fSDan Kimmel 		if (lastbuf != NULL) {
27635602294fSDan Kimmel 			/* Only one buf can be shared at once */
27645602294fSDan Kimmel 			VERIFY(!arc_buf_is_shared(lastbuf));
27655602294fSDan Kimmel 			/* hdr is uncompressed so can't have compressed buf */
27665602294fSDan Kimmel 			VERIFY(!ARC_BUF_COMPRESSED(lastbuf));
2767dcbf3bd6SGeorge Wilson 
2768*770499e1SDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2769*770499e1SDan Kimmel 			arc_hdr_free_pabd(hdr);
2770dcbf3bd6SGeorge Wilson 
27715602294fSDan Kimmel 			/*
27725602294fSDan Kimmel 			 * We must setup a new shared block between the
27735602294fSDan Kimmel 			 * last buffer and the hdr. The data would have
27745602294fSDan Kimmel 			 * been allocated by the arc buf so we need to transfer
27755602294fSDan Kimmel 			 * ownership to the hdr since it's now being shared.
27765602294fSDan Kimmel 			 */
27775602294fSDan Kimmel 			arc_share_buf(hdr, lastbuf);
27785602294fSDan Kimmel 		}
27795602294fSDan Kimmel 	} else if (HDR_SHARED_DATA(hdr)) {
2780dcbf3bd6SGeorge Wilson 		/*
27815602294fSDan Kimmel 		 * Uncompressed shared buffers are always at the end
27825602294fSDan Kimmel 		 * of the list. Compressed buffers don't have the
27835602294fSDan Kimmel 		 * same requirements. This makes it hard to
27845602294fSDan Kimmel 		 * simply assert that the lastbuf is shared so
27855602294fSDan Kimmel 		 * we rely on the hdr's compression flags to determine
27865602294fSDan Kimmel 		 * if we have a compressed, shared buffer.
2787dcbf3bd6SGeorge Wilson 		 */
27885602294fSDan Kimmel 		ASSERT3P(lastbuf, !=, NULL);
27895602294fSDan Kimmel 		ASSERT(arc_buf_is_shared(lastbuf) ||
27905602294fSDan Kimmel 		    HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
2791dcbf3bd6SGeorge Wilson 	}
2792dcbf3bd6SGeorge Wilson 
27935602294fSDan Kimmel 	/*
27945602294fSDan Kimmel 	 * Free the checksum if we're removing the last uncompressed buf from
27955602294fSDan Kimmel 	 * this hdr.
27965602294fSDan Kimmel 	 */
27975602294fSDan Kimmel 	if (!arc_hdr_has_uncompressed_buf(hdr)) {
2798dcbf3bd6SGeorge Wilson 		arc_cksum_free(hdr);
27995602294fSDan Kimmel 	}
2800dcbf3bd6SGeorge Wilson 
2801dcbf3bd6SGeorge Wilson 	/* clean up the buf */
2802dcbf3bd6SGeorge Wilson 	buf->b_hdr = NULL;
2803dcbf3bd6SGeorge Wilson 	kmem_cache_free(buf_cache, buf);
2804dcbf3bd6SGeorge Wilson }
2805dcbf3bd6SGeorge Wilson 
2806dcbf3bd6SGeorge Wilson static void
2807*770499e1SDan Kimmel arc_hdr_alloc_pabd(arc_buf_hdr_t *hdr)
2808dcbf3bd6SGeorge Wilson {
2809dcbf3bd6SGeorge Wilson 	ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
281089c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
2811dcbf3bd6SGeorge Wilson 	ASSERT(!HDR_SHARED_DATA(hdr));
2812ea8dc4b6Seschrock 
2813*770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2814*770499e1SDan Kimmel 	hdr->b_l1hdr.b_pabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr);
2815dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
2816*770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
281789c86e32SChris Williamson 
2818dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
2819dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
2820ea8dc4b6Seschrock }
2821ea8dc4b6Seschrock 
2822244781f1SPrakash Surya static void
2823*770499e1SDan Kimmel arc_hdr_free_pabd(arc_buf_hdr_t *hdr)
2824244781f1SPrakash Surya {
2825dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2826*770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2827244781f1SPrakash Surya 
2828dcbf3bd6SGeorge Wilson 	/*
2829dcbf3bd6SGeorge Wilson 	 * If the hdr is currently being written to the l2arc then
2830dcbf3bd6SGeorge Wilson 	 * we defer freeing the data by adding it to the l2arc_free_on_write
2831dcbf3bd6SGeorge Wilson 	 * list. The l2arc will free the data once it's finished
2832dcbf3bd6SGeorge Wilson 	 * writing it to the l2arc device.
2833dcbf3bd6SGeorge Wilson 	 */
2834dcbf3bd6SGeorge Wilson 	if (HDR_L2_WRITING(hdr)) {
2835dcbf3bd6SGeorge Wilson 		arc_hdr_free_on_write(hdr);
2836dcbf3bd6SGeorge Wilson 		ARCSTAT_BUMP(arcstat_l2_free_on_write);
2837dcbf3bd6SGeorge Wilson 	} else {
2838*770499e1SDan Kimmel 		arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
2839dcbf3bd6SGeorge Wilson 		    arc_hdr_size(hdr), hdr);
2840dcbf3bd6SGeorge Wilson 	}
2841*770499e1SDan Kimmel 	hdr->b_l1hdr.b_pabd = NULL;
2842dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
2843dcbf3bd6SGeorge Wilson 
2844dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
2845dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
2846dcbf3bd6SGeorge Wilson }
2847dcbf3bd6SGeorge Wilson 
2848dcbf3bd6SGeorge Wilson static arc_buf_hdr_t *
2849dcbf3bd6SGeorge Wilson arc_hdr_alloc(uint64_t spa, int32_t psize, int32_t lsize,
28505602294fSDan Kimmel     enum zio_compress compression_type, arc_buf_contents_t type)
2851dcbf3bd6SGeorge Wilson {
2852dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr;
2853dcbf3bd6SGeorge Wilson 
2854dcbf3bd6SGeorge Wilson 	VERIFY(type == ARC_BUFC_DATA || type == ARC_BUFC_METADATA);
2855dcbf3bd6SGeorge Wilson 
2856dcbf3bd6SGeorge Wilson 	hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
2857dcbf3bd6SGeorge Wilson 	ASSERT(HDR_EMPTY(hdr));
2858dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
2859dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_thawed, ==, NULL);
2860dcbf3bd6SGeorge Wilson 	HDR_SET_PSIZE(hdr, psize);
2861dcbf3bd6SGeorge Wilson 	HDR_SET_LSIZE(hdr, lsize);
2862dcbf3bd6SGeorge Wilson 	hdr->b_spa = spa;
2863dcbf3bd6SGeorge Wilson 	hdr->b_type = type;
2864dcbf3bd6SGeorge Wilson 	hdr->b_flags = 0;
2865dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(hdr, arc_bufc_to_flags(type) | ARC_FLAG_HAS_L1HDR);
28665602294fSDan Kimmel 	arc_hdr_set_compress(hdr, compression_type);
2867dcbf3bd6SGeorge Wilson 
2868dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_state = arc_anon;
2869dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_arc_access = 0;
2870dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_bufcnt = 0;
2871dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_buf = NULL;
2872dcbf3bd6SGeorge Wilson 
2873dcbf3bd6SGeorge Wilson 	/*
2874dcbf3bd6SGeorge Wilson 	 * Allocate the hdr's buffer. This will contain either
2875dcbf3bd6SGeorge Wilson 	 * the compressed or uncompressed data depending on the block
2876dcbf3bd6SGeorge Wilson 	 * it references and compressed arc enablement.
2877dcbf3bd6SGeorge Wilson 	 */
2878*770499e1SDan Kimmel 	arc_hdr_alloc_pabd(hdr);
2879dcbf3bd6SGeorge Wilson 	ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2880dcbf3bd6SGeorge Wilson 
2881dcbf3bd6SGeorge Wilson 	return (hdr);
2882244781f1SPrakash Surya }
2883244781f1SPrakash Surya 
2884fa94a07fSbrendan /*
2885dcbf3bd6SGeorge Wilson  * Transition between the two allocation states for the arc_buf_hdr struct.
2886dcbf3bd6SGeorge Wilson  * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
2887dcbf3bd6SGeorge Wilson  * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
2888dcbf3bd6SGeorge Wilson  * version is used when a cache buffer is only in the L2ARC in order to reduce
2889dcbf3bd6SGeorge Wilson  * memory usage.
2890fa94a07fSbrendan  */
2891dcbf3bd6SGeorge Wilson static arc_buf_hdr_t *
2892dcbf3bd6SGeorge Wilson arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
2893fa94a07fSbrendan {
2894dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L2HDR(hdr));
2895dcbf3bd6SGeorge Wilson 
2896dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *nhdr;
2897dcbf3bd6SGeorge Wilson 	l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
2898dcbf3bd6SGeorge Wilson 
2899dcbf3bd6SGeorge Wilson 	ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
2900dcbf3bd6SGeorge Wilson 	    (old == hdr_l2only_cache && new == hdr_full_cache));
2901dcbf3bd6SGeorge Wilson 
2902dcbf3bd6SGeorge Wilson 	nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
2903dcbf3bd6SGeorge Wilson 
2904dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
2905dcbf3bd6SGeorge Wilson 	buf_hash_remove(hdr);
2906dcbf3bd6SGeorge Wilson 
2907dcbf3bd6SGeorge Wilson 	bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
2908dcbf3bd6SGeorge Wilson 
2909dcbf3bd6SGeorge Wilson 	if (new == hdr_full_cache) {
2910dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(nhdr, ARC_FLAG_HAS_L1HDR);
2911dcbf3bd6SGeorge Wilson 		/*
2912dcbf3bd6SGeorge Wilson 		 * arc_access and arc_change_state need to be aware that a
2913dcbf3bd6SGeorge Wilson 		 * header has just come out of L2ARC, so we set its state to
2914dcbf3bd6SGeorge Wilson 		 * l2c_only even though it's about to change.
2915dcbf3bd6SGeorge Wilson 		 */
2916dcbf3bd6SGeorge Wilson 		nhdr->b_l1hdr.b_state = arc_l2c_only;
2917dcbf3bd6SGeorge Wilson 
2918dcbf3bd6SGeorge Wilson 		/* Verify previous threads set to NULL before freeing */
2919*770499e1SDan Kimmel 		ASSERT3P(nhdr->b_l1hdr.b_pabd, ==, NULL);
2920dcbf3bd6SGeorge Wilson 	} else {
2921dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2922dcbf3bd6SGeorge Wilson 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
2923dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
2924dcbf3bd6SGeorge Wilson 
2925dcbf3bd6SGeorge Wilson 		/*
2926dcbf3bd6SGeorge Wilson 		 * If we've reached here, We must have been called from
2927dcbf3bd6SGeorge Wilson 		 * arc_evict_hdr(), as such we should have already been
2928dcbf3bd6SGeorge Wilson 		 * removed from any ghost list we were previously on
2929dcbf3bd6SGeorge Wilson 		 * (which protects us from racing with arc_evict_state),
2930dcbf3bd6SGeorge Wilson 		 * thus no locking is needed during this check.
2931dcbf3bd6SGeorge Wilson 		 */
2932dcbf3bd6SGeorge Wilson 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
2933cd1c8b85SMatthew Ahrens 
2934dcbf3bd6SGeorge Wilson 		/*
2935dcbf3bd6SGeorge Wilson 		 * A buffer must not be moved into the arc_l2c_only
2936dcbf3bd6SGeorge Wilson 		 * state if it's not finished being written out to the
2937*770499e1SDan Kimmel 		 * l2arc device. Otherwise, the b_l1hdr.b_pabd field
2938dcbf3bd6SGeorge Wilson 		 * might try to be accessed, even though it was removed.
2939dcbf3bd6SGeorge Wilson 		 */
2940dcbf3bd6SGeorge Wilson 		VERIFY(!HDR_L2_WRITING(hdr));
2941*770499e1SDan Kimmel 		VERIFY3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2942fa94a07fSbrendan 
2943dcbf3bd6SGeorge Wilson #ifdef ZFS_DEBUG
2944dcbf3bd6SGeorge Wilson 		if (hdr->b_l1hdr.b_thawed != NULL) {
2945dcbf3bd6SGeorge Wilson 			kmem_free(hdr->b_l1hdr.b_thawed, 1);
2946dcbf3bd6SGeorge Wilson 			hdr->b_l1hdr.b_thawed = NULL;
2947dcbf3bd6SGeorge Wilson 		}
2948dcbf3bd6SGeorge Wilson #endif
2949244781f1SPrakash Surya 
2950dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(nhdr, ARC_FLAG_HAS_L1HDR);
2951dcbf3bd6SGeorge Wilson 	}
2952244781f1SPrakash Surya 	/*
2953dcbf3bd6SGeorge Wilson 	 * The header has been reallocated so we need to re-insert it into any
2954dcbf3bd6SGeorge Wilson 	 * lists it was on.
2955244781f1SPrakash Surya 	 */
2956dcbf3bd6SGeorge Wilson 	(void) buf_hash_insert(nhdr, NULL);
2957244781f1SPrakash Surya 
2958dcbf3bd6SGeorge Wilson 	ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
2959dcbf3bd6SGeorge Wilson 
2960dcbf3bd6SGeorge Wilson 	mutex_enter(&dev->l2ad_mtx);
2961244781f1SPrakash Surya 
2962244781f1SPrakash Surya 	/*
2963dcbf3bd6SGeorge Wilson 	 * We must place the realloc'ed header back into the list at
2964dcbf3bd6SGeorge Wilson 	 * the same spot. Otherwise, if it's placed earlier in the list,
2965dcbf3bd6SGeorge Wilson 	 * l2arc_write_buffers() could find it during the function's
2966dcbf3bd6SGeorge Wilson 	 * write phase, and try to write it out to the l2arc.
2967244781f1SPrakash Surya 	 */
2968dcbf3bd6SGeorge Wilson 	list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
2969dcbf3bd6SGeorge Wilson 	list_remove(&dev->l2ad_buflist, hdr);
2970dcbf3bd6SGeorge Wilson 
2971dcbf3bd6SGeorge Wilson 	mutex_exit(&dev->l2ad_mtx);
2972244781f1SPrakash Surya 
2973244781f1SPrakash Surya 	/*
2974dcbf3bd6SGeorge Wilson 	 * Since we're using the pointer address as the tag when
2975dcbf3bd6SGeorge Wilson 	 * incrementing and decrementing the l2ad_alloc refcount, we
2976dcbf3bd6SGeorge Wilson 	 * must remove the old pointer (that we're about to destroy) and
2977dcbf3bd6SGeorge Wilson 	 * add the new pointer to the refcount. Otherwise we'd remove
2978dcbf3bd6SGeorge Wilson 	 * the wrong pointer address when calling arc_hdr_destroy() later.
2979244781f1SPrakash Surya 	 */
2980244781f1SPrakash Surya 
2981dcbf3bd6SGeorge Wilson 	(void) refcount_remove_many(&dev->l2ad_alloc, arc_hdr_size(hdr), hdr);
2982dcbf3bd6SGeorge Wilson 	(void) refcount_add_many(&dev->l2ad_alloc, arc_hdr_size(nhdr), nhdr);
2983244781f1SPrakash Surya 
2984dcbf3bd6SGeorge Wilson 	buf_discard_identity(hdr);
2985dcbf3bd6SGeorge Wilson 	kmem_cache_free(old, hdr);
2986244781f1SPrakash Surya 
2987dcbf3bd6SGeorge Wilson 	return (nhdr);
2988244781f1SPrakash Surya }
2989244781f1SPrakash Surya 
2990bbfa8ea8SMatthew Ahrens /*
2991dcbf3bd6SGeorge Wilson  * Allocate a new arc_buf_hdr_t and arc_buf_t and return the buf to the caller.
2992dcbf3bd6SGeorge Wilson  * The buf is returned thawed since we expect the consumer to modify it.
2993bbfa8ea8SMatthew Ahrens  */
2994dcbf3bd6SGeorge Wilson arc_buf_t *
29955602294fSDan Kimmel arc_alloc_buf(spa_t *spa, void *tag, arc_buf_contents_t type, int32_t size)
2996ea8dc4b6Seschrock {
2997dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), size, size,
2998dcbf3bd6SGeorge Wilson 	    ZIO_COMPRESS_OFF, type);
2999dcbf3bd6SGeorge Wilson 	ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
30005602294fSDan Kimmel 
30015602294fSDan Kimmel 	arc_buf_t *buf = NULL;
30025602294fSDan Kimmel 	VERIFY0(arc_buf_alloc_impl(hdr, tag, B_FALSE, B_FALSE, &buf));
3003dcbf3bd6SGeorge Wilson 	arc_buf_thaw(buf);
30045602294fSDan Kimmel 
30055602294fSDan Kimmel 	return (buf);
30065602294fSDan Kimmel }
30075602294fSDan Kimmel 
30085602294fSDan Kimmel /*
30095602294fSDan Kimmel  * Allocate a compressed buf in the same manner as arc_alloc_buf. Don't use this
30105602294fSDan Kimmel  * for bufs containing metadata.
30115602294fSDan Kimmel  */
30125602294fSDan Kimmel arc_buf_t *
30135602294fSDan Kimmel arc_alloc_compressed_buf(spa_t *spa, void *tag, uint64_t psize, uint64_t lsize,
30145602294fSDan Kimmel     enum zio_compress compression_type)
30155602294fSDan Kimmel {
30165602294fSDan Kimmel 	ASSERT3U(lsize, >, 0);
30175602294fSDan Kimmel 	ASSERT3U(lsize, >=, psize);
30185602294fSDan Kimmel 	ASSERT(compression_type > ZIO_COMPRESS_OFF);
30195602294fSDan Kimmel 	ASSERT(compression_type < ZIO_COMPRESS_FUNCTIONS);
30205602294fSDan Kimmel 
30215602294fSDan Kimmel 	arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
30225602294fSDan Kimmel 	    compression_type, ARC_BUFC_DATA);
30235602294fSDan Kimmel 	ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
30245602294fSDan Kimmel 
30255602294fSDan Kimmel 	arc_buf_t *buf = NULL;
30265602294fSDan Kimmel 	VERIFY0(arc_buf_alloc_impl(hdr, tag, B_TRUE, B_FALSE, &buf));
30275602294fSDan Kimmel 	arc_buf_thaw(buf);
30285602294fSDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
30295602294fSDan Kimmel 
3030*770499e1SDan Kimmel 	if (!arc_buf_is_shared(buf)) {
3031*770499e1SDan Kimmel 		/*
3032*770499e1SDan Kimmel 		 * To ensure that the hdr has the correct data in it if we call
3033*770499e1SDan Kimmel 		 * arc_decompress() on this buf before it's been written to
3034*770499e1SDan Kimmel 		 * disk, it's easiest if we just set up sharing between the
3035*770499e1SDan Kimmel 		 * buf and the hdr.
3036*770499e1SDan Kimmel 		 */
3037*770499e1SDan Kimmel 		ASSERT(!abd_is_linear(hdr->b_l1hdr.b_pabd));
3038*770499e1SDan Kimmel 		arc_hdr_free_pabd(hdr);
3039*770499e1SDan Kimmel 		arc_share_buf(hdr, buf);
3040*770499e1SDan Kimmel 	}
3041*770499e1SDan Kimmel 
3042dcbf3bd6SGeorge Wilson 	return (buf);
3043ea8dc4b6Seschrock }
3044ea8dc4b6Seschrock 
3045a52fc310SPrakash Surya static void
3046a52fc310SPrakash Surya arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
3047a52fc310SPrakash Surya {
3048a52fc310SPrakash Surya 	l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
3049a52fc310SPrakash Surya 	l2arc_dev_t *dev = l2hdr->b_dev;
3050dcbf3bd6SGeorge Wilson 	uint64_t asize = arc_hdr_size(hdr);
3051a52fc310SPrakash Surya 
3052a52fc310SPrakash Surya 	ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
3053a52fc310SPrakash Surya 	ASSERT(HDR_HAS_L2HDR(hdr));
3054a52fc310SPrakash Surya 
3055a52fc310SPrakash Surya 	list_remove(&dev->l2ad_buflist, hdr);
3056a52fc310SPrakash Surya 
3057dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_l2_asize, -asize);
3058dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_l2_size, -HDR_GET_LSIZE(hdr));
3059a52fc310SPrakash Surya 
3060dcbf3bd6SGeorge Wilson 	vdev_space_update(dev->l2ad_vdev, -asize, 0, 0);
3061a52fc310SPrakash Surya 
3062dcbf3bd6SGeorge Wilson 	(void) refcount_remove_many(&dev->l2ad_alloc, asize, hdr);
3063dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
3064a52fc310SPrakash Surya }
3065a52fc310SPrakash Surya 
3066fa9e4066Sahrens static void
3067ea8dc4b6Seschrock arc_hdr_destroy(arc_buf_hdr_t *hdr)
3068fa9e4066Sahrens {
306989c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr)) {
307089c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_buf == NULL ||
3071dcbf3bd6SGeorge Wilson 		    hdr->b_l1hdr.b_bufcnt > 0);
307289c86e32SChris Williamson 		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
307389c86e32SChris Williamson 		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
307489c86e32SChris Williamson 	}
3075ea8dc4b6Seschrock 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
307689c86e32SChris Williamson 	ASSERT(!HDR_IN_HASH_TABLE(hdr));
307789c86e32SChris Williamson 
3078dcbf3bd6SGeorge Wilson 	if (!HDR_EMPTY(hdr))
3079dcbf3bd6SGeorge Wilson 		buf_discard_identity(hdr);
3080dcbf3bd6SGeorge Wilson 
308189c86e32SChris Williamson 	if (HDR_HAS_L2HDR(hdr)) {
3082a52fc310SPrakash Surya 		l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3083a52fc310SPrakash Surya 		boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
3084b24ab676SJeff Bonwick 
3085a52fc310SPrakash Surya 		if (!buflist_held)
3086a52fc310SPrakash Surya 			mutex_enter(&dev->l2ad_mtx);
308789c86e32SChris Williamson 
3088244781f1SPrakash Surya 		/*
3089a52fc310SPrakash Surya 		 * Even though we checked this conditional above, we
3090a52fc310SPrakash Surya 		 * need to check this again now that we have the
3091a52fc310SPrakash Surya 		 * l2ad_mtx. This is because we could be racing with
3092a52fc310SPrakash Surya 		 * another thread calling l2arc_evict() which might have
3093a52fc310SPrakash Surya 		 * destroyed this header's L2 portion as we were waiting
3094a52fc310SPrakash Surya 		 * to acquire the l2ad_mtx. If that happens, we don't
3095a52fc310SPrakash Surya 		 * want to re-destroy the header's L2 portion.
3096244781f1SPrakash Surya 		 */
3097a52fc310SPrakash Surya 		if (HDR_HAS_L2HDR(hdr))
3098a52fc310SPrakash Surya 			arc_hdr_l2hdr_destroy(hdr);
3099b24ab676SJeff Bonwick 
3100b24ab676SJeff Bonwick 		if (!buflist_held)
3101a52fc310SPrakash Surya 			mutex_exit(&dev->l2ad_mtx);
3102fa94a07fSbrendan 	}
3103fa94a07fSbrendan 
3104dcbf3bd6SGeorge Wilson 	if (HDR_HAS_L1HDR(hdr)) {
3105dcbf3bd6SGeorge Wilson 		arc_cksum_free(hdr);
310689c86e32SChris Williamson 
3107dcbf3bd6SGeorge Wilson 		while (hdr->b_l1hdr.b_buf != NULL)
31085602294fSDan Kimmel 			arc_buf_destroy_impl(hdr->b_l1hdr.b_buf);
310989c86e32SChris Williamson 
311089c86e32SChris Williamson #ifdef ZFS_DEBUG
311189c86e32SChris Williamson 		if (hdr->b_l1hdr.b_thawed != NULL) {
311289c86e32SChris Williamson 			kmem_free(hdr->b_l1hdr.b_thawed, 1);
311389c86e32SChris Williamson 			hdr->b_l1hdr.b_thawed = NULL;
311489c86e32SChris Williamson 		}
311589c86e32SChris Williamson #endif
3116dcbf3bd6SGeorge Wilson 
3117*770499e1SDan Kimmel 		if (hdr->b_l1hdr.b_pabd != NULL) {
3118*770499e1SDan Kimmel 			arc_hdr_free_pabd(hdr);
3119dcbf3bd6SGeorge Wilson 		}
31203f9d6ad7SLin Ling 	}
3121ea8dc4b6Seschrock 
3122fa9e4066Sahrens 	ASSERT3P(hdr->b_hash_next, ==, NULL);
312389c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr)) {
3124244781f1SPrakash Surya 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
312589c86e32SChris Williamson 		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
312689c86e32SChris Williamson 		kmem_cache_free(hdr_full_cache, hdr);
312789c86e32SChris Williamson 	} else {
312889c86e32SChris Williamson 		kmem_cache_free(hdr_l2only_cache, hdr);
312989c86e32SChris Williamson 	}
3130fa9e4066Sahrens }
3131fa9e4066Sahrens 
3132fa9e4066Sahrens void
3133dcbf3bd6SGeorge Wilson arc_buf_destroy(arc_buf_t *buf, void* tag)
3134ea8dc4b6Seschrock {
3135ea8dc4b6Seschrock 	arc_buf_hdr_t *hdr = buf->b_hdr;
3136ea8dc4b6Seschrock 	kmutex_t *hash_lock = HDR_LOCK(hdr);
3137fa9e4066Sahrens 
313889c86e32SChris Williamson 	if (hdr->b_l1hdr.b_state == arc_anon) {
3139dcbf3bd6SGeorge Wilson 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
3140dcbf3bd6SGeorge Wilson 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3141dcbf3bd6SGeorge Wilson 		VERIFY0(remove_reference(hdr, NULL, tag));
3142dcbf3bd6SGeorge Wilson 		arc_hdr_destroy(hdr);
3143dcbf3bd6SGeorge Wilson 		return;
3144ea8dc4b6Seschrock 	}
3145ea8dc4b6Seschrock 
3146ea8dc4b6Seschrock 	mutex_enter(hash_lock);
3147dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr, ==, buf->b_hdr);
3148dcbf3bd6SGeorge Wilson 	ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
31493f9d6ad7SLin Ling 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3150dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_state, !=, arc_anon);
3151dcbf3bd6SGeorge Wilson 	ASSERT3P(buf->b_data, !=, NULL);
3152ea8dc4b6Seschrock 
3153ea8dc4b6Seschrock 	(void) remove_reference(hdr, hash_lock, tag);
31545602294fSDan Kimmel 	arc_buf_destroy_impl(buf);
3155ea8dc4b6Seschrock 	mutex_exit(hash_lock);
3156fa9e4066Sahrens }
3157fa9e4066Sahrens 
3158fa9e4066Sahrens /*
3159244781f1SPrakash Surya  * Evict the arc_buf_hdr that is provided as a parameter. The resultant
3160244781f1SPrakash Surya  * state of the header is dependent on it's state prior to entering this
3161244781f1SPrakash Surya  * function. The following transitions are possible:
3162874395d5Smaybee  *
3163244781f1SPrakash Surya  *    - arc_mru -> arc_mru_ghost
3164244781f1SPrakash Surya  *    - arc_mfu -> arc_mfu_ghost
3165244781f1SPrakash Surya  *    - arc_mru_ghost -> arc_l2c_only
3166244781f1SPrakash Surya  *    - arc_mru_ghost -> deleted
3167244781f1SPrakash Surya  *    - arc_mfu_ghost -> arc_l2c_only
3168244781f1SPrakash Surya  *    - arc_mfu_ghost -> deleted
3169fa9e4066Sahrens  */
3170244781f1SPrakash Surya static int64_t
3171244781f1SPrakash Surya arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3172fa9e4066Sahrens {
3173244781f1SPrakash Surya 	arc_state_t *evicted_state, *state;
3174244781f1SPrakash Surya 	int64_t bytes_evicted = 0;
3175fa9e4066Sahrens 
3176244781f1SPrakash Surya 	ASSERT(MUTEX_HELD(hash_lock));
3177244781f1SPrakash Surya 	ASSERT(HDR_HAS_L1HDR(hdr));
3178fa9e4066Sahrens 
3179244781f1SPrakash Surya 	state = hdr->b_l1hdr.b_state;
3180244781f1SPrakash Surya 	if (GHOST_STATE(state)) {
3181244781f1SPrakash Surya 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3182dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3183fa9e4066Sahrens 
3184244781f1SPrakash Surya 		/*
3185244781f1SPrakash Surya 		 * l2arc_write_buffers() relies on a header's L1 portion
3186*770499e1SDan Kimmel 		 * (i.e. its b_pabd field) during it's write phase.
3187244781f1SPrakash Surya 		 * Thus, we cannot push a header onto the arc_l2c_only
3188244781f1SPrakash Surya 		 * state (removing it's L1 piece) until the header is
3189244781f1SPrakash Surya 		 * done being written to the l2arc.
3190244781f1SPrakash Surya 		 */
3191244781f1SPrakash Surya 		if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
3192244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_evict_l2_skip);
3193244781f1SPrakash Surya 			return (bytes_evicted);
31943a5286a1SMatthew Ahrens 		}
3195244781f1SPrakash Surya 
3196244781f1SPrakash Surya 		ARCSTAT_BUMP(arcstat_deleted);
3197dcbf3bd6SGeorge Wilson 		bytes_evicted += HDR_GET_LSIZE(hdr);
3198244781f1SPrakash Surya 
3199244781f1SPrakash Surya 		DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
3200244781f1SPrakash Surya 
3201*770499e1SDan Kimmel 		ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3202244781f1SPrakash Surya 		if (HDR_HAS_L2HDR(hdr)) {
3203244781f1SPrakash Surya 			/*
3204244781f1SPrakash Surya 			 * This buffer is cached on the 2nd Level ARC;
3205244781f1SPrakash Surya 			 * don't destroy the header.
3206244781f1SPrakash Surya 			 */
3207244781f1SPrakash Surya 			arc_change_state(arc_l2c_only, hdr, hash_lock);
32083a5286a1SMatthew Ahrens 			/*
3209244781f1SPrakash Surya 			 * dropping from L1+L2 cached to L2-only,
3210244781f1SPrakash Surya 			 * realloc to remove the L1 header.
32113a5286a1SMatthew Ahrens 			 */
3212244781f1SPrakash Surya 			hdr = arc_hdr_realloc(hdr, hdr_full_cache,
3213244781f1SPrakash Surya 			    hdr_l2only_cache);
3214244781f1SPrakash Surya 		} else {
3215244781f1SPrakash Surya 			arc_change_state(arc_anon, hdr, hash_lock);
3216244781f1SPrakash Surya 			arc_hdr_destroy(hdr);
32173a5286a1SMatthew Ahrens 		}
3218244781f1SPrakash Surya 		return (bytes_evicted);
32193a5286a1SMatthew Ahrens 	}
32203a5286a1SMatthew Ahrens 
3221244781f1SPrakash Surya 	ASSERT(state == arc_mru || state == arc_mfu);
3222244781f1SPrakash Surya 	evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
3223244781f1SPrakash Surya 
3224244781f1SPrakash Surya 	/* prefetch buffers have a minimum lifespan */
3225244781f1SPrakash Surya 	if (HDR_IO_IN_PROGRESS(hdr) ||
3226244781f1SPrakash Surya 	    ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
3227244781f1SPrakash Surya 	    ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
3228244781f1SPrakash Surya 	    arc_min_prefetch_lifespan)) {
3229244781f1SPrakash Surya 		ARCSTAT_BUMP(arcstat_evict_skip);
3230244781f1SPrakash Surya 		return (bytes_evicted);
3231244781f1SPrakash Surya 	}
3232244781f1SPrakash Surya 
3233244781f1SPrakash Surya 	ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
3234244781f1SPrakash Surya 	while (hdr->b_l1hdr.b_buf) {
3235244781f1SPrakash Surya 		arc_buf_t *buf = hdr->b_l1hdr.b_buf;
3236244781f1SPrakash Surya 		if (!mutex_tryenter(&buf->b_evict_lock)) {
3237244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_mutex_miss);
3238244781f1SPrakash Surya 			break;
323913506d1eSmaybee 		}
3240244781f1SPrakash Surya 		if (buf->b_data != NULL)
3241dcbf3bd6SGeorge Wilson 			bytes_evicted += HDR_GET_LSIZE(hdr);
3242dcbf3bd6SGeorge Wilson 		mutex_exit(&buf->b_evict_lock);
32435602294fSDan Kimmel 		arc_buf_destroy_impl(buf);
3244244781f1SPrakash Surya 	}
324569962b56SMatthew Ahrens 
3246244781f1SPrakash Surya 	if (HDR_HAS_L2HDR(hdr)) {
3247dcbf3bd6SGeorge Wilson 		ARCSTAT_INCR(arcstat_evict_l2_cached, HDR_GET_LSIZE(hdr));
3248244781f1SPrakash Surya 	} else {
3249dcbf3bd6SGeorge Wilson 		if (l2arc_write_eligible(hdr->b_spa, hdr)) {
3250dcbf3bd6SGeorge Wilson 			ARCSTAT_INCR(arcstat_evict_l2_eligible,
3251dcbf3bd6SGeorge Wilson 			    HDR_GET_LSIZE(hdr));
3252dcbf3bd6SGeorge Wilson 		} else {
3253dcbf3bd6SGeorge Wilson 			ARCSTAT_INCR(arcstat_evict_l2_ineligible,
3254dcbf3bd6SGeorge Wilson 			    HDR_GET_LSIZE(hdr));
3255dcbf3bd6SGeorge Wilson 		}
3256244781f1SPrakash Surya 	}
3257244781f1SPrakash Surya 
3258dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_bufcnt == 0) {
3259dcbf3bd6SGeorge Wilson 		arc_cksum_free(hdr);
3260dcbf3bd6SGeorge Wilson 
3261dcbf3bd6SGeorge Wilson 		bytes_evicted += arc_hdr_size(hdr);
3262dcbf3bd6SGeorge Wilson 
3263dcbf3bd6SGeorge Wilson 		/*
3264dcbf3bd6SGeorge Wilson 		 * If this hdr is being evicted and has a compressed
3265dcbf3bd6SGeorge Wilson 		 * buffer then we discard it here before we change states.
3266dcbf3bd6SGeorge Wilson 		 * This ensures that the accounting is updated correctly
3267*770499e1SDan Kimmel 		 * in arc_free_data_impl().
3268dcbf3bd6SGeorge Wilson 		 */
3269*770499e1SDan Kimmel 		arc_hdr_free_pabd(hdr);
3270dcbf3bd6SGeorge Wilson 
3271244781f1SPrakash Surya 		arc_change_state(evicted_state, hdr, hash_lock);
3272244781f1SPrakash Surya 		ASSERT(HDR_IN_HASH_TABLE(hdr));
3273dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
3274244781f1SPrakash Surya 		DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
3275244781f1SPrakash Surya 	}
3276244781f1SPrakash Surya 
3277244781f1SPrakash Surya 	return (bytes_evicted);
3278244781f1SPrakash Surya }
3279244781f1SPrakash Surya 
3280244781f1SPrakash Surya static uint64_t
3281244781f1SPrakash Surya arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
3282244781f1SPrakash Surya     uint64_t spa, int64_t bytes)
3283244781f1SPrakash Surya {
3284244781f1SPrakash Surya 	multilist_sublist_t *mls;
3285244781f1SPrakash Surya 	uint64_t bytes_evicted = 0;
3286244781f1SPrakash Surya 	arc_buf_hdr_t *hdr;
3287244781f1SPrakash Surya 	kmutex_t *hash_lock;
3288244781f1SPrakash Surya 	int evict_count = 0;
3289244781f1SPrakash Surya 
3290244781f1SPrakash Surya 	ASSERT3P(marker, !=, NULL);
3291244781f1SPrakash Surya 	IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3292244781f1SPrakash Surya 
3293244781f1SPrakash Surya 	mls = multilist_sublist_lock(ml, idx);
3294244781f1SPrakash Surya 
3295244781f1SPrakash Surya 	for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
3296244781f1SPrakash Surya 	    hdr = multilist_sublist_prev(mls, marker)) {
3297244781f1SPrakash Surya 		if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
3298244781f1SPrakash Surya 		    (evict_count >= zfs_arc_evict_batch_limit))
3299244781f1SPrakash Surya 			break;
330069962b56SMatthew Ahrens 
330169962b56SMatthew Ahrens 		/*
3302244781f1SPrakash Surya 		 * To keep our iteration location, move the marker
3303244781f1SPrakash Surya 		 * forward. Since we're not holding hdr's hash lock, we
3304244781f1SPrakash Surya 		 * must be very careful and not remove 'hdr' from the
3305244781f1SPrakash Surya 		 * sublist. Otherwise, other consumers might mistake the
3306244781f1SPrakash Surya 		 * 'hdr' as not being on a sublist when they call the
3307244781f1SPrakash Surya 		 * multilist_link_active() function (they all rely on
3308244781f1SPrakash Surya 		 * the hash lock protecting concurrent insertions and
3309244781f1SPrakash Surya 		 * removals). multilist_sublist_move_forward() was
3310244781f1SPrakash Surya 		 * specifically implemented to ensure this is the case
3311244781f1SPrakash Surya 		 * (only 'marker' will be removed and re-inserted).
3312244781f1SPrakash Surya 		 */
3313244781f1SPrakash Surya 		multilist_sublist_move_forward(mls, marker);
3314244781f1SPrakash Surya 
3315244781f1SPrakash Surya 		/*
3316244781f1SPrakash Surya 		 * The only case where the b_spa field should ever be
3317244781f1SPrakash Surya 		 * zero, is the marker headers inserted by
3318244781f1SPrakash Surya 		 * arc_evict_state(). It's possible for multiple threads
3319244781f1SPrakash Surya 		 * to be calling arc_evict_state() concurrently (e.g.
3320244781f1SPrakash Surya 		 * dsl_pool_close() and zio_inject_fault()), so we must
3321244781f1SPrakash Surya 		 * skip any markers we see from these other threads.
332269962b56SMatthew Ahrens 		 */
3323244781f1SPrakash Surya 		if (hdr->b_spa == 0)
3324244781f1SPrakash Surya 			continue;
3325244781f1SPrakash Surya 
3326244781f1SPrakash Surya 		/* we're only interested in evicting buffers of a certain spa */
3327244781f1SPrakash Surya 		if (spa != 0 && hdr->b_spa != spa) {
3328244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_evict_skip);
332969962b56SMatthew Ahrens 			continue;
333069962b56SMatthew Ahrens 		}
333169962b56SMatthew Ahrens 
33327adb730bSGeorge Wilson 		hash_lock = HDR_LOCK(hdr);
33335ea40c06SBrendan Gregg - Sun Microsystems 
3334244781f1SPrakash Surya 		/*
3335244781f1SPrakash Surya 		 * We aren't calling this function from any code path
3336244781f1SPrakash Surya 		 * that would already be holding a hash lock, so we're
3337244781f1SPrakash Surya 		 * asserting on this assumption to be defensive in case
3338244781f1SPrakash Surya 		 * this ever changes. Without this check, it would be
3339244781f1SPrakash Surya 		 * possible to incorrectly increment arcstat_mutex_miss
3340244781f1SPrakash Surya 		 * below (e.g. if the code changed such that we called
3341244781f1SPrakash Surya 		 * this function with a hash lock held).
3342244781f1SPrakash Surya 		 */
3343244781f1SPrakash Surya 		ASSERT(!MUTEX_HELD(hash_lock));
334444cb6abcSbmc 
3345244781f1SPrakash Surya 		if (mutex_tryenter(hash_lock)) {
3346244781f1SPrakash Surya 			uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
3347244781f1SPrakash Surya 			mutex_exit(hash_lock);
3348fa9e4066Sahrens 
3349244781f1SPrakash Surya 			bytes_evicted += evicted;
3350fa9e4066Sahrens 
3351244781f1SPrakash Surya 			/*
3352244781f1SPrakash Surya 			 * If evicted is zero, arc_evict_hdr() must have
3353244781f1SPrakash Surya 			 * decided to skip this header, don't increment
3354244781f1SPrakash Surya 			 * evict_count in this case.
3355244781f1SPrakash Surya 			 */
3356244781f1SPrakash Surya 			if (evicted != 0)
3357244781f1SPrakash Surya 				evict_count++;
335844cb6abcSbmc 
3359244781f1SPrakash Surya 			/*
3360244781f1SPrakash Surya 			 * If arc_size isn't overflowing, signal any
3361244781f1SPrakash Surya 			 * threads that might happen to be waiting.
3362244781f1SPrakash Surya 			 *
3363244781f1SPrakash Surya 			 * For each header evicted, we wake up a single
3364244781f1SPrakash Surya 			 * thread. If we used cv_broadcast, we could
3365244781f1SPrakash Surya 			 * wake up "too many" threads causing arc_size
3366244781f1SPrakash Surya 			 * to significantly overflow arc_c; since
3367*770499e1SDan Kimmel 			 * arc_get_data_impl() doesn't check for overflow
3368244781f1SPrakash Surya 			 * when it's woken up (it doesn't because it's
3369244781f1SPrakash Surya 			 * possible for the ARC to be overflowing while
3370244781f1SPrakash Surya 			 * full of un-evictable buffers, and the
3371244781f1SPrakash Surya 			 * function should proceed in this case).
3372244781f1SPrakash Surya 			 *
3373244781f1SPrakash Surya 			 * If threads are left sleeping, due to not
3374244781f1SPrakash Surya 			 * using cv_broadcast, they will be woken up
3375244781f1SPrakash Surya 			 * just before arc_reclaim_thread() sleeps.
3376244781f1SPrakash Surya 			 */
3377244781f1SPrakash Surya 			mutex_enter(&arc_reclaim_lock);
3378244781f1SPrakash Surya 			if (!arc_is_overflowing())
3379244781f1SPrakash Surya 				cv_signal(&arc_reclaim_waiters_cv);
3380244781f1SPrakash Surya 			mutex_exit(&arc_reclaim_lock);
3381244781f1SPrakash Surya 		} else {
3382244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_mutex_miss);
3383244781f1SPrakash Surya 		}
3384244781f1SPrakash Surya 	}
3385f4d2e9e6Smaybee 
3386244781f1SPrakash Surya 	multilist_sublist_unlock(mls);
338744cb6abcSbmc 
3388244781f1SPrakash Surya 	return (bytes_evicted);
3389fa9e4066Sahrens }
3390fa9e4066Sahrens 
3391fa9e4066Sahrens /*
3392244781f1SPrakash Surya  * Evict buffers from the given arc state, until we've removed the
3393244781f1SPrakash Surya  * specified number of bytes. Move the removed buffers to the
3394244781f1SPrakash Surya  * appropriate evict state.
3395244781f1SPrakash Surya  *
3396244781f1SPrakash Surya  * This function makes a "best effort". It skips over any buffers
3397244781f1SPrakash Surya  * it can't get a hash_lock on, and so, may not catch all candidates.
3398244781f1SPrakash Surya  * It may also return without evicting as much space as requested.
3399244781f1SPrakash Surya  *
3400244781f1SPrakash Surya  * If bytes is specified using the special value ARC_EVICT_ALL, this
3401244781f1SPrakash Surya  * will evict all available (i.e. unlocked and evictable) buffers from
3402244781f1SPrakash Surya  * the given arc state; which is used by arc_flush().
3403fa9e4066Sahrens  */
3404244781f1SPrakash Surya static uint64_t
3405244781f1SPrakash Surya arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
3406244781f1SPrakash Surya     arc_buf_contents_t type)
3407fa9e4066Sahrens {
3408244781f1SPrakash Surya 	uint64_t total_evicted = 0;
340994c2d0ebSMatthew Ahrens 	multilist_t *ml = state->arcs_list[type];
3410244781f1SPrakash Surya 	int num_sublists;
3411244781f1SPrakash Surya 	arc_buf_hdr_t **markers;
3412fa9e4066Sahrens 
3413244781f1SPrakash Surya 	IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3414b802aa8cSSanjeev Bagewadi 
3415244781f1SPrakash Surya 	num_sublists = multilist_get_num_sublists(ml);
3416b802aa8cSSanjeev Bagewadi 
3417244781f1SPrakash Surya 	/*
3418244781f1SPrakash Surya 	 * If we've tried to evict from each sublist, made some
3419244781f1SPrakash Surya 	 * progress, but still have not hit the target number of bytes
3420244781f1SPrakash Surya 	 * to evict, we want to keep trying. The markers allow us to
3421244781f1SPrakash Surya 	 * pick up where we left off for each individual sublist, rather
3422244781f1SPrakash Surya 	 * than starting from the tail each time.
3423244781f1SPrakash Surya 	 */
3424244781f1SPrakash Surya 	markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
3425244781f1SPrakash Surya 	for (int i = 0; i < num_sublists; i++) {
3426244781f1SPrakash Surya 		markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
342769962b56SMatthew Ahrens 
342869962b56SMatthew Ahrens 		/*
3429244781f1SPrakash Surya 		 * A b_spa of 0 is used to indicate that this header is
3430244781f1SPrakash Surya 		 * a marker. This fact is used in arc_adjust_type() and
3431244781f1SPrakash Surya 		 * arc_evict_state_impl().
343269962b56SMatthew Ahrens 		 */
3433244781f1SPrakash Surya 		markers[i]->b_spa = 0;
3434fa94a07fSbrendan 
3435244781f1SPrakash Surya 		multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3436244781f1SPrakash Surya 		multilist_sublist_insert_tail(mls, markers[i]);
3437244781f1SPrakash Surya 		multilist_sublist_unlock(mls);
3438244781f1SPrakash Surya 	}
3439fa94a07fSbrendan 
3440244781f1SPrakash Surya 	/*
3441244781f1SPrakash Surya 	 * While we haven't hit our target number of bytes to evict, or
3442244781f1SPrakash Surya 	 * we're evicting all available buffers.
3443244781f1SPrakash Surya 	 */
3444244781f1SPrakash Surya 	while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
3445244781f1SPrakash Surya 		/*
3446244781f1SPrakash Surya 		 * Start eviction using a randomly selected sublist,
3447244781f1SPrakash Surya 		 * this is to try and evenly balance eviction across all
3448244781f1SPrakash Surya 		 * sublists. Always starting at the same sublist
3449244781f1SPrakash Surya 		 * (e.g. index 0) would cause evictions to favor certain
3450244781f1SPrakash Surya 		 * sublists over others.
3451244781f1SPrakash Surya 		 */
3452244781f1SPrakash Surya 		int sublist_idx = multilist_get_random_index(ml);
3453244781f1SPrakash Surya 		uint64_t scan_evicted = 0;
3454244781f1SPrakash Surya 
3455244781f1SPrakash Surya 		for (int i = 0; i < num_sublists; i++) {
3456244781f1SPrakash Surya 			uint64_t bytes_remaining;
3457244781f1SPrakash Surya 			uint64_t bytes_evicted;
3458244781f1SPrakash Surya 
3459244781f1SPrakash Surya 			if (bytes == ARC_EVICT_ALL)
3460244781f1SPrakash Surya 				bytes_remaining = ARC_EVICT_ALL;
3461244781f1SPrakash Surya 			else if (total_evicted < bytes)
3462244781f1SPrakash Surya 				bytes_remaining = bytes - total_evicted;
3463244781f1SPrakash Surya 			else
3464fa9e4066Sahrens 				break;
3465244781f1SPrakash Surya 
3466244781f1SPrakash Surya 			bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
3467244781f1SPrakash Surya 			    markers[sublist_idx], spa, bytes_remaining);
3468244781f1SPrakash Surya 
3469244781f1SPrakash Surya 			scan_evicted += bytes_evicted;
3470244781f1SPrakash Surya 			total_evicted += bytes_evicted;
3471244781f1SPrakash Surya 
3472244781f1SPrakash Surya 			/* we've reached the end, wrap to the beginning */
3473244781f1SPrakash Surya 			if (++sublist_idx >= num_sublists)
3474244781f1SPrakash Surya 				sublist_idx = 0;
3475244781f1SPrakash Surya 		}
3476244781f1SPrakash Surya 
3477244781f1SPrakash Surya 		/*
3478244781f1SPrakash Surya 		 * If we didn't evict anything during this scan, we have
3479244781f1SPrakash Surya 		 * no reason to believe we'll evict more during another
3480244781f1SPrakash Surya 		 * scan, so break the loop.
3481244781f1SPrakash Surya 		 */
3482244781f1SPrakash Surya 		if (scan_evicted == 0) {
3483244781f1SPrakash Surya 			/* This isn't possible, let's make that obvious */
3484244781f1SPrakash Surya 			ASSERT3S(bytes, !=, 0);
3485244781f1SPrakash Surya 
3486b802aa8cSSanjeev Bagewadi 			/*
3487244781f1SPrakash Surya 			 * When bytes is ARC_EVICT_ALL, the only way to
3488244781f1SPrakash Surya 			 * break the loop is when scan_evicted is zero.
3489244781f1SPrakash Surya 			 * In that case, we actually have evicted enough,
3490244781f1SPrakash Surya 			 * so we don't want to increment the kstat.
3491b802aa8cSSanjeev Bagewadi 			 */
3492244781f1SPrakash Surya 			if (bytes != ARC_EVICT_ALL) {
3493244781f1SPrakash Surya 				ASSERT3S(total_evicted, <, bytes);
3494244781f1SPrakash Surya 				ARCSTAT_BUMP(arcstat_evict_not_enough);
3495244781f1SPrakash Surya 			}
3496244781f1SPrakash Surya 
3497244781f1SPrakash Surya 			break;
349869962b56SMatthew Ahrens 		}
3499244781f1SPrakash Surya 	}
3500244781f1SPrakash Surya 
3501244781f1SPrakash Surya 	for (int i = 0; i < num_sublists; i++) {
3502244781f1SPrakash Surya 		multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3503244781f1SPrakash Surya 		multilist_sublist_remove(mls, markers[i]);
3504244781f1SPrakash Surya 		multilist_sublist_unlock(mls);
350569962b56SMatthew Ahrens 
3506244781f1SPrakash Surya 		kmem_cache_free(hdr_full_cache, markers[i]);
3507fa9e4066Sahrens 	}
3508244781f1SPrakash Surya 	kmem_free(markers, sizeof (*markers) * num_sublists);
3509fa9e4066Sahrens 
3510244781f1SPrakash Surya 	return (total_evicted);
3511244781f1SPrakash Surya }
3512244781f1SPrakash Surya 
3513244781f1SPrakash Surya /*
3514244781f1SPrakash Surya  * Flush all "evictable" data of the given type from the arc state
3515244781f1SPrakash Surya  * specified. This will not evict any "active" buffers (i.e. referenced).
3516244781f1SPrakash Surya  *
3517dcbf3bd6SGeorge Wilson  * When 'retry' is set to B_FALSE, the function will make a single pass
3518244781f1SPrakash Surya  * over the state and evict any buffers that it can. Since it doesn't
3519244781f1SPrakash Surya  * continually retry the eviction, it might end up leaving some buffers
3520244781f1SPrakash Surya  * in the ARC due to lock misses.
3521244781f1SPrakash Surya  *
3522dcbf3bd6SGeorge Wilson  * When 'retry' is set to B_TRUE, the function will continually retry the
3523244781f1SPrakash Surya  * eviction until *all* evictable buffers have been removed from the
3524244781f1SPrakash Surya  * state. As a result, if concurrent insertions into the state are
3525244781f1SPrakash Surya  * allowed (e.g. if the ARC isn't shutting down), this function might
3526244781f1SPrakash Surya  * wind up in an infinite loop, continually trying to evict buffers.
3527244781f1SPrakash Surya  */
3528244781f1SPrakash Surya static uint64_t
3529244781f1SPrakash Surya arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
3530244781f1SPrakash Surya     boolean_t retry)
3531244781f1SPrakash Surya {
3532244781f1SPrakash Surya 	uint64_t evicted = 0;
3533244781f1SPrakash Surya 
3534dcbf3bd6SGeorge Wilson 	while (refcount_count(&state->arcs_esize[type]) != 0) {
3535244781f1SPrakash Surya 		evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
3536244781f1SPrakash Surya 
3537244781f1SPrakash Surya 		if (!retry)
3538244781f1SPrakash Surya 			break;
35390e8c6158Smaybee 	}
35400e8c6158Smaybee 
3541244781f1SPrakash Surya 	return (evicted);
3542244781f1SPrakash Surya }
3543244781f1SPrakash Surya 
3544244781f1SPrakash Surya /*
3545244781f1SPrakash Surya  * Evict the specified number of bytes from the state specified,
3546244781f1SPrakash Surya  * restricting eviction to the spa and type given. This function
3547244781f1SPrakash Surya  * prevents us from trying to evict more from a state's list than
3548244781f1SPrakash Surya  * is "evictable", and to skip evicting altogether when passed a
3549244781f1SPrakash Surya  * negative value for "bytes". In contrast, arc_evict_state() will
3550244781f1SPrakash Surya  * evict everything it can, when passed a negative value for "bytes".
3551244781f1SPrakash Surya  */
3552244781f1SPrakash Surya static uint64_t
3553244781f1SPrakash Surya arc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
3554244781f1SPrakash Surya     arc_buf_contents_t type)
3555244781f1SPrakash Surya {
3556244781f1SPrakash Surya 	int64_t delta;
3557244781f1SPrakash Surya 
3558dcbf3bd6SGeorge Wilson 	if (bytes > 0 && refcount_count(&state->arcs_esize[type]) > 0) {
3559dcbf3bd6SGeorge Wilson 		delta = MIN(refcount_count(&state->arcs_esize[type]), bytes);
3560244781f1SPrakash Surya 		return (arc_evict_state(state, spa, delta, type));
3561fa9e4066Sahrens 	}
3562fa9e4066Sahrens 
3563244781f1SPrakash Surya 	return (0);
3564fa9e4066Sahrens }
3565fa9e4066Sahrens 
3566244781f1SPrakash Surya /*
3567244781f1SPrakash Surya  * Evict metadata buffers from the cache, such that arc_meta_used is
3568244781f1SPrakash Surya  * capped by the arc_meta_limit tunable.
3569244781f1SPrakash Surya  */
3570244781f1SPrakash Surya static uint64_t
3571244781f1SPrakash Surya arc_adjust_meta(void)
3572244781f1SPrakash Surya {
3573244781f1SPrakash Surya 	uint64_t total_evicted = 0;
3574244781f1SPrakash Surya 	int64_t target;
3575244781f1SPrakash Surya 
3576244781f1SPrakash Surya 	/*
3577244781f1SPrakash Surya 	 * If we're over the meta limit, we want to evict enough
3578244781f1SPrakash Surya 	 * metadata to get back under the meta limit. We don't want to
3579244781f1SPrakash Surya 	 * evict so much that we drop the MRU below arc_p, though. If
3580244781f1SPrakash Surya 	 * we're over the meta limit more than we're over arc_p, we
3581244781f1SPrakash Surya 	 * evict some from the MRU here, and some from the MFU below.
3582244781f1SPrakash Surya 	 */
3583244781f1SPrakash Surya 	target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
35842fd872a7SPrakash Surya 	    (int64_t)(refcount_count(&arc_anon->arcs_size) +
35852fd872a7SPrakash Surya 	    refcount_count(&arc_mru->arcs_size) - arc_p));
3586244781f1SPrakash Surya 
3587244781f1SPrakash Surya 	total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3588244781f1SPrakash Surya 
3589244781f1SPrakash Surya 	/*
3590244781f1SPrakash Surya 	 * Similar to the above, we want to evict enough bytes to get us
3591244781f1SPrakash Surya 	 * below the meta limit, but not so much as to drop us below the
35925602294fSDan Kimmel 	 * space allotted to the MFU (which is defined as arc_c - arc_p).
3593244781f1SPrakash Surya 	 */
3594244781f1SPrakash Surya 	target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
35952fd872a7SPrakash Surya 	    (int64_t)(refcount_count(&arc_mfu->arcs_size) - (arc_c - arc_p)));
3596244781f1SPrakash Surya 
3597244781f1SPrakash Surya 	total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3598244781f1SPrakash Surya 
3599244781f1SPrakash Surya 	return (total_evicted);
3600244781f1SPrakash Surya }
3601244781f1SPrakash Surya 
3602244781f1SPrakash Surya /*
3603244781f1SPrakash Surya  * Return the type of the oldest buffer in the given arc state
3604244781f1SPrakash Surya  *
3605244781f1SPrakash Surya  * This function will select a random sublist of type ARC_BUFC_DATA and
3606244781f1SPrakash Surya  * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
3607244781f1SPrakash Surya  * is compared, and the type which contains the "older" buffer will be
3608244781f1SPrakash Surya  * returned.
3609244781f1SPrakash Surya  */
3610244781f1SPrakash Surya static arc_buf_contents_t
3611244781f1SPrakash Surya arc_adjust_type(arc_state_t *state)
3612244781f1SPrakash Surya {
361394c2d0ebSMatthew Ahrens 	multilist_t *data_ml = state->arcs_list[ARC_BUFC_DATA];
361494c2d0ebSMatthew Ahrens 	multilist_t *meta_ml = state->arcs_list[ARC_BUFC_METADATA];
3615244781f1SPrakash Surya 	int data_idx = multilist_get_random_index(data_ml);
3616244781f1SPrakash Surya 	int meta_idx = multilist_get_random_index(meta_ml);
3617244781f1SPrakash Surya 	multilist_sublist_t *data_mls;
3618244781f1SPrakash Surya 	multilist_sublist_t *meta_mls;
3619244781f1SPrakash Surya 	arc_buf_contents_t type;
3620244781f1SPrakash Surya 	arc_buf_hdr_t *data_hdr;
3621244781f1SPrakash Surya 	arc_buf_hdr_t *meta_hdr;
3622244781f1SPrakash Surya 
3623244781f1SPrakash Surya 	/*
3624244781f1SPrakash Surya 	 * We keep the sublist lock until we're finished, to prevent
3625244781f1SPrakash Surya 	 * the headers from being destroyed via arc_evict_state().
3626244781f1SPrakash Surya 	 */
3627244781f1SPrakash Surya 	data_mls = multilist_sublist_lock(data_ml, data_idx);
3628244781f1SPrakash Surya 	meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
3629244781f1SPrakash Surya 
3630244781f1SPrakash Surya 	/*
3631244781f1SPrakash Surya 	 * These two loops are to ensure we skip any markers that
3632244781f1SPrakash Surya 	 * might be at the tail of the lists due to arc_evict_state().
3633244781f1SPrakash Surya 	 */
3634244781f1SPrakash Surya 
3635244781f1SPrakash Surya 	for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
3636244781f1SPrakash Surya 	    data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
3637244781f1SPrakash Surya 		if (data_hdr->b_spa != 0)
3638244781f1SPrakash Surya 			break;
3639244781f1SPrakash Surya 	}
3640244781f1SPrakash Surya 
3641244781f1SPrakash Surya 	for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
3642244781f1SPrakash Surya 	    meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
3643244781f1SPrakash Surya 		if (meta_hdr->b_spa != 0)
3644244781f1SPrakash Surya 			break;
3645244781f1SPrakash Surya 	}
3646244781f1SPrakash Surya 
3647244781f1SPrakash Surya 	if (data_hdr == NULL && meta_hdr == NULL) {
3648244781f1SPrakash Surya 		type = ARC_BUFC_DATA;
3649244781f1SPrakash Surya 	} else if (data_hdr == NULL) {
3650244781f1SPrakash Surya 		ASSERT3P(meta_hdr, !=, NULL);
3651244781f1SPrakash Surya 		type = ARC_BUFC_METADATA;
3652244781f1SPrakash Surya 	} else if (meta_hdr == NULL) {
3653244781f1SPrakash Surya 		ASSERT3P(data_hdr, !=, NULL);
3654244781f1SPrakash Surya 		type = ARC_BUFC_DATA;
3655244781f1SPrakash Surya 	} else {
3656244781f1SPrakash Surya 		ASSERT3P(data_hdr, !=, NULL);
3657244781f1SPrakash Surya 		ASSERT3P(meta_hdr, !=, NULL);
3658244781f1SPrakash Surya 
3659244781f1SPrakash Surya 		/* The headers can't be on the sublist without an L1 header */
3660244781f1SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(data_hdr));
3661244781f1SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(meta_hdr));
3662244781f1SPrakash Surya 
3663244781f1SPrakash Surya 		if (data_hdr->b_l1hdr.b_arc_access <
3664244781f1SPrakash Surya 		    meta_hdr->b_l1hdr.b_arc_access) {
3665244781f1SPrakash Surya 			type = ARC_BUFC_DATA;
3666244781f1SPrakash Surya 		} else {
3667244781f1SPrakash Surya 			type = ARC_BUFC_METADATA;
3668244781f1SPrakash Surya 		}
3669244781f1SPrakash Surya 	}
3670244781f1SPrakash Surya 
3671244781f1SPrakash Surya 	multilist_sublist_unlock(meta_mls);
3672244781f1SPrakash Surya 	multilist_sublist_unlock(data_mls);
3673244781f1SPrakash Surya 
3674244781f1SPrakash Surya 	return (type);
3675244781f1SPrakash Surya }
3676244781f1SPrakash Surya 
3677244781f1SPrakash Surya /*
3678244781f1SPrakash Surya  * Evict buffers from the cache, such that arc_size is capped by arc_c.
3679244781f1SPrakash Surya  */
3680244781f1SPrakash Surya static uint64_t
3681fa9e4066Sahrens arc_adjust(void)
3682fa9e4066Sahrens {
3683244781f1SPrakash Surya 	uint64_t total_evicted = 0;
3684244781f1SPrakash Surya 	uint64_t bytes;
3685244781f1SPrakash Surya 	int64_t target;
3686fa9e4066Sahrens 
36875a98e54bSBrendan Gregg - Sun Microsystems 	/*
3688244781f1SPrakash Surya 	 * If we're over arc_meta_limit, we want to correct that before
3689244781f1SPrakash Surya 	 * potentially evicting data buffers below.
36905a98e54bSBrendan Gregg - Sun Microsystems 	 */
3691244781f1SPrakash Surya 	total_evicted += arc_adjust_meta();
36925a98e54bSBrendan Gregg - Sun Microsystems 
3693244781f1SPrakash Surya 	/*
3694244781f1SPrakash Surya 	 * Adjust MRU size
3695244781f1SPrakash Surya 	 *
3696244781f1SPrakash Surya 	 * If we're over the target cache size, we want to evict enough
3697244781f1SPrakash Surya 	 * from the list to get back to our target size. We don't want
3698244781f1SPrakash Surya 	 * to evict too much from the MRU, such that it drops below
3699244781f1SPrakash Surya 	 * arc_p. So, if we're over our target cache size more than
3700244781f1SPrakash Surya 	 * the MRU is over arc_p, we'll evict enough to get back to
3701244781f1SPrakash Surya 	 * arc_p here, and then evict more from the MFU below.
3702244781f1SPrakash Surya 	 */
3703244781f1SPrakash Surya 	target = MIN((int64_t)(arc_size - arc_c),
37042fd872a7SPrakash Surya 	    (int64_t)(refcount_count(&arc_anon->arcs_size) +
37052fd872a7SPrakash Surya 	    refcount_count(&arc_mru->arcs_size) + arc_meta_used - arc_p));
3706fa9e4066Sahrens 
3707244781f1SPrakash Surya 	/*
3708244781f1SPrakash Surya 	 * If we're below arc_meta_min, always prefer to evict data.
3709244781f1SPrakash Surya 	 * Otherwise, try to satisfy the requested number of bytes to
3710244781f1SPrakash Surya 	 * evict from the type which contains older buffers; in an
3711244781f1SPrakash Surya 	 * effort to keep newer buffers in the cache regardless of their
3712244781f1SPrakash Surya 	 * type. If we cannot satisfy the number of bytes from this
3713244781f1SPrakash Surya 	 * type, spill over into the next type.
3714244781f1SPrakash Surya 	 */
3715244781f1SPrakash Surya 	if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
3716244781f1SPrakash Surya 	    arc_meta_used > arc_meta_min) {
3717244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3718244781f1SPrakash Surya 		total_evicted += bytes;
37190e8c6158Smaybee 
3720244781f1SPrakash Surya 		/*
3721244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
3722244781f1SPrakash Surya 		 * metadata, we try to get the rest from data.
3723244781f1SPrakash Surya 		 */
3724244781f1SPrakash Surya 		target -= bytes;
3725244781f1SPrakash Surya 
3726244781f1SPrakash Surya 		total_evicted +=
3727244781f1SPrakash Surya 		    arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3728244781f1SPrakash Surya 	} else {
3729244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3730244781f1SPrakash Surya 		total_evicted += bytes;
3731244781f1SPrakash Surya 
3732244781f1SPrakash Surya 		/*
3733244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
3734244781f1SPrakash Surya 		 * data, we try to get the rest from metadata.
3735244781f1SPrakash Surya 		 */
3736244781f1SPrakash Surya 		target -= bytes;
3737244781f1SPrakash Surya 
3738244781f1SPrakash Surya 		total_evicted +=
3739244781f1SPrakash Surya 		    arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3740fa9e4066Sahrens 	}
3741fa9e4066Sahrens 
37425a98e54bSBrendan Gregg - Sun Microsystems 	/*
37435a98e54bSBrendan Gregg - Sun Microsystems 	 * Adjust MFU size
3744244781f1SPrakash Surya 	 *
3745244781f1SPrakash Surya 	 * Now that we've tried to evict enough from the MRU to get its
3746244781f1SPrakash Surya 	 * size back to arc_p, if we're still above the target cache
3747244781f1SPrakash Surya 	 * size, we evict the rest from the MFU.
37485a98e54bSBrendan Gregg - Sun Microsystems 	 */
3749244781f1SPrakash Surya 	target = arc_size - arc_c;
3750fa9e4066Sahrens 
375131c46cf2SAlek Pinchuk 	if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
3752244781f1SPrakash Surya 	    arc_meta_used > arc_meta_min) {
3753244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3754244781f1SPrakash Surya 		total_evicted += bytes;
37555a98e54bSBrendan Gregg - Sun Microsystems 
3756244781f1SPrakash Surya 		/*
3757244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
3758244781f1SPrakash Surya 		 * metadata, we try to get the rest from data.
3759244781f1SPrakash Surya 		 */
3760244781f1SPrakash Surya 		target -= bytes;
3761244781f1SPrakash Surya 
3762244781f1SPrakash Surya 		total_evicted +=
3763244781f1SPrakash Surya 		    arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3764244781f1SPrakash Surya 	} else {
3765244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3766244781f1SPrakash Surya 		total_evicted += bytes;
3767244781f1SPrakash Surya 
3768244781f1SPrakash Surya 		/*
3769244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
3770244781f1SPrakash Surya 		 * data, we try to get the rest from data.
3771244781f1SPrakash Surya 		 */
3772244781f1SPrakash Surya 		target -= bytes;
3773fa9e4066Sahrens 
3774244781f1SPrakash Surya 		total_evicted +=
3775244781f1SPrakash Surya 		    arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
37765a98e54bSBrendan Gregg - Sun Microsystems 	}
3777fa9e4066Sahrens 
37785a98e54bSBrendan Gregg - Sun Microsystems 	/*
37795a98e54bSBrendan Gregg - Sun Microsystems 	 * Adjust ghost lists
3780244781f1SPrakash Surya 	 *
3781244781f1SPrakash Surya 	 * In addition to the above, the ARC also defines target values
3782244781f1SPrakash Surya 	 * for the ghost lists. The sum of the mru list and mru ghost
3783244781f1SPrakash Surya 	 * list should never exceed the target size of the cache, and
3784244781f1SPrakash Surya 	 * the sum of the mru list, mfu list, mru ghost list, and mfu
3785244781f1SPrakash Surya 	 * ghost list should never exceed twice the target size of the
3786244781f1SPrakash Surya 	 * cache. The following logic enforces these limits on the ghost
3787244781f1SPrakash Surya 	 * caches, and evicts from them as needed.
37885a98e54bSBrendan Gregg - Sun Microsystems 	 */
37892fd872a7SPrakash Surya 	target = refcount_count(&arc_mru->arcs_size) +
37902fd872a7SPrakash Surya 	    refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
3791fa9e4066Sahrens 
3792244781f1SPrakash Surya 	bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
3793244781f1SPrakash Surya 	total_evicted += bytes;
3794fa9e4066Sahrens 
3795244781f1SPrakash Surya 	target -= bytes;
37960e8c6158Smaybee 
3797244781f1SPrakash Surya 	total_evicted +=
3798244781f1SPrakash Surya 	    arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
37995a98e54bSBrendan Gregg - Sun Microsystems 
3800244781f1SPrakash Surya 	/*
3801244781f1SPrakash Surya 	 * We assume the sum of the mru list and mfu list is less than
3802244781f1SPrakash Surya 	 * or equal to arc_c (we enforced this above), which means we
3803244781f1SPrakash Surya 	 * can use the simpler of the two equations below:
3804244781f1SPrakash Surya 	 *
3805244781f1SPrakash Surya 	 *	mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
3806244781f1SPrakash Surya 	 *		    mru ghost + mfu ghost <= arc_c
3807244781f1SPrakash Surya 	 */
38082fd872a7SPrakash Surya 	target = refcount_count(&arc_mru_ghost->arcs_size) +
38092fd872a7SPrakash Surya 	    refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
3810244781f1SPrakash Surya 
3811244781f1SPrakash Surya 	bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
3812244781f1SPrakash Surya 	total_evicted += bytes;
3813244781f1SPrakash Surya 
3814244781f1SPrakash Surya 	target -= bytes;
3815244781f1SPrakash Surya 
3816244781f1SPrakash Surya 	total_evicted +=
3817244781f1SPrakash Surya 	    arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
3818244781f1SPrakash Surya 
3819244781f1SPrakash Surya 	return (total_evicted);
3820fa9e4066Sahrens }
3821fa9e4066Sahrens 
3822fa9e4066Sahrens void
3823244781f1SPrakash Surya arc_flush(spa_t *spa, boolean_t retry)
3824fa9e4066Sahrens {
3825ac05c741SMark Maybee 	uint64_t guid = 0;
3826ac05c741SMark Maybee 
3827244781f1SPrakash Surya 	/*
3828dcbf3bd6SGeorge Wilson 	 * If retry is B_TRUE, a spa must not be specified since we have
3829244781f1SPrakash Surya 	 * no good way to determine if all of a spa's buffers have been
3830244781f1SPrakash Surya 	 * evicted from an arc state.
3831244781f1SPrakash Surya 	 */
3832244781f1SPrakash Surya 	ASSERT(!retry || spa == 0);
3833244781f1SPrakash Surya 
383489c86e32SChris Williamson 	if (spa != NULL)
3835e9103aaeSGarrett D'Amore 		guid = spa_load_guid(spa);
3836ac05c741SMark Maybee 
3837244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
3838244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
3839244781f1SPrakash Surya 
3840244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
3841244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
3842874395d5Smaybee 
3843244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
3844244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
3845244781f1SPrakash Surya 
3846244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
3847244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
3848fa9e4066Sahrens }
3849fa9e4066Sahrens 
3850fa9e4066Sahrens void
38512ec99e3eSMatthew Ahrens arc_shrink(int64_t to_free)
3852fa9e4066Sahrens {
385344cb6abcSbmc 	if (arc_c > arc_c_min) {
3854fa9e4066Sahrens 
385544cb6abcSbmc 		if (arc_c > arc_c_min + to_free)
385644cb6abcSbmc 			atomic_add_64(&arc_c, -to_free);
385749e3519aSmaybee 		else
385844cb6abcSbmc 			arc_c = arc_c_min;
385944cb6abcSbmc 
386044cb6abcSbmc 		atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
386144cb6abcSbmc 		if (arc_c > arc_size)
386244cb6abcSbmc 			arc_c = MAX(arc_size, arc_c_min);
386344cb6abcSbmc 		if (arc_p > arc_c)
386444cb6abcSbmc 			arc_p = (arc_c >> 1);
386544cb6abcSbmc 		ASSERT(arc_c >= arc_c_min);
386644cb6abcSbmc 		ASSERT((int64_t)arc_p >= 0);
386749e3519aSmaybee 	}
3868fa9e4066Sahrens 
386944cb6abcSbmc 	if (arc_size > arc_c)
3870244781f1SPrakash Surya 		(void) arc_adjust();
3871fa9e4066Sahrens }
3872fa9e4066Sahrens 
38732ec99e3eSMatthew Ahrens typedef enum free_memory_reason_t {
38742ec99e3eSMatthew Ahrens 	FMR_UNKNOWN,
38752ec99e3eSMatthew Ahrens 	FMR_NEEDFREE,
38762ec99e3eSMatthew Ahrens 	FMR_LOTSFREE,
38772ec99e3eSMatthew Ahrens 	FMR_SWAPFS_MINFREE,
38782ec99e3eSMatthew Ahrens 	FMR_PAGES_PP_MAXIMUM,
38792ec99e3eSMatthew Ahrens 	FMR_HEAP_ARENA,
38802ec99e3eSMatthew Ahrens 	FMR_ZIO_ARENA,
38812ec99e3eSMatthew Ahrens } free_memory_reason_t;
38822ec99e3eSMatthew Ahrens 
38832ec99e3eSMatthew Ahrens int64_t last_free_memory;
38842ec99e3eSMatthew Ahrens free_memory_reason_t last_free_reason;
38852ec99e3eSMatthew Ahrens 
388694dd93aeSGeorge Wilson /*
38872ec99e3eSMatthew Ahrens  * Additional reserve of pages for pp_reserve.
388894dd93aeSGeorge Wilson  */
38892ec99e3eSMatthew Ahrens int64_t arc_pages_pp_reserve = 64;
3890fa9e4066Sahrens 
38912ec99e3eSMatthew Ahrens /*
38922ec99e3eSMatthew Ahrens  * Additional reserve of pages for swapfs.
38932ec99e3eSMatthew Ahrens  */
38942ec99e3eSMatthew Ahrens int64_t arc_swapfs_reserve = 64;
38953cff2f43Sstans 
38962ec99e3eSMatthew Ahrens /*
38972ec99e3eSMatthew Ahrens  * Return the amount of memory that can be consumed before reclaim will be
38982ec99e3eSMatthew Ahrens  * needed.  Positive if there is sufficient free memory, negative indicates
38992ec99e3eSMatthew Ahrens  * the amount of memory that needs to be freed up.
39002ec99e3eSMatthew Ahrens  */
39012ec99e3eSMatthew Ahrens static int64_t
39022ec99e3eSMatthew Ahrens arc_available_memory(void)
39032ec99e3eSMatthew Ahrens {
39042ec99e3eSMatthew Ahrens 	int64_t lowest = INT64_MAX;
39052ec99e3eSMatthew Ahrens 	int64_t n;
39062ec99e3eSMatthew Ahrens 	free_memory_reason_t r = FMR_UNKNOWN;
39073cff2f43Sstans 
39082ec99e3eSMatthew Ahrens #ifdef _KERNEL
39092ec99e3eSMatthew Ahrens 	if (needfree > 0) {
39102ec99e3eSMatthew Ahrens 		n = PAGESIZE * (-needfree);
39112ec99e3eSMatthew Ahrens 		if (n < lowest) {
39122ec99e3eSMatthew Ahrens 			lowest = n;
39132ec99e3eSMatthew Ahrens 			r = FMR_NEEDFREE;
39142ec99e3eSMatthew Ahrens 		}
39152ec99e3eSMatthew Ahrens 	}
3916fa9e4066Sahrens 
3917fa9e4066Sahrens 	/*
3918fa9e4066Sahrens 	 * check that we're out of range of the pageout scanner.  It starts to
3919fa9e4066Sahrens 	 * schedule paging if freemem is less than lotsfree and needfree.
3920fa9e4066Sahrens 	 * lotsfree is the high-water mark for pageout, and needfree is the
3921fa9e4066Sahrens 	 * number of needed free pages.  We add extra pages here to make sure
3922fa9e4066Sahrens 	 * the scanner doesn't start up while we're freeing memory.
3923fa9e4066Sahrens 	 */
39242ec99e3eSMatthew Ahrens 	n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
39252ec99e3eSMatthew Ahrens 	if (n < lowest) {
39262ec99e3eSMatthew Ahrens 		lowest = n;
39272ec99e3eSMatthew Ahrens 		r = FMR_LOTSFREE;
39282ec99e3eSMatthew Ahrens 	}
3929fa9e4066Sahrens 
3930fa9e4066Sahrens 	/*
3931fa9e4066Sahrens 	 * check to make sure that swapfs has enough space so that anon
3932fa94a07fSbrendan 	 * reservations can still succeed. anon_resvmem() checks that the
3933fa9e4066Sahrens 	 * availrmem is greater than swapfs_minfree, and the number of reserved
3934fa9e4066Sahrens 	 * swap pages.  We also add a bit of extra here just to prevent
3935fa9e4066Sahrens 	 * circumstances from getting really dire.
3936fa9e4066Sahrens 	 */
39372ec99e3eSMatthew Ahrens 	n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
39382ec99e3eSMatthew Ahrens 	    desfree - arc_swapfs_reserve);
39392ec99e3eSMatthew Ahrens 	if (n < lowest) {
39402ec99e3eSMatthew Ahrens 		lowest = n;
39412ec99e3eSMatthew Ahrens 		r = FMR_SWAPFS_MINFREE;
39422ec99e3eSMatthew Ahrens 	}
39432ec99e3eSMatthew Ahrens 
3944fa9e4066Sahrens 
3945cf746768SBryan Cantrill 	/*
3946cf746768SBryan Cantrill 	 * Check that we have enough availrmem that memory locking (e.g., via
3947cf746768SBryan Cantrill 	 * mlock(3C) or memcntl(2)) can still succeed.  (pages_pp_maximum
3948cf746768SBryan Cantrill 	 * stores the number of pages that cannot be locked; when availrmem
3949cf746768SBryan Cantrill 	 * drops below pages_pp_maximum, page locking mechanisms such as
3950cf746768SBryan Cantrill 	 * page_pp_lock() will fail.)
3951cf746768SBryan Cantrill 	 */
39522ec99e3eSMatthew Ahrens 	n = PAGESIZE * (availrmem - pages_pp_maximum -
39532ec99e3eSMatthew Ahrens 	    arc_pages_pp_reserve);
39542ec99e3eSMatthew Ahrens 	if (n < lowest) {
39552ec99e3eSMatthew Ahrens 		lowest = n;
39562ec99e3eSMatthew Ahrens 		r = FMR_PAGES_PP_MAXIMUM;
39572ec99e3eSMatthew Ahrens 	}
3958cf746768SBryan Cantrill 
39595dc8af33Smaybee #if defined(__i386)
3960fa9e4066Sahrens 	/*
3961fa9e4066Sahrens 	 * If we're on an i386 platform, it's possible that we'll exhaust the
3962fa9e4066Sahrens 	 * kernel heap space before we ever run out of available physical
3963fa9e4066Sahrens 	 * memory.  Most checks of the size of the heap_area compare against
3964fa9e4066Sahrens 	 * tune.t_minarmem, which is the minimum available real memory that we
3965fa9e4066Sahrens 	 * can have in the system.  However, this is generally fixed at 25 pages
3966fa9e4066Sahrens 	 * which is so low that it's useless.  In this comparison, we seek to
3967fa9e4066Sahrens 	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
3968fa94a07fSbrendan 	 * heap is allocated.  (Or, in the calculation, if less than 1/4th is
3969fa9e4066Sahrens 	 * free)
3970fa9e4066Sahrens 	 */
39710dd053d7SPrakash Surya 	n = (int64_t)vmem_size(heap_arena, VMEM_FREE) -
39722ec99e3eSMatthew Ahrens 	    (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2);
39732ec99e3eSMatthew Ahrens 	if (n < lowest) {
39742ec99e3eSMatthew Ahrens 		lowest = n;
39752ec99e3eSMatthew Ahrens 		r = FMR_HEAP_ARENA;
39762ec99e3eSMatthew Ahrens 	}
3977fa9e4066Sahrens #endif
3978fa9e4066Sahrens 
397994dd93aeSGeorge Wilson 	/*
398094dd93aeSGeorge Wilson 	 * If zio data pages are being allocated out of a separate heap segment,
398194dd93aeSGeorge Wilson 	 * then enforce that the size of available vmem for this arena remains
39820dd053d7SPrakash Surya 	 * above about 1/4th (1/(2^arc_zio_arena_free_shift)) free.
398394dd93aeSGeorge Wilson 	 *
39840dd053d7SPrakash Surya 	 * Note that reducing the arc_zio_arena_free_shift keeps more virtual
39850dd053d7SPrakash Surya 	 * memory (in the zio_arena) free, which can avoid memory
39860dd053d7SPrakash Surya 	 * fragmentation issues.
398794dd93aeSGeorge Wilson 	 */
39882ec99e3eSMatthew Ahrens 	if (zio_arena != NULL) {
39890dd053d7SPrakash Surya 		n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
39900dd053d7SPrakash Surya 		    (vmem_size(zio_arena, VMEM_ALLOC) >>
39910dd053d7SPrakash Surya 		    arc_zio_arena_free_shift);
39922ec99e3eSMatthew Ahrens 		if (n < lowest) {
39932ec99e3eSMatthew Ahrens 			lowest = n;
39942ec99e3eSMatthew Ahrens 			r = FMR_ZIO_ARENA;
39952ec99e3eSMatthew Ahrens 		}
39962ec99e3eSMatthew Ahrens 	}
3997fa9e4066Sahrens #else
39982ec99e3eSMatthew Ahrens 	/* Every 100 calls, free a small amount */
3999fa9e4066Sahrens 	if (spa_get_random(100) == 0)
40002ec99e3eSMatthew Ahrens 		lowest = -1024;
4001fa9e4066Sahrens #endif
40022ec99e3eSMatthew Ahrens 
40032ec99e3eSMatthew Ahrens 	last_free_memory = lowest;
40042ec99e3eSMatthew Ahrens 	last_free_reason = r;
40052ec99e3eSMatthew Ahrens 
40062ec99e3eSMatthew Ahrens 	return (lowest);
40072ec99e3eSMatthew Ahrens }
40082ec99e3eSMatthew Ahrens 
40092ec99e3eSMatthew Ahrens 
40102ec99e3eSMatthew Ahrens /*
40112ec99e3eSMatthew Ahrens  * Determine if the system is under memory pressure and is asking
4012dcbf3bd6SGeorge Wilson  * to reclaim memory. A return value of B_TRUE indicates that the system
40132ec99e3eSMatthew Ahrens  * is under memory pressure and that the arc should adjust accordingly.
40142ec99e3eSMatthew Ahrens  */
40152ec99e3eSMatthew Ahrens static boolean_t
40162ec99e3eSMatthew Ahrens arc_reclaim_needed(void)
40172ec99e3eSMatthew Ahrens {
40182ec99e3eSMatthew Ahrens 	return (arc_available_memory() < 0);
4019fa9e4066Sahrens }
4020fa9e4066Sahrens 
4021fa9e4066Sahrens static void
40222ec99e3eSMatthew Ahrens arc_kmem_reap_now(void)
4023fa9e4066Sahrens {
4024fa9e4066Sahrens 	size_t			i;
4025fa9e4066Sahrens 	kmem_cache_t		*prev_cache = NULL;
4026ad23a2dbSjohansen 	kmem_cache_t		*prev_data_cache = NULL;
4027fa9e4066Sahrens 	extern kmem_cache_t	*zio_buf_cache[];
4028ad23a2dbSjohansen 	extern kmem_cache_t	*zio_data_buf_cache[];
402983803b51SGeorge Wilson 	extern kmem_cache_t	*range_seg_cache;
4030*770499e1SDan Kimmel 	extern kmem_cache_t	*abd_chunk_cache;
4031fa9e4066Sahrens 
4032033f9833Sek #ifdef _KERNEL
40330e8c6158Smaybee 	if (arc_meta_used >= arc_meta_limit) {
40340e8c6158Smaybee 		/*
40350e8c6158Smaybee 		 * We are exceeding our meta-data cache limit.
40360e8c6158Smaybee 		 * Purge some DNLC entries to release holds on meta-data.
40370e8c6158Smaybee 		 */
40380e8c6158Smaybee 		dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
40390e8c6158Smaybee 	}
40405dc8af33Smaybee #if defined(__i386)
40415dc8af33Smaybee 	/*
40425dc8af33Smaybee 	 * Reclaim unused memory from all kmem caches.
40435dc8af33Smaybee 	 */
40445dc8af33Smaybee 	kmem_reap();
40455dc8af33Smaybee #endif
4046033f9833Sek #endif
4047033f9833Sek 
4048fa9e4066Sahrens 	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
4049fa9e4066Sahrens 		if (zio_buf_cache[i] != prev_cache) {
4050fa9e4066Sahrens 			prev_cache = zio_buf_cache[i];
4051fa9e4066Sahrens 			kmem_cache_reap_now(zio_buf_cache[i]);
4052fa9e4066Sahrens 		}
4053ad23a2dbSjohansen 		if (zio_data_buf_cache[i] != prev_data_cache) {
4054ad23a2dbSjohansen 			prev_data_cache = zio_data_buf_cache[i];
4055ad23a2dbSjohansen 			kmem_cache_reap_now(zio_data_buf_cache[i]);
4056ad23a2dbSjohansen 		}
4057fa9e4066Sahrens 	}
4058*770499e1SDan Kimmel 	kmem_cache_reap_now(abd_chunk_cache);
4059ea8dc4b6Seschrock 	kmem_cache_reap_now(buf_cache);
406089c86e32SChris Williamson 	kmem_cache_reap_now(hdr_full_cache);
406189c86e32SChris Williamson 	kmem_cache_reap_now(hdr_l2only_cache);
406283803b51SGeorge Wilson 	kmem_cache_reap_now(range_seg_cache);
406394dd93aeSGeorge Wilson 
40642ec99e3eSMatthew Ahrens 	if (zio_arena != NULL) {
40652ec99e3eSMatthew Ahrens 		/*
40662ec99e3eSMatthew Ahrens 		 * Ask the vmem arena to reclaim unused memory from its
40672ec99e3eSMatthew Ahrens 		 * quantum caches.
40682ec99e3eSMatthew Ahrens 		 */
406994dd93aeSGeorge Wilson 		vmem_qcache_reap(zio_arena);
40702ec99e3eSMatthew Ahrens 	}
4071fa9e4066Sahrens }
4072fa9e4066Sahrens 
4073244781f1SPrakash Surya /*
4074*770499e1SDan Kimmel  * Threads can block in arc_get_data_impl() waiting for this thread to evict
4075244781f1SPrakash Surya  * enough data and signal them to proceed. When this happens, the threads in
4076*770499e1SDan Kimmel  * arc_get_data_impl() are sleeping while holding the hash lock for their
4077244781f1SPrakash Surya  * particular arc header. Thus, we must be careful to never sleep on a
4078244781f1SPrakash Surya  * hash lock in this thread. This is to prevent the following deadlock:
4079244781f1SPrakash Surya  *
4080*770499e1SDan Kimmel  *  - Thread A sleeps on CV in arc_get_data_impl() holding hash lock "L",
4081244781f1SPrakash Surya  *    waiting for the reclaim thread to signal it.
4082244781f1SPrakash Surya  *
4083244781f1SPrakash Surya  *  - arc_reclaim_thread() tries to acquire hash lock "L" using mutex_enter,
4084244781f1SPrakash Surya  *    fails, and goes to sleep forever.
4085244781f1SPrakash Surya  *
4086244781f1SPrakash Surya  * This possible deadlock is avoided by always acquiring a hash lock
4087244781f1SPrakash Surya  * using mutex_tryenter() from arc_reclaim_thread().
4088244781f1SPrakash Surya  */
4089fa9e4066Sahrens static void
4090fa9e4066Sahrens arc_reclaim_thread(void)
4091fa9e4066Sahrens {
4092a8f6344fSEli Rosenthal 	hrtime_t		growtime = 0;
4093fa9e4066Sahrens 	callb_cpr_t		cpr;
4094fa9e4066Sahrens 
4095244781f1SPrakash Surya 	CALLB_CPR_INIT(&cpr, &arc_reclaim_lock, callb_generic_cpr, FTAG);
4096fa9e4066Sahrens 
4097244781f1SPrakash Surya 	mutex_enter(&arc_reclaim_lock);
4098244781f1SPrakash Surya 	while (!arc_reclaim_thread_exit) {
4099244781f1SPrakash Surya 		uint64_t evicted = 0;
4100244781f1SPrakash Surya 
4101dcbf3bd6SGeorge Wilson 		/*
4102dcbf3bd6SGeorge Wilson 		 * This is necessary in order for the mdb ::arc dcmd to
4103dcbf3bd6SGeorge Wilson 		 * show up to date information. Since the ::arc command
4104dcbf3bd6SGeorge Wilson 		 * does not call the kstat's update function, without
4105dcbf3bd6SGeorge Wilson 		 * this call, the command may show stale stats for the
4106dcbf3bd6SGeorge Wilson 		 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
4107dcbf3bd6SGeorge Wilson 		 * with this change, the data might be up to 1 second
4108dcbf3bd6SGeorge Wilson 		 * out of date; but that should suffice. The arc_state_t
4109dcbf3bd6SGeorge Wilson 		 * structures can be queried directly if more accurate
4110dcbf3bd6SGeorge Wilson 		 * information is needed.
4111dcbf3bd6SGeorge Wilson 		 */
4112dcbf3bd6SGeorge Wilson 		if (arc_ksp != NULL)
4113dcbf3bd6SGeorge Wilson 			arc_ksp->ks_update(arc_ksp, KSTAT_READ);
4114dcbf3bd6SGeorge Wilson 
4115244781f1SPrakash Surya 		mutex_exit(&arc_reclaim_lock);
4116244781f1SPrakash Surya 
4117405a5a0fSMatthew Ahrens 		/*
4118405a5a0fSMatthew Ahrens 		 * We call arc_adjust() before (possibly) calling
4119405a5a0fSMatthew Ahrens 		 * arc_kmem_reap_now(), so that we can wake up
4120*770499e1SDan Kimmel 		 * arc_get_data_impl() sooner.
4121405a5a0fSMatthew Ahrens 		 */
4122405a5a0fSMatthew Ahrens 		evicted = arc_adjust();
4123405a5a0fSMatthew Ahrens 
4124405a5a0fSMatthew Ahrens 		int64_t free_memory = arc_available_memory();
41252ec99e3eSMatthew Ahrens 		if (free_memory < 0) {
4126fa9e4066Sahrens 
41272ec99e3eSMatthew Ahrens 			arc_no_grow = B_TRUE;
41282ec99e3eSMatthew Ahrens 			arc_warm = B_TRUE;
4129fa9e4066Sahrens 
41302ec99e3eSMatthew Ahrens 			/*
41312ec99e3eSMatthew Ahrens 			 * Wait at least zfs_grow_retry (default 60) seconds
41322ec99e3eSMatthew Ahrens 			 * before considering growing.
41332ec99e3eSMatthew Ahrens 			 */
4134a8f6344fSEli Rosenthal 			growtime = gethrtime() + SEC2NSEC(arc_grow_retry);
4135fa9e4066Sahrens 
41362ec99e3eSMatthew Ahrens 			arc_kmem_reap_now();
4137fa9e4066Sahrens 
41382ec99e3eSMatthew Ahrens 			/*
41392ec99e3eSMatthew Ahrens 			 * If we are still low on memory, shrink the ARC
41402ec99e3eSMatthew Ahrens 			 * so that we have arc_shrink_min free space.
41412ec99e3eSMatthew Ahrens 			 */
41422ec99e3eSMatthew Ahrens 			free_memory = arc_available_memory();
41432ec99e3eSMatthew Ahrens 
41442ec99e3eSMatthew Ahrens 			int64_t to_free =
41452ec99e3eSMatthew Ahrens 			    (arc_c >> arc_shrink_shift) - free_memory;
41462ec99e3eSMatthew Ahrens 			if (to_free > 0) {
41472ec99e3eSMatthew Ahrens #ifdef _KERNEL
41482ec99e3eSMatthew Ahrens 				to_free = MAX(to_free, ptob(needfree));
41492ec99e3eSMatthew Ahrens #endif
41502ec99e3eSMatthew Ahrens 				arc_shrink(to_free);
41512ec99e3eSMatthew Ahrens 			}
41522ec99e3eSMatthew Ahrens 		} else if (free_memory < arc_c >> arc_no_grow_shift) {
41532ec99e3eSMatthew Ahrens 			arc_no_grow = B_TRUE;
4154a8f6344fSEli Rosenthal 		} else if (gethrtime() >= growtime) {
41552ec99e3eSMatthew Ahrens 			arc_no_grow = B_FALSE;
4156fa9e4066Sahrens 		}
4157fa9e4066Sahrens 
4158244781f1SPrakash Surya 		mutex_enter(&arc_reclaim_lock);
4159244781f1SPrakash Surya 
4160244781f1SPrakash Surya 		/*
4161244781f1SPrakash Surya 		 * If evicted is zero, we couldn't evict anything via
4162244781f1SPrakash Surya 		 * arc_adjust(). This could be due to hash lock
4163244781f1SPrakash Surya 		 * collisions, but more likely due to the majority of
4164244781f1SPrakash Surya 		 * arc buffers being unevictable. Therefore, even if
4165244781f1SPrakash Surya 		 * arc_size is above arc_c, another pass is unlikely to
4166244781f1SPrakash Surya 		 * be helpful and could potentially cause us to enter an
4167244781f1SPrakash Surya 		 * infinite loop.
4168244781f1SPrakash Surya 		 */
4169244781f1SPrakash Surya 		if (arc_size <= arc_c || evicted == 0) {
4170244781f1SPrakash Surya 			/*
4171244781f1SPrakash Surya 			 * We're either no longer overflowing, or we
4172244781f1SPrakash Surya 			 * can't evict anything more, so we should wake
4173244781f1SPrakash Surya 			 * up any threads before we go to sleep.
4174244781f1SPrakash Surya 			 */
4175244781f1SPrakash Surya 			cv_broadcast(&arc_reclaim_waiters_cv);
4176244781f1SPrakash Surya 
4177244781f1SPrakash Surya 			/*
4178244781f1SPrakash Surya 			 * Block until signaled, or after one second (we
4179244781f1SPrakash Surya 			 * might need to perform arc_kmem_reap_now()
4180244781f1SPrakash Surya 			 * even if we aren't being signalled)
4181244781f1SPrakash Surya 			 */
4182244781f1SPrakash Surya 			CALLB_CPR_SAFE_BEGIN(&cpr);
4183a8f6344fSEli Rosenthal 			(void) cv_timedwait_hires(&arc_reclaim_thread_cv,
4184a8f6344fSEli Rosenthal 			    &arc_reclaim_lock, SEC2NSEC(1), MSEC2NSEC(1), 0);
4185244781f1SPrakash Surya 			CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_lock);
4186244781f1SPrakash Surya 		}
4187244781f1SPrakash Surya 	}
4188244781f1SPrakash Surya 
4189dcbf3bd6SGeorge Wilson 	arc_reclaim_thread_exit = B_FALSE;
4190244781f1SPrakash Surya 	cv_broadcast(&arc_reclaim_thread_cv);
4191244781f1SPrakash Surya 	CALLB_CPR_EXIT(&cpr);		/* drops arc_reclaim_lock */
4192244781f1SPrakash Surya 	thread_exit();
4193244781f1SPrakash Surya }
4194244781f1SPrakash Surya 
4195ea8dc4b6Seschrock /*
4196ea8dc4b6Seschrock  * Adapt arc info given the number of bytes we are trying to add and
4197ea8dc4b6Seschrock  * the state that we are comming from.  This function is only called
4198ea8dc4b6Seschrock  * when we are adding new content to the cache.
4199ea8dc4b6Seschrock  */
4200fa9e4066Sahrens static void
4201ea8dc4b6Seschrock arc_adapt(int bytes, arc_state_t *state)
4202fa9e4066Sahrens {
4203ea8dc4b6Seschrock 	int mult;
42045a98e54bSBrendan Gregg - Sun Microsystems 	uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
42052fd872a7SPrakash Surya 	int64_t mrug_size = refcount_count(&arc_mru_ghost->arcs_size);
42062fd872a7SPrakash Surya 	int64_t mfug_size = refcount_count(&arc_mfu_ghost->arcs_size);
4207ea8dc4b6Seschrock 
4208fa94a07fSbrendan 	if (state == arc_l2c_only)
4209fa94a07fSbrendan 		return;
4210fa94a07fSbrendan 
4211ea8dc4b6Seschrock 	ASSERT(bytes > 0);
4212fa9e4066Sahrens 	/*
4213ea8dc4b6Seschrock 	 * Adapt the target size of the MRU list:
4214ea8dc4b6Seschrock 	 *	- if we just hit in the MRU ghost list, then increase
4215ea8dc4b6Seschrock 	 *	  the target size of the MRU list.
4216ea8dc4b6Seschrock 	 *	- if we just hit in the MFU ghost list, then increase
4217ea8dc4b6Seschrock 	 *	  the target size of the MFU list by decreasing the
4218ea8dc4b6Seschrock 	 *	  target size of the MRU list.
4219fa9e4066Sahrens 	 */
422044cb6abcSbmc 	if (state == arc_mru_ghost) {
42212fd872a7SPrakash Surya 		mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
42223e4e8481STom Erickson 		mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
4223ea8dc4b6Seschrock 
42245a98e54bSBrendan Gregg - Sun Microsystems 		arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
422544cb6abcSbmc 	} else if (state == arc_mfu_ghost) {
42265a98e54bSBrendan Gregg - Sun Microsystems 		uint64_t delta;
42275a98e54bSBrendan Gregg - Sun Microsystems 
42282fd872a7SPrakash Surya 		mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
42293e4e8481STom Erickson 		mult = MIN(mult, 10);
4230ea8dc4b6Seschrock 
42315a98e54bSBrendan Gregg - Sun Microsystems 		delta = MIN(bytes * mult, arc_p);
42325a98e54bSBrendan Gregg - Sun Microsystems 		arc_p = MAX(arc_p_min, arc_p - delta);
4233ea8dc4b6Seschrock 	}
423444cb6abcSbmc 	ASSERT((int64_t)arc_p >= 0);
4235fa9e4066Sahrens 
4236fa9e4066Sahrens 	if (arc_reclaim_needed()) {
4237244781f1SPrakash Surya 		cv_signal(&arc_reclaim_thread_cv);
4238fa9e4066Sahrens 		return;
4239fa9e4066Sahrens 	}
4240fa9e4066Sahrens 
424144cb6abcSbmc 	if (arc_no_grow)
4242fa9e4066Sahrens 		return;
4243fa9e4066Sahrens 
424444cb6abcSbmc 	if (arc_c >= arc_c_max)
4245ea8dc4b6Seschrock 		return;
4246ea8dc4b6Seschrock 
4247fa9e4066Sahrens 	/*
4248ea8dc4b6Seschrock 	 * If we're within (2 * maxblocksize) bytes of the target
4249ea8dc4b6Seschrock 	 * cache size, increment the target cache size
4250fa9e4066Sahrens 	 */
425144cb6abcSbmc 	if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
425244cb6abcSbmc 		atomic_add_64(&arc_c, (int64_t)bytes);
425344cb6abcSbmc 		if (arc_c > arc_c_max)
425444cb6abcSbmc 			arc_c = arc_c_max;
425544cb6abcSbmc 		else if (state == arc_anon)
425644cb6abcSbmc 			atomic_add_64(&arc_p, (int64_t)bytes);
425744cb6abcSbmc 		if (arc_p > arc_c)
425844cb6abcSbmc 			arc_p = arc_c;
4259fa9e4066Sahrens 	}
426044cb6abcSbmc 	ASSERT((int64_t)arc_p >= 0);
4261fa9e4066Sahrens }
4262fa9e4066Sahrens 
4263fa9e4066Sahrens /*
4264244781f1SPrakash Surya  * Check if arc_size has grown past our upper threshold, determined by
4265244781f1SPrakash Surya  * zfs_arc_overflow_shift.
4266fa9e4066Sahrens  */
4267244781f1SPrakash Surya static boolean_t
4268244781f1SPrakash Surya arc_is_overflowing(void)
4269fa9e4066Sahrens {
4270244781f1SPrakash Surya 	/* Always allow at least one block of overflow */
4271244781f1SPrakash Surya 	uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
4272244781f1SPrakash Surya 	    arc_c >> zfs_arc_overflow_shift);
4273fa9e4066Sahrens 
4274244781f1SPrakash Surya 	return (arc_size >= arc_c + overflow);
4275fa9e4066Sahrens }
4276fa9e4066Sahrens 
4277*770499e1SDan Kimmel static abd_t *
4278*770499e1SDan Kimmel arc_get_data_abd(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4279*770499e1SDan Kimmel {
4280*770499e1SDan Kimmel 	arc_buf_contents_t type = arc_buf_type(hdr);
4281*770499e1SDan Kimmel 
4282*770499e1SDan Kimmel 	arc_get_data_impl(hdr, size, tag);
4283*770499e1SDan Kimmel 	if (type == ARC_BUFC_METADATA) {
4284*770499e1SDan Kimmel 		return (abd_alloc(size, B_TRUE));
4285*770499e1SDan Kimmel 	} else {
4286*770499e1SDan Kimmel 		ASSERT(type == ARC_BUFC_DATA);
4287*770499e1SDan Kimmel 		return (abd_alloc(size, B_FALSE));
4288*770499e1SDan Kimmel 	}
4289*770499e1SDan Kimmel }
4290*770499e1SDan Kimmel 
4291*770499e1SDan Kimmel static void *
4292*770499e1SDan Kimmel arc_get_data_buf(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4293*770499e1SDan Kimmel {
4294*770499e1SDan Kimmel 	arc_buf_contents_t type = arc_buf_type(hdr);
4295*770499e1SDan Kimmel 
4296*770499e1SDan Kimmel 	arc_get_data_impl(hdr, size, tag);
4297*770499e1SDan Kimmel 	if (type == ARC_BUFC_METADATA) {
4298*770499e1SDan Kimmel 		return (zio_buf_alloc(size));
4299*770499e1SDan Kimmel 	} else {
4300*770499e1SDan Kimmel 		ASSERT(type == ARC_BUFC_DATA);
4301*770499e1SDan Kimmel 		return (zio_data_buf_alloc(size));
4302*770499e1SDan Kimmel 	}
4303*770499e1SDan Kimmel }
4304*770499e1SDan Kimmel 
4305fa9e4066Sahrens /*
4306dcbf3bd6SGeorge Wilson  * Allocate a block and return it to the caller. If we are hitting the
4307dcbf3bd6SGeorge Wilson  * hard limit for the cache size, we must sleep, waiting for the eviction
4308dcbf3bd6SGeorge Wilson  * thread to catch up. If we're past the target size but below the hard
4309dcbf3bd6SGeorge Wilson  * limit, we'll only signal the reclaim thread and continue on.
4310fa9e4066Sahrens  */
4311*770499e1SDan Kimmel static void
4312*770499e1SDan Kimmel arc_get_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4313fa9e4066Sahrens {
4314*770499e1SDan Kimmel 	arc_state_t *state = hdr->b_l1hdr.b_state;
4315*770499e1SDan Kimmel 	arc_buf_contents_t type = arc_buf_type(hdr);
4316fa9e4066Sahrens 
431744eda4d7Smaybee 	arc_adapt(size, state);
4318fa9e4066Sahrens 
431944eda4d7Smaybee 	/*
4320244781f1SPrakash Surya 	 * If arc_size is currently overflowing, and has grown past our
4321244781f1SPrakash Surya 	 * upper limit, we must be adding data faster than the evict
4322244781f1SPrakash Surya 	 * thread can evict. Thus, to ensure we don't compound the
4323244781f1SPrakash Surya 	 * problem by adding more data and forcing arc_size to grow even
4324244781f1SPrakash Surya 	 * further past it's target size, we halt and wait for the
4325244781f1SPrakash Surya 	 * eviction thread to catch up.
4326244781f1SPrakash Surya 	 *
4327244781f1SPrakash Surya 	 * It's also possible that the reclaim thread is unable to evict
4328244781f1SPrakash Surya 	 * enough buffers to get arc_size below the overflow limit (e.g.
4329244781f1SPrakash Surya 	 * due to buffers being un-evictable, or hash lock collisions).
4330244781f1SPrakash Surya 	 * In this case, we want to proceed regardless if we're
4331244781f1SPrakash Surya 	 * overflowing; thus we don't use a while loop here.
433244eda4d7Smaybee 	 */
4333244781f1SPrakash Surya 	if (arc_is_overflowing()) {
4334244781f1SPrakash Surya 		mutex_enter(&arc_reclaim_lock);
4335244781f1SPrakash Surya 
4336244781f1SPrakash Surya 		/*
4337244781f1SPrakash Surya 		 * Now that we've acquired the lock, we may no longer be
4338244781f1SPrakash Surya 		 * over the overflow limit, lets check.
4339244781f1SPrakash Surya 		 *
4340244781f1SPrakash Surya 		 * We're ignoring the case of spurious wake ups. If that
4341244781f1SPrakash Surya 		 * were to happen, it'd let this thread consume an ARC
4342244781f1SPrakash Surya 		 * buffer before it should have (i.e. before we're under
4343244781f1SPrakash Surya 		 * the overflow limit and were signalled by the reclaim
4344244781f1SPrakash Surya 		 * thread). As long as that is a rare occurrence, it
4345244781f1SPrakash Surya 		 * shouldn't cause any harm.
4346244781f1SPrakash Surya 		 */
4347244781f1SPrakash Surya 		if (arc_is_overflowing()) {
4348244781f1SPrakash Surya 			cv_signal(&arc_reclaim_thread_cv);
4349244781f1SPrakash Surya 			cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
4350ad23a2dbSjohansen 		}
4351244781f1SPrakash Surya 
4352244781f1SPrakash Surya 		mutex_exit(&arc_reclaim_lock);
435344eda4d7Smaybee 	}
435444eda4d7Smaybee 
4355dcbf3bd6SGeorge Wilson 	VERIFY3U(hdr->b_type, ==, type);
4356244781f1SPrakash Surya 	if (type == ARC_BUFC_METADATA) {
4357244781f1SPrakash Surya 		arc_space_consume(size, ARC_SPACE_META);
4358fa9e4066Sahrens 	} else {
4359244781f1SPrakash Surya 		arc_space_consume(size, ARC_SPACE_DATA);
436044eda4d7Smaybee 	}
4361244781f1SPrakash Surya 
436244eda4d7Smaybee 	/*
436344eda4d7Smaybee 	 * Update the state size.  Note that ghost states have a
436444eda4d7Smaybee 	 * "ghost size" and so don't need to be updated.
436544eda4d7Smaybee 	 */
4366dcbf3bd6SGeorge Wilson 	if (!GHOST_STATE(state)) {
436744eda4d7Smaybee 
4368dcbf3bd6SGeorge Wilson 		(void) refcount_add_many(&state->arcs_size, size, tag);
4369244781f1SPrakash Surya 
4370244781f1SPrakash Surya 		/*
4371244781f1SPrakash Surya 		 * If this is reached via arc_read, the link is
4372244781f1SPrakash Surya 		 * protected by the hash lock. If reached via
4373244781f1SPrakash Surya 		 * arc_buf_alloc, the header should not be accessed by
4374244781f1SPrakash Surya 		 * any other thread. And, if reached via arc_read_done,
4375244781f1SPrakash Surya 		 * the hash lock will protect it if it's found in the
4376244781f1SPrakash Surya 		 * hash table; otherwise no other thread should be
4377244781f1SPrakash Surya 		 * trying to [add|remove]_reference it.
4378244781f1SPrakash Surya 		 */
4379244781f1SPrakash Surya 		if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
438089c86e32SChris Williamson 			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4381dcbf3bd6SGeorge Wilson 			(void) refcount_add_many(&state->arcs_esize[type],
4382dcbf3bd6SGeorge Wilson 			    size, tag);
4383fa9e4066Sahrens 		}
4384dcbf3bd6SGeorge Wilson 
4385641fbdaeSmaybee 		/*
4386641fbdaeSmaybee 		 * If we are growing the cache, and we are adding anonymous
438744cb6abcSbmc 		 * data, and we have outgrown arc_p, update arc_p
4388641fbdaeSmaybee 		 */
438989c86e32SChris Williamson 		if (arc_size < arc_c && hdr->b_l1hdr.b_state == arc_anon &&
43902fd872a7SPrakash Surya 		    (refcount_count(&arc_anon->arcs_size) +
43912fd872a7SPrakash Surya 		    refcount_count(&arc_mru->arcs_size) > arc_p))
439244cb6abcSbmc 			arc_p = MIN(arc_c, arc_p + size);
4393fa9e4066Sahrens 	}
4394*770499e1SDan Kimmel }
4395*770499e1SDan Kimmel 
4396*770499e1SDan Kimmel static void
4397*770499e1SDan Kimmel arc_free_data_abd(arc_buf_hdr_t *hdr, abd_t *abd, uint64_t size, void *tag)
4398*770499e1SDan Kimmel {
4399*770499e1SDan Kimmel 	arc_free_data_impl(hdr, size, tag);
4400*770499e1SDan Kimmel 	abd_free(abd);
4401*770499e1SDan Kimmel }
4402*770499e1SDan Kimmel 
4403*770499e1SDan Kimmel static void
4404*770499e1SDan Kimmel arc_free_data_buf(arc_buf_hdr_t *hdr, void *buf, uint64_t size, void *tag)
4405*770499e1SDan Kimmel {
4406*770499e1SDan Kimmel 	arc_buf_contents_t type = arc_buf_type(hdr);
4407*770499e1SDan Kimmel 
4408*770499e1SDan Kimmel 	arc_free_data_impl(hdr, size, tag);
4409*770499e1SDan Kimmel 	if (type == ARC_BUFC_METADATA) {
4410*770499e1SDan Kimmel 		zio_buf_free(buf, size);
4411*770499e1SDan Kimmel 	} else {
4412*770499e1SDan Kimmel 		ASSERT(type == ARC_BUFC_DATA);
4413*770499e1SDan Kimmel 		zio_data_buf_free(buf, size);
4414*770499e1SDan Kimmel 	}
4415dcbf3bd6SGeorge Wilson }
4416dcbf3bd6SGeorge Wilson 
4417dcbf3bd6SGeorge Wilson /*
4418dcbf3bd6SGeorge Wilson  * Free the arc data buffer.
4419dcbf3bd6SGeorge Wilson  */
4420dcbf3bd6SGeorge Wilson static void
4421*770499e1SDan Kimmel arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4422dcbf3bd6SGeorge Wilson {
4423dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
4424dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type = arc_buf_type(hdr);
4425dcbf3bd6SGeorge Wilson 
4426dcbf3bd6SGeorge Wilson 	/* protected by hash lock, if in the hash table */
4427dcbf3bd6SGeorge Wilson 	if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
4428dcbf3bd6SGeorge Wilson 		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4429dcbf3bd6SGeorge Wilson 		ASSERT(state != arc_anon && state != arc_l2c_only);
4430dcbf3bd6SGeorge Wilson 
4431dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_esize[type],
4432dcbf3bd6SGeorge Wilson 		    size, tag);
4433dcbf3bd6SGeorge Wilson 	}
4434dcbf3bd6SGeorge Wilson 	(void) refcount_remove_many(&state->arcs_size, size, tag);
4435dcbf3bd6SGeorge Wilson 
4436dcbf3bd6SGeorge Wilson 	VERIFY3U(hdr->b_type, ==, type);
4437dcbf3bd6SGeorge Wilson 	if (type == ARC_BUFC_METADATA) {
4438dcbf3bd6SGeorge Wilson 		arc_space_return(size, ARC_SPACE_META);
4439dcbf3bd6SGeorge Wilson 	} else {
4440dcbf3bd6SGeorge Wilson 		ASSERT(type == ARC_BUFC_DATA);
4441dcbf3bd6SGeorge Wilson 		arc_space_return(size, ARC_SPACE_DATA);
4442dcbf3bd6SGeorge Wilson 	}
4443fa9e4066Sahrens }
4444fa9e4066Sahrens 
4445fa9e4066Sahrens /*
4446fa9e4066Sahrens  * This routine is called whenever a buffer is accessed.
4447ea8dc4b6Seschrock  * NOTE: the hash lock is dropped in this function.
4448fa9e4066Sahrens  */
4449fa9e4066Sahrens static void
44507adb730bSGeorge Wilson arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
4451fa9e4066Sahrens {
4452d3d50737SRafael Vanoni 	clock_t now;
4453d3d50737SRafael Vanoni 
4454fa9e4066Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
445589c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
4456fa9e4066Sahrens 
445789c86e32SChris Williamson 	if (hdr->b_l1hdr.b_state == arc_anon) {
4458fa9e4066Sahrens 		/*
4459fa9e4066Sahrens 		 * This buffer is not in the cache, and does not
4460fa9e4066Sahrens 		 * appear in our "ghost" list.  Add the new buffer
4461fa9e4066Sahrens 		 * to the MRU state.
4462fa9e4066Sahrens 		 */
4463fa9e4066Sahrens 
446489c86e32SChris Williamson 		ASSERT0(hdr->b_l1hdr.b_arc_access);
446589c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
44667adb730bSGeorge Wilson 		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
44677adb730bSGeorge Wilson 		arc_change_state(arc_mru, hdr, hash_lock);
4468fa9e4066Sahrens 
446989c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mru) {
4470d3d50737SRafael Vanoni 		now = ddi_get_lbolt();
4471d3d50737SRafael Vanoni 
4472fa9e4066Sahrens 		/*
447313506d1eSmaybee 		 * If this buffer is here because of a prefetch, then either:
447413506d1eSmaybee 		 * - clear the flag if this is a "referencing" read
447513506d1eSmaybee 		 *   (any subsequent access will bump this into the MFU state).
447613506d1eSmaybee 		 * or
447713506d1eSmaybee 		 * - move the buffer to the head of the list if this is
447813506d1eSmaybee 		 *   another prefetch (to make it less likely to be evicted).
4479fa9e4066Sahrens 		 */
448089c86e32SChris Williamson 		if (HDR_PREFETCH(hdr)) {
448189c86e32SChris Williamson 			if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4482244781f1SPrakash Surya 				/* link protected by hash lock */
4483244781f1SPrakash Surya 				ASSERT(multilist_link_active(
448489c86e32SChris Williamson 				    &hdr->b_l1hdr.b_arc_node));
448513506d1eSmaybee 			} else {
4486dcbf3bd6SGeorge Wilson 				arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
448744cb6abcSbmc 				ARCSTAT_BUMP(arcstat_mru_hits);
448813506d1eSmaybee 			}
448989c86e32SChris Williamson 			hdr->b_l1hdr.b_arc_access = now;
4490fa9e4066Sahrens 			return;
4491fa9e4066Sahrens 		}
4492fa9e4066Sahrens 
4493fa9e4066Sahrens 		/*
4494fa9e4066Sahrens 		 * This buffer has been "accessed" only once so far,
4495fa9e4066Sahrens 		 * but it is still in the cache. Move it to the MFU
4496fa9e4066Sahrens 		 * state.
4497fa9e4066Sahrens 		 */
449889c86e32SChris Williamson 		if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
4499fa9e4066Sahrens 			/*
4500fa9e4066Sahrens 			 * More than 125ms have passed since we
4501fa9e4066Sahrens 			 * instantiated this buffer.  Move it to the
4502fa9e4066Sahrens 			 * most frequently used state.
4503fa9e4066Sahrens 			 */
450489c86e32SChris Williamson 			hdr->b_l1hdr.b_arc_access = now;
45057adb730bSGeorge Wilson 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
45067adb730bSGeorge Wilson 			arc_change_state(arc_mfu, hdr, hash_lock);
4507fa9e4066Sahrens 		}
450844cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mru_hits);
450989c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
4510fa9e4066Sahrens 		arc_state_t	*new_state;
4511fa9e4066Sahrens 		/*
4512fa9e4066Sahrens 		 * This buffer has been "accessed" recently, but
4513fa9e4066Sahrens 		 * was evicted from the cache.  Move it to the
4514fa9e4066Sahrens 		 * MFU state.
4515fa9e4066Sahrens 		 */
4516fa9e4066Sahrens 
451789c86e32SChris Williamson 		if (HDR_PREFETCH(hdr)) {
451844cb6abcSbmc 			new_state = arc_mru;
451989c86e32SChris Williamson 			if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0)
4520dcbf3bd6SGeorge Wilson 				arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
45217adb730bSGeorge Wilson 			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
4522fa9e4066Sahrens 		} else {
452344cb6abcSbmc 			new_state = arc_mfu;
45247adb730bSGeorge Wilson 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4525fa9e4066Sahrens 		}
4526fa9e4066Sahrens 
452789c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
45287adb730bSGeorge Wilson 		arc_change_state(new_state, hdr, hash_lock);
4529fa9e4066Sahrens 
453044cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
453189c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mfu) {
4532fa9e4066Sahrens 		/*
4533fa9e4066Sahrens 		 * This buffer has been accessed more than once and is
4534fa9e4066Sahrens 		 * still in the cache.  Keep it in the MFU state.
4535fa9e4066Sahrens 		 *
453613506d1eSmaybee 		 * NOTE: an add_reference() that occurred when we did
453713506d1eSmaybee 		 * the arc_read() will have kicked this off the list.
453813506d1eSmaybee 		 * If it was a prefetch, we will explicitly move it to
453913506d1eSmaybee 		 * the head of the list now.
4540fa9e4066Sahrens 		 */
454189c86e32SChris Williamson 		if ((HDR_PREFETCH(hdr)) != 0) {
454289c86e32SChris Williamson 			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4543244781f1SPrakash Surya 			/* link protected by hash_lock */
4544244781f1SPrakash Surya 			ASSERT(multilist_link_active(&hdr->b_l1hdr.b_arc_node));
454513506d1eSmaybee 		}
454644cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mfu_hits);
454789c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
454889c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
454944cb6abcSbmc 		arc_state_t	*new_state = arc_mfu;
4550fa9e4066Sahrens 		/*
4551fa9e4066Sahrens 		 * This buffer has been accessed more than once but has
4552fa9e4066Sahrens 		 * been evicted from the cache.  Move it back to the
4553fa9e4066Sahrens 		 * MFU state.
4554fa9e4066Sahrens 		 */
4555fa9e4066Sahrens 
455689c86e32SChris Williamson 		if (HDR_PREFETCH(hdr)) {
455713506d1eSmaybee 			/*
455813506d1eSmaybee 			 * This is a prefetch access...
455913506d1eSmaybee 			 * move this block back to the MRU state.
456013506d1eSmaybee 			 */
456189c86e32SChris Williamson 			ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
456244cb6abcSbmc 			new_state = arc_mru;
456313506d1eSmaybee 		}
456413506d1eSmaybee 
456589c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
45667adb730bSGeorge Wilson 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
45677adb730bSGeorge Wilson 		arc_change_state(new_state, hdr, hash_lock);
4568fa9e4066Sahrens 
456944cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
457089c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
4571fa94a07fSbrendan 		/*
4572fa94a07fSbrendan 		 * This buffer is on the 2nd Level ARC.
4573fa94a07fSbrendan 		 */
4574fa94a07fSbrendan 
457589c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
45767adb730bSGeorge Wilson 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
45777adb730bSGeorge Wilson 		arc_change_state(arc_mfu, hdr, hash_lock);
4578fa9e4066Sahrens 	} else {
4579fa9e4066Sahrens 		ASSERT(!"invalid arc state");
4580fa9e4066Sahrens 	}
4581fa9e4066Sahrens }
4582fa9e4066Sahrens 
4583fa9e4066Sahrens /* a generic arc_done_func_t which you can use */
4584fa9e4066Sahrens /* ARGSUSED */
4585fa9e4066Sahrens void
4586fa9e4066Sahrens arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
4587fa9e4066Sahrens {
45883f9d6ad7SLin Ling 	if (zio == NULL || zio->io_error == 0)
45895602294fSDan Kimmel 		bcopy(buf->b_data, arg, arc_buf_size(buf));
4590dcbf3bd6SGeorge Wilson 	arc_buf_destroy(buf, arg);
4591fa9e4066Sahrens }
4592fa9e4066Sahrens 
45930e8c6158Smaybee /* a generic arc_done_func_t */
4594fa9e4066Sahrens void
4595fa9e4066Sahrens arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
4596fa9e4066Sahrens {
4597fa9e4066Sahrens 	arc_buf_t **bufp = arg;
4598fa9e4066Sahrens 	if (zio && zio->io_error) {
4599dcbf3bd6SGeorge Wilson 		arc_buf_destroy(buf, arg);
4600fa9e4066Sahrens 		*bufp = NULL;
4601fa9e4066Sahrens 	} else {
4602fa9e4066Sahrens 		*bufp = buf;
46033f9d6ad7SLin Ling 		ASSERT(buf->b_data);
4604fa9e4066Sahrens 	}
4605fa9e4066Sahrens }
4606fa9e4066Sahrens 
4607dcbf3bd6SGeorge Wilson static void
4608dcbf3bd6SGeorge Wilson arc_hdr_verify(arc_buf_hdr_t *hdr, blkptr_t *bp)
4609dcbf3bd6SGeorge Wilson {
4610dcbf3bd6SGeorge Wilson 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
4611dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_PSIZE(hdr), ==, 0);
4612dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
4613dcbf3bd6SGeorge Wilson 	} else {
4614dcbf3bd6SGeorge Wilson 		if (HDR_COMPRESSION_ENABLED(hdr)) {
4615dcbf3bd6SGeorge Wilson 			ASSERT3U(HDR_GET_COMPRESS(hdr), ==,
4616dcbf3bd6SGeorge Wilson 			    BP_GET_COMPRESS(bp));
4617dcbf3bd6SGeorge Wilson 		}
4618dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
4619dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_PSIZE(hdr), ==, BP_GET_PSIZE(bp));
4620dcbf3bd6SGeorge Wilson 	}
4621dcbf3bd6SGeorge Wilson }
4622dcbf3bd6SGeorge Wilson 
4623fa9e4066Sahrens static void
4624fa9e4066Sahrens arc_read_done(zio_t *zio)
4625fa9e4066Sahrens {
4626dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t	*hdr = zio->io_private;
46275d7b4d43SMatthew Ahrens 	kmutex_t	*hash_lock = NULL;
46285602294fSDan Kimmel 	arc_callback_t	*callback_list;
46295602294fSDan Kimmel 	arc_callback_t	*acb;
46305602294fSDan Kimmel 	boolean_t	freeable = B_FALSE;
46315602294fSDan Kimmel 	boolean_t	no_zio_error = (zio->io_error == 0);
4632fa9e4066Sahrens 
4633bbf4a8dfSmaybee 	/*
4634bbf4a8dfSmaybee 	 * The hdr was inserted into hash-table and removed from lists
4635bbf4a8dfSmaybee 	 * prior to starting I/O.  We should find this header, since
4636bbf4a8dfSmaybee 	 * it's in the hash table, and it should be legit since it's
4637bbf4a8dfSmaybee 	 * not possible to evict it during the I/O.  The only possible
4638bbf4a8dfSmaybee 	 * reason for it not to be found is if we were freed during the
4639bbf4a8dfSmaybee 	 * read.
4640bbf4a8dfSmaybee 	 */
46415d7b4d43SMatthew Ahrens 	if (HDR_IN_HASH_TABLE(hdr)) {
46425d7b4d43SMatthew Ahrens 		ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
46435d7b4d43SMatthew Ahrens 		ASSERT3U(hdr->b_dva.dva_word[0], ==,
46445d7b4d43SMatthew Ahrens 		    BP_IDENTITY(zio->io_bp)->dva_word[0]);
46455d7b4d43SMatthew Ahrens 		ASSERT3U(hdr->b_dva.dva_word[1], ==,
46465d7b4d43SMatthew Ahrens 		    BP_IDENTITY(zio->io_bp)->dva_word[1]);
46475d7b4d43SMatthew Ahrens 
46485d7b4d43SMatthew Ahrens 		arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
46495d7b4d43SMatthew Ahrens 		    &hash_lock);
46505d7b4d43SMatthew Ahrens 
4651dcbf3bd6SGeorge Wilson 		ASSERT((found == hdr &&
46525d7b4d43SMatthew Ahrens 		    DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
46535d7b4d43SMatthew Ahrens 		    (found == hdr && HDR_L2_READING(hdr)));
4654dcbf3bd6SGeorge Wilson 		ASSERT3P(hash_lock, !=, NULL);
4655dcbf3bd6SGeorge Wilson 	}
4656dcbf3bd6SGeorge Wilson 
46575602294fSDan Kimmel 	if (no_zio_error) {
4658dcbf3bd6SGeorge Wilson 		/* byteswap if necessary */
4659dcbf3bd6SGeorge Wilson 		if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
4660dcbf3bd6SGeorge Wilson 			if (BP_GET_LEVEL(zio->io_bp) > 0) {
4661dcbf3bd6SGeorge Wilson 				hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
4662dcbf3bd6SGeorge Wilson 			} else {
4663dcbf3bd6SGeorge Wilson 				hdr->b_l1hdr.b_byteswap =
4664dcbf3bd6SGeorge Wilson 				    DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
4665dcbf3bd6SGeorge Wilson 			}
4666dcbf3bd6SGeorge Wilson 		} else {
4667dcbf3bd6SGeorge Wilson 			hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
4668dcbf3bd6SGeorge Wilson 		}
46695d7b4d43SMatthew Ahrens 	}
4670fa94a07fSbrendan 
4671dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_L2_EVICTED);
467289c86e32SChris Williamson 	if (l2arc_noprefetch && HDR_PREFETCH(hdr))
4673dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_L2CACHE);
4674fa9e4066Sahrens 
467589c86e32SChris Williamson 	callback_list = hdr->b_l1hdr.b_acb;
4676dcbf3bd6SGeorge Wilson 	ASSERT3P(callback_list, !=, NULL);
46776b4acc8bSahrens 
46785602294fSDan Kimmel 	if (hash_lock && no_zio_error && hdr->b_l1hdr.b_state == arc_anon) {
4679b24ab676SJeff Bonwick 		/*
4680b24ab676SJeff Bonwick 		 * Only call arc_access on anonymous buffers.  This is because
4681b24ab676SJeff Bonwick 		 * if we've issued an I/O for an evicted buffer, we've already
4682b24ab676SJeff Bonwick 		 * called arc_access (to prevent any simultaneous readers from
4683b24ab676SJeff Bonwick 		 * getting confused).
4684b24ab676SJeff Bonwick 		 */
4685b24ab676SJeff Bonwick 		arc_access(hdr, hash_lock);
4686b24ab676SJeff Bonwick 	}
4687b24ab676SJeff Bonwick 
46885602294fSDan Kimmel 	/*
46895602294fSDan Kimmel 	 * If a read request has a callback (i.e. acb_done is not NULL), then we
46905602294fSDan Kimmel 	 * make a buf containing the data according to the parameters which were
46915602294fSDan Kimmel 	 * passed in. The implementation of arc_buf_alloc_impl() ensures that we
46925602294fSDan Kimmel 	 * aren't needlessly decompressing the data multiple times.
46935602294fSDan Kimmel 	 */
46945602294fSDan Kimmel 	int callback_cnt = 0;
46955602294fSDan Kimmel 	for (acb = callback_list; acb != NULL; acb = acb->acb_next) {
46965602294fSDan Kimmel 		if (!acb->acb_done)
46975602294fSDan Kimmel 			continue;
46985602294fSDan Kimmel 
46995602294fSDan Kimmel 		/* This is a demand read since prefetches don't use callbacks */
47005602294fSDan Kimmel 		callback_cnt++;
47015602294fSDan Kimmel 
47025602294fSDan Kimmel 		int error = arc_buf_alloc_impl(hdr, acb->acb_private,
47035602294fSDan Kimmel 		    acb->acb_compressed, no_zio_error, &acb->acb_buf);
47045602294fSDan Kimmel 		if (no_zio_error) {
47055602294fSDan Kimmel 			zio->io_error = error;
4706fa9e4066Sahrens 		}
4707fa9e4066Sahrens 	}
470889c86e32SChris Williamson 	hdr->b_l1hdr.b_acb = NULL;
4709dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
47105602294fSDan Kimmel 	if (callback_cnt == 0) {
4711dcbf3bd6SGeorge Wilson 		ASSERT(HDR_PREFETCH(hdr));
4712dcbf3bd6SGeorge Wilson 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
4713*770499e1SDan Kimmel 		ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
4714b24ab676SJeff Bonwick 	}
4715fa9e4066Sahrens 
471689c86e32SChris Williamson 	ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
471789c86e32SChris Williamson 	    callback_list != NULL);
4718fa9e4066Sahrens 
47195602294fSDan Kimmel 	if (no_zio_error) {
4720dcbf3bd6SGeorge Wilson 		arc_hdr_verify(hdr, zio->io_bp);
4721dcbf3bd6SGeorge Wilson 	} else {
4722dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
472389c86e32SChris Williamson 		if (hdr->b_l1hdr.b_state != arc_anon)
472444cb6abcSbmc 			arc_change_state(arc_anon, hdr, hash_lock);
4725ea8dc4b6Seschrock 		if (HDR_IN_HASH_TABLE(hdr))
4726ea8dc4b6Seschrock 			buf_hash_remove(hdr);
472789c86e32SChris Williamson 		freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4728fa9e4066Sahrens 	}
4729fa9e4066Sahrens 
4730ea8dc4b6Seschrock 	/*
473113506d1eSmaybee 	 * Broadcast before we drop the hash_lock to avoid the possibility
473213506d1eSmaybee 	 * that the hdr (and hence the cv) might be freed before we get to
473313506d1eSmaybee 	 * the cv_broadcast().
4734ea8dc4b6Seschrock 	 */
473589c86e32SChris Williamson 	cv_broadcast(&hdr->b_l1hdr.b_cv);
4736ea8dc4b6Seschrock 
473789c86e32SChris Williamson 	if (hash_lock != NULL) {
473844eda4d7Smaybee 		mutex_exit(hash_lock);
4739fa9e4066Sahrens 	} else {
4740fa9e4066Sahrens 		/*
4741fa9e4066Sahrens 		 * This block was freed while we waited for the read to
4742fa9e4066Sahrens 		 * complete.  It has been removed from the hash table and
4743fa9e4066Sahrens 		 * moved to the anonymous state (so that it won't show up
4744fa9e4066Sahrens 		 * in the cache).
4745fa9e4066Sahrens 		 */
474689c86e32SChris Williamson 		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
474789c86e32SChris Williamson 		freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4748fa9e4066Sahrens 	}
4749fa9e4066Sahrens 
4750fa9e4066Sahrens 	/* execute each callback and free its structure */
4751fa9e4066Sahrens 	while ((acb = callback_list) != NULL) {
4752fa9e4066Sahrens 		if (acb->acb_done)
4753fa9e4066Sahrens 			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
4754fa9e4066Sahrens 
4755fa9e4066Sahrens 		if (acb->acb_zio_dummy != NULL) {
4756fa9e4066Sahrens 			acb->acb_zio_dummy->io_error = zio->io_error;
4757fa9e4066Sahrens 			zio_nowait(acb->acb_zio_dummy);
4758fa9e4066Sahrens 		}
4759fa9e4066Sahrens 
4760fa9e4066Sahrens 		callback_list = acb->acb_next;
4761fa9e4066Sahrens 		kmem_free(acb, sizeof (arc_callback_t));
4762fa9e4066Sahrens 	}
4763fa9e4066Sahrens 
4764fa9e4066Sahrens 	if (freeable)
4765ea8dc4b6Seschrock 		arc_hdr_destroy(hdr);
4766fa9e4066Sahrens }
4767fa9e4066Sahrens 
4768fa9e4066Sahrens /*
4769fc98fea5SBart Coddens  * "Read" the block at the specified DVA (in bp) via the
4770fa9e4066Sahrens  * cache.  If the block is found in the cache, invoke the provided
4771fa9e4066Sahrens  * callback immediately and return.  Note that the `zio' parameter
4772fa9e4066Sahrens  * in the callback will be NULL in this case, since no IO was
4773fa9e4066Sahrens  * required.  If the block is not in the cache pass the read request
4774fa9e4066Sahrens  * on to the spa with a substitute callback function, so that the
4775fa9e4066Sahrens  * requested block will be added to the cache.
4776fa9e4066Sahrens  *
4777fa9e4066Sahrens  * If a read request arrives for a block that has a read in-progress,
4778fa9e4066Sahrens  * either wait for the in-progress read to complete (and return the
4779fa9e4066Sahrens  * results); or, if this is a read with a "done" func, add a record
4780fa9e4066Sahrens  * to the read to invoke the "done" func when the read completes,
4781fa9e4066Sahrens  * and return; or just return.
4782fa9e4066Sahrens  *
4783fa9e4066Sahrens  * arc_read_done() will invoke all the requested "done" functions
4784fa9e4066Sahrens  * for readers of this block.
4785fa9e4066Sahrens  */
4786fa9e4066Sahrens int
47871b912ec7SGeorge Wilson arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
47887adb730bSGeorge Wilson     void *private, zio_priority_t priority, int zio_flags,
47897adb730bSGeorge Wilson     arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
4790fa9e4066Sahrens {
47915d7b4d43SMatthew Ahrens 	arc_buf_hdr_t *hdr = NULL;
47925d7b4d43SMatthew Ahrens 	kmutex_t *hash_lock = NULL;
4793fa94a07fSbrendan 	zio_t *rzio;
4794e9103aaeSGarrett D'Amore 	uint64_t guid = spa_load_guid(spa);
47955602294fSDan Kimmel 	boolean_t compressed_read = (zio_flags & ZIO_FLAG_RAW) != 0;
4796fa9e4066Sahrens 
47975d7b4d43SMatthew Ahrens 	ASSERT(!BP_IS_EMBEDDED(bp) ||
47985d7b4d43SMatthew Ahrens 	    BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
47995d7b4d43SMatthew Ahrens 
4800fa9e4066Sahrens top:
48015d7b4d43SMatthew Ahrens 	if (!BP_IS_EMBEDDED(bp)) {
48025d7b4d43SMatthew Ahrens 		/*
48035d7b4d43SMatthew Ahrens 		 * Embedded BP's have no DVA and require no I/O to "read".
48045d7b4d43SMatthew Ahrens 		 * Create an anonymous arc buf to back it.
48055d7b4d43SMatthew Ahrens 		 */
48065d7b4d43SMatthew Ahrens 		hdr = buf_hash_find(guid, bp, &hash_lock);
48075d7b4d43SMatthew Ahrens 	}
48085d7b4d43SMatthew Ahrens 
4809*770499e1SDan Kimmel 	if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_pabd != NULL) {
4810dcbf3bd6SGeorge Wilson 		arc_buf_t *buf = NULL;
48117adb730bSGeorge Wilson 		*arc_flags |= ARC_FLAG_CACHED;
481213506d1eSmaybee 
4813fa9e4066Sahrens 		if (HDR_IO_IN_PROGRESS(hdr)) {
481413506d1eSmaybee 
4815cf6106c8SMatthew Ahrens 			if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
4816cf6106c8SMatthew Ahrens 			    priority == ZIO_PRIORITY_SYNC_READ) {
4817cf6106c8SMatthew Ahrens 				/*
4818cf6106c8SMatthew Ahrens 				 * This sync read must wait for an
4819cf6106c8SMatthew Ahrens 				 * in-progress async read (e.g. a predictive
4820cf6106c8SMatthew Ahrens 				 * prefetch).  Async reads are queued
4821cf6106c8SMatthew Ahrens 				 * separately at the vdev_queue layer, so
4822cf6106c8SMatthew Ahrens 				 * this is a form of priority inversion.
4823cf6106c8SMatthew Ahrens 				 * Ideally, we would "inherit" the demand
4824cf6106c8SMatthew Ahrens 				 * i/o's priority by moving the i/o from
4825cf6106c8SMatthew Ahrens 				 * the async queue to the synchronous queue,
4826cf6106c8SMatthew Ahrens 				 * but there is currently no mechanism to do
4827cf6106c8SMatthew Ahrens 				 * so.  Track this so that we can evaluate
4828cf6106c8SMatthew Ahrens 				 * the magnitude of this potential performance
4829cf6106c8SMatthew Ahrens 				 * problem.
4830cf6106c8SMatthew Ahrens 				 *
4831cf6106c8SMatthew Ahrens 				 * Note that if the prefetch i/o is already
4832cf6106c8SMatthew Ahrens 				 * active (has been issued to the device),
4833cf6106c8SMatthew Ahrens 				 * the prefetch improved performance, because
4834cf6106c8SMatthew Ahrens 				 * we issued it sooner than we would have
4835cf6106c8SMatthew Ahrens 				 * without the prefetch.
4836cf6106c8SMatthew Ahrens 				 */
4837cf6106c8SMatthew Ahrens 				DTRACE_PROBE1(arc__sync__wait__for__async,
4838cf6106c8SMatthew Ahrens 				    arc_buf_hdr_t *, hdr);
4839cf6106c8SMatthew Ahrens 				ARCSTAT_BUMP(arcstat_sync_wait_for_async);
4840cf6106c8SMatthew Ahrens 			}
4841cf6106c8SMatthew Ahrens 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
4842dcbf3bd6SGeorge Wilson 				arc_hdr_clear_flags(hdr,
4843dcbf3bd6SGeorge Wilson 				    ARC_FLAG_PREDICTIVE_PREFETCH);
4844cf6106c8SMatthew Ahrens 			}
4845cf6106c8SMatthew Ahrens 
48467adb730bSGeorge Wilson 			if (*arc_flags & ARC_FLAG_WAIT) {
484789c86e32SChris Williamson 				cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
484813506d1eSmaybee 				mutex_exit(hash_lock);
484913506d1eSmaybee 				goto top;
485013506d1eSmaybee 			}
48517adb730bSGeorge Wilson 			ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
485213506d1eSmaybee 
485313506d1eSmaybee 			if (done) {
4854cf6106c8SMatthew Ahrens 				arc_callback_t *acb = NULL;
4855fa9e4066Sahrens 
4856fa9e4066Sahrens 				acb = kmem_zalloc(sizeof (arc_callback_t),
4857fa9e4066Sahrens 				    KM_SLEEP);
4858fa9e4066Sahrens 				acb->acb_done = done;
4859fa9e4066Sahrens 				acb->acb_private = private;
48605602294fSDan Kimmel 				acb->acb_compressed = compressed_read;
4861fa9e4066Sahrens 				if (pio != NULL)
4862fa9e4066Sahrens 					acb->acb_zio_dummy = zio_null(pio,
4863a3f829aeSBill Moore 					    spa, NULL, NULL, NULL, zio_flags);
4864fa9e4066Sahrens 
4865dcbf3bd6SGeorge Wilson 				ASSERT3P(acb->acb_done, !=, NULL);
486689c86e32SChris Williamson 				acb->acb_next = hdr->b_l1hdr.b_acb;
486789c86e32SChris Williamson 				hdr->b_l1hdr.b_acb = acb;
4868fa9e4066Sahrens 				mutex_exit(hash_lock);
4869fa9e4066Sahrens 				return (0);
4870fa9e4066Sahrens 			}
4871fa9e4066Sahrens 			mutex_exit(hash_lock);
4872fa9e4066Sahrens 			return (0);
4873fa9e4066Sahrens 		}
4874fa9e4066Sahrens 
487589c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
487689c86e32SChris Williamson 		    hdr->b_l1hdr.b_state == arc_mfu);
4877fa9e4066Sahrens 
4878ea8dc4b6Seschrock 		if (done) {
4879cf6106c8SMatthew Ahrens 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
4880cf6106c8SMatthew Ahrens 				/*
4881cf6106c8SMatthew Ahrens 				 * This is a demand read which does not have to
4882cf6106c8SMatthew Ahrens 				 * wait for i/o because we did a predictive
4883cf6106c8SMatthew Ahrens 				 * prefetch i/o for it, which has completed.
4884cf6106c8SMatthew Ahrens 				 */
4885cf6106c8SMatthew Ahrens 				DTRACE_PROBE1(
4886cf6106c8SMatthew Ahrens 				    arc__demand__hit__predictive__prefetch,
4887cf6106c8SMatthew Ahrens 				    arc_buf_hdr_t *, hdr);
4888cf6106c8SMatthew Ahrens 				ARCSTAT_BUMP(
4889cf6106c8SMatthew Ahrens 				    arcstat_demand_hit_predictive_prefetch);
4890dcbf3bd6SGeorge Wilson 				arc_hdr_clear_flags(hdr,
4891dcbf3bd6SGeorge Wilson 				    ARC_FLAG_PREDICTIVE_PREFETCH);
4892cf6106c8SMatthew Ahrens 			}
4893dcbf3bd6SGeorge Wilson 			ASSERT(!BP_IS_EMBEDDED(bp) || !BP_IS_HOLE(bp));
4894dcbf3bd6SGeorge Wilson 
48955602294fSDan Kimmel 			/* Get a buf with the desired data in it. */
48965602294fSDan Kimmel 			VERIFY0(arc_buf_alloc_impl(hdr, private,
48975602294fSDan Kimmel 			    compressed_read, B_TRUE, &buf));
48987adb730bSGeorge Wilson 		} else if (*arc_flags & ARC_FLAG_PREFETCH &&
489989c86e32SChris Williamson 		    refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4900dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
4901fa9e4066Sahrens 		}
4902fa9e4066Sahrens 		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
490344eda4d7Smaybee 		arc_access(hdr, hash_lock);
49047adb730bSGeorge Wilson 		if (*arc_flags & ARC_FLAG_L2CACHE)
4905dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
490644eda4d7Smaybee 		mutex_exit(hash_lock);
490744cb6abcSbmc 		ARCSTAT_BUMP(arcstat_hits);
490889c86e32SChris Williamson 		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
490989c86e32SChris Williamson 		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
491044cb6abcSbmc 		    data, metadata, hits);
491144cb6abcSbmc 
4912fa9e4066Sahrens 		if (done)
4913fa9e4066Sahrens 			done(NULL, buf, private);
4914fa9e4066Sahrens 	} else {
4915dcbf3bd6SGeorge Wilson 		uint64_t lsize = BP_GET_LSIZE(bp);
4916dcbf3bd6SGeorge Wilson 		uint64_t psize = BP_GET_PSIZE(bp);
49175d7b4d43SMatthew Ahrens 		arc_callback_t *acb;
49183a737e0dSbrendan 		vdev_t *vd = NULL;
4919d5285caeSGeorge Wilson 		uint64_t addr = 0;
49205a98e54bSBrendan Gregg - Sun Microsystems 		boolean_t devw = B_FALSE;
4921dcbf3bd6SGeorge Wilson 		uint64_t size;
4922fa9e4066Sahrens 
4923fa9e4066Sahrens 		if (hdr == NULL) {
4924fa9e4066Sahrens 			/* this block is not in the cache */
49255d7b4d43SMatthew Ahrens 			arc_buf_hdr_t *exists = NULL;
4926ad23a2dbSjohansen 			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
4927dcbf3bd6SGeorge Wilson 			hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
4928dcbf3bd6SGeorge Wilson 			    BP_GET_COMPRESS(bp), type);
4929dcbf3bd6SGeorge Wilson 
49305d7b4d43SMatthew Ahrens 			if (!BP_IS_EMBEDDED(bp)) {
49315d7b4d43SMatthew Ahrens 				hdr->b_dva = *BP_IDENTITY(bp);
49325d7b4d43SMatthew Ahrens 				hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
49335d7b4d43SMatthew Ahrens 				exists = buf_hash_insert(hdr, &hash_lock);
49345d7b4d43SMatthew Ahrens 			}
49355d7b4d43SMatthew Ahrens 			if (exists != NULL) {
4936fa9e4066Sahrens 				/* somebody beat us to the hash insert */
4937fa9e4066Sahrens 				mutex_exit(hash_lock);
49383f9d6ad7SLin Ling 				buf_discard_identity(hdr);
4939dcbf3bd6SGeorge Wilson 				arc_hdr_destroy(hdr);
4940fa9e4066Sahrens 				goto top; /* restart the IO request */
4941fa9e4066Sahrens 			}
4942fa9e4066Sahrens 		} else {
494389c86e32SChris Williamson 			/*
494489c86e32SChris Williamson 			 * This block is in the ghost cache. If it was L2-only
494589c86e32SChris Williamson 			 * (and thus didn't have an L1 hdr), we realloc the
494689c86e32SChris Williamson 			 * header to add an L1 hdr.
494789c86e32SChris Williamson 			 */
494889c86e32SChris Williamson 			if (!HDR_HAS_L1HDR(hdr)) {
494989c86e32SChris Williamson 				hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
495089c86e32SChris Williamson 				    hdr_full_cache);
495189c86e32SChris Williamson 			}
4952*770499e1SDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
495389c86e32SChris Williamson 			ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
4954ea8dc4b6Seschrock 			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
495589c86e32SChris Williamson 			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4956244781f1SPrakash Surya 			ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
49575602294fSDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
495813506d1eSmaybee 
4959cf6106c8SMatthew Ahrens 			/*
4960dcbf3bd6SGeorge Wilson 			 * This is a delicate dance that we play here.
4961dcbf3bd6SGeorge Wilson 			 * This hdr is in the ghost list so we access it
4962dcbf3bd6SGeorge Wilson 			 * to move it out of the ghost list before we
4963dcbf3bd6SGeorge Wilson 			 * initiate the read. If it's a prefetch then
4964dcbf3bd6SGeorge Wilson 			 * it won't have a callback so we'll remove the
4965dcbf3bd6SGeorge Wilson 			 * reference that arc_buf_alloc_impl() created. We
4966dcbf3bd6SGeorge Wilson 			 * do this after we've called arc_access() to
4967dcbf3bd6SGeorge Wilson 			 * avoid hitting an assert in remove_reference().
4968cf6106c8SMatthew Ahrens 			 */
49697e453561SWilliam Gorrell 			arc_access(hdr, hash_lock);
4970*770499e1SDan Kimmel 			arc_hdr_alloc_pabd(hdr);
4971dcbf3bd6SGeorge Wilson 		}
4972*770499e1SDan Kimmel 		ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
4973dcbf3bd6SGeorge Wilson 		size = arc_hdr_size(hdr);
4974dcbf3bd6SGeorge Wilson 
4975dcbf3bd6SGeorge Wilson 		/*
4976dcbf3bd6SGeorge Wilson 		 * If compression is enabled on the hdr, then will do
4977dcbf3bd6SGeorge Wilson 		 * RAW I/O and will store the compressed data in the hdr's
4978dcbf3bd6SGeorge Wilson 		 * data block. Otherwise, the hdr's data block will contain
4979dcbf3bd6SGeorge Wilson 		 * the uncompressed data.
4980dcbf3bd6SGeorge Wilson 		 */
4981dcbf3bd6SGeorge Wilson 		if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
4982dcbf3bd6SGeorge Wilson 			zio_flags |= ZIO_FLAG_RAW;
4983fa9e4066Sahrens 		}
4984fa9e4066Sahrens 
4985dcbf3bd6SGeorge Wilson 		if (*arc_flags & ARC_FLAG_PREFETCH)
4986dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
4987dcbf3bd6SGeorge Wilson 		if (*arc_flags & ARC_FLAG_L2CACHE)
4988dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
4989dcbf3bd6SGeorge Wilson 		if (BP_GET_LEVEL(bp) > 0)
4990dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_INDIRECT);
4991cf6106c8SMatthew Ahrens 		if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
4992dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_PREDICTIVE_PREFETCH);
499389c86e32SChris Williamson 		ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
49945614b00aSWilliam Gorrell 
4995fa9e4066Sahrens 		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
4996fa9e4066Sahrens 		acb->acb_done = done;
4997fa9e4066Sahrens 		acb->acb_private = private;
49985602294fSDan Kimmel 		acb->acb_compressed = compressed_read;
4999fa9e4066Sahrens 
5000dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
500189c86e32SChris Williamson 		hdr->b_l1hdr.b_acb = acb;
5002dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5003fa9e4066Sahrens 
500489c86e32SChris Williamson 		if (HDR_HAS_L2HDR(hdr) &&
500589c86e32SChris Williamson 		    (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
500689c86e32SChris Williamson 			devw = hdr->b_l2hdr.b_dev->l2ad_writing;
500789c86e32SChris Williamson 			addr = hdr->b_l2hdr.b_daddr;
5008e14bb325SJeff Bonwick 			/*
5009e14bb325SJeff Bonwick 			 * Lock out device removal.
5010e14bb325SJeff Bonwick 			 */
5011e14bb325SJeff Bonwick 			if (vdev_is_dead(vd) ||
5012e14bb325SJeff Bonwick 			    !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
5013e14bb325SJeff Bonwick 				vd = NULL;
50143a737e0dSbrendan 		}
50153a737e0dSbrendan 
5016dcbf3bd6SGeorge Wilson 		if (priority == ZIO_PRIORITY_ASYNC_READ)
5017dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5018dcbf3bd6SGeorge Wilson 		else
5019dcbf3bd6SGeorge Wilson 			arc_hdr_clear_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5020dcbf3bd6SGeorge Wilson 
50215d7b4d43SMatthew Ahrens 		if (hash_lock != NULL)
50225d7b4d43SMatthew Ahrens 			mutex_exit(hash_lock);
50233a737e0dSbrendan 
50243e30c24aSWill Andrews 		/*
50253e30c24aSWill Andrews 		 * At this point, we have a level 1 cache miss.  Try again in
50263e30c24aSWill Andrews 		 * L2ARC if possible.
50273e30c24aSWill Andrews 		 */
5028dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, lsize);
5029dcbf3bd6SGeorge Wilson 
50305c28183bSBrendan Gregg - Sun Microsystems 		DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
5031dcbf3bd6SGeorge Wilson 		    uint64_t, lsize, zbookmark_phys_t *, zb);
503244cb6abcSbmc 		ARCSTAT_BUMP(arcstat_misses);
503389c86e32SChris Williamson 		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
503489c86e32SChris Williamson 		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
503544cb6abcSbmc 		    data, metadata, misses);
5036ea8dc4b6Seschrock 
50375a98e54bSBrendan Gregg - Sun Microsystems 		if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
5038fa94a07fSbrendan 			/*
5039fa94a07fSbrendan 			 * Read from the L2ARC if the following are true:
50403a737e0dSbrendan 			 * 1. The L2ARC vdev was previously cached.
50413a737e0dSbrendan 			 * 2. This buffer still has L2ARC metadata.
50423a737e0dSbrendan 			 * 3. This buffer isn't currently writing to the L2ARC.
50433a737e0dSbrendan 			 * 4. The L2ARC entry wasn't evicted, which may
50443a737e0dSbrendan 			 *    also have invalidated the vdev.
50455a98e54bSBrendan Gregg - Sun Microsystems 			 * 5. This isn't prefetch and l2arc_noprefetch is set.
5046fa94a07fSbrendan 			 */
504789c86e32SChris Williamson 			if (HDR_HAS_L2HDR(hdr) &&
50485a98e54bSBrendan Gregg - Sun Microsystems 			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
50495a98e54bSBrendan Gregg - Sun Microsystems 			    !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
5050fa94a07fSbrendan 				l2arc_read_callback_t *cb;
5051fa94a07fSbrendan 
5052c5904d13Seschrock 				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
5053c5904d13Seschrock 				ARCSTAT_BUMP(arcstat_l2_hits);
5054c5904d13Seschrock 
5055fa94a07fSbrendan 				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
5056fa94a07fSbrendan 				    KM_SLEEP);
5057dcbf3bd6SGeorge Wilson 				cb->l2rcb_hdr = hdr;
5058fa94a07fSbrendan 				cb->l2rcb_bp = *bp;
5059fa94a07fSbrendan 				cb->l2rcb_zb = *zb;
50603baa08fcSek 				cb->l2rcb_flags = zio_flags;
5061fa94a07fSbrendan 
5062d5285caeSGeorge Wilson 				ASSERT(addr >= VDEV_LABEL_START_SIZE &&
5063dcbf3bd6SGeorge Wilson 				    addr + lsize < vd->vdev_psize -
5064d5285caeSGeorge Wilson 				    VDEV_LABEL_END_SIZE);
5065d5285caeSGeorge Wilson 
5066fa94a07fSbrendan 				/*
5067e14bb325SJeff Bonwick 				 * l2arc read.  The SCL_L2ARC lock will be
5068e14bb325SJeff Bonwick 				 * released by l2arc_read_done().
5069aad02571SSaso Kiselkov 				 * Issue a null zio if the underlying buffer
5070aad02571SSaso Kiselkov 				 * was squashed to zero size by compression.
5071fa94a07fSbrendan 				 */
5072dcbf3bd6SGeorge Wilson 				ASSERT3U(HDR_GET_COMPRESS(hdr), !=,
5073dcbf3bd6SGeorge Wilson 				    ZIO_COMPRESS_EMPTY);
5074dcbf3bd6SGeorge Wilson 				rzio = zio_read_phys(pio, vd, addr,
5075*770499e1SDan Kimmel 				    size, hdr->b_l1hdr.b_pabd,
5076dcbf3bd6SGeorge Wilson 				    ZIO_CHECKSUM_OFF,
5077dcbf3bd6SGeorge Wilson 				    l2arc_read_done, cb, priority,
5078dcbf3bd6SGeorge Wilson 				    zio_flags | ZIO_FLAG_DONT_CACHE |
5079dcbf3bd6SGeorge Wilson 				    ZIO_FLAG_CANFAIL |
5080dcbf3bd6SGeorge Wilson 				    ZIO_FLAG_DONT_PROPAGATE |
5081dcbf3bd6SGeorge Wilson 				    ZIO_FLAG_DONT_RETRY, B_FALSE);
5082fa94a07fSbrendan 				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
5083fa94a07fSbrendan 				    zio_t *, rzio);
5084dcbf3bd6SGeorge Wilson 				ARCSTAT_INCR(arcstat_l2_read_bytes, size);
5085fa94a07fSbrendan 
50867adb730bSGeorge Wilson 				if (*arc_flags & ARC_FLAG_NOWAIT) {
50873a737e0dSbrendan 					zio_nowait(rzio);
50883a737e0dSbrendan 					return (0);
50893a737e0dSbrendan 				}
5090fa94a07fSbrendan 
50917adb730bSGeorge Wilson 				ASSERT(*arc_flags & ARC_FLAG_WAIT);
50923a737e0dSbrendan 				if (zio_wait(rzio) == 0)
50933a737e0dSbrendan 					return (0);
50943a737e0dSbrendan 
50953a737e0dSbrendan 				/* l2arc read error; goto zio_read() */
5096fa94a07fSbrendan 			} else {
5097fa94a07fSbrendan 				DTRACE_PROBE1(l2arc__miss,
5098fa94a07fSbrendan 				    arc_buf_hdr_t *, hdr);
5099fa94a07fSbrendan 				ARCSTAT_BUMP(arcstat_l2_misses);
5100fa94a07fSbrendan 				if (HDR_L2_WRITING(hdr))
5101fa94a07fSbrendan 					ARCSTAT_BUMP(arcstat_l2_rw_clash);
5102e14bb325SJeff Bonwick 				spa_config_exit(spa, SCL_L2ARC, vd);
5103fa94a07fSbrendan 			}
51045a98e54bSBrendan Gregg - Sun Microsystems 		} else {
510576a25fafSBill Moore 			if (vd != NULL)
510676a25fafSBill Moore 				spa_config_exit(spa, SCL_L2ARC, vd);
51075a98e54bSBrendan Gregg - Sun Microsystems 			if (l2arc_ndev != 0) {
51085a98e54bSBrendan Gregg - Sun Microsystems 				DTRACE_PROBE1(l2arc__miss,
51095a98e54bSBrendan Gregg - Sun Microsystems 				    arc_buf_hdr_t *, hdr);
51105a98e54bSBrendan Gregg - Sun Microsystems 				ARCSTAT_BUMP(arcstat_l2_misses);
51115a98e54bSBrendan Gregg - Sun Microsystems 			}
5112fa94a07fSbrendan 		}
5113c5904d13Seschrock 
5114*770499e1SDan Kimmel 		rzio = zio_read(pio, spa, bp, hdr->b_l1hdr.b_pabd, size,
5115dcbf3bd6SGeorge Wilson 		    arc_read_done, hdr, priority, zio_flags, zb);
5116fa9e4066Sahrens 
51177adb730bSGeorge Wilson 		if (*arc_flags & ARC_FLAG_WAIT)
5118fa9e4066Sahrens 			return (zio_wait(rzio));
5119fa9e4066Sahrens 
51207adb730bSGeorge Wilson 		ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
5121fa9e4066Sahrens 		zio_nowait(rzio);
5122fa9e4066Sahrens 	}
5123fa9e4066Sahrens 	return (0);
5124fa9e4066Sahrens }
5125fa9e4066Sahrens 
51266e6d5868SMatthew Ahrens /*
51276e6d5868SMatthew Ahrens  * Notify the arc that a block was freed, and thus will never be used again.
51286e6d5868SMatthew Ahrens  */
51296e6d5868SMatthew Ahrens void
51306e6d5868SMatthew Ahrens arc_freed(spa_t *spa, const blkptr_t *bp)
51316e6d5868SMatthew Ahrens {
51326e6d5868SMatthew Ahrens 	arc_buf_hdr_t *hdr;
51336e6d5868SMatthew Ahrens 	kmutex_t *hash_lock;
51346e6d5868SMatthew Ahrens 	uint64_t guid = spa_load_guid(spa);
51356e6d5868SMatthew Ahrens 
51365d7b4d43SMatthew Ahrens 	ASSERT(!BP_IS_EMBEDDED(bp));
51375d7b4d43SMatthew Ahrens 
51385d7b4d43SMatthew Ahrens 	hdr = buf_hash_find(guid, bp, &hash_lock);
51396e6d5868SMatthew Ahrens 	if (hdr == NULL)
51406e6d5868SMatthew Ahrens 		return;
51416e6d5868SMatthew Ahrens 
5142dcbf3bd6SGeorge Wilson 	/*
5143dcbf3bd6SGeorge Wilson 	 * We might be trying to free a block that is still doing I/O
5144dcbf3bd6SGeorge Wilson 	 * (i.e. prefetch) or has a reference (i.e. a dedup-ed,
5145dcbf3bd6SGeorge Wilson 	 * dmu_sync-ed block). If this block is being prefetched, then it
5146dcbf3bd6SGeorge Wilson 	 * would still have the ARC_FLAG_IO_IN_PROGRESS flag set on the hdr
5147dcbf3bd6SGeorge Wilson 	 * until the I/O completes. A block may also have a reference if it is
5148dcbf3bd6SGeorge Wilson 	 * part of a dedup-ed, dmu_synced write. The dmu_sync() function would
5149dcbf3bd6SGeorge Wilson 	 * have written the new block to its final resting place on disk but
5150dcbf3bd6SGeorge Wilson 	 * without the dedup flag set. This would have left the hdr in the MRU
5151dcbf3bd6SGeorge Wilson 	 * state and discoverable. When the txg finally syncs it detects that
5152dcbf3bd6SGeorge Wilson 	 * the block was overridden in open context and issues an override I/O.
5153dcbf3bd6SGeorge Wilson 	 * Since this is a dedup block, the override I/O will determine if the
5154dcbf3bd6SGeorge Wilson 	 * block is already in the DDT. If so, then it will replace the io_bp
5155dcbf3bd6SGeorge Wilson 	 * with the bp from the DDT and allow the I/O to finish. When the I/O
5156dcbf3bd6SGeorge Wilson 	 * reaches the done callback, dbuf_write_override_done, it will
5157dcbf3bd6SGeorge Wilson 	 * check to see if the io_bp and io_bp_override are identical.
5158dcbf3bd6SGeorge Wilson 	 * If they are not, then it indicates that the bp was replaced with
5159dcbf3bd6SGeorge Wilson 	 * the bp in the DDT and the override bp is freed. This allows
5160dcbf3bd6SGeorge Wilson 	 * us to arrive here with a reference on a block that is being
5161dcbf3bd6SGeorge Wilson 	 * freed. So if we have an I/O in progress, or a reference to
5162dcbf3bd6SGeorge Wilson 	 * this hdr, then we don't destroy the hdr.
5163dcbf3bd6SGeorge Wilson 	 */
5164dcbf3bd6SGeorge Wilson 	if (!HDR_HAS_L1HDR(hdr) || (!HDR_IO_IN_PROGRESS(hdr) &&
5165dcbf3bd6SGeorge Wilson 	    refcount_is_zero(&hdr->b_l1hdr.b_refcnt))) {
5166dcbf3bd6SGeorge Wilson 		arc_change_state(arc_anon, hdr, hash_lock);
5167dcbf3bd6SGeorge Wilson 		arc_hdr_destroy(hdr);
51686e6d5868SMatthew Ahrens 		mutex_exit(hash_lock);
5169bbfa8ea8SMatthew Ahrens 	} else {
5170dcbf3bd6SGeorge Wilson 		mutex_exit(hash_lock);
5171ea8dc4b6Seschrock 	}
5172dd6ef538Smaybee 
5173ea8dc4b6Seschrock }
5174ea8dc4b6Seschrock 
5175fa9e4066Sahrens /*
51763e30c24aSWill Andrews  * Release this buffer from the cache, making it an anonymous buffer.  This
51773e30c24aSWill Andrews  * must be done after a read and prior to modifying the buffer contents.
5178fa9e4066Sahrens  * If the buffer has more than one reference, we must make
5179088f3894Sahrens  * a new hdr for the buffer.
5180fa9e4066Sahrens  */
5181fa9e4066Sahrens void
5182fa9e4066Sahrens arc_release(arc_buf_t *buf, void *tag)
5183fa9e4066Sahrens {
518489c86e32SChris Williamson 	arc_buf_hdr_t *hdr = buf->b_hdr;
5185fa9e4066Sahrens 
51863f9d6ad7SLin Ling 	/*
51873f9d6ad7SLin Ling 	 * It would be nice to assert that if it's DMU metadata (level >
51883f9d6ad7SLin Ling 	 * 0 || it's the dnode file), then it must be syncing context.
51893f9d6ad7SLin Ling 	 * But we don't know that information at this level.
51903f9d6ad7SLin Ling 	 */
51913f9d6ad7SLin Ling 
51923f9d6ad7SLin Ling 	mutex_enter(&buf->b_evict_lock);
51936f83844dSMark Maybee 
5194244781f1SPrakash Surya 	ASSERT(HDR_HAS_L1HDR(hdr));
5195244781f1SPrakash Surya 
519689c86e32SChris Williamson 	/*
519789c86e32SChris Williamson 	 * We don't grab the hash lock prior to this check, because if
519889c86e32SChris Williamson 	 * the buffer's header is in the arc_anon state, it won't be
519989c86e32SChris Williamson 	 * linked into the hash table.
520089c86e32SChris Williamson 	 */
520189c86e32SChris Williamson 	if (hdr->b_l1hdr.b_state == arc_anon) {
520289c86e32SChris Williamson 		mutex_exit(&buf->b_evict_lock);
520389c86e32SChris Williamson 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
520489c86e32SChris Williamson 		ASSERT(!HDR_IN_HASH_TABLE(hdr));
520589c86e32SChris Williamson 		ASSERT(!HDR_HAS_L2HDR(hdr));
5206dcbf3bd6SGeorge Wilson 		ASSERT(HDR_EMPTY(hdr));
5207fa9e4066Sahrens 
5208dcbf3bd6SGeorge Wilson 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
520989c86e32SChris Williamson 		ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
521089c86e32SChris Williamson 		ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
521189c86e32SChris Williamson 
521289c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = 0;
5213dcbf3bd6SGeorge Wilson 
5214dcbf3bd6SGeorge Wilson 		/*
5215dcbf3bd6SGeorge Wilson 		 * If the buf is being overridden then it may already
5216dcbf3bd6SGeorge Wilson 		 * have a hdr that is not empty.
5217dcbf3bd6SGeorge Wilson 		 */
5218dcbf3bd6SGeorge Wilson 		buf_discard_identity(hdr);
521989c86e32SChris Williamson 		arc_buf_thaw(buf);
522089c86e32SChris Williamson 
522189c86e32SChris Williamson 		return;
5222fa9e4066Sahrens 	}
5223fa9e4066Sahrens 
522489c86e32SChris Williamson 	kmutex_t *hash_lock = HDR_LOCK(hdr);
522589c86e32SChris Williamson 	mutex_enter(hash_lock);
522689c86e32SChris Williamson 
522789c86e32SChris Williamson 	/*
522889c86e32SChris Williamson 	 * This assignment is only valid as long as the hash_lock is
522989c86e32SChris Williamson 	 * held, we must be careful not to reference state or the
523089c86e32SChris Williamson 	 * b_state field after dropping the lock.
523189c86e32SChris Williamson 	 */
523289c86e32SChris Williamson 	arc_state_t *state = hdr->b_l1hdr.b_state;
523389c86e32SChris Williamson 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
523489c86e32SChris Williamson 	ASSERT3P(state, !=, arc_anon);
523589c86e32SChris Williamson 
523689c86e32SChris Williamson 	/* this buffer is not on any list */
52375602294fSDan Kimmel 	ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), >, 0);
523889c86e32SChris Williamson 
523989c86e32SChris Williamson 	if (HDR_HAS_L2HDR(hdr)) {
524089c86e32SChris Williamson 		mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
5241244781f1SPrakash Surya 
5242244781f1SPrakash Surya 		/*
5243a52fc310SPrakash Surya 		 * We have to recheck this conditional again now that
5244a52fc310SPrakash Surya 		 * we're holding the l2ad_mtx to prevent a race with
5245a52fc310SPrakash Surya 		 * another thread which might be concurrently calling
5246a52fc310SPrakash Surya 		 * l2arc_evict(). In that case, l2arc_evict() might have
5247a52fc310SPrakash Surya 		 * destroyed the header's L2 portion as we were waiting
5248a52fc310SPrakash Surya 		 * to acquire the l2ad_mtx.
5249244781f1SPrakash Surya 		 */
5250a52fc310SPrakash Surya 		if (HDR_HAS_L2HDR(hdr))
5251a52fc310SPrakash Surya 			arc_hdr_l2hdr_destroy(hdr);
5252244781f1SPrakash Surya 
525389c86e32SChris Williamson 		mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
52546f83844dSMark Maybee 	}
52556f83844dSMark Maybee 
5256ea8dc4b6Seschrock 	/*
5257ea8dc4b6Seschrock 	 * Do we have more than one buf?
5258ea8dc4b6Seschrock 	 */
5259dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_bufcnt > 1) {
5260fa9e4066Sahrens 		arc_buf_hdr_t *nhdr;
5261ac05c741SMark Maybee 		uint64_t spa = hdr->b_spa;
5262dcbf3bd6SGeorge Wilson 		uint64_t psize = HDR_GET_PSIZE(hdr);
5263dcbf3bd6SGeorge Wilson 		uint64_t lsize = HDR_GET_LSIZE(hdr);
5264dcbf3bd6SGeorge Wilson 		enum zio_compress compress = HDR_GET_COMPRESS(hdr);
526589c86e32SChris Williamson 		arc_buf_contents_t type = arc_buf_type(hdr);
5266dcbf3bd6SGeorge Wilson 		VERIFY3U(hdr->b_type, ==, type);
5267fa9e4066Sahrens 
526889c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
5269dcbf3bd6SGeorge Wilson 		(void) remove_reference(hdr, hash_lock, tag);
5270dcbf3bd6SGeorge Wilson 
52715602294fSDan Kimmel 		if (arc_buf_is_shared(buf) && !ARC_BUF_COMPRESSED(buf)) {
5272dcbf3bd6SGeorge Wilson 			ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
5273dcbf3bd6SGeorge Wilson 			ASSERT(ARC_BUF_LAST(buf));
5274dcbf3bd6SGeorge Wilson 		}
5275dcbf3bd6SGeorge Wilson 
5276fa9e4066Sahrens 		/*
52773f9d6ad7SLin Ling 		 * Pull the data off of this hdr and attach it to
5278dcbf3bd6SGeorge Wilson 		 * a new anonymous hdr. Also find the last buffer
5279dcbf3bd6SGeorge Wilson 		 * in the hdr's buffer list.
5280fa9e4066Sahrens 		 */
52815602294fSDan Kimmel 		arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
5282dcbf3bd6SGeorge Wilson 		ASSERT3P(lastbuf, !=, NULL);
5283dcbf3bd6SGeorge Wilson 
5284dcbf3bd6SGeorge Wilson 		/*
5285dcbf3bd6SGeorge Wilson 		 * If the current arc_buf_t and the hdr are sharing their data
52865602294fSDan Kimmel 		 * buffer, then we must stop sharing that block.
5287dcbf3bd6SGeorge Wilson 		 */
5288dcbf3bd6SGeorge Wilson 		if (arc_buf_is_shared(buf)) {
5289dcbf3bd6SGeorge Wilson 			VERIFY(!arc_buf_is_shared(lastbuf));
5290ea8dc4b6Seschrock 
5291dcbf3bd6SGeorge Wilson 			/*
5292dcbf3bd6SGeorge Wilson 			 * First, sever the block sharing relationship between
52935602294fSDan Kimmel 			 * buf and the arc_buf_hdr_t.
5294dcbf3bd6SGeorge Wilson 			 */
5295dcbf3bd6SGeorge Wilson 			arc_unshare_buf(hdr, buf);
52965602294fSDan Kimmel 
52975602294fSDan Kimmel 			/*
5298*770499e1SDan Kimmel 			 * Now we need to recreate the hdr's b_pabd. Since we
52995602294fSDan Kimmel 			 * have lastbuf handy, we try to share with it, but if
5300*770499e1SDan Kimmel 			 * we can't then we allocate a new b_pabd and copy the
53015602294fSDan Kimmel 			 * data from buf into it.
53025602294fSDan Kimmel 			 */
53035602294fSDan Kimmel 			if (arc_can_share(hdr, lastbuf)) {
53045602294fSDan Kimmel 				arc_share_buf(hdr, lastbuf);
53055602294fSDan Kimmel 			} else {
5306*770499e1SDan Kimmel 				arc_hdr_alloc_pabd(hdr);
5307*770499e1SDan Kimmel 				abd_copy_from_buf(hdr->b_l1hdr.b_pabd,
5308*770499e1SDan Kimmel 				    buf->b_data, psize);
53095602294fSDan Kimmel 			}
5310dcbf3bd6SGeorge Wilson 			VERIFY3P(lastbuf->b_data, !=, NULL);
5311dcbf3bd6SGeorge Wilson 		} else if (HDR_SHARED_DATA(hdr)) {
53125602294fSDan Kimmel 			/*
53135602294fSDan Kimmel 			 * Uncompressed shared buffers are always at the end
53145602294fSDan Kimmel 			 * of the list. Compressed buffers don't have the
53155602294fSDan Kimmel 			 * same requirements. This makes it hard to
53165602294fSDan Kimmel 			 * simply assert that the lastbuf is shared so
53175602294fSDan Kimmel 			 * we rely on the hdr's compression flags to determine
53185602294fSDan Kimmel 			 * if we have a compressed, shared buffer.
53195602294fSDan Kimmel 			 */
53205602294fSDan Kimmel 			ASSERT(arc_buf_is_shared(lastbuf) ||
53215602294fSDan Kimmel 			    HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
53225602294fSDan Kimmel 			ASSERT(!ARC_BUF_SHARED(buf));
5323dcbf3bd6SGeorge Wilson 		}
5324*770499e1SDan Kimmel 		ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
532589c86e32SChris Williamson 		ASSERT3P(state, !=, arc_l2c_only);
53262fd872a7SPrakash Surya 
5327dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_size,
53285602294fSDan Kimmel 		    arc_buf_size(buf), buf);
53292fd872a7SPrakash Surya 
533089c86e32SChris Williamson 		if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
533189c86e32SChris Williamson 			ASSERT3P(state, !=, arc_l2c_only);
5332dcbf3bd6SGeorge Wilson 			(void) refcount_remove_many(&state->arcs_esize[type],
53335602294fSDan Kimmel 			    arc_buf_size(buf), buf);
5334ea8dc4b6Seschrock 		}
53359253d63dSGeorge Wilson 
5336dcbf3bd6SGeorge Wilson 		hdr->b_l1hdr.b_bufcnt -= 1;
5337c717a561Smaybee 		arc_cksum_verify(buf);
5338cd1c8b85SMatthew Ahrens 		arc_buf_unwatch(buf);
5339ea8dc4b6Seschrock 
5340fa9e4066Sahrens 		mutex_exit(hash_lock);
5341fa9e4066Sahrens 
5342dcbf3bd6SGeorge Wilson 		/*
5343*770499e1SDan Kimmel 		 * Allocate a new hdr. The new hdr will contain a b_pabd
5344dcbf3bd6SGeorge Wilson 		 * buffer which will be freed in arc_write().
5345dcbf3bd6SGeorge Wilson 		 */
5346dcbf3bd6SGeorge Wilson 		nhdr = arc_hdr_alloc(spa, psize, lsize, compress, type);
5347dcbf3bd6SGeorge Wilson 		ASSERT3P(nhdr->b_l1hdr.b_buf, ==, NULL);
5348dcbf3bd6SGeorge Wilson 		ASSERT0(nhdr->b_l1hdr.b_bufcnt);
5349dcbf3bd6SGeorge Wilson 		ASSERT0(refcount_count(&nhdr->b_l1hdr.b_refcnt));
5350dcbf3bd6SGeorge Wilson 		VERIFY3U(nhdr->b_type, ==, type);
5351dcbf3bd6SGeorge Wilson 		ASSERT(!HDR_SHARED_DATA(nhdr));
535289c86e32SChris Williamson 
535389c86e32SChris Williamson 		nhdr->b_l1hdr.b_buf = buf;
5354dcbf3bd6SGeorge Wilson 		nhdr->b_l1hdr.b_bufcnt = 1;
535589c86e32SChris Williamson 		(void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
5356af2c4821Smaybee 		buf->b_hdr = nhdr;
5357dcbf3bd6SGeorge Wilson 
53583f9d6ad7SLin Ling 		mutex_exit(&buf->b_evict_lock);
5359dcbf3bd6SGeorge Wilson 		(void) refcount_add_many(&arc_anon->arcs_size,
53605602294fSDan Kimmel 		    arc_buf_size(buf), buf);
5361fa9e4066Sahrens 	} else {
53623f9d6ad7SLin Ling 		mutex_exit(&buf->b_evict_lock);
536389c86e32SChris Williamson 		ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
5364244781f1SPrakash Surya 		/* protected by hash lock, or hdr is on arc_anon */
5365244781f1SPrakash Surya 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
5366fa9e4066Sahrens 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
536789c86e32SChris Williamson 		arc_change_state(arc_anon, hdr, hash_lock);
536889c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = 0;
536989c86e32SChris Williamson 		mutex_exit(hash_lock);
5370fa94a07fSbrendan 
53713f9d6ad7SLin Ling 		buf_discard_identity(hdr);
5372c717a561Smaybee 		arc_buf_thaw(buf);
5373fa9e4066Sahrens 	}
5374fa9e4066Sahrens }
5375fa9e4066Sahrens 
5376fa9e4066Sahrens int
5377fa9e4066Sahrens arc_released(arc_buf_t *buf)
5378fa9e4066Sahrens {
53796f83844dSMark Maybee 	int released;
53806f83844dSMark Maybee 
53813f9d6ad7SLin Ling 	mutex_enter(&buf->b_evict_lock);
538289c86e32SChris Williamson 	released = (buf->b_data != NULL &&
538389c86e32SChris Williamson 	    buf->b_hdr->b_l1hdr.b_state == arc_anon);
53843f9d6ad7SLin Ling 	mutex_exit(&buf->b_evict_lock);
53856f83844dSMark Maybee 	return (released);
5386ea8dc4b6Seschrock }
5387ea8dc4b6Seschrock 
5388ea8dc4b6Seschrock #ifdef ZFS_DEBUG
5389ea8dc4b6Seschrock int
5390ea8dc4b6Seschrock arc_referenced(arc_buf_t *buf)
5391ea8dc4b6Seschrock {
53926f83844dSMark Maybee 	int referenced;
53936f83844dSMark Maybee 
53943f9d6ad7SLin Ling 	mutex_enter(&buf->b_evict_lock);
539589c86e32SChris Williamson 	referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
53963f9d6ad7SLin Ling 	mutex_exit(&buf->b_evict_lock);
53976f83844dSMark Maybee 	return (referenced);
5398ea8dc4b6Seschrock }
5399ea8dc4b6Seschrock #endif
5400ea8dc4b6Seschrock 
5401c717a561Smaybee static void
5402c717a561Smaybee arc_write_ready(zio_t *zio)
5403c717a561Smaybee {
5404c717a561Smaybee 	arc_write_callback_t *callback = zio->io_private;
5405c717a561Smaybee 	arc_buf_t *buf = callback->awcb_buf;
54060a4e9518Sgw 	arc_buf_hdr_t *hdr = buf->b_hdr;
5407dcbf3bd6SGeorge Wilson 	uint64_t psize = BP_IS_HOLE(zio->io_bp) ? 0 : BP_GET_PSIZE(zio->io_bp);
5408c717a561Smaybee 
540989c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
541089c86e32SChris Williamson 	ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
5411dcbf3bd6SGeorge Wilson 	ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
5412e14bb325SJeff Bonwick 
54130a4e9518Sgw 	/*
5414dcbf3bd6SGeorge Wilson 	 * If we're reexecuting this zio because the pool suspended, then
5415dcbf3bd6SGeorge Wilson 	 * cleanup any state that was previously set the first time the
54165602294fSDan Kimmel 	 * callback was invoked.
54170a4e9518Sgw 	 */
5418dcbf3bd6SGeorge Wilson 	if (zio->io_flags & ZIO_FLAG_REEXECUTED) {
5419dcbf3bd6SGeorge Wilson 		arc_cksum_free(hdr);
5420dcbf3bd6SGeorge Wilson 		arc_buf_unwatch(buf);
5421*770499e1SDan Kimmel 		if (hdr->b_l1hdr.b_pabd != NULL) {
5422dcbf3bd6SGeorge Wilson 			if (arc_buf_is_shared(buf)) {
5423dcbf3bd6SGeorge Wilson 				arc_unshare_buf(hdr, buf);
5424dcbf3bd6SGeorge Wilson 			} else {
5425*770499e1SDan Kimmel 				arc_hdr_free_pabd(hdr);
5426dcbf3bd6SGeorge Wilson 			}
54270a4e9518Sgw 		}
54280a4e9518Sgw 	}
5429*770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
5430dcbf3bd6SGeorge Wilson 	ASSERT(!HDR_SHARED_DATA(hdr));
5431dcbf3bd6SGeorge Wilson 	ASSERT(!arc_buf_is_shared(buf));
5432dcbf3bd6SGeorge Wilson 
5433dcbf3bd6SGeorge Wilson 	callback->awcb_ready(zio, buf, callback->awcb_private);
5434dcbf3bd6SGeorge Wilson 
5435dcbf3bd6SGeorge Wilson 	if (HDR_IO_IN_PROGRESS(hdr))
5436dcbf3bd6SGeorge Wilson 		ASSERT(zio->io_flags & ZIO_FLAG_REEXECUTED);
5437dcbf3bd6SGeorge Wilson 
5438dcbf3bd6SGeorge Wilson 	arc_cksum_compute(buf);
5439dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5440dcbf3bd6SGeorge Wilson 
5441dcbf3bd6SGeorge Wilson 	enum zio_compress compress;
5442dcbf3bd6SGeorge Wilson 	if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
5443dcbf3bd6SGeorge Wilson 		compress = ZIO_COMPRESS_OFF;
5444dcbf3bd6SGeorge Wilson 	} else {
5445dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(zio->io_bp));
5446dcbf3bd6SGeorge Wilson 		compress = BP_GET_COMPRESS(zio->io_bp);
5447dcbf3bd6SGeorge Wilson 	}
5448dcbf3bd6SGeorge Wilson 	HDR_SET_PSIZE(hdr, psize);
5449dcbf3bd6SGeorge Wilson 	arc_hdr_set_compress(hdr, compress);
5450dcbf3bd6SGeorge Wilson 
5451*770499e1SDan Kimmel 
5452dcbf3bd6SGeorge Wilson 	/*
5453*770499e1SDan Kimmel 	 * Fill the hdr with data. If the hdr is compressed, the data we want
5454*770499e1SDan Kimmel 	 * is available from the zio, otherwise we can take it from the buf.
5455*770499e1SDan Kimmel 	 *
5456*770499e1SDan Kimmel 	 * We might be able to share the buf's data with the hdr here. However,
5457*770499e1SDan Kimmel 	 * doing so would cause the ARC to be full of linear ABDs if we write a
5458*770499e1SDan Kimmel 	 * lot of shareable data. As a compromise, we check whether scattered
5459*770499e1SDan Kimmel 	 * ABDs are allowed, and assume that if they are then the user wants
5460*770499e1SDan Kimmel 	 * the ARC to be primarily filled with them regardless of the data being
5461*770499e1SDan Kimmel 	 * written. Therefore, if they're allowed then we allocate one and copy
5462*770499e1SDan Kimmel 	 * the data into it; otherwise, we share the data directly if we can.
5463dcbf3bd6SGeorge Wilson 	 */
5464*770499e1SDan Kimmel 	if (zfs_abd_scatter_enabled || !arc_can_share(hdr, buf)) {
5465*770499e1SDan Kimmel 		arc_hdr_alloc_pabd(hdr);
5466*770499e1SDan Kimmel 
5467*770499e1SDan Kimmel 		/*
5468*770499e1SDan Kimmel 		 * Ideally, we would always copy the io_abd into b_pabd, but the
5469*770499e1SDan Kimmel 		 * user may have disabled compressed ARC, thus we must check the
5470*770499e1SDan Kimmel 		 * hdr's compression setting rather than the io_bp's.
5471*770499e1SDan Kimmel 		 */
5472*770499e1SDan Kimmel 		if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
5473*770499e1SDan Kimmel 			ASSERT3U(BP_GET_COMPRESS(zio->io_bp), !=,
5474*770499e1SDan Kimmel 			    ZIO_COMPRESS_OFF);
5475*770499e1SDan Kimmel 			ASSERT3U(psize, >, 0);
5476*770499e1SDan Kimmel 
5477*770499e1SDan Kimmel 			abd_copy(hdr->b_l1hdr.b_pabd, zio->io_abd, psize);
5478*770499e1SDan Kimmel 		} else {
5479*770499e1SDan Kimmel 			ASSERT3U(zio->io_orig_size, ==, arc_hdr_size(hdr));
5480*770499e1SDan Kimmel 
5481*770499e1SDan Kimmel 			abd_copy_from_buf(hdr->b_l1hdr.b_pabd, buf->b_data,
5482*770499e1SDan Kimmel 			    arc_buf_size(buf));
5483*770499e1SDan Kimmel 		}
5484dcbf3bd6SGeorge Wilson 	} else {
5485*770499e1SDan Kimmel 		ASSERT3P(buf->b_data, ==, abd_to_buf(zio->io_orig_abd));
54865602294fSDan Kimmel 		ASSERT3U(zio->io_orig_size, ==, arc_buf_size(buf));
5487dcbf3bd6SGeorge Wilson 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
5488dcbf3bd6SGeorge Wilson 
5489dcbf3bd6SGeorge Wilson 		arc_share_buf(hdr, buf);
5490dcbf3bd6SGeorge Wilson 	}
5491*770499e1SDan Kimmel 
5492dcbf3bd6SGeorge Wilson 	arc_hdr_verify(hdr, zio->io_bp);
5493c717a561Smaybee }
5494c717a561Smaybee 
54958df0bcf0SPaul Dagnelie static void
54968df0bcf0SPaul Dagnelie arc_write_children_ready(zio_t *zio)
54978df0bcf0SPaul Dagnelie {
54988df0bcf0SPaul Dagnelie 	arc_write_callback_t *callback = zio->io_private;
54998df0bcf0SPaul Dagnelie 	arc_buf_t *buf = callback->awcb_buf;
55008df0bcf0SPaul Dagnelie 
55018df0bcf0SPaul Dagnelie 	callback->awcb_children_ready(zio, buf, callback->awcb_private);
55028df0bcf0SPaul Dagnelie }
55038df0bcf0SPaul Dagnelie 
550469962b56SMatthew Ahrens /*
550569962b56SMatthew Ahrens  * The SPA calls this callback for each physical write that happens on behalf
550669962b56SMatthew Ahrens  * of a logical write.  See the comment in dbuf_write_physdone() for details.
550769962b56SMatthew Ahrens  */
550869962b56SMatthew Ahrens static void
550969962b56SMatthew Ahrens arc_write_physdone(zio_t *zio)
551069962b56SMatthew Ahrens {
551169962b56SMatthew Ahrens 	arc_write_callback_t *cb = zio->io_private;
551269962b56SMatthew Ahrens 	if (cb->awcb_physdone != NULL)
551369962b56SMatthew Ahrens 		cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
551469962b56SMatthew Ahrens }
551569962b56SMatthew Ahrens 
5516fa9e4066Sahrens static void
5517fa9e4066Sahrens arc_write_done(zio_t *zio)
5518fa9e4066Sahrens {
5519c717a561Smaybee 	arc_write_callback_t *callback = zio->io_private;
5520c717a561Smaybee 	arc_buf_t *buf = callback->awcb_buf;
5521c717a561Smaybee 	arc_buf_hdr_t *hdr = buf->b_hdr;
5522fa9e4066Sahrens 
5523dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5524b24ab676SJeff Bonwick 
5525b24ab676SJeff Bonwick 	if (zio->io_error == 0) {
5526dcbf3bd6SGeorge Wilson 		arc_hdr_verify(hdr, zio->io_bp);
5527dcbf3bd6SGeorge Wilson 
55285d7b4d43SMatthew Ahrens 		if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
552943466aaeSMax Grossman 			buf_discard_identity(hdr);
553043466aaeSMax Grossman 		} else {
553143466aaeSMax Grossman 			hdr->b_dva = *BP_IDENTITY(zio->io_bp);
553243466aaeSMax Grossman 			hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
553343466aaeSMax Grossman 		}
5534b24ab676SJeff Bonwick 	} else {
5535dcbf3bd6SGeorge Wilson 		ASSERT(HDR_EMPTY(hdr));
5536b24ab676SJeff Bonwick 	}
5537fa9e4066Sahrens 
5538ea8dc4b6Seschrock 	/*
55395d7b4d43SMatthew Ahrens 	 * If the block to be written was all-zero or compressed enough to be
55405d7b4d43SMatthew Ahrens 	 * embedded in the BP, no write was performed so there will be no
55415d7b4d43SMatthew Ahrens 	 * dva/birth/checksum.  The buffer must therefore remain anonymous
55425d7b4d43SMatthew Ahrens 	 * (and uncached).
5543ea8dc4b6Seschrock 	 */
5544dcbf3bd6SGeorge Wilson 	if (!HDR_EMPTY(hdr)) {
5545fa9e4066Sahrens 		arc_buf_hdr_t *exists;
5546fa9e4066Sahrens 		kmutex_t *hash_lock;
5547fa9e4066Sahrens 
55485602294fSDan Kimmel 		ASSERT3U(zio->io_error, ==, 0);
5549b24ab676SJeff Bonwick 
55506b4acc8bSahrens 		arc_cksum_verify(buf);
55516b4acc8bSahrens 
5552fa9e4066Sahrens 		exists = buf_hash_insert(hdr, &hash_lock);
555389c86e32SChris Williamson 		if (exists != NULL) {
5554fa9e4066Sahrens 			/*
5555fa9e4066Sahrens 			 * This can only happen if we overwrite for
5556fa9e4066Sahrens 			 * sync-to-convergence, because we remove
5557fa9e4066Sahrens 			 * buffers from the hash table when we arc_free().
5558fa9e4066Sahrens 			 */
5559b24ab676SJeff Bonwick 			if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
5560b24ab676SJeff Bonwick 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5561b24ab676SJeff Bonwick 					panic("bad overwrite, hdr=%p exists=%p",
5562b24ab676SJeff Bonwick 					    (void *)hdr, (void *)exists);
556389c86e32SChris Williamson 				ASSERT(refcount_is_zero(
556489c86e32SChris Williamson 				    &exists->b_l1hdr.b_refcnt));
5565b24ab676SJeff Bonwick 				arc_change_state(arc_anon, exists, hash_lock);
5566b24ab676SJeff Bonwick 				mutex_exit(hash_lock);
5567b24ab676SJeff Bonwick 				arc_hdr_destroy(exists);
5568b24ab676SJeff Bonwick 				exists = buf_hash_insert(hdr, &hash_lock);
5569b24ab676SJeff Bonwick 				ASSERT3P(exists, ==, NULL);
557080901aeaSGeorge Wilson 			} else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
557180901aeaSGeorge Wilson 				/* nopwrite */
557280901aeaSGeorge Wilson 				ASSERT(zio->io_prop.zp_nopwrite);
557380901aeaSGeorge Wilson 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
557480901aeaSGeorge Wilson 					panic("bad nopwrite, hdr=%p exists=%p",
557580901aeaSGeorge Wilson 					    (void *)hdr, (void *)exists);
5576b24ab676SJeff Bonwick 			} else {
5577b24ab676SJeff Bonwick 				/* Dedup */
5578dcbf3bd6SGeorge Wilson 				ASSERT(hdr->b_l1hdr.b_bufcnt == 1);
557989c86e32SChris Williamson 				ASSERT(hdr->b_l1hdr.b_state == arc_anon);
5580b24ab676SJeff Bonwick 				ASSERT(BP_GET_DEDUP(zio->io_bp));
5581b24ab676SJeff Bonwick 				ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
5582ae46e4c7SMatthew Ahrens 			}
5583fa9e4066Sahrens 		}
5584dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5585088f3894Sahrens 		/* if it's not anon, we are doing a scrub */
558689c86e32SChris Williamson 		if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
5587088f3894Sahrens 			arc_access(hdr, hash_lock);
558844eda4d7Smaybee 		mutex_exit(hash_lock);
5589ea8dc4b6Seschrock 	} else {
5590dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5591fa9e4066Sahrens 	}
5592ea8dc4b6Seschrock 
559389c86e32SChris Williamson 	ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5594b24ab676SJeff Bonwick 	callback->awcb_done(zio, buf, callback->awcb_private);
5595fa9e4066Sahrens 
5596*770499e1SDan Kimmel 	abd_put(zio->io_abd);
5597c717a561Smaybee 	kmem_free(callback, sizeof (arc_write_callback_t));
5598fa9e4066Sahrens }
5599fa9e4066Sahrens 
5600c717a561Smaybee zio_t *
5601dcbf3bd6SGeorge Wilson arc_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
5602dcbf3bd6SGeorge Wilson     boolean_t l2arc, const zio_prop_t *zp, arc_done_func_t *ready,
56038df0bcf0SPaul Dagnelie     arc_done_func_t *children_ready, arc_done_func_t *physdone,
560469962b56SMatthew Ahrens     arc_done_func_t *done, void *private, zio_priority_t priority,
56057802d7bfSMatthew Ahrens     int zio_flags, const zbookmark_phys_t *zb)
5606fa9e4066Sahrens {
5607fa9e4066Sahrens 	arc_buf_hdr_t *hdr = buf->b_hdr;
5608c717a561Smaybee 	arc_write_callback_t *callback;
5609e14bb325SJeff Bonwick 	zio_t *zio;
5610fa9e4066Sahrens 
5611dcbf3bd6SGeorge Wilson 	ASSERT3P(ready, !=, NULL);
5612dcbf3bd6SGeorge Wilson 	ASSERT3P(done, !=, NULL);
5613fa9e4066Sahrens 	ASSERT(!HDR_IO_ERROR(hdr));
561489c86e32SChris Williamson 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5615dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5616dcbf3bd6SGeorge Wilson 	ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
56173baa08fcSek 	if (l2arc)
5618dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
56195602294fSDan Kimmel 	if (ARC_BUF_COMPRESSED(buf)) {
56205602294fSDan Kimmel 		ASSERT3U(zp->zp_compress, !=, ZIO_COMPRESS_OFF);
56215602294fSDan Kimmel 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, arc_buf_size(buf));
56225602294fSDan Kimmel 		zio_flags |= ZIO_FLAG_RAW;
56235602294fSDan Kimmel 	}
5624c717a561Smaybee 	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
5625c717a561Smaybee 	callback->awcb_ready = ready;
56268df0bcf0SPaul Dagnelie 	callback->awcb_children_ready = children_ready;
562769962b56SMatthew Ahrens 	callback->awcb_physdone = physdone;
5628c717a561Smaybee 	callback->awcb_done = done;
5629c717a561Smaybee 	callback->awcb_private = private;
5630c717a561Smaybee 	callback->awcb_buf = buf;
5631088f3894Sahrens 
5632dcbf3bd6SGeorge Wilson 	/*
5633*770499e1SDan Kimmel 	 * The hdr's b_pabd is now stale, free it now. A new data block
5634dcbf3bd6SGeorge Wilson 	 * will be allocated when the zio pipeline calls arc_write_ready().
5635dcbf3bd6SGeorge Wilson 	 */
5636*770499e1SDan Kimmel 	if (hdr->b_l1hdr.b_pabd != NULL) {
5637dcbf3bd6SGeorge Wilson 		/*
5638dcbf3bd6SGeorge Wilson 		 * If the buf is currently sharing the data block with
5639dcbf3bd6SGeorge Wilson 		 * the hdr then we need to break that relationship here.
5640dcbf3bd6SGeorge Wilson 		 * The hdr will remain with a NULL data pointer and the
5641dcbf3bd6SGeorge Wilson 		 * buf will take sole ownership of the block.
5642dcbf3bd6SGeorge Wilson 		 */
5643dcbf3bd6SGeorge Wilson 		if (arc_buf_is_shared(buf)) {
5644dcbf3bd6SGeorge Wilson 			arc_unshare_buf(hdr, buf);
5645dcbf3bd6SGeorge Wilson 		} else {
5646*770499e1SDan Kimmel 			arc_hdr_free_pabd(hdr);
5647dcbf3bd6SGeorge Wilson 		}
5648dcbf3bd6SGeorge Wilson 		VERIFY3P(buf->b_data, !=, NULL);
5649dcbf3bd6SGeorge Wilson 		arc_hdr_set_compress(hdr, ZIO_COMPRESS_OFF);
5650dcbf3bd6SGeorge Wilson 	}
5651dcbf3bd6SGeorge Wilson 	ASSERT(!arc_buf_is_shared(buf));
5652*770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
5653dcbf3bd6SGeorge Wilson 
5654*770499e1SDan Kimmel 	zio = zio_write(pio, spa, txg, bp,
5655*770499e1SDan Kimmel 	    abd_get_from_buf(buf->b_data, HDR_GET_LSIZE(hdr)),
56565602294fSDan Kimmel 	    HDR_GET_LSIZE(hdr), arc_buf_size(buf), zp, arc_write_ready,
56578df0bcf0SPaul Dagnelie 	    (children_ready != NULL) ? arc_write_children_ready : NULL,
56588df0bcf0SPaul Dagnelie 	    arc_write_physdone, arc_write_done, callback,
565969962b56SMatthew Ahrens 	    priority, zio_flags, zb);
5660fa9e4066Sahrens 
5661c717a561Smaybee 	return (zio);
5662fa9e4066Sahrens }
5663fa9e4066Sahrens 
56641ab7f2deSmaybee static int
566569962b56SMatthew Ahrens arc_memory_throttle(uint64_t reserve, uint64_t txg)
56661ab7f2deSmaybee {
56671ab7f2deSmaybee #ifdef _KERNEL
56681ab7f2deSmaybee 	uint64_t available_memory = ptob(freemem);
56691ab7f2deSmaybee 	static uint64_t page_load = 0;
56701ab7f2deSmaybee 	static uint64_t last_txg = 0;
56711ab7f2deSmaybee 
56721ab7f2deSmaybee #if defined(__i386)
56731ab7f2deSmaybee 	available_memory =
56741ab7f2deSmaybee 	    MIN(available_memory, vmem_size(heap_arena, VMEM_FREE));
56751ab7f2deSmaybee #endif
567669962b56SMatthew Ahrens 
567769962b56SMatthew Ahrens 	if (freemem > physmem * arc_lotsfree_percent / 100)
56781ab7f2deSmaybee 		return (0);
56791ab7f2deSmaybee 
56801ab7f2deSmaybee 	if (txg > last_txg) {
56811ab7f2deSmaybee 		last_txg = txg;
56821ab7f2deSmaybee 		page_load = 0;
56831ab7f2deSmaybee 	}
56841ab7f2deSmaybee 	/*
56851ab7f2deSmaybee 	 * If we are in pageout, we know that memory is already tight,
56861ab7f2deSmaybee 	 * the arc is already going to be evicting, so we just want to
56871ab7f2deSmaybee 	 * continue to let page writes occur as quickly as possible.
56881ab7f2deSmaybee 	 */
56891ab7f2deSmaybee 	if (curproc == proc_pageout) {
56901ab7f2deSmaybee 		if (page_load > MAX(ptob(minfree), available_memory) / 4)
5691be6fd75aSMatthew Ahrens 			return (SET_ERROR(ERESTART));
56921ab7f2deSmaybee 		/* Note: reserve is inflated, so we deflate */
56931ab7f2deSmaybee 		page_load += reserve / 8;
56941ab7f2deSmaybee 		return (0);
56951ab7f2deSmaybee 	} else if (page_load > 0 && arc_reclaim_needed()) {
56961ab7f2deSmaybee 		/* memory is low, delay before restarting */
56971ab7f2deSmaybee 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
5698be6fd75aSMatthew Ahrens 		return (SET_ERROR(EAGAIN));
56991ab7f2deSmaybee 	}
57001ab7f2deSmaybee 	page_load = 0;
57011ab7f2deSmaybee #endif
57021ab7f2deSmaybee 	return (0);
57031ab7f2deSmaybee }
57041ab7f2deSmaybee 
5705fa9e4066Sahrens void
57061ab7f2deSmaybee arc_tempreserve_clear(uint64_t reserve)
5707fa9e4066Sahrens {
57081ab7f2deSmaybee 	atomic_add_64(&arc_tempreserve, -reserve);
5709fa9e4066Sahrens 	ASSERT((int64_t)arc_tempreserve >= 0);
5710fa9e4066Sahrens }
5711fa9e4066Sahrens 
5712fa9e4066Sahrens int
57131ab7f2deSmaybee arc_tempreserve_space(uint64_t reserve, uint64_t txg)
5714fa9e4066Sahrens {
57151ab7f2deSmaybee 	int error;
57162fdbea25SAleksandr Guzovskiy 	uint64_t anon_size;
57171ab7f2deSmaybee 
57181ab7f2deSmaybee 	if (reserve > arc_c/4 && !arc_no_grow)
57191ab7f2deSmaybee 		arc_c = MIN(arc_c_max, reserve * 4);
57201ab7f2deSmaybee 	if (reserve > arc_c)
5721be6fd75aSMatthew Ahrens 		return (SET_ERROR(ENOMEM));
5722112fe045Smaybee 
57232fdbea25SAleksandr Guzovskiy 	/*
57242fdbea25SAleksandr Guzovskiy 	 * Don't count loaned bufs as in flight dirty data to prevent long
57252fdbea25SAleksandr Guzovskiy 	 * network delays from blocking transactions that are ready to be
57262fdbea25SAleksandr Guzovskiy 	 * assigned to a txg.
57272fdbea25SAleksandr Guzovskiy 	 */
57285602294fSDan Kimmel 
57295602294fSDan Kimmel 	/* assert that it has not wrapped around */
57305602294fSDan Kimmel 	ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
57315602294fSDan Kimmel 
57322fd872a7SPrakash Surya 	anon_size = MAX((int64_t)(refcount_count(&arc_anon->arcs_size) -
57332fd872a7SPrakash Surya 	    arc_loaned_bytes), 0);
57342fdbea25SAleksandr Guzovskiy 
57351ab7f2deSmaybee 	/*
57361ab7f2deSmaybee 	 * Writes will, almost always, require additional memory allocations
5737f7170741SWill Andrews 	 * in order to compress/encrypt/etc the data.  We therefore need to
57381ab7f2deSmaybee 	 * make sure that there is sufficient available memory for this.
57391ab7f2deSmaybee 	 */
574069962b56SMatthew Ahrens 	error = arc_memory_throttle(reserve, txg);
574169962b56SMatthew Ahrens 	if (error != 0)
57421ab7f2deSmaybee 		return (error);
57431ab7f2deSmaybee 
5744fa9e4066Sahrens 	/*
5745112fe045Smaybee 	 * Throttle writes when the amount of dirty data in the cache
5746112fe045Smaybee 	 * gets too large.  We try to keep the cache less than half full
5747112fe045Smaybee 	 * of dirty blocks so that our sync times don't grow too large.
5748112fe045Smaybee 	 * Note: if two requests come in concurrently, we might let them
5749112fe045Smaybee 	 * both succeed, when one of them should fail.  Not a huge deal.
5750fa9e4066Sahrens 	 */
57512fdbea25SAleksandr Guzovskiy 
57522fdbea25SAleksandr Guzovskiy 	if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
57532fdbea25SAleksandr Guzovskiy 	    anon_size > arc_c / 4) {
5754dcbf3bd6SGeorge Wilson 		uint64_t meta_esize =
5755dcbf3bd6SGeorge Wilson 		    refcount_count(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
5756dcbf3bd6SGeorge Wilson 		uint64_t data_esize =
5757dcbf3bd6SGeorge Wilson 		    refcount_count(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
57580e8c6158Smaybee 		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
57590e8c6158Smaybee 		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
5760dcbf3bd6SGeorge Wilson 		    arc_tempreserve >> 10, meta_esize >> 10,
5761dcbf3bd6SGeorge Wilson 		    data_esize >> 10, reserve >> 10, arc_c >> 10);
5762be6fd75aSMatthew Ahrens 		return (SET_ERROR(ERESTART));
5763fa9e4066Sahrens 	}
57641ab7f2deSmaybee 	atomic_add_64(&arc_tempreserve, reserve);
5765fa9e4066Sahrens 	return (0);
5766fa9e4066Sahrens }
5767fa9e4066Sahrens 
57684076b1bfSPrakash Surya static void
57694076b1bfSPrakash Surya arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
57704076b1bfSPrakash Surya     kstat_named_t *evict_data, kstat_named_t *evict_metadata)
57714076b1bfSPrakash Surya {
57722fd872a7SPrakash Surya 	size->value.ui64 = refcount_count(&state->arcs_size);
5773dcbf3bd6SGeorge Wilson 	evict_data->value.ui64 =
5774dcbf3bd6SGeorge Wilson 	    refcount_count(&state->arcs_esize[ARC_BUFC_DATA]);
5775dcbf3bd6SGeorge Wilson 	evict_metadata->value.ui64 =
5776dcbf3bd6SGeorge Wilson 	    refcount_count(&state->arcs_esize[ARC_BUFC_METADATA]);
57774076b1bfSPrakash Surya }
57784076b1bfSPrakash Surya 
57794076b1bfSPrakash Surya static int
57804076b1bfSPrakash Surya arc_kstat_update(kstat_t *ksp, int rw)
57814076b1bfSPrakash Surya {
57824076b1bfSPrakash Surya 	arc_stats_t *as = ksp->ks_data;
57834076b1bfSPrakash Surya 
57844076b1bfSPrakash Surya 	if (rw == KSTAT_WRITE) {
57854076b1bfSPrakash Surya 		return (EACCES);
57864076b1bfSPrakash Surya 	} else {
57874076b1bfSPrakash Surya 		arc_kstat_update_state(arc_anon,
57884076b1bfSPrakash Surya 		    &as->arcstat_anon_size,
57894076b1bfSPrakash Surya 		    &as->arcstat_anon_evictable_data,
57904076b1bfSPrakash Surya 		    &as->arcstat_anon_evictable_metadata);
57914076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mru,
57924076b1bfSPrakash Surya 		    &as->arcstat_mru_size,
57934076b1bfSPrakash Surya 		    &as->arcstat_mru_evictable_data,
57944076b1bfSPrakash Surya 		    &as->arcstat_mru_evictable_metadata);
57954076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mru_ghost,
57964076b1bfSPrakash Surya 		    &as->arcstat_mru_ghost_size,
57974076b1bfSPrakash Surya 		    &as->arcstat_mru_ghost_evictable_data,
57984076b1bfSPrakash Surya 		    &as->arcstat_mru_ghost_evictable_metadata);
57994076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mfu,
58004076b1bfSPrakash Surya 		    &as->arcstat_mfu_size,
58014076b1bfSPrakash Surya 		    &as->arcstat_mfu_evictable_data,
58024076b1bfSPrakash Surya 		    &as->arcstat_mfu_evictable_metadata);
58034076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mfu_ghost,
58044076b1bfSPrakash Surya 		    &as->arcstat_mfu_ghost_size,
58054076b1bfSPrakash Surya 		    &as->arcstat_mfu_ghost_evictable_data,
58064076b1bfSPrakash Surya 		    &as->arcstat_mfu_ghost_evictable_metadata);
58074076b1bfSPrakash Surya 	}
58084076b1bfSPrakash Surya 
58094076b1bfSPrakash Surya 	return (0);
58104076b1bfSPrakash Surya }
58114076b1bfSPrakash Surya 
5812dcbf3bd6SGeorge Wilson /*
5813dcbf3bd6SGeorge Wilson  * This function *must* return indices evenly distributed between all
5814dcbf3bd6SGeorge Wilson  * sublists of the multilist. This is needed due to how the ARC eviction
5815dcbf3bd6SGeorge Wilson  * code is laid out; arc_evict_state() assumes ARC buffers are evenly
5816dcbf3bd6SGeorge Wilson  * distributed between all sublists and uses this assumption when
5817dcbf3bd6SGeorge Wilson  * deciding which sublist to evict from and how much to evict from it.
5818dcbf3bd6SGeorge Wilson  */
5819dcbf3bd6SGeorge Wilson unsigned int
5820dcbf3bd6SGeorge Wilson arc_state_multilist_index_func(multilist_t *ml, void *obj)
5821dcbf3bd6SGeorge Wilson {
5822dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = obj;
5823dcbf3bd6SGeorge Wilson 
5824dcbf3bd6SGeorge Wilson 	/*
5825dcbf3bd6SGeorge Wilson 	 * We rely on b_dva to generate evenly distributed index
5826dcbf3bd6SGeorge Wilson 	 * numbers using buf_hash below. So, as an added precaution,
5827dcbf3bd6SGeorge Wilson 	 * let's make sure we never add empty buffers to the arc lists.
5828dcbf3bd6SGeorge Wilson 	 */
5829dcbf3bd6SGeorge Wilson 	ASSERT(!HDR_EMPTY(hdr));
5830dcbf3bd6SGeorge Wilson 
5831dcbf3bd6SGeorge Wilson 	/*
5832dcbf3bd6SGeorge Wilson 	 * The assumption here, is the hash value for a given
5833dcbf3bd6SGeorge Wilson 	 * arc_buf_hdr_t will remain constant throughout it's lifetime
5834dcbf3bd6SGeorge Wilson 	 * (i.e. it's b_spa, b_dva, and b_birth fields don't change).
5835dcbf3bd6SGeorge Wilson 	 * Thus, we don't need to store the header's sublist index
5836dcbf3bd6SGeorge Wilson 	 * on insertion, as this index can be recalculated on removal.
5837dcbf3bd6SGeorge Wilson 	 *
5838dcbf3bd6SGeorge Wilson 	 * Also, the low order bits of the hash value are thought to be
5839dcbf3bd6SGeorge Wilson 	 * distributed evenly. Otherwise, in the case that the multilist
5840dcbf3bd6SGeorge Wilson 	 * has a power of two number of sublists, each sublists' usage
5841dcbf3bd6SGeorge Wilson 	 * would not be evenly distributed.
5842dcbf3bd6SGeorge Wilson 	 */
5843dcbf3bd6SGeorge Wilson 	return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
5844dcbf3bd6SGeorge Wilson 	    multilist_get_num_sublists(ml));
5845dcbf3bd6SGeorge Wilson }
5846dcbf3bd6SGeorge Wilson 
5847dcbf3bd6SGeorge Wilson static void
5848dcbf3bd6SGeorge Wilson arc_state_init(void)
5849dcbf3bd6SGeorge Wilson {
5850dcbf3bd6SGeorge Wilson 	arc_anon = &ARC_anon;
5851dcbf3bd6SGeorge Wilson 	arc_mru = &ARC_mru;
5852dcbf3bd6SGeorge Wilson 	arc_mru_ghost = &ARC_mru_ghost;
5853dcbf3bd6SGeorge Wilson 	arc_mfu = &ARC_mfu;
5854dcbf3bd6SGeorge Wilson 	arc_mfu_ghost = &ARC_mfu_ghost;
5855dcbf3bd6SGeorge Wilson 	arc_l2c_only = &ARC_l2c_only;
5856dcbf3bd6SGeorge Wilson 
585794c2d0ebSMatthew Ahrens 	arc_mru->arcs_list[ARC_BUFC_METADATA] =
585894c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
5859dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
586010fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
586194c2d0ebSMatthew Ahrens 	arc_mru->arcs_list[ARC_BUFC_DATA] =
586294c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
5863dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
586410fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
586594c2d0ebSMatthew Ahrens 	arc_mru_ghost->arcs_list[ARC_BUFC_METADATA] =
586694c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
5867dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
586810fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
586994c2d0ebSMatthew Ahrens 	arc_mru_ghost->arcs_list[ARC_BUFC_DATA] =
587094c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
5871dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
587210fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
587394c2d0ebSMatthew Ahrens 	arc_mfu->arcs_list[ARC_BUFC_METADATA] =
587494c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
5875dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
587610fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
587794c2d0ebSMatthew Ahrens 	arc_mfu->arcs_list[ARC_BUFC_DATA] =
587894c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
5879dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
588010fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
588194c2d0ebSMatthew Ahrens 	arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA] =
588294c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
5883dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
588410fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
588594c2d0ebSMatthew Ahrens 	arc_mfu_ghost->arcs_list[ARC_BUFC_DATA] =
588694c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
5887dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
588810fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
588994c2d0ebSMatthew Ahrens 	arc_l2c_only->arcs_list[ARC_BUFC_METADATA] =
589094c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
5891dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
589210fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
589394c2d0ebSMatthew Ahrens 	arc_l2c_only->arcs_list[ARC_BUFC_DATA] =
589494c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
5895dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
589610fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
5897dcbf3bd6SGeorge Wilson 
5898dcbf3bd6SGeorge Wilson 	refcount_create(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
5899dcbf3bd6SGeorge Wilson 	refcount_create(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
5900dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
5901dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
5902dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
5903dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
5904dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
5905dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
5906dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
5907dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
5908dcbf3bd6SGeorge Wilson 	refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
5909dcbf3bd6SGeorge Wilson 	refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
5910dcbf3bd6SGeorge Wilson 
5911dcbf3bd6SGeorge Wilson 	refcount_create(&arc_anon->arcs_size);
5912dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru->arcs_size);
5913dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru_ghost->arcs_size);
5914dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu->arcs_size);
5915dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu_ghost->arcs_size);
5916dcbf3bd6SGeorge Wilson 	refcount_create(&arc_l2c_only->arcs_size);
5917dcbf3bd6SGeorge Wilson }
5918dcbf3bd6SGeorge Wilson 
5919dcbf3bd6SGeorge Wilson static void
5920dcbf3bd6SGeorge Wilson arc_state_fini(void)
5921dcbf3bd6SGeorge Wilson {
5922dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
5923dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
5924dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
5925dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
5926dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
5927dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
5928dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
5929dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
5930dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
5931dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
5932dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
5933dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
5934dcbf3bd6SGeorge Wilson 
5935dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_anon->arcs_size);
5936dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru->arcs_size);
5937dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru_ghost->arcs_size);
5938dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu->arcs_size);
5939dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu_ghost->arcs_size);
5940dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_l2c_only->arcs_size);
5941dcbf3bd6SGeorge Wilson 
594294c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_METADATA]);
594394c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
594494c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_METADATA]);
594594c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
594694c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_DATA]);
594794c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
594894c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_DATA]);
594994c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
5950dcbf3bd6SGeorge Wilson }
5951dcbf3bd6SGeorge Wilson 
5952dcbf3bd6SGeorge Wilson uint64_t
5953dcbf3bd6SGeorge Wilson arc_max_bytes(void)
5954244781f1SPrakash Surya {
5955dcbf3bd6SGeorge Wilson 	return (arc_c_max);
5956244781f1SPrakash Surya }
5957244781f1SPrakash Surya 
5958fa9e4066Sahrens void
5959fa9e4066Sahrens arc_init(void)
5960fa9e4066Sahrens {
59612ec99e3eSMatthew Ahrens 	/*
59622ec99e3eSMatthew Ahrens 	 * allmem is "all memory that we could possibly use".
59632ec99e3eSMatthew Ahrens 	 */
59642ec99e3eSMatthew Ahrens #ifdef _KERNEL
59652ec99e3eSMatthew Ahrens 	uint64_t allmem = ptob(physmem - swapfs_minfree);
59662ec99e3eSMatthew Ahrens #else
59672ec99e3eSMatthew Ahrens 	uint64_t allmem = (physmem * PAGESIZE) / 2;
59682ec99e3eSMatthew Ahrens #endif
59692ec99e3eSMatthew Ahrens 
5970244781f1SPrakash Surya 	mutex_init(&arc_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
5971244781f1SPrakash Surya 	cv_init(&arc_reclaim_thread_cv, NULL, CV_DEFAULT, NULL);
5972244781f1SPrakash Surya 	cv_init(&arc_reclaim_waiters_cv, NULL, CV_DEFAULT, NULL);
5973244781f1SPrakash Surya 
597413506d1eSmaybee 	/* Convert seconds to clock ticks */
5975b19a79ecSperrin 	arc_min_prefetch_lifespan = 1 * hz;
597613506d1eSmaybee 
5977112fe045Smaybee 	/* set min cache to 1/32 of all memory, or 64MB, whichever is more */
59782ec99e3eSMatthew Ahrens 	arc_c_min = MAX(allmem / 32, 64 << 20);
5979112fe045Smaybee 	/* set max to 3/4 of all memory, or all but 1GB, whichever is more */
59802ec99e3eSMatthew Ahrens 	if (allmem >= 1 << 30)
59812ec99e3eSMatthew Ahrens 		arc_c_max = allmem - (1 << 30);
5982fa9e4066Sahrens 	else
598344cb6abcSbmc 		arc_c_max = arc_c_min;
59842ec99e3eSMatthew Ahrens 	arc_c_max = MAX(allmem * 3 / 4, arc_c_max);
5985a2eea2e1Sahrens 
59868fe00bfbSMatthew Ahrens 	/*
59878fe00bfbSMatthew Ahrens 	 * In userland, there's only the memory pressure that we artificially
59888fe00bfbSMatthew Ahrens 	 * create (see arc_available_memory()).  Don't let arc_c get too
59898fe00bfbSMatthew Ahrens 	 * small, because it can cause transactions to be larger than
59908fe00bfbSMatthew Ahrens 	 * arc_c, causing arc_tempreserve_space() to fail.
59918fe00bfbSMatthew Ahrens 	 */
59928fe00bfbSMatthew Ahrens #ifndef _KERNEL
59938fe00bfbSMatthew Ahrens 	arc_c_min = arc_c_max / 2;
59948fe00bfbSMatthew Ahrens #endif
59958fe00bfbSMatthew Ahrens 
5996a2eea2e1Sahrens 	/*
5997a2eea2e1Sahrens 	 * Allow the tunables to override our calculations if they are
5998a2eea2e1Sahrens 	 * reasonable (ie. over 64MB)
5999a2eea2e1Sahrens 	 */
6000e5961710SMatthew Ahrens 	if (zfs_arc_max > 64 << 20 && zfs_arc_max < allmem) {
600144cb6abcSbmc 		arc_c_max = zfs_arc_max;
6002e5961710SMatthew Ahrens 		arc_c_min = MIN(arc_c_min, arc_c_max);
6003e5961710SMatthew Ahrens 	}
60042ec99e3eSMatthew Ahrens 	if (zfs_arc_min > 64 << 20 && zfs_arc_min <= arc_c_max)
600544cb6abcSbmc 		arc_c_min = zfs_arc_min;
6006a2eea2e1Sahrens 
600744cb6abcSbmc 	arc_c = arc_c_max;
600844cb6abcSbmc 	arc_p = (arc_c >> 1);
6009dcbf3bd6SGeorge Wilson 	arc_size = 0;
6010fa9e4066Sahrens 
60110e8c6158Smaybee 	/* limit meta-data to 1/4 of the arc capacity */
60120e8c6158Smaybee 	arc_meta_limit = arc_c_max / 4;
60131116048bSek 
6014af868f46SMatthew Ahrens #ifdef _KERNEL
6015af868f46SMatthew Ahrens 	/*
6016af868f46SMatthew Ahrens 	 * Metadata is stored in the kernel's heap.  Don't let us
6017af868f46SMatthew Ahrens 	 * use more than half the heap for the ARC.
6018af868f46SMatthew Ahrens 	 */
6019af868f46SMatthew Ahrens 	arc_meta_limit = MIN(arc_meta_limit,
6020af868f46SMatthew Ahrens 	    vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 2);
6021af868f46SMatthew Ahrens #endif
6022af868f46SMatthew Ahrens 
60231116048bSek 	/* Allow the tunable to override if it is reasonable */
60241116048bSek 	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
60251116048bSek 		arc_meta_limit = zfs_arc_meta_limit;
60261116048bSek 
60270e8c6158Smaybee 	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
60280e8c6158Smaybee 		arc_c_min = arc_meta_limit / 2;
60290e8c6158Smaybee 
60303a5286a1SMatthew Ahrens 	if (zfs_arc_meta_min > 0) {
60313a5286a1SMatthew Ahrens 		arc_meta_min = zfs_arc_meta_min;
60323a5286a1SMatthew Ahrens 	} else {
60333a5286a1SMatthew Ahrens 		arc_meta_min = arc_c_min / 2;
60343a5286a1SMatthew Ahrens 	}
60353a5286a1SMatthew Ahrens 
60365a98e54bSBrendan Gregg - Sun Microsystems 	if (zfs_arc_grow_retry > 0)
60375a98e54bSBrendan Gregg - Sun Microsystems 		arc_grow_retry = zfs_arc_grow_retry;
60385a98e54bSBrendan Gregg - Sun Microsystems 
60395a98e54bSBrendan Gregg - Sun Microsystems 	if (zfs_arc_shrink_shift > 0)
60405a98e54bSBrendan Gregg - Sun Microsystems 		arc_shrink_shift = zfs_arc_shrink_shift;
60415a98e54bSBrendan Gregg - Sun Microsystems 
60422ec99e3eSMatthew Ahrens 	/*
60432ec99e3eSMatthew Ahrens 	 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
60442ec99e3eSMatthew Ahrens 	 */
60452ec99e3eSMatthew Ahrens 	if (arc_no_grow_shift >= arc_shrink_shift)
60462ec99e3eSMatthew Ahrens 		arc_no_grow_shift = arc_shrink_shift - 1;
60472ec99e3eSMatthew Ahrens 
60485a98e54bSBrendan Gregg - Sun Microsystems 	if (zfs_arc_p_min_shift > 0)
60495a98e54bSBrendan Gregg - Sun Microsystems 		arc_p_min_shift = zfs_arc_p_min_shift;
60505a98e54bSBrendan Gregg - Sun Microsystems 
6051fa9e4066Sahrens 	/* if kmem_flags are set, lets try to use less memory */
6052fa9e4066Sahrens 	if (kmem_debugging())
605344cb6abcSbmc 		arc_c = arc_c / 2;
605444cb6abcSbmc 	if (arc_c < arc_c_min)
605544cb6abcSbmc 		arc_c = arc_c_min;
605644cb6abcSbmc 
6057dcbf3bd6SGeorge Wilson 	arc_state_init();
6058fa9e4066Sahrens 	buf_init();
6059fa9e4066Sahrens 
6060dcbf3bd6SGeorge Wilson 	arc_reclaim_thread_exit = B_FALSE;
6061fa9e4066Sahrens 
606244cb6abcSbmc 	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
606344cb6abcSbmc 	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
606444cb6abcSbmc 
606544cb6abcSbmc 	if (arc_ksp != NULL) {
606644cb6abcSbmc 		arc_ksp->ks_data = &arc_stats;
60674076b1bfSPrakash Surya 		arc_ksp->ks_update = arc_kstat_update;
606844cb6abcSbmc 		kstat_install(arc_ksp);
606944cb6abcSbmc 	}
607044cb6abcSbmc 
6071fa9e4066Sahrens 	(void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
6072fa9e4066Sahrens 	    TS_RUN, minclsyspri);
607349e3519aSmaybee 
6074dcbf3bd6SGeorge Wilson 	arc_dead = B_FALSE;
60753a737e0dSbrendan 	arc_warm = B_FALSE;
60761ab7f2deSmaybee 
607769962b56SMatthew Ahrens 	/*
607869962b56SMatthew Ahrens 	 * Calculate maximum amount of dirty data per pool.
607969962b56SMatthew Ahrens 	 *
608069962b56SMatthew Ahrens 	 * If it has been set by /etc/system, take that.
608169962b56SMatthew Ahrens 	 * Otherwise, use a percentage of physical memory defined by
608269962b56SMatthew Ahrens 	 * zfs_dirty_data_max_percent (default 10%) with a cap at
608369962b56SMatthew Ahrens 	 * zfs_dirty_data_max_max (default 4GB).
608469962b56SMatthew Ahrens 	 */
608569962b56SMatthew Ahrens 	if (zfs_dirty_data_max == 0) {
608669962b56SMatthew Ahrens 		zfs_dirty_data_max = physmem * PAGESIZE *
608769962b56SMatthew Ahrens 		    zfs_dirty_data_max_percent / 100;
608869962b56SMatthew Ahrens 		zfs_dirty_data_max = MIN(zfs_dirty_data_max,
608969962b56SMatthew Ahrens 		    zfs_dirty_data_max_max);
609069962b56SMatthew Ahrens 	}
6091fa9e4066Sahrens }
6092fa9e4066Sahrens 
6093fa9e4066Sahrens void
6094fa9e4066Sahrens arc_fini(void)
6095fa9e4066Sahrens {
6096244781f1SPrakash Surya 	mutex_enter(&arc_reclaim_lock);
6097dcbf3bd6SGeorge Wilson 	arc_reclaim_thread_exit = B_TRUE;
6098244781f1SPrakash Surya 	/*
6099244781f1SPrakash Surya 	 * The reclaim thread will set arc_reclaim_thread_exit back to
6100dcbf3bd6SGeorge Wilson 	 * B_FALSE when it is finished exiting; we're waiting for that.
6101244781f1SPrakash Surya 	 */
6102244781f1SPrakash Surya 	while (arc_reclaim_thread_exit) {
6103244781f1SPrakash Surya 		cv_signal(&arc_reclaim_thread_cv);
6104244781f1SPrakash Surya 		cv_wait(&arc_reclaim_thread_cv, &arc_reclaim_lock);
6105244781f1SPrakash Surya 	}
6106244781f1SPrakash Surya 	mutex_exit(&arc_reclaim_lock);
6107fa9e4066Sahrens 
6108dcbf3bd6SGeorge Wilson 	/* Use B_TRUE to ensure *all* buffers are evicted */
6109dcbf3bd6SGeorge Wilson 	arc_flush(NULL, B_TRUE);
6110fa9e4066Sahrens 
6111dcbf3bd6SGeorge Wilson 	arc_dead = B_TRUE;
6112fa9e4066Sahrens 
611344cb6abcSbmc 	if (arc_ksp != NULL) {
611444cb6abcSbmc 		kstat_delete(arc_ksp);
611544cb6abcSbmc 		arc_ksp = NULL;
611644cb6abcSbmc 	}
611744cb6abcSbmc 
6118244781f1SPrakash Surya 	mutex_destroy(&arc_reclaim_lock);
6119244781f1SPrakash Surya 	cv_destroy(&arc_reclaim_thread_cv);
6120244781f1SPrakash Surya 	cv_destroy(&arc_reclaim_waiters_cv);
6121244781f1SPrakash Surya 
6122dcbf3bd6SGeorge Wilson 	arc_state_fini();
6123fa9e4066Sahrens 	buf_fini();
61242fdbea25SAleksandr Guzovskiy 
612589c86e32SChris Williamson 	ASSERT0(arc_loaned_bytes);
6126fa9e4066Sahrens }
6127fa94a07fSbrendan 
6128fa94a07fSbrendan /*
6129fa94a07fSbrendan  * Level 2 ARC
6130fa94a07fSbrendan  *
6131fa94a07fSbrendan  * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
6132fa94a07fSbrendan  * It uses dedicated storage devices to hold cached data, which are populated
6133fa94a07fSbrendan  * using large infrequent writes.  The main role of this cache is to boost
6134fa94a07fSbrendan  * the performance of random read workloads.  The intended L2ARC devices
6135fa94a07fSbrendan  * include short-stroked disks, solid state disks, and other media with
6136fa94a07fSbrendan  * substantially faster read latency than disk.
6137fa94a07fSbrendan  *
6138fa94a07fSbrendan  *                 +-----------------------+
6139fa94a07fSbrendan  *                 |         ARC           |
6140fa94a07fSbrendan  *                 +-----------------------+
6141fa94a07fSbrendan  *                    |         ^     ^
6142fa94a07fSbrendan  *                    |         |     |
6143fa94a07fSbrendan  *      l2arc_feed_thread()    arc_read()
6144fa94a07fSbrendan  *                    |         |     |
6145fa94a07fSbrendan  *                    |  l2arc read   |
6146fa94a07fSbrendan  *                    V         |     |
6147fa94a07fSbrendan  *               +---------------+    |
6148fa94a07fSbrendan  *               |     L2ARC     |    |
6149fa94a07fSbrendan  *               +---------------+    |
6150fa94a07fSbrendan  *                   |    ^           |
6151fa94a07fSbrendan  *          l2arc_write() |           |
6152fa94a07fSbrendan  *                   |    |           |
6153fa94a07fSbrendan  *                   V    |           |
6154fa94a07fSbrendan  *                 +-------+      +-------+
6155fa94a07fSbrendan  *                 | vdev  |      | vdev  |
6156fa94a07fSbrendan  *                 | cache |      | cache |
6157fa94a07fSbrendan  *                 +-------+      +-------+
6158fa94a07fSbrendan  *                 +=========+     .-----.
6159fa94a07fSbrendan  *                 :  L2ARC  :    |-_____-|
6160fa94a07fSbrendan  *                 : devices :    | Disks |
6161fa94a07fSbrendan  *                 +=========+    `-_____-'
6162fa94a07fSbrendan  *
6163fa94a07fSbrendan  * Read requests are satisfied from the following sources, in order:
6164fa94a07fSbrendan  *
6165fa94a07fSbrendan  *	1) ARC
6166fa94a07fSbrendan  *	2) vdev cache of L2ARC devices
6167fa94a07fSbrendan  *	3) L2ARC devices
6168fa94a07fSbrendan  *	4) vdev cache of disks
6169fa94a07fSbrendan  *	5) disks
6170fa94a07fSbrendan  *
6171fa94a07fSbrendan  * Some L2ARC device types exhibit extremely slow write performance.
6172fa94a07fSbrendan  * To accommodate for this there are some significant differences between
6173fa94a07fSbrendan  * the L2ARC and traditional cache design:
6174fa94a07fSbrendan  *
6175fa94a07fSbrendan  * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
6176fa94a07fSbrendan  * the ARC behave as usual, freeing buffers and placing headers on ghost
6177fa94a07fSbrendan  * lists.  The ARC does not send buffers to the L2ARC during eviction as
6178fa94a07fSbrendan  * this would add inflated write latencies for all ARC memory pressure.
6179fa94a07fSbrendan  *
6180fa94a07fSbrendan  * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
6181fa94a07fSbrendan  * It does this by periodically scanning buffers from the eviction-end of
6182fa94a07fSbrendan  * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
6183aad02571SSaso Kiselkov  * not already there. It scans until a headroom of buffers is satisfied,
6184aad02571SSaso Kiselkov  * which itself is a buffer for ARC eviction. If a compressible buffer is
6185aad02571SSaso Kiselkov  * found during scanning and selected for writing to an L2ARC device, we
6186aad02571SSaso Kiselkov  * temporarily boost scanning headroom during the next scan cycle to make
6187aad02571SSaso Kiselkov  * sure we adapt to compression effects (which might significantly reduce
6188aad02571SSaso Kiselkov  * the data volume we write to L2ARC). The thread that does this is
6189fa94a07fSbrendan  * l2arc_feed_thread(), illustrated below; example sizes are included to
6190fa94a07fSbrendan  * provide a better sense of ratio than this diagram:
6191fa94a07fSbrendan  *
6192fa94a07fSbrendan  *	       head -->                        tail
6193fa94a07fSbrendan  *	        +---------------------+----------+
6194fa94a07fSbrendan  *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
6195fa94a07fSbrendan  *	        +---------------------+----------+   |   o L2ARC eligible
6196fa94a07fSbrendan  *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
6197fa94a07fSbrendan  *	        +---------------------+----------+   |
6198fa94a07fSbrendan  *	             15.9 Gbytes      ^ 32 Mbytes    |
6199fa94a07fSbrendan  *	                           headroom          |
6200fa94a07fSbrendan  *	                                      l2arc_feed_thread()
6201fa94a07fSbrendan  *	                                             |
6202fa94a07fSbrendan  *	                 l2arc write hand <--[oooo]--'
6203fa94a07fSbrendan  *	                         |           8 Mbyte
6204fa94a07fSbrendan  *	                         |          write max
6205fa94a07fSbrendan  *	                         V
6206fa94a07fSbrendan  *		  +==============================+
6207fa94a07fSbrendan  *	L2ARC dev |####|#|###|###|    |####| ... |
6208fa94a07fSbrendan  *	          +==============================+
6209fa94a07fSbrendan  *	                     32 Gbytes
6210fa94a07fSbrendan  *
6211fa94a07fSbrendan  * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
6212fa94a07fSbrendan  * evicted, then the L2ARC has cached a buffer much sooner than it probably
6213fa94a07fSbrendan  * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
6214fa94a07fSbrendan  * safe to say that this is an uncommon case, since buffers at the end of
6215fa94a07fSbrendan  * the ARC lists have moved there due to inactivity.
6216fa94a07fSbrendan  *
6217fa94a07fSbrendan  * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
6218fa94a07fSbrendan  * then the L2ARC simply misses copying some buffers.  This serves as a
6219fa94a07fSbrendan  * pressure valve to prevent heavy read workloads from both stalling the ARC
6220fa94a07fSbrendan  * with waits and clogging the L2ARC with writes.  This also helps prevent
6221fa94a07fSbrendan  * the potential for the L2ARC to churn if it attempts to cache content too
6222fa94a07fSbrendan  * quickly, such as during backups of the entire pool.
6223fa94a07fSbrendan  *
62243a737e0dSbrendan  * 5. After system boot and before the ARC has filled main memory, there are
62253a737e0dSbrendan  * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
62263a737e0dSbrendan  * lists can remain mostly static.  Instead of searching from tail of these
62273a737e0dSbrendan  * lists as pictured, the l2arc_feed_thread() will search from the list heads
62283a737e0dSbrendan  * for eligible buffers, greatly increasing its chance of finding them.
62293a737e0dSbrendan  *
62303a737e0dSbrendan  * The L2ARC device write speed is also boosted during this time so that
62313a737e0dSbrendan  * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
62323a737e0dSbrendan  * there are no L2ARC reads, and no fear of degrading read performance
62333a737e0dSbrendan  * through increased writes.
62343a737e0dSbrendan  *
62353a737e0dSbrendan  * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
6236fa94a07fSbrendan  * the vdev queue can aggregate them into larger and fewer writes.  Each
6237fa94a07fSbrendan  * device is written to in a rotor fashion, sweeping writes through
6238fa94a07fSbrendan  * available space then repeating.
6239fa94a07fSbrendan  *
62403a737e0dSbrendan  * 7. The L2ARC does not store dirty content.  It never needs to flush
6241fa94a07fSbrendan  * write buffers back to disk based storage.
6242fa94a07fSbrendan  *
62433a737e0dSbrendan  * 8. If an ARC buffer is written (and dirtied) which also exists in the
6244fa94a07fSbrendan  * L2ARC, the now stale L2ARC buffer is immediately dropped.
6245fa94a07fSbrendan  *
6246fa94a07fSbrendan  * The performance of the L2ARC can be tweaked by a number of tunables, which
6247fa94a07fSbrendan  * may be necessary for different workloads:
6248fa94a07fSbrendan  *
6249fa94a07fSbrendan  *	l2arc_write_max		max write bytes per interval
62503a737e0dSbrendan  *	l2arc_write_boost	extra write bytes during device warmup
6251fa94a07fSbrendan  *	l2arc_noprefetch	skip caching prefetched buffers
6252fa94a07fSbrendan  *	l2arc_headroom		number of max device writes to precache
6253aad02571SSaso Kiselkov  *	l2arc_headroom_boost	when we find compressed buffers during ARC
6254aad02571SSaso Kiselkov  *				scanning, we multiply headroom by this
6255aad02571SSaso Kiselkov  *				percentage factor for the next scan cycle,
6256aad02571SSaso Kiselkov  *				since more compressed buffers are likely to
6257aad02571SSaso Kiselkov  *				be present
6258fa94a07fSbrendan  *	l2arc_feed_secs		seconds between L2ARC writing
6259fa94a07fSbrendan  *
6260fa94a07fSbrendan  * Tunables may be removed or added as future performance improvements are
6261fa94a07fSbrendan  * integrated, and also may become zpool properties.
62625a98e54bSBrendan Gregg - Sun Microsystems  *
62635a98e54bSBrendan Gregg - Sun Microsystems  * There are three key functions that control how the L2ARC warms up:
62645a98e54bSBrendan Gregg - Sun Microsystems  *
62655a98e54bSBrendan Gregg - Sun Microsystems  *	l2arc_write_eligible()	check if a buffer is eligible to cache
62665a98e54bSBrendan Gregg - Sun Microsystems  *	l2arc_write_size()	calculate how much to write
62675a98e54bSBrendan Gregg - Sun Microsystems  *	l2arc_write_interval()	calculate sleep delay between writes
62685a98e54bSBrendan Gregg - Sun Microsystems  *
62695a98e54bSBrendan Gregg - Sun Microsystems  * These three functions determine what to write, how much, and how quickly
62705a98e54bSBrendan Gregg - Sun Microsystems  * to send writes.
6271fa94a07fSbrendan  */
6272fa94a07fSbrendan 
62735a98e54bSBrendan Gregg - Sun Microsystems static boolean_t
62747adb730bSGeorge Wilson l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
62755a98e54bSBrendan Gregg - Sun Microsystems {
62765a98e54bSBrendan Gregg - Sun Microsystems 	/*
62775a98e54bSBrendan Gregg - Sun Microsystems 	 * A buffer is *not* eligible for the L2ARC if it:
62785a98e54bSBrendan Gregg - Sun Microsystems 	 * 1. belongs to a different spa.
62795ea40c06SBrendan Gregg - Sun Microsystems 	 * 2. is already cached on the L2ARC.
62805ea40c06SBrendan Gregg - Sun Microsystems 	 * 3. has an I/O in progress (it may be an incomplete read).
62815ea40c06SBrendan Gregg - Sun Microsystems 	 * 4. is flagged not eligible (zfs property).
62825a98e54bSBrendan Gregg - Sun Microsystems 	 */
628389c86e32SChris Williamson 	if (hdr->b_spa != spa_guid || HDR_HAS_L2HDR(hdr) ||
62847adb730bSGeorge Wilson 	    HDR_IO_IN_PROGRESS(hdr) || !HDR_L2CACHE(hdr))
62855a98e54bSBrendan Gregg - Sun Microsystems 		return (B_FALSE);
62865a98e54bSBrendan Gregg - Sun Microsystems 
62875a98e54bSBrendan Gregg - Sun Microsystems 	return (B_TRUE);
62885a98e54bSBrendan Gregg - Sun Microsystems }
62895a98e54bSBrendan Gregg - Sun Microsystems 
62905a98e54bSBrendan Gregg - Sun Microsystems static uint64_t
6291aad02571SSaso Kiselkov l2arc_write_size(void)
62925a98e54bSBrendan Gregg - Sun Microsystems {
62935a98e54bSBrendan Gregg - Sun Microsystems 	uint64_t size;
62945a98e54bSBrendan Gregg - Sun Microsystems 
6295aad02571SSaso Kiselkov 	/*
6296aad02571SSaso Kiselkov 	 * Make sure our globals have meaningful values in case the user
6297aad02571SSaso Kiselkov 	 * altered them.
6298aad02571SSaso Kiselkov 	 */
6299aad02571SSaso Kiselkov 	size = l2arc_write_max;
6300aad02571SSaso Kiselkov 	if (size == 0) {
6301aad02571SSaso Kiselkov 		cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
6302aad02571SSaso Kiselkov 		    "be greater than zero, resetting it to the default (%d)",
6303aad02571SSaso Kiselkov 		    L2ARC_WRITE_SIZE);
6304aad02571SSaso Kiselkov 		size = l2arc_write_max = L2ARC_WRITE_SIZE;
6305aad02571SSaso Kiselkov 	}
63065a98e54bSBrendan Gregg - Sun Microsystems 
63075a98e54bSBrendan Gregg - Sun Microsystems 	if (arc_warm == B_FALSE)
6308aad02571SSaso Kiselkov 		size += l2arc_write_boost;
63095a98e54bSBrendan Gregg - Sun Microsystems 
63105a98e54bSBrendan Gregg - Sun Microsystems 	return (size);
63115a98e54bSBrendan Gregg - Sun Microsystems 
63125a98e54bSBrendan Gregg - Sun Microsystems }
63135a98e54bSBrendan Gregg - Sun Microsystems 
63145a98e54bSBrendan Gregg - Sun Microsystems static clock_t
63155a98e54bSBrendan Gregg - Sun Microsystems l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
63165a98e54bSBrendan Gregg - Sun Microsystems {
6317d3d50737SRafael Vanoni 	clock_t interval, next, now;
63185a98e54bSBrendan Gregg - Sun Microsystems 
63195a98e54bSBrendan Gregg - Sun Microsystems 	/*
63205a98e54bSBrendan Gregg - Sun Microsystems 	 * If the ARC lists are busy, increase our write rate; if the
63215a98e54bSBrendan Gregg - Sun Microsystems 	 * lists are stale, idle back.  This is achieved by checking
63225a98e54bSBrendan Gregg - Sun Microsystems 	 * how much we previously wrote - if it was more than half of
63235a98e54bSBrendan Gregg - Sun Microsystems 	 * what we wanted, schedule the next write much sooner.
63245a98e54bSBrendan Gregg - Sun Microsystems 	 */
63255a98e54bSBrendan Gregg - Sun Microsystems 	if (l2arc_feed_again && wrote > (wanted / 2))
63265a98e54bSBrendan Gregg - Sun Microsystems 		interval = (hz * l2arc_feed_min_ms) / 1000;
63275a98e54bSBrendan Gregg - Sun Microsystems 	else
63285a98e54bSBrendan Gregg - Sun Microsystems 		interval = hz * l2arc_feed_secs;
63295a98e54bSBrendan Gregg - Sun Microsystems 
6330d3d50737SRafael Vanoni 	now = ddi_get_lbolt();
6331d3d50737SRafael Vanoni 	next = MAX(now, MIN(now + interval, began + interval));
63325a98e54bSBrendan Gregg - Sun Microsystems 
63335a98e54bSBrendan Gregg - Sun Microsystems 	return (next);
63345a98e54bSBrendan Gregg - Sun Microsystems }
63355a98e54bSBrendan Gregg - Sun Microsystems 
6336fa94a07fSbrendan /*
6337fa94a07fSbrendan  * Cycle through L2ARC devices.  This is how L2ARC load balances.
63383a737e0dSbrendan  * If a device is returned, this also returns holding the spa config lock.
6339fa94a07fSbrendan  */
6340fa94a07fSbrendan static l2arc_dev_t *
6341fa94a07fSbrendan l2arc_dev_get_next(void)
6342fa94a07fSbrendan {
63433a737e0dSbrendan 	l2arc_dev_t *first, *next = NULL;
63443a737e0dSbrendan 
63453a737e0dSbrendan 	/*
63463a737e0dSbrendan 	 * Lock out the removal of spas (spa_namespace_lock), then removal
63473a737e0dSbrendan 	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
63483a737e0dSbrendan 	 * both locks will be dropped and a spa config lock held instead.
63493a737e0dSbrendan 	 */
63503a737e0dSbrendan 	mutex_enter(&spa_namespace_lock);
63513a737e0dSbrendan 	mutex_enter(&l2arc_dev_mtx);
6352fa94a07fSbrendan 
6353c5904d13Seschrock 	/* if there are no vdevs, there is nothing to do */
6354c5904d13Seschrock 	if (l2arc_ndev == 0)
63553a737e0dSbrendan 		goto out;
6356c5904d13Seschrock 
6357c5904d13Seschrock 	first = NULL;
6358c5904d13Seschrock 	next = l2arc_dev_last;
6359c5904d13Seschrock 	do {
6360c5904d13Seschrock 		/* loop around the list looking for a non-faulted vdev */
6361c5904d13Seschrock 		if (next == NULL) {
6362fa94a07fSbrendan 			next = list_head(l2arc_dev_list);
6363c5904d13Seschrock 		} else {
6364c5904d13Seschrock 			next = list_next(l2arc_dev_list, next);
6365c5904d13Seschrock 			if (next == NULL)
6366c5904d13Seschrock 				next = list_head(l2arc_dev_list);
6367c5904d13Seschrock 		}
6368c5904d13Seschrock 
6369c5904d13Seschrock 		/* if we have come back to the start, bail out */
6370c5904d13Seschrock 		if (first == NULL)
6371c5904d13Seschrock 			first = next;
6372c5904d13Seschrock 		else if (next == first)
6373c5904d13Seschrock 			break;
6374c5904d13Seschrock 
6375c5904d13Seschrock 	} while (vdev_is_dead(next->l2ad_vdev));
6376c5904d13Seschrock 
6377c5904d13Seschrock 	/* if we were unable to find any usable vdevs, return NULL */
6378c5904d13Seschrock 	if (vdev_is_dead(next->l2ad_vdev))
63793a737e0dSbrendan 		next = NULL;
6380fa94a07fSbrendan 
6381fa94a07fSbrendan 	l2arc_dev_last = next;
6382fa94a07fSbrendan 
63833a737e0dSbrendan out:
63843a737e0dSbrendan 	mutex_exit(&l2arc_dev_mtx);
63853a737e0dSbrendan 
63863a737e0dSbrendan 	/*
63873a737e0dSbrendan 	 * Grab the config lock to prevent the 'next' device from being
63883a737e0dSbrendan 	 * removed while we are writing to it.
63893a737e0dSbrendan 	 */
63903a737e0dSbrendan 	if (next != NULL)
6391e14bb325SJeff Bonwick 		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
63923a737e0dSbrendan 	mutex_exit(&spa_namespace_lock);
63933a737e0dSbrendan 
6394fa94a07fSbrendan 	return (next);
6395fa94a07fSbrendan }
6396fa94a07fSbrendan 
63973a737e0dSbrendan /*
63983a737e0dSbrendan  * Free buffers that were tagged for destruction.
63993a737e0dSbrendan  */
64003a737e0dSbrendan static void
64013a737e0dSbrendan l2arc_do_free_on_write()
64023a737e0dSbrendan {
64033a737e0dSbrendan 	list_t *buflist;
64043a737e0dSbrendan 	l2arc_data_free_t *df, *df_prev;
64053a737e0dSbrendan 
64063a737e0dSbrendan 	mutex_enter(&l2arc_free_on_write_mtx);
64073a737e0dSbrendan 	buflist = l2arc_free_on_write;
64083a737e0dSbrendan 
64093a737e0dSbrendan 	for (df = list_tail(buflist); df; df = df_prev) {
64103a737e0dSbrendan 		df_prev = list_prev(buflist, df);
6411*770499e1SDan Kimmel 		ASSERT3P(df->l2df_abd, !=, NULL);
6412*770499e1SDan Kimmel 		abd_free(df->l2df_abd);
64133a737e0dSbrendan 		list_remove(buflist, df);
64143a737e0dSbrendan 		kmem_free(df, sizeof (l2arc_data_free_t));
64153a737e0dSbrendan 	}
64163a737e0dSbrendan 
64173a737e0dSbrendan 	mutex_exit(&l2arc_free_on_write_mtx);
64183a737e0dSbrendan }
64193a737e0dSbrendan 
6420fa94a07fSbrendan /*
6421fa94a07fSbrendan  * A write to a cache device has completed.  Update all headers to allow
6422fa94a07fSbrendan  * reads from these buffers to begin.
6423fa94a07fSbrendan  */
6424fa94a07fSbrendan static void
6425fa94a07fSbrendan l2arc_write_done(zio_t *zio)
6426fa94a07fSbrendan {
6427fa94a07fSbrendan 	l2arc_write_callback_t *cb;
6428fa94a07fSbrendan 	l2arc_dev_t *dev;
6429fa94a07fSbrendan 	list_t *buflist;
64307adb730bSGeorge Wilson 	arc_buf_hdr_t *head, *hdr, *hdr_prev;
6431fa94a07fSbrendan 	kmutex_t *hash_lock;
64323038a2b4SSaso Kiselkov 	int64_t bytes_dropped = 0;
6433fa94a07fSbrendan 
6434fa94a07fSbrendan 	cb = zio->io_private;
6435dcbf3bd6SGeorge Wilson 	ASSERT3P(cb, !=, NULL);
6436fa94a07fSbrendan 	dev = cb->l2wcb_dev;
6437dcbf3bd6SGeorge Wilson 	ASSERT3P(dev, !=, NULL);
6438fa94a07fSbrendan 	head = cb->l2wcb_head;
6439dcbf3bd6SGeorge Wilson 	ASSERT3P(head, !=, NULL);
644089c86e32SChris Williamson 	buflist = &dev->l2ad_buflist;
6441dcbf3bd6SGeorge Wilson 	ASSERT3P(buflist, !=, NULL);
6442fa94a07fSbrendan 	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
6443fa94a07fSbrendan 	    l2arc_write_callback_t *, cb);
6444fa94a07fSbrendan 
6445fa94a07fSbrendan 	if (zio->io_error != 0)
6446fa94a07fSbrendan 		ARCSTAT_BUMP(arcstat_l2_writes_error);
6447fa94a07fSbrendan 
6448fa94a07fSbrendan 	/*
6449fa94a07fSbrendan 	 * All writes completed, or an error was hit.
6450fa94a07fSbrendan 	 */
6451244781f1SPrakash Surya top:
6452244781f1SPrakash Surya 	mutex_enter(&dev->l2ad_mtx);
64537adb730bSGeorge Wilson 	for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
64547adb730bSGeorge Wilson 		hdr_prev = list_prev(buflist, hdr);
6455fa94a07fSbrendan 
64567adb730bSGeorge Wilson 		hash_lock = HDR_LOCK(hdr);
6457244781f1SPrakash Surya 
6458244781f1SPrakash Surya 		/*
6459244781f1SPrakash Surya 		 * We cannot use mutex_enter or else we can deadlock
6460244781f1SPrakash Surya 		 * with l2arc_write_buffers (due to swapping the order
6461244781f1SPrakash Surya 		 * the hash lock and l2ad_mtx are taken).
6462244781f1SPrakash Surya 		 */
6463fa94a07fSbrendan 		if (!mutex_tryenter(hash_lock)) {
6464fa94a07fSbrendan 			/*
6465244781f1SPrakash Surya 			 * Missed the hash lock. We must retry so we
6466244781f1SPrakash Surya 			 * don't leave the ARC_FLAG_L2_WRITING bit set.
6467fa94a07fSbrendan 			 */
6468244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
6469244781f1SPrakash Surya 
6470244781f1SPrakash Surya 			/*
6471244781f1SPrakash Surya 			 * We don't want to rescan the headers we've
6472244781f1SPrakash Surya 			 * already marked as having been written out, so
6473244781f1SPrakash Surya 			 * we reinsert the head node so we can pick up
6474244781f1SPrakash Surya 			 * where we left off.
6475244781f1SPrakash Surya 			 */
6476244781f1SPrakash Surya 			list_remove(buflist, head);
6477244781f1SPrakash Surya 			list_insert_after(buflist, hdr, head);
6478244781f1SPrakash Surya 
6479244781f1SPrakash Surya 			mutex_exit(&dev->l2ad_mtx);
6480244781f1SPrakash Surya 
6481244781f1SPrakash Surya 			/*
6482244781f1SPrakash Surya 			 * We wait for the hash lock to become available
6483244781f1SPrakash Surya 			 * to try and prevent busy waiting, and increase
6484244781f1SPrakash Surya 			 * the chance we'll be able to acquire the lock
6485244781f1SPrakash Surya 			 * the next time around.
6486244781f1SPrakash Surya 			 */
6487244781f1SPrakash Surya 			mutex_enter(hash_lock);
6488244781f1SPrakash Surya 			mutex_exit(hash_lock);
6489244781f1SPrakash Surya 			goto top;
6490fa94a07fSbrendan 		}
6491fa94a07fSbrendan 
649289c86e32SChris Williamson 		/*
6493244781f1SPrakash Surya 		 * We could not have been moved into the arc_l2c_only
6494244781f1SPrakash Surya 		 * state while in-flight due to our ARC_FLAG_L2_WRITING
6495244781f1SPrakash Surya 		 * bit being set. Let's just ensure that's being enforced.
6496244781f1SPrakash Surya 		 */
6497244781f1SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(hdr));
6498244781f1SPrakash Surya 
6499fa94a07fSbrendan 		if (zio->io_error != 0) {
6500fa94a07fSbrendan 			/*
65013a737e0dSbrendan 			 * Error - drop L2ARC entry.
6502fa94a07fSbrendan 			 */
65037adb730bSGeorge Wilson 			list_remove(buflist, hdr);
6504dcbf3bd6SGeorge Wilson 			arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
650589c86e32SChris Williamson 
6506dcbf3bd6SGeorge Wilson 			ARCSTAT_INCR(arcstat_l2_asize, -arc_hdr_size(hdr));
6507dcbf3bd6SGeorge Wilson 			ARCSTAT_INCR(arcstat_l2_size, -HDR_GET_LSIZE(hdr));
6508a52fc310SPrakash Surya 
6509dcbf3bd6SGeorge Wilson 			bytes_dropped += arc_hdr_size(hdr);
6510a52fc310SPrakash Surya 			(void) refcount_remove_many(&dev->l2ad_alloc,
6511dcbf3bd6SGeorge Wilson 			    arc_hdr_size(hdr), hdr);
6512fa94a07fSbrendan 		}
6513fa94a07fSbrendan 
6514fa94a07fSbrendan 		/*
6515244781f1SPrakash Surya 		 * Allow ARC to begin reads and ghost list evictions to
6516244781f1SPrakash Surya 		 * this L2ARC entry.
6517fa94a07fSbrendan 		 */
6518dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_L2_WRITING);
6519fa94a07fSbrendan 
6520fa94a07fSbrendan 		mutex_exit(hash_lock);
6521fa94a07fSbrendan 	}
6522fa94a07fSbrendan 
6523fa94a07fSbrendan 	atomic_inc_64(&l2arc_writes_done);
6524fa94a07fSbrendan 	list_remove(buflist, head);
652589c86e32SChris Williamson 	ASSERT(!HDR_HAS_L1HDR(head));
652689c86e32SChris Williamson 	kmem_cache_free(hdr_l2only_cache, head);
652789c86e32SChris Williamson 	mutex_exit(&dev->l2ad_mtx);
6528fa94a07fSbrendan 
65293038a2b4SSaso Kiselkov 	vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
65303038a2b4SSaso Kiselkov 
65313a737e0dSbrendan 	l2arc_do_free_on_write();
6532fa94a07fSbrendan 
6533fa94a07fSbrendan 	kmem_free(cb, sizeof (l2arc_write_callback_t));
6534fa94a07fSbrendan }
6535fa94a07fSbrendan 
6536fa94a07fSbrendan /*
6537fa94a07fSbrendan  * A read to a cache device completed.  Validate buffer contents before
6538fa94a07fSbrendan  * handing over to the regular ARC routines.
6539fa94a07fSbrendan  */
6540fa94a07fSbrendan static void
6541fa94a07fSbrendan l2arc_read_done(zio_t *zio)
6542fa94a07fSbrendan {
6543fa94a07fSbrendan 	l2arc_read_callback_t *cb;
6544fa94a07fSbrendan 	arc_buf_hdr_t *hdr;
6545fa94a07fSbrendan 	kmutex_t *hash_lock;
6546dcbf3bd6SGeorge Wilson 	boolean_t valid_cksum;
6547fa94a07fSbrendan 
6548dcbf3bd6SGeorge Wilson 	ASSERT3P(zio->io_vd, !=, NULL);
6549e14bb325SJeff Bonwick 	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
6550e14bb325SJeff Bonwick 
6551e14bb325SJeff Bonwick 	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
6552e14bb325SJeff Bonwick 
6553fa94a07fSbrendan 	cb = zio->io_private;
6554dcbf3bd6SGeorge Wilson 	ASSERT3P(cb, !=, NULL);
6555dcbf3bd6SGeorge Wilson 	hdr = cb->l2rcb_hdr;
6556dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr, !=, NULL);
6557fa94a07fSbrendan 
6558dcbf3bd6SGeorge Wilson 	hash_lock = HDR_LOCK(hdr);
6559fa94a07fSbrendan 	mutex_enter(hash_lock);
65603f9d6ad7SLin Ling 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
6561fa94a07fSbrendan 
6562*770499e1SDan Kimmel 	ASSERT3P(zio->io_abd, !=, NULL);
6563aad02571SSaso Kiselkov 
6564fa94a07fSbrendan 	/*
6565fa94a07fSbrendan 	 * Check this survived the L2ARC journey.
6566fa94a07fSbrendan 	 */
6567*770499e1SDan Kimmel 	ASSERT3P(zio->io_abd, ==, hdr->b_l1hdr.b_pabd);
6568dcbf3bd6SGeorge Wilson 	zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
6569dcbf3bd6SGeorge Wilson 	zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
6570dcbf3bd6SGeorge Wilson 
6571dcbf3bd6SGeorge Wilson 	valid_cksum = arc_cksum_is_equal(hdr, zio);
6572dcbf3bd6SGeorge Wilson 	if (valid_cksum && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
6573fa94a07fSbrendan 		mutex_exit(hash_lock);
6574dcbf3bd6SGeorge Wilson 		zio->io_private = hdr;
6575fa94a07fSbrendan 		arc_read_done(zio);
6576fa94a07fSbrendan 	} else {
6577fa94a07fSbrendan 		mutex_exit(hash_lock);
6578fa94a07fSbrendan 		/*
6579fa94a07fSbrendan 		 * Buffer didn't survive caching.  Increment stats and
6580fa94a07fSbrendan 		 * reissue to the original storage device.
6581fa94a07fSbrendan 		 */
65823a737e0dSbrendan 		if (zio->io_error != 0) {
6583fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_io_error);
65843a737e0dSbrendan 		} else {
6585be6fd75aSMatthew Ahrens 			zio->io_error = SET_ERROR(EIO);
65863a737e0dSbrendan 		}
6587dcbf3bd6SGeorge Wilson 		if (!valid_cksum)
6588fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
6589fa94a07fSbrendan 
6590e14bb325SJeff Bonwick 		/*
6591e14bb325SJeff Bonwick 		 * If there's no waiter, issue an async i/o to the primary
6592e14bb325SJeff Bonwick 		 * storage now.  If there *is* a waiter, the caller must
6593e14bb325SJeff Bonwick 		 * issue the i/o in a context where it's OK to block.
6594e14bb325SJeff Bonwick 		 */
6595a3f829aeSBill Moore 		if (zio->io_waiter == NULL) {
6596a3f829aeSBill Moore 			zio_t *pio = zio_unique_parent(zio);
6597a3f829aeSBill Moore 
6598a3f829aeSBill Moore 			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
6599a3f829aeSBill Moore 
6600dcbf3bd6SGeorge Wilson 			zio_nowait(zio_read(pio, zio->io_spa, zio->io_bp,
6601*770499e1SDan Kimmel 			    hdr->b_l1hdr.b_pabd, zio->io_size, arc_read_done,
6602dcbf3bd6SGeorge Wilson 			    hdr, zio->io_priority, cb->l2rcb_flags,
6603dcbf3bd6SGeorge Wilson 			    &cb->l2rcb_zb));
6604a3f829aeSBill Moore 		}
6605fa94a07fSbrendan 	}
6606fa94a07fSbrendan 
6607fa94a07fSbrendan 	kmem_free(cb, sizeof (l2arc_read_callback_t));
6608fa94a07fSbrendan }
6609fa94a07fSbrendan 
6610fa94a07fSbrendan /*
6611fa94a07fSbrendan  * This is the list priority from which the L2ARC will search for pages to
6612fa94a07fSbrendan  * cache.  This is used within loops (0..3) to cycle through lists in the
6613fa94a07fSbrendan  * desired order.  This order can have a significant effect on cache
6614fa94a07fSbrendan  * performance.
6615fa94a07fSbrendan  *
6616fa94a07fSbrendan  * Currently the metadata lists are hit first, MFU then MRU, followed by
6617fa94a07fSbrendan  * the data lists.  This function returns a locked list, and also returns
6618fa94a07fSbrendan  * the lock pointer.
6619fa94a07fSbrendan  */
6620244781f1SPrakash Surya static multilist_sublist_t *
6621244781f1SPrakash Surya l2arc_sublist_lock(int list_num)
6622fa94a07fSbrendan {
6623244781f1SPrakash Surya 	multilist_t *ml = NULL;
6624244781f1SPrakash Surya 	unsigned int idx;
6625fa94a07fSbrendan 
6626fa94a07fSbrendan 	ASSERT(list_num >= 0 && list_num <= 3);
6627fa94a07fSbrendan 
6628fa94a07fSbrendan 	switch (list_num) {
6629fa94a07fSbrendan 	case 0:
663094c2d0ebSMatthew Ahrens 		ml = arc_mfu->arcs_list[ARC_BUFC_METADATA];
6631fa94a07fSbrendan 		break;
6632fa94a07fSbrendan 	case 1:
663394c2d0ebSMatthew Ahrens 		ml = arc_mru->arcs_list[ARC_BUFC_METADATA];
6634fa94a07fSbrendan 		break;
6635fa94a07fSbrendan 	case 2:
663694c2d0ebSMatthew Ahrens 		ml = arc_mfu->arcs_list[ARC_BUFC_DATA];
6637fa94a07fSbrendan 		break;
6638fa94a07fSbrendan 	case 3:
663994c2d0ebSMatthew Ahrens 		ml = arc_mru->arcs_list[ARC_BUFC_DATA];
6640fa94a07fSbrendan 		break;
6641fa94a07fSbrendan 	}
6642fa94a07fSbrendan 
6643244781f1SPrakash Surya 	/*
6644244781f1SPrakash Surya 	 * Return a randomly-selected sublist. This is acceptable
6645244781f1SPrakash Surya 	 * because the caller feeds only a little bit of data for each
6646244781f1SPrakash Surya 	 * call (8MB). Subsequent calls will result in different
6647244781f1SPrakash Surya 	 * sublists being selected.
6648244781f1SPrakash Surya 	 */
6649244781f1SPrakash Surya 	idx = multilist_get_random_index(ml);
6650244781f1SPrakash Surya 	return (multilist_sublist_lock(ml, idx));
6651fa94a07fSbrendan }
6652fa94a07fSbrendan 
6653fa94a07fSbrendan /*
6654fa94a07fSbrendan  * Evict buffers from the device write hand to the distance specified in
6655fa94a07fSbrendan  * bytes.  This distance may span populated buffers, it may span nothing.
6656fa94a07fSbrendan  * This is clearing a region on the L2ARC device ready for writing.
6657fa94a07fSbrendan  * If the 'all' boolean is set, every buffer is evicted.
6658fa94a07fSbrendan  */
6659fa94a07fSbrendan static void
6660fa94a07fSbrendan l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
6661fa94a07fSbrendan {
6662fa94a07fSbrendan 	list_t *buflist;
66637adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr, *hdr_prev;
6664fa94a07fSbrendan 	kmutex_t *hash_lock;
6665fa94a07fSbrendan 	uint64_t taddr;
6666fa94a07fSbrendan 
666789c86e32SChris Williamson 	buflist = &dev->l2ad_buflist;
6668fa94a07fSbrendan 
6669fa94a07fSbrendan 	if (!all && dev->l2ad_first) {
6670fa94a07fSbrendan 		/*
6671fa94a07fSbrendan 		 * This is the first sweep through the device.  There is
6672fa94a07fSbrendan 		 * nothing to evict.
6673fa94a07fSbrendan 		 */
6674fa94a07fSbrendan 		return;
6675fa94a07fSbrendan 	}
6676fa94a07fSbrendan 
66773a737e0dSbrendan 	if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
6678fa94a07fSbrendan 		/*
6679fa94a07fSbrendan 		 * When nearing the end of the device, evict to the end
6680fa94a07fSbrendan 		 * before the device write hand jumps to the start.
6681fa94a07fSbrendan 		 */
6682fa94a07fSbrendan 		taddr = dev->l2ad_end;
6683fa94a07fSbrendan 	} else {
6684fa94a07fSbrendan 		taddr = dev->l2ad_hand + distance;
6685fa94a07fSbrendan 	}
6686fa94a07fSbrendan 	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
6687fa94a07fSbrendan 	    uint64_t, taddr, boolean_t, all);
6688fa94a07fSbrendan 
6689fa94a07fSbrendan top:
669089c86e32SChris Williamson 	mutex_enter(&dev->l2ad_mtx);
66917adb730bSGeorge Wilson 	for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
66927adb730bSGeorge Wilson 		hdr_prev = list_prev(buflist, hdr);
6693fa94a07fSbrendan 
66947adb730bSGeorge Wilson 		hash_lock = HDR_LOCK(hdr);
6695244781f1SPrakash Surya 
6696244781f1SPrakash Surya 		/*
6697244781f1SPrakash Surya 		 * We cannot use mutex_enter or else we can deadlock
6698244781f1SPrakash Surya 		 * with l2arc_write_buffers (due to swapping the order
6699244781f1SPrakash Surya 		 * the hash lock and l2ad_mtx are taken).
6700244781f1SPrakash Surya 		 */
6701fa94a07fSbrendan 		if (!mutex_tryenter(hash_lock)) {
6702fa94a07fSbrendan 			/*
6703fa94a07fSbrendan 			 * Missed the hash lock.  Retry.
6704fa94a07fSbrendan 			 */
6705fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
670689c86e32SChris Williamson 			mutex_exit(&dev->l2ad_mtx);
6707fa94a07fSbrendan 			mutex_enter(hash_lock);
6708fa94a07fSbrendan 			mutex_exit(hash_lock);
6709fa94a07fSbrendan 			goto top;
6710fa94a07fSbrendan 		}
6711fa94a07fSbrendan 
67127adb730bSGeorge Wilson 		if (HDR_L2_WRITE_HEAD(hdr)) {
6713fa94a07fSbrendan 			/*
6714fa94a07fSbrendan 			 * We hit a write head node.  Leave it for
6715fa94a07fSbrendan 			 * l2arc_write_done().
6716fa94a07fSbrendan 			 */
67177adb730bSGeorge Wilson 			list_remove(buflist, hdr);
6718fa94a07fSbrendan 			mutex_exit(hash_lock);
6719fa94a07fSbrendan 			continue;
6720fa94a07fSbrendan 		}
6721fa94a07fSbrendan 
672289c86e32SChris Williamson 		if (!all && HDR_HAS_L2HDR(hdr) &&
672389c86e32SChris Williamson 		    (hdr->b_l2hdr.b_daddr > taddr ||
672489c86e32SChris Williamson 		    hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
6725fa94a07fSbrendan 			/*
6726fa94a07fSbrendan 			 * We've evicted to the target address,
6727fa94a07fSbrendan 			 * or the end of the device.
6728fa94a07fSbrendan 			 */
6729fa94a07fSbrendan 			mutex_exit(hash_lock);
6730fa94a07fSbrendan 			break;
6731fa94a07fSbrendan 		}
6732fa94a07fSbrendan 
673389c86e32SChris Williamson 		ASSERT(HDR_HAS_L2HDR(hdr));
673489c86e32SChris Williamson 		if (!HDR_HAS_L1HDR(hdr)) {
67357adb730bSGeorge Wilson 			ASSERT(!HDR_L2_READING(hdr));
6736fa94a07fSbrendan 			/*
6737fa94a07fSbrendan 			 * This doesn't exist in the ARC.  Destroy.
6738fa94a07fSbrendan 			 * arc_hdr_destroy() will call list_remove()
6739fa94a07fSbrendan 			 * and decrement arcstat_l2_size.
6740fa94a07fSbrendan 			 */
67417adb730bSGeorge Wilson 			arc_change_state(arc_anon, hdr, hash_lock);
67427adb730bSGeorge Wilson 			arc_hdr_destroy(hdr);
6743fa94a07fSbrendan 		} else {
674489c86e32SChris Williamson 			ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
674589c86e32SChris Williamson 			ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
67463a737e0dSbrendan 			/*
67473a737e0dSbrendan 			 * Invalidate issued or about to be issued
67483a737e0dSbrendan 			 * reads, since we may be about to write
67493a737e0dSbrendan 			 * over this location.
67503a737e0dSbrendan 			 */
67517adb730bSGeorge Wilson 			if (HDR_L2_READING(hdr)) {
67523a737e0dSbrendan 				ARCSTAT_BUMP(arcstat_l2_evict_reading);
6753dcbf3bd6SGeorge Wilson 				arc_hdr_set_flags(hdr, ARC_FLAG_L2_EVICTED);
67543a737e0dSbrendan 			}
67553a737e0dSbrendan 
6756244781f1SPrakash Surya 			/* Ensure this header has finished being written */
6757244781f1SPrakash Surya 			ASSERT(!HDR_L2_WRITING(hdr));
6758a52fc310SPrakash Surya 
6759a52fc310SPrakash Surya 			arc_hdr_l2hdr_destroy(hdr);
6760fa94a07fSbrendan 		}
6761fa94a07fSbrendan 		mutex_exit(hash_lock);
6762fa94a07fSbrendan 	}
676389c86e32SChris Williamson 	mutex_exit(&dev->l2ad_mtx);
6764fa94a07fSbrendan }
6765fa94a07fSbrendan 
6766fa94a07fSbrendan /*
6767fa94a07fSbrendan  * Find and write ARC buffers to the L2ARC device.
6768fa94a07fSbrendan  *
67697adb730bSGeorge Wilson  * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
6770fa94a07fSbrendan  * for reading until they have completed writing.
6771aad02571SSaso Kiselkov  * The headroom_boost is an in-out parameter used to maintain headroom boost
6772aad02571SSaso Kiselkov  * state between calls to this function.
6773aad02571SSaso Kiselkov  *
6774aad02571SSaso Kiselkov  * Returns the number of bytes actually written (which may be smaller than
6775aad02571SSaso Kiselkov  * the delta by which the device hand has changed due to alignment).
6776fa94a07fSbrendan  */
67775a98e54bSBrendan Gregg - Sun Microsystems static uint64_t
6778dcbf3bd6SGeorge Wilson l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
6779fa94a07fSbrendan {
67807adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr, *hdr_prev, *head;
6781dcbf3bd6SGeorge Wilson 	uint64_t write_asize, write_psize, write_sz, headroom;
6782aad02571SSaso Kiselkov 	boolean_t full;
6783fa94a07fSbrendan 	l2arc_write_callback_t *cb;
6784fa94a07fSbrendan 	zio_t *pio, *wzio;
6785e9103aaeSGarrett D'Amore 	uint64_t guid = spa_load_guid(spa);
6786fa94a07fSbrendan 
6787dcbf3bd6SGeorge Wilson 	ASSERT3P(dev->l2ad_vdev, !=, NULL);
6788aad02571SSaso Kiselkov 
6789fa94a07fSbrendan 	pio = NULL;
6790dcbf3bd6SGeorge Wilson 	write_sz = write_asize = write_psize = 0;
6791fa94a07fSbrendan 	full = B_FALSE;
679289c86e32SChris Williamson 	head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
6793dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(head, ARC_FLAG_L2_WRITE_HEAD | ARC_FLAG_HAS_L2HDR);
6794aad02571SSaso Kiselkov 
6795fa94a07fSbrendan 	/*
6796fa94a07fSbrendan 	 * Copy buffers for L2ARC writing.
6797fa94a07fSbrendan 	 */
6798fa94a07fSbrendan 	for (int try = 0; try <= 3; try++) {
6799244781f1SPrakash Surya 		multilist_sublist_t *mls = l2arc_sublist_lock(try);
6800aad02571SSaso Kiselkov 		uint64_t passed_sz = 0;
6801aad02571SSaso Kiselkov 
68023a737e0dSbrendan 		/*
68033a737e0dSbrendan 		 * L2ARC fast warmup.
68043a737e0dSbrendan 		 *
68053a737e0dSbrendan 		 * Until the ARC is warm and starts to evict, read from the
68063a737e0dSbrendan 		 * head of the ARC lists rather than the tail.
68073a737e0dSbrendan 		 */
68083a737e0dSbrendan 		if (arc_warm == B_FALSE)
6809244781f1SPrakash Surya 			hdr = multilist_sublist_head(mls);
68103a737e0dSbrendan 		else
6811244781f1SPrakash Surya 			hdr = multilist_sublist_tail(mls);
68123a737e0dSbrendan 
6813aad02571SSaso Kiselkov 		headroom = target_sz * l2arc_headroom;
6814dcbf3bd6SGeorge Wilson 		if (zfs_compressed_arc_enabled)
6815aad02571SSaso Kiselkov 			headroom = (headroom * l2arc_headroom_boost) / 100;
6816aad02571SSaso Kiselkov 
68177adb730bSGeorge Wilson 		for (; hdr; hdr = hdr_prev) {
6818aad02571SSaso Kiselkov 			kmutex_t *hash_lock;
6819aad02571SSaso Kiselkov 
68203a737e0dSbrendan 			if (arc_warm == B_FALSE)
6821244781f1SPrakash Surya 				hdr_prev = multilist_sublist_next(mls, hdr);
68223a737e0dSbrendan 			else
6823244781f1SPrakash Surya 				hdr_prev = multilist_sublist_prev(mls, hdr);
6824fa94a07fSbrendan 
68257adb730bSGeorge Wilson 			hash_lock = HDR_LOCK(hdr);
6826aad02571SSaso Kiselkov 			if (!mutex_tryenter(hash_lock)) {
6827fa94a07fSbrendan 				/*
6828fa94a07fSbrendan 				 * Skip this buffer rather than waiting.
6829fa94a07fSbrendan 				 */
6830fa94a07fSbrendan 				continue;
6831fa94a07fSbrendan 			}
6832fa94a07fSbrendan 
6833dcbf3bd6SGeorge Wilson 			passed_sz += HDR_GET_LSIZE(hdr);
6834fa94a07fSbrendan 			if (passed_sz > headroom) {
6835fa94a07fSbrendan 				/*
6836fa94a07fSbrendan 				 * Searched too far.
6837fa94a07fSbrendan 				 */
6838fa94a07fSbrendan 				mutex_exit(hash_lock);
6839fa94a07fSbrendan 				break;
6840fa94a07fSbrendan 			}
6841fa94a07fSbrendan 
68427adb730bSGeorge Wilson 			if (!l2arc_write_eligible(guid, hdr)) {
6843fa94a07fSbrendan 				mutex_exit(hash_lock);
6844fa94a07fSbrendan 				continue;
6845fa94a07fSbrendan 			}
6846fa94a07fSbrendan 
6847dcbf3bd6SGeorge Wilson 			if ((write_asize + HDR_GET_LSIZE(hdr)) > target_sz) {
6848fa94a07fSbrendan 				full = B_TRUE;
6849fa94a07fSbrendan 				mutex_exit(hash_lock);
6850fa94a07fSbrendan 				break;
6851fa94a07fSbrendan 			}
6852fa94a07fSbrendan 
6853fa94a07fSbrendan 			if (pio == NULL) {
6854fa94a07fSbrendan 				/*
6855fa94a07fSbrendan 				 * Insert a dummy header on the buflist so
6856fa94a07fSbrendan 				 * l2arc_write_done() can find where the
6857fa94a07fSbrendan 				 * write buffers begin without searching.
6858fa94a07fSbrendan 				 */
6859244781f1SPrakash Surya 				mutex_enter(&dev->l2ad_mtx);
686089c86e32SChris Williamson 				list_insert_head(&dev->l2ad_buflist, head);
6861244781f1SPrakash Surya 				mutex_exit(&dev->l2ad_mtx);
6862fa94a07fSbrendan 
6863fa94a07fSbrendan 				cb = kmem_alloc(
6864fa94a07fSbrendan 				    sizeof (l2arc_write_callback_t), KM_SLEEP);
6865fa94a07fSbrendan 				cb->l2wcb_dev = dev;
6866fa94a07fSbrendan 				cb->l2wcb_head = head;
6867fa94a07fSbrendan 				pio = zio_root(spa, l2arc_write_done, cb,
6868fa94a07fSbrendan 				    ZIO_FLAG_CANFAIL);
6869fa94a07fSbrendan 			}
6870fa94a07fSbrendan 
687189c86e32SChris Williamson 			hdr->b_l2hdr.b_dev = dev;
6872dcbf3bd6SGeorge Wilson 			hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
6873dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr,
6874dcbf3bd6SGeorge Wilson 			    ARC_FLAG_L2_WRITING | ARC_FLAG_HAS_L2HDR);
6875dcbf3bd6SGeorge Wilson 
6876dcbf3bd6SGeorge Wilson 			mutex_enter(&dev->l2ad_mtx);
6877dcbf3bd6SGeorge Wilson 			list_insert_head(&dev->l2ad_buflist, hdr);
6878dcbf3bd6SGeorge Wilson 			mutex_exit(&dev->l2ad_mtx);
6879dcbf3bd6SGeorge Wilson 
6880aad02571SSaso Kiselkov 			/*
6881dcbf3bd6SGeorge Wilson 			 * We rely on the L1 portion of the header below, so
6882dcbf3bd6SGeorge Wilson 			 * it's invalid for this header to have been evicted out
6883dcbf3bd6SGeorge Wilson 			 * of the ghost cache, prior to being written out. The
6884dcbf3bd6SGeorge Wilson 			 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
6885aad02571SSaso Kiselkov 			 */
6886dcbf3bd6SGeorge Wilson 			ASSERT(HDR_HAS_L1HDR(hdr));
6887dcbf3bd6SGeorge Wilson 
6888dcbf3bd6SGeorge Wilson 			ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
6889*770499e1SDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
6890dcbf3bd6SGeorge Wilson 			ASSERT3U(arc_hdr_size(hdr), >, 0);
6891dcbf3bd6SGeorge Wilson 			uint64_t size = arc_hdr_size(hdr);
6892dcbf3bd6SGeorge Wilson 
6893dcbf3bd6SGeorge Wilson 			(void) refcount_add_many(&dev->l2ad_alloc, size, hdr);
6894aad02571SSaso Kiselkov 
6895a52fc310SPrakash Surya 			/*
6896dcbf3bd6SGeorge Wilson 			 * Normally the L2ARC can use the hdr's data, but if
6897dcbf3bd6SGeorge Wilson 			 * we're sharing data between the hdr and one of its
6898dcbf3bd6SGeorge Wilson 			 * bufs, L2ARC needs its own copy of the data so that
6899dcbf3bd6SGeorge Wilson 			 * the ZIO below can't race with the buf consumer. To
6900dcbf3bd6SGeorge Wilson 			 * ensure that this copy will be available for the
6901dcbf3bd6SGeorge Wilson 			 * lifetime of the ZIO and be cleaned up afterwards, we
6902dcbf3bd6SGeorge Wilson 			 * add it to the l2arc_free_on_write queue.
6903a52fc310SPrakash Surya 			 */
6904*770499e1SDan Kimmel 			abd_t *to_write;
6905dcbf3bd6SGeorge Wilson 			if (!HDR_SHARED_DATA(hdr)) {
6906*770499e1SDan Kimmel 				to_write = hdr->b_l1hdr.b_pabd;
6907dcbf3bd6SGeorge Wilson 			} else {
6908*770499e1SDan Kimmel 				to_write = abd_alloc_for_io(size,
6909*770499e1SDan Kimmel 				    HDR_ISTYPE_METADATA(hdr));
6910*770499e1SDan Kimmel 				abd_copy(to_write, hdr->b_l1hdr.b_pabd, size);
6911*770499e1SDan Kimmel 				l2arc_free_abd_on_write(to_write, size,
6912*770499e1SDan Kimmel 				    arc_buf_type(hdr));
6913dcbf3bd6SGeorge Wilson 			}
6914dcbf3bd6SGeorge Wilson 			wzio = zio_write_phys(pio, dev->l2ad_vdev,
6915dcbf3bd6SGeorge Wilson 			    hdr->b_l2hdr.b_daddr, size, to_write,
6916dcbf3bd6SGeorge Wilson 			    ZIO_CHECKSUM_OFF, NULL, hdr,
6917dcbf3bd6SGeorge Wilson 			    ZIO_PRIORITY_ASYNC_WRITE,
6918dcbf3bd6SGeorge Wilson 			    ZIO_FLAG_CANFAIL, B_FALSE);
6919aad02571SSaso Kiselkov 
6920dcbf3bd6SGeorge Wilson 			write_sz += HDR_GET_LSIZE(hdr);
6921dcbf3bd6SGeorge Wilson 			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
6922dcbf3bd6SGeorge Wilson 			    zio_t *, wzio);
6923fa94a07fSbrendan 
6924dcbf3bd6SGeorge Wilson 			write_asize += size;
6925fa94a07fSbrendan 			/*
6926dcbf3bd6SGeorge Wilson 			 * Keep the clock hand suitably device-aligned.
6927fa94a07fSbrendan 			 */
6928dcbf3bd6SGeorge Wilson 			uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev,
6929dcbf3bd6SGeorge Wilson 			    size);
6930dcbf3bd6SGeorge Wilson 			write_psize += asize;
6931dcbf3bd6SGeorge Wilson 			dev->l2ad_hand += asize;
6932fa94a07fSbrendan 
6933fa94a07fSbrendan 			mutex_exit(hash_lock);
6934fa94a07fSbrendan 
6935dcbf3bd6SGeorge Wilson 			(void) zio_nowait(wzio);
6936aad02571SSaso Kiselkov 		}
6937aad02571SSaso Kiselkov 
6938244781f1SPrakash Surya 		multilist_sublist_unlock(mls);
6939aad02571SSaso Kiselkov 
6940aad02571SSaso Kiselkov 		if (full == B_TRUE)
6941aad02571SSaso Kiselkov 			break;
6942aad02571SSaso Kiselkov 	}
6943aad02571SSaso Kiselkov 
6944aad02571SSaso Kiselkov 	/* No buffers selected for writing? */
6945aad02571SSaso Kiselkov 	if (pio == NULL) {
6946aad02571SSaso Kiselkov 		ASSERT0(write_sz);
694789c86e32SChris Williamson 		ASSERT(!HDR_HAS_L1HDR(head));
694889c86e32SChris Williamson 		kmem_cache_free(hdr_l2only_cache, head);
6949aad02571SSaso Kiselkov 		return (0);
6950aad02571SSaso Kiselkov 	}
6951aad02571SSaso Kiselkov 
6952aad02571SSaso Kiselkov 	ASSERT3U(write_asize, <=, target_sz);
6953fa94a07fSbrendan 	ARCSTAT_BUMP(arcstat_l2_writes_sent);
6954aad02571SSaso Kiselkov 	ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
6955fa94a07fSbrendan 	ARCSTAT_INCR(arcstat_l2_size, write_sz);
6956dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_l2_asize, write_asize);
6957dcbf3bd6SGeorge Wilson 	vdev_space_update(dev->l2ad_vdev, write_asize, 0, 0);
6958fa94a07fSbrendan 
6959fa94a07fSbrendan 	/*
6960fa94a07fSbrendan 	 * Bump device hand to the device start if it is approaching the end.
6961fa94a07fSbrendan 	 * l2arc_evict() will already have evicted ahead for this case.
6962fa94a07fSbrendan 	 */
69633a737e0dSbrendan 	if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
6964fa94a07fSbrendan 		dev->l2ad_hand = dev->l2ad_start;
6965fa94a07fSbrendan 		dev->l2ad_first = B_FALSE;
6966fa94a07fSbrendan 	}
6967fa94a07fSbrendan 
69685a98e54bSBrendan Gregg - Sun Microsystems 	dev->l2ad_writing = B_TRUE;
6969fa94a07fSbrendan 	(void) zio_wait(pio);
69705a98e54bSBrendan Gregg - Sun Microsystems 	dev->l2ad_writing = B_FALSE;
69715a98e54bSBrendan Gregg - Sun Microsystems 
6972aad02571SSaso Kiselkov 	return (write_asize);
6973aad02571SSaso Kiselkov }
6974aad02571SSaso Kiselkov 
6975fa94a07fSbrendan /*
6976fa94a07fSbrendan  * This thread feeds the L2ARC at regular intervals.  This is the beating
6977fa94a07fSbrendan  * heart of the L2ARC.
6978fa94a07fSbrendan  */
6979fa94a07fSbrendan static void
6980fa94a07fSbrendan l2arc_feed_thread(void)
6981fa94a07fSbrendan {
6982fa94a07fSbrendan 	callb_cpr_t cpr;
6983fa94a07fSbrendan 	l2arc_dev_t *dev;
6984fa94a07fSbrendan 	spa_t *spa;
69855a98e54bSBrendan Gregg - Sun Microsystems 	uint64_t size, wrote;
6986d3d50737SRafael Vanoni 	clock_t begin, next = ddi_get_lbolt();
6987fa94a07fSbrendan 
6988fa94a07fSbrendan 	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
6989fa94a07fSbrendan 
6990fa94a07fSbrendan 	mutex_enter(&l2arc_feed_thr_lock);
6991fa94a07fSbrendan 
6992fa94a07fSbrendan 	while (l2arc_thread_exit == 0) {
6993fa94a07fSbrendan 		CALLB_CPR_SAFE_BEGIN(&cpr);
6994fa94a07fSbrendan 		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
69955a98e54bSBrendan Gregg - Sun Microsystems 		    next);
6996fa94a07fSbrendan 		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
6997d3d50737SRafael Vanoni 		next = ddi_get_lbolt() + hz;
6998fa94a07fSbrendan 
69993a737e0dSbrendan 		/*
70003a737e0dSbrendan 		 * Quick check for L2ARC devices.
70013a737e0dSbrendan 		 */
7002c5904d13Seschrock 		mutex_enter(&l2arc_dev_mtx);
70033a737e0dSbrendan 		if (l2arc_ndev == 0) {
70043a737e0dSbrendan 			mutex_exit(&l2arc_dev_mtx);
70053a737e0dSbrendan 			continue;
70063a737e0dSbrendan 		}
70073a737e0dSbrendan 		mutex_exit(&l2arc_dev_mtx);
7008d3d50737SRafael Vanoni 		begin = ddi_get_lbolt();
7009c5904d13Seschrock 
7010fa94a07fSbrendan 		/*
7011c5904d13Seschrock 		 * This selects the next l2arc device to write to, and in
7012c5904d13Seschrock 		 * doing so the next spa to feed from: dev->l2ad_spa.   This
70133a737e0dSbrendan 		 * will return NULL if there are now no l2arc devices or if
70143a737e0dSbrendan 		 * they are all faulted.
70153a737e0dSbrendan 		 *
70163a737e0dSbrendan 		 * If a device is returned, its spa's config lock is also
70173a737e0dSbrendan 		 * held to prevent device removal.  l2arc_dev_get_next()
70183a737e0dSbrendan 		 * will grab and release l2arc_dev_mtx.
7019fa94a07fSbrendan 		 */
70203a737e0dSbrendan 		if ((dev = l2arc_dev_get_next()) == NULL)
7021fa94a07fSbrendan 			continue;
70223a737e0dSbrendan 
70233a737e0dSbrendan 		spa = dev->l2ad_spa;
7024dcbf3bd6SGeorge Wilson 		ASSERT3P(spa, !=, NULL);
7025fa94a07fSbrendan 
7026f9af39baSGeorge Wilson 		/*
7027f9af39baSGeorge Wilson 		 * If the pool is read-only then force the feed thread to
7028f9af39baSGeorge Wilson 		 * sleep a little longer.
7029f9af39baSGeorge Wilson 		 */
7030f9af39baSGeorge Wilson 		if (!spa_writeable(spa)) {
7031f9af39baSGeorge Wilson 			next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
7032f9af39baSGeorge Wilson 			spa_config_exit(spa, SCL_L2ARC, dev);
7033f9af39baSGeorge Wilson 			continue;
7034f9af39baSGeorge Wilson 		}
7035f9af39baSGeorge Wilson 
7036fa94a07fSbrendan 		/*
7037fa94a07fSbrendan 		 * Avoid contributing to memory pressure.
7038fa94a07fSbrendan 		 */
7039fa94a07fSbrendan 		if (arc_reclaim_needed()) {
7040fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
7041e14bb325SJeff Bonwick 			spa_config_exit(spa, SCL_L2ARC, dev);
7042fa94a07fSbrendan 			continue;
7043fa94a07fSbrendan 		}
7044fa94a07fSbrendan 
7045fa94a07fSbrendan 		ARCSTAT_BUMP(arcstat_l2_feeds);
7046fa94a07fSbrendan 
7047aad02571SSaso Kiselkov 		size = l2arc_write_size();
70483a737e0dSbrendan 
7049fa94a07fSbrendan 		/*
7050fa94a07fSbrendan 		 * Evict L2ARC buffers that will be overwritten.
7051fa94a07fSbrendan 		 */
70523a737e0dSbrendan 		l2arc_evict(dev, size, B_FALSE);
7053fa94a07fSbrendan 
7054fa94a07fSbrendan 		/*
7055fa94a07fSbrendan 		 * Write ARC buffers.
7056fa94a07fSbrendan 		 */
7057dcbf3bd6SGeorge Wilson 		wrote = l2arc_write_buffers(spa, dev, size);
70585a98e54bSBrendan Gregg - Sun Microsystems 
70595a98e54bSBrendan Gregg - Sun Microsystems 		/*
70605a98e54bSBrendan Gregg - Sun Microsystems 		 * Calculate interval between writes.
70615a98e54bSBrendan Gregg - Sun Microsystems 		 */
70625a98e54bSBrendan Gregg - Sun Microsystems 		next = l2arc_write_interval(begin, size, wrote);
7063e14bb325SJeff Bonwick 		spa_config_exit(spa, SCL_L2ARC, dev);
7064fa94a07fSbrendan 	}
7065fa94a07fSbrendan 
7066fa94a07fSbrendan 	l2arc_thread_exit = 0;
7067fa94a07fSbrendan 	cv_broadcast(&l2arc_feed_thr_cv);
7068fa94a07fSbrendan 	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
7069fa94a07fSbrendan 	thread_exit();
7070fa94a07fSbrendan }
7071fa94a07fSbrendan 
7072c5904d13Seschrock boolean_t
7073c5904d13Seschrock l2arc_vdev_present(vdev_t *vd)
7074c5904d13Seschrock {
7075c5904d13Seschrock 	l2arc_dev_t *dev;
7076c5904d13Seschrock 
7077c5904d13Seschrock 	mutex_enter(&l2arc_dev_mtx);
7078c5904d13Seschrock 	for (dev = list_head(l2arc_dev_list); dev != NULL;
7079c5904d13Seschrock 	    dev = list_next(l2arc_dev_list, dev)) {
7080c5904d13Seschrock 		if (dev->l2ad_vdev == vd)
7081c5904d13Seschrock 			break;
7082c5904d13Seschrock 	}
7083c5904d13Seschrock 	mutex_exit(&l2arc_dev_mtx);
7084c5904d13Seschrock 
7085c5904d13Seschrock 	return (dev != NULL);
7086c5904d13Seschrock }
7087c5904d13Seschrock 
7088fa94a07fSbrendan /*
7089fa94a07fSbrendan  * Add a vdev for use by the L2ARC.  By this point the spa has already
7090fa94a07fSbrendan  * validated the vdev and opened it.
7091fa94a07fSbrendan  */
7092fa94a07fSbrendan void
7093573ca77eSGeorge Wilson l2arc_add_vdev(spa_t *spa, vdev_t *vd)
7094fa94a07fSbrendan {
7095fa94a07fSbrendan 	l2arc_dev_t *adddev;
7096fa94a07fSbrendan 
7097c5904d13Seschrock 	ASSERT(!l2arc_vdev_present(vd));
7098c5904d13Seschrock 
7099fa94a07fSbrendan 	/*
7100fa94a07fSbrendan 	 * Create a new l2arc device entry.
7101fa94a07fSbrendan 	 */
7102fa94a07fSbrendan 	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
7103fa94a07fSbrendan 	adddev->l2ad_spa = spa;
7104fa94a07fSbrendan 	adddev->l2ad_vdev = vd;
7105573ca77eSGeorge Wilson 	adddev->l2ad_start = VDEV_LABEL_START_SIZE;
7106573ca77eSGeorge Wilson 	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
7107fa94a07fSbrendan 	adddev->l2ad_hand = adddev->l2ad_start;
7108fa94a07fSbrendan 	adddev->l2ad_first = B_TRUE;
71095a98e54bSBrendan Gregg - Sun Microsystems 	adddev->l2ad_writing = B_FALSE;
7110fa94a07fSbrendan 
711189c86e32SChris Williamson 	mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
7112fa94a07fSbrendan 	/*
7113fa94a07fSbrendan 	 * This is a list of all ARC buffers that are still valid on the
7114fa94a07fSbrendan 	 * device.
7115fa94a07fSbrendan 	 */
711689c86e32SChris Williamson 	list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
711789c86e32SChris Williamson 	    offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
7118fa94a07fSbrendan 
7119b24ab676SJeff Bonwick 	vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
7120a52fc310SPrakash Surya 	refcount_create(&adddev->l2ad_alloc);
7121fa94a07fSbrendan 
7122fa94a07fSbrendan 	/*
7123fa94a07fSbrendan 	 * Add device to global list
7124fa94a07fSbrendan 	 */
7125fa94a07fSbrendan 	mutex_enter(&l2arc_dev_mtx);
7126fa94a07fSbrendan 	list_insert_head(l2arc_dev_list, adddev);
7127fa94a07fSbrendan 	atomic_inc_64(&l2arc_ndev);
7128fa94a07fSbrendan 	mutex_exit(&l2arc_dev_mtx);
7129fa94a07fSbrendan }
7130fa94a07fSbrendan 
7131fa94a07fSbrendan /*
7132fa94a07fSbrendan  * Remove a vdev from the L2ARC.
7133fa94a07fSbrendan  */
7134fa94a07fSbrendan void
7135fa94a07fSbrendan l2arc_remove_vdev(vdev_t *vd)
7136fa94a07fSbrendan {
7137fa94a07fSbrendan 	l2arc_dev_t *dev, *nextdev, *remdev = NULL;
7138fa94a07fSbrendan 
7139fa94a07fSbrendan 	/*
7140fa94a07fSbrendan 	 * Find the device by vdev
7141fa94a07fSbrendan 	 */
7142fa94a07fSbrendan 	mutex_enter(&l2arc_dev_mtx);
7143fa94a07fSbrendan 	for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
7144fa94a07fSbrendan 		nextdev = list_next(l2arc_dev_list, dev);
7145fa94a07fSbrendan 		if (vd == dev->l2ad_vdev) {
7146fa94a07fSbrendan 			remdev = dev;
7147fa94a07fSbrendan 			break;
7148fa94a07fSbrendan 		}
7149fa94a07fSbrendan 	}
7150dcbf3bd6SGeorge Wilson 	ASSERT3P(remdev, !=, NULL);
7151fa94a07fSbrendan 
7152fa94a07fSbrendan 	/*
7153fa94a07fSbrendan 	 * Remove device from global list
7154fa94a07fSbrendan 	 */
7155fa94a07fSbrendan 	list_remove(l2arc_dev_list, remdev);
7156fa94a07fSbrendan 	l2arc_dev_last = NULL;		/* may have been invalidated */
71573a737e0dSbrendan 	atomic_dec_64(&l2arc_ndev);
71583a737e0dSbrendan 	mutex_exit(&l2arc_dev_mtx);
7159fa94a07fSbrendan 
7160fa94a07fSbrendan 	/*
7161fa94a07fSbrendan 	 * Clear all buflists and ARC references.  L2ARC device flush.
7162fa94a07fSbrendan 	 */
7163fa94a07fSbrendan 	l2arc_evict(remdev, 0, B_TRUE);
716489c86e32SChris Williamson 	list_destroy(&remdev->l2ad_buflist);
716589c86e32SChris Williamson 	mutex_destroy(&remdev->l2ad_mtx);
7166a52fc310SPrakash Surya 	refcount_destroy(&remdev->l2ad_alloc);
7167fa94a07fSbrendan 	kmem_free(remdev, sizeof (l2arc_dev_t));
7168fa94a07fSbrendan }
7169fa94a07fSbrendan 
7170fa94a07fSbrendan void
7171e14bb325SJeff Bonwick l2arc_init(void)
7172fa94a07fSbrendan {
7173fa94a07fSbrendan 	l2arc_thread_exit = 0;
7174fa94a07fSbrendan 	l2arc_ndev = 0;
7175fa94a07fSbrendan 	l2arc_writes_sent = 0;
7176fa94a07fSbrendan 	l2arc_writes_done = 0;
7177fa94a07fSbrendan 
7178fa94a07fSbrendan 	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
7179fa94a07fSbrendan 	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
7180fa94a07fSbrendan 	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
7181fa94a07fSbrendan 	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
7182fa94a07fSbrendan 
7183fa94a07fSbrendan 	l2arc_dev_list = &L2ARC_dev_list;
7184fa94a07fSbrendan 	l2arc_free_on_write = &L2ARC_free_on_write;
7185fa94a07fSbrendan 	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
7186fa94a07fSbrendan 	    offsetof(l2arc_dev_t, l2ad_node));
7187fa94a07fSbrendan 	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
7188fa94a07fSbrendan 	    offsetof(l2arc_data_free_t, l2df_list_node));
7189fa94a07fSbrendan }
7190fa94a07fSbrendan 
7191fa94a07fSbrendan void
7192e14bb325SJeff Bonwick l2arc_fini(void)
7193fa94a07fSbrendan {
71943a737e0dSbrendan 	/*
71953a737e0dSbrendan 	 * This is called from dmu_fini(), which is called from spa_fini();
71963a737e0dSbrendan 	 * Because of this, we can assume that all l2arc devices have
71973a737e0dSbrendan 	 * already been removed when the pools themselves were removed.
71983a737e0dSbrendan 	 */
71993a737e0dSbrendan 
72003a737e0dSbrendan 	l2arc_do_free_on_write();
72013a737e0dSbrendan 
7202fa94a07fSbrendan 	mutex_destroy(&l2arc_feed_thr_lock);
7203fa94a07fSbrendan 	cv_destroy(&l2arc_feed_thr_cv);
7204fa94a07fSbrendan 	mutex_destroy(&l2arc_dev_mtx);
7205fa94a07fSbrendan 	mutex_destroy(&l2arc_free_on_write_mtx);
7206fa94a07fSbrendan 
7207fa94a07fSbrendan 	list_destroy(l2arc_dev_list);
7208fa94a07fSbrendan 	list_destroy(l2arc_free_on_write);
7209fa94a07fSbrendan }
7210e14bb325SJeff Bonwick 
7211e14bb325SJeff Bonwick void
7212e14bb325SJeff Bonwick l2arc_start(void)
7213e14bb325SJeff Bonwick {
72148ad4d6ddSJeff Bonwick 	if (!(spa_mode_global & FWRITE))
7215e14bb325SJeff Bonwick 		return;
7216e14bb325SJeff Bonwick 
7217e14bb325SJeff Bonwick 	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
7218e14bb325SJeff Bonwick 	    TS_RUN, minclsyspri);
7219e14bb325SJeff Bonwick }
7220e14bb325SJeff Bonwick 
7221e14bb325SJeff Bonwick void
7222e14bb325SJeff Bonwick l2arc_stop(void)
7223e14bb325SJeff Bonwick {
72248ad4d6ddSJeff Bonwick 	if (!(spa_mode_global & FWRITE))
7225e14bb325SJeff Bonwick 		return;
7226e14bb325SJeff Bonwick 
7227e14bb325SJeff Bonwick 	mutex_enter(&l2arc_feed_thr_lock);
7228e14bb325SJeff Bonwick 	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
7229e14bb325SJeff Bonwick 	l2arc_thread_exit = 1;
7230e14bb325SJeff Bonwick 	while (l2arc_thread_exit != 0)
7231e14bb325SJeff Bonwick 		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
7232e14bb325SJeff Bonwick 	mutex_exit(&l2arc_feed_thr_lock);
7233e14bb325SJeff Bonwick }
7234