xref: /illumos-gate/usr/src/uts/common/fs/zfs/arc.c (revision abe1fd01)
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.
24fa98e487SMatthew Ahrens  * Copyright (c) 2011, 2018 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>
277de753e34SBrad 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 
288de753e34SBrad Lewis /*
289de753e34SBrad Lewis  * This thread's job is to keep enough free memory in the system, by
290de753e34SBrad Lewis  * calling arc_kmem_reap_now() plus arc_shrink(), which improves
291de753e34SBrad Lewis  * arc_available_memory().
292de753e34SBrad Lewis  */
293de753e34SBrad Lewis static zthr_t		*arc_reap_zthr;
294de753e34SBrad Lewis 
295de753e34SBrad Lewis /*
296de753e34SBrad Lewis  * This thread's job is to keep arc_size under arc_c, by calling
297de753e34SBrad Lewis  * arc_adjust(), which improves arc_is_overflowing().
298de753e34SBrad Lewis  */
299de753e34SBrad Lewis static zthr_t		*arc_adjust_zthr;
300de753e34SBrad Lewis 
301de753e34SBrad Lewis static kmutex_t		arc_adjust_lock;
302de753e34SBrad Lewis static kcondvar_t	arc_adjust_waiters_cv;
303de753e34SBrad 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 */
317de753e34SBrad Lewis int arc_grow_retry = 60;
318fa9e4066Sahrens 
319de753e34SBrad Lewis /*
320de753e34SBrad Lewis  * Minimum time between calls to arc_kmem_reap_soon().  Note that this will
321de753e34SBrad Lewis  * be converted to ticks, so with the default hz=100, a setting of 15 ms
322de753e34SBrad Lewis  * will actually wait 2 ticks, or 20ms.
323de753e34SBrad Lewis  */
324de753e34SBrad 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 */
327de753e34SBrad 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 */
330de753e34SBrad Lewis int arc_p_min_shift = 4;
3315a98e54bSBrendan Gregg - Sun Microsystems 
3325a98e54bSBrendan Gregg - Sun Microsystems /* log2(fraction of arc to reclaim) */
333de753e34SBrad 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 
358de753e34SBrad 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 
382*abe1fd01SDon Brady /*
383*abe1fd01SDon Brady  * ARC dirty data constraints for arc_tempreserve_space() throttle
384*abe1fd01SDon Brady  */
385*abe1fd01SDon Brady uint_t zfs_arc_dirty_limit_percent = 50;	/* total dirty data limit */
386*abe1fd01SDon Brady uint_t zfs_arc_anon_limit_percent = 25;		/* anon block dirty limit */
387*abe1fd01SDon Brady uint_t zfs_arc_pool_dirty_percent = 20;		/* each pool's anon allowance */
388*abe1fd01SDon Brady 
389dcbf3bd6SGeorge Wilson boolean_t zfs_compressed_arc_enabled = B_TRUE;
390dcbf3bd6SGeorge Wilson 
391fa9e4066Sahrens /*
392fa94a07fSbrendan  * Note that buffers can be in one of 6 states:
393fa9e4066Sahrens  *	ARC_anon	- anonymous (discussed below)
394ea8dc4b6Seschrock  *	ARC_mru		- recently used, currently cached
395ea8dc4b6Seschrock  *	ARC_mru_ghost	- recentely used, no longer in cache
396ea8dc4b6Seschrock  *	ARC_mfu		- frequently used, currently cached
397ea8dc4b6Seschrock  *	ARC_mfu_ghost	- frequently used, no longer in cache
398fa94a07fSbrendan  *	ARC_l2c_only	- exists in L2ARC but not other states
3990e8c6158Smaybee  * When there are no active references to the buffer, they are
4000e8c6158Smaybee  * are linked onto a list in one of these arc states.  These are
4010e8c6158Smaybee  * the only buffers that can be evicted or deleted.  Within each
4020e8c6158Smaybee  * state there are multiple lists, one for meta-data and one for
4030e8c6158Smaybee  * non-meta-data.  Meta-data (indirect blocks, blocks of dnodes,
4040e8c6158Smaybee  * etc.) is tracked separately so that it can be managed more
405fa94a07fSbrendan  * explicitly: favored over data, limited explicitly.
406fa9e4066Sahrens  *
407fa9e4066Sahrens  * Anonymous buffers are buffers that are not associated with
408fa9e4066Sahrens  * a DVA.  These are buffers that hold dirty block copies
409fa9e4066Sahrens  * before they are written to stable storage.  By definition,
410ea8dc4b6Seschrock  * they are "ref'd" and are considered part of arc_mru
411fa9e4066Sahrens  * that cannot be freed.  Generally, they will aquire a DVA
412ea8dc4b6Seschrock  * as they are written and migrate onto the arc_mru list.
413fa94a07fSbrendan  *
414fa94a07fSbrendan  * The ARC_l2c_only state is for buffers that are in the second
415fa94a07fSbrendan  * level ARC but no longer in any of the ARC_m* lists.  The second
416fa94a07fSbrendan  * level ARC itself may also contain buffers that are in any of
417fa94a07fSbrendan  * the ARC_m* states - meaning that a buffer can exist in two
418fa94a07fSbrendan  * places.  The reason for the ARC_l2c_only state is to keep the
419fa94a07fSbrendan  * buffer header in the hash table, so that reads that hit the
420fa94a07fSbrendan  * second level ARC benefit from these fast lookups.
421fa9e4066Sahrens  */
422fa9e4066Sahrens 
423fa9e4066Sahrens typedef struct arc_state {
424244781f1SPrakash Surya 	/*
425244781f1SPrakash Surya 	 * list of evictable buffers
426244781f1SPrakash Surya 	 */
42794c2d0ebSMatthew Ahrens 	multilist_t *arcs_list[ARC_BUFC_NUMTYPES];
428244781f1SPrakash Surya 	/*
429244781f1SPrakash Surya 	 * total amount of evictable data in this state
430244781f1SPrakash Surya 	 */
431dcbf3bd6SGeorge Wilson 	refcount_t arcs_esize[ARC_BUFC_NUMTYPES];
432244781f1SPrakash Surya 	/*
433244781f1SPrakash Surya 	 * total amount of data in this state; this includes: evictable,
434244781f1SPrakash Surya 	 * non-evictable, ARC_BUFC_DATA, and ARC_BUFC_METADATA.
435244781f1SPrakash Surya 	 */
4362fd872a7SPrakash Surya 	refcount_t arcs_size;
437fa9e4066Sahrens } arc_state_t;
438fa9e4066Sahrens 
439fa94a07fSbrendan /* The 6 states: */
440fa9e4066Sahrens static arc_state_t ARC_anon;
441ea8dc4b6Seschrock static arc_state_t ARC_mru;
442ea8dc4b6Seschrock static arc_state_t ARC_mru_ghost;
443ea8dc4b6Seschrock static arc_state_t ARC_mfu;
444ea8dc4b6Seschrock static arc_state_t ARC_mfu_ghost;
445fa94a07fSbrendan static arc_state_t ARC_l2c_only;
446fa9e4066Sahrens 
44744cb6abcSbmc typedef struct arc_stats {
44844cb6abcSbmc 	kstat_named_t arcstat_hits;
44944cb6abcSbmc 	kstat_named_t arcstat_misses;
45044cb6abcSbmc 	kstat_named_t arcstat_demand_data_hits;
45144cb6abcSbmc 	kstat_named_t arcstat_demand_data_misses;
45244cb6abcSbmc 	kstat_named_t arcstat_demand_metadata_hits;
45344cb6abcSbmc 	kstat_named_t arcstat_demand_metadata_misses;
45444cb6abcSbmc 	kstat_named_t arcstat_prefetch_data_hits;
45544cb6abcSbmc 	kstat_named_t arcstat_prefetch_data_misses;
45644cb6abcSbmc 	kstat_named_t arcstat_prefetch_metadata_hits;
45744cb6abcSbmc 	kstat_named_t arcstat_prefetch_metadata_misses;
45844cb6abcSbmc 	kstat_named_t arcstat_mru_hits;
45944cb6abcSbmc 	kstat_named_t arcstat_mru_ghost_hits;
46044cb6abcSbmc 	kstat_named_t arcstat_mfu_hits;
46144cb6abcSbmc 	kstat_named_t arcstat_mfu_ghost_hits;
46244cb6abcSbmc 	kstat_named_t arcstat_deleted;
4633e30c24aSWill Andrews 	/*
4643e30c24aSWill Andrews 	 * Number of buffers that could not be evicted because the hash lock
4653e30c24aSWill Andrews 	 * was held by another thread.  The lock may not necessarily be held
4663e30c24aSWill Andrews 	 * by something using the same buffer, since hash locks are shared
4673e30c24aSWill Andrews 	 * by multiple buffers.
4683e30c24aSWill Andrews 	 */
46944cb6abcSbmc 	kstat_named_t arcstat_mutex_miss;
4703e30c24aSWill Andrews 	/*
4713e30c24aSWill Andrews 	 * Number of buffers skipped because they have I/O in progress, are
4723e30c24aSWill Andrews 	 * indrect prefetch buffers that have not lived long enough, or are
4733e30c24aSWill Andrews 	 * not from the spa we're trying to evict from.
4743e30c24aSWill Andrews 	 */
47544cb6abcSbmc 	kstat_named_t arcstat_evict_skip;
476244781f1SPrakash Surya 	/*
477244781f1SPrakash Surya 	 * Number of times arc_evict_state() was unable to evict enough
478244781f1SPrakash Surya 	 * buffers to reach it's target amount.
479244781f1SPrakash Surya 	 */
480244781f1SPrakash Surya 	kstat_named_t arcstat_evict_not_enough;
4815ea40c06SBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_evict_l2_cached;
4825ea40c06SBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_evict_l2_eligible;
4835ea40c06SBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_evict_l2_ineligible;
484244781f1SPrakash Surya 	kstat_named_t arcstat_evict_l2_skip;
48544cb6abcSbmc 	kstat_named_t arcstat_hash_elements;
48644cb6abcSbmc 	kstat_named_t arcstat_hash_elements_max;
48744cb6abcSbmc 	kstat_named_t arcstat_hash_collisions;
48844cb6abcSbmc 	kstat_named_t arcstat_hash_chains;
48944cb6abcSbmc 	kstat_named_t arcstat_hash_chain_max;
49044cb6abcSbmc 	kstat_named_t arcstat_p;
49144cb6abcSbmc 	kstat_named_t arcstat_c;
49244cb6abcSbmc 	kstat_named_t arcstat_c_min;
49344cb6abcSbmc 	kstat_named_t arcstat_c_max;
4943a2d8a1bSPaul Dagnelie 	/* Not updated directly; only synced in arc_kstat_update. */
49544cb6abcSbmc 	kstat_named_t arcstat_size;
496dcbf3bd6SGeorge Wilson 	/*
497770499e1SDan Kimmel 	 * Number of compressed bytes stored in the arc_buf_hdr_t's b_pabd.
498dcbf3bd6SGeorge Wilson 	 * Note that the compressed bytes may match the uncompressed bytes
499dcbf3bd6SGeorge Wilson 	 * if the block is either not compressed or compressed arc is disabled.
500dcbf3bd6SGeorge Wilson 	 */
501dcbf3bd6SGeorge Wilson 	kstat_named_t arcstat_compressed_size;
502dcbf3bd6SGeorge Wilson 	/*
503770499e1SDan Kimmel 	 * Uncompressed size of the data stored in b_pabd. If compressed
504dcbf3bd6SGeorge Wilson 	 * arc is disabled then this value will be identical to the stat
505dcbf3bd6SGeorge Wilson 	 * above.
506dcbf3bd6SGeorge Wilson 	 */
507dcbf3bd6SGeorge Wilson 	kstat_named_t arcstat_uncompressed_size;
508dcbf3bd6SGeorge Wilson 	/*
509dcbf3bd6SGeorge Wilson 	 * Number of bytes stored in all the arc_buf_t's. This is classified
510dcbf3bd6SGeorge Wilson 	 * as "overhead" since this data is typically short-lived and will
511dcbf3bd6SGeorge Wilson 	 * be evicted from the arc when it becomes unreferenced unless the
512dcbf3bd6SGeorge Wilson 	 * zfs_keep_uncompressed_metadata or zfs_keep_uncompressed_level
513dcbf3bd6SGeorge Wilson 	 * values have been set (see comment in dbuf.c for more information).
514dcbf3bd6SGeorge Wilson 	 */
515dcbf3bd6SGeorge Wilson 	kstat_named_t arcstat_overhead_size;
5164076b1bfSPrakash Surya 	/*
5174076b1bfSPrakash Surya 	 * Number of bytes consumed by internal ARC structures necessary
5184076b1bfSPrakash Surya 	 * for tracking purposes; these structures are not actually
5194076b1bfSPrakash Surya 	 * backed by ARC buffers. This includes arc_buf_hdr_t structures
5204076b1bfSPrakash Surya 	 * (allocated via arc_buf_hdr_t_full and arc_buf_hdr_t_l2only
5214076b1bfSPrakash Surya 	 * caches), and arc_buf_t structures (allocated via arc_buf_t
5224076b1bfSPrakash Surya 	 * cache).
5233a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5244076b1bfSPrakash Surya 	 */
525fa94a07fSbrendan 	kstat_named_t arcstat_hdr_size;
5264076b1bfSPrakash Surya 	/*
5274076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers of type equal to
5284076b1bfSPrakash Surya 	 * ARC_BUFC_DATA. This is generally consumed by buffers backing
5294076b1bfSPrakash Surya 	 * on disk user data (e.g. plain file contents).
5303a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5314076b1bfSPrakash Surya 	 */
5325a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_data_size;
5334076b1bfSPrakash Surya 	/*
5344076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers of type equal to
5354076b1bfSPrakash Surya 	 * ARC_BUFC_METADATA. This is generally consumed by buffers
5364076b1bfSPrakash Surya 	 * backing on disk data that is used for internal ZFS
5374076b1bfSPrakash Surya 	 * structures (e.g. ZAP, dnode, indirect blocks, etc).
5383a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5394076b1bfSPrakash Surya 	 */
5404076b1bfSPrakash Surya 	kstat_named_t arcstat_metadata_size;
5414076b1bfSPrakash Surya 	/*
5424076b1bfSPrakash Surya 	 * Number of bytes consumed by various buffers and structures
5434076b1bfSPrakash Surya 	 * not actually backed with ARC buffers. This includes bonus
5444076b1bfSPrakash Surya 	 * buffers (allocated directly via zio_buf_* functions),
5454076b1bfSPrakash Surya 	 * dmu_buf_impl_t structures (allocated via dmu_buf_impl_t
5464076b1bfSPrakash Surya 	 * cache), and dnode_t structures (allocated via dnode_t cache).
5473a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5484076b1bfSPrakash Surya 	 */
5495a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_other_size;
5504076b1bfSPrakash Surya 	/*
5514076b1bfSPrakash Surya 	 * Total number of bytes consumed by ARC buffers residing in the
5524076b1bfSPrakash Surya 	 * arc_anon state. This includes *all* buffers in the arc_anon
5534076b1bfSPrakash Surya 	 * state; e.g. data, metadata, evictable, and unevictable buffers
5544076b1bfSPrakash Surya 	 * are all included in this value.
5553a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5564076b1bfSPrakash Surya 	 */
5574076b1bfSPrakash Surya 	kstat_named_t arcstat_anon_size;
5584076b1bfSPrakash Surya 	/*
5594076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
5604076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_DATA,
5614076b1bfSPrakash Surya 	 * residing in the arc_anon state, and are eligible for eviction
5624076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
5633a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5644076b1bfSPrakash Surya 	 */
5654076b1bfSPrakash Surya 	kstat_named_t arcstat_anon_evictable_data;
5664076b1bfSPrakash Surya 	/*
5674076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
5684076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_METADATA,
5694076b1bfSPrakash Surya 	 * residing in the arc_anon state, and are eligible for eviction
5704076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
5713a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5724076b1bfSPrakash Surya 	 */
5734076b1bfSPrakash Surya 	kstat_named_t arcstat_anon_evictable_metadata;
5744076b1bfSPrakash Surya 	/*
5754076b1bfSPrakash Surya 	 * Total number of bytes consumed by ARC buffers residing in the
5764076b1bfSPrakash Surya 	 * arc_mru state. This includes *all* buffers in the arc_mru
5774076b1bfSPrakash Surya 	 * state; e.g. data, metadata, evictable, and unevictable buffers
5784076b1bfSPrakash Surya 	 * are all included in this value.
5793a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5804076b1bfSPrakash Surya 	 */
5814076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_size;
5824076b1bfSPrakash Surya 	/*
5834076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
5844076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_DATA,
5854076b1bfSPrakash Surya 	 * residing in the arc_mru state, and are eligible for eviction
5864076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
5873a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5884076b1bfSPrakash Surya 	 */
5894076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_evictable_data;
5904076b1bfSPrakash Surya 	/*
5914076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
5924076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_METADATA,
5934076b1bfSPrakash Surya 	 * residing in the arc_mru state, and are eligible for eviction
5944076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
5953a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5964076b1bfSPrakash Surya 	 */
5974076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_evictable_metadata;
5984076b1bfSPrakash Surya 	/*
5994076b1bfSPrakash Surya 	 * Total number of bytes that *would have been* consumed by ARC
6004076b1bfSPrakash Surya 	 * buffers in the arc_mru_ghost state. The key thing to note
6014076b1bfSPrakash Surya 	 * here, is the fact that this size doesn't actually indicate
6024076b1bfSPrakash Surya 	 * RAM consumption. The ghost lists only consist of headers and
6034076b1bfSPrakash Surya 	 * don't actually have ARC buffers linked off of these headers.
6044076b1bfSPrakash Surya 	 * Thus, *if* the headers had associated ARC buffers, these
6054076b1bfSPrakash Surya 	 * buffers *would have* consumed this number of bytes.
6063a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6074076b1bfSPrakash Surya 	 */
6084076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_ghost_size;
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_DATA, 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_data;
6164076b1bfSPrakash Surya 	/*
6174076b1bfSPrakash Surya 	 * Number of bytes that *would have been* consumed by ARC
6184076b1bfSPrakash Surya 	 * buffers that are eligible for eviction, of type
6194076b1bfSPrakash Surya 	 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
6203a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6214076b1bfSPrakash Surya 	 */
6224076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_ghost_evictable_metadata;
6234076b1bfSPrakash Surya 	/*
6244076b1bfSPrakash Surya 	 * Total number of bytes consumed by ARC buffers residing in the
6254076b1bfSPrakash Surya 	 * arc_mfu state. This includes *all* buffers in the arc_mfu
6264076b1bfSPrakash Surya 	 * state; e.g. data, metadata, evictable, and unevictable buffers
6274076b1bfSPrakash Surya 	 * are all included in this value.
6283a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6294076b1bfSPrakash Surya 	 */
6304076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_size;
6314076b1bfSPrakash Surya 	/*
6324076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that are eligible for
6334076b1bfSPrakash Surya 	 * eviction, of type ARC_BUFC_DATA, and reside in the arc_mfu
6344076b1bfSPrakash Surya 	 * state.
6353a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6364076b1bfSPrakash Surya 	 */
6374076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_evictable_data;
6384076b1bfSPrakash Surya 	/*
6394076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that are eligible for
6404076b1bfSPrakash Surya 	 * eviction, of type ARC_BUFC_METADATA, and reside in the
6414076b1bfSPrakash Surya 	 * arc_mfu state.
6423a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6434076b1bfSPrakash Surya 	 */
6444076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_evictable_metadata;
6454076b1bfSPrakash Surya 	/*
6464076b1bfSPrakash Surya 	 * Total number of bytes that *would have been* consumed by ARC
6474076b1bfSPrakash Surya 	 * buffers in the arc_mfu_ghost state. See the comment above
6484076b1bfSPrakash Surya 	 * arcstat_mru_ghost_size for more details.
6493a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6504076b1bfSPrakash Surya 	 */
6514076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_ghost_size;
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_DATA, and linked off the arc_mfu_ghost state.
6563a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6574076b1bfSPrakash Surya 	 */
6584076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_ghost_evictable_data;
6594076b1bfSPrakash Surya 	/*
6604076b1bfSPrakash Surya 	 * Number of bytes that *would have been* consumed by ARC
6614076b1bfSPrakash Surya 	 * buffers that are eligible for eviction, of type
6624076b1bfSPrakash Surya 	 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
6633a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6644076b1bfSPrakash Surya 	 */
6654076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_ghost_evictable_metadata;
666fa94a07fSbrendan 	kstat_named_t arcstat_l2_hits;
667fa94a07fSbrendan 	kstat_named_t arcstat_l2_misses;
668fa94a07fSbrendan 	kstat_named_t arcstat_l2_feeds;
669fa94a07fSbrendan 	kstat_named_t arcstat_l2_rw_clash;
6705a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_l2_read_bytes;
6715a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_l2_write_bytes;
672fa94a07fSbrendan 	kstat_named_t arcstat_l2_writes_sent;
673fa94a07fSbrendan 	kstat_named_t arcstat_l2_writes_done;
674fa94a07fSbrendan 	kstat_named_t arcstat_l2_writes_error;
675244781f1SPrakash Surya 	kstat_named_t arcstat_l2_writes_lock_retry;
676fa94a07fSbrendan 	kstat_named_t arcstat_l2_evict_lock_retry;
677fa94a07fSbrendan 	kstat_named_t arcstat_l2_evict_reading;
67889c86e32SChris Williamson 	kstat_named_t arcstat_l2_evict_l1cached;
679fa94a07fSbrendan 	kstat_named_t arcstat_l2_free_on_write;
680fa94a07fSbrendan 	kstat_named_t arcstat_l2_abort_lowmem;
681fa94a07fSbrendan 	kstat_named_t arcstat_l2_cksum_bad;
682fa94a07fSbrendan 	kstat_named_t arcstat_l2_io_error;
68316a7e5acSAndriy Gapon 	kstat_named_t arcstat_l2_lsize;
68416a7e5acSAndriy Gapon 	kstat_named_t arcstat_l2_psize;
6853a2d8a1bSPaul Dagnelie 	/* Not updated directly; only synced in arc_kstat_update. */
686fa94a07fSbrendan 	kstat_named_t arcstat_l2_hdr_size;
6871ab7f2deSmaybee 	kstat_named_t arcstat_memory_throttle_count;
6883a2d8a1bSPaul Dagnelie 	/* Not updated directly; only synced in arc_kstat_update. */
68920128a08SGeorge Wilson 	kstat_named_t arcstat_meta_used;
69020128a08SGeorge Wilson 	kstat_named_t arcstat_meta_limit;
69120128a08SGeorge Wilson 	kstat_named_t arcstat_meta_max;
6923a5286a1SMatthew Ahrens 	kstat_named_t arcstat_meta_min;
693cf6106c8SMatthew Ahrens 	kstat_named_t arcstat_sync_wait_for_async;
694cf6106c8SMatthew Ahrens 	kstat_named_t arcstat_demand_hit_predictive_prefetch;
69544cb6abcSbmc } arc_stats_t;
69644cb6abcSbmc 
69744cb6abcSbmc static arc_stats_t arc_stats = {
69844cb6abcSbmc 	{ "hits",			KSTAT_DATA_UINT64 },
69944cb6abcSbmc 	{ "misses",			KSTAT_DATA_UINT64 },
70044cb6abcSbmc 	{ "demand_data_hits",		KSTAT_DATA_UINT64 },
70144cb6abcSbmc 	{ "demand_data_misses",		KSTAT_DATA_UINT64 },
70244cb6abcSbmc 	{ "demand_metadata_hits",	KSTAT_DATA_UINT64 },
70344cb6abcSbmc 	{ "demand_metadata_misses",	KSTAT_DATA_UINT64 },
70444cb6abcSbmc 	{ "prefetch_data_hits",		KSTAT_DATA_UINT64 },
70544cb6abcSbmc 	{ "prefetch_data_misses",	KSTAT_DATA_UINT64 },
70644cb6abcSbmc 	{ "prefetch_metadata_hits",	KSTAT_DATA_UINT64 },
70744cb6abcSbmc 	{ "prefetch_metadata_misses",	KSTAT_DATA_UINT64 },
70844cb6abcSbmc 	{ "mru_hits",			KSTAT_DATA_UINT64 },
70944cb6abcSbmc 	{ "mru_ghost_hits",		KSTAT_DATA_UINT64 },
71044cb6abcSbmc 	{ "mfu_hits",			KSTAT_DATA_UINT64 },
71144cb6abcSbmc 	{ "mfu_ghost_hits",		KSTAT_DATA_UINT64 },
71244cb6abcSbmc 	{ "deleted",			KSTAT_DATA_UINT64 },
71344cb6abcSbmc 	{ "mutex_miss",			KSTAT_DATA_UINT64 },
71444cb6abcSbmc 	{ "evict_skip",			KSTAT_DATA_UINT64 },
715244781f1SPrakash Surya 	{ "evict_not_enough",		KSTAT_DATA_UINT64 },
7165ea40c06SBrendan Gregg - Sun Microsystems 	{ "evict_l2_cached",		KSTAT_DATA_UINT64 },
7175ea40c06SBrendan Gregg - Sun Microsystems 	{ "evict_l2_eligible",		KSTAT_DATA_UINT64 },
7185ea40c06SBrendan Gregg - Sun Microsystems 	{ "evict_l2_ineligible",	KSTAT_DATA_UINT64 },
719244781f1SPrakash Surya 	{ "evict_l2_skip",		KSTAT_DATA_UINT64 },
72044cb6abcSbmc 	{ "hash_elements",		KSTAT_DATA_UINT64 },
72144cb6abcSbmc 	{ "hash_elements_max",		KSTAT_DATA_UINT64 },
72244cb6abcSbmc 	{ "hash_collisions",		KSTAT_DATA_UINT64 },
72344cb6abcSbmc 	{ "hash_chains",		KSTAT_DATA_UINT64 },
72444cb6abcSbmc 	{ "hash_chain_max",		KSTAT_DATA_UINT64 },
72544cb6abcSbmc 	{ "p",				KSTAT_DATA_UINT64 },
72644cb6abcSbmc 	{ "c",				KSTAT_DATA_UINT64 },
72744cb6abcSbmc 	{ "c_min",			KSTAT_DATA_UINT64 },
72844cb6abcSbmc 	{ "c_max",			KSTAT_DATA_UINT64 },
729fa94a07fSbrendan 	{ "size",			KSTAT_DATA_UINT64 },
730dcbf3bd6SGeorge Wilson 	{ "compressed_size",		KSTAT_DATA_UINT64 },
731dcbf3bd6SGeorge Wilson 	{ "uncompressed_size",		KSTAT_DATA_UINT64 },
732dcbf3bd6SGeorge Wilson 	{ "overhead_size",		KSTAT_DATA_UINT64 },
733fa94a07fSbrendan 	{ "hdr_size",			KSTAT_DATA_UINT64 },
7345a98e54bSBrendan Gregg - Sun Microsystems 	{ "data_size",			KSTAT_DATA_UINT64 },
7354076b1bfSPrakash Surya 	{ "metadata_size",		KSTAT_DATA_UINT64 },
7365a98e54bSBrendan Gregg - Sun Microsystems 	{ "other_size",			KSTAT_DATA_UINT64 },
7374076b1bfSPrakash Surya 	{ "anon_size",			KSTAT_DATA_UINT64 },
7384076b1bfSPrakash Surya 	{ "anon_evictable_data",	KSTAT_DATA_UINT64 },
7394076b1bfSPrakash Surya 	{ "anon_evictable_metadata",	KSTAT_DATA_UINT64 },
7404076b1bfSPrakash Surya 	{ "mru_size",			KSTAT_DATA_UINT64 },
7414076b1bfSPrakash Surya 	{ "mru_evictable_data",		KSTAT_DATA_UINT64 },
7424076b1bfSPrakash Surya 	{ "mru_evictable_metadata",	KSTAT_DATA_UINT64 },
7434076b1bfSPrakash Surya 	{ "mru_ghost_size",		KSTAT_DATA_UINT64 },
7444076b1bfSPrakash Surya 	{ "mru_ghost_evictable_data",	KSTAT_DATA_UINT64 },
7454076b1bfSPrakash Surya 	{ "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
7464076b1bfSPrakash Surya 	{ "mfu_size",			KSTAT_DATA_UINT64 },
7474076b1bfSPrakash Surya 	{ "mfu_evictable_data",		KSTAT_DATA_UINT64 },
7484076b1bfSPrakash Surya 	{ "mfu_evictable_metadata",	KSTAT_DATA_UINT64 },
7494076b1bfSPrakash Surya 	{ "mfu_ghost_size",		KSTAT_DATA_UINT64 },
7504076b1bfSPrakash Surya 	{ "mfu_ghost_evictable_data",	KSTAT_DATA_UINT64 },
7514076b1bfSPrakash Surya 	{ "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
752fa94a07fSbrendan 	{ "l2_hits",			KSTAT_DATA_UINT64 },
753fa94a07fSbrendan 	{ "l2_misses",			KSTAT_DATA_UINT64 },
754fa94a07fSbrendan 	{ "l2_feeds",			KSTAT_DATA_UINT64 },
755fa94a07fSbrendan 	{ "l2_rw_clash",		KSTAT_DATA_UINT64 },
7565a98e54bSBrendan Gregg - Sun Microsystems 	{ "l2_read_bytes",		KSTAT_DATA_UINT64 },
7575a98e54bSBrendan Gregg - Sun Microsystems 	{ "l2_write_bytes",		KSTAT_DATA_UINT64 },
758fa94a07fSbrendan 	{ "l2_writes_sent",		KSTAT_DATA_UINT64 },
759fa94a07fSbrendan 	{ "l2_writes_done",		KSTAT_DATA_UINT64 },
760fa94a07fSbrendan 	{ "l2_writes_error",		KSTAT_DATA_UINT64 },
761244781f1SPrakash Surya 	{ "l2_writes_lock_retry",	KSTAT_DATA_UINT64 },
762fa94a07fSbrendan 	{ "l2_evict_lock_retry",	KSTAT_DATA_UINT64 },
763fa94a07fSbrendan 	{ "l2_evict_reading",		KSTAT_DATA_UINT64 },
76489c86e32SChris Williamson 	{ "l2_evict_l1cached",		KSTAT_DATA_UINT64 },
765fa94a07fSbrendan 	{ "l2_free_on_write",		KSTAT_DATA_UINT64 },
766fa94a07fSbrendan 	{ "l2_abort_lowmem",		KSTAT_DATA_UINT64 },
767fa94a07fSbrendan 	{ "l2_cksum_bad",		KSTAT_DATA_UINT64 },
768fa94a07fSbrendan 	{ "l2_io_error",		KSTAT_DATA_UINT64 },
769fa94a07fSbrendan 	{ "l2_size",			KSTAT_DATA_UINT64 },
770aad02571SSaso Kiselkov 	{ "l2_asize",			KSTAT_DATA_UINT64 },
7711ab7f2deSmaybee 	{ "l2_hdr_size",		KSTAT_DATA_UINT64 },
7729253d63dSGeorge Wilson 	{ "memory_throttle_count",	KSTAT_DATA_UINT64 },
77320128a08SGeorge Wilson 	{ "arc_meta_used",		KSTAT_DATA_UINT64 },
77420128a08SGeorge Wilson 	{ "arc_meta_limit",		KSTAT_DATA_UINT64 },
7753a5286a1SMatthew Ahrens 	{ "arc_meta_max",		KSTAT_DATA_UINT64 },
776cf6106c8SMatthew Ahrens 	{ "arc_meta_min",		KSTAT_DATA_UINT64 },
777cf6106c8SMatthew Ahrens 	{ "sync_wait_for_async",	KSTAT_DATA_UINT64 },
778cf6106c8SMatthew Ahrens 	{ "demand_hit_predictive_prefetch", KSTAT_DATA_UINT64 },
77944cb6abcSbmc };
78044cb6abcSbmc 
78144cb6abcSbmc #define	ARCSTAT(stat)	(arc_stats.stat.value.ui64)
78244cb6abcSbmc 
78344cb6abcSbmc #define	ARCSTAT_INCR(stat, val) \
784f7170741SWill Andrews 	atomic_add_64(&arc_stats.stat.value.ui64, (val))
78544cb6abcSbmc 
786b24ab676SJeff Bonwick #define	ARCSTAT_BUMP(stat)	ARCSTAT_INCR(stat, 1)
78744cb6abcSbmc #define	ARCSTAT_BUMPDOWN(stat)	ARCSTAT_INCR(stat, -1)
78844cb6abcSbmc 
78944cb6abcSbmc #define	ARCSTAT_MAX(stat, val) {					\
79044cb6abcSbmc 	uint64_t m;							\
79144cb6abcSbmc 	while ((val) > (m = arc_stats.stat.value.ui64) &&		\
79244cb6abcSbmc 	    (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val))))	\
79344cb6abcSbmc 		continue;						\
79444cb6abcSbmc }
79544cb6abcSbmc 
79644cb6abcSbmc #define	ARCSTAT_MAXSTAT(stat) \
79744cb6abcSbmc 	ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
79844cb6abcSbmc 
79944cb6abcSbmc /*
80044cb6abcSbmc  * We define a macro to allow ARC hits/misses to be easily broken down by
80144cb6abcSbmc  * two separate conditions, giving a total of four different subtypes for
80244cb6abcSbmc  * each of hits and misses (so eight statistics total).
80344cb6abcSbmc  */
80444cb6abcSbmc #define	ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
80544cb6abcSbmc 	if (cond1) {							\
80644cb6abcSbmc 		if (cond2) {						\
80744cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
80844cb6abcSbmc 		} else {						\
80944cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
81044cb6abcSbmc 		}							\
81144cb6abcSbmc 	} else {							\
81244cb6abcSbmc 		if (cond2) {						\
81344cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
81444cb6abcSbmc 		} else {						\
81544cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
81644cb6abcSbmc 		}							\
81744cb6abcSbmc 	}
81844cb6abcSbmc 
81944cb6abcSbmc kstat_t			*arc_ksp;
820b24ab676SJeff Bonwick static arc_state_t	*arc_anon;
82144cb6abcSbmc static arc_state_t	*arc_mru;
82244cb6abcSbmc static arc_state_t	*arc_mru_ghost;
82344cb6abcSbmc static arc_state_t	*arc_mfu;
82444cb6abcSbmc static arc_state_t	*arc_mfu_ghost;
825fa94a07fSbrendan static arc_state_t	*arc_l2c_only;
82644cb6abcSbmc 
82744cb6abcSbmc /*
82844cb6abcSbmc  * There are several ARC variables that are critical to export as kstats --
82944cb6abcSbmc  * but we don't want to have to grovel around in the kstat whenever we wish to
83044cb6abcSbmc  * manipulate them.  For these variables, we therefore define them to be in
83144cb6abcSbmc  * terms of the statistic variable.  This assures that we are not introducing
83244cb6abcSbmc  * the possibility of inconsistency by having shadow copies of the variables,
83344cb6abcSbmc  * while still allowing the code to be readable.
83444cb6abcSbmc  */
83544cb6abcSbmc #define	arc_p		ARCSTAT(arcstat_p)	/* target size of MRU */
83644cb6abcSbmc #define	arc_c		ARCSTAT(arcstat_c)	/* target size of cache */
83744cb6abcSbmc #define	arc_c_min	ARCSTAT(arcstat_c_min)	/* min target cache size */
83844cb6abcSbmc #define	arc_c_max	ARCSTAT(arcstat_c_max)	/* max target cache size */
83920128a08SGeorge Wilson #define	arc_meta_limit	ARCSTAT(arcstat_meta_limit) /* max size for metadata */
8403a5286a1SMatthew Ahrens #define	arc_meta_min	ARCSTAT(arcstat_meta_min) /* min size for metadata */
84120128a08SGeorge Wilson #define	arc_meta_max	ARCSTAT(arcstat_meta_max) /* max size of metadata */
84244cb6abcSbmc 
843dcbf3bd6SGeorge Wilson /* compressed size of entire arc */
844dcbf3bd6SGeorge Wilson #define	arc_compressed_size	ARCSTAT(arcstat_compressed_size)
845dcbf3bd6SGeorge Wilson /* uncompressed size of entire arc */
846dcbf3bd6SGeorge Wilson #define	arc_uncompressed_size	ARCSTAT(arcstat_uncompressed_size)
847dcbf3bd6SGeorge Wilson /* number of bytes in the arc from arc_buf_t's */
848dcbf3bd6SGeorge Wilson #define	arc_overhead_size	ARCSTAT(arcstat_overhead_size)
849aad02571SSaso Kiselkov 
8503a2d8a1bSPaul Dagnelie /*
8513a2d8a1bSPaul Dagnelie  * There are also some ARC variables that we want to export, but that are
8523a2d8a1bSPaul Dagnelie  * updated so often that having the canonical representation be the statistic
8533a2d8a1bSPaul Dagnelie  * variable causes a performance bottleneck. We want to use aggsum_t's for these
8543a2d8a1bSPaul Dagnelie  * instead, but still be able to export the kstat in the same way as before.
8553a2d8a1bSPaul Dagnelie  * The solution is to always use the aggsum version, except in the kstat update
8563a2d8a1bSPaul Dagnelie  * callback.
8573a2d8a1bSPaul Dagnelie  */
8583a2d8a1bSPaul Dagnelie aggsum_t arc_size;
8593a2d8a1bSPaul Dagnelie aggsum_t arc_meta_used;
8603a2d8a1bSPaul Dagnelie aggsum_t astat_data_size;
8613a2d8a1bSPaul Dagnelie aggsum_t astat_metadata_size;
8623a2d8a1bSPaul Dagnelie aggsum_t astat_hdr_size;
8633a2d8a1bSPaul Dagnelie aggsum_t astat_other_size;
8643a2d8a1bSPaul Dagnelie aggsum_t astat_l2_hdr_size;
8653a2d8a1bSPaul Dagnelie 
86644cb6abcSbmc static int		arc_no_grow;	/* Don't try to grow cache size */
867de753e34SBrad Lewis static hrtime_t		arc_growtime;
86844cb6abcSbmc static uint64_t		arc_tempreserve;
8692fdbea25SAleksandr Guzovskiy static uint64_t		arc_loaned_bytes;
870fa9e4066Sahrens 
871fa9e4066Sahrens typedef struct arc_callback arc_callback_t;
872fa9e4066Sahrens 
873fa9e4066Sahrens struct arc_callback {
874fa9e4066Sahrens 	void			*acb_private;
875c717a561Smaybee 	arc_done_func_t		*acb_done;
876fa9e4066Sahrens 	arc_buf_t		*acb_buf;
8775602294fSDan Kimmel 	boolean_t		acb_compressed;
878fa9e4066Sahrens 	zio_t			*acb_zio_dummy;
879fa9e4066Sahrens 	arc_callback_t		*acb_next;
880fa9e4066Sahrens };
881fa9e4066Sahrens 
882c717a561Smaybee typedef struct arc_write_callback arc_write_callback_t;
883c717a561Smaybee 
884c717a561Smaybee struct arc_write_callback {
885c717a561Smaybee 	void		*awcb_private;
886c717a561Smaybee 	arc_done_func_t	*awcb_ready;
8878df0bcf0SPaul Dagnelie 	arc_done_func_t	*awcb_children_ready;
88869962b56SMatthew Ahrens 	arc_done_func_t	*awcb_physdone;
889c717a561Smaybee 	arc_done_func_t	*awcb_done;
890c717a561Smaybee 	arc_buf_t	*awcb_buf;
891c717a561Smaybee };
892c717a561Smaybee 
89389c86e32SChris Williamson /*
89489c86e32SChris Williamson  * ARC buffers are separated into multiple structs as a memory saving measure:
89589c86e32SChris Williamson  *   - Common fields struct, always defined, and embedded within it:
89689c86e32SChris Williamson  *       - L2-only fields, always allocated but undefined when not in L2ARC
89789c86e32SChris Williamson  *       - L1-only fields, only allocated when in L1ARC
89889c86e32SChris Williamson  *
89989c86e32SChris Williamson  *           Buffer in L1                     Buffer only in L2
90089c86e32SChris Williamson  *    +------------------------+          +------------------------+
90189c86e32SChris Williamson  *    | arc_buf_hdr_t          |          | arc_buf_hdr_t          |
90289c86e32SChris Williamson  *    |                        |          |                        |
90389c86e32SChris Williamson  *    |                        |          |                        |
90489c86e32SChris Williamson  *    |                        |          |                        |
90589c86e32SChris Williamson  *    +------------------------+          +------------------------+
90689c86e32SChris Williamson  *    | l2arc_buf_hdr_t        |          | l2arc_buf_hdr_t        |
90789c86e32SChris Williamson  *    | (undefined if L1-only) |          |                        |
90889c86e32SChris Williamson  *    +------------------------+          +------------------------+
90989c86e32SChris Williamson  *    | l1arc_buf_hdr_t        |
91089c86e32SChris Williamson  *    |                        |
91189c86e32SChris Williamson  *    |                        |
91289c86e32SChris Williamson  *    |                        |
91389c86e32SChris Williamson  *    |                        |
91489c86e32SChris Williamson  *    +------------------------+
91589c86e32SChris Williamson  *
91689c86e32SChris Williamson  * Because it's possible for the L2ARC to become extremely large, we can wind
91789c86e32SChris Williamson  * up eating a lot of memory in L2ARC buffer headers, so the size of a header
91889c86e32SChris Williamson  * is minimized by only allocating the fields necessary for an L1-cached buffer
91989c86e32SChris Williamson  * when a header is actually in the L1 cache. The sub-headers (l1arc_buf_hdr and
92089c86e32SChris Williamson  * l2arc_buf_hdr) are embedded rather than allocated separately to save a couple
92189c86e32SChris Williamson  * words in pointers. arc_hdr_realloc() is used to switch a header between
92289c86e32SChris Williamson  * these two allocation states.
92389c86e32SChris Williamson  */
92489c86e32SChris Williamson typedef struct l1arc_buf_hdr {
9256b4acc8bSahrens 	kmutex_t		b_freeze_lock;
926dcbf3bd6SGeorge Wilson 	zio_cksum_t		*b_freeze_cksum;
92789c86e32SChris Williamson #ifdef ZFS_DEBUG
92889c86e32SChris Williamson 	/*
9295602294fSDan Kimmel 	 * Used for debugging with kmem_flags - by allocating and freeing
93089c86e32SChris Williamson 	 * b_thawed when the buffer is thawed, we get a record of the stack
93189c86e32SChris Williamson 	 * trace that thawed it.
93289c86e32SChris Williamson 	 */
9333f9d6ad7SLin Ling 	void			*b_thawed;
93489c86e32SChris Williamson #endif
9356b4acc8bSahrens 
936fa9e4066Sahrens 	arc_buf_t		*b_buf;
937dcbf3bd6SGeorge Wilson 	uint32_t		b_bufcnt;
93889c86e32SChris Williamson 	/* for waiting on writes to complete */
939ad23a2dbSjohansen 	kcondvar_t		b_cv;
940dcbf3bd6SGeorge Wilson 	uint8_t			b_byteswap;
941ad23a2dbSjohansen 
942fa9e4066Sahrens 	/* protected by arc state mutex */
943fa9e4066Sahrens 	arc_state_t		*b_state;
944244781f1SPrakash Surya 	multilist_node_t	b_arc_node;
945fa9e4066Sahrens 
946fa9e4066Sahrens 	/* updated atomically */
947fa9e4066Sahrens 	clock_t			b_arc_access;
948fa9e4066Sahrens 
949fa9e4066Sahrens 	/* self protecting */
950fa9e4066Sahrens 	refcount_t		b_refcnt;
951fa94a07fSbrendan 
95289c86e32SChris Williamson 	arc_callback_t		*b_acb;
953770499e1SDan Kimmel 	abd_t			*b_pabd;
95489c86e32SChris Williamson } l1arc_buf_hdr_t;
95589c86e32SChris Williamson 
95689c86e32SChris Williamson typedef struct l2arc_dev l2arc_dev_t;
95789c86e32SChris Williamson 
95889c86e32SChris Williamson typedef struct l2arc_buf_hdr {
95989c86e32SChris Williamson 	/* protected by arc_buf_hdr mutex */
96089c86e32SChris Williamson 	l2arc_dev_t		*b_dev;		/* L2ARC device */
96189c86e32SChris Williamson 	uint64_t		b_daddr;	/* disk address, offset byte */
96289c86e32SChris Williamson 
963fa94a07fSbrendan 	list_node_t		b_l2node;
96489c86e32SChris Williamson } l2arc_buf_hdr_t;
96589c86e32SChris Williamson 
96689c86e32SChris Williamson struct arc_buf_hdr {
96789c86e32SChris Williamson 	/* protected by hash lock */
96889c86e32SChris Williamson 	dva_t			b_dva;
96989c86e32SChris Williamson 	uint64_t		b_birth;
97089c86e32SChris Williamson 
971dcbf3bd6SGeorge Wilson 	arc_buf_contents_t	b_type;
97289c86e32SChris Williamson 	arc_buf_hdr_t		*b_hash_next;
97389c86e32SChris Williamson 	arc_flags_t		b_flags;
97489c86e32SChris Williamson 
975dcbf3bd6SGeorge Wilson 	/*
976dcbf3bd6SGeorge Wilson 	 * This field stores the size of the data buffer after
977dcbf3bd6SGeorge Wilson 	 * compression, and is set in the arc's zio completion handlers.
978dcbf3bd6SGeorge Wilson 	 * It is in units of SPA_MINBLOCKSIZE (e.g. 1 == 512 bytes).
979dcbf3bd6SGeorge Wilson 	 *
980dcbf3bd6SGeorge Wilson 	 * While the block pointers can store up to 32MB in their psize
981dcbf3bd6SGeorge Wilson 	 * field, we can only store up to 32MB minus 512B. This is due
982dcbf3bd6SGeorge Wilson 	 * to the bp using a bias of 1, whereas we use a bias of 0 (i.e.
983dcbf3bd6SGeorge Wilson 	 * a field of zeros represents 512B in the bp). We can't use a
984dcbf3bd6SGeorge Wilson 	 * bias of 1 since we need to reserve a psize of zero, here, to
985dcbf3bd6SGeorge Wilson 	 * represent holes and embedded blocks.
986dcbf3bd6SGeorge Wilson 	 *
987dcbf3bd6SGeorge Wilson 	 * This isn't a problem in practice, since the maximum size of a
988dcbf3bd6SGeorge Wilson 	 * buffer is limited to 16MB, so we never need to store 32MB in
989dcbf3bd6SGeorge Wilson 	 * this field. Even in the upstream illumos code base, the
990dcbf3bd6SGeorge Wilson 	 * maximum size of a buffer is limited to 16MB.
991dcbf3bd6SGeorge Wilson 	 */
992dcbf3bd6SGeorge Wilson 	uint16_t		b_psize;
993dcbf3bd6SGeorge Wilson 
994dcbf3bd6SGeorge Wilson 	/*
995dcbf3bd6SGeorge Wilson 	 * This field stores the size of the data buffer before
996dcbf3bd6SGeorge Wilson 	 * compression, and cannot change once set. It is in units
997dcbf3bd6SGeorge Wilson 	 * of SPA_MINBLOCKSIZE (e.g. 2 == 1024 bytes)
998dcbf3bd6SGeorge Wilson 	 */
999dcbf3bd6SGeorge Wilson 	uint16_t		b_lsize;	/* immutable */
1000dcbf3bd6SGeorge Wilson 	uint64_t		b_spa;		/* immutable */
100189c86e32SChris Williamson 
100289c86e32SChris Williamson 	/* L2ARC fields. Undefined when not in L2ARC. */
100389c86e32SChris Williamson 	l2arc_buf_hdr_t		b_l2hdr;
100489c86e32SChris Williamson 	/* L1ARC fields. Undefined when in l2arc_only state */
100589c86e32SChris Williamson 	l1arc_buf_hdr_t		b_l1hdr;
1006fa9e4066Sahrens };
1007fa9e4066Sahrens 
1008ea8dc4b6Seschrock #define	GHOST_STATE(state)	\
1009fa94a07fSbrendan 	((state) == arc_mru_ghost || (state) == arc_mfu_ghost ||	\
1010fa94a07fSbrendan 	(state) == arc_l2c_only)
1011ea8dc4b6Seschrock 
10127adb730bSGeorge Wilson #define	HDR_IN_HASH_TABLE(hdr)	((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
10137adb730bSGeorge Wilson #define	HDR_IO_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
10147adb730bSGeorge Wilson #define	HDR_IO_ERROR(hdr)	((hdr)->b_flags & ARC_FLAG_IO_ERROR)
10157adb730bSGeorge Wilson #define	HDR_PREFETCH(hdr)	((hdr)->b_flags & ARC_FLAG_PREFETCH)
1016dcbf3bd6SGeorge Wilson #define	HDR_COMPRESSION_ENABLED(hdr)	\
1017dcbf3bd6SGeorge Wilson 	((hdr)->b_flags & ARC_FLAG_COMPRESSED_ARC)
101889c86e32SChris Williamson 
10197adb730bSGeorge Wilson #define	HDR_L2CACHE(hdr)	((hdr)->b_flags & ARC_FLAG_L2CACHE)
10207adb730bSGeorge Wilson #define	HDR_L2_READING(hdr)	\
1021dcbf3bd6SGeorge Wilson 	(((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) &&	\
1022dcbf3bd6SGeorge Wilson 	((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
10237adb730bSGeorge Wilson #define	HDR_L2_WRITING(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITING)
10247adb730bSGeorge Wilson #define	HDR_L2_EVICTED(hdr)	((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
10257adb730bSGeorge Wilson #define	HDR_L2_WRITE_HEAD(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
1026dcbf3bd6SGeorge Wilson #define	HDR_SHARED_DATA(hdr)	((hdr)->b_flags & ARC_FLAG_SHARED_DATA)
1027fa9e4066Sahrens 
102889c86e32SChris Williamson #define	HDR_ISTYPE_METADATA(hdr)	\
1029dcbf3bd6SGeorge Wilson 	((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
103089c86e32SChris Williamson #define	HDR_ISTYPE_DATA(hdr)	(!HDR_ISTYPE_METADATA(hdr))
103189c86e32SChris Williamson 
103289c86e32SChris Williamson #define	HDR_HAS_L1HDR(hdr)	((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
103389c86e32SChris Williamson #define	HDR_HAS_L2HDR(hdr)	((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
103489c86e32SChris Williamson 
1035dcbf3bd6SGeorge Wilson /* For storing compression mode in b_flags */
1036dcbf3bd6SGeorge Wilson #define	HDR_COMPRESS_OFFSET	(highbit64(ARC_FLAG_COMPRESS_0) - 1)
1037dcbf3bd6SGeorge Wilson 
1038dcbf3bd6SGeorge Wilson #define	HDR_GET_COMPRESS(hdr)	((enum zio_compress)BF32_GET((hdr)->b_flags, \
1039dcbf3bd6SGeorge Wilson 	HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS))
1040dcbf3bd6SGeorge Wilson #define	HDR_SET_COMPRESS(hdr, cmp) BF32_SET((hdr)->b_flags, \
1041dcbf3bd6SGeorge Wilson 	HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS, (cmp));
1042dcbf3bd6SGeorge Wilson 
1043dcbf3bd6SGeorge Wilson #define	ARC_BUF_LAST(buf)	((buf)->b_next == NULL)
10445602294fSDan Kimmel #define	ARC_BUF_SHARED(buf)	((buf)->b_flags & ARC_BUF_FLAG_SHARED)
10455602294fSDan Kimmel #define	ARC_BUF_COMPRESSED(buf)	((buf)->b_flags & ARC_BUF_FLAG_COMPRESSED)
1046dcbf3bd6SGeorge Wilson 
1047e6c728e1Sbrendan /*
1048e6c728e1Sbrendan  * Other sizes
1049e6c728e1Sbrendan  */
1050e6c728e1Sbrendan 
105189c86e32SChris Williamson #define	HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
105289c86e32SChris Williamson #define	HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
1053e6c728e1Sbrendan 
1054fa9e4066Sahrens /*
1055fa9e4066Sahrens  * Hash table routines
1056fa9e4066Sahrens  */
1057fa9e4066Sahrens 
1058fa9e4066Sahrens #define	HT_LOCK_PAD	64
1059fa9e4066Sahrens 
1060fa9e4066Sahrens struct ht_lock {
1061fa9e4066Sahrens 	kmutex_t	ht_lock;
1062fa9e4066Sahrens #ifdef _KERNEL
1063fa9e4066Sahrens 	unsigned char	pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
1064fa9e4066Sahrens #endif
1065fa9e4066Sahrens };
1066fa9e4066Sahrens 
1067fa9e4066Sahrens #define	BUF_LOCKS 256
1068fa9e4066Sahrens typedef struct buf_hash_table {
1069fa9e4066Sahrens 	uint64_t ht_mask;
1070fa9e4066Sahrens 	arc_buf_hdr_t **ht_table;
1071fa9e4066Sahrens 	struct ht_lock ht_locks[BUF_LOCKS];
1072fa9e4066Sahrens } buf_hash_table_t;
1073fa9e4066Sahrens 
1074fa9e4066Sahrens static buf_hash_table_t buf_hash_table;
1075fa9e4066Sahrens 
1076fa9e4066Sahrens #define	BUF_HASH_INDEX(spa, dva, birth) \
1077fa9e4066Sahrens 	(buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
1078fa9e4066Sahrens #define	BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
1079fa9e4066Sahrens #define	BUF_HASH_LOCK(idx)	(&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
10803f9d6ad7SLin Ling #define	HDR_LOCK(hdr) \
10813f9d6ad7SLin Ling 	(BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
1082fa9e4066Sahrens 
1083fa9e4066Sahrens uint64_t zfs_crc64_table[256];
1084fa9e4066Sahrens 
1085fa94a07fSbrendan /*
1086fa94a07fSbrendan  * Level 2 ARC
1087fa94a07fSbrendan  */
1088fa94a07fSbrendan 
1089fa94a07fSbrendan #define	L2ARC_WRITE_SIZE	(8 * 1024 * 1024)	/* initial write max */
1090aad02571SSaso Kiselkov #define	L2ARC_HEADROOM		2			/* num of writes */
1091aad02571SSaso Kiselkov /*
1092aad02571SSaso Kiselkov  * If we discover during ARC scan any buffers to be compressed, we boost
1093aad02571SSaso Kiselkov  * our headroom for the next scanning cycle by this percentage multiple.
1094aad02571SSaso Kiselkov  */
1095aad02571SSaso Kiselkov #define	L2ARC_HEADROOM_BOOST	200
10965a98e54bSBrendan Gregg - Sun Microsystems #define	L2ARC_FEED_SECS		1		/* caching interval secs */
10975a98e54bSBrendan Gregg - Sun Microsystems #define	L2ARC_FEED_MIN_MS	200		/* min caching interval ms */
1098fa94a07fSbrendan 
1099fa94a07fSbrendan #define	l2arc_writes_sent	ARCSTAT(arcstat_l2_writes_sent)
1100fa94a07fSbrendan #define	l2arc_writes_done	ARCSTAT(arcstat_l2_writes_done)
1101fa94a07fSbrendan 
1102f7170741SWill Andrews /* L2ARC Performance Tunables */
1103fa94a07fSbrendan uint64_t l2arc_write_max = L2ARC_WRITE_SIZE;	/* default max write size */
11043a737e0dSbrendan uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE;	/* extra write during warmup */
1105fa94a07fSbrendan uint64_t l2arc_headroom = L2ARC_HEADROOM;	/* number of dev writes */
1106aad02571SSaso Kiselkov uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
1107fa94a07fSbrendan uint64_t l2arc_feed_secs = L2ARC_FEED_SECS;	/* interval seconds */
11085a98e54bSBrendan Gregg - Sun Microsystems uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS;	/* min interval milliseconds */
1109fa94a07fSbrendan boolean_t l2arc_noprefetch = B_TRUE;		/* don't cache prefetch bufs */
11105a98e54bSBrendan Gregg - Sun Microsystems boolean_t l2arc_feed_again = B_TRUE;		/* turbo warmup */
11115a98e54bSBrendan Gregg - Sun Microsystems boolean_t l2arc_norw = B_TRUE;			/* no reads during writes */
1112fa94a07fSbrendan 
1113fa94a07fSbrendan /*
1114fa94a07fSbrendan  * L2ARC Internals
1115fa94a07fSbrendan  */
111689c86e32SChris Williamson struct l2arc_dev {
1117fa94a07fSbrendan 	vdev_t			*l2ad_vdev;	/* vdev */
1118fa94a07fSbrendan 	spa_t			*l2ad_spa;	/* spa */
1119fa94a07fSbrendan 	uint64_t		l2ad_hand;	/* next write location */
1120fa94a07fSbrendan 	uint64_t		l2ad_start;	/* first addr on device */
1121fa94a07fSbrendan 	uint64_t		l2ad_end;	/* last addr on device */
1122fa94a07fSbrendan 	boolean_t		l2ad_first;	/* first sweep through */
11235a98e54bSBrendan Gregg - Sun Microsystems 	boolean_t		l2ad_writing;	/* currently writing */
112489c86e32SChris Williamson 	kmutex_t		l2ad_mtx;	/* lock for buffer list */
112589c86e32SChris Williamson 	list_t			l2ad_buflist;	/* buffer list */
1126fa94a07fSbrendan 	list_node_t		l2ad_node;	/* device list node */
1127a52fc310SPrakash Surya 	refcount_t		l2ad_alloc;	/* allocated bytes */
112889c86e32SChris Williamson };
1129fa94a07fSbrendan 
1130fa94a07fSbrendan static list_t L2ARC_dev_list;			/* device list */
1131fa94a07fSbrendan static list_t *l2arc_dev_list;			/* device list pointer */
1132fa94a07fSbrendan static kmutex_t l2arc_dev_mtx;			/* device list mutex */
1133fa94a07fSbrendan static l2arc_dev_t *l2arc_dev_last;		/* last device used */
1134fa94a07fSbrendan static list_t L2ARC_free_on_write;		/* free after write buf list */
1135fa94a07fSbrendan static list_t *l2arc_free_on_write;		/* free after write list ptr */
1136fa94a07fSbrendan static kmutex_t l2arc_free_on_write_mtx;	/* mutex for list */
1137fa94a07fSbrendan static uint64_t l2arc_ndev;			/* number of devices */
1138fa94a07fSbrendan 
1139fa94a07fSbrendan typedef struct l2arc_read_callback {
11405602294fSDan Kimmel 	arc_buf_hdr_t		*l2rcb_hdr;		/* read header */
1141aad02571SSaso Kiselkov 	blkptr_t		l2rcb_bp;		/* original blkptr */
11427802d7bfSMatthew Ahrens 	zbookmark_phys_t	l2rcb_zb;		/* original bookmark */
1143aad02571SSaso Kiselkov 	int			l2rcb_flags;		/* original flags */
1144403a8da7SAndriy Gapon 	abd_t			*l2rcb_abd;		/* temporary buffer */
1145fa94a07fSbrendan } l2arc_read_callback_t;
1146fa94a07fSbrendan 
1147fa94a07fSbrendan typedef struct l2arc_write_callback {
1148fa94a07fSbrendan 	l2arc_dev_t	*l2wcb_dev;		/* device info */
1149fa94a07fSbrendan 	arc_buf_hdr_t	*l2wcb_head;		/* head of write buflist */
1150fa94a07fSbrendan } l2arc_write_callback_t;
1151fa94a07fSbrendan 
1152fa94a07fSbrendan typedef struct l2arc_data_free {
1153fa94a07fSbrendan 	/* protected by l2arc_free_on_write_mtx */
1154770499e1SDan Kimmel 	abd_t		*l2df_abd;
1155fa94a07fSbrendan 	size_t		l2df_size;
1156dcbf3bd6SGeorge Wilson 	arc_buf_contents_t l2df_type;
1157fa94a07fSbrendan 	list_node_t	l2df_list_node;
1158fa94a07fSbrendan } l2arc_data_free_t;
1159fa94a07fSbrendan 
1160fa94a07fSbrendan static kmutex_t l2arc_feed_thr_lock;
1161fa94a07fSbrendan static kcondvar_t l2arc_feed_thr_cv;
1162fa94a07fSbrendan static uint8_t l2arc_thread_exit;
1163fa94a07fSbrendan 
1164770499e1SDan Kimmel static abd_t *arc_get_data_abd(arc_buf_hdr_t *, uint64_t, void *);
1165dcbf3bd6SGeorge Wilson static void *arc_get_data_buf(arc_buf_hdr_t *, uint64_t, void *);
1166770499e1SDan Kimmel static void arc_get_data_impl(arc_buf_hdr_t *, uint64_t, void *);
1167770499e1SDan Kimmel static void arc_free_data_abd(arc_buf_hdr_t *, abd_t *, uint64_t, void *);
1168dcbf3bd6SGeorge Wilson static void arc_free_data_buf(arc_buf_hdr_t *, void *, uint64_t, void *);
1169770499e1SDan Kimmel static void arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag);
1170770499e1SDan Kimmel static void arc_hdr_free_pabd(arc_buf_hdr_t *);
1171770499e1SDan Kimmel static void arc_hdr_alloc_pabd(arc_buf_hdr_t *);
11727adb730bSGeorge Wilson static void arc_access(arc_buf_hdr_t *, kmutex_t *);
1173244781f1SPrakash Surya static boolean_t arc_is_overflowing();
11747adb730bSGeorge Wilson static void arc_buf_watch(arc_buf_t *);
11757adb730bSGeorge Wilson 
117689c86e32SChris Williamson static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
117789c86e32SChris Williamson static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
1178dcbf3bd6SGeorge Wilson static inline void arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
1179dcbf3bd6SGeorge Wilson static inline void arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
118089c86e32SChris Williamson 
11817adb730bSGeorge Wilson static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
11827adb730bSGeorge Wilson static void l2arc_read_done(zio_t *);
1183fa94a07fSbrendan 
11843a2d8a1bSPaul Dagnelie 
11853a2d8a1bSPaul Dagnelie /*
11863a2d8a1bSPaul Dagnelie  * We use Cityhash for this. It's fast, and has good hash properties without
11873a2d8a1bSPaul Dagnelie  * requiring any large static buffers.
11883a2d8a1bSPaul Dagnelie  */
1189fa9e4066Sahrens static uint64_t
1190ac05c741SMark Maybee buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
1191fa9e4066Sahrens {
11923a2d8a1bSPaul Dagnelie 	return (cityhash4(spa, dva->dva_word[0], dva->dva_word[1], birth));
1193fa9e4066Sahrens }
1194fa9e4066Sahrens 
1195dcbf3bd6SGeorge Wilson #define	HDR_EMPTY(hdr)						\
1196dcbf3bd6SGeorge Wilson 	((hdr)->b_dva.dva_word[0] == 0 &&			\
1197dcbf3bd6SGeorge Wilson 	(hdr)->b_dva.dva_word[1] == 0)
1198fa9e4066Sahrens 
1199dcbf3bd6SGeorge Wilson #define	HDR_EQUAL(spa, dva, birth, hdr)				\
1200dcbf3bd6SGeorge Wilson 	((hdr)->b_dva.dva_word[0] == (dva)->dva_word[0]) &&	\
1201dcbf3bd6SGeorge Wilson 	((hdr)->b_dva.dva_word[1] == (dva)->dva_word[1]) &&	\
1202dcbf3bd6SGeorge Wilson 	((hdr)->b_birth == birth) && ((hdr)->b_spa == spa)
1203fa9e4066Sahrens 
12043f9d6ad7SLin Ling static void
12053f9d6ad7SLin Ling buf_discard_identity(arc_buf_hdr_t *hdr)
12063f9d6ad7SLin Ling {
12073f9d6ad7SLin Ling 	hdr->b_dva.dva_word[0] = 0;
12083f9d6ad7SLin Ling 	hdr->b_dva.dva_word[1] = 0;
12093f9d6ad7SLin Ling 	hdr->b_birth = 0;
12103f9d6ad7SLin Ling }
12113f9d6ad7SLin Ling 
1212fa9e4066Sahrens static arc_buf_hdr_t *
12135d7b4d43SMatthew Ahrens buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
1214fa9e4066Sahrens {
12155d7b4d43SMatthew Ahrens 	const dva_t *dva = BP_IDENTITY(bp);
12165d7b4d43SMatthew Ahrens 	uint64_t birth = BP_PHYSICAL_BIRTH(bp);
1217fa9e4066Sahrens 	uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1218fa9e4066Sahrens 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
12197adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr;
1220fa9e4066Sahrens 
1221fa9e4066Sahrens 	mutex_enter(hash_lock);
12227adb730bSGeorge Wilson 	for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
12237adb730bSGeorge Wilson 	    hdr = hdr->b_hash_next) {
1224dcbf3bd6SGeorge Wilson 		if (HDR_EQUAL(spa, dva, birth, hdr)) {
1225fa9e4066Sahrens 			*lockp = hash_lock;
12267adb730bSGeorge Wilson 			return (hdr);
1227fa9e4066Sahrens 		}
1228fa9e4066Sahrens 	}
1229fa9e4066Sahrens 	mutex_exit(hash_lock);
1230fa9e4066Sahrens 	*lockp = NULL;
1231fa9e4066Sahrens 	return (NULL);
1232fa9e4066Sahrens }
1233fa9e4066Sahrens 
1234fa9e4066Sahrens /*
1235fa9e4066Sahrens  * Insert an entry into the hash table.  If there is already an element
1236fa9e4066Sahrens  * equal to elem in the hash table, then the already existing element
1237fa9e4066Sahrens  * will be returned and the new element will not be inserted.
1238fa9e4066Sahrens  * Otherwise returns NULL.
123989c86e32SChris Williamson  * If lockp == NULL, the caller is assumed to already hold the hash lock.
1240fa9e4066Sahrens  */
1241fa9e4066Sahrens static arc_buf_hdr_t *
12427adb730bSGeorge Wilson buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1243fa9e4066Sahrens {
12447adb730bSGeorge Wilson 	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1245fa9e4066Sahrens 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
12467adb730bSGeorge Wilson 	arc_buf_hdr_t *fhdr;
124744cb6abcSbmc 	uint32_t i;
1248fa9e4066Sahrens 
12497adb730bSGeorge Wilson 	ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
12507adb730bSGeorge Wilson 	ASSERT(hdr->b_birth != 0);
12517adb730bSGeorge Wilson 	ASSERT(!HDR_IN_HASH_TABLE(hdr));
125289c86e32SChris Williamson 
125389c86e32SChris Williamson 	if (lockp != NULL) {
125489c86e32SChris Williamson 		*lockp = hash_lock;
125589c86e32SChris Williamson 		mutex_enter(hash_lock);
125689c86e32SChris Williamson 	} else {
125789c86e32SChris Williamson 		ASSERT(MUTEX_HELD(hash_lock));
125889c86e32SChris Williamson 	}
125989c86e32SChris Williamson 
12607adb730bSGeorge Wilson 	for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
12617adb730bSGeorge Wilson 	    fhdr = fhdr->b_hash_next, i++) {
1262dcbf3bd6SGeorge Wilson 		if (HDR_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
12637adb730bSGeorge Wilson 			return (fhdr);
1264fa9e4066Sahrens 	}
1265fa9e4066Sahrens 
12667adb730bSGeorge Wilson 	hdr->b_hash_next = buf_hash_table.ht_table[idx];
12677adb730bSGeorge Wilson 	buf_hash_table.ht_table[idx] = hdr;
1268dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1269fa9e4066Sahrens 
1270fa9e4066Sahrens 	/* collect some hash table performance data */
1271fa9e4066Sahrens 	if (i > 0) {
127244cb6abcSbmc 		ARCSTAT_BUMP(arcstat_hash_collisions);
1273fa9e4066Sahrens 		if (i == 1)
127444cb6abcSbmc 			ARCSTAT_BUMP(arcstat_hash_chains);
127544cb6abcSbmc 
127644cb6abcSbmc 		ARCSTAT_MAX(arcstat_hash_chain_max, i);
1277fa9e4066Sahrens 	}
127844cb6abcSbmc 
127944cb6abcSbmc 	ARCSTAT_BUMP(arcstat_hash_elements);
128044cb6abcSbmc 	ARCSTAT_MAXSTAT(arcstat_hash_elements);
1281fa9e4066Sahrens 
1282fa9e4066Sahrens 	return (NULL);
1283fa9e4066Sahrens }
1284fa9e4066Sahrens 
1285fa9e4066Sahrens static void
12867adb730bSGeorge Wilson buf_hash_remove(arc_buf_hdr_t *hdr)
1287fa9e4066Sahrens {
12887adb730bSGeorge Wilson 	arc_buf_hdr_t *fhdr, **hdrp;
12897adb730bSGeorge Wilson 	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1290fa9e4066Sahrens 
1291fa9e4066Sahrens 	ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
12927adb730bSGeorge Wilson 	ASSERT(HDR_IN_HASH_TABLE(hdr));
1293fa9e4066Sahrens 
12947adb730bSGeorge Wilson 	hdrp = &buf_hash_table.ht_table[idx];
12957adb730bSGeorge Wilson 	while ((fhdr = *hdrp) != hdr) {
1296dcbf3bd6SGeorge Wilson 		ASSERT3P(fhdr, !=, NULL);
12977adb730bSGeorge Wilson 		hdrp = &fhdr->b_hash_next;
1298fa9e4066Sahrens 	}
12997adb730bSGeorge Wilson 	*hdrp = hdr->b_hash_next;
13007adb730bSGeorge Wilson 	hdr->b_hash_next = NULL;
1301dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1302fa9e4066Sahrens 
1303fa9e4066Sahrens 	/* collect some hash table performance data */
130444cb6abcSbmc 	ARCSTAT_BUMPDOWN(arcstat_hash_elements);
130544cb6abcSbmc 
1306fa9e4066Sahrens 	if (buf_hash_table.ht_table[idx] &&
1307fa9e4066Sahrens 	    buf_hash_table.ht_table[idx]->b_hash_next == NULL)
130844cb6abcSbmc 		ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1309fa9e4066Sahrens }
1310fa9e4066Sahrens 
1311fa9e4066Sahrens /*
1312fa9e4066Sahrens  * Global data structures and functions for the buf kmem cache.
1313fa9e4066Sahrens  */
131489c86e32SChris Williamson static kmem_cache_t *hdr_full_cache;
131589c86e32SChris Williamson static kmem_cache_t *hdr_l2only_cache;
1316fa9e4066Sahrens static kmem_cache_t *buf_cache;
1317fa9e4066Sahrens 
1318fa9e4066Sahrens static void
1319fa9e4066Sahrens buf_fini(void)
1320fa9e4066Sahrens {
1321fa9e4066Sahrens 	int i;
1322fa9e4066Sahrens 
1323fa9e4066Sahrens 	kmem_free(buf_hash_table.ht_table,
1324fa9e4066Sahrens 	    (buf_hash_table.ht_mask + 1) * sizeof (void *));
1325fa9e4066Sahrens 	for (i = 0; i < BUF_LOCKS; i++)
1326fa9e4066Sahrens 		mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
132789c86e32SChris Williamson 	kmem_cache_destroy(hdr_full_cache);
132889c86e32SChris Williamson 	kmem_cache_destroy(hdr_l2only_cache);
1329fa9e4066Sahrens 	kmem_cache_destroy(buf_cache);
1330fa9e4066Sahrens }
1331fa9e4066Sahrens 
1332fa9e4066Sahrens /*
1333fa9e4066Sahrens  * Constructor callback - called when the cache is empty
1334fa9e4066Sahrens  * and a new buf is requested.
1335fa9e4066Sahrens  */
1336fa9e4066Sahrens /* ARGSUSED */
1337fa9e4066Sahrens static int
133889c86e32SChris Williamson hdr_full_cons(void *vbuf, void *unused, int kmflag)
1339fa9e4066Sahrens {
13407adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr = vbuf;
1341fa9e4066Sahrens 
134289c86e32SChris Williamson 	bzero(hdr, HDR_FULL_SIZE);
134389c86e32SChris Williamson 	cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
134489c86e32SChris Williamson 	refcount_create(&hdr->b_l1hdr.b_refcnt);
134589c86e32SChris Williamson 	mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1346244781f1SPrakash Surya 	multilist_link_init(&hdr->b_l1hdr.b_arc_node);
134789c86e32SChris Williamson 	arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
134889c86e32SChris Williamson 
134989c86e32SChris Williamson 	return (0);
135089c86e32SChris Williamson }
135189c86e32SChris Williamson 
135289c86e32SChris Williamson /* ARGSUSED */
135389c86e32SChris Williamson static int
135489c86e32SChris Williamson hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
135589c86e32SChris Williamson {
135689c86e32SChris Williamson 	arc_buf_hdr_t *hdr = vbuf;
135789c86e32SChris Williamson 
135889c86e32SChris Williamson 	bzero(hdr, HDR_L2ONLY_SIZE);
135989c86e32SChris Williamson 	arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1360fa94a07fSbrendan 
1361fa9e4066Sahrens 	return (0);
1362fa9e4066Sahrens }
1363fa9e4066Sahrens 
13646f83844dSMark Maybee /* ARGSUSED */
13656f83844dSMark Maybee static int
13666f83844dSMark Maybee buf_cons(void *vbuf, void *unused, int kmflag)
13676f83844dSMark Maybee {
13686f83844dSMark Maybee 	arc_buf_t *buf = vbuf;
13696f83844dSMark Maybee 
13706f83844dSMark Maybee 	bzero(buf, sizeof (arc_buf_t));
13713f9d6ad7SLin Ling 	mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
13725a98e54bSBrendan Gregg - Sun Microsystems 	arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
13735a98e54bSBrendan Gregg - Sun Microsystems 
13746f83844dSMark Maybee 	return (0);
13756f83844dSMark Maybee }
13766f83844dSMark Maybee 
1377fa9e4066Sahrens /*
1378fa9e4066Sahrens  * Destructor callback - called when a cached buf is
1379fa9e4066Sahrens  * no longer required.
1380fa9e4066Sahrens  */
1381fa9e4066Sahrens /* ARGSUSED */
1382fa9e4066Sahrens static void
138389c86e32SChris Williamson hdr_full_dest(void *vbuf, void *unused)
138489c86e32SChris Williamson {
138589c86e32SChris Williamson 	arc_buf_hdr_t *hdr = vbuf;
138689c86e32SChris Williamson 
1387dcbf3bd6SGeorge Wilson 	ASSERT(HDR_EMPTY(hdr));
138889c86e32SChris Williamson 	cv_destroy(&hdr->b_l1hdr.b_cv);
138989c86e32SChris Williamson 	refcount_destroy(&hdr->b_l1hdr.b_refcnt);
139089c86e32SChris Williamson 	mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1391244781f1SPrakash Surya 	ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
139289c86e32SChris Williamson 	arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
139389c86e32SChris Williamson }
139489c86e32SChris Williamson 
139589c86e32SChris Williamson /* ARGSUSED */
139689c86e32SChris Williamson static void
139789c86e32SChris Williamson hdr_l2only_dest(void *vbuf, void *unused)
1398fa9e4066Sahrens {
13997adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr = vbuf;
1400fa9e4066Sahrens 
1401dcbf3bd6SGeorge Wilson 	ASSERT(HDR_EMPTY(hdr));
140289c86e32SChris Williamson 	arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1403fa9e4066Sahrens }
1404fa9e4066Sahrens 
14056f83844dSMark Maybee /* ARGSUSED */
14066f83844dSMark Maybee static void
14076f83844dSMark Maybee buf_dest(void *vbuf, void *unused)
14086f83844dSMark Maybee {
14096f83844dSMark Maybee 	arc_buf_t *buf = vbuf;
14106f83844dSMark Maybee 
14113f9d6ad7SLin Ling 	mutex_destroy(&buf->b_evict_lock);
14125a98e54bSBrendan Gregg - Sun Microsystems 	arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
14136f83844dSMark Maybee }
14146f83844dSMark Maybee 
1415fa9e4066Sahrens /*
1416fa9e4066Sahrens  * Reclaim callback -- invoked when memory is low.
1417fa9e4066Sahrens  */
1418fa9e4066Sahrens /* ARGSUSED */
1419fa9e4066Sahrens static void
1420fa9e4066Sahrens hdr_recl(void *unused)
1421fa9e4066Sahrens {
1422fa9e4066Sahrens 	dprintf("hdr_recl called\n");
142349e3519aSmaybee 	/*
142449e3519aSmaybee 	 * umem calls the reclaim func when we destroy the buf cache,
142549e3519aSmaybee 	 * which is after we do arc_fini().
142649e3519aSmaybee 	 */
1427de753e34SBrad Lewis 	if (arc_initialized)
1428de753e34SBrad Lewis 		zthr_wakeup(arc_reap_zthr);
1429fa9e4066Sahrens }
1430fa9e4066Sahrens 
1431fa9e4066Sahrens static void
1432fa9e4066Sahrens buf_init(void)
1433fa9e4066Sahrens {
1434fa9e4066Sahrens 	uint64_t *ct;
1435ea8dc4b6Seschrock 	uint64_t hsize = 1ULL << 12;
1436fa9e4066Sahrens 	int i, j;
1437fa9e4066Sahrens 
1438fa9e4066Sahrens 	/*
1439fa9e4066Sahrens 	 * The hash table is big enough to fill all of physical memory
144063e911b6SMatthew Ahrens 	 * with an average block size of zfs_arc_average_blocksize (default 8K).
144163e911b6SMatthew Ahrens 	 * By default, the table will take up
144263e911b6SMatthew Ahrens 	 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1443fa9e4066Sahrens 	 */
144463e911b6SMatthew Ahrens 	while (hsize * zfs_arc_average_blocksize < physmem * PAGESIZE)
1445fa9e4066Sahrens 		hsize <<= 1;
1446ea8dc4b6Seschrock retry:
1447fa9e4066Sahrens 	buf_hash_table.ht_mask = hsize - 1;
1448ea8dc4b6Seschrock 	buf_hash_table.ht_table =
1449ea8dc4b6Seschrock 	    kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1450ea8dc4b6Seschrock 	if (buf_hash_table.ht_table == NULL) {
1451ea8dc4b6Seschrock 		ASSERT(hsize > (1ULL << 8));
1452ea8dc4b6Seschrock 		hsize >>= 1;
1453ea8dc4b6Seschrock 		goto retry;
1454ea8dc4b6Seschrock 	}
1455fa9e4066Sahrens 
145689c86e32SChris Williamson 	hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
145789c86e32SChris Williamson 	    0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
145889c86e32SChris Williamson 	hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
145989c86e32SChris Williamson 	    HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
146089c86e32SChris Williamson 	    NULL, NULL, 0);
1461fa9e4066Sahrens 	buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
14626f83844dSMark Maybee 	    0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1463fa9e4066Sahrens 
1464fa9e4066Sahrens 	for (i = 0; i < 256; i++)
1465fa9e4066Sahrens 		for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1466fa9e4066Sahrens 			*ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1467fa9e4066Sahrens 
1468fa9e4066Sahrens 	for (i = 0; i < BUF_LOCKS; i++) {
1469fa9e4066Sahrens 		mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1470fa9e4066Sahrens 		    NULL, MUTEX_DEFAULT, NULL);
1471fa9e4066Sahrens 	}
1472fa9e4066Sahrens }
1473fa9e4066Sahrens 
14745602294fSDan Kimmel /*
14755602294fSDan Kimmel  * This is the size that the buf occupies in memory. If the buf is compressed,
14765602294fSDan Kimmel  * it will correspond to the compressed size. You should use this method of
14775602294fSDan Kimmel  * getting the buf size unless you explicitly need the logical size.
14785602294fSDan Kimmel  */
14795602294fSDan Kimmel int32_t
14805602294fSDan Kimmel arc_buf_size(arc_buf_t *buf)
14815602294fSDan Kimmel {
14825602294fSDan Kimmel 	return (ARC_BUF_COMPRESSED(buf) ?
14835602294fSDan Kimmel 	    HDR_GET_PSIZE(buf->b_hdr) : HDR_GET_LSIZE(buf->b_hdr));
14845602294fSDan Kimmel }
14855602294fSDan Kimmel 
14865602294fSDan Kimmel int32_t
14875602294fSDan Kimmel arc_buf_lsize(arc_buf_t *buf)
14885602294fSDan Kimmel {
14895602294fSDan Kimmel 	return (HDR_GET_LSIZE(buf->b_hdr));
14905602294fSDan Kimmel }
14915602294fSDan Kimmel 
14925602294fSDan Kimmel enum zio_compress
14935602294fSDan Kimmel arc_get_compression(arc_buf_t *buf)
14945602294fSDan Kimmel {
14955602294fSDan Kimmel 	return (ARC_BUF_COMPRESSED(buf) ?
14965602294fSDan Kimmel 	    HDR_GET_COMPRESS(buf->b_hdr) : ZIO_COMPRESS_OFF);
14975602294fSDan Kimmel }
14985602294fSDan Kimmel 
1499dcbf3bd6SGeorge Wilson #define	ARC_MINTIME	(hz>>4) /* 62 ms */
1500244781f1SPrakash Surya 
1501dcbf3bd6SGeorge Wilson static inline boolean_t
1502dcbf3bd6SGeorge Wilson arc_buf_is_shared(arc_buf_t *buf)
1503dcbf3bd6SGeorge Wilson {
1504dcbf3bd6SGeorge Wilson 	boolean_t shared = (buf->b_data != NULL &&
1505770499e1SDan Kimmel 	    buf->b_hdr->b_l1hdr.b_pabd != NULL &&
1506770499e1SDan Kimmel 	    abd_is_linear(buf->b_hdr->b_l1hdr.b_pabd) &&
1507770499e1SDan Kimmel 	    buf->b_data == abd_to_buf(buf->b_hdr->b_l1hdr.b_pabd));
1508dcbf3bd6SGeorge Wilson 	IMPLY(shared, HDR_SHARED_DATA(buf->b_hdr));
15095602294fSDan Kimmel 	IMPLY(shared, ARC_BUF_SHARED(buf));
15105602294fSDan Kimmel 	IMPLY(shared, ARC_BUF_COMPRESSED(buf) || ARC_BUF_LAST(buf));
15115602294fSDan Kimmel 
15125602294fSDan Kimmel 	/*
15135602294fSDan Kimmel 	 * It would be nice to assert arc_can_share() too, but the "hdr isn't
15145602294fSDan Kimmel 	 * already being shared" requirement prevents us from doing that.
15155602294fSDan Kimmel 	 */
15165602294fSDan Kimmel 
1517dcbf3bd6SGeorge Wilson 	return (shared);
1518dcbf3bd6SGeorge Wilson }
1519c546f36aSArne Jansen 
15205602294fSDan Kimmel /*
15215602294fSDan Kimmel  * Free the checksum associated with this header. If there is no checksum, this
15225602294fSDan Kimmel  * is a no-op.
15235602294fSDan Kimmel  */
1524dcbf3bd6SGeorge Wilson static inline void
1525dcbf3bd6SGeorge Wilson arc_cksum_free(arc_buf_hdr_t *hdr)
1526dcbf3bd6SGeorge Wilson {
1527dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
1528dcbf3bd6SGeorge Wilson 	mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1529dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
1530dcbf3bd6SGeorge Wilson 		kmem_free(hdr->b_l1hdr.b_freeze_cksum, sizeof (zio_cksum_t));
1531dcbf3bd6SGeorge Wilson 		hdr->b_l1hdr.b_freeze_cksum = NULL;
153289c86e32SChris Williamson 	}
1533dcbf3bd6SGeorge Wilson 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
153489c86e32SChris Williamson }
153589c86e32SChris Williamson 
15365602294fSDan Kimmel /*
15375602294fSDan Kimmel  * Return true iff at least one of the bufs on hdr is not compressed.
15385602294fSDan Kimmel  */
15395602294fSDan Kimmel static boolean_t
15405602294fSDan Kimmel arc_hdr_has_uncompressed_buf(arc_buf_hdr_t *hdr)
15415602294fSDan Kimmel {
15425602294fSDan Kimmel 	for (arc_buf_t *b = hdr->b_l1hdr.b_buf; b != NULL; b = b->b_next) {
15435602294fSDan Kimmel 		if (!ARC_BUF_COMPRESSED(b)) {
15445602294fSDan Kimmel 			return (B_TRUE);
15455602294fSDan Kimmel 		}
15465602294fSDan Kimmel 	}
15475602294fSDan Kimmel 	return (B_FALSE);
15485602294fSDan Kimmel }
15495602294fSDan Kimmel 
15505602294fSDan Kimmel /*
15515602294fSDan Kimmel  * If we've turned on the ZFS_DEBUG_MODIFY flag, verify that the buf's data
15525602294fSDan Kimmel  * matches the checksum that is stored in the hdr. If there is no checksum,
15535602294fSDan Kimmel  * or if the buf is compressed, this is a no-op.
15545602294fSDan Kimmel  */
15556b4acc8bSahrens static void
15566b4acc8bSahrens arc_cksum_verify(arc_buf_t *buf)
15576b4acc8bSahrens {
1558dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
15596b4acc8bSahrens 	zio_cksum_t zc;
15606b4acc8bSahrens 
1561cc60fd72Sahrens 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
15626b4acc8bSahrens 		return;
15636b4acc8bSahrens 
15645602294fSDan Kimmel 	if (ARC_BUF_COMPRESSED(buf)) {
15655602294fSDan Kimmel 		ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
15665602294fSDan Kimmel 		    arc_hdr_has_uncompressed_buf(hdr));
15675602294fSDan Kimmel 		return;
15685602294fSDan Kimmel 	}
15695602294fSDan Kimmel 
1570dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
1571dcbf3bd6SGeorge Wilson 
1572dcbf3bd6SGeorge Wilson 	mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1573dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_freeze_cksum == NULL || HDR_IO_ERROR(hdr)) {
1574dcbf3bd6SGeorge Wilson 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
15756b4acc8bSahrens 		return;
15766b4acc8bSahrens 	}
15775602294fSDan Kimmel 
15785602294fSDan Kimmel 	fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL, &zc);
1579dcbf3bd6SGeorge Wilson 	if (!ZIO_CHECKSUM_EQUAL(*hdr->b_l1hdr.b_freeze_cksum, zc))
15806b4acc8bSahrens 		panic("buffer modified while frozen!");
1581dcbf3bd6SGeorge Wilson 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
15826b4acc8bSahrens }
15836b4acc8bSahrens 
1584dcbf3bd6SGeorge Wilson static boolean_t
1585dcbf3bd6SGeorge Wilson arc_cksum_is_equal(arc_buf_hdr_t *hdr, zio_t *zio)
1586fa94a07fSbrendan {
1587dcbf3bd6SGeorge Wilson 	enum zio_compress compress = BP_GET_COMPRESS(zio->io_bp);
1588dcbf3bd6SGeorge Wilson 	boolean_t valid_cksum;
1589fa94a07fSbrendan 
1590dcbf3bd6SGeorge Wilson 	ASSERT(!BP_IS_EMBEDDED(zio->io_bp));
1591dcbf3bd6SGeorge Wilson 	VERIFY3U(BP_GET_PSIZE(zio->io_bp), ==, HDR_GET_PSIZE(hdr));
1592dcbf3bd6SGeorge Wilson 
1593dcbf3bd6SGeorge Wilson 	/*
1594dcbf3bd6SGeorge Wilson 	 * We rely on the blkptr's checksum to determine if the block
1595dcbf3bd6SGeorge Wilson 	 * is valid or not. When compressed arc is enabled, the l2arc
1596dcbf3bd6SGeorge Wilson 	 * writes the block to the l2arc just as it appears in the pool.
1597dcbf3bd6SGeorge Wilson 	 * This allows us to use the blkptr's checksum to validate the
1598dcbf3bd6SGeorge Wilson 	 * data that we just read off of the l2arc without having to store
1599dcbf3bd6SGeorge Wilson 	 * a separate checksum in the arc_buf_hdr_t. However, if compressed
1600dcbf3bd6SGeorge Wilson 	 * arc is disabled, then the data written to the l2arc is always
1601dcbf3bd6SGeorge Wilson 	 * uncompressed and won't match the block as it exists in the main
1602dcbf3bd6SGeorge Wilson 	 * pool. When this is the case, we must first compress it if it is
1603dcbf3bd6SGeorge Wilson 	 * compressed on the main pool before we can validate the checksum.
1604dcbf3bd6SGeorge Wilson 	 */
1605dcbf3bd6SGeorge Wilson 	if (!HDR_COMPRESSION_ENABLED(hdr) && compress != ZIO_COMPRESS_OFF) {
1606dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
1607dcbf3bd6SGeorge Wilson 		uint64_t lsize = HDR_GET_LSIZE(hdr);
1608dcbf3bd6SGeorge Wilson 		uint64_t csize;
1609dcbf3bd6SGeorge Wilson 
161001a059eeSRoman Strashkin 		abd_t *cdata = abd_alloc_linear(HDR_GET_PSIZE(hdr), B_TRUE);
161101a059eeSRoman Strashkin 		csize = zio_compress_data(compress, zio->io_abd,
161201a059eeSRoman Strashkin 		    abd_to_buf(cdata), lsize);
1613770499e1SDan Kimmel 
1614dcbf3bd6SGeorge Wilson 		ASSERT3U(csize, <=, HDR_GET_PSIZE(hdr));
1615dcbf3bd6SGeorge Wilson 		if (csize < HDR_GET_PSIZE(hdr)) {
1616dcbf3bd6SGeorge Wilson 			/*
1617dcbf3bd6SGeorge Wilson 			 * Compressed blocks are always a multiple of the
1618dcbf3bd6SGeorge Wilson 			 * smallest ashift in the pool. Ideally, we would
1619dcbf3bd6SGeorge Wilson 			 * like to round up the csize to the next
1620dcbf3bd6SGeorge Wilson 			 * spa_min_ashift but that value may have changed
1621dcbf3bd6SGeorge Wilson 			 * since the block was last written. Instead,
1622dcbf3bd6SGeorge Wilson 			 * we rely on the fact that the hdr's psize
1623dcbf3bd6SGeorge Wilson 			 * was set to the psize of the block when it was
1624dcbf3bd6SGeorge Wilson 			 * last written. We set the csize to that value
1625dcbf3bd6SGeorge Wilson 			 * and zero out any part that should not contain
1626dcbf3bd6SGeorge Wilson 			 * data.
1627dcbf3bd6SGeorge Wilson 			 */
162801a059eeSRoman Strashkin 			abd_zero_off(cdata, csize, HDR_GET_PSIZE(hdr) - csize);
1629dcbf3bd6SGeorge Wilson 			csize = HDR_GET_PSIZE(hdr);
1630dcbf3bd6SGeorge Wilson 		}
163101a059eeSRoman Strashkin 		zio_push_transform(zio, cdata, csize, HDR_GET_PSIZE(hdr), NULL);
1632dcbf3bd6SGeorge Wilson 	}
1633fa94a07fSbrendan 
1634dcbf3bd6SGeorge Wilson 	/*
1635dcbf3bd6SGeorge Wilson 	 * Block pointers always store the checksum for the logical data.
1636dcbf3bd6SGeorge Wilson 	 * If the block pointer has the gang bit set, then the checksum
1637dcbf3bd6SGeorge Wilson 	 * it represents is for the reconstituted data and not for an
1638dcbf3bd6SGeorge Wilson 	 * individual gang member. The zio pipeline, however, must be able to
1639dcbf3bd6SGeorge Wilson 	 * determine the checksum of each of the gang constituents so it
1640dcbf3bd6SGeorge Wilson 	 * treats the checksum comparison differently than what we need
1641dcbf3bd6SGeorge Wilson 	 * for l2arc blocks. This prevents us from using the
1642dcbf3bd6SGeorge Wilson 	 * zio_checksum_error() interface directly. Instead we must call the
1643dcbf3bd6SGeorge Wilson 	 * zio_checksum_error_impl() so that we can ensure the checksum is
1644dcbf3bd6SGeorge Wilson 	 * generated using the correct checksum algorithm and accounts for the
1645dcbf3bd6SGeorge Wilson 	 * logical I/O size and not just a gang fragment.
1646dcbf3bd6SGeorge Wilson 	 */
1647dcbf3bd6SGeorge Wilson 	valid_cksum = (zio_checksum_error_impl(zio->io_spa, zio->io_bp,
1648770499e1SDan Kimmel 	    BP_GET_CHECKSUM(zio->io_bp), zio->io_abd, zio->io_size,
1649dcbf3bd6SGeorge Wilson 	    zio->io_offset, NULL) == 0);
1650dcbf3bd6SGeorge Wilson 	zio_pop_transforms(zio);
1651dcbf3bd6SGeorge Wilson 	return (valid_cksum);
1652fa94a07fSbrendan }
1653fa94a07fSbrendan 
16545602294fSDan Kimmel /*
16555602294fSDan Kimmel  * Given a buf full of data, if ZFS_DEBUG_MODIFY is enabled this computes a
16565602294fSDan Kimmel  * checksum and attaches it to the buf's hdr so that we can ensure that the buf
16575602294fSDan Kimmel  * isn't modified later on. If buf is compressed or there is already a checksum
16585602294fSDan Kimmel  * on the hdr, this is a no-op (we only checksum uncompressed bufs).
16595602294fSDan Kimmel  */
16606b4acc8bSahrens static void
1661dcbf3bd6SGeorge Wilson arc_cksum_compute(arc_buf_t *buf)
16626b4acc8bSahrens {
1663dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
1664dcbf3bd6SGeorge Wilson 
1665dcbf3bd6SGeorge Wilson 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
16666b4acc8bSahrens 		return;
16676b4acc8bSahrens 
1668dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
16695602294fSDan Kimmel 
167089c86e32SChris Williamson 	mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1671dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
16725602294fSDan Kimmel 		ASSERT(arc_hdr_has_uncompressed_buf(hdr));
16735602294fSDan Kimmel 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
16745602294fSDan Kimmel 		return;
16755602294fSDan Kimmel 	} else if (ARC_BUF_COMPRESSED(buf)) {
1676dcbf3bd6SGeorge Wilson 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
16776b4acc8bSahrens 		return;
16786b4acc8bSahrens 	}
16795602294fSDan Kimmel 
16805602294fSDan Kimmel 	ASSERT(!ARC_BUF_COMPRESSED(buf));
1681dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t),
1682dcbf3bd6SGeorge Wilson 	    KM_SLEEP);
16835602294fSDan Kimmel 	fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL,
1684dcbf3bd6SGeorge Wilson 	    hdr->b_l1hdr.b_freeze_cksum);
1685dcbf3bd6SGeorge Wilson 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1686cd1c8b85SMatthew Ahrens 	arc_buf_watch(buf);
1687cd1c8b85SMatthew Ahrens }
1688cd1c8b85SMatthew Ahrens 
1689cd1c8b85SMatthew Ahrens #ifndef _KERNEL
1690cd1c8b85SMatthew Ahrens typedef struct procctl {
1691cd1c8b85SMatthew Ahrens 	long cmd;
1692cd1c8b85SMatthew Ahrens 	prwatch_t prwatch;
1693cd1c8b85SMatthew Ahrens } procctl_t;
1694cd1c8b85SMatthew Ahrens #endif
1695cd1c8b85SMatthew Ahrens 
1696cd1c8b85SMatthew Ahrens /* ARGSUSED */
1697cd1c8b85SMatthew Ahrens static void
1698cd1c8b85SMatthew Ahrens arc_buf_unwatch(arc_buf_t *buf)
1699cd1c8b85SMatthew Ahrens {
1700cd1c8b85SMatthew Ahrens #ifndef _KERNEL
1701cd1c8b85SMatthew Ahrens 	if (arc_watch) {
1702cd1c8b85SMatthew Ahrens 		int result;
1703cd1c8b85SMatthew Ahrens 		procctl_t ctl;
1704cd1c8b85SMatthew Ahrens 		ctl.cmd = PCWATCH;
1705cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1706cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_size = 0;
1707cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_wflags = 0;
1708cd1c8b85SMatthew Ahrens 		result = write(arc_procfd, &ctl, sizeof (ctl));
1709cd1c8b85SMatthew Ahrens 		ASSERT3U(result, ==, sizeof (ctl));
1710cd1c8b85SMatthew Ahrens 	}
1711cd1c8b85SMatthew Ahrens #endif
1712cd1c8b85SMatthew Ahrens }
1713cd1c8b85SMatthew Ahrens 
1714cd1c8b85SMatthew Ahrens /* ARGSUSED */
1715cd1c8b85SMatthew Ahrens static void
1716cd1c8b85SMatthew Ahrens arc_buf_watch(arc_buf_t *buf)
1717cd1c8b85SMatthew Ahrens {
1718cd1c8b85SMatthew Ahrens #ifndef _KERNEL
1719cd1c8b85SMatthew Ahrens 	if (arc_watch) {
1720cd1c8b85SMatthew Ahrens 		int result;
1721cd1c8b85SMatthew Ahrens 		procctl_t ctl;
1722cd1c8b85SMatthew Ahrens 		ctl.cmd = PCWATCH;
1723cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
17245602294fSDan Kimmel 		ctl.prwatch.pr_size = arc_buf_size(buf);
1725cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_wflags = WA_WRITE;
1726cd1c8b85SMatthew Ahrens 		result = write(arc_procfd, &ctl, sizeof (ctl));
1727cd1c8b85SMatthew Ahrens 		ASSERT3U(result, ==, sizeof (ctl));
1728cd1c8b85SMatthew Ahrens 	}
1729cd1c8b85SMatthew Ahrens #endif
17306b4acc8bSahrens }
17316b4acc8bSahrens 
173289c86e32SChris Williamson static arc_buf_contents_t
173389c86e32SChris Williamson arc_buf_type(arc_buf_hdr_t *hdr)
173489c86e32SChris Williamson {
1735dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type;
173689c86e32SChris Williamson 	if (HDR_ISTYPE_METADATA(hdr)) {
1737dcbf3bd6SGeorge Wilson 		type = ARC_BUFC_METADATA;
173889c86e32SChris Williamson 	} else {
1739dcbf3bd6SGeorge Wilson 		type = ARC_BUFC_DATA;
174089c86e32SChris Williamson 	}
1741dcbf3bd6SGeorge Wilson 	VERIFY3U(hdr->b_type, ==, type);
1742dcbf3bd6SGeorge Wilson 	return (type);
174389c86e32SChris Williamson }
174489c86e32SChris Williamson 
17455602294fSDan Kimmel boolean_t
17465602294fSDan Kimmel arc_is_metadata(arc_buf_t *buf)
17475602294fSDan Kimmel {
17485602294fSDan Kimmel 	return (HDR_ISTYPE_METADATA(buf->b_hdr) != 0);
17495602294fSDan Kimmel }
17505602294fSDan Kimmel 
175189c86e32SChris Williamson static uint32_t
175289c86e32SChris Williamson arc_bufc_to_flags(arc_buf_contents_t type)
175389c86e32SChris Williamson {
175489c86e32SChris Williamson 	switch (type) {
175589c86e32SChris Williamson 	case ARC_BUFC_DATA:
175689c86e32SChris Williamson 		/* metadata field is 0 if buffer contains normal data */
175789c86e32SChris Williamson 		return (0);
175889c86e32SChris Williamson 	case ARC_BUFC_METADATA:
175989c86e32SChris Williamson 		return (ARC_FLAG_BUFC_METADATA);
176089c86e32SChris Williamson 	default:
176189c86e32SChris Williamson 		break;
176289c86e32SChris Williamson 	}
176389c86e32SChris Williamson 	panic("undefined ARC buffer type!");
176489c86e32SChris Williamson 	return ((uint32_t)-1);
176589c86e32SChris Williamson }
176689c86e32SChris Williamson 
17676b4acc8bSahrens void
17686b4acc8bSahrens arc_buf_thaw(arc_buf_t *buf)
17696b4acc8bSahrens {
1770dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
1771dcbf3bd6SGeorge Wilson 
17725602294fSDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
17735602294fSDan Kimmel 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
17745602294fSDan Kimmel 
17755602294fSDan Kimmel 	arc_cksum_verify(buf);
17765602294fSDan Kimmel 
17775602294fSDan Kimmel 	/*
17785602294fSDan Kimmel 	 * Compressed buffers do not manipulate the b_freeze_cksum or
17795602294fSDan Kimmel 	 * allocate b_thawed.
17805602294fSDan Kimmel 	 */
17815602294fSDan Kimmel 	if (ARC_BUF_COMPRESSED(buf)) {
17825602294fSDan Kimmel 		ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
17835602294fSDan Kimmel 		    arc_hdr_has_uncompressed_buf(hdr));
17845602294fSDan Kimmel 		return;
1785fa94a07fSbrendan 	}
17866b4acc8bSahrens 
1787dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
1788dcbf3bd6SGeorge Wilson 	arc_cksum_free(hdr);
17893f9d6ad7SLin Ling 
1790dcbf3bd6SGeorge Wilson 	mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
179189c86e32SChris Williamson #ifdef ZFS_DEBUG
17923f9d6ad7SLin Ling 	if (zfs_flags & ZFS_DEBUG_MODIFY) {
1793dcbf3bd6SGeorge Wilson 		if (hdr->b_l1hdr.b_thawed != NULL)
1794dcbf3bd6SGeorge Wilson 			kmem_free(hdr->b_l1hdr.b_thawed, 1);
1795dcbf3bd6SGeorge Wilson 		hdr->b_l1hdr.b_thawed = kmem_alloc(1, KM_SLEEP);
17963f9d6ad7SLin Ling 	}
179789c86e32SChris Williamson #endif
17983f9d6ad7SLin Ling 
1799dcbf3bd6SGeorge Wilson 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1800cd1c8b85SMatthew Ahrens 
1801cd1c8b85SMatthew Ahrens 	arc_buf_unwatch(buf);
18026b4acc8bSahrens }
18036b4acc8bSahrens 
18046b4acc8bSahrens void
18056b4acc8bSahrens arc_buf_freeze(arc_buf_t *buf)
18066b4acc8bSahrens {
1807dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
18083f9d6ad7SLin Ling 	kmutex_t *hash_lock;
18093f9d6ad7SLin Ling 
1810cc60fd72Sahrens 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1811cc60fd72Sahrens 		return;
1812cc60fd72Sahrens 
18135602294fSDan Kimmel 	if (ARC_BUF_COMPRESSED(buf)) {
18145602294fSDan Kimmel 		ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
18155602294fSDan Kimmel 		    arc_hdr_has_uncompressed_buf(hdr));
18165602294fSDan Kimmel 		return;
18175602294fSDan Kimmel 	}
18185602294fSDan Kimmel 
1819dcbf3bd6SGeorge Wilson 	hash_lock = HDR_LOCK(hdr);
18203f9d6ad7SLin Ling 	mutex_enter(hash_lock);
18213f9d6ad7SLin Ling 
1822dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
1823dcbf3bd6SGeorge Wilson 	ASSERT(hdr->b_l1hdr.b_freeze_cksum != NULL ||
1824dcbf3bd6SGeorge Wilson 	    hdr->b_l1hdr.b_state == arc_anon);
1825dcbf3bd6SGeorge Wilson 	arc_cksum_compute(buf);
18263f9d6ad7SLin Ling 	mutex_exit(hash_lock);
18276b4acc8bSahrens }
18286b4acc8bSahrens 
1829dcbf3bd6SGeorge Wilson /*
1830dcbf3bd6SGeorge Wilson  * The arc_buf_hdr_t's b_flags should never be modified directly. Instead,
1831dcbf3bd6SGeorge Wilson  * the following functions should be used to ensure that the flags are
1832dcbf3bd6SGeorge Wilson  * updated in a thread-safe way. When manipulating the flags either
1833dcbf3bd6SGeorge Wilson  * the hash_lock must be held or the hdr must be undiscoverable. This
1834dcbf3bd6SGeorge Wilson  * ensures that we're not racing with any other threads when updating
1835dcbf3bd6SGeorge Wilson  * the flags.
1836dcbf3bd6SGeorge Wilson  */
1837dcbf3bd6SGeorge Wilson static inline void
1838dcbf3bd6SGeorge Wilson arc_hdr_set_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 static inline void
1845dcbf3bd6SGeorge Wilson arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
1846dcbf3bd6SGeorge Wilson {
1847dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
1848dcbf3bd6SGeorge Wilson 	hdr->b_flags &= ~flags;
1849dcbf3bd6SGeorge Wilson }
1850dcbf3bd6SGeorge Wilson 
1851dcbf3bd6SGeorge Wilson /*
1852dcbf3bd6SGeorge Wilson  * Setting the compression bits in the arc_buf_hdr_t's b_flags is
1853dcbf3bd6SGeorge Wilson  * done in a special way since we have to clear and set bits
1854dcbf3bd6SGeorge Wilson  * at the same time. Consumers that wish to set the compression bits
1855dcbf3bd6SGeorge Wilson  * must use this function to ensure that the flags are updated in
1856dcbf3bd6SGeorge Wilson  * thread-safe manner.
1857dcbf3bd6SGeorge Wilson  */
1858fa9e4066Sahrens static void
1859dcbf3bd6SGeorge Wilson arc_hdr_set_compress(arc_buf_hdr_t *hdr, enum zio_compress cmp)
1860fa9e4066Sahrens {
1861dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
1862fa9e4066Sahrens 
1863dcbf3bd6SGeorge Wilson 	/*
1864dcbf3bd6SGeorge Wilson 	 * Holes and embedded blocks will always have a psize = 0 so
1865dcbf3bd6SGeorge Wilson 	 * we ignore the compression of the blkptr and set the
1866dcbf3bd6SGeorge Wilson 	 * arc_buf_hdr_t's compression to ZIO_COMPRESS_OFF.
1867dcbf3bd6SGeorge Wilson 	 * Holes and embedded blocks remain anonymous so we don't
1868dcbf3bd6SGeorge Wilson 	 * want to uncompress them. Mark them as uncompressed.
1869dcbf3bd6SGeorge Wilson 	 */
1870dcbf3bd6SGeorge Wilson 	if (!zfs_compressed_arc_enabled || HDR_GET_PSIZE(hdr) == 0) {
1871dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
1872dcbf3bd6SGeorge Wilson 		HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_OFF);
1873dcbf3bd6SGeorge Wilson 		ASSERT(!HDR_COMPRESSION_ENABLED(hdr));
1874dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
1875dcbf3bd6SGeorge Wilson 	} else {
1876dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
1877dcbf3bd6SGeorge Wilson 		HDR_SET_COMPRESS(hdr, cmp);
1878dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, cmp);
1879dcbf3bd6SGeorge Wilson 		ASSERT(HDR_COMPRESSION_ENABLED(hdr));
1880dcbf3bd6SGeorge Wilson 	}
1881dcbf3bd6SGeorge Wilson }
1882244781f1SPrakash Surya 
18835602294fSDan Kimmel /*
18845602294fSDan Kimmel  * Looks for another buf on the same hdr which has the data decompressed, copies
18855602294fSDan Kimmel  * from it, and returns true. If no such buf exists, returns false.
18865602294fSDan Kimmel  */
18875602294fSDan Kimmel static boolean_t
18885602294fSDan Kimmel arc_buf_try_copy_decompressed_data(arc_buf_t *buf)
18895602294fSDan Kimmel {
18905602294fSDan Kimmel 	arc_buf_hdr_t *hdr = buf->b_hdr;
18915602294fSDan Kimmel 	boolean_t copied = B_FALSE;
18925602294fSDan Kimmel 
18935602294fSDan Kimmel 	ASSERT(HDR_HAS_L1HDR(hdr));
18945602294fSDan Kimmel 	ASSERT3P(buf->b_data, !=, NULL);
18955602294fSDan Kimmel 	ASSERT(!ARC_BUF_COMPRESSED(buf));
18965602294fSDan Kimmel 
18975602294fSDan Kimmel 	for (arc_buf_t *from = hdr->b_l1hdr.b_buf; from != NULL;
18985602294fSDan Kimmel 	    from = from->b_next) {
18995602294fSDan Kimmel 		/* can't use our own data buffer */
19005602294fSDan Kimmel 		if (from == buf) {
19015602294fSDan Kimmel 			continue;
19025602294fSDan Kimmel 		}
19035602294fSDan Kimmel 
19045602294fSDan Kimmel 		if (!ARC_BUF_COMPRESSED(from)) {
19055602294fSDan Kimmel 			bcopy(from->b_data, buf->b_data, arc_buf_size(buf));
19065602294fSDan Kimmel 			copied = B_TRUE;
19075602294fSDan Kimmel 			break;
19085602294fSDan Kimmel 		}
19095602294fSDan Kimmel 	}
19105602294fSDan Kimmel 
19115602294fSDan Kimmel 	/*
19125602294fSDan Kimmel 	 * There were no decompressed bufs, so there should not be a
19135602294fSDan Kimmel 	 * checksum on the hdr either.
19145602294fSDan Kimmel 	 */
19155602294fSDan Kimmel 	EQUIV(!copied, hdr->b_l1hdr.b_freeze_cksum == NULL);
19165602294fSDan Kimmel 
19175602294fSDan Kimmel 	return (copied);
19185602294fSDan Kimmel }
19195602294fSDan Kimmel 
19205602294fSDan Kimmel /*
19215602294fSDan Kimmel  * Given a buf that has a data buffer attached to it, this function will
19225602294fSDan Kimmel  * efficiently fill the buf with data of the specified compression setting from
19235602294fSDan Kimmel  * the hdr and update the hdr's b_freeze_cksum if necessary. If the buf and hdr
19245602294fSDan Kimmel  * are already sharing a data buf, no copy is performed.
19255602294fSDan Kimmel  *
19265602294fSDan Kimmel  * If the buf is marked as compressed but uncompressed data was requested, this
19275602294fSDan Kimmel  * will allocate a new data buffer for the buf, remove that flag, and fill the
19285602294fSDan Kimmel  * buf with uncompressed data. You can't request a compressed buf on a hdr with
19295602294fSDan Kimmel  * uncompressed data, and (since we haven't added support for it yet) if you
19305602294fSDan Kimmel  * want compressed data your buf must already be marked as compressed and have
19315602294fSDan Kimmel  * the correct-sized data buffer.
19325602294fSDan Kimmel  */
1933dcbf3bd6SGeorge Wilson static int
19345602294fSDan Kimmel arc_buf_fill(arc_buf_t *buf, boolean_t compressed)
1935dcbf3bd6SGeorge Wilson {
1936dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
19375602294fSDan Kimmel 	boolean_t hdr_compressed = (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
1938dcbf3bd6SGeorge Wilson 	dmu_object_byteswap_t bswap = hdr->b_l1hdr.b_byteswap;
193989c86e32SChris Williamson 
19405602294fSDan Kimmel 	ASSERT3P(buf->b_data, !=, NULL);
19415602294fSDan Kimmel 	IMPLY(compressed, hdr_compressed);
19425602294fSDan Kimmel 	IMPLY(compressed, ARC_BUF_COMPRESSED(buf));
19435602294fSDan Kimmel 
19445602294fSDan Kimmel 	if (hdr_compressed == compressed) {
19455602294fSDan Kimmel 		if (!arc_buf_is_shared(buf)) {
1946770499e1SDan Kimmel 			abd_copy_to_buf(buf->b_data, hdr->b_l1hdr.b_pabd,
19475602294fSDan Kimmel 			    arc_buf_size(buf));
19485602294fSDan Kimmel 		}
1949dcbf3bd6SGeorge Wilson 	} else {
19505602294fSDan Kimmel 		ASSERT(hdr_compressed);
19515602294fSDan Kimmel 		ASSERT(!compressed);
1952dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, HDR_GET_PSIZE(hdr));
19535602294fSDan Kimmel 
19545602294fSDan Kimmel 		/*
19555602294fSDan Kimmel 		 * If the buf is sharing its data with the hdr, unlink it and
19565602294fSDan Kimmel 		 * allocate a new data buffer for the buf.
19575602294fSDan Kimmel 		 */
19585602294fSDan Kimmel 		if (arc_buf_is_shared(buf)) {
19595602294fSDan Kimmel 			ASSERT(ARC_BUF_COMPRESSED(buf));
19605602294fSDan Kimmel 
19615602294fSDan Kimmel 			/* We need to give the buf it's own b_data */
19625602294fSDan Kimmel 			buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
19635602294fSDan Kimmel 			buf->b_data =
19645602294fSDan Kimmel 			    arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
19655602294fSDan Kimmel 			arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
19665602294fSDan Kimmel 
19675602294fSDan Kimmel 			/* Previously overhead was 0; just add new overhead */
19685602294fSDan Kimmel 			ARCSTAT_INCR(arcstat_overhead_size, HDR_GET_LSIZE(hdr));
19695602294fSDan Kimmel 		} else if (ARC_BUF_COMPRESSED(buf)) {
19705602294fSDan Kimmel 			/* We need to reallocate the buf's b_data */
19715602294fSDan Kimmel 			arc_free_data_buf(hdr, buf->b_data, HDR_GET_PSIZE(hdr),
19725602294fSDan Kimmel 			    buf);
19735602294fSDan Kimmel 			buf->b_data =
19745602294fSDan Kimmel 			    arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
19755602294fSDan Kimmel 
19765602294fSDan Kimmel 			/* We increased the size of b_data; update overhead */
19775602294fSDan Kimmel 			ARCSTAT_INCR(arcstat_overhead_size,
19785602294fSDan Kimmel 			    HDR_GET_LSIZE(hdr) - HDR_GET_PSIZE(hdr));
19795602294fSDan Kimmel 		}
19805602294fSDan Kimmel 
19815602294fSDan Kimmel 		/*
19825602294fSDan Kimmel 		 * Regardless of the buf's previous compression settings, it
19835602294fSDan Kimmel 		 * should not be compressed at the end of this function.
19845602294fSDan Kimmel 		 */
19855602294fSDan Kimmel 		buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
19865602294fSDan Kimmel 
19875602294fSDan Kimmel 		/*
19885602294fSDan Kimmel 		 * Try copying the data from another buf which already has a
19895602294fSDan Kimmel 		 * decompressed version. If that's not possible, it's time to
19905602294fSDan Kimmel 		 * bite the bullet and decompress the data from the hdr.
19915602294fSDan Kimmel 		 */
19925602294fSDan Kimmel 		if (arc_buf_try_copy_decompressed_data(buf)) {
19935602294fSDan Kimmel 			/* Skip byteswapping and checksumming (already done) */
19945602294fSDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, !=, NULL);
19955602294fSDan Kimmel 			return (0);
19965602294fSDan Kimmel 		} else {
19975602294fSDan Kimmel 			int error = zio_decompress_data(HDR_GET_COMPRESS(hdr),
1998770499e1SDan Kimmel 			    hdr->b_l1hdr.b_pabd, buf->b_data,
19995602294fSDan Kimmel 			    HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
20005602294fSDan Kimmel 
20015602294fSDan Kimmel 			/*
20025602294fSDan Kimmel 			 * Absent hardware errors or software bugs, this should
20035602294fSDan Kimmel 			 * be impossible, but log it anyway so we can debug it.
20045602294fSDan Kimmel 			 */
20055602294fSDan Kimmel 			if (error != 0) {
20065602294fSDan Kimmel 				zfs_dbgmsg(
20075602294fSDan Kimmel 				    "hdr %p, compress %d, psize %d, lsize %d",
20085602294fSDan Kimmel 				    hdr, HDR_GET_COMPRESS(hdr),
20095602294fSDan Kimmel 				    HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
20105602294fSDan Kimmel 				return (SET_ERROR(EIO));
20115602294fSDan Kimmel 			}
2012ea8dc4b6Seschrock 		}
2013fa9e4066Sahrens 	}
20145602294fSDan Kimmel 
20155602294fSDan Kimmel 	/* Byteswap the buf's data if necessary */
2016dcbf3bd6SGeorge Wilson 	if (bswap != DMU_BSWAP_NUMFUNCS) {
2017dcbf3bd6SGeorge Wilson 		ASSERT(!HDR_SHARED_DATA(hdr));
2018dcbf3bd6SGeorge Wilson 		ASSERT3U(bswap, <, DMU_BSWAP_NUMFUNCS);
2019dcbf3bd6SGeorge Wilson 		dmu_ot_byteswap[bswap].ob_func(buf->b_data, HDR_GET_LSIZE(hdr));
2020dcbf3bd6SGeorge Wilson 	}
20215602294fSDan Kimmel 
20225602294fSDan Kimmel 	/* Compute the hdr's checksum if necessary */
2023dcbf3bd6SGeorge Wilson 	arc_cksum_compute(buf);
20245602294fSDan Kimmel 
2025dcbf3bd6SGeorge Wilson 	return (0);
2026fa9e4066Sahrens }
2027fa9e4066Sahrens 
20285602294fSDan Kimmel int
20295602294fSDan Kimmel arc_decompress(arc_buf_t *buf)
20305602294fSDan Kimmel {
20315602294fSDan Kimmel 	return (arc_buf_fill(buf, B_FALSE));
20325602294fSDan Kimmel }
20335602294fSDan Kimmel 
2034dcbf3bd6SGeorge Wilson /*
2035770499e1SDan Kimmel  * Return the size of the block, b_pabd, that is stored in the arc_buf_hdr_t.
2036dcbf3bd6SGeorge Wilson  */
2037dcbf3bd6SGeorge Wilson static uint64_t
2038dcbf3bd6SGeorge Wilson arc_hdr_size(arc_buf_hdr_t *hdr)
2039fa9e4066Sahrens {
2040dcbf3bd6SGeorge Wilson 	uint64_t size;
2041fa9e4066Sahrens 
2042dcbf3bd6SGeorge Wilson 	if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
2043dcbf3bd6SGeorge Wilson 	    HDR_GET_PSIZE(hdr) > 0) {
2044dcbf3bd6SGeorge Wilson 		size = HDR_GET_PSIZE(hdr);
2045dcbf3bd6SGeorge Wilson 	} else {
2046dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, 0);
2047dcbf3bd6SGeorge Wilson 		size = HDR_GET_LSIZE(hdr);
2048dcbf3bd6SGeorge Wilson 	}
2049dcbf3bd6SGeorge Wilson 	return (size);
2050dcbf3bd6SGeorge Wilson }
2051fa9e4066Sahrens 
2052dcbf3bd6SGeorge Wilson /*
2053dcbf3bd6SGeorge Wilson  * Increment the amount of evictable space in the arc_state_t's refcount.
2054dcbf3bd6SGeorge Wilson  * We account for the space used by the hdr and the arc buf individually
2055dcbf3bd6SGeorge Wilson  * so that we can add and remove them from the refcount individually.
2056dcbf3bd6SGeorge Wilson  */
2057dcbf3bd6SGeorge Wilson static void
2058dcbf3bd6SGeorge Wilson arc_evictable_space_increment(arc_buf_hdr_t *hdr, arc_state_t *state)
2059dcbf3bd6SGeorge Wilson {
2060dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type = arc_buf_type(hdr);
2061244781f1SPrakash Surya 
2062dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
20630e8c6158Smaybee 
2064dcbf3bd6SGeorge Wilson 	if (GHOST_STATE(state)) {
2065dcbf3bd6SGeorge Wilson 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
2066dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2067770499e1SDan Kimmel 		ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
20685602294fSDan Kimmel 		(void) refcount_add_many(&state->arcs_esize[type],
20695602294fSDan Kimmel 		    HDR_GET_LSIZE(hdr), hdr);
2070dcbf3bd6SGeorge Wilson 		return;
2071dcbf3bd6SGeorge Wilson 	}
2072dcbf3bd6SGeorge Wilson 
2073dcbf3bd6SGeorge Wilson 	ASSERT(!GHOST_STATE(state));
2074770499e1SDan Kimmel 	if (hdr->b_l1hdr.b_pabd != NULL) {
2075dcbf3bd6SGeorge Wilson 		(void) refcount_add_many(&state->arcs_esize[type],
2076dcbf3bd6SGeorge Wilson 		    arc_hdr_size(hdr), hdr);
2077dcbf3bd6SGeorge Wilson 	}
2078dcbf3bd6SGeorge Wilson 	for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2079dcbf3bd6SGeorge Wilson 	    buf = buf->b_next) {
20805602294fSDan Kimmel 		if (arc_buf_is_shared(buf))
2081dcbf3bd6SGeorge Wilson 			continue;
20825602294fSDan Kimmel 		(void) refcount_add_many(&state->arcs_esize[type],
20835602294fSDan Kimmel 		    arc_buf_size(buf), buf);
2084fa9e4066Sahrens 	}
2085fa9e4066Sahrens }
2086fa9e4066Sahrens 
2087fa9e4066Sahrens /*
2088dcbf3bd6SGeorge Wilson  * Decrement the amount of evictable space in the arc_state_t's refcount.
2089dcbf3bd6SGeorge Wilson  * We account for the space used by the hdr and the arc buf individually
2090dcbf3bd6SGeorge Wilson  * so that we can add and remove them from the refcount individually.
2091fa9e4066Sahrens  */
2092fa9e4066Sahrens static void
20935602294fSDan Kimmel arc_evictable_space_decrement(arc_buf_hdr_t *hdr, arc_state_t *state)
2094fa9e4066Sahrens {
2095dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type = arc_buf_type(hdr);
2096dcbf3bd6SGeorge Wilson 
2097dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2098dcbf3bd6SGeorge Wilson 
2099dcbf3bd6SGeorge Wilson 	if (GHOST_STATE(state)) {
2100dcbf3bd6SGeorge Wilson 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
2101dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2102770499e1SDan Kimmel 		ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2103dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_esize[type],
21045602294fSDan Kimmel 		    HDR_GET_LSIZE(hdr), hdr);
2105dcbf3bd6SGeorge Wilson 		return;
2106dcbf3bd6SGeorge Wilson 	}
2107dcbf3bd6SGeorge Wilson 
2108dcbf3bd6SGeorge Wilson 	ASSERT(!GHOST_STATE(state));
2109770499e1SDan Kimmel 	if (hdr->b_l1hdr.b_pabd != NULL) {
2110dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_esize[type],
2111dcbf3bd6SGeorge Wilson 		    arc_hdr_size(hdr), hdr);
2112dcbf3bd6SGeorge Wilson 	}
2113dcbf3bd6SGeorge Wilson 	for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2114dcbf3bd6SGeorge Wilson 	    buf = buf->b_next) {
21155602294fSDan Kimmel 		if (arc_buf_is_shared(buf))
2116dcbf3bd6SGeorge Wilson 			continue;
2117dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_esize[type],
21185602294fSDan Kimmel 		    arc_buf_size(buf), buf);
2119dcbf3bd6SGeorge Wilson 	}
2120dcbf3bd6SGeorge Wilson }
2121dcbf3bd6SGeorge Wilson 
2122dcbf3bd6SGeorge Wilson /*
2123dcbf3bd6SGeorge Wilson  * Add a reference to this hdr indicating that someone is actively
2124dcbf3bd6SGeorge Wilson  * referencing that memory. When the refcount transitions from 0 to 1,
2125dcbf3bd6SGeorge Wilson  * we remove it from the respective arc_state_t list to indicate that
2126dcbf3bd6SGeorge Wilson  * it is not evictable.
2127dcbf3bd6SGeorge Wilson  */
2128dcbf3bd6SGeorge Wilson static void
2129dcbf3bd6SGeorge Wilson add_reference(arc_buf_hdr_t *hdr, void *tag)
2130dcbf3bd6SGeorge Wilson {
2131dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2132dcbf3bd6SGeorge Wilson 	if (!MUTEX_HELD(HDR_LOCK(hdr))) {
2133dcbf3bd6SGeorge Wilson 		ASSERT(hdr->b_l1hdr.b_state == arc_anon);
2134dcbf3bd6SGeorge Wilson 		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2135dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2136dcbf3bd6SGeorge Wilson 	}
2137dcbf3bd6SGeorge Wilson 
2138dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
2139dcbf3bd6SGeorge Wilson 
2140dcbf3bd6SGeorge Wilson 	if ((refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
2141dcbf3bd6SGeorge Wilson 	    (state != arc_anon)) {
2142dcbf3bd6SGeorge Wilson 		/* We don't use the L2-only state list. */
2143dcbf3bd6SGeorge Wilson 		if (state != arc_l2c_only) {
214494c2d0ebSMatthew Ahrens 			multilist_remove(state->arcs_list[arc_buf_type(hdr)],
2145dcbf3bd6SGeorge Wilson 			    hdr);
21465602294fSDan Kimmel 			arc_evictable_space_decrement(hdr, state);
2147dcbf3bd6SGeorge Wilson 		}
2148dcbf3bd6SGeorge Wilson 		/* remove the prefetch flag if we get a reference */
2149dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
2150dcbf3bd6SGeorge Wilson 	}
2151dcbf3bd6SGeorge Wilson }
2152dcbf3bd6SGeorge Wilson 
2153dcbf3bd6SGeorge Wilson /*
2154dcbf3bd6SGeorge Wilson  * Remove a reference from this hdr. When the reference transitions from
2155dcbf3bd6SGeorge Wilson  * 1 to 0 and we're not anonymous, then we add this hdr to the arc_state_t's
2156dcbf3bd6SGeorge Wilson  * list making it eligible for eviction.
2157dcbf3bd6SGeorge Wilson  */
2158dcbf3bd6SGeorge Wilson static int
2159dcbf3bd6SGeorge Wilson remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
2160dcbf3bd6SGeorge Wilson {
2161dcbf3bd6SGeorge Wilson 	int cnt;
2162dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
2163dcbf3bd6SGeorge Wilson 
2164dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2165dcbf3bd6SGeorge Wilson 	ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
2166dcbf3bd6SGeorge Wilson 	ASSERT(!GHOST_STATE(state));
2167dcbf3bd6SGeorge Wilson 
2168dcbf3bd6SGeorge Wilson 	/*
2169dcbf3bd6SGeorge Wilson 	 * arc_l2c_only counts as a ghost state so we don't need to explicitly
2170dcbf3bd6SGeorge Wilson 	 * check to prevent usage of the arc_l2c_only list.
2171dcbf3bd6SGeorge Wilson 	 */
2172dcbf3bd6SGeorge Wilson 	if (((cnt = refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
2173dcbf3bd6SGeorge Wilson 	    (state != arc_anon)) {
217494c2d0ebSMatthew Ahrens 		multilist_insert(state->arcs_list[arc_buf_type(hdr)], hdr);
2175dcbf3bd6SGeorge Wilson 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
2176dcbf3bd6SGeorge Wilson 		arc_evictable_space_increment(hdr, state);
2177dcbf3bd6SGeorge Wilson 	}
2178dcbf3bd6SGeorge Wilson 	return (cnt);
2179dcbf3bd6SGeorge Wilson }
2180dcbf3bd6SGeorge Wilson 
2181dcbf3bd6SGeorge Wilson /*
2182dcbf3bd6SGeorge Wilson  * Move the supplied buffer to the indicated state. The hash lock
2183dcbf3bd6SGeorge Wilson  * for the buffer must be held by the caller.
2184dcbf3bd6SGeorge Wilson  */
2185dcbf3bd6SGeorge Wilson static void
2186dcbf3bd6SGeorge Wilson arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
2187dcbf3bd6SGeorge Wilson     kmutex_t *hash_lock)
2188dcbf3bd6SGeorge Wilson {
2189dcbf3bd6SGeorge Wilson 	arc_state_t *old_state;
2190dcbf3bd6SGeorge Wilson 	int64_t refcnt;
2191dcbf3bd6SGeorge Wilson 	uint32_t bufcnt;
2192dcbf3bd6SGeorge Wilson 	boolean_t update_old, update_new;
2193dcbf3bd6SGeorge Wilson 	arc_buf_contents_t buftype = arc_buf_type(hdr);
219489c86e32SChris Williamson 
219589c86e32SChris Williamson 	/*
219689c86e32SChris Williamson 	 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
219789c86e32SChris Williamson 	 * in arc_read() when bringing a buffer out of the L2ARC.  However, the
219889c86e32SChris Williamson 	 * L1 hdr doesn't always exist when we change state to arc_anon before
219989c86e32SChris Williamson 	 * destroying a header, in which case reallocating to add the L1 hdr is
220089c86e32SChris Williamson 	 * pointless.
220189c86e32SChris Williamson 	 */
220289c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr)) {
220389c86e32SChris Williamson 		old_state = hdr->b_l1hdr.b_state;
220489c86e32SChris Williamson 		refcnt = refcount_count(&hdr->b_l1hdr.b_refcnt);
2205dcbf3bd6SGeorge Wilson 		bufcnt = hdr->b_l1hdr.b_bufcnt;
2206770499e1SDan Kimmel 		update_old = (bufcnt > 0 || hdr->b_l1hdr.b_pabd != NULL);
220789c86e32SChris Williamson 	} else {
220889c86e32SChris Williamson 		old_state = arc_l2c_only;
220989c86e32SChris Williamson 		refcnt = 0;
2210dcbf3bd6SGeorge Wilson 		bufcnt = 0;
2211dcbf3bd6SGeorge Wilson 		update_old = B_FALSE;
221289c86e32SChris Williamson 	}
2213dcbf3bd6SGeorge Wilson 	update_new = update_old;
2214fa9e4066Sahrens 
2215fa9e4066Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
221669962b56SMatthew Ahrens 	ASSERT3P(new_state, !=, old_state);
2217dcbf3bd6SGeorge Wilson 	ASSERT(!GHOST_STATE(new_state) || bufcnt == 0);
2218dcbf3bd6SGeorge Wilson 	ASSERT(old_state != arc_anon || bufcnt <= 1);
2219fa9e4066Sahrens 
2220fa9e4066Sahrens 	/*
2221fa9e4066Sahrens 	 * If this buffer is evictable, transfer it from the
2222fa9e4066Sahrens 	 * old state list to the new state list.
2223fa9e4066Sahrens 	 */
2224ea8dc4b6Seschrock 	if (refcnt == 0) {
222589c86e32SChris Williamson 		if (old_state != arc_anon && old_state != arc_l2c_only) {
222689c86e32SChris Williamson 			ASSERT(HDR_HAS_L1HDR(hdr));
222794c2d0ebSMatthew Ahrens 			multilist_remove(old_state->arcs_list[buftype], hdr);
2228ea8dc4b6Seschrock 
2229dcbf3bd6SGeorge Wilson 			if (GHOST_STATE(old_state)) {
2230dcbf3bd6SGeorge Wilson 				ASSERT0(bufcnt);
2231dcbf3bd6SGeorge Wilson 				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2232dcbf3bd6SGeorge Wilson 				update_old = B_TRUE;
2233ea8dc4b6Seschrock 			}
22345602294fSDan Kimmel 			arc_evictable_space_decrement(hdr, old_state);
2235fa9e4066Sahrens 		}
223689c86e32SChris Williamson 		if (new_state != arc_anon && new_state != arc_l2c_only) {
2237fa9e4066Sahrens 
223889c86e32SChris Williamson 			/*
223989c86e32SChris Williamson 			 * An L1 header always exists here, since if we're
224089c86e32SChris Williamson 			 * moving to some L1-cached state (i.e. not l2c_only or
224189c86e32SChris Williamson 			 * anonymous), we realloc the header to add an L1hdr
224289c86e32SChris Williamson 			 * beforehand.
224389c86e32SChris Williamson 			 */
224489c86e32SChris Williamson 			ASSERT(HDR_HAS_L1HDR(hdr));
224594c2d0ebSMatthew Ahrens 			multilist_insert(new_state->arcs_list[buftype], hdr);
2246ea8dc4b6Seschrock 
2247ea8dc4b6Seschrock 			if (GHOST_STATE(new_state)) {
2248dcbf3bd6SGeorge Wilson 				ASSERT0(bufcnt);
2249dcbf3bd6SGeorge Wilson 				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2250dcbf3bd6SGeorge Wilson 				update_new = B_TRUE;
2251ea8dc4b6Seschrock 			}
2252dcbf3bd6SGeorge Wilson 			arc_evictable_space_increment(hdr, new_state);
2253fa9e4066Sahrens 		}
2254fa9e4066Sahrens 	}
2255fa9e4066Sahrens 
2256dcbf3bd6SGeorge Wilson 	ASSERT(!HDR_EMPTY(hdr));
22577adb730bSGeorge Wilson 	if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
22587adb730bSGeorge Wilson 		buf_hash_remove(hdr);
2259fa9e4066Sahrens 
226089c86e32SChris Williamson 	/* adjust state sizes (ignore arc_l2c_only) */
22612fd872a7SPrakash Surya 
2262dcbf3bd6SGeorge Wilson 	if (update_new && new_state != arc_l2c_only) {
22632fd872a7SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(hdr));
22642fd872a7SPrakash Surya 		if (GHOST_STATE(new_state)) {
2265dcbf3bd6SGeorge Wilson 			ASSERT0(bufcnt);
22662fd872a7SPrakash Surya 
22672fd872a7SPrakash Surya 			/*
2268dcbf3bd6SGeorge Wilson 			 * When moving a header to a ghost state, we first
22692fd872a7SPrakash Surya 			 * remove all arc buffers. Thus, we'll have a
2270dcbf3bd6SGeorge Wilson 			 * bufcnt of zero, and no arc buffer to use for
22712fd872a7SPrakash Surya 			 * the reference. As a result, we use the arc
22722fd872a7SPrakash Surya 			 * header pointer for the reference.
22732fd872a7SPrakash Surya 			 */
22742fd872a7SPrakash Surya 			(void) refcount_add_many(&new_state->arcs_size,
2275dcbf3bd6SGeorge Wilson 			    HDR_GET_LSIZE(hdr), hdr);
2276770499e1SDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
22772fd872a7SPrakash Surya 		} else {
2278dcbf3bd6SGeorge Wilson 			uint32_t buffers = 0;
22792fd872a7SPrakash Surya 
22802fd872a7SPrakash Surya 			/*
22812fd872a7SPrakash Surya 			 * Each individual buffer holds a unique reference,
22822fd872a7SPrakash Surya 			 * thus we must remove each of these references one
22832fd872a7SPrakash Surya 			 * at a time.
22842fd872a7SPrakash Surya 			 */
22852fd872a7SPrakash Surya 			for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
22862fd872a7SPrakash Surya 			    buf = buf->b_next) {
2287dcbf3bd6SGeorge Wilson 				ASSERT3U(bufcnt, !=, 0);
2288dcbf3bd6SGeorge Wilson 				buffers++;
2289dcbf3bd6SGeorge Wilson 
2290dcbf3bd6SGeorge Wilson 				/*
2291dcbf3bd6SGeorge Wilson 				 * When the arc_buf_t is sharing the data
2292dcbf3bd6SGeorge Wilson 				 * block with the hdr, the owner of the
2293dcbf3bd6SGeorge Wilson 				 * reference belongs to the hdr. Only
2294dcbf3bd6SGeorge Wilson 				 * add to the refcount if the arc_buf_t is
2295dcbf3bd6SGeorge Wilson 				 * not shared.
2296dcbf3bd6SGeorge Wilson 				 */
22975602294fSDan Kimmel 				if (arc_buf_is_shared(buf))
2298dcbf3bd6SGeorge Wilson 					continue;
2299dcbf3bd6SGeorge Wilson 
23002fd872a7SPrakash Surya 				(void) refcount_add_many(&new_state->arcs_size,
23015602294fSDan Kimmel 				    arc_buf_size(buf), buf);
2302dcbf3bd6SGeorge Wilson 			}
2303dcbf3bd6SGeorge Wilson 			ASSERT3U(bufcnt, ==, buffers);
2304dcbf3bd6SGeorge Wilson 
2305770499e1SDan Kimmel 			if (hdr->b_l1hdr.b_pabd != NULL) {
2306dcbf3bd6SGeorge Wilson 				(void) refcount_add_many(&new_state->arcs_size,
2307dcbf3bd6SGeorge Wilson 				    arc_hdr_size(hdr), hdr);
2308dcbf3bd6SGeorge Wilson 			} else {
2309dcbf3bd6SGeorge Wilson 				ASSERT(GHOST_STATE(old_state));
23102fd872a7SPrakash Surya 			}
23112fd872a7SPrakash Surya 		}
23122fd872a7SPrakash Surya 	}
23132fd872a7SPrakash Surya 
2314dcbf3bd6SGeorge Wilson 	if (update_old && old_state != arc_l2c_only) {
23152fd872a7SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(hdr));
23162fd872a7SPrakash Surya 		if (GHOST_STATE(old_state)) {
2317dcbf3bd6SGeorge Wilson 			ASSERT0(bufcnt);
2318770499e1SDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2319dcbf3bd6SGeorge Wilson 
23202fd872a7SPrakash Surya 			/*
23212fd872a7SPrakash Surya 			 * When moving a header off of a ghost state,
2322dcbf3bd6SGeorge Wilson 			 * the header will not contain any arc buffers.
2323dcbf3bd6SGeorge Wilson 			 * We use the arc header pointer for the reference
2324dcbf3bd6SGeorge Wilson 			 * which is exactly what we did when we put the
2325dcbf3bd6SGeorge Wilson 			 * header on the ghost state.
23262fd872a7SPrakash Surya 			 */
23272fd872a7SPrakash Surya 
23282fd872a7SPrakash Surya 			(void) refcount_remove_many(&old_state->arcs_size,
2329dcbf3bd6SGeorge Wilson 			    HDR_GET_LSIZE(hdr), hdr);
23302fd872a7SPrakash Surya 		} else {
2331dcbf3bd6SGeorge Wilson 			uint32_t buffers = 0;
23322fd872a7SPrakash Surya 
23332fd872a7SPrakash Surya 			/*
23342fd872a7SPrakash Surya 			 * Each individual buffer holds a unique reference,
23352fd872a7SPrakash Surya 			 * thus we must remove each of these references one
23362fd872a7SPrakash Surya 			 * at a time.
23372fd872a7SPrakash Surya 			 */
23382fd872a7SPrakash Surya 			for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
23392fd872a7SPrakash Surya 			    buf = buf->b_next) {
23405602294fSDan Kimmel 				ASSERT3U(bufcnt, !=, 0);
2341dcbf3bd6SGeorge Wilson 				buffers++;
2342dcbf3bd6SGeorge Wilson 
2343dcbf3bd6SGeorge Wilson 				/*
2344dcbf3bd6SGeorge Wilson 				 * When the arc_buf_t is sharing the data
2345dcbf3bd6SGeorge Wilson 				 * block with the hdr, the owner of the
2346dcbf3bd6SGeorge Wilson 				 * reference belongs to the hdr. Only
2347dcbf3bd6SGeorge Wilson 				 * add to the refcount if the arc_buf_t is
2348dcbf3bd6SGeorge Wilson 				 * not shared.
2349dcbf3bd6SGeorge Wilson 				 */
23505602294fSDan Kimmel 				if (arc_buf_is_shared(buf))
2351dcbf3bd6SGeorge Wilson 					continue;
2352dcbf3bd6SGeorge Wilson 
23532fd872a7SPrakash Surya 				(void) refcount_remove_many(
23545602294fSDan Kimmel 				    &old_state->arcs_size, arc_buf_size(buf),
2355dcbf3bd6SGeorge Wilson 				    buf);
23562fd872a7SPrakash Surya 			}
2357dcbf3bd6SGeorge Wilson 			ASSERT3U(bufcnt, ==, buffers);
2358770499e1SDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2359dcbf3bd6SGeorge Wilson 			(void) refcount_remove_many(
2360dcbf3bd6SGeorge Wilson 			    &old_state->arcs_size, arc_hdr_size(hdr), hdr);
23612fd872a7SPrakash Surya 		}
2362fa9e4066Sahrens 	}
23632fd872a7SPrakash Surya 
236489c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr))
236589c86e32SChris Williamson 		hdr->b_l1hdr.b_state = new_state;
2366fa94a07fSbrendan 
236789c86e32SChris Williamson 	/*
236889c86e32SChris Williamson 	 * L2 headers should never be on the L2 state list since they don't
236989c86e32SChris Williamson 	 * have L1 headers allocated.
237089c86e32SChris Williamson 	 */
237194c2d0ebSMatthew Ahrens 	ASSERT(multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
237294c2d0ebSMatthew Ahrens 	    multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
2373fa9e4066Sahrens }
2374fa9e4066Sahrens 
23750e8c6158Smaybee void
23765a98e54bSBrendan Gregg - Sun Microsystems arc_space_consume(uint64_t space, arc_space_type_t type)
23770e8c6158Smaybee {
23785a98e54bSBrendan Gregg - Sun Microsystems 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
23795a98e54bSBrendan Gregg - Sun Microsystems 
23805a98e54bSBrendan Gregg - Sun Microsystems 	switch (type) {
23815a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_DATA:
23823a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_data_size, space);
23835a98e54bSBrendan Gregg - Sun Microsystems 		break;
23844076b1bfSPrakash Surya 	case ARC_SPACE_META:
23853a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_metadata_size, space);
23864076b1bfSPrakash Surya 		break;
23875a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_OTHER:
23883a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_other_size, space);
23895a98e54bSBrendan Gregg - Sun Microsystems 		break;
23905a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_HDRS:
23913a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_hdr_size, space);
23925a98e54bSBrendan Gregg - Sun Microsystems 		break;
23935a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_L2HDRS:
23943a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_l2_hdr_size, space);
23955a98e54bSBrendan Gregg - Sun Microsystems 		break;
23965a98e54bSBrendan Gregg - Sun Microsystems 	}
23975a98e54bSBrendan Gregg - Sun Microsystems 
23984076b1bfSPrakash Surya 	if (type != ARC_SPACE_DATA)
23993a2d8a1bSPaul Dagnelie 		aggsum_add(&arc_meta_used, space);
24004076b1bfSPrakash Surya 
24013a2d8a1bSPaul Dagnelie 	aggsum_add(&arc_size, space);
24020e8c6158Smaybee }
24030e8c6158Smaybee 
24040e8c6158Smaybee void
24055a98e54bSBrendan Gregg - Sun Microsystems arc_space_return(uint64_t space, arc_space_type_t type)
24060e8c6158Smaybee {
24075a98e54bSBrendan Gregg - Sun Microsystems 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
24085a98e54bSBrendan Gregg - Sun Microsystems 
24095a98e54bSBrendan Gregg - Sun Microsystems 	switch (type) {
24105a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_DATA:
24113a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_data_size, -space);
24125a98e54bSBrendan Gregg - Sun Microsystems 		break;
24134076b1bfSPrakash Surya 	case ARC_SPACE_META:
24143a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_metadata_size, -space);
24154076b1bfSPrakash Surya 		break;
24165a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_OTHER:
24173a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_other_size, -space);
24185a98e54bSBrendan Gregg - Sun Microsystems 		break;
24195a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_HDRS:
24203a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_hdr_size, -space);
24215a98e54bSBrendan Gregg - Sun Microsystems 		break;
24225a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_L2HDRS:
24233a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_l2_hdr_size, -space);
24245a98e54bSBrendan Gregg - Sun Microsystems 		break;
24255a98e54bSBrendan Gregg - Sun Microsystems 	}
24265a98e54bSBrendan Gregg - Sun Microsystems 
24274076b1bfSPrakash Surya 	if (type != ARC_SPACE_DATA) {
24283a2d8a1bSPaul Dagnelie 		ASSERT(aggsum_compare(&arc_meta_used, space) >= 0);
24293a2d8a1bSPaul Dagnelie 		/*
24303a2d8a1bSPaul Dagnelie 		 * We use the upper bound here rather than the precise value
24313a2d8a1bSPaul Dagnelie 		 * because the arc_meta_max value doesn't need to be
24323a2d8a1bSPaul Dagnelie 		 * precise. It's only consumed by humans via arcstats.
24333a2d8a1bSPaul Dagnelie 		 */
24343a2d8a1bSPaul Dagnelie 		if (arc_meta_max < aggsum_upper_bound(&arc_meta_used))
24353a2d8a1bSPaul Dagnelie 			arc_meta_max = aggsum_upper_bound(&arc_meta_used);
24363a2d8a1bSPaul Dagnelie 		aggsum_add(&arc_meta_used, -space);
24374076b1bfSPrakash Surya 	}
24384076b1bfSPrakash Surya 
24393a2d8a1bSPaul Dagnelie 	ASSERT(aggsum_compare(&arc_size, space) >= 0);
24403a2d8a1bSPaul Dagnelie 	aggsum_add(&arc_size, -space);
24410e8c6158Smaybee }
24420e8c6158Smaybee 
2443dcbf3bd6SGeorge Wilson /*
24445602294fSDan Kimmel  * Given a hdr and a buf, returns whether that buf can share its b_data buffer
2445770499e1SDan Kimmel  * with the hdr's b_pabd.
2446dcbf3bd6SGeorge Wilson  */
24475602294fSDan Kimmel static boolean_t
24485602294fSDan Kimmel arc_can_share(arc_buf_hdr_t *hdr, arc_buf_t *buf)
24495602294fSDan Kimmel {
24505602294fSDan Kimmel 	/*
24515602294fSDan Kimmel 	 * The criteria for sharing a hdr's data are:
24525602294fSDan Kimmel 	 * 1. the hdr's compression matches the buf's compression
24535602294fSDan Kimmel 	 * 2. the hdr doesn't need to be byteswapped
24545602294fSDan Kimmel 	 * 3. the hdr isn't already being shared
24555602294fSDan Kimmel 	 * 4. the buf is either compressed or it is the last buf in the hdr list
24565602294fSDan Kimmel 	 *
24575602294fSDan Kimmel 	 * Criterion #4 maintains the invariant that shared uncompressed
24585602294fSDan Kimmel 	 * bufs must be the final buf in the hdr's b_buf list. Reading this, you
24595602294fSDan Kimmel 	 * might ask, "if a compressed buf is allocated first, won't that be the
24605602294fSDan Kimmel 	 * last thing in the list?", but in that case it's impossible to create
24615602294fSDan Kimmel 	 * a shared uncompressed buf anyway (because the hdr must be compressed
24625602294fSDan Kimmel 	 * to have the compressed buf). You might also think that #3 is
24635602294fSDan Kimmel 	 * sufficient to make this guarantee, however it's possible
24645602294fSDan Kimmel 	 * (specifically in the rare L2ARC write race mentioned in
24655602294fSDan Kimmel 	 * arc_buf_alloc_impl()) there will be an existing uncompressed buf that
24665602294fSDan Kimmel 	 * is sharable, but wasn't at the time of its allocation. Rather than
24675602294fSDan Kimmel 	 * allow a new shared uncompressed buf to be created and then shuffle
24685602294fSDan Kimmel 	 * the list around to make it the last element, this simply disallows
24695602294fSDan Kimmel 	 * sharing if the new buf isn't the first to be added.
24705602294fSDan Kimmel 	 */
24715602294fSDan Kimmel 	ASSERT3P(buf->b_hdr, ==, hdr);
24725602294fSDan Kimmel 	boolean_t hdr_compressed = HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF;
24735602294fSDan Kimmel 	boolean_t buf_compressed = ARC_BUF_COMPRESSED(buf) != 0;
24745602294fSDan Kimmel 	return (buf_compressed == hdr_compressed &&
24755602294fSDan Kimmel 	    hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS &&
24765602294fSDan Kimmel 	    !HDR_SHARED_DATA(hdr) &&
24775602294fSDan Kimmel 	    (ARC_BUF_LAST(buf) || ARC_BUF_COMPRESSED(buf)));
24785602294fSDan Kimmel }
24795602294fSDan Kimmel 
24805602294fSDan Kimmel /*
24815602294fSDan Kimmel  * Allocate a buf for this hdr. If you care about the data that's in the hdr,
24825602294fSDan Kimmel  * or if you want a compressed buffer, pass those flags in. Returns 0 if the
24835602294fSDan Kimmel  * copy was made successfully, or an error code otherwise.
24845602294fSDan Kimmel  */
24855602294fSDan Kimmel static int
24865602294fSDan Kimmel arc_buf_alloc_impl(arc_buf_hdr_t *hdr, void *tag, boolean_t compressed,
24875602294fSDan Kimmel     boolean_t fill, arc_buf_t **ret)
2488fa9e4066Sahrens {
2489fa9e4066Sahrens 	arc_buf_t *buf;
2490fa9e4066Sahrens 
2491dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2492dcbf3bd6SGeorge Wilson 	ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
2493dcbf3bd6SGeorge Wilson 	VERIFY(hdr->b_type == ARC_BUFC_DATA ||
2494dcbf3bd6SGeorge Wilson 	    hdr->b_type == ARC_BUFC_METADATA);
24955602294fSDan Kimmel 	ASSERT3P(ret, !=, NULL);
24965602294fSDan Kimmel 	ASSERT3P(*ret, ==, NULL);
2497dcbf3bd6SGeorge Wilson 
24985602294fSDan Kimmel 	buf = *ret = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2499fa9e4066Sahrens 	buf->b_hdr = hdr;
250044eda4d7Smaybee 	buf->b_data = NULL;
25015602294fSDan Kimmel 	buf->b_next = hdr->b_l1hdr.b_buf;
25025602294fSDan Kimmel 	buf->b_flags = 0;
250389c86e32SChris Williamson 
2504dcbf3bd6SGeorge Wilson 	add_reference(hdr, tag);
2505dcbf3bd6SGeorge Wilson 
2506dcbf3bd6SGeorge Wilson 	/*
2507dcbf3bd6SGeorge Wilson 	 * We're about to change the hdr's b_flags. We must either
2508dcbf3bd6SGeorge Wilson 	 * hold the hash_lock or be undiscoverable.
2509dcbf3bd6SGeorge Wilson 	 */
2510dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2511dcbf3bd6SGeorge Wilson 
2512dcbf3bd6SGeorge Wilson 	/*
25135602294fSDan Kimmel 	 * Only honor requests for compressed bufs if the hdr is actually
25145602294fSDan Kimmel 	 * compressed.
25155602294fSDan Kimmel 	 */
25165602294fSDan Kimmel 	if (compressed && HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF)
25175602294fSDan Kimmel 		buf->b_flags |= ARC_BUF_FLAG_COMPRESSED;
25185602294fSDan Kimmel 
25195602294fSDan Kimmel 	/*
25205602294fSDan Kimmel 	 * If the hdr's data can be shared then we share the data buffer and
25215602294fSDan Kimmel 	 * set the appropriate bit in the hdr's b_flags to indicate the hdr is
2522770499e1SDan Kimmel 	 * sharing it's b_pabd with the arc_buf_t. Otherwise, we allocate a new
25235602294fSDan Kimmel 	 * buffer to store the buf's data.
25245602294fSDan Kimmel 	 *
2525770499e1SDan Kimmel 	 * There are two additional restrictions here because we're sharing
2526770499e1SDan Kimmel 	 * hdr -> buf instead of the usual buf -> hdr. First, the hdr can't be
2527770499e1SDan Kimmel 	 * actively involved in an L2ARC write, because if this buf is used by
2528770499e1SDan Kimmel 	 * an arc_write() then the hdr's data buffer will be released when the
25295602294fSDan Kimmel 	 * write completes, even though the L2ARC write might still be using it.
2530770499e1SDan Kimmel 	 * Second, the hdr's ABD must be linear so that the buf's user doesn't
2531770499e1SDan Kimmel 	 * need to be ABD-aware.
2532dcbf3bd6SGeorge Wilson 	 */
2533770499e1SDan Kimmel 	boolean_t can_share = arc_can_share(hdr, buf) && !HDR_L2_WRITING(hdr) &&
2534770499e1SDan Kimmel 	    abd_is_linear(hdr->b_l1hdr.b_pabd);
25355602294fSDan Kimmel 
25365602294fSDan Kimmel 	/* Set up b_data and sharing */
25375602294fSDan Kimmel 	if (can_share) {
2538770499e1SDan Kimmel 		buf->b_data = abd_to_buf(hdr->b_l1hdr.b_pabd);
25395602294fSDan Kimmel 		buf->b_flags |= ARC_BUF_FLAG_SHARED;
2540dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
2541dcbf3bd6SGeorge Wilson 	} else {
25425602294fSDan Kimmel 		buf->b_data =
25435602294fSDan Kimmel 		    arc_get_data_buf(hdr, arc_buf_size(buf), buf);
25445602294fSDan Kimmel 		ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
2545dcbf3bd6SGeorge Wilson 	}
2546dcbf3bd6SGeorge Wilson 	VERIFY3P(buf->b_data, !=, NULL);
254789c86e32SChris Williamson 
254889c86e32SChris Williamson 	hdr->b_l1hdr.b_buf = buf;
2549dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_bufcnt += 1;
255089c86e32SChris Williamson 
25515602294fSDan Kimmel 	/*
25525602294fSDan Kimmel 	 * If the user wants the data from the hdr, we need to either copy or
25535602294fSDan Kimmel 	 * decompress the data.
25545602294fSDan Kimmel 	 */
25555602294fSDan Kimmel 	if (fill) {
25565602294fSDan Kimmel 		return (arc_buf_fill(buf, ARC_BUF_COMPRESSED(buf) != 0));
25575602294fSDan Kimmel 	}
2558dcbf3bd6SGeorge Wilson 
25595602294fSDan Kimmel 	return (0);
25605602294fSDan Kimmel }
2561dcbf3bd6SGeorge Wilson 
25625602294fSDan Kimmel static char *arc_onloan_tag = "onloan";
2563fa9e4066Sahrens 
25645602294fSDan Kimmel static inline void
25655602294fSDan Kimmel arc_loaned_bytes_update(int64_t delta)
25665602294fSDan Kimmel {
25675602294fSDan Kimmel 	atomic_add_64(&arc_loaned_bytes, delta);
2568dcbf3bd6SGeorge Wilson 
25695602294fSDan Kimmel 	/* assert that it did not wrap around */
25705602294fSDan Kimmel 	ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
2571fa9e4066Sahrens }
2572fa9e4066Sahrens 
25732fdbea25SAleksandr Guzovskiy /*
25742fdbea25SAleksandr Guzovskiy  * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
25752fdbea25SAleksandr Guzovskiy  * flight data by arc_tempreserve_space() until they are "returned". Loaned
25762fdbea25SAleksandr Guzovskiy  * buffers must be returned to the arc before they can be used by the DMU or
25772fdbea25SAleksandr Guzovskiy  * freed.
25782fdbea25SAleksandr Guzovskiy  */
25792fdbea25SAleksandr Guzovskiy arc_buf_t *
25805602294fSDan Kimmel arc_loan_buf(spa_t *spa, boolean_t is_metadata, int size)
25812fdbea25SAleksandr Guzovskiy {
25825602294fSDan Kimmel 	arc_buf_t *buf = arc_alloc_buf(spa, arc_onloan_tag,
25835602294fSDan Kimmel 	    is_metadata ? ARC_BUFC_METADATA : ARC_BUFC_DATA, size);
25845602294fSDan Kimmel 
25859be12bd7SAllan Jude 	arc_loaned_bytes_update(arc_buf_size(buf));
25865602294fSDan Kimmel 
25875602294fSDan Kimmel 	return (buf);
25885602294fSDan Kimmel }
25892fdbea25SAleksandr Guzovskiy 
25905602294fSDan Kimmel arc_buf_t *
25915602294fSDan Kimmel arc_loan_compressed_buf(spa_t *spa, uint64_t psize, uint64_t lsize,
25925602294fSDan Kimmel     enum zio_compress compression_type)
25935602294fSDan Kimmel {
25945602294fSDan Kimmel 	arc_buf_t *buf = arc_alloc_compressed_buf(spa, arc_onloan_tag,
25955602294fSDan Kimmel 	    psize, lsize, compression_type);
25965602294fSDan Kimmel 
25979be12bd7SAllan Jude 	arc_loaned_bytes_update(arc_buf_size(buf));
25982fdbea25SAleksandr Guzovskiy 
25992fdbea25SAleksandr Guzovskiy 	return (buf);
26002fdbea25SAleksandr Guzovskiy }
26012fdbea25SAleksandr Guzovskiy 
26025602294fSDan Kimmel 
26032fdbea25SAleksandr Guzovskiy /*
26042fdbea25SAleksandr Guzovskiy  * Return a loaned arc buffer to the arc.
26052fdbea25SAleksandr Guzovskiy  */
26062fdbea25SAleksandr Guzovskiy void
26072fdbea25SAleksandr Guzovskiy arc_return_buf(arc_buf_t *buf, void *tag)
26082fdbea25SAleksandr Guzovskiy {
26092fdbea25SAleksandr Guzovskiy 	arc_buf_hdr_t *hdr = buf->b_hdr;
26102fdbea25SAleksandr Guzovskiy 
2611dcbf3bd6SGeorge Wilson 	ASSERT3P(buf->b_data, !=, NULL);
261289c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
261389c86e32SChris Williamson 	(void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
261489c86e32SChris Williamson 	(void) refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
26152fdbea25SAleksandr Guzovskiy 
26165602294fSDan Kimmel 	arc_loaned_bytes_update(-arc_buf_size(buf));
26172fdbea25SAleksandr Guzovskiy }
26182fdbea25SAleksandr Guzovskiy 
2619c242f9a0Schunli zhang - Sun Microsystems - Irvine United States /* Detach an arc_buf from a dbuf (tag) */
2620c242f9a0Schunli zhang - Sun Microsystems - Irvine United States void
2621c242f9a0Schunli zhang - Sun Microsystems - Irvine United States arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
2622c242f9a0Schunli zhang - Sun Microsystems - Irvine United States {
262389c86e32SChris Williamson 	arc_buf_hdr_t *hdr = buf->b_hdr;
2624c242f9a0Schunli zhang - Sun Microsystems - Irvine United States 
2625dcbf3bd6SGeorge Wilson 	ASSERT3P(buf->b_data, !=, NULL);
262689c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
262789c86e32SChris Williamson 	(void) refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
262889c86e32SChris Williamson 	(void) refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
2629c242f9a0Schunli zhang - Sun Microsystems - Irvine United States 
26305602294fSDan Kimmel 	arc_loaned_bytes_update(arc_buf_size(buf));
2631c242f9a0Schunli zhang - Sun Microsystems - Irvine United States }
2632c242f9a0Schunli zhang - Sun Microsystems - Irvine United States 
2633dcbf3bd6SGeorge Wilson static void
2634770499e1SDan Kimmel l2arc_free_abd_on_write(abd_t *abd, size_t size, arc_buf_contents_t type)
2635ea8dc4b6Seschrock {
2636dcbf3bd6SGeorge Wilson 	l2arc_data_free_t *df = kmem_alloc(sizeof (*df), KM_SLEEP);
2637ea8dc4b6Seschrock 
2638770499e1SDan Kimmel 	df->l2df_abd = abd;
2639dcbf3bd6SGeorge Wilson 	df->l2df_size = size;
2640dcbf3bd6SGeorge Wilson 	df->l2df_type = type;
2641dcbf3bd6SGeorge Wilson 	mutex_enter(&l2arc_free_on_write_mtx);
2642dcbf3bd6SGeorge Wilson 	list_insert_head(l2arc_free_on_write, df);
2643dcbf3bd6SGeorge Wilson 	mutex_exit(&l2arc_free_on_write_mtx);
2644dcbf3bd6SGeorge Wilson }
2645b24ab676SJeff Bonwick 
2646dcbf3bd6SGeorge Wilson static void
2647dcbf3bd6SGeorge Wilson arc_hdr_free_on_write(arc_buf_hdr_t *hdr)
2648dcbf3bd6SGeorge Wilson {
2649dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
2650dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type = arc_buf_type(hdr);
2651dcbf3bd6SGeorge Wilson 	uint64_t size = arc_hdr_size(hdr);
2652dcbf3bd6SGeorge Wilson 
2653dcbf3bd6SGeorge Wilson 	/* protected by hash lock, if in the hash table */
2654dcbf3bd6SGeorge Wilson 	if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
2655dcbf3bd6SGeorge Wilson 		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2656dcbf3bd6SGeorge Wilson 		ASSERT(state != arc_anon && state != arc_l2c_only);
2657dcbf3bd6SGeorge Wilson 
2658dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_esize[type],
2659dcbf3bd6SGeorge Wilson 		    size, hdr);
2660dcbf3bd6SGeorge Wilson 	}
2661dcbf3bd6SGeorge Wilson 	(void) refcount_remove_many(&state->arcs_size, size, hdr);
26626de76ce2SAndriy Gapon 	if (type == ARC_BUFC_METADATA) {
26636de76ce2SAndriy Gapon 		arc_space_return(size, ARC_SPACE_META);
26646de76ce2SAndriy Gapon 	} else {
26656de76ce2SAndriy Gapon 		ASSERT(type == ARC_BUFC_DATA);
26666de76ce2SAndriy Gapon 		arc_space_return(size, ARC_SPACE_DATA);
26676de76ce2SAndriy Gapon 	}
2668dcbf3bd6SGeorge Wilson 
2669770499e1SDan Kimmel 	l2arc_free_abd_on_write(hdr->b_l1hdr.b_pabd, size, type);
2670dcbf3bd6SGeorge Wilson }
2671dcbf3bd6SGeorge Wilson 
2672dcbf3bd6SGeorge Wilson /*
2673dcbf3bd6SGeorge Wilson  * Share the arc_buf_t's data with the hdr. Whenever we are sharing the
2674dcbf3bd6SGeorge Wilson  * data buffer, we transfer the refcount ownership to the hdr and update
2675dcbf3bd6SGeorge Wilson  * the appropriate kstats.
2676dcbf3bd6SGeorge Wilson  */
2677dcbf3bd6SGeorge Wilson static void
2678dcbf3bd6SGeorge Wilson arc_share_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2679dcbf3bd6SGeorge Wilson {
2680dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
2681dcbf3bd6SGeorge Wilson 
26825602294fSDan Kimmel 	ASSERT(arc_can_share(hdr, buf));
2683770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2684dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
26859253d63dSGeorge Wilson 
26869253d63dSGeorge Wilson 	/*
2687dcbf3bd6SGeorge Wilson 	 * Start sharing the data buffer. We transfer the
2688dcbf3bd6SGeorge Wilson 	 * refcount ownership to the hdr since it always owns
2689dcbf3bd6SGeorge Wilson 	 * the refcount whenever an arc_buf_t is shared.
26909253d63dSGeorge Wilson 	 */
2691dcbf3bd6SGeorge Wilson 	refcount_transfer_ownership(&state->arcs_size, buf, hdr);
2692770499e1SDan Kimmel 	hdr->b_l1hdr.b_pabd = abd_get_from_buf(buf->b_data, arc_buf_size(buf));
2693770499e1SDan Kimmel 	abd_take_ownership_of_buf(hdr->b_l1hdr.b_pabd,
2694770499e1SDan Kimmel 	    HDR_ISTYPE_METADATA(hdr));
2695dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
26965602294fSDan Kimmel 	buf->b_flags |= ARC_BUF_FLAG_SHARED;
2697dcbf3bd6SGeorge Wilson 
2698dcbf3bd6SGeorge Wilson 	/*
2699dcbf3bd6SGeorge Wilson 	 * Since we've transferred ownership to the hdr we need
2700dcbf3bd6SGeorge Wilson 	 * to increment its compressed and uncompressed kstats and
2701dcbf3bd6SGeorge Wilson 	 * decrement the overhead size.
2702dcbf3bd6SGeorge Wilson 	 */
2703dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
2704dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
27055602294fSDan Kimmel 	ARCSTAT_INCR(arcstat_overhead_size, -arc_buf_size(buf));
2706ea8dc4b6Seschrock }
2707ea8dc4b6Seschrock 
2708dcbf3bd6SGeorge Wilson static void
2709dcbf3bd6SGeorge Wilson arc_unshare_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2710ea8dc4b6Seschrock {
2711dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
2712dcbf3bd6SGeorge Wilson 
2713dcbf3bd6SGeorge Wilson 	ASSERT(arc_buf_is_shared(buf));
2714770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2715dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2716ea8dc4b6Seschrock 
27179b23f181Smaybee 	/*
2718dcbf3bd6SGeorge Wilson 	 * We are no longer sharing this buffer so we need
2719dcbf3bd6SGeorge Wilson 	 * to transfer its ownership to the rightful owner.
27209b23f181Smaybee 	 */
2721dcbf3bd6SGeorge Wilson 	refcount_transfer_ownership(&state->arcs_size, hdr, buf);
2722dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2723770499e1SDan Kimmel 	abd_release_ownership_of_buf(hdr->b_l1hdr.b_pabd);
2724770499e1SDan Kimmel 	abd_put(hdr->b_l1hdr.b_pabd);
2725770499e1SDan Kimmel 	hdr->b_l1hdr.b_pabd = NULL;
27265602294fSDan Kimmel 	buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
2727dcbf3bd6SGeorge Wilson 
2728dcbf3bd6SGeorge Wilson 	/*
2729dcbf3bd6SGeorge Wilson 	 * Since the buffer is no longer shared between
2730dcbf3bd6SGeorge Wilson 	 * the arc buf and the hdr, count it as overhead.
2731dcbf3bd6SGeorge Wilson 	 */
2732dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
2733dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
27345602294fSDan Kimmel 	ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
2735dcbf3bd6SGeorge Wilson }
2736dcbf3bd6SGeorge Wilson 
2737dcbf3bd6SGeorge Wilson /*
27385602294fSDan Kimmel  * Remove an arc_buf_t from the hdr's buf list and return the last
27395602294fSDan Kimmel  * arc_buf_t on the list. If no buffers remain on the list then return
27405602294fSDan Kimmel  * NULL.
27415602294fSDan Kimmel  */
27425602294fSDan Kimmel static arc_buf_t *
27435602294fSDan Kimmel arc_buf_remove(arc_buf_hdr_t *hdr, arc_buf_t *buf)
27445602294fSDan Kimmel {
27455602294fSDan Kimmel 	ASSERT(HDR_HAS_L1HDR(hdr));
27465602294fSDan Kimmel 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
27475602294fSDan Kimmel 
27485602294fSDan Kimmel 	arc_buf_t **bufp = &hdr->b_l1hdr.b_buf;
27495602294fSDan Kimmel 	arc_buf_t *lastbuf = NULL;
27505602294fSDan Kimmel 
27515602294fSDan Kimmel 	/*
27525602294fSDan Kimmel 	 * Remove the buf from the hdr list and locate the last
27535602294fSDan Kimmel 	 * remaining buffer on the list.
27545602294fSDan Kimmel 	 */
27555602294fSDan Kimmel 	while (*bufp != NULL) {
27565602294fSDan Kimmel 		if (*bufp == buf)
27575602294fSDan Kimmel 			*bufp = buf->b_next;
27585602294fSDan Kimmel 
27595602294fSDan Kimmel 		/*
27605602294fSDan Kimmel 		 * If we've removed a buffer in the middle of
27615602294fSDan Kimmel 		 * the list then update the lastbuf and update
27625602294fSDan Kimmel 		 * bufp.
27635602294fSDan Kimmel 		 */
27645602294fSDan Kimmel 		if (*bufp != NULL) {
27655602294fSDan Kimmel 			lastbuf = *bufp;
27665602294fSDan Kimmel 			bufp = &(*bufp)->b_next;
27675602294fSDan Kimmel 		}
27685602294fSDan Kimmel 	}
27695602294fSDan Kimmel 	buf->b_next = NULL;
27705602294fSDan Kimmel 	ASSERT3P(lastbuf, !=, buf);
27715602294fSDan Kimmel 	IMPLY(hdr->b_l1hdr.b_bufcnt > 0, lastbuf != NULL);
27725602294fSDan Kimmel 	IMPLY(hdr->b_l1hdr.b_bufcnt > 0, hdr->b_l1hdr.b_buf != NULL);
27735602294fSDan Kimmel 	IMPLY(lastbuf != NULL, ARC_BUF_LAST(lastbuf));
27745602294fSDan Kimmel 
27755602294fSDan Kimmel 	return (lastbuf);
27765602294fSDan Kimmel }
27775602294fSDan Kimmel 
27785602294fSDan Kimmel /*
27795602294fSDan Kimmel  * Free up buf->b_data and pull the arc_buf_t off of the the arc_buf_hdr_t's
27805602294fSDan Kimmel  * list and free it.
2781dcbf3bd6SGeorge Wilson  */
2782dcbf3bd6SGeorge Wilson static void
27835602294fSDan Kimmel arc_buf_destroy_impl(arc_buf_t *buf)
2784dcbf3bd6SGeorge Wilson {
2785dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
2786dcbf3bd6SGeorge Wilson 
2787dcbf3bd6SGeorge Wilson 	/*
27885602294fSDan Kimmel 	 * Free up the data associated with the buf but only if we're not
27895602294fSDan Kimmel 	 * sharing this with the hdr. If we are sharing it with the hdr, the
27905602294fSDan Kimmel 	 * hdr is responsible for doing the free.
2791dcbf3bd6SGeorge Wilson 	 */
2792dcbf3bd6SGeorge Wilson 	if (buf->b_data != NULL) {
2793dcbf3bd6SGeorge Wilson 		/*
2794dcbf3bd6SGeorge Wilson 		 * We're about to change the hdr's b_flags. We must either
2795dcbf3bd6SGeorge Wilson 		 * hold the hash_lock or be undiscoverable.
2796dcbf3bd6SGeorge Wilson 		 */
2797dcbf3bd6SGeorge Wilson 		ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2798dcbf3bd6SGeorge Wilson 
2799dcbf3bd6SGeorge Wilson 		arc_cksum_verify(buf);
2800dcbf3bd6SGeorge Wilson 		arc_buf_unwatch(buf);
2801dcbf3bd6SGeorge Wilson 
28025602294fSDan Kimmel 		if (arc_buf_is_shared(buf)) {
2803dcbf3bd6SGeorge Wilson 			arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2804dcbf3bd6SGeorge Wilson 		} else {
28055602294fSDan Kimmel 			uint64_t size = arc_buf_size(buf);
2806dcbf3bd6SGeorge Wilson 			arc_free_data_buf(hdr, buf->b_data, size, buf);
2807dcbf3bd6SGeorge Wilson 			ARCSTAT_INCR(arcstat_overhead_size, -size);
2808dcbf3bd6SGeorge Wilson 		}
2809dcbf3bd6SGeorge Wilson 		buf->b_data = NULL;
2810dcbf3bd6SGeorge Wilson 
2811dcbf3bd6SGeorge Wilson 		ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
2812dcbf3bd6SGeorge Wilson 		hdr->b_l1hdr.b_bufcnt -= 1;
2813dcbf3bd6SGeorge Wilson 	}
2814dcbf3bd6SGeorge Wilson 
28155602294fSDan Kimmel 	arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
2816dcbf3bd6SGeorge Wilson 
28175602294fSDan Kimmel 	if (ARC_BUF_SHARED(buf) && !ARC_BUF_COMPRESSED(buf)) {
2818dcbf3bd6SGeorge Wilson 		/*
28195602294fSDan Kimmel 		 * If the current arc_buf_t is sharing its data buffer with the
2820770499e1SDan Kimmel 		 * hdr, then reassign the hdr's b_pabd to share it with the new
28215602294fSDan Kimmel 		 * buffer at the end of the list. The shared buffer is always
28225602294fSDan Kimmel 		 * the last one on the hdr's buffer list.
28235602294fSDan Kimmel 		 *
28245602294fSDan Kimmel 		 * There is an equivalent case for compressed bufs, but since
28255602294fSDan Kimmel 		 * they aren't guaranteed to be the last buf in the list and
28265602294fSDan Kimmel 		 * that is an exceedingly rare case, we just allow that space be
28275602294fSDan Kimmel 		 * wasted temporarily.
2828dcbf3bd6SGeorge Wilson 		 */
28295602294fSDan Kimmel 		if (lastbuf != NULL) {
28305602294fSDan Kimmel 			/* Only one buf can be shared at once */
28315602294fSDan Kimmel 			VERIFY(!arc_buf_is_shared(lastbuf));
28325602294fSDan Kimmel 			/* hdr is uncompressed so can't have compressed buf */
28335602294fSDan Kimmel 			VERIFY(!ARC_BUF_COMPRESSED(lastbuf));
2834dcbf3bd6SGeorge Wilson 
2835770499e1SDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2836770499e1SDan Kimmel 			arc_hdr_free_pabd(hdr);
2837dcbf3bd6SGeorge Wilson 
28385602294fSDan Kimmel 			/*
28395602294fSDan Kimmel 			 * We must setup a new shared block between the
28405602294fSDan Kimmel 			 * last buffer and the hdr. The data would have
28415602294fSDan Kimmel 			 * been allocated by the arc buf so we need to transfer
28425602294fSDan Kimmel 			 * ownership to the hdr since it's now being shared.
28435602294fSDan Kimmel 			 */
28445602294fSDan Kimmel 			arc_share_buf(hdr, lastbuf);
28455602294fSDan Kimmel 		}
28465602294fSDan Kimmel 	} else if (HDR_SHARED_DATA(hdr)) {
2847dcbf3bd6SGeorge Wilson 		/*
28485602294fSDan Kimmel 		 * Uncompressed shared buffers are always at the end
28495602294fSDan Kimmel 		 * of the list. Compressed buffers don't have the
28505602294fSDan Kimmel 		 * same requirements. This makes it hard to
28515602294fSDan Kimmel 		 * simply assert that the lastbuf is shared so
28525602294fSDan Kimmel 		 * we rely on the hdr's compression flags to determine
28535602294fSDan Kimmel 		 * if we have a compressed, shared buffer.
2854dcbf3bd6SGeorge Wilson 		 */
28555602294fSDan Kimmel 		ASSERT3P(lastbuf, !=, NULL);
28565602294fSDan Kimmel 		ASSERT(arc_buf_is_shared(lastbuf) ||
28575602294fSDan Kimmel 		    HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
2858dcbf3bd6SGeorge Wilson 	}
2859dcbf3bd6SGeorge Wilson 
28605602294fSDan Kimmel 	/*
28615602294fSDan Kimmel 	 * Free the checksum if we're removing the last uncompressed buf from
28625602294fSDan Kimmel 	 * this hdr.
28635602294fSDan Kimmel 	 */
28645602294fSDan Kimmel 	if (!arc_hdr_has_uncompressed_buf(hdr)) {
2865dcbf3bd6SGeorge Wilson 		arc_cksum_free(hdr);
28665602294fSDan Kimmel 	}
2867dcbf3bd6SGeorge Wilson 
2868dcbf3bd6SGeorge Wilson 	/* clean up the buf */
2869dcbf3bd6SGeorge Wilson 	buf->b_hdr = NULL;
2870dcbf3bd6SGeorge Wilson 	kmem_cache_free(buf_cache, buf);
2871dcbf3bd6SGeorge Wilson }
2872dcbf3bd6SGeorge Wilson 
2873dcbf3bd6SGeorge Wilson static void
2874770499e1SDan Kimmel arc_hdr_alloc_pabd(arc_buf_hdr_t *hdr)
2875dcbf3bd6SGeorge Wilson {
2876dcbf3bd6SGeorge Wilson 	ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
287789c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
2878dcbf3bd6SGeorge Wilson 	ASSERT(!HDR_SHARED_DATA(hdr));
2879ea8dc4b6Seschrock 
2880770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2881770499e1SDan Kimmel 	hdr->b_l1hdr.b_pabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr);
2882dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
2883770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
288489c86e32SChris Williamson 
2885dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
2886dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
2887ea8dc4b6Seschrock }
2888ea8dc4b6Seschrock 
2889244781f1SPrakash Surya static void
2890770499e1SDan Kimmel arc_hdr_free_pabd(arc_buf_hdr_t *hdr)
2891244781f1SPrakash Surya {
2892dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2893770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2894244781f1SPrakash Surya 
2895dcbf3bd6SGeorge Wilson 	/*
2896dcbf3bd6SGeorge Wilson 	 * If the hdr is currently being written to the l2arc then
2897dcbf3bd6SGeorge Wilson 	 * we defer freeing the data by adding it to the l2arc_free_on_write
2898dcbf3bd6SGeorge Wilson 	 * list. The l2arc will free the data once it's finished
2899dcbf3bd6SGeorge Wilson 	 * writing it to the l2arc device.
2900dcbf3bd6SGeorge Wilson 	 */
2901dcbf3bd6SGeorge Wilson 	if (HDR_L2_WRITING(hdr)) {
2902dcbf3bd6SGeorge Wilson 		arc_hdr_free_on_write(hdr);
2903dcbf3bd6SGeorge Wilson 		ARCSTAT_BUMP(arcstat_l2_free_on_write);
2904dcbf3bd6SGeorge Wilson 	} else {
2905770499e1SDan Kimmel 		arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
2906dcbf3bd6SGeorge Wilson 		    arc_hdr_size(hdr), hdr);
2907dcbf3bd6SGeorge Wilson 	}
2908770499e1SDan Kimmel 	hdr->b_l1hdr.b_pabd = NULL;
2909dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
2910dcbf3bd6SGeorge Wilson 
2911dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
2912dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
2913dcbf3bd6SGeorge Wilson }
2914dcbf3bd6SGeorge Wilson 
2915dcbf3bd6SGeorge Wilson static arc_buf_hdr_t *
2916dcbf3bd6SGeorge Wilson arc_hdr_alloc(uint64_t spa, int32_t psize, int32_t lsize,
29175602294fSDan Kimmel     enum zio_compress compression_type, arc_buf_contents_t type)
2918dcbf3bd6SGeorge Wilson {
2919dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr;
2920dcbf3bd6SGeorge Wilson 
2921dcbf3bd6SGeorge Wilson 	VERIFY(type == ARC_BUFC_DATA || type == ARC_BUFC_METADATA);
2922dcbf3bd6SGeorge Wilson 
2923dcbf3bd6SGeorge Wilson 	hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
2924dcbf3bd6SGeorge Wilson 	ASSERT(HDR_EMPTY(hdr));
2925dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
2926dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_thawed, ==, NULL);
2927dcbf3bd6SGeorge Wilson 	HDR_SET_PSIZE(hdr, psize);
2928dcbf3bd6SGeorge Wilson 	HDR_SET_LSIZE(hdr, lsize);
2929dcbf3bd6SGeorge Wilson 	hdr->b_spa = spa;
2930dcbf3bd6SGeorge Wilson 	hdr->b_type = type;
2931dcbf3bd6SGeorge Wilson 	hdr->b_flags = 0;
2932dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(hdr, arc_bufc_to_flags(type) | ARC_FLAG_HAS_L1HDR);
29335602294fSDan Kimmel 	arc_hdr_set_compress(hdr, compression_type);
2934dcbf3bd6SGeorge Wilson 
2935dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_state = arc_anon;
2936dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_arc_access = 0;
2937dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_bufcnt = 0;
2938dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_buf = NULL;
2939dcbf3bd6SGeorge Wilson 
2940dcbf3bd6SGeorge Wilson 	/*
2941dcbf3bd6SGeorge Wilson 	 * Allocate the hdr's buffer. This will contain either
2942dcbf3bd6SGeorge Wilson 	 * the compressed or uncompressed data depending on the block
2943dcbf3bd6SGeorge Wilson 	 * it references and compressed arc enablement.
2944dcbf3bd6SGeorge Wilson 	 */
2945770499e1SDan Kimmel 	arc_hdr_alloc_pabd(hdr);
2946dcbf3bd6SGeorge Wilson 	ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2947dcbf3bd6SGeorge Wilson 
2948dcbf3bd6SGeorge Wilson 	return (hdr);
2949244781f1SPrakash Surya }
2950244781f1SPrakash Surya 
2951fa94a07fSbrendan /*
2952dcbf3bd6SGeorge Wilson  * Transition between the two allocation states for the arc_buf_hdr struct.
2953dcbf3bd6SGeorge Wilson  * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
2954dcbf3bd6SGeorge Wilson  * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
2955dcbf3bd6SGeorge Wilson  * version is used when a cache buffer is only in the L2ARC in order to reduce
2956dcbf3bd6SGeorge Wilson  * memory usage.
2957fa94a07fSbrendan  */
2958dcbf3bd6SGeorge Wilson static arc_buf_hdr_t *
2959dcbf3bd6SGeorge Wilson arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
2960fa94a07fSbrendan {
2961dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L2HDR(hdr));
2962dcbf3bd6SGeorge Wilson 
2963dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *nhdr;
2964dcbf3bd6SGeorge Wilson 	l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
2965dcbf3bd6SGeorge Wilson 
2966dcbf3bd6SGeorge Wilson 	ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
2967dcbf3bd6SGeorge Wilson 	    (old == hdr_l2only_cache && new == hdr_full_cache));
2968dcbf3bd6SGeorge Wilson 
2969dcbf3bd6SGeorge Wilson 	nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
2970dcbf3bd6SGeorge Wilson 
2971dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
2972dcbf3bd6SGeorge Wilson 	buf_hash_remove(hdr);
2973dcbf3bd6SGeorge Wilson 
2974dcbf3bd6SGeorge Wilson 	bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
2975dcbf3bd6SGeorge Wilson 
2976dcbf3bd6SGeorge Wilson 	if (new == hdr_full_cache) {
2977dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(nhdr, ARC_FLAG_HAS_L1HDR);
2978dcbf3bd6SGeorge Wilson 		/*
2979dcbf3bd6SGeorge Wilson 		 * arc_access and arc_change_state need to be aware that a
2980dcbf3bd6SGeorge Wilson 		 * header has just come out of L2ARC, so we set its state to
2981dcbf3bd6SGeorge Wilson 		 * l2c_only even though it's about to change.
2982dcbf3bd6SGeorge Wilson 		 */
2983dcbf3bd6SGeorge Wilson 		nhdr->b_l1hdr.b_state = arc_l2c_only;
2984dcbf3bd6SGeorge Wilson 
2985dcbf3bd6SGeorge Wilson 		/* Verify previous threads set to NULL before freeing */
2986770499e1SDan Kimmel 		ASSERT3P(nhdr->b_l1hdr.b_pabd, ==, NULL);
2987dcbf3bd6SGeorge Wilson 	} else {
2988dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2989dcbf3bd6SGeorge Wilson 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
2990dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
2991dcbf3bd6SGeorge Wilson 
2992dcbf3bd6SGeorge Wilson 		/*
2993dcbf3bd6SGeorge Wilson 		 * If we've reached here, We must have been called from
2994dcbf3bd6SGeorge Wilson 		 * arc_evict_hdr(), as such we should have already been
2995dcbf3bd6SGeorge Wilson 		 * removed from any ghost list we were previously on
2996dcbf3bd6SGeorge Wilson 		 * (which protects us from racing with arc_evict_state),
2997dcbf3bd6SGeorge Wilson 		 * thus no locking is needed during this check.
2998dcbf3bd6SGeorge Wilson 		 */
2999dcbf3bd6SGeorge Wilson 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3000cd1c8b85SMatthew Ahrens 
3001dcbf3bd6SGeorge Wilson 		/*
3002dcbf3bd6SGeorge Wilson 		 * A buffer must not be moved into the arc_l2c_only
3003dcbf3bd6SGeorge Wilson 		 * state if it's not finished being written out to the
3004770499e1SDan Kimmel 		 * l2arc device. Otherwise, the b_l1hdr.b_pabd field
3005dcbf3bd6SGeorge Wilson 		 * might try to be accessed, even though it was removed.
3006dcbf3bd6SGeorge Wilson 		 */
3007dcbf3bd6SGeorge Wilson 		VERIFY(!HDR_L2_WRITING(hdr));
3008770499e1SDan Kimmel 		VERIFY3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3009fa94a07fSbrendan 
3010dcbf3bd6SGeorge Wilson #ifdef ZFS_DEBUG
3011dcbf3bd6SGeorge Wilson 		if (hdr->b_l1hdr.b_thawed != NULL) {
3012dcbf3bd6SGeorge Wilson 			kmem_free(hdr->b_l1hdr.b_thawed, 1);
3013dcbf3bd6SGeorge Wilson 			hdr->b_l1hdr.b_thawed = NULL;
3014dcbf3bd6SGeorge Wilson 		}
3015dcbf3bd6SGeorge Wilson #endif
3016244781f1SPrakash Surya 
3017dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(nhdr, ARC_FLAG_HAS_L1HDR);
3018dcbf3bd6SGeorge Wilson 	}
3019244781f1SPrakash Surya 	/*
3020dcbf3bd6SGeorge Wilson 	 * The header has been reallocated so we need to re-insert it into any
3021dcbf3bd6SGeorge Wilson 	 * lists it was on.
3022244781f1SPrakash Surya 	 */
3023dcbf3bd6SGeorge Wilson 	(void) buf_hash_insert(nhdr, NULL);
3024244781f1SPrakash Surya 
3025dcbf3bd6SGeorge Wilson 	ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
3026dcbf3bd6SGeorge Wilson 
3027dcbf3bd6SGeorge Wilson 	mutex_enter(&dev->l2ad_mtx);
3028244781f1SPrakash Surya 
3029244781f1SPrakash Surya 	/*
3030dcbf3bd6SGeorge Wilson 	 * We must place the realloc'ed header back into the list at
3031dcbf3bd6SGeorge Wilson 	 * the same spot. Otherwise, if it's placed earlier in the list,
3032dcbf3bd6SGeorge Wilson 	 * l2arc_write_buffers() could find it during the function's
3033dcbf3bd6SGeorge Wilson 	 * write phase, and try to write it out to the l2arc.
3034244781f1SPrakash Surya 	 */
3035dcbf3bd6SGeorge Wilson 	list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
3036dcbf3bd6SGeorge Wilson 	list_remove(&dev->l2ad_buflist, hdr);
3037dcbf3bd6SGeorge Wilson 
3038dcbf3bd6SGeorge Wilson 	mutex_exit(&dev->l2ad_mtx);
3039244781f1SPrakash Surya 
3040244781f1SPrakash Surya 	/*
3041dcbf3bd6SGeorge Wilson 	 * Since we're using the pointer address as the tag when
3042dcbf3bd6SGeorge Wilson 	 * incrementing and decrementing the l2ad_alloc refcount, we
3043dcbf3bd6SGeorge Wilson 	 * must remove the old pointer (that we're about to destroy) and
3044dcbf3bd6SGeorge Wilson 	 * add the new pointer to the refcount. Otherwise we'd remove
3045dcbf3bd6SGeorge Wilson 	 * the wrong pointer address when calling arc_hdr_destroy() later.
3046244781f1SPrakash Surya 	 */
3047244781f1SPrakash Surya 
3048dcbf3bd6SGeorge Wilson 	(void) refcount_remove_many(&dev->l2ad_alloc, arc_hdr_size(hdr), hdr);
3049dcbf3bd6SGeorge Wilson 	(void) refcount_add_many(&dev->l2ad_alloc, arc_hdr_size(nhdr), nhdr);
3050244781f1SPrakash Surya 
3051dcbf3bd6SGeorge Wilson 	buf_discard_identity(hdr);
3052dcbf3bd6SGeorge Wilson 	kmem_cache_free(old, hdr);
3053244781f1SPrakash Surya 
3054dcbf3bd6SGeorge Wilson 	return (nhdr);
3055244781f1SPrakash Surya }
3056244781f1SPrakash Surya 
3057bbfa8ea8SMatthew Ahrens /*
3058dcbf3bd6SGeorge Wilson  * Allocate a new arc_buf_hdr_t and arc_buf_t and return the buf to the caller.
3059dcbf3bd6SGeorge Wilson  * The buf is returned thawed since we expect the consumer to modify it.
3060bbfa8ea8SMatthew Ahrens  */
3061dcbf3bd6SGeorge Wilson arc_buf_t *
30625602294fSDan Kimmel arc_alloc_buf(spa_t *spa, void *tag, arc_buf_contents_t type, int32_t size)
3063ea8dc4b6Seschrock {
3064dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), size, size,
3065dcbf3bd6SGeorge Wilson 	    ZIO_COMPRESS_OFF, type);
3066dcbf3bd6SGeorge Wilson 	ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
30675602294fSDan Kimmel 
30685602294fSDan Kimmel 	arc_buf_t *buf = NULL;
30695602294fSDan Kimmel 	VERIFY0(arc_buf_alloc_impl(hdr, tag, B_FALSE, B_FALSE, &buf));
3070dcbf3bd6SGeorge Wilson 	arc_buf_thaw(buf);
30715602294fSDan Kimmel 
30725602294fSDan Kimmel 	return (buf);
30735602294fSDan Kimmel }
30745602294fSDan Kimmel 
30755602294fSDan Kimmel /*
30765602294fSDan Kimmel  * Allocate a compressed buf in the same manner as arc_alloc_buf. Don't use this
30775602294fSDan Kimmel  * for bufs containing metadata.
30785602294fSDan Kimmel  */
30795602294fSDan Kimmel arc_buf_t *
30805602294fSDan Kimmel arc_alloc_compressed_buf(spa_t *spa, void *tag, uint64_t psize, uint64_t lsize,
30815602294fSDan Kimmel     enum zio_compress compression_type)
30825602294fSDan Kimmel {
30835602294fSDan Kimmel 	ASSERT3U(lsize, >, 0);
30845602294fSDan Kimmel 	ASSERT3U(lsize, >=, psize);
30855602294fSDan Kimmel 	ASSERT(compression_type > ZIO_COMPRESS_OFF);
30865602294fSDan Kimmel 	ASSERT(compression_type < ZIO_COMPRESS_FUNCTIONS);
30875602294fSDan Kimmel 
30885602294fSDan Kimmel 	arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
30895602294fSDan Kimmel 	    compression_type, ARC_BUFC_DATA);
30905602294fSDan Kimmel 	ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
30915602294fSDan Kimmel 
30925602294fSDan Kimmel 	arc_buf_t *buf = NULL;
30935602294fSDan Kimmel 	VERIFY0(arc_buf_alloc_impl(hdr, tag, B_TRUE, B_FALSE, &buf));
30945602294fSDan Kimmel 	arc_buf_thaw(buf);
30955602294fSDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
30965602294fSDan Kimmel 
3097770499e1SDan Kimmel 	if (!arc_buf_is_shared(buf)) {
3098770499e1SDan Kimmel 		/*
3099770499e1SDan Kimmel 		 * To ensure that the hdr has the correct data in it if we call
3100770499e1SDan Kimmel 		 * arc_decompress() on this buf before it's been written to
3101770499e1SDan Kimmel 		 * disk, it's easiest if we just set up sharing between the
3102770499e1SDan Kimmel 		 * buf and the hdr.
3103770499e1SDan Kimmel 		 */
3104770499e1SDan Kimmel 		ASSERT(!abd_is_linear(hdr->b_l1hdr.b_pabd));
3105770499e1SDan Kimmel 		arc_hdr_free_pabd(hdr);
3106770499e1SDan Kimmel 		arc_share_buf(hdr, buf);
3107770499e1SDan Kimmel 	}
3108770499e1SDan Kimmel 
3109dcbf3bd6SGeorge Wilson 	return (buf);
3110ea8dc4b6Seschrock }
3111ea8dc4b6Seschrock 
3112a52fc310SPrakash Surya static void
3113a52fc310SPrakash Surya arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
3114a52fc310SPrakash Surya {
3115a52fc310SPrakash Surya 	l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
3116a52fc310SPrakash Surya 	l2arc_dev_t *dev = l2hdr->b_dev;
311716a7e5acSAndriy Gapon 	uint64_t psize = arc_hdr_size(hdr);
3118a52fc310SPrakash Surya 
3119a52fc310SPrakash Surya 	ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
3120a52fc310SPrakash Surya 	ASSERT(HDR_HAS_L2HDR(hdr));
3121a52fc310SPrakash Surya 
3122a52fc310SPrakash Surya 	list_remove(&dev->l2ad_buflist, hdr);
3123a52fc310SPrakash Surya 
312416a7e5acSAndriy Gapon 	ARCSTAT_INCR(arcstat_l2_psize, -psize);
312516a7e5acSAndriy Gapon 	ARCSTAT_INCR(arcstat_l2_lsize, -HDR_GET_LSIZE(hdr));
3126a52fc310SPrakash Surya 
312716a7e5acSAndriy Gapon 	vdev_space_update(dev->l2ad_vdev, -psize, 0, 0);
3128a52fc310SPrakash Surya 
312916a7e5acSAndriy Gapon 	(void) refcount_remove_many(&dev->l2ad_alloc, psize, hdr);
3130dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
3131a52fc310SPrakash Surya }
3132a52fc310SPrakash Surya 
3133fa9e4066Sahrens static void
3134ea8dc4b6Seschrock arc_hdr_destroy(arc_buf_hdr_t *hdr)
3135fa9e4066Sahrens {
313689c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr)) {
313789c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_buf == NULL ||
3138dcbf3bd6SGeorge Wilson 		    hdr->b_l1hdr.b_bufcnt > 0);
313989c86e32SChris Williamson 		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
314089c86e32SChris Williamson 		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
314189c86e32SChris Williamson 	}
3142ea8dc4b6Seschrock 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
314389c86e32SChris Williamson 	ASSERT(!HDR_IN_HASH_TABLE(hdr));
314489c86e32SChris Williamson 
3145dcbf3bd6SGeorge Wilson 	if (!HDR_EMPTY(hdr))
3146dcbf3bd6SGeorge Wilson 		buf_discard_identity(hdr);
3147dcbf3bd6SGeorge Wilson 
314889c86e32SChris Williamson 	if (HDR_HAS_L2HDR(hdr)) {
3149a52fc310SPrakash Surya 		l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3150a52fc310SPrakash Surya 		boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
3151b24ab676SJeff Bonwick 
3152a52fc310SPrakash Surya 		if (!buflist_held)
3153a52fc310SPrakash Surya 			mutex_enter(&dev->l2ad_mtx);
315489c86e32SChris Williamson 
3155244781f1SPrakash Surya 		/*
3156a52fc310SPrakash Surya 		 * Even though we checked this conditional above, we
3157a52fc310SPrakash Surya 		 * need to check this again now that we have the
3158a52fc310SPrakash Surya 		 * l2ad_mtx. This is because we could be racing with
3159a52fc310SPrakash Surya 		 * another thread calling l2arc_evict() which might have
3160a52fc310SPrakash Surya 		 * destroyed this header's L2 portion as we were waiting
3161a52fc310SPrakash Surya 		 * to acquire the l2ad_mtx. If that happens, we don't
3162a52fc310SPrakash Surya 		 * want to re-destroy the header's L2 portion.
3163244781f1SPrakash Surya 		 */
3164a52fc310SPrakash Surya 		if (HDR_HAS_L2HDR(hdr))
3165a52fc310SPrakash Surya 			arc_hdr_l2hdr_destroy(hdr);
3166b24ab676SJeff Bonwick 
3167b24ab676SJeff Bonwick 		if (!buflist_held)
3168a52fc310SPrakash Surya 			mutex_exit(&dev->l2ad_mtx);
3169fa94a07fSbrendan 	}
3170fa94a07fSbrendan 
3171dcbf3bd6SGeorge Wilson 	if (HDR_HAS_L1HDR(hdr)) {
3172dcbf3bd6SGeorge Wilson 		arc_cksum_free(hdr);
317389c86e32SChris Williamson 
3174dcbf3bd6SGeorge Wilson 		while (hdr->b_l1hdr.b_buf != NULL)
31755602294fSDan Kimmel 			arc_buf_destroy_impl(hdr->b_l1hdr.b_buf);
317689c86e32SChris Williamson 
317789c86e32SChris Williamson #ifdef ZFS_DEBUG
317889c86e32SChris Williamson 		if (hdr->b_l1hdr.b_thawed != NULL) {
317989c86e32SChris Williamson 			kmem_free(hdr->b_l1hdr.b_thawed, 1);
318089c86e32SChris Williamson 			hdr->b_l1hdr.b_thawed = NULL;
318189c86e32SChris Williamson 		}
318289c86e32SChris Williamson #endif
3183dcbf3bd6SGeorge Wilson 
3184770499e1SDan Kimmel 		if (hdr->b_l1hdr.b_pabd != NULL) {
3185770499e1SDan Kimmel 			arc_hdr_free_pabd(hdr);
3186dcbf3bd6SGeorge Wilson 		}
31873f9d6ad7SLin Ling 	}
3188ea8dc4b6Seschrock 
3189fa9e4066Sahrens 	ASSERT3P(hdr->b_hash_next, ==, NULL);
319089c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr)) {
3191244781f1SPrakash Surya 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
319289c86e32SChris Williamson 		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
319389c86e32SChris Williamson 		kmem_cache_free(hdr_full_cache, hdr);
319489c86e32SChris Williamson 	} else {
319589c86e32SChris Williamson 		kmem_cache_free(hdr_l2only_cache, hdr);
319689c86e32SChris Williamson 	}
3197fa9e4066Sahrens }
3198fa9e4066Sahrens 
3199fa9e4066Sahrens void
3200dcbf3bd6SGeorge Wilson arc_buf_destroy(arc_buf_t *buf, void* tag)
3201ea8dc4b6Seschrock {
3202ea8dc4b6Seschrock 	arc_buf_hdr_t *hdr = buf->b_hdr;
3203ea8dc4b6Seschrock 	kmutex_t *hash_lock = HDR_LOCK(hdr);
3204fa9e4066Sahrens 
320589c86e32SChris Williamson 	if (hdr->b_l1hdr.b_state == arc_anon) {
3206dcbf3bd6SGeorge Wilson 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
3207dcbf3bd6SGeorge Wilson 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3208dcbf3bd6SGeorge Wilson 		VERIFY0(remove_reference(hdr, NULL, tag));
3209dcbf3bd6SGeorge Wilson 		arc_hdr_destroy(hdr);
3210dcbf3bd6SGeorge Wilson 		return;
3211ea8dc4b6Seschrock 	}
3212ea8dc4b6Seschrock 
3213ea8dc4b6Seschrock 	mutex_enter(hash_lock);
3214dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr, ==, buf->b_hdr);
3215dcbf3bd6SGeorge Wilson 	ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
32163f9d6ad7SLin Ling 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3217dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_state, !=, arc_anon);
3218dcbf3bd6SGeorge Wilson 	ASSERT3P(buf->b_data, !=, NULL);
3219ea8dc4b6Seschrock 
3220ea8dc4b6Seschrock 	(void) remove_reference(hdr, hash_lock, tag);
32215602294fSDan Kimmel 	arc_buf_destroy_impl(buf);
3222ea8dc4b6Seschrock 	mutex_exit(hash_lock);
3223fa9e4066Sahrens }
3224fa9e4066Sahrens 
3225fa9e4066Sahrens /*
3226244781f1SPrakash Surya  * Evict the arc_buf_hdr that is provided as a parameter. The resultant
3227244781f1SPrakash Surya  * state of the header is dependent on it's state prior to entering this
3228244781f1SPrakash Surya  * function. The following transitions are possible:
3229874395d5Smaybee  *
3230244781f1SPrakash Surya  *    - arc_mru -> arc_mru_ghost
3231244781f1SPrakash Surya  *    - arc_mfu -> arc_mfu_ghost
3232244781f1SPrakash Surya  *    - arc_mru_ghost -> arc_l2c_only
3233244781f1SPrakash Surya  *    - arc_mru_ghost -> deleted
3234244781f1SPrakash Surya  *    - arc_mfu_ghost -> arc_l2c_only
3235244781f1SPrakash Surya  *    - arc_mfu_ghost -> deleted
3236fa9e4066Sahrens  */
3237244781f1SPrakash Surya static int64_t
3238244781f1SPrakash Surya arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3239fa9e4066Sahrens {
3240244781f1SPrakash Surya 	arc_state_t *evicted_state, *state;
3241244781f1SPrakash Surya 	int64_t bytes_evicted = 0;
3242fa9e4066Sahrens 
3243244781f1SPrakash Surya 	ASSERT(MUTEX_HELD(hash_lock));
3244244781f1SPrakash Surya 	ASSERT(HDR_HAS_L1HDR(hdr));
3245fa9e4066Sahrens 
3246244781f1SPrakash Surya 	state = hdr->b_l1hdr.b_state;
3247244781f1SPrakash Surya 	if (GHOST_STATE(state)) {
3248244781f1SPrakash Surya 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3249dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3250fa9e4066Sahrens 
3251244781f1SPrakash Surya 		/*
3252244781f1SPrakash Surya 		 * l2arc_write_buffers() relies on a header's L1 portion
3253770499e1SDan Kimmel 		 * (i.e. its b_pabd field) during it's write phase.
3254244781f1SPrakash Surya 		 * Thus, we cannot push a header onto the arc_l2c_only
3255244781f1SPrakash Surya 		 * state (removing it's L1 piece) until the header is
3256244781f1SPrakash Surya 		 * done being written to the l2arc.
3257244781f1SPrakash Surya 		 */
3258244781f1SPrakash Surya 		if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
3259244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_evict_l2_skip);
3260244781f1SPrakash Surya 			return (bytes_evicted);
32613a5286a1SMatthew Ahrens 		}
3262244781f1SPrakash Surya 
3263244781f1SPrakash Surya 		ARCSTAT_BUMP(arcstat_deleted);
3264dcbf3bd6SGeorge Wilson 		bytes_evicted += HDR_GET_LSIZE(hdr);
3265244781f1SPrakash Surya 
3266244781f1SPrakash Surya 		DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
3267244781f1SPrakash Surya 
3268770499e1SDan Kimmel 		ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3269244781f1SPrakash Surya 		if (HDR_HAS_L2HDR(hdr)) {
3270244781f1SPrakash Surya 			/*
3271244781f1SPrakash Surya 			 * This buffer is cached on the 2nd Level ARC;
3272244781f1SPrakash Surya 			 * don't destroy the header.
3273244781f1SPrakash Surya 			 */
3274244781f1SPrakash Surya 			arc_change_state(arc_l2c_only, hdr, hash_lock);
32753a5286a1SMatthew Ahrens 			/*
3276244781f1SPrakash Surya 			 * dropping from L1+L2 cached to L2-only,
3277244781f1SPrakash Surya 			 * realloc to remove the L1 header.
32783a5286a1SMatthew Ahrens 			 */
3279244781f1SPrakash Surya 			hdr = arc_hdr_realloc(hdr, hdr_full_cache,
3280244781f1SPrakash Surya 			    hdr_l2only_cache);
3281244781f1SPrakash Surya 		} else {
3282244781f1SPrakash Surya 			arc_change_state(arc_anon, hdr, hash_lock);
3283244781f1SPrakash Surya 			arc_hdr_destroy(hdr);
32843a5286a1SMatthew Ahrens 		}
3285244781f1SPrakash Surya 		return (bytes_evicted);
32863a5286a1SMatthew Ahrens 	}
32873a5286a1SMatthew Ahrens 
3288244781f1SPrakash Surya 	ASSERT(state == arc_mru || state == arc_mfu);
3289244781f1SPrakash Surya 	evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
3290244781f1SPrakash Surya 
3291244781f1SPrakash Surya 	/* prefetch buffers have a minimum lifespan */
3292244781f1SPrakash Surya 	if (HDR_IO_IN_PROGRESS(hdr) ||
3293244781f1SPrakash Surya 	    ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
3294244781f1SPrakash Surya 	    ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
3295244781f1SPrakash Surya 	    arc_min_prefetch_lifespan)) {
3296244781f1SPrakash Surya 		ARCSTAT_BUMP(arcstat_evict_skip);
3297244781f1SPrakash Surya 		return (bytes_evicted);
3298244781f1SPrakash Surya 	}
3299244781f1SPrakash Surya 
3300244781f1SPrakash Surya 	ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
3301244781f1SPrakash Surya 	while (hdr->b_l1hdr.b_buf) {
3302244781f1SPrakash Surya 		arc_buf_t *buf = hdr->b_l1hdr.b_buf;
3303244781f1SPrakash Surya 		if (!mutex_tryenter(&buf->b_evict_lock)) {
3304244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_mutex_miss);
3305244781f1SPrakash Surya 			break;
330613506d1eSmaybee 		}
3307244781f1SPrakash Surya 		if (buf->b_data != NULL)
3308dcbf3bd6SGeorge Wilson 			bytes_evicted += HDR_GET_LSIZE(hdr);
3309dcbf3bd6SGeorge Wilson 		mutex_exit(&buf->b_evict_lock);
33105602294fSDan Kimmel 		arc_buf_destroy_impl(buf);
3311244781f1SPrakash Surya 	}
331269962b56SMatthew Ahrens 
3313244781f1SPrakash Surya 	if (HDR_HAS_L2HDR(hdr)) {
3314dcbf3bd6SGeorge Wilson 		ARCSTAT_INCR(arcstat_evict_l2_cached, HDR_GET_LSIZE(hdr));
3315244781f1SPrakash Surya 	} else {
3316dcbf3bd6SGeorge Wilson 		if (l2arc_write_eligible(hdr->b_spa, hdr)) {
3317dcbf3bd6SGeorge Wilson 			ARCSTAT_INCR(arcstat_evict_l2_eligible,
3318dcbf3bd6SGeorge Wilson 			    HDR_GET_LSIZE(hdr));
3319dcbf3bd6SGeorge Wilson 		} else {
3320dcbf3bd6SGeorge Wilson 			ARCSTAT_INCR(arcstat_evict_l2_ineligible,
3321dcbf3bd6SGeorge Wilson 			    HDR_GET_LSIZE(hdr));
3322dcbf3bd6SGeorge Wilson 		}
3323244781f1SPrakash Surya 	}
3324244781f1SPrakash Surya 
3325dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_bufcnt == 0) {
3326dcbf3bd6SGeorge Wilson 		arc_cksum_free(hdr);
3327dcbf3bd6SGeorge Wilson 
3328dcbf3bd6SGeorge Wilson 		bytes_evicted += arc_hdr_size(hdr);
3329dcbf3bd6SGeorge Wilson 
3330dcbf3bd6SGeorge Wilson 		/*
3331dcbf3bd6SGeorge Wilson 		 * If this hdr is being evicted and has a compressed
3332dcbf3bd6SGeorge Wilson 		 * buffer then we discard it here before we change states.
3333dcbf3bd6SGeorge Wilson 		 * This ensures that the accounting is updated correctly
3334770499e1SDan Kimmel 		 * in arc_free_data_impl().
3335dcbf3bd6SGeorge Wilson 		 */
3336770499e1SDan Kimmel 		arc_hdr_free_pabd(hdr);
3337dcbf3bd6SGeorge Wilson 
3338244781f1SPrakash Surya 		arc_change_state(evicted_state, hdr, hash_lock);
3339244781f1SPrakash Surya 		ASSERT(HDR_IN_HASH_TABLE(hdr));
3340dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
3341244781f1SPrakash Surya 		DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
3342244781f1SPrakash Surya 	}
3343244781f1SPrakash Surya 
3344244781f1SPrakash Surya 	return (bytes_evicted);
3345244781f1SPrakash Surya }
3346244781f1SPrakash Surya 
3347244781f1SPrakash Surya static uint64_t
3348244781f1SPrakash Surya arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
3349244781f1SPrakash Surya     uint64_t spa, int64_t bytes)
3350244781f1SPrakash Surya {
3351244781f1SPrakash Surya 	multilist_sublist_t *mls;
3352244781f1SPrakash Surya 	uint64_t bytes_evicted = 0;
3353244781f1SPrakash Surya 	arc_buf_hdr_t *hdr;
3354244781f1SPrakash Surya 	kmutex_t *hash_lock;
3355244781f1SPrakash Surya 	int evict_count = 0;
3356244781f1SPrakash Surya 
3357244781f1SPrakash Surya 	ASSERT3P(marker, !=, NULL);
3358244781f1SPrakash Surya 	IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3359244781f1SPrakash Surya 
3360244781f1SPrakash Surya 	mls = multilist_sublist_lock(ml, idx);
3361244781f1SPrakash Surya 
3362244781f1SPrakash Surya 	for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
3363244781f1SPrakash Surya 	    hdr = multilist_sublist_prev(mls, marker)) {
3364244781f1SPrakash Surya 		if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
3365244781f1SPrakash Surya 		    (evict_count >= zfs_arc_evict_batch_limit))
3366244781f1SPrakash Surya 			break;
336769962b56SMatthew Ahrens 
336869962b56SMatthew Ahrens 		/*
3369244781f1SPrakash Surya 		 * To keep our iteration location, move the marker
3370244781f1SPrakash Surya 		 * forward. Since we're not holding hdr's hash lock, we
3371244781f1SPrakash Surya 		 * must be very careful and not remove 'hdr' from the
3372244781f1SPrakash Surya 		 * sublist. Otherwise, other consumers might mistake the
3373244781f1SPrakash Surya 		 * 'hdr' as not being on a sublist when they call the
3374244781f1SPrakash Surya 		 * multilist_link_active() function (they all rely on
3375244781f1SPrakash Surya 		 * the hash lock protecting concurrent insertions and
3376244781f1SPrakash Surya 		 * removals). multilist_sublist_move_forward() was
3377244781f1SPrakash Surya 		 * specifically implemented to ensure this is the case
3378244781f1SPrakash Surya 		 * (only 'marker' will be removed and re-inserted).
3379244781f1SPrakash Surya 		 */
3380244781f1SPrakash Surya 		multilist_sublist_move_forward(mls, marker);
3381244781f1SPrakash Surya 
3382244781f1SPrakash Surya 		/*
3383244781f1SPrakash Surya 		 * The only case where the b_spa field should ever be
3384244781f1SPrakash Surya 		 * zero, is the marker headers inserted by
3385244781f1SPrakash Surya 		 * arc_evict_state(). It's possible for multiple threads
3386244781f1SPrakash Surya 		 * to be calling arc_evict_state() concurrently (e.g.
3387244781f1SPrakash Surya 		 * dsl_pool_close() and zio_inject_fault()), so we must
3388244781f1SPrakash Surya 		 * skip any markers we see from these other threads.
338969962b56SMatthew Ahrens 		 */
3390244781f1SPrakash Surya 		if (hdr->b_spa == 0)
3391244781f1SPrakash Surya 			continue;
3392244781f1SPrakash Surya 
3393244781f1SPrakash Surya 		/* we're only interested in evicting buffers of a certain spa */
3394244781f1SPrakash Surya 		if (spa != 0 && hdr->b_spa != spa) {
3395244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_evict_skip);
339669962b56SMatthew Ahrens 			continue;
339769962b56SMatthew Ahrens 		}
339869962b56SMatthew Ahrens 
33997adb730bSGeorge Wilson 		hash_lock = HDR_LOCK(hdr);
34005ea40c06SBrendan Gregg - Sun Microsystems 
3401244781f1SPrakash Surya 		/*
3402244781f1SPrakash Surya 		 * We aren't calling this function from any code path
3403244781f1SPrakash Surya 		 * that would already be holding a hash lock, so we're
3404244781f1SPrakash Surya 		 * asserting on this assumption to be defensive in case
3405244781f1SPrakash Surya 		 * this ever changes. Without this check, it would be
3406244781f1SPrakash Surya 		 * possible to incorrectly increment arcstat_mutex_miss
3407244781f1SPrakash Surya 		 * below (e.g. if the code changed such that we called
3408244781f1SPrakash Surya 		 * this function with a hash lock held).
3409244781f1SPrakash Surya 		 */
3410244781f1SPrakash Surya 		ASSERT(!MUTEX_HELD(hash_lock));
341144cb6abcSbmc 
3412244781f1SPrakash Surya 		if (mutex_tryenter(hash_lock)) {
3413244781f1SPrakash Surya 			uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
3414244781f1SPrakash Surya 			mutex_exit(hash_lock);
3415fa9e4066Sahrens 
3416244781f1SPrakash Surya 			bytes_evicted += evicted;
3417fa9e4066Sahrens 
3418244781f1SPrakash Surya 			/*
3419244781f1SPrakash Surya 			 * If evicted is zero, arc_evict_hdr() must have
3420244781f1SPrakash Surya 			 * decided to skip this header, don't increment
3421244781f1SPrakash Surya 			 * evict_count in this case.
3422244781f1SPrakash Surya 			 */
3423244781f1SPrakash Surya 			if (evicted != 0)
3424244781f1SPrakash Surya 				evict_count++;
342544cb6abcSbmc 
3426244781f1SPrakash Surya 			/*
3427244781f1SPrakash Surya 			 * If arc_size isn't overflowing, signal any
3428244781f1SPrakash Surya 			 * threads that might happen to be waiting.
3429244781f1SPrakash Surya 			 *
3430244781f1SPrakash Surya 			 * For each header evicted, we wake up a single
3431244781f1SPrakash Surya 			 * thread. If we used cv_broadcast, we could
3432244781f1SPrakash Surya 			 * wake up "too many" threads causing arc_size
3433244781f1SPrakash Surya 			 * to significantly overflow arc_c; since
3434770499e1SDan Kimmel 			 * arc_get_data_impl() doesn't check for overflow
3435244781f1SPrakash Surya 			 * when it's woken up (it doesn't because it's
3436244781f1SPrakash Surya 			 * possible for the ARC to be overflowing while
3437244781f1SPrakash Surya 			 * full of un-evictable buffers, and the
3438244781f1SPrakash Surya 			 * function should proceed in this case).
3439244781f1SPrakash Surya 			 *
3440244781f1SPrakash Surya 			 * If threads are left sleeping, due to not
3441de753e34SBrad Lewis 			 * using cv_broadcast here, they will be woken
3442de753e34SBrad Lewis 			 * up via cv_broadcast in arc_adjust_cb() just
3443de753e34SBrad Lewis 			 * before arc_adjust_zthr sleeps.
3444244781f1SPrakash Surya 			 */
3445de753e34SBrad Lewis 			mutex_enter(&arc_adjust_lock);
3446244781f1SPrakash Surya 			if (!arc_is_overflowing())
3447de753e34SBrad Lewis 				cv_signal(&arc_adjust_waiters_cv);
3448de753e34SBrad Lewis 			mutex_exit(&arc_adjust_lock);
3449244781f1SPrakash Surya 		} else {
3450244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_mutex_miss);
3451244781f1SPrakash Surya 		}
3452244781f1SPrakash Surya 	}
3453f4d2e9e6Smaybee 
3454244781f1SPrakash Surya 	multilist_sublist_unlock(mls);
345544cb6abcSbmc 
3456244781f1SPrakash Surya 	return (bytes_evicted);
3457fa9e4066Sahrens }
3458fa9e4066Sahrens 
3459fa9e4066Sahrens /*
3460244781f1SPrakash Surya  * Evict buffers from the given arc state, until we've removed the
3461244781f1SPrakash Surya  * specified number of bytes. Move the removed buffers to the
3462244781f1SPrakash Surya  * appropriate evict state.
3463244781f1SPrakash Surya  *
3464244781f1SPrakash Surya  * This function makes a "best effort". It skips over any buffers
3465244781f1SPrakash Surya  * it can't get a hash_lock on, and so, may not catch all candidates.
3466244781f1SPrakash Surya  * It may also return without evicting as much space as requested.
3467244781f1SPrakash Surya  *
3468244781f1SPrakash Surya  * If bytes is specified using the special value ARC_EVICT_ALL, this
3469244781f1SPrakash Surya  * will evict all available (i.e. unlocked and evictable) buffers from
3470244781f1SPrakash Surya  * the given arc state; which is used by arc_flush().
3471fa9e4066Sahrens  */
3472244781f1SPrakash Surya static uint64_t
3473244781f1SPrakash Surya arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
3474244781f1SPrakash Surya     arc_buf_contents_t type)
3475fa9e4066Sahrens {
3476244781f1SPrakash Surya 	uint64_t total_evicted = 0;
347794c2d0ebSMatthew Ahrens 	multilist_t *ml = state->arcs_list[type];
3478244781f1SPrakash Surya 	int num_sublists;
3479244781f1SPrakash Surya 	arc_buf_hdr_t **markers;
3480fa9e4066Sahrens 
3481244781f1SPrakash Surya 	IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3482b802aa8cSSanjeev Bagewadi 
3483244781f1SPrakash Surya 	num_sublists = multilist_get_num_sublists(ml);
3484b802aa8cSSanjeev Bagewadi 
3485244781f1SPrakash Surya 	/*
3486244781f1SPrakash Surya 	 * If we've tried to evict from each sublist, made some
3487244781f1SPrakash Surya 	 * progress, but still have not hit the target number of bytes
3488244781f1SPrakash Surya 	 * to evict, we want to keep trying. The markers allow us to
3489244781f1SPrakash Surya 	 * pick up where we left off for each individual sublist, rather
3490244781f1SPrakash Surya 	 * than starting from the tail each time.
3491244781f1SPrakash Surya 	 */
3492244781f1SPrakash Surya 	markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
3493244781f1SPrakash Surya 	for (int i = 0; i < num_sublists; i++) {
3494244781f1SPrakash Surya 		markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
349569962b56SMatthew Ahrens 
349669962b56SMatthew Ahrens 		/*
3497244781f1SPrakash Surya 		 * A b_spa of 0 is used to indicate that this header is
3498244781f1SPrakash Surya 		 * a marker. This fact is used in arc_adjust_type() and
3499244781f1SPrakash Surya 		 * arc_evict_state_impl().
350069962b56SMatthew Ahrens 		 */
3501244781f1SPrakash Surya 		markers[i]->b_spa = 0;
3502fa94a07fSbrendan 
3503244781f1SPrakash Surya 		multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3504244781f1SPrakash Surya 		multilist_sublist_insert_tail(mls, markers[i]);
3505244781f1SPrakash Surya 		multilist_sublist_unlock(mls);
3506244781f1SPrakash Surya 	}
3507fa94a07fSbrendan 
3508244781f1SPrakash Surya 	/*
3509244781f1SPrakash Surya 	 * While we haven't hit our target number of bytes to evict, or
3510244781f1SPrakash Surya 	 * we're evicting all available buffers.
3511244781f1SPrakash Surya 	 */
3512244781f1SPrakash Surya 	while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
3513244781f1SPrakash Surya 		/*
3514244781f1SPrakash Surya 		 * Start eviction using a randomly selected sublist,
3515244781f1SPrakash Surya 		 * this is to try and evenly balance eviction across all
3516244781f1SPrakash Surya 		 * sublists. Always starting at the same sublist
3517244781f1SPrakash Surya 		 * (e.g. index 0) would cause evictions to favor certain
3518244781f1SPrakash Surya 		 * sublists over others.
3519244781f1SPrakash Surya 		 */
3520244781f1SPrakash Surya 		int sublist_idx = multilist_get_random_index(ml);
3521244781f1SPrakash Surya 		uint64_t scan_evicted = 0;
3522244781f1SPrakash Surya 
3523244781f1SPrakash Surya 		for (int i = 0; i < num_sublists; i++) {
3524244781f1SPrakash Surya 			uint64_t bytes_remaining;
3525244781f1SPrakash Surya 			uint64_t bytes_evicted;
3526244781f1SPrakash Surya 
3527244781f1SPrakash Surya 			if (bytes == ARC_EVICT_ALL)
3528244781f1SPrakash Surya 				bytes_remaining = ARC_EVICT_ALL;
3529244781f1SPrakash Surya 			else if (total_evicted < bytes)
3530244781f1SPrakash Surya 				bytes_remaining = bytes - total_evicted;
3531244781f1SPrakash Surya 			else
3532fa9e4066Sahrens 				break;
3533244781f1SPrakash Surya 
3534244781f1SPrakash Surya 			bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
3535244781f1SPrakash Surya 			    markers[sublist_idx], spa, bytes_remaining);
3536244781f1SPrakash Surya 
3537244781f1SPrakash Surya 			scan_evicted += bytes_evicted;
3538244781f1SPrakash Surya 			total_evicted += bytes_evicted;
3539244781f1SPrakash Surya 
3540244781f1SPrakash Surya 			/* we've reached the end, wrap to the beginning */
3541244781f1SPrakash Surya 			if (++sublist_idx >= num_sublists)
3542244781f1SPrakash Surya 				sublist_idx = 0;
3543244781f1SPrakash Surya 		}
3544244781f1SPrakash Surya 
3545244781f1SPrakash Surya 		/*
3546244781f1SPrakash Surya 		 * If we didn't evict anything during this scan, we have
3547244781f1SPrakash Surya 		 * no reason to believe we'll evict more during another
3548244781f1SPrakash Surya 		 * scan, so break the loop.
3549244781f1SPrakash Surya 		 */
3550244781f1SPrakash Surya 		if (scan_evicted == 0) {
3551244781f1SPrakash Surya 			/* This isn't possible, let's make that obvious */
3552244781f1SPrakash Surya 			ASSERT3S(bytes, !=, 0);
3553244781f1SPrakash Surya 
3554b802aa8cSSanjeev Bagewadi 			/*
3555244781f1SPrakash Surya 			 * When bytes is ARC_EVICT_ALL, the only way to
3556244781f1SPrakash Surya 			 * break the loop is when scan_evicted is zero.
3557244781f1SPrakash Surya 			 * In that case, we actually have evicted enough,
3558244781f1SPrakash Surya 			 * so we don't want to increment the kstat.
3559b802aa8cSSanjeev Bagewadi 			 */
3560244781f1SPrakash Surya 			if (bytes != ARC_EVICT_ALL) {
3561244781f1SPrakash Surya 				ASSERT3S(total_evicted, <, bytes);
3562244781f1SPrakash Surya 				ARCSTAT_BUMP(arcstat_evict_not_enough);
3563244781f1SPrakash Surya 			}
3564244781f1SPrakash Surya 
3565244781f1SPrakash Surya 			break;
356669962b56SMatthew Ahrens 		}
3567244781f1SPrakash Surya 	}
3568244781f1SPrakash Surya 
3569244781f1SPrakash Surya 	for (int i = 0; i < num_sublists; i++) {
3570244781f1SPrakash Surya 		multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3571244781f1SPrakash Surya 		multilist_sublist_remove(mls, markers[i]);
3572244781f1SPrakash Surya 		multilist_sublist_unlock(mls);
357369962b56SMatthew Ahrens 
3574244781f1SPrakash Surya 		kmem_cache_free(hdr_full_cache, markers[i]);
3575fa9e4066Sahrens 	}
3576244781f1SPrakash Surya 	kmem_free(markers, sizeof (*markers) * num_sublists);
3577fa9e4066Sahrens 
3578244781f1SPrakash Surya 	return (total_evicted);
3579244781f1SPrakash Surya }
3580244781f1SPrakash Surya 
3581244781f1SPrakash Surya /*
3582244781f1SPrakash Surya  * Flush all "evictable" data of the given type from the arc state
3583244781f1SPrakash Surya  * specified. This will not evict any "active" buffers (i.e. referenced).
3584244781f1SPrakash Surya  *
3585dcbf3bd6SGeorge Wilson  * When 'retry' is set to B_FALSE, the function will make a single pass
3586244781f1SPrakash Surya  * over the state and evict any buffers that it can. Since it doesn't
3587244781f1SPrakash Surya  * continually retry the eviction, it might end up leaving some buffers
3588244781f1SPrakash Surya  * in the ARC due to lock misses.
3589244781f1SPrakash Surya  *
3590dcbf3bd6SGeorge Wilson  * When 'retry' is set to B_TRUE, the function will continually retry the
3591244781f1SPrakash Surya  * eviction until *all* evictable buffers have been removed from the
3592244781f1SPrakash Surya  * state. As a result, if concurrent insertions into the state are
3593244781f1SPrakash Surya  * allowed (e.g. if the ARC isn't shutting down), this function might
3594244781f1SPrakash Surya  * wind up in an infinite loop, continually trying to evict buffers.
3595244781f1SPrakash Surya  */
3596244781f1SPrakash Surya static uint64_t
3597244781f1SPrakash Surya arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
3598244781f1SPrakash Surya     boolean_t retry)
3599244781f1SPrakash Surya {
3600244781f1SPrakash Surya 	uint64_t evicted = 0;
3601244781f1SPrakash Surya 
3602dcbf3bd6SGeorge Wilson 	while (refcount_count(&state->arcs_esize[type]) != 0) {
3603244781f1SPrakash Surya 		evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
3604244781f1SPrakash Surya 
3605244781f1SPrakash Surya 		if (!retry)
3606244781f1SPrakash Surya 			break;
36070e8c6158Smaybee 	}
36080e8c6158Smaybee 
3609244781f1SPrakash Surya 	return (evicted);
3610244781f1SPrakash Surya }
3611244781f1SPrakash Surya 
3612244781f1SPrakash Surya /*
3613244781f1SPrakash Surya  * Evict the specified number of bytes from the state specified,
3614244781f1SPrakash Surya  * restricting eviction to the spa and type given. This function
3615244781f1SPrakash Surya  * prevents us from trying to evict more from a state's list than
3616244781f1SPrakash Surya  * is "evictable", and to skip evicting altogether when passed a
3617244781f1SPrakash Surya  * negative value for "bytes". In contrast, arc_evict_state() will
3618244781f1SPrakash Surya  * evict everything it can, when passed a negative value for "bytes".
3619244781f1SPrakash Surya  */
3620244781f1SPrakash Surya static uint64_t
3621244781f1SPrakash Surya arc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
3622244781f1SPrakash Surya     arc_buf_contents_t type)
3623244781f1SPrakash Surya {
3624244781f1SPrakash Surya 	int64_t delta;
3625244781f1SPrakash Surya 
3626dcbf3bd6SGeorge Wilson 	if (bytes > 0 && refcount_count(&state->arcs_esize[type]) > 0) {
3627dcbf3bd6SGeorge Wilson 		delta = MIN(refcount_count(&state->arcs_esize[type]), bytes);
3628244781f1SPrakash Surya 		return (arc_evict_state(state, spa, delta, type));
3629fa9e4066Sahrens 	}
3630fa9e4066Sahrens 
3631244781f1SPrakash Surya 	return (0);
3632fa9e4066Sahrens }
3633fa9e4066Sahrens 
3634244781f1SPrakash Surya /*
3635244781f1SPrakash Surya  * Evict metadata buffers from the cache, such that arc_meta_used is
3636244781f1SPrakash Surya  * capped by the arc_meta_limit tunable.
3637244781f1SPrakash Surya  */
3638244781f1SPrakash Surya static uint64_t
36393a2d8a1bSPaul Dagnelie arc_adjust_meta(uint64_t meta_used)
3640244781f1SPrakash Surya {
3641244781f1SPrakash Surya 	uint64_t total_evicted = 0;
3642244781f1SPrakash Surya 	int64_t target;
3643244781f1SPrakash Surya 
3644244781f1SPrakash Surya 	/*
3645244781f1SPrakash Surya 	 * If we're over the meta limit, we want to evict enough
3646244781f1SPrakash Surya 	 * metadata to get back under the meta limit. We don't want to
3647244781f1SPrakash Surya 	 * evict so much that we drop the MRU below arc_p, though. If
3648244781f1SPrakash Surya 	 * we're over the meta limit more than we're over arc_p, we
3649244781f1SPrakash Surya 	 * evict some from the MRU here, and some from the MFU below.
3650244781f1SPrakash Surya 	 */
36513a2d8a1bSPaul Dagnelie 	target = MIN((int64_t)(meta_used - arc_meta_limit),
36522fd872a7SPrakash Surya 	    (int64_t)(refcount_count(&arc_anon->arcs_size) +
36532fd872a7SPrakash Surya 	    refcount_count(&arc_mru->arcs_size) - arc_p));
3654244781f1SPrakash Surya 
3655244781f1SPrakash Surya 	total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3656244781f1SPrakash Surya 
3657244781f1SPrakash Surya 	/*
3658244781f1SPrakash Surya 	 * Similar to the above, we want to evict enough bytes to get us
3659244781f1SPrakash Surya 	 * below the meta limit, but not so much as to drop us below the
36605602294fSDan Kimmel 	 * space allotted to the MFU (which is defined as arc_c - arc_p).
3661244781f1SPrakash Surya 	 */
36623a2d8a1bSPaul Dagnelie 	target = MIN((int64_t)(meta_used - arc_meta_limit),
36633a2d8a1bSPaul Dagnelie 	    (int64_t)(refcount_count(&arc_mfu->arcs_size) -
36643a2d8a1bSPaul Dagnelie 	    (arc_c - arc_p)));
3665244781f1SPrakash Surya 
3666244781f1SPrakash Surya 	total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3667244781f1SPrakash Surya 
3668244781f1SPrakash Surya 	return (total_evicted);
3669244781f1SPrakash Surya }
3670244781f1SPrakash Surya 
3671244781f1SPrakash Surya /*
3672244781f1SPrakash Surya  * Return the type of the oldest buffer in the given arc state
3673244781f1SPrakash Surya  *
3674244781f1SPrakash Surya  * This function will select a random sublist of type ARC_BUFC_DATA and
3675244781f1SPrakash Surya  * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
3676244781f1SPrakash Surya  * is compared, and the type which contains the "older" buffer will be
3677244781f1SPrakash Surya  * returned.
3678244781f1SPrakash Surya  */
3679244781f1SPrakash Surya static arc_buf_contents_t
3680244781f1SPrakash Surya arc_adjust_type(arc_state_t *state)
3681244781f1SPrakash Surya {
368294c2d0ebSMatthew Ahrens 	multilist_t *data_ml = state->arcs_list[ARC_BUFC_DATA];
368394c2d0ebSMatthew Ahrens 	multilist_t *meta_ml = state->arcs_list[ARC_BUFC_METADATA];
3684244781f1SPrakash Surya 	int data_idx = multilist_get_random_index(data_ml);
3685244781f1SPrakash Surya 	int meta_idx = multilist_get_random_index(meta_ml);
3686244781f1SPrakash Surya 	multilist_sublist_t *data_mls;
3687244781f1SPrakash Surya 	multilist_sublist_t *meta_mls;
3688244781f1SPrakash Surya 	arc_buf_contents_t type;
3689244781f1SPrakash Surya 	arc_buf_hdr_t *data_hdr;
3690244781f1SPrakash Surya 	arc_buf_hdr_t *meta_hdr;
3691244781f1SPrakash Surya 
3692244781f1SPrakash Surya 	/*
3693244781f1SPrakash Surya 	 * We keep the sublist lock until we're finished, to prevent
3694244781f1SPrakash Surya 	 * the headers from being destroyed via arc_evict_state().
3695244781f1SPrakash Surya 	 */
3696244781f1SPrakash Surya 	data_mls = multilist_sublist_lock(data_ml, data_idx);
3697244781f1SPrakash Surya 	meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
3698244781f1SPrakash Surya 
3699244781f1SPrakash Surya 	/*
3700244781f1SPrakash Surya 	 * These two loops are to ensure we skip any markers that
3701244781f1SPrakash Surya 	 * might be at the tail of the lists due to arc_evict_state().
3702244781f1SPrakash Surya 	 */
3703244781f1SPrakash Surya 
3704244781f1SPrakash Surya 	for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
3705244781f1SPrakash Surya 	    data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
3706244781f1SPrakash Surya 		if (data_hdr->b_spa != 0)
3707244781f1SPrakash Surya 			break;
3708244781f1SPrakash Surya 	}
3709244781f1SPrakash Surya 
3710244781f1SPrakash Surya 	for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
3711244781f1SPrakash Surya 	    meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
3712244781f1SPrakash Surya 		if (meta_hdr->b_spa != 0)
3713244781f1SPrakash Surya 			break;
3714244781f1SPrakash Surya 	}
3715244781f1SPrakash Surya 
3716244781f1SPrakash Surya 	if (data_hdr == NULL && meta_hdr == NULL) {
3717244781f1SPrakash Surya 		type = ARC_BUFC_DATA;
3718244781f1SPrakash Surya 	} else if (data_hdr == NULL) {
3719244781f1SPrakash Surya 		ASSERT3P(meta_hdr, !=, NULL);
3720244781f1SPrakash Surya 		type = ARC_BUFC_METADATA;
3721244781f1SPrakash Surya 	} else if (meta_hdr == NULL) {
3722244781f1SPrakash Surya 		ASSERT3P(data_hdr, !=, NULL);
3723244781f1SPrakash Surya 		type = ARC_BUFC_DATA;
3724244781f1SPrakash Surya 	} else {
3725244781f1SPrakash Surya 		ASSERT3P(data_hdr, !=, NULL);
3726244781f1SPrakash Surya 		ASSERT3P(meta_hdr, !=, NULL);
3727244781f1SPrakash Surya 
3728244781f1SPrakash Surya 		/* The headers can't be on the sublist without an L1 header */
3729244781f1SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(data_hdr));
3730244781f1SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(meta_hdr));
3731244781f1SPrakash Surya 
3732244781f1SPrakash Surya 		if (data_hdr->b_l1hdr.b_arc_access <
3733244781f1SPrakash Surya 		    meta_hdr->b_l1hdr.b_arc_access) {
3734244781f1SPrakash Surya 			type = ARC_BUFC_DATA;
3735244781f1SPrakash Surya 		} else {
3736244781f1SPrakash Surya 			type = ARC_BUFC_METADATA;
3737244781f1SPrakash Surya 		}
3738244781f1SPrakash Surya 	}
3739244781f1SPrakash Surya 
3740244781f1SPrakash Surya 	multilist_sublist_unlock(meta_mls);
3741244781f1SPrakash Surya 	multilist_sublist_unlock(data_mls);
3742244781f1SPrakash Surya 
3743244781f1SPrakash Surya 	return (type);
3744244781f1SPrakash Surya }
3745244781f1SPrakash Surya 
3746244781f1SPrakash Surya /*
3747244781f1SPrakash Surya  * Evict buffers from the cache, such that arc_size is capped by arc_c.
3748244781f1SPrakash Surya  */
3749244781f1SPrakash Surya static uint64_t
3750fa9e4066Sahrens arc_adjust(void)
3751fa9e4066Sahrens {
3752244781f1SPrakash Surya 	uint64_t total_evicted = 0;
3753244781f1SPrakash Surya 	uint64_t bytes;
3754244781f1SPrakash Surya 	int64_t target;
37553a2d8a1bSPaul Dagnelie 	uint64_t asize = aggsum_value(&arc_size);
37563a2d8a1bSPaul Dagnelie 	uint64_t ameta = aggsum_value(&arc_meta_used);
3757fa9e4066Sahrens 
37585a98e54bSBrendan Gregg - Sun Microsystems 	/*
3759244781f1SPrakash Surya 	 * If we're over arc_meta_limit, we want to correct that before
3760244781f1SPrakash Surya 	 * potentially evicting data buffers below.
37615a98e54bSBrendan Gregg - Sun Microsystems 	 */
37623a2d8a1bSPaul Dagnelie 	total_evicted += arc_adjust_meta(ameta);
37635a98e54bSBrendan Gregg - Sun Microsystems 
3764244781f1SPrakash Surya 	/*
3765244781f1SPrakash Surya 	 * Adjust MRU size
3766244781f1SPrakash Surya 	 *
3767244781f1SPrakash Surya 	 * If we're over the target cache size, we want to evict enough
3768244781f1SPrakash Surya 	 * from the list to get back to our target size. We don't want
3769244781f1SPrakash Surya 	 * to evict too much from the MRU, such that it drops below
3770244781f1SPrakash Surya 	 * arc_p. So, if we're over our target cache size more than
3771244781f1SPrakash Surya 	 * the MRU is over arc_p, we'll evict enough to get back to
3772244781f1SPrakash Surya 	 * arc_p here, and then evict more from the MFU below.
3773244781f1SPrakash Surya 	 */
37743a2d8a1bSPaul Dagnelie 	target = MIN((int64_t)(asize - arc_c),
37752fd872a7SPrakash Surya 	    (int64_t)(refcount_count(&arc_anon->arcs_size) +
37763a2d8a1bSPaul Dagnelie 	    refcount_count(&arc_mru->arcs_size) + ameta - arc_p));
3777fa9e4066Sahrens 
3778244781f1SPrakash Surya 	/*
3779244781f1SPrakash Surya 	 * If we're below arc_meta_min, always prefer to evict data.
3780244781f1SPrakash Surya 	 * Otherwise, try to satisfy the requested number of bytes to
3781244781f1SPrakash Surya 	 * evict from the type which contains older buffers; in an
3782244781f1SPrakash Surya 	 * effort to keep newer buffers in the cache regardless of their
3783244781f1SPrakash Surya 	 * type. If we cannot satisfy the number of bytes from this
3784244781f1SPrakash Surya 	 * type, spill over into the next type.
3785244781f1SPrakash Surya 	 */
3786244781f1SPrakash Surya 	if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
37873a2d8a1bSPaul Dagnelie 	    ameta > arc_meta_min) {
3788244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3789244781f1SPrakash Surya 		total_evicted += bytes;
37900e8c6158Smaybee 
3791244781f1SPrakash Surya 		/*
3792244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
3793244781f1SPrakash Surya 		 * metadata, we try to get the rest from data.
3794244781f1SPrakash Surya 		 */
3795244781f1SPrakash Surya 		target -= bytes;
3796244781f1SPrakash Surya 
3797244781f1SPrakash Surya 		total_evicted +=
3798244781f1SPrakash Surya 		    arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3799244781f1SPrakash Surya 	} else {
3800244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3801244781f1SPrakash Surya 		total_evicted += bytes;
3802244781f1SPrakash Surya 
3803244781f1SPrakash Surya 		/*
3804244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
3805244781f1SPrakash Surya 		 * data, we try to get the rest from metadata.
3806244781f1SPrakash Surya 		 */
3807244781f1SPrakash Surya 		target -= bytes;
3808244781f1SPrakash Surya 
3809244781f1SPrakash Surya 		total_evicted +=
3810244781f1SPrakash Surya 		    arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3811fa9e4066Sahrens 	}
3812fa9e4066Sahrens 
38135a98e54bSBrendan Gregg - Sun Microsystems 	/*
38145a98e54bSBrendan Gregg - Sun Microsystems 	 * Adjust MFU size
3815244781f1SPrakash Surya 	 *
3816244781f1SPrakash Surya 	 * Now that we've tried to evict enough from the MRU to get its
3817244781f1SPrakash Surya 	 * size back to arc_p, if we're still above the target cache
3818244781f1SPrakash Surya 	 * size, we evict the rest from the MFU.
38195a98e54bSBrendan Gregg - Sun Microsystems 	 */
38203a2d8a1bSPaul Dagnelie 	target = asize - arc_c;
3821fa9e4066Sahrens 
382231c46cf2SAlek Pinchuk 	if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
38233a2d8a1bSPaul Dagnelie 	    ameta > arc_meta_min) {
3824244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3825244781f1SPrakash Surya 		total_evicted += bytes;
38265a98e54bSBrendan Gregg - Sun Microsystems 
3827244781f1SPrakash Surya 		/*
3828244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
3829244781f1SPrakash Surya 		 * metadata, we try to get the rest from data.
3830244781f1SPrakash Surya 		 */
3831244781f1SPrakash Surya 		target -= bytes;
3832244781f1SPrakash Surya 
3833244781f1SPrakash Surya 		total_evicted +=
3834244781f1SPrakash Surya 		    arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3835244781f1SPrakash Surya 	} else {
3836244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3837244781f1SPrakash Surya 		total_evicted += bytes;
3838244781f1SPrakash Surya 
3839244781f1SPrakash Surya 		/*
3840244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
3841244781f1SPrakash Surya 		 * data, we try to get the rest from data.
3842244781f1SPrakash Surya 		 */
3843244781f1SPrakash Surya 		target -= bytes;
3844fa9e4066Sahrens 
3845244781f1SPrakash Surya 		total_evicted +=
3846244781f1SPrakash Surya 		    arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
38475a98e54bSBrendan Gregg - Sun Microsystems 	}
3848fa9e4066Sahrens 
38495a98e54bSBrendan Gregg - Sun Microsystems 	/*
38505a98e54bSBrendan Gregg - Sun Microsystems 	 * Adjust ghost lists
3851244781f1SPrakash Surya 	 *
3852244781f1SPrakash Surya 	 * In addition to the above, the ARC also defines target values
3853244781f1SPrakash Surya 	 * for the ghost lists. The sum of the mru list and mru ghost
3854244781f1SPrakash Surya 	 * list should never exceed the target size of the cache, and
3855244781f1SPrakash Surya 	 * the sum of the mru list, mfu list, mru ghost list, and mfu
3856244781f1SPrakash Surya 	 * ghost list should never exceed twice the target size of the
3857244781f1SPrakash Surya 	 * cache. The following logic enforces these limits on the ghost
3858244781f1SPrakash Surya 	 * caches, and evicts from them as needed.
38595a98e54bSBrendan Gregg - Sun Microsystems 	 */
38602fd872a7SPrakash Surya 	target = refcount_count(&arc_mru->arcs_size) +
38612fd872a7SPrakash Surya 	    refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
3862fa9e4066Sahrens 
3863244781f1SPrakash Surya 	bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
3864244781f1SPrakash Surya 	total_evicted += bytes;
3865fa9e4066Sahrens 
3866244781f1SPrakash Surya 	target -= bytes;
38670e8c6158Smaybee 
3868244781f1SPrakash Surya 	total_evicted +=
3869244781f1SPrakash Surya 	    arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
38705a98e54bSBrendan Gregg - Sun Microsystems 
3871244781f1SPrakash Surya 	/*
3872244781f1SPrakash Surya 	 * We assume the sum of the mru list and mfu list is less than
3873244781f1SPrakash Surya 	 * or equal to arc_c (we enforced this above), which means we
3874244781f1SPrakash Surya 	 * can use the simpler of the two equations below:
3875244781f1SPrakash Surya 	 *
3876244781f1SPrakash Surya 	 *	mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
3877244781f1SPrakash Surya 	 *		    mru ghost + mfu ghost <= arc_c
3878244781f1SPrakash Surya 	 */
38792fd872a7SPrakash Surya 	target = refcount_count(&arc_mru_ghost->arcs_size) +
38802fd872a7SPrakash Surya 	    refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
3881244781f1SPrakash Surya 
3882244781f1SPrakash Surya 	bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
3883244781f1SPrakash Surya 	total_evicted += bytes;
3884244781f1SPrakash Surya 
3885244781f1SPrakash Surya 	target -= bytes;
3886244781f1SPrakash Surya 
3887244781f1SPrakash Surya 	total_evicted +=
3888244781f1SPrakash Surya 	    arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
3889244781f1SPrakash Surya 
3890244781f1SPrakash Surya 	return (total_evicted);
3891fa9e4066Sahrens }
3892fa9e4066Sahrens 
3893fa9e4066Sahrens void
3894244781f1SPrakash Surya arc_flush(spa_t *spa, boolean_t retry)
3895fa9e4066Sahrens {
3896ac05c741SMark Maybee 	uint64_t guid = 0;
3897ac05c741SMark Maybee 
3898244781f1SPrakash Surya 	/*
3899dcbf3bd6SGeorge Wilson 	 * If retry is B_TRUE, a spa must not be specified since we have
3900244781f1SPrakash Surya 	 * no good way to determine if all of a spa's buffers have been
3901244781f1SPrakash Surya 	 * evicted from an arc state.
3902244781f1SPrakash Surya 	 */
3903244781f1SPrakash Surya 	ASSERT(!retry || spa == 0);
3904244781f1SPrakash Surya 
390589c86e32SChris Williamson 	if (spa != NULL)
3906e9103aaeSGarrett D'Amore 		guid = spa_load_guid(spa);
3907ac05c741SMark Maybee 
3908244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
3909244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
3910244781f1SPrakash Surya 
3911244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
3912244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
3913874395d5Smaybee 
3914244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
3915244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
3916244781f1SPrakash Surya 
3917244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
3918244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
3919fa9e4066Sahrens }
3920fa9e4066Sahrens 
3921de753e34SBrad Lewis static void
3922de753e34SBrad Lewis arc_reduce_target_size(int64_t to_free)
3923fa9e4066Sahrens {
39243a2d8a1bSPaul Dagnelie 	uint64_t asize = aggsum_value(&arc_size);
392544cb6abcSbmc 	if (arc_c > arc_c_min) {
3926fa9e4066Sahrens 
392744cb6abcSbmc 		if (arc_c > arc_c_min + to_free)
392844cb6abcSbmc 			atomic_add_64(&arc_c, -to_free);
392949e3519aSmaybee 		else
393044cb6abcSbmc 			arc_c = arc_c_min;
393144cb6abcSbmc 
393244cb6abcSbmc 		atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
39333a2d8a1bSPaul Dagnelie 		if (asize < arc_c)
39343a2d8a1bSPaul Dagnelie 			arc_c = MAX(asize, arc_c_min);
393544cb6abcSbmc 		if (arc_p > arc_c)
393644cb6abcSbmc 			arc_p = (arc_c >> 1);
393744cb6abcSbmc 		ASSERT(arc_c >= arc_c_min);
393844cb6abcSbmc 		ASSERT((int64_t)arc_p >= 0);
393949e3519aSmaybee 	}
3940fa9e4066Sahrens 
3941de753e34SBrad Lewis 	if (asize > arc_c) {
3942de753e34SBrad Lewis 		/* See comment in arc_adjust_cb_check() on why lock+flag */
3943de753e34SBrad Lewis 		mutex_enter(&arc_adjust_lock);
3944de753e34SBrad Lewis 		arc_adjust_needed = B_TRUE;
3945de753e34SBrad Lewis 		mutex_exit(&arc_adjust_lock);
3946de753e34SBrad Lewis 		zthr_wakeup(arc_adjust_zthr);
3947de753e34SBrad Lewis 	}
3948fa9e4066Sahrens }
3949fa9e4066Sahrens 
39502ec99e3eSMatthew Ahrens typedef enum free_memory_reason_t {
39512ec99e3eSMatthew Ahrens 	FMR_UNKNOWN,
39522ec99e3eSMatthew Ahrens 	FMR_NEEDFREE,
39532ec99e3eSMatthew Ahrens 	FMR_LOTSFREE,
39542ec99e3eSMatthew Ahrens 	FMR_SWAPFS_MINFREE,
39552ec99e3eSMatthew Ahrens 	FMR_PAGES_PP_MAXIMUM,
39562ec99e3eSMatthew Ahrens 	FMR_HEAP_ARENA,
39572ec99e3eSMatthew Ahrens 	FMR_ZIO_ARENA,
39582ec99e3eSMatthew Ahrens } free_memory_reason_t;
39592ec99e3eSMatthew Ahrens 
39602ec99e3eSMatthew Ahrens int64_t last_free_memory;
39612ec99e3eSMatthew Ahrens free_memory_reason_t last_free_reason;
39622ec99e3eSMatthew Ahrens 
396394dd93aeSGeorge Wilson /*
39642ec99e3eSMatthew Ahrens  * Additional reserve of pages for pp_reserve.
396594dd93aeSGeorge Wilson  */
39662ec99e3eSMatthew Ahrens int64_t arc_pages_pp_reserve = 64;
3967fa9e4066Sahrens 
39682ec99e3eSMatthew Ahrens /*
39692ec99e3eSMatthew Ahrens  * Additional reserve of pages for swapfs.
39702ec99e3eSMatthew Ahrens  */
39712ec99e3eSMatthew Ahrens int64_t arc_swapfs_reserve = 64;
39723cff2f43Sstans 
39732ec99e3eSMatthew Ahrens /*
39742ec99e3eSMatthew Ahrens  * Return the amount of memory that can be consumed before reclaim will be
39752ec99e3eSMatthew Ahrens  * needed.  Positive if there is sufficient free memory, negative indicates
39762ec99e3eSMatthew Ahrens  * the amount of memory that needs to be freed up.
39772ec99e3eSMatthew Ahrens  */
39782ec99e3eSMatthew Ahrens static int64_t
39792ec99e3eSMatthew Ahrens arc_available_memory(void)
39802ec99e3eSMatthew Ahrens {
39812ec99e3eSMatthew Ahrens 	int64_t lowest = INT64_MAX;
39822ec99e3eSMatthew Ahrens 	int64_t n;
39832ec99e3eSMatthew Ahrens 	free_memory_reason_t r = FMR_UNKNOWN;
39843cff2f43Sstans 
39852ec99e3eSMatthew Ahrens #ifdef _KERNEL
39862ec99e3eSMatthew Ahrens 	if (needfree > 0) {
39872ec99e3eSMatthew Ahrens 		n = PAGESIZE * (-needfree);
39882ec99e3eSMatthew Ahrens 		if (n < lowest) {
39892ec99e3eSMatthew Ahrens 			lowest = n;
39902ec99e3eSMatthew Ahrens 			r = FMR_NEEDFREE;
39912ec99e3eSMatthew Ahrens 		}
39922ec99e3eSMatthew Ahrens 	}
3993fa9e4066Sahrens 
3994fa9e4066Sahrens 	/*
3995fa9e4066Sahrens 	 * check that we're out of range of the pageout scanner.  It starts to
3996fa9e4066Sahrens 	 * schedule paging if freemem is less than lotsfree and needfree.
3997fa9e4066Sahrens 	 * lotsfree is the high-water mark for pageout, and needfree is the
3998fa9e4066Sahrens 	 * number of needed free pages.  We add extra pages here to make sure
3999fa9e4066Sahrens 	 * the scanner doesn't start up while we're freeing memory.
4000fa9e4066Sahrens 	 */
40012ec99e3eSMatthew Ahrens 	n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
40022ec99e3eSMatthew Ahrens 	if (n < lowest) {
40032ec99e3eSMatthew Ahrens 		lowest = n;
40042ec99e3eSMatthew Ahrens 		r = FMR_LOTSFREE;
40052ec99e3eSMatthew Ahrens 	}
4006fa9e4066Sahrens 
4007fa9e4066Sahrens 	/*
4008fa9e4066Sahrens 	 * check to make sure that swapfs has enough space so that anon
4009fa94a07fSbrendan 	 * reservations can still succeed. anon_resvmem() checks that the
4010fa9e4066Sahrens 	 * availrmem is greater than swapfs_minfree, and the number of reserved
4011fa9e4066Sahrens 	 * swap pages.  We also add a bit of extra here just to prevent
4012fa9e4066Sahrens 	 * circumstances from getting really dire.
4013fa9e4066Sahrens 	 */
40142ec99e3eSMatthew Ahrens 	n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
40152ec99e3eSMatthew Ahrens 	    desfree - arc_swapfs_reserve);
40162ec99e3eSMatthew Ahrens 	if (n < lowest) {
40172ec99e3eSMatthew Ahrens 		lowest = n;
40182ec99e3eSMatthew Ahrens 		r = FMR_SWAPFS_MINFREE;
40192ec99e3eSMatthew Ahrens 	}
40202ec99e3eSMatthew Ahrens 
4021fa9e4066Sahrens 
4022cf746768SBryan Cantrill 	/*
4023cf746768SBryan Cantrill 	 * Check that we have enough availrmem that memory locking (e.g., via
4024cf746768SBryan Cantrill 	 * mlock(3C) or memcntl(2)) can still succeed.  (pages_pp_maximum
4025cf746768SBryan Cantrill 	 * stores the number of pages that cannot be locked; when availrmem
4026cf746768SBryan Cantrill 	 * drops below pages_pp_maximum, page locking mechanisms such as
4027cf746768SBryan Cantrill 	 * page_pp_lock() will fail.)
4028cf746768SBryan Cantrill 	 */
40292ec99e3eSMatthew Ahrens 	n = PAGESIZE * (availrmem - pages_pp_maximum -
40302ec99e3eSMatthew Ahrens 	    arc_pages_pp_reserve);
40312ec99e3eSMatthew Ahrens 	if (n < lowest) {
40322ec99e3eSMatthew Ahrens 		lowest = n;
40332ec99e3eSMatthew Ahrens 		r = FMR_PAGES_PP_MAXIMUM;
40342ec99e3eSMatthew Ahrens 	}
4035cf746768SBryan Cantrill 
40365dc8af33Smaybee #if defined(__i386)
4037fa9e4066Sahrens 	/*
4038fa9e4066Sahrens 	 * If we're on an i386 platform, it's possible that we'll exhaust the
4039fa9e4066Sahrens 	 * kernel heap space before we ever run out of available physical
4040fa9e4066Sahrens 	 * memory.  Most checks of the size of the heap_area compare against
4041fa9e4066Sahrens 	 * tune.t_minarmem, which is the minimum available real memory that we
4042fa9e4066Sahrens 	 * can have in the system.  However, this is generally fixed at 25 pages
4043fa9e4066Sahrens 	 * which is so low that it's useless.  In this comparison, we seek to
4044fa9e4066Sahrens 	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
4045fa94a07fSbrendan 	 * heap is allocated.  (Or, in the calculation, if less than 1/4th is
4046fa9e4066Sahrens 	 * free)
4047fa9e4066Sahrens 	 */
40480dd053d7SPrakash Surya 	n = (int64_t)vmem_size(heap_arena, VMEM_FREE) -
40492ec99e3eSMatthew Ahrens 	    (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2);
40502ec99e3eSMatthew Ahrens 	if (n < lowest) {
40512ec99e3eSMatthew Ahrens 		lowest = n;
40522ec99e3eSMatthew Ahrens 		r = FMR_HEAP_ARENA;
40532ec99e3eSMatthew Ahrens 	}
4054fa9e4066Sahrens #endif
4055fa9e4066Sahrens 
405694dd93aeSGeorge Wilson 	/*
405794dd93aeSGeorge Wilson 	 * If zio data pages are being allocated out of a separate heap segment,
405894dd93aeSGeorge Wilson 	 * then enforce that the size of available vmem for this arena remains
40590dd053d7SPrakash Surya 	 * above about 1/4th (1/(2^arc_zio_arena_free_shift)) free.
406094dd93aeSGeorge Wilson 	 *
40610dd053d7SPrakash Surya 	 * Note that reducing the arc_zio_arena_free_shift keeps more virtual
40620dd053d7SPrakash Surya 	 * memory (in the zio_arena) free, which can avoid memory
40630dd053d7SPrakash Surya 	 * fragmentation issues.
406494dd93aeSGeorge Wilson 	 */
40652ec99e3eSMatthew Ahrens 	if (zio_arena != NULL) {
40660dd053d7SPrakash Surya 		n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
40670dd053d7SPrakash Surya 		    (vmem_size(zio_arena, VMEM_ALLOC) >>
40680dd053d7SPrakash Surya 		    arc_zio_arena_free_shift);
40692ec99e3eSMatthew Ahrens 		if (n < lowest) {
40702ec99e3eSMatthew Ahrens 			lowest = n;
40712ec99e3eSMatthew Ahrens 			r = FMR_ZIO_ARENA;
40722ec99e3eSMatthew Ahrens 		}
40732ec99e3eSMatthew Ahrens 	}
4074fa9e4066Sahrens #else
40752ec99e3eSMatthew Ahrens 	/* Every 100 calls, free a small amount */
4076fa9e4066Sahrens 	if (spa_get_random(100) == 0)
40772ec99e3eSMatthew Ahrens 		lowest = -1024;
4078fa9e4066Sahrens #endif
40792ec99e3eSMatthew Ahrens 
40802ec99e3eSMatthew Ahrens 	last_free_memory = lowest;
40812ec99e3eSMatthew Ahrens 	last_free_reason = r;
40822ec99e3eSMatthew Ahrens 
40832ec99e3eSMatthew Ahrens 	return (lowest);
40842ec99e3eSMatthew Ahrens }
40852ec99e3eSMatthew Ahrens 
40862ec99e3eSMatthew Ahrens 
40872ec99e3eSMatthew Ahrens /*
40882ec99e3eSMatthew Ahrens  * Determine if the system is under memory pressure and is asking
4089dcbf3bd6SGeorge Wilson  * to reclaim memory. A return value of B_TRUE indicates that the system
40902ec99e3eSMatthew Ahrens  * is under memory pressure and that the arc should adjust accordingly.
40912ec99e3eSMatthew Ahrens  */
40922ec99e3eSMatthew Ahrens static boolean_t
40932ec99e3eSMatthew Ahrens arc_reclaim_needed(void)
40942ec99e3eSMatthew Ahrens {
40952ec99e3eSMatthew Ahrens 	return (arc_available_memory() < 0);
4096fa9e4066Sahrens }
4097fa9e4066Sahrens 
4098fa9e4066Sahrens static void
4099de753e34SBrad Lewis arc_kmem_reap_soon(void)
4100fa9e4066Sahrens {
4101fa9e4066Sahrens 	size_t			i;
4102fa9e4066Sahrens 	kmem_cache_t		*prev_cache = NULL;
4103ad23a2dbSjohansen 	kmem_cache_t		*prev_data_cache = NULL;
4104fa9e4066Sahrens 	extern kmem_cache_t	*zio_buf_cache[];
4105ad23a2dbSjohansen 	extern kmem_cache_t	*zio_data_buf_cache[];
410683803b51SGeorge Wilson 	extern kmem_cache_t	*range_seg_cache;
4107770499e1SDan Kimmel 	extern kmem_cache_t	*abd_chunk_cache;
4108fa9e4066Sahrens 
4109033f9833Sek #ifdef _KERNEL
41103a2d8a1bSPaul Dagnelie 	if (aggsum_compare(&arc_meta_used, arc_meta_limit) >= 0) {
41110e8c6158Smaybee 		/*
41120e8c6158Smaybee 		 * We are exceeding our meta-data cache limit.
41130e8c6158Smaybee 		 * Purge some DNLC entries to release holds on meta-data.
41140e8c6158Smaybee 		 */
41150e8c6158Smaybee 		dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
41160e8c6158Smaybee 	}
41175dc8af33Smaybee #if defined(__i386)
41185dc8af33Smaybee 	/*
41195dc8af33Smaybee 	 * Reclaim unused memory from all kmem caches.
41205dc8af33Smaybee 	 */
41215dc8af33Smaybee 	kmem_reap();
41225dc8af33Smaybee #endif
4123033f9833Sek #endif
4124033f9833Sek 
4125fa9e4066Sahrens 	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
4126fa9e4066Sahrens 		if (zio_buf_cache[i] != prev_cache) {
4127fa9e4066Sahrens 			prev_cache = zio_buf_cache[i];
412836a64e62STim Kordas 			kmem_cache_reap_soon(zio_buf_cache[i]);
4129fa9e4066Sahrens 		}
4130ad23a2dbSjohansen 		if (zio_data_buf_cache[i] != prev_data_cache) {
4131ad23a2dbSjohansen 			prev_data_cache = zio_data_buf_cache[i];
413236a64e62STim Kordas 			kmem_cache_reap_soon(zio_data_buf_cache[i]);
4133ad23a2dbSjohansen 		}
4134fa9e4066Sahrens 	}
413536a64e62STim Kordas 	kmem_cache_reap_soon(abd_chunk_cache);
413636a64e62STim Kordas 	kmem_cache_reap_soon(buf_cache);
413736a64e62STim Kordas 	kmem_cache_reap_soon(hdr_full_cache);
413836a64e62STim Kordas 	kmem_cache_reap_soon(hdr_l2only_cache);
413936a64e62STim Kordas 	kmem_cache_reap_soon(range_seg_cache);
414094dd93aeSGeorge Wilson 
41412ec99e3eSMatthew Ahrens 	if (zio_arena != NULL) {
41422ec99e3eSMatthew Ahrens 		/*
41432ec99e3eSMatthew Ahrens 		 * Ask the vmem arena to reclaim unused memory from its
41442ec99e3eSMatthew Ahrens 		 * quantum caches.
41452ec99e3eSMatthew Ahrens 		 */
414694dd93aeSGeorge Wilson 		vmem_qcache_reap(zio_arena);
41472ec99e3eSMatthew Ahrens 	}
4148fa9e4066Sahrens }
4149fa9e4066Sahrens 
4150de753e34SBrad Lewis /* ARGSUSED */
4151de753e34SBrad Lewis static boolean_t
4152de753e34SBrad Lewis arc_adjust_cb_check(void *arg, zthr_t *zthr)
4153de753e34SBrad Lewis {
4154de753e34SBrad Lewis 	/*
4155de753e34SBrad Lewis 	 * This is necessary in order for the mdb ::arc dcmd to
4156de753e34SBrad Lewis 	 * show up to date information. Since the ::arc command
4157de753e34SBrad Lewis 	 * does not call the kstat's update function, without
4158de753e34SBrad Lewis 	 * this call, the command may show stale stats for the
4159de753e34SBrad Lewis 	 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
4160de753e34SBrad Lewis 	 * with this change, the data might be up to 1 second
4161de753e34SBrad Lewis 	 * out of date(the arc_adjust_zthr has a maximum sleep
4162de753e34SBrad Lewis 	 * time of 1 second); but that should suffice.  The
4163de753e34SBrad Lewis 	 * arc_state_t structures can be queried directly if more
4164de753e34SBrad Lewis 	 * accurate information is needed.
4165de753e34SBrad Lewis 	 */
4166de753e34SBrad Lewis 	if (arc_ksp != NULL)
4167de753e34SBrad Lewis 		arc_ksp->ks_update(arc_ksp, KSTAT_READ);
4168de753e34SBrad Lewis 
4169de753e34SBrad Lewis 	/*
4170de753e34SBrad Lewis 	 * We have to rely on arc_get_data_impl() to tell us when to adjust,
4171de753e34SBrad Lewis 	 * rather than checking if we are overflowing here, so that we are
4172de753e34SBrad Lewis 	 * sure to not leave arc_get_data_impl() waiting on
4173de753e34SBrad Lewis 	 * arc_adjust_waiters_cv.  If we have become "not overflowing" since
4174de753e34SBrad Lewis 	 * arc_get_data_impl() checked, we need to wake it up.  We could
4175de753e34SBrad Lewis 	 * broadcast the CV here, but arc_get_data_impl() may have not yet
4176de753e34SBrad Lewis 	 * gone to sleep.  We would need to use a mutex to ensure that this
4177de753e34SBrad Lewis 	 * function doesn't broadcast until arc_get_data_impl() has gone to
4178de753e34SBrad Lewis 	 * sleep (e.g. the arc_adjust_lock).  However, the lock ordering of
4179de753e34SBrad Lewis 	 * such a lock would necessarily be incorrect with respect to the
4180de753e34SBrad Lewis 	 * zthr_lock, which is held before this function is called, and is
4181de753e34SBrad Lewis 	 * held by arc_get_data_impl() when it calls zthr_wakeup().
4182de753e34SBrad Lewis 	 */
4183de753e34SBrad Lewis 	return (arc_adjust_needed);
4184de753e34SBrad Lewis }
4185de753e34SBrad Lewis 
4186244781f1SPrakash Surya /*
4187de753e34SBrad Lewis  * Keep arc_size under arc_c by running arc_adjust which evicts data
4188de753e34SBrad Lewis  * from the ARC.
4189244781f1SPrakash Surya  */
41903f7978d0SAlan Somers /* ARGSUSED */
4191de753e34SBrad Lewis static int
4192de753e34SBrad Lewis arc_adjust_cb(void *arg, zthr_t *zthr)
4193fa9e4066Sahrens {
4194de753e34SBrad Lewis 	uint64_t evicted = 0;
4195fa9e4066Sahrens 
4196de753e34SBrad Lewis 	/* Evict from cache */
4197de753e34SBrad Lewis 	evicted = arc_adjust();
4198244781f1SPrakash Surya 
4199de753e34SBrad Lewis 	/*
4200de753e34SBrad Lewis 	 * If evicted is zero, we couldn't evict anything
4201de753e34SBrad Lewis 	 * via arc_adjust(). This could be due to hash lock
4202de753e34SBrad Lewis 	 * collisions, but more likely due to the majority of
4203de753e34SBrad Lewis 	 * arc buffers being unevictable. Therefore, even if
4204de753e34SBrad Lewis 	 * arc_size is above arc_c, another pass is unlikely to
4205de753e34SBrad Lewis 	 * be helpful and could potentially cause us to enter an
4206de753e34SBrad Lewis 	 * infinite loop.  Additionally, zthr_iscancelled() is
4207de753e34SBrad Lewis 	 * checked here so that if the arc is shutting down, the
4208de753e34SBrad Lewis 	 * broadcast will wake any remaining arc adjust waiters.
4209de753e34SBrad Lewis 	 */
4210de753e34SBrad Lewis 	mutex_enter(&arc_adjust_lock);
4211de753e34SBrad Lewis 	arc_adjust_needed = !zthr_iscancelled(arc_adjust_zthr) &&
4212de753e34SBrad Lewis 	    evicted > 0 && aggsum_compare(&arc_size, arc_c) > 0;
4213de753e34SBrad Lewis 	if (!arc_adjust_needed) {
4214dcbf3bd6SGeorge Wilson 		/*
4215de753e34SBrad Lewis 		 * We're either no longer overflowing, or we
4216de753e34SBrad Lewis 		 * can't evict anything more, so we should wake
4217de753e34SBrad Lewis 		 * up any waiters.
4218dcbf3bd6SGeorge Wilson 		 */
4219de753e34SBrad Lewis 		cv_broadcast(&arc_adjust_waiters_cv);
4220de753e34SBrad Lewis 	}
4221de753e34SBrad Lewis 	mutex_exit(&arc_adjust_lock);
4222dcbf3bd6SGeorge Wilson 
4223de753e34SBrad Lewis 	return (0);
4224de753e34SBrad Lewis }
4225244781f1SPrakash Surya 
4226de753e34SBrad Lewis /* ARGSUSED */
4227de753e34SBrad Lewis static boolean_t
4228de753e34SBrad Lewis arc_reap_cb_check(void *arg, zthr_t *zthr)
4229de753e34SBrad Lewis {
4230de753e34SBrad Lewis 	int64_t free_memory = arc_available_memory();
4231de753e34SBrad Lewis 
4232de753e34SBrad Lewis 	/*
4233de753e34SBrad Lewis 	 * If a kmem reap is already active, don't schedule more.  We must
4234de753e34SBrad Lewis 	 * check for this because kmem_cache_reap_soon() won't actually
4235de753e34SBrad Lewis 	 * block on the cache being reaped (this is to prevent callers from
4236de753e34SBrad Lewis 	 * becoming implicitly blocked by a system-wide kmem reap -- which,
4237de753e34SBrad Lewis 	 * on a system with many, many full magazines, can take minutes).
4238de753e34SBrad Lewis 	 */
4239de753e34SBrad Lewis 	if (!kmem_cache_reap_active() &&
4240de753e34SBrad Lewis 	    free_memory < 0) {
4241de753e34SBrad Lewis 		arc_no_grow = B_TRUE;
4242de753e34SBrad Lewis 		arc_warm = B_TRUE;
4243405a5a0fSMatthew Ahrens 		/*
4244de753e34SBrad Lewis 		 * Wait at least zfs_grow_retry (default 60) seconds
4245de753e34SBrad Lewis 		 * before considering growing.
4246405a5a0fSMatthew Ahrens 		 */
4247de753e34SBrad Lewis 		arc_growtime = gethrtime() + SEC2NSEC(arc_grow_retry);
4248de753e34SBrad Lewis 		return (B_TRUE);
4249de753e34SBrad Lewis 	} else if (free_memory < arc_c >> arc_no_grow_shift) {
4250de753e34SBrad Lewis 		arc_no_grow = B_TRUE;
4251de753e34SBrad Lewis 	} else if (gethrtime() >= arc_growtime) {
4252de753e34SBrad Lewis 		arc_no_grow = B_FALSE;
4253de753e34SBrad Lewis 	}
4254405a5a0fSMatthew Ahrens 
4255de753e34SBrad Lewis 	return (B_FALSE);
4256de753e34SBrad Lewis }
4257fa9e4066Sahrens 
4258de753e34SBrad Lewis /*
4259de753e34SBrad Lewis  * Keep enough free memory in the system by reaping the ARC's kmem
4260de753e34SBrad Lewis  * caches.  To cause more slabs to be reapable, we may reduce the
4261de753e34SBrad Lewis  * target size of the cache (arc_c), causing the arc_adjust_cb()
4262de753e34SBrad Lewis  * to free more buffers.
4263de753e34SBrad Lewis  */
4264de753e34SBrad Lewis /* ARGSUSED */
4265de753e34SBrad Lewis static int
4266de753e34SBrad Lewis arc_reap_cb(void *arg, zthr_t *zthr)
4267de753e34SBrad Lewis {
4268de753e34SBrad Lewis 	int64_t free_memory;
4269fa9e4066Sahrens 
4270de753e34SBrad Lewis 	/*
4271de753e34SBrad Lewis 	 * Kick off asynchronous kmem_reap()'s of all our caches.
4272de753e34SBrad Lewis 	 */
4273de753e34SBrad Lewis 	arc_kmem_reap_soon();
4274fa9e4066Sahrens 
4275de753e34SBrad Lewis 	/*
4276de753e34SBrad Lewis 	 * Wait at least arc_kmem_cache_reap_retry_ms between
4277de753e34SBrad Lewis 	 * arc_kmem_reap_soon() calls. Without this check it is possible to
4278de753e34SBrad Lewis 	 * end up in a situation where we spend lots of time reaping
4279de753e34SBrad Lewis 	 * caches, while we're near arc_c_min.  Waiting here also gives the
4280de753e34SBrad Lewis 	 * subsequent free memory check a chance of finding that the
4281de753e34SBrad Lewis 	 * asynchronous reap has already freed enough memory, and we don't
4282de753e34SBrad Lewis 	 * need to call arc_reduce_target_size().
4283de753e34SBrad Lewis 	 */
4284de753e34SBrad Lewis 	delay((hz * arc_kmem_cache_reap_retry_ms + 999) / 1000);
4285de753e34SBrad Lewis 
4286de753e34SBrad Lewis 	/*
4287de753e34SBrad Lewis 	 * Reduce the target size as needed to maintain the amount of free
4288de753e34SBrad Lewis 	 * memory in the system at a fraction of the arc_size (1/128th by
4289de753e34SBrad Lewis 	 * default).  If oversubscribed (free_memory < 0) then reduce the
4290de753e34SBrad Lewis 	 * target arc_size by the deficit amount plus the fractional
4291de753e34SBrad Lewis 	 * amount.  If free memory is positive but less then the fractional
4292de753e34SBrad Lewis 	 * amount, reduce by what is needed to hit the fractional amount.
4293de753e34SBrad Lewis 	 */
4294de753e34SBrad Lewis 	free_memory = arc_available_memory();
42952ec99e3eSMatthew Ahrens 
4296de753e34SBrad Lewis 	int64_t to_free =
4297de753e34SBrad Lewis 	    (arc_c >> arc_shrink_shift) - free_memory;
4298de753e34SBrad Lewis 	if (to_free > 0) {
42992ec99e3eSMatthew Ahrens #ifdef _KERNEL
4300de753e34SBrad Lewis 		to_free = MAX(to_free, ptob(needfree));
43012ec99e3eSMatthew Ahrens #endif
4302de753e34SBrad Lewis 		arc_reduce_target_size(to_free);
4303244781f1SPrakash Surya 	}
4304244781f1SPrakash Surya 
4305de753e34SBrad Lewis 	return (0);
4306244781f1SPrakash Surya }
4307244781f1SPrakash Surya 
4308ea8dc4b6Seschrock /*
4309ea8dc4b6Seschrock  * Adapt arc info given the number of bytes we are trying to add and
4310ea8dc4b6Seschrock  * the state that we are comming from.  This function is only called
4311ea8dc4b6Seschrock  * when we are adding new content to the cache.
4312ea8dc4b6Seschrock  */
4313fa9e4066Sahrens static void
4314ea8dc4b6Seschrock arc_adapt(int bytes, arc_state_t *state)
4315fa9e4066Sahrens {
4316ea8dc4b6Seschrock 	int mult;
43175a98e54bSBrendan Gregg - Sun Microsystems 	uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
43182fd872a7SPrakash Surya 	int64_t mrug_size = refcount_count(&arc_mru_ghost->arcs_size);
43192fd872a7SPrakash Surya 	int64_t mfug_size = refcount_count(&arc_mfu_ghost->arcs_size);
4320ea8dc4b6Seschrock 
4321fa94a07fSbrendan 	if (state == arc_l2c_only)
4322fa94a07fSbrendan 		return;
4323fa94a07fSbrendan 
4324ea8dc4b6Seschrock 	ASSERT(bytes > 0);
4325fa9e4066Sahrens 	/*
4326ea8dc4b6Seschrock 	 * Adapt the target size of the MRU list:
4327ea8dc4b6Seschrock 	 *	- if we just hit in the MRU ghost list, then increase
4328ea8dc4b6Seschrock 	 *	  the target size of the MRU list.
4329ea8dc4b6Seschrock 	 *	- if we just hit in the MFU ghost list, then increase
4330ea8dc4b6Seschrock 	 *	  the target size of the MFU list by decreasing the
4331ea8dc4b6Seschrock 	 *	  target size of the MRU list.
4332fa9e4066Sahrens 	 */
433344cb6abcSbmc 	if (state == arc_mru_ghost) {
43342fd872a7SPrakash Surya 		mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
43353e4e8481STom Erickson 		mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
4336ea8dc4b6Seschrock 
43375a98e54bSBrendan Gregg - Sun Microsystems 		arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
433844cb6abcSbmc 	} else if (state == arc_mfu_ghost) {
43395a98e54bSBrendan Gregg - Sun Microsystems 		uint64_t delta;
43405a98e54bSBrendan Gregg - Sun Microsystems 
43412fd872a7SPrakash Surya 		mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
43423e4e8481STom Erickson 		mult = MIN(mult, 10);
4343ea8dc4b6Seschrock 
43445a98e54bSBrendan Gregg - Sun Microsystems 		delta = MIN(bytes * mult, arc_p);
43455a98e54bSBrendan Gregg - Sun Microsystems 		arc_p = MAX(arc_p_min, arc_p - delta);
4346ea8dc4b6Seschrock 	}
434744cb6abcSbmc 	ASSERT((int64_t)arc_p >= 0);
4348fa9e4066Sahrens 
4349de753e34SBrad Lewis 	/*
4350de753e34SBrad Lewis 	 * Wake reap thread if we do not have any available memory
4351de753e34SBrad Lewis 	 */
4352fa9e4066Sahrens 	if (arc_reclaim_needed()) {
4353de753e34SBrad Lewis 		zthr_wakeup(arc_reap_zthr);
4354fa9e4066Sahrens 		return;
4355fa9e4066Sahrens 	}
4356fa9e4066Sahrens 
4357de753e34SBrad Lewis 
435844cb6abcSbmc 	if (arc_no_grow)
4359fa9e4066Sahrens 		return;
4360fa9e4066Sahrens 
436144cb6abcSbmc 	if (arc_c >= arc_c_max)
4362ea8dc4b6Seschrock 		return;
4363ea8dc4b6Seschrock 
4364fa9e4066Sahrens 	/*
4365ea8dc4b6Seschrock 	 * If we're within (2 * maxblocksize) bytes of the target
4366ea8dc4b6Seschrock 	 * cache size, increment the target cache size
4367fa9e4066Sahrens 	 */
43683a2d8a1bSPaul Dagnelie 	if (aggsum_compare(&arc_size, arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) >
43693a2d8a1bSPaul Dagnelie 	    0) {
437044cb6abcSbmc 		atomic_add_64(&arc_c, (int64_t)bytes);
437144cb6abcSbmc 		if (arc_c > arc_c_max)
437244cb6abcSbmc 			arc_c = arc_c_max;
437344cb6abcSbmc 		else if (state == arc_anon)
437444cb6abcSbmc 			atomic_add_64(&arc_p, (int64_t)bytes);
437544cb6abcSbmc 		if (arc_p > arc_c)
437644cb6abcSbmc 			arc_p = arc_c;
4377fa9e4066Sahrens 	}
437844cb6abcSbmc 	ASSERT((int64_t)arc_p >= 0);
4379fa9e4066Sahrens }
4380fa9e4066Sahrens 
4381fa9e4066Sahrens /*
4382244781f1SPrakash Surya  * Check if arc_size has grown past our upper threshold, determined by
4383244781f1SPrakash Surya  * zfs_arc_overflow_shift.
4384fa9e4066Sahrens  */
4385244781f1SPrakash Surya static boolean_t
4386244781f1SPrakash Surya arc_is_overflowing(void)
4387fa9e4066Sahrens {
4388244781f1SPrakash Surya 	/* Always allow at least one block of overflow */
4389244781f1SPrakash Surya 	uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
4390244781f1SPrakash Surya 	    arc_c >> zfs_arc_overflow_shift);
4391fa9e4066Sahrens 
43923a2d8a1bSPaul Dagnelie 	/*
43933a2d8a1bSPaul Dagnelie 	 * We just compare the lower bound here for performance reasons. Our
43943a2d8a1bSPaul Dagnelie 	 * primary goals are to make sure that the arc never grows without
43953a2d8a1bSPaul Dagnelie 	 * bound, and that it can reach its maximum size. This check
43963a2d8a1bSPaul Dagnelie 	 * accomplishes both goals. The maximum amount we could run over by is
43973a2d8a1bSPaul Dagnelie 	 * 2 * aggsum_borrow_multiplier * NUM_CPUS * the average size of a block
43983a2d8a1bSPaul Dagnelie 	 * in the ARC. In practice, that's in the tens of MB, which is low
43993a2d8a1bSPaul Dagnelie 	 * enough to be safe.
44003a2d8a1bSPaul Dagnelie 	 */
44013a2d8a1bSPaul Dagnelie 	return (aggsum_lower_bound(&arc_size) >= arc_c + overflow);
4402fa9e4066Sahrens }
4403fa9e4066Sahrens 
4404770499e1SDan Kimmel static abd_t *
4405770499e1SDan Kimmel arc_get_data_abd(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4406770499e1SDan Kimmel {
4407770499e1SDan Kimmel 	arc_buf_contents_t type = arc_buf_type(hdr);
4408770499e1SDan Kimmel 
4409770499e1SDan Kimmel 	arc_get_data_impl(hdr, size, tag);
4410770499e1SDan Kimmel 	if (type == ARC_BUFC_METADATA) {
4411770499e1SDan Kimmel 		return (abd_alloc(size, B_TRUE));
4412770499e1SDan Kimmel 	} else {
4413770499e1SDan Kimmel 		ASSERT(type == ARC_BUFC_DATA);
4414770499e1SDan Kimmel 		return (abd_alloc(size, B_FALSE));
4415770499e1SDan Kimmel 	}
4416770499e1SDan Kimmel }
4417770499e1SDan Kimmel 
4418770499e1SDan Kimmel static void *
4419770499e1SDan Kimmel arc_get_data_buf(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4420770499e1SDan Kimmel {
4421770499e1SDan Kimmel 	arc_buf_contents_t type = arc_buf_type(hdr);
4422770499e1SDan Kimmel 
4423770499e1SDan Kimmel 	arc_get_data_impl(hdr, size, tag);
4424770499e1SDan Kimmel 	if (type == ARC_BUFC_METADATA) {
4425770499e1SDan Kimmel 		return (zio_buf_alloc(size));
4426770499e1SDan Kimmel 	} else {
4427770499e1SDan Kimmel 		ASSERT(type == ARC_BUFC_DATA);
4428770499e1SDan Kimmel 		return (zio_data_buf_alloc(size));
4429770499e1SDan Kimmel 	}
4430770499e1SDan Kimmel }
4431770499e1SDan Kimmel 
4432fa9e4066Sahrens /*
4433dcbf3bd6SGeorge Wilson  * Allocate a block and return it to the caller. If we are hitting the
4434dcbf3bd6SGeorge Wilson  * hard limit for the cache size, we must sleep, waiting for the eviction
4435dcbf3bd6SGeorge Wilson  * thread to catch up. If we're past the target size but below the hard
4436dcbf3bd6SGeorge Wilson  * limit, we'll only signal the reclaim thread and continue on.
4437fa9e4066Sahrens  */
4438770499e1SDan Kimmel static void
4439770499e1SDan Kimmel arc_get_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4440fa9e4066Sahrens {
4441770499e1SDan Kimmel 	arc_state_t *state = hdr->b_l1hdr.b_state;
4442770499e1SDan Kimmel 	arc_buf_contents_t type = arc_buf_type(hdr);
4443fa9e4066Sahrens 
444444eda4d7Smaybee 	arc_adapt(size, state);
4445fa9e4066Sahrens 
444644eda4d7Smaybee 	/*
4447244781f1SPrakash Surya 	 * If arc_size is currently overflowing, and has grown past our
4448244781f1SPrakash Surya 	 * upper limit, we must be adding data faster than the evict
4449244781f1SPrakash Surya 	 * thread can evict. Thus, to ensure we don't compound the
4450244781f1SPrakash Surya 	 * problem by adding more data and forcing arc_size to grow even
4451244781f1SPrakash Surya 	 * further past it's target size, we halt and wait for the
4452244781f1SPrakash Surya 	 * eviction thread to catch up.
4453244781f1SPrakash Surya 	 *
4454244781f1SPrakash Surya 	 * It's also possible that the reclaim thread is unable to evict
4455244781f1SPrakash Surya 	 * enough buffers to get arc_size below the overflow limit (e.g.
4456244781f1SPrakash Surya 	 * due to buffers being un-evictable, or hash lock collisions).
4457244781f1SPrakash Surya 	 * In this case, we want to proceed regardless if we're
4458244781f1SPrakash Surya 	 * overflowing; thus we don't use a while loop here.
445944eda4d7Smaybee 	 */
4460244781f1SPrakash Surya 	if (arc_is_overflowing()) {
4461de753e34SBrad Lewis 		mutex_enter(&arc_adjust_lock);
4462244781f1SPrakash Surya 
4463244781f1SPrakash Surya 		/*
4464244781f1SPrakash Surya 		 * Now that we've acquired the lock, we may no longer be
4465244781f1SPrakash Surya 		 * over the overflow limit, lets check.
4466244781f1SPrakash Surya 		 *
4467244781f1SPrakash Surya 		 * We're ignoring the case of spurious wake ups. If that
4468244781f1SPrakash Surya 		 * were to happen, it'd let this thread consume an ARC
4469244781f1SPrakash Surya 		 * buffer before it should have (i.e. before we're under
4470244781f1SPrakash Surya 		 * the overflow limit and were signalled by the reclaim
4471244781f1SPrakash Surya 		 * thread). As long as that is a rare occurrence, it
4472244781f1SPrakash Surya 		 * shouldn't cause any harm.
4473244781f1SPrakash Surya 		 */
4474244781f1SPrakash Surya 		if (arc_is_overflowing()) {
4475de753e34SBrad Lewis 			arc_adjust_needed = B_TRUE;
4476de753e34SBrad Lewis 			zthr_wakeup(arc_adjust_zthr);
4477de753e34SBrad Lewis 			(void) cv_wait(&arc_adjust_waiters_cv,
4478de753e34SBrad Lewis 			    &arc_adjust_lock);
4479ad23a2dbSjohansen 		}
4480de753e34SBrad Lewis 		mutex_exit(&arc_adjust_lock);
448144eda4d7Smaybee 	}
448244eda4d7Smaybee 
4483dcbf3bd6SGeorge Wilson 	VERIFY3U(hdr->b_type, ==, type);
4484244781f1SPrakash Surya 	if (type == ARC_BUFC_METADATA) {
4485244781f1SPrakash Surya 		arc_space_consume(size, ARC_SPACE_META);
4486fa9e4066Sahrens 	} else {
4487244781f1SPrakash Surya 		arc_space_consume(size, ARC_SPACE_DATA);
448844eda4d7Smaybee 	}
4489244781f1SPrakash Surya 
449044eda4d7Smaybee 	/*
449144eda4d7Smaybee 	 * Update the state size.  Note that ghost states have a
449244eda4d7Smaybee 	 * "ghost size" and so don't need to be updated.
449344eda4d7Smaybee 	 */
4494dcbf3bd6SGeorge Wilson 	if (!GHOST_STATE(state)) {
449544eda4d7Smaybee 
4496dcbf3bd6SGeorge Wilson 		(void) refcount_add_many(&state->arcs_size, size, tag);
4497244781f1SPrakash Surya 
4498244781f1SPrakash Surya 		/*
4499244781f1SPrakash Surya 		 * If this is reached via arc_read, the link is
4500244781f1SPrakash Surya 		 * protected by the hash lock. If reached via
4501244781f1SPrakash Surya 		 * arc_buf_alloc, the header should not be accessed by
4502244781f1SPrakash Surya 		 * any other thread. And, if reached via arc_read_done,
4503244781f1SPrakash Surya 		 * the hash lock will protect it if it's found in the
4504244781f1SPrakash Surya 		 * hash table; otherwise no other thread should be
4505244781f1SPrakash Surya 		 * trying to [add|remove]_reference it.
4506244781f1SPrakash Surya 		 */
4507244781f1SPrakash Surya 		if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
450889c86e32SChris Williamson 			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4509dcbf3bd6SGeorge Wilson 			(void) refcount_add_many(&state->arcs_esize[type],
4510dcbf3bd6SGeorge Wilson 			    size, tag);
4511fa9e4066Sahrens 		}
4512dcbf3bd6SGeorge Wilson 
4513641fbdaeSmaybee 		/*
4514641fbdaeSmaybee 		 * If we are growing the cache, and we are adding anonymous
451544cb6abcSbmc 		 * data, and we have outgrown arc_p, update arc_p
4516641fbdaeSmaybee 		 */
45173a2d8a1bSPaul Dagnelie 		if (aggsum_compare(&arc_size, arc_c) < 0 &&
45183a2d8a1bSPaul Dagnelie 		    hdr->b_l1hdr.b_state == arc_anon &&
45192fd872a7SPrakash Surya 		    (refcount_count(&arc_anon->arcs_size) +
45202fd872a7SPrakash Surya 		    refcount_count(&arc_mru->arcs_size) > arc_p))
452144cb6abcSbmc 			arc_p = MIN(arc_c, arc_p + size);
4522fa9e4066Sahrens 	}
4523770499e1SDan Kimmel }
4524770499e1SDan Kimmel 
4525770499e1SDan Kimmel static void
4526770499e1SDan Kimmel arc_free_data_abd(arc_buf_hdr_t *hdr, abd_t *abd, uint64_t size, void *tag)
4527770499e1SDan Kimmel {
4528770499e1SDan Kimmel 	arc_free_data_impl(hdr, size, tag);
4529770499e1SDan Kimmel 	abd_free(abd);
4530770499e1SDan Kimmel }
4531770499e1SDan Kimmel 
4532770499e1SDan Kimmel static void
4533770499e1SDan Kimmel arc_free_data_buf(arc_buf_hdr_t *hdr, void *buf, uint64_t size, void *tag)
4534770499e1SDan Kimmel {
4535770499e1SDan Kimmel 	arc_buf_contents_t type = arc_buf_type(hdr);
4536770499e1SDan Kimmel 
4537770499e1SDan Kimmel 	arc_free_data_impl(hdr, size, tag);
4538770499e1SDan Kimmel 	if (type == ARC_BUFC_METADATA) {
4539770499e1SDan Kimmel 		zio_buf_free(buf, size);
4540770499e1SDan Kimmel 	} else {
4541770499e1SDan Kimmel 		ASSERT(type == ARC_BUFC_DATA);
4542770499e1SDan Kimmel 		zio_data_buf_free(buf, size);
4543770499e1SDan Kimmel 	}
4544dcbf3bd6SGeorge Wilson }
4545dcbf3bd6SGeorge Wilson 
4546dcbf3bd6SGeorge Wilson /*
4547dcbf3bd6SGeorge Wilson  * Free the arc data buffer.
4548dcbf3bd6SGeorge Wilson  */
4549dcbf3bd6SGeorge Wilson static void
4550770499e1SDan Kimmel arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4551dcbf3bd6SGeorge Wilson {
4552dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
4553dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type = arc_buf_type(hdr);
4554dcbf3bd6SGeorge Wilson 
4555dcbf3bd6SGeorge Wilson 	/* protected by hash lock, if in the hash table */
4556dcbf3bd6SGeorge Wilson 	if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
4557dcbf3bd6SGeorge Wilson 		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4558dcbf3bd6SGeorge Wilson 		ASSERT(state != arc_anon && state != arc_l2c_only);
4559dcbf3bd6SGeorge Wilson 
4560dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_esize[type],
4561dcbf3bd6SGeorge Wilson 		    size, tag);
4562dcbf3bd6SGeorge Wilson 	}
4563dcbf3bd6SGeorge Wilson 	(void) refcount_remove_many(&state->arcs_size, size, tag);
4564dcbf3bd6SGeorge Wilson 
4565dcbf3bd6SGeorge Wilson 	VERIFY3U(hdr->b_type, ==, type);
4566dcbf3bd6SGeorge Wilson 	if (type == ARC_BUFC_METADATA) {
4567dcbf3bd6SGeorge Wilson 		arc_space_return(size, ARC_SPACE_META);
4568dcbf3bd6SGeorge Wilson 	} else {
4569dcbf3bd6SGeorge Wilson 		ASSERT(type == ARC_BUFC_DATA);
4570dcbf3bd6SGeorge Wilson 		arc_space_return(size, ARC_SPACE_DATA);
4571dcbf3bd6SGeorge Wilson 	}
4572fa9e4066Sahrens }
4573fa9e4066Sahrens 
4574fa9e4066Sahrens /*
4575fa9e4066Sahrens  * This routine is called whenever a buffer is accessed.
4576ea8dc4b6Seschrock  * NOTE: the hash lock is dropped in this function.
4577fa9e4066Sahrens  */
4578fa9e4066Sahrens static void
45797adb730bSGeorge Wilson arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
4580fa9e4066Sahrens {
4581d3d50737SRafael Vanoni 	clock_t now;
4582d3d50737SRafael Vanoni 
4583fa9e4066Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
458489c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
4585fa9e4066Sahrens 
458689c86e32SChris Williamson 	if (hdr->b_l1hdr.b_state == arc_anon) {
4587fa9e4066Sahrens 		/*
4588fa9e4066Sahrens 		 * This buffer is not in the cache, and does not
4589fa9e4066Sahrens 		 * appear in our "ghost" list.  Add the new buffer
4590fa9e4066Sahrens 		 * to the MRU state.
4591fa9e4066Sahrens 		 */
4592fa9e4066Sahrens 
459389c86e32SChris Williamson 		ASSERT0(hdr->b_l1hdr.b_arc_access);
459489c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
45957adb730bSGeorge Wilson 		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
45967adb730bSGeorge Wilson 		arc_change_state(arc_mru, hdr, hash_lock);
4597fa9e4066Sahrens 
459889c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mru) {
4599d3d50737SRafael Vanoni 		now = ddi_get_lbolt();
4600d3d50737SRafael Vanoni 
4601fa9e4066Sahrens 		/*
460213506d1eSmaybee 		 * If this buffer is here because of a prefetch, then either:
460313506d1eSmaybee 		 * - clear the flag if this is a "referencing" read
460413506d1eSmaybee 		 *   (any subsequent access will bump this into the MFU state).
460513506d1eSmaybee 		 * or
460613506d1eSmaybee 		 * - move the buffer to the head of the list if this is
460713506d1eSmaybee 		 *   another prefetch (to make it less likely to be evicted).
4608fa9e4066Sahrens 		 */
460989c86e32SChris Williamson 		if (HDR_PREFETCH(hdr)) {
461089c86e32SChris Williamson 			if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4611244781f1SPrakash Surya 				/* link protected by hash lock */
4612244781f1SPrakash Surya 				ASSERT(multilist_link_active(
461389c86e32SChris Williamson 				    &hdr->b_l1hdr.b_arc_node));
461413506d1eSmaybee 			} else {
4615dcbf3bd6SGeorge Wilson 				arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
461644cb6abcSbmc 				ARCSTAT_BUMP(arcstat_mru_hits);
461713506d1eSmaybee 			}
461889c86e32SChris Williamson 			hdr->b_l1hdr.b_arc_access = now;
4619fa9e4066Sahrens 			return;
4620fa9e4066Sahrens 		}
4621fa9e4066Sahrens 
4622fa9e4066Sahrens 		/*
4623fa9e4066Sahrens 		 * This buffer has been "accessed" only once so far,
4624fa9e4066Sahrens 		 * but it is still in the cache. Move it to the MFU
4625fa9e4066Sahrens 		 * state.
4626fa9e4066Sahrens 		 */
462789c86e32SChris Williamson 		if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
4628fa9e4066Sahrens 			/*
4629fa9e4066Sahrens 			 * More than 125ms have passed since we
4630fa9e4066Sahrens 			 * instantiated this buffer.  Move it to the
4631fa9e4066Sahrens 			 * most frequently used state.
4632fa9e4066Sahrens 			 */
463389c86e32SChris Williamson 			hdr->b_l1hdr.b_arc_access = now;
46347adb730bSGeorge Wilson 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
46357adb730bSGeorge Wilson 			arc_change_state(arc_mfu, hdr, hash_lock);
4636fa9e4066Sahrens 		}
463744cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mru_hits);
463889c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
4639fa9e4066Sahrens 		arc_state_t	*new_state;
4640fa9e4066Sahrens 		/*
4641fa9e4066Sahrens 		 * This buffer has been "accessed" recently, but
4642fa9e4066Sahrens 		 * was evicted from the cache.  Move it to the
4643fa9e4066Sahrens 		 * MFU state.
4644fa9e4066Sahrens 		 */
4645fa9e4066Sahrens 
464689c86e32SChris Williamson 		if (HDR_PREFETCH(hdr)) {
464744cb6abcSbmc 			new_state = arc_mru;
464889c86e32SChris Williamson 			if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0)
4649dcbf3bd6SGeorge Wilson 				arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
46507adb730bSGeorge Wilson 			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
4651fa9e4066Sahrens 		} else {
465244cb6abcSbmc 			new_state = arc_mfu;
46537adb730bSGeorge Wilson 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4654fa9e4066Sahrens 		}
4655fa9e4066Sahrens 
465689c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
46577adb730bSGeorge Wilson 		arc_change_state(new_state, hdr, hash_lock);
4658fa9e4066Sahrens 
465944cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
466089c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mfu) {
4661fa9e4066Sahrens 		/*
4662fa9e4066Sahrens 		 * This buffer has been accessed more than once and is
4663fa9e4066Sahrens 		 * still in the cache.  Keep it in the MFU state.
4664fa9e4066Sahrens 		 *
466513506d1eSmaybee 		 * NOTE: an add_reference() that occurred when we did
466613506d1eSmaybee 		 * the arc_read() will have kicked this off the list.
466713506d1eSmaybee 		 * If it was a prefetch, we will explicitly move it to
466813506d1eSmaybee 		 * the head of the list now.
4669fa9e4066Sahrens 		 */
467089c86e32SChris Williamson 		if ((HDR_PREFETCH(hdr)) != 0) {
467189c86e32SChris Williamson 			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4672244781f1SPrakash Surya 			/* link protected by hash_lock */
4673244781f1SPrakash Surya 			ASSERT(multilist_link_active(&hdr->b_l1hdr.b_arc_node));
467413506d1eSmaybee 		}
467544cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mfu_hits);
467689c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
467789c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
467844cb6abcSbmc 		arc_state_t	*new_state = arc_mfu;
4679fa9e4066Sahrens 		/*
4680fa9e4066Sahrens 		 * This buffer has been accessed more than once but has
4681fa9e4066Sahrens 		 * been evicted from the cache.  Move it back to the
4682fa9e4066Sahrens 		 * MFU state.
4683fa9e4066Sahrens 		 */
4684fa9e4066Sahrens 
468589c86e32SChris Williamson 		if (HDR_PREFETCH(hdr)) {
468613506d1eSmaybee 			/*
468713506d1eSmaybee 			 * This is a prefetch access...
468813506d1eSmaybee 			 * move this block back to the MRU state.
468913506d1eSmaybee 			 */
469089c86e32SChris Williamson 			ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
469144cb6abcSbmc 			new_state = arc_mru;
469213506d1eSmaybee 		}
469313506d1eSmaybee 
469489c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
46957adb730bSGeorge Wilson 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
46967adb730bSGeorge Wilson 		arc_change_state(new_state, hdr, hash_lock);
4697fa9e4066Sahrens 
469844cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
469989c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
4700fa94a07fSbrendan 		/*
4701fa94a07fSbrendan 		 * This buffer is on the 2nd Level ARC.
4702fa94a07fSbrendan 		 */
4703fa94a07fSbrendan 
470489c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
47057adb730bSGeorge Wilson 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
47067adb730bSGeorge Wilson 		arc_change_state(arc_mfu, hdr, hash_lock);
4707fa9e4066Sahrens 	} else {
4708fa9e4066Sahrens 		ASSERT(!"invalid arc state");
4709fa9e4066Sahrens 	}
4710fa9e4066Sahrens }
4711fa9e4066Sahrens 
4712fa9e4066Sahrens /* a generic arc_done_func_t which you can use */
4713fa9e4066Sahrens /* ARGSUSED */
4714fa9e4066Sahrens void
4715fa9e4066Sahrens arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
4716fa9e4066Sahrens {
47173f9d6ad7SLin Ling 	if (zio == NULL || zio->io_error == 0)
47185602294fSDan Kimmel 		bcopy(buf->b_data, arg, arc_buf_size(buf));
4719dcbf3bd6SGeorge Wilson 	arc_buf_destroy(buf, arg);
4720fa9e4066Sahrens }
4721fa9e4066Sahrens 
47220e8c6158Smaybee /* a generic arc_done_func_t */
4723fa9e4066Sahrens void
4724fa9e4066Sahrens arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
4725fa9e4066Sahrens {
4726fa9e4066Sahrens 	arc_buf_t **bufp = arg;
4727fa98e487SMatthew Ahrens 	if (buf == NULL) {
4728fa98e487SMatthew Ahrens 		ASSERT(zio == NULL || zio->io_error != 0);
4729fa9e4066Sahrens 		*bufp = NULL;
4730fa9e4066Sahrens 	} else {
4731fa98e487SMatthew Ahrens 		ASSERT(zio == NULL || zio->io_error == 0);
4732fa9e4066Sahrens 		*bufp = buf;
4733fa98e487SMatthew Ahrens 		ASSERT(buf->b_data != NULL);
4734fa9e4066Sahrens 	}
4735fa9e4066Sahrens }
4736fa9e4066Sahrens 
4737dcbf3bd6SGeorge Wilson static void
4738dcbf3bd6SGeorge Wilson arc_hdr_verify(arc_buf_hdr_t *hdr, blkptr_t *bp)
4739dcbf3bd6SGeorge Wilson {
4740dcbf3bd6SGeorge Wilson 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
4741dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_PSIZE(hdr), ==, 0);
4742dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
4743dcbf3bd6SGeorge Wilson 	} else {
4744dcbf3bd6SGeorge Wilson 		if (HDR_COMPRESSION_ENABLED(hdr)) {
4745dcbf3bd6SGeorge Wilson 			ASSERT3U(HDR_GET_COMPRESS(hdr), ==,
4746dcbf3bd6SGeorge Wilson 			    BP_GET_COMPRESS(bp));
4747dcbf3bd6SGeorge Wilson 		}
4748dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
4749dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_PSIZE(hdr), ==, BP_GET_PSIZE(bp));
4750dcbf3bd6SGeorge Wilson 	}
4751dcbf3bd6SGeorge Wilson }
4752dcbf3bd6SGeorge Wilson 
4753fa9e4066Sahrens static void
4754fa9e4066Sahrens arc_read_done(zio_t *zio)
4755fa9e4066Sahrens {
4756dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t	*hdr = zio->io_private;
47575d7b4d43SMatthew Ahrens 	kmutex_t	*hash_lock = NULL;
47585602294fSDan Kimmel 	arc_callback_t	*callback_list;
47595602294fSDan Kimmel 	arc_callback_t	*acb;
47605602294fSDan Kimmel 	boolean_t	freeable = B_FALSE;
47615602294fSDan Kimmel 	boolean_t	no_zio_error = (zio->io_error == 0);
4762fa9e4066Sahrens 
4763bbf4a8dfSmaybee 	/*
4764bbf4a8dfSmaybee 	 * The hdr was inserted into hash-table and removed from lists
4765bbf4a8dfSmaybee 	 * prior to starting I/O.  We should find this header, since
4766bbf4a8dfSmaybee 	 * it's in the hash table, and it should be legit since it's
4767bbf4a8dfSmaybee 	 * not possible to evict it during the I/O.  The only possible
4768bbf4a8dfSmaybee 	 * reason for it not to be found is if we were freed during the
4769bbf4a8dfSmaybee 	 * read.
4770bbf4a8dfSmaybee 	 */
47715d7b4d43SMatthew Ahrens 	if (HDR_IN_HASH_TABLE(hdr)) {
47725d7b4d43SMatthew Ahrens 		ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
47735d7b4d43SMatthew Ahrens 		ASSERT3U(hdr->b_dva.dva_word[0], ==,
47745d7b4d43SMatthew Ahrens 		    BP_IDENTITY(zio->io_bp)->dva_word[0]);
47755d7b4d43SMatthew Ahrens 		ASSERT3U(hdr->b_dva.dva_word[1], ==,
47765d7b4d43SMatthew Ahrens 		    BP_IDENTITY(zio->io_bp)->dva_word[1]);
47775d7b4d43SMatthew Ahrens 
47785d7b4d43SMatthew Ahrens 		arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
47795d7b4d43SMatthew Ahrens 		    &hash_lock);
47805d7b4d43SMatthew Ahrens 
4781dcbf3bd6SGeorge Wilson 		ASSERT((found == hdr &&
47825d7b4d43SMatthew Ahrens 		    DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
47835d7b4d43SMatthew Ahrens 		    (found == hdr && HDR_L2_READING(hdr)));
4784dcbf3bd6SGeorge Wilson 		ASSERT3P(hash_lock, !=, NULL);
4785dcbf3bd6SGeorge Wilson 	}
4786dcbf3bd6SGeorge Wilson 
47875602294fSDan Kimmel 	if (no_zio_error) {
4788dcbf3bd6SGeorge Wilson 		/* byteswap if necessary */
4789dcbf3bd6SGeorge Wilson 		if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
4790dcbf3bd6SGeorge Wilson 			if (BP_GET_LEVEL(zio->io_bp) > 0) {
4791dcbf3bd6SGeorge Wilson 				hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
4792dcbf3bd6SGeorge Wilson 			} else {
4793dcbf3bd6SGeorge Wilson 				hdr->b_l1hdr.b_byteswap =
4794dcbf3bd6SGeorge Wilson 				    DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
4795dcbf3bd6SGeorge Wilson 			}
4796dcbf3bd6SGeorge Wilson 		} else {
4797dcbf3bd6SGeorge Wilson 			hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
4798dcbf3bd6SGeorge Wilson 		}
47995d7b4d43SMatthew Ahrens 	}
4800fa94a07fSbrendan 
4801dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_L2_EVICTED);
480289c86e32SChris Williamson 	if (l2arc_noprefetch && HDR_PREFETCH(hdr))
4803dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_L2CACHE);
4804fa9e4066Sahrens 
480589c86e32SChris Williamson 	callback_list = hdr->b_l1hdr.b_acb;
4806dcbf3bd6SGeorge Wilson 	ASSERT3P(callback_list, !=, NULL);
48076b4acc8bSahrens 
48085602294fSDan Kimmel 	if (hash_lock && no_zio_error && hdr->b_l1hdr.b_state == arc_anon) {
4809b24ab676SJeff Bonwick 		/*
4810b24ab676SJeff Bonwick 		 * Only call arc_access on anonymous buffers.  This is because
4811b24ab676SJeff Bonwick 		 * if we've issued an I/O for an evicted buffer, we've already
4812b24ab676SJeff Bonwick 		 * called arc_access (to prevent any simultaneous readers from
4813b24ab676SJeff Bonwick 		 * getting confused).
4814b24ab676SJeff Bonwick 		 */
4815b24ab676SJeff Bonwick 		arc_access(hdr, hash_lock);
4816b24ab676SJeff Bonwick 	}
4817b24ab676SJeff Bonwick 
48185602294fSDan Kimmel 	/*
48195602294fSDan Kimmel 	 * If a read request has a callback (i.e. acb_done is not NULL), then we
48205602294fSDan Kimmel 	 * make a buf containing the data according to the parameters which were
48215602294fSDan Kimmel 	 * passed in. The implementation of arc_buf_alloc_impl() ensures that we
48225602294fSDan Kimmel 	 * aren't needlessly decompressing the data multiple times.
48235602294fSDan Kimmel 	 */
48245602294fSDan Kimmel 	int callback_cnt = 0;
48255602294fSDan Kimmel 	for (acb = callback_list; acb != NULL; acb = acb->acb_next) {
48265602294fSDan Kimmel 		if (!acb->acb_done)
48275602294fSDan Kimmel 			continue;
48285602294fSDan Kimmel 
48295602294fSDan Kimmel 		/* This is a demand read since prefetches don't use callbacks */
48305602294fSDan Kimmel 		callback_cnt++;
48315602294fSDan Kimmel 
48325602294fSDan Kimmel 		if (no_zio_error) {
4833fa98e487SMatthew Ahrens 			int error = arc_buf_alloc_impl(hdr, acb->acb_private,
4834fa98e487SMatthew Ahrens 			    acb->acb_compressed, zio->io_error == 0,
4835fa98e487SMatthew Ahrens 			    &acb->acb_buf);
4836fa98e487SMatthew Ahrens 			if (error != 0) {
4837fa98e487SMatthew Ahrens 				/*
4838fa98e487SMatthew Ahrens 				 * Decompression failed.  Set io_error
4839fa98e487SMatthew Ahrens 				 * so that when we call acb_done (below),
4840fa98e487SMatthew Ahrens 				 * we will indicate that the read failed.
4841fa98e487SMatthew Ahrens 				 * Note that in the unusual case where one
4842fa98e487SMatthew Ahrens 				 * callback is compressed and another
4843fa98e487SMatthew Ahrens 				 * uncompressed, we will mark all of them
4844fa98e487SMatthew Ahrens 				 * as failed, even though the uncompressed
4845fa98e487SMatthew Ahrens 				 * one can't actually fail.  In this case,
4846fa98e487SMatthew Ahrens 				 * the hdr will not be anonymous, because
4847fa98e487SMatthew Ahrens 				 * if there are multiple callbacks, it's
4848fa98e487SMatthew Ahrens 				 * because multiple threads found the same
4849fa98e487SMatthew Ahrens 				 * arc buf in the hash table.
4850fa98e487SMatthew Ahrens 				 */
4851fa98e487SMatthew Ahrens 				zio->io_error = error;
4852fa98e487SMatthew Ahrens 			}
4853fa9e4066Sahrens 		}
4854fa9e4066Sahrens 	}
4855fa98e487SMatthew Ahrens 	/*
4856fa98e487SMatthew Ahrens 	 * If there are multiple callbacks, we must have the hash lock,
4857fa98e487SMatthew Ahrens 	 * because the only way for multiple threads to find this hdr is
4858fa98e487SMatthew Ahrens 	 * in the hash table.  This ensures that if there are multiple
4859fa98e487SMatthew Ahrens 	 * callbacks, the hdr is not anonymous.  If it were anonymous,
4860fa98e487SMatthew Ahrens 	 * we couldn't use arc_buf_destroy() in the error case below.
4861fa98e487SMatthew Ahrens 	 */
4862fa98e487SMatthew Ahrens 	ASSERT(callback_cnt < 2 || hash_lock != NULL);
4863fa98e487SMatthew Ahrens 
486489c86e32SChris Williamson 	hdr->b_l1hdr.b_acb = NULL;
4865dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
48665602294fSDan Kimmel 	if (callback_cnt == 0) {
4867dcbf3bd6SGeorge Wilson 		ASSERT(HDR_PREFETCH(hdr));
4868dcbf3bd6SGeorge Wilson 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
4869770499e1SDan Kimmel 		ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
4870b24ab676SJeff Bonwick 	}
4871fa9e4066Sahrens 
487289c86e32SChris Williamson 	ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
487389c86e32SChris Williamson 	    callback_list != NULL);
4874fa9e4066Sahrens 
48755602294fSDan Kimmel 	if (no_zio_error) {
4876dcbf3bd6SGeorge Wilson 		arc_hdr_verify(hdr, zio->io_bp);
4877dcbf3bd6SGeorge Wilson 	} else {
4878dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
487989c86e32SChris Williamson 		if (hdr->b_l1hdr.b_state != arc_anon)
488044cb6abcSbmc 			arc_change_state(arc_anon, hdr, hash_lock);
4881ea8dc4b6Seschrock 		if (HDR_IN_HASH_TABLE(hdr))
4882ea8dc4b6Seschrock 			buf_hash_remove(hdr);
488389c86e32SChris Williamson 		freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4884fa9e4066Sahrens 	}
4885fa9e4066Sahrens 
4886ea8dc4b6Seschrock 	/*
488713506d1eSmaybee 	 * Broadcast before we drop the hash_lock to avoid the possibility
488813506d1eSmaybee 	 * that the hdr (and hence the cv) might be freed before we get to
488913506d1eSmaybee 	 * the cv_broadcast().
4890ea8dc4b6Seschrock 	 */
489189c86e32SChris Williamson 	cv_broadcast(&hdr->b_l1hdr.b_cv);
4892ea8dc4b6Seschrock 
489389c86e32SChris Williamson 	if (hash_lock != NULL) {
489444eda4d7Smaybee 		mutex_exit(hash_lock);
4895fa9e4066Sahrens 	} else {
4896fa9e4066Sahrens 		/*
4897fa9e4066Sahrens 		 * This block was freed while we waited for the read to
4898fa9e4066Sahrens 		 * complete.  It has been removed from the hash table and
4899fa9e4066Sahrens 		 * moved to the anonymous state (so that it won't show up
4900fa9e4066Sahrens 		 * in the cache).
4901fa9e4066Sahrens 		 */
490289c86e32SChris Williamson 		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
490389c86e32SChris Williamson 		freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4904fa9e4066Sahrens 	}
4905fa9e4066Sahrens 
4906fa9e4066Sahrens 	/* execute each callback and free its structure */
4907fa9e4066Sahrens 	while ((acb = callback_list) != NULL) {
4908fa98e487SMatthew Ahrens 		if (acb->acb_done != NULL) {
4909fa98e487SMatthew Ahrens 			if (zio->io_error != 0 && acb->acb_buf != NULL) {
4910fa98e487SMatthew Ahrens 				/*
4911fa98e487SMatthew Ahrens 				 * If arc_buf_alloc_impl() fails during
4912fa98e487SMatthew Ahrens 				 * decompression, the buf will still be
4913fa98e487SMatthew Ahrens 				 * allocated, and needs to be freed here.
4914fa98e487SMatthew Ahrens 				 */
4915fa98e487SMatthew Ahrens 				arc_buf_destroy(acb->acb_buf, acb->acb_private);
4916fa98e487SMatthew Ahrens 				acb->acb_buf = NULL;
4917fa98e487SMatthew Ahrens 			}
4918fa9e4066Sahrens 			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
4919fa98e487SMatthew Ahrens 		}
4920fa9e4066Sahrens 
4921fa9e4066Sahrens 		if (acb->acb_zio_dummy != NULL) {
4922fa9e4066Sahrens 			acb->acb_zio_dummy->io_error = zio->io_error;
4923fa9e4066Sahrens 			zio_nowait(acb->acb_zio_dummy);
4924fa9e4066Sahrens 		}
4925fa9e4066Sahrens 
4926fa9e4066Sahrens 		callback_list = acb->acb_next;
4927fa9e4066Sahrens 		kmem_free(acb, sizeof (arc_callback_t));
4928fa9e4066Sahrens 	}
4929fa9e4066Sahrens 
4930fa9e4066Sahrens 	if (freeable)
4931ea8dc4b6Seschrock 		arc_hdr_destroy(hdr);
4932fa9e4066Sahrens }
4933fa9e4066Sahrens 
4934fa9e4066Sahrens /*
4935fc98fea5SBart Coddens  * "Read" the block at the specified DVA (in bp) via the
4936fa9e4066Sahrens  * cache.  If the block is found in the cache, invoke the provided
4937fa9e4066Sahrens  * callback immediately and return.  Note that the `zio' parameter
4938fa9e4066Sahrens  * in the callback will be NULL in this case, since no IO was
4939fa9e4066Sahrens  * required.  If the block is not in the cache pass the read request
4940fa9e4066Sahrens  * on to the spa with a substitute callback function, so that the
4941fa9e4066Sahrens  * requested block will be added to the cache.
4942fa9e4066Sahrens  *
4943fa9e4066Sahrens  * If a read request arrives for a block that has a read in-progress,
4944fa9e4066Sahrens  * either wait for the in-progress read to complete (and return the
4945fa9e4066Sahrens  * results); or, if this is a read with a "done" func, add a record
4946fa9e4066Sahrens  * to the read to invoke the "done" func when the read completes,
4947fa9e4066Sahrens  * and return; or just return.
4948fa9e4066Sahrens  *
4949fa9e4066Sahrens  * arc_read_done() will invoke all the requested "done" functions
4950fa9e4066Sahrens  * for readers of this block.
4951fa9e4066Sahrens  */
4952fa9e4066Sahrens int
49531b912ec7SGeorge Wilson arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
49547adb730bSGeorge Wilson     void *private, zio_priority_t priority, int zio_flags,
49557adb730bSGeorge Wilson     arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
4956fa9e4066Sahrens {
49575d7b4d43SMatthew Ahrens 	arc_buf_hdr_t *hdr = NULL;
49585d7b4d43SMatthew Ahrens 	kmutex_t *hash_lock = NULL;
4959fa94a07fSbrendan 	zio_t *rzio;
4960e9103aaeSGarrett D'Amore 	uint64_t guid = spa_load_guid(spa);
49615602294fSDan Kimmel 	boolean_t compressed_read = (zio_flags & ZIO_FLAG_RAW) != 0;
4962fa9e4066Sahrens 
49635d7b4d43SMatthew Ahrens 	ASSERT(!BP_IS_EMBEDDED(bp) ||
49645d7b4d43SMatthew Ahrens 	    BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
49655d7b4d43SMatthew Ahrens 
4966fa9e4066Sahrens top:
49675d7b4d43SMatthew Ahrens 	if (!BP_IS_EMBEDDED(bp)) {
49685d7b4d43SMatthew Ahrens 		/*
49695d7b4d43SMatthew Ahrens 		 * Embedded BP's have no DVA and require no I/O to "read".
49705d7b4d43SMatthew Ahrens 		 * Create an anonymous arc buf to back it.
49715d7b4d43SMatthew Ahrens 		 */
49725d7b4d43SMatthew Ahrens 		hdr = buf_hash_find(guid, bp, &hash_lock);
49735d7b4d43SMatthew Ahrens 	}
49745d7b4d43SMatthew Ahrens 
4975770499e1SDan Kimmel 	if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_pabd != NULL) {
4976dcbf3bd6SGeorge Wilson 		arc_buf_t *buf = NULL;
49777adb730bSGeorge Wilson 		*arc_flags |= ARC_FLAG_CACHED;
497813506d1eSmaybee 
4979fa9e4066Sahrens 		if (HDR_IO_IN_PROGRESS(hdr)) {
498013506d1eSmaybee 
4981cf6106c8SMatthew Ahrens 			if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
4982cf6106c8SMatthew Ahrens 			    priority == ZIO_PRIORITY_SYNC_READ) {
4983cf6106c8SMatthew Ahrens 				/*
4984cf6106c8SMatthew Ahrens 				 * This sync read must wait for an
4985cf6106c8SMatthew Ahrens 				 * in-progress async read (e.g. a predictive
4986cf6106c8SMatthew Ahrens 				 * prefetch).  Async reads are queued
4987cf6106c8SMatthew Ahrens 				 * separately at the vdev_queue layer, so
4988cf6106c8SMatthew Ahrens 				 * this is a form of priority inversion.
4989cf6106c8SMatthew Ahrens 				 * Ideally, we would "inherit" the demand
4990cf6106c8SMatthew Ahrens 				 * i/o's priority by moving the i/o from
4991cf6106c8SMatthew Ahrens 				 * the async queue to the synchronous queue,
4992cf6106c8SMatthew Ahrens 				 * but there is currently no mechanism to do
4993cf6106c8SMatthew Ahrens 				 * so.  Track this so that we can evaluate
4994cf6106c8SMatthew Ahrens 				 * the magnitude of this potential performance
4995cf6106c8SMatthew Ahrens 				 * problem.
4996cf6106c8SMatthew Ahrens 				 *
4997cf6106c8SMatthew Ahrens 				 * Note that if the prefetch i/o is already
4998cf6106c8SMatthew Ahrens 				 * active (has been issued to the device),
4999cf6106c8SMatthew Ahrens 				 * the prefetch improved performance, because
5000cf6106c8SMatthew Ahrens 				 * we issued it sooner than we would have
5001cf6106c8SMatthew Ahrens 				 * without the prefetch.
5002cf6106c8SMatthew Ahrens 				 */
5003cf6106c8SMatthew Ahrens 				DTRACE_PROBE1(arc__sync__wait__for__async,
5004cf6106c8SMatthew Ahrens 				    arc_buf_hdr_t *, hdr);
5005cf6106c8SMatthew Ahrens 				ARCSTAT_BUMP(arcstat_sync_wait_for_async);
5006cf6106c8SMatthew Ahrens 			}
5007cf6106c8SMatthew Ahrens 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5008dcbf3bd6SGeorge Wilson 				arc_hdr_clear_flags(hdr,
5009dcbf3bd6SGeorge Wilson 				    ARC_FLAG_PREDICTIVE_PREFETCH);
5010cf6106c8SMatthew Ahrens 			}
5011cf6106c8SMatthew Ahrens 
50127adb730bSGeorge Wilson 			if (*arc_flags & ARC_FLAG_WAIT) {
501389c86e32SChris Williamson 				cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
501413506d1eSmaybee 				mutex_exit(hash_lock);
501513506d1eSmaybee 				goto top;
501613506d1eSmaybee 			}
50177adb730bSGeorge Wilson 			ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
501813506d1eSmaybee 
501913506d1eSmaybee 			if (done) {
5020cf6106c8SMatthew Ahrens 				arc_callback_t *acb = NULL;
5021fa9e4066Sahrens 
5022fa9e4066Sahrens 				acb = kmem_zalloc(sizeof (arc_callback_t),
5023fa9e4066Sahrens 				    KM_SLEEP);
5024fa9e4066Sahrens 				acb->acb_done = done;
5025fa9e4066Sahrens 				acb->acb_private = private;
50265602294fSDan Kimmel 				acb->acb_compressed = compressed_read;
5027fa9e4066Sahrens 				if (pio != NULL)
5028fa9e4066Sahrens 					acb->acb_zio_dummy = zio_null(pio,
5029a3f829aeSBill Moore 					    spa, NULL, NULL, NULL, zio_flags);
5030fa9e4066Sahrens 
5031dcbf3bd6SGeorge Wilson 				ASSERT3P(acb->acb_done, !=, NULL);
503289c86e32SChris Williamson 				acb->acb_next = hdr->b_l1hdr.b_acb;
503389c86e32SChris Williamson 				hdr->b_l1hdr.b_acb = acb;
5034fa9e4066Sahrens 				mutex_exit(hash_lock);
5035fa9e4066Sahrens 				return (0);
5036fa9e4066Sahrens 			}
5037fa9e4066Sahrens 			mutex_exit(hash_lock);
5038fa9e4066Sahrens 			return (0);
5039fa9e4066Sahrens 		}
5040fa9e4066Sahrens 
504189c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
504289c86e32SChris Williamson 		    hdr->b_l1hdr.b_state == arc_mfu);
5043fa9e4066Sahrens 
5044ea8dc4b6Seschrock 		if (done) {
5045cf6106c8SMatthew Ahrens 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5046cf6106c8SMatthew Ahrens 				/*
5047cf6106c8SMatthew Ahrens 				 * This is a demand read which does not have to
5048cf6106c8SMatthew Ahrens 				 * wait for i/o because we did a predictive
5049cf6106c8SMatthew Ahrens 				 * prefetch i/o for it, which has completed.
5050cf6106c8SMatthew Ahrens 				 */
5051cf6106c8SMatthew Ahrens 				DTRACE_PROBE1(
5052cf6106c8SMatthew Ahrens 				    arc__demand__hit__predictive__prefetch,
5053cf6106c8SMatthew Ahrens 				    arc_buf_hdr_t *, hdr);
5054cf6106c8SMatthew Ahrens 				ARCSTAT_BUMP(
5055cf6106c8SMatthew Ahrens 				    arcstat_demand_hit_predictive_prefetch);
5056dcbf3bd6SGeorge Wilson 				arc_hdr_clear_flags(hdr,
5057dcbf3bd6SGeorge Wilson 				    ARC_FLAG_PREDICTIVE_PREFETCH);
5058cf6106c8SMatthew Ahrens 			}
5059dcbf3bd6SGeorge Wilson 			ASSERT(!BP_IS_EMBEDDED(bp) || !BP_IS_HOLE(bp));
5060dcbf3bd6SGeorge Wilson 
50615602294fSDan Kimmel 			/* Get a buf with the desired data in it. */
50625602294fSDan Kimmel 			VERIFY0(arc_buf_alloc_impl(hdr, private,
50635602294fSDan Kimmel 			    compressed_read, B_TRUE, &buf));
50647adb730bSGeorge Wilson 		} else if (*arc_flags & ARC_FLAG_PREFETCH &&
506589c86e32SChris Williamson 		    refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
5066dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5067fa9e4066Sahrens 		}
5068fa9e4066Sahrens 		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
506944eda4d7Smaybee 		arc_access(hdr, hash_lock);
50707adb730bSGeorge Wilson 		if (*arc_flags & ARC_FLAG_L2CACHE)
5071dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
507244eda4d7Smaybee 		mutex_exit(hash_lock);
507344cb6abcSbmc 		ARCSTAT_BUMP(arcstat_hits);
507489c86e32SChris Williamson 		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
507589c86e32SChris Williamson 		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
507644cb6abcSbmc 		    data, metadata, hits);
507744cb6abcSbmc 
5078fa9e4066Sahrens 		if (done)
5079fa9e4066Sahrens 			done(NULL, buf, private);
5080fa9e4066Sahrens 	} else {
5081dcbf3bd6SGeorge Wilson 		uint64_t lsize = BP_GET_LSIZE(bp);
5082dcbf3bd6SGeorge Wilson 		uint64_t psize = BP_GET_PSIZE(bp);
50835d7b4d43SMatthew Ahrens 		arc_callback_t *acb;
50843a737e0dSbrendan 		vdev_t *vd = NULL;
5085d5285caeSGeorge Wilson 		uint64_t addr = 0;
50865a98e54bSBrendan Gregg - Sun Microsystems 		boolean_t devw = B_FALSE;
5087dcbf3bd6SGeorge Wilson 		uint64_t size;
5088fa9e4066Sahrens 
5089fa9e4066Sahrens 		if (hdr == NULL) {
5090fa9e4066Sahrens 			/* this block is not in the cache */
50915d7b4d43SMatthew Ahrens 			arc_buf_hdr_t *exists = NULL;
5092ad23a2dbSjohansen 			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
5093dcbf3bd6SGeorge Wilson 			hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
5094dcbf3bd6SGeorge Wilson 			    BP_GET_COMPRESS(bp), type);
5095dcbf3bd6SGeorge Wilson 
50965d7b4d43SMatthew Ahrens 			if (!BP_IS_EMBEDDED(bp)) {
50975d7b4d43SMatthew Ahrens 				hdr->b_dva = *BP_IDENTITY(bp);
50985d7b4d43SMatthew Ahrens 				hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
50995d7b4d43SMatthew Ahrens 				exists = buf_hash_insert(hdr, &hash_lock);
51005d7b4d43SMatthew Ahrens 			}
51015d7b4d43SMatthew Ahrens 			if (exists != NULL) {
5102fa9e4066Sahrens 				/* somebody beat us to the hash insert */
5103fa9e4066Sahrens 				mutex_exit(hash_lock);
51043f9d6ad7SLin Ling 				buf_discard_identity(hdr);
5105dcbf3bd6SGeorge Wilson 				arc_hdr_destroy(hdr);
5106fa9e4066Sahrens 				goto top; /* restart the IO request */
5107fa9e4066Sahrens 			}
5108fa9e4066Sahrens 		} else {
510989c86e32SChris Williamson 			/*
511089c86e32SChris Williamson 			 * This block is in the ghost cache. If it was L2-only
511189c86e32SChris Williamson 			 * (and thus didn't have an L1 hdr), we realloc the
511289c86e32SChris Williamson 			 * header to add an L1 hdr.
511389c86e32SChris Williamson 			 */
511489c86e32SChris Williamson 			if (!HDR_HAS_L1HDR(hdr)) {
511589c86e32SChris Williamson 				hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
511689c86e32SChris Williamson 				    hdr_full_cache);
511789c86e32SChris Williamson 			}
5118770499e1SDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
511989c86e32SChris Williamson 			ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
5120ea8dc4b6Seschrock 			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
512189c86e32SChris Williamson 			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5122244781f1SPrakash Surya 			ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
51235602294fSDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
512413506d1eSmaybee 
5125cf6106c8SMatthew Ahrens 			/*
5126dcbf3bd6SGeorge Wilson 			 * This is a delicate dance that we play here.
5127dcbf3bd6SGeorge Wilson 			 * This hdr is in the ghost list so we access it
5128dcbf3bd6SGeorge Wilson 			 * to move it out of the ghost list before we
5129dcbf3bd6SGeorge Wilson 			 * initiate the read. If it's a prefetch then
5130dcbf3bd6SGeorge Wilson 			 * it won't have a callback so we'll remove the
5131dcbf3bd6SGeorge Wilson 			 * reference that arc_buf_alloc_impl() created. We
5132dcbf3bd6SGeorge Wilson 			 * do this after we've called arc_access() to
5133dcbf3bd6SGeorge Wilson 			 * avoid hitting an assert in remove_reference().
5134cf6106c8SMatthew Ahrens 			 */
51357e453561SWilliam Gorrell 			arc_access(hdr, hash_lock);
5136770499e1SDan Kimmel 			arc_hdr_alloc_pabd(hdr);
5137dcbf3bd6SGeorge Wilson 		}
5138770499e1SDan Kimmel 		ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
5139dcbf3bd6SGeorge Wilson 		size = arc_hdr_size(hdr);
5140dcbf3bd6SGeorge Wilson 
5141dcbf3bd6SGeorge Wilson 		/*
5142dcbf3bd6SGeorge Wilson 		 * If compression is enabled on the hdr, then will do
5143dcbf3bd6SGeorge Wilson 		 * RAW I/O and will store the compressed data in the hdr's
5144dcbf3bd6SGeorge Wilson 		 * data block. Otherwise, the hdr's data block will contain
5145dcbf3bd6SGeorge Wilson 		 * the uncompressed data.
5146dcbf3bd6SGeorge Wilson 		 */
5147dcbf3bd6SGeorge Wilson 		if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
5148dcbf3bd6SGeorge Wilson 			zio_flags |= ZIO_FLAG_RAW;
5149fa9e4066Sahrens 		}
5150fa9e4066Sahrens 
5151dcbf3bd6SGeorge Wilson 		if (*arc_flags & ARC_FLAG_PREFETCH)
5152dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5153dcbf3bd6SGeorge Wilson 		if (*arc_flags & ARC_FLAG_L2CACHE)
5154dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5155dcbf3bd6SGeorge Wilson 		if (BP_GET_LEVEL(bp) > 0)
5156dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_INDIRECT);
5157cf6106c8SMatthew Ahrens 		if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
5158dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_PREDICTIVE_PREFETCH);
515989c86e32SChris Williamson 		ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
51605614b00aSWilliam Gorrell 
5161fa9e4066Sahrens 		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
5162fa9e4066Sahrens 		acb->acb_done = done;
5163fa9e4066Sahrens 		acb->acb_private = private;
51645602294fSDan Kimmel 		acb->acb_compressed = compressed_read;
5165fa9e4066Sahrens 
5166dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
516789c86e32SChris Williamson 		hdr->b_l1hdr.b_acb = acb;
5168dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5169fa9e4066Sahrens 
517089c86e32SChris Williamson 		if (HDR_HAS_L2HDR(hdr) &&
517189c86e32SChris Williamson 		    (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
517289c86e32SChris Williamson 			devw = hdr->b_l2hdr.b_dev->l2ad_writing;
517389c86e32SChris Williamson 			addr = hdr->b_l2hdr.b_daddr;
5174e14bb325SJeff Bonwick 			/*
51755cabbc6bSPrashanth Sreenivasa 			 * Lock out L2ARC device removal.
5176e14bb325SJeff Bonwick 			 */
5177e14bb325SJeff Bonwick 			if (vdev_is_dead(vd) ||
5178e14bb325SJeff Bonwick 			    !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
5179e14bb325SJeff Bonwick 				vd = NULL;
51803a737e0dSbrendan 		}
51813a737e0dSbrendan 
5182dcbf3bd6SGeorge Wilson 		if (priority == ZIO_PRIORITY_ASYNC_READ)
5183dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5184dcbf3bd6SGeorge Wilson 		else
5185dcbf3bd6SGeorge Wilson 			arc_hdr_clear_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5186dcbf3bd6SGeorge Wilson 
51875d7b4d43SMatthew Ahrens 		if (hash_lock != NULL)
51885d7b4d43SMatthew Ahrens 			mutex_exit(hash_lock);
51893a737e0dSbrendan 
51903e30c24aSWill Andrews 		/*
51913e30c24aSWill Andrews 		 * At this point, we have a level 1 cache miss.  Try again in
51923e30c24aSWill Andrews 		 * L2ARC if possible.
51933e30c24aSWill Andrews 		 */
5194dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, lsize);
5195dcbf3bd6SGeorge Wilson 
51965c28183bSBrendan Gregg - Sun Microsystems 		DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
5197dcbf3bd6SGeorge Wilson 		    uint64_t, lsize, zbookmark_phys_t *, zb);
519844cb6abcSbmc 		ARCSTAT_BUMP(arcstat_misses);
519989c86e32SChris Williamson 		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
520089c86e32SChris Williamson 		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
520144cb6abcSbmc 		    data, metadata, misses);
5202ea8dc4b6Seschrock 
52035a98e54bSBrendan Gregg - Sun Microsystems 		if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
5204fa94a07fSbrendan 			/*
5205fa94a07fSbrendan 			 * Read from the L2ARC if the following are true:
52063a737e0dSbrendan 			 * 1. The L2ARC vdev was previously cached.
52073a737e0dSbrendan 			 * 2. This buffer still has L2ARC metadata.
52083a737e0dSbrendan 			 * 3. This buffer isn't currently writing to the L2ARC.
52093a737e0dSbrendan 			 * 4. The L2ARC entry wasn't evicted, which may
52103a737e0dSbrendan 			 *    also have invalidated the vdev.
52115a98e54bSBrendan Gregg - Sun Microsystems 			 * 5. This isn't prefetch and l2arc_noprefetch is set.
5212fa94a07fSbrendan 			 */
521389c86e32SChris Williamson 			if (HDR_HAS_L2HDR(hdr) &&
52145a98e54bSBrendan Gregg - Sun Microsystems 			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
52155a98e54bSBrendan Gregg - Sun Microsystems 			    !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
5216fa94a07fSbrendan 				l2arc_read_callback_t *cb;
5217403a8da7SAndriy Gapon 				abd_t *abd;
5218403a8da7SAndriy Gapon 				uint64_t asize;
5219fa94a07fSbrendan 
5220c5904d13Seschrock 				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
5221c5904d13Seschrock 				ARCSTAT_BUMP(arcstat_l2_hits);
5222c5904d13Seschrock 
5223fa94a07fSbrendan 				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
5224fa94a07fSbrendan 				    KM_SLEEP);
5225dcbf3bd6SGeorge Wilson 				cb->l2rcb_hdr = hdr;
5226fa94a07fSbrendan 				cb->l2rcb_bp = *bp;
5227fa94a07fSbrendan 				cb->l2rcb_zb = *zb;
52283baa08fcSek 				cb->l2rcb_flags = zio_flags;
5229fa94a07fSbrendan 
5230403a8da7SAndriy Gapon 				asize = vdev_psize_to_asize(vd, size);
5231403a8da7SAndriy Gapon 				if (asize != size) {
5232403a8da7SAndriy Gapon 					abd = abd_alloc_for_io(asize,
5233403a8da7SAndriy Gapon 					    HDR_ISTYPE_METADATA(hdr));
5234403a8da7SAndriy Gapon 					cb->l2rcb_abd = abd;
5235403a8da7SAndriy Gapon 				} else {
5236403a8da7SAndriy Gapon 					abd = hdr->b_l1hdr.b_pabd;
5237403a8da7SAndriy Gapon 				}
5238403a8da7SAndriy Gapon 
5239d5285caeSGeorge Wilson 				ASSERT(addr >= VDEV_LABEL_START_SIZE &&
5240403a8da7SAndriy Gapon 				    addr + asize <= vd->vdev_psize -
5241d5285caeSGeorge Wilson 				    VDEV_LABEL_END_SIZE);
5242d5285caeSGeorge Wilson 
5243fa94a07fSbrendan 				/*
5244e14bb325SJeff Bonwick 				 * l2arc read.  The SCL_L2ARC lock will be
5245e14bb325SJeff Bonwick 				 * released by l2arc_read_done().
5246aad02571SSaso Kiselkov 				 * Issue a null zio if the underlying buffer
5247aad02571SSaso Kiselkov 				 * was squashed to zero size by compression.
5248fa94a07fSbrendan 				 */
5249dcbf3bd6SGeorge Wilson 				ASSERT3U(HDR_GET_COMPRESS(hdr), !=,
5250dcbf3bd6SGeorge Wilson 				    ZIO_COMPRESS_EMPTY);
5251dcbf3bd6SGeorge Wilson 				rzio = zio_read_phys(pio, vd, addr,
5252403a8da7SAndriy Gapon 				    asize, abd,
5253dcbf3bd6SGeorge Wilson 				    ZIO_CHECKSUM_OFF,
5254dcbf3bd6SGeorge Wilson 				    l2arc_read_done, cb, priority,
5255dcbf3bd6SGeorge Wilson 				    zio_flags | ZIO_FLAG_DONT_CACHE |
5256dcbf3bd6SGeorge Wilson 				    ZIO_FLAG_CANFAIL |
5257dcbf3bd6SGeorge Wilson 				    ZIO_FLAG_DONT_PROPAGATE |
5258dcbf3bd6SGeorge Wilson 				    ZIO_FLAG_DONT_RETRY, B_FALSE);
5259fa94a07fSbrendan 				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
5260fa94a07fSbrendan 				    zio_t *, rzio);
5261dcbf3bd6SGeorge Wilson 				ARCSTAT_INCR(arcstat_l2_read_bytes, size);
5262fa94a07fSbrendan 
52637adb730bSGeorge Wilson 				if (*arc_flags & ARC_FLAG_NOWAIT) {
52643a737e0dSbrendan 					zio_nowait(rzio);
52653a737e0dSbrendan 					return (0);
52663a737e0dSbrendan 				}
5267fa94a07fSbrendan 
52687adb730bSGeorge Wilson 				ASSERT(*arc_flags & ARC_FLAG_WAIT);
52693a737e0dSbrendan 				if (zio_wait(rzio) == 0)
52703a737e0dSbrendan 					return (0);
52713a737e0dSbrendan 
52723a737e0dSbrendan 				/* l2arc read error; goto zio_read() */
5273fa94a07fSbrendan 			} else {
5274fa94a07fSbrendan 				DTRACE_PROBE1(l2arc__miss,
5275fa94a07fSbrendan 				    arc_buf_hdr_t *, hdr);
5276fa94a07fSbrendan 				ARCSTAT_BUMP(arcstat_l2_misses);
5277fa94a07fSbrendan 				if (HDR_L2_WRITING(hdr))
5278fa94a07fSbrendan 					ARCSTAT_BUMP(arcstat_l2_rw_clash);
5279e14bb325SJeff Bonwick 				spa_config_exit(spa, SCL_L2ARC, vd);
5280fa94a07fSbrendan 			}
52815a98e54bSBrendan Gregg - Sun Microsystems 		} else {
528276a25fafSBill Moore 			if (vd != NULL)
528376a25fafSBill Moore 				spa_config_exit(spa, SCL_L2ARC, vd);
52845a98e54bSBrendan Gregg - Sun Microsystems 			if (l2arc_ndev != 0) {
52855a98e54bSBrendan Gregg - Sun Microsystems 				DTRACE_PROBE1(l2arc__miss,
52865a98e54bSBrendan Gregg - Sun Microsystems 				    arc_buf_hdr_t *, hdr);
52875a98e54bSBrendan Gregg - Sun Microsystems 				ARCSTAT_BUMP(arcstat_l2_misses);
52885a98e54bSBrendan Gregg - Sun Microsystems 			}
5289fa94a07fSbrendan 		}
5290c5904d13Seschrock 
5291770499e1SDan Kimmel 		rzio = zio_read(pio, spa, bp, hdr->b_l1hdr.b_pabd, size,
5292dcbf3bd6SGeorge Wilson 		    arc_read_done, hdr, priority, zio_flags, zb);
5293fa9e4066Sahrens 
52947adb730bSGeorge Wilson 		if (*arc_flags & ARC_FLAG_WAIT)
5295fa9e4066Sahrens 			return (zio_wait(rzio));
5296fa9e4066Sahrens 
52977adb730bSGeorge Wilson 		ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
5298fa9e4066Sahrens 		zio_nowait(rzio);
5299fa9e4066Sahrens 	}
5300fa9e4066Sahrens 	return (0);
5301fa9e4066Sahrens }
5302fa9e4066Sahrens 
53036e6d5868SMatthew Ahrens /*
53046e6d5868SMatthew Ahrens  * Notify the arc that a block was freed, and thus will never be used again.
53056e6d5868SMatthew Ahrens  */
53066e6d5868SMatthew Ahrens void
53076e6d5868SMatthew Ahrens arc_freed(spa_t *spa, const blkptr_t *bp)
53086e6d5868SMatthew Ahrens {
53096e6d5868SMatthew Ahrens 	arc_buf_hdr_t *hdr;
53106e6d5868SMatthew Ahrens 	kmutex_t *hash_lock;
53116e6d5868SMatthew Ahrens 	uint64_t guid = spa_load_guid(spa);
53126e6d5868SMatthew Ahrens 
53135d7b4d43SMatthew Ahrens 	ASSERT(!BP_IS_EMBEDDED(bp));
53145d7b4d43SMatthew Ahrens 
53155d7b4d43SMatthew Ahrens 	hdr = buf_hash_find(guid, bp, &hash_lock);
53166e6d5868SMatthew Ahrens 	if (hdr == NULL)
53176e6d5868SMatthew Ahrens 		return;
53186e6d5868SMatthew Ahrens 
5319dcbf3bd6SGeorge Wilson 	/*
5320dcbf3bd6SGeorge Wilson 	 * We might be trying to free a block that is still doing I/O
5321dcbf3bd6SGeorge Wilson 	 * (i.e. prefetch) or has a reference (i.e. a dedup-ed,
5322dcbf3bd6SGeorge Wilson 	 * dmu_sync-ed block). If this block is being prefetched, then it
5323dcbf3bd6SGeorge Wilson 	 * would still have the ARC_FLAG_IO_IN_PROGRESS flag set on the hdr
5324dcbf3bd6SGeorge Wilson 	 * until the I/O completes. A block may also have a reference if it is
5325dcbf3bd6SGeorge Wilson 	 * part of a dedup-ed, dmu_synced write. The dmu_sync() function would
5326dcbf3bd6SGeorge Wilson 	 * have written the new block to its final resting place on disk but
5327dcbf3bd6SGeorge Wilson 	 * without the dedup flag set. This would have left the hdr in the MRU
5328dcbf3bd6SGeorge Wilson 	 * state and discoverable. When the txg finally syncs it detects that
5329dcbf3bd6SGeorge Wilson 	 * the block was overridden in open context and issues an override I/O.
5330dcbf3bd6SGeorge Wilson 	 * Since this is a dedup block, the override I/O will determine if the
5331dcbf3bd6SGeorge Wilson 	 * block is already in the DDT. If so, then it will replace the io_bp
5332dcbf3bd6SGeorge Wilson 	 * with the bp from the DDT and allow the I/O to finish. When the I/O
5333dcbf3bd6SGeorge Wilson 	 * reaches the done callback, dbuf_write_override_done, it will
5334dcbf3bd6SGeorge Wilson 	 * check to see if the io_bp and io_bp_override are identical.
5335dcbf3bd6SGeorge Wilson 	 * If they are not, then it indicates that the bp was replaced with
5336dcbf3bd6SGeorge Wilson 	 * the bp in the DDT and the override bp is freed. This allows
5337dcbf3bd6SGeorge Wilson 	 * us to arrive here with a reference on a block that is being
5338dcbf3bd6SGeorge Wilson 	 * freed. So if we have an I/O in progress, or a reference to
5339dcbf3bd6SGeorge Wilson 	 * this hdr, then we don't destroy the hdr.
5340dcbf3bd6SGeorge Wilson 	 */
5341dcbf3bd6SGeorge Wilson 	if (!HDR_HAS_L1HDR(hdr) || (!HDR_IO_IN_PROGRESS(hdr) &&
5342dcbf3bd6SGeorge Wilson 	    refcount_is_zero(&hdr->b_l1hdr.b_refcnt))) {
5343dcbf3bd6SGeorge Wilson 		arc_change_state(arc_anon, hdr, hash_lock);
5344dcbf3bd6SGeorge Wilson 		arc_hdr_destroy(hdr);
53456e6d5868SMatthew Ahrens 		mutex_exit(hash_lock);
5346bbfa8ea8SMatthew Ahrens 	} else {
5347dcbf3bd6SGeorge Wilson 		mutex_exit(hash_lock);
5348ea8dc4b6Seschrock 	}
5349dd6ef538Smaybee 
5350ea8dc4b6Seschrock }
5351ea8dc4b6Seschrock 
5352fa9e4066Sahrens /*
53533e30c24aSWill Andrews  * Release this buffer from the cache, making it an anonymous buffer.  This
53543e30c24aSWill Andrews  * must be done after a read and prior to modifying the buffer contents.
5355fa9e4066Sahrens  * If the buffer has more than one reference, we must make
5356088f3894Sahrens  * a new hdr for the buffer.
5357fa9e4066Sahrens  */
5358fa9e4066Sahrens void
5359fa9e4066Sahrens arc_release(arc_buf_t *buf, void *tag)
5360fa9e4066Sahrens {
536189c86e32SChris Williamson 	arc_buf_hdr_t *hdr = buf->b_hdr;
5362fa9e4066Sahrens 
53633f9d6ad7SLin Ling 	/*
53643f9d6ad7SLin Ling 	 * It would be nice to assert that if it's DMU metadata (level >
53653f9d6ad7SLin Ling 	 * 0 || it's the dnode file), then it must be syncing context.
53663f9d6ad7SLin Ling 	 * But we don't know that information at this level.
53673f9d6ad7SLin Ling 	 */
53683f9d6ad7SLin Ling 
53693f9d6ad7SLin Ling 	mutex_enter(&buf->b_evict_lock);
53706f83844dSMark Maybee 
5371244781f1SPrakash Surya 	ASSERT(HDR_HAS_L1HDR(hdr));
5372244781f1SPrakash Surya 
537389c86e32SChris Williamson 	/*
537489c86e32SChris Williamson 	 * We don't grab the hash lock prior to this check, because if
537589c86e32SChris Williamson 	 * the buffer's header is in the arc_anon state, it won't be
537689c86e32SChris Williamson 	 * linked into the hash table.
537789c86e32SChris Williamson 	 */
537889c86e32SChris Williamson 	if (hdr->b_l1hdr.b_state == arc_anon) {
537989c86e32SChris Williamson 		mutex_exit(&buf->b_evict_lock);
538089c86e32SChris Williamson 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
538189c86e32SChris Williamson 		ASSERT(!HDR_IN_HASH_TABLE(hdr));
538289c86e32SChris Williamson 		ASSERT(!HDR_HAS_L2HDR(hdr));
5383dcbf3bd6SGeorge Wilson 		ASSERT(HDR_EMPTY(hdr));
5384fa9e4066Sahrens 
5385dcbf3bd6SGeorge Wilson 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
538689c86e32SChris Williamson 		ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
538789c86e32SChris Williamson 		ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
538889c86e32SChris Williamson 
538989c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = 0;
5390dcbf3bd6SGeorge Wilson 
5391dcbf3bd6SGeorge Wilson 		/*
5392dcbf3bd6SGeorge Wilson 		 * If the buf is being overridden then it may already
5393dcbf3bd6SGeorge Wilson 		 * have a hdr that is not empty.
5394dcbf3bd6SGeorge Wilson 		 */
5395dcbf3bd6SGeorge Wilson 		buf_discard_identity(hdr);
539689c86e32SChris Williamson 		arc_buf_thaw(buf);
539789c86e32SChris Williamson 
539889c86e32SChris Williamson 		return;
5399fa9e4066Sahrens 	}
5400fa9e4066Sahrens 
540189c86e32SChris Williamson 	kmutex_t *hash_lock = HDR_LOCK(hdr);
540289c86e32SChris Williamson 	mutex_enter(hash_lock);
540389c86e32SChris Williamson 
540489c86e32SChris Williamson 	/*
540589c86e32SChris Williamson 	 * This assignment is only valid as long as the hash_lock is
540689c86e32SChris Williamson 	 * held, we must be careful not to reference state or the
540789c86e32SChris Williamson 	 * b_state field after dropping the lock.
540889c86e32SChris Williamson 	 */
540989c86e32SChris Williamson 	arc_state_t *state = hdr->b_l1hdr.b_state;
541089c86e32SChris Williamson 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
541189c86e32SChris Williamson 	ASSERT3P(state, !=, arc_anon);
541289c86e32SChris Williamson 
541389c86e32SChris Williamson 	/* this buffer is not on any list */
54145602294fSDan Kimmel 	ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), >, 0);
541589c86e32SChris Williamson 
541689c86e32SChris Williamson 	if (HDR_HAS_L2HDR(hdr)) {
541789c86e32SChris Williamson 		mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
5418244781f1SPrakash Surya 
5419244781f1SPrakash Surya 		/*
5420a52fc310SPrakash Surya 		 * We have to recheck this conditional again now that
5421a52fc310SPrakash Surya 		 * we're holding the l2ad_mtx to prevent a race with
5422a52fc310SPrakash Surya 		 * another thread which might be concurrently calling
5423a52fc310SPrakash Surya 		 * l2arc_evict(). In that case, l2arc_evict() might have
5424a52fc310SPrakash Surya 		 * destroyed the header's L2 portion as we were waiting
5425a52fc310SPrakash Surya 		 * to acquire the l2ad_mtx.
5426244781f1SPrakash Surya 		 */
5427a52fc310SPrakash Surya 		if (HDR_HAS_L2HDR(hdr))
5428a52fc310SPrakash Surya 			arc_hdr_l2hdr_destroy(hdr);
5429244781f1SPrakash Surya 
543089c86e32SChris Williamson 		mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
54316f83844dSMark Maybee 	}
54326f83844dSMark Maybee 
5433ea8dc4b6Seschrock 	/*
5434ea8dc4b6Seschrock 	 * Do we have more than one buf?
5435ea8dc4b6Seschrock 	 */
5436dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_bufcnt > 1) {
5437fa9e4066Sahrens 		arc_buf_hdr_t *nhdr;
5438ac05c741SMark Maybee 		uint64_t spa = hdr->b_spa;
5439dcbf3bd6SGeorge Wilson 		uint64_t psize = HDR_GET_PSIZE(hdr);
5440dcbf3bd6SGeorge Wilson 		uint64_t lsize = HDR_GET_LSIZE(hdr);
5441dcbf3bd6SGeorge Wilson 		enum zio_compress compress = HDR_GET_COMPRESS(hdr);
544289c86e32SChris Williamson 		arc_buf_contents_t type = arc_buf_type(hdr);
5443dcbf3bd6SGeorge Wilson 		VERIFY3U(hdr->b_type, ==, type);
5444fa9e4066Sahrens 
544589c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
5446dcbf3bd6SGeorge Wilson 		(void) remove_reference(hdr, hash_lock, tag);
5447dcbf3bd6SGeorge Wilson 
54485602294fSDan Kimmel 		if (arc_buf_is_shared(buf) && !ARC_BUF_COMPRESSED(buf)) {
5449dcbf3bd6SGeorge Wilson 			ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
5450dcbf3bd6SGeorge Wilson 			ASSERT(ARC_BUF_LAST(buf));
5451dcbf3bd6SGeorge Wilson 		}
5452dcbf3bd6SGeorge Wilson 
5453fa9e4066Sahrens 		/*
54543f9d6ad7SLin Ling 		 * Pull the data off of this hdr and attach it to
5455dcbf3bd6SGeorge Wilson 		 * a new anonymous hdr. Also find the last buffer
5456dcbf3bd6SGeorge Wilson 		 * in the hdr's buffer list.
5457fa9e4066Sahrens 		 */
54585602294fSDan Kimmel 		arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
5459dcbf3bd6SGeorge Wilson 		ASSERT3P(lastbuf, !=, NULL);
5460dcbf3bd6SGeorge Wilson 
5461dcbf3bd6SGeorge Wilson 		/*
5462dcbf3bd6SGeorge Wilson 		 * If the current arc_buf_t and the hdr are sharing their data
54635602294fSDan Kimmel 		 * buffer, then we must stop sharing that block.
5464dcbf3bd6SGeorge Wilson 		 */
5465dcbf3bd6SGeorge Wilson 		if (arc_buf_is_shared(buf)) {
5466dcbf3bd6SGeorge Wilson 			VERIFY(!arc_buf_is_shared(lastbuf));
5467ea8dc4b6Seschrock 
5468dcbf3bd6SGeorge Wilson 			/*
5469dcbf3bd6SGeorge Wilson 			 * First, sever the block sharing relationship between
54705602294fSDan Kimmel 			 * buf and the arc_buf_hdr_t.
5471dcbf3bd6SGeorge Wilson 			 */
5472dcbf3bd6SGeorge Wilson 			arc_unshare_buf(hdr, buf);
54735602294fSDan Kimmel 
54745602294fSDan Kimmel 			/*
5475770499e1SDan Kimmel 			 * Now we need to recreate the hdr's b_pabd. Since we
54765602294fSDan Kimmel 			 * have lastbuf handy, we try to share with it, but if
5477770499e1SDan Kimmel 			 * we can't then we allocate a new b_pabd and copy the
54785602294fSDan Kimmel 			 * data from buf into it.
54795602294fSDan Kimmel 			 */
54805602294fSDan Kimmel 			if (arc_can_share(hdr, lastbuf)) {
54815602294fSDan Kimmel 				arc_share_buf(hdr, lastbuf);
54825602294fSDan Kimmel 			} else {
5483770499e1SDan Kimmel 				arc_hdr_alloc_pabd(hdr);
5484770499e1SDan Kimmel 				abd_copy_from_buf(hdr->b_l1hdr.b_pabd,
5485770499e1SDan Kimmel 				    buf->b_data, psize);
54865602294fSDan Kimmel 			}
5487dcbf3bd6SGeorge Wilson 			VERIFY3P(lastbuf->b_data, !=, NULL);
5488dcbf3bd6SGeorge Wilson 		} else if (HDR_SHARED_DATA(hdr)) {
54895602294fSDan Kimmel 			/*
54905602294fSDan Kimmel 			 * Uncompressed shared buffers are always at the end
54915602294fSDan Kimmel 			 * of the list. Compressed buffers don't have the
54925602294fSDan Kimmel 			 * same requirements. This makes it hard to
54935602294fSDan Kimmel 			 * simply assert that the lastbuf is shared so
54945602294fSDan Kimmel 			 * we rely on the hdr's compression flags to determine
54955602294fSDan Kimmel 			 * if we have a compressed, shared buffer.
54965602294fSDan Kimmel 			 */
54975602294fSDan Kimmel 			ASSERT(arc_buf_is_shared(lastbuf) ||
54985602294fSDan Kimmel 			    HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
54995602294fSDan Kimmel 			ASSERT(!ARC_BUF_SHARED(buf));
5500dcbf3bd6SGeorge Wilson 		}
5501770499e1SDan Kimmel 		ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
550289c86e32SChris Williamson 		ASSERT3P(state, !=, arc_l2c_only);
55032fd872a7SPrakash Surya 
5504dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_size,
55055602294fSDan Kimmel 		    arc_buf_size(buf), buf);
55062fd872a7SPrakash Surya 
550789c86e32SChris Williamson 		if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
550889c86e32SChris Williamson 			ASSERT3P(state, !=, arc_l2c_only);
5509dcbf3bd6SGeorge Wilson 			(void) refcount_remove_many(&state->arcs_esize[type],
55105602294fSDan Kimmel 			    arc_buf_size(buf), buf);
5511ea8dc4b6Seschrock 		}
55129253d63dSGeorge Wilson 
5513dcbf3bd6SGeorge Wilson 		hdr->b_l1hdr.b_bufcnt -= 1;
5514c717a561Smaybee 		arc_cksum_verify(buf);
5515cd1c8b85SMatthew Ahrens 		arc_buf_unwatch(buf);
5516ea8dc4b6Seschrock 
5517fa9e4066Sahrens 		mutex_exit(hash_lock);
5518fa9e4066Sahrens 
5519dcbf3bd6SGeorge Wilson 		/*
5520770499e1SDan Kimmel 		 * Allocate a new hdr. The new hdr will contain a b_pabd
5521dcbf3bd6SGeorge Wilson 		 * buffer which will be freed in arc_write().
5522dcbf3bd6SGeorge Wilson 		 */
5523dcbf3bd6SGeorge Wilson 		nhdr = arc_hdr_alloc(spa, psize, lsize, compress, type);
5524dcbf3bd6SGeorge Wilson 		ASSERT3P(nhdr->b_l1hdr.b_buf, ==, NULL);
5525dcbf3bd6SGeorge Wilson 		ASSERT0(nhdr->b_l1hdr.b_bufcnt);
5526dcbf3bd6SGeorge Wilson 		ASSERT0(refcount_count(&nhdr->b_l1hdr.b_refcnt));
5527dcbf3bd6SGeorge Wilson 		VERIFY3U(nhdr->b_type, ==, type);
5528dcbf3bd6SGeorge Wilson 		ASSERT(!HDR_SHARED_DATA(nhdr));
552989c86e32SChris Williamson 
553089c86e32SChris Williamson 		nhdr->b_l1hdr.b_buf = buf;
5531dcbf3bd6SGeorge Wilson 		nhdr->b_l1hdr.b_bufcnt = 1;
553289c86e32SChris Williamson 		(void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
5533af2c4821Smaybee 		buf->b_hdr = nhdr;
5534dcbf3bd6SGeorge Wilson 
55353f9d6ad7SLin Ling 		mutex_exit(&buf->b_evict_lock);
5536dcbf3bd6SGeorge Wilson 		(void) refcount_add_many(&arc_anon->arcs_size,
55375602294fSDan Kimmel 		    arc_buf_size(buf), buf);
5538fa9e4066Sahrens 	} else {
55393f9d6ad7SLin Ling 		mutex_exit(&buf->b_evict_lock);
554089c86e32SChris Williamson 		ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
5541244781f1SPrakash Surya 		/* protected by hash lock, or hdr is on arc_anon */
5542244781f1SPrakash Surya 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
5543fa9e4066Sahrens 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
554489c86e32SChris Williamson 		arc_change_state(arc_anon, hdr, hash_lock);
554589c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = 0;
554689c86e32SChris Williamson 		mutex_exit(hash_lock);
5547fa94a07fSbrendan 
55483f9d6ad7SLin Ling 		buf_discard_identity(hdr);
5549c717a561Smaybee 		arc_buf_thaw(buf);
5550fa9e4066Sahrens 	}
5551fa9e4066Sahrens }
5552fa9e4066Sahrens 
5553fa9e4066Sahrens int
5554fa9e4066Sahrens arc_released(arc_buf_t *buf)
5555fa9e4066Sahrens {
55566f83844dSMark Maybee 	int released;
55576f83844dSMark Maybee 
55583f9d6ad7SLin Ling 	mutex_enter(&buf->b_evict_lock);
555989c86e32SChris Williamson 	released = (buf->b_data != NULL &&
556089c86e32SChris Williamson 	    buf->b_hdr->b_l1hdr.b_state == arc_anon);
55613f9d6ad7SLin Ling 	mutex_exit(&buf->b_evict_lock);
55626f83844dSMark Maybee 	return (released);
5563ea8dc4b6Seschrock }
5564ea8dc4b6Seschrock 
5565ea8dc4b6Seschrock #ifdef ZFS_DEBUG
5566ea8dc4b6Seschrock int
5567ea8dc4b6Seschrock arc_referenced(arc_buf_t *buf)
5568ea8dc4b6Seschrock {
55696f83844dSMark Maybee 	int referenced;
55706f83844dSMark Maybee 
55713f9d6ad7SLin Ling 	mutex_enter(&buf->b_evict_lock);
557289c86e32SChris Williamson 	referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
55733f9d6ad7SLin Ling 	mutex_exit(&buf->b_evict_lock);
55746f83844dSMark Maybee 	return (referenced);
5575ea8dc4b6Seschrock }
5576ea8dc4b6Seschrock #endif
5577ea8dc4b6Seschrock 
5578c717a561Smaybee static void
5579c717a561Smaybee arc_write_ready(zio_t *zio)
5580c717a561Smaybee {
5581c717a561Smaybee 	arc_write_callback_t *callback = zio->io_private;
5582c717a561Smaybee 	arc_buf_t *buf = callback->awcb_buf;
55830a4e9518Sgw 	arc_buf_hdr_t *hdr = buf->b_hdr;
5584dcbf3bd6SGeorge Wilson 	uint64_t psize = BP_IS_HOLE(zio->io_bp) ? 0 : BP_GET_PSIZE(zio->io_bp);
5585c717a561Smaybee 
558689c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
558789c86e32SChris Williamson 	ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
5588dcbf3bd6SGeorge Wilson 	ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
5589e14bb325SJeff Bonwick 
55900a4e9518Sgw 	/*
5591dcbf3bd6SGeorge Wilson 	 * If we're reexecuting this zio because the pool suspended, then
5592dcbf3bd6SGeorge Wilson 	 * cleanup any state that was previously set the first time the
55935602294fSDan Kimmel 	 * callback was invoked.
55940a4e9518Sgw 	 */
5595dcbf3bd6SGeorge Wilson 	if (zio->io_flags & ZIO_FLAG_REEXECUTED) {
5596dcbf3bd6SGeorge Wilson 		arc_cksum_free(hdr);
5597dcbf3bd6SGeorge Wilson 		arc_buf_unwatch(buf);
5598770499e1SDan Kimmel 		if (hdr->b_l1hdr.b_pabd != NULL) {
5599dcbf3bd6SGeorge Wilson 			if (arc_buf_is_shared(buf)) {
5600dcbf3bd6SGeorge Wilson 				arc_unshare_buf(hdr, buf);
5601dcbf3bd6SGeorge Wilson 			} else {
5602770499e1SDan Kimmel 				arc_hdr_free_pabd(hdr);
5603dcbf3bd6SGeorge Wilson 			}
56040a4e9518Sgw 		}
56050a4e9518Sgw 	}
5606770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
5607dcbf3bd6SGeorge Wilson 	ASSERT(!HDR_SHARED_DATA(hdr));
5608dcbf3bd6SGeorge Wilson 	ASSERT(!arc_buf_is_shared(buf));
5609dcbf3bd6SGeorge Wilson 
5610dcbf3bd6SGeorge Wilson 	callback->awcb_ready(zio, buf, callback->awcb_private);
5611dcbf3bd6SGeorge Wilson 
5612dcbf3bd6SGeorge Wilson 	if (HDR_IO_IN_PROGRESS(hdr))
5613dcbf3bd6SGeorge Wilson 		ASSERT(zio->io_flags & ZIO_FLAG_REEXECUTED);
5614dcbf3bd6SGeorge Wilson 
5615dcbf3bd6SGeorge Wilson 	arc_cksum_compute(buf);
5616dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5617dcbf3bd6SGeorge Wilson 
5618dcbf3bd6SGeorge Wilson 	enum zio_compress compress;
5619dcbf3bd6SGeorge Wilson 	if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
5620dcbf3bd6SGeorge Wilson 		compress = ZIO_COMPRESS_OFF;
5621dcbf3bd6SGeorge Wilson 	} else {
5622dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(zio->io_bp));
5623dcbf3bd6SGeorge Wilson 		compress = BP_GET_COMPRESS(zio->io_bp);
5624dcbf3bd6SGeorge Wilson 	}
5625dcbf3bd6SGeorge Wilson 	HDR_SET_PSIZE(hdr, psize);
5626dcbf3bd6SGeorge Wilson 	arc_hdr_set_compress(hdr, compress);
5627dcbf3bd6SGeorge Wilson 
5628770499e1SDan Kimmel 
5629dcbf3bd6SGeorge Wilson 	/*
5630770499e1SDan Kimmel 	 * Fill the hdr with data. If the hdr is compressed, the data we want
5631770499e1SDan Kimmel 	 * is available from the zio, otherwise we can take it from the buf.
5632770499e1SDan Kimmel 	 *
5633770499e1SDan Kimmel 	 * We might be able to share the buf's data with the hdr here. However,
5634770499e1SDan Kimmel 	 * doing so would cause the ARC to be full of linear ABDs if we write a
5635770499e1SDan Kimmel 	 * lot of shareable data. As a compromise, we check whether scattered
5636770499e1SDan Kimmel 	 * ABDs are allowed, and assume that if they are then the user wants
5637770499e1SDan Kimmel 	 * the ARC to be primarily filled with them regardless of the data being
5638770499e1SDan Kimmel 	 * written. Therefore, if they're allowed then we allocate one and copy
5639770499e1SDan Kimmel 	 * the data into it; otherwise, we share the data directly if we can.
5640dcbf3bd6SGeorge Wilson 	 */
5641770499e1SDan Kimmel 	if (zfs_abd_scatter_enabled || !arc_can_share(hdr, buf)) {
5642770499e1SDan Kimmel 		arc_hdr_alloc_pabd(hdr);
5643770499e1SDan Kimmel 
5644770499e1SDan Kimmel 		/*
5645770499e1SDan Kimmel 		 * Ideally, we would always copy the io_abd into b_pabd, but the
5646770499e1SDan Kimmel 		 * user may have disabled compressed ARC, thus we must check the
5647770499e1SDan Kimmel 		 * hdr's compression setting rather than the io_bp's.
5648770499e1SDan Kimmel 		 */
5649770499e1SDan Kimmel 		if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
5650770499e1SDan Kimmel 			ASSERT3U(BP_GET_COMPRESS(zio->io_bp), !=,
5651770499e1SDan Kimmel 			    ZIO_COMPRESS_OFF);
5652770499e1SDan Kimmel 			ASSERT3U(psize, >, 0);
5653770499e1SDan Kimmel 
5654770499e1SDan Kimmel 			abd_copy(hdr->b_l1hdr.b_pabd, zio->io_abd, psize);
5655770499e1SDan Kimmel 		} else {
5656770499e1SDan Kimmel 			ASSERT3U(zio->io_orig_size, ==, arc_hdr_size(hdr));
5657770499e1SDan Kimmel 
5658770499e1SDan Kimmel 			abd_copy_from_buf(hdr->b_l1hdr.b_pabd, buf->b_data,
5659770499e1SDan Kimmel 			    arc_buf_size(buf));
5660770499e1SDan Kimmel 		}
5661dcbf3bd6SGeorge Wilson 	} else {
5662770499e1SDan Kimmel 		ASSERT3P(buf->b_data, ==, abd_to_buf(zio->io_orig_abd));
56635602294fSDan Kimmel 		ASSERT3U(zio->io_orig_size, ==, arc_buf_size(buf));
5664dcbf3bd6SGeorge Wilson 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
5665dcbf3bd6SGeorge Wilson 
5666dcbf3bd6SGeorge Wilson 		arc_share_buf(hdr, buf);
5667dcbf3bd6SGeorge Wilson 	}
5668770499e1SDan Kimmel 
5669dcbf3bd6SGeorge Wilson 	arc_hdr_verify(hdr, zio->io_bp);
5670c717a561Smaybee }
5671c717a561Smaybee 
56728df0bcf0SPaul Dagnelie static void
56738df0bcf0SPaul Dagnelie arc_write_children_ready(zio_t *zio)
56748df0bcf0SPaul Dagnelie {
56758df0bcf0SPaul Dagnelie 	arc_write_callback_t *callback = zio->io_private;
56768df0bcf0SPaul Dagnelie 	arc_buf_t *buf = callback->awcb_buf;
56778df0bcf0SPaul Dagnelie 
56788df0bcf0SPaul Dagnelie 	callback->awcb_children_ready(zio, buf, callback->awcb_private);
56798df0bcf0SPaul Dagnelie }
56808df0bcf0SPaul Dagnelie 
568169962b56SMatthew Ahrens /*
568269962b56SMatthew Ahrens  * The SPA calls this callback for each physical write that happens on behalf
568369962b56SMatthew Ahrens  * of a logical write.  See the comment in dbuf_write_physdone() for details.
568469962b56SMatthew Ahrens  */
568569962b56SMatthew Ahrens static void
568669962b56SMatthew Ahrens arc_write_physdone(zio_t *zio)
568769962b56SMatthew Ahrens {
568869962b56SMatthew Ahrens 	arc_write_callback_t *cb = zio->io_private;
568969962b56SMatthew Ahrens 	if (cb->awcb_physdone != NULL)
569069962b56SMatthew Ahrens 		cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
569169962b56SMatthew Ahrens }
569269962b56SMatthew Ahrens 
5693fa9e4066Sahrens static void
5694fa9e4066Sahrens arc_write_done(zio_t *zio)
5695fa9e4066Sahrens {
5696c717a561Smaybee 	arc_write_callback_t *callback = zio->io_private;
5697c717a561Smaybee 	arc_buf_t *buf = callback->awcb_buf;
5698c717a561Smaybee 	arc_buf_hdr_t *hdr = buf->b_hdr;
5699fa9e4066Sahrens 
5700dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5701b24ab676SJeff Bonwick 
5702b24ab676SJeff Bonwick 	if (zio->io_error == 0) {
5703dcbf3bd6SGeorge Wilson 		arc_hdr_verify(hdr, zio->io_bp);
5704dcbf3bd6SGeorge Wilson 
57055d7b4d43SMatthew Ahrens 		if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
570643466aaeSMax Grossman 			buf_discard_identity(hdr);
570743466aaeSMax Grossman 		} else {
570843466aaeSMax Grossman 			hdr->b_dva = *BP_IDENTITY(zio->io_bp);
570943466aaeSMax Grossman 			hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
571043466aaeSMax Grossman 		}
5711b24ab676SJeff Bonwick 	} else {
5712dcbf3bd6SGeorge Wilson 		ASSERT(HDR_EMPTY(hdr));
5713b24ab676SJeff Bonwick 	}
5714fa9e4066Sahrens 
5715ea8dc4b6Seschrock 	/*
57165d7b4d43SMatthew Ahrens 	 * If the block to be written was all-zero or compressed enough to be
57175d7b4d43SMatthew Ahrens 	 * embedded in the BP, no write was performed so there will be no
57185d7b4d43SMatthew Ahrens 	 * dva/birth/checksum.  The buffer must therefore remain anonymous
57195d7b4d43SMatthew Ahrens 	 * (and uncached).
5720ea8dc4b6Seschrock 	 */
5721dcbf3bd6SGeorge Wilson 	if (!HDR_EMPTY(hdr)) {
5722fa9e4066Sahrens 		arc_buf_hdr_t *exists;
5723fa9e4066Sahrens 		kmutex_t *hash_lock;
5724fa9e4066Sahrens 
57255602294fSDan Kimmel 		ASSERT3U(zio->io_error, ==, 0);
5726b24ab676SJeff Bonwick 
57276b4acc8bSahrens 		arc_cksum_verify(buf);
57286b4acc8bSahrens 
5729fa9e4066Sahrens 		exists = buf_hash_insert(hdr, &hash_lock);
573089c86e32SChris Williamson 		if (exists != NULL) {
5731fa9e4066Sahrens 			/*
5732fa9e4066Sahrens 			 * This can only happen if we overwrite for
5733fa9e4066Sahrens 			 * sync-to-convergence, because we remove
5734fa9e4066Sahrens 			 * buffers from the hash table when we arc_free().
5735fa9e4066Sahrens 			 */
5736b24ab676SJeff Bonwick 			if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
5737b24ab676SJeff Bonwick 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5738b24ab676SJeff Bonwick 					panic("bad overwrite, hdr=%p exists=%p",
5739b24ab676SJeff Bonwick 					    (void *)hdr, (void *)exists);
574089c86e32SChris Williamson 				ASSERT(refcount_is_zero(
574189c86e32SChris Williamson 				    &exists->b_l1hdr.b_refcnt));
5742b24ab676SJeff Bonwick 				arc_change_state(arc_anon, exists, hash_lock);
5743b24ab676SJeff Bonwick 				mutex_exit(hash_lock);
5744b24ab676SJeff Bonwick 				arc_hdr_destroy(exists);
5745b24ab676SJeff Bonwick 				exists = buf_hash_insert(hdr, &hash_lock);
5746b24ab676SJeff Bonwick 				ASSERT3P(exists, ==, NULL);
574780901aeaSGeorge Wilson 			} else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
574880901aeaSGeorge Wilson 				/* nopwrite */
574980901aeaSGeorge Wilson 				ASSERT(zio->io_prop.zp_nopwrite);
575080901aeaSGeorge Wilson 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
575180901aeaSGeorge Wilson 					panic("bad nopwrite, hdr=%p exists=%p",
575280901aeaSGeorge Wilson 					    (void *)hdr, (void *)exists);
5753b24ab676SJeff Bonwick 			} else {
5754b24ab676SJeff Bonwick 				/* Dedup */
5755dcbf3bd6SGeorge Wilson 				ASSERT(hdr->b_l1hdr.b_bufcnt == 1);
575689c86e32SChris Williamson 				ASSERT(hdr->b_l1hdr.b_state == arc_anon);
5757b24ab676SJeff Bonwick 				ASSERT(BP_GET_DEDUP(zio->io_bp));
5758b24ab676SJeff Bonwick 				ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
5759ae46e4c7SMatthew Ahrens 			}
5760fa9e4066Sahrens 		}
5761dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5762088f3894Sahrens 		/* if it's not anon, we are doing a scrub */
576389c86e32SChris Williamson 		if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
5764088f3894Sahrens 			arc_access(hdr, hash_lock);
576544eda4d7Smaybee 		mutex_exit(hash_lock);
5766ea8dc4b6Seschrock 	} else {
5767dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5768fa9e4066Sahrens 	}
5769ea8dc4b6Seschrock 
577089c86e32SChris Williamson 	ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5771b24ab676SJeff Bonwick 	callback->awcb_done(zio, buf, callback->awcb_private);
5772fa9e4066Sahrens 
5773770499e1SDan Kimmel 	abd_put(zio->io_abd);
5774c717a561Smaybee 	kmem_free(callback, sizeof (arc_write_callback_t));
5775fa9e4066Sahrens }
5776fa9e4066Sahrens 
5777c717a561Smaybee zio_t *
5778dcbf3bd6SGeorge Wilson arc_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
5779dcbf3bd6SGeorge Wilson     boolean_t l2arc, const zio_prop_t *zp, arc_done_func_t *ready,
57808df0bcf0SPaul Dagnelie     arc_done_func_t *children_ready, arc_done_func_t *physdone,
578169962b56SMatthew Ahrens     arc_done_func_t *done, void *private, zio_priority_t priority,
57827802d7bfSMatthew Ahrens     int zio_flags, const zbookmark_phys_t *zb)
5783fa9e4066Sahrens {
5784fa9e4066Sahrens 	arc_buf_hdr_t *hdr = buf->b_hdr;
5785c717a561Smaybee 	arc_write_callback_t *callback;
5786e14bb325SJeff Bonwick 	zio_t *zio;
5787adaec86aSMatthew Ahrens 	zio_prop_t localprop = *zp;
5788fa9e4066Sahrens 
5789dcbf3bd6SGeorge Wilson 	ASSERT3P(ready, !=, NULL);
5790dcbf3bd6SGeorge Wilson 	ASSERT3P(done, !=, NULL);
5791fa9e4066Sahrens 	ASSERT(!HDR_IO_ERROR(hdr));
579289c86e32SChris Williamson 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5793dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5794dcbf3bd6SGeorge Wilson 	ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
57953baa08fcSek 	if (l2arc)
5796dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
57975602294fSDan Kimmel 	if (ARC_BUF_COMPRESSED(buf)) {
5798adaec86aSMatthew Ahrens 		/*
5799adaec86aSMatthew Ahrens 		 * We're writing a pre-compressed buffer.  Make the
5800adaec86aSMatthew Ahrens 		 * compression algorithm requested by the zio_prop_t match
5801adaec86aSMatthew Ahrens 		 * the pre-compressed buffer's compression algorithm.
5802adaec86aSMatthew Ahrens 		 */
5803adaec86aSMatthew Ahrens 		localprop.zp_compress = HDR_GET_COMPRESS(hdr);
5804adaec86aSMatthew Ahrens 
58055602294fSDan Kimmel 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, arc_buf_size(buf));
58065602294fSDan Kimmel 		zio_flags |= ZIO_FLAG_RAW;
58075602294fSDan Kimmel 	}
5808c717a561Smaybee 	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
5809c717a561Smaybee 	callback->awcb_ready = ready;
58108df0bcf0SPaul Dagnelie 	callback->awcb_children_ready = children_ready;
581169962b56SMatthew Ahrens 	callback->awcb_physdone = physdone;
5812c717a561Smaybee 	callback->awcb_done = done;
5813c717a561Smaybee 	callback->awcb_private = private;
5814c717a561Smaybee 	callback->awcb_buf = buf;
5815088f3894Sahrens 
5816dcbf3bd6SGeorge Wilson 	/*
5817770499e1SDan Kimmel 	 * The hdr's b_pabd is now stale, free it now. A new data block
5818dcbf3bd6SGeorge Wilson 	 * will be allocated when the zio pipeline calls arc_write_ready().
5819dcbf3bd6SGeorge Wilson 	 */
5820770499e1SDan Kimmel 	if (hdr->b_l1hdr.b_pabd != NULL) {
5821dcbf3bd6SGeorge Wilson 		/*
5822dcbf3bd6SGeorge Wilson 		 * If the buf is currently sharing the data block with
5823dcbf3bd6SGeorge Wilson 		 * the hdr then we need to break that relationship here.
5824dcbf3bd6SGeorge Wilson 		 * The hdr will remain with a NULL data pointer and the
5825dcbf3bd6SGeorge Wilson 		 * buf will take sole ownership of the block.
5826dcbf3bd6SGeorge Wilson 		 */
5827dcbf3bd6SGeorge Wilson 		if (arc_buf_is_shared(buf)) {
5828dcbf3bd6SGeorge Wilson 			arc_unshare_buf(hdr, buf);
5829dcbf3bd6SGeorge Wilson 		} else {
5830770499e1SDan Kimmel 			arc_hdr_free_pabd(hdr);
5831dcbf3bd6SGeorge Wilson 		}
5832dcbf3bd6SGeorge Wilson 		VERIFY3P(buf->b_data, !=, NULL);
5833dcbf3bd6SGeorge Wilson 		arc_hdr_set_compress(hdr, ZIO_COMPRESS_OFF);
5834dcbf3bd6SGeorge Wilson 	}
5835dcbf3bd6SGeorge Wilson 	ASSERT(!arc_buf_is_shared(buf));
5836770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
5837dcbf3bd6SGeorge Wilson 
5838770499e1SDan Kimmel 	zio = zio_write(pio, spa, txg, bp,
5839770499e1SDan Kimmel 	    abd_get_from_buf(buf->b_data, HDR_GET_LSIZE(hdr)),
5840adaec86aSMatthew Ahrens 	    HDR_GET_LSIZE(hdr), arc_buf_size(buf), &localprop, arc_write_ready,
58418df0bcf0SPaul Dagnelie 	    (children_ready != NULL) ? arc_write_children_ready : NULL,
58428df0bcf0SPaul Dagnelie 	    arc_write_physdone, arc_write_done, callback,
584369962b56SMatthew Ahrens 	    priority, zio_flags, zb);
5844fa9e4066Sahrens 
5845c717a561Smaybee 	return (zio);
5846fa9e4066Sahrens }
5847fa9e4066Sahrens 
58481ab7f2deSmaybee static int
5849*abe1fd01SDon Brady arc_memory_throttle(spa_t *spa, uint64_t reserve, uint64_t txg)
58501ab7f2deSmaybee {
58511ab7f2deSmaybee #ifdef _KERNEL
58521ab7f2deSmaybee 	uint64_t available_memory = ptob(freemem);
58531ab7f2deSmaybee 
58541ab7f2deSmaybee #if defined(__i386)
58551ab7f2deSmaybee 	available_memory =
58561ab7f2deSmaybee 	    MIN(available_memory, vmem_size(heap_arena, VMEM_FREE));
58571ab7f2deSmaybee #endif
585869962b56SMatthew Ahrens 
585969962b56SMatthew Ahrens 	if (freemem > physmem * arc_lotsfree_percent / 100)
58601ab7f2deSmaybee 		return (0);
58611ab7f2deSmaybee 
5862*abe1fd01SDon Brady 	if (txg > spa->spa_lowmem_last_txg) {
5863*abe1fd01SDon Brady 		spa->spa_lowmem_last_txg = txg;
5864*abe1fd01SDon Brady 		spa->spa_lowmem_page_load = 0;
58651ab7f2deSmaybee 	}
58661ab7f2deSmaybee 	/*
58671ab7f2deSmaybee 	 * If we are in pageout, we know that memory is already tight,
58681ab7f2deSmaybee 	 * the arc is already going to be evicting, so we just want to
58691ab7f2deSmaybee 	 * continue to let page writes occur as quickly as possible.
58701ab7f2deSmaybee 	 */
58711ab7f2deSmaybee 	if (curproc == proc_pageout) {
5872*abe1fd01SDon Brady 		if (spa->spa_lowmem_page_load >
5873*abe1fd01SDon Brady 		    MAX(ptob(minfree), available_memory) / 4)
5874be6fd75aSMatthew Ahrens 			return (SET_ERROR(ERESTART));
58751ab7f2deSmaybee 		/* Note: reserve is inflated, so we deflate */
5876*abe1fd01SDon Brady 		atomic_add_64(&spa->spa_lowmem_page_load, reserve / 8);
58771ab7f2deSmaybee 		return (0);
5878*abe1fd01SDon Brady 	} else if (spa->spa_lowmem_page_load > 0 && arc_reclaim_needed()) {
58791ab7f2deSmaybee 		/* memory is low, delay before restarting */
58801ab7f2deSmaybee 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
5881be6fd75aSMatthew Ahrens 		return (SET_ERROR(EAGAIN));
58821ab7f2deSmaybee 	}
5883*abe1fd01SDon Brady 	spa->spa_lowmem_page_load = 0;
5884*abe1fd01SDon Brady #endif /* _KERNEL */
58851ab7f2deSmaybee 	return (0);
58861ab7f2deSmaybee }
58871ab7f2deSmaybee 
5888fa9e4066Sahrens void
58891ab7f2deSmaybee arc_tempreserve_clear(uint64_t reserve)
5890fa9e4066Sahrens {
58911ab7f2deSmaybee 	atomic_add_64(&arc_tempreserve, -reserve);
5892fa9e4066Sahrens 	ASSERT((int64_t)arc_tempreserve >= 0);
5893fa9e4066Sahrens }
5894fa9e4066Sahrens 
5895fa9e4066Sahrens int
5896*abe1fd01SDon Brady arc_tempreserve_space(spa_t *spa, uint64_t reserve, uint64_t txg)
5897fa9e4066Sahrens {
58981ab7f2deSmaybee 	int error;
58992fdbea25SAleksandr Guzovskiy 	uint64_t anon_size;
59001ab7f2deSmaybee 
59011ab7f2deSmaybee 	if (reserve > arc_c/4 && !arc_no_grow)
59021ab7f2deSmaybee 		arc_c = MIN(arc_c_max, reserve * 4);
59031ab7f2deSmaybee 	if (reserve > arc_c)
5904be6fd75aSMatthew Ahrens 		return (SET_ERROR(ENOMEM));
5905112fe045Smaybee 
59062fdbea25SAleksandr Guzovskiy 	/*
59072fdbea25SAleksandr Guzovskiy 	 * Don't count loaned bufs as in flight dirty data to prevent long
59082fdbea25SAleksandr Guzovskiy 	 * network delays from blocking transactions that are ready to be
59092fdbea25SAleksandr Guzovskiy 	 * assigned to a txg.
59102fdbea25SAleksandr Guzovskiy 	 */
59115602294fSDan Kimmel 
59125602294fSDan Kimmel 	/* assert that it has not wrapped around */
59135602294fSDan Kimmel 	ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
59145602294fSDan Kimmel 
59152fd872a7SPrakash Surya 	anon_size = MAX((int64_t)(refcount_count(&arc_anon->arcs_size) -
59162fd872a7SPrakash Surya 	    arc_loaned_bytes), 0);
59172fdbea25SAleksandr Guzovskiy 
59181ab7f2deSmaybee 	/*
59191ab7f2deSmaybee 	 * Writes will, almost always, require additional memory allocations
5920f7170741SWill Andrews 	 * in order to compress/encrypt/etc the data.  We therefore need to
59211ab7f2deSmaybee 	 * make sure that there is sufficient available memory for this.
59221ab7f2deSmaybee 	 */
5923*abe1fd01SDon Brady 	error = arc_memory_throttle(spa, reserve, txg);
592469962b56SMatthew Ahrens 	if (error != 0)
59251ab7f2deSmaybee 		return (error);
59261ab7f2deSmaybee 
5927fa9e4066Sahrens 	/*
5928112fe045Smaybee 	 * Throttle writes when the amount of dirty data in the cache
5929112fe045Smaybee 	 * gets too large.  We try to keep the cache less than half full
5930112fe045Smaybee 	 * of dirty blocks so that our sync times don't grow too large.
5931*abe1fd01SDon Brady 	 *
5932*abe1fd01SDon Brady 	 * In the case of one pool being built on another pool, we want
5933*abe1fd01SDon Brady 	 * to make sure we don't end up throttling the lower (backing)
5934*abe1fd01SDon Brady 	 * pool when the upper pool is the majority contributor to dirty
5935*abe1fd01SDon Brady 	 * data. To insure we make forward progress during throttling, we
5936*abe1fd01SDon Brady 	 * also check the current pool's net dirty data and only throttle
5937*abe1fd01SDon Brady 	 * if it exceeds zfs_arc_pool_dirty_percent of the anonymous dirty
5938*abe1fd01SDon Brady 	 * data in the cache.
5939*abe1fd01SDon Brady 	 *
5940112fe045Smaybee 	 * Note: if two requests come in concurrently, we might let them
5941112fe045Smaybee 	 * both succeed, when one of them should fail.  Not a huge deal.
5942fa9e4066Sahrens 	 */
5943*abe1fd01SDon Brady 	uint64_t total_dirty = reserve + arc_tempreserve + anon_size;
5944*abe1fd01SDon Brady 	uint64_t spa_dirty_anon = spa_dirty_data(spa);
59452fdbea25SAleksandr Guzovskiy 
5946*abe1fd01SDon Brady 	if (total_dirty > arc_c * zfs_arc_dirty_limit_percent / 100 &&
5947*abe1fd01SDon Brady 	    anon_size > arc_c * zfs_arc_anon_limit_percent / 100 &&
5948*abe1fd01SDon Brady 	    spa_dirty_anon > anon_size * zfs_arc_pool_dirty_percent / 100) {
5949dcbf3bd6SGeorge Wilson 		uint64_t meta_esize =
5950dcbf3bd6SGeorge Wilson 		    refcount_count(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
5951dcbf3bd6SGeorge Wilson 		uint64_t data_esize =
5952dcbf3bd6SGeorge Wilson 		    refcount_count(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
59530e8c6158Smaybee 		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
59540e8c6158Smaybee 		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
5955dcbf3bd6SGeorge Wilson 		    arc_tempreserve >> 10, meta_esize >> 10,
5956dcbf3bd6SGeorge Wilson 		    data_esize >> 10, reserve >> 10, arc_c >> 10);
5957be6fd75aSMatthew Ahrens 		return (SET_ERROR(ERESTART));
5958fa9e4066Sahrens 	}
59591ab7f2deSmaybee 	atomic_add_64(&arc_tempreserve, reserve);
5960fa9e4066Sahrens 	return (0);
5961fa9e4066Sahrens }
5962fa9e4066Sahrens 
59634076b1bfSPrakash Surya static void
59644076b1bfSPrakash Surya arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
59654076b1bfSPrakash Surya     kstat_named_t *evict_data, kstat_named_t *evict_metadata)
59664076b1bfSPrakash Surya {
59672fd872a7SPrakash Surya 	size->value.ui64 = refcount_count(&state->arcs_size);
5968dcbf3bd6SGeorge Wilson 	evict_data->value.ui64 =
5969dcbf3bd6SGeorge Wilson 	    refcount_count(&state->arcs_esize[ARC_BUFC_DATA]);
5970dcbf3bd6SGeorge Wilson 	evict_metadata->value.ui64 =
5971dcbf3bd6SGeorge Wilson 	    refcount_count(&state->arcs_esize[ARC_BUFC_METADATA]);
59724076b1bfSPrakash Surya }
59734076b1bfSPrakash Surya 
59744076b1bfSPrakash Surya static int
59754076b1bfSPrakash Surya arc_kstat_update(kstat_t *ksp, int rw)
59764076b1bfSPrakash Surya {
59774076b1bfSPrakash Surya 	arc_stats_t *as = ksp->ks_data;
59784076b1bfSPrakash Surya 
59794076b1bfSPrakash Surya 	if (rw == KSTAT_WRITE) {
59804076b1bfSPrakash Surya 		return (EACCES);
59814076b1bfSPrakash Surya 	} else {
59824076b1bfSPrakash Surya 		arc_kstat_update_state(arc_anon,
59834076b1bfSPrakash Surya 		    &as->arcstat_anon_size,
59844076b1bfSPrakash Surya 		    &as->arcstat_anon_evictable_data,
59854076b1bfSPrakash Surya 		    &as->arcstat_anon_evictable_metadata);
59864076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mru,
59874076b1bfSPrakash Surya 		    &as->arcstat_mru_size,
59884076b1bfSPrakash Surya 		    &as->arcstat_mru_evictable_data,
59894076b1bfSPrakash Surya 		    &as->arcstat_mru_evictable_metadata);
59904076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mru_ghost,
59914076b1bfSPrakash Surya 		    &as->arcstat_mru_ghost_size,
59924076b1bfSPrakash Surya 		    &as->arcstat_mru_ghost_evictable_data,
59934076b1bfSPrakash Surya 		    &as->arcstat_mru_ghost_evictable_metadata);
59944076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mfu,
59954076b1bfSPrakash Surya 		    &as->arcstat_mfu_size,
59964076b1bfSPrakash Surya 		    &as->arcstat_mfu_evictable_data,
59974076b1bfSPrakash Surya 		    &as->arcstat_mfu_evictable_metadata);
59984076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mfu_ghost,
59994076b1bfSPrakash Surya 		    &as->arcstat_mfu_ghost_size,
60004076b1bfSPrakash Surya 		    &as->arcstat_mfu_ghost_evictable_data,
60014076b1bfSPrakash Surya 		    &as->arcstat_mfu_ghost_evictable_metadata);
60023a2d8a1bSPaul Dagnelie 
60033a2d8a1bSPaul Dagnelie 		ARCSTAT(arcstat_size) = aggsum_value(&arc_size);
60043a2d8a1bSPaul Dagnelie 		ARCSTAT(arcstat_meta_used) = aggsum_value(&arc_meta_used);
60053a2d8a1bSPaul Dagnelie 		ARCSTAT(arcstat_data_size) = aggsum_value(&astat_data_size);
60063a2d8a1bSPaul Dagnelie 		ARCSTAT(arcstat_metadata_size) =
60073a2d8a1bSPaul Dagnelie 		    aggsum_value(&astat_metadata_size);
60083a2d8a1bSPaul Dagnelie 		ARCSTAT(arcstat_hdr_size) = aggsum_value(&astat_hdr_size);
60093a2d8a1bSPaul Dagnelie 		ARCSTAT(arcstat_other_size) = aggsum_value(&astat_other_size);
60103a2d8a1bSPaul Dagnelie 		ARCSTAT(arcstat_l2_hdr_size) = aggsum_value(&astat_l2_hdr_size);
60114076b1bfSPrakash Surya 	}
60124076b1bfSPrakash Surya 
60134076b1bfSPrakash Surya 	return (0);
60144076b1bfSPrakash Surya }
60154076b1bfSPrakash Surya 
6016dcbf3bd6SGeorge Wilson /*
6017dcbf3bd6SGeorge Wilson  * This function *must* return indices evenly distributed between all
6018dcbf3bd6SGeorge Wilson  * sublists of the multilist. This is needed due to how the ARC eviction
6019dcbf3bd6SGeorge Wilson  * code is laid out; arc_evict_state() assumes ARC buffers are evenly
6020dcbf3bd6SGeorge Wilson  * distributed between all sublists and uses this assumption when
6021dcbf3bd6SGeorge Wilson  * deciding which sublist to evict from and how much to evict from it.
6022dcbf3bd6SGeorge Wilson  */
6023dcbf3bd6SGeorge Wilson unsigned int
6024dcbf3bd6SGeorge Wilson arc_state_multilist_index_func(multilist_t *ml, void *obj)
6025dcbf3bd6SGeorge Wilson {
6026dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = obj;
6027dcbf3bd6SGeorge Wilson 
6028dcbf3bd6SGeorge Wilson 	/*
6029dcbf3bd6SGeorge Wilson 	 * We rely on b_dva to generate evenly distributed index
6030dcbf3bd6SGeorge Wilson 	 * numbers using buf_hash below. So, as an added precaution,
6031dcbf3bd6SGeorge Wilson 	 * let's make sure we never add empty buffers to the arc lists.
6032dcbf3bd6SGeorge Wilson 	 */
6033dcbf3bd6SGeorge Wilson 	ASSERT(!HDR_EMPTY(hdr));
6034dcbf3bd6SGeorge Wilson 
6035dcbf3bd6SGeorge Wilson 	/*
6036dcbf3bd6SGeorge Wilson 	 * The assumption here, is the hash value for a given
6037dcbf3bd6SGeorge Wilson 	 * arc_buf_hdr_t will remain constant throughout it's lifetime
6038dcbf3bd6SGeorge Wilson 	 * (i.e. it's b_spa, b_dva, and b_birth fields don't change).
6039dcbf3bd6SGeorge Wilson 	 * Thus, we don't need to store the header's sublist index
6040dcbf3bd6SGeorge Wilson 	 * on insertion, as this index can be recalculated on removal.
6041dcbf3bd6SGeorge Wilson 	 *
6042dcbf3bd6SGeorge Wilson 	 * Also, the low order bits of the hash value are thought to be
6043dcbf3bd6SGeorge Wilson 	 * distributed evenly. Otherwise, in the case that the multilist
6044dcbf3bd6SGeorge Wilson 	 * has a power of two number of sublists, each sublists' usage
6045dcbf3bd6SGeorge Wilson 	 * would not be evenly distributed.
6046dcbf3bd6SGeorge Wilson 	 */
6047dcbf3bd6SGeorge Wilson 	return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
6048dcbf3bd6SGeorge Wilson 	    multilist_get_num_sublists(ml));
6049dcbf3bd6SGeorge Wilson }
6050dcbf3bd6SGeorge Wilson 
6051dcbf3bd6SGeorge Wilson static void
6052dcbf3bd6SGeorge Wilson arc_state_init(void)
6053dcbf3bd6SGeorge Wilson {
6054dcbf3bd6SGeorge Wilson 	arc_anon = &ARC_anon;
6055dcbf3bd6SGeorge Wilson 	arc_mru = &ARC_mru;
6056dcbf3bd6SGeorge Wilson 	arc_mru_ghost = &ARC_mru_ghost;
6057dcbf3bd6SGeorge Wilson 	arc_mfu = &ARC_mfu;
6058dcbf3bd6SGeorge Wilson 	arc_mfu_ghost = &ARC_mfu_ghost;
6059dcbf3bd6SGeorge Wilson 	arc_l2c_only = &ARC_l2c_only;
6060dcbf3bd6SGeorge Wilson 
606194c2d0ebSMatthew Ahrens 	arc_mru->arcs_list[ARC_BUFC_METADATA] =
606294c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
6063dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
606410fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
606594c2d0ebSMatthew Ahrens 	arc_mru->arcs_list[ARC_BUFC_DATA] =
606694c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
6067dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
606810fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
606994c2d0ebSMatthew Ahrens 	arc_mru_ghost->arcs_list[ARC_BUFC_METADATA] =
607094c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
6071dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
607210fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
607394c2d0ebSMatthew Ahrens 	arc_mru_ghost->arcs_list[ARC_BUFC_DATA] =
607494c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
6075dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
607610fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
607794c2d0ebSMatthew Ahrens 	arc_mfu->arcs_list[ARC_BUFC_METADATA] =
607894c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
6079dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
608010fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
608194c2d0ebSMatthew Ahrens 	arc_mfu->arcs_list[ARC_BUFC_DATA] =
608294c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
6083dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
608410fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
608594c2d0ebSMatthew Ahrens 	arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA] =
608694c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
6087dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
608810fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
608994c2d0ebSMatthew Ahrens 	arc_mfu_ghost->arcs_list[ARC_BUFC_DATA] =
609094c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
6091dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
609210fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
609394c2d0ebSMatthew Ahrens 	arc_l2c_only->arcs_list[ARC_BUFC_METADATA] =
609494c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
6095dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
609610fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
609794c2d0ebSMatthew Ahrens 	arc_l2c_only->arcs_list[ARC_BUFC_DATA] =
609894c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
6099dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
610010fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
6101dcbf3bd6SGeorge Wilson 
6102dcbf3bd6SGeorge Wilson 	refcount_create(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6103dcbf3bd6SGeorge Wilson 	refcount_create(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6104dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
6105dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
6106dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
6107dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
6108dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
6109dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
6110dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
6111dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
6112dcbf3bd6SGeorge Wilson 	refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
6113dcbf3bd6SGeorge Wilson 	refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
6114dcbf3bd6SGeorge Wilson 
6115dcbf3bd6SGeorge Wilson 	refcount_create(&arc_anon->arcs_size);
6116dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru->arcs_size);
6117dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru_ghost->arcs_size);
6118dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu->arcs_size);
6119dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu_ghost->arcs_size);
6120dcbf3bd6SGeorge Wilson 	refcount_create(&arc_l2c_only->arcs_size);
61213a2d8a1bSPaul Dagnelie 
61223a2d8a1bSPaul Dagnelie 	aggsum_init(&arc_meta_used, 0);
61233a2d8a1bSPaul Dagnelie 	aggsum_init(&arc_size, 0);
61243a2d8a1bSPaul Dagnelie 	aggsum_init(&astat_data_size, 0);
61253a2d8a1bSPaul Dagnelie 	aggsum_init(&astat_metadata_size, 0);
61263a2d8a1bSPaul Dagnelie 	aggsum_init(&astat_hdr_size, 0);
61273a2d8a1bSPaul Dagnelie 	aggsum_init(&astat_other_size, 0);
61283a2d8a1bSPaul Dagnelie 	aggsum_init(&astat_l2_hdr_size, 0);
6129dcbf3bd6SGeorge Wilson }
6130dcbf3bd6SGeorge Wilson 
6131dcbf3bd6SGeorge Wilson static void
6132dcbf3bd6SGeorge Wilson arc_state_fini(void)
6133dcbf3bd6SGeorge Wilson {
6134dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6135dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6136dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
6137dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
6138dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
6139dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
6140dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
6141dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
6142dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
6143dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
6144dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
6145dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
6146dcbf3bd6SGeorge Wilson 
6147dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_anon->arcs_size);
6148dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru->arcs_size);
6149dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru_ghost->arcs_size);
6150dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu->arcs_size);
6151dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu_ghost->arcs_size);
6152dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_l2c_only->arcs_size);
6153dcbf3bd6SGeorge Wilson 
615494c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_METADATA]);
615594c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
615694c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_METADATA]);
615794c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
615894c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_DATA]);
615994c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
616094c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_DATA]);
616194c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
6162dcbf3bd6SGeorge Wilson }
6163dcbf3bd6SGeorge Wilson 
6164dcbf3bd6SGeorge Wilson uint64_t
6165dcbf3bd6SGeorge Wilson arc_max_bytes(void)
6166244781f1SPrakash Surya {
6167dcbf3bd6SGeorge Wilson 	return (arc_c_max);
6168244781f1SPrakash Surya }
6169244781f1SPrakash Surya 
6170fa9e4066Sahrens void
6171fa9e4066Sahrens arc_init(void)
6172fa9e4066Sahrens {
61732ec99e3eSMatthew Ahrens 	/*
61742ec99e3eSMatthew Ahrens 	 * allmem is "all memory that we could possibly use".
61752ec99e3eSMatthew Ahrens 	 */
61762ec99e3eSMatthew Ahrens #ifdef _KERNEL
61772ec99e3eSMatthew Ahrens 	uint64_t allmem = ptob(physmem - swapfs_minfree);
61782ec99e3eSMatthew Ahrens #else
61792ec99e3eSMatthew Ahrens 	uint64_t allmem = (physmem * PAGESIZE) / 2;
61802ec99e3eSMatthew Ahrens #endif
6181de753e34SBrad Lewis 	mutex_init(&arc_adjust_lock, NULL, MUTEX_DEFAULT, NULL);
6182de753e34SBrad Lewis 	cv_init(&arc_adjust_waiters_cv, NULL, CV_DEFAULT, NULL);
6183244781f1SPrakash Surya 
618413506d1eSmaybee 	/* Convert seconds to clock ticks */
6185b19a79ecSperrin 	arc_min_prefetch_lifespan = 1 * hz;
618613506d1eSmaybee 
6187112fe045Smaybee 	/* set min cache to 1/32 of all memory, or 64MB, whichever is more */
61882ec99e3eSMatthew Ahrens 	arc_c_min = MAX(allmem / 32, 64 << 20);
6189112fe045Smaybee 	/* set max to 3/4 of all memory, or all but 1GB, whichever is more */
61902ec99e3eSMatthew Ahrens 	if (allmem >= 1 << 30)
61912ec99e3eSMatthew Ahrens 		arc_c_max = allmem - (1 << 30);
6192fa9e4066Sahrens 	else
619344cb6abcSbmc 		arc_c_max = arc_c_min;
61942ec99e3eSMatthew Ahrens 	arc_c_max = MAX(allmem * 3 / 4, arc_c_max);
6195a2eea2e1Sahrens 
61968fe00bfbSMatthew Ahrens 	/*
61978fe00bfbSMatthew Ahrens 	 * In userland, there's only the memory pressure that we artificially
61988fe00bfbSMatthew Ahrens 	 * create (see arc_available_memory()).  Don't let arc_c get too
61998fe00bfbSMatthew Ahrens 	 * small, because it can cause transactions to be larger than
62008fe00bfbSMatthew Ahrens 	 * arc_c, causing arc_tempreserve_space() to fail.
62018fe00bfbSMatthew Ahrens 	 */
62028fe00bfbSMatthew Ahrens #ifndef _KERNEL
62038fe00bfbSMatthew Ahrens 	arc_c_min = arc_c_max / 2;
62048fe00bfbSMatthew Ahrens #endif
62058fe00bfbSMatthew Ahrens 
6206a2eea2e1Sahrens 	/*
6207a2eea2e1Sahrens 	 * Allow the tunables to override our calculations if they are
6208a2eea2e1Sahrens 	 * reasonable (ie. over 64MB)
6209a2eea2e1Sahrens 	 */
6210e5961710SMatthew Ahrens 	if (zfs_arc_max > 64 << 20 && zfs_arc_max < allmem) {
621144cb6abcSbmc 		arc_c_max = zfs_arc_max;
6212e5961710SMatthew Ahrens 		arc_c_min = MIN(arc_c_min, arc_c_max);
6213e5961710SMatthew Ahrens 	}
62142ec99e3eSMatthew Ahrens 	if (zfs_arc_min > 64 << 20 && zfs_arc_min <= arc_c_max)
621544cb6abcSbmc 		arc_c_min = zfs_arc_min;
6216a2eea2e1Sahrens 
621744cb6abcSbmc 	arc_c = arc_c_max;
621844cb6abcSbmc 	arc_p = (arc_c >> 1);
6219fa9e4066Sahrens 
62200e8c6158Smaybee 	/* limit meta-data to 1/4 of the arc capacity */
62210e8c6158Smaybee 	arc_meta_limit = arc_c_max / 4;
62221116048bSek 
6223af868f46SMatthew Ahrens #ifdef _KERNEL
6224af868f46SMatthew Ahrens 	/*
6225af868f46SMatthew Ahrens 	 * Metadata is stored in the kernel's heap.  Don't let us
6226af868f46SMatthew Ahrens 	 * use more than half the heap for the ARC.
6227af868f46SMatthew Ahrens 	 */
6228af868f46SMatthew Ahrens 	arc_meta_limit = MIN(arc_meta_limit,
6229af868f46SMatthew Ahrens 	    vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 2);
6230af868f46SMatthew Ahrens #endif
6231af868f46SMatthew Ahrens 
62321116048bSek 	/* Allow the tunable to override if it is reasonable */
62331116048bSek 	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
62341116048bSek 		arc_meta_limit = zfs_arc_meta_limit;
62351116048bSek 
62360e8c6158Smaybee 	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
62370e8c6158Smaybee 		arc_c_min = arc_meta_limit / 2;
62380e8c6158Smaybee 
62393a5286a1SMatthew Ahrens 	if (zfs_arc_meta_min > 0) {
62403a5286a1SMatthew Ahrens 		arc_meta_min = zfs_arc_meta_min;
62413a5286a1SMatthew Ahrens 	} else {
62423a5286a1SMatthew Ahrens 		arc_meta_min = arc_c_min / 2;
62433a5286a1SMatthew Ahrens 	}
62443a5286a1SMatthew Ahrens 
62455a98e54bSBrendan Gregg - Sun Microsystems 	if (zfs_arc_grow_retry > 0)
62465a98e54bSBrendan Gregg - Sun Microsystems 		arc_grow_retry = zfs_arc_grow_retry;
62475a98e54bSBrendan Gregg - Sun Microsystems 
62485a98e54bSBrendan Gregg - Sun Microsystems 	if (zfs_arc_shrink_shift > 0)
62495a98e54bSBrendan Gregg - Sun Microsystems 		arc_shrink_shift = zfs_arc_shrink_shift;
62505a98e54bSBrendan Gregg - Sun Microsystems 
62512ec99e3eSMatthew Ahrens 	/*
62522ec99e3eSMatthew Ahrens 	 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
62532ec99e3eSMatthew Ahrens 	 */
62542ec99e3eSMatthew Ahrens 	if (arc_no_grow_shift >= arc_shrink_shift)
62552ec99e3eSMatthew Ahrens 		arc_no_grow_shift = arc_shrink_shift - 1;
62562ec99e3eSMatthew Ahrens 
62575a98e54bSBrendan Gregg - Sun Microsystems 	if (zfs_arc_p_min_shift > 0)
62585a98e54bSBrendan Gregg - Sun Microsystems 		arc_p_min_shift = zfs_arc_p_min_shift;
62595a98e54bSBrendan Gregg - Sun Microsystems 
6260fa9e4066Sahrens 	/* if kmem_flags are set, lets try to use less memory */
6261fa9e4066Sahrens 	if (kmem_debugging())
626244cb6abcSbmc 		arc_c = arc_c / 2;
626344cb6abcSbmc 	if (arc_c < arc_c_min)
626444cb6abcSbmc 		arc_c = arc_c_min;
626544cb6abcSbmc 
6266dcbf3bd6SGeorge Wilson 	arc_state_init();
6267fa9e4066Sahrens 
6268de753e34SBrad Lewis 	/*
6269de753e34SBrad Lewis 	 * The arc must be "uninitialized", so that hdr_recl() (which is
6270de753e34SBrad Lewis 	 * registered by buf_init()) will not access arc_reap_zthr before
6271de753e34SBrad Lewis 	 * it is created.
6272de753e34SBrad Lewis 	 */
6273de753e34SBrad Lewis 	ASSERT(!arc_initialized);
6274de753e34SBrad Lewis 	buf_init();
6275fa9e4066Sahrens 
627644cb6abcSbmc 	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
627744cb6abcSbmc 	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
627844cb6abcSbmc 
627944cb6abcSbmc 	if (arc_ksp != NULL) {
628044cb6abcSbmc 		arc_ksp->ks_data = &arc_stats;
62814076b1bfSPrakash Surya 		arc_ksp->ks_update = arc_kstat_update;
628244cb6abcSbmc 		kstat_install(arc_ksp);
628344cb6abcSbmc 	}
628444cb6abcSbmc 
6285de753e34SBrad Lewis 	arc_adjust_zthr = zthr_create(arc_adjust_cb_check,
6286de753e34SBrad Lewis 	    arc_adjust_cb, NULL);
6287de753e34SBrad Lewis 	arc_reap_zthr = zthr_create_timer(arc_reap_cb_check,
6288de753e34SBrad Lewis 	    arc_reap_cb, NULL, SEC2NSEC(1));
628949e3519aSmaybee 
6290de753e34SBrad Lewis 	arc_initialized = B_TRUE;
62913a737e0dSbrendan 	arc_warm = B_FALSE;
62921ab7f2deSmaybee 
629369962b56SMatthew Ahrens 	/*
629469962b56SMatthew Ahrens 	 * Calculate maximum amount of dirty data per pool.
629569962b56SMatthew Ahrens 	 *
629669962b56SMatthew Ahrens 	 * If it has been set by /etc/system, take that.
629769962b56SMatthew Ahrens 	 * Otherwise, use a percentage of physical memory defined by
629869962b56SMatthew Ahrens 	 * zfs_dirty_data_max_percent (default 10%) with a cap at
629969962b56SMatthew Ahrens 	 * zfs_dirty_data_max_max (default 4GB).
630069962b56SMatthew Ahrens 	 */
630169962b56SMatthew Ahrens 	if (zfs_dirty_data_max == 0) {
630269962b56SMatthew Ahrens 		zfs_dirty_data_max = physmem * PAGESIZE *
630369962b56SMatthew Ahrens 		    zfs_dirty_data_max_percent / 100;
630469962b56SMatthew Ahrens 		zfs_dirty_data_max = MIN(zfs_dirty_data_max,
630569962b56SMatthew Ahrens 		    zfs_dirty_data_max_max);
630669962b56SMatthew Ahrens 	}
6307fa9e4066Sahrens }
6308fa9e4066Sahrens 
6309fa9e4066Sahrens void
6310fa9e4066Sahrens arc_fini(void)
6311fa9e4066Sahrens {
6312dcbf3bd6SGeorge Wilson 	/* Use B_TRUE to ensure *all* buffers are evicted */
6313dcbf3bd6SGeorge Wilson 	arc_flush(NULL, B_TRUE);
6314fa9e4066Sahrens 
6315de753e34SBrad Lewis 	arc_initialized = B_FALSE;
6316fa9e4066Sahrens 
631744cb6abcSbmc 	if (arc_ksp != NULL) {
631844cb6abcSbmc 		kstat_delete(arc_ksp);
631944cb6abcSbmc 		arc_ksp = NULL;
632044cb6abcSbmc 	}
632144cb6abcSbmc 
6322de753e34SBrad Lewis 	(void) zthr_cancel(arc_adjust_zthr);
6323de753e34SBrad Lewis 	zthr_destroy(arc_adjust_zthr);
6324de753e34SBrad Lewis 
6325de753e34SBrad Lewis 	(void) zthr_cancel(arc_reap_zthr);
6326de753e34SBrad Lewis 	zthr_destroy(arc_reap_zthr);
6327de753e34SBrad Lewis 
6328de753e34SBrad Lewis 	mutex_destroy(&arc_adjust_lock);
6329de753e34SBrad Lewis 	cv_destroy(&arc_adjust_waiters_cv);
6330244781f1SPrakash Surya 
6331dcbf3bd6SGeorge Wilson 	arc_state_fini();
6332fa9e4066Sahrens 	buf_fini();
63332fdbea25SAleksandr Guzovskiy 
633489c86e32SChris Williamson 	ASSERT0(arc_loaned_bytes);
6335fa9e4066Sahrens }
6336fa94a07fSbrendan 
6337fa94a07fSbrendan /*
6338fa94a07fSbrendan  * Level 2 ARC
6339fa94a07fSbrendan  *
6340fa94a07fSbrendan  * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
6341fa94a07fSbrendan  * It uses dedicated storage devices to hold cached data, which are populated
6342fa94a07fSbrendan  * using large infrequent writes.  The main role of this cache is to boost
6343fa94a07fSbrendan  * the performance of random read workloads.  The intended L2ARC devices
6344fa94a07fSbrendan  * include short-stroked disks, solid state disks, and other media with
6345fa94a07fSbrendan  * substantially faster read latency than disk.
6346fa94a07fSbrendan  *
6347fa94a07fSbrendan  *                 +-----------------------+
6348fa94a07fSbrendan  *                 |         ARC           |
6349fa94a07fSbrendan  *                 +-----------------------+
6350fa94a07fSbrendan  *                    |         ^     ^
6351fa94a07fSbrendan  *                    |         |     |
6352fa94a07fSbrendan  *      l2arc_feed_thread()    arc_read()
6353fa94a07fSbrendan  *                    |         |     |
6354fa94a07fSbrendan  *                    |  l2arc read   |
6355fa94a07fSbrendan  *                    V         |     |
6356fa94a07fSbrendan  *               +---------------+    |
6357fa94a07fSbrendan  *               |     L2ARC     |    |
6358fa94a07fSbrendan  *               +---------------+    |
6359fa94a07fSbrendan  *                   |    ^           |
6360fa94a07fSbrendan  *          l2arc_write() |           |
6361fa94a07fSbrendan  *                   |    |           |
6362fa94a07fSbrendan  *                   V    |           |
6363fa94a07fSbrendan  *                 +-------+      +-------+
6364fa94a07fSbrendan  *                 | vdev  |      | vdev  |
6365fa94a07fSbrendan  *                 | cache |      | cache |
6366fa94a07fSbrendan  *                 +-------+      +-------+
6367fa94a07fSbrendan  *                 +=========+     .-----.
6368fa94a07fSbrendan  *                 :  L2ARC  :    |-_____-|
6369fa94a07fSbrendan  *                 : devices :    | Disks |
6370fa94a07fSbrendan  *                 +=========+    `-_____-'
6371fa94a07fSbrendan  *
6372fa94a07fSbrendan  * Read requests are satisfied from the following sources, in order:
6373fa94a07fSbrendan  *
6374fa94a07fSbrendan  *	1) ARC
6375fa94a07fSbrendan  *	2) vdev cache of L2ARC devices
6376fa94a07fSbrendan  *	3) L2ARC devices
6377fa94a07fSbrendan  *	4) vdev cache of disks
6378fa94a07fSbrendan  *	5) disks
6379fa94a07fSbrendan  *
6380fa94a07fSbrendan  * Some L2ARC device types exhibit extremely slow write performance.
6381fa94a07fSbrendan  * To accommodate for this there are some significant differences between
6382fa94a07fSbrendan  * the L2ARC and traditional cache design:
6383fa94a07fSbrendan  *
6384fa94a07fSbrendan  * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
6385fa94a07fSbrendan  * the ARC behave as usual, freeing buffers and placing headers on ghost
6386fa94a07fSbrendan  * lists.  The ARC does not send buffers to the L2ARC during eviction as
6387fa94a07fSbrendan  * this would add inflated write latencies for all ARC memory pressure.
6388fa94a07fSbrendan  *
6389fa94a07fSbrendan  * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
6390fa94a07fSbrendan  * It does this by periodically scanning buffers from the eviction-end of
6391fa94a07fSbrendan  * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
6392aad02571SSaso Kiselkov  * not already there. It scans until a headroom of buffers is satisfied,
6393aad02571SSaso Kiselkov  * which itself is a buffer for ARC eviction. If a compressible buffer is
6394aad02571SSaso Kiselkov  * found during scanning and selected for writing to an L2ARC device, we
6395aad02571SSaso Kiselkov  * temporarily boost scanning headroom during the next scan cycle to make
6396aad02571SSaso Kiselkov  * sure we adapt to compression effects (which might significantly reduce
6397aad02571SSaso Kiselkov  * the data volume we write to L2ARC). The thread that does this is
6398fa94a07fSbrendan  * l2arc_feed_thread(), illustrated below; example sizes are included to
6399fa94a07fSbrendan  * provide a better sense of ratio than this diagram:
6400fa94a07fSbrendan  *
6401fa94a07fSbrendan  *	       head -->                        tail
6402fa94a07fSbrendan  *	        +---------------------+----------+
6403fa94a07fSbrendan  *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
6404fa94a07fSbrendan  *	        +---------------------+----------+   |   o L2ARC eligible
6405fa94a07fSbrendan  *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
6406fa94a07fSbrendan  *	        +---------------------+----------+   |
6407fa94a07fSbrendan  *	             15.9 Gbytes      ^ 32 Mbytes    |
6408fa94a07fSbrendan  *	                           headroom          |
6409fa94a07fSbrendan  *	                                      l2arc_feed_thread()
6410fa94a07fSbrendan  *	                                             |
6411fa94a07fSbrendan  *	                 l2arc write hand <--[oooo]--'
6412fa94a07fSbrendan  *	                         |           8 Mbyte
6413fa94a07fSbrendan  *	                         |          write max
6414fa94a07fSbrendan  *	                         V
6415fa94a07fSbrendan  *		  +==============================+
6416fa94a07fSbrendan  *	L2ARC dev |####|#|###|###|    |####| ... |
6417fa94a07fSbrendan  *	          +==============================+
6418fa94a07fSbrendan  *	                     32 Gbytes
6419fa94a07fSbrendan  *
6420fa94a07fSbrendan  * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
6421fa94a07fSbrendan  * evicted, then the L2ARC has cached a buffer much sooner than it probably
6422fa94a07fSbrendan  * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
6423fa94a07fSbrendan  * safe to say that this is an uncommon case, since buffers at the end of
6424fa94a07fSbrendan  * the ARC lists have moved there due to inactivity.
6425fa94a07fSbrendan  *
6426fa94a07fSbrendan  * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
6427fa94a07fSbrendan  * then the L2ARC simply misses copying some buffers.  This serves as a
6428fa94a07fSbrendan  * pressure valve to prevent heavy read workloads from both stalling the ARC
6429fa94a07fSbrendan  * with waits and clogging the L2ARC with writes.  This also helps prevent
6430fa94a07fSbrendan  * the potential for the L2ARC to churn if it attempts to cache content too
6431fa94a07fSbrendan  * quickly, such as during backups of the entire pool.
6432fa94a07fSbrendan  *
64333a737e0dSbrendan  * 5. After system boot and before the ARC has filled main memory, there are
64343a737e0dSbrendan  * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
64353a737e0dSbrendan  * lists can remain mostly static.  Instead of searching from tail of these
64363a737e0dSbrendan  * lists as pictured, the l2arc_feed_thread() will search from the list heads
64373a737e0dSbrendan  * for eligible buffers, greatly increasing its chance of finding them.
64383a737e0dSbrendan  *
64393a737e0dSbrendan  * The L2ARC device write speed is also boosted during this time so that
64403a737e0dSbrendan  * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
64413a737e0dSbrendan  * there are no L2ARC reads, and no fear of degrading read performance
64423a737e0dSbrendan  * through increased writes.
64433a737e0dSbrendan  *
64443a737e0dSbrendan  * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
6445fa94a07fSbrendan  * the vdev queue can aggregate them into larger and fewer writes.  Each
6446fa94a07fSbrendan  * device is written to in a rotor fashion, sweeping writes through
6447fa94a07fSbrendan  * available space then repeating.
6448fa94a07fSbrendan  *
64493a737e0dSbrendan  * 7. The L2ARC does not store dirty content.  It never needs to flush
6450fa94a07fSbrendan  * write buffers back to disk based storage.
6451fa94a07fSbrendan  *
64523a737e0dSbrendan  * 8. If an ARC buffer is written (and dirtied) which also exists in the
6453fa94a07fSbrendan  * L2ARC, the now stale L2ARC buffer is immediately dropped.
6454fa94a07fSbrendan  *
6455fa94a07fSbrendan  * The performance of the L2ARC can be tweaked by a number of tunables, which
6456fa94a07fSbrendan  * may be necessary for different workloads:
6457fa94a07fSbrendan  *
6458fa94a07fSbrendan  *	l2arc_write_max		max write bytes per interval
64593a737e0dSbrendan  *	l2arc_write_boost	extra write bytes during device warmup
6460fa94a07fSbrendan  *	l2arc_noprefetch	skip caching prefetched buffers
6461fa94a07fSbrendan  *	l2arc_headroom		number of max device writes to precache
6462aad02571SSaso Kiselkov  *	l2arc_headroom_boost	when we find compressed buffers during ARC
6463aad02571SSaso Kiselkov  *				scanning, we multiply headroom by this
6464aad02571SSaso Kiselkov  *				percentage factor for the next scan cycle,
6465aad02571SSaso Kiselkov  *				since more compressed buffers are likely to
6466aad02571SSaso Kiselkov  *				be present
6467fa94a07fSbrendan  *	l2arc_feed_secs		seconds between L2ARC writing
6468fa94a07fSbrendan  *
6469fa94a07fSbrendan  * Tunables may be removed or added as future performance improvements are
6470fa94a07fSbrendan  * integrated, and also may become zpool properties.
64715a98e54bSBrendan Gregg - Sun Microsystems  *
64725a98e54bSBrendan Gregg - Sun Microsystems  * There are three key functions that control how the L2ARC warms up:
64735a98e54bSBrendan Gregg - Sun Microsystems  *
64745a98e54bSBrendan Gregg - Sun Microsystems  *	l2arc_write_eligible()	check if a buffer is eligible to cache
64755a98e54bSBrendan Gregg - Sun Microsystems  *	l2arc_write_size()	calculate how much to write
64765a98e54bSBrendan Gregg - Sun Microsystems  *	l2arc_write_interval()	calculate sleep delay between writes
64775a98e54bSBrendan Gregg - Sun Microsystems  *
64785a98e54bSBrendan Gregg - Sun Microsystems  * These three functions determine what to write, how much, and how quickly
64795a98e54bSBrendan Gregg - Sun Microsystems  * to send writes.
6480fa94a07fSbrendan  */
6481fa94a07fSbrendan 
64825a98e54bSBrendan Gregg - Sun Microsystems static boolean_t
64837adb730bSGeorge Wilson l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
64845a98e54bSBrendan Gregg - Sun Microsystems {
64855a98e54bSBrendan Gregg - Sun Microsystems 	/*
64865a98e54bSBrendan Gregg - Sun Microsystems 	 * A buffer is *not* eligible for the L2ARC if it:
64875a98e54bSBrendan Gregg - Sun Microsystems 	 * 1. belongs to a different spa.
64885ea40c06SBrendan Gregg - Sun Microsystems 	 * 2. is already cached on the L2ARC.
64895ea40c06SBrendan Gregg - Sun Microsystems 	 * 3. has an I/O in progress (it may be an incomplete read).
64905ea40c06SBrendan Gregg - Sun Microsystems 	 * 4. is flagged not eligible (zfs property).
64915a98e54bSBrendan Gregg - Sun Microsystems 	 */
649289c86e32SChris Williamson 	if (hdr->b_spa != spa_guid || HDR_HAS_L2HDR(hdr) ||
64937adb730bSGeorge Wilson 	    HDR_IO_IN_PROGRESS(hdr) || !HDR_L2CACHE(hdr))
64945a98e54bSBrendan Gregg - Sun Microsystems 		return (B_FALSE);
64955a98e54bSBrendan Gregg - Sun Microsystems 
64965a98e54bSBrendan Gregg - Sun Microsystems 	return (B_TRUE);
64975a98e54bSBrendan Gregg - Sun Microsystems }
64985a98e54bSBrendan Gregg - Sun Microsystems 
64995a98e54bSBrendan Gregg - Sun Microsystems static uint64_t
6500aad02571SSaso Kiselkov l2arc_write_size(void)
65015a98e54bSBrendan Gregg - Sun Microsystems {
65025a98e54bSBrendan Gregg - Sun Microsystems 	uint64_t size;
65035a98e54bSBrendan Gregg - Sun Microsystems 
6504aad02571SSaso Kiselkov 	/*
6505aad02571SSaso Kiselkov 	 * Make sure our globals have meaningful values in case the user
6506aad02571SSaso Kiselkov 	 * altered them.
6507aad02571SSaso Kiselkov 	 */
6508aad02571SSaso Kiselkov 	size = l2arc_write_max;
6509aad02571SSaso Kiselkov 	if (size == 0) {
6510aad02571SSaso Kiselkov 		cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
6511aad02571SSaso Kiselkov 		    "be greater than zero, resetting it to the default (%d)",
6512aad02571SSaso Kiselkov 		    L2ARC_WRITE_SIZE);
6513aad02571SSaso Kiselkov 		size = l2arc_write_max = L2ARC_WRITE_SIZE;
6514aad02571SSaso Kiselkov 	}
65155a98e54bSBrendan Gregg - Sun Microsystems 
65165a98e54bSBrendan Gregg - Sun Microsystems 	if (arc_warm == B_FALSE)
6517aad02571SSaso Kiselkov 		size += l2arc_write_boost;
65185a98e54bSBrendan Gregg - Sun Microsystems 
65195a98e54bSBrendan Gregg - Sun Microsystems 	return (size);
65205a98e54bSBrendan Gregg - Sun Microsystems 
65215a98e54bSBrendan Gregg - Sun Microsystems }
65225a98e54bSBrendan Gregg - Sun Microsystems 
65235a98e54bSBrendan Gregg - Sun Microsystems static clock_t
65245a98e54bSBrendan Gregg - Sun Microsystems l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
65255a98e54bSBrendan Gregg - Sun Microsystems {
6526d3d50737SRafael Vanoni 	clock_t interval, next, now;
65275a98e54bSBrendan Gregg - Sun Microsystems 
65285a98e54bSBrendan Gregg - Sun Microsystems 	/*
65295a98e54bSBrendan Gregg - Sun Microsystems 	 * If the ARC lists are busy, increase our write rate; if the
65305a98e54bSBrendan Gregg - Sun Microsystems 	 * lists are stale, idle back.  This is achieved by checking
65315a98e54bSBrendan Gregg - Sun Microsystems 	 * how much we previously wrote - if it was more than half of
65325a98e54bSBrendan Gregg - Sun Microsystems 	 * what we wanted, schedule the next write much sooner.
65335a98e54bSBrendan Gregg - Sun Microsystems 	 */
65345a98e54bSBrendan Gregg - Sun Microsystems 	if (l2arc_feed_again && wrote > (wanted / 2))
65355a98e54bSBrendan Gregg - Sun Microsystems 		interval = (hz * l2arc_feed_min_ms) / 1000;
65365a98e54bSBrendan Gregg - Sun Microsystems 	else
65375a98e54bSBrendan Gregg - Sun Microsystems 		interval = hz * l2arc_feed_secs;
65385a98e54bSBrendan Gregg - Sun Microsystems 
6539d3d50737SRafael Vanoni 	now = ddi_get_lbolt();
6540d3d50737SRafael Vanoni 	next = MAX(now, MIN(now + interval, began + interval));
65415a98e54bSBrendan Gregg - Sun Microsystems 
65425a98e54bSBrendan Gregg - Sun Microsystems 	return (next);
65435a98e54bSBrendan Gregg - Sun Microsystems }
65445a98e54bSBrendan Gregg - Sun Microsystems 
6545fa94a07fSbrendan /*
6546fa94a07fSbrendan  * Cycle through L2ARC devices.  This is how L2ARC load balances.
65473a737e0dSbrendan  * If a device is returned, this also returns holding the spa config lock.
6548fa94a07fSbrendan  */
6549fa94a07fSbrendan static l2arc_dev_t *
6550fa94a07fSbrendan l2arc_dev_get_next(void)
6551fa94a07fSbrendan {
65523a737e0dSbrendan 	l2arc_dev_t *first, *next = NULL;
65533a737e0dSbrendan 
65543a737e0dSbrendan 	/*
65553a737e0dSbrendan 	 * Lock out the removal of spas (spa_namespace_lock), then removal
65563a737e0dSbrendan 	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
65573a737e0dSbrendan 	 * both locks will be dropped and a spa config lock held instead.
65583a737e0dSbrendan 	 */
65593a737e0dSbrendan 	mutex_enter(&spa_namespace_lock);
65603a737e0dSbrendan 	mutex_enter(&l2arc_dev_mtx);
6561fa94a07fSbrendan 
6562c5904d13Seschrock 	/* if there are no vdevs, there is nothing to do */
6563c5904d13Seschrock 	if (l2arc_ndev == 0)
65643a737e0dSbrendan 		goto out;
6565c5904d13Seschrock 
6566c5904d13Seschrock 	first = NULL;
6567c5904d13Seschrock 	next = l2arc_dev_last;
6568c5904d13Seschrock 	do {
6569c5904d13Seschrock 		/* loop around the list looking for a non-faulted vdev */
6570c5904d13Seschrock 		if (next == NULL) {
6571fa94a07fSbrendan 			next = list_head(l2arc_dev_list);
6572c5904d13Seschrock 		} else {
6573c5904d13Seschrock 			next = list_next(l2arc_dev_list, next);
6574c5904d13Seschrock 			if (next == NULL)
6575c5904d13Seschrock 				next = list_head(l2arc_dev_list);
6576c5904d13Seschrock 		}
6577c5904d13Seschrock 
6578c5904d13Seschrock 		/* if we have come back to the start, bail out */
6579c5904d13Seschrock 		if (first == NULL)
6580c5904d13Seschrock 			first = next;
6581c5904d13Seschrock 		else if (next == first)
6582c5904d13Seschrock 			break;
6583c5904d13Seschrock 
6584c5904d13Seschrock 	} while (vdev_is_dead(next->l2ad_vdev));
6585c5904d13Seschrock 
6586c5904d13Seschrock 	/* if we were unable to find any usable vdevs, return NULL */
6587c5904d13Seschrock 	if (vdev_is_dead(next->l2ad_vdev))
65883a737e0dSbrendan 		next = NULL;
6589fa94a07fSbrendan 
6590fa94a07fSbrendan 	l2arc_dev_last = next;
6591fa94a07fSbrendan 
65923a737e0dSbrendan out:
65933a737e0dSbrendan 	mutex_exit(&l2arc_dev_mtx);
65943a737e0dSbrendan 
65953a737e0dSbrendan 	/*
65963a737e0dSbrendan 	 * Grab the config lock to prevent the 'next' device from being
65973a737e0dSbrendan 	 * removed while we are writing to it.
65983a737e0dSbrendan 	 */
65993a737e0dSbrendan 	if (next != NULL)
6600e14bb325SJeff Bonwick 		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
66013a737e0dSbrendan 	mutex_exit(&spa_namespace_lock);
66023a737e0dSbrendan 
6603fa94a07fSbrendan 	return (next);
6604fa94a07fSbrendan }
6605fa94a07fSbrendan 
66063a737e0dSbrendan /*
66073a737e0dSbrendan  * Free buffers that were tagged for destruction.
66083a737e0dSbrendan  */
66093a737e0dSbrendan static void
66103a737e0dSbrendan l2arc_do_free_on_write()
66113a737e0dSbrendan {
66123a737e0dSbrendan 	list_t *buflist;
66133a737e0dSbrendan 	l2arc_data_free_t *df, *df_prev;
66143a737e0dSbrendan 
66153a737e0dSbrendan 	mutex_enter(&l2arc_free_on_write_mtx);
66163a737e0dSbrendan 	buflist = l2arc_free_on_write;
66173a737e0dSbrendan 
66183a737e0dSbrendan 	for (df = list_tail(buflist); df; df = df_prev) {
66193a737e0dSbrendan 		df_prev = list_prev(buflist, df);
6620770499e1SDan Kimmel 		ASSERT3P(df->l2df_abd, !=, NULL);
6621770499e1SDan Kimmel 		abd_free(df->l2df_abd);
66223a737e0dSbrendan 		list_remove(buflist, df);
66233a737e0dSbrendan 		kmem_free(df, sizeof (l2arc_data_free_t));
66243a737e0dSbrendan 	}
66253a737e0dSbrendan 
66263a737e0dSbrendan 	mutex_exit(&l2arc_free_on_write_mtx);
66273a737e0dSbrendan }
66283a737e0dSbrendan 
6629fa94a07fSbrendan /*
6630fa94a07fSbrendan  * A write to a cache device has completed.  Update all headers to allow
6631fa94a07fSbrendan  * reads from these buffers to begin.
6632fa94a07fSbrendan  */
6633fa94a07fSbrendan static void
6634fa94a07fSbrendan l2arc_write_done(zio_t *zio)
6635fa94a07fSbrendan {
6636fa94a07fSbrendan 	l2arc_write_callback_t *cb;
6637fa94a07fSbrendan 	l2arc_dev_t *dev;
6638fa94a07fSbrendan 	list_t *buflist;
66397adb730bSGeorge Wilson 	arc_buf_hdr_t *head, *hdr, *hdr_prev;
6640fa94a07fSbrendan 	kmutex_t *hash_lock;
66413038a2b4SSaso Kiselkov 	int64_t bytes_dropped = 0;
6642fa94a07fSbrendan 
6643fa94a07fSbrendan 	cb = zio->io_private;
6644dcbf3bd6SGeorge Wilson 	ASSERT3P(cb, !=, NULL);
6645fa94a07fSbrendan 	dev = cb->l2wcb_dev;
6646dcbf3bd6SGeorge Wilson 	ASSERT3P(dev, !=, NULL);
6647fa94a07fSbrendan 	head = cb->l2wcb_head;
6648dcbf3bd6SGeorge Wilson 	ASSERT3P(head, !=, NULL);
664989c86e32SChris Williamson 	buflist = &dev->l2ad_buflist;
6650dcbf3bd6SGeorge Wilson 	ASSERT3P(buflist, !=, NULL);
6651fa94a07fSbrendan 	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
6652fa94a07fSbrendan 	    l2arc_write_callback_t *, cb);
6653fa94a07fSbrendan 
6654fa94a07fSbrendan 	if (zio->io_error != 0)
6655fa94a07fSbrendan 		ARCSTAT_BUMP(arcstat_l2_writes_error);
6656fa94a07fSbrendan 
6657fa94a07fSbrendan 	/*
6658fa94a07fSbrendan 	 * All writes completed, or an error was hit.
6659fa94a07fSbrendan 	 */
6660244781f1SPrakash Surya top:
6661244781f1SPrakash Surya 	mutex_enter(&dev->l2ad_mtx);
66627adb730bSGeorge Wilson 	for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
66637adb730bSGeorge Wilson 		hdr_prev = list_prev(buflist, hdr);
6664fa94a07fSbrendan 
66657adb730bSGeorge Wilson 		hash_lock = HDR_LOCK(hdr);
6666244781f1SPrakash Surya 
6667244781f1SPrakash Surya 		/*
6668244781f1SPrakash Surya 		 * We cannot use mutex_enter or else we can deadlock
6669244781f1SPrakash Surya 		 * with l2arc_write_buffers (due to swapping the order
6670244781f1SPrakash Surya 		 * the hash lock and l2ad_mtx are taken).
6671244781f1SPrakash Surya 		 */
6672fa94a07fSbrendan 		if (!mutex_tryenter(hash_lock)) {
6673fa94a07fSbrendan 			/*
6674244781f1SPrakash Surya 			 * Missed the hash lock. We must retry so we
6675244781f1SPrakash Surya 			 * don't leave the ARC_FLAG_L2_WRITING bit set.
6676fa94a07fSbrendan 			 */
6677244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
6678244781f1SPrakash Surya 
6679244781f1SPrakash Surya 			/*
6680244781f1SPrakash Surya 			 * We don't want to rescan the headers we've
6681244781f1SPrakash Surya 			 * already marked as having been written out, so
6682244781f1SPrakash Surya 			 * we reinsert the head node so we can pick up
6683244781f1SPrakash Surya 			 * where we left off.
6684244781f1SPrakash Surya 			 */
6685244781f1SPrakash Surya 			list_remove(buflist, head);
6686244781f1SPrakash Surya 			list_insert_after(buflist, hdr, head);
6687244781f1SPrakash Surya 
6688244781f1SPrakash Surya 			mutex_exit(&dev->l2ad_mtx);
6689244781f1SPrakash Surya 
6690244781f1SPrakash Surya 			/*
6691244781f1SPrakash Surya 			 * We wait for the hash lock to become available
6692244781f1SPrakash Surya 			 * to try and prevent busy waiting, and increase
6693244781f1SPrakash Surya 			 * the chance we'll be able to acquire the lock
6694244781f1SPrakash Surya 			 * the next time around.
6695244781f1SPrakash Surya 			 */
6696244781f1SPrakash Surya 			mutex_enter(hash_lock);
6697244781f1SPrakash Surya 			mutex_exit(hash_lock);
6698244781f1SPrakash Surya 			goto top;
6699fa94a07fSbrendan 		}
6700fa94a07fSbrendan 
670189c86e32SChris Williamson 		/*
6702244781f1SPrakash Surya 		 * We could not have been moved into the arc_l2c_only
6703244781f1SPrakash Surya 		 * state while in-flight due to our ARC_FLAG_L2_WRITING
6704244781f1SPrakash Surya 		 * bit being set. Let's just ensure that's being enforced.
6705244781f1SPrakash Surya 		 */
6706244781f1SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(hdr));
6707244781f1SPrakash Surya 
6708fa94a07fSbrendan 		if (zio->io_error != 0) {
6709fa94a07fSbrendan 			/*
67103a737e0dSbrendan 			 * Error - drop L2ARC entry.
6711fa94a07fSbrendan 			 */
67127adb730bSGeorge Wilson 			list_remove(buflist, hdr);
6713dcbf3bd6SGeorge Wilson 			arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
671489c86e32SChris Williamson 
671516a7e5acSAndriy Gapon 			ARCSTAT_INCR(arcstat_l2_psize, -arc_hdr_size(hdr));
671616a7e5acSAndriy Gapon 			ARCSTAT_INCR(arcstat_l2_lsize, -HDR_GET_LSIZE(hdr));
6717a52fc310SPrakash Surya 
6718dcbf3bd6SGeorge Wilson 			bytes_dropped += arc_hdr_size(hdr);
6719a52fc310SPrakash Surya 			(void) refcount_remove_many(&dev->l2ad_alloc,
6720dcbf3bd6SGeorge Wilson 			    arc_hdr_size(hdr), hdr);
6721fa94a07fSbrendan 		}
6722fa94a07fSbrendan 
6723fa94a07fSbrendan 		/*
6724244781f1SPrakash Surya 		 * Allow ARC to begin reads and ghost list evictions to
6725244781f1SPrakash Surya 		 * this L2ARC entry.
6726fa94a07fSbrendan 		 */
6727dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_L2_WRITING);
6728fa94a07fSbrendan 
6729fa94a07fSbrendan 		mutex_exit(hash_lock);
6730fa94a07fSbrendan 	}
6731fa94a07fSbrendan 
6732fa94a07fSbrendan 	atomic_inc_64(&l2arc_writes_done);
6733fa94a07fSbrendan 	list_remove(buflist, head);
673489c86e32SChris Williamson 	ASSERT(!HDR_HAS_L1HDR(head));
673589c86e32SChris Williamson 	kmem_cache_free(hdr_l2only_cache, head);
673689c86e32SChris Williamson 	mutex_exit(&dev->l2ad_mtx);
6737fa94a07fSbrendan 
67383038a2b4SSaso Kiselkov 	vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
67393038a2b4SSaso Kiselkov 
67403a737e0dSbrendan 	l2arc_do_free_on_write();
6741fa94a07fSbrendan 
6742fa94a07fSbrendan 	kmem_free(cb, sizeof (l2arc_write_callback_t));
6743fa94a07fSbrendan }
6744fa94a07fSbrendan 
6745fa94a07fSbrendan /*
6746fa94a07fSbrendan  * A read to a cache device completed.  Validate buffer contents before
6747fa94a07fSbrendan  * handing over to the regular ARC routines.
6748fa94a07fSbrendan  */
6749fa94a07fSbrendan static void
6750fa94a07fSbrendan l2arc_read_done(zio_t *zio)
6751fa94a07fSbrendan {
6752fa94a07fSbrendan 	l2arc_read_callback_t *cb;
6753fa94a07fSbrendan 	arc_buf_hdr_t *hdr;
6754fa94a07fSbrendan 	kmutex_t *hash_lock;
6755dcbf3bd6SGeorge Wilson 	boolean_t valid_cksum;
6756fa94a07fSbrendan 
6757dcbf3bd6SGeorge Wilson 	ASSERT3P(zio->io_vd, !=, NULL);
6758e14bb325SJeff Bonwick 	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
6759e14bb325SJeff Bonwick 
6760e14bb325SJeff Bonwick 	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
6761e14bb325SJeff Bonwick 
6762fa94a07fSbrendan 	cb = zio->io_private;
6763dcbf3bd6SGeorge Wilson 	ASSERT3P(cb, !=, NULL);
6764dcbf3bd6SGeorge Wilson 	hdr = cb->l2rcb_hdr;
6765dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr, !=, NULL);
6766fa94a07fSbrendan 
6767dcbf3bd6SGeorge Wilson 	hash_lock = HDR_LOCK(hdr);
6768fa94a07fSbrendan 	mutex_enter(hash_lock);
67693f9d6ad7SLin Ling 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
6770fa94a07fSbrendan 
6771403a8da7SAndriy Gapon 	/*
6772403a8da7SAndriy Gapon 	 * If the data was read into a temporary buffer,
6773403a8da7SAndriy Gapon 	 * move it and free the buffer.
6774403a8da7SAndriy Gapon 	 */
6775403a8da7SAndriy Gapon 	if (cb->l2rcb_abd != NULL) {
6776403a8da7SAndriy Gapon 		ASSERT3U(arc_hdr_size(hdr), <, zio->io_size);
6777403a8da7SAndriy Gapon 		if (zio->io_error == 0) {
6778403a8da7SAndriy Gapon 			abd_copy(hdr->b_l1hdr.b_pabd, cb->l2rcb_abd,
6779403a8da7SAndriy Gapon 			    arc_hdr_size(hdr));
6780403a8da7SAndriy Gapon 		}
6781403a8da7SAndriy Gapon 
6782403a8da7SAndriy Gapon 		/*
6783403a8da7SAndriy Gapon 		 * The following must be done regardless of whether
6784403a8da7SAndriy Gapon 		 * there was an error:
6785403a8da7SAndriy Gapon 		 * - free the temporary buffer
6786403a8da7SAndriy Gapon 		 * - point zio to the real ARC buffer
6787403a8da7SAndriy Gapon 		 * - set zio size accordingly
6788403a8da7SAndriy Gapon 		 * These are required because zio is either re-used for
6789403a8da7SAndriy Gapon 		 * an I/O of the block in the case of the error
6790403a8da7SAndriy Gapon 		 * or the zio is passed to arc_read_done() and it
6791403a8da7SAndriy Gapon 		 * needs real data.
6792403a8da7SAndriy Gapon 		 */
6793403a8da7SAndriy Gapon 		abd_free(cb->l2rcb_abd);
6794403a8da7SAndriy Gapon 		zio->io_size = zio->io_orig_size = arc_hdr_size(hdr);
6795403a8da7SAndriy Gapon 		zio->io_abd = zio->io_orig_abd = hdr->b_l1hdr.b_pabd;
6796403a8da7SAndriy Gapon 	}
6797403a8da7SAndriy Gapon 
6798770499e1SDan Kimmel 	ASSERT3P(zio->io_abd, !=, NULL);
6799aad02571SSaso Kiselkov 
6800fa94a07fSbrendan 	/*
6801fa94a07fSbrendan 	 * Check this survived the L2ARC journey.
6802fa94a07fSbrendan 	 */
6803770499e1SDan Kimmel 	ASSERT3P(zio->io_abd, ==, hdr->b_l1hdr.b_pabd);
6804dcbf3bd6SGeorge Wilson 	zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
6805dcbf3bd6SGeorge Wilson 	zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
6806dcbf3bd6SGeorge Wilson 
6807dcbf3bd6SGeorge Wilson 	valid_cksum = arc_cksum_is_equal(hdr, zio);
6808dcbf3bd6SGeorge Wilson 	if (valid_cksum && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
6809fa94a07fSbrendan 		mutex_exit(hash_lock);
6810dcbf3bd6SGeorge Wilson 		zio->io_private = hdr;
6811fa94a07fSbrendan 		arc_read_done(zio);
6812fa94a07fSbrendan 	} else {
6813fa94a07fSbrendan 		mutex_exit(hash_lock);
6814fa94a07fSbrendan 		/*
6815fa94a07fSbrendan 		 * Buffer didn't survive caching.  Increment stats and
6816fa94a07fSbrendan 		 * reissue to the original storage device.
6817fa94a07fSbrendan 		 */
68183a737e0dSbrendan 		if (zio->io_error != 0) {
6819fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_io_error);
68203a737e0dSbrendan 		} else {
6821be6fd75aSMatthew Ahrens 			zio->io_error = SET_ERROR(EIO);
68223a737e0dSbrendan 		}
6823dcbf3bd6SGeorge Wilson 		if (!valid_cksum)
6824fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
6825fa94a07fSbrendan 
6826e14bb325SJeff Bonwick 		/*
6827e14bb325SJeff Bonwick 		 * If there's no waiter, issue an async i/o to the primary
6828e14bb325SJeff Bonwick 		 * storage now.  If there *is* a waiter, the caller must
6829e14bb325SJeff Bonwick 		 * issue the i/o in a context where it's OK to block.
6830e14bb325SJeff Bonwick 		 */
6831a3f829aeSBill Moore 		if (zio->io_waiter == NULL) {
6832a3f829aeSBill Moore 			zio_t *pio = zio_unique_parent(zio);
6833a3f829aeSBill Moore 
6834a3f829aeSBill Moore 			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
6835a3f829aeSBill Moore 
6836dcbf3bd6SGeorge Wilson 			zio_nowait(zio_read(pio, zio->io_spa, zio->io_bp,
6837770499e1SDan Kimmel 			    hdr->b_l1hdr.b_pabd, zio->io_size, arc_read_done,
6838dcbf3bd6SGeorge Wilson 			    hdr, zio->io_priority, cb->l2rcb_flags,
6839dcbf3bd6SGeorge Wilson 			    &cb->l2rcb_zb));
6840a3f829aeSBill Moore 		}
6841fa94a07fSbrendan 	}
6842fa94a07fSbrendan 
6843fa94a07fSbrendan 	kmem_free(cb, sizeof (l2arc_read_callback_t));
6844fa94a07fSbrendan }
6845fa94a07fSbrendan 
6846fa94a07fSbrendan /*
6847fa94a07fSbrendan  * This is the list priority from which the L2ARC will search for pages to
6848fa94a07fSbrendan  * cache.  This is used within loops (0..3) to cycle through lists in the
6849fa94a07fSbrendan  * desired order.  This order can have a significant effect on cache
6850fa94a07fSbrendan  * performance.
6851fa94a07fSbrendan  *
6852fa94a07fSbrendan  * Currently the metadata lists are hit first, MFU then MRU, followed by
6853fa94a07fSbrendan  * the data lists.  This function returns a locked list, and also returns
6854fa94a07fSbrendan  * the lock pointer.
6855fa94a07fSbrendan  */
6856244781f1SPrakash Surya static multilist_sublist_t *
6857244781f1SPrakash Surya l2arc_sublist_lock(int list_num)
6858fa94a07fSbrendan {
6859244781f1SPrakash Surya 	multilist_t *ml = NULL;
6860244781f1SPrakash Surya 	unsigned int idx;
6861fa94a07fSbrendan 
6862fa94a07fSbrendan 	ASSERT(list_num >= 0 && list_num <= 3);
6863fa94a07fSbrendan 
6864fa94a07fSbrendan 	switch (list_num) {
6865fa94a07fSbrendan 	case 0:
686694c2d0ebSMatthew Ahrens 		ml = arc_mfu->arcs_list[ARC_BUFC_METADATA];
6867fa94a07fSbrendan 		break;
6868fa94a07fSbrendan 	case 1:
686994c2d0ebSMatthew Ahrens 		ml = arc_mru->arcs_list[ARC_BUFC_METADATA];
6870fa94a07fSbrendan 		break;
6871fa94a07fSbrendan 	case 2:
687294c2d0ebSMatthew Ahrens 		ml = arc_mfu->arcs_list[ARC_BUFC_DATA];
6873fa94a07fSbrendan 		break;
6874fa94a07fSbrendan 	case 3:
687594c2d0ebSMatthew Ahrens 		ml = arc_mru->arcs_list[ARC_BUFC_DATA];
6876fa94a07fSbrendan 		break;
6877fa94a07fSbrendan 	}
6878fa94a07fSbrendan 
6879244781f1SPrakash Surya 	/*
6880244781f1SPrakash Surya 	 * Return a randomly-selected sublist. This is acceptable
6881244781f1SPrakash Surya 	 * because the caller feeds only a little bit of data for each
6882244781f1SPrakash Surya 	 * call (8MB). Subsequent calls will result in different
6883244781f1SPrakash Surya 	 * sublists being selected.
6884244781f1SPrakash Surya 	 */
6885244781f1SPrakash Surya 	idx = multilist_get_random_index(ml);
6886244781f1SPrakash Surya 	return (multilist_sublist_lock(ml, idx));
6887fa94a07fSbrendan }
6888fa94a07fSbrendan 
6889fa94a07fSbrendan /*
6890fa94a07fSbrendan  * Evict buffers from the device write hand to the distance specified in
6891fa94a07fSbrendan  * bytes.  This distance may span populated buffers, it may span nothing.
6892fa94a07fSbrendan  * This is clearing a region on the L2ARC device ready for writing.
6893fa94a07fSbrendan  * If the 'all' boolean is set, every buffer is evicted.
6894fa94a07fSbrendan  */
6895fa94a07fSbrendan static void
6896fa94a07fSbrendan l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
6897fa94a07fSbrendan {
6898fa94a07fSbrendan 	list_t *buflist;
68997adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr, *hdr_prev;
6900fa94a07fSbrendan 	kmutex_t *hash_lock;
6901fa94a07fSbrendan 	uint64_t taddr;
6902fa94a07fSbrendan 
690389c86e32SChris Williamson 	buflist = &dev->l2ad_buflist;
6904fa94a07fSbrendan 
6905fa94a07fSbrendan 	if (!all && dev->l2ad_first) {
6906fa94a07fSbrendan 		/*
6907fa94a07fSbrendan 		 * This is the first sweep through the device.  There is
6908fa94a07fSbrendan 		 * nothing to evict.
6909fa94a07fSbrendan 		 */
6910fa94a07fSbrendan 		return;
6911fa94a07fSbrendan 	}
6912fa94a07fSbrendan 
69133a737e0dSbrendan 	if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
6914fa94a07fSbrendan 		/*
6915fa94a07fSbrendan 		 * When nearing the end of the device, evict to the end
6916fa94a07fSbrendan 		 * before the device write hand jumps to the start.
6917fa94a07fSbrendan 		 */
6918fa94a07fSbrendan 		taddr = dev->l2ad_end;
6919fa94a07fSbrendan 	} else {
6920fa94a07fSbrendan 		taddr = dev->l2ad_hand + distance;
6921fa94a07fSbrendan 	}
6922fa94a07fSbrendan 	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
6923fa94a07fSbrendan 	    uint64_t, taddr, boolean_t, all);
6924fa94a07fSbrendan 
6925fa94a07fSbrendan top:
692689c86e32SChris Williamson 	mutex_enter(&dev->l2ad_mtx);
69277adb730bSGeorge Wilson 	for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
69287adb730bSGeorge Wilson 		hdr_prev = list_prev(buflist, hdr);
6929fa94a07fSbrendan 
69307adb730bSGeorge Wilson 		hash_lock = HDR_LOCK(hdr);
6931244781f1SPrakash Surya 
6932244781f1SPrakash Surya 		/*
6933244781f1SPrakash Surya 		 * We cannot use mutex_enter or else we can deadlock
6934244781f1SPrakash Surya 		 * with l2arc_write_buffers (due to swapping the order
6935244781f1SPrakash Surya 		 * the hash lock and l2ad_mtx are taken).
6936244781f1SPrakash Surya 		 */
6937fa94a07fSbrendan 		if (!mutex_tryenter(hash_lock)) {
6938fa94a07fSbrendan 			/*
6939fa94a07fSbrendan 			 * Missed the hash lock.  Retry.
6940fa94a07fSbrendan 			 */
6941fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
694289c86e32SChris Williamson 			mutex_exit(&dev->l2ad_mtx);
6943fa94a07fSbrendan 			mutex_enter(hash_lock);
6944fa94a07fSbrendan 			mutex_exit(hash_lock);
6945fa94a07fSbrendan 			goto top;
6946fa94a07fSbrendan 		}
6947fa94a07fSbrendan 
6948267ae6c3SAndriy Gapon 		/*
6949267ae6c3SAndriy Gapon 		 * A header can't be on this list if it doesn't have L2 header.
6950267ae6c3SAndriy Gapon 		 */
6951267ae6c3SAndriy Gapon 		ASSERT(HDR_HAS_L2HDR(hdr));
6952fa94a07fSbrendan 
6953267ae6c3SAndriy Gapon 		/* Ensure this header has finished being written. */
6954267ae6c3SAndriy Gapon 		ASSERT(!HDR_L2_WRITING(hdr));
6955267ae6c3SAndriy Gapon 		ASSERT(!HDR_L2_WRITE_HEAD(hdr));
6956267ae6c3SAndriy Gapon 
6957267ae6c3SAndriy Gapon 		if (!all && (hdr->b_l2hdr.b_daddr >= taddr ||
695889c86e32SChris Williamson 		    hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
6959fa94a07fSbrendan 			/*
6960fa94a07fSbrendan 			 * We've evicted to the target address,
6961fa94a07fSbrendan 			 * or the end of the device.
6962fa94a07fSbrendan 			 */
6963fa94a07fSbrendan 			mutex_exit(hash_lock);
6964fa94a07fSbrendan 			break;
6965fa94a07fSbrendan 		}
6966fa94a07fSbrendan 
696789c86e32SChris Williamson 		if (!HDR_HAS_L1HDR(hdr)) {
69687adb730bSGeorge Wilson 			ASSERT(!HDR_L2_READING(hdr));
6969fa94a07fSbrendan 			/*
6970fa94a07fSbrendan 			 * This doesn't exist in the ARC.  Destroy.
6971fa94a07fSbrendan 			 * arc_hdr_destroy() will call list_remove()
697216a7e5acSAndriy Gapon 			 * and decrement arcstat_l2_lsize.
6973fa94a07fSbrendan 			 */
69747adb730bSGeorge Wilson 			arc_change_state(arc_anon, hdr, hash_lock);
69757adb730bSGeorge Wilson 			arc_hdr_destroy(hdr);
6976fa94a07fSbrendan 		} else {
697789c86e32SChris Williamson 			ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
697889c86e32SChris Williamson 			ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
69793a737e0dSbrendan 			/*
69803a737e0dSbrendan 			 * Invalidate issued or about to be issued
69813a737e0dSbrendan 			 * reads, since we may be about to write
69823a737e0dSbrendan 			 * over this location.
69833a737e0dSbrendan 			 */
69847adb730bSGeorge Wilson 			if (HDR_L2_READING(hdr)) {
69853a737e0dSbrendan 				ARCSTAT_BUMP(arcstat_l2_evict_reading);
6986dcbf3bd6SGeorge Wilson 				arc_hdr_set_flags(hdr, ARC_FLAG_L2_EVICTED);
69873a737e0dSbrendan 			}
69883a737e0dSbrendan 
6989a52fc310SPrakash Surya 			arc_hdr_l2hdr_destroy(hdr);
6990fa94a07fSbrendan 		}
6991fa94a07fSbrendan 		mutex_exit(hash_lock);
6992fa94a07fSbrendan 	}
699389c86e32SChris Williamson 	mutex_exit(&dev->l2ad_mtx);
6994fa94a07fSbrendan }
6995fa94a07fSbrendan 
6996fa94a07fSbrendan /*
6997fa94a07fSbrendan  * Find and write ARC buffers to the L2ARC device.
6998fa94a07fSbrendan  *
69997adb730bSGeorge Wilson  * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
7000fa94a07fSbrendan  * for reading until they have completed writing.
7001aad02571SSaso Kiselkov  * The headroom_boost is an in-out parameter used to maintain headroom boost
7002aad02571SSaso Kiselkov  * state between calls to this function.
7003aad02571SSaso Kiselkov  *
7004aad02571SSaso Kiselkov  * Returns the number of bytes actually written (which may be smaller than
7005aad02571SSaso Kiselkov  * the delta by which the device hand has changed due to alignment).
7006fa94a07fSbrendan  */
70075a98e54bSBrendan Gregg - Sun Microsystems static uint64_t
7008dcbf3bd6SGeorge Wilson l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
7009fa94a07fSbrendan {
70107adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr, *hdr_prev, *head;
701116a7e5acSAndriy Gapon 	uint64_t write_asize, write_psize, write_lsize, headroom;
7012aad02571SSaso Kiselkov 	boolean_t full;
7013fa94a07fSbrendan 	l2arc_write_callback_t *cb;
7014fa94a07fSbrendan 	zio_t *pio, *wzio;
7015e9103aaeSGarrett D'Amore 	uint64_t guid = spa_load_guid(spa);
7016fa94a07fSbrendan 
7017dcbf3bd6SGeorge Wilson 	ASSERT3P(dev->l2ad_vdev, !=, NULL);
7018aad02571SSaso Kiselkov 
7019fa94a07fSbrendan 	pio = NULL;
702016a7e5acSAndriy Gapon 	write_lsize = write_asize = write_psize = 0;
7021fa94a07fSbrendan 	full = B_FALSE;
702289c86e32SChris Williamson 	head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
7023dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(head, ARC_FLAG_L2_WRITE_HEAD | ARC_FLAG_HAS_L2HDR);
7024aad02571SSaso Kiselkov 
7025fa94a07fSbrendan 	/*
7026fa94a07fSbrendan 	 * Copy buffers for L2ARC writing.
7027fa94a07fSbrendan 	 */
7028fa94a07fSbrendan 	for (int try = 0; try <= 3; try++) {
7029244781f1SPrakash Surya 		multilist_sublist_t *mls = l2arc_sublist_lock(try);
7030aad02571SSaso Kiselkov 		uint64_t passed_sz = 0;
7031aad02571SSaso Kiselkov 
70323a737e0dSbrendan 		/*
70333a737e0dSbrendan 		 * L2ARC fast warmup.
70343a737e0dSbrendan 		 *
70353a737e0dSbrendan 		 * Until the ARC is warm and starts to evict, read from the
70363a737e0dSbrendan 		 * head of the ARC lists rather than the tail.
70373a737e0dSbrendan 		 */
70383a737e0dSbrendan 		if (arc_warm == B_FALSE)
7039244781f1SPrakash Surya 			hdr = multilist_sublist_head(mls);
70403a737e0dSbrendan 		else
7041244781f1SPrakash Surya 			hdr = multilist_sublist_tail(mls);
70423a737e0dSbrendan 
7043aad02571SSaso Kiselkov 		headroom = target_sz * l2arc_headroom;
7044dcbf3bd6SGeorge Wilson 		if (zfs_compressed_arc_enabled)
7045aad02571SSaso Kiselkov 			headroom = (headroom * l2arc_headroom_boost) / 100;
7046aad02571SSaso Kiselkov 
70477adb730bSGeorge Wilson 		for (; hdr; hdr = hdr_prev) {
7048aad02571SSaso Kiselkov 			kmutex_t *hash_lock;
7049aad02571SSaso Kiselkov 
70503a737e0dSbrendan 			if (arc_warm == B_FALSE)
7051244781f1SPrakash Surya 				hdr_prev = multilist_sublist_next(mls, hdr);
70523a737e0dSbrendan 			else
7053244781f1SPrakash Surya 				hdr_prev = multilist_sublist_prev(mls, hdr);
7054fa94a07fSbrendan 
70557adb730bSGeorge Wilson 			hash_lock = HDR_LOCK(hdr);
7056aad02571SSaso Kiselkov 			if (!mutex_tryenter(hash_lock)) {
7057fa94a07fSbrendan 				/*
7058fa94a07fSbrendan 				 * Skip this buffer rather than waiting.
7059fa94a07fSbrendan 				 */
7060fa94a07fSbrendan 				continue;
7061fa94a07fSbrendan 			}
7062fa94a07fSbrendan 
7063dcbf3bd6SGeorge Wilson 			passed_sz += HDR_GET_LSIZE(hdr);
7064fa94a07fSbrendan 			if (passed_sz > headroom) {
7065fa94a07fSbrendan 				/*
7066fa94a07fSbrendan 				 * Searched too far.
7067fa94a07fSbrendan 				 */
7068fa94a07fSbrendan 				mutex_exit(hash_lock);
7069fa94a07fSbrendan 				break;
7070fa94a07fSbrendan 			}
7071fa94a07fSbrendan 
70727adb730bSGeorge Wilson 			if (!l2arc_write_eligible(guid, hdr)) {
7073fa94a07fSbrendan 				mutex_exit(hash_lock);
7074fa94a07fSbrendan 				continue;
7075fa94a07fSbrendan 			}
7076fa94a07fSbrendan 
707716a7e5acSAndriy Gapon 			/*
707816a7e5acSAndriy Gapon 			 * We rely on the L1 portion of the header below, so
707916a7e5acSAndriy Gapon 			 * it's invalid for this header to have been evicted out
708016a7e5acSAndriy Gapon 			 * of the ghost cache, prior to being written out. The
708116a7e5acSAndriy Gapon 			 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
708216a7e5acSAndriy Gapon 			 */
708316a7e5acSAndriy Gapon 			ASSERT(HDR_HAS_L1HDR(hdr));
708416a7e5acSAndriy Gapon 
708516a7e5acSAndriy Gapon 			ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
708616a7e5acSAndriy Gapon 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
708716a7e5acSAndriy Gapon 			ASSERT3U(arc_hdr_size(hdr), >, 0);
708816a7e5acSAndriy Gapon 			uint64_t psize = arc_hdr_size(hdr);
708916a7e5acSAndriy Gapon 			uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev,
709016a7e5acSAndriy Gapon 			    psize);
709116a7e5acSAndriy Gapon 
709216a7e5acSAndriy Gapon 			if ((write_asize + asize) > target_sz) {
7093fa94a07fSbrendan 				full = B_TRUE;
7094fa94a07fSbrendan 				mutex_exit(hash_lock);
7095fa94a07fSbrendan 				break;
7096fa94a07fSbrendan 			}
7097fa94a07fSbrendan 
7098fa94a07fSbrendan 			if (pio == NULL) {
7099fa94a07fSbrendan 				/*
7100fa94a07fSbrendan 				 * Insert a dummy header on the buflist so
7101fa94a07fSbrendan 				 * l2arc_write_done() can find where the
7102fa94a07fSbrendan 				 * write buffers begin without searching.
7103fa94a07fSbrendan 				 */
7104244781f1SPrakash Surya 				mutex_enter(&dev->l2ad_mtx);
710589c86e32SChris Williamson 				list_insert_head(&dev->l2ad_buflist, head);
7106244781f1SPrakash Surya 				mutex_exit(&dev->l2ad_mtx);
7107fa94a07fSbrendan 
7108fa94a07fSbrendan 				cb = kmem_alloc(
7109fa94a07fSbrendan 				    sizeof (l2arc_write_callback_t), KM_SLEEP);
7110fa94a07fSbrendan 				cb->l2wcb_dev = dev;
7111fa94a07fSbrendan 				cb->l2wcb_head = head;
7112fa94a07fSbrendan 				pio = zio_root(spa, l2arc_write_done, cb,
7113fa94a07fSbrendan 				    ZIO_FLAG_CANFAIL);
7114fa94a07fSbrendan 			}
7115fa94a07fSbrendan 
711689c86e32SChris Williamson 			hdr->b_l2hdr.b_dev = dev;
7117dcbf3bd6SGeorge Wilson 			hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
7118dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr,
7119dcbf3bd6SGeorge Wilson 			    ARC_FLAG_L2_WRITING | ARC_FLAG_HAS_L2HDR);
7120dcbf3bd6SGeorge Wilson 
7121dcbf3bd6SGeorge Wilson 			mutex_enter(&dev->l2ad_mtx);
7122dcbf3bd6SGeorge Wilson 			list_insert_head(&dev->l2ad_buflist, hdr);
7123dcbf3bd6SGeorge Wilson 			mutex_exit(&dev->l2ad_mtx);
7124dcbf3bd6SGeorge Wilson 
712516a7e5acSAndriy Gapon 			(void) refcount_add_many(&dev->l2ad_alloc, psize, hdr);
7126aad02571SSaso Kiselkov 
7127a52fc310SPrakash Surya 			/*
7128dcbf3bd6SGeorge Wilson 			 * Normally the L2ARC can use the hdr's data, but if
7129dcbf3bd6SGeorge Wilson 			 * we're sharing data between the hdr and one of its
7130dcbf3bd6SGeorge Wilson 			 * bufs, L2ARC needs its own copy of the data so that
7131403a8da7SAndriy Gapon 			 * the ZIO below can't race with the buf consumer.
7132403a8da7SAndriy Gapon 			 * Another case where we need to create a copy of the
7133403a8da7SAndriy Gapon 			 * data is when the buffer size is not device-aligned
7134403a8da7SAndriy Gapon 			 * and we need to pad the block to make it such.
7135403a8da7SAndriy Gapon 			 * That also keeps the clock hand suitably aligned.
7136403a8da7SAndriy Gapon 			 *
7137403a8da7SAndriy Gapon 			 * To ensure that the copy will be available for the
7138dcbf3bd6SGeorge Wilson 			 * lifetime of the ZIO and be cleaned up afterwards, we
7139dcbf3bd6SGeorge Wilson 			 * add it to the l2arc_free_on_write queue.
7140a52fc310SPrakash Surya 			 */
7141770499e1SDan Kimmel 			abd_t *to_write;
714216a7e5acSAndriy Gapon 			if (!HDR_SHARED_DATA(hdr) && psize == asize) {
7143770499e1SDan Kimmel 				to_write = hdr->b_l1hdr.b_pabd;
7144dcbf3bd6SGeorge Wilson 			} else {
7145403a8da7SAndriy Gapon 				to_write = abd_alloc_for_io(asize,
7146770499e1SDan Kimmel 				    HDR_ISTYPE_METADATA(hdr));
714716a7e5acSAndriy Gapon 				abd_copy(to_write, hdr->b_l1hdr.b_pabd, psize);
714816a7e5acSAndriy Gapon 				if (asize != psize) {
714916a7e5acSAndriy Gapon 					abd_zero_off(to_write, psize,
715016a7e5acSAndriy Gapon 					    asize - psize);
7151403a8da7SAndriy Gapon 				}
715216a7e5acSAndriy Gapon 				l2arc_free_abd_on_write(to_write, asize,
7153770499e1SDan Kimmel 				    arc_buf_type(hdr));
7154dcbf3bd6SGeorge Wilson 			}
7155dcbf3bd6SGeorge Wilson 			wzio = zio_write_phys(pio, dev->l2ad_vdev,
7156403a8da7SAndriy Gapon 			    hdr->b_l2hdr.b_daddr, asize, to_write,
7157dcbf3bd6SGeorge Wilson 			    ZIO_CHECKSUM_OFF, NULL, hdr,
7158dcbf3bd6SGeorge Wilson 			    ZIO_PRIORITY_ASYNC_WRITE,
7159dcbf3bd6SGeorge Wilson 			    ZIO_FLAG_CANFAIL, B_FALSE);
7160aad02571SSaso Kiselkov 
716116a7e5acSAndriy Gapon 			write_lsize += HDR_GET_LSIZE(hdr);
7162dcbf3bd6SGeorge Wilson 			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
7163dcbf3bd6SGeorge Wilson 			    zio_t *, wzio);
7164fa94a07fSbrendan 
716516a7e5acSAndriy Gapon 			write_psize += psize;
716616a7e5acSAndriy Gapon 			write_asize += asize;
7167dcbf3bd6SGeorge Wilson 			dev->l2ad_hand += asize;
7168fa94a07fSbrendan 
7169fa94a07fSbrendan 			mutex_exit(hash_lock);
7170fa94a07fSbrendan 
7171dcbf3bd6SGeorge Wilson 			(void) zio_nowait(wzio);
7172aad02571SSaso Kiselkov 		}
7173aad02571SSaso Kiselkov 
7174244781f1SPrakash Surya 		multilist_sublist_unlock(mls);
7175aad02571SSaso Kiselkov 
7176aad02571SSaso Kiselkov 		if (full == B_TRUE)
7177aad02571SSaso Kiselkov 			break;
7178aad02571SSaso Kiselkov 	}
7179aad02571SSaso Kiselkov 
7180aad02571SSaso Kiselkov 	/* No buffers selected for writing? */
7181aad02571SSaso Kiselkov 	if (pio == NULL) {
718216a7e5acSAndriy Gapon 		ASSERT0(write_lsize);
718389c86e32SChris Williamson 		ASSERT(!HDR_HAS_L1HDR(head));
718489c86e32SChris Williamson 		kmem_cache_free(hdr_l2only_cache, head);
7185aad02571SSaso Kiselkov 		return (0);
7186aad02571SSaso Kiselkov 	}
7187aad02571SSaso Kiselkov 
7188aad02571SSaso Kiselkov 	ASSERT3U(write_asize, <=, target_sz);
7189fa94a07fSbrendan 	ARCSTAT_BUMP(arcstat_l2_writes_sent);
719016a7e5acSAndriy Gapon 	ARCSTAT_INCR(arcstat_l2_write_bytes, write_psize);
719116a7e5acSAndriy Gapon 	ARCSTAT_INCR(arcstat_l2_lsize, write_lsize);
719216a7e5acSAndriy Gapon 	ARCSTAT_INCR(arcstat_l2_psize, write_psize);
719316a7e5acSAndriy Gapon 	vdev_space_update(dev->l2ad_vdev, write_psize, 0, 0);
7194fa94a07fSbrendan 
7195fa94a07fSbrendan 	/*
7196fa94a07fSbrendan 	 * Bump device hand to the device start if it is approaching the end.
7197fa94a07fSbrendan 	 * l2arc_evict() will already have evicted ahead for this case.
7198fa94a07fSbrendan 	 */
71993a737e0dSbrendan 	if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
7200fa94a07fSbrendan 		dev->l2ad_hand = dev->l2ad_start;
7201fa94a07fSbrendan 		dev->l2ad_first = B_FALSE;
7202fa94a07fSbrendan 	}
7203fa94a07fSbrendan 
72045a98e54bSBrendan Gregg - Sun Microsystems 	dev->l2ad_writing = B_TRUE;
7205fa94a07fSbrendan 	(void) zio_wait(pio);
72065a98e54bSBrendan Gregg - Sun Microsystems 	dev->l2ad_writing = B_FALSE;
72075a98e54bSBrendan Gregg - Sun Microsystems 
7208aad02571SSaso Kiselkov 	return (write_asize);
7209aad02571SSaso Kiselkov }
7210aad02571SSaso Kiselkov 
7211fa94a07fSbrendan /*
7212fa94a07fSbrendan  * This thread feeds the L2ARC at regular intervals.  This is the beating
7213fa94a07fSbrendan  * heart of the L2ARC.
7214fa94a07fSbrendan  */
72153f7978d0SAlan Somers /* ARGSUSED */
7216fa94a07fSbrendan static void
72173f7978d0SAlan Somers l2arc_feed_thread(void *unused)
7218fa94a07fSbrendan {
7219fa94a07fSbrendan 	callb_cpr_t cpr;
7220fa94a07fSbrendan 	l2arc_dev_t *dev;
7221fa94a07fSbrendan 	spa_t *spa;
72225a98e54bSBrendan Gregg - Sun Microsystems 	uint64_t size, wrote;
7223d3d50737SRafael Vanoni 	clock_t begin, next = ddi_get_lbolt();
7224fa94a07fSbrendan 
7225fa94a07fSbrendan 	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
7226fa94a07fSbrendan 
7227fa94a07fSbrendan 	mutex_enter(&l2arc_feed_thr_lock);
7228fa94a07fSbrendan 
7229fa94a07fSbrendan 	while (l2arc_thread_exit == 0) {
7230fa94a07fSbrendan 		CALLB_CPR_SAFE_BEGIN(&cpr);
7231fa94a07fSbrendan 		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
72325a98e54bSBrendan Gregg - Sun Microsystems 		    next);
7233fa94a07fSbrendan 		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
7234d3d50737SRafael Vanoni 		next = ddi_get_lbolt() + hz;
7235fa94a07fSbrendan 
72363a737e0dSbrendan 		/*
72373a737e0dSbrendan 		 * Quick check for L2ARC devices.
72383a737e0dSbrendan 		 */
7239c5904d13Seschrock 		mutex_enter(&l2arc_dev_mtx);
72403a737e0dSbrendan 		if (l2arc_ndev == 0) {
72413a737e0dSbrendan 			mutex_exit(&l2arc_dev_mtx);
72423a737e0dSbrendan 			continue;
72433a737e0dSbrendan 		}
72443a737e0dSbrendan 		mutex_exit(&l2arc_dev_mtx);
7245d3d50737SRafael Vanoni 		begin = ddi_get_lbolt();
7246c5904d13Seschrock 
7247fa94a07fSbrendan 		/*
7248c5904d13Seschrock 		 * This selects the next l2arc device to write to, and in
7249c5904d13Seschrock 		 * doing so the next spa to feed from: dev->l2ad_spa.   This
72503a737e0dSbrendan 		 * will return NULL if there are now no l2arc devices or if
72513a737e0dSbrendan 		 * they are all faulted.
72523a737e0dSbrendan 		 *
72533a737e0dSbrendan 		 * If a device is returned, its spa's config lock is also
72543a737e0dSbrendan 		 * held to prevent device removal.  l2arc_dev_get_next()
72553a737e0dSbrendan 		 * will grab and release l2arc_dev_mtx.
7256fa94a07fSbrendan 		 */
72573a737e0dSbrendan 		if ((dev = l2arc_dev_get_next()) == NULL)
7258fa94a07fSbrendan 			continue;
72593a737e0dSbrendan 
72603a737e0dSbrendan 		spa = dev->l2ad_spa;
7261dcbf3bd6SGeorge Wilson 		ASSERT3P(spa, !=, NULL);
7262fa94a07fSbrendan 
7263f9af39baSGeorge Wilson 		/*
7264f9af39baSGeorge Wilson 		 * If the pool is read-only then force the feed thread to
7265f9af39baSGeorge Wilson 		 * sleep a little longer.
7266f9af39baSGeorge Wilson 		 */
7267f9af39baSGeorge Wilson 		if (!spa_writeable(spa)) {
7268f9af39baSGeorge Wilson 			next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
7269f9af39baSGeorge Wilson 			spa_config_exit(spa, SCL_L2ARC, dev);
7270f9af39baSGeorge Wilson 			continue;
7271f9af39baSGeorge Wilson 		}
7272f9af39baSGeorge Wilson 
7273fa94a07fSbrendan 		/*
7274fa94a07fSbrendan 		 * Avoid contributing to memory pressure.
7275fa94a07fSbrendan 		 */
7276fa94a07fSbrendan 		if (arc_reclaim_needed()) {
7277fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
7278e14bb325SJeff Bonwick 			spa_config_exit(spa, SCL_L2ARC, dev);
7279fa94a07fSbrendan 			continue;
7280fa94a07fSbrendan 		}
7281fa94a07fSbrendan 
7282fa94a07fSbrendan 		ARCSTAT_BUMP(arcstat_l2_feeds);
7283fa94a07fSbrendan 
7284aad02571SSaso Kiselkov 		size = l2arc_write_size();
72853a737e0dSbrendan 
7286fa94a07fSbrendan 		/*
7287fa94a07fSbrendan 		 * Evict L2ARC buffers that will be overwritten.
7288fa94a07fSbrendan 		 */
72893a737e0dSbrendan 		l2arc_evict(dev, size, B_FALSE);
7290fa94a07fSbrendan 
7291fa94a07fSbrendan 		/*
7292fa94a07fSbrendan 		 * Write ARC buffers.
7293fa94a07fSbrendan 		 */
7294dcbf3bd6SGeorge Wilson 		wrote = l2arc_write_buffers(spa, dev, size);
72955a98e54bSBrendan Gregg - Sun Microsystems 
72965a98e54bSBrendan Gregg - Sun Microsystems 		/*
72975a98e54bSBrendan Gregg - Sun Microsystems 		 * Calculate interval between writes.
72985a98e54bSBrendan Gregg - Sun Microsystems 		 */
72995a98e54bSBrendan Gregg - Sun Microsystems 		next = l2arc_write_interval(begin, size, wrote);
7300e14bb325SJeff Bonwick 		spa_config_exit(spa, SCL_L2ARC, dev);
7301fa94a07fSbrendan 	}
7302fa94a07fSbrendan 
7303fa94a07fSbrendan 	l2arc_thread_exit = 0;
7304fa94a07fSbrendan 	cv_broadcast(&l2arc_feed_thr_cv);
7305fa94a07fSbrendan 	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
7306fa94a07fSbrendan 	thread_exit();
7307fa94a07fSbrendan }
7308fa94a07fSbrendan 
7309c5904d13Seschrock boolean_t
7310c5904d13Seschrock l2arc_vdev_present(vdev_t *vd)
7311c5904d13Seschrock {
7312c5904d13Seschrock 	l2arc_dev_t *dev;
7313c5904d13Seschrock 
7314c5904d13Seschrock 	mutex_enter(&l2arc_dev_mtx);
7315c5904d13Seschrock 	for (dev = list_head(l2arc_dev_list); dev != NULL;
7316c5904d13Seschrock 	    dev = list_next(l2arc_dev_list, dev)) {
7317c5904d13Seschrock 		if (dev->l2ad_vdev == vd)
7318c5904d13Seschrock 			break;
7319c5904d13Seschrock 	}
7320c5904d13Seschrock 	mutex_exit(&l2arc_dev_mtx);
7321c5904d13Seschrock 
7322c5904d13Seschrock 	return (dev != NULL);
7323c5904d13Seschrock }
7324c5904d13Seschrock 
7325fa94a07fSbrendan /*
7326fa94a07fSbrendan  * Add a vdev for use by the L2ARC.  By this point the spa has already
7327fa94a07fSbrendan  * validated the vdev and opened it.
7328fa94a07fSbrendan  */
7329fa94a07fSbrendan void
7330573ca77eSGeorge Wilson l2arc_add_vdev(spa_t *spa, vdev_t *vd)
7331fa94a07fSbrendan {
7332fa94a07fSbrendan 	l2arc_dev_t *adddev;
7333fa94a07fSbrendan 
7334c5904d13Seschrock 	ASSERT(!l2arc_vdev_present(vd));
7335c5904d13Seschrock 
7336fa94a07fSbrendan 	/*
7337fa94a07fSbrendan 	 * Create a new l2arc device entry.
7338fa94a07fSbrendan 	 */
7339fa94a07fSbrendan 	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
7340fa94a07fSbrendan 	adddev->l2ad_spa = spa;
7341fa94a07fSbrendan 	adddev->l2ad_vdev = vd;
7342573ca77eSGeorge Wilson 	adddev->l2ad_start = VDEV_LABEL_START_SIZE;
7343573ca77eSGeorge Wilson 	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
7344fa94a07fSbrendan 	adddev->l2ad_hand = adddev->l2ad_start;
7345fa94a07fSbrendan 	adddev->l2ad_first = B_TRUE;
73465a98e54bSBrendan Gregg - Sun Microsystems 	adddev->l2ad_writing = B_FALSE;
7347fa94a07fSbrendan 
734889c86e32SChris Williamson 	mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
7349fa94a07fSbrendan 	/*
7350fa94a07fSbrendan 	 * This is a list of all ARC buffers that are still valid on the
7351fa94a07fSbrendan 	 * device.
7352fa94a07fSbrendan 	 */
735389c86e32SChris Williamson 	list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
735489c86e32SChris Williamson 	    offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
7355fa94a07fSbrendan 
7356b24ab676SJeff Bonwick 	vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
7357a52fc310SPrakash Surya 	refcount_create(&adddev->l2ad_alloc);
7358fa94a07fSbrendan 
7359fa94a07fSbrendan 	/*
7360fa94a07fSbrendan 	 * Add device to global list
7361fa94a07fSbrendan 	 */
7362fa94a07fSbrendan 	mutex_enter(&l2arc_dev_mtx);
7363fa94a07fSbrendan 	list_insert_head(l2arc_dev_list, adddev);
7364fa94a07fSbrendan 	atomic_inc_64(&l2arc_ndev);
7365fa94a07fSbrendan 	mutex_exit(&l2arc_dev_mtx);
7366fa94a07fSbrendan }
7367fa94a07fSbrendan 
7368fa94a07fSbrendan /*
7369fa94a07fSbrendan  * Remove a vdev from the L2ARC.
7370fa94a07fSbrendan  */
7371fa94a07fSbrendan void
7372fa94a07fSbrendan l2arc_remove_vdev(vdev_t *vd)
7373fa94a07fSbrendan {
7374fa94a07fSbrendan 	l2arc_dev_t *dev, *nextdev, *remdev = NULL;
7375fa94a07fSbrendan 
7376fa94a07fSbrendan 	/*
7377fa94a07fSbrendan 	 * Find the device by vdev
7378fa94a07fSbrendan 	 */
7379fa94a07fSbrendan 	mutex_enter(&l2arc_dev_mtx);
7380fa94a07fSbrendan 	for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
7381fa94a07fSbrendan 		nextdev = list_next(l2arc_dev_list, dev);
7382fa94a07fSbrendan 		if (vd == dev->l2ad_vdev) {
7383fa94a07fSbrendan 			remdev = dev;
7384fa94a07fSbrendan 			break;
7385fa94a07fSbrendan 		}
7386fa94a07fSbrendan 	}
7387dcbf3bd6SGeorge Wilson 	ASSERT3P(remdev, !=, NULL);
7388fa94a07fSbrendan 
7389fa94a07fSbrendan 	/*
7390fa94a07fSbrendan 	 * Remove device from global list
7391fa94a07fSbrendan 	 */
7392fa94a07fSbrendan 	list_remove(l2arc_dev_list, remdev);
7393fa94a07fSbrendan 	l2arc_dev_last = NULL;		/* may have been invalidated */
73943a737e0dSbrendan 	atomic_dec_64(&l2arc_ndev);
73953a737e0dSbrendan 	mutex_exit(&l2arc_dev_mtx);
7396fa94a07fSbrendan 
7397fa94a07fSbrendan 	/*
7398fa94a07fSbrendan 	 * Clear all buflists and ARC references.  L2ARC device flush.
7399fa94a07fSbrendan 	 */
7400fa94a07fSbrendan 	l2arc_evict(remdev, 0, B_TRUE);
740189c86e32SChris Williamson 	list_destroy(&remdev->l2ad_buflist);
740289c86e32SChris Williamson 	mutex_destroy(&remdev->l2ad_mtx);
7403a52fc310SPrakash Surya 	refcount_destroy(&remdev->l2ad_alloc);
7404fa94a07fSbrendan 	kmem_free(remdev, sizeof (l2arc_dev_t));
7405fa94a07fSbrendan }
7406fa94a07fSbrendan 
7407fa94a07fSbrendan void
7408e14bb325SJeff Bonwick l2arc_init(void)
7409fa94a07fSbrendan {
7410fa94a07fSbrendan 	l2arc_thread_exit = 0;
7411fa94a07fSbrendan 	l2arc_ndev = 0;
7412fa94a07fSbrendan 	l2arc_writes_sent = 0;
7413fa94a07fSbrendan 	l2arc_writes_done = 0;
7414fa94a07fSbrendan 
7415fa94a07fSbrendan 	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
7416fa94a07fSbrendan 	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
7417fa94a07fSbrendan 	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
7418fa94a07fSbrendan 	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
7419fa94a07fSbrendan 
7420fa94a07fSbrendan 	l2arc_dev_list = &L2ARC_dev_list;
7421fa94a07fSbrendan 	l2arc_free_on_write = &L2ARC_free_on_write;
7422fa94a07fSbrendan 	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
7423fa94a07fSbrendan 	    offsetof(l2arc_dev_t, l2ad_node));
7424fa94a07fSbrendan 	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
7425fa94a07fSbrendan 	    offsetof(l2arc_data_free_t, l2df_list_node));
7426fa94a07fSbrendan }
7427fa94a07fSbrendan 
7428fa94a07fSbrendan void
7429e14bb325SJeff Bonwick l2arc_fini(void)
7430fa94a07fSbrendan {
74313a737e0dSbrendan 	/*
74323a737e0dSbrendan 	 * This is called from dmu_fini(), which is called from spa_fini();
74333a737e0dSbrendan 	 * Because of this, we can assume that all l2arc devices have
74343a737e0dSbrendan 	 * already been removed when the pools themselves were removed.
74353a737e0dSbrendan 	 */
74363a737e0dSbrendan 
74373a737e0dSbrendan 	l2arc_do_free_on_write();
74383a737e0dSbrendan 
7439fa94a07fSbrendan 	mutex_destroy(&l2arc_feed_thr_lock);
7440fa94a07fSbrendan 	cv_destroy(&l2arc_feed_thr_cv);
7441fa94a07fSbrendan 	mutex_destroy(&l2arc_dev_mtx);
7442fa94a07fSbrendan 	mutex_destroy(&l2arc_free_on_write_mtx);
7443fa94a07fSbrendan 
7444fa94a07fSbrendan 	list_destroy(l2arc_dev_list);
7445fa94a07fSbrendan 	list_destroy(l2arc_free_on_write);
7446fa94a07fSbrendan }
7447e14bb325SJeff Bonwick 
7448e14bb325SJeff Bonwick void
7449e14bb325SJeff Bonwick l2arc_start(void)
7450e14bb325SJeff Bonwick {
74518ad4d6ddSJeff Bonwick 	if (!(spa_mode_global & FWRITE))
7452e14bb325SJeff Bonwick 		return;
7453e14bb325SJeff Bonwick 
7454e14bb325SJeff Bonwick 	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
7455e14bb325SJeff Bonwick 	    TS_RUN, minclsyspri);
7456e14bb325SJeff Bonwick }
7457e14bb325SJeff Bonwick 
7458e14bb325SJeff Bonwick void
7459e14bb325SJeff Bonwick l2arc_stop(void)
7460e14bb325SJeff Bonwick {
74618ad4d6ddSJeff Bonwick 	if (!(spa_mode_global & FWRITE))
7462e14bb325SJeff Bonwick 		return;
7463e14bb325SJeff Bonwick 
7464e14bb325SJeff Bonwick 	mutex_enter(&l2arc_feed_thr_lock);
7465e14bb325SJeff Bonwick 	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
7466e14bb325SJeff Bonwick 	l2arc_thread_exit = 1;
7467e14bb325SJeff Bonwick 	while (l2arc_thread_exit != 0)
7468e14bb325SJeff Bonwick 		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
7469e14bb325SJeff Bonwick 	mutex_exit(&l2arc_feed_thr_lock);
7470e14bb325SJeff Bonwick }
7471