xref: /illumos-gate/usr/src/uts/common/fs/zfs/arc.c (revision de753e34)
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.
2336a64e62STim Kordas  * Copyright (c) 2018, Joyent, Inc.
2410fbdecbSMatthew Ahrens  * Copyright (c) 2011, 2017 by Delphix. All rights reserved.
2571cb1b74SSaso Kiselkov  * Copyright (c) 2014 by Saso Kiselkov. All rights reserved.
2601a059eeSRoman Strashkin  * Copyright 2017 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
131770499e1SDan 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
134770499e1SDan Kimmel  * ability to store the physical data (b_pabd) associated with the DVA of the
135770499e1SDan 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
138770499e1SDan 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
177770499e1SDan 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
194770499e1SDan Kimmel  * existing uncompressed arc_buf_t, decompresses the hdr's b_pabd buffer into a
195770499e1SDan 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   +---->+---------+
219770499e1SDan 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  *
233770499e1SDan 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
238770499e1SDan 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  *
244770499e1SDan Kimmel  * When the L2ARC is in use, it will also take advantage of the b_pabd. The
245770499e1SDan 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>
266770499e1SDan Kimmel #include <sys/zio_checksum.h>
267244781f1SPrakash Surya #include <sys/multilist.h>
268770499e1SDan 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>
277*de753e34SBrad Lewis #include <sys/zthr.h>
278b24ab676SJeff Bonwick #include <zfs_fletcher.h>
2793a2d8a1bSPaul Dagnelie #include <sys/aggsum.h>
2803a2d8a1bSPaul Dagnelie #include <sys/cityhash.h>
281fa9e4066Sahrens 
282cd1c8b85SMatthew Ahrens #ifndef _KERNEL
283cd1c8b85SMatthew Ahrens /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
284cd1c8b85SMatthew Ahrens boolean_t arc_watch = B_FALSE;
285cd1c8b85SMatthew Ahrens int arc_procfd;
286cd1c8b85SMatthew Ahrens #endif
287cd1c8b85SMatthew Ahrens 
288*de753e34SBrad Lewis /*
289*de753e34SBrad Lewis  * This thread's job is to keep enough free memory in the system, by
290*de753e34SBrad Lewis  * calling arc_kmem_reap_now() plus arc_shrink(), which improves
291*de753e34SBrad Lewis  * arc_available_memory().
292*de753e34SBrad Lewis  */
293*de753e34SBrad Lewis static zthr_t		*arc_reap_zthr;
294*de753e34SBrad Lewis 
295*de753e34SBrad Lewis /*
296*de753e34SBrad Lewis  * This thread's job is to keep arc_size under arc_c, by calling
297*de753e34SBrad Lewis  * arc_adjust(), which improves arc_is_overflowing().
298*de753e34SBrad Lewis  */
299*de753e34SBrad Lewis static zthr_t		*arc_adjust_zthr;
300*de753e34SBrad Lewis 
301*de753e34SBrad Lewis static kmutex_t		arc_adjust_lock;
302*de753e34SBrad Lewis static kcondvar_t	arc_adjust_waiters_cv;
303*de753e34SBrad Lewis static boolean_t	arc_adjust_needed = B_FALSE;
304244781f1SPrakash Surya 
3052ec99e3eSMatthew Ahrens uint_t arc_reduce_dnlc_percent = 3;
306fa9e4066Sahrens 
30769962b56SMatthew Ahrens /*
308244781f1SPrakash Surya  * The number of headers to evict in arc_evict_state_impl() before
309244781f1SPrakash Surya  * dropping the sublist lock and evicting from another sublist. A lower
310244781f1SPrakash Surya  * value means we're more likely to evict the "correct" header (i.e. the
311244781f1SPrakash Surya  * oldest header in the arc state), but comes with higher overhead
312244781f1SPrakash Surya  * (i.e. more invocations of arc_evict_state_impl()).
313244781f1SPrakash Surya  */
314244781f1SPrakash Surya int zfs_arc_evict_batch_limit = 10;
315244781f1SPrakash Surya 
316fa9e4066Sahrens /* number of seconds before growing cache again */
317*de753e34SBrad Lewis int arc_grow_retry = 60;
318fa9e4066Sahrens 
319*de753e34SBrad Lewis /*
320*de753e34SBrad Lewis  * Minimum time between calls to arc_kmem_reap_soon().  Note that this will
321*de753e34SBrad Lewis  * be converted to ticks, so with the default hz=100, a setting of 15 ms
322*de753e34SBrad Lewis  * will actually wait 2 ticks, or 20ms.
323*de753e34SBrad Lewis  */
324*de753e34SBrad Lewis int arc_kmem_cache_reap_retry_ms = 1000;
32536a64e62STim Kordas 
326770499e1SDan Kimmel /* shift of arc_c for calculating overflow limit in arc_get_data_impl */
327*de753e34SBrad Lewis int zfs_arc_overflow_shift = 8;
328244781f1SPrakash Surya 
3295a98e54bSBrendan Gregg - Sun Microsystems /* shift of arc_c for calculating both min and max arc_p */
330*de753e34SBrad Lewis int arc_p_min_shift = 4;
3315a98e54bSBrendan Gregg - Sun Microsystems 
3325a98e54bSBrendan Gregg - Sun Microsystems /* log2(fraction of arc to reclaim) */
333*de753e34SBrad Lewis int arc_shrink_shift = 7;
3342ec99e3eSMatthew Ahrens 
3352ec99e3eSMatthew Ahrens /*
3362ec99e3eSMatthew Ahrens  * log2(fraction of ARC which must be free to allow growing).
3372ec99e3eSMatthew Ahrens  * I.e. If there is less than arc_c >> arc_no_grow_shift free memory,
3382ec99e3eSMatthew Ahrens  * when reading a new block into the ARC, we will evict an equal-sized block
3392ec99e3eSMatthew Ahrens  * from the ARC.
3402ec99e3eSMatthew Ahrens  *
3412ec99e3eSMatthew Ahrens  * This must be less than arc_shrink_shift, so that when we shrink the ARC,
3422ec99e3eSMatthew Ahrens  * we will still not allow it to grow.
3432ec99e3eSMatthew Ahrens  */
3442ec99e3eSMatthew Ahrens int			arc_no_grow_shift = 5;
3452ec99e3eSMatthew Ahrens 
3465a98e54bSBrendan Gregg - Sun Microsystems 
34713506d1eSmaybee /*
348b19a79ecSperrin  * minimum lifespan of a prefetch block in clock ticks
349b19a79ecSperrin  * (initialized in arc_init())
35013506d1eSmaybee  */
351b19a79ecSperrin static int		arc_min_prefetch_lifespan;
35213506d1eSmaybee 
35369962b56SMatthew Ahrens /*
35469962b56SMatthew Ahrens  * If this percent of memory is free, don't throttle.
35569962b56SMatthew Ahrens  */
35669962b56SMatthew Ahrens int arc_lotsfree_percent = 10;
35769962b56SMatthew Ahrens 
358*de753e34SBrad Lewis static boolean_t arc_initialized;
359fa9e4066Sahrens 
3603a737e0dSbrendan /*
3613a737e0dSbrendan  * The arc has filled available memory and has now warmed up.
3623a737e0dSbrendan  */
3633a737e0dSbrendan static boolean_t arc_warm;
3643a737e0dSbrendan 
3650dd053d7SPrakash Surya /*
3660dd053d7SPrakash Surya  * log2 fraction of the zio arena to keep free.
3670dd053d7SPrakash Surya  */
3680dd053d7SPrakash Surya int arc_zio_arena_free_shift = 2;
3690dd053d7SPrakash Surya 
370a2eea2e1Sahrens /*
371a2eea2e1Sahrens  * These tunables are for performance analysis.
372a2eea2e1Sahrens  */
373a2eea2e1Sahrens uint64_t zfs_arc_max;
374a2eea2e1Sahrens uint64_t zfs_arc_min;
3751116048bSek uint64_t zfs_arc_meta_limit = 0;
3763a5286a1SMatthew Ahrens uint64_t zfs_arc_meta_min = 0;
3775a98e54bSBrendan Gregg - Sun Microsystems int zfs_arc_grow_retry = 0;
3785a98e54bSBrendan Gregg - Sun Microsystems int zfs_arc_shrink_shift = 0;
3795a98e54bSBrendan Gregg - Sun Microsystems int zfs_arc_p_min_shift = 0;
38063e911b6SMatthew Ahrens int zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
381a2eea2e1Sahrens 
382dcbf3bd6SGeorge Wilson boolean_t zfs_compressed_arc_enabled = B_TRUE;
383dcbf3bd6SGeorge Wilson 
384fa9e4066Sahrens /*
385fa94a07fSbrendan  * Note that buffers can be in one of 6 states:
386fa9e4066Sahrens  *	ARC_anon	- anonymous (discussed below)
387ea8dc4b6Seschrock  *	ARC_mru		- recently used, currently cached
388ea8dc4b6Seschrock  *	ARC_mru_ghost	- recentely used, no longer in cache
389ea8dc4b6Seschrock  *	ARC_mfu		- frequently used, currently cached
390ea8dc4b6Seschrock  *	ARC_mfu_ghost	- frequently used, no longer in cache
391fa94a07fSbrendan  *	ARC_l2c_only	- exists in L2ARC but not other states
3920e8c6158Smaybee  * When there are no active references to the buffer, they are
3930e8c6158Smaybee  * are linked onto a list in one of these arc states.  These are
3940e8c6158Smaybee  * the only buffers that can be evicted or deleted.  Within each
3950e8c6158Smaybee  * state there are multiple lists, one for meta-data and one for
3960e8c6158Smaybee  * non-meta-data.  Meta-data (indirect blocks, blocks of dnodes,
3970e8c6158Smaybee  * etc.) is tracked separately so that it can be managed more
398fa94a07fSbrendan  * explicitly: favored over data, limited explicitly.
399fa9e4066Sahrens  *
400fa9e4066Sahrens  * Anonymous buffers are buffers that are not associated with
401fa9e4066Sahrens  * a DVA.  These are buffers that hold dirty block copies
402fa9e4066Sahrens  * before they are written to stable storage.  By definition,
403ea8dc4b6Seschrock  * they are "ref'd" and are considered part of arc_mru
404fa9e4066Sahrens  * that cannot be freed.  Generally, they will aquire a DVA
405ea8dc4b6Seschrock  * as they are written and migrate onto the arc_mru list.
406fa94a07fSbrendan  *
407fa94a07fSbrendan  * The ARC_l2c_only state is for buffers that are in the second
408fa94a07fSbrendan  * level ARC but no longer in any of the ARC_m* lists.  The second
409fa94a07fSbrendan  * level ARC itself may also contain buffers that are in any of
410fa94a07fSbrendan  * the ARC_m* states - meaning that a buffer can exist in two
411fa94a07fSbrendan  * places.  The reason for the ARC_l2c_only state is to keep the
412fa94a07fSbrendan  * buffer header in the hash table, so that reads that hit the
413fa94a07fSbrendan  * second level ARC benefit from these fast lookups.
414fa9e4066Sahrens  */
415fa9e4066Sahrens 
416fa9e4066Sahrens typedef struct arc_state {
417244781f1SPrakash Surya 	/*
418244781f1SPrakash Surya 	 * list of evictable buffers
419244781f1SPrakash Surya 	 */
42094c2d0ebSMatthew Ahrens 	multilist_t *arcs_list[ARC_BUFC_NUMTYPES];
421244781f1SPrakash Surya 	/*
422244781f1SPrakash Surya 	 * total amount of evictable data in this state
423244781f1SPrakash Surya 	 */
424dcbf3bd6SGeorge Wilson 	refcount_t arcs_esize[ARC_BUFC_NUMTYPES];
425244781f1SPrakash Surya 	/*
426244781f1SPrakash Surya 	 * total amount of data in this state; this includes: evictable,
427244781f1SPrakash Surya 	 * non-evictable, ARC_BUFC_DATA, and ARC_BUFC_METADATA.
428244781f1SPrakash Surya 	 */
4292fd872a7SPrakash Surya 	refcount_t arcs_size;
430fa9e4066Sahrens } arc_state_t;
431fa9e4066Sahrens 
432fa94a07fSbrendan /* The 6 states: */
433fa9e4066Sahrens static arc_state_t ARC_anon;
434ea8dc4b6Seschrock static arc_state_t ARC_mru;
435ea8dc4b6Seschrock static arc_state_t ARC_mru_ghost;
436ea8dc4b6Seschrock static arc_state_t ARC_mfu;
437ea8dc4b6Seschrock static arc_state_t ARC_mfu_ghost;
438fa94a07fSbrendan static arc_state_t ARC_l2c_only;
439fa9e4066Sahrens 
44044cb6abcSbmc typedef struct arc_stats {
44144cb6abcSbmc 	kstat_named_t arcstat_hits;
44244cb6abcSbmc 	kstat_named_t arcstat_misses;
44344cb6abcSbmc 	kstat_named_t arcstat_demand_data_hits;
44444cb6abcSbmc 	kstat_named_t arcstat_demand_data_misses;
44544cb6abcSbmc 	kstat_named_t arcstat_demand_metadata_hits;
44644cb6abcSbmc 	kstat_named_t arcstat_demand_metadata_misses;
44744cb6abcSbmc 	kstat_named_t arcstat_prefetch_data_hits;
44844cb6abcSbmc 	kstat_named_t arcstat_prefetch_data_misses;
44944cb6abcSbmc 	kstat_named_t arcstat_prefetch_metadata_hits;
45044cb6abcSbmc 	kstat_named_t arcstat_prefetch_metadata_misses;
45144cb6abcSbmc 	kstat_named_t arcstat_mru_hits;
45244cb6abcSbmc 	kstat_named_t arcstat_mru_ghost_hits;
45344cb6abcSbmc 	kstat_named_t arcstat_mfu_hits;
45444cb6abcSbmc 	kstat_named_t arcstat_mfu_ghost_hits;
45544cb6abcSbmc 	kstat_named_t arcstat_deleted;
4563e30c24aSWill Andrews 	/*
4573e30c24aSWill Andrews 	 * Number of buffers that could not be evicted because the hash lock
4583e30c24aSWill Andrews 	 * was held by another thread.  The lock may not necessarily be held
4593e30c24aSWill Andrews 	 * by something using the same buffer, since hash locks are shared
4603e30c24aSWill Andrews 	 * by multiple buffers.
4613e30c24aSWill Andrews 	 */
46244cb6abcSbmc 	kstat_named_t arcstat_mutex_miss;
4633e30c24aSWill Andrews 	/*
4643e30c24aSWill Andrews 	 * Number of buffers skipped because they have I/O in progress, are
4653e30c24aSWill Andrews 	 * indrect prefetch buffers that have not lived long enough, or are
4663e30c24aSWill Andrews 	 * not from the spa we're trying to evict from.
4673e30c24aSWill Andrews 	 */
46844cb6abcSbmc 	kstat_named_t arcstat_evict_skip;
469244781f1SPrakash Surya 	/*
470244781f1SPrakash Surya 	 * Number of times arc_evict_state() was unable to evict enough
471244781f1SPrakash Surya 	 * buffers to reach it's target amount.
472244781f1SPrakash Surya 	 */
473244781f1SPrakash Surya 	kstat_named_t arcstat_evict_not_enough;
4745ea40c06SBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_evict_l2_cached;
4755ea40c06SBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_evict_l2_eligible;
4765ea40c06SBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_evict_l2_ineligible;
477244781f1SPrakash Surya 	kstat_named_t arcstat_evict_l2_skip;
47844cb6abcSbmc 	kstat_named_t arcstat_hash_elements;
47944cb6abcSbmc 	kstat_named_t arcstat_hash_elements_max;
48044cb6abcSbmc 	kstat_named_t arcstat_hash_collisions;
48144cb6abcSbmc 	kstat_named_t arcstat_hash_chains;
48244cb6abcSbmc 	kstat_named_t arcstat_hash_chain_max;
48344cb6abcSbmc 	kstat_named_t arcstat_p;
48444cb6abcSbmc 	kstat_named_t arcstat_c;
48544cb6abcSbmc 	kstat_named_t arcstat_c_min;
48644cb6abcSbmc 	kstat_named_t arcstat_c_max;
4873a2d8a1bSPaul Dagnelie 	/* Not updated directly; only synced in arc_kstat_update. */
48844cb6abcSbmc 	kstat_named_t arcstat_size;
489dcbf3bd6SGeorge Wilson 	/*
490770499e1SDan Kimmel 	 * Number of compressed bytes stored in the arc_buf_hdr_t's b_pabd.
491dcbf3bd6SGeorge Wilson 	 * Note that the compressed bytes may match the uncompressed bytes
492dcbf3bd6SGeorge Wilson 	 * if the block is either not compressed or compressed arc is disabled.
493dcbf3bd6SGeorge Wilson 	 */
494dcbf3bd6SGeorge Wilson 	kstat_named_t arcstat_compressed_size;
495dcbf3bd6SGeorge Wilson 	/*
496770499e1SDan Kimmel 	 * Uncompressed size of the data stored in b_pabd. If compressed
497dcbf3bd6SGeorge Wilson 	 * arc is disabled then this value will be identical to the stat
498dcbf3bd6SGeorge Wilson 	 * above.
499dcbf3bd6SGeorge Wilson 	 */
500dcbf3bd6SGeorge Wilson 	kstat_named_t arcstat_uncompressed_size;
501dcbf3bd6SGeorge Wilson 	/*
502dcbf3bd6SGeorge Wilson 	 * Number of bytes stored in all the arc_buf_t's. This is classified
503dcbf3bd6SGeorge Wilson 	 * as "overhead" since this data is typically short-lived and will
504dcbf3bd6SGeorge Wilson 	 * be evicted from the arc when it becomes unreferenced unless the
505dcbf3bd6SGeorge Wilson 	 * zfs_keep_uncompressed_metadata or zfs_keep_uncompressed_level
506dcbf3bd6SGeorge Wilson 	 * values have been set (see comment in dbuf.c for more information).
507dcbf3bd6SGeorge Wilson 	 */
508dcbf3bd6SGeorge Wilson 	kstat_named_t arcstat_overhead_size;
5094076b1bfSPrakash Surya 	/*
5104076b1bfSPrakash Surya 	 * Number of bytes consumed by internal ARC structures necessary
5114076b1bfSPrakash Surya 	 * for tracking purposes; these structures are not actually
5124076b1bfSPrakash Surya 	 * backed by ARC buffers. This includes arc_buf_hdr_t structures
5134076b1bfSPrakash Surya 	 * (allocated via arc_buf_hdr_t_full and arc_buf_hdr_t_l2only
5144076b1bfSPrakash Surya 	 * caches), and arc_buf_t structures (allocated via arc_buf_t
5154076b1bfSPrakash Surya 	 * cache).
5163a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5174076b1bfSPrakash Surya 	 */
518fa94a07fSbrendan 	kstat_named_t arcstat_hdr_size;
5194076b1bfSPrakash Surya 	/*
5204076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers of type equal to
5214076b1bfSPrakash Surya 	 * ARC_BUFC_DATA. This is generally consumed by buffers backing
5224076b1bfSPrakash Surya 	 * on disk user data (e.g. plain file contents).
5233a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5244076b1bfSPrakash Surya 	 */
5255a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_data_size;
5264076b1bfSPrakash Surya 	/*
5274076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers of type equal to
5284076b1bfSPrakash Surya 	 * ARC_BUFC_METADATA. This is generally consumed by buffers
5294076b1bfSPrakash Surya 	 * backing on disk data that is used for internal ZFS
5304076b1bfSPrakash Surya 	 * structures (e.g. ZAP, dnode, indirect blocks, etc).
5313a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5324076b1bfSPrakash Surya 	 */
5334076b1bfSPrakash Surya 	kstat_named_t arcstat_metadata_size;
5344076b1bfSPrakash Surya 	/*
5354076b1bfSPrakash Surya 	 * Number of bytes consumed by various buffers and structures
5364076b1bfSPrakash Surya 	 * not actually backed with ARC buffers. This includes bonus
5374076b1bfSPrakash Surya 	 * buffers (allocated directly via zio_buf_* functions),
5384076b1bfSPrakash Surya 	 * dmu_buf_impl_t structures (allocated via dmu_buf_impl_t
5394076b1bfSPrakash Surya 	 * cache), and dnode_t structures (allocated via dnode_t cache).
5403a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5414076b1bfSPrakash Surya 	 */
5425a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_other_size;
5434076b1bfSPrakash Surya 	/*
5444076b1bfSPrakash Surya 	 * Total number of bytes consumed by ARC buffers residing in the
5454076b1bfSPrakash Surya 	 * arc_anon state. This includes *all* buffers in the arc_anon
5464076b1bfSPrakash Surya 	 * state; e.g. data, metadata, evictable, and unevictable buffers
5474076b1bfSPrakash Surya 	 * are all included in this value.
5483a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5494076b1bfSPrakash Surya 	 */
5504076b1bfSPrakash Surya 	kstat_named_t arcstat_anon_size;
5514076b1bfSPrakash Surya 	/*
5524076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
5534076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_DATA,
5544076b1bfSPrakash Surya 	 * residing in the arc_anon state, and are eligible for eviction
5554076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
5563a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5574076b1bfSPrakash Surya 	 */
5584076b1bfSPrakash Surya 	kstat_named_t arcstat_anon_evictable_data;
5594076b1bfSPrakash Surya 	/*
5604076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
5614076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_METADATA,
5624076b1bfSPrakash Surya 	 * residing in the arc_anon state, and are eligible for eviction
5634076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
5643a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5654076b1bfSPrakash Surya 	 */
5664076b1bfSPrakash Surya 	kstat_named_t arcstat_anon_evictable_metadata;
5674076b1bfSPrakash Surya 	/*
5684076b1bfSPrakash Surya 	 * Total number of bytes consumed by ARC buffers residing in the
5694076b1bfSPrakash Surya 	 * arc_mru state. This includes *all* buffers in the arc_mru
5704076b1bfSPrakash Surya 	 * state; e.g. data, metadata, evictable, and unevictable buffers
5714076b1bfSPrakash Surya 	 * are all included in this value.
5723a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5734076b1bfSPrakash Surya 	 */
5744076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_size;
5754076b1bfSPrakash Surya 	/*
5764076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
5774076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_DATA,
5784076b1bfSPrakash Surya 	 * residing in the arc_mru state, and are eligible for eviction
5794076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
5803a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5814076b1bfSPrakash Surya 	 */
5824076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_evictable_data;
5834076b1bfSPrakash Surya 	/*
5844076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
5854076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_METADATA,
5864076b1bfSPrakash Surya 	 * residing in the arc_mru state, and are eligible for eviction
5874076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
5883a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5894076b1bfSPrakash Surya 	 */
5904076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_evictable_metadata;
5914076b1bfSPrakash Surya 	/*
5924076b1bfSPrakash Surya 	 * Total number of bytes that *would have been* consumed by ARC
5934076b1bfSPrakash Surya 	 * buffers in the arc_mru_ghost state. The key thing to note
5944076b1bfSPrakash Surya 	 * here, is the fact that this size doesn't actually indicate
5954076b1bfSPrakash Surya 	 * RAM consumption. The ghost lists only consist of headers and
5964076b1bfSPrakash Surya 	 * don't actually have ARC buffers linked off of these headers.
5974076b1bfSPrakash Surya 	 * Thus, *if* the headers had associated ARC buffers, these
5984076b1bfSPrakash Surya 	 * buffers *would have* consumed this number of bytes.
5993a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6004076b1bfSPrakash Surya 	 */
6014076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_ghost_size;
6024076b1bfSPrakash Surya 	/*
6034076b1bfSPrakash Surya 	 * Number of bytes that *would have been* consumed by ARC
6044076b1bfSPrakash Surya 	 * buffers that are eligible for eviction, of type
6054076b1bfSPrakash Surya 	 * ARC_BUFC_DATA, and linked off the arc_mru_ghost state.
6063a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6074076b1bfSPrakash Surya 	 */
6084076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_ghost_evictable_data;
6094076b1bfSPrakash Surya 	/*
6104076b1bfSPrakash Surya 	 * Number of bytes that *would have been* consumed by ARC
6114076b1bfSPrakash Surya 	 * buffers that are eligible for eviction, of type
6124076b1bfSPrakash Surya 	 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
6133a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6144076b1bfSPrakash Surya 	 */
6154076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_ghost_evictable_metadata;
6164076b1bfSPrakash Surya 	/*
6174076b1bfSPrakash Surya 	 * Total number of bytes consumed by ARC buffers residing in the
6184076b1bfSPrakash Surya 	 * arc_mfu state. This includes *all* buffers in the arc_mfu
6194076b1bfSPrakash Surya 	 * state; e.g. data, metadata, evictable, and unevictable buffers
6204076b1bfSPrakash Surya 	 * are all included in this value.
6213a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6224076b1bfSPrakash Surya 	 */
6234076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_size;
6244076b1bfSPrakash Surya 	/*
6254076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that are eligible for
6264076b1bfSPrakash Surya 	 * eviction, of type ARC_BUFC_DATA, and reside in the arc_mfu
6274076b1bfSPrakash Surya 	 * state.
6283a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6294076b1bfSPrakash Surya 	 */
6304076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_evictable_data;
6314076b1bfSPrakash Surya 	/*
6324076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that are eligible for
6334076b1bfSPrakash Surya 	 * eviction, of type ARC_BUFC_METADATA, and reside in the
6344076b1bfSPrakash Surya 	 * arc_mfu state.
6353a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6364076b1bfSPrakash Surya 	 */
6374076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_evictable_metadata;
6384076b1bfSPrakash Surya 	/*
6394076b1bfSPrakash Surya 	 * Total number of bytes that *would have been* consumed by ARC
6404076b1bfSPrakash Surya 	 * buffers in the arc_mfu_ghost state. See the comment above
6414076b1bfSPrakash Surya 	 * arcstat_mru_ghost_size for more details.
6423a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6434076b1bfSPrakash Surya 	 */
6444076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_ghost_size;
6454076b1bfSPrakash Surya 	/*
6464076b1bfSPrakash Surya 	 * Number of bytes that *would have been* consumed by ARC
6474076b1bfSPrakash Surya 	 * buffers that are eligible for eviction, of type
6484076b1bfSPrakash Surya 	 * ARC_BUFC_DATA, and linked off the arc_mfu_ghost state.
6493a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6504076b1bfSPrakash Surya 	 */
6514076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_ghost_evictable_data;
6524076b1bfSPrakash Surya 	/*
6534076b1bfSPrakash Surya 	 * Number of bytes that *would have been* consumed by ARC
6544076b1bfSPrakash Surya 	 * buffers that are eligible for eviction, of type
6554076b1bfSPrakash Surya 	 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
6563a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6574076b1bfSPrakash Surya 	 */
6584076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_ghost_evictable_metadata;
659fa94a07fSbrendan 	kstat_named_t arcstat_l2_hits;
660fa94a07fSbrendan 	kstat_named_t arcstat_l2_misses;
661fa94a07fSbrendan 	kstat_named_t arcstat_l2_feeds;
662fa94a07fSbrendan 	kstat_named_t arcstat_l2_rw_clash;
6635a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_l2_read_bytes;
6645a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_l2_write_bytes;
665fa94a07fSbrendan 	kstat_named_t arcstat_l2_writes_sent;
666fa94a07fSbrendan 	kstat_named_t arcstat_l2_writes_done;
667fa94a07fSbrendan 	kstat_named_t arcstat_l2_writes_error;
668244781f1SPrakash Surya 	kstat_named_t arcstat_l2_writes_lock_retry;
669fa94a07fSbrendan 	kstat_named_t arcstat_l2_evict_lock_retry;
670fa94a07fSbrendan 	kstat_named_t arcstat_l2_evict_reading;
67189c86e32SChris Williamson 	kstat_named_t arcstat_l2_evict_l1cached;
672fa94a07fSbrendan 	kstat_named_t arcstat_l2_free_on_write;
673fa94a07fSbrendan 	kstat_named_t arcstat_l2_abort_lowmem;
674fa94a07fSbrendan 	kstat_named_t arcstat_l2_cksum_bad;
675fa94a07fSbrendan 	kstat_named_t arcstat_l2_io_error;
67616a7e5acSAndriy Gapon 	kstat_named_t arcstat_l2_lsize;
67716a7e5acSAndriy Gapon 	kstat_named_t arcstat_l2_psize;
6783a2d8a1bSPaul Dagnelie 	/* Not updated directly; only synced in arc_kstat_update. */
679fa94a07fSbrendan 	kstat_named_t arcstat_l2_hdr_size;
6801ab7f2deSmaybee 	kstat_named_t arcstat_memory_throttle_count;
6813a2d8a1bSPaul Dagnelie 	/* Not updated directly; only synced in arc_kstat_update. */
68220128a08SGeorge Wilson 	kstat_named_t arcstat_meta_used;
68320128a08SGeorge Wilson 	kstat_named_t arcstat_meta_limit;
68420128a08SGeorge Wilson 	kstat_named_t arcstat_meta_max;
6853a5286a1SMatthew Ahrens 	kstat_named_t arcstat_meta_min;
686cf6106c8SMatthew Ahrens 	kstat_named_t arcstat_sync_wait_for_async;
687cf6106c8SMatthew Ahrens 	kstat_named_t arcstat_demand_hit_predictive_prefetch;
68844cb6abcSbmc } arc_stats_t;
68944cb6abcSbmc 
69044cb6abcSbmc static arc_stats_t arc_stats = {
69144cb6abcSbmc 	{ "hits",			KSTAT_DATA_UINT64 },
69244cb6abcSbmc 	{ "misses",			KSTAT_DATA_UINT64 },
69344cb6abcSbmc 	{ "demand_data_hits",		KSTAT_DATA_UINT64 },
69444cb6abcSbmc 	{ "demand_data_misses",		KSTAT_DATA_UINT64 },
69544cb6abcSbmc 	{ "demand_metadata_hits",	KSTAT_DATA_UINT64 },
69644cb6abcSbmc 	{ "demand_metadata_misses",	KSTAT_DATA_UINT64 },
69744cb6abcSbmc 	{ "prefetch_data_hits",		KSTAT_DATA_UINT64 },
69844cb6abcSbmc 	{ "prefetch_data_misses",	KSTAT_DATA_UINT64 },
69944cb6abcSbmc 	{ "prefetch_metadata_hits",	KSTAT_DATA_UINT64 },
70044cb6abcSbmc 	{ "prefetch_metadata_misses",	KSTAT_DATA_UINT64 },
70144cb6abcSbmc 	{ "mru_hits",			KSTAT_DATA_UINT64 },
70244cb6abcSbmc 	{ "mru_ghost_hits",		KSTAT_DATA_UINT64 },
70344cb6abcSbmc 	{ "mfu_hits",			KSTAT_DATA_UINT64 },
70444cb6abcSbmc 	{ "mfu_ghost_hits",		KSTAT_DATA_UINT64 },
70544cb6abcSbmc 	{ "deleted",			KSTAT_DATA_UINT64 },
70644cb6abcSbmc 	{ "mutex_miss",			KSTAT_DATA_UINT64 },
70744cb6abcSbmc 	{ "evict_skip",			KSTAT_DATA_UINT64 },
708244781f1SPrakash Surya 	{ "evict_not_enough",		KSTAT_DATA_UINT64 },
7095ea40c06SBrendan Gregg - Sun Microsystems 	{ "evict_l2_cached",		KSTAT_DATA_UINT64 },
7105ea40c06SBrendan Gregg - Sun Microsystems 	{ "evict_l2_eligible",		KSTAT_DATA_UINT64 },
7115ea40c06SBrendan Gregg - Sun Microsystems 	{ "evict_l2_ineligible",	KSTAT_DATA_UINT64 },
712244781f1SPrakash Surya 	{ "evict_l2_skip",		KSTAT_DATA_UINT64 },
71344cb6abcSbmc 	{ "hash_elements",		KSTAT_DATA_UINT64 },
71444cb6abcSbmc 	{ "hash_elements_max",		KSTAT_DATA_UINT64 },
71544cb6abcSbmc 	{ "hash_collisions",		KSTAT_DATA_UINT64 },
71644cb6abcSbmc 	{ "hash_chains",		KSTAT_DATA_UINT64 },
71744cb6abcSbmc 	{ "hash_chain_max",		KSTAT_DATA_UINT64 },
71844cb6abcSbmc 	{ "p",				KSTAT_DATA_UINT64 },
71944cb6abcSbmc 	{ "c",				KSTAT_DATA_UINT64 },
72044cb6abcSbmc 	{ "c_min",			KSTAT_DATA_UINT64 },
72144cb6abcSbmc 	{ "c_max",			KSTAT_DATA_UINT64 },
722fa94a07fSbrendan 	{ "size",			KSTAT_DATA_UINT64 },
723dcbf3bd6SGeorge Wilson 	{ "compressed_size",		KSTAT_DATA_UINT64 },
724dcbf3bd6SGeorge Wilson 	{ "uncompressed_size",		KSTAT_DATA_UINT64 },
725dcbf3bd6SGeorge Wilson 	{ "overhead_size",		KSTAT_DATA_UINT64 },
726fa94a07fSbrendan 	{ "hdr_size",			KSTAT_DATA_UINT64 },
7275a98e54bSBrendan Gregg - Sun Microsystems 	{ "data_size",			KSTAT_DATA_UINT64 },
7284076b1bfSPrakash Surya 	{ "metadata_size",		KSTAT_DATA_UINT64 },
7295a98e54bSBrendan Gregg - Sun Microsystems 	{ "other_size",			KSTAT_DATA_UINT64 },
7304076b1bfSPrakash Surya 	{ "anon_size",			KSTAT_DATA_UINT64 },
7314076b1bfSPrakash Surya 	{ "anon_evictable_data",	KSTAT_DATA_UINT64 },
7324076b1bfSPrakash Surya 	{ "anon_evictable_metadata",	KSTAT_DATA_UINT64 },
7334076b1bfSPrakash Surya 	{ "mru_size",			KSTAT_DATA_UINT64 },
7344076b1bfSPrakash Surya 	{ "mru_evictable_data",		KSTAT_DATA_UINT64 },
7354076b1bfSPrakash Surya 	{ "mru_evictable_metadata",	KSTAT_DATA_UINT64 },
7364076b1bfSPrakash Surya 	{ "mru_ghost_size",		KSTAT_DATA_UINT64 },
7374076b1bfSPrakash Surya 	{ "mru_ghost_evictable_data",	KSTAT_DATA_UINT64 },
7384076b1bfSPrakash Surya 	{ "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
7394076b1bfSPrakash Surya 	{ "mfu_size",			KSTAT_DATA_UINT64 },
7404076b1bfSPrakash Surya 	{ "mfu_evictable_data",		KSTAT_DATA_UINT64 },
7414076b1bfSPrakash Surya 	{ "mfu_evictable_metadata",	KSTAT_DATA_UINT64 },
7424076b1bfSPrakash Surya 	{ "mfu_ghost_size",		KSTAT_DATA_UINT64 },
7434076b1bfSPrakash Surya 	{ "mfu_ghost_evictable_data",	KSTAT_DATA_UINT64 },
7444076b1bfSPrakash Surya 	{ "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
745fa94a07fSbrendan 	{ "l2_hits",			KSTAT_DATA_UINT64 },
746fa94a07fSbrendan 	{ "l2_misses",			KSTAT_DATA_UINT64 },
747fa94a07fSbrendan 	{ "l2_feeds",			KSTAT_DATA_UINT64 },
748fa94a07fSbrendan 	{ "l2_rw_clash",		KSTAT_DATA_UINT64 },
7495a98e54bSBrendan Gregg - Sun Microsystems 	{ "l2_read_bytes",		KSTAT_DATA_UINT64 },
7505a98e54bSBrendan Gregg - Sun Microsystems 	{ "l2_write_bytes",		KSTAT_DATA_UINT64 },
751fa94a07fSbrendan 	{ "l2_writes_sent",		KSTAT_DATA_UINT64 },
752fa94a07fSbrendan 	{ "l2_writes_done",		KSTAT_DATA_UINT64 },
753fa94a07fSbrendan 	{ "l2_writes_error",		KSTAT_DATA_UINT64 },
754244781f1SPrakash Surya 	{ "l2_writes_lock_retry",	KSTAT_DATA_UINT64 },
755fa94a07fSbrendan 	{ "l2_evict_lock_retry",	KSTAT_DATA_UINT64 },
756fa94a07fSbrendan 	{ "l2_evict_reading",		KSTAT_DATA_UINT64 },
75789c86e32SChris Williamson 	{ "l2_evict_l1cached",		KSTAT_DATA_UINT64 },
758fa94a07fSbrendan 	{ "l2_free_on_write",		KSTAT_DATA_UINT64 },
759fa94a07fSbrendan 	{ "l2_abort_lowmem",		KSTAT_DATA_UINT64 },
760fa94a07fSbrendan 	{ "l2_cksum_bad",		KSTAT_DATA_UINT64 },
761fa94a07fSbrendan 	{ "l2_io_error",		KSTAT_DATA_UINT64 },
762fa94a07fSbrendan 	{ "l2_size",			KSTAT_DATA_UINT64 },
763aad02571SSaso Kiselkov 	{ "l2_asize",			KSTAT_DATA_UINT64 },
7641ab7f2deSmaybee 	{ "l2_hdr_size",		KSTAT_DATA_UINT64 },
7659253d63dSGeorge Wilson 	{ "memory_throttle_count",	KSTAT_DATA_UINT64 },
76620128a08SGeorge Wilson 	{ "arc_meta_used",		KSTAT_DATA_UINT64 },
76720128a08SGeorge Wilson 	{ "arc_meta_limit",		KSTAT_DATA_UINT64 },
7683a5286a1SMatthew Ahrens 	{ "arc_meta_max",		KSTAT_DATA_UINT64 },
769cf6106c8SMatthew Ahrens 	{ "arc_meta_min",		KSTAT_DATA_UINT64 },
770cf6106c8SMatthew Ahrens 	{ "sync_wait_for_async",	KSTAT_DATA_UINT64 },
771cf6106c8SMatthew Ahrens 	{ "demand_hit_predictive_prefetch", KSTAT_DATA_UINT64 },
77244cb6abcSbmc };
77344cb6abcSbmc 
77444cb6abcSbmc #define	ARCSTAT(stat)	(arc_stats.stat.value.ui64)
77544cb6abcSbmc 
77644cb6abcSbmc #define	ARCSTAT_INCR(stat, val) \
777f7170741SWill Andrews 	atomic_add_64(&arc_stats.stat.value.ui64, (val))
77844cb6abcSbmc 
779b24ab676SJeff Bonwick #define	ARCSTAT_BUMP(stat)	ARCSTAT_INCR(stat, 1)
78044cb6abcSbmc #define	ARCSTAT_BUMPDOWN(stat)	ARCSTAT_INCR(stat, -1)
78144cb6abcSbmc 
78244cb6abcSbmc #define	ARCSTAT_MAX(stat, val) {					\
78344cb6abcSbmc 	uint64_t m;							\
78444cb6abcSbmc 	while ((val) > (m = arc_stats.stat.value.ui64) &&		\
78544cb6abcSbmc 	    (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val))))	\
78644cb6abcSbmc 		continue;						\
78744cb6abcSbmc }
78844cb6abcSbmc 
78944cb6abcSbmc #define	ARCSTAT_MAXSTAT(stat) \
79044cb6abcSbmc 	ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
79144cb6abcSbmc 
79244cb6abcSbmc /*
79344cb6abcSbmc  * We define a macro to allow ARC hits/misses to be easily broken down by
79444cb6abcSbmc  * two separate conditions, giving a total of four different subtypes for
79544cb6abcSbmc  * each of hits and misses (so eight statistics total).
79644cb6abcSbmc  */
79744cb6abcSbmc #define	ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
79844cb6abcSbmc 	if (cond1) {							\
79944cb6abcSbmc 		if (cond2) {						\
80044cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
80144cb6abcSbmc 		} else {						\
80244cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
80344cb6abcSbmc 		}							\
80444cb6abcSbmc 	} else {							\
80544cb6abcSbmc 		if (cond2) {						\
80644cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
80744cb6abcSbmc 		} else {						\
80844cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
80944cb6abcSbmc 		}							\
81044cb6abcSbmc 	}
81144cb6abcSbmc 
81244cb6abcSbmc kstat_t			*arc_ksp;
813b24ab676SJeff Bonwick static arc_state_t	*arc_anon;
81444cb6abcSbmc static arc_state_t	*arc_mru;
81544cb6abcSbmc static arc_state_t	*arc_mru_ghost;
81644cb6abcSbmc static arc_state_t	*arc_mfu;
81744cb6abcSbmc static arc_state_t	*arc_mfu_ghost;
818fa94a07fSbrendan static arc_state_t	*arc_l2c_only;
81944cb6abcSbmc 
82044cb6abcSbmc /*
82144cb6abcSbmc  * There are several ARC variables that are critical to export as kstats --
82244cb6abcSbmc  * but we don't want to have to grovel around in the kstat whenever we wish to
82344cb6abcSbmc  * manipulate them.  For these variables, we therefore define them to be in
82444cb6abcSbmc  * terms of the statistic variable.  This assures that we are not introducing
82544cb6abcSbmc  * the possibility of inconsistency by having shadow copies of the variables,
82644cb6abcSbmc  * while still allowing the code to be readable.
82744cb6abcSbmc  */
82844cb6abcSbmc #define	arc_p		ARCSTAT(arcstat_p)	/* target size of MRU */
82944cb6abcSbmc #define	arc_c		ARCSTAT(arcstat_c)	/* target size of cache */
83044cb6abcSbmc #define	arc_c_min	ARCSTAT(arcstat_c_min)	/* min target cache size */
83144cb6abcSbmc #define	arc_c_max	ARCSTAT(arcstat_c_max)	/* max target cache size */
83220128a08SGeorge Wilson #define	arc_meta_limit	ARCSTAT(arcstat_meta_limit) /* max size for metadata */
8333a5286a1SMatthew Ahrens #define	arc_meta_min	ARCSTAT(arcstat_meta_min) /* min size for metadata */
83420128a08SGeorge Wilson #define	arc_meta_max	ARCSTAT(arcstat_meta_max) /* max size of metadata */
83544cb6abcSbmc 
836dcbf3bd6SGeorge Wilson /* compressed size of entire arc */
837dcbf3bd6SGeorge Wilson #define	arc_compressed_size	ARCSTAT(arcstat_compressed_size)
838dcbf3bd6SGeorge Wilson /* uncompressed size of entire arc */
839dcbf3bd6SGeorge Wilson #define	arc_uncompressed_size	ARCSTAT(arcstat_uncompressed_size)
840dcbf3bd6SGeorge Wilson /* number of bytes in the arc from arc_buf_t's */
841dcbf3bd6SGeorge Wilson #define	arc_overhead_size	ARCSTAT(arcstat_overhead_size)
842aad02571SSaso Kiselkov 
8433a2d8a1bSPaul Dagnelie /*
8443a2d8a1bSPaul Dagnelie  * There are also some ARC variables that we want to export, but that are
8453a2d8a1bSPaul Dagnelie  * updated so often that having the canonical representation be the statistic
8463a2d8a1bSPaul Dagnelie  * variable causes a performance bottleneck. We want to use aggsum_t's for these
8473a2d8a1bSPaul Dagnelie  * instead, but still be able to export the kstat in the same way as before.
8483a2d8a1bSPaul Dagnelie  * The solution is to always use the aggsum version, except in the kstat update
8493a2d8a1bSPaul Dagnelie  * callback.
8503a2d8a1bSPaul Dagnelie  */
8513a2d8a1bSPaul Dagnelie aggsum_t arc_size;
8523a2d8a1bSPaul Dagnelie aggsum_t arc_meta_used;
8533a2d8a1bSPaul Dagnelie aggsum_t astat_data_size;
8543a2d8a1bSPaul Dagnelie aggsum_t astat_metadata_size;
8553a2d8a1bSPaul Dagnelie aggsum_t astat_hdr_size;
8563a2d8a1bSPaul Dagnelie aggsum_t astat_other_size;
8573a2d8a1bSPaul Dagnelie aggsum_t astat_l2_hdr_size;
8583a2d8a1bSPaul Dagnelie 
85944cb6abcSbmc static int		arc_no_grow;	/* Don't try to grow cache size */
860*de753e34SBrad Lewis static hrtime_t		arc_growtime;
86144cb6abcSbmc static uint64_t		arc_tempreserve;
8622fdbea25SAleksandr Guzovskiy static uint64_t		arc_loaned_bytes;
863fa9e4066Sahrens 
864fa9e4066Sahrens typedef struct arc_callback arc_callback_t;
865fa9e4066Sahrens 
866fa9e4066Sahrens struct arc_callback {
867fa9e4066Sahrens 	void			*acb_private;
868c717a561Smaybee 	arc_done_func_t		*acb_done;
869fa9e4066Sahrens 	arc_buf_t		*acb_buf;
8705602294fSDan Kimmel 	boolean_t		acb_compressed;
871fa9e4066Sahrens 	zio_t			*acb_zio_dummy;
872fa9e4066Sahrens 	arc_callback_t		*acb_next;
873fa9e4066Sahrens };
874fa9e4066Sahrens 
875c717a561Smaybee typedef struct arc_write_callback arc_write_callback_t;
876c717a561Smaybee 
877c717a561Smaybee struct arc_write_callback {
878c717a561Smaybee 	void		*awcb_private;
879c717a561Smaybee 	arc_done_func_t	*awcb_ready;
8808df0bcf0SPaul Dagnelie 	arc_done_func_t	*awcb_children_ready;
88169962b56SMatthew Ahrens 	arc_done_func_t	*awcb_physdone;
882c717a561Smaybee 	arc_done_func_t	*awcb_done;
883c717a561Smaybee 	arc_buf_t	*awcb_buf;
884c717a561Smaybee };
885c717a561Smaybee 
88689c86e32SChris Williamson /*
88789c86e32SChris Williamson  * ARC buffers are separated into multiple structs as a memory saving measure:
88889c86e32SChris Williamson  *   - Common fields struct, always defined, and embedded within it:
88989c86e32SChris Williamson  *       - L2-only fields, always allocated but undefined when not in L2ARC
89089c86e32SChris Williamson  *       - L1-only fields, only allocated when in L1ARC
89189c86e32SChris Williamson  *
89289c86e32SChris Williamson  *           Buffer in L1                     Buffer only in L2
89389c86e32SChris Williamson  *    +------------------------+          +------------------------+
89489c86e32SChris Williamson  *    | arc_buf_hdr_t          |          | arc_buf_hdr_t          |
89589c86e32SChris Williamson  *    |                        |          |                        |
89689c86e32SChris Williamson  *    |                        |          |                        |
89789c86e32SChris Williamson  *    |                        |          |                        |
89889c86e32SChris Williamson  *    +------------------------+          +------------------------+
89989c86e32SChris Williamson  *    | l2arc_buf_hdr_t        |          | l2arc_buf_hdr_t        |
90089c86e32SChris Williamson  *    | (undefined if L1-only) |          |                        |
90189c86e32SChris Williamson  *    +------------------------+          +------------------------+
90289c86e32SChris Williamson  *    | l1arc_buf_hdr_t        |
90389c86e32SChris Williamson  *    |                        |
90489c86e32SChris Williamson  *    |                        |
90589c86e32SChris Williamson  *    |                        |
90689c86e32SChris Williamson  *    |                        |
90789c86e32SChris Williamson  *    +------------------------+
90889c86e32SChris Williamson  *
90989c86e32SChris Williamson  * Because it's possible for the L2ARC to become extremely large, we can wind
91089c86e32SChris Williamson  * up eating a lot of memory in L2ARC buffer headers, so the size of a header
91189c86e32SChris Williamson  * is minimized by only allocating the fields necessary for an L1-cached buffer
91289c86e32SChris Williamson  * when a header is actually in the L1 cache. The sub-headers (l1arc_buf_hdr and
91389c86e32SChris Williamson  * l2arc_buf_hdr) are embedded rather than allocated separately to save a couple
91489c86e32SChris Williamson  * words in pointers. arc_hdr_realloc() is used to switch a header between
91589c86e32SChris Williamson  * these two allocation states.
91689c86e32SChris Williamson  */
91789c86e32SChris Williamson typedef struct l1arc_buf_hdr {
9186b4acc8bSahrens 	kmutex_t		b_freeze_lock;
919dcbf3bd6SGeorge Wilson 	zio_cksum_t		*b_freeze_cksum;
92089c86e32SChris Williamson #ifdef ZFS_DEBUG
92189c86e32SChris Williamson 	/*
9225602294fSDan Kimmel 	 * Used for debugging with kmem_flags - by allocating and freeing
92389c86e32SChris Williamson 	 * b_thawed when the buffer is thawed, we get a record of the stack
92489c86e32SChris Williamson 	 * trace that thawed it.
92589c86e32SChris Williamson 	 */
9263f9d6ad7SLin Ling 	void			*b_thawed;
92789c86e32SChris Williamson #endif
9286b4acc8bSahrens 
929fa9e4066Sahrens 	arc_buf_t		*b_buf;
930dcbf3bd6SGeorge Wilson 	uint32_t		b_bufcnt;
93189c86e32SChris Williamson 	/* for waiting on writes to complete */
932ad23a2dbSjohansen 	kcondvar_t		b_cv;
933dcbf3bd6SGeorge Wilson 	uint8_t			b_byteswap;
934ad23a2dbSjohansen 
935fa9e4066Sahrens 	/* protected by arc state mutex */
936fa9e4066Sahrens 	arc_state_t		*b_state;
937244781f1SPrakash Surya 	multilist_node_t	b_arc_node;
938fa9e4066Sahrens 
939fa9e4066Sahrens 	/* updated atomically */
940fa9e4066Sahrens 	clock_t			b_arc_access;
941fa9e4066Sahrens 
942fa9e4066Sahrens 	/* self protecting */
943fa9e4066Sahrens 	refcount_t		b_refcnt;
944fa94a07fSbrendan 
94589c86e32SChris Williamson 	arc_callback_t		*b_acb;
946770499e1SDan Kimmel 	abd_t			*b_pabd;
94789c86e32SChris Williamson } l1arc_buf_hdr_t;
94889c86e32SChris Williamson 
94989c86e32SChris Williamson typedef struct l2arc_dev l2arc_dev_t;
95089c86e32SChris Williamson 
95189c86e32SChris Williamson typedef struct l2arc_buf_hdr {
95289c86e32SChris Williamson 	/* protected by arc_buf_hdr mutex */
95389c86e32SChris Williamson 	l2arc_dev_t		*b_dev;		/* L2ARC device */
95489c86e32SChris Williamson 	uint64_t		b_daddr;	/* disk address, offset byte */
95589c86e32SChris Williamson 
956fa94a07fSbrendan 	list_node_t		b_l2node;
95789c86e32SChris Williamson } l2arc_buf_hdr_t;
95889c86e32SChris Williamson 
95989c86e32SChris Williamson struct arc_buf_hdr {
96089c86e32SChris Williamson 	/* protected by hash lock */
96189c86e32SChris Williamson 	dva_t			b_dva;
96289c86e32SChris Williamson 	uint64_t		b_birth;
96389c86e32SChris Williamson 
964dcbf3bd6SGeorge Wilson 	arc_buf_contents_t	b_type;
96589c86e32SChris Williamson 	arc_buf_hdr_t		*b_hash_next;
96689c86e32SChris Williamson 	arc_flags_t		b_flags;
96789c86e32SChris Williamson 
968dcbf3bd6SGeorge Wilson 	/*
969dcbf3bd6SGeorge Wilson 	 * This field stores the size of the data buffer after
970dcbf3bd6SGeorge Wilson 	 * compression, and is set in the arc's zio completion handlers.
971dcbf3bd6SGeorge Wilson 	 * It is in units of SPA_MINBLOCKSIZE (e.g. 1 == 512 bytes).
972dcbf3bd6SGeorge Wilson 	 *
973dcbf3bd6SGeorge Wilson 	 * While the block pointers can store up to 32MB in their psize
974dcbf3bd6SGeorge Wilson 	 * field, we can only store up to 32MB minus 512B. This is due
975dcbf3bd6SGeorge Wilson 	 * to the bp using a bias of 1, whereas we use a bias of 0 (i.e.
976dcbf3bd6SGeorge Wilson 	 * a field of zeros represents 512B in the bp). We can't use a
977dcbf3bd6SGeorge Wilson 	 * bias of 1 since we need to reserve a psize of zero, here, to
978dcbf3bd6SGeorge Wilson 	 * represent holes and embedded blocks.
979dcbf3bd6SGeorge Wilson 	 *
980dcbf3bd6SGeorge Wilson 	 * This isn't a problem in practice, since the maximum size of a
981dcbf3bd6SGeorge Wilson 	 * buffer is limited to 16MB, so we never need to store 32MB in
982dcbf3bd6SGeorge Wilson 	 * this field. Even in the upstream illumos code base, the
983dcbf3bd6SGeorge Wilson 	 * maximum size of a buffer is limited to 16MB.
984dcbf3bd6SGeorge Wilson 	 */
985dcbf3bd6SGeorge Wilson 	uint16_t		b_psize;
986dcbf3bd6SGeorge Wilson 
987dcbf3bd6SGeorge Wilson 	/*
988dcbf3bd6SGeorge Wilson 	 * This field stores the size of the data buffer before
989dcbf3bd6SGeorge Wilson 	 * compression, and cannot change once set. It is in units
990dcbf3bd6SGeorge Wilson 	 * of SPA_MINBLOCKSIZE (e.g. 2 == 1024 bytes)
991dcbf3bd6SGeorge Wilson 	 */
992dcbf3bd6SGeorge Wilson 	uint16_t		b_lsize;	/* immutable */
993dcbf3bd6SGeorge Wilson 	uint64_t		b_spa;		/* immutable */
99489c86e32SChris Williamson 
99589c86e32SChris Williamson 	/* L2ARC fields. Undefined when not in L2ARC. */
99689c86e32SChris Williamson 	l2arc_buf_hdr_t		b_l2hdr;
99789c86e32SChris Williamson 	/* L1ARC fields. Undefined when in l2arc_only state */
99889c86e32SChris Williamson 	l1arc_buf_hdr_t		b_l1hdr;
999fa9e4066Sahrens };
1000fa9e4066Sahrens 
1001ea8dc4b6Seschrock #define	GHOST_STATE(state)	\
1002fa94a07fSbrendan 	((state) == arc_mru_ghost || (state) == arc_mfu_ghost ||	\
1003fa94a07fSbrendan 	(state) == arc_l2c_only)
1004ea8dc4b6Seschrock 
10057adb730bSGeorge Wilson #define	HDR_IN_HASH_TABLE(hdr)	((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
10067adb730bSGeorge Wilson #define	HDR_IO_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
10077adb730bSGeorge Wilson #define	HDR_IO_ERROR(hdr)	((hdr)->b_flags & ARC_FLAG_IO_ERROR)
10087adb730bSGeorge Wilson #define	HDR_PREFETCH(hdr)	((hdr)->b_flags & ARC_FLAG_PREFETCH)
1009dcbf3bd6SGeorge Wilson #define	HDR_COMPRESSION_ENABLED(hdr)	\
1010dcbf3bd6SGeorge Wilson 	((hdr)->b_flags & ARC_FLAG_COMPRESSED_ARC)
101189c86e32SChris Williamson 
10127adb730bSGeorge Wilson #define	HDR_L2CACHE(hdr)	((hdr)->b_flags & ARC_FLAG_L2CACHE)
10137adb730bSGeorge Wilson #define	HDR_L2_READING(hdr)	\
1014dcbf3bd6SGeorge Wilson 	(((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) &&	\
1015dcbf3bd6SGeorge Wilson 	((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
10167adb730bSGeorge Wilson #define	HDR_L2_WRITING(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITING)
10177adb730bSGeorge Wilson #define	HDR_L2_EVICTED(hdr)	((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
10187adb730bSGeorge Wilson #define	HDR_L2_WRITE_HEAD(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
1019dcbf3bd6SGeorge Wilson #define	HDR_SHARED_DATA(hdr)	((hdr)->b_flags & ARC_FLAG_SHARED_DATA)
1020fa9e4066Sahrens 
102189c86e32SChris Williamson #define	HDR_ISTYPE_METADATA(hdr)	\
1022dcbf3bd6SGeorge Wilson 	((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
102389c86e32SChris Williamson #define	HDR_ISTYPE_DATA(hdr)	(!HDR_ISTYPE_METADATA(hdr))
102489c86e32SChris Williamson 
102589c86e32SChris Williamson #define	HDR_HAS_L1HDR(hdr)	((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
102689c86e32SChris Williamson #define	HDR_HAS_L2HDR(hdr)	((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
102789c86e32SChris Williamson 
1028dcbf3bd6SGeorge Wilson /* For storing compression mode in b_flags */
1029dcbf3bd6SGeorge Wilson #define	HDR_COMPRESS_OFFSET	(highbit64(ARC_FLAG_COMPRESS_0) - 1)
1030dcbf3bd6SGeorge Wilson 
1031dcbf3bd6SGeorge Wilson #define	HDR_GET_COMPRESS(hdr)	((enum zio_compress)BF32_GET((hdr)->b_flags, \
1032dcbf3bd6SGeorge Wilson 	HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS))
1033dcbf3bd6SGeorge Wilson #define	HDR_SET_COMPRESS(hdr, cmp) BF32_SET((hdr)->b_flags, \
1034dcbf3bd6SGeorge Wilson 	HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS, (cmp));
1035dcbf3bd6SGeorge Wilson 
1036dcbf3bd6SGeorge Wilson #define	ARC_BUF_LAST(buf)	((buf)->b_next == NULL)
10375602294fSDan Kimmel #define	ARC_BUF_SHARED(buf)	((buf)->b_flags & ARC_BUF_FLAG_SHARED)
10385602294fSDan Kimmel #define	ARC_BUF_COMPRESSED(buf)	((buf)->b_flags & ARC_BUF_FLAG_COMPRESSED)
1039dcbf3bd6SGeorge Wilson 
1040e6c728e1Sbrendan /*
1041e6c728e1Sbrendan  * Other sizes
1042e6c728e1Sbrendan  */
1043e6c728e1Sbrendan 
104489c86e32SChris Williamson #define	HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
104589c86e32SChris Williamson #define	HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
1046e6c728e1Sbrendan 
1047fa9e4066Sahrens /*
1048fa9e4066Sahrens  * Hash table routines
1049fa9e4066Sahrens  */
1050fa9e4066Sahrens 
1051fa9e4066Sahrens #define	HT_LOCK_PAD	64
1052fa9e4066Sahrens 
1053fa9e4066Sahrens struct ht_lock {
1054fa9e4066Sahrens 	kmutex_t	ht_lock;
1055fa9e4066Sahrens #ifdef _KERNEL
1056fa9e4066Sahrens 	unsigned char	pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
1057fa9e4066Sahrens #endif
1058fa9e4066Sahrens };
1059fa9e4066Sahrens 
1060fa9e4066Sahrens #define	BUF_LOCKS 256
1061fa9e4066Sahrens typedef struct buf_hash_table {
1062fa9e4066Sahrens 	uint64_t ht_mask;
1063fa9e4066Sahrens 	arc_buf_hdr_t **ht_table;
1064fa9e4066Sahrens 	struct ht_lock ht_locks[BUF_LOCKS];
1065fa9e4066Sahrens } buf_hash_table_t;
1066fa9e4066Sahrens 
1067fa9e4066Sahrens static buf_hash_table_t buf_hash_table;
1068fa9e4066Sahrens 
1069fa9e4066Sahrens #define	BUF_HASH_INDEX(spa, dva, birth) \
1070fa9e4066Sahrens 	(buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
1071fa9e4066Sahrens #define	BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
1072fa9e4066Sahrens #define	BUF_HASH_LOCK(idx)	(&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
10733f9d6ad7SLin Ling #define	HDR_LOCK(hdr) \
10743f9d6ad7SLin Ling 	(BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
1075fa9e4066Sahrens 
1076fa9e4066Sahrens uint64_t zfs_crc64_table[256];
1077fa9e4066Sahrens 
1078fa94a07fSbrendan /*
1079fa94a07fSbrendan  * Level 2 ARC
1080fa94a07fSbrendan  */
1081fa94a07fSbrendan 
1082fa94a07fSbrendan #define	L2ARC_WRITE_SIZE	(8 * 1024 * 1024)	/* initial write max */
1083aad02571SSaso Kiselkov #define	L2ARC_HEADROOM		2			/* num of writes */
1084aad02571SSaso Kiselkov /*
1085aad02571SSaso Kiselkov  * If we discover during ARC scan any buffers to be compressed, we boost
1086aad02571SSaso Kiselkov  * our headroom for the next scanning cycle by this percentage multiple.
1087aad02571SSaso Kiselkov  */
1088aad02571SSaso Kiselkov #define	L2ARC_HEADROOM_BOOST	200
10895a98e54bSBrendan Gregg - Sun Microsystems #define	L2ARC_FEED_SECS		1		/* caching interval secs */
10905a98e54bSBrendan Gregg - Sun Microsystems #define	L2ARC_FEED_MIN_MS	200		/* min caching interval ms */
1091fa94a07fSbrendan 
1092fa94a07fSbrendan #define	l2arc_writes_sent	ARCSTAT(arcstat_l2_writes_sent)
1093fa94a07fSbrendan #define	l2arc_writes_done	ARCSTAT(arcstat_l2_writes_done)
1094fa94a07fSbrendan 
1095f7170741SWill Andrews /* L2ARC Performance Tunables */
1096fa94a07fSbrendan uint64_t l2arc_write_max = L2ARC_WRITE_SIZE;	/* default max write size */
10973a737e0dSbrendan uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE;	/* extra write during warmup */
1098fa94a07fSbrendan uint64_t l2arc_headroom = L2ARC_HEADROOM;	/* number of dev writes */
1099aad02571SSaso Kiselkov uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
1100fa94a07fSbrendan uint64_t l2arc_feed_secs = L2ARC_FEED_SECS;	/* interval seconds */
11015a98e54bSBrendan Gregg - Sun Microsystems uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS;	/* min interval milliseconds */
1102fa94a07fSbrendan boolean_t l2arc_noprefetch = B_TRUE;		/* don't cache prefetch bufs */
11035a98e54bSBrendan Gregg - Sun Microsystems boolean_t l2arc_feed_again = B_TRUE;		/* turbo warmup */
11045a98e54bSBrendan Gregg - Sun Microsystems boolean_t l2arc_norw = B_TRUE;			/* no reads during writes */
1105fa94a07fSbrendan 
1106fa94a07fSbrendan /*
1107fa94a07fSbrendan  * L2ARC Internals
1108fa94a07fSbrendan  */
110989c86e32SChris Williamson struct l2arc_dev {
1110fa94a07fSbrendan 	vdev_t			*l2ad_vdev;	/* vdev */
1111fa94a07fSbrendan 	spa_t			*l2ad_spa;	/* spa */
1112fa94a07fSbrendan 	uint64_t		l2ad_hand;	/* next write location */
1113fa94a07fSbrendan 	uint64_t		l2ad_start;	/* first addr on device */
1114fa94a07fSbrendan 	uint64_t		l2ad_end;	/* last addr on device */
1115fa94a07fSbrendan 	boolean_t		l2ad_first;	/* first sweep through */
11165a98e54bSBrendan Gregg - Sun Microsystems 	boolean_t		l2ad_writing;	/* currently writing */
111789c86e32SChris Williamson 	kmutex_t		l2ad_mtx;	/* lock for buffer list */
111889c86e32SChris Williamson 	list_t			l2ad_buflist;	/* buffer list */
1119fa94a07fSbrendan 	list_node_t		l2ad_node;	/* device list node */
1120a52fc310SPrakash Surya 	refcount_t		l2ad_alloc;	/* allocated bytes */
112189c86e32SChris Williamson };
1122fa94a07fSbrendan 
1123fa94a07fSbrendan static list_t L2ARC_dev_list;			/* device list */
1124fa94a07fSbrendan static list_t *l2arc_dev_list;			/* device list pointer */
1125fa94a07fSbrendan static kmutex_t l2arc_dev_mtx;			/* device list mutex */
1126fa94a07fSbrendan static l2arc_dev_t *l2arc_dev_last;		/* last device used */
1127fa94a07fSbrendan static list_t L2ARC_free_on_write;		/* free after write buf list */
1128fa94a07fSbrendan static list_t *l2arc_free_on_write;		/* free after write list ptr */
1129fa94a07fSbrendan static kmutex_t l2arc_free_on_write_mtx;	/* mutex for list */
1130fa94a07fSbrendan static uint64_t l2arc_ndev;			/* number of devices */
1131fa94a07fSbrendan 
1132fa94a07fSbrendan typedef struct l2arc_read_callback {
11335602294fSDan Kimmel 	arc_buf_hdr_t		*l2rcb_hdr;		/* read header */
1134aad02571SSaso Kiselkov 	blkptr_t		l2rcb_bp;		/* original blkptr */
11357802d7bfSMatthew Ahrens 	zbookmark_phys_t	l2rcb_zb;		/* original bookmark */
1136aad02571SSaso Kiselkov 	int			l2rcb_flags;		/* original flags */
1137403a8da7SAndriy Gapon 	abd_t			*l2rcb_abd;		/* temporary buffer */
1138fa94a07fSbrendan } l2arc_read_callback_t;
1139fa94a07fSbrendan 
1140fa94a07fSbrendan typedef struct l2arc_write_callback {
1141fa94a07fSbrendan 	l2arc_dev_t	*l2wcb_dev;		/* device info */
1142fa94a07fSbrendan 	arc_buf_hdr_t	*l2wcb_head;		/* head of write buflist */
1143fa94a07fSbrendan } l2arc_write_callback_t;
1144fa94a07fSbrendan 
1145fa94a07fSbrendan typedef struct l2arc_data_free {
1146fa94a07fSbrendan 	/* protected by l2arc_free_on_write_mtx */
1147770499e1SDan Kimmel 	abd_t		*l2df_abd;
1148fa94a07fSbrendan 	size_t		l2df_size;
1149dcbf3bd6SGeorge Wilson 	arc_buf_contents_t l2df_type;
1150fa94a07fSbrendan 	list_node_t	l2df_list_node;
1151fa94a07fSbrendan } l2arc_data_free_t;
1152fa94a07fSbrendan 
1153fa94a07fSbrendan static kmutex_t l2arc_feed_thr_lock;
1154fa94a07fSbrendan static kcondvar_t l2arc_feed_thr_cv;
1155fa94a07fSbrendan static uint8_t l2arc_thread_exit;
1156fa94a07fSbrendan 
1157770499e1SDan Kimmel static abd_t *arc_get_data_abd(arc_buf_hdr_t *, uint64_t, void *);
1158dcbf3bd6SGeorge Wilson static void *arc_get_data_buf(arc_buf_hdr_t *, uint64_t, void *);
1159770499e1SDan Kimmel static void arc_get_data_impl(arc_buf_hdr_t *, uint64_t, void *);
1160770499e1SDan Kimmel static void arc_free_data_abd(arc_buf_hdr_t *, abd_t *, uint64_t, void *);
1161dcbf3bd6SGeorge Wilson static void arc_free_data_buf(arc_buf_hdr_t *, void *, uint64_t, void *);
1162770499e1SDan Kimmel static void arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag);
1163770499e1SDan Kimmel static void arc_hdr_free_pabd(arc_buf_hdr_t *);
1164770499e1SDan Kimmel static void arc_hdr_alloc_pabd(arc_buf_hdr_t *);
11657adb730bSGeorge Wilson static void arc_access(arc_buf_hdr_t *, kmutex_t *);
1166244781f1SPrakash Surya static boolean_t arc_is_overflowing();
11677adb730bSGeorge Wilson static void arc_buf_watch(arc_buf_t *);
11687adb730bSGeorge Wilson 
116989c86e32SChris Williamson static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
117089c86e32SChris Williamson static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
1171dcbf3bd6SGeorge Wilson static inline void arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
1172dcbf3bd6SGeorge Wilson static inline void arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
117389c86e32SChris Williamson 
11747adb730bSGeorge Wilson static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
11757adb730bSGeorge Wilson static void l2arc_read_done(zio_t *);
1176fa94a07fSbrendan 
11773a2d8a1bSPaul Dagnelie 
11783a2d8a1bSPaul Dagnelie /*
11793a2d8a1bSPaul Dagnelie  * We use Cityhash for this. It's fast, and has good hash properties without
11803a2d8a1bSPaul Dagnelie  * requiring any large static buffers.
11813a2d8a1bSPaul Dagnelie  */
1182fa9e4066Sahrens static uint64_t
1183ac05c741SMark Maybee buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
1184fa9e4066Sahrens {
11853a2d8a1bSPaul Dagnelie 	return (cityhash4(spa, dva->dva_word[0], dva->dva_word[1], birth));
1186fa9e4066Sahrens }
1187fa9e4066Sahrens 
1188dcbf3bd6SGeorge Wilson #define	HDR_EMPTY(hdr)						\
1189dcbf3bd6SGeorge Wilson 	((hdr)->b_dva.dva_word[0] == 0 &&			\
1190dcbf3bd6SGeorge Wilson 	(hdr)->b_dva.dva_word[1] == 0)
1191fa9e4066Sahrens 
1192dcbf3bd6SGeorge Wilson #define	HDR_EQUAL(spa, dva, birth, hdr)				\
1193dcbf3bd6SGeorge Wilson 	((hdr)->b_dva.dva_word[0] == (dva)->dva_word[0]) &&	\
1194dcbf3bd6SGeorge Wilson 	((hdr)->b_dva.dva_word[1] == (dva)->dva_word[1]) &&	\
1195dcbf3bd6SGeorge Wilson 	((hdr)->b_birth == birth) && ((hdr)->b_spa == spa)
1196fa9e4066Sahrens 
11973f9d6ad7SLin Ling static void
11983f9d6ad7SLin Ling buf_discard_identity(arc_buf_hdr_t *hdr)
11993f9d6ad7SLin Ling {
12003f9d6ad7SLin Ling 	hdr->b_dva.dva_word[0] = 0;
12013f9d6ad7SLin Ling 	hdr->b_dva.dva_word[1] = 0;
12023f9d6ad7SLin Ling 	hdr->b_birth = 0;
12033f9d6ad7SLin Ling }
12043f9d6ad7SLin Ling 
1205fa9e4066Sahrens static arc_buf_hdr_t *
12065d7b4d43SMatthew Ahrens buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
1207fa9e4066Sahrens {
12085d7b4d43SMatthew Ahrens 	const dva_t *dva = BP_IDENTITY(bp);
12095d7b4d43SMatthew Ahrens 	uint64_t birth = BP_PHYSICAL_BIRTH(bp);
1210fa9e4066Sahrens 	uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1211fa9e4066Sahrens 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
12127adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr;
1213fa9e4066Sahrens 
1214fa9e4066Sahrens 	mutex_enter(hash_lock);
12157adb730bSGeorge Wilson 	for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
12167adb730bSGeorge Wilson 	    hdr = hdr->b_hash_next) {
1217dcbf3bd6SGeorge Wilson 		if (HDR_EQUAL(spa, dva, birth, hdr)) {
1218fa9e4066Sahrens 			*lockp = hash_lock;
12197adb730bSGeorge Wilson 			return (hdr);
1220fa9e4066Sahrens 		}
1221fa9e4066Sahrens 	}
1222fa9e4066Sahrens 	mutex_exit(hash_lock);
1223fa9e4066Sahrens 	*lockp = NULL;
1224fa9e4066Sahrens 	return (NULL);
1225fa9e4066Sahrens }
1226fa9e4066Sahrens 
1227fa9e4066Sahrens /*
1228fa9e4066Sahrens  * Insert an entry into the hash table.  If there is already an element
1229fa9e4066Sahrens  * equal to elem in the hash table, then the already existing element
1230fa9e4066Sahrens  * will be returned and the new element will not be inserted.
1231fa9e4066Sahrens  * Otherwise returns NULL.
123289c86e32SChris Williamson  * If lockp == NULL, the caller is assumed to already hold the hash lock.
1233fa9e4066Sahrens  */
1234fa9e4066Sahrens static arc_buf_hdr_t *
12357adb730bSGeorge Wilson buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1236fa9e4066Sahrens {
12377adb730bSGeorge Wilson 	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1238fa9e4066Sahrens 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
12397adb730bSGeorge Wilson 	arc_buf_hdr_t *fhdr;
124044cb6abcSbmc 	uint32_t i;
1241fa9e4066Sahrens 
12427adb730bSGeorge Wilson 	ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
12437adb730bSGeorge Wilson 	ASSERT(hdr->b_birth != 0);
12447adb730bSGeorge Wilson 	ASSERT(!HDR_IN_HASH_TABLE(hdr));
124589c86e32SChris Williamson 
124689c86e32SChris Williamson 	if (lockp != NULL) {
124789c86e32SChris Williamson 		*lockp = hash_lock;
124889c86e32SChris Williamson 		mutex_enter(hash_lock);
124989c86e32SChris Williamson 	} else {
125089c86e32SChris Williamson 		ASSERT(MUTEX_HELD(hash_lock));
125189c86e32SChris Williamson 	}
125289c86e32SChris Williamson 
12537adb730bSGeorge Wilson 	for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
12547adb730bSGeorge Wilson 	    fhdr = fhdr->b_hash_next, i++) {
1255dcbf3bd6SGeorge Wilson 		if (HDR_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
12567adb730bSGeorge Wilson 			return (fhdr);
1257fa9e4066Sahrens 	}
1258fa9e4066Sahrens 
12597adb730bSGeorge Wilson 	hdr->b_hash_next = buf_hash_table.ht_table[idx];
12607adb730bSGeorge Wilson 	buf_hash_table.ht_table[idx] = hdr;
1261dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1262fa9e4066Sahrens 
1263fa9e4066Sahrens 	/* collect some hash table performance data */
1264fa9e4066Sahrens 	if (i > 0) {
126544cb6abcSbmc 		ARCSTAT_BUMP(arcstat_hash_collisions);
1266fa9e4066Sahrens 		if (i == 1)
126744cb6abcSbmc 			ARCSTAT_BUMP(arcstat_hash_chains);
126844cb6abcSbmc 
126944cb6abcSbmc 		ARCSTAT_MAX(arcstat_hash_chain_max, i);
1270fa9e4066Sahrens 	}
127144cb6abcSbmc 
127244cb6abcSbmc 	ARCSTAT_BUMP(arcstat_hash_elements);
127344cb6abcSbmc 	ARCSTAT_MAXSTAT(arcstat_hash_elements);
1274fa9e4066Sahrens 
1275fa9e4066Sahrens 	return (NULL);
1276fa9e4066Sahrens }
1277fa9e4066Sahrens 
1278fa9e4066Sahrens static void
12797adb730bSGeorge Wilson buf_hash_remove(arc_buf_hdr_t *hdr)
1280fa9e4066Sahrens {
12817adb730bSGeorge Wilson 	arc_buf_hdr_t *fhdr, **hdrp;
12827adb730bSGeorge Wilson 	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1283fa9e4066Sahrens 
1284fa9e4066Sahrens 	ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
12857adb730bSGeorge Wilson 	ASSERT(HDR_IN_HASH_TABLE(hdr));
1286fa9e4066Sahrens 
12877adb730bSGeorge Wilson 	hdrp = &buf_hash_table.ht_table[idx];
12887adb730bSGeorge Wilson 	while ((fhdr = *hdrp) != hdr) {
1289dcbf3bd6SGeorge Wilson 		ASSERT3P(fhdr, !=, NULL);
12907adb730bSGeorge Wilson 		hdrp = &fhdr->b_hash_next;
1291fa9e4066Sahrens 	}
12927adb730bSGeorge Wilson 	*hdrp = hdr->b_hash_next;
12937adb730bSGeorge Wilson 	hdr->b_hash_next = NULL;
1294dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1295fa9e4066Sahrens 
1296fa9e4066Sahrens 	/* collect some hash table performance data */
129744cb6abcSbmc 	ARCSTAT_BUMPDOWN(arcstat_hash_elements);
129844cb6abcSbmc 
1299fa9e4066Sahrens 	if (buf_hash_table.ht_table[idx] &&
1300fa9e4066Sahrens 	    buf_hash_table.ht_table[idx]->b_hash_next == NULL)
130144cb6abcSbmc 		ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1302fa9e4066Sahrens }
1303fa9e4066Sahrens 
1304fa9e4066Sahrens /*
1305fa9e4066Sahrens  * Global data structures and functions for the buf kmem cache.
1306fa9e4066Sahrens  */
130789c86e32SChris Williamson static kmem_cache_t *hdr_full_cache;
130889c86e32SChris Williamson static kmem_cache_t *hdr_l2only_cache;
1309fa9e4066Sahrens static kmem_cache_t *buf_cache;
1310fa9e4066Sahrens 
1311fa9e4066Sahrens static void
1312fa9e4066Sahrens buf_fini(void)
1313fa9e4066Sahrens {
1314fa9e4066Sahrens 	int i;
1315fa9e4066Sahrens 
1316fa9e4066Sahrens 	kmem_free(buf_hash_table.ht_table,
1317fa9e4066Sahrens 	    (buf_hash_table.ht_mask + 1) * sizeof (void *));
1318fa9e4066Sahrens 	for (i = 0; i < BUF_LOCKS; i++)
1319fa9e4066Sahrens 		mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
132089c86e32SChris Williamson 	kmem_cache_destroy(hdr_full_cache);
132189c86e32SChris Williamson 	kmem_cache_destroy(hdr_l2only_cache);
1322fa9e4066Sahrens 	kmem_cache_destroy(buf_cache);
1323fa9e4066Sahrens }
1324fa9e4066Sahrens 
1325fa9e4066Sahrens /*
1326fa9e4066Sahrens  * Constructor callback - called when the cache is empty
1327fa9e4066Sahrens  * and a new buf is requested.
1328fa9e4066Sahrens  */
1329fa9e4066Sahrens /* ARGSUSED */
1330fa9e4066Sahrens static int
133189c86e32SChris Williamson hdr_full_cons(void *vbuf, void *unused, int kmflag)
1332fa9e4066Sahrens {
13337adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr = vbuf;
1334fa9e4066Sahrens 
133589c86e32SChris Williamson 	bzero(hdr, HDR_FULL_SIZE);
133689c86e32SChris Williamson 	cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
133789c86e32SChris Williamson 	refcount_create(&hdr->b_l1hdr.b_refcnt);
133889c86e32SChris Williamson 	mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1339244781f1SPrakash Surya 	multilist_link_init(&hdr->b_l1hdr.b_arc_node);
134089c86e32SChris Williamson 	arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
134189c86e32SChris Williamson 
134289c86e32SChris Williamson 	return (0);
134389c86e32SChris Williamson }
134489c86e32SChris Williamson 
134589c86e32SChris Williamson /* ARGSUSED */
134689c86e32SChris Williamson static int
134789c86e32SChris Williamson hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
134889c86e32SChris Williamson {
134989c86e32SChris Williamson 	arc_buf_hdr_t *hdr = vbuf;
135089c86e32SChris Williamson 
135189c86e32SChris Williamson 	bzero(hdr, HDR_L2ONLY_SIZE);
135289c86e32SChris Williamson 	arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1353fa94a07fSbrendan 
1354fa9e4066Sahrens 	return (0);
1355fa9e4066Sahrens }
1356fa9e4066Sahrens 
13576f83844dSMark Maybee /* ARGSUSED */
13586f83844dSMark Maybee static int
13596f83844dSMark Maybee buf_cons(void *vbuf, void *unused, int kmflag)
13606f83844dSMark Maybee {
13616f83844dSMark Maybee 	arc_buf_t *buf = vbuf;
13626f83844dSMark Maybee 
13636f83844dSMark Maybee 	bzero(buf, sizeof (arc_buf_t));
13643f9d6ad7SLin Ling 	mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
13655a98e54bSBrendan Gregg - Sun Microsystems 	arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
13665a98e54bSBrendan Gregg - Sun Microsystems 
13676f83844dSMark Maybee 	return (0);
13686f83844dSMark Maybee }
13696f83844dSMark Maybee 
1370fa9e4066Sahrens /*
1371fa9e4066Sahrens  * Destructor callback - called when a cached buf is
1372fa9e4066Sahrens  * no longer required.
1373fa9e4066Sahrens  */
1374fa9e4066Sahrens /* ARGSUSED */
1375fa9e4066Sahrens static void
137689c86e32SChris Williamson hdr_full_dest(void *vbuf, void *unused)
137789c86e32SChris Williamson {
137889c86e32SChris Williamson 	arc_buf_hdr_t *hdr = vbuf;
137989c86e32SChris Williamson 
1380dcbf3bd6SGeorge Wilson 	ASSERT(HDR_EMPTY(hdr));
138189c86e32SChris Williamson 	cv_destroy(&hdr->b_l1hdr.b_cv);
138289c86e32SChris Williamson 	refcount_destroy(&hdr->b_l1hdr.b_refcnt);
138389c86e32SChris Williamson 	mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1384244781f1SPrakash Surya 	ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
138589c86e32SChris Williamson 	arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
138689c86e32SChris Williamson }
138789c86e32SChris Williamson 
138889c86e32SChris Williamson /* ARGSUSED */
138989c86e32SChris Williamson static void
139089c86e32SChris Williamson hdr_l2only_dest(void *vbuf, void *unused)
1391fa9e4066Sahrens {
13927adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr = vbuf;
1393fa9e4066Sahrens 
1394dcbf3bd6SGeorge Wilson 	ASSERT(HDR_EMPTY(hdr));
139589c86e32SChris Williamson 	arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1396fa9e4066Sahrens }
1397fa9e4066Sahrens 
13986f83844dSMark Maybee /* ARGSUSED */
13996f83844dSMark Maybee static void
14006f83844dSMark Maybee buf_dest(void *vbuf, void *unused)
14016f83844dSMark Maybee {
14026f83844dSMark Maybee 	arc_buf_t *buf = vbuf;
14036f83844dSMark Maybee 
14043f9d6ad7SLin Ling 	mutex_destroy(&buf->b_evict_lock);
14055a98e54bSBrendan Gregg - Sun Microsystems 	arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
14066f83844dSMark Maybee }
14076f83844dSMark Maybee 
1408fa9e4066Sahrens /*
1409fa9e4066Sahrens  * Reclaim callback -- invoked when memory is low.
1410fa9e4066Sahrens  */
1411fa9e4066Sahrens /* ARGSUSED */
1412fa9e4066Sahrens static void
1413fa9e4066Sahrens hdr_recl(void *unused)
1414fa9e4066Sahrens {
1415fa9e4066Sahrens 	dprintf("hdr_recl called\n");
141649e3519aSmaybee 	/*
141749e3519aSmaybee 	 * umem calls the reclaim func when we destroy the buf cache,
141849e3519aSmaybee 	 * which is after we do arc_fini().
141949e3519aSmaybee 	 */
1420*de753e34SBrad Lewis 	if (arc_initialized)
1421*de753e34SBrad Lewis 		zthr_wakeup(arc_reap_zthr);
1422fa9e4066Sahrens }
1423fa9e4066Sahrens 
1424fa9e4066Sahrens static void
1425fa9e4066Sahrens buf_init(void)
1426fa9e4066Sahrens {
1427fa9e4066Sahrens 	uint64_t *ct;
1428ea8dc4b6Seschrock 	uint64_t hsize = 1ULL << 12;
1429fa9e4066Sahrens 	int i, j;
1430fa9e4066Sahrens 
1431fa9e4066Sahrens 	/*
1432fa9e4066Sahrens 	 * The hash table is big enough to fill all of physical memory
143363e911b6SMatthew Ahrens 	 * with an average block size of zfs_arc_average_blocksize (default 8K).
143463e911b6SMatthew Ahrens 	 * By default, the table will take up
143563e911b6SMatthew Ahrens 	 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1436fa9e4066Sahrens 	 */
143763e911b6SMatthew Ahrens 	while (hsize * zfs_arc_average_blocksize < physmem * PAGESIZE)
1438fa9e4066Sahrens 		hsize <<= 1;
1439ea8dc4b6Seschrock retry:
1440fa9e4066Sahrens 	buf_hash_table.ht_mask = hsize - 1;
1441ea8dc4b6Seschrock 	buf_hash_table.ht_table =
1442ea8dc4b6Seschrock 	    kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1443ea8dc4b6Seschrock 	if (buf_hash_table.ht_table == NULL) {
1444ea8dc4b6Seschrock 		ASSERT(hsize > (1ULL << 8));
1445ea8dc4b6Seschrock 		hsize >>= 1;
1446ea8dc4b6Seschrock 		goto retry;
1447ea8dc4b6Seschrock 	}
1448fa9e4066Sahrens 
144989c86e32SChris Williamson 	hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
145089c86e32SChris Williamson 	    0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
145189c86e32SChris Williamson 	hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
145289c86e32SChris Williamson 	    HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
145389c86e32SChris Williamson 	    NULL, NULL, 0);
1454fa9e4066Sahrens 	buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
14556f83844dSMark Maybee 	    0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1456fa9e4066Sahrens 
1457fa9e4066Sahrens 	for (i = 0; i < 256; i++)
1458fa9e4066Sahrens 		for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1459fa9e4066Sahrens 			*ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1460fa9e4066Sahrens 
1461fa9e4066Sahrens 	for (i = 0; i < BUF_LOCKS; i++) {
1462fa9e4066Sahrens 		mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1463fa9e4066Sahrens 		    NULL, MUTEX_DEFAULT, NULL);
1464fa9e4066Sahrens 	}
1465fa9e4066Sahrens }
1466fa9e4066Sahrens 
14675602294fSDan Kimmel /*
14685602294fSDan Kimmel  * This is the size that the buf occupies in memory. If the buf is compressed,
14695602294fSDan Kimmel  * it will correspond to the compressed size. You should use this method of
14705602294fSDan Kimmel  * getting the buf size unless you explicitly need the logical size.
14715602294fSDan Kimmel  */
14725602294fSDan Kimmel int32_t
14735602294fSDan Kimmel arc_buf_size(arc_buf_t *buf)
14745602294fSDan Kimmel {
14755602294fSDan Kimmel 	return (ARC_BUF_COMPRESSED(buf) ?
14765602294fSDan Kimmel 	    HDR_GET_PSIZE(buf->b_hdr) : HDR_GET_LSIZE(buf->b_hdr));
14775602294fSDan Kimmel }
14785602294fSDan Kimmel 
14795602294fSDan Kimmel int32_t
14805602294fSDan Kimmel arc_buf_lsize(arc_buf_t *buf)
14815602294fSDan Kimmel {
14825602294fSDan Kimmel 	return (HDR_GET_LSIZE(buf->b_hdr));
14835602294fSDan Kimmel }
14845602294fSDan Kimmel 
14855602294fSDan Kimmel enum zio_compress
14865602294fSDan Kimmel arc_get_compression(arc_buf_t *buf)
14875602294fSDan Kimmel {
14885602294fSDan Kimmel 	return (ARC_BUF_COMPRESSED(buf) ?
14895602294fSDan Kimmel 	    HDR_GET_COMPRESS(buf->b_hdr) : ZIO_COMPRESS_OFF);
14905602294fSDan Kimmel }
14915602294fSDan Kimmel 
1492dcbf3bd6SGeorge Wilson #define	ARC_MINTIME	(hz>>4) /* 62 ms */
1493244781f1SPrakash Surya 
1494dcbf3bd6SGeorge Wilson static inline boolean_t
1495dcbf3bd6SGeorge Wilson arc_buf_is_shared(arc_buf_t *buf)
1496dcbf3bd6SGeorge Wilson {
1497dcbf3bd6SGeorge Wilson 	boolean_t shared = (buf->b_data != NULL &&
1498770499e1SDan Kimmel 	    buf->b_hdr->b_l1hdr.b_pabd != NULL &&
1499770499e1SDan Kimmel 	    abd_is_linear(buf->b_hdr->b_l1hdr.b_pabd) &&
1500770499e1SDan Kimmel 	    buf->b_data == abd_to_buf(buf->b_hdr->b_l1hdr.b_pabd));
1501dcbf3bd6SGeorge Wilson 	IMPLY(shared, HDR_SHARED_DATA(buf->b_hdr));
15025602294fSDan Kimmel 	IMPLY(shared, ARC_BUF_SHARED(buf));
15035602294fSDan Kimmel 	IMPLY(shared, ARC_BUF_COMPRESSED(buf) || ARC_BUF_LAST(buf));
15045602294fSDan Kimmel 
15055602294fSDan Kimmel 	/*
15065602294fSDan Kimmel 	 * It would be nice to assert arc_can_share() too, but the "hdr isn't
15075602294fSDan Kimmel 	 * already being shared" requirement prevents us from doing that.
15085602294fSDan Kimmel 	 */
15095602294fSDan Kimmel 
1510dcbf3bd6SGeorge Wilson 	return (shared);
1511dcbf3bd6SGeorge Wilson }
1512c546f36aSArne Jansen 
15135602294fSDan Kimmel /*
15145602294fSDan Kimmel  * Free the checksum associated with this header. If there is no checksum, this
15155602294fSDan Kimmel  * is a no-op.
15165602294fSDan Kimmel  */
1517dcbf3bd6SGeorge Wilson static inline void
1518dcbf3bd6SGeorge Wilson arc_cksum_free(arc_buf_hdr_t *hdr)
1519dcbf3bd6SGeorge Wilson {
1520dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
1521dcbf3bd6SGeorge Wilson 	mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1522dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
1523dcbf3bd6SGeorge Wilson 		kmem_free(hdr->b_l1hdr.b_freeze_cksum, sizeof (zio_cksum_t));
1524dcbf3bd6SGeorge Wilson 		hdr->b_l1hdr.b_freeze_cksum = NULL;
152589c86e32SChris Williamson 	}
1526dcbf3bd6SGeorge Wilson 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
152789c86e32SChris Williamson }
152889c86e32SChris Williamson 
15295602294fSDan Kimmel /*
15305602294fSDan Kimmel  * Return true iff at least one of the bufs on hdr is not compressed.
15315602294fSDan Kimmel  */
15325602294fSDan Kimmel static boolean_t
15335602294fSDan Kimmel arc_hdr_has_uncompressed_buf(arc_buf_hdr_t *hdr)
15345602294fSDan Kimmel {
15355602294fSDan Kimmel 	for (arc_buf_t *b = hdr->b_l1hdr.b_buf; b != NULL; b = b->b_next) {
15365602294fSDan Kimmel 		if (!ARC_BUF_COMPRESSED(b)) {
15375602294fSDan Kimmel 			return (B_TRUE);
15385602294fSDan Kimmel 		}
15395602294fSDan Kimmel 	}
15405602294fSDan Kimmel 	return (B_FALSE);
15415602294fSDan Kimmel }
15425602294fSDan Kimmel 
15435602294fSDan Kimmel /*
15445602294fSDan Kimmel  * If we've turned on the ZFS_DEBUG_MODIFY flag, verify that the buf's data
15455602294fSDan Kimmel  * matches the checksum that is stored in the hdr. If there is no checksum,
15465602294fSDan Kimmel  * or if the buf is compressed, this is a no-op.
15475602294fSDan Kimmel  */
15486b4acc8bSahrens static void
15496b4acc8bSahrens arc_cksum_verify(arc_buf_t *buf)
15506b4acc8bSahrens {
1551dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
15526b4acc8bSahrens 	zio_cksum_t zc;
15536b4acc8bSahrens 
1554cc60fd72Sahrens 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
15556b4acc8bSahrens 		return;
15566b4acc8bSahrens 
15575602294fSDan Kimmel 	if (ARC_BUF_COMPRESSED(buf)) {
15585602294fSDan Kimmel 		ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
15595602294fSDan Kimmel 		    arc_hdr_has_uncompressed_buf(hdr));
15605602294fSDan Kimmel 		return;
15615602294fSDan Kimmel 	}
15625602294fSDan Kimmel 
1563dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
1564dcbf3bd6SGeorge Wilson 
1565dcbf3bd6SGeorge Wilson 	mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1566dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_freeze_cksum == NULL || HDR_IO_ERROR(hdr)) {
1567dcbf3bd6SGeorge Wilson 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
15686b4acc8bSahrens 		return;
15696b4acc8bSahrens 	}
15705602294fSDan Kimmel 
15715602294fSDan Kimmel 	fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL, &zc);
1572dcbf3bd6SGeorge Wilson 	if (!ZIO_CHECKSUM_EQUAL(*hdr->b_l1hdr.b_freeze_cksum, zc))
15736b4acc8bSahrens 		panic("buffer modified while frozen!");
1574dcbf3bd6SGeorge Wilson 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
15756b4acc8bSahrens }
15766b4acc8bSahrens 
1577dcbf3bd6SGeorge Wilson static boolean_t
1578dcbf3bd6SGeorge Wilson arc_cksum_is_equal(arc_buf_hdr_t *hdr, zio_t *zio)
1579fa94a07fSbrendan {
1580dcbf3bd6SGeorge Wilson 	enum zio_compress compress = BP_GET_COMPRESS(zio->io_bp);
1581dcbf3bd6SGeorge Wilson 	boolean_t valid_cksum;
1582fa94a07fSbrendan 
1583dcbf3bd6SGeorge Wilson 	ASSERT(!BP_IS_EMBEDDED(zio->io_bp));
1584dcbf3bd6SGeorge Wilson 	VERIFY3U(BP_GET_PSIZE(zio->io_bp), ==, HDR_GET_PSIZE(hdr));
1585dcbf3bd6SGeorge Wilson 
1586dcbf3bd6SGeorge Wilson 	/*
1587dcbf3bd6SGeorge Wilson 	 * We rely on the blkptr's checksum to determine if the block
1588dcbf3bd6SGeorge Wilson 	 * is valid or not. When compressed arc is enabled, the l2arc
1589dcbf3bd6SGeorge Wilson 	 * writes the block to the l2arc just as it appears in the pool.
1590dcbf3bd6SGeorge Wilson 	 * This allows us to use the blkptr's checksum to validate the
1591dcbf3bd6SGeorge Wilson 	 * data that we just read off of the l2arc without having to store
1592dcbf3bd6SGeorge Wilson 	 * a separate checksum in the arc_buf_hdr_t. However, if compressed
1593dcbf3bd6SGeorge Wilson 	 * arc is disabled, then the data written to the l2arc is always
1594dcbf3bd6SGeorge Wilson 	 * uncompressed and won't match the block as it exists in the main
1595dcbf3bd6SGeorge Wilson 	 * pool. When this is the case, we must first compress it if it is
1596dcbf3bd6SGeorge Wilson 	 * compressed on the main pool before we can validate the checksum.
1597dcbf3bd6SGeorge Wilson 	 */
1598dcbf3bd6SGeorge Wilson 	if (!HDR_COMPRESSION_ENABLED(hdr) && compress != ZIO_COMPRESS_OFF) {
1599dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
1600dcbf3bd6SGeorge Wilson 		uint64_t lsize = HDR_GET_LSIZE(hdr);
1601dcbf3bd6SGeorge Wilson 		uint64_t csize;
1602dcbf3bd6SGeorge Wilson 
160301a059eeSRoman Strashkin 		abd_t *cdata = abd_alloc_linear(HDR_GET_PSIZE(hdr), B_TRUE);
160401a059eeSRoman Strashkin 		csize = zio_compress_data(compress, zio->io_abd,
160501a059eeSRoman Strashkin 		    abd_to_buf(cdata), lsize);
1606770499e1SDan Kimmel 
1607dcbf3bd6SGeorge Wilson 		ASSERT3U(csize, <=, HDR_GET_PSIZE(hdr));
1608dcbf3bd6SGeorge Wilson 		if (csize < HDR_GET_PSIZE(hdr)) {
1609dcbf3bd6SGeorge Wilson 			/*
1610dcbf3bd6SGeorge Wilson 			 * Compressed blocks are always a multiple of the
1611dcbf3bd6SGeorge Wilson 			 * smallest ashift in the pool. Ideally, we would
1612dcbf3bd6SGeorge Wilson 			 * like to round up the csize to the next
1613dcbf3bd6SGeorge Wilson 			 * spa_min_ashift but that value may have changed
1614dcbf3bd6SGeorge Wilson 			 * since the block was last written. Instead,
1615dcbf3bd6SGeorge Wilson 			 * we rely on the fact that the hdr's psize
1616dcbf3bd6SGeorge Wilson 			 * was set to the psize of the block when it was
1617dcbf3bd6SGeorge Wilson 			 * last written. We set the csize to that value
1618dcbf3bd6SGeorge Wilson 			 * and zero out any part that should not contain
1619dcbf3bd6SGeorge Wilson 			 * data.
1620dcbf3bd6SGeorge Wilson 			 */
162101a059eeSRoman Strashkin 			abd_zero_off(cdata, csize, HDR_GET_PSIZE(hdr) - csize);
1622dcbf3bd6SGeorge Wilson 			csize = HDR_GET_PSIZE(hdr);
1623dcbf3bd6SGeorge Wilson 		}
162401a059eeSRoman Strashkin 		zio_push_transform(zio, cdata, csize, HDR_GET_PSIZE(hdr), NULL);
1625dcbf3bd6SGeorge Wilson 	}
1626fa94a07fSbrendan 
1627dcbf3bd6SGeorge Wilson 	/*
1628dcbf3bd6SGeorge Wilson 	 * Block pointers always store the checksum for the logical data.
1629dcbf3bd6SGeorge Wilson 	 * If the block pointer has the gang bit set, then the checksum
1630dcbf3bd6SGeorge Wilson 	 * it represents is for the reconstituted data and not for an
1631dcbf3bd6SGeorge Wilson 	 * individual gang member. The zio pipeline, however, must be able to
1632dcbf3bd6SGeorge Wilson 	 * determine the checksum of each of the gang constituents so it
1633dcbf3bd6SGeorge Wilson 	 * treats the checksum comparison differently than what we need
1634dcbf3bd6SGeorge Wilson 	 * for l2arc blocks. This prevents us from using the
1635dcbf3bd6SGeorge Wilson 	 * zio_checksum_error() interface directly. Instead we must call the
1636dcbf3bd6SGeorge Wilson 	 * zio_checksum_error_impl() so that we can ensure the checksum is
1637dcbf3bd6SGeorge Wilson 	 * generated using the correct checksum algorithm and accounts for the
1638dcbf3bd6SGeorge Wilson 	 * logical I/O size and not just a gang fragment.
1639dcbf3bd6SGeorge Wilson 	 */
1640dcbf3bd6SGeorge Wilson 	valid_cksum = (zio_checksum_error_impl(zio->io_spa, zio->io_bp,
1641770499e1SDan Kimmel 	    BP_GET_CHECKSUM(zio->io_bp), zio->io_abd, zio->io_size,
1642dcbf3bd6SGeorge Wilson 	    zio->io_offset, NULL) == 0);
1643dcbf3bd6SGeorge Wilson 	zio_pop_transforms(zio);
1644dcbf3bd6SGeorge Wilson 	return (valid_cksum);
1645fa94a07fSbrendan }
1646fa94a07fSbrendan 
16475602294fSDan Kimmel /*
16485602294fSDan Kimmel  * Given a buf full of data, if ZFS_DEBUG_MODIFY is enabled this computes a
16495602294fSDan Kimmel  * checksum and attaches it to the buf's hdr so that we can ensure that the buf
16505602294fSDan Kimmel  * isn't modified later on. If buf is compressed or there is already a checksum
16515602294fSDan Kimmel  * on the hdr, this is a no-op (we only checksum uncompressed bufs).
16525602294fSDan Kimmel  */
16536b4acc8bSahrens static void
1654dcbf3bd6SGeorge Wilson arc_cksum_compute(arc_buf_t *buf)
16556b4acc8bSahrens {
1656dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
1657dcbf3bd6SGeorge Wilson 
1658dcbf3bd6SGeorge Wilson 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
16596b4acc8bSahrens 		return;
16606b4acc8bSahrens 
1661dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
16625602294fSDan Kimmel 
166389c86e32SChris Williamson 	mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1664dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
16655602294fSDan Kimmel 		ASSERT(arc_hdr_has_uncompressed_buf(hdr));
16665602294fSDan Kimmel 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
16675602294fSDan Kimmel 		return;
16685602294fSDan Kimmel 	} else if (ARC_BUF_COMPRESSED(buf)) {
1669dcbf3bd6SGeorge Wilson 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
16706b4acc8bSahrens 		return;
16716b4acc8bSahrens 	}
16725602294fSDan Kimmel 
16735602294fSDan Kimmel 	ASSERT(!ARC_BUF_COMPRESSED(buf));
1674dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t),
1675dcbf3bd6SGeorge Wilson 	    KM_SLEEP);
16765602294fSDan Kimmel 	fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL,
1677dcbf3bd6SGeorge Wilson 	    hdr->b_l1hdr.b_freeze_cksum);
1678dcbf3bd6SGeorge Wilson 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1679cd1c8b85SMatthew Ahrens 	arc_buf_watch(buf);
1680cd1c8b85SMatthew Ahrens }
1681cd1c8b85SMatthew Ahrens 
1682cd1c8b85SMatthew Ahrens #ifndef _KERNEL
1683cd1c8b85SMatthew Ahrens typedef struct procctl {
1684cd1c8b85SMatthew Ahrens 	long cmd;
1685cd1c8b85SMatthew Ahrens 	prwatch_t prwatch;
1686cd1c8b85SMatthew Ahrens } procctl_t;
1687cd1c8b85SMatthew Ahrens #endif
1688cd1c8b85SMatthew Ahrens 
1689cd1c8b85SMatthew Ahrens /* ARGSUSED */
1690cd1c8b85SMatthew Ahrens static void
1691cd1c8b85SMatthew Ahrens arc_buf_unwatch(arc_buf_t *buf)
1692cd1c8b85SMatthew Ahrens {
1693cd1c8b85SMatthew Ahrens #ifndef _KERNEL
1694cd1c8b85SMatthew Ahrens 	if (arc_watch) {
1695cd1c8b85SMatthew Ahrens 		int result;
1696cd1c8b85SMatthew Ahrens 		procctl_t ctl;
1697cd1c8b85SMatthew Ahrens 		ctl.cmd = PCWATCH;
1698cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1699cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_size = 0;
1700cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_wflags = 0;
1701cd1c8b85SMatthew Ahrens 		result = write(arc_procfd, &ctl, sizeof (ctl));
1702cd1c8b85SMatthew Ahrens 		ASSERT3U(result, ==, sizeof (ctl));
1703cd1c8b85SMatthew Ahrens 	}
1704cd1c8b85SMatthew Ahrens #endif
1705cd1c8b85SMatthew Ahrens }
1706cd1c8b85SMatthew Ahrens 
1707cd1c8b85SMatthew Ahrens /* ARGSUSED */
1708cd1c8b85SMatthew Ahrens static void
1709cd1c8b85SMatthew Ahrens arc_buf_watch(arc_buf_t *buf)
1710cd1c8b85SMatthew Ahrens {
1711cd1c8b85SMatthew Ahrens #ifndef _KERNEL
1712cd1c8b85SMatthew Ahrens 	if (arc_watch) {
1713cd1c8b85SMatthew Ahrens 		int result;
1714cd1c8b85SMatthew Ahrens 		procctl_t ctl;
1715cd1c8b85SMatthew Ahrens 		ctl.cmd = PCWATCH;
1716cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
17175602294fSDan Kimmel 		ctl.prwatch.pr_size = arc_buf_size(buf);
1718cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_wflags = WA_WRITE;
1719cd1c8b85SMatthew Ahrens 		result = write(arc_procfd, &ctl, sizeof (ctl));
1720cd1c8b85SMatthew Ahrens 		ASSERT3U(result, ==, sizeof (ctl));
1721cd1c8b85SMatthew Ahrens 	}
1722cd1c8b85SMatthew Ahrens #endif
17236b4acc8bSahrens }
17246b4acc8bSahrens 
172589c86e32SChris Williamson static arc_buf_contents_t
172689c86e32SChris Williamson arc_buf_type(arc_buf_hdr_t *hdr)
172789c86e32SChris Williamson {
1728dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type;
172989c86e32SChris Williamson 	if (HDR_ISTYPE_METADATA(hdr)) {
1730dcbf3bd6SGeorge Wilson 		type = ARC_BUFC_METADATA;
173189c86e32SChris Williamson 	} else {
1732dcbf3bd6SGeorge Wilson 		type = ARC_BUFC_DATA;
173389c86e32SChris Williamson 	}
1734dcbf3bd6SGeorge Wilson 	VERIFY3U(hdr->b_type, ==, type);
1735dcbf3bd6SGeorge Wilson 	return (type);
173689c86e32SChris Williamson }
173789c86e32SChris Williamson 
17385602294fSDan Kimmel boolean_t
17395602294fSDan Kimmel arc_is_metadata(arc_buf_t *buf)
17405602294fSDan Kimmel {
17415602294fSDan Kimmel 	return (HDR_ISTYPE_METADATA(buf->b_hdr) != 0);
17425602294fSDan Kimmel }
17435602294fSDan Kimmel 
174489c86e32SChris Williamson static uint32_t
174589c86e32SChris Williamson arc_bufc_to_flags(arc_buf_contents_t type)
174689c86e32SChris Williamson {
174789c86e32SChris Williamson 	switch (type) {
174889c86e32SChris Williamson 	case ARC_BUFC_DATA:
174989c86e32SChris Williamson 		/* metadata field is 0 if buffer contains normal data */
175089c86e32SChris Williamson 		return (0);
175189c86e32SChris Williamson 	case ARC_BUFC_METADATA:
175289c86e32SChris Williamson 		return (ARC_FLAG_BUFC_METADATA);
175389c86e32SChris Williamson 	default:
175489c86e32SChris Williamson 		break;
175589c86e32SChris Williamson 	}
175689c86e32SChris Williamson 	panic("undefined ARC buffer type!");
175789c86e32SChris Williamson 	return ((uint32_t)-1);
175889c86e32SChris Williamson }
175989c86e32SChris Williamson 
17606b4acc8bSahrens void
17616b4acc8bSahrens arc_buf_thaw(arc_buf_t *buf)
17626b4acc8bSahrens {
1763dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
1764dcbf3bd6SGeorge Wilson 
17655602294fSDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
17665602294fSDan Kimmel 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
17675602294fSDan Kimmel 
17685602294fSDan Kimmel 	arc_cksum_verify(buf);
17695602294fSDan Kimmel 
17705602294fSDan Kimmel 	/*
17715602294fSDan Kimmel 	 * Compressed buffers do not manipulate the b_freeze_cksum or
17725602294fSDan Kimmel 	 * allocate b_thawed.
17735602294fSDan Kimmel 	 */
17745602294fSDan Kimmel 	if (ARC_BUF_COMPRESSED(buf)) {
17755602294fSDan Kimmel 		ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
17765602294fSDan Kimmel 		    arc_hdr_has_uncompressed_buf(hdr));
17775602294fSDan Kimmel 		return;
1778fa94a07fSbrendan 	}
17796b4acc8bSahrens 
1780dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
1781dcbf3bd6SGeorge Wilson 	arc_cksum_free(hdr);
17823f9d6ad7SLin Ling 
1783dcbf3bd6SGeorge Wilson 	mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
178489c86e32SChris Williamson #ifdef ZFS_DEBUG
17853f9d6ad7SLin Ling 	if (zfs_flags & ZFS_DEBUG_MODIFY) {
1786dcbf3bd6SGeorge Wilson 		if (hdr->b_l1hdr.b_thawed != NULL)
1787dcbf3bd6SGeorge Wilson 			kmem_free(hdr->b_l1hdr.b_thawed, 1);
1788dcbf3bd6SGeorge Wilson 		hdr->b_l1hdr.b_thawed = kmem_alloc(1, KM_SLEEP);
17893f9d6ad7SLin Ling 	}
179089c86e32SChris Williamson #endif
17913f9d6ad7SLin Ling 
1792dcbf3bd6SGeorge Wilson 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1793cd1c8b85SMatthew Ahrens 
1794cd1c8b85SMatthew Ahrens 	arc_buf_unwatch(buf);
17956b4acc8bSahrens }
17966b4acc8bSahrens 
17976b4acc8bSahrens void
17986b4acc8bSahrens arc_buf_freeze(arc_buf_t *buf)
17996b4acc8bSahrens {
1800dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
18013f9d6ad7SLin Ling 	kmutex_t *hash_lock;
18023f9d6ad7SLin Ling 
1803cc60fd72Sahrens 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1804cc60fd72Sahrens 		return;
1805cc60fd72Sahrens 
18065602294fSDan Kimmel 	if (ARC_BUF_COMPRESSED(buf)) {
18075602294fSDan Kimmel 		ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
18085602294fSDan Kimmel 		    arc_hdr_has_uncompressed_buf(hdr));
18095602294fSDan Kimmel 		return;
18105602294fSDan Kimmel 	}
18115602294fSDan Kimmel 
1812dcbf3bd6SGeorge Wilson 	hash_lock = HDR_LOCK(hdr);
18133f9d6ad7SLin Ling 	mutex_enter(hash_lock);
18143f9d6ad7SLin Ling 
1815dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
1816dcbf3bd6SGeorge Wilson 	ASSERT(hdr->b_l1hdr.b_freeze_cksum != NULL ||
1817dcbf3bd6SGeorge Wilson 	    hdr->b_l1hdr.b_state == arc_anon);
1818dcbf3bd6SGeorge Wilson 	arc_cksum_compute(buf);
18193f9d6ad7SLin Ling 	mutex_exit(hash_lock);
18206b4acc8bSahrens }
18216b4acc8bSahrens 
1822dcbf3bd6SGeorge Wilson /*
1823dcbf3bd6SGeorge Wilson  * The arc_buf_hdr_t's b_flags should never be modified directly. Instead,
1824dcbf3bd6SGeorge Wilson  * the following functions should be used to ensure that the flags are
1825dcbf3bd6SGeorge Wilson  * updated in a thread-safe way. When manipulating the flags either
1826dcbf3bd6SGeorge Wilson  * the hash_lock must be held or the hdr must be undiscoverable. This
1827dcbf3bd6SGeorge Wilson  * ensures that we're not racing with any other threads when updating
1828dcbf3bd6SGeorge Wilson  * the flags.
1829dcbf3bd6SGeorge Wilson  */
1830dcbf3bd6SGeorge Wilson static inline void
1831dcbf3bd6SGeorge Wilson arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
1832dcbf3bd6SGeorge Wilson {
1833dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
1834dcbf3bd6SGeorge Wilson 	hdr->b_flags |= flags;
1835dcbf3bd6SGeorge Wilson }
1836dcbf3bd6SGeorge Wilson 
1837dcbf3bd6SGeorge Wilson static inline void
1838dcbf3bd6SGeorge Wilson arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
1839dcbf3bd6SGeorge Wilson {
1840dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
1841dcbf3bd6SGeorge Wilson 	hdr->b_flags &= ~flags;
1842dcbf3bd6SGeorge Wilson }
1843dcbf3bd6SGeorge Wilson 
1844dcbf3bd6SGeorge Wilson /*
1845dcbf3bd6SGeorge Wilson  * Setting the compression bits in the arc_buf_hdr_t's b_flags is
1846dcbf3bd6SGeorge Wilson  * done in a special way since we have to clear and set bits
1847dcbf3bd6SGeorge Wilson  * at the same time. Consumers that wish to set the compression bits
1848dcbf3bd6SGeorge Wilson  * must use this function to ensure that the flags are updated in
1849dcbf3bd6SGeorge Wilson  * thread-safe manner.
1850dcbf3bd6SGeorge Wilson  */
1851fa9e4066Sahrens static void
1852dcbf3bd6SGeorge Wilson arc_hdr_set_compress(arc_buf_hdr_t *hdr, enum zio_compress cmp)
1853fa9e4066Sahrens {
1854dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
1855fa9e4066Sahrens 
1856dcbf3bd6SGeorge Wilson 	/*
1857dcbf3bd6SGeorge Wilson 	 * Holes and embedded blocks will always have a psize = 0 so
1858dcbf3bd6SGeorge Wilson 	 * we ignore the compression of the blkptr and set the
1859dcbf3bd6SGeorge Wilson 	 * arc_buf_hdr_t's compression to ZIO_COMPRESS_OFF.
1860dcbf3bd6SGeorge Wilson 	 * Holes and embedded blocks remain anonymous so we don't
1861dcbf3bd6SGeorge Wilson 	 * want to uncompress them. Mark them as uncompressed.
1862dcbf3bd6SGeorge Wilson 	 */
1863dcbf3bd6SGeorge Wilson 	if (!zfs_compressed_arc_enabled || HDR_GET_PSIZE(hdr) == 0) {
1864dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
1865dcbf3bd6SGeorge Wilson 		HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_OFF);
1866dcbf3bd6SGeorge Wilson 		ASSERT(!HDR_COMPRESSION_ENABLED(hdr));
1867dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
1868dcbf3bd6SGeorge Wilson 	} else {
1869dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
1870dcbf3bd6SGeorge Wilson 		HDR_SET_COMPRESS(hdr, cmp);
1871dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, cmp);
1872dcbf3bd6SGeorge Wilson 		ASSERT(HDR_COMPRESSION_ENABLED(hdr));
1873dcbf3bd6SGeorge Wilson 	}
1874dcbf3bd6SGeorge Wilson }
1875244781f1SPrakash Surya 
18765602294fSDan Kimmel /*
18775602294fSDan Kimmel  * Looks for another buf on the same hdr which has the data decompressed, copies
18785602294fSDan Kimmel  * from it, and returns true. If no such buf exists, returns false.
18795602294fSDan Kimmel  */
18805602294fSDan Kimmel static boolean_t
18815602294fSDan Kimmel arc_buf_try_copy_decompressed_data(arc_buf_t *buf)
18825602294fSDan Kimmel {
18835602294fSDan Kimmel 	arc_buf_hdr_t *hdr = buf->b_hdr;
18845602294fSDan Kimmel 	boolean_t copied = B_FALSE;
18855602294fSDan Kimmel 
18865602294fSDan Kimmel 	ASSERT(HDR_HAS_L1HDR(hdr));
18875602294fSDan Kimmel 	ASSERT3P(buf->b_data, !=, NULL);
18885602294fSDan Kimmel 	ASSERT(!ARC_BUF_COMPRESSED(buf));
18895602294fSDan Kimmel 
18905602294fSDan Kimmel 	for (arc_buf_t *from = hdr->b_l1hdr.b_buf; from != NULL;
18915602294fSDan Kimmel 	    from = from->b_next) {
18925602294fSDan Kimmel 		/* can't use our own data buffer */
18935602294fSDan Kimmel 		if (from == buf) {
18945602294fSDan Kimmel 			continue;
18955602294fSDan Kimmel 		}
18965602294fSDan Kimmel 
18975602294fSDan Kimmel 		if (!ARC_BUF_COMPRESSED(from)) {
18985602294fSDan Kimmel 			bcopy(from->b_data, buf->b_data, arc_buf_size(buf));
18995602294fSDan Kimmel 			copied = B_TRUE;
19005602294fSDan Kimmel 			break;
19015602294fSDan Kimmel 		}
19025602294fSDan Kimmel 	}
19035602294fSDan Kimmel 
19045602294fSDan Kimmel 	/*
19055602294fSDan Kimmel 	 * There were no decompressed bufs, so there should not be a
19065602294fSDan Kimmel 	 * checksum on the hdr either.
19075602294fSDan Kimmel 	 */
19085602294fSDan Kimmel 	EQUIV(!copied, hdr->b_l1hdr.b_freeze_cksum == NULL);
19095602294fSDan Kimmel 
19105602294fSDan Kimmel 	return (copied);
19115602294fSDan Kimmel }
19125602294fSDan Kimmel 
19135602294fSDan Kimmel /*
19145602294fSDan Kimmel  * Given a buf that has a data buffer attached to it, this function will
19155602294fSDan Kimmel  * efficiently fill the buf with data of the specified compression setting from
19165602294fSDan Kimmel  * the hdr and update the hdr's b_freeze_cksum if necessary. If the buf and hdr
19175602294fSDan Kimmel  * are already sharing a data buf, no copy is performed.
19185602294fSDan Kimmel  *
19195602294fSDan Kimmel  * If the buf is marked as compressed but uncompressed data was requested, this
19205602294fSDan Kimmel  * will allocate a new data buffer for the buf, remove that flag, and fill the
19215602294fSDan Kimmel  * buf with uncompressed data. You can't request a compressed buf on a hdr with
19225602294fSDan Kimmel  * uncompressed data, and (since we haven't added support for it yet) if you
19235602294fSDan Kimmel  * want compressed data your buf must already be marked as compressed and have
19245602294fSDan Kimmel  * the correct-sized data buffer.
19255602294fSDan Kimmel  */
1926dcbf3bd6SGeorge Wilson static int
19275602294fSDan Kimmel arc_buf_fill(arc_buf_t *buf, boolean_t compressed)
1928dcbf3bd6SGeorge Wilson {
1929dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
19305602294fSDan Kimmel 	boolean_t hdr_compressed = (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
1931dcbf3bd6SGeorge Wilson 	dmu_object_byteswap_t bswap = hdr->b_l1hdr.b_byteswap;
193289c86e32SChris Williamson 
19335602294fSDan Kimmel 	ASSERT3P(buf->b_data, !=, NULL);
19345602294fSDan Kimmel 	IMPLY(compressed, hdr_compressed);
19355602294fSDan Kimmel 	IMPLY(compressed, ARC_BUF_COMPRESSED(buf));
19365602294fSDan Kimmel 
19375602294fSDan Kimmel 	if (hdr_compressed == compressed) {
19385602294fSDan Kimmel 		if (!arc_buf_is_shared(buf)) {
1939770499e1SDan Kimmel 			abd_copy_to_buf(buf->b_data, hdr->b_l1hdr.b_pabd,
19405602294fSDan Kimmel 			    arc_buf_size(buf));
19415602294fSDan Kimmel 		}
1942dcbf3bd6SGeorge Wilson 	} else {
19435602294fSDan Kimmel 		ASSERT(hdr_compressed);
19445602294fSDan Kimmel 		ASSERT(!compressed);
1945dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, HDR_GET_PSIZE(hdr));
19465602294fSDan Kimmel 
19475602294fSDan Kimmel 		/*
19485602294fSDan Kimmel 		 * If the buf is sharing its data with the hdr, unlink it and
19495602294fSDan Kimmel 		 * allocate a new data buffer for the buf.
19505602294fSDan Kimmel 		 */
19515602294fSDan Kimmel 		if (arc_buf_is_shared(buf)) {
19525602294fSDan Kimmel 			ASSERT(ARC_BUF_COMPRESSED(buf));
19535602294fSDan Kimmel 
19545602294fSDan Kimmel 			/* We need to give the buf it's own b_data */
19555602294fSDan Kimmel 			buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
19565602294fSDan Kimmel 			buf->b_data =
19575602294fSDan Kimmel 			    arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
19585602294fSDan Kimmel 			arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
19595602294fSDan Kimmel 
19605602294fSDan Kimmel 			/* Previously overhead was 0; just add new overhead */
19615602294fSDan Kimmel 			ARCSTAT_INCR(arcstat_overhead_size, HDR_GET_LSIZE(hdr));
19625602294fSDan Kimmel 		} else if (ARC_BUF_COMPRESSED(buf)) {
19635602294fSDan Kimmel 			/* We need to reallocate the buf's b_data */
19645602294fSDan Kimmel 			arc_free_data_buf(hdr, buf->b_data, HDR_GET_PSIZE(hdr),
19655602294fSDan Kimmel 			    buf);
19665602294fSDan Kimmel 			buf->b_data =
19675602294fSDan Kimmel 			    arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
19685602294fSDan Kimmel 
19695602294fSDan Kimmel 			/* We increased the size of b_data; update overhead */
19705602294fSDan Kimmel 			ARCSTAT_INCR(arcstat_overhead_size,
19715602294fSDan Kimmel 			    HDR_GET_LSIZE(hdr) - HDR_GET_PSIZE(hdr));
19725602294fSDan Kimmel 		}
19735602294fSDan Kimmel 
19745602294fSDan Kimmel 		/*
19755602294fSDan Kimmel 		 * Regardless of the buf's previous compression settings, it
19765602294fSDan Kimmel 		 * should not be compressed at the end of this function.
19775602294fSDan Kimmel 		 */
19785602294fSDan Kimmel 		buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
19795602294fSDan Kimmel 
19805602294fSDan Kimmel 		/*
19815602294fSDan Kimmel 		 * Try copying the data from another buf which already has a
19825602294fSDan Kimmel 		 * decompressed version. If that's not possible, it's time to
19835602294fSDan Kimmel 		 * bite the bullet and decompress the data from the hdr.
19845602294fSDan Kimmel 		 */
19855602294fSDan Kimmel 		if (arc_buf_try_copy_decompressed_data(buf)) {
19865602294fSDan Kimmel 			/* Skip byteswapping and checksumming (already done) */
19875602294fSDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, !=, NULL);
19885602294fSDan Kimmel 			return (0);
19895602294fSDan Kimmel 		} else {
19905602294fSDan Kimmel 			int error = zio_decompress_data(HDR_GET_COMPRESS(hdr),
1991770499e1SDan Kimmel 			    hdr->b_l1hdr.b_pabd, buf->b_data,
19925602294fSDan Kimmel 			    HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
19935602294fSDan Kimmel 
19945602294fSDan Kimmel 			/*
19955602294fSDan Kimmel 			 * Absent hardware errors or software bugs, this should
19965602294fSDan Kimmel 			 * be impossible, but log it anyway so we can debug it.
19975602294fSDan Kimmel 			 */
19985602294fSDan Kimmel 			if (error != 0) {
19995602294fSDan Kimmel 				zfs_dbgmsg(
20005602294fSDan Kimmel 				    "hdr %p, compress %d, psize %d, lsize %d",
20015602294fSDan Kimmel 				    hdr, HDR_GET_COMPRESS(hdr),
20025602294fSDan Kimmel 				    HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
20035602294fSDan Kimmel 				return (SET_ERROR(EIO));
20045602294fSDan Kimmel 			}
2005ea8dc4b6Seschrock 		}
2006fa9e4066Sahrens 	}
20075602294fSDan Kimmel 
20085602294fSDan Kimmel 	/* Byteswap the buf's data if necessary */
2009dcbf3bd6SGeorge Wilson 	if (bswap != DMU_BSWAP_NUMFUNCS) {
2010dcbf3bd6SGeorge Wilson 		ASSERT(!HDR_SHARED_DATA(hdr));
2011dcbf3bd6SGeorge Wilson 		ASSERT3U(bswap, <, DMU_BSWAP_NUMFUNCS);
2012dcbf3bd6SGeorge Wilson 		dmu_ot_byteswap[bswap].ob_func(buf->b_data, HDR_GET_LSIZE(hdr));
2013dcbf3bd6SGeorge Wilson 	}
20145602294fSDan Kimmel 
20155602294fSDan Kimmel 	/* Compute the hdr's checksum if necessary */
2016dcbf3bd6SGeorge Wilson 	arc_cksum_compute(buf);
20175602294fSDan Kimmel 
2018dcbf3bd6SGeorge Wilson 	return (0);
2019fa9e4066Sahrens }
2020fa9e4066Sahrens 
20215602294fSDan Kimmel int
20225602294fSDan Kimmel arc_decompress(arc_buf_t *buf)
20235602294fSDan Kimmel {
20245602294fSDan Kimmel 	return (arc_buf_fill(buf, B_FALSE));
20255602294fSDan Kimmel }
20265602294fSDan Kimmel 
2027dcbf3bd6SGeorge Wilson /*
2028770499e1SDan Kimmel  * Return the size of the block, b_pabd, that is stored in the arc_buf_hdr_t.
2029dcbf3bd6SGeorge Wilson  */
2030dcbf3bd6SGeorge Wilson static uint64_t
2031dcbf3bd6SGeorge Wilson arc_hdr_size(arc_buf_hdr_t *hdr)
2032fa9e4066Sahrens {
2033dcbf3bd6SGeorge Wilson 	uint64_t size;
2034fa9e4066Sahrens 
2035dcbf3bd6SGeorge Wilson 	if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
2036dcbf3bd6SGeorge Wilson 	    HDR_GET_PSIZE(hdr) > 0) {
2037dcbf3bd6SGeorge Wilson 		size = HDR_GET_PSIZE(hdr);
2038dcbf3bd6SGeorge Wilson 	} else {
2039dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, 0);
2040dcbf3bd6SGeorge Wilson 		size = HDR_GET_LSIZE(hdr);
2041dcbf3bd6SGeorge Wilson 	}
2042dcbf3bd6SGeorge Wilson 	return (size);
2043dcbf3bd6SGeorge Wilson }
2044fa9e4066Sahrens 
2045dcbf3bd6SGeorge Wilson /*
2046dcbf3bd6SGeorge Wilson  * Increment the amount of evictable space in the arc_state_t's refcount.
2047dcbf3bd6SGeorge Wilson  * We account for the space used by the hdr and the arc buf individually
2048dcbf3bd6SGeorge Wilson  * so that we can add and remove them from the refcount individually.
2049dcbf3bd6SGeorge Wilson  */
2050dcbf3bd6SGeorge Wilson static void
2051dcbf3bd6SGeorge Wilson arc_evictable_space_increment(arc_buf_hdr_t *hdr, arc_state_t *state)
2052dcbf3bd6SGeorge Wilson {
2053dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type = arc_buf_type(hdr);
2054244781f1SPrakash Surya 
2055dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
20560e8c6158Smaybee 
2057dcbf3bd6SGeorge Wilson 	if (GHOST_STATE(state)) {
2058dcbf3bd6SGeorge Wilson 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
2059dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2060770499e1SDan Kimmel 		ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
20615602294fSDan Kimmel 		(void) refcount_add_many(&state->arcs_esize[type],
20625602294fSDan Kimmel 		    HDR_GET_LSIZE(hdr), hdr);
2063dcbf3bd6SGeorge Wilson 		return;
2064dcbf3bd6SGeorge Wilson 	}
2065dcbf3bd6SGeorge Wilson 
2066dcbf3bd6SGeorge Wilson 	ASSERT(!GHOST_STATE(state));
2067770499e1SDan Kimmel 	if (hdr->b_l1hdr.b_pabd != NULL) {
2068dcbf3bd6SGeorge Wilson 		(void) refcount_add_many(&state->arcs_esize[type],
2069dcbf3bd6SGeorge Wilson 		    arc_hdr_size(hdr), hdr);
2070dcbf3bd6SGeorge Wilson 	}
2071dcbf3bd6SGeorge Wilson 	for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2072dcbf3bd6SGeorge Wilson 	    buf = buf->b_next) {
20735602294fSDan Kimmel 		if (arc_buf_is_shared(buf))
2074dcbf3bd6SGeorge Wilson 			continue;
20755602294fSDan Kimmel 		(void) refcount_add_many(&state->arcs_esize[type],
20765602294fSDan Kimmel 		    arc_buf_size(buf), buf);
2077fa9e4066Sahrens 	}
2078fa9e4066Sahrens }
2079fa9e4066Sahrens 
2080fa9e4066Sahrens /*
2081dcbf3bd6SGeorge Wilson  * Decrement the amount of evictable space in the arc_state_t's refcount.
2082dcbf3bd6SGeorge Wilson  * We account for the space used by the hdr and the arc buf individually
2083dcbf3bd6SGeorge Wilson  * so that we can add and remove them from the refcount individually.
2084fa9e4066Sahrens  */
2085fa9e4066Sahrens static void
20865602294fSDan Kimmel arc_evictable_space_decrement(arc_buf_hdr_t *hdr, arc_state_t *state)
2087fa9e4066Sahrens {
2088dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type = arc_buf_type(hdr);
2089dcbf3bd6SGeorge Wilson 
2090dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2091dcbf3bd6SGeorge Wilson 
2092dcbf3bd6SGeorge Wilson 	if (GHOST_STATE(state)) {
2093dcbf3bd6SGeorge Wilson 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
2094dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2095770499e1SDan Kimmel 		ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2096dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_esize[type],
20975602294fSDan Kimmel 		    HDR_GET_LSIZE(hdr), hdr);
2098dcbf3bd6SGeorge Wilson 		return;
2099dcbf3bd6SGeorge Wilson 	}
2100dcbf3bd6SGeorge Wilson 
2101dcbf3bd6SGeorge Wilson 	ASSERT(!GHOST_STATE(state));
2102770499e1SDan Kimmel 	if (hdr->b_l1hdr.b_pabd != NULL) {
2103dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_esize[type],
2104dcbf3bd6SGeorge Wilson 		    arc_hdr_size(hdr), hdr);
2105dcbf3bd6SGeorge Wilson 	}
2106dcbf3bd6SGeorge Wilson 	for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2107dcbf3bd6SGeorge Wilson 	    buf = buf->b_next) {
21085602294fSDan Kimmel 		if (arc_buf_is_shared(buf))
2109dcbf3bd6SGeorge Wilson 			continue;
2110dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_esize[type],
21115602294fSDan Kimmel 		    arc_buf_size(buf), buf);
2112dcbf3bd6SGeorge Wilson 	}
2113dcbf3bd6SGeorge Wilson }
2114dcbf3bd6SGeorge Wilson 
2115dcbf3bd6SGeorge Wilson /*
2116dcbf3bd6SGeorge Wilson  * Add a reference to this hdr indicating that someone is actively
2117dcbf3bd6SGeorge Wilson  * referencing that memory. When the refcount transitions from 0 to 1,
2118dcbf3bd6SGeorge Wilson  * we remove it from the respective arc_state_t list to indicate that
2119dcbf3bd6SGeorge Wilson  * it is not evictable.
2120dcbf3bd6SGeorge Wilson  */
2121dcbf3bd6SGeorge Wilson static void
2122dcbf3bd6SGeorge Wilson add_reference(arc_buf_hdr_t *hdr, void *tag)
2123dcbf3bd6SGeorge Wilson {
2124dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2125dcbf3bd6SGeorge Wilson 	if (!MUTEX_HELD(HDR_LOCK(hdr))) {
2126dcbf3bd6SGeorge Wilson 		ASSERT(hdr->b_l1hdr.b_state == arc_anon);
2127dcbf3bd6SGeorge Wilson 		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2128dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2129dcbf3bd6SGeorge Wilson 	}
2130dcbf3bd6SGeorge Wilson 
2131dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
2132dcbf3bd6SGeorge Wilson 
2133dcbf3bd6SGeorge Wilson 	if ((refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
2134dcbf3bd6SGeorge Wilson 	    (state != arc_anon)) {
2135dcbf3bd6SGeorge Wilson 		/* We don't use the L2-only state list. */
2136dcbf3bd6SGeorge Wilson 		if (state != arc_l2c_only) {
213794c2d0ebSMatthew Ahrens 			multilist_remove(state->arcs_list[arc_buf_type(hdr)],
2138dcbf3bd6SGeorge Wilson 			    hdr);
21395602294fSDan Kimmel 			arc_evictable_space_decrement(hdr, state);
2140dcbf3bd6SGeorge Wilson 		}
2141dcbf3bd6SGeorge Wilson 		/* remove the prefetch flag if we get a reference */
2142dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
2143dcbf3bd6SGeorge Wilson 	}
2144dcbf3bd6SGeorge Wilson }
2145dcbf3bd6SGeorge Wilson 
2146dcbf3bd6SGeorge Wilson /*
2147dcbf3bd6SGeorge Wilson  * Remove a reference from this hdr. When the reference transitions from
2148dcbf3bd6SGeorge Wilson  * 1 to 0 and we're not anonymous, then we add this hdr to the arc_state_t's
2149dcbf3bd6SGeorge Wilson  * list making it eligible for eviction.
2150dcbf3bd6SGeorge Wilson  */
2151dcbf3bd6SGeorge Wilson static int
2152dcbf3bd6SGeorge Wilson remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
2153dcbf3bd6SGeorge Wilson {
2154dcbf3bd6SGeorge Wilson 	int cnt;
2155dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
2156dcbf3bd6SGeorge Wilson 
2157dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2158dcbf3bd6SGeorge Wilson 	ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
2159dcbf3bd6SGeorge Wilson 	ASSERT(!GHOST_STATE(state));
2160dcbf3bd6SGeorge Wilson 
2161dcbf3bd6SGeorge Wilson 	/*
2162dcbf3bd6SGeorge Wilson 	 * arc_l2c_only counts as a ghost state so we don't need to explicitly
2163dcbf3bd6SGeorge Wilson 	 * check to prevent usage of the arc_l2c_only list.
2164dcbf3bd6SGeorge Wilson 	 */
2165dcbf3bd6SGeorge Wilson 	if (((cnt = refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
2166dcbf3bd6SGeorge Wilson 	    (state != arc_anon)) {
216794c2d0ebSMatthew Ahrens 		multilist_insert(state->arcs_list[arc_buf_type(hdr)], hdr);
2168dcbf3bd6SGeorge Wilson 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
2169dcbf3bd6SGeorge Wilson 		arc_evictable_space_increment(hdr, state);
2170dcbf3bd6SGeorge Wilson 	}
2171dcbf3bd6SGeorge Wilson 	return (cnt);
2172dcbf3bd6SGeorge Wilson }
2173dcbf3bd6SGeorge Wilson 
2174dcbf3bd6SGeorge Wilson /*
2175dcbf3bd6SGeorge Wilson  * Move the supplied buffer to the indicated state. The hash lock
2176dcbf3bd6SGeorge Wilson  * for the buffer must be held by the caller.
2177dcbf3bd6SGeorge Wilson  */
2178dcbf3bd6SGeorge Wilson static void
2179dcbf3bd6SGeorge Wilson arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
2180dcbf3bd6SGeorge Wilson     kmutex_t *hash_lock)
2181dcbf3bd6SGeorge Wilson {
2182dcbf3bd6SGeorge Wilson 	arc_state_t *old_state;
2183dcbf3bd6SGeorge Wilson 	int64_t refcnt;
2184dcbf3bd6SGeorge Wilson 	uint32_t bufcnt;
2185dcbf3bd6SGeorge Wilson 	boolean_t update_old, update_new;
2186dcbf3bd6SGeorge Wilson 	arc_buf_contents_t buftype = arc_buf_type(hdr);
218789c86e32SChris Williamson 
218889c86e32SChris Williamson 	/*
218989c86e32SChris Williamson 	 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
219089c86e32SChris Williamson 	 * in arc_read() when bringing a buffer out of the L2ARC.  However, the
219189c86e32SChris Williamson 	 * L1 hdr doesn't always exist when we change state to arc_anon before
219289c86e32SChris Williamson 	 * destroying a header, in which case reallocating to add the L1 hdr is
219389c86e32SChris Williamson 	 * pointless.
219489c86e32SChris Williamson 	 */
219589c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr)) {
219689c86e32SChris Williamson 		old_state = hdr->b_l1hdr.b_state;
219789c86e32SChris Williamson 		refcnt = refcount_count(&hdr->b_l1hdr.b_refcnt);
2198dcbf3bd6SGeorge Wilson 		bufcnt = hdr->b_l1hdr.b_bufcnt;
2199770499e1SDan Kimmel 		update_old = (bufcnt > 0 || hdr->b_l1hdr.b_pabd != NULL);
220089c86e32SChris Williamson 	} else {
220189c86e32SChris Williamson 		old_state = arc_l2c_only;
220289c86e32SChris Williamson 		refcnt = 0;
2203dcbf3bd6SGeorge Wilson 		bufcnt = 0;
2204dcbf3bd6SGeorge Wilson 		update_old = B_FALSE;
220589c86e32SChris Williamson 	}
2206dcbf3bd6SGeorge Wilson 	update_new = update_old;
2207fa9e4066Sahrens 
2208fa9e4066Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
220969962b56SMatthew Ahrens 	ASSERT3P(new_state, !=, old_state);
2210dcbf3bd6SGeorge Wilson 	ASSERT(!GHOST_STATE(new_state) || bufcnt == 0);
2211dcbf3bd6SGeorge Wilson 	ASSERT(old_state != arc_anon || bufcnt <= 1);
2212fa9e4066Sahrens 
2213fa9e4066Sahrens 	/*
2214fa9e4066Sahrens 	 * If this buffer is evictable, transfer it from the
2215fa9e4066Sahrens 	 * old state list to the new state list.
2216fa9e4066Sahrens 	 */
2217ea8dc4b6Seschrock 	if (refcnt == 0) {
221889c86e32SChris Williamson 		if (old_state != arc_anon && old_state != arc_l2c_only) {
221989c86e32SChris Williamson 			ASSERT(HDR_HAS_L1HDR(hdr));
222094c2d0ebSMatthew Ahrens 			multilist_remove(old_state->arcs_list[buftype], hdr);
2221ea8dc4b6Seschrock 
2222dcbf3bd6SGeorge Wilson 			if (GHOST_STATE(old_state)) {
2223dcbf3bd6SGeorge Wilson 				ASSERT0(bufcnt);
2224dcbf3bd6SGeorge Wilson 				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2225dcbf3bd6SGeorge Wilson 				update_old = B_TRUE;
2226ea8dc4b6Seschrock 			}
22275602294fSDan Kimmel 			arc_evictable_space_decrement(hdr, old_state);
2228fa9e4066Sahrens 		}
222989c86e32SChris Williamson 		if (new_state != arc_anon && new_state != arc_l2c_only) {
2230fa9e4066Sahrens 
223189c86e32SChris Williamson 			/*
223289c86e32SChris Williamson 			 * An L1 header always exists here, since if we're
223389c86e32SChris Williamson 			 * moving to some L1-cached state (i.e. not l2c_only or
223489c86e32SChris Williamson 			 * anonymous), we realloc the header to add an L1hdr
223589c86e32SChris Williamson 			 * beforehand.
223689c86e32SChris Williamson 			 */
223789c86e32SChris Williamson 			ASSERT(HDR_HAS_L1HDR(hdr));
223894c2d0ebSMatthew Ahrens 			multilist_insert(new_state->arcs_list[buftype], hdr);
2239ea8dc4b6Seschrock 
2240ea8dc4b6Seschrock 			if (GHOST_STATE(new_state)) {
2241dcbf3bd6SGeorge Wilson 				ASSERT0(bufcnt);
2242dcbf3bd6SGeorge Wilson 				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2243dcbf3bd6SGeorge Wilson 				update_new = B_TRUE;
2244ea8dc4b6Seschrock 			}
2245dcbf3bd6SGeorge Wilson 			arc_evictable_space_increment(hdr, new_state);
2246fa9e4066Sahrens 		}
2247fa9e4066Sahrens 	}
2248fa9e4066Sahrens 
2249dcbf3bd6SGeorge Wilson 	ASSERT(!HDR_EMPTY(hdr));
22507adb730bSGeorge Wilson 	if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
22517adb730bSGeorge Wilson 		buf_hash_remove(hdr);
2252fa9e4066Sahrens 
225389c86e32SChris Williamson 	/* adjust state sizes (ignore arc_l2c_only) */
22542fd872a7SPrakash Surya 
2255dcbf3bd6SGeorge Wilson 	if (update_new && new_state != arc_l2c_only) {
22562fd872a7SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(hdr));
22572fd872a7SPrakash Surya 		if (GHOST_STATE(new_state)) {
2258dcbf3bd6SGeorge Wilson 			ASSERT0(bufcnt);
22592fd872a7SPrakash Surya 
22602fd872a7SPrakash Surya 			/*
2261dcbf3bd6SGeorge Wilson 			 * When moving a header to a ghost state, we first
22622fd872a7SPrakash Surya 			 * remove all arc buffers. Thus, we'll have a
2263dcbf3bd6SGeorge Wilson 			 * bufcnt of zero, and no arc buffer to use for
22642fd872a7SPrakash Surya 			 * the reference. As a result, we use the arc
22652fd872a7SPrakash Surya 			 * header pointer for the reference.
22662fd872a7SPrakash Surya 			 */
22672fd872a7SPrakash Surya 			(void) refcount_add_many(&new_state->arcs_size,
2268dcbf3bd6SGeorge Wilson 			    HDR_GET_LSIZE(hdr), hdr);
2269770499e1SDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
22702fd872a7SPrakash Surya 		} else {
2271dcbf3bd6SGeorge Wilson 			uint32_t buffers = 0;
22722fd872a7SPrakash Surya 
22732fd872a7SPrakash Surya 			/*
22742fd872a7SPrakash Surya 			 * Each individual buffer holds a unique reference,
22752fd872a7SPrakash Surya 			 * thus we must remove each of these references one
22762fd872a7SPrakash Surya 			 * at a time.
22772fd872a7SPrakash Surya 			 */
22782fd872a7SPrakash Surya 			for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
22792fd872a7SPrakash Surya 			    buf = buf->b_next) {
2280dcbf3bd6SGeorge Wilson 				ASSERT3U(bufcnt, !=, 0);
2281dcbf3bd6SGeorge Wilson 				buffers++;
2282dcbf3bd6SGeorge Wilson 
2283dcbf3bd6SGeorge Wilson 				/*
2284dcbf3bd6SGeorge Wilson 				 * When the arc_buf_t is sharing the data
2285dcbf3bd6SGeorge Wilson 				 * block with the hdr, the owner of the
2286dcbf3bd6SGeorge Wilson 				 * reference belongs to the hdr. Only
2287dcbf3bd6SGeorge Wilson 				 * add to the refcount if the arc_buf_t is
2288dcbf3bd6SGeorge Wilson 				 * not shared.
2289dcbf3bd6SGeorge Wilson 				 */
22905602294fSDan Kimmel 				if (arc_buf_is_shared(buf))
2291dcbf3bd6SGeorge Wilson 					continue;
2292dcbf3bd6SGeorge Wilson 
22932fd872a7SPrakash Surya 				(void) refcount_add_many(&new_state->arcs_size,
22945602294fSDan Kimmel 				    arc_buf_size(buf), buf);
2295dcbf3bd6SGeorge Wilson 			}
2296dcbf3bd6SGeorge Wilson 			ASSERT3U(bufcnt, ==, buffers);
2297dcbf3bd6SGeorge Wilson 
2298770499e1SDan Kimmel 			if (hdr->b_l1hdr.b_pabd != NULL) {
2299dcbf3bd6SGeorge Wilson 				(void) refcount_add_many(&new_state->arcs_size,
2300dcbf3bd6SGeorge Wilson 				    arc_hdr_size(hdr), hdr);
2301dcbf3bd6SGeorge Wilson 			} else {
2302dcbf3bd6SGeorge Wilson 				ASSERT(GHOST_STATE(old_state));
23032fd872a7SPrakash Surya 			}
23042fd872a7SPrakash Surya 		}
23052fd872a7SPrakash Surya 	}
23062fd872a7SPrakash Surya 
2307dcbf3bd6SGeorge Wilson 	if (update_old && old_state != arc_l2c_only) {
23082fd872a7SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(hdr));
23092fd872a7SPrakash Surya 		if (GHOST_STATE(old_state)) {
2310dcbf3bd6SGeorge Wilson 			ASSERT0(bufcnt);
2311770499e1SDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2312dcbf3bd6SGeorge Wilson 
23132fd872a7SPrakash Surya 			/*
23142fd872a7SPrakash Surya 			 * When moving a header off of a ghost state,
2315dcbf3bd6SGeorge Wilson 			 * the header will not contain any arc buffers.
2316dcbf3bd6SGeorge Wilson 			 * We use the arc header pointer for the reference
2317dcbf3bd6SGeorge Wilson 			 * which is exactly what we did when we put the
2318dcbf3bd6SGeorge Wilson 			 * header on the ghost state.
23192fd872a7SPrakash Surya 			 */
23202fd872a7SPrakash Surya 
23212fd872a7SPrakash Surya 			(void) refcount_remove_many(&old_state->arcs_size,
2322dcbf3bd6SGeorge Wilson 			    HDR_GET_LSIZE(hdr), hdr);
23232fd872a7SPrakash Surya 		} else {
2324dcbf3bd6SGeorge Wilson 			uint32_t buffers = 0;
23252fd872a7SPrakash Surya 
23262fd872a7SPrakash Surya 			/*
23272fd872a7SPrakash Surya 			 * Each individual buffer holds a unique reference,
23282fd872a7SPrakash Surya 			 * thus we must remove each of these references one
23292fd872a7SPrakash Surya 			 * at a time.
23302fd872a7SPrakash Surya 			 */
23312fd872a7SPrakash Surya 			for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
23322fd872a7SPrakash Surya 			    buf = buf->b_next) {
23335602294fSDan Kimmel 				ASSERT3U(bufcnt, !=, 0);
2334dcbf3bd6SGeorge Wilson 				buffers++;
2335dcbf3bd6SGeorge Wilson 
2336dcbf3bd6SGeorge Wilson 				/*
2337dcbf3bd6SGeorge Wilson 				 * When the arc_buf_t is sharing the data
2338dcbf3bd6SGeorge Wilson 				 * block with the hdr, the owner of the
2339dcbf3bd6SGeorge Wilson 				 * reference belongs to the hdr. Only
2340dcbf3bd6SGeorge Wilson 				 * add to the refcount if the arc_buf_t is
2341dcbf3bd6SGeorge Wilson 				 * not shared.
2342dcbf3bd6SGeorge Wilson 				 */
23435602294fSDan Kimmel 				if (arc_buf_is_shared(buf))
2344dcbf3bd6SGeorge Wilson 					continue;
2345dcbf3bd6SGeorge Wilson 
23462fd872a7SPrakash Surya 				(void) refcount_remove_many(
23475602294fSDan Kimmel 				    &old_state->arcs_size, arc_buf_size(buf),
2348dcbf3bd6SGeorge Wilson 				    buf);
23492fd872a7SPrakash Surya 			}
2350dcbf3bd6SGeorge Wilson 			ASSERT3U(bufcnt, ==, buffers);
2351770499e1SDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2352dcbf3bd6SGeorge Wilson 			(void) refcount_remove_many(
2353dcbf3bd6SGeorge Wilson 			    &old_state->arcs_size, arc_hdr_size(hdr), hdr);
23542fd872a7SPrakash Surya 		}
2355fa9e4066Sahrens 	}
23562fd872a7SPrakash Surya 
235789c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr))
235889c86e32SChris Williamson 		hdr->b_l1hdr.b_state = new_state;
2359fa94a07fSbrendan 
236089c86e32SChris Williamson 	/*
236189c86e32SChris Williamson 	 * L2 headers should never be on the L2 state list since they don't
236289c86e32SChris Williamson 	 * have L1 headers allocated.
236389c86e32SChris Williamson 	 */
236494c2d0ebSMatthew Ahrens 	ASSERT(multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
236594c2d0ebSMatthew Ahrens 	    multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
2366fa9e4066Sahrens }
2367fa9e4066Sahrens 
23680e8c6158Smaybee void
23695a98e54bSBrendan Gregg - Sun Microsystems arc_space_consume(uint64_t space, arc_space_type_t type)
23700e8c6158Smaybee {
23715a98e54bSBrendan Gregg - Sun Microsystems 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
23725a98e54bSBrendan Gregg - Sun Microsystems 
23735a98e54bSBrendan Gregg - Sun Microsystems 	switch (type) {
23745a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_DATA:
23753a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_data_size, space);
23765a98e54bSBrendan Gregg - Sun Microsystems 		break;
23774076b1bfSPrakash Surya 	case ARC_SPACE_META:
23783a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_metadata_size, space);
23794076b1bfSPrakash Surya 		break;
23805a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_OTHER:
23813a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_other_size, space);
23825a98e54bSBrendan Gregg - Sun Microsystems 		break;
23835a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_HDRS:
23843a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_hdr_size, space);
23855a98e54bSBrendan Gregg - Sun Microsystems 		break;
23865a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_L2HDRS:
23873a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_l2_hdr_size, space);
23885a98e54bSBrendan Gregg - Sun Microsystems 		break;
23895a98e54bSBrendan Gregg - Sun Microsystems 	}
23905a98e54bSBrendan Gregg - Sun Microsystems 
23914076b1bfSPrakash Surya 	if (type != ARC_SPACE_DATA)
23923a2d8a1bSPaul Dagnelie 		aggsum_add(&arc_meta_used, space);
23934076b1bfSPrakash Surya 
23943a2d8a1bSPaul Dagnelie 	aggsum_add(&arc_size, space);
23950e8c6158Smaybee }
23960e8c6158Smaybee 
23970e8c6158Smaybee void
23985a98e54bSBrendan Gregg - Sun Microsystems arc_space_return(uint64_t space, arc_space_type_t type)
23990e8c6158Smaybee {
24005a98e54bSBrendan Gregg - Sun Microsystems 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
24015a98e54bSBrendan Gregg - Sun Microsystems 
24025a98e54bSBrendan Gregg - Sun Microsystems 	switch (type) {
24035a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_DATA:
24043a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_data_size, -space);
24055a98e54bSBrendan Gregg - Sun Microsystems 		break;
24064076b1bfSPrakash Surya 	case ARC_SPACE_META:
24073a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_metadata_size, -space);
24084076b1bfSPrakash Surya 		break;
24095a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_OTHER:
24103a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_other_size, -space);
24115a98e54bSBrendan Gregg - Sun Microsystems 		break;
24125a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_HDRS:
24133a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_hdr_size, -space);
24145a98e54bSBrendan Gregg - Sun Microsystems 		break;
24155a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_L2HDRS:
24163a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_l2_hdr_size, -space);
24175a98e54bSBrendan Gregg - Sun Microsystems 		break;
24185a98e54bSBrendan Gregg - Sun Microsystems 	}
24195a98e54bSBrendan Gregg - Sun Microsystems 
24204076b1bfSPrakash Surya 	if (type != ARC_SPACE_DATA) {
24213a2d8a1bSPaul Dagnelie 		ASSERT(aggsum_compare(&arc_meta_used, space) >= 0);
24223a2d8a1bSPaul Dagnelie 		/*
24233a2d8a1bSPaul Dagnelie 		 * We use the upper bound here rather than the precise value
24243a2d8a1bSPaul Dagnelie 		 * because the arc_meta_max value doesn't need to be
24253a2d8a1bSPaul Dagnelie 		 * precise. It's only consumed by humans via arcstats.
24263a2d8a1bSPaul Dagnelie 		 */
24273a2d8a1bSPaul Dagnelie 		if (arc_meta_max < aggsum_upper_bound(&arc_meta_used))
24283a2d8a1bSPaul Dagnelie 			arc_meta_max = aggsum_upper_bound(&arc_meta_used);
24293a2d8a1bSPaul Dagnelie 		aggsum_add(&arc_meta_used, -space);
24304076b1bfSPrakash Surya 	}
24314076b1bfSPrakash Surya 
24323a2d8a1bSPaul Dagnelie 	ASSERT(aggsum_compare(&arc_size, space) >= 0);
24333a2d8a1bSPaul Dagnelie 	aggsum_add(&arc_size, -space);
24340e8c6158Smaybee }
24350e8c6158Smaybee 
2436dcbf3bd6SGeorge Wilson /*
24375602294fSDan Kimmel  * Given a hdr and a buf, returns whether that buf can share its b_data buffer
2438770499e1SDan Kimmel  * with the hdr's b_pabd.
2439dcbf3bd6SGeorge Wilson  */
24405602294fSDan Kimmel static boolean_t
24415602294fSDan Kimmel arc_can_share(arc_buf_hdr_t *hdr, arc_buf_t *buf)
24425602294fSDan Kimmel {
24435602294fSDan Kimmel 	/*
24445602294fSDan Kimmel 	 * The criteria for sharing a hdr's data are:
24455602294fSDan Kimmel 	 * 1. the hdr's compression matches the buf's compression
24465602294fSDan Kimmel 	 * 2. the hdr doesn't need to be byteswapped
24475602294fSDan Kimmel 	 * 3. the hdr isn't already being shared
24485602294fSDan Kimmel 	 * 4. the buf is either compressed or it is the last buf in the hdr list
24495602294fSDan Kimmel 	 *
24505602294fSDan Kimmel 	 * Criterion #4 maintains the invariant that shared uncompressed
24515602294fSDan Kimmel 	 * bufs must be the final buf in the hdr's b_buf list. Reading this, you
24525602294fSDan Kimmel 	 * might ask, "if a compressed buf is allocated first, won't that be the
24535602294fSDan Kimmel 	 * last thing in the list?", but in that case it's impossible to create
24545602294fSDan Kimmel 	 * a shared uncompressed buf anyway (because the hdr must be compressed
24555602294fSDan Kimmel 	 * to have the compressed buf). You might also think that #3 is
24565602294fSDan Kimmel 	 * sufficient to make this guarantee, however it's possible
24575602294fSDan Kimmel 	 * (specifically in the rare L2ARC write race mentioned in
24585602294fSDan Kimmel 	 * arc_buf_alloc_impl()) there will be an existing uncompressed buf that
24595602294fSDan Kimmel 	 * is sharable, but wasn't at the time of its allocation. Rather than
24605602294fSDan Kimmel 	 * allow a new shared uncompressed buf to be created and then shuffle
24615602294fSDan Kimmel 	 * the list around to make it the last element, this simply disallows
24625602294fSDan Kimmel 	 * sharing if the new buf isn't the first to be added.
24635602294fSDan Kimmel 	 */
24645602294fSDan Kimmel 	ASSERT3P(buf->b_hdr, ==, hdr);
24655602294fSDan Kimmel 	boolean_t hdr_compressed = HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF;
24665602294fSDan Kimmel 	boolean_t buf_compressed = ARC_BUF_COMPRESSED(buf) != 0;
24675602294fSDan Kimmel 	return (buf_compressed == hdr_compressed &&
24685602294fSDan Kimmel 	    hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS &&
24695602294fSDan Kimmel 	    !HDR_SHARED_DATA(hdr) &&
24705602294fSDan Kimmel 	    (ARC_BUF_LAST(buf) || ARC_BUF_COMPRESSED(buf)));
24715602294fSDan Kimmel }
24725602294fSDan Kimmel 
24735602294fSDan Kimmel /*
24745602294fSDan Kimmel  * Allocate a buf for this hdr. If you care about the data that's in the hdr,
24755602294fSDan Kimmel  * or if you want a compressed buffer, pass those flags in. Returns 0 if the
24765602294fSDan Kimmel  * copy was made successfully, or an error code otherwise.
24775602294fSDan Kimmel  */
24785602294fSDan Kimmel static int
24795602294fSDan Kimmel arc_buf_alloc_impl(arc_buf_hdr_t *hdr, void *tag, boolean_t compressed,
24805602294fSDan Kimmel     boolean_t fill, arc_buf_t **ret)
2481fa9e4066Sahrens {
2482fa9e4066Sahrens 	arc_buf_t *buf;
2483fa9e4066Sahrens 
2484dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2485dcbf3bd6SGeorge Wilson 	ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
2486dcbf3bd6SGeorge Wilson 	VERIFY(hdr->b_type == ARC_BUFC_DATA ||
2487dcbf3bd6SGeorge Wilson 	    hdr->b_type == ARC_BUFC_METADATA);
24885602294fSDan Kimmel 	ASSERT3P(ret, !=, NULL);
24895602294fSDan Kimmel 	ASSERT3P(*ret, ==, NULL);
2490dcbf3bd6SGeorge Wilson 
24915602294fSDan Kimmel 	buf = *ret = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2492fa9e4066Sahrens 	buf->b_hdr = hdr;
249344eda4d7Smaybee 	buf->b_data = NULL;
24945602294fSDan Kimmel 	buf->b_next = hdr->b_l1hdr.b_buf;
24955602294fSDan Kimmel 	buf->b_flags = 0;
249689c86e32SChris Williamson 
2497dcbf3bd6SGeorge Wilson 	add_reference(hdr, tag);
2498dcbf3bd6SGeorge Wilson 
2499dcbf3bd6SGeorge Wilson 	/*
2500dcbf3bd6SGeorge Wilson 	 * We're about to change the hdr's b_flags. We must either
2501dcbf3bd6SGeorge Wilson 	 * hold the hash_lock or be undiscoverable.
2502dcbf3bd6SGeorge Wilson 	 */
2503dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2504dcbf3bd6SGeorge Wilson 
2505dcbf3bd6SGeorge Wilson 	/*
25065602294fSDan Kimmel 	 * Only honor requests for compressed bufs if the hdr is actually
25075602294fSDan Kimmel 	 * compressed.
25085602294fSDan Kimmel 	 */
25095602294fSDan Kimmel 	if (compressed && HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF)
25105602294fSDan Kimmel 		buf->b_flags |= ARC_BUF_FLAG_COMPRESSED;
25115602294fSDan Kimmel 
25125602294fSDan Kimmel 	/*
25135602294fSDan Kimmel 	 * If the hdr's data can be shared then we share the data buffer and
25145602294fSDan Kimmel 	 * set the appropriate bit in the hdr's b_flags to indicate the hdr is
2515770499e1SDan Kimmel 	 * sharing it's b_pabd with the arc_buf_t. Otherwise, we allocate a new
25165602294fSDan Kimmel 	 * buffer to store the buf's data.
25175602294fSDan Kimmel 	 *
2518770499e1SDan Kimmel 	 * There are two additional restrictions here because we're sharing
2519770499e1SDan Kimmel 	 * hdr -> buf instead of the usual buf -> hdr. First, the hdr can't be
2520770499e1SDan Kimmel 	 * actively involved in an L2ARC write, because if this buf is used by
2521770499e1SDan Kimmel 	 * an arc_write() then the hdr's data buffer will be released when the
25225602294fSDan Kimmel 	 * write completes, even though the L2ARC write might still be using it.
2523770499e1SDan Kimmel 	 * Second, the hdr's ABD must be linear so that the buf's user doesn't
2524770499e1SDan Kimmel 	 * need to be ABD-aware.
2525dcbf3bd6SGeorge Wilson 	 */
2526770499e1SDan Kimmel 	boolean_t can_share = arc_can_share(hdr, buf) && !HDR_L2_WRITING(hdr) &&
2527770499e1SDan Kimmel 	    abd_is_linear(hdr->b_l1hdr.b_pabd);
25285602294fSDan Kimmel 
25295602294fSDan Kimmel 	/* Set up b_data and sharing */
25305602294fSDan Kimmel 	if (can_share) {
2531770499e1SDan Kimmel 		buf->b_data = abd_to_buf(hdr->b_l1hdr.b_pabd);
25325602294fSDan Kimmel 		buf->b_flags |= ARC_BUF_FLAG_SHARED;
2533dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
2534dcbf3bd6SGeorge Wilson 	} else {
25355602294fSDan Kimmel 		buf->b_data =
25365602294fSDan Kimmel 		    arc_get_data_buf(hdr, arc_buf_size(buf), buf);
25375602294fSDan Kimmel 		ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
2538dcbf3bd6SGeorge Wilson 	}
2539dcbf3bd6SGeorge Wilson 	VERIFY3P(buf->b_data, !=, NULL);
254089c86e32SChris Williamson 
254189c86e32SChris Williamson 	hdr->b_l1hdr.b_buf = buf;
2542dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_bufcnt += 1;
254389c86e32SChris Williamson 
25445602294fSDan Kimmel 	/*
25455602294fSDan Kimmel 	 * If the user wants the data from the hdr, we need to either copy or
25465602294fSDan Kimmel 	 * decompress the data.
25475602294fSDan Kimmel 	 */
25485602294fSDan Kimmel 	if (fill) {
25495602294fSDan Kimmel 		return (arc_buf_fill(buf, ARC_BUF_COMPRESSED(buf) != 0));
25505602294fSDan Kimmel 	}
2551dcbf3bd6SGeorge Wilson 
25525602294fSDan Kimmel 	return (0);
25535602294fSDan Kimmel }
2554dcbf3bd6SGeorge Wilson 
25555602294fSDan Kimmel static char *arc_onloan_tag = "onloan";
2556fa9e4066Sahrens 
25575602294fSDan Kimmel static inline void
25585602294fSDan Kimmel arc_loaned_bytes_update(int64_t delta)
25595602294fSDan Kimmel {
25605602294fSDan Kimmel 	atomic_add_64(&arc_loaned_bytes, delta);
2561dcbf3bd6SGeorge Wilson 
25625602294fSDan Kimmel 	/* assert that it did not wrap around */
25635602294fSDan Kimmel 	ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
2564fa9e4066Sahrens }
2565fa9e4066Sahrens 
25662fdbea25SAleksandr Guzovskiy /*
25672fdbea25SAleksandr Guzovskiy  * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
25682fdbea25SAleksandr Guzovskiy  * flight data by arc_tempreserve_space() until they are "returned". Loaned
25692fdbea25SAleksandr Guzovskiy  * buffers must be returned to the arc before they can be used by the DMU or
25702fdbea25SAleksandr Guzovskiy  * freed.
25712fdbea25SAleksandr Guzovskiy  */
25722fdbea25SAleksandr Guzovskiy arc_buf_t *
25735602294fSDan Kimmel arc_loan_buf(spa_t *spa, boolean_t is_metadata, int size)
25742fdbea25SAleksandr Guzovskiy {
25755602294fSDan Kimmel 	arc_buf_t *buf = arc_alloc_buf(spa, arc_onloan_tag,
25765602294fSDan Kimmel 	    is_metadata ? ARC_BUFC_METADATA : ARC_BUFC_DATA, size);
25775602294fSDan Kimmel 
25789be12bd7SAllan Jude 	arc_loaned_bytes_update(arc_buf_size(buf));
25795602294fSDan Kimmel 
25805602294fSDan Kimmel 	return (buf);
25815602294fSDan Kimmel }
25822fdbea25SAleksandr Guzovskiy 
25835602294fSDan Kimmel arc_buf_t *
25845602294fSDan Kimmel arc_loan_compressed_buf(spa_t *spa, uint64_t psize, uint64_t lsize,
25855602294fSDan Kimmel     enum zio_compress compression_type)
25865602294fSDan Kimmel {
25875602294fSDan Kimmel 	arc_buf_t *buf = arc_alloc_compressed_buf(spa, arc_onloan_tag,
25885602294fSDan Kimmel 	    psize, lsize, compression_type);
25895602294fSDan Kimmel 
25909be12bd7SAllan Jude 	arc_loaned_bytes_update(arc_buf_size(buf));
25912fdbea25SAleksandr Guzovskiy 
25922fdbea25SAleksandr Guzovskiy 	return (buf);
25932fdbea25SAleksandr Guzovskiy }
25942fdbea25SAleksandr Guzovskiy 
25955602294fSDan Kimmel 
25962fdbea25SAleksandr Guzovskiy /*
25972fdbea25SAleksandr Guzovskiy  * Return a loaned arc buffer to the arc.
25982fdbea25SAleksandr Guzovskiy  */
25992fdbea25SAleksandr Guzovskiy void
26002fdbea25SAleksandr Guzovskiy arc_return_buf(arc_buf_t *buf, void *tag)
26012fdbea25SAleksandr Guzovskiy {
26022fdbea25SAleksandr Guzovskiy 	arc_buf_hdr_t *hdr = buf->b_hdr;
26032fdbea25SAleksandr Guzovskiy 
2604dcbf3bd6SGeorge Wilson 	ASSERT3P(buf->b_data, !=, NULL);
260589c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
260689c86e32SChris Williamson 	(void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
260789c86e32SChris Williamson 	(void) refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
26082fdbea25SAleksandr Guzovskiy 
26095602294fSDan Kimmel 	arc_loaned_bytes_update(-arc_buf_size(buf));
26102fdbea25SAleksandr Guzovskiy }
26112fdbea25SAleksandr Guzovskiy 
2612c242f9a0Schunli zhang - Sun Microsystems - Irvine United States /* Detach an arc_buf from a dbuf (tag) */
2613c242f9a0Schunli zhang - Sun Microsystems - Irvine United States void
2614c242f9a0Schunli zhang - Sun Microsystems - Irvine United States arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
2615c242f9a0Schunli zhang - Sun Microsystems - Irvine United States {
261689c86e32SChris Williamson 	arc_buf_hdr_t *hdr = buf->b_hdr;
2617c242f9a0Schunli zhang - Sun Microsystems - Irvine United States 
2618dcbf3bd6SGeorge Wilson 	ASSERT3P(buf->b_data, !=, NULL);
261989c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
262089c86e32SChris Williamson 	(void) refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
262189c86e32SChris Williamson 	(void) refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
2622c242f9a0Schunli zhang - Sun Microsystems - Irvine United States 
26235602294fSDan Kimmel 	arc_loaned_bytes_update(arc_buf_size(buf));
2624c242f9a0Schunli zhang - Sun Microsystems - Irvine United States }
2625c242f9a0Schunli zhang - Sun Microsystems - Irvine United States 
2626dcbf3bd6SGeorge Wilson static void
2627770499e1SDan Kimmel l2arc_free_abd_on_write(abd_t *abd, size_t size, arc_buf_contents_t type)
2628ea8dc4b6Seschrock {
2629dcbf3bd6SGeorge Wilson 	l2arc_data_free_t *df = kmem_alloc(sizeof (*df), KM_SLEEP);
2630ea8dc4b6Seschrock 
2631770499e1SDan Kimmel 	df->l2df_abd = abd;
2632dcbf3bd6SGeorge Wilson 	df->l2df_size = size;
2633dcbf3bd6SGeorge Wilson 	df->l2df_type = type;
2634dcbf3bd6SGeorge Wilson 	mutex_enter(&l2arc_free_on_write_mtx);
2635dcbf3bd6SGeorge Wilson 	list_insert_head(l2arc_free_on_write, df);
2636dcbf3bd6SGeorge Wilson 	mutex_exit(&l2arc_free_on_write_mtx);
2637dcbf3bd6SGeorge Wilson }
2638b24ab676SJeff Bonwick 
2639dcbf3bd6SGeorge Wilson static void
2640dcbf3bd6SGeorge Wilson arc_hdr_free_on_write(arc_buf_hdr_t *hdr)
2641dcbf3bd6SGeorge Wilson {
2642dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
2643dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type = arc_buf_type(hdr);
2644dcbf3bd6SGeorge Wilson 	uint64_t size = arc_hdr_size(hdr);
2645dcbf3bd6SGeorge Wilson 
2646dcbf3bd6SGeorge Wilson 	/* protected by hash lock, if in the hash table */
2647dcbf3bd6SGeorge Wilson 	if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
2648dcbf3bd6SGeorge Wilson 		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2649dcbf3bd6SGeorge Wilson 		ASSERT(state != arc_anon && state != arc_l2c_only);
2650dcbf3bd6SGeorge Wilson 
2651dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_esize[type],
2652dcbf3bd6SGeorge Wilson 		    size, hdr);
2653dcbf3bd6SGeorge Wilson 	}
2654dcbf3bd6SGeorge Wilson 	(void) refcount_remove_many(&state->arcs_size, size, hdr);
26556de76ce2SAndriy Gapon 	if (type == ARC_BUFC_METADATA) {
26566de76ce2SAndriy Gapon 		arc_space_return(size, ARC_SPACE_META);
26576de76ce2SAndriy Gapon 	} else {
26586de76ce2SAndriy Gapon 		ASSERT(type == ARC_BUFC_DATA);
26596de76ce2SAndriy Gapon 		arc_space_return(size, ARC_SPACE_DATA);
26606de76ce2SAndriy Gapon 	}
2661dcbf3bd6SGeorge Wilson 
2662770499e1SDan Kimmel 	l2arc_free_abd_on_write(hdr->b_l1hdr.b_pabd, size, type);
2663dcbf3bd6SGeorge Wilson }
2664dcbf3bd6SGeorge Wilson 
2665dcbf3bd6SGeorge Wilson /*
2666dcbf3bd6SGeorge Wilson  * Share the arc_buf_t's data with the hdr. Whenever we are sharing the
2667dcbf3bd6SGeorge Wilson  * data buffer, we transfer the refcount ownership to the hdr and update
2668dcbf3bd6SGeorge Wilson  * the appropriate kstats.
2669dcbf3bd6SGeorge Wilson  */
2670dcbf3bd6SGeorge Wilson static void
2671dcbf3bd6SGeorge Wilson arc_share_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2672dcbf3bd6SGeorge Wilson {
2673dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
2674dcbf3bd6SGeorge Wilson 
26755602294fSDan Kimmel 	ASSERT(arc_can_share(hdr, buf));
2676770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2677dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
26789253d63dSGeorge Wilson 
26799253d63dSGeorge Wilson 	/*
2680dcbf3bd6SGeorge Wilson 	 * Start sharing the data buffer. We transfer the
2681dcbf3bd6SGeorge Wilson 	 * refcount ownership to the hdr since it always owns
2682dcbf3bd6SGeorge Wilson 	 * the refcount whenever an arc_buf_t is shared.
26839253d63dSGeorge Wilson 	 */
2684dcbf3bd6SGeorge Wilson 	refcount_transfer_ownership(&state->arcs_size, buf, hdr);
2685770499e1SDan Kimmel 	hdr->b_l1hdr.b_pabd = abd_get_from_buf(buf->b_data, arc_buf_size(buf));
2686770499e1SDan Kimmel 	abd_take_ownership_of_buf(hdr->b_l1hdr.b_pabd,
2687770499e1SDan Kimmel 	    HDR_ISTYPE_METADATA(hdr));
2688dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
26895602294fSDan Kimmel 	buf->b_flags |= ARC_BUF_FLAG_SHARED;
2690dcbf3bd6SGeorge Wilson 
2691dcbf3bd6SGeorge Wilson 	/*
2692dcbf3bd6SGeorge Wilson 	 * Since we've transferred ownership to the hdr we need
2693dcbf3bd6SGeorge Wilson 	 * to increment its compressed and uncompressed kstats and
2694dcbf3bd6SGeorge Wilson 	 * decrement the overhead size.
2695dcbf3bd6SGeorge Wilson 	 */
2696dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
2697dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
26985602294fSDan Kimmel 	ARCSTAT_INCR(arcstat_overhead_size, -arc_buf_size(buf));
2699ea8dc4b6Seschrock }
2700ea8dc4b6Seschrock 
2701dcbf3bd6SGeorge Wilson static void
2702dcbf3bd6SGeorge Wilson arc_unshare_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2703ea8dc4b6Seschrock {
2704dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
2705dcbf3bd6SGeorge Wilson 
2706dcbf3bd6SGeorge Wilson 	ASSERT(arc_buf_is_shared(buf));
2707770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2708dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2709ea8dc4b6Seschrock 
27109b23f181Smaybee 	/*
2711dcbf3bd6SGeorge Wilson 	 * We are no longer sharing this buffer so we need
2712dcbf3bd6SGeorge Wilson 	 * to transfer its ownership to the rightful owner.
27139b23f181Smaybee 	 */
2714dcbf3bd6SGeorge Wilson 	refcount_transfer_ownership(&state->arcs_size, hdr, buf);
2715dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2716770499e1SDan Kimmel 	abd_release_ownership_of_buf(hdr->b_l1hdr.b_pabd);
2717770499e1SDan Kimmel 	abd_put(hdr->b_l1hdr.b_pabd);
2718770499e1SDan Kimmel 	hdr->b_l1hdr.b_pabd = NULL;
27195602294fSDan Kimmel 	buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
2720dcbf3bd6SGeorge Wilson 
2721dcbf3bd6SGeorge Wilson 	/*
2722dcbf3bd6SGeorge Wilson 	 * Since the buffer is no longer shared between
2723dcbf3bd6SGeorge Wilson 	 * the arc buf and the hdr, count it as overhead.
2724dcbf3bd6SGeorge Wilson 	 */
2725dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
2726dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
27275602294fSDan Kimmel 	ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
2728dcbf3bd6SGeorge Wilson }
2729dcbf3bd6SGeorge Wilson 
2730dcbf3bd6SGeorge Wilson /*
27315602294fSDan Kimmel  * Remove an arc_buf_t from the hdr's buf list and return the last
27325602294fSDan Kimmel  * arc_buf_t on the list. If no buffers remain on the list then return
27335602294fSDan Kimmel  * NULL.
27345602294fSDan Kimmel  */
27355602294fSDan Kimmel static arc_buf_t *
27365602294fSDan Kimmel arc_buf_remove(arc_buf_hdr_t *hdr, arc_buf_t *buf)
27375602294fSDan Kimmel {
27385602294fSDan Kimmel 	ASSERT(HDR_HAS_L1HDR(hdr));
27395602294fSDan Kimmel 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
27405602294fSDan Kimmel 
27415602294fSDan Kimmel 	arc_buf_t **bufp = &hdr->b_l1hdr.b_buf;
27425602294fSDan Kimmel 	arc_buf_t *lastbuf = NULL;
27435602294fSDan Kimmel 
27445602294fSDan Kimmel 	/*
27455602294fSDan Kimmel 	 * Remove the buf from the hdr list and locate the last
27465602294fSDan Kimmel 	 * remaining buffer on the list.
27475602294fSDan Kimmel 	 */
27485602294fSDan Kimmel 	while (*bufp != NULL) {
27495602294fSDan Kimmel 		if (*bufp == buf)
27505602294fSDan Kimmel 			*bufp = buf->b_next;
27515602294fSDan Kimmel 
27525602294fSDan Kimmel 		/*
27535602294fSDan Kimmel 		 * If we've removed a buffer in the middle of
27545602294fSDan Kimmel 		 * the list then update the lastbuf and update
27555602294fSDan Kimmel 		 * bufp.
27565602294fSDan Kimmel 		 */
27575602294fSDan Kimmel 		if (*bufp != NULL) {
27585602294fSDan Kimmel 			lastbuf = *bufp;
27595602294fSDan Kimmel 			bufp = &(*bufp)->b_next;
27605602294fSDan Kimmel 		}
27615602294fSDan Kimmel 	}
27625602294fSDan Kimmel 	buf->b_next = NULL;
27635602294fSDan Kimmel 	ASSERT3P(lastbuf, !=, buf);
27645602294fSDan Kimmel 	IMPLY(hdr->b_l1hdr.b_bufcnt > 0, lastbuf != NULL);
27655602294fSDan Kimmel 	IMPLY(hdr->b_l1hdr.b_bufcnt > 0, hdr->b_l1hdr.b_buf != NULL);
27665602294fSDan Kimmel 	IMPLY(lastbuf != NULL, ARC_BUF_LAST(lastbuf));
27675602294fSDan Kimmel 
27685602294fSDan Kimmel 	return (lastbuf);
27695602294fSDan Kimmel }
27705602294fSDan Kimmel 
27715602294fSDan Kimmel /*
27725602294fSDan Kimmel  * Free up buf->b_data and pull the arc_buf_t off of the the arc_buf_hdr_t's
27735602294fSDan Kimmel  * list and free it.
2774dcbf3bd6SGeorge Wilson  */
2775dcbf3bd6SGeorge Wilson static void
27765602294fSDan Kimmel arc_buf_destroy_impl(arc_buf_t *buf)
2777dcbf3bd6SGeorge Wilson {
2778dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
2779dcbf3bd6SGeorge Wilson 
2780dcbf3bd6SGeorge Wilson 	/*
27815602294fSDan Kimmel 	 * Free up the data associated with the buf but only if we're not
27825602294fSDan Kimmel 	 * sharing this with the hdr. If we are sharing it with the hdr, the
27835602294fSDan Kimmel 	 * hdr is responsible for doing the free.
2784dcbf3bd6SGeorge Wilson 	 */
2785dcbf3bd6SGeorge Wilson 	if (buf->b_data != NULL) {
2786dcbf3bd6SGeorge Wilson 		/*
2787dcbf3bd6SGeorge Wilson 		 * We're about to change the hdr's b_flags. We must either
2788dcbf3bd6SGeorge Wilson 		 * hold the hash_lock or be undiscoverable.
2789dcbf3bd6SGeorge Wilson 		 */
2790dcbf3bd6SGeorge Wilson 		ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2791dcbf3bd6SGeorge Wilson 
2792dcbf3bd6SGeorge Wilson 		arc_cksum_verify(buf);
2793dcbf3bd6SGeorge Wilson 		arc_buf_unwatch(buf);
2794dcbf3bd6SGeorge Wilson 
27955602294fSDan Kimmel 		if (arc_buf_is_shared(buf)) {
2796dcbf3bd6SGeorge Wilson 			arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2797dcbf3bd6SGeorge Wilson 		} else {
27985602294fSDan Kimmel 			uint64_t size = arc_buf_size(buf);
2799dcbf3bd6SGeorge Wilson 			arc_free_data_buf(hdr, buf->b_data, size, buf);
2800dcbf3bd6SGeorge Wilson 			ARCSTAT_INCR(arcstat_overhead_size, -size);
2801dcbf3bd6SGeorge Wilson 		}
2802dcbf3bd6SGeorge Wilson 		buf->b_data = NULL;
2803dcbf3bd6SGeorge Wilson 
2804dcbf3bd6SGeorge Wilson 		ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
2805dcbf3bd6SGeorge Wilson 		hdr->b_l1hdr.b_bufcnt -= 1;
2806dcbf3bd6SGeorge Wilson 	}
2807dcbf3bd6SGeorge Wilson 
28085602294fSDan Kimmel 	arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
2809dcbf3bd6SGeorge Wilson 
28105602294fSDan Kimmel 	if (ARC_BUF_SHARED(buf) && !ARC_BUF_COMPRESSED(buf)) {
2811dcbf3bd6SGeorge Wilson 		/*
28125602294fSDan Kimmel 		 * If the current arc_buf_t is sharing its data buffer with the
2813770499e1SDan Kimmel 		 * hdr, then reassign the hdr's b_pabd to share it with the new
28145602294fSDan Kimmel 		 * buffer at the end of the list. The shared buffer is always
28155602294fSDan Kimmel 		 * the last one on the hdr's buffer list.
28165602294fSDan Kimmel 		 *
28175602294fSDan Kimmel 		 * There is an equivalent case for compressed bufs, but since
28185602294fSDan Kimmel 		 * they aren't guaranteed to be the last buf in the list and
28195602294fSDan Kimmel 		 * that is an exceedingly rare case, we just allow that space be
28205602294fSDan Kimmel 		 * wasted temporarily.
2821dcbf3bd6SGeorge Wilson 		 */
28225602294fSDan Kimmel 		if (lastbuf != NULL) {
28235602294fSDan Kimmel 			/* Only one buf can be shared at once */
28245602294fSDan Kimmel 			VERIFY(!arc_buf_is_shared(lastbuf));
28255602294fSDan Kimmel 			/* hdr is uncompressed so can't have compressed buf */
28265602294fSDan Kimmel 			VERIFY(!ARC_BUF_COMPRESSED(lastbuf));
2827dcbf3bd6SGeorge Wilson 
2828770499e1SDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2829770499e1SDan Kimmel 			arc_hdr_free_pabd(hdr);
2830dcbf3bd6SGeorge Wilson 
28315602294fSDan Kimmel 			/*
28325602294fSDan Kimmel 			 * We must setup a new shared block between the
28335602294fSDan Kimmel 			 * last buffer and the hdr. The data would have
28345602294fSDan Kimmel 			 * been allocated by the arc buf so we need to transfer
28355602294fSDan Kimmel 			 * ownership to the hdr since it's now being shared.
28365602294fSDan Kimmel 			 */
28375602294fSDan Kimmel 			arc_share_buf(hdr, lastbuf);
28385602294fSDan Kimmel 		}
28395602294fSDan Kimmel 	} else if (HDR_SHARED_DATA(hdr)) {
2840dcbf3bd6SGeorge Wilson 		/*
28415602294fSDan Kimmel 		 * Uncompressed shared buffers are always at the end
28425602294fSDan Kimmel 		 * of the list. Compressed buffers don't have the
28435602294fSDan Kimmel 		 * same requirements. This makes it hard to
28445602294fSDan Kimmel 		 * simply assert that the lastbuf is shared so
28455602294fSDan Kimmel 		 * we rely on the hdr's compression flags to determine
28465602294fSDan Kimmel 		 * if we have a compressed, shared buffer.
2847dcbf3bd6SGeorge Wilson 		 */
28485602294fSDan Kimmel 		ASSERT3P(lastbuf, !=, NULL);
28495602294fSDan Kimmel 		ASSERT(arc_buf_is_shared(lastbuf) ||
28505602294fSDan Kimmel 		    HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
2851dcbf3bd6SGeorge Wilson 	}
2852dcbf3bd6SGeorge Wilson 
28535602294fSDan Kimmel 	/*
28545602294fSDan Kimmel 	 * Free the checksum if we're removing the last uncompressed buf from
28555602294fSDan Kimmel 	 * this hdr.
28565602294fSDan Kimmel 	 */
28575602294fSDan Kimmel 	if (!arc_hdr_has_uncompressed_buf(hdr)) {
2858dcbf3bd6SGeorge Wilson 		arc_cksum_free(hdr);
28595602294fSDan Kimmel 	}
2860dcbf3bd6SGeorge Wilson 
2861dcbf3bd6SGeorge Wilson 	/* clean up the buf */
2862dcbf3bd6SGeorge Wilson 	buf->b_hdr = NULL;
2863dcbf3bd6SGeorge Wilson 	kmem_cache_free(buf_cache, buf);
2864dcbf3bd6SGeorge Wilson }
2865dcbf3bd6SGeorge Wilson 
2866dcbf3bd6SGeorge Wilson static void
2867770499e1SDan Kimmel arc_hdr_alloc_pabd(arc_buf_hdr_t *hdr)
2868dcbf3bd6SGeorge Wilson {
2869dcbf3bd6SGeorge Wilson 	ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
287089c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
2871dcbf3bd6SGeorge Wilson 	ASSERT(!HDR_SHARED_DATA(hdr));
2872ea8dc4b6Seschrock 
2873770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2874770499e1SDan Kimmel 	hdr->b_l1hdr.b_pabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr);
2875dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
2876770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
287789c86e32SChris Williamson 
2878dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
2879dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
2880ea8dc4b6Seschrock }
2881ea8dc4b6Seschrock 
2882244781f1SPrakash Surya static void
2883770499e1SDan Kimmel arc_hdr_free_pabd(arc_buf_hdr_t *hdr)
2884244781f1SPrakash Surya {
2885dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2886770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2887244781f1SPrakash Surya 
2888dcbf3bd6SGeorge Wilson 	/*
2889dcbf3bd6SGeorge Wilson 	 * If the hdr is currently being written to the l2arc then
2890dcbf3bd6SGeorge Wilson 	 * we defer freeing the data by adding it to the l2arc_free_on_write
2891dcbf3bd6SGeorge Wilson 	 * list. The l2arc will free the data once it's finished
2892dcbf3bd6SGeorge Wilson 	 * writing it to the l2arc device.
2893dcbf3bd6SGeorge Wilson 	 */
2894dcbf3bd6SGeorge Wilson 	if (HDR_L2_WRITING(hdr)) {
2895dcbf3bd6SGeorge Wilson 		arc_hdr_free_on_write(hdr);
2896dcbf3bd6SGeorge Wilson 		ARCSTAT_BUMP(arcstat_l2_free_on_write);
2897dcbf3bd6SGeorge Wilson 	} else {
2898770499e1SDan Kimmel 		arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
2899dcbf3bd6SGeorge Wilson 		    arc_hdr_size(hdr), hdr);
2900dcbf3bd6SGeorge Wilson 	}
2901770499e1SDan Kimmel 	hdr->b_l1hdr.b_pabd = NULL;
2902dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
2903dcbf3bd6SGeorge Wilson 
2904dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
2905dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
2906dcbf3bd6SGeorge Wilson }
2907dcbf3bd6SGeorge Wilson 
2908dcbf3bd6SGeorge Wilson static arc_buf_hdr_t *
2909dcbf3bd6SGeorge Wilson arc_hdr_alloc(uint64_t spa, int32_t psize, int32_t lsize,
29105602294fSDan Kimmel     enum zio_compress compression_type, arc_buf_contents_t type)
2911dcbf3bd6SGeorge Wilson {
2912dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr;
2913dcbf3bd6SGeorge Wilson 
2914dcbf3bd6SGeorge Wilson 	VERIFY(type == ARC_BUFC_DATA || type == ARC_BUFC_METADATA);
2915dcbf3bd6SGeorge Wilson 
2916dcbf3bd6SGeorge Wilson 	hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
2917dcbf3bd6SGeorge Wilson 	ASSERT(HDR_EMPTY(hdr));
2918dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
2919dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_thawed, ==, NULL);
2920dcbf3bd6SGeorge Wilson 	HDR_SET_PSIZE(hdr, psize);
2921dcbf3bd6SGeorge Wilson 	HDR_SET_LSIZE(hdr, lsize);
2922dcbf3bd6SGeorge Wilson 	hdr->b_spa = spa;
2923dcbf3bd6SGeorge Wilson 	hdr->b_type = type;
2924dcbf3bd6SGeorge Wilson 	hdr->b_flags = 0;
2925dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(hdr, arc_bufc_to_flags(type) | ARC_FLAG_HAS_L1HDR);
29265602294fSDan Kimmel 	arc_hdr_set_compress(hdr, compression_type);
2927dcbf3bd6SGeorge Wilson 
2928dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_state = arc_anon;
2929dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_arc_access = 0;
2930dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_bufcnt = 0;
2931dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_buf = NULL;
2932dcbf3bd6SGeorge Wilson 
2933dcbf3bd6SGeorge Wilson 	/*
2934dcbf3bd6SGeorge Wilson 	 * Allocate the hdr's buffer. This will contain either
2935dcbf3bd6SGeorge Wilson 	 * the compressed or uncompressed data depending on the block
2936dcbf3bd6SGeorge Wilson 	 * it references and compressed arc enablement.
2937dcbf3bd6SGeorge Wilson 	 */
2938770499e1SDan Kimmel 	arc_hdr_alloc_pabd(hdr);
2939dcbf3bd6SGeorge Wilson 	ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2940dcbf3bd6SGeorge Wilson 
2941dcbf3bd6SGeorge Wilson 	return (hdr);
2942244781f1SPrakash Surya }
2943244781f1SPrakash Surya 
2944fa94a07fSbrendan /*
2945dcbf3bd6SGeorge Wilson  * Transition between the two allocation states for the arc_buf_hdr struct.
2946dcbf3bd6SGeorge Wilson  * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
2947dcbf3bd6SGeorge Wilson  * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
2948dcbf3bd6SGeorge Wilson  * version is used when a cache buffer is only in the L2ARC in order to reduce
2949dcbf3bd6SGeorge Wilson  * memory usage.
2950fa94a07fSbrendan  */
2951dcbf3bd6SGeorge Wilson static arc_buf_hdr_t *
2952dcbf3bd6SGeorge Wilson arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
2953fa94a07fSbrendan {
2954dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L2HDR(hdr));
2955dcbf3bd6SGeorge Wilson 
2956dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *nhdr;
2957dcbf3bd6SGeorge Wilson 	l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
2958dcbf3bd6SGeorge Wilson 
2959dcbf3bd6SGeorge Wilson 	ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
2960dcbf3bd6SGeorge Wilson 	    (old == hdr_l2only_cache && new == hdr_full_cache));
2961dcbf3bd6SGeorge Wilson 
2962dcbf3bd6SGeorge Wilson 	nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
2963dcbf3bd6SGeorge Wilson 
2964dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
2965dcbf3bd6SGeorge Wilson 	buf_hash_remove(hdr);
2966dcbf3bd6SGeorge Wilson 
2967dcbf3bd6SGeorge Wilson 	bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
2968dcbf3bd6SGeorge Wilson 
2969dcbf3bd6SGeorge Wilson 	if (new == hdr_full_cache) {
2970dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(nhdr, ARC_FLAG_HAS_L1HDR);
2971dcbf3bd6SGeorge Wilson 		/*
2972dcbf3bd6SGeorge Wilson 		 * arc_access and arc_change_state need to be aware that a
2973dcbf3bd6SGeorge Wilson 		 * header has just come out of L2ARC, so we set its state to
2974dcbf3bd6SGeorge Wilson 		 * l2c_only even though it's about to change.
2975dcbf3bd6SGeorge Wilson 		 */
2976dcbf3bd6SGeorge Wilson 		nhdr->b_l1hdr.b_state = arc_l2c_only;
2977dcbf3bd6SGeorge Wilson 
2978dcbf3bd6SGeorge Wilson 		/* Verify previous threads set to NULL before freeing */
2979770499e1SDan Kimmel 		ASSERT3P(nhdr->b_l1hdr.b_pabd, ==, NULL);
2980dcbf3bd6SGeorge Wilson 	} else {
2981dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2982dcbf3bd6SGeorge Wilson 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
2983dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
2984dcbf3bd6SGeorge Wilson 
2985dcbf3bd6SGeorge Wilson 		/*
2986dcbf3bd6SGeorge Wilson 		 * If we've reached here, We must have been called from
2987dcbf3bd6SGeorge Wilson 		 * arc_evict_hdr(), as such we should have already been
2988dcbf3bd6SGeorge Wilson 		 * removed from any ghost list we were previously on
2989dcbf3bd6SGeorge Wilson 		 * (which protects us from racing with arc_evict_state),
2990dcbf3bd6SGeorge Wilson 		 * thus no locking is needed during this check.
2991dcbf3bd6SGeorge Wilson 		 */
2992dcbf3bd6SGeorge Wilson 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
2993cd1c8b85SMatthew Ahrens 
2994dcbf3bd6SGeorge Wilson 		/*
2995dcbf3bd6SGeorge Wilson 		 * A buffer must not be moved into the arc_l2c_only
2996dcbf3bd6SGeorge Wilson 		 * state if it's not finished being written out to the
2997770499e1SDan Kimmel 		 * l2arc device. Otherwise, the b_l1hdr.b_pabd field
2998dcbf3bd6SGeorge Wilson 		 * might try to be accessed, even though it was removed.
2999dcbf3bd6SGeorge Wilson 		 */
3000dcbf3bd6SGeorge Wilson 		VERIFY(!HDR_L2_WRITING(hdr));
3001770499e1SDan Kimmel 		VERIFY3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3002fa94a07fSbrendan 
3003dcbf3bd6SGeorge Wilson #ifdef ZFS_DEBUG
3004dcbf3bd6SGeorge Wilson 		if (hdr->b_l1hdr.b_thawed != NULL) {
3005dcbf3bd6SGeorge Wilson 			kmem_free(hdr->b_l1hdr.b_thawed, 1);
3006dcbf3bd6SGeorge Wilson 			hdr->b_l1hdr.b_thawed = NULL;
3007dcbf3bd6SGeorge Wilson 		}
3008dcbf3bd6SGeorge Wilson #endif
3009244781f1SPrakash Surya 
3010dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(nhdr, ARC_FLAG_HAS_L1HDR);
3011dcbf3bd6SGeorge Wilson 	}
3012244781f1SPrakash Surya 	/*
3013dcbf3bd6SGeorge Wilson 	 * The header has been reallocated so we need to re-insert it into any
3014dcbf3bd6SGeorge Wilson 	 * lists it was on.
3015244781f1SPrakash Surya 	 */
3016dcbf3bd6SGeorge Wilson 	(void) buf_hash_insert(nhdr, NULL);
3017244781f1SPrakash Surya 
3018dcbf3bd6SGeorge Wilson 	ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
3019dcbf3bd6SGeorge Wilson 
3020dcbf3bd6SGeorge Wilson 	mutex_enter(&dev->l2ad_mtx);
3021244781f1SPrakash Surya 
3022244781f1SPrakash Surya 	/*
3023dcbf3bd6SGeorge Wilson 	 * We must place the realloc'ed header back into the list at
3024dcbf3bd6SGeorge Wilson 	 * the same spot. Otherwise, if it's placed earlier in the list,
3025dcbf3bd6SGeorge Wilson 	 * l2arc_write_buffers() could find it during the function's
3026dcbf3bd6SGeorge Wilson 	 * write phase, and try to write it out to the l2arc.
3027244781f1SPrakash Surya 	 */
3028dcbf3bd6SGeorge Wilson 	list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
3029dcbf3bd6SGeorge Wilson 	list_remove(&dev->l2ad_buflist, hdr);
3030dcbf3bd6SGeorge Wilson 
3031dcbf3bd6SGeorge Wilson 	mutex_exit(&dev->l2ad_mtx);
3032244781f1SPrakash Surya 
3033244781f1SPrakash Surya 	/*
3034dcbf3bd6SGeorge Wilson 	 * Since we're using the pointer address as the tag when
3035dcbf3bd6SGeorge Wilson 	 * incrementing and decrementing the l2ad_alloc refcount, we
3036dcbf3bd6SGeorge Wilson 	 * must remove the old pointer (that we're about to destroy) and
3037dcbf3bd6SGeorge Wilson 	 * add the new pointer to the refcount. Otherwise we'd remove
3038dcbf3bd6SGeorge Wilson 	 * the wrong pointer address when calling arc_hdr_destroy() later.
3039244781f1SPrakash Surya 	 */
3040244781f1SPrakash Surya 
3041dcbf3bd6SGeorge Wilson 	(void) refcount_remove_many(&dev->l2ad_alloc, arc_hdr_size(hdr), hdr);
3042dcbf3bd6SGeorge Wilson 	(void) refcount_add_many(&dev->l2ad_alloc, arc_hdr_size(nhdr), nhdr);
3043244781f1SPrakash Surya 
3044dcbf3bd6SGeorge Wilson 	buf_discard_identity(hdr);
3045dcbf3bd6SGeorge Wilson 	kmem_cache_free(old, hdr);
3046244781f1SPrakash Surya 
3047dcbf3bd6SGeorge Wilson 	return (nhdr);
3048244781f1SPrakash Surya }
3049244781f1SPrakash Surya 
3050bbfa8ea8SMatthew Ahrens /*
3051dcbf3bd6SGeorge Wilson  * Allocate a new arc_buf_hdr_t and arc_buf_t and return the buf to the caller.
3052dcbf3bd6SGeorge Wilson  * The buf is returned thawed since we expect the consumer to modify it.
3053bbfa8ea8SMatthew Ahrens  */
3054dcbf3bd6SGeorge Wilson arc_buf_t *
30555602294fSDan Kimmel arc_alloc_buf(spa_t *spa, void *tag, arc_buf_contents_t type, int32_t size)
3056ea8dc4b6Seschrock {
3057dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), size, size,
3058dcbf3bd6SGeorge Wilson 	    ZIO_COMPRESS_OFF, type);
3059dcbf3bd6SGeorge Wilson 	ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
30605602294fSDan Kimmel 
30615602294fSDan Kimmel 	arc_buf_t *buf = NULL;
30625602294fSDan Kimmel 	VERIFY0(arc_buf_alloc_impl(hdr, tag, B_FALSE, B_FALSE, &buf));
3063dcbf3bd6SGeorge Wilson 	arc_buf_thaw(buf);
30645602294fSDan Kimmel 
30655602294fSDan Kimmel 	return (buf);
30665602294fSDan Kimmel }
30675602294fSDan Kimmel 
30685602294fSDan Kimmel /*
30695602294fSDan Kimmel  * Allocate a compressed buf in the same manner as arc_alloc_buf. Don't use this
30705602294fSDan Kimmel  * for bufs containing metadata.
30715602294fSDan Kimmel  */
30725602294fSDan Kimmel arc_buf_t *
30735602294fSDan Kimmel arc_alloc_compressed_buf(spa_t *spa, void *tag, uint64_t psize, uint64_t lsize,
30745602294fSDan Kimmel     enum zio_compress compression_type)
30755602294fSDan Kimmel {
30765602294fSDan Kimmel 	ASSERT3U(lsize, >, 0);
30775602294fSDan Kimmel 	ASSERT3U(lsize, >=, psize);
30785602294fSDan Kimmel 	ASSERT(compression_type > ZIO_COMPRESS_OFF);
30795602294fSDan Kimmel 	ASSERT(compression_type < ZIO_COMPRESS_FUNCTIONS);
30805602294fSDan Kimmel 
30815602294fSDan Kimmel 	arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
30825602294fSDan Kimmel 	    compression_type, ARC_BUFC_DATA);
30835602294fSDan Kimmel 	ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
30845602294fSDan Kimmel 
30855602294fSDan Kimmel 	arc_buf_t *buf = NULL;
30865602294fSDan Kimmel 	VERIFY0(arc_buf_alloc_impl(hdr, tag, B_TRUE, B_FALSE, &buf));
30875602294fSDan Kimmel 	arc_buf_thaw(buf);
30885602294fSDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
30895602294fSDan Kimmel 
3090770499e1SDan Kimmel 	if (!arc_buf_is_shared(buf)) {
3091770499e1SDan Kimmel 		/*
3092770499e1SDan Kimmel 		 * To ensure that the hdr has the correct data in it if we call
3093770499e1SDan Kimmel 		 * arc_decompress() on this buf before it's been written to
3094770499e1SDan Kimmel 		 * disk, it's easiest if we just set up sharing between the
3095770499e1SDan Kimmel 		 * buf and the hdr.
3096770499e1SDan Kimmel 		 */
3097770499e1SDan Kimmel 		ASSERT(!abd_is_linear(hdr->b_l1hdr.b_pabd));
3098770499e1SDan Kimmel 		arc_hdr_free_pabd(hdr);
3099770499e1SDan Kimmel 		arc_share_buf(hdr, buf);
3100770499e1SDan Kimmel 	}
3101770499e1SDan Kimmel 
3102dcbf3bd6SGeorge Wilson 	return (buf);
3103ea8dc4b6Seschrock }
3104ea8dc4b6Seschrock 
3105a52fc310SPrakash Surya static void
3106a52fc310SPrakash Surya arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
3107a52fc310SPrakash Surya {
3108a52fc310SPrakash Surya 	l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
3109a52fc310SPrakash Surya 	l2arc_dev_t *dev = l2hdr->b_dev;
311016a7e5acSAndriy Gapon 	uint64_t psize = arc_hdr_size(hdr);
3111a52fc310SPrakash Surya 
3112a52fc310SPrakash Surya 	ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
3113a52fc310SPrakash Surya 	ASSERT(HDR_HAS_L2HDR(hdr));
3114a52fc310SPrakash Surya 
3115a52fc310SPrakash Surya 	list_remove(&dev->l2ad_buflist, hdr);
3116a52fc310SPrakash Surya 
311716a7e5acSAndriy Gapon 	ARCSTAT_INCR(arcstat_l2_psize, -psize);
311816a7e5acSAndriy Gapon 	ARCSTAT_INCR(arcstat_l2_lsize, -HDR_GET_LSIZE(hdr));
3119a52fc310SPrakash Surya 
312016a7e5acSAndriy Gapon 	vdev_space_update(dev->l2ad_vdev, -psize, 0, 0);
3121a52fc310SPrakash Surya 
312216a7e5acSAndriy Gapon 	(void) refcount_remove_many(&dev->l2ad_alloc, psize, hdr);
3123dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
3124a52fc310SPrakash Surya }
3125a52fc310SPrakash Surya 
3126fa9e4066Sahrens static void
3127ea8dc4b6Seschrock arc_hdr_destroy(arc_buf_hdr_t *hdr)
3128fa9e4066Sahrens {
312989c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr)) {
313089c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_buf == NULL ||
3131dcbf3bd6SGeorge Wilson 		    hdr->b_l1hdr.b_bufcnt > 0);
313289c86e32SChris Williamson 		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
313389c86e32SChris Williamson 		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
313489c86e32SChris Williamson 	}
3135ea8dc4b6Seschrock 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
313689c86e32SChris Williamson 	ASSERT(!HDR_IN_HASH_TABLE(hdr));
313789c86e32SChris Williamson 
3138dcbf3bd6SGeorge Wilson 	if (!HDR_EMPTY(hdr))
3139dcbf3bd6SGeorge Wilson 		buf_discard_identity(hdr);
3140dcbf3bd6SGeorge Wilson 
314189c86e32SChris Williamson 	if (HDR_HAS_L2HDR(hdr)) {
3142a52fc310SPrakash Surya 		l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3143a52fc310SPrakash Surya 		boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
3144b24ab676SJeff Bonwick 
3145a52fc310SPrakash Surya 		if (!buflist_held)
3146a52fc310SPrakash Surya 			mutex_enter(&dev->l2ad_mtx);
314789c86e32SChris Williamson 
3148244781f1SPrakash Surya 		/*
3149a52fc310SPrakash Surya 		 * Even though we checked this conditional above, we
3150a52fc310SPrakash Surya 		 * need to check this again now that we have the
3151a52fc310SPrakash Surya 		 * l2ad_mtx. This is because we could be racing with
3152a52fc310SPrakash Surya 		 * another thread calling l2arc_evict() which might have
3153a52fc310SPrakash Surya 		 * destroyed this header's L2 portion as we were waiting
3154a52fc310SPrakash Surya 		 * to acquire the l2ad_mtx. If that happens, we don't
3155a52fc310SPrakash Surya 		 * want to re-destroy the header's L2 portion.
3156244781f1SPrakash Surya 		 */
3157a52fc310SPrakash Surya 		if (HDR_HAS_L2HDR(hdr))
3158a52fc310SPrakash Surya 			arc_hdr_l2hdr_destroy(hdr);
3159b24ab676SJeff Bonwick 
3160b24ab676SJeff Bonwick 		if (!buflist_held)
3161a52fc310SPrakash Surya 			mutex_exit(&dev->l2ad_mtx);
3162fa94a07fSbrendan 	}
3163fa94a07fSbrendan 
3164dcbf3bd6SGeorge Wilson 	if (HDR_HAS_L1HDR(hdr)) {
3165dcbf3bd6SGeorge Wilson 		arc_cksum_free(hdr);
316689c86e32SChris Williamson 
3167dcbf3bd6SGeorge Wilson 		while (hdr->b_l1hdr.b_buf != NULL)
31685602294fSDan Kimmel 			arc_buf_destroy_impl(hdr->b_l1hdr.b_buf);
316989c86e32SChris Williamson 
317089c86e32SChris Williamson #ifdef ZFS_DEBUG
317189c86e32SChris Williamson 		if (hdr->b_l1hdr.b_thawed != NULL) {
317289c86e32SChris Williamson 			kmem_free(hdr->b_l1hdr.b_thawed, 1);
317389c86e32SChris Williamson 			hdr->b_l1hdr.b_thawed = NULL;
317489c86e32SChris Williamson 		}
317589c86e32SChris Williamson #endif
3176dcbf3bd6SGeorge Wilson 
3177770499e1SDan Kimmel 		if (hdr->b_l1hdr.b_pabd != NULL) {
3178770499e1SDan Kimmel 			arc_hdr_free_pabd(hdr);
3179dcbf3bd6SGeorge Wilson 		}
31803f9d6ad7SLin Ling 	}
3181ea8dc4b6Seschrock 
3182fa9e4066Sahrens 	ASSERT3P(hdr->b_hash_next, ==, NULL);
318389c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr)) {
3184244781f1SPrakash Surya 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
318589c86e32SChris Williamson 		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
318689c86e32SChris Williamson 		kmem_cache_free(hdr_full_cache, hdr);
318789c86e32SChris Williamson 	} else {
318889c86e32SChris Williamson 		kmem_cache_free(hdr_l2only_cache, hdr);
318989c86e32SChris Williamson 	}
3190fa9e4066Sahrens }
3191fa9e4066Sahrens 
3192fa9e4066Sahrens void
3193dcbf3bd6SGeorge Wilson arc_buf_destroy(arc_buf_t *buf, void* tag)
3194ea8dc4b6Seschrock {
3195ea8dc4b6Seschrock 	arc_buf_hdr_t *hdr = buf->b_hdr;
3196ea8dc4b6Seschrock 	kmutex_t *hash_lock = HDR_LOCK(hdr);
3197fa9e4066Sahrens 
319889c86e32SChris Williamson 	if (hdr->b_l1hdr.b_state == arc_anon) {
3199dcbf3bd6SGeorge Wilson 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
3200dcbf3bd6SGeorge Wilson 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3201dcbf3bd6SGeorge Wilson 		VERIFY0(remove_reference(hdr, NULL, tag));
3202dcbf3bd6SGeorge Wilson 		arc_hdr_destroy(hdr);
3203dcbf3bd6SGeorge Wilson 		return;
3204ea8dc4b6Seschrock 	}
3205ea8dc4b6Seschrock 
3206ea8dc4b6Seschrock 	mutex_enter(hash_lock);
3207dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr, ==, buf->b_hdr);
3208dcbf3bd6SGeorge Wilson 	ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
32093f9d6ad7SLin Ling 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3210dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_state, !=, arc_anon);
3211dcbf3bd6SGeorge Wilson 	ASSERT3P(buf->b_data, !=, NULL);
3212ea8dc4b6Seschrock 
3213ea8dc4b6Seschrock 	(void) remove_reference(hdr, hash_lock, tag);
32145602294fSDan Kimmel 	arc_buf_destroy_impl(buf);
3215ea8dc4b6Seschrock 	mutex_exit(hash_lock);
3216fa9e4066Sahrens }
3217fa9e4066Sahrens 
3218fa9e4066Sahrens /*
3219244781f1SPrakash Surya  * Evict the arc_buf_hdr that is provided as a parameter. The resultant
3220244781f1SPrakash Surya  * state of the header is dependent on it's state prior to entering this
3221244781f1SPrakash Surya  * function. The following transitions are possible:
3222874395d5Smaybee  *
3223244781f1SPrakash Surya  *    - arc_mru -> arc_mru_ghost
3224244781f1SPrakash Surya  *    - arc_mfu -> arc_mfu_ghost
3225244781f1SPrakash Surya  *    - arc_mru_ghost -> arc_l2c_only
3226244781f1SPrakash Surya  *    - arc_mru_ghost -> deleted
3227244781f1SPrakash Surya  *    - arc_mfu_ghost -> arc_l2c_only
3228244781f1SPrakash Surya  *    - arc_mfu_ghost -> deleted
3229fa9e4066Sahrens  */
3230244781f1SPrakash Surya static int64_t
3231244781f1SPrakash Surya arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3232fa9e4066Sahrens {
3233244781f1SPrakash Surya 	arc_state_t *evicted_state, *state;
3234244781f1SPrakash Surya 	int64_t bytes_evicted = 0;
3235fa9e4066Sahrens 
3236244781f1SPrakash Surya 	ASSERT(MUTEX_HELD(hash_lock));
3237244781f1SPrakash Surya 	ASSERT(HDR_HAS_L1HDR(hdr));
3238fa9e4066Sahrens 
3239244781f1SPrakash Surya 	state = hdr->b_l1hdr.b_state;
3240244781f1SPrakash Surya 	if (GHOST_STATE(state)) {
3241244781f1SPrakash Surya 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3242dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3243fa9e4066Sahrens 
3244244781f1SPrakash Surya 		/*
3245244781f1SPrakash Surya 		 * l2arc_write_buffers() relies on a header's L1 portion
3246770499e1SDan Kimmel 		 * (i.e. its b_pabd field) during it's write phase.
3247244781f1SPrakash Surya 		 * Thus, we cannot push a header onto the arc_l2c_only
3248244781f1SPrakash Surya 		 * state (removing it's L1 piece) until the header is
3249244781f1SPrakash Surya 		 * done being written to the l2arc.
3250244781f1SPrakash Surya 		 */
3251244781f1SPrakash Surya 		if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
3252244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_evict_l2_skip);
3253244781f1SPrakash Surya 			return (bytes_evicted);
32543a5286a1SMatthew Ahrens 		}
3255244781f1SPrakash Surya 
3256244781f1SPrakash Surya 		ARCSTAT_BUMP(arcstat_deleted);
3257dcbf3bd6SGeorge Wilson 		bytes_evicted += HDR_GET_LSIZE(hdr);
3258244781f1SPrakash Surya 
3259244781f1SPrakash Surya 		DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
3260244781f1SPrakash Surya 
3261770499e1SDan Kimmel 		ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3262244781f1SPrakash Surya 		if (HDR_HAS_L2HDR(hdr)) {
3263244781f1SPrakash Surya 			/*
3264244781f1SPrakash Surya 			 * This buffer is cached on the 2nd Level ARC;
3265244781f1SPrakash Surya 			 * don't destroy the header.
3266244781f1SPrakash Surya 			 */
3267244781f1SPrakash Surya 			arc_change_state(arc_l2c_only, hdr, hash_lock);
32683a5286a1SMatthew Ahrens 			/*
3269244781f1SPrakash Surya 			 * dropping from L1+L2 cached to L2-only,
3270244781f1SPrakash Surya 			 * realloc to remove the L1 header.
32713a5286a1SMatthew Ahrens 			 */
3272244781f1SPrakash Surya 			hdr = arc_hdr_realloc(hdr, hdr_full_cache,
3273244781f1SPrakash Surya 			    hdr_l2only_cache);
3274244781f1SPrakash Surya 		} else {
3275244781f1SPrakash Surya 			arc_change_state(arc_anon, hdr, hash_lock);
3276244781f1SPrakash Surya 			arc_hdr_destroy(hdr);
32773a5286a1SMatthew Ahrens 		}
3278244781f1SPrakash Surya 		return (bytes_evicted);
32793a5286a1SMatthew Ahrens 	}
32803a5286a1SMatthew Ahrens 
3281244781f1SPrakash Surya 	ASSERT(state == arc_mru || state == arc_mfu);
3282244781f1SPrakash Surya 	evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
3283244781f1SPrakash Surya 
3284244781f1SPrakash Surya 	/* prefetch buffers have a minimum lifespan */
3285244781f1SPrakash Surya 	if (HDR_IO_IN_PROGRESS(hdr) ||
3286244781f1SPrakash Surya 	    ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
3287244781f1SPrakash Surya 	    ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
3288244781f1SPrakash Surya 	    arc_min_prefetch_lifespan)) {
3289244781f1SPrakash Surya 		ARCSTAT_BUMP(arcstat_evict_skip);
3290244781f1SPrakash Surya 		return (bytes_evicted);
3291244781f1SPrakash Surya 	}
3292244781f1SPrakash Surya 
3293244781f1SPrakash Surya 	ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
3294244781f1SPrakash Surya 	while (hdr->b_l1hdr.b_buf) {
3295244781f1SPrakash Surya 		arc_buf_t *buf = hdr->b_l1hdr.b_buf;
3296244781f1SPrakash Surya 		if (!mutex_tryenter(&buf->b_evict_lock)) {
3297244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_mutex_miss);
3298244781f1SPrakash Surya 			break;
329913506d1eSmaybee 		}
3300244781f1SPrakash Surya 		if (buf->b_data != NULL)
3301dcbf3bd6SGeorge Wilson 			bytes_evicted += HDR_GET_LSIZE(hdr);
3302dcbf3bd6SGeorge Wilson 		mutex_exit(&buf->b_evict_lock);
33035602294fSDan Kimmel 		arc_buf_destroy_impl(buf);
3304244781f1SPrakash Surya 	}
330569962b56SMatthew Ahrens 
3306244781f1SPrakash Surya 	if (HDR_HAS_L2HDR(hdr)) {
3307dcbf3bd6SGeorge Wilson 		ARCSTAT_INCR(arcstat_evict_l2_cached, HDR_GET_LSIZE(hdr));
3308244781f1SPrakash Surya 	} else {
3309dcbf3bd6SGeorge Wilson 		if (l2arc_write_eligible(hdr->b_spa, hdr)) {
3310dcbf3bd6SGeorge Wilson 			ARCSTAT_INCR(arcstat_evict_l2_eligible,
3311dcbf3bd6SGeorge Wilson 			    HDR_GET_LSIZE(hdr));
3312dcbf3bd6SGeorge Wilson 		} else {
3313dcbf3bd6SGeorge Wilson 			ARCSTAT_INCR(arcstat_evict_l2_ineligible,
3314dcbf3bd6SGeorge Wilson 			    HDR_GET_LSIZE(hdr));
3315dcbf3bd6SGeorge Wilson 		}
3316244781f1SPrakash Surya 	}
3317244781f1SPrakash Surya 
3318dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_bufcnt == 0) {
3319dcbf3bd6SGeorge Wilson 		arc_cksum_free(hdr);
3320dcbf3bd6SGeorge Wilson 
3321dcbf3bd6SGeorge Wilson 		bytes_evicted += arc_hdr_size(hdr);
3322dcbf3bd6SGeorge Wilson 
3323dcbf3bd6SGeorge Wilson 		/*
3324dcbf3bd6SGeorge Wilson 		 * If this hdr is being evicted and has a compressed
3325dcbf3bd6SGeorge Wilson 		 * buffer then we discard it here before we change states.
3326dcbf3bd6SGeorge Wilson 		 * This ensures that the accounting is updated correctly
3327770499e1SDan Kimmel 		 * in arc_free_data_impl().
3328dcbf3bd6SGeorge Wilson 		 */
3329770499e1SDan Kimmel 		arc_hdr_free_pabd(hdr);
3330dcbf3bd6SGeorge Wilson 
3331244781f1SPrakash Surya 		arc_change_state(evicted_state, hdr, hash_lock);
3332244781f1SPrakash Surya 		ASSERT(HDR_IN_HASH_TABLE(hdr));
3333dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
3334244781f1SPrakash Surya 		DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
3335244781f1SPrakash Surya 	}
3336244781f1SPrakash Surya 
3337244781f1SPrakash Surya 	return (bytes_evicted);
3338244781f1SPrakash Surya }
3339244781f1SPrakash Surya 
3340244781f1SPrakash Surya static uint64_t
3341244781f1SPrakash Surya arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
3342244781f1SPrakash Surya     uint64_t spa, int64_t bytes)
3343244781f1SPrakash Surya {
3344244781f1SPrakash Surya 	multilist_sublist_t *mls;
3345244781f1SPrakash Surya 	uint64_t bytes_evicted = 0;
3346244781f1SPrakash Surya 	arc_buf_hdr_t *hdr;
3347244781f1SPrakash Surya 	kmutex_t *hash_lock;
3348244781f1SPrakash Surya 	int evict_count = 0;
3349244781f1SPrakash Surya 
3350244781f1SPrakash Surya 	ASSERT3P(marker, !=, NULL);
3351244781f1SPrakash Surya 	IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3352244781f1SPrakash Surya 
3353244781f1SPrakash Surya 	mls = multilist_sublist_lock(ml, idx);
3354244781f1SPrakash Surya 
3355244781f1SPrakash Surya 	for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
3356244781f1SPrakash Surya 	    hdr = multilist_sublist_prev(mls, marker)) {
3357244781f1SPrakash Surya 		if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
3358244781f1SPrakash Surya 		    (evict_count >= zfs_arc_evict_batch_limit))
3359244781f1SPrakash Surya 			break;
336069962b56SMatthew Ahrens 
336169962b56SMatthew Ahrens 		/*
3362244781f1SPrakash Surya 		 * To keep our iteration location, move the marker
3363244781f1SPrakash Surya 		 * forward. Since we're not holding hdr's hash lock, we
3364244781f1SPrakash Surya 		 * must be very careful and not remove 'hdr' from the
3365244781f1SPrakash Surya 		 * sublist. Otherwise, other consumers might mistake the
3366244781f1SPrakash Surya 		 * 'hdr' as not being on a sublist when they call the
3367244781f1SPrakash Surya 		 * multilist_link_active() function (they all rely on
3368244781f1SPrakash Surya 		 * the hash lock protecting concurrent insertions and
3369244781f1SPrakash Surya 		 * removals). multilist_sublist_move_forward() was
3370244781f1SPrakash Surya 		 * specifically implemented to ensure this is the case
3371244781f1SPrakash Surya 		 * (only 'marker' will be removed and re-inserted).
3372244781f1SPrakash Surya 		 */
3373244781f1SPrakash Surya 		multilist_sublist_move_forward(mls, marker);
3374244781f1SPrakash Surya 
3375244781f1SPrakash Surya 		/*
3376244781f1SPrakash Surya 		 * The only case where the b_spa field should ever be
3377244781f1SPrakash Surya 		 * zero, is the marker headers inserted by
3378244781f1SPrakash Surya 		 * arc_evict_state(). It's possible for multiple threads
3379244781f1SPrakash Surya 		 * to be calling arc_evict_state() concurrently (e.g.
3380244781f1SPrakash Surya 		 * dsl_pool_close() and zio_inject_fault()), so we must
3381244781f1SPrakash Surya 		 * skip any markers we see from these other threads.
338269962b56SMatthew Ahrens 		 */
3383244781f1SPrakash Surya 		if (hdr->b_spa == 0)
3384244781f1SPrakash Surya 			continue;
3385244781f1SPrakash Surya 
3386244781f1SPrakash Surya 		/* we're only interested in evicting buffers of a certain spa */
3387244781f1SPrakash Surya 		if (spa != 0 && hdr->b_spa != spa) {
3388244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_evict_skip);
338969962b56SMatthew Ahrens 			continue;
339069962b56SMatthew Ahrens 		}
339169962b56SMatthew Ahrens 
33927adb730bSGeorge Wilson 		hash_lock = HDR_LOCK(hdr);
33935ea40c06SBrendan Gregg - Sun Microsystems 
3394244781f1SPrakash Surya 		/*
3395244781f1SPrakash Surya 		 * We aren't calling this function from any code path
3396244781f1SPrakash Surya 		 * that would already be holding a hash lock, so we're
3397244781f1SPrakash Surya 		 * asserting on this assumption to be defensive in case
3398244781f1SPrakash Surya 		 * this ever changes. Without this check, it would be
3399244781f1SPrakash Surya 		 * possible to incorrectly increment arcstat_mutex_miss
3400244781f1SPrakash Surya 		 * below (e.g. if the code changed such that we called
3401244781f1SPrakash Surya 		 * this function with a hash lock held).
3402244781f1SPrakash Surya 		 */
3403244781f1SPrakash Surya 		ASSERT(!MUTEX_HELD(hash_lock));
340444cb6abcSbmc 
3405244781f1SPrakash Surya 		if (mutex_tryenter(hash_lock)) {
3406244781f1SPrakash Surya 			uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
3407244781f1SPrakash Surya 			mutex_exit(hash_lock);
3408fa9e4066Sahrens 
3409244781f1SPrakash Surya 			bytes_evicted += evicted;
3410fa9e4066Sahrens 
3411244781f1SPrakash Surya 			/*
3412244781f1SPrakash Surya 			 * If evicted is zero, arc_evict_hdr() must have
3413244781f1SPrakash Surya 			 * decided to skip this header, don't increment
3414244781f1SPrakash Surya 			 * evict_count in this case.
3415244781f1SPrakash Surya 			 */
3416244781f1SPrakash Surya 			if (evicted != 0)
3417244781f1SPrakash Surya 				evict_count++;
341844cb6abcSbmc 
3419244781f1SPrakash Surya 			/*
3420244781f1SPrakash Surya 			 * If arc_size isn't overflowing, signal any
3421244781f1SPrakash Surya 			 * threads that might happen to be waiting.
3422244781f1SPrakash Surya 			 *
3423244781f1SPrakash Surya 			 * For each header evicted, we wake up a single
3424244781f1SPrakash Surya 			 * thread. If we used cv_broadcast, we could
3425244781f1SPrakash Surya 			 * wake up "too many" threads causing arc_size
3426244781f1SPrakash Surya 			 * to significantly overflow arc_c; since
3427770499e1SDan Kimmel 			 * arc_get_data_impl() doesn't check for overflow
3428244781f1SPrakash Surya 			 * when it's woken up (it doesn't because it's
3429244781f1SPrakash Surya 			 * possible for the ARC to be overflowing while
3430244781f1SPrakash Surya 			 * full of un-evictable buffers, and the
3431244781f1SPrakash Surya 			 * function should proceed in this case).
3432244781f1SPrakash Surya 			 *
3433244781f1SPrakash Surya 			 * If threads are left sleeping, due to not
3434*de753e34SBrad Lewis 			 * using cv_broadcast here, they will be woken
3435*de753e34SBrad Lewis 			 * up via cv_broadcast in arc_adjust_cb() just
3436*de753e34SBrad Lewis 			 * before arc_adjust_zthr sleeps.
3437244781f1SPrakash Surya 			 */
3438*de753e34SBrad Lewis 			mutex_enter(&arc_adjust_lock);
3439244781f1SPrakash Surya 			if (!arc_is_overflowing())
3440*de753e34SBrad Lewis 				cv_signal(&arc_adjust_waiters_cv);
3441*de753e34SBrad Lewis 			mutex_exit(&arc_adjust_lock);
3442244781f1SPrakash Surya 		} else {
3443244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_mutex_miss);
3444244781f1SPrakash Surya 		}
3445244781f1SPrakash Surya 	}
3446f4d2e9e6Smaybee 
3447244781f1SPrakash Surya 	multilist_sublist_unlock(mls);
344844cb6abcSbmc 
3449244781f1SPrakash Surya 	return (bytes_evicted);
3450fa9e4066Sahrens }
3451fa9e4066Sahrens 
3452fa9e4066Sahrens /*
3453244781f1SPrakash Surya  * Evict buffers from the given arc state, until we've removed the
3454244781f1SPrakash Surya  * specified number of bytes. Move the removed buffers to the
3455244781f1SPrakash Surya  * appropriate evict state.
3456244781f1SPrakash Surya  *
3457244781f1SPrakash Surya  * This function makes a "best effort". It skips over any buffers
3458244781f1SPrakash Surya  * it can't get a hash_lock on, and so, may not catch all candidates.
3459244781f1SPrakash Surya  * It may also return without evicting as much space as requested.
3460244781f1SPrakash Surya  *
3461244781f1SPrakash Surya  * If bytes is specified using the special value ARC_EVICT_ALL, this
3462244781f1SPrakash Surya  * will evict all available (i.e. unlocked and evictable) buffers from
3463244781f1SPrakash Surya  * the given arc state; which is used by arc_flush().
3464fa9e4066Sahrens  */
3465244781f1SPrakash Surya static uint64_t
3466244781f1SPrakash Surya arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
3467244781f1SPrakash Surya     arc_buf_contents_t type)
3468fa9e4066Sahrens {
3469244781f1SPrakash Surya 	uint64_t total_evicted = 0;
347094c2d0ebSMatthew Ahrens 	multilist_t *ml = state->arcs_list[type];
3471244781f1SPrakash Surya 	int num_sublists;
3472244781f1SPrakash Surya 	arc_buf_hdr_t **markers;
3473fa9e4066Sahrens 
3474244781f1SPrakash Surya 	IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3475b802aa8cSSanjeev Bagewadi 
3476244781f1SPrakash Surya 	num_sublists = multilist_get_num_sublists(ml);
3477b802aa8cSSanjeev Bagewadi 
3478244781f1SPrakash Surya 	/*
3479244781f1SPrakash Surya 	 * If we've tried to evict from each sublist, made some
3480244781f1SPrakash Surya 	 * progress, but still have not hit the target number of bytes
3481244781f1SPrakash Surya 	 * to evict, we want to keep trying. The markers allow us to
3482244781f1SPrakash Surya 	 * pick up where we left off for each individual sublist, rather
3483244781f1SPrakash Surya 	 * than starting from the tail each time.
3484244781f1SPrakash Surya 	 */
3485244781f1SPrakash Surya 	markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
3486244781f1SPrakash Surya 	for (int i = 0; i < num_sublists; i++) {
3487244781f1SPrakash Surya 		markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
348869962b56SMatthew Ahrens 
348969962b56SMatthew Ahrens 		/*
3490244781f1SPrakash Surya 		 * A b_spa of 0 is used to indicate that this header is
3491244781f1SPrakash Surya 		 * a marker. This fact is used in arc_adjust_type() and
3492244781f1SPrakash Surya 		 * arc_evict_state_impl().
349369962b56SMatthew Ahrens 		 */
3494244781f1SPrakash Surya 		markers[i]->b_spa = 0;
3495fa94a07fSbrendan 
3496244781f1SPrakash Surya 		multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3497244781f1SPrakash Surya 		multilist_sublist_insert_tail(mls, markers[i]);
3498244781f1SPrakash Surya 		multilist_sublist_unlock(mls);
3499244781f1SPrakash Surya 	}
3500fa94a07fSbrendan 
3501244781f1SPrakash Surya 	/*
3502244781f1SPrakash Surya 	 * While we haven't hit our target number of bytes to evict, or
3503244781f1SPrakash Surya 	 * we're evicting all available buffers.
3504244781f1SPrakash Surya 	 */
3505244781f1SPrakash Surya 	while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
3506244781f1SPrakash Surya 		/*
3507244781f1SPrakash Surya 		 * Start eviction using a randomly selected sublist,
3508244781f1SPrakash Surya 		 * this is to try and evenly balance eviction across all
3509244781f1SPrakash Surya 		 * sublists. Always starting at the same sublist
3510244781f1SPrakash Surya 		 * (e.g. index 0) would cause evictions to favor certain
3511244781f1SPrakash Surya 		 * sublists over others.
3512244781f1SPrakash Surya 		 */
3513244781f1SPrakash Surya 		int sublist_idx = multilist_get_random_index(ml);
3514244781f1SPrakash Surya 		uint64_t scan_evicted = 0;
3515244781f1SPrakash Surya 
3516244781f1SPrakash Surya 		for (int i = 0; i < num_sublists; i++) {
3517244781f1SPrakash Surya 			uint64_t bytes_remaining;
3518244781f1SPrakash Surya 			uint64_t bytes_evicted;
3519244781f1SPrakash Surya 
3520244781f1SPrakash Surya 			if (bytes == ARC_EVICT_ALL)
3521244781f1SPrakash Surya 				bytes_remaining = ARC_EVICT_ALL;
3522244781f1SPrakash Surya 			else if (total_evicted < bytes)
3523244781f1SPrakash Surya 				bytes_remaining = bytes - total_evicted;
3524244781f1SPrakash Surya 			else
3525fa9e4066Sahrens 				break;
3526244781f1SPrakash Surya 
3527244781f1SPrakash Surya 			bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
3528244781f1SPrakash Surya 			    markers[sublist_idx], spa, bytes_remaining);
3529244781f1SPrakash Surya 
3530244781f1SPrakash Surya 			scan_evicted += bytes_evicted;
3531244781f1SPrakash Surya 			total_evicted += bytes_evicted;
3532244781f1SPrakash Surya 
3533244781f1SPrakash Surya 			/* we've reached the end, wrap to the beginning */
3534244781f1SPrakash Surya 			if (++sublist_idx >= num_sublists)
3535244781f1SPrakash Surya 				sublist_idx = 0;
3536244781f1SPrakash Surya 		}
3537244781f1SPrakash Surya 
3538244781f1SPrakash Surya 		/*
3539244781f1SPrakash Surya 		 * If we didn't evict anything during this scan, we have
3540244781f1SPrakash Surya 		 * no reason to believe we'll evict more during another
3541244781f1SPrakash Surya 		 * scan, so break the loop.
3542244781f1SPrakash Surya 		 */
3543244781f1SPrakash Surya 		if (scan_evicted == 0) {
3544244781f1SPrakash Surya 			/* This isn't possible, let's make that obvious */
3545244781f1SPrakash Surya 			ASSERT3S(bytes, !=, 0);
3546244781f1SPrakash Surya 
3547b802aa8cSSanjeev Bagewadi 			/*
3548244781f1SPrakash Surya 			 * When bytes is ARC_EVICT_ALL, the only way to
3549244781f1SPrakash Surya 			 * break the loop is when scan_evicted is zero.
3550244781f1SPrakash Surya 			 * In that case, we actually have evicted enough,
3551244781f1SPrakash Surya 			 * so we don't want to increment the kstat.
3552b802aa8cSSanjeev Bagewadi 			 */
3553244781f1SPrakash Surya 			if (bytes != ARC_EVICT_ALL) {
3554244781f1SPrakash Surya 				ASSERT3S(total_evicted, <, bytes);
3555244781f1SPrakash Surya 				ARCSTAT_BUMP(arcstat_evict_not_enough);
3556244781f1SPrakash Surya 			}
3557244781f1SPrakash Surya 
3558244781f1SPrakash Surya 			break;
355969962b56SMatthew Ahrens 		}
3560244781f1SPrakash Surya 	}
3561244781f1SPrakash Surya 
3562244781f1SPrakash Surya 	for (int i = 0; i < num_sublists; i++) {
3563244781f1SPrakash Surya 		multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3564244781f1SPrakash Surya 		multilist_sublist_remove(mls, markers[i]);
3565244781f1SPrakash Surya 		multilist_sublist_unlock(mls);
356669962b56SMatthew Ahrens 
3567244781f1SPrakash Surya 		kmem_cache_free(hdr_full_cache, markers[i]);
3568fa9e4066Sahrens 	}
3569244781f1SPrakash Surya 	kmem_free(markers, sizeof (*markers) * num_sublists);
3570fa9e4066Sahrens 
3571244781f1SPrakash Surya 	return (total_evicted);
3572244781f1SPrakash Surya }
3573244781f1SPrakash Surya 
3574244781f1SPrakash Surya /*
3575244781f1SPrakash Surya  * Flush all "evictable" data of the given type from the arc state
3576244781f1SPrakash Surya  * specified. This will not evict any "active" buffers (i.e. referenced).
3577244781f1SPrakash Surya  *
3578dcbf3bd6SGeorge Wilson  * When 'retry' is set to B_FALSE, the function will make a single pass
3579244781f1SPrakash Surya  * over the state and evict any buffers that it can. Since it doesn't
3580244781f1SPrakash Surya  * continually retry the eviction, it might end up leaving some buffers
3581244781f1SPrakash Surya  * in the ARC due to lock misses.
3582244781f1SPrakash Surya  *
3583dcbf3bd6SGeorge Wilson  * When 'retry' is set to B_TRUE, the function will continually retry the
3584244781f1SPrakash Surya  * eviction until *all* evictable buffers have been removed from the
3585244781f1SPrakash Surya  * state. As a result, if concurrent insertions into the state are
3586244781f1SPrakash Surya  * allowed (e.g. if the ARC isn't shutting down), this function might
3587244781f1SPrakash Surya  * wind up in an infinite loop, continually trying to evict buffers.
3588244781f1SPrakash Surya  */
3589244781f1SPrakash Surya static uint64_t
3590244781f1SPrakash Surya arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
3591244781f1SPrakash Surya     boolean_t retry)
3592244781f1SPrakash Surya {
3593244781f1SPrakash Surya 	uint64_t evicted = 0;
3594244781f1SPrakash Surya 
3595dcbf3bd6SGeorge Wilson 	while (refcount_count(&state->arcs_esize[type]) != 0) {
3596244781f1SPrakash Surya 		evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
3597244781f1SPrakash Surya 
3598244781f1SPrakash Surya 		if (!retry)
3599244781f1SPrakash Surya 			break;
36000e8c6158Smaybee 	}
36010e8c6158Smaybee 
3602244781f1SPrakash Surya 	return (evicted);
3603244781f1SPrakash Surya }
3604244781f1SPrakash Surya 
3605244781f1SPrakash Surya /*
3606244781f1SPrakash Surya  * Evict the specified number of bytes from the state specified,
3607244781f1SPrakash Surya  * restricting eviction to the spa and type given. This function
3608244781f1SPrakash Surya  * prevents us from trying to evict more from a state's list than
3609244781f1SPrakash Surya  * is "evictable", and to skip evicting altogether when passed a
3610244781f1SPrakash Surya  * negative value for "bytes". In contrast, arc_evict_state() will
3611244781f1SPrakash Surya  * evict everything it can, when passed a negative value for "bytes".
3612244781f1SPrakash Surya  */
3613244781f1SPrakash Surya static uint64_t
3614244781f1SPrakash Surya arc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
3615244781f1SPrakash Surya     arc_buf_contents_t type)
3616244781f1SPrakash Surya {
3617244781f1SPrakash Surya 	int64_t delta;
3618244781f1SPrakash Surya 
3619dcbf3bd6SGeorge Wilson 	if (bytes > 0 && refcount_count(&state->arcs_esize[type]) > 0) {
3620dcbf3bd6SGeorge Wilson 		delta = MIN(refcount_count(&state->arcs_esize[type]), bytes);
3621244781f1SPrakash Surya 		return (arc_evict_state(state, spa, delta, type));
3622fa9e4066Sahrens 	}
3623fa9e4066Sahrens 
3624244781f1SPrakash Surya 	return (0);
3625fa9e4066Sahrens }
3626fa9e4066Sahrens 
3627244781f1SPrakash Surya /*
3628244781f1SPrakash Surya  * Evict metadata buffers from the cache, such that arc_meta_used is
3629244781f1SPrakash Surya  * capped by the arc_meta_limit tunable.
3630244781f1SPrakash Surya  */
3631244781f1SPrakash Surya static uint64_t
36323a2d8a1bSPaul Dagnelie arc_adjust_meta(uint64_t meta_used)
3633244781f1SPrakash Surya {
3634244781f1SPrakash Surya 	uint64_t total_evicted = 0;
3635244781f1SPrakash Surya 	int64_t target;
3636244781f1SPrakash Surya 
3637244781f1SPrakash Surya 	/*
3638244781f1SPrakash Surya 	 * If we're over the meta limit, we want to evict enough
3639244781f1SPrakash Surya 	 * metadata to get back under the meta limit. We don't want to
3640244781f1SPrakash Surya 	 * evict so much that we drop the MRU below arc_p, though. If
3641244781f1SPrakash Surya 	 * we're over the meta limit more than we're over arc_p, we
3642244781f1SPrakash Surya 	 * evict some from the MRU here, and some from the MFU below.
3643244781f1SPrakash Surya 	 */
36443a2d8a1bSPaul Dagnelie 	target = MIN((int64_t)(meta_used - arc_meta_limit),
36452fd872a7SPrakash Surya 	    (int64_t)(refcount_count(&arc_anon->arcs_size) +
36462fd872a7SPrakash Surya 	    refcount_count(&arc_mru->arcs_size) - arc_p));
3647244781f1SPrakash Surya 
3648244781f1SPrakash Surya 	total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3649244781f1SPrakash Surya 
3650244781f1SPrakash Surya 	/*
3651244781f1SPrakash Surya 	 * Similar to the above, we want to evict enough bytes to get us
3652244781f1SPrakash Surya 	 * below the meta limit, but not so much as to drop us below the
36535602294fSDan Kimmel 	 * space allotted to the MFU (which is defined as arc_c - arc_p).
3654244781f1SPrakash Surya 	 */
36553a2d8a1bSPaul Dagnelie 	target = MIN((int64_t)(meta_used - arc_meta_limit),
36563a2d8a1bSPaul Dagnelie 	    (int64_t)(refcount_count(&arc_mfu->arcs_size) -
36573a2d8a1bSPaul Dagnelie 	    (arc_c - arc_p)));
3658244781f1SPrakash Surya 
3659244781f1SPrakash Surya 	total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3660244781f1SPrakash Surya 
3661244781f1SPrakash Surya 	return (total_evicted);
3662244781f1SPrakash Surya }
3663244781f1SPrakash Surya 
3664244781f1SPrakash Surya /*
3665244781f1SPrakash Surya  * Return the type of the oldest buffer in the given arc state
3666244781f1SPrakash Surya  *
3667244781f1SPrakash Surya  * This function will select a random sublist of type ARC_BUFC_DATA and
3668244781f1SPrakash Surya  * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
3669244781f1SPrakash Surya  * is compared, and the type which contains the "older" buffer will be
3670244781f1SPrakash Surya  * returned.
3671244781f1SPrakash Surya  */
3672244781f1SPrakash Surya static arc_buf_contents_t
3673244781f1SPrakash Surya arc_adjust_type(arc_state_t *state)
3674244781f1SPrakash Surya {
367594c2d0ebSMatthew Ahrens 	multilist_t *data_ml = state->arcs_list[ARC_BUFC_DATA];
367694c2d0ebSMatthew Ahrens 	multilist_t *meta_ml = state->arcs_list[ARC_BUFC_METADATA];
3677244781f1SPrakash Surya 	int data_idx = multilist_get_random_index(data_ml);
3678244781f1SPrakash Surya 	int meta_idx = multilist_get_random_index(meta_ml);
3679244781f1SPrakash Surya 	multilist_sublist_t *data_mls;
3680244781f1SPrakash Surya 	multilist_sublist_t *meta_mls;
3681244781f1SPrakash Surya 	arc_buf_contents_t type;
3682244781f1SPrakash Surya 	arc_buf_hdr_t *data_hdr;
3683244781f1SPrakash Surya 	arc_buf_hdr_t *meta_hdr;
3684244781f1SPrakash Surya 
3685244781f1SPrakash Surya 	/*
3686244781f1SPrakash Surya 	 * We keep the sublist lock until we're finished, to prevent
3687244781f1SPrakash Surya 	 * the headers from being destroyed via arc_evict_state().
3688244781f1SPrakash Surya 	 */
3689244781f1SPrakash Surya 	data_mls = multilist_sublist_lock(data_ml, data_idx);
3690244781f1SPrakash Surya 	meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
3691244781f1SPrakash Surya 
3692244781f1SPrakash Surya 	/*
3693244781f1SPrakash Surya 	 * These two loops are to ensure we skip any markers that
3694244781f1SPrakash Surya 	 * might be at the tail of the lists due to arc_evict_state().
3695244781f1SPrakash Surya 	 */
3696244781f1SPrakash Surya 
3697244781f1SPrakash Surya 	for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
3698244781f1SPrakash Surya 	    data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
3699244781f1SPrakash Surya 		if (data_hdr->b_spa != 0)
3700244781f1SPrakash Surya 			break;
3701244781f1SPrakash Surya 	}
3702244781f1SPrakash Surya 
3703244781f1SPrakash Surya 	for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
3704244781f1SPrakash Surya 	    meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
3705244781f1SPrakash Surya 		if (meta_hdr->b_spa != 0)
3706244781f1SPrakash Surya 			break;
3707244781f1SPrakash Surya 	}
3708244781f1SPrakash Surya 
3709244781f1SPrakash Surya 	if (data_hdr == NULL && meta_hdr == NULL) {
3710244781f1SPrakash Surya 		type = ARC_BUFC_DATA;
3711244781f1SPrakash Surya 	} else if (data_hdr == NULL) {
3712244781f1SPrakash Surya 		ASSERT3P(meta_hdr, !=, NULL);
3713244781f1SPrakash Surya 		type = ARC_BUFC_METADATA;
3714244781f1SPrakash Surya 	} else if (meta_hdr == NULL) {
3715244781f1SPrakash Surya 		ASSERT3P(data_hdr, !=, NULL);
3716244781f1SPrakash Surya 		type = ARC_BUFC_DATA;
3717244781f1SPrakash Surya 	} else {
3718244781f1SPrakash Surya 		ASSERT3P(data_hdr, !=, NULL);
3719244781f1SPrakash Surya 		ASSERT3P(meta_hdr, !=, NULL);
3720244781f1SPrakash Surya 
3721244781f1SPrakash Surya 		/* The headers can't be on the sublist without an L1 header */
3722244781f1SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(data_hdr));
3723244781f1SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(meta_hdr));
3724244781f1SPrakash Surya 
3725244781f1SPrakash Surya 		if (data_hdr->b_l1hdr.b_arc_access <
3726244781f1SPrakash Surya 		    meta_hdr->b_l1hdr.b_arc_access) {
3727244781f1SPrakash Surya 			type = ARC_BUFC_DATA;
3728244781f1SPrakash Surya 		} else {
3729244781f1SPrakash Surya 			type = ARC_BUFC_METADATA;
3730244781f1SPrakash Surya 		}
3731244781f1SPrakash Surya 	}
3732244781f1SPrakash Surya 
3733244781f1SPrakash Surya 	multilist_sublist_unlock(meta_mls);
3734244781f1SPrakash Surya 	multilist_sublist_unlock(data_mls);
3735244781f1SPrakash Surya 
3736244781f1SPrakash Surya 	return (type);
3737244781f1SPrakash Surya }
3738244781f1SPrakash Surya 
3739244781f1SPrakash Surya /*
3740244781f1SPrakash Surya  * Evict buffers from the cache, such that arc_size is capped by arc_c.
3741244781f1SPrakash Surya  */
3742244781f1SPrakash Surya static uint64_t
3743fa9e4066Sahrens arc_adjust(void)
3744fa9e4066Sahrens {
3745244781f1SPrakash Surya 	uint64_t total_evicted = 0;
3746244781f1SPrakash Surya 	uint64_t bytes;
3747244781f1SPrakash Surya 	int64_t target;
37483a2d8a1bSPaul Dagnelie 	uint64_t asize = aggsum_value(&arc_size);
37493a2d8a1bSPaul Dagnelie 	uint64_t ameta = aggsum_value(&arc_meta_used);
3750fa9e4066Sahrens 
37515a98e54bSBrendan Gregg - Sun Microsystems 	/*
3752244781f1SPrakash Surya 	 * If we're over arc_meta_limit, we want to correct that before
3753244781f1SPrakash Surya 	 * potentially evicting data buffers below.
37545a98e54bSBrendan Gregg - Sun Microsystems 	 */
37553a2d8a1bSPaul Dagnelie 	total_evicted += arc_adjust_meta(ameta);
37565a98e54bSBrendan Gregg - Sun Microsystems 
3757244781f1SPrakash Surya 	/*
3758244781f1SPrakash Surya 	 * Adjust MRU size
3759244781f1SPrakash Surya 	 *
3760244781f1SPrakash Surya 	 * If we're over the target cache size, we want to evict enough
3761244781f1SPrakash Surya 	 * from the list to get back to our target size. We don't want
3762244781f1SPrakash Surya 	 * to evict too much from the MRU, such that it drops below
3763244781f1SPrakash Surya 	 * arc_p. So, if we're over our target cache size more than
3764244781f1SPrakash Surya 	 * the MRU is over arc_p, we'll evict enough to get back to
3765244781f1SPrakash Surya 	 * arc_p here, and then evict more from the MFU below.
3766244781f1SPrakash Surya 	 */
37673a2d8a1bSPaul Dagnelie 	target = MIN((int64_t)(asize - arc_c),
37682fd872a7SPrakash Surya 	    (int64_t)(refcount_count(&arc_anon->arcs_size) +
37693a2d8a1bSPaul Dagnelie 	    refcount_count(&arc_mru->arcs_size) + ameta - arc_p));
3770fa9e4066Sahrens 
3771244781f1SPrakash Surya 	/*
3772244781f1SPrakash Surya 	 * If we're below arc_meta_min, always prefer to evict data.
3773244781f1SPrakash Surya 	 * Otherwise, try to satisfy the requested number of bytes to
3774244781f1SPrakash Surya 	 * evict from the type which contains older buffers; in an
3775244781f1SPrakash Surya 	 * effort to keep newer buffers in the cache regardless of their
3776244781f1SPrakash Surya 	 * type. If we cannot satisfy the number of bytes from this
3777244781f1SPrakash Surya 	 * type, spill over into the next type.
3778244781f1SPrakash Surya 	 */
3779244781f1SPrakash Surya 	if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
37803a2d8a1bSPaul Dagnelie 	    ameta > arc_meta_min) {
3781244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3782244781f1SPrakash Surya 		total_evicted += bytes;
37830e8c6158Smaybee 
3784244781f1SPrakash Surya 		/*
3785244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
3786244781f1SPrakash Surya 		 * metadata, we try to get the rest from data.
3787244781f1SPrakash Surya 		 */
3788244781f1SPrakash Surya 		target -= bytes;
3789244781f1SPrakash Surya 
3790244781f1SPrakash Surya 		total_evicted +=
3791244781f1SPrakash Surya 		    arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3792244781f1SPrakash Surya 	} else {
3793244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3794244781f1SPrakash Surya 		total_evicted += bytes;
3795244781f1SPrakash Surya 
3796244781f1SPrakash Surya 		/*
3797244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
3798244781f1SPrakash Surya 		 * data, we try to get the rest from metadata.
3799244781f1SPrakash Surya 		 */
3800244781f1SPrakash Surya 		target -= bytes;
3801244781f1SPrakash Surya 
3802244781f1SPrakash Surya 		total_evicted +=
3803244781f1SPrakash Surya 		    arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3804fa9e4066Sahrens 	}
3805fa9e4066Sahrens 
38065a98e54bSBrendan Gregg - Sun Microsystems 	/*
38075a98e54bSBrendan Gregg - Sun Microsystems 	 * Adjust MFU size
3808244781f1SPrakash Surya 	 *
3809244781f1SPrakash Surya 	 * Now that we've tried to evict enough from the MRU to get its
3810244781f1SPrakash Surya 	 * size back to arc_p, if we're still above the target cache
3811244781f1SPrakash Surya 	 * size, we evict the rest from the MFU.
38125a98e54bSBrendan Gregg - Sun Microsystems 	 */
38133a2d8a1bSPaul Dagnelie 	target = asize - arc_c;
3814fa9e4066Sahrens 
381531c46cf2SAlek Pinchuk 	if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
38163a2d8a1bSPaul Dagnelie 	    ameta > arc_meta_min) {
3817244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3818244781f1SPrakash Surya 		total_evicted += bytes;
38195a98e54bSBrendan Gregg - Sun Microsystems 
3820244781f1SPrakash Surya 		/*
3821244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
3822244781f1SPrakash Surya 		 * metadata, we try to get the rest from data.
3823244781f1SPrakash Surya 		 */
3824244781f1SPrakash Surya 		target -= bytes;
3825244781f1SPrakash Surya 
3826244781f1SPrakash Surya 		total_evicted +=
3827244781f1SPrakash Surya 		    arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3828244781f1SPrakash Surya 	} else {
3829244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3830244781f1SPrakash Surya 		total_evicted += bytes;
3831244781f1SPrakash Surya 
3832244781f1SPrakash Surya 		/*
3833244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
3834244781f1SPrakash Surya 		 * data, we try to get the rest from data.
3835244781f1SPrakash Surya 		 */
3836244781f1SPrakash Surya 		target -= bytes;
3837fa9e4066Sahrens 
3838244781f1SPrakash Surya 		total_evicted +=
3839244781f1SPrakash Surya 		    arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
38405a98e54bSBrendan Gregg - Sun Microsystems 	}
3841fa9e4066Sahrens 
38425a98e54bSBrendan Gregg - Sun Microsystems 	/*
38435a98e54bSBrendan Gregg - Sun Microsystems 	 * Adjust ghost lists
3844244781f1SPrakash Surya 	 *
3845244781f1SPrakash Surya 	 * In addition to the above, the ARC also defines target values
3846244781f1SPrakash Surya 	 * for the ghost lists. The sum of the mru list and mru ghost
3847244781f1SPrakash Surya 	 * list should never exceed the target size of the cache, and
3848244781f1SPrakash Surya 	 * the sum of the mru list, mfu list, mru ghost list, and mfu
3849244781f1SPrakash Surya 	 * ghost list should never exceed twice the target size of the
3850244781f1SPrakash Surya 	 * cache. The following logic enforces these limits on the ghost
3851244781f1SPrakash Surya 	 * caches, and evicts from them as needed.
38525a98e54bSBrendan Gregg - Sun Microsystems 	 */
38532fd872a7SPrakash Surya 	target = refcount_count(&arc_mru->arcs_size) +
38542fd872a7SPrakash Surya 	    refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
3855fa9e4066Sahrens 
3856244781f1SPrakash Surya 	bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
3857244781f1SPrakash Surya 	total_evicted += bytes;
3858fa9e4066Sahrens 
3859244781f1SPrakash Surya 	target -= bytes;
38600e8c6158Smaybee 
3861244781f1SPrakash Surya 	total_evicted +=
3862244781f1SPrakash Surya 	    arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
38635a98e54bSBrendan Gregg - Sun Microsystems 
3864244781f1SPrakash Surya 	/*
3865244781f1SPrakash Surya 	 * We assume the sum of the mru list and mfu list is less than
3866244781f1SPrakash Surya 	 * or equal to arc_c (we enforced this above), which means we
3867244781f1SPrakash Surya 	 * can use the simpler of the two equations below:
3868244781f1SPrakash Surya 	 *
3869244781f1SPrakash Surya 	 *	mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
3870244781f1SPrakash Surya 	 *		    mru ghost + mfu ghost <= arc_c
3871244781f1SPrakash Surya 	 */
38722fd872a7SPrakash Surya 	target = refcount_count(&arc_mru_ghost->arcs_size) +
38732fd872a7SPrakash Surya 	    refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
3874244781f1SPrakash Surya 
3875244781f1SPrakash Surya 	bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
3876244781f1SPrakash Surya 	total_evicted += bytes;
3877244781f1SPrakash Surya 
3878244781f1SPrakash Surya 	target -= bytes;
3879244781f1SPrakash Surya 
3880244781f1SPrakash Surya 	total_evicted +=
3881244781f1SPrakash Surya 	    arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
3882244781f1SPrakash Surya 
3883244781f1SPrakash Surya 	return (total_evicted);
3884fa9e4066Sahrens }
3885fa9e4066Sahrens 
3886fa9e4066Sahrens void
3887244781f1SPrakash Surya arc_flush(spa_t *spa, boolean_t retry)
3888fa9e4066Sahrens {
3889ac05c741SMark Maybee 	uint64_t guid = 0;
3890ac05c741SMark Maybee 
3891244781f1SPrakash Surya 	/*
3892dcbf3bd6SGeorge Wilson 	 * If retry is B_TRUE, a spa must not be specified since we have
3893244781f1SPrakash Surya 	 * no good way to determine if all of a spa's buffers have been
3894244781f1SPrakash Surya 	 * evicted from an arc state.
3895244781f1SPrakash Surya 	 */
3896244781f1SPrakash Surya 	ASSERT(!retry || spa == 0);
3897244781f1SPrakash Surya 
389889c86e32SChris Williamson 	if (spa != NULL)
3899e9103aaeSGarrett D'Amore 		guid = spa_load_guid(spa);
3900ac05c741SMark Maybee 
3901244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
3902244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
3903244781f1SPrakash Surya 
3904244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
3905244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
3906874395d5Smaybee 
3907244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
3908244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
3909244781f1SPrakash Surya 
3910244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
3911244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
3912fa9e4066Sahrens }
3913fa9e4066Sahrens 
3914*de753e34SBrad Lewis static void
3915*de753e34SBrad Lewis arc_reduce_target_size(int64_t to_free)
3916fa9e4066Sahrens {
39173a2d8a1bSPaul Dagnelie 	uint64_t asize = aggsum_value(&arc_size);
391844cb6abcSbmc 	if (arc_c > arc_c_min) {
3919fa9e4066Sahrens 
392044cb6abcSbmc 		if (arc_c > arc_c_min + to_free)
392144cb6abcSbmc 			atomic_add_64(&arc_c, -to_free);
392249e3519aSmaybee 		else
392344cb6abcSbmc 			arc_c = arc_c_min;
392444cb6abcSbmc 
392544cb6abcSbmc 		atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
39263a2d8a1bSPaul Dagnelie 		if (asize < arc_c)
39273a2d8a1bSPaul Dagnelie 			arc_c = MAX(asize, arc_c_min);
392844cb6abcSbmc 		if (arc_p > arc_c)
392944cb6abcSbmc 			arc_p = (arc_c >> 1);
393044cb6abcSbmc 		ASSERT(arc_c >= arc_c_min);
393144cb6abcSbmc 		ASSERT((int64_t)arc_p >= 0);
393249e3519aSmaybee 	}
3933fa9e4066Sahrens 
3934*de753e34SBrad Lewis 	if (asize > arc_c) {
3935*de753e34SBrad Lewis 		/* See comment in arc_adjust_cb_check() on why lock+flag */
3936*de753e34SBrad Lewis 		mutex_enter(&arc_adjust_lock);
3937*de753e34SBrad Lewis 		arc_adjust_needed = B_TRUE;
3938*de753e34SBrad Lewis 		mutex_exit(&arc_adjust_lock);
3939*de753e34SBrad Lewis 		zthr_wakeup(arc_adjust_zthr);
3940*de753e34SBrad Lewis 	}
3941fa9e4066Sahrens }
3942fa9e4066Sahrens 
39432ec99e3eSMatthew Ahrens typedef enum free_memory_reason_t {
39442ec99e3eSMatthew Ahrens 	FMR_UNKNOWN,
39452ec99e3eSMatthew Ahrens 	FMR_NEEDFREE,
39462ec99e3eSMatthew Ahrens 	FMR_LOTSFREE,
39472ec99e3eSMatthew Ahrens 	FMR_SWAPFS_MINFREE,
39482ec99e3eSMatthew Ahrens 	FMR_PAGES_PP_MAXIMUM,
39492ec99e3eSMatthew Ahrens 	FMR_HEAP_ARENA,
39502ec99e3eSMatthew Ahrens 	FMR_ZIO_ARENA,
39512ec99e3eSMatthew Ahrens } free_memory_reason_t;
39522ec99e3eSMatthew Ahrens 
39532ec99e3eSMatthew Ahrens int64_t last_free_memory;
39542ec99e3eSMatthew Ahrens free_memory_reason_t last_free_reason;
39552ec99e3eSMatthew Ahrens 
395694dd93aeSGeorge Wilson /*
39572ec99e3eSMatthew Ahrens  * Additional reserve of pages for pp_reserve.
395894dd93aeSGeorge Wilson  */
39592ec99e3eSMatthew Ahrens int64_t arc_pages_pp_reserve = 64;
3960fa9e4066Sahrens 
39612ec99e3eSMatthew Ahrens /*
39622ec99e3eSMatthew Ahrens  * Additional reserve of pages for swapfs.
39632ec99e3eSMatthew Ahrens  */
39642ec99e3eSMatthew Ahrens int64_t arc_swapfs_reserve = 64;
39653cff2f43Sstans 
39662ec99e3eSMatthew Ahrens /*
39672ec99e3eSMatthew Ahrens  * Return the amount of memory that can be consumed before reclaim will be
39682ec99e3eSMatthew Ahrens  * needed.  Positive if there is sufficient free memory, negative indicates
39692ec99e3eSMatthew Ahrens  * the amount of memory that needs to be freed up.
39702ec99e3eSMatthew Ahrens  */
39712ec99e3eSMatthew Ahrens static int64_t
39722ec99e3eSMatthew Ahrens arc_available_memory(void)
39732ec99e3eSMatthew Ahrens {
39742ec99e3eSMatthew Ahrens 	int64_t lowest = INT64_MAX;
39752ec99e3eSMatthew Ahrens 	int64_t n;
39762ec99e3eSMatthew Ahrens 	free_memory_reason_t r = FMR_UNKNOWN;
39773cff2f43Sstans 
39782ec99e3eSMatthew Ahrens #ifdef _KERNEL
39792ec99e3eSMatthew Ahrens 	if (needfree > 0) {
39802ec99e3eSMatthew Ahrens 		n = PAGESIZE * (-needfree);
39812ec99e3eSMatthew Ahrens 		if (n < lowest) {
39822ec99e3eSMatthew Ahrens 			lowest = n;
39832ec99e3eSMatthew Ahrens 			r = FMR_NEEDFREE;
39842ec99e3eSMatthew Ahrens 		}
39852ec99e3eSMatthew Ahrens 	}
3986fa9e4066Sahrens 
3987fa9e4066Sahrens 	/*
3988fa9e4066Sahrens 	 * check that we're out of range of the pageout scanner.  It starts to
3989fa9e4066Sahrens 	 * schedule paging if freemem is less than lotsfree and needfree.
3990fa9e4066Sahrens 	 * lotsfree is the high-water mark for pageout, and needfree is the
3991fa9e4066Sahrens 	 * number of needed free pages.  We add extra pages here to make sure
3992fa9e4066Sahrens 	 * the scanner doesn't start up while we're freeing memory.
3993fa9e4066Sahrens 	 */
39942ec99e3eSMatthew Ahrens 	n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
39952ec99e3eSMatthew Ahrens 	if (n < lowest) {
39962ec99e3eSMatthew Ahrens 		lowest = n;
39972ec99e3eSMatthew Ahrens 		r = FMR_LOTSFREE;
39982ec99e3eSMatthew Ahrens 	}
3999fa9e4066Sahrens 
4000fa9e4066Sahrens 	/*
4001fa9e4066Sahrens 	 * check to make sure that swapfs has enough space so that anon
4002fa94a07fSbrendan 	 * reservations can still succeed. anon_resvmem() checks that the
4003fa9e4066Sahrens 	 * availrmem is greater than swapfs_minfree, and the number of reserved
4004fa9e4066Sahrens 	 * swap pages.  We also add a bit of extra here just to prevent
4005fa9e4066Sahrens 	 * circumstances from getting really dire.
4006fa9e4066Sahrens 	 */
40072ec99e3eSMatthew Ahrens 	n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
40082ec99e3eSMatthew Ahrens 	    desfree - arc_swapfs_reserve);
40092ec99e3eSMatthew Ahrens 	if (n < lowest) {
40102ec99e3eSMatthew Ahrens 		lowest = n;
40112ec99e3eSMatthew Ahrens 		r = FMR_SWAPFS_MINFREE;
40122ec99e3eSMatthew Ahrens 	}
40132ec99e3eSMatthew Ahrens 
4014fa9e4066Sahrens 
4015cf746768SBryan Cantrill 	/*
4016cf746768SBryan Cantrill 	 * Check that we have enough availrmem that memory locking (e.g., via
4017cf746768SBryan Cantrill 	 * mlock(3C) or memcntl(2)) can still succeed.  (pages_pp_maximum
4018cf746768SBryan Cantrill 	 * stores the number of pages that cannot be locked; when availrmem
4019cf746768SBryan Cantrill 	 * drops below pages_pp_maximum, page locking mechanisms such as
4020cf746768SBryan Cantrill 	 * page_pp_lock() will fail.)
4021cf746768SBryan Cantrill 	 */
40222ec99e3eSMatthew Ahrens 	n = PAGESIZE * (availrmem - pages_pp_maximum -
40232ec99e3eSMatthew Ahrens 	    arc_pages_pp_reserve);
40242ec99e3eSMatthew Ahrens 	if (n < lowest) {
40252ec99e3eSMatthew Ahrens 		lowest = n;
40262ec99e3eSMatthew Ahrens 		r = FMR_PAGES_PP_MAXIMUM;
40272ec99e3eSMatthew Ahrens 	}
4028cf746768SBryan Cantrill 
40295dc8af33Smaybee #if defined(__i386)
4030fa9e4066Sahrens 	/*
4031fa9e4066Sahrens 	 * If we're on an i386 platform, it's possible that we'll exhaust the
4032fa9e4066Sahrens 	 * kernel heap space before we ever run out of available physical
4033fa9e4066Sahrens 	 * memory.  Most checks of the size of the heap_area compare against
4034fa9e4066Sahrens 	 * tune.t_minarmem, which is the minimum available real memory that we
4035fa9e4066Sahrens 	 * can have in the system.  However, this is generally fixed at 25 pages
4036fa9e4066Sahrens 	 * which is so low that it's useless.  In this comparison, we seek to
4037fa9e4066Sahrens 	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
4038fa94a07fSbrendan 	 * heap is allocated.  (Or, in the calculation, if less than 1/4th is
4039fa9e4066Sahrens 	 * free)
4040fa9e4066Sahrens 	 */
40410dd053d7SPrakash Surya 	n = (int64_t)vmem_size(heap_arena, VMEM_FREE) -
40422ec99e3eSMatthew Ahrens 	    (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2);
40432ec99e3eSMatthew Ahrens 	if (n < lowest) {
40442ec99e3eSMatthew Ahrens 		lowest = n;
40452ec99e3eSMatthew Ahrens 		r = FMR_HEAP_ARENA;
40462ec99e3eSMatthew Ahrens 	}
4047fa9e4066Sahrens #endif
4048fa9e4066Sahrens 
404994dd93aeSGeorge Wilson 	/*
405094dd93aeSGeorge Wilson 	 * If zio data pages are being allocated out of a separate heap segment,
405194dd93aeSGeorge Wilson 	 * then enforce that the size of available vmem for this arena remains
40520dd053d7SPrakash Surya 	 * above about 1/4th (1/(2^arc_zio_arena_free_shift)) free.
405394dd93aeSGeorge Wilson 	 *
40540dd053d7SPrakash Surya 	 * Note that reducing the arc_zio_arena_free_shift keeps more virtual
40550dd053d7SPrakash Surya 	 * memory (in the zio_arena) free, which can avoid memory
40560dd053d7SPrakash Surya 	 * fragmentation issues.
405794dd93aeSGeorge Wilson 	 */
40582ec99e3eSMatthew Ahrens 	if (zio_arena != NULL) {
40590dd053d7SPrakash Surya 		n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
40600dd053d7SPrakash Surya 		    (vmem_size(zio_arena, VMEM_ALLOC) >>
40610dd053d7SPrakash Surya 		    arc_zio_arena_free_shift);
40622ec99e3eSMatthew Ahrens 		if (n < lowest) {
40632ec99e3eSMatthew Ahrens 			lowest = n;
40642ec99e3eSMatthew Ahrens 			r = FMR_ZIO_ARENA;
40652ec99e3eSMatthew Ahrens 		}
40662ec99e3eSMatthew Ahrens 	}
4067fa9e4066Sahrens #else
40682ec99e3eSMatthew Ahrens 	/* Every 100 calls, free a small amount */
4069fa9e4066Sahrens 	if (spa_get_random(100) == 0)
40702ec99e3eSMatthew Ahrens 		lowest = -1024;
4071fa9e4066Sahrens #endif
40722ec99e3eSMatthew Ahrens 
40732ec99e3eSMatthew Ahrens 	last_free_memory = lowest;
40742ec99e3eSMatthew Ahrens 	last_free_reason = r;
40752ec99e3eSMatthew Ahrens 
40762ec99e3eSMatthew Ahrens 	return (lowest);
40772ec99e3eSMatthew Ahrens }
40782ec99e3eSMatthew Ahrens 
40792ec99e3eSMatthew Ahrens 
40802ec99e3eSMatthew Ahrens /*
40812ec99e3eSMatthew Ahrens  * Determine if the system is under memory pressure and is asking
4082dcbf3bd6SGeorge Wilson  * to reclaim memory. A return value of B_TRUE indicates that the system
40832ec99e3eSMatthew Ahrens  * is under memory pressure and that the arc should adjust accordingly.
40842ec99e3eSMatthew Ahrens  */
40852ec99e3eSMatthew Ahrens static boolean_t
40862ec99e3eSMatthew Ahrens arc_reclaim_needed(void)
40872ec99e3eSMatthew Ahrens {
40882ec99e3eSMatthew Ahrens 	return (arc_available_memory() < 0);
4089fa9e4066Sahrens }
4090fa9e4066Sahrens 
4091fa9e4066Sahrens static void
4092*de753e34SBrad Lewis arc_kmem_reap_soon(void)
4093fa9e4066Sahrens {
4094fa9e4066Sahrens 	size_t			i;
4095fa9e4066Sahrens 	kmem_cache_t		*prev_cache = NULL;
4096ad23a2dbSjohansen 	kmem_cache_t		*prev_data_cache = NULL;
4097fa9e4066Sahrens 	extern kmem_cache_t	*zio_buf_cache[];
4098ad23a2dbSjohansen 	extern kmem_cache_t	*zio_data_buf_cache[];
409983803b51SGeorge Wilson 	extern kmem_cache_t	*range_seg_cache;
4100770499e1SDan Kimmel 	extern kmem_cache_t	*abd_chunk_cache;
4101fa9e4066Sahrens 
4102033f9833Sek #ifdef _KERNEL
41033a2d8a1bSPaul Dagnelie 	if (aggsum_compare(&arc_meta_used, arc_meta_limit) >= 0) {
41040e8c6158Smaybee 		/*
41050e8c6158Smaybee 		 * We are exceeding our meta-data cache limit.
41060e8c6158Smaybee 		 * Purge some DNLC entries to release holds on meta-data.
41070e8c6158Smaybee 		 */
41080e8c6158Smaybee 		dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
41090e8c6158Smaybee 	}
41105dc8af33Smaybee #if defined(__i386)
41115dc8af33Smaybee 	/*
41125dc8af33Smaybee 	 * Reclaim unused memory from all kmem caches.
41135dc8af33Smaybee 	 */
41145dc8af33Smaybee 	kmem_reap();
41155dc8af33Smaybee #endif
4116033f9833Sek #endif
4117033f9833Sek 
4118fa9e4066Sahrens 	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
4119fa9e4066Sahrens 		if (zio_buf_cache[i] != prev_cache) {
4120fa9e4066Sahrens 			prev_cache = zio_buf_cache[i];
412136a64e62STim Kordas 			kmem_cache_reap_soon(zio_buf_cache[i]);
4122fa9e4066Sahrens 		}
4123ad23a2dbSjohansen 		if (zio_data_buf_cache[i] != prev_data_cache) {
4124ad23a2dbSjohansen 			prev_data_cache = zio_data_buf_cache[i];
412536a64e62STim Kordas 			kmem_cache_reap_soon(zio_data_buf_cache[i]);
4126ad23a2dbSjohansen 		}
4127fa9e4066Sahrens 	}
412836a64e62STim Kordas 	kmem_cache_reap_soon(abd_chunk_cache);
412936a64e62STim Kordas 	kmem_cache_reap_soon(buf_cache);
413036a64e62STim Kordas 	kmem_cache_reap_soon(hdr_full_cache);
413136a64e62STim Kordas 	kmem_cache_reap_soon(hdr_l2only_cache);
413236a64e62STim Kordas 	kmem_cache_reap_soon(range_seg_cache);
413394dd93aeSGeorge Wilson 
41342ec99e3eSMatthew Ahrens 	if (zio_arena != NULL) {
41352ec99e3eSMatthew Ahrens 		/*
41362ec99e3eSMatthew Ahrens 		 * Ask the vmem arena to reclaim unused memory from its
41372ec99e3eSMatthew Ahrens 		 * quantum caches.
41382ec99e3eSMatthew Ahrens 		 */
413994dd93aeSGeorge Wilson 		vmem_qcache_reap(zio_arena);
41402ec99e3eSMatthew Ahrens 	}
4141fa9e4066Sahrens }
4142fa9e4066Sahrens 
4143*de753e34SBrad Lewis /* ARGSUSED */
4144*de753e34SBrad Lewis static boolean_t
4145*de753e34SBrad Lewis arc_adjust_cb_check(void *arg, zthr_t *zthr)
4146*de753e34SBrad Lewis {
4147*de753e34SBrad Lewis 	/*
4148*de753e34SBrad Lewis 	 * This is necessary in order for the mdb ::arc dcmd to
4149*de753e34SBrad Lewis 	 * show up to date information. Since the ::arc command
4150*de753e34SBrad Lewis 	 * does not call the kstat's update function, without
4151*de753e34SBrad Lewis 	 * this call, the command may show stale stats for the
4152*de753e34SBrad Lewis 	 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
4153*de753e34SBrad Lewis 	 * with this change, the data might be up to 1 second
4154*de753e34SBrad Lewis 	 * out of date(the arc_adjust_zthr has a maximum sleep
4155*de753e34SBrad Lewis 	 * time of 1 second); but that should suffice.  The
4156*de753e34SBrad Lewis 	 * arc_state_t structures can be queried directly if more
4157*de753e34SBrad Lewis 	 * accurate information is needed.
4158*de753e34SBrad Lewis 	 */
4159*de753e34SBrad Lewis 	if (arc_ksp != NULL)
4160*de753e34SBrad Lewis 		arc_ksp->ks_update(arc_ksp, KSTAT_READ);
4161*de753e34SBrad Lewis 
4162*de753e34SBrad Lewis 	/*
4163*de753e34SBrad Lewis 	 * We have to rely on arc_get_data_impl() to tell us when to adjust,
4164*de753e34SBrad Lewis 	 * rather than checking if we are overflowing here, so that we are
4165*de753e34SBrad Lewis 	 * sure to not leave arc_get_data_impl() waiting on
4166*de753e34SBrad Lewis 	 * arc_adjust_waiters_cv.  If we have become "not overflowing" since
4167*de753e34SBrad Lewis 	 * arc_get_data_impl() checked, we need to wake it up.  We could
4168*de753e34SBrad Lewis 	 * broadcast the CV here, but arc_get_data_impl() may have not yet
4169*de753e34SBrad Lewis 	 * gone to sleep.  We would need to use a mutex to ensure that this
4170*de753e34SBrad Lewis 	 * function doesn't broadcast until arc_get_data_impl() has gone to
4171*de753e34SBrad Lewis 	 * sleep (e.g. the arc_adjust_lock).  However, the lock ordering of
4172*de753e34SBrad Lewis 	 * such a lock would necessarily be incorrect with respect to the
4173*de753e34SBrad Lewis 	 * zthr_lock, which is held before this function is called, and is
4174*de753e34SBrad Lewis 	 * held by arc_get_data_impl() when it calls zthr_wakeup().
4175*de753e34SBrad Lewis 	 */
4176*de753e34SBrad Lewis 	return (arc_adjust_needed);
4177*de753e34SBrad Lewis }
4178*de753e34SBrad Lewis 
4179244781f1SPrakash Surya /*
4180*de753e34SBrad Lewis  * Keep arc_size under arc_c by running arc_adjust which evicts data
4181*de753e34SBrad Lewis  * from the ARC.
4182244781f1SPrakash Surya  */
41833f7978d0SAlan Somers /* ARGSUSED */
4184*de753e34SBrad Lewis static int
4185*de753e34SBrad Lewis arc_adjust_cb(void *arg, zthr_t *zthr)
4186fa9e4066Sahrens {
4187*de753e34SBrad Lewis 	uint64_t evicted = 0;
4188fa9e4066Sahrens 
4189*de753e34SBrad Lewis 	/* Evict from cache */
4190*de753e34SBrad Lewis 	evicted = arc_adjust();
4191244781f1SPrakash Surya 
4192*de753e34SBrad Lewis 	/*
4193*de753e34SBrad Lewis 	 * If evicted is zero, we couldn't evict anything
4194*de753e34SBrad Lewis 	 * via arc_adjust(). This could be due to hash lock
4195*de753e34SBrad Lewis 	 * collisions, but more likely due to the majority of
4196*de753e34SBrad Lewis 	 * arc buffers being unevictable. Therefore, even if
4197*de753e34SBrad Lewis 	 * arc_size is above arc_c, another pass is unlikely to
4198*de753e34SBrad Lewis 	 * be helpful and could potentially cause us to enter an
4199*de753e34SBrad Lewis 	 * infinite loop.  Additionally, zthr_iscancelled() is
4200*de753e34SBrad Lewis 	 * checked here so that if the arc is shutting down, the
4201*de753e34SBrad Lewis 	 * broadcast will wake any remaining arc adjust waiters.
4202*de753e34SBrad Lewis 	 */
4203*de753e34SBrad Lewis 	mutex_enter(&arc_adjust_lock);
4204*de753e34SBrad Lewis 	arc_adjust_needed = !zthr_iscancelled(arc_adjust_zthr) &&
4205*de753e34SBrad Lewis 	    evicted > 0 && aggsum_compare(&arc_size, arc_c) > 0;
4206*de753e34SBrad Lewis 	if (!arc_adjust_needed) {
4207dcbf3bd6SGeorge Wilson 		/*
4208*de753e34SBrad Lewis 		 * We're either no longer overflowing, or we
4209*de753e34SBrad Lewis 		 * can't evict anything more, so we should wake
4210*de753e34SBrad Lewis 		 * up any waiters.
4211dcbf3bd6SGeorge Wilson 		 */
4212*de753e34SBrad Lewis 		cv_broadcast(&arc_adjust_waiters_cv);
4213*de753e34SBrad Lewis 	}
4214*de753e34SBrad Lewis 	mutex_exit(&arc_adjust_lock);
4215dcbf3bd6SGeorge Wilson 
4216*de753e34SBrad Lewis 	return (0);
4217*de753e34SBrad Lewis }
4218244781f1SPrakash Surya 
4219*de753e34SBrad Lewis /* ARGSUSED */
4220*de753e34SBrad Lewis static boolean_t
4221*de753e34SBrad Lewis arc_reap_cb_check(void *arg, zthr_t *zthr)
4222*de753e34SBrad Lewis {
4223*de753e34SBrad Lewis 	int64_t free_memory = arc_available_memory();
4224*de753e34SBrad Lewis 
4225*de753e34SBrad Lewis 	/*
4226*de753e34SBrad Lewis 	 * If a kmem reap is already active, don't schedule more.  We must
4227*de753e34SBrad Lewis 	 * check for this because kmem_cache_reap_soon() won't actually
4228*de753e34SBrad Lewis 	 * block on the cache being reaped (this is to prevent callers from
4229*de753e34SBrad Lewis 	 * becoming implicitly blocked by a system-wide kmem reap -- which,
4230*de753e34SBrad Lewis 	 * on a system with many, many full magazines, can take minutes).
4231*de753e34SBrad Lewis 	 */
4232*de753e34SBrad Lewis 	if (!kmem_cache_reap_active() &&
4233*de753e34SBrad Lewis 	    free_memory < 0) {
4234*de753e34SBrad Lewis 		arc_no_grow = B_TRUE;
4235*de753e34SBrad Lewis 		arc_warm = B_TRUE;
4236405a5a0fSMatthew Ahrens 		/*
4237*de753e34SBrad Lewis 		 * Wait at least zfs_grow_retry (default 60) seconds
4238*de753e34SBrad Lewis 		 * before considering growing.
4239405a5a0fSMatthew Ahrens 		 */
4240*de753e34SBrad Lewis 		arc_growtime = gethrtime() + SEC2NSEC(arc_grow_retry);
4241*de753e34SBrad Lewis 		return (B_TRUE);
4242*de753e34SBrad Lewis 	} else if (free_memory < arc_c >> arc_no_grow_shift) {
4243*de753e34SBrad Lewis 		arc_no_grow = B_TRUE;
4244*de753e34SBrad Lewis 	} else if (gethrtime() >= arc_growtime) {
4245*de753e34SBrad Lewis 		arc_no_grow = B_FALSE;
4246*de753e34SBrad Lewis 	}
4247405a5a0fSMatthew Ahrens 
4248*de753e34SBrad Lewis 	return (B_FALSE);
4249*de753e34SBrad Lewis }
4250fa9e4066Sahrens 
4251*de753e34SBrad Lewis /*
4252*de753e34SBrad Lewis  * Keep enough free memory in the system by reaping the ARC's kmem
4253*de753e34SBrad Lewis  * caches.  To cause more slabs to be reapable, we may reduce the
4254*de753e34SBrad Lewis  * target size of the cache (arc_c), causing the arc_adjust_cb()
4255*de753e34SBrad Lewis  * to free more buffers.
4256*de753e34SBrad Lewis  */
4257*de753e34SBrad Lewis /* ARGSUSED */
4258*de753e34SBrad Lewis static int
4259*de753e34SBrad Lewis arc_reap_cb(void *arg, zthr_t *zthr)
4260*de753e34SBrad Lewis {
4261*de753e34SBrad Lewis 	int64_t free_memory;
4262fa9e4066Sahrens 
4263*de753e34SBrad Lewis 	/*
4264*de753e34SBrad Lewis 	 * Kick off asynchronous kmem_reap()'s of all our caches.
4265*de753e34SBrad Lewis 	 */
4266*de753e34SBrad Lewis 	arc_kmem_reap_soon();
4267fa9e4066Sahrens 
4268*de753e34SBrad Lewis 	/*
4269*de753e34SBrad Lewis 	 * Wait at least arc_kmem_cache_reap_retry_ms between
4270*de753e34SBrad Lewis 	 * arc_kmem_reap_soon() calls. Without this check it is possible to
4271*de753e34SBrad Lewis 	 * end up in a situation where we spend lots of time reaping
4272*de753e34SBrad Lewis 	 * caches, while we're near arc_c_min.  Waiting here also gives the
4273*de753e34SBrad Lewis 	 * subsequent free memory check a chance of finding that the
4274*de753e34SBrad Lewis 	 * asynchronous reap has already freed enough memory, and we don't
4275*de753e34SBrad Lewis 	 * need to call arc_reduce_target_size().
4276*de753e34SBrad Lewis 	 */
4277*de753e34SBrad Lewis 	delay((hz * arc_kmem_cache_reap_retry_ms + 999) / 1000);
4278*de753e34SBrad Lewis 
4279*de753e34SBrad Lewis 	/*
4280*de753e34SBrad Lewis 	 * Reduce the target size as needed to maintain the amount of free
4281*de753e34SBrad Lewis 	 * memory in the system at a fraction of the arc_size (1/128th by
4282*de753e34SBrad Lewis 	 * default).  If oversubscribed (free_memory < 0) then reduce the
4283*de753e34SBrad Lewis 	 * target arc_size by the deficit amount plus the fractional
4284*de753e34SBrad Lewis 	 * amount.  If free memory is positive but less then the fractional
4285*de753e34SBrad Lewis 	 * amount, reduce by what is needed to hit the fractional amount.
4286*de753e34SBrad Lewis 	 */
4287*de753e34SBrad Lewis 	free_memory = arc_available_memory();
42882ec99e3eSMatthew Ahrens 
4289*de753e34SBrad Lewis 	int64_t to_free =
4290*de753e34SBrad Lewis 	    (arc_c >> arc_shrink_shift) - free_memory;
4291*de753e34SBrad Lewis 	if (to_free > 0) {
42922ec99e3eSMatthew Ahrens #ifdef _KERNEL
4293*de753e34SBrad Lewis 		to_free = MAX(to_free, ptob(needfree));
42942ec99e3eSMatthew Ahrens #endif
4295*de753e34SBrad Lewis 		arc_reduce_target_size(to_free);
4296244781f1SPrakash Surya 	}
4297244781f1SPrakash Surya 
4298*de753e34SBrad Lewis 	return (0);
4299244781f1SPrakash Surya }
4300244781f1SPrakash Surya 
4301ea8dc4b6Seschrock /*
4302ea8dc4b6Seschrock  * Adapt arc info given the number of bytes we are trying to add and
4303ea8dc4b6Seschrock  * the state that we are comming from.  This function is only called
4304ea8dc4b6Seschrock  * when we are adding new content to the cache.
4305ea8dc4b6Seschrock  */
4306fa9e4066Sahrens static void
4307ea8dc4b6Seschrock arc_adapt(int bytes, arc_state_t *state)
4308fa9e4066Sahrens {
4309ea8dc4b6Seschrock 	int mult;
43105a98e54bSBrendan Gregg - Sun Microsystems 	uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
43112fd872a7SPrakash Surya 	int64_t mrug_size = refcount_count(&arc_mru_ghost->arcs_size);
43122fd872a7SPrakash Surya 	int64_t mfug_size = refcount_count(&arc_mfu_ghost->arcs_size);
4313ea8dc4b6Seschrock 
4314fa94a07fSbrendan 	if (state == arc_l2c_only)
4315fa94a07fSbrendan 		return;
4316fa94a07fSbrendan 
4317ea8dc4b6Seschrock 	ASSERT(bytes > 0);
4318fa9e4066Sahrens 	/*
4319ea8dc4b6Seschrock 	 * Adapt the target size of the MRU list:
4320ea8dc4b6Seschrock 	 *	- if we just hit in the MRU ghost list, then increase
4321ea8dc4b6Seschrock 	 *	  the target size of the MRU list.
4322ea8dc4b6Seschrock 	 *	- if we just hit in the MFU ghost list, then increase
4323ea8dc4b6Seschrock 	 *	  the target size of the MFU list by decreasing the
4324ea8dc4b6Seschrock 	 *	  target size of the MRU list.
4325fa9e4066Sahrens 	 */
432644cb6abcSbmc 	if (state == arc_mru_ghost) {
43272fd872a7SPrakash Surya 		mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
43283e4e8481STom Erickson 		mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
4329ea8dc4b6Seschrock 
43305a98e54bSBrendan Gregg - Sun Microsystems 		arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
433144cb6abcSbmc 	} else if (state == arc_mfu_ghost) {
43325a98e54bSBrendan Gregg - Sun Microsystems 		uint64_t delta;
43335a98e54bSBrendan Gregg - Sun Microsystems 
43342fd872a7SPrakash Surya 		mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
43353e4e8481STom Erickson 		mult = MIN(mult, 10);
4336ea8dc4b6Seschrock 
43375a98e54bSBrendan Gregg - Sun Microsystems 		delta = MIN(bytes * mult, arc_p);
43385a98e54bSBrendan Gregg - Sun Microsystems 		arc_p = MAX(arc_p_min, arc_p - delta);
4339ea8dc4b6Seschrock 	}
434044cb6abcSbmc 	ASSERT((int64_t)arc_p >= 0);
4341fa9e4066Sahrens 
4342*de753e34SBrad Lewis 	/*
4343*de753e34SBrad Lewis 	 * Wake reap thread if we do not have any available memory
4344*de753e34SBrad Lewis 	 */
4345fa9e4066Sahrens 	if (arc_reclaim_needed()) {
4346*de753e34SBrad Lewis 		zthr_wakeup(arc_reap_zthr);
4347fa9e4066Sahrens 		return;
4348fa9e4066Sahrens 	}
4349fa9e4066Sahrens 
4350*de753e34SBrad Lewis 
435144cb6abcSbmc 	if (arc_no_grow)
4352fa9e4066Sahrens 		return;
4353fa9e4066Sahrens 
435444cb6abcSbmc 	if (arc_c >= arc_c_max)
4355ea8dc4b6Seschrock 		return;
4356ea8dc4b6Seschrock 
4357fa9e4066Sahrens 	/*
4358ea8dc4b6Seschrock 	 * If we're within (2 * maxblocksize) bytes of the target
4359ea8dc4b6Seschrock 	 * cache size, increment the target cache size
4360fa9e4066Sahrens 	 */
43613a2d8a1bSPaul Dagnelie 	if (aggsum_compare(&arc_size, arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) >
43623a2d8a1bSPaul Dagnelie 	    0) {
436344cb6abcSbmc 		atomic_add_64(&arc_c, (int64_t)bytes);
436444cb6abcSbmc 		if (arc_c > arc_c_max)
436544cb6abcSbmc 			arc_c = arc_c_max;
436644cb6abcSbmc 		else if (state == arc_anon)
436744cb6abcSbmc 			atomic_add_64(&arc_p, (int64_t)bytes);
436844cb6abcSbmc 		if (arc_p > arc_c)
436944cb6abcSbmc 			arc_p = arc_c;
4370fa9e4066Sahrens 	}
437144cb6abcSbmc 	ASSERT((int64_t)arc_p >= 0);
4372fa9e4066Sahrens }
4373fa9e4066Sahrens 
4374fa9e4066Sahrens /*
4375244781f1SPrakash Surya  * Check if arc_size has grown past our upper threshold, determined by
4376244781f1SPrakash Surya  * zfs_arc_overflow_shift.
4377fa9e4066Sahrens  */
4378244781f1SPrakash Surya static boolean_t
4379244781f1SPrakash Surya arc_is_overflowing(void)
4380fa9e4066Sahrens {
4381244781f1SPrakash Surya 	/* Always allow at least one block of overflow */
4382244781f1SPrakash Surya 	uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
4383244781f1SPrakash Surya 	    arc_c >> zfs_arc_overflow_shift);
4384fa9e4066Sahrens 
43853a2d8a1bSPaul Dagnelie 	/*
43863a2d8a1bSPaul Dagnelie 	 * We just compare the lower bound here for performance reasons. Our
43873a2d8a1bSPaul Dagnelie 	 * primary goals are to make sure that the arc never grows without
43883a2d8a1bSPaul Dagnelie 	 * bound, and that it can reach its maximum size. This check
43893a2d8a1bSPaul Dagnelie 	 * accomplishes both goals. The maximum amount we could run over by is
43903a2d8a1bSPaul Dagnelie 	 * 2 * aggsum_borrow_multiplier * NUM_CPUS * the average size of a block
43913a2d8a1bSPaul Dagnelie 	 * in the ARC. In practice, that's in the tens of MB, which is low
43923a2d8a1bSPaul Dagnelie 	 * enough to be safe.
43933a2d8a1bSPaul Dagnelie 	 */
43943a2d8a1bSPaul Dagnelie 	return (aggsum_lower_bound(&arc_size) >= arc_c + overflow);
4395fa9e4066Sahrens }
4396fa9e4066Sahrens 
4397770499e1SDan Kimmel static abd_t *
4398770499e1SDan Kimmel arc_get_data_abd(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4399770499e1SDan Kimmel {
4400770499e1SDan Kimmel 	arc_buf_contents_t type = arc_buf_type(hdr);
4401770499e1SDan Kimmel 
4402770499e1SDan Kimmel 	arc_get_data_impl(hdr, size, tag);
4403770499e1SDan Kimmel 	if (type == ARC_BUFC_METADATA) {
4404770499e1SDan Kimmel 		return (abd_alloc(size, B_TRUE));
4405770499e1SDan Kimmel 	} else {
4406770499e1SDan Kimmel 		ASSERT(type == ARC_BUFC_DATA);
4407770499e1SDan Kimmel 		return (abd_alloc(size, B_FALSE));
4408770499e1SDan Kimmel 	}
4409770499e1SDan Kimmel }
4410770499e1SDan Kimmel 
4411770499e1SDan Kimmel static void *
4412770499e1SDan Kimmel arc_get_data_buf(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4413770499e1SDan Kimmel {
4414770499e1SDan Kimmel 	arc_buf_contents_t type = arc_buf_type(hdr);
4415770499e1SDan Kimmel 
4416770499e1SDan Kimmel 	arc_get_data_impl(hdr, size, tag);
4417770499e1SDan Kimmel 	if (type == ARC_BUFC_METADATA) {
4418770499e1SDan Kimmel 		return (zio_buf_alloc(size));
4419770499e1SDan Kimmel 	} else {
4420770499e1SDan Kimmel 		ASSERT(type == ARC_BUFC_DATA);
4421770499e1SDan Kimmel 		return (zio_data_buf_alloc(size));
4422770499e1SDan Kimmel 	}
4423770499e1SDan Kimmel }
4424770499e1SDan Kimmel 
4425fa9e4066Sahrens /*
4426dcbf3bd6SGeorge Wilson  * Allocate a block and return it to the caller. If we are hitting the
4427dcbf3bd6SGeorge Wilson  * hard limit for the cache size, we must sleep, waiting for the eviction
4428dcbf3bd6SGeorge Wilson  * thread to catch up. If we're past the target size but below the hard
4429dcbf3bd6SGeorge Wilson  * limit, we'll only signal the reclaim thread and continue on.
4430fa9e4066Sahrens  */
4431770499e1SDan Kimmel static void
4432770499e1SDan Kimmel arc_get_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4433fa9e4066Sahrens {
4434770499e1SDan Kimmel 	arc_state_t *state = hdr->b_l1hdr.b_state;
4435770499e1SDan Kimmel 	arc_buf_contents_t type = arc_buf_type(hdr);
4436fa9e4066Sahrens 
443744eda4d7Smaybee 	arc_adapt(size, state);
4438fa9e4066Sahrens 
443944eda4d7Smaybee 	/*
4440244781f1SPrakash Surya 	 * If arc_size is currently overflowing, and has grown past our
4441244781f1SPrakash Surya 	 * upper limit, we must be adding data faster than the evict
4442244781f1SPrakash Surya 	 * thread can evict. Thus, to ensure we don't compound the
4443244781f1SPrakash Surya 	 * problem by adding more data and forcing arc_size to grow even
4444244781f1SPrakash Surya 	 * further past it's target size, we halt and wait for the
4445244781f1SPrakash Surya 	 * eviction thread to catch up.
4446244781f1SPrakash Surya 	 *
4447244781f1SPrakash Surya 	 * It's also possible that the reclaim thread is unable to evict
4448244781f1SPrakash Surya 	 * enough buffers to get arc_size below the overflow limit (e.g.
4449244781f1SPrakash Surya 	 * due to buffers being un-evictable, or hash lock collisions).
4450244781f1SPrakash Surya 	 * In this case, we want to proceed regardless if we're
4451244781f1SPrakash Surya 	 * overflowing; thus we don't use a while loop here.
445244eda4d7Smaybee 	 */
4453244781f1SPrakash Surya 	if (arc_is_overflowing()) {
4454*de753e34SBrad Lewis 		mutex_enter(&arc_adjust_lock);
4455244781f1SPrakash Surya 
4456244781f1SPrakash Surya 		/*
4457244781f1SPrakash Surya 		 * Now that we've acquired the lock, we may no longer be
4458244781f1SPrakash Surya 		 * over the overflow limit, lets check.
4459244781f1SPrakash Surya 		 *
4460244781f1SPrakash Surya 		 * We're ignoring the case of spurious wake ups. If that
4461244781f1SPrakash Surya 		 * were to happen, it'd let this thread consume an ARC
4462244781f1SPrakash Surya 		 * buffer before it should have (i.e. before we're under
4463244781f1SPrakash Surya 		 * the overflow limit and were signalled by the reclaim
4464244781f1SPrakash Surya 		 * thread). As long as that is a rare occurrence, it
4465244781f1SPrakash Surya 		 * shouldn't cause any harm.
4466244781f1SPrakash Surya 		 */
4467244781f1SPrakash Surya 		if (arc_is_overflowing()) {
4468*de753e34SBrad Lewis 			arc_adjust_needed = B_TRUE;
4469*de753e34SBrad Lewis 			zthr_wakeup(arc_adjust_zthr);
4470*de753e34SBrad Lewis 			(void) cv_wait(&arc_adjust_waiters_cv,
4471*de753e34SBrad Lewis 			    &arc_adjust_lock);
4472ad23a2dbSjohansen 		}
4473*de753e34SBrad Lewis 		mutex_exit(&arc_adjust_lock);
447444eda4d7Smaybee 	}
447544eda4d7Smaybee 
4476dcbf3bd6SGeorge Wilson 	VERIFY3U(hdr->b_type, ==, type);
4477244781f1SPrakash Surya 	if (type == ARC_BUFC_METADATA) {
4478244781f1SPrakash Surya 		arc_space_consume(size, ARC_SPACE_META);
4479fa9e4066Sahrens 	} else {
4480244781f1SPrakash Surya 		arc_space_consume(size, ARC_SPACE_DATA);
448144eda4d7Smaybee 	}
4482244781f1SPrakash Surya 
448344eda4d7Smaybee 	/*
448444eda4d7Smaybee 	 * Update the state size.  Note that ghost states have a
448544eda4d7Smaybee 	 * "ghost size" and so don't need to be updated.
448644eda4d7Smaybee 	 */
4487dcbf3bd6SGeorge Wilson 	if (!GHOST_STATE(state)) {
448844eda4d7Smaybee 
4489dcbf3bd6SGeorge Wilson 		(void) refcount_add_many(&state->arcs_size, size, tag);
4490244781f1SPrakash Surya 
4491244781f1SPrakash Surya 		/*
4492244781f1SPrakash Surya 		 * If this is reached via arc_read, the link is
4493244781f1SPrakash Surya 		 * protected by the hash lock. If reached via
4494244781f1SPrakash Surya 		 * arc_buf_alloc, the header should not be accessed by
4495244781f1SPrakash Surya 		 * any other thread. And, if reached via arc_read_done,
4496244781f1SPrakash Surya 		 * the hash lock will protect it if it's found in the
4497244781f1SPrakash Surya 		 * hash table; otherwise no other thread should be
4498244781f1SPrakash Surya 		 * trying to [add|remove]_reference it.
4499244781f1SPrakash Surya 		 */
4500244781f1SPrakash Surya 		if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
450189c86e32SChris Williamson 			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4502dcbf3bd6SGeorge Wilson 			(void) refcount_add_many(&state->arcs_esize[type],
4503dcbf3bd6SGeorge Wilson 			    size, tag);
4504fa9e4066Sahrens 		}
4505dcbf3bd6SGeorge Wilson 
4506641fbdaeSmaybee 		/*
4507641fbdaeSmaybee 		 * If we are growing the cache, and we are adding anonymous
450844cb6abcSbmc 		 * data, and we have outgrown arc_p, update arc_p
4509641fbdaeSmaybee 		 */
45103a2d8a1bSPaul Dagnelie 		if (aggsum_compare(&arc_size, arc_c) < 0 &&
45113a2d8a1bSPaul Dagnelie 		    hdr->b_l1hdr.b_state == arc_anon &&
45122fd872a7SPrakash Surya 		    (refcount_count(&arc_anon->arcs_size) +
45132fd872a7SPrakash Surya 		    refcount_count(&arc_mru->arcs_size) > arc_p))
451444cb6abcSbmc 			arc_p = MIN(arc_c, arc_p + size);
4515fa9e4066Sahrens 	}
4516770499e1SDan Kimmel }
4517770499e1SDan Kimmel 
4518770499e1SDan Kimmel static void
4519770499e1SDan Kimmel arc_free_data_abd(arc_buf_hdr_t *hdr, abd_t *abd, uint64_t size, void *tag)
4520770499e1SDan Kimmel {
4521770499e1SDan Kimmel 	arc_free_data_impl(hdr, size, tag);
4522770499e1SDan Kimmel 	abd_free(abd);
4523770499e1SDan Kimmel }
4524770499e1SDan Kimmel 
4525770499e1SDan Kimmel static void
4526770499e1SDan Kimmel arc_free_data_buf(arc_buf_hdr_t *hdr, void *buf, uint64_t size, void *tag)
4527770499e1SDan Kimmel {
4528770499e1SDan Kimmel 	arc_buf_contents_t type = arc_buf_type(hdr);
4529770499e1SDan Kimmel 
4530770499e1SDan Kimmel 	arc_free_data_impl(hdr, size, tag);
4531770499e1SDan Kimmel 	if (type == ARC_BUFC_METADATA) {
4532770499e1SDan Kimmel 		zio_buf_free(buf, size);
4533770499e1SDan Kimmel 	} else {
4534770499e1SDan Kimmel 		ASSERT(type == ARC_BUFC_DATA);
4535770499e1SDan Kimmel 		zio_data_buf_free(buf, size);
4536770499e1SDan Kimmel 	}
4537dcbf3bd6SGeorge Wilson }
4538dcbf3bd6SGeorge Wilson 
4539dcbf3bd6SGeorge Wilson /*
4540dcbf3bd6SGeorge Wilson  * Free the arc data buffer.
4541dcbf3bd6SGeorge Wilson  */
4542dcbf3bd6SGeorge Wilson static void
4543770499e1SDan Kimmel arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4544dcbf3bd6SGeorge Wilson {
4545dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
4546dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type = arc_buf_type(hdr);
4547dcbf3bd6SGeorge Wilson 
4548dcbf3bd6SGeorge Wilson 	/* protected by hash lock, if in the hash table */
4549dcbf3bd6SGeorge Wilson 	if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
4550dcbf3bd6SGeorge Wilson 		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4551dcbf3bd6SGeorge Wilson 		ASSERT(state != arc_anon && state != arc_l2c_only);
4552dcbf3bd6SGeorge Wilson 
4553dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_esize[type],
4554dcbf3bd6SGeorge Wilson 		    size, tag);
4555dcbf3bd6SGeorge Wilson 	}
4556dcbf3bd6SGeorge Wilson 	(void) refcount_remove_many(&state->arcs_size, size, tag);
4557dcbf3bd6SGeorge Wilson 
4558dcbf3bd6SGeorge Wilson 	VERIFY3U(hdr->b_type, ==, type);
4559dcbf3bd6SGeorge Wilson 	if (type == ARC_BUFC_METADATA) {
4560dcbf3bd6SGeorge Wilson 		arc_space_return(size, ARC_SPACE_META);
4561dcbf3bd6SGeorge Wilson 	} else {
4562dcbf3bd6SGeorge Wilson 		ASSERT(type == ARC_BUFC_DATA);
4563dcbf3bd6SGeorge Wilson 		arc_space_return(size, ARC_SPACE_DATA);
4564dcbf3bd6SGeorge Wilson 	}
4565fa9e4066Sahrens }
4566fa9e4066Sahrens 
4567fa9e4066Sahrens /*
4568fa9e4066Sahrens  * This routine is called whenever a buffer is accessed.
4569ea8dc4b6Seschrock  * NOTE: the hash lock is dropped in this function.
4570fa9e4066Sahrens  */
4571fa9e4066Sahrens static void
45727adb730bSGeorge Wilson arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
4573fa9e4066Sahrens {
4574d3d50737SRafael Vanoni 	clock_t now;
4575d3d50737SRafael Vanoni 
4576fa9e4066Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
457789c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
4578fa9e4066Sahrens 
457989c86e32SChris Williamson 	if (hdr->b_l1hdr.b_state == arc_anon) {
4580fa9e4066Sahrens 		/*
4581fa9e4066Sahrens 		 * This buffer is not in the cache, and does not
4582fa9e4066Sahrens 		 * appear in our "ghost" list.  Add the new buffer
4583fa9e4066Sahrens 		 * to the MRU state.
4584fa9e4066Sahrens 		 */
4585fa9e4066Sahrens 
458689c86e32SChris Williamson 		ASSERT0(hdr->b_l1hdr.b_arc_access);
458789c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
45887adb730bSGeorge Wilson 		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
45897adb730bSGeorge Wilson 		arc_change_state(arc_mru, hdr, hash_lock);
4590fa9e4066Sahrens 
459189c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mru) {
4592d3d50737SRafael Vanoni 		now = ddi_get_lbolt();
4593d3d50737SRafael Vanoni 
4594fa9e4066Sahrens 		/*
459513506d1eSmaybee 		 * If this buffer is here because of a prefetch, then either:
459613506d1eSmaybee 		 * - clear the flag if this is a "referencing" read
459713506d1eSmaybee 		 *   (any subsequent access will bump this into the MFU state).
459813506d1eSmaybee 		 * or
459913506d1eSmaybee 		 * - move the buffer to the head of the list if this is
460013506d1eSmaybee 		 *   another prefetch (to make it less likely to be evicted).
4601fa9e4066Sahrens 		 */
460289c86e32SChris Williamson 		if (HDR_PREFETCH(hdr)) {
460389c86e32SChris Williamson 			if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4604244781f1SPrakash Surya 				/* link protected by hash lock */
4605244781f1SPrakash Surya 				ASSERT(multilist_link_active(
460689c86e32SChris Williamson 				    &hdr->b_l1hdr.b_arc_node));
460713506d1eSmaybee 			} else {
4608dcbf3bd6SGeorge Wilson 				arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
460944cb6abcSbmc 				ARCSTAT_BUMP(arcstat_mru_hits);
461013506d1eSmaybee 			}
461189c86e32SChris Williamson 			hdr->b_l1hdr.b_arc_access = now;
4612fa9e4066Sahrens 			return;
4613fa9e4066Sahrens 		}
4614fa9e4066Sahrens 
4615fa9e4066Sahrens 		/*
4616fa9e4066Sahrens 		 * This buffer has been "accessed" only once so far,
4617fa9e4066Sahrens 		 * but it is still in the cache. Move it to the MFU
4618fa9e4066Sahrens 		 * state.
4619fa9e4066Sahrens 		 */
462089c86e32SChris Williamson 		if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
4621fa9e4066Sahrens 			/*
4622fa9e4066Sahrens 			 * More than 125ms have passed since we
4623fa9e4066Sahrens 			 * instantiated this buffer.  Move it to the
4624fa9e4066Sahrens 			 * most frequently used state.
4625fa9e4066Sahrens 			 */
462689c86e32SChris Williamson 			hdr->b_l1hdr.b_arc_access = now;
46277adb730bSGeorge Wilson 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
46287adb730bSGeorge Wilson 			arc_change_state(arc_mfu, hdr, hash_lock);
4629fa9e4066Sahrens 		}
463044cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mru_hits);
463189c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
4632fa9e4066Sahrens 		arc_state_t	*new_state;
4633fa9e4066Sahrens 		/*
4634fa9e4066Sahrens 		 * This buffer has been "accessed" recently, but
4635fa9e4066Sahrens 		 * was evicted from the cache.  Move it to the
4636fa9e4066Sahrens 		 * MFU state.
4637fa9e4066Sahrens 		 */
4638fa9e4066Sahrens 
463989c86e32SChris Williamson 		if (HDR_PREFETCH(hdr)) {
464044cb6abcSbmc 			new_state = arc_mru;
464189c86e32SChris Williamson 			if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0)
4642dcbf3bd6SGeorge Wilson 				arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
46437adb730bSGeorge Wilson 			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
4644fa9e4066Sahrens 		} else {
464544cb6abcSbmc 			new_state = arc_mfu;
46467adb730bSGeorge Wilson 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4647fa9e4066Sahrens 		}
4648fa9e4066Sahrens 
464989c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
46507adb730bSGeorge Wilson 		arc_change_state(new_state, hdr, hash_lock);
4651fa9e4066Sahrens 
465244cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
465389c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mfu) {
4654fa9e4066Sahrens 		/*
4655fa9e4066Sahrens 		 * This buffer has been accessed more than once and is
4656fa9e4066Sahrens 		 * still in the cache.  Keep it in the MFU state.
4657fa9e4066Sahrens 		 *
465813506d1eSmaybee 		 * NOTE: an add_reference() that occurred when we did
465913506d1eSmaybee 		 * the arc_read() will have kicked this off the list.
466013506d1eSmaybee 		 * If it was a prefetch, we will explicitly move it to
466113506d1eSmaybee 		 * the head of the list now.
4662fa9e4066Sahrens 		 */
466389c86e32SChris Williamson 		if ((HDR_PREFETCH(hdr)) != 0) {
466489c86e32SChris Williamson 			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4665244781f1SPrakash Surya 			/* link protected by hash_lock */
4666244781f1SPrakash Surya 			ASSERT(multilist_link_active(&hdr->b_l1hdr.b_arc_node));
466713506d1eSmaybee 		}
466844cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mfu_hits);
466989c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
467089c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
467144cb6abcSbmc 		arc_state_t	*new_state = arc_mfu;
4672fa9e4066Sahrens 		/*
4673fa9e4066Sahrens 		 * This buffer has been accessed more than once but has
4674fa9e4066Sahrens 		 * been evicted from the cache.  Move it back to the
4675fa9e4066Sahrens 		 * MFU state.
4676fa9e4066Sahrens 		 */
4677fa9e4066Sahrens 
467889c86e32SChris Williamson 		if (HDR_PREFETCH(hdr)) {
467913506d1eSmaybee 			/*
468013506d1eSmaybee 			 * This is a prefetch access...
468113506d1eSmaybee 			 * move this block back to the MRU state.
468213506d1eSmaybee 			 */
468389c86e32SChris Williamson 			ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
468444cb6abcSbmc 			new_state = arc_mru;
468513506d1eSmaybee 		}
468613506d1eSmaybee 
468789c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
46887adb730bSGeorge Wilson 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
46897adb730bSGeorge Wilson 		arc_change_state(new_state, hdr, hash_lock);
4690fa9e4066Sahrens 
469144cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
469289c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
4693fa94a07fSbrendan 		/*
4694fa94a07fSbrendan 		 * This buffer is on the 2nd Level ARC.
4695fa94a07fSbrendan 		 */
4696fa94a07fSbrendan 
469789c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
46987adb730bSGeorge Wilson 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
46997adb730bSGeorge Wilson 		arc_change_state(arc_mfu, hdr, hash_lock);
4700fa9e4066Sahrens 	} else {
4701fa9e4066Sahrens 		ASSERT(!"invalid arc state");
4702fa9e4066Sahrens 	}
4703fa9e4066Sahrens }
4704fa9e4066Sahrens 
4705fa9e4066Sahrens /* a generic arc_done_func_t which you can use */
4706fa9e4066Sahrens /* ARGSUSED */
4707fa9e4066Sahrens void
4708fa9e4066Sahrens arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
4709fa9e4066Sahrens {
47103f9d6ad7SLin Ling 	if (zio == NULL || zio->io_error == 0)
47115602294fSDan Kimmel 		bcopy(buf->b_data, arg, arc_buf_size(buf));
4712dcbf3bd6SGeorge Wilson 	arc_buf_destroy(buf, arg);
4713fa9e4066Sahrens }
4714fa9e4066Sahrens 
47150e8c6158Smaybee /* a generic arc_done_func_t */
4716fa9e4066Sahrens void
4717fa9e4066Sahrens arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
4718fa9e4066Sahrens {
4719fa9e4066Sahrens 	arc_buf_t **bufp = arg;
4720fa9e4066Sahrens 	if (zio && zio->io_error) {
4721dcbf3bd6SGeorge Wilson 		arc_buf_destroy(buf, arg);
4722fa9e4066Sahrens 		*bufp = NULL;
4723fa9e4066Sahrens 	} else {
4724fa9e4066Sahrens 		*bufp = buf;
47253f9d6ad7SLin Ling 		ASSERT(buf->b_data);
4726fa9e4066Sahrens 	}
4727fa9e4066Sahrens }
4728fa9e4066Sahrens 
4729dcbf3bd6SGeorge Wilson static void
4730dcbf3bd6SGeorge Wilson arc_hdr_verify(arc_buf_hdr_t *hdr, blkptr_t *bp)
4731dcbf3bd6SGeorge Wilson {
4732dcbf3bd6SGeorge Wilson 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
4733dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_PSIZE(hdr), ==, 0);
4734dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
4735dcbf3bd6SGeorge Wilson 	} else {
4736dcbf3bd6SGeorge Wilson 		if (HDR_COMPRESSION_ENABLED(hdr)) {
4737dcbf3bd6SGeorge Wilson 			ASSERT3U(HDR_GET_COMPRESS(hdr), ==,
4738dcbf3bd6SGeorge Wilson 			    BP_GET_COMPRESS(bp));
4739dcbf3bd6SGeorge Wilson 		}
4740dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
4741dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_PSIZE(hdr), ==, BP_GET_PSIZE(bp));
4742dcbf3bd6SGeorge Wilson 	}
4743dcbf3bd6SGeorge Wilson }
4744dcbf3bd6SGeorge Wilson 
4745fa9e4066Sahrens static void
4746fa9e4066Sahrens arc_read_done(zio_t *zio)
4747fa9e4066Sahrens {
4748dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t	*hdr = zio->io_private;
47495d7b4d43SMatthew Ahrens 	kmutex_t	*hash_lock = NULL;
47505602294fSDan Kimmel 	arc_callback_t	*callback_list;
47515602294fSDan Kimmel 	arc_callback_t	*acb;
47525602294fSDan Kimmel 	boolean_t	freeable = B_FALSE;
47535602294fSDan Kimmel 	boolean_t	no_zio_error = (zio->io_error == 0);
4754fa9e4066Sahrens 
4755bbf4a8dfSmaybee 	/*
4756bbf4a8dfSmaybee 	 * The hdr was inserted into hash-table and removed from lists
4757bbf4a8dfSmaybee 	 * prior to starting I/O.  We should find this header, since
4758bbf4a8dfSmaybee 	 * it's in the hash table, and it should be legit since it's
4759bbf4a8dfSmaybee 	 * not possible to evict it during the I/O.  The only possible
4760bbf4a8dfSmaybee 	 * reason for it not to be found is if we were freed during the
4761bbf4a8dfSmaybee 	 * read.
4762bbf4a8dfSmaybee 	 */
47635d7b4d43SMatthew Ahrens 	if (HDR_IN_HASH_TABLE(hdr)) {
47645d7b4d43SMatthew Ahrens 		ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
47655d7b4d43SMatthew Ahrens 		ASSERT3U(hdr->b_dva.dva_word[0], ==,
47665d7b4d43SMatthew Ahrens 		    BP_IDENTITY(zio->io_bp)->dva_word[0]);
47675d7b4d43SMatthew Ahrens 		ASSERT3U(hdr->b_dva.dva_word[1], ==,
47685d7b4d43SMatthew Ahrens 		    BP_IDENTITY(zio->io_bp)->dva_word[1]);
47695d7b4d43SMatthew Ahrens 
47705d7b4d43SMatthew Ahrens 		arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
47715d7b4d43SMatthew Ahrens 		    &hash_lock);
47725d7b4d43SMatthew Ahrens 
4773dcbf3bd6SGeorge Wilson 		ASSERT((found == hdr &&
47745d7b4d43SMatthew Ahrens 		    DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
47755d7b4d43SMatthew Ahrens 		    (found == hdr && HDR_L2_READING(hdr)));
4776dcbf3bd6SGeorge Wilson 		ASSERT3P(hash_lock, !=, NULL);
4777dcbf3bd6SGeorge Wilson 	}
4778dcbf3bd6SGeorge Wilson 
47795602294fSDan Kimmel 	if (no_zio_error) {
4780dcbf3bd6SGeorge Wilson 		/* byteswap if necessary */
4781dcbf3bd6SGeorge Wilson 		if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
4782dcbf3bd6SGeorge Wilson 			if (BP_GET_LEVEL(zio->io_bp) > 0) {
4783dcbf3bd6SGeorge Wilson 				hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
4784dcbf3bd6SGeorge Wilson 			} else {
4785dcbf3bd6SGeorge Wilson 				hdr->b_l1hdr.b_byteswap =
4786dcbf3bd6SGeorge Wilson 				    DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
4787dcbf3bd6SGeorge Wilson 			}
4788dcbf3bd6SGeorge Wilson 		} else {
4789dcbf3bd6SGeorge Wilson 			hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
4790dcbf3bd6SGeorge Wilson 		}
47915d7b4d43SMatthew Ahrens 	}
4792fa94a07fSbrendan 
4793dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_L2_EVICTED);
479489c86e32SChris Williamson 	if (l2arc_noprefetch && HDR_PREFETCH(hdr))
4795dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_L2CACHE);
4796fa9e4066Sahrens 
479789c86e32SChris Williamson 	callback_list = hdr->b_l1hdr.b_acb;
4798dcbf3bd6SGeorge Wilson 	ASSERT3P(callback_list, !=, NULL);
47996b4acc8bSahrens 
48005602294fSDan Kimmel 	if (hash_lock && no_zio_error && hdr->b_l1hdr.b_state == arc_anon) {
4801b24ab676SJeff Bonwick 		/*
4802b24ab676SJeff Bonwick 		 * Only call arc_access on anonymous buffers.  This is because
4803b24ab676SJeff Bonwick 		 * if we've issued an I/O for an evicted buffer, we've already
4804b24ab676SJeff Bonwick 		 * called arc_access (to prevent any simultaneous readers from
4805b24ab676SJeff Bonwick 		 * getting confused).
4806b24ab676SJeff Bonwick 		 */
4807b24ab676SJeff Bonwick 		arc_access(hdr, hash_lock);
4808b24ab676SJeff Bonwick 	}
4809b24ab676SJeff Bonwick 
48105602294fSDan Kimmel 	/*
48115602294fSDan Kimmel 	 * If a read request has a callback (i.e. acb_done is not NULL), then we
48125602294fSDan Kimmel 	 * make a buf containing the data according to the parameters which were
48135602294fSDan Kimmel 	 * passed in. The implementation of arc_buf_alloc_impl() ensures that we
48145602294fSDan Kimmel 	 * aren't needlessly decompressing the data multiple times.
48155602294fSDan Kimmel 	 */
48165602294fSDan Kimmel 	int callback_cnt = 0;
48175602294fSDan Kimmel 	for (acb = callback_list; acb != NULL; acb = acb->acb_next) {
48185602294fSDan Kimmel 		if (!acb->acb_done)
48195602294fSDan Kimmel 			continue;
48205602294fSDan Kimmel 
48215602294fSDan Kimmel 		/* This is a demand read since prefetches don't use callbacks */
48225602294fSDan Kimmel 		callback_cnt++;
48235602294fSDan Kimmel 
48245602294fSDan Kimmel 		int error = arc_buf_alloc_impl(hdr, acb->acb_private,
48255602294fSDan Kimmel 		    acb->acb_compressed, no_zio_error, &acb->acb_buf);
48265602294fSDan Kimmel 		if (no_zio_error) {
48275602294fSDan Kimmel 			zio->io_error = error;
4828fa9e4066Sahrens 		}
4829fa9e4066Sahrens 	}
483089c86e32SChris Williamson 	hdr->b_l1hdr.b_acb = NULL;
4831dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
48325602294fSDan Kimmel 	if (callback_cnt == 0) {
4833dcbf3bd6SGeorge Wilson 		ASSERT(HDR_PREFETCH(hdr));
4834dcbf3bd6SGeorge Wilson 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
4835770499e1SDan Kimmel 		ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
4836b24ab676SJeff Bonwick 	}
4837fa9e4066Sahrens 
483889c86e32SChris Williamson 	ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
483989c86e32SChris Williamson 	    callback_list != NULL);
4840fa9e4066Sahrens 
48415602294fSDan Kimmel 	if (no_zio_error) {
4842dcbf3bd6SGeorge Wilson 		arc_hdr_verify(hdr, zio->io_bp);
4843dcbf3bd6SGeorge Wilson 	} else {
4844dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
484589c86e32SChris Williamson 		if (hdr->b_l1hdr.b_state != arc_anon)
484644cb6abcSbmc 			arc_change_state(arc_anon, hdr, hash_lock);
4847ea8dc4b6Seschrock 		if (HDR_IN_HASH_TABLE(hdr))
4848ea8dc4b6Seschrock 			buf_hash_remove(hdr);
484989c86e32SChris Williamson 		freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4850fa9e4066Sahrens 	}
4851fa9e4066Sahrens 
4852ea8dc4b6Seschrock 	/*
485313506d1eSmaybee 	 * Broadcast before we drop the hash_lock to avoid the possibility
485413506d1eSmaybee 	 * that the hdr (and hence the cv) might be freed before we get to
485513506d1eSmaybee 	 * the cv_broadcast().
4856ea8dc4b6Seschrock 	 */
485789c86e32SChris Williamson 	cv_broadcast(&hdr->b_l1hdr.b_cv);
4858ea8dc4b6Seschrock 
485989c86e32SChris Williamson 	if (hash_lock != NULL) {
486044eda4d7Smaybee 		mutex_exit(hash_lock);
4861fa9e4066Sahrens 	} else {
4862fa9e4066Sahrens 		/*
4863fa9e4066Sahrens 		 * This block was freed while we waited for the read to
4864fa9e4066Sahrens 		 * complete.  It has been removed from the hash table and
4865fa9e4066Sahrens 		 * moved to the anonymous state (so that it won't show up
4866fa9e4066Sahrens 		 * in the cache).
4867fa9e4066Sahrens 		 */
486889c86e32SChris Williamson 		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
486989c86e32SChris Williamson 		freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4870fa9e4066Sahrens 	}
4871fa9e4066Sahrens 
4872fa9e4066Sahrens 	/* execute each callback and free its structure */
4873fa9e4066Sahrens 	while ((acb = callback_list) != NULL) {
4874fa9e4066Sahrens 		if (acb->acb_done)
4875fa9e4066Sahrens 			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
4876fa9e4066Sahrens 
4877fa9e4066Sahrens 		if (acb->acb_zio_dummy != NULL) {
4878fa9e4066Sahrens 			acb->acb_zio_dummy->io_error = zio->io_error;
4879fa9e4066Sahrens 			zio_nowait(acb->acb_zio_dummy);
4880fa9e4066Sahrens 		}
4881fa9e4066Sahrens 
4882fa9e4066Sahrens 		callback_list = acb->acb_next;
4883fa9e4066Sahrens 		kmem_free(acb, sizeof (arc_callback_t));
4884fa9e4066Sahrens 	}
4885fa9e4066Sahrens 
4886fa9e4066Sahrens 	if (freeable)
4887ea8dc4b6Seschrock 		arc_hdr_destroy(hdr);
4888fa9e4066Sahrens }
4889fa9e4066Sahrens 
4890fa9e4066Sahrens /*
4891fc98fea5SBart Coddens  * "Read" the block at the specified DVA (in bp) via the
4892fa9e4066Sahrens  * cache.  If the block is found in the cache, invoke the provided
4893fa9e4066Sahrens  * callback immediately and return.  Note that the `zio' parameter
4894fa9e4066Sahrens  * in the callback will be NULL in this case, since no IO was
4895fa9e4066Sahrens  * required.  If the block is not in the cache pass the read request
4896fa9e4066Sahrens  * on to the spa with a substitute callback function, so that the
4897fa9e4066Sahrens  * requested block will be added to the cache.
4898fa9e4066Sahrens  *
4899fa9e4066Sahrens  * If a read request arrives for a block that has a read in-progress,
4900fa9e4066Sahrens  * either wait for the in-progress read to complete (and return the
4901fa9e4066Sahrens  * results); or, if this is a read with a "done" func, add a record
4902fa9e4066Sahrens  * to the read to invoke the "done" func when the read completes,
4903fa9e4066Sahrens  * and return; or just return.
4904fa9e4066Sahrens  *
4905fa9e4066Sahrens  * arc_read_done() will invoke all the requested "done" functions
4906fa9e4066Sahrens  * for readers of this block.
4907fa9e4066Sahrens  */
4908fa9e4066Sahrens int
49091b912ec7SGeorge Wilson arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
49107adb730bSGeorge Wilson     void *private, zio_priority_t priority, int zio_flags,
49117adb730bSGeorge Wilson     arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
4912fa9e4066Sahrens {
49135d7b4d43SMatthew Ahrens 	arc_buf_hdr_t *hdr = NULL;
49145d7b4d43SMatthew Ahrens 	kmutex_t *hash_lock = NULL;
4915fa94a07fSbrendan 	zio_t *rzio;
4916e9103aaeSGarrett D'Amore 	uint64_t guid = spa_load_guid(spa);
49175602294fSDan Kimmel 	boolean_t compressed_read = (zio_flags & ZIO_FLAG_RAW) != 0;
4918fa9e4066Sahrens 
49195d7b4d43SMatthew Ahrens 	ASSERT(!BP_IS_EMBEDDED(bp) ||
49205d7b4d43SMatthew Ahrens 	    BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
49215d7b4d43SMatthew Ahrens 
4922fa9e4066Sahrens top:
49235d7b4d43SMatthew Ahrens 	if (!BP_IS_EMBEDDED(bp)) {
49245d7b4d43SMatthew Ahrens 		/*
49255d7b4d43SMatthew Ahrens 		 * Embedded BP's have no DVA and require no I/O to "read".
49265d7b4d43SMatthew Ahrens 		 * Create an anonymous arc buf to back it.
49275d7b4d43SMatthew Ahrens 		 */
49285d7b4d43SMatthew Ahrens 		hdr = buf_hash_find(guid, bp, &hash_lock);
49295d7b4d43SMatthew Ahrens 	}
49305d7b4d43SMatthew Ahrens 
4931770499e1SDan Kimmel 	if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_pabd != NULL) {
4932dcbf3bd6SGeorge Wilson 		arc_buf_t *buf = NULL;
49337adb730bSGeorge Wilson 		*arc_flags |= ARC_FLAG_CACHED;
493413506d1eSmaybee 
4935fa9e4066Sahrens 		if (HDR_IO_IN_PROGRESS(hdr)) {
493613506d1eSmaybee 
4937cf6106c8SMatthew Ahrens 			if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
4938cf6106c8SMatthew Ahrens 			    priority == ZIO_PRIORITY_SYNC_READ) {
4939cf6106c8SMatthew Ahrens 				/*
4940cf6106c8SMatthew Ahrens 				 * This sync read must wait for an
4941cf6106c8SMatthew Ahrens 				 * in-progress async read (e.g. a predictive
4942cf6106c8SMatthew Ahrens 				 * prefetch).  Async reads are queued
4943cf6106c8SMatthew Ahrens 				 * separately at the vdev_queue layer, so
4944cf6106c8SMatthew Ahrens 				 * this is a form of priority inversion.
4945cf6106c8SMatthew Ahrens 				 * Ideally, we would "inherit" the demand
4946cf6106c8SMatthew Ahrens 				 * i/o's priority by moving the i/o from
4947cf6106c8SMatthew Ahrens 				 * the async queue to the synchronous queue,
4948cf6106c8SMatthew Ahrens 				 * but there is currently no mechanism to do
4949cf6106c8SMatthew Ahrens 				 * so.  Track this so that we can evaluate
4950cf6106c8SMatthew Ahrens 				 * the magnitude of this potential performance
4951cf6106c8SMatthew Ahrens 				 * problem.
4952cf6106c8SMatthew Ahrens 				 *
4953cf6106c8SMatthew Ahrens 				 * Note that if the prefetch i/o is already
4954cf6106c8SMatthew Ahrens 				 * active (has been issued to the device),
4955cf6106c8SMatthew Ahrens 				 * the prefetch improved performance, because
4956cf6106c8SMatthew Ahrens 				 * we issued it sooner than we would have
4957cf6106c8SMatthew Ahrens 				 * without the prefetch.
4958cf6106c8SMatthew Ahrens 				 */
4959cf6106c8SMatthew Ahrens 				DTRACE_PROBE1(arc__sync__wait__for__async,
4960cf6106c8SMatthew Ahrens 				    arc_buf_hdr_t *, hdr);
4961cf6106c8SMatthew Ahrens 				ARCSTAT_BUMP(arcstat_sync_wait_for_async);
4962cf6106c8SMatthew Ahrens 			}
4963cf6106c8SMatthew Ahrens 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
4964dcbf3bd6SGeorge Wilson 				arc_hdr_clear_flags(hdr,
4965dcbf3bd6SGeorge Wilson 				    ARC_FLAG_PREDICTIVE_PREFETCH);
4966cf6106c8SMatthew Ahrens 			}
4967cf6106c8SMatthew Ahrens 
49687adb730bSGeorge Wilson 			if (*arc_flags & ARC_FLAG_WAIT) {
496989c86e32SChris Williamson 				cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
497013506d1eSmaybee 				mutex_exit(hash_lock);
497113506d1eSmaybee 				goto top;
497213506d1eSmaybee 			}
49737adb730bSGeorge Wilson 			ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
497413506d1eSmaybee 
497513506d1eSmaybee 			if (done) {
4976cf6106c8SMatthew Ahrens 				arc_callback_t *acb = NULL;
4977fa9e4066Sahrens 
4978fa9e4066Sahrens 				acb = kmem_zalloc(sizeof (arc_callback_t),
4979fa9e4066Sahrens 				    KM_SLEEP);
4980fa9e4066Sahrens 				acb->acb_done = done;
4981fa9e4066Sahrens 				acb->acb_private = private;
49825602294fSDan Kimmel 				acb->acb_compressed = compressed_read;
4983fa9e4066Sahrens 				if (pio != NULL)
4984fa9e4066Sahrens 					acb->acb_zio_dummy = zio_null(pio,
4985a3f829aeSBill Moore 					    spa, NULL, NULL, NULL, zio_flags);
4986fa9e4066Sahrens 
4987dcbf3bd6SGeorge Wilson 				ASSERT3P(acb->acb_done, !=, NULL);
498889c86e32SChris Williamson 				acb->acb_next = hdr->b_l1hdr.b_acb;
498989c86e32SChris Williamson 				hdr->b_l1hdr.b_acb = acb;
4990fa9e4066Sahrens 				mutex_exit(hash_lock);
4991fa9e4066Sahrens 				return (0);
4992fa9e4066Sahrens 			}
4993fa9e4066Sahrens 			mutex_exit(hash_lock);
4994fa9e4066Sahrens 			return (0);
4995fa9e4066Sahrens 		}
4996fa9e4066Sahrens 
499789c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
499889c86e32SChris Williamson 		    hdr->b_l1hdr.b_state == arc_mfu);
4999fa9e4066Sahrens 
5000ea8dc4b6Seschrock 		if (done) {
5001cf6106c8SMatthew Ahrens 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5002cf6106c8SMatthew Ahrens 				/*
5003cf6106c8SMatthew Ahrens 				 * This is a demand read which does not have to
5004cf6106c8SMatthew Ahrens 				 * wait for i/o because we did a predictive
5005cf6106c8SMatthew Ahrens 				 * prefetch i/o for it, which has completed.
5006cf6106c8SMatthew Ahrens 				 */
5007cf6106c8SMatthew Ahrens 				DTRACE_PROBE1(
5008cf6106c8SMatthew Ahrens 				    arc__demand__hit__predictive__prefetch,
5009cf6106c8SMatthew Ahrens 				    arc_buf_hdr_t *, hdr);
5010cf6106c8SMatthew Ahrens 				ARCSTAT_BUMP(
5011cf6106c8SMatthew Ahrens 				    arcstat_demand_hit_predictive_prefetch);
5012dcbf3bd6SGeorge Wilson 				arc_hdr_clear_flags(hdr,
5013dcbf3bd6SGeorge Wilson 				    ARC_FLAG_PREDICTIVE_PREFETCH);
5014cf6106c8SMatthew Ahrens 			}
5015dcbf3bd6SGeorge Wilson 			ASSERT(!BP_IS_EMBEDDED(bp) || !BP_IS_HOLE(bp));
5016dcbf3bd6SGeorge Wilson 
50175602294fSDan Kimmel 			/* Get a buf with the desired data in it. */
50185602294fSDan Kimmel 			VERIFY0(arc_buf_alloc_impl(hdr, private,
50195602294fSDan Kimmel 			    compressed_read, B_TRUE, &buf));
50207adb730bSGeorge Wilson 		} else if (*arc_flags & ARC_FLAG_PREFETCH &&
502189c86e32SChris Williamson 		    refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
5022dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5023fa9e4066Sahrens 		}
5024fa9e4066Sahrens 		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
502544eda4d7Smaybee 		arc_access(hdr, hash_lock);
50267adb730bSGeorge Wilson 		if (*arc_flags & ARC_FLAG_L2CACHE)
5027dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
502844eda4d7Smaybee 		mutex_exit(hash_lock);
502944cb6abcSbmc 		ARCSTAT_BUMP(arcstat_hits);
503089c86e32SChris Williamson 		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
503189c86e32SChris Williamson 		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
503244cb6abcSbmc 		    data, metadata, hits);
503344cb6abcSbmc 
5034fa9e4066Sahrens 		if (done)
5035fa9e4066Sahrens 			done(NULL, buf, private);
5036fa9e4066Sahrens 	} else {
5037dcbf3bd6SGeorge Wilson 		uint64_t lsize = BP_GET_LSIZE(bp);
5038dcbf3bd6SGeorge Wilson 		uint64_t psize = BP_GET_PSIZE(bp);
50395d7b4d43SMatthew Ahrens 		arc_callback_t *acb;
50403a737e0dSbrendan 		vdev_t *vd = NULL;
5041d5285caeSGeorge Wilson 		uint64_t addr = 0;
50425a98e54bSBrendan Gregg - Sun Microsystems 		boolean_t devw = B_FALSE;
5043dcbf3bd6SGeorge Wilson 		uint64_t size;
5044fa9e4066Sahrens 
5045fa9e4066Sahrens 		if (hdr == NULL) {
5046fa9e4066Sahrens 			/* this block is not in the cache */
50475d7b4d43SMatthew Ahrens 			arc_buf_hdr_t *exists = NULL;
5048ad23a2dbSjohansen 			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
5049dcbf3bd6SGeorge Wilson 			hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
5050dcbf3bd6SGeorge Wilson 			    BP_GET_COMPRESS(bp), type);
5051dcbf3bd6SGeorge Wilson 
50525d7b4d43SMatthew Ahrens 			if (!BP_IS_EMBEDDED(bp)) {
50535d7b4d43SMatthew Ahrens 				hdr->b_dva = *BP_IDENTITY(bp);
50545d7b4d43SMatthew Ahrens 				hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
50555d7b4d43SMatthew Ahrens 				exists = buf_hash_insert(hdr, &hash_lock);
50565d7b4d43SMatthew Ahrens 			}
50575d7b4d43SMatthew Ahrens 			if (exists != NULL) {
5058fa9e4066Sahrens 				/* somebody beat us to the hash insert */
5059fa9e4066Sahrens 				mutex_exit(hash_lock);
50603f9d6ad7SLin Ling 				buf_discard_identity(hdr);
5061dcbf3bd6SGeorge Wilson 				arc_hdr_destroy(hdr);
5062fa9e4066Sahrens 				goto top; /* restart the IO request */
5063fa9e4066Sahrens 			}
5064fa9e4066Sahrens 		} else {
506589c86e32SChris Williamson 			/*
506689c86e32SChris Williamson 			 * This block is in the ghost cache. If it was L2-only
506789c86e32SChris Williamson 			 * (and thus didn't have an L1 hdr), we realloc the
506889c86e32SChris Williamson 			 * header to add an L1 hdr.
506989c86e32SChris Williamson 			 */
507089c86e32SChris Williamson 			if (!HDR_HAS_L1HDR(hdr)) {
507189c86e32SChris Williamson 				hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
507289c86e32SChris Williamson 				    hdr_full_cache);
507389c86e32SChris Williamson 			}
5074770499e1SDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
507589c86e32SChris Williamson 			ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
5076ea8dc4b6Seschrock 			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
507789c86e32SChris Williamson 			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5078244781f1SPrakash Surya 			ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
50795602294fSDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
508013506d1eSmaybee 
5081cf6106c8SMatthew Ahrens 			/*
5082dcbf3bd6SGeorge Wilson 			 * This is a delicate dance that we play here.
5083dcbf3bd6SGeorge Wilson 			 * This hdr is in the ghost list so we access it
5084dcbf3bd6SGeorge Wilson 			 * to move it out of the ghost list before we
5085dcbf3bd6SGeorge Wilson 			 * initiate the read. If it's a prefetch then
5086dcbf3bd6SGeorge Wilson 			 * it won't have a callback so we'll remove the
5087dcbf3bd6SGeorge Wilson 			 * reference that arc_buf_alloc_impl() created. We
5088dcbf3bd6SGeorge Wilson 			 * do this after we've called arc_access() to
5089dcbf3bd6SGeorge Wilson 			 * avoid hitting an assert in remove_reference().
5090cf6106c8SMatthew Ahrens 			 */
50917e453561SWilliam Gorrell 			arc_access(hdr, hash_lock);
5092770499e1SDan Kimmel 			arc_hdr_alloc_pabd(hdr);
5093dcbf3bd6SGeorge Wilson 		}
5094770499e1SDan Kimmel 		ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
5095dcbf3bd6SGeorge Wilson 		size = arc_hdr_size(hdr);
5096dcbf3bd6SGeorge Wilson 
5097dcbf3bd6SGeorge Wilson 		/*
5098dcbf3bd6SGeorge Wilson 		 * If compression is enabled on the hdr, then will do
5099dcbf3bd6SGeorge Wilson 		 * RAW I/O and will store the compressed data in the hdr's
5100dcbf3bd6SGeorge Wilson 		 * data block. Otherwise, the hdr's data block will contain
5101dcbf3bd6SGeorge Wilson 		 * the uncompressed data.
5102dcbf3bd6SGeorge Wilson 		 */
5103dcbf3bd6SGeorge Wilson 		if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
5104dcbf3bd6SGeorge Wilson 			zio_flags |= ZIO_FLAG_RAW;
5105fa9e4066Sahrens 		}
5106fa9e4066Sahrens 
5107dcbf3bd6SGeorge Wilson 		if (*arc_flags & ARC_FLAG_PREFETCH)
5108dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5109dcbf3bd6SGeorge Wilson 		if (*arc_flags & ARC_FLAG_L2CACHE)
5110dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5111dcbf3bd6SGeorge Wilson 		if (BP_GET_LEVEL(bp) > 0)
5112dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_INDIRECT);
5113cf6106c8SMatthew Ahrens 		if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
5114dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_PREDICTIVE_PREFETCH);
511589c86e32SChris Williamson 		ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
51165614b00aSWilliam Gorrell 
5117fa9e4066Sahrens 		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
5118fa9e4066Sahrens 		acb->acb_done = done;
5119fa9e4066Sahrens 		acb->acb_private = private;
51205602294fSDan Kimmel 		acb->acb_compressed = compressed_read;
5121fa9e4066Sahrens 
5122dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
512389c86e32SChris Williamson 		hdr->b_l1hdr.b_acb = acb;
5124dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5125fa9e4066Sahrens 
512689c86e32SChris Williamson 		if (HDR_HAS_L2HDR(hdr) &&
512789c86e32SChris Williamson 		    (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
512889c86e32SChris Williamson 			devw = hdr->b_l2hdr.b_dev->l2ad_writing;
512989c86e32SChris Williamson 			addr = hdr->b_l2hdr.b_daddr;
5130e14bb325SJeff Bonwick 			/*
51315cabbc6bSPrashanth Sreenivasa 			 * Lock out L2ARC device removal.
5132e14bb325SJeff Bonwick 			 */
5133e14bb325SJeff Bonwick 			if (vdev_is_dead(vd) ||
5134e14bb325SJeff Bonwick 			    !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
5135e14bb325SJeff Bonwick 				vd = NULL;
51363a737e0dSbrendan 		}
51373a737e0dSbrendan 
5138dcbf3bd6SGeorge Wilson 		if (priority == ZIO_PRIORITY_ASYNC_READ)
5139dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5140dcbf3bd6SGeorge Wilson 		else
5141dcbf3bd6SGeorge Wilson 			arc_hdr_clear_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5142dcbf3bd6SGeorge Wilson 
51435d7b4d43SMatthew Ahrens 		if (hash_lock != NULL)
51445d7b4d43SMatthew Ahrens 			mutex_exit(hash_lock);
51453a737e0dSbrendan 
51463e30c24aSWill Andrews 		/*
51473e30c24aSWill Andrews 		 * At this point, we have a level 1 cache miss.  Try again in
51483e30c24aSWill Andrews 		 * L2ARC if possible.
51493e30c24aSWill Andrews 		 */
5150dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, lsize);
5151dcbf3bd6SGeorge Wilson 
51525c28183bSBrendan Gregg - Sun Microsystems 		DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
5153dcbf3bd6SGeorge Wilson 		    uint64_t, lsize, zbookmark_phys_t *, zb);
515444cb6abcSbmc 		ARCSTAT_BUMP(arcstat_misses);
515589c86e32SChris Williamson 		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
515689c86e32SChris Williamson 		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
515744cb6abcSbmc 		    data, metadata, misses);
5158ea8dc4b6Seschrock 
51595a98e54bSBrendan Gregg - Sun Microsystems 		if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
5160fa94a07fSbrendan 			/*
5161fa94a07fSbrendan 			 * Read from the L2ARC if the following are true:
51623a737e0dSbrendan 			 * 1. The L2ARC vdev was previously cached.
51633a737e0dSbrendan 			 * 2. This buffer still has L2ARC metadata.
51643a737e0dSbrendan 			 * 3. This buffer isn't currently writing to the L2ARC.
51653a737e0dSbrendan 			 * 4. The L2ARC entry wasn't evicted, which may
51663a737e0dSbrendan 			 *    also have invalidated the vdev.
51675a98e54bSBrendan Gregg - Sun Microsystems 			 * 5. This isn't prefetch and l2arc_noprefetch is set.
5168fa94a07fSbrendan 			 */
516989c86e32SChris Williamson 			if (HDR_HAS_L2HDR(hdr) &&
51705a98e54bSBrendan Gregg - Sun Microsystems 			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
51715a98e54bSBrendan Gregg - Sun Microsystems 			    !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
5172fa94a07fSbrendan 				l2arc_read_callback_t *cb;
5173403a8da7SAndriy Gapon 				abd_t *abd;
5174403a8da7SAndriy Gapon 				uint64_t asize;
5175fa94a07fSbrendan 
5176c5904d13Seschrock 				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
5177c5904d13Seschrock 				ARCSTAT_BUMP(arcstat_l2_hits);
5178c5904d13Seschrock 
5179fa94a07fSbrendan 				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
5180fa94a07fSbrendan 				    KM_SLEEP);
5181dcbf3bd6SGeorge Wilson 				cb->l2rcb_hdr = hdr;
5182fa94a07fSbrendan 				cb->l2rcb_bp = *bp;
5183fa94a07fSbrendan 				cb->l2rcb_zb = *zb;
51843baa08fcSek 				cb->l2rcb_flags = zio_flags;
5185fa94a07fSbrendan 
5186403a8da7SAndriy Gapon 				asize = vdev_psize_to_asize(vd, size);
5187403a8da7SAndriy Gapon 				if (asize != size) {
5188403a8da7SAndriy Gapon 					abd = abd_alloc_for_io(asize,
5189403a8da7SAndriy Gapon 					    HDR_ISTYPE_METADATA(hdr));
5190403a8da7SAndriy Gapon 					cb->l2rcb_abd = abd;
5191403a8da7SAndriy Gapon 				} else {
5192403a8da7SAndriy Gapon 					abd = hdr->b_l1hdr.b_pabd;
5193403a8da7SAndriy Gapon 				}
5194403a8da7SAndriy Gapon 
5195d5285caeSGeorge Wilson 				ASSERT(addr >= VDEV_LABEL_START_SIZE &&
5196403a8da7SAndriy Gapon 				    addr + asize <= vd->vdev_psize -
5197d5285caeSGeorge Wilson 				    VDEV_LABEL_END_SIZE);
5198d5285caeSGeorge Wilson 
5199fa94a07fSbrendan 				/*
5200e14bb325SJeff Bonwick 				 * l2arc read.  The SCL_L2ARC lock will be
5201e14bb325SJeff Bonwick 				 * released by l2arc_read_done().
5202aad02571SSaso Kiselkov 				 * Issue a null zio if the underlying buffer
5203aad02571SSaso Kiselkov 				 * was squashed to zero size by compression.
5204fa94a07fSbrendan 				 */
5205dcbf3bd6SGeorge Wilson 				ASSERT3U(HDR_GET_COMPRESS(hdr), !=,
5206dcbf3bd6SGeorge Wilson 				    ZIO_COMPRESS_EMPTY);
5207dcbf3bd6SGeorge Wilson 				rzio = zio_read_phys(pio, vd, addr,
5208403a8da7SAndriy Gapon 				    asize, abd,
5209dcbf3bd6SGeorge Wilson 				    ZIO_CHECKSUM_OFF,
5210dcbf3bd6SGeorge Wilson 				    l2arc_read_done, cb, priority,
5211dcbf3bd6SGeorge Wilson 				    zio_flags | ZIO_FLAG_DONT_CACHE |
5212dcbf3bd6SGeorge Wilson 				    ZIO_FLAG_CANFAIL |
5213dcbf3bd6SGeorge Wilson 				    ZIO_FLAG_DONT_PROPAGATE |
5214dcbf3bd6SGeorge Wilson 				    ZIO_FLAG_DONT_RETRY, B_FALSE);
5215fa94a07fSbrendan 				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
5216fa94a07fSbrendan 				    zio_t *, rzio);
5217dcbf3bd6SGeorge Wilson 				ARCSTAT_INCR(arcstat_l2_read_bytes, size);
5218fa94a07fSbrendan 
52197adb730bSGeorge Wilson 				if (*arc_flags & ARC_FLAG_NOWAIT) {
52203a737e0dSbrendan 					zio_nowait(rzio);
52213a737e0dSbrendan 					return (0);
52223a737e0dSbrendan 				}
5223fa94a07fSbrendan 
52247adb730bSGeorge Wilson 				ASSERT(*arc_flags & ARC_FLAG_WAIT);
52253a737e0dSbrendan 				if (zio_wait(rzio) == 0)
52263a737e0dSbrendan 					return (0);
52273a737e0dSbrendan 
52283a737e0dSbrendan 				/* l2arc read error; goto zio_read() */
5229fa94a07fSbrendan 			} else {
5230fa94a07fSbrendan 				DTRACE_PROBE1(l2arc__miss,
5231fa94a07fSbrendan 				    arc_buf_hdr_t *, hdr);
5232fa94a07fSbrendan 				ARCSTAT_BUMP(arcstat_l2_misses);
5233fa94a07fSbrendan 				if (HDR_L2_WRITING(hdr))
5234fa94a07fSbrendan 					ARCSTAT_BUMP(arcstat_l2_rw_clash);
5235e14bb325SJeff Bonwick 				spa_config_exit(spa, SCL_L2ARC, vd);
5236fa94a07fSbrendan 			}
52375a98e54bSBrendan Gregg - Sun Microsystems 		} else {
523876a25fafSBill Moore 			if (vd != NULL)
523976a25fafSBill Moore 				spa_config_exit(spa, SCL_L2ARC, vd);
52405a98e54bSBrendan Gregg - Sun Microsystems 			if (l2arc_ndev != 0) {
52415a98e54bSBrendan Gregg - Sun Microsystems 				DTRACE_PROBE1(l2arc__miss,
52425a98e54bSBrendan Gregg - Sun Microsystems 				    arc_buf_hdr_t *, hdr);
52435a98e54bSBrendan Gregg - Sun Microsystems 				ARCSTAT_BUMP(arcstat_l2_misses);
52445a98e54bSBrendan Gregg - Sun Microsystems 			}
5245fa94a07fSbrendan 		}
5246c5904d13Seschrock 
5247770499e1SDan Kimmel 		rzio = zio_read(pio, spa, bp, hdr->b_l1hdr.b_pabd, size,
5248dcbf3bd6SGeorge Wilson 		    arc_read_done, hdr, priority, zio_flags, zb);
5249fa9e4066Sahrens 
52507adb730bSGeorge Wilson 		if (*arc_flags & ARC_FLAG_WAIT)
5251fa9e4066Sahrens 			return (zio_wait(rzio));
5252fa9e4066Sahrens 
52537adb730bSGeorge Wilson 		ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
5254fa9e4066Sahrens 		zio_nowait(rzio);
5255fa9e4066Sahrens 	}
5256fa9e4066Sahrens 	return (0);
5257fa9e4066Sahrens }
5258fa9e4066Sahrens 
52596e6d5868SMatthew Ahrens /*
52606e6d5868SMatthew Ahrens  * Notify the arc that a block was freed, and thus will never be used again.
52616e6d5868SMatthew Ahrens  */
52626e6d5868SMatthew Ahrens void
52636e6d5868SMatthew Ahrens arc_freed(spa_t *spa, const blkptr_t *bp)
52646e6d5868SMatthew Ahrens {
52656e6d5868SMatthew Ahrens 	arc_buf_hdr_t *hdr;
52666e6d5868SMatthew Ahrens 	kmutex_t *hash_lock;
52676e6d5868SMatthew Ahrens 	uint64_t guid = spa_load_guid(spa);
52686e6d5868SMatthew Ahrens 
52695d7b4d43SMatthew Ahrens 	ASSERT(!BP_IS_EMBEDDED(bp));
52705d7b4d43SMatthew Ahrens 
52715d7b4d43SMatthew Ahrens 	hdr = buf_hash_find(guid, bp, &hash_lock);
52726e6d5868SMatthew Ahrens 	if (hdr == NULL)
52736e6d5868SMatthew Ahrens 		return;
52746e6d5868SMatthew Ahrens 
5275dcbf3bd6SGeorge Wilson 	/*
5276dcbf3bd6SGeorge Wilson 	 * We might be trying to free a block that is still doing I/O
5277dcbf3bd6SGeorge Wilson 	 * (i.e. prefetch) or has a reference (i.e. a dedup-ed,
5278dcbf3bd6SGeorge Wilson 	 * dmu_sync-ed block). If this block is being prefetched, then it
5279dcbf3bd6SGeorge Wilson 	 * would still have the ARC_FLAG_IO_IN_PROGRESS flag set on the hdr
5280dcbf3bd6SGeorge Wilson 	 * until the I/O completes. A block may also have a reference if it is
5281dcbf3bd6SGeorge Wilson 	 * part of a dedup-ed, dmu_synced write. The dmu_sync() function would
5282dcbf3bd6SGeorge Wilson 	 * have written the new block to its final resting place on disk but
5283dcbf3bd6SGeorge Wilson 	 * without the dedup flag set. This would have left the hdr in the MRU
5284dcbf3bd6SGeorge Wilson 	 * state and discoverable. When the txg finally syncs it detects that
5285dcbf3bd6SGeorge Wilson 	 * the block was overridden in open context and issues an override I/O.
5286dcbf3bd6SGeorge Wilson 	 * Since this is a dedup block, the override I/O will determine if the
5287dcbf3bd6SGeorge Wilson 	 * block is already in the DDT. If so, then it will replace the io_bp
5288dcbf3bd6SGeorge Wilson 	 * with the bp from the DDT and allow the I/O to finish. When the I/O
5289dcbf3bd6SGeorge Wilson 	 * reaches the done callback, dbuf_write_override_done, it will
5290dcbf3bd6SGeorge Wilson 	 * check to see if the io_bp and io_bp_override are identical.
5291dcbf3bd6SGeorge Wilson 	 * If they are not, then it indicates that the bp was replaced with
5292dcbf3bd6SGeorge Wilson 	 * the bp in the DDT and the override bp is freed. This allows
5293dcbf3bd6SGeorge Wilson 	 * us to arrive here with a reference on a block that is being
5294dcbf3bd6SGeorge Wilson 	 * freed. So if we have an I/O in progress, or a reference to
5295dcbf3bd6SGeorge Wilson 	 * this hdr, then we don't destroy the hdr.
5296dcbf3bd6SGeorge Wilson 	 */
5297dcbf3bd6SGeorge Wilson 	if (!HDR_HAS_L1HDR(hdr) || (!HDR_IO_IN_PROGRESS(hdr) &&
5298dcbf3bd6SGeorge Wilson 	    refcount_is_zero(&hdr->b_l1hdr.b_refcnt))) {
5299dcbf3bd6SGeorge Wilson 		arc_change_state(arc_anon, hdr, hash_lock);
5300dcbf3bd6SGeorge Wilson 		arc_hdr_destroy(hdr);
53016e6d5868SMatthew Ahrens 		mutex_exit(hash_lock);
5302bbfa8ea8SMatthew Ahrens 	} else {
5303dcbf3bd6SGeorge Wilson 		mutex_exit(hash_lock);
5304ea8dc4b6Seschrock 	}
5305dd6ef538Smaybee 
5306ea8dc4b6Seschrock }
5307ea8dc4b6Seschrock 
5308fa9e4066Sahrens /*
53093e30c24aSWill Andrews  * Release this buffer from the cache, making it an anonymous buffer.  This
53103e30c24aSWill Andrews  * must be done after a read and prior to modifying the buffer contents.
5311fa9e4066Sahrens  * If the buffer has more than one reference, we must make
5312088f3894Sahrens  * a new hdr for the buffer.
5313fa9e4066Sahrens  */
5314fa9e4066Sahrens void
5315fa9e4066Sahrens arc_release(arc_buf_t *buf, void *tag)
5316fa9e4066Sahrens {
531789c86e32SChris Williamson 	arc_buf_hdr_t *hdr = buf->b_hdr;
5318fa9e4066Sahrens 
53193f9d6ad7SLin Ling 	/*
53203f9d6ad7SLin Ling 	 * It would be nice to assert that if it's DMU metadata (level >
53213f9d6ad7SLin Ling 	 * 0 || it's the dnode file), then it must be syncing context.
53223f9d6ad7SLin Ling 	 * But we don't know that information at this level.
53233f9d6ad7SLin Ling 	 */
53243f9d6ad7SLin Ling 
53253f9d6ad7SLin Ling 	mutex_enter(&buf->b_evict_lock);
53266f83844dSMark Maybee 
5327244781f1SPrakash Surya 	ASSERT(HDR_HAS_L1HDR(hdr));
5328244781f1SPrakash Surya 
532989c86e32SChris Williamson 	/*
533089c86e32SChris Williamson 	 * We don't grab the hash lock prior to this check, because if
533189c86e32SChris Williamson 	 * the buffer's header is in the arc_anon state, it won't be
533289c86e32SChris Williamson 	 * linked into the hash table.
533389c86e32SChris Williamson 	 */
533489c86e32SChris Williamson 	if (hdr->b_l1hdr.b_state == arc_anon) {
533589c86e32SChris Williamson 		mutex_exit(&buf->b_evict_lock);
533689c86e32SChris Williamson 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
533789c86e32SChris Williamson 		ASSERT(!HDR_IN_HASH_TABLE(hdr));
533889c86e32SChris Williamson 		ASSERT(!HDR_HAS_L2HDR(hdr));
5339dcbf3bd6SGeorge Wilson 		ASSERT(HDR_EMPTY(hdr));
5340fa9e4066Sahrens 
5341dcbf3bd6SGeorge Wilson 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
534289c86e32SChris Williamson 		ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
534389c86e32SChris Williamson 		ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
534489c86e32SChris Williamson 
534589c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = 0;
5346dcbf3bd6SGeorge Wilson 
5347dcbf3bd6SGeorge Wilson 		/*
5348dcbf3bd6SGeorge Wilson 		 * If the buf is being overridden then it may already
5349dcbf3bd6SGeorge Wilson 		 * have a hdr that is not empty.
5350dcbf3bd6SGeorge Wilson 		 */
5351dcbf3bd6SGeorge Wilson 		buf_discard_identity(hdr);
535289c86e32SChris Williamson 		arc_buf_thaw(buf);
535389c86e32SChris Williamson 
535489c86e32SChris Williamson 		return;
5355fa9e4066Sahrens 	}
5356fa9e4066Sahrens 
535789c86e32SChris Williamson 	kmutex_t *hash_lock = HDR_LOCK(hdr);
535889c86e32SChris Williamson 	mutex_enter(hash_lock);
535989c86e32SChris Williamson 
536089c86e32SChris Williamson 	/*
536189c86e32SChris Williamson 	 * This assignment is only valid as long as the hash_lock is
536289c86e32SChris Williamson 	 * held, we must be careful not to reference state or the
536389c86e32SChris Williamson 	 * b_state field after dropping the lock.
536489c86e32SChris Williamson 	 */
536589c86e32SChris Williamson 	arc_state_t *state = hdr->b_l1hdr.b_state;
536689c86e32SChris Williamson 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
536789c86e32SChris Williamson 	ASSERT3P(state, !=, arc_anon);
536889c86e32SChris Williamson 
536989c86e32SChris Williamson 	/* this buffer is not on any list */
53705602294fSDan Kimmel 	ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), >, 0);
537189c86e32SChris Williamson 
537289c86e32SChris Williamson 	if (HDR_HAS_L2HDR(hdr)) {
537389c86e32SChris Williamson 		mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
5374244781f1SPrakash Surya 
5375244781f1SPrakash Surya 		/*
5376a52fc310SPrakash Surya 		 * We have to recheck this conditional again now that
5377a52fc310SPrakash Surya 		 * we're holding the l2ad_mtx to prevent a race with
5378a52fc310SPrakash Surya 		 * another thread which might be concurrently calling
5379a52fc310SPrakash Surya 		 * l2arc_evict(). In that case, l2arc_evict() might have
5380a52fc310SPrakash Surya 		 * destroyed the header's L2 portion as we were waiting
5381a52fc310SPrakash Surya 		 * to acquire the l2ad_mtx.
5382244781f1SPrakash Surya 		 */
5383a52fc310SPrakash Surya 		if (HDR_HAS_L2HDR(hdr))
5384a52fc310SPrakash Surya 			arc_hdr_l2hdr_destroy(hdr);
5385244781f1SPrakash Surya 
538689c86e32SChris Williamson 		mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
53876f83844dSMark Maybee 	}
53886f83844dSMark Maybee 
5389ea8dc4b6Seschrock 	/*
5390ea8dc4b6Seschrock 	 * Do we have more than one buf?
5391ea8dc4b6Seschrock 	 */
5392dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_bufcnt > 1) {
5393fa9e4066Sahrens 		arc_buf_hdr_t *nhdr;
5394ac05c741SMark Maybee 		uint64_t spa = hdr->b_spa;
5395dcbf3bd6SGeorge Wilson 		uint64_t psize = HDR_GET_PSIZE(hdr);
5396dcbf3bd6SGeorge Wilson 		uint64_t lsize = HDR_GET_LSIZE(hdr);
5397dcbf3bd6SGeorge Wilson 		enum zio_compress compress = HDR_GET_COMPRESS(hdr);
539889c86e32SChris Williamson 		arc_buf_contents_t type = arc_buf_type(hdr);
5399dcbf3bd6SGeorge Wilson 		VERIFY3U(hdr->b_type, ==, type);
5400fa9e4066Sahrens 
540189c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
5402dcbf3bd6SGeorge Wilson 		(void) remove_reference(hdr, hash_lock, tag);
5403dcbf3bd6SGeorge Wilson 
54045602294fSDan Kimmel 		if (arc_buf_is_shared(buf) && !ARC_BUF_COMPRESSED(buf)) {
5405dcbf3bd6SGeorge Wilson 			ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
5406dcbf3bd6SGeorge Wilson 			ASSERT(ARC_BUF_LAST(buf));
5407dcbf3bd6SGeorge Wilson 		}
5408dcbf3bd6SGeorge Wilson 
5409fa9e4066Sahrens 		/*
54103f9d6ad7SLin Ling 		 * Pull the data off of this hdr and attach it to
5411dcbf3bd6SGeorge Wilson 		 * a new anonymous hdr. Also find the last buffer
5412dcbf3bd6SGeorge Wilson 		 * in the hdr's buffer list.
5413fa9e4066Sahrens 		 */
54145602294fSDan Kimmel 		arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
5415dcbf3bd6SGeorge Wilson 		ASSERT3P(lastbuf, !=, NULL);
5416dcbf3bd6SGeorge Wilson 
5417dcbf3bd6SGeorge Wilson 		/*
5418dcbf3bd6SGeorge Wilson 		 * If the current arc_buf_t and the hdr are sharing their data
54195602294fSDan Kimmel 		 * buffer, then we must stop sharing that block.
5420dcbf3bd6SGeorge Wilson 		 */
5421dcbf3bd6SGeorge Wilson 		if (arc_buf_is_shared(buf)) {
5422dcbf3bd6SGeorge Wilson 			VERIFY(!arc_buf_is_shared(lastbuf));
5423ea8dc4b6Seschrock 
5424dcbf3bd6SGeorge Wilson 			/*
5425dcbf3bd6SGeorge Wilson 			 * First, sever the block sharing relationship between
54265602294fSDan Kimmel 			 * buf and the arc_buf_hdr_t.
5427dcbf3bd6SGeorge Wilson 			 */
5428dcbf3bd6SGeorge Wilson 			arc_unshare_buf(hdr, buf);
54295602294fSDan Kimmel 
54305602294fSDan Kimmel 			/*
5431770499e1SDan Kimmel 			 * Now we need to recreate the hdr's b_pabd. Since we
54325602294fSDan Kimmel 			 * have lastbuf handy, we try to share with it, but if
5433770499e1SDan Kimmel 			 * we can't then we allocate a new b_pabd and copy the
54345602294fSDan Kimmel 			 * data from buf into it.
54355602294fSDan Kimmel 			 */
54365602294fSDan Kimmel 			if (arc_can_share(hdr, lastbuf)) {
54375602294fSDan Kimmel 				arc_share_buf(hdr, lastbuf);
54385602294fSDan Kimmel 			} else {
5439770499e1SDan Kimmel 				arc_hdr_alloc_pabd(hdr);
5440770499e1SDan Kimmel 				abd_copy_from_buf(hdr->b_l1hdr.b_pabd,
5441770499e1SDan Kimmel 				    buf->b_data, psize);
54425602294fSDan Kimmel 			}
5443dcbf3bd6SGeorge Wilson 			VERIFY3P(lastbuf->b_data, !=, NULL);
5444dcbf3bd6SGeorge Wilson 		} else if (HDR_SHARED_DATA(hdr)) {
54455602294fSDan Kimmel 			/*
54465602294fSDan Kimmel 			 * Uncompressed shared buffers are always at the end
54475602294fSDan Kimmel 			 * of the list. Compressed buffers don't have the
54485602294fSDan Kimmel 			 * same requirements. This makes it hard to
54495602294fSDan Kimmel 			 * simply assert that the lastbuf is shared so
54505602294fSDan Kimmel 			 * we rely on the hdr's compression flags to determine
54515602294fSDan Kimmel 			 * if we have a compressed, shared buffer.
54525602294fSDan Kimmel 			 */
54535602294fSDan Kimmel 			ASSERT(arc_buf_is_shared(lastbuf) ||
54545602294fSDan Kimmel 			    HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
54555602294fSDan Kimmel 			ASSERT(!ARC_BUF_SHARED(buf));
5456dcbf3bd6SGeorge Wilson 		}
5457770499e1SDan Kimmel 		ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
545889c86e32SChris Williamson 		ASSERT3P(state, !=, arc_l2c_only);
54592fd872a7SPrakash Surya 
5460dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_size,
54615602294fSDan Kimmel 		    arc_buf_size(buf), buf);
54622fd872a7SPrakash Surya 
546389c86e32SChris Williamson 		if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
546489c86e32SChris Williamson 			ASSERT3P(state, !=, arc_l2c_only);
5465dcbf3bd6SGeorge Wilson 			(void) refcount_remove_many(&state->arcs_esize[type],
54665602294fSDan Kimmel 			    arc_buf_size(buf), buf);
5467ea8dc4b6Seschrock 		}
54689253d63dSGeorge Wilson 
5469dcbf3bd6SGeorge Wilson 		hdr->b_l1hdr.b_bufcnt -= 1;
5470c717a561Smaybee 		arc_cksum_verify(buf);
5471cd1c8b85SMatthew Ahrens 		arc_buf_unwatch(buf);
5472ea8dc4b6Seschrock 
5473fa9e4066Sahrens 		mutex_exit(hash_lock);
5474fa9e4066Sahrens 
5475dcbf3bd6SGeorge Wilson 		/*
5476770499e1SDan Kimmel 		 * Allocate a new hdr. The new hdr will contain a b_pabd
5477dcbf3bd6SGeorge Wilson 		 * buffer which will be freed in arc_write().
5478dcbf3bd6SGeorge Wilson 		 */
5479dcbf3bd6SGeorge Wilson 		nhdr = arc_hdr_alloc(spa, psize, lsize, compress, type);
5480dcbf3bd6SGeorge Wilson 		ASSERT3P(nhdr->b_l1hdr.b_buf, ==, NULL);
5481dcbf3bd6SGeorge Wilson 		ASSERT0(nhdr->b_l1hdr.b_bufcnt);
5482dcbf3bd6SGeorge Wilson 		ASSERT0(refcount_count(&nhdr->b_l1hdr.b_refcnt));
5483dcbf3bd6SGeorge Wilson 		VERIFY3U(nhdr->b_type, ==, type);
5484dcbf3bd6SGeorge Wilson 		ASSERT(!HDR_SHARED_DATA(nhdr));
548589c86e32SChris Williamson 
548689c86e32SChris Williamson 		nhdr->b_l1hdr.b_buf = buf;
5487dcbf3bd6SGeorge Wilson 		nhdr->b_l1hdr.b_bufcnt = 1;
548889c86e32SChris Williamson 		(void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
5489af2c4821Smaybee 		buf->b_hdr = nhdr;
5490dcbf3bd6SGeorge Wilson 
54913f9d6ad7SLin Ling 		mutex_exit(&buf->b_evict_lock);
5492dcbf3bd6SGeorge Wilson 		(void) refcount_add_many(&arc_anon->arcs_size,
54935602294fSDan Kimmel 		    arc_buf_size(buf), buf);
5494fa9e4066Sahrens 	} else {
54953f9d6ad7SLin Ling 		mutex_exit(&buf->b_evict_lock);
549689c86e32SChris Williamson 		ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
5497244781f1SPrakash Surya 		/* protected by hash lock, or hdr is on arc_anon */
5498244781f1SPrakash Surya 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
5499fa9e4066Sahrens 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
550089c86e32SChris Williamson 		arc_change_state(arc_anon, hdr, hash_lock);
550189c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = 0;
550289c86e32SChris Williamson 		mutex_exit(hash_lock);
5503fa94a07fSbrendan 
55043f9d6ad7SLin Ling 		buf_discard_identity(hdr);
5505c717a561Smaybee 		arc_buf_thaw(buf);
5506fa9e4066Sahrens 	}
5507fa9e4066Sahrens }
5508fa9e4066Sahrens 
5509fa9e4066Sahrens int
5510fa9e4066Sahrens arc_released(arc_buf_t *buf)
5511fa9e4066Sahrens {
55126f83844dSMark Maybee 	int released;
55136f83844dSMark Maybee 
55143f9d6ad7SLin Ling 	mutex_enter(&buf->b_evict_lock);
551589c86e32SChris Williamson 	released = (buf->b_data != NULL &&
551689c86e32SChris Williamson 	    buf->b_hdr->b_l1hdr.b_state == arc_anon);
55173f9d6ad7SLin Ling 	mutex_exit(&buf->b_evict_lock);
55186f83844dSMark Maybee 	return (released);
5519ea8dc4b6Seschrock }
5520ea8dc4b6Seschrock 
5521ea8dc4b6Seschrock #ifdef ZFS_DEBUG
5522ea8dc4b6Seschrock int
5523ea8dc4b6Seschrock arc_referenced(arc_buf_t *buf)
5524ea8dc4b6Seschrock {
55256f83844dSMark Maybee 	int referenced;
55266f83844dSMark Maybee 
55273f9d6ad7SLin Ling 	mutex_enter(&buf->b_evict_lock);
552889c86e32SChris Williamson 	referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
55293f9d6ad7SLin Ling 	mutex_exit(&buf->b_evict_lock);
55306f83844dSMark Maybee 	return (referenced);
5531ea8dc4b6Seschrock }
5532ea8dc4b6Seschrock #endif
5533ea8dc4b6Seschrock 
5534c717a561Smaybee static void
5535c717a561Smaybee arc_write_ready(zio_t *zio)
5536c717a561Smaybee {
5537c717a561Smaybee 	arc_write_callback_t *callback = zio->io_private;
5538c717a561Smaybee 	arc_buf_t *buf = callback->awcb_buf;
55390a4e9518Sgw 	arc_buf_hdr_t *hdr = buf->b_hdr;
5540dcbf3bd6SGeorge Wilson 	uint64_t psize = BP_IS_HOLE(zio->io_bp) ? 0 : BP_GET_PSIZE(zio->io_bp);
5541c717a561Smaybee 
554289c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
554389c86e32SChris Williamson 	ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
5544dcbf3bd6SGeorge Wilson 	ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
5545e14bb325SJeff Bonwick 
55460a4e9518Sgw 	/*
5547dcbf3bd6SGeorge Wilson 	 * If we're reexecuting this zio because the pool suspended, then
5548dcbf3bd6SGeorge Wilson 	 * cleanup any state that was previously set the first time the
55495602294fSDan Kimmel 	 * callback was invoked.
55500a4e9518Sgw 	 */
5551dcbf3bd6SGeorge Wilson 	if (zio->io_flags & ZIO_FLAG_REEXECUTED) {
5552dcbf3bd6SGeorge Wilson 		arc_cksum_free(hdr);
5553dcbf3bd6SGeorge Wilson 		arc_buf_unwatch(buf);
5554770499e1SDan Kimmel 		if (hdr->b_l1hdr.b_pabd != NULL) {
5555dcbf3bd6SGeorge Wilson 			if (arc_buf_is_shared(buf)) {
5556dcbf3bd6SGeorge Wilson 				arc_unshare_buf(hdr, buf);
5557dcbf3bd6SGeorge Wilson 			} else {
5558770499e1SDan Kimmel 				arc_hdr_free_pabd(hdr);
5559dcbf3bd6SGeorge Wilson 			}
55600a4e9518Sgw 		}
55610a4e9518Sgw 	}
5562770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
5563dcbf3bd6SGeorge Wilson 	ASSERT(!HDR_SHARED_DATA(hdr));
5564dcbf3bd6SGeorge Wilson 	ASSERT(!arc_buf_is_shared(buf));
5565dcbf3bd6SGeorge Wilson 
5566dcbf3bd6SGeorge Wilson 	callback->awcb_ready(zio, buf, callback->awcb_private);
5567dcbf3bd6SGeorge Wilson 
5568dcbf3bd6SGeorge Wilson 	if (HDR_IO_IN_PROGRESS(hdr))
5569dcbf3bd6SGeorge Wilson 		ASSERT(zio->io_flags & ZIO_FLAG_REEXECUTED);
5570dcbf3bd6SGeorge Wilson 
5571dcbf3bd6SGeorge Wilson 	arc_cksum_compute(buf);
5572dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5573dcbf3bd6SGeorge Wilson 
5574dcbf3bd6SGeorge Wilson 	enum zio_compress compress;
5575dcbf3bd6SGeorge Wilson 	if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
5576dcbf3bd6SGeorge Wilson 		compress = ZIO_COMPRESS_OFF;
5577dcbf3bd6SGeorge Wilson 	} else {
5578dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(zio->io_bp));
5579dcbf3bd6SGeorge Wilson 		compress = BP_GET_COMPRESS(zio->io_bp);
5580dcbf3bd6SGeorge Wilson 	}
5581dcbf3bd6SGeorge Wilson 	HDR_SET_PSIZE(hdr, psize);
5582dcbf3bd6SGeorge Wilson 	arc_hdr_set_compress(hdr, compress);
5583dcbf3bd6SGeorge Wilson 
5584770499e1SDan Kimmel 
5585dcbf3bd6SGeorge Wilson 	/*
5586770499e1SDan Kimmel 	 * Fill the hdr with data. If the hdr is compressed, the data we want
5587770499e1SDan Kimmel 	 * is available from the zio, otherwise we can take it from the buf.
5588770499e1SDan Kimmel 	 *
5589770499e1SDan Kimmel 	 * We might be able to share the buf's data with the hdr here. However,
5590770499e1SDan Kimmel 	 * doing so would cause the ARC to be full of linear ABDs if we write a
5591770499e1SDan Kimmel 	 * lot of shareable data. As a compromise, we check whether scattered
5592770499e1SDan Kimmel 	 * ABDs are allowed, and assume that if they are then the user wants
5593770499e1SDan Kimmel 	 * the ARC to be primarily filled with them regardless of the data being
5594770499e1SDan Kimmel 	 * written. Therefore, if they're allowed then we allocate one and copy
5595770499e1SDan Kimmel 	 * the data into it; otherwise, we share the data directly if we can.
5596dcbf3bd6SGeorge Wilson 	 */
5597770499e1SDan Kimmel 	if (zfs_abd_scatter_enabled || !arc_can_share(hdr, buf)) {
5598770499e1SDan Kimmel 		arc_hdr_alloc_pabd(hdr);
5599770499e1SDan Kimmel 
5600770499e1SDan Kimmel 		/*
5601770499e1SDan Kimmel 		 * Ideally, we would always copy the io_abd into b_pabd, but the
5602770499e1SDan Kimmel 		 * user may have disabled compressed ARC, thus we must check the
5603770499e1SDan Kimmel 		 * hdr's compression setting rather than the io_bp's.
5604770499e1SDan Kimmel 		 */
5605770499e1SDan Kimmel 		if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
5606770499e1SDan Kimmel 			ASSERT3U(BP_GET_COMPRESS(zio->io_bp), !=,
5607770499e1SDan Kimmel 			    ZIO_COMPRESS_OFF);
5608770499e1SDan Kimmel 			ASSERT3U(psize, >, 0);
5609770499e1SDan Kimmel 
5610770499e1SDan Kimmel 			abd_copy(hdr->b_l1hdr.b_pabd, zio->io_abd, psize);
5611770499e1SDan Kimmel 		} else {
5612770499e1SDan Kimmel 			ASSERT3U(zio->io_orig_size, ==, arc_hdr_size(hdr));
5613770499e1SDan Kimmel 
5614770499e1SDan Kimmel 			abd_copy_from_buf(hdr->b_l1hdr.b_pabd, buf->b_data,
5615770499e1SDan Kimmel 			    arc_buf_size(buf));
5616770499e1SDan Kimmel 		}
5617dcbf3bd6SGeorge Wilson 	} else {
5618770499e1SDan Kimmel 		ASSERT3P(buf->b_data, ==, abd_to_buf(zio->io_orig_abd));
56195602294fSDan Kimmel 		ASSERT3U(zio->io_orig_size, ==, arc_buf_size(buf));
5620dcbf3bd6SGeorge Wilson 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
5621dcbf3bd6SGeorge Wilson 
5622dcbf3bd6SGeorge Wilson 		arc_share_buf(hdr, buf);
5623dcbf3bd6SGeorge Wilson 	}
5624770499e1SDan Kimmel 
5625dcbf3bd6SGeorge Wilson 	arc_hdr_verify(hdr, zio->io_bp);
5626c717a561Smaybee }
5627c717a561Smaybee 
56288df0bcf0SPaul Dagnelie static void
56298df0bcf0SPaul Dagnelie arc_write_children_ready(zio_t *zio)
56308df0bcf0SPaul Dagnelie {
56318df0bcf0SPaul Dagnelie 	arc_write_callback_t *callback = zio->io_private;
56328df0bcf0SPaul Dagnelie 	arc_buf_t *buf = callback->awcb_buf;
56338df0bcf0SPaul Dagnelie 
56348df0bcf0SPaul Dagnelie 	callback->awcb_children_ready(zio, buf, callback->awcb_private);
56358df0bcf0SPaul Dagnelie }
56368df0bcf0SPaul Dagnelie 
563769962b56SMatthew Ahrens /*
563869962b56SMatthew Ahrens  * The SPA calls this callback for each physical write that happens on behalf
563969962b56SMatthew Ahrens  * of a logical write.  See the comment in dbuf_write_physdone() for details.
564069962b56SMatthew Ahrens  */
564169962b56SMatthew Ahrens static void
564269962b56SMatthew Ahrens arc_write_physdone(zio_t *zio)
564369962b56SMatthew Ahrens {
564469962b56SMatthew Ahrens 	arc_write_callback_t *cb = zio->io_private;
564569962b56SMatthew Ahrens 	if (cb->awcb_physdone != NULL)
564669962b56SMatthew Ahrens 		cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
564769962b56SMatthew Ahrens }
564869962b56SMatthew Ahrens 
5649fa9e4066Sahrens static void
5650fa9e4066Sahrens arc_write_done(zio_t *zio)
5651fa9e4066Sahrens {
5652c717a561Smaybee 	arc_write_callback_t *callback = zio->io_private;
5653c717a561Smaybee 	arc_buf_t *buf = callback->awcb_buf;
5654c717a561Smaybee 	arc_buf_hdr_t *hdr = buf->b_hdr;
5655fa9e4066Sahrens 
5656dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5657b24ab676SJeff Bonwick 
5658b24ab676SJeff Bonwick 	if (zio->io_error == 0) {
5659dcbf3bd6SGeorge Wilson 		arc_hdr_verify(hdr, zio->io_bp);
5660dcbf3bd6SGeorge Wilson 
56615d7b4d43SMatthew Ahrens 		if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
566243466aaeSMax Grossman 			buf_discard_identity(hdr);
566343466aaeSMax Grossman 		} else {
566443466aaeSMax Grossman 			hdr->b_dva = *BP_IDENTITY(zio->io_bp);
566543466aaeSMax Grossman 			hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
566643466aaeSMax Grossman 		}
5667b24ab676SJeff Bonwick 	} else {
5668dcbf3bd6SGeorge Wilson 		ASSERT(HDR_EMPTY(hdr));
5669b24ab676SJeff Bonwick 	}
5670fa9e4066Sahrens 
5671ea8dc4b6Seschrock 	/*
56725d7b4d43SMatthew Ahrens 	 * If the block to be written was all-zero or compressed enough to be
56735d7b4d43SMatthew Ahrens 	 * embedded in the BP, no write was performed so there will be no
56745d7b4d43SMatthew Ahrens 	 * dva/birth/checksum.  The buffer must therefore remain anonymous
56755d7b4d43SMatthew Ahrens 	 * (and uncached).
5676ea8dc4b6Seschrock 	 */
5677dcbf3bd6SGeorge Wilson 	if (!HDR_EMPTY(hdr)) {
5678fa9e4066Sahrens 		arc_buf_hdr_t *exists;
5679fa9e4066Sahrens 		kmutex_t *hash_lock;
5680fa9e4066Sahrens 
56815602294fSDan Kimmel 		ASSERT3U(zio->io_error, ==, 0);
5682b24ab676SJeff Bonwick 
56836b4acc8bSahrens 		arc_cksum_verify(buf);
56846b4acc8bSahrens 
5685fa9e4066Sahrens 		exists = buf_hash_insert(hdr, &hash_lock);
568689c86e32SChris Williamson 		if (exists != NULL) {
5687fa9e4066Sahrens 			/*
5688fa9e4066Sahrens 			 * This can only happen if we overwrite for
5689fa9e4066Sahrens 			 * sync-to-convergence, because we remove
5690fa9e4066Sahrens 			 * buffers from the hash table when we arc_free().
5691fa9e4066Sahrens 			 */
5692b24ab676SJeff Bonwick 			if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
5693b24ab676SJeff Bonwick 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5694b24ab676SJeff Bonwick 					panic("bad overwrite, hdr=%p exists=%p",
5695b24ab676SJeff Bonwick 					    (void *)hdr, (void *)exists);
569689c86e32SChris Williamson 				ASSERT(refcount_is_zero(
569789c86e32SChris Williamson 				    &exists->b_l1hdr.b_refcnt));
5698b24ab676SJeff Bonwick 				arc_change_state(arc_anon, exists, hash_lock);
5699b24ab676SJeff Bonwick 				mutex_exit(hash_lock);
5700b24ab676SJeff Bonwick 				arc_hdr_destroy(exists);
5701b24ab676SJeff Bonwick 				exists = buf_hash_insert(hdr, &hash_lock);
5702b24ab676SJeff Bonwick 				ASSERT3P(exists, ==, NULL);
570380901aeaSGeorge Wilson 			} else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
570480901aeaSGeorge Wilson 				/* nopwrite */
570580901aeaSGeorge Wilson 				ASSERT(zio->io_prop.zp_nopwrite);
570680901aeaSGeorge Wilson 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
570780901aeaSGeorge Wilson 					panic("bad nopwrite, hdr=%p exists=%p",
570880901aeaSGeorge Wilson 					    (void *)hdr, (void *)exists);
5709b24ab676SJeff Bonwick 			} else {
5710b24ab676SJeff Bonwick 				/* Dedup */
5711dcbf3bd6SGeorge Wilson 				ASSERT(hdr->b_l1hdr.b_bufcnt == 1);
571289c86e32SChris Williamson 				ASSERT(hdr->b_l1hdr.b_state == arc_anon);
5713b24ab676SJeff Bonwick 				ASSERT(BP_GET_DEDUP(zio->io_bp));
5714b24ab676SJeff Bonwick 				ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
5715ae46e4c7SMatthew Ahrens 			}
5716fa9e4066Sahrens 		}
5717dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5718088f3894Sahrens 		/* if it's not anon, we are doing a scrub */
571989c86e32SChris Williamson 		if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
5720088f3894Sahrens 			arc_access(hdr, hash_lock);
572144eda4d7Smaybee 		mutex_exit(hash_lock);
5722ea8dc4b6Seschrock 	} else {
5723dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5724fa9e4066Sahrens 	}
5725ea8dc4b6Seschrock 
572689c86e32SChris Williamson 	ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5727b24ab676SJeff Bonwick 	callback->awcb_done(zio, buf, callback->awcb_private);
5728fa9e4066Sahrens 
5729770499e1SDan Kimmel 	abd_put(zio->io_abd);
5730c717a561Smaybee 	kmem_free(callback, sizeof (arc_write_callback_t));
5731fa9e4066Sahrens }
5732fa9e4066Sahrens 
5733c717a561Smaybee zio_t *
5734dcbf3bd6SGeorge Wilson arc_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
5735dcbf3bd6SGeorge Wilson     boolean_t l2arc, const zio_prop_t *zp, arc_done_func_t *ready,
57368df0bcf0SPaul Dagnelie     arc_done_func_t *children_ready, arc_done_func_t *physdone,
573769962b56SMatthew Ahrens     arc_done_func_t *done, void *private, zio_priority_t priority,
57387802d7bfSMatthew Ahrens     int zio_flags, const zbookmark_phys_t *zb)
5739fa9e4066Sahrens {
5740fa9e4066Sahrens 	arc_buf_hdr_t *hdr = buf->b_hdr;
5741c717a561Smaybee 	arc_write_callback_t *callback;
5742e14bb325SJeff Bonwick 	zio_t *zio;
5743adaec86aSMatthew Ahrens 	zio_prop_t localprop = *zp;
5744fa9e4066Sahrens 
5745dcbf3bd6SGeorge Wilson 	ASSERT3P(ready, !=, NULL);
5746dcbf3bd6SGeorge Wilson 	ASSERT3P(done, !=, NULL);
5747fa9e4066Sahrens 	ASSERT(!HDR_IO_ERROR(hdr));
574889c86e32SChris Williamson 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5749dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5750dcbf3bd6SGeorge Wilson 	ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
57513baa08fcSek 	if (l2arc)
5752dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
57535602294fSDan Kimmel 	if (ARC_BUF_COMPRESSED(buf)) {
5754adaec86aSMatthew Ahrens 		/*
5755adaec86aSMatthew Ahrens 		 * We're writing a pre-compressed buffer.  Make the
5756adaec86aSMatthew Ahrens 		 * compression algorithm requested by the zio_prop_t match
5757adaec86aSMatthew Ahrens 		 * the pre-compressed buffer's compression algorithm.
5758adaec86aSMatthew Ahrens 		 */
5759adaec86aSMatthew Ahrens 		localprop.zp_compress = HDR_GET_COMPRESS(hdr);
5760adaec86aSMatthew Ahrens 
57615602294fSDan Kimmel 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, arc_buf_size(buf));
57625602294fSDan Kimmel 		zio_flags |= ZIO_FLAG_RAW;
57635602294fSDan Kimmel 	}
5764c717a561Smaybee 	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
5765c717a561Smaybee 	callback->awcb_ready = ready;
57668df0bcf0SPaul Dagnelie 	callback->awcb_children_ready = children_ready;
576769962b56SMatthew Ahrens 	callback->awcb_physdone = physdone;
5768c717a561Smaybee 	callback->awcb_done = done;
5769c717a561Smaybee 	callback->awcb_private = private;
5770c717a561Smaybee 	callback->awcb_buf = buf;
5771088f3894Sahrens 
5772dcbf3bd6SGeorge Wilson 	/*
5773770499e1SDan Kimmel 	 * The hdr's b_pabd is now stale, free it now. A new data block
5774dcbf3bd6SGeorge Wilson 	 * will be allocated when the zio pipeline calls arc_write_ready().
5775dcbf3bd6SGeorge Wilson 	 */
5776770499e1SDan Kimmel 	if (hdr->b_l1hdr.b_pabd != NULL) {
5777dcbf3bd6SGeorge Wilson 		/*
5778dcbf3bd6SGeorge Wilson 		 * If the buf is currently sharing the data block with
5779dcbf3bd6SGeorge Wilson 		 * the hdr then we need to break that relationship here.
5780dcbf3bd6SGeorge Wilson 		 * The hdr will remain with a NULL data pointer and the
5781dcbf3bd6SGeorge Wilson 		 * buf will take sole ownership of the block.
5782dcbf3bd6SGeorge Wilson 		 */
5783dcbf3bd6SGeorge Wilson 		if (arc_buf_is_shared(buf)) {
5784dcbf3bd6SGeorge Wilson 			arc_unshare_buf(hdr, buf);
5785dcbf3bd6SGeorge Wilson 		} else {
5786770499e1SDan Kimmel 			arc_hdr_free_pabd(hdr);
5787dcbf3bd6SGeorge Wilson 		}
5788dcbf3bd6SGeorge Wilson 		VERIFY3P(buf->b_data, !=, NULL);
5789dcbf3bd6SGeorge Wilson 		arc_hdr_set_compress(hdr, ZIO_COMPRESS_OFF);
5790dcbf3bd6SGeorge Wilson 	}
5791dcbf3bd6SGeorge Wilson 	ASSERT(!arc_buf_is_shared(buf));
5792770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
5793dcbf3bd6SGeorge Wilson 
5794770499e1SDan Kimmel 	zio = zio_write(pio, spa, txg, bp,
5795770499e1SDan Kimmel 	    abd_get_from_buf(buf->b_data, HDR_GET_LSIZE(hdr)),
5796adaec86aSMatthew Ahrens 	    HDR_GET_LSIZE(hdr), arc_buf_size(buf), &localprop, arc_write_ready,
57978df0bcf0SPaul Dagnelie 	    (children_ready != NULL) ? arc_write_children_ready : NULL,
57988df0bcf0SPaul Dagnelie 	    arc_write_physdone, arc_write_done, callback,
579969962b56SMatthew Ahrens 	    priority, zio_flags, zb);
5800fa9e4066Sahrens 
5801c717a561Smaybee 	return (zio);
5802fa9e4066Sahrens }
5803fa9e4066Sahrens 
58041ab7f2deSmaybee static int
580569962b56SMatthew Ahrens arc_memory_throttle(uint64_t reserve, uint64_t txg)
58061ab7f2deSmaybee {
58071ab7f2deSmaybee #ifdef _KERNEL
58081ab7f2deSmaybee 	uint64_t available_memory = ptob(freemem);
58091ab7f2deSmaybee 	static uint64_t page_load = 0;
58101ab7f2deSmaybee 	static uint64_t last_txg = 0;
58111ab7f2deSmaybee 
58121ab7f2deSmaybee #if defined(__i386)
58131ab7f2deSmaybee 	available_memory =
58141ab7f2deSmaybee 	    MIN(available_memory, vmem_size(heap_arena, VMEM_FREE));
58151ab7f2deSmaybee #endif
581669962b56SMatthew Ahrens 
581769962b56SMatthew Ahrens 	if (freemem > physmem * arc_lotsfree_percent / 100)
58181ab7f2deSmaybee 		return (0);
58191ab7f2deSmaybee 
58201ab7f2deSmaybee 	if (txg > last_txg) {
58211ab7f2deSmaybee 		last_txg = txg;
58221ab7f2deSmaybee 		page_load = 0;
58231ab7f2deSmaybee 	}
58241ab7f2deSmaybee 	/*
58251ab7f2deSmaybee 	 * If we are in pageout, we know that memory is already tight,
58261ab7f2deSmaybee 	 * the arc is already going to be evicting, so we just want to
58271ab7f2deSmaybee 	 * continue to let page writes occur as quickly as possible.
58281ab7f2deSmaybee 	 */
58291ab7f2deSmaybee 	if (curproc == proc_pageout) {
58301ab7f2deSmaybee 		if (page_load > MAX(ptob(minfree), available_memory) / 4)
5831be6fd75aSMatthew Ahrens 			return (SET_ERROR(ERESTART));
58321ab7f2deSmaybee 		/* Note: reserve is inflated, so we deflate */
58331ab7f2deSmaybee 		page_load += reserve / 8;
58341ab7f2deSmaybee 		return (0);
58351ab7f2deSmaybee 	} else if (page_load > 0 && arc_reclaim_needed()) {
58361ab7f2deSmaybee 		/* memory is low, delay before restarting */
58371ab7f2deSmaybee 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
5838be6fd75aSMatthew Ahrens 		return (SET_ERROR(EAGAIN));
58391ab7f2deSmaybee 	}
58401ab7f2deSmaybee 	page_load = 0;
58411ab7f2deSmaybee #endif
58421ab7f2deSmaybee 	return (0);
58431ab7f2deSmaybee }
58441ab7f2deSmaybee 
5845fa9e4066Sahrens void
58461ab7f2deSmaybee arc_tempreserve_clear(uint64_t reserve)
5847fa9e4066Sahrens {
58481ab7f2deSmaybee 	atomic_add_64(&arc_tempreserve, -reserve);
5849fa9e4066Sahrens 	ASSERT((int64_t)arc_tempreserve >= 0);
5850fa9e4066Sahrens }
5851fa9e4066Sahrens 
5852fa9e4066Sahrens int
58531ab7f2deSmaybee arc_tempreserve_space(uint64_t reserve, uint64_t txg)
5854fa9e4066Sahrens {
58551ab7f2deSmaybee 	int error;
58562fdbea25SAleksandr Guzovskiy 	uint64_t anon_size;
58571ab7f2deSmaybee 
58581ab7f2deSmaybee 	if (reserve > arc_c/4 && !arc_no_grow)
58591ab7f2deSmaybee 		arc_c = MIN(arc_c_max, reserve * 4);
58601ab7f2deSmaybee 	if (reserve > arc_c)
5861be6fd75aSMatthew Ahrens 		return (SET_ERROR(ENOMEM));
5862112fe045Smaybee 
58632fdbea25SAleksandr Guzovskiy 	/*
58642fdbea25SAleksandr Guzovskiy 	 * Don't count loaned bufs as in flight dirty data to prevent long
58652fdbea25SAleksandr Guzovskiy 	 * network delays from blocking transactions that are ready to be
58662fdbea25SAleksandr Guzovskiy 	 * assigned to a txg.
58672fdbea25SAleksandr Guzovskiy 	 */
58685602294fSDan Kimmel 
58695602294fSDan Kimmel 	/* assert that it has not wrapped around */
58705602294fSDan Kimmel 	ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
58715602294fSDan Kimmel 
58722fd872a7SPrakash Surya 	anon_size = MAX((int64_t)(refcount_count(&arc_anon->arcs_size) -
58732fd872a7SPrakash Surya 	    arc_loaned_bytes), 0);
58742fdbea25SAleksandr Guzovskiy 
58751ab7f2deSmaybee 	/*
58761ab7f2deSmaybee 	 * Writes will, almost always, require additional memory allocations
5877f7170741SWill Andrews 	 * in order to compress/encrypt/etc the data.  We therefore need to
58781ab7f2deSmaybee 	 * make sure that there is sufficient available memory for this.
58791ab7f2deSmaybee 	 */
588069962b56SMatthew Ahrens 	error = arc_memory_throttle(reserve, txg);
588169962b56SMatthew Ahrens 	if (error != 0)
58821ab7f2deSmaybee 		return (error);
58831ab7f2deSmaybee 
5884fa9e4066Sahrens 	/*
5885112fe045Smaybee 	 * Throttle writes when the amount of dirty data in the cache
5886112fe045Smaybee 	 * gets too large.  We try to keep the cache less than half full
5887112fe045Smaybee 	 * of dirty blocks so that our sync times don't grow too large.
5888112fe045Smaybee 	 * Note: if two requests come in concurrently, we might let them
5889112fe045Smaybee 	 * both succeed, when one of them should fail.  Not a huge deal.
5890fa9e4066Sahrens 	 */
58912fdbea25SAleksandr Guzovskiy 
58922fdbea25SAleksandr Guzovskiy 	if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
58932fdbea25SAleksandr Guzovskiy 	    anon_size > arc_c / 4) {
5894dcbf3bd6SGeorge Wilson 		uint64_t meta_esize =
5895dcbf3bd6SGeorge Wilson 		    refcount_count(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
5896dcbf3bd6SGeorge Wilson 		uint64_t data_esize =
5897dcbf3bd6SGeorge Wilson 		    refcount_count(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
58980e8c6158Smaybee 		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
58990e8c6158Smaybee 		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
5900dcbf3bd6SGeorge Wilson 		    arc_tempreserve >> 10, meta_esize >> 10,
5901dcbf3bd6SGeorge Wilson 		    data_esize >> 10, reserve >> 10, arc_c >> 10);
5902be6fd75aSMatthew Ahrens 		return (SET_ERROR(ERESTART));
5903fa9e4066Sahrens 	}
59041ab7f2deSmaybee 	atomic_add_64(&arc_tempreserve, reserve);
5905fa9e4066Sahrens 	return (0);
5906fa9e4066Sahrens }
5907fa9e4066Sahrens 
59084076b1bfSPrakash Surya static void
59094076b1bfSPrakash Surya arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
59104076b1bfSPrakash Surya     kstat_named_t *evict_data, kstat_named_t *evict_metadata)
59114076b1bfSPrakash Surya {
59122fd872a7SPrakash Surya 	size->value.ui64 = refcount_count(&state->arcs_size);
5913dcbf3bd6SGeorge Wilson 	evict_data->value.ui64 =
5914dcbf3bd6SGeorge Wilson 	    refcount_count(&state->arcs_esize[ARC_BUFC_DATA]);
5915dcbf3bd6SGeorge Wilson 	evict_metadata->value.ui64 =
5916dcbf3bd6SGeorge Wilson 	    refcount_count(&state->arcs_esize[ARC_BUFC_METADATA]);
59174076b1bfSPrakash Surya }
59184076b1bfSPrakash Surya 
59194076b1bfSPrakash Surya static int
59204076b1bfSPrakash Surya arc_kstat_update(kstat_t *ksp, int rw)
59214076b1bfSPrakash Surya {
59224076b1bfSPrakash Surya 	arc_stats_t *as = ksp->ks_data;
59234076b1bfSPrakash Surya 
59244076b1bfSPrakash Surya 	if (rw == KSTAT_WRITE) {
59254076b1bfSPrakash Surya 		return (EACCES);
59264076b1bfSPrakash Surya 	} else {
59274076b1bfSPrakash Surya 		arc_kstat_update_state(arc_anon,
59284076b1bfSPrakash Surya 		    &as->arcstat_anon_size,
59294076b1bfSPrakash Surya 		    &as->arcstat_anon_evictable_data,
59304076b1bfSPrakash Surya 		    &as->arcstat_anon_evictable_metadata);
59314076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mru,
59324076b1bfSPrakash Surya 		    &as->arcstat_mru_size,
59334076b1bfSPrakash Surya 		    &as->arcstat_mru_evictable_data,
59344076b1bfSPrakash Surya 		    &as->arcstat_mru_evictable_metadata);
59354076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mru_ghost,
59364076b1bfSPrakash Surya 		    &as->arcstat_mru_ghost_size,
59374076b1bfSPrakash Surya 		    &as->arcstat_mru_ghost_evictable_data,
59384076b1bfSPrakash Surya 		    &as->arcstat_mru_ghost_evictable_metadata);
59394076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mfu,
59404076b1bfSPrakash Surya 		    &as->arcstat_mfu_size,
59414076b1bfSPrakash Surya 		    &as->arcstat_mfu_evictable_data,
59424076b1bfSPrakash Surya 		    &as->arcstat_mfu_evictable_metadata);
59434076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mfu_ghost,
59444076b1bfSPrakash Surya 		    &as->arcstat_mfu_ghost_size,
59454076b1bfSPrakash Surya 		    &as->arcstat_mfu_ghost_evictable_data,
59464076b1bfSPrakash Surya 		    &as->arcstat_mfu_ghost_evictable_metadata);
59473a2d8a1bSPaul Dagnelie 
59483a2d8a1bSPaul Dagnelie 		ARCSTAT(arcstat_size) = aggsum_value(&arc_size);
59493a2d8a1bSPaul Dagnelie 		ARCSTAT(arcstat_meta_used) = aggsum_value(&arc_meta_used);
59503a2d8a1bSPaul Dagnelie 		ARCSTAT(arcstat_data_size) = aggsum_value(&astat_data_size);
59513a2d8a1bSPaul Dagnelie 		ARCSTAT(arcstat_metadata_size) =
59523a2d8a1bSPaul Dagnelie 		    aggsum_value(&astat_metadata_size);
59533a2d8a1bSPaul Dagnelie 		ARCSTAT(arcstat_hdr_size) = aggsum_value(&astat_hdr_size);
59543a2d8a1bSPaul Dagnelie 		ARCSTAT(arcstat_other_size) = aggsum_value(&astat_other_size);
59553a2d8a1bSPaul Dagnelie 		ARCSTAT(arcstat_l2_hdr_size) = aggsum_value(&astat_l2_hdr_size);
59564076b1bfSPrakash Surya 	}
59574076b1bfSPrakash Surya 
59584076b1bfSPrakash Surya 	return (0);
59594076b1bfSPrakash Surya }
59604076b1bfSPrakash Surya 
5961dcbf3bd6SGeorge Wilson /*
5962dcbf3bd6SGeorge Wilson  * This function *must* return indices evenly distributed between all
5963dcbf3bd6SGeorge Wilson  * sublists of the multilist. This is needed due to how the ARC eviction
5964dcbf3bd6SGeorge Wilson  * code is laid out; arc_evict_state() assumes ARC buffers are evenly
5965dcbf3bd6SGeorge Wilson  * distributed between all sublists and uses this assumption when
5966dcbf3bd6SGeorge Wilson  * deciding which sublist to evict from and how much to evict from it.
5967dcbf3bd6SGeorge Wilson  */
5968dcbf3bd6SGeorge Wilson unsigned int
5969dcbf3bd6SGeorge Wilson arc_state_multilist_index_func(multilist_t *ml, void *obj)
5970dcbf3bd6SGeorge Wilson {
5971dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = obj;
5972dcbf3bd6SGeorge Wilson 
5973dcbf3bd6SGeorge Wilson 	/*
5974dcbf3bd6SGeorge Wilson 	 * We rely on b_dva to generate evenly distributed index
5975dcbf3bd6SGeorge Wilson 	 * numbers using buf_hash below. So, as an added precaution,
5976dcbf3bd6SGeorge Wilson 	 * let's make sure we never add empty buffers to the arc lists.
5977dcbf3bd6SGeorge Wilson 	 */
5978dcbf3bd6SGeorge Wilson 	ASSERT(!HDR_EMPTY(hdr));
5979dcbf3bd6SGeorge Wilson 
5980dcbf3bd6SGeorge Wilson 	/*
5981dcbf3bd6SGeorge Wilson 	 * The assumption here, is the hash value for a given
5982dcbf3bd6SGeorge Wilson 	 * arc_buf_hdr_t will remain constant throughout it's lifetime
5983dcbf3bd6SGeorge Wilson 	 * (i.e. it's b_spa, b_dva, and b_birth fields don't change).
5984dcbf3bd6SGeorge Wilson 	 * Thus, we don't need to store the header's sublist index
5985dcbf3bd6SGeorge Wilson 	 * on insertion, as this index can be recalculated on removal.
5986dcbf3bd6SGeorge Wilson 	 *
5987dcbf3bd6SGeorge Wilson 	 * Also, the low order bits of the hash value are thought to be
5988dcbf3bd6SGeorge Wilson 	 * distributed evenly. Otherwise, in the case that the multilist
5989dcbf3bd6SGeorge Wilson 	 * has a power of two number of sublists, each sublists' usage
5990dcbf3bd6SGeorge Wilson 	 * would not be evenly distributed.
5991dcbf3bd6SGeorge Wilson 	 */
5992dcbf3bd6SGeorge Wilson 	return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
5993dcbf3bd6SGeorge Wilson 	    multilist_get_num_sublists(ml));
5994dcbf3bd6SGeorge Wilson }
5995dcbf3bd6SGeorge Wilson 
5996dcbf3bd6SGeorge Wilson static void
5997dcbf3bd6SGeorge Wilson arc_state_init(void)
5998dcbf3bd6SGeorge Wilson {
5999dcbf3bd6SGeorge Wilson 	arc_anon = &ARC_anon;
6000dcbf3bd6SGeorge Wilson 	arc_mru = &ARC_mru;
6001dcbf3bd6SGeorge Wilson 	arc_mru_ghost = &ARC_mru_ghost;
6002dcbf3bd6SGeorge Wilson 	arc_mfu = &ARC_mfu;
6003dcbf3bd6SGeorge Wilson 	arc_mfu_ghost = &ARC_mfu_ghost;
6004dcbf3bd6SGeorge Wilson 	arc_l2c_only = &ARC_l2c_only;
6005dcbf3bd6SGeorge Wilson 
600694c2d0ebSMatthew Ahrens 	arc_mru->arcs_list[ARC_BUFC_METADATA] =
600794c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
6008dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
600910fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
601094c2d0ebSMatthew Ahrens 	arc_mru->arcs_list[ARC_BUFC_DATA] =
601194c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
6012dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
601310fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
601494c2d0ebSMatthew Ahrens 	arc_mru_ghost->arcs_list[ARC_BUFC_METADATA] =
601594c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
6016dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
601710fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
601894c2d0ebSMatthew Ahrens 	arc_mru_ghost->arcs_list[ARC_BUFC_DATA] =
601994c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
6020dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
602110fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
602294c2d0ebSMatthew Ahrens 	arc_mfu->arcs_list[ARC_BUFC_METADATA] =
602394c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
6024dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
602510fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
602694c2d0ebSMatthew Ahrens 	arc_mfu->arcs_list[ARC_BUFC_DATA] =
602794c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
6028dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
602910fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
603094c2d0ebSMatthew Ahrens 	arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA] =
603194c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
6032dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
603310fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
603494c2d0ebSMatthew Ahrens 	arc_mfu_ghost->arcs_list[ARC_BUFC_DATA] =
603594c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
6036dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
603710fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
603894c2d0ebSMatthew Ahrens 	arc_l2c_only->arcs_list[ARC_BUFC_METADATA] =
603994c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
6040dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
604110fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
604294c2d0ebSMatthew Ahrens 	arc_l2c_only->arcs_list[ARC_BUFC_DATA] =
604394c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
6044dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
604510fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
6046dcbf3bd6SGeorge Wilson 
6047dcbf3bd6SGeorge Wilson 	refcount_create(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6048dcbf3bd6SGeorge Wilson 	refcount_create(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6049dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
6050dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
6051dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
6052dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
6053dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
6054dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
6055dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
6056dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
6057dcbf3bd6SGeorge Wilson 	refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
6058dcbf3bd6SGeorge Wilson 	refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
6059dcbf3bd6SGeorge Wilson 
6060dcbf3bd6SGeorge Wilson 	refcount_create(&arc_anon->arcs_size);
6061dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru->arcs_size);
6062dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru_ghost->arcs_size);
6063dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu->arcs_size);
6064dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu_ghost->arcs_size);
6065dcbf3bd6SGeorge Wilson 	refcount_create(&arc_l2c_only->arcs_size);
60663a2d8a1bSPaul Dagnelie 
60673a2d8a1bSPaul Dagnelie 	aggsum_init(&arc_meta_used, 0);
60683a2d8a1bSPaul Dagnelie 	aggsum_init(&arc_size, 0);
60693a2d8a1bSPaul Dagnelie 	aggsum_init(&astat_data_size, 0);
60703a2d8a1bSPaul Dagnelie 	aggsum_init(&astat_metadata_size, 0);
60713a2d8a1bSPaul Dagnelie 	aggsum_init(&astat_hdr_size, 0);
60723a2d8a1bSPaul Dagnelie 	aggsum_init(&astat_other_size, 0);
60733a2d8a1bSPaul Dagnelie 	aggsum_init(&astat_l2_hdr_size, 0);
6074dcbf3bd6SGeorge Wilson }
6075dcbf3bd6SGeorge Wilson 
6076dcbf3bd6SGeorge Wilson static void
6077dcbf3bd6SGeorge Wilson arc_state_fini(void)
6078dcbf3bd6SGeorge Wilson {
6079dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6080dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6081dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
6082dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
6083dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
6084dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
6085dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
6086dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
6087dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
6088dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
6089dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
6090dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
6091dcbf3bd6SGeorge Wilson 
6092dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_anon->arcs_size);
6093dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru->arcs_size);
6094dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru_ghost->arcs_size);
6095dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu->arcs_size);
6096dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu_ghost->arcs_size);
6097dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_l2c_only->arcs_size);
6098dcbf3bd6SGeorge Wilson 
609994c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_METADATA]);
610094c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
610194c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_METADATA]);
610294c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
610394c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_DATA]);
610494c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
610594c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_DATA]);
610694c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
6107dcbf3bd6SGeorge Wilson }
6108dcbf3bd6SGeorge Wilson 
6109dcbf3bd6SGeorge Wilson uint64_t
6110dcbf3bd6SGeorge Wilson arc_max_bytes(void)
6111244781f1SPrakash Surya {
6112dcbf3bd6SGeorge Wilson 	return (arc_c_max);
6113244781f1SPrakash Surya }
6114244781f1SPrakash Surya 
6115fa9e4066Sahrens void
6116fa9e4066Sahrens arc_init(void)
6117fa9e4066Sahrens {
61182ec99e3eSMatthew Ahrens 	/*
61192ec99e3eSMatthew Ahrens 	 * allmem is "all memory that we could possibly use".
61202ec99e3eSMatthew Ahrens 	 */
61212ec99e3eSMatthew Ahrens #ifdef _KERNEL
61222ec99e3eSMatthew Ahrens 	uint64_t allmem = ptob(physmem - swapfs_minfree);
61232ec99e3eSMatthew Ahrens #else
61242ec99e3eSMatthew Ahrens 	uint64_t allmem = (physmem * PAGESIZE) / 2;
61252ec99e3eSMatthew Ahrens #endif
6126*de753e34SBrad Lewis 	mutex_init(&arc_adjust_lock, NULL, MUTEX_DEFAULT, NULL);
6127*de753e34SBrad Lewis 	cv_init(&arc_adjust_waiters_cv, NULL, CV_DEFAULT, NULL);
6128244781f1SPrakash Surya 
612913506d1eSmaybee 	/* Convert seconds to clock ticks */
6130b19a79ecSperrin 	arc_min_prefetch_lifespan = 1 * hz;
613113506d1eSmaybee 
6132112fe045Smaybee 	/* set min cache to 1/32 of all memory, or 64MB, whichever is more */
61332ec99e3eSMatthew Ahrens 	arc_c_min = MAX(allmem / 32, 64 << 20);
6134112fe045Smaybee 	/* set max to 3/4 of all memory, or all but 1GB, whichever is more */
61352ec99e3eSMatthew Ahrens 	if (allmem >= 1 << 30)
61362ec99e3eSMatthew Ahrens 		arc_c_max = allmem - (1 << 30);
6137fa9e4066Sahrens 	else
613844cb6abcSbmc 		arc_c_max = arc_c_min;
61392ec99e3eSMatthew Ahrens 	arc_c_max = MAX(allmem * 3 / 4, arc_c_max);
6140a2eea2e1Sahrens 
61418fe00bfbSMatthew Ahrens 	/*
61428fe00bfbSMatthew Ahrens 	 * In userland, there's only the memory pressure that we artificially
61438fe00bfbSMatthew Ahrens 	 * create (see arc_available_memory()).  Don't let arc_c get too
61448fe00bfbSMatthew Ahrens 	 * small, because it can cause transactions to be larger than
61458fe00bfbSMatthew Ahrens 	 * arc_c, causing arc_tempreserve_space() to fail.
61468fe00bfbSMatthew Ahrens 	 */
61478fe00bfbSMatthew Ahrens #ifndef _KERNEL
61488fe00bfbSMatthew Ahrens 	arc_c_min = arc_c_max / 2;
61498fe00bfbSMatthew Ahrens #endif
61508fe00bfbSMatthew Ahrens 
6151a2eea2e1Sahrens 	/*
6152a2eea2e1Sahrens 	 * Allow the tunables to override our calculations if they are
6153a2eea2e1Sahrens 	 * reasonable (ie. over 64MB)
6154a2eea2e1Sahrens 	 */
6155e5961710SMatthew Ahrens 	if (zfs_arc_max > 64 << 20 && zfs_arc_max < allmem) {
615644cb6abcSbmc 		arc_c_max = zfs_arc_max;
6157e5961710SMatthew Ahrens 		arc_c_min = MIN(arc_c_min, arc_c_max);
6158e5961710SMatthew Ahrens 	}
61592ec99e3eSMatthew Ahrens 	if (zfs_arc_min > 64 << 20 && zfs_arc_min <= arc_c_max)
616044cb6abcSbmc 		arc_c_min = zfs_arc_min;
6161a2eea2e1Sahrens 
616244cb6abcSbmc 	arc_c = arc_c_max;
616344cb6abcSbmc 	arc_p = (arc_c >> 1);
6164fa9e4066Sahrens 
61650e8c6158Smaybee 	/* limit meta-data to 1/4 of the arc capacity */
61660e8c6158Smaybee 	arc_meta_limit = arc_c_max / 4;
61671116048bSek 
6168af868f46SMatthew Ahrens #ifdef _KERNEL
6169af868f46SMatthew Ahrens 	/*
6170af868f46SMatthew Ahrens 	 * Metadata is stored in the kernel's heap.  Don't let us
6171af868f46SMatthew Ahrens 	 * use more than half the heap for the ARC.
6172af868f46SMatthew Ahrens 	 */
6173af868f46SMatthew Ahrens 	arc_meta_limit = MIN(arc_meta_limit,
6174af868f46SMatthew Ahrens 	    vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 2);
6175af868f46SMatthew Ahrens #endif
6176af868f46SMatthew Ahrens 
61771116048bSek 	/* Allow the tunable to override if it is reasonable */
61781116048bSek 	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
61791116048bSek 		arc_meta_limit = zfs_arc_meta_limit;
61801116048bSek 
61810e8c6158Smaybee 	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
61820e8c6158Smaybee 		arc_c_min = arc_meta_limit / 2;
61830e8c6158Smaybee 
61843a5286a1SMatthew Ahrens 	if (zfs_arc_meta_min > 0) {
61853a5286a1SMatthew Ahrens 		arc_meta_min = zfs_arc_meta_min;
61863a5286a1SMatthew Ahrens 	} else {
61873a5286a1SMatthew Ahrens 		arc_meta_min = arc_c_min / 2;
61883a5286a1SMatthew Ahrens 	}
61893a5286a1SMatthew Ahrens 
61905a98e54bSBrendan Gregg - Sun Microsystems 	if (zfs_arc_grow_retry > 0)
61915a98e54bSBrendan Gregg - Sun Microsystems 		arc_grow_retry = zfs_arc_grow_retry;
61925a98e54bSBrendan Gregg - Sun Microsystems 
61935a98e54bSBrendan Gregg - Sun Microsystems 	if (zfs_arc_shrink_shift > 0)
61945a98e54bSBrendan Gregg - Sun Microsystems 		arc_shrink_shift = zfs_arc_shrink_shift;
61955a98e54bSBrendan Gregg - Sun Microsystems 
61962ec99e3eSMatthew Ahrens 	/*
61972ec99e3eSMatthew Ahrens 	 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
61982ec99e3eSMatthew Ahrens 	 */
61992ec99e3eSMatthew Ahrens 	if (arc_no_grow_shift >= arc_shrink_shift)
62002ec99e3eSMatthew Ahrens 		arc_no_grow_shift = arc_shrink_shift - 1;
62012ec99e3eSMatthew Ahrens 
62025a98e54bSBrendan Gregg - Sun Microsystems 	if (zfs_arc_p_min_shift > 0)
62035a98e54bSBrendan Gregg - Sun Microsystems 		arc_p_min_shift = zfs_arc_p_min_shift;
62045a98e54bSBrendan Gregg - Sun Microsystems 
6205fa9e4066Sahrens 	/* if kmem_flags are set, lets try to use less memory */
6206fa9e4066Sahrens 	if (kmem_debugging())
620744cb6abcSbmc 		arc_c = arc_c / 2;
620844cb6abcSbmc 	if (arc_c < arc_c_min)
620944cb6abcSbmc 		arc_c = arc_c_min;
621044cb6abcSbmc 
6211dcbf3bd6SGeorge Wilson 	arc_state_init();
6212fa9e4066Sahrens 
6213*de753e34SBrad Lewis 	/*
6214*de753e34SBrad Lewis 	 * The arc must be "uninitialized", so that hdr_recl() (which is
6215*de753e34SBrad Lewis 	 * registered by buf_init()) will not access arc_reap_zthr before
6216*de753e34SBrad Lewis 	 * it is created.
6217*de753e34SBrad Lewis 	 */
6218*de753e34SBrad Lewis 	ASSERT(!arc_initialized);
6219*de753e34SBrad Lewis 	buf_init();
6220fa9e4066Sahrens 
622144cb6abcSbmc 	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
622244cb6abcSbmc 	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
622344cb6abcSbmc 
622444cb6abcSbmc 	if (arc_ksp != NULL) {
622544cb6abcSbmc 		arc_ksp->ks_data = &arc_stats;
62264076b1bfSPrakash Surya 		arc_ksp->ks_update = arc_kstat_update;
622744cb6abcSbmc 		kstat_install(arc_ksp);
622844cb6abcSbmc 	}
622944cb6abcSbmc 
6230*de753e34SBrad Lewis 	arc_adjust_zthr = zthr_create(arc_adjust_cb_check,
6231*de753e34SBrad Lewis 	    arc_adjust_cb, NULL);
6232*de753e34SBrad Lewis 	arc_reap_zthr = zthr_create_timer(arc_reap_cb_check,
6233*de753e34SBrad Lewis 	    arc_reap_cb, NULL, SEC2NSEC(1));
623449e3519aSmaybee 
6235*de753e34SBrad Lewis 	arc_initialized = B_TRUE;
62363a737e0dSbrendan 	arc_warm = B_FALSE;
62371ab7f2deSmaybee 
623869962b56SMatthew Ahrens 	/*
623969962b56SMatthew Ahrens 	 * Calculate maximum amount of dirty data per pool.
624069962b56SMatthew Ahrens 	 *
624169962b56SMatthew Ahrens 	 * If it has been set by /etc/system, take that.
624269962b56SMatthew Ahrens 	 * Otherwise, use a percentage of physical memory defined by
624369962b56SMatthew Ahrens 	 * zfs_dirty_data_max_percent (default 10%) with a cap at
624469962b56SMatthew Ahrens 	 * zfs_dirty_data_max_max (default 4GB).
624569962b56SMatthew Ahrens 	 */
624669962b56SMatthew Ahrens 	if (zfs_dirty_data_max == 0) {
624769962b56SMatthew Ahrens 		zfs_dirty_data_max = physmem * PAGESIZE *
624869962b56SMatthew Ahrens 		    zfs_dirty_data_max_percent / 100;
624969962b56SMatthew Ahrens 		zfs_dirty_data_max = MIN(zfs_dirty_data_max,
625069962b56SMatthew Ahrens 		    zfs_dirty_data_max_max);
625169962b56SMatthew Ahrens 	}
6252fa9e4066Sahrens }
6253fa9e4066Sahrens 
6254fa9e4066Sahrens void
6255fa9e4066Sahrens arc_fini(void)
6256fa9e4066Sahrens {
6257dcbf3bd6SGeorge Wilson 	/* Use B_TRUE to ensure *all* buffers are evicted */
6258dcbf3bd6SGeorge Wilson 	arc_flush(NULL, B_TRUE);
6259fa9e4066Sahrens 
6260*de753e34SBrad Lewis 	arc_initialized = B_FALSE;
6261fa9e4066Sahrens 
626244cb6abcSbmc 	if (arc_ksp != NULL) {
626344cb6abcSbmc 		kstat_delete(arc_ksp);
626444cb6abcSbmc 		arc_ksp = NULL;
626544cb6abcSbmc 	}
626644cb6abcSbmc 
6267*de753e34SBrad Lewis 	(void) zthr_cancel(arc_adjust_zthr);
6268*de753e34SBrad Lewis 	zthr_destroy(arc_adjust_zthr);
6269*de753e34SBrad Lewis 
6270*de753e34SBrad Lewis 	(void) zthr_cancel(arc_reap_zthr);
6271*de753e34SBrad Lewis 	zthr_destroy(arc_reap_zthr);
6272*de753e34SBrad Lewis 
6273*de753e34SBrad Lewis 	mutex_destroy(&arc_adjust_lock);
6274*de753e34SBrad Lewis 	cv_destroy(&arc_adjust_waiters_cv);
6275244781f1SPrakash Surya 
6276dcbf3bd6SGeorge Wilson 	arc_state_fini();
6277fa9e4066Sahrens 	buf_fini();
62782fdbea25SAleksandr Guzovskiy 
627989c86e32SChris Williamson 	ASSERT0(arc_loaned_bytes);
6280fa9e4066Sahrens }
6281fa94a07fSbrendan 
6282fa94a07fSbrendan /*
6283fa94a07fSbrendan  * Level 2 ARC
6284fa94a07fSbrendan  *
6285fa94a07fSbrendan  * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
6286fa94a07fSbrendan  * It uses dedicated storage devices to hold cached data, which are populated
6287fa94a07fSbrendan  * using large infrequent writes.  The main role of this cache is to boost
6288fa94a07fSbrendan  * the performance of random read workloads.  The intended L2ARC devices
6289fa94a07fSbrendan  * include short-stroked disks, solid state disks, and other media with
6290fa94a07fSbrendan  * substantially faster read latency than disk.
6291fa94a07fSbrendan  *
6292fa94a07fSbrendan  *                 +-----------------------+
6293fa94a07fSbrendan  *                 |         ARC           |
6294fa94a07fSbrendan  *                 +-----------------------+
6295fa94a07fSbrendan  *                    |         ^     ^
6296fa94a07fSbrendan  *                    |         |     |
6297fa94a07fSbrendan  *      l2arc_feed_thread()    arc_read()
6298fa94a07fSbrendan  *                    |         |     |
6299fa94a07fSbrendan  *                    |  l2arc read   |
6300fa94a07fSbrendan  *                    V         |     |
6301fa94a07fSbrendan  *               +---------------+    |
6302fa94a07fSbrendan  *               |     L2ARC     |    |
6303fa94a07fSbrendan  *               +---------------+    |
6304fa94a07fSbrendan  *                   |    ^           |
6305fa94a07fSbrendan  *          l2arc_write() |           |
6306fa94a07fSbrendan  *                   |    |           |
6307fa94a07fSbrendan  *                   V    |           |
6308fa94a07fSbrendan  *                 +-------+      +-------+
6309fa94a07fSbrendan  *                 | vdev  |      | vdev  |
6310fa94a07fSbrendan  *                 | cache |      | cache |
6311fa94a07fSbrendan  *                 +-------+      +-------+
6312fa94a07fSbrendan  *                 +=========+     .-----.
6313fa94a07fSbrendan  *                 :  L2ARC  :    |-_____-|
6314fa94a07fSbrendan  *                 : devices :    | Disks |
6315fa94a07fSbrendan  *                 +=========+    `-_____-'
6316fa94a07fSbrendan  *
6317fa94a07fSbrendan  * Read requests are satisfied from the following sources, in order:
6318fa94a07fSbrendan  *
6319fa94a07fSbrendan  *	1) ARC
6320fa94a07fSbrendan  *	2) vdev cache of L2ARC devices
6321fa94a07fSbrendan  *	3) L2ARC devices
6322fa94a07fSbrendan  *	4) vdev cache of disks
6323fa94a07fSbrendan  *	5) disks
6324fa94a07fSbrendan  *
6325fa94a07fSbrendan  * Some L2ARC device types exhibit extremely slow write performance.
6326fa94a07fSbrendan  * To accommodate for this there are some significant differences between
6327fa94a07fSbrendan  * the L2ARC and traditional cache design:
6328fa94a07fSbrendan  *
6329fa94a07fSbrendan  * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
6330fa94a07fSbrendan  * the ARC behave as usual, freeing buffers and placing headers on ghost
6331fa94a07fSbrendan  * lists.  The ARC does not send buffers to the L2ARC during eviction as
6332fa94a07fSbrendan  * this would add inflated write latencies for all ARC memory pressure.
6333fa94a07fSbrendan  *
6334fa94a07fSbrendan  * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
6335fa94a07fSbrendan  * It does this by periodically scanning buffers from the eviction-end of
6336fa94a07fSbrendan  * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
6337aad02571SSaso Kiselkov  * not already there. It scans until a headroom of buffers is satisfied,
6338aad02571SSaso Kiselkov  * which itself is a buffer for ARC eviction. If a compressible buffer is
6339aad02571SSaso Kiselkov  * found during scanning and selected for writing to an L2ARC device, we
6340aad02571SSaso Kiselkov  * temporarily boost scanning headroom during the next scan cycle to make
6341aad02571SSaso Kiselkov  * sure we adapt to compression effects (which might significantly reduce
6342aad02571SSaso Kiselkov  * the data volume we write to L2ARC). The thread that does this is
6343fa94a07fSbrendan  * l2arc_feed_thread(), illustrated below; example sizes are included to
6344fa94a07fSbrendan  * provide a better sense of ratio than this diagram:
6345fa94a07fSbrendan  *
6346fa94a07fSbrendan  *	       head -->                        tail
6347fa94a07fSbrendan  *	        +---------------------+----------+
6348fa94a07fSbrendan  *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
6349fa94a07fSbrendan  *	        +---------------------+----------+   |   o L2ARC eligible
6350fa94a07fSbrendan  *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
6351fa94a07fSbrendan  *	        +---------------------+----------+   |
6352fa94a07fSbrendan  *	             15.9 Gbytes      ^ 32 Mbytes    |
6353fa94a07fSbrendan  *	                           headroom          |
6354fa94a07fSbrendan  *	                                      l2arc_feed_thread()
6355fa94a07fSbrendan  *	                                             |
6356fa94a07fSbrendan  *	                 l2arc write hand <--[oooo]--'
6357fa94a07fSbrendan  *	                         |           8 Mbyte
6358fa94a07fSbrendan  *	                         |          write max
6359fa94a07fSbrendan  *	                         V
6360fa94a07fSbrendan  *		  +==============================+
6361fa94a07fSbrendan  *	L2ARC dev |####|#|###|###|    |####| ... |
6362fa94a07fSbrendan  *	          +==============================+
6363fa94a07fSbrendan  *	                     32 Gbytes
6364fa94a07fSbrendan  *
6365fa94a07fSbrendan  * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
6366fa94a07fSbrendan  * evicted, then the L2ARC has cached a buffer much sooner than it probably
6367fa94a07fSbrendan  * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
6368fa94a07fSbrendan  * safe to say that this is an uncommon case, since buffers at the end of
6369fa94a07fSbrendan  * the ARC lists have moved there due to inactivity.
6370fa94a07fSbrendan  *
6371fa94a07fSbrendan  * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
6372fa94a07fSbrendan  * then the L2ARC simply misses copying some buffers.  This serves as a
6373fa94a07fSbrendan  * pressure valve to prevent heavy read workloads from both stalling the ARC
6374fa94a07fSbrendan  * with waits and clogging the L2ARC with writes.  This also helps prevent
6375fa94a07fSbrendan  * the potential for the L2ARC to churn if it attempts to cache content too
6376fa94a07fSbrendan  * quickly, such as during backups of the entire pool.
6377fa94a07fSbrendan  *
63783a737e0dSbrendan  * 5. After system boot and before the ARC has filled main memory, there are
63793a737e0dSbrendan  * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
63803a737e0dSbrendan  * lists can remain mostly static.  Instead of searching from tail of these
63813a737e0dSbrendan  * lists as pictured, the l2arc_feed_thread() will search from the list heads
63823a737e0dSbrendan  * for eligible buffers, greatly increasing its chance of finding them.
63833a737e0dSbrendan  *
63843a737e0dSbrendan  * The L2ARC device write speed is also boosted during this time so that
63853a737e0dSbrendan  * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
63863a737e0dSbrendan  * there are no L2ARC reads, and no fear of degrading read performance
63873a737e0dSbrendan  * through increased writes.
63883a737e0dSbrendan  *
63893a737e0dSbrendan  * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
6390fa94a07fSbrendan  * the vdev queue can aggregate them into larger and fewer writes.  Each
6391fa94a07fSbrendan  * device is written to in a rotor fashion, sweeping writes through
6392fa94a07fSbrendan  * available space then repeating.
6393fa94a07fSbrendan  *
63943a737e0dSbrendan  * 7. The L2ARC does not store dirty content.  It never needs to flush
6395fa94a07fSbrendan  * write buffers back to disk based storage.
6396fa94a07fSbrendan  *
63973a737e0dSbrendan  * 8. If an ARC buffer is written (and dirtied) which also exists in the
6398fa94a07fSbrendan  * L2ARC, the now stale L2ARC buffer is immediately dropped.
6399fa94a07fSbrendan  *
6400fa94a07fSbrendan  * The performance of the L2ARC can be tweaked by a number of tunables, which
6401fa94a07fSbrendan  * may be necessary for different workloads:
6402fa94a07fSbrendan  *
6403fa94a07fSbrendan  *	l2arc_write_max		max write bytes per interval
64043a737e0dSbrendan  *	l2arc_write_boost	extra write bytes during device warmup
6405fa94a07fSbrendan  *	l2arc_noprefetch	skip caching prefetched buffers
6406fa94a07fSbrendan  *	l2arc_headroom		number of max device writes to precache
6407aad02571SSaso Kiselkov  *	l2arc_headroom_boost	when we find compressed buffers during ARC
6408aad02571SSaso Kiselkov  *				scanning, we multiply headroom by this
6409aad02571SSaso Kiselkov  *				percentage factor for the next scan cycle,
6410aad02571SSaso Kiselkov  *				since more compressed buffers are likely to
6411aad02571SSaso Kiselkov  *				be present
6412fa94a07fSbrendan  *	l2arc_feed_secs		seconds between L2ARC writing
6413fa94a07fSbrendan  *
6414fa94a07fSbrendan  * Tunables may be removed or added as future performance improvements are
6415fa94a07fSbrendan  * integrated, and also may become zpool properties.
64165a98e54bSBrendan Gregg - Sun Microsystems  *
64175a98e54bSBrendan Gregg - Sun Microsystems  * There are three key functions that control how the L2ARC warms up:
64185a98e54bSBrendan Gregg - Sun Microsystems  *
64195a98e54bSBrendan Gregg - Sun Microsystems  *	l2arc_write_eligible()	check if a buffer is eligible to cache
64205a98e54bSBrendan Gregg - Sun Microsystems  *	l2arc_write_size()	calculate how much to write
64215a98e54bSBrendan Gregg - Sun Microsystems  *	l2arc_write_interval()	calculate sleep delay between writes
64225a98e54bSBrendan Gregg - Sun Microsystems  *
64235a98e54bSBrendan Gregg - Sun Microsystems  * These three functions determine what to write, how much, and how quickly
64245a98e54bSBrendan Gregg - Sun Microsystems  * to send writes.
6425fa94a07fSbrendan  */
6426fa94a07fSbrendan 
64275a98e54bSBrendan Gregg - Sun Microsystems static boolean_t
64287adb730bSGeorge Wilson l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
64295a98e54bSBrendan Gregg - Sun Microsystems {
64305a98e54bSBrendan Gregg - Sun Microsystems 	/*
64315a98e54bSBrendan Gregg - Sun Microsystems 	 * A buffer is *not* eligible for the L2ARC if it:
64325a98e54bSBrendan Gregg - Sun Microsystems 	 * 1. belongs to a different spa.
64335ea40c06SBrendan Gregg - Sun Microsystems 	 * 2. is already cached on the L2ARC.
64345ea40c06SBrendan Gregg - Sun Microsystems 	 * 3. has an I/O in progress (it may be an incomplete read).
64355ea40c06SBrendan Gregg - Sun Microsystems 	 * 4. is flagged not eligible (zfs property).
64365a98e54bSBrendan Gregg - Sun Microsystems 	 */
643789c86e32SChris Williamson 	if (hdr->b_spa != spa_guid || HDR_HAS_L2HDR(hdr) ||
64387adb730bSGeorge Wilson 	    HDR_IO_IN_PROGRESS(hdr) || !HDR_L2CACHE(hdr))
64395a98e54bSBrendan Gregg - Sun Microsystems 		return (B_FALSE);
64405a98e54bSBrendan Gregg - Sun Microsystems 
64415a98e54bSBrendan Gregg - Sun Microsystems 	return (B_TRUE);
64425a98e54bSBrendan Gregg - Sun Microsystems }
64435a98e54bSBrendan Gregg - Sun Microsystems 
64445a98e54bSBrendan Gregg - Sun Microsystems static uint64_t
6445aad02571SSaso Kiselkov l2arc_write_size(void)
64465a98e54bSBrendan Gregg - Sun Microsystems {
64475a98e54bSBrendan Gregg - Sun Microsystems 	uint64_t size;
64485a98e54bSBrendan Gregg - Sun Microsystems 
6449aad02571SSaso Kiselkov 	/*
6450aad02571SSaso Kiselkov 	 * Make sure our globals have meaningful values in case the user
6451aad02571SSaso Kiselkov 	 * altered them.
6452aad02571SSaso Kiselkov 	 */
6453aad02571SSaso Kiselkov 	size = l2arc_write_max;
6454aad02571SSaso Kiselkov 	if (size == 0) {
6455aad02571SSaso Kiselkov 		cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
6456aad02571SSaso Kiselkov 		    "be greater than zero, resetting it to the default (%d)",
6457aad02571SSaso Kiselkov 		    L2ARC_WRITE_SIZE);
6458aad02571SSaso Kiselkov 		size = l2arc_write_max = L2ARC_WRITE_SIZE;
6459aad02571SSaso Kiselkov 	}
64605a98e54bSBrendan Gregg - Sun Microsystems 
64615a98e54bSBrendan Gregg - Sun Microsystems 	if (arc_warm == B_FALSE)
6462aad02571SSaso Kiselkov 		size += l2arc_write_boost;
64635a98e54bSBrendan Gregg - Sun Microsystems 
64645a98e54bSBrendan Gregg - Sun Microsystems 	return (size);
64655a98e54bSBrendan Gregg - Sun Microsystems 
64665a98e54bSBrendan Gregg - Sun Microsystems }
64675a98e54bSBrendan Gregg - Sun Microsystems 
64685a98e54bSBrendan Gregg - Sun Microsystems static clock_t
64695a98e54bSBrendan Gregg - Sun Microsystems l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
64705a98e54bSBrendan Gregg - Sun Microsystems {
6471d3d50737SRafael Vanoni 	clock_t interval, next, now;
64725a98e54bSBrendan Gregg - Sun Microsystems 
64735a98e54bSBrendan Gregg - Sun Microsystems 	/*
64745a98e54bSBrendan Gregg - Sun Microsystems 	 * If the ARC lists are busy, increase our write rate; if the
64755a98e54bSBrendan Gregg - Sun Microsystems 	 * lists are stale, idle back.  This is achieved by checking
64765a98e54bSBrendan Gregg - Sun Microsystems 	 * how much we previously wrote - if it was more than half of
64775a98e54bSBrendan Gregg - Sun Microsystems 	 * what we wanted, schedule the next write much sooner.
64785a98e54bSBrendan Gregg - Sun Microsystems 	 */
64795a98e54bSBrendan Gregg - Sun Microsystems 	if (l2arc_feed_again && wrote > (wanted / 2))
64805a98e54bSBrendan Gregg - Sun Microsystems 		interval = (hz * l2arc_feed_min_ms) / 1000;
64815a98e54bSBrendan Gregg - Sun Microsystems 	else
64825a98e54bSBrendan Gregg - Sun Microsystems 		interval = hz * l2arc_feed_secs;
64835a98e54bSBrendan Gregg - Sun Microsystems 
6484d3d50737SRafael Vanoni 	now = ddi_get_lbolt();
6485d3d50737SRafael Vanoni 	next = MAX(now, MIN(now + interval, began + interval));
64865a98e54bSBrendan Gregg - Sun Microsystems 
64875a98e54bSBrendan Gregg - Sun Microsystems 	return (next);
64885a98e54bSBrendan Gregg - Sun Microsystems }
64895a98e54bSBrendan Gregg - Sun Microsystems 
6490fa94a07fSbrendan /*
6491fa94a07fSbrendan  * Cycle through L2ARC devices.  This is how L2ARC load balances.
64923a737e0dSbrendan  * If a device is returned, this also returns holding the spa config lock.
6493fa94a07fSbrendan  */
6494fa94a07fSbrendan static l2arc_dev_t *
6495fa94a07fSbrendan l2arc_dev_get_next(void)
6496fa94a07fSbrendan {
64973a737e0dSbrendan 	l2arc_dev_t *first, *next = NULL;
64983a737e0dSbrendan 
64993a737e0dSbrendan 	/*
65003a737e0dSbrendan 	 * Lock out the removal of spas (spa_namespace_lock), then removal
65013a737e0dSbrendan 	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
65023a737e0dSbrendan 	 * both locks will be dropped and a spa config lock held instead.
65033a737e0dSbrendan 	 */
65043a737e0dSbrendan 	mutex_enter(&spa_namespace_lock);
65053a737e0dSbrendan 	mutex_enter(&l2arc_dev_mtx);
6506fa94a07fSbrendan 
6507c5904d13Seschrock 	/* if there are no vdevs, there is nothing to do */
6508c5904d13Seschrock 	if (l2arc_ndev == 0)
65093a737e0dSbrendan 		goto out;
6510c5904d13Seschrock 
6511c5904d13Seschrock 	first = NULL;
6512c5904d13Seschrock 	next = l2arc_dev_last;
6513c5904d13Seschrock 	do {
6514c5904d13Seschrock 		/* loop around the list looking for a non-faulted vdev */
6515c5904d13Seschrock 		if (next == NULL) {
6516fa94a07fSbrendan 			next = list_head(l2arc_dev_list);
6517c5904d13Seschrock 		} else {
6518c5904d13Seschrock 			next = list_next(l2arc_dev_list, next);
6519c5904d13Seschrock 			if (next == NULL)
6520c5904d13Seschrock 				next = list_head(l2arc_dev_list);
6521c5904d13Seschrock 		}
6522c5904d13Seschrock 
6523c5904d13Seschrock 		/* if we have come back to the start, bail out */
6524c5904d13Seschrock 		if (first == NULL)
6525c5904d13Seschrock 			first = next;
6526c5904d13Seschrock 		else if (next == first)
6527c5904d13Seschrock 			break;
6528c5904d13Seschrock 
6529c5904d13Seschrock 	} while (vdev_is_dead(next->l2ad_vdev));
6530c5904d13Seschrock 
6531c5904d13Seschrock 	/* if we were unable to find any usable vdevs, return NULL */
6532c5904d13Seschrock 	if (vdev_is_dead(next->l2ad_vdev))
65333a737e0dSbrendan 		next = NULL;
6534fa94a07fSbrendan 
6535fa94a07fSbrendan 	l2arc_dev_last = next;
6536fa94a07fSbrendan 
65373a737e0dSbrendan out:
65383a737e0dSbrendan 	mutex_exit(&l2arc_dev_mtx);
65393a737e0dSbrendan 
65403a737e0dSbrendan 	/*
65413a737e0dSbrendan 	 * Grab the config lock to prevent the 'next' device from being
65423a737e0dSbrendan 	 * removed while we are writing to it.
65433a737e0dSbrendan 	 */
65443a737e0dSbrendan 	if (next != NULL)
6545e14bb325SJeff Bonwick 		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
65463a737e0dSbrendan 	mutex_exit(&spa_namespace_lock);
65473a737e0dSbrendan 
6548fa94a07fSbrendan 	return (next);
6549fa94a07fSbrendan }
6550fa94a07fSbrendan 
65513a737e0dSbrendan /*
65523a737e0dSbrendan  * Free buffers that were tagged for destruction.
65533a737e0dSbrendan  */
65543a737e0dSbrendan static void
65553a737e0dSbrendan l2arc_do_free_on_write()
65563a737e0dSbrendan {
65573a737e0dSbrendan 	list_t *buflist;
65583a737e0dSbrendan 	l2arc_data_free_t *df, *df_prev;
65593a737e0dSbrendan 
65603a737e0dSbrendan 	mutex_enter(&l2arc_free_on_write_mtx);
65613a737e0dSbrendan 	buflist = l2arc_free_on_write;
65623a737e0dSbrendan 
65633a737e0dSbrendan 	for (df = list_tail(buflist); df; df = df_prev) {
65643a737e0dSbrendan 		df_prev = list_prev(buflist, df);
6565770499e1SDan Kimmel 		ASSERT3P(df->l2df_abd, !=, NULL);
6566770499e1SDan Kimmel 		abd_free(df->l2df_abd);
65673a737e0dSbrendan 		list_remove(buflist, df);
65683a737e0dSbrendan 		kmem_free(df, sizeof (l2arc_data_free_t));
65693a737e0dSbrendan 	}
65703a737e0dSbrendan 
65713a737e0dSbrendan 	mutex_exit(&l2arc_free_on_write_mtx);
65723a737e0dSbrendan }
65733a737e0dSbrendan 
6574fa94a07fSbrendan /*
6575fa94a07fSbrendan  * A write to a cache device has completed.  Update all headers to allow
6576fa94a07fSbrendan  * reads from these buffers to begin.
6577fa94a07fSbrendan  */
6578fa94a07fSbrendan static void
6579fa94a07fSbrendan l2arc_write_done(zio_t *zio)
6580fa94a07fSbrendan {
6581fa94a07fSbrendan 	l2arc_write_callback_t *cb;
6582fa94a07fSbrendan 	l2arc_dev_t *dev;
6583fa94a07fSbrendan 	list_t *buflist;
65847adb730bSGeorge Wilson 	arc_buf_hdr_t *head, *hdr, *hdr_prev;
6585fa94a07fSbrendan 	kmutex_t *hash_lock;
65863038a2b4SSaso Kiselkov 	int64_t bytes_dropped = 0;
6587fa94a07fSbrendan 
6588fa94a07fSbrendan 	cb = zio->io_private;
6589dcbf3bd6SGeorge Wilson 	ASSERT3P(cb, !=, NULL);
6590fa94a07fSbrendan 	dev = cb->l2wcb_dev;
6591dcbf3bd6SGeorge Wilson 	ASSERT3P(dev, !=, NULL);
6592fa94a07fSbrendan 	head = cb->l2wcb_head;
6593dcbf3bd6SGeorge Wilson 	ASSERT3P(head, !=, NULL);
659489c86e32SChris Williamson 	buflist = &dev->l2ad_buflist;
6595dcbf3bd6SGeorge Wilson 	ASSERT3P(buflist, !=, NULL);
6596fa94a07fSbrendan 	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
6597fa94a07fSbrendan 	    l2arc_write_callback_t *, cb);
6598fa94a07fSbrendan 
6599fa94a07fSbrendan 	if (zio->io_error != 0)
6600fa94a07fSbrendan 		ARCSTAT_BUMP(arcstat_l2_writes_error);
6601fa94a07fSbrendan 
6602fa94a07fSbrendan 	/*
6603fa94a07fSbrendan 	 * All writes completed, or an error was hit.
6604fa94a07fSbrendan 	 */
6605244781f1SPrakash Surya top:
6606244781f1SPrakash Surya 	mutex_enter(&dev->l2ad_mtx);
66077adb730bSGeorge Wilson 	for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
66087adb730bSGeorge Wilson 		hdr_prev = list_prev(buflist, hdr);
6609fa94a07fSbrendan 
66107adb730bSGeorge Wilson 		hash_lock = HDR_LOCK(hdr);
6611244781f1SPrakash Surya 
6612244781f1SPrakash Surya 		/*
6613244781f1SPrakash Surya 		 * We cannot use mutex_enter or else we can deadlock
6614244781f1SPrakash Surya 		 * with l2arc_write_buffers (due to swapping the order
6615244781f1SPrakash Surya 		 * the hash lock and l2ad_mtx are taken).
6616244781f1SPrakash Surya 		 */
6617fa94a07fSbrendan 		if (!mutex_tryenter(hash_lock)) {
6618fa94a07fSbrendan 			/*
6619244781f1SPrakash Surya 			 * Missed the hash lock. We must retry so we
6620244781f1SPrakash Surya 			 * don't leave the ARC_FLAG_L2_WRITING bit set.
6621fa94a07fSbrendan 			 */
6622244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
6623244781f1SPrakash Surya 
6624244781f1SPrakash Surya 			/*
6625244781f1SPrakash Surya 			 * We don't want to rescan the headers we've
6626244781f1SPrakash Surya 			 * already marked as having been written out, so
6627244781f1SPrakash Surya 			 * we reinsert the head node so we can pick up
6628244781f1SPrakash Surya 			 * where we left off.
6629244781f1SPrakash Surya 			 */
6630244781f1SPrakash Surya 			list_remove(buflist, head);
6631244781f1SPrakash Surya 			list_insert_after(buflist, hdr, head);
6632244781f1SPrakash Surya 
6633244781f1SPrakash Surya 			mutex_exit(&dev->l2ad_mtx);
6634244781f1SPrakash Surya 
6635244781f1SPrakash Surya 			/*
6636244781f1SPrakash Surya 			 * We wait for the hash lock to become available
6637244781f1SPrakash Surya 			 * to try and prevent busy waiting, and increase
6638244781f1SPrakash Surya 			 * the chance we'll be able to acquire the lock
6639244781f1SPrakash Surya 			 * the next time around.
6640244781f1SPrakash Surya 			 */
6641244781f1SPrakash Surya 			mutex_enter(hash_lock);
6642244781f1SPrakash Surya 			mutex_exit(hash_lock);
6643244781f1SPrakash Surya 			goto top;
6644fa94a07fSbrendan 		}
6645fa94a07fSbrendan 
664689c86e32SChris Williamson 		/*
6647244781f1SPrakash Surya 		 * We could not have been moved into the arc_l2c_only
6648244781f1SPrakash Surya 		 * state while in-flight due to our ARC_FLAG_L2_WRITING
6649244781f1SPrakash Surya 		 * bit being set. Let's just ensure that's being enforced.
6650244781f1SPrakash Surya 		 */
6651244781f1SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(hdr));
6652244781f1SPrakash Surya 
6653fa94a07fSbrendan 		if (zio->io_error != 0) {
6654fa94a07fSbrendan 			/*
66553a737e0dSbrendan 			 * Error - drop L2ARC entry.
6656fa94a07fSbrendan 			 */
66577adb730bSGeorge Wilson 			list_remove(buflist, hdr);
6658dcbf3bd6SGeorge Wilson 			arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
665989c86e32SChris Williamson 
666016a7e5acSAndriy Gapon 			ARCSTAT_INCR(arcstat_l2_psize, -arc_hdr_size(hdr));
666116a7e5acSAndriy Gapon 			ARCSTAT_INCR(arcstat_l2_lsize, -HDR_GET_LSIZE(hdr));
6662a52fc310SPrakash Surya 
6663dcbf3bd6SGeorge Wilson 			bytes_dropped += arc_hdr_size(hdr);
6664a52fc310SPrakash Surya 			(void) refcount_remove_many(&dev->l2ad_alloc,
6665dcbf3bd6SGeorge Wilson 			    arc_hdr_size(hdr), hdr);
6666fa94a07fSbrendan 		}
6667fa94a07fSbrendan 
6668fa94a07fSbrendan 		/*
6669244781f1SPrakash Surya 		 * Allow ARC to begin reads and ghost list evictions to
6670244781f1SPrakash Surya 		 * this L2ARC entry.
6671fa94a07fSbrendan 		 */
6672dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_L2_WRITING);
6673fa94a07fSbrendan 
6674fa94a07fSbrendan 		mutex_exit(hash_lock);
6675fa94a07fSbrendan 	}
6676fa94a07fSbrendan 
6677fa94a07fSbrendan 	atomic_inc_64(&l2arc_writes_done);
6678fa94a07fSbrendan 	list_remove(buflist, head);
667989c86e32SChris Williamson 	ASSERT(!HDR_HAS_L1HDR(head));
668089c86e32SChris Williamson 	kmem_cache_free(hdr_l2only_cache, head);
668189c86e32SChris Williamson 	mutex_exit(&dev->l2ad_mtx);
6682fa94a07fSbrendan 
66833038a2b4SSaso Kiselkov 	vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
66843038a2b4SSaso Kiselkov 
66853a737e0dSbrendan 	l2arc_do_free_on_write();
6686fa94a07fSbrendan 
6687fa94a07fSbrendan 	kmem_free(cb, sizeof (l2arc_write_callback_t));
6688fa94a07fSbrendan }
6689fa94a07fSbrendan 
6690fa94a07fSbrendan /*
6691fa94a07fSbrendan  * A read to a cache device completed.  Validate buffer contents before
6692fa94a07fSbrendan  * handing over to the regular ARC routines.
6693fa94a07fSbrendan  */
6694fa94a07fSbrendan static void
6695fa94a07fSbrendan l2arc_read_done(zio_t *zio)
6696fa94a07fSbrendan {
6697fa94a07fSbrendan 	l2arc_read_callback_t *cb;
6698fa94a07fSbrendan 	arc_buf_hdr_t *hdr;
6699fa94a07fSbrendan 	kmutex_t *hash_lock;
6700dcbf3bd6SGeorge Wilson 	boolean_t valid_cksum;
6701fa94a07fSbrendan 
6702dcbf3bd6SGeorge Wilson 	ASSERT3P(zio->io_vd, !=, NULL);
6703e14bb325SJeff Bonwick 	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
6704e14bb325SJeff Bonwick 
6705e14bb325SJeff Bonwick 	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
6706e14bb325SJeff Bonwick 
6707fa94a07fSbrendan 	cb = zio->io_private;
6708dcbf3bd6SGeorge Wilson 	ASSERT3P(cb, !=, NULL);
6709dcbf3bd6SGeorge Wilson 	hdr = cb->l2rcb_hdr;
6710dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr, !=, NULL);
6711fa94a07fSbrendan 
6712dcbf3bd6SGeorge Wilson 	hash_lock = HDR_LOCK(hdr);
6713fa94a07fSbrendan 	mutex_enter(hash_lock);
67143f9d6ad7SLin Ling 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
6715fa94a07fSbrendan 
6716403a8da7SAndriy Gapon 	/*
6717403a8da7SAndriy Gapon 	 * If the data was read into a temporary buffer,
6718403a8da7SAndriy Gapon 	 * move it and free the buffer.
6719403a8da7SAndriy Gapon 	 */
6720403a8da7SAndriy Gapon 	if (cb->l2rcb_abd != NULL) {
6721403a8da7SAndriy Gapon 		ASSERT3U(arc_hdr_size(hdr), <, zio->io_size);
6722403a8da7SAndriy Gapon 		if (zio->io_error == 0) {
6723403a8da7SAndriy Gapon 			abd_copy(hdr->b_l1hdr.b_pabd, cb->l2rcb_abd,
6724403a8da7SAndriy Gapon 			    arc_hdr_size(hdr));
6725403a8da7SAndriy Gapon 		}
6726403a8da7SAndriy Gapon 
6727403a8da7SAndriy Gapon 		/*
6728403a8da7SAndriy Gapon 		 * The following must be done regardless of whether
6729403a8da7SAndriy Gapon 		 * there was an error:
6730403a8da7SAndriy Gapon 		 * - free the temporary buffer
6731403a8da7SAndriy Gapon 		 * - point zio to the real ARC buffer
6732403a8da7SAndriy Gapon 		 * - set zio size accordingly
6733403a8da7SAndriy Gapon 		 * These are required because zio is either re-used for
6734403a8da7SAndriy Gapon 		 * an I/O of the block in the case of the error
6735403a8da7SAndriy Gapon 		 * or the zio is passed to arc_read_done() and it
6736403a8da7SAndriy Gapon 		 * needs real data.
6737403a8da7SAndriy Gapon 		 */
6738403a8da7SAndriy Gapon 		abd_free(cb->l2rcb_abd);
6739403a8da7SAndriy Gapon 		zio->io_size = zio->io_orig_size = arc_hdr_size(hdr);
6740403a8da7SAndriy Gapon 		zio->io_abd = zio->io_orig_abd = hdr->b_l1hdr.b_pabd;
6741403a8da7SAndriy Gapon 	}
6742403a8da7SAndriy Gapon 
6743770499e1SDan Kimmel 	ASSERT3P(zio->io_abd, !=, NULL);
6744aad02571SSaso Kiselkov 
6745fa94a07fSbrendan 	/*
6746fa94a07fSbrendan 	 * Check this survived the L2ARC journey.
6747fa94a07fSbrendan 	 */
6748770499e1SDan Kimmel 	ASSERT3P(zio->io_abd, ==, hdr->b_l1hdr.b_pabd);
6749dcbf3bd6SGeorge Wilson 	zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
6750dcbf3bd6SGeorge Wilson 	zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
6751dcbf3bd6SGeorge Wilson 
6752dcbf3bd6SGeorge Wilson 	valid_cksum = arc_cksum_is_equal(hdr, zio);
6753dcbf3bd6SGeorge Wilson 	if (valid_cksum && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
6754fa94a07fSbrendan 		mutex_exit(hash_lock);
6755dcbf3bd6SGeorge Wilson 		zio->io_private = hdr;
6756fa94a07fSbrendan 		arc_read_done(zio);
6757fa94a07fSbrendan 	} else {
6758fa94a07fSbrendan 		mutex_exit(hash_lock);
6759fa94a07fSbrendan 		/*
6760fa94a07fSbrendan 		 * Buffer didn't survive caching.  Increment stats and
6761fa94a07fSbrendan 		 * reissue to the original storage device.
6762fa94a07fSbrendan 		 */
67633a737e0dSbrendan 		if (zio->io_error != 0) {
6764fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_io_error);
67653a737e0dSbrendan 		} else {
6766be6fd75aSMatthew Ahrens 			zio->io_error = SET_ERROR(EIO);
67673a737e0dSbrendan 		}
6768dcbf3bd6SGeorge Wilson 		if (!valid_cksum)
6769fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
6770fa94a07fSbrendan 
6771e14bb325SJeff Bonwick 		/*
6772e14bb325SJeff Bonwick 		 * If there's no waiter, issue an async i/o to the primary
6773e14bb325SJeff Bonwick 		 * storage now.  If there *is* a waiter, the caller must
6774e14bb325SJeff Bonwick 		 * issue the i/o in a context where it's OK to block.
6775e14bb325SJeff Bonwick 		 */
6776a3f829aeSBill Moore 		if (zio->io_waiter == NULL) {
6777a3f829aeSBill Moore 			zio_t *pio = zio_unique_parent(zio);
6778a3f829aeSBill Moore 
6779a3f829aeSBill Moore 			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
6780a3f829aeSBill Moore 
6781dcbf3bd6SGeorge Wilson 			zio_nowait(zio_read(pio, zio->io_spa, zio->io_bp,
6782770499e1SDan Kimmel 			    hdr->b_l1hdr.b_pabd, zio->io_size, arc_read_done,
6783dcbf3bd6SGeorge Wilson 			    hdr, zio->io_priority, cb->l2rcb_flags,
6784dcbf3bd6SGeorge Wilson 			    &cb->l2rcb_zb));
6785a3f829aeSBill Moore 		}
6786fa94a07fSbrendan 	}
6787fa94a07fSbrendan 
6788fa94a07fSbrendan 	kmem_free(cb, sizeof (l2arc_read_callback_t));
6789fa94a07fSbrendan }
6790fa94a07fSbrendan 
6791fa94a07fSbrendan /*
6792fa94a07fSbrendan  * This is the list priority from which the L2ARC will search for pages to
6793fa94a07fSbrendan  * cache.  This is used within loops (0..3) to cycle through lists in the
6794fa94a07fSbrendan  * desired order.  This order can have a significant effect on cache
6795fa94a07fSbrendan  * performance.
6796fa94a07fSbrendan  *
6797fa94a07fSbrendan  * Currently the metadata lists are hit first, MFU then MRU, followed by
6798fa94a07fSbrendan  * the data lists.  This function returns a locked list, and also returns
6799fa94a07fSbrendan  * the lock pointer.
6800fa94a07fSbrendan  */
6801244781f1SPrakash Surya static multilist_sublist_t *
6802244781f1SPrakash Surya l2arc_sublist_lock(int list_num)
6803fa94a07fSbrendan {
6804244781f1SPrakash Surya 	multilist_t *ml = NULL;
6805244781f1SPrakash Surya 	unsigned int idx;
6806fa94a07fSbrendan 
6807fa94a07fSbrendan 	ASSERT(list_num >= 0 && list_num <= 3);
6808fa94a07fSbrendan 
6809fa94a07fSbrendan 	switch (list_num) {
6810fa94a07fSbrendan 	case 0:
681194c2d0ebSMatthew Ahrens 		ml = arc_mfu->arcs_list[ARC_BUFC_METADATA];
6812fa94a07fSbrendan 		break;
6813fa94a07fSbrendan 	case 1:
681494c2d0ebSMatthew Ahrens 		ml = arc_mru->arcs_list[ARC_BUFC_METADATA];
6815fa94a07fSbrendan 		break;
6816fa94a07fSbrendan 	case 2:
681794c2d0ebSMatthew Ahrens 		ml = arc_mfu->arcs_list[ARC_BUFC_DATA];
6818fa94a07fSbrendan 		break;
6819fa94a07fSbrendan 	case 3:
682094c2d0ebSMatthew Ahrens 		ml = arc_mru->arcs_list[ARC_BUFC_DATA];
6821fa94a07fSbrendan 		break;
6822fa94a07fSbrendan 	}
6823fa94a07fSbrendan 
6824244781f1SPrakash Surya 	/*
6825244781f1SPrakash Surya 	 * Return a randomly-selected sublist. This is acceptable
6826244781f1SPrakash Surya 	 * because the caller feeds only a little bit of data for each
6827244781f1SPrakash Surya 	 * call (8MB). Subsequent calls will result in different
6828244781f1SPrakash Surya 	 * sublists being selected.
6829244781f1SPrakash Surya 	 */
6830244781f1SPrakash Surya 	idx = multilist_get_random_index(ml);
6831244781f1SPrakash Surya 	return (multilist_sublist_lock(ml, idx));
6832fa94a07fSbrendan }
6833fa94a07fSbrendan 
6834fa94a07fSbrendan /*
6835fa94a07fSbrendan  * Evict buffers from the device write hand to the distance specified in
6836fa94a07fSbrendan  * bytes.  This distance may span populated buffers, it may span nothing.
6837fa94a07fSbrendan  * This is clearing a region on the L2ARC device ready for writing.
6838fa94a07fSbrendan  * If the 'all' boolean is set, every buffer is evicted.
6839fa94a07fSbrendan  */
6840fa94a07fSbrendan static void
6841fa94a07fSbrendan l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
6842fa94a07fSbrendan {
6843fa94a07fSbrendan 	list_t *buflist;
68447adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr, *hdr_prev;
6845fa94a07fSbrendan 	kmutex_t *hash_lock;
6846fa94a07fSbrendan 	uint64_t taddr;
6847fa94a07fSbrendan 
684889c86e32SChris Williamson 	buflist = &dev->l2ad_buflist;
6849fa94a07fSbrendan 
6850fa94a07fSbrendan 	if (!all && dev->l2ad_first) {
6851fa94a07fSbrendan 		/*
6852fa94a07fSbrendan 		 * This is the first sweep through the device.  There is
6853fa94a07fSbrendan 		 * nothing to evict.
6854fa94a07fSbrendan 		 */
6855fa94a07fSbrendan 		return;
6856fa94a07fSbrendan 	}
6857fa94a07fSbrendan 
68583a737e0dSbrendan 	if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
6859fa94a07fSbrendan 		/*
6860fa94a07fSbrendan 		 * When nearing the end of the device, evict to the end
6861fa94a07fSbrendan 		 * before the device write hand jumps to the start.
6862fa94a07fSbrendan 		 */
6863fa94a07fSbrendan 		taddr = dev->l2ad_end;
6864fa94a07fSbrendan 	} else {
6865fa94a07fSbrendan 		taddr = dev->l2ad_hand + distance;
6866fa94a07fSbrendan 	}
6867fa94a07fSbrendan 	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
6868fa94a07fSbrendan 	    uint64_t, taddr, boolean_t, all);
6869fa94a07fSbrendan 
6870fa94a07fSbrendan top:
687189c86e32SChris Williamson 	mutex_enter(&dev->l2ad_mtx);
68727adb730bSGeorge Wilson 	for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
68737adb730bSGeorge Wilson 		hdr_prev = list_prev(buflist, hdr);
6874fa94a07fSbrendan 
68757adb730bSGeorge Wilson 		hash_lock = HDR_LOCK(hdr);
6876244781f1SPrakash Surya 
6877244781f1SPrakash Surya 		/*
6878244781f1SPrakash Surya 		 * We cannot use mutex_enter or else we can deadlock
6879244781f1SPrakash Surya 		 * with l2arc_write_buffers (due to swapping the order
6880244781f1SPrakash Surya 		 * the hash lock and l2ad_mtx are taken).
6881244781f1SPrakash Surya 		 */
6882fa94a07fSbrendan 		if (!mutex_tryenter(hash_lock)) {
6883fa94a07fSbrendan 			/*
6884fa94a07fSbrendan 			 * Missed the hash lock.  Retry.
6885fa94a07fSbrendan 			 */
6886fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
688789c86e32SChris Williamson 			mutex_exit(&dev->l2ad_mtx);
6888fa94a07fSbrendan 			mutex_enter(hash_lock);
6889fa94a07fSbrendan 			mutex_exit(hash_lock);
6890fa94a07fSbrendan 			goto top;
6891fa94a07fSbrendan 		}
6892fa94a07fSbrendan 
6893267ae6c3SAndriy Gapon 		/*
6894267ae6c3SAndriy Gapon 		 * A header can't be on this list if it doesn't have L2 header.
6895267ae6c3SAndriy Gapon 		 */
6896267ae6c3SAndriy Gapon 		ASSERT(HDR_HAS_L2HDR(hdr));
6897fa94a07fSbrendan 
6898267ae6c3SAndriy Gapon 		/* Ensure this header has finished being written. */
6899267ae6c3SAndriy Gapon 		ASSERT(!HDR_L2_WRITING(hdr));
6900267ae6c3SAndriy Gapon 		ASSERT(!HDR_L2_WRITE_HEAD(hdr));
6901267ae6c3SAndriy Gapon 
6902267ae6c3SAndriy Gapon 		if (!all && (hdr->b_l2hdr.b_daddr >= taddr ||
690389c86e32SChris Williamson 		    hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
6904fa94a07fSbrendan 			/*
6905fa94a07fSbrendan 			 * We've evicted to the target address,
6906fa94a07fSbrendan 			 * or the end of the device.
6907fa94a07fSbrendan 			 */
6908fa94a07fSbrendan 			mutex_exit(hash_lock);
6909fa94a07fSbrendan 			break;
6910fa94a07fSbrendan 		}
6911fa94a07fSbrendan 
691289c86e32SChris Williamson 		if (!HDR_HAS_L1HDR(hdr)) {
69137adb730bSGeorge Wilson 			ASSERT(!HDR_L2_READING(hdr));
6914fa94a07fSbrendan 			/*
6915fa94a07fSbrendan 			 * This doesn't exist in the ARC.  Destroy.
6916fa94a07fSbrendan 			 * arc_hdr_destroy() will call list_remove()
691716a7e5acSAndriy Gapon 			 * and decrement arcstat_l2_lsize.
6918fa94a07fSbrendan 			 */
69197adb730bSGeorge Wilson 			arc_change_state(arc_anon, hdr, hash_lock);
69207adb730bSGeorge Wilson 			arc_hdr_destroy(hdr);
6921fa94a07fSbrendan 		} else {
692289c86e32SChris Williamson 			ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
692389c86e32SChris Williamson 			ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
69243a737e0dSbrendan 			/*
69253a737e0dSbrendan 			 * Invalidate issued or about to be issued
69263a737e0dSbrendan 			 * reads, since we may be about to write
69273a737e0dSbrendan 			 * over this location.
69283a737e0dSbrendan 			 */
69297adb730bSGeorge Wilson 			if (HDR_L2_READING(hdr)) {
69303a737e0dSbrendan 				ARCSTAT_BUMP(arcstat_l2_evict_reading);
6931dcbf3bd6SGeorge Wilson 				arc_hdr_set_flags(hdr, ARC_FLAG_L2_EVICTED);
69323a737e0dSbrendan 			}
69333a737e0dSbrendan 
6934a52fc310SPrakash Surya 			arc_hdr_l2hdr_destroy(hdr);
6935fa94a07fSbrendan 		}
6936fa94a07fSbrendan 		mutex_exit(hash_lock);
6937fa94a07fSbrendan 	}
693889c86e32SChris Williamson 	mutex_exit(&dev->l2ad_mtx);
6939fa94a07fSbrendan }
6940fa94a07fSbrendan 
6941fa94a07fSbrendan /*
6942fa94a07fSbrendan  * Find and write ARC buffers to the L2ARC device.
6943fa94a07fSbrendan  *
69447adb730bSGeorge Wilson  * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
6945fa94a07fSbrendan  * for reading until they have completed writing.
6946aad02571SSaso Kiselkov  * The headroom_boost is an in-out parameter used to maintain headroom boost
6947aad02571SSaso Kiselkov  * state between calls to this function.
6948aad02571SSaso Kiselkov  *
6949aad02571SSaso Kiselkov  * Returns the number of bytes actually written (which may be smaller than
6950aad02571SSaso Kiselkov  * the delta by which the device hand has changed due to alignment).
6951fa94a07fSbrendan  */
69525a98e54bSBrendan Gregg - Sun Microsystems static uint64_t
6953dcbf3bd6SGeorge Wilson l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
6954fa94a07fSbrendan {
69557adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr, *hdr_prev, *head;
695616a7e5acSAndriy Gapon 	uint64_t write_asize, write_psize, write_lsize, headroom;
6957aad02571SSaso Kiselkov 	boolean_t full;
6958fa94a07fSbrendan 	l2arc_write_callback_t *cb;
6959fa94a07fSbrendan 	zio_t *pio, *wzio;
6960e9103aaeSGarrett D'Amore 	uint64_t guid = spa_load_guid(spa);
6961fa94a07fSbrendan 
6962dcbf3bd6SGeorge Wilson 	ASSERT3P(dev->l2ad_vdev, !=, NULL);
6963aad02571SSaso Kiselkov 
6964fa94a07fSbrendan 	pio = NULL;
696516a7e5acSAndriy Gapon 	write_lsize = write_asize = write_psize = 0;
6966fa94a07fSbrendan 	full = B_FALSE;
696789c86e32SChris Williamson 	head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
6968dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(head, ARC_FLAG_L2_WRITE_HEAD | ARC_FLAG_HAS_L2HDR);
6969aad02571SSaso Kiselkov 
6970fa94a07fSbrendan 	/*
6971fa94a07fSbrendan 	 * Copy buffers for L2ARC writing.
6972fa94a07fSbrendan 	 */
6973fa94a07fSbrendan 	for (int try = 0; try <= 3; try++) {
6974244781f1SPrakash Surya 		multilist_sublist_t *mls = l2arc_sublist_lock(try);
6975aad02571SSaso Kiselkov 		uint64_t passed_sz = 0;
6976aad02571SSaso Kiselkov 
69773a737e0dSbrendan 		/*
69783a737e0dSbrendan 		 * L2ARC fast warmup.
69793a737e0dSbrendan 		 *
69803a737e0dSbrendan 		 * Until the ARC is warm and starts to evict, read from the
69813a737e0dSbrendan 		 * head of the ARC lists rather than the tail.
69823a737e0dSbrendan 		 */
69833a737e0dSbrendan 		if (arc_warm == B_FALSE)
6984244781f1SPrakash Surya 			hdr = multilist_sublist_head(mls);
69853a737e0dSbrendan 		else
6986244781f1SPrakash Surya 			hdr = multilist_sublist_tail(mls);
69873a737e0dSbrendan 
6988aad02571SSaso Kiselkov 		headroom = target_sz * l2arc_headroom;
6989dcbf3bd6SGeorge Wilson 		if (zfs_compressed_arc_enabled)
6990aad02571SSaso Kiselkov 			headroom = (headroom * l2arc_headroom_boost) / 100;
6991aad02571SSaso Kiselkov 
69927adb730bSGeorge Wilson 		for (; hdr; hdr = hdr_prev) {
6993aad02571SSaso Kiselkov 			kmutex_t *hash_lock;
6994aad02571SSaso Kiselkov 
69953a737e0dSbrendan 			if (arc_warm == B_FALSE)
6996244781f1SPrakash Surya 				hdr_prev = multilist_sublist_next(mls, hdr);
69973a737e0dSbrendan 			else
6998244781f1SPrakash Surya 				hdr_prev = multilist_sublist_prev(mls, hdr);
6999fa94a07fSbrendan 
70007adb730bSGeorge Wilson 			hash_lock = HDR_LOCK(hdr);
7001aad02571SSaso Kiselkov 			if (!mutex_tryenter(hash_lock)) {
7002fa94a07fSbrendan 				/*
7003fa94a07fSbrendan 				 * Skip this buffer rather than waiting.
7004fa94a07fSbrendan 				 */
7005fa94a07fSbrendan 				continue;
7006fa94a07fSbrendan 			}
7007fa94a07fSbrendan 
7008dcbf3bd6SGeorge Wilson 			passed_sz += HDR_GET_LSIZE(hdr);
7009fa94a07fSbrendan 			if (passed_sz > headroom) {
7010fa94a07fSbrendan 				/*
7011fa94a07fSbrendan 				 * Searched too far.
7012fa94a07fSbrendan 				 */
7013fa94a07fSbrendan 				mutex_exit(hash_lock);
7014fa94a07fSbrendan 				break;
7015fa94a07fSbrendan 			}
7016fa94a07fSbrendan 
70177adb730bSGeorge Wilson 			if (!l2arc_write_eligible(guid, hdr)) {
7018fa94a07fSbrendan 				mutex_exit(hash_lock);
7019fa94a07fSbrendan 				continue;
7020fa94a07fSbrendan 			}
7021fa94a07fSbrendan 
702216a7e5acSAndriy Gapon 			/*
702316a7e5acSAndriy Gapon 			 * We rely on the L1 portion of the header below, so
702416a7e5acSAndriy Gapon 			 * it's invalid for this header to have been evicted out
702516a7e5acSAndriy Gapon 			 * of the ghost cache, prior to being written out. The
702616a7e5acSAndriy Gapon 			 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
702716a7e5acSAndriy Gapon 			 */
702816a7e5acSAndriy Gapon 			ASSERT(HDR_HAS_L1HDR(hdr));
702916a7e5acSAndriy Gapon 
703016a7e5acSAndriy Gapon 			ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
703116a7e5acSAndriy Gapon 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
703216a7e5acSAndriy Gapon 			ASSERT3U(arc_hdr_size(hdr), >, 0);
703316a7e5acSAndriy Gapon 			uint64_t psize = arc_hdr_size(hdr);
703416a7e5acSAndriy Gapon 			uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev,
703516a7e5acSAndriy Gapon 			    psize);
703616a7e5acSAndriy Gapon 
703716a7e5acSAndriy Gapon 			if ((write_asize + asize) > target_sz) {
7038fa94a07fSbrendan 				full = B_TRUE;
7039fa94a07fSbrendan 				mutex_exit(hash_lock);
7040fa94a07fSbrendan 				break;
7041fa94a07fSbrendan 			}
7042fa94a07fSbrendan 
7043fa94a07fSbrendan 			if (pio == NULL) {
7044fa94a07fSbrendan 				/*
7045fa94a07fSbrendan 				 * Insert a dummy header on the buflist so
7046fa94a07fSbrendan 				 * l2arc_write_done() can find where the
7047fa94a07fSbrendan 				 * write buffers begin without searching.
7048fa94a07fSbrendan 				 */
7049244781f1SPrakash Surya 				mutex_enter(&dev->l2ad_mtx);
705089c86e32SChris Williamson 				list_insert_head(&dev->l2ad_buflist, head);
7051244781f1SPrakash Surya 				mutex_exit(&dev->l2ad_mtx);
7052fa94a07fSbrendan 
7053fa94a07fSbrendan 				cb = kmem_alloc(
7054fa94a07fSbrendan 				    sizeof (l2arc_write_callback_t), KM_SLEEP);
7055fa94a07fSbrendan 				cb->l2wcb_dev = dev;
7056fa94a07fSbrendan 				cb->l2wcb_head = head;
7057fa94a07fSbrendan 				pio = zio_root(spa, l2arc_write_done, cb,
7058fa94a07fSbrendan 				    ZIO_FLAG_CANFAIL);
7059fa94a07fSbrendan 			}
7060fa94a07fSbrendan 
706189c86e32SChris Williamson 			hdr->b_l2hdr.b_dev = dev;
7062dcbf3bd6SGeorge Wilson 			hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
7063dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr,
7064dcbf3bd6SGeorge Wilson 			    ARC_FLAG_L2_WRITING | ARC_FLAG_HAS_L2HDR);
7065dcbf3bd6SGeorge Wilson 
7066dcbf3bd6SGeorge Wilson 			mutex_enter(&dev->l2ad_mtx);
7067dcbf3bd6SGeorge Wilson 			list_insert_head(&dev->l2ad_buflist, hdr);
7068dcbf3bd6SGeorge Wilson 			mutex_exit(&dev->l2ad_mtx);
7069dcbf3bd6SGeorge Wilson 
707016a7e5acSAndriy Gapon 			(void) refcount_add_many(&dev->l2ad_alloc, psize, hdr);
7071aad02571SSaso Kiselkov 
7072a52fc310SPrakash Surya 			/*
7073dcbf3bd6SGeorge Wilson 			 * Normally the L2ARC can use the hdr's data, but if
7074dcbf3bd6SGeorge Wilson 			 * we're sharing data between the hdr and one of its
7075dcbf3bd6SGeorge Wilson 			 * bufs, L2ARC needs its own copy of the data so that
7076403a8da7SAndriy Gapon 			 * the ZIO below can't race with the buf consumer.
7077403a8da7SAndriy Gapon 			 * Another case where we need to create a copy of the
7078403a8da7SAndriy Gapon 			 * data is when the buffer size is not device-aligned
7079403a8da7SAndriy Gapon 			 * and we need to pad the block to make it such.
7080403a8da7SAndriy Gapon 			 * That also keeps the clock hand suitably aligned.
7081403a8da7SAndriy Gapon 			 *
7082403a8da7SAndriy Gapon 			 * To ensure that the copy will be available for the
7083dcbf3bd6SGeorge Wilson 			 * lifetime of the ZIO and be cleaned up afterwards, we
7084dcbf3bd6SGeorge Wilson 			 * add it to the l2arc_free_on_write queue.
7085a52fc310SPrakash Surya 			 */
7086770499e1SDan Kimmel 			abd_t *to_write;
708716a7e5acSAndriy Gapon 			if (!HDR_SHARED_DATA(hdr) && psize == asize) {
7088770499e1SDan Kimmel 				to_write = hdr->b_l1hdr.b_pabd;
7089dcbf3bd6SGeorge Wilson 			} else {
7090403a8da7SAndriy Gapon 				to_write = abd_alloc_for_io(asize,
7091770499e1SDan Kimmel 				    HDR_ISTYPE_METADATA(hdr));
709216a7e5acSAndriy Gapon 				abd_copy(to_write, hdr->b_l1hdr.b_pabd, psize);
709316a7e5acSAndriy Gapon 				if (asize != psize) {
709416a7e5acSAndriy Gapon 					abd_zero_off(to_write, psize,
709516a7e5acSAndriy Gapon 					    asize - psize);
7096403a8da7SAndriy Gapon 				}
709716a7e5acSAndriy Gapon 				l2arc_free_abd_on_write(to_write, asize,
7098770499e1SDan Kimmel 				    arc_buf_type(hdr));
7099dcbf3bd6SGeorge Wilson 			}
7100dcbf3bd6SGeorge Wilson 			wzio = zio_write_phys(pio, dev->l2ad_vdev,
7101403a8da7SAndriy Gapon 			    hdr->b_l2hdr.b_daddr, asize, to_write,
7102dcbf3bd6SGeorge Wilson 			    ZIO_CHECKSUM_OFF, NULL, hdr,
7103dcbf3bd6SGeorge Wilson 			    ZIO_PRIORITY_ASYNC_WRITE,
7104dcbf3bd6SGeorge Wilson 			    ZIO_FLAG_CANFAIL, B_FALSE);
7105aad02571SSaso Kiselkov 
710616a7e5acSAndriy Gapon 			write_lsize += HDR_GET_LSIZE(hdr);
7107dcbf3bd6SGeorge Wilson 			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
7108dcbf3bd6SGeorge Wilson 			    zio_t *, wzio);
7109fa94a07fSbrendan 
711016a7e5acSAndriy Gapon 			write_psize += psize;
711116a7e5acSAndriy Gapon 			write_asize += asize;
7112dcbf3bd6SGeorge Wilson 			dev->l2ad_hand += asize;
7113fa94a07fSbrendan 
7114fa94a07fSbrendan 			mutex_exit(hash_lock);
7115fa94a07fSbrendan 
7116dcbf3bd6SGeorge Wilson 			(void) zio_nowait(wzio);
7117aad02571SSaso Kiselkov 		}
7118aad02571SSaso Kiselkov 
7119244781f1SPrakash Surya 		multilist_sublist_unlock(mls);
7120aad02571SSaso Kiselkov 
7121aad02571SSaso Kiselkov 		if (full == B_TRUE)
7122aad02571SSaso Kiselkov 			break;
7123aad02571SSaso Kiselkov 	}
7124aad02571SSaso Kiselkov 
7125aad02571SSaso Kiselkov 	/* No buffers selected for writing? */
7126aad02571SSaso Kiselkov 	if (pio == NULL) {
712716a7e5acSAndriy Gapon 		ASSERT0(write_lsize);
712889c86e32SChris Williamson 		ASSERT(!HDR_HAS_L1HDR(head));
712989c86e32SChris Williamson 		kmem_cache_free(hdr_l2only_cache, head);
7130aad02571SSaso Kiselkov 		return (0);
7131aad02571SSaso Kiselkov 	}
7132aad02571SSaso Kiselkov 
7133aad02571SSaso Kiselkov 	ASSERT3U(write_asize, <=, target_sz);
7134fa94a07fSbrendan 	ARCSTAT_BUMP(arcstat_l2_writes_sent);
713516a7e5acSAndriy Gapon 	ARCSTAT_INCR(arcstat_l2_write_bytes, write_psize);
713616a7e5acSAndriy Gapon 	ARCSTAT_INCR(arcstat_l2_lsize, write_lsize);
713716a7e5acSAndriy Gapon 	ARCSTAT_INCR(arcstat_l2_psize, write_psize);
713816a7e5acSAndriy Gapon 	vdev_space_update(dev->l2ad_vdev, write_psize, 0, 0);
7139fa94a07fSbrendan 
7140fa94a07fSbrendan 	/*
7141fa94a07fSbrendan 	 * Bump device hand to the device start if it is approaching the end.
7142fa94a07fSbrendan 	 * l2arc_evict() will already have evicted ahead for this case.
7143fa94a07fSbrendan 	 */
71443a737e0dSbrendan 	if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
7145fa94a07fSbrendan 		dev->l2ad_hand = dev->l2ad_start;
7146fa94a07fSbrendan 		dev->l2ad_first = B_FALSE;
7147fa94a07fSbrendan 	}
7148fa94a07fSbrendan 
71495a98e54bSBrendan Gregg - Sun Microsystems 	dev->l2ad_writing = B_TRUE;
7150fa94a07fSbrendan 	(void) zio_wait(pio);
71515a98e54bSBrendan Gregg - Sun Microsystems 	dev->l2ad_writing = B_FALSE;
71525a98e54bSBrendan Gregg - Sun Microsystems 
7153aad02571SSaso Kiselkov 	return (write_asize);
7154aad02571SSaso Kiselkov }
7155aad02571SSaso Kiselkov 
7156fa94a07fSbrendan /*
7157fa94a07fSbrendan  * This thread feeds the L2ARC at regular intervals.  This is the beating
7158fa94a07fSbrendan  * heart of the L2ARC.
7159fa94a07fSbrendan  */
71603f7978d0SAlan Somers /* ARGSUSED */
7161fa94a07fSbrendan static void
71623f7978d0SAlan Somers l2arc_feed_thread(void *unused)
7163fa94a07fSbrendan {
7164fa94a07fSbrendan 	callb_cpr_t cpr;
7165fa94a07fSbrendan 	l2arc_dev_t *dev;
7166fa94a07fSbrendan 	spa_t *spa;
71675a98e54bSBrendan Gregg - Sun Microsystems 	uint64_t size, wrote;
7168d3d50737SRafael Vanoni 	clock_t begin, next = ddi_get_lbolt();
7169fa94a07fSbrendan 
7170fa94a07fSbrendan 	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
7171fa94a07fSbrendan 
7172fa94a07fSbrendan 	mutex_enter(&l2arc_feed_thr_lock);
7173fa94a07fSbrendan 
7174fa94a07fSbrendan 	while (l2arc_thread_exit == 0) {
7175fa94a07fSbrendan 		CALLB_CPR_SAFE_BEGIN(&cpr);
7176fa94a07fSbrendan 		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
71775a98e54bSBrendan Gregg - Sun Microsystems 		    next);
7178fa94a07fSbrendan 		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
7179d3d50737SRafael Vanoni 		next = ddi_get_lbolt() + hz;
7180fa94a07fSbrendan 
71813a737e0dSbrendan 		/*
71823a737e0dSbrendan 		 * Quick check for L2ARC devices.
71833a737e0dSbrendan 		 */
7184c5904d13Seschrock 		mutex_enter(&l2arc_dev_mtx);
71853a737e0dSbrendan 		if (l2arc_ndev == 0) {
71863a737e0dSbrendan 			mutex_exit(&l2arc_dev_mtx);
71873a737e0dSbrendan 			continue;
71883a737e0dSbrendan 		}
71893a737e0dSbrendan 		mutex_exit(&l2arc_dev_mtx);
7190d3d50737SRafael Vanoni 		begin = ddi_get_lbolt();
7191c5904d13Seschrock 
7192fa94a07fSbrendan 		/*
7193c5904d13Seschrock 		 * This selects the next l2arc device to write to, and in
7194c5904d13Seschrock 		 * doing so the next spa to feed from: dev->l2ad_spa.   This
71953a737e0dSbrendan 		 * will return NULL if there are now no l2arc devices or if
71963a737e0dSbrendan 		 * they are all faulted.
71973a737e0dSbrendan 		 *
71983a737e0dSbrendan 		 * If a device is returned, its spa's config lock is also
71993a737e0dSbrendan 		 * held to prevent device removal.  l2arc_dev_get_next()
72003a737e0dSbrendan 		 * will grab and release l2arc_dev_mtx.
7201fa94a07fSbrendan 		 */
72023a737e0dSbrendan 		if ((dev = l2arc_dev_get_next()) == NULL)
7203fa94a07fSbrendan 			continue;
72043a737e0dSbrendan 
72053a737e0dSbrendan 		spa = dev->l2ad_spa;
7206dcbf3bd6SGeorge Wilson 		ASSERT3P(spa, !=, NULL);
7207fa94a07fSbrendan 
7208f9af39baSGeorge Wilson 		/*
7209f9af39baSGeorge Wilson 		 * If the pool is read-only then force the feed thread to
7210f9af39baSGeorge Wilson 		 * sleep a little longer.
7211f9af39baSGeorge Wilson 		 */
7212f9af39baSGeorge Wilson 		if (!spa_writeable(spa)) {
7213f9af39baSGeorge Wilson 			next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
7214f9af39baSGeorge Wilson 			spa_config_exit(spa, SCL_L2ARC, dev);
7215f9af39baSGeorge Wilson 			continue;
7216f9af39baSGeorge Wilson 		}
7217f9af39baSGeorge Wilson 
7218fa94a07fSbrendan 		/*
7219fa94a07fSbrendan 		 * Avoid contributing to memory pressure.
7220fa94a07fSbrendan 		 */
7221fa94a07fSbrendan 		if (arc_reclaim_needed()) {
7222fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
7223e14bb325SJeff Bonwick 			spa_config_exit(spa, SCL_L2ARC, dev);
7224fa94a07fSbrendan 			continue;
7225fa94a07fSbrendan 		}
7226fa94a07fSbrendan 
7227fa94a07fSbrendan 		ARCSTAT_BUMP(arcstat_l2_feeds);
7228fa94a07fSbrendan 
7229aad02571SSaso Kiselkov 		size = l2arc_write_size();
72303a737e0dSbrendan 
7231fa94a07fSbrendan 		/*
7232fa94a07fSbrendan 		 * Evict L2ARC buffers that will be overwritten.
7233fa94a07fSbrendan 		 */
72343a737e0dSbrendan 		l2arc_evict(dev, size, B_FALSE);
7235fa94a07fSbrendan 
7236fa94a07fSbrendan 		/*
7237fa94a07fSbrendan 		 * Write ARC buffers.
7238fa94a07fSbrendan 		 */
7239dcbf3bd6SGeorge Wilson 		wrote = l2arc_write_buffers(spa, dev, size);
72405a98e54bSBrendan Gregg - Sun Microsystems 
72415a98e54bSBrendan Gregg - Sun Microsystems 		/*
72425a98e54bSBrendan Gregg - Sun Microsystems 		 * Calculate interval between writes.
72435a98e54bSBrendan Gregg - Sun Microsystems 		 */
72445a98e54bSBrendan Gregg - Sun Microsystems 		next = l2arc_write_interval(begin, size, wrote);
7245e14bb325SJeff Bonwick 		spa_config_exit(spa, SCL_L2ARC, dev);
7246fa94a07fSbrendan 	}
7247fa94a07fSbrendan 
7248fa94a07fSbrendan 	l2arc_thread_exit = 0;
7249fa94a07fSbrendan 	cv_broadcast(&l2arc_feed_thr_cv);
7250fa94a07fSbrendan 	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
7251fa94a07fSbrendan 	thread_exit();
7252fa94a07fSbrendan }
7253fa94a07fSbrendan 
7254c5904d13Seschrock boolean_t
7255c5904d13Seschrock l2arc_vdev_present(vdev_t *vd)
7256c5904d13Seschrock {
7257c5904d13Seschrock 	l2arc_dev_t *dev;
7258c5904d13Seschrock 
7259c5904d13Seschrock 	mutex_enter(&l2arc_dev_mtx);
7260c5904d13Seschrock 	for (dev = list_head(l2arc_dev_list); dev != NULL;
7261c5904d13Seschrock 	    dev = list_next(l2arc_dev_list, dev)) {
7262c5904d13Seschrock 		if (dev->l2ad_vdev == vd)
7263c5904d13Seschrock 			break;
7264c5904d13Seschrock 	}
7265c5904d13Seschrock 	mutex_exit(&l2arc_dev_mtx);
7266c5904d13Seschrock 
7267c5904d13Seschrock 	return (dev != NULL);
7268c5904d13Seschrock }
7269c5904d13Seschrock 
7270fa94a07fSbrendan /*
7271fa94a07fSbrendan  * Add a vdev for use by the L2ARC.  By this point the spa has already
7272fa94a07fSbrendan  * validated the vdev and opened it.
7273fa94a07fSbrendan  */
7274fa94a07fSbrendan void
7275573ca77eSGeorge Wilson l2arc_add_vdev(spa_t *spa, vdev_t *vd)
7276fa94a07fSbrendan {
7277fa94a07fSbrendan 	l2arc_dev_t *adddev;
7278fa94a07fSbrendan 
7279c5904d13Seschrock 	ASSERT(!l2arc_vdev_present(vd));
7280c5904d13Seschrock 
7281fa94a07fSbrendan 	/*
7282fa94a07fSbrendan 	 * Create a new l2arc device entry.
7283fa94a07fSbrendan 	 */
7284fa94a07fSbrendan 	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
7285fa94a07fSbrendan 	adddev->l2ad_spa = spa;
7286fa94a07fSbrendan 	adddev->l2ad_vdev = vd;
7287573ca77eSGeorge Wilson 	adddev->l2ad_start = VDEV_LABEL_START_SIZE;
7288573ca77eSGeorge Wilson 	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
7289fa94a07fSbrendan 	adddev->l2ad_hand = adddev->l2ad_start;
7290fa94a07fSbrendan 	adddev->l2ad_first = B_TRUE;
72915a98e54bSBrendan Gregg - Sun Microsystems 	adddev->l2ad_writing = B_FALSE;
7292fa94a07fSbrendan 
729389c86e32SChris Williamson 	mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
7294fa94a07fSbrendan 	/*
7295fa94a07fSbrendan 	 * This is a list of all ARC buffers that are still valid on the
7296fa94a07fSbrendan 	 * device.
7297fa94a07fSbrendan 	 */
729889c86e32SChris Williamson 	list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
729989c86e32SChris Williamson 	    offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
7300fa94a07fSbrendan 
7301b24ab676SJeff Bonwick 	vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
7302a52fc310SPrakash Surya 	refcount_create(&adddev->l2ad_alloc);
7303fa94a07fSbrendan 
7304fa94a07fSbrendan 	/*
7305fa94a07fSbrendan 	 * Add device to global list
7306fa94a07fSbrendan 	 */
7307fa94a07fSbrendan 	mutex_enter(&l2arc_dev_mtx);
7308fa94a07fSbrendan 	list_insert_head(l2arc_dev_list, adddev);
7309fa94a07fSbrendan 	atomic_inc_64(&l2arc_ndev);
7310fa94a07fSbrendan 	mutex_exit(&l2arc_dev_mtx);
7311fa94a07fSbrendan }
7312fa94a07fSbrendan 
7313fa94a07fSbrendan /*
7314fa94a07fSbrendan  * Remove a vdev from the L2ARC.
7315fa94a07fSbrendan  */
7316fa94a07fSbrendan void
7317fa94a07fSbrendan l2arc_remove_vdev(vdev_t *vd)
7318fa94a07fSbrendan {
7319fa94a07fSbrendan 	l2arc_dev_t *dev, *nextdev, *remdev = NULL;
7320fa94a07fSbrendan 
7321fa94a07fSbrendan 	/*
7322fa94a07fSbrendan 	 * Find the device by vdev
7323fa94a07fSbrendan 	 */
7324fa94a07fSbrendan 	mutex_enter(&l2arc_dev_mtx);
7325fa94a07fSbrendan 	for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
7326fa94a07fSbrendan 		nextdev = list_next(l2arc_dev_list, dev);
7327fa94a07fSbrendan 		if (vd == dev->l2ad_vdev) {
7328fa94a07fSbrendan 			remdev = dev;
7329fa94a07fSbrendan 			break;
7330fa94a07fSbrendan 		}
7331fa94a07fSbrendan 	}
7332dcbf3bd6SGeorge Wilson 	ASSERT3P(remdev, !=, NULL);
7333fa94a07fSbrendan 
7334fa94a07fSbrendan 	/*
7335fa94a07fSbrendan 	 * Remove device from global list
7336fa94a07fSbrendan 	 */
7337fa94a07fSbrendan 	list_remove(l2arc_dev_list, remdev);
7338fa94a07fSbrendan 	l2arc_dev_last = NULL;		/* may have been invalidated */
73393a737e0dSbrendan 	atomic_dec_64(&l2arc_ndev);
73403a737e0dSbrendan 	mutex_exit(&l2arc_dev_mtx);
7341fa94a07fSbrendan 
7342fa94a07fSbrendan 	/*
7343fa94a07fSbrendan 	 * Clear all buflists and ARC references.  L2ARC device flush.
7344fa94a07fSbrendan 	 */
7345fa94a07fSbrendan 	l2arc_evict(remdev, 0, B_TRUE);
734689c86e32SChris Williamson 	list_destroy(&remdev->l2ad_buflist);
734789c86e32SChris Williamson 	mutex_destroy(&remdev->l2ad_mtx);
7348a52fc310SPrakash Surya 	refcount_destroy(&remdev->l2ad_alloc);
7349fa94a07fSbrendan 	kmem_free(remdev, sizeof (l2arc_dev_t));
7350fa94a07fSbrendan }
7351fa94a07fSbrendan 
7352fa94a07fSbrendan void
7353e14bb325SJeff Bonwick l2arc_init(void)
7354fa94a07fSbrendan {
7355fa94a07fSbrendan 	l2arc_thread_exit = 0;
7356fa94a07fSbrendan 	l2arc_ndev = 0;
7357fa94a07fSbrendan 	l2arc_writes_sent = 0;
7358fa94a07fSbrendan 	l2arc_writes_done = 0;
7359fa94a07fSbrendan 
7360fa94a07fSbrendan 	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
7361fa94a07fSbrendan 	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
7362fa94a07fSbrendan 	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
7363fa94a07fSbrendan 	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
7364fa94a07fSbrendan 
7365fa94a07fSbrendan 	l2arc_dev_list = &L2ARC_dev_list;
7366fa94a07fSbrendan 	l2arc_free_on_write = &L2ARC_free_on_write;
7367fa94a07fSbrendan 	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
7368fa94a07fSbrendan 	    offsetof(l2arc_dev_t, l2ad_node));
7369fa94a07fSbrendan 	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
7370fa94a07fSbrendan 	    offsetof(l2arc_data_free_t, l2df_list_node));
7371fa94a07fSbrendan }
7372fa94a07fSbrendan 
7373fa94a07fSbrendan void
7374e14bb325SJeff Bonwick l2arc_fini(void)
7375fa94a07fSbrendan {
73763a737e0dSbrendan 	/*
73773a737e0dSbrendan 	 * This is called from dmu_fini(), which is called from spa_fini();
73783a737e0dSbrendan 	 * Because of this, we can assume that all l2arc devices have
73793a737e0dSbrendan 	 * already been removed when the pools themselves were removed.
73803a737e0dSbrendan 	 */
73813a737e0dSbrendan 
73823a737e0dSbrendan 	l2arc_do_free_on_write();
73833a737e0dSbrendan 
7384fa94a07fSbrendan 	mutex_destroy(&l2arc_feed_thr_lock);
7385fa94a07fSbrendan 	cv_destroy(&l2arc_feed_thr_cv);
7386fa94a07fSbrendan 	mutex_destroy(&l2arc_dev_mtx);
7387fa94a07fSbrendan 	mutex_destroy(&l2arc_free_on_write_mtx);
7388fa94a07fSbrendan 
7389fa94a07fSbrendan 	list_destroy(l2arc_dev_list);
7390fa94a07fSbrendan 	list_destroy(l2arc_free_on_write);
7391fa94a07fSbrendan }
7392e14bb325SJeff Bonwick 
7393e14bb325SJeff Bonwick void
7394e14bb325SJeff Bonwick l2arc_start(void)
7395e14bb325SJeff Bonwick {
73968ad4d6ddSJeff Bonwick 	if (!(spa_mode_global & FWRITE))
7397e14bb325SJeff Bonwick 		return;
7398e14bb325SJeff Bonwick 
7399e14bb325SJeff Bonwick 	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
7400e14bb325SJeff Bonwick 	    TS_RUN, minclsyspri);
7401e14bb325SJeff Bonwick }
7402e14bb325SJeff Bonwick 
7403e14bb325SJeff Bonwick void
7404e14bb325SJeff Bonwick l2arc_stop(void)
7405e14bb325SJeff Bonwick {
74068ad4d6ddSJeff Bonwick 	if (!(spa_mode_global & FWRITE))
7407e14bb325SJeff Bonwick 		return;
7408e14bb325SJeff Bonwick 
7409e14bb325SJeff Bonwick 	mutex_enter(&l2arc_feed_thr_lock);
7410e14bb325SJeff Bonwick 	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
7411e14bb325SJeff Bonwick 	l2arc_thread_exit = 1;
7412e14bb325SJeff Bonwick 	while (l2arc_thread_exit != 0)
7413e14bb325SJeff Bonwick 		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
7414e14bb325SJeff Bonwick 	mutex_exit(&l2arc_feed_thr_lock);
7415e14bb325SJeff Bonwick }
7416