xref: /illumos-gate/usr/src/uts/common/fs/zfs/arc.c (revision 94c2d0eb22e9624151ee84a7edbf7178e1bf4087)
1fa9e4066Sahrens /*
2fa9e4066Sahrens  * CDDL HEADER START
3fa9e4066Sahrens  *
4fa9e4066Sahrens  * The contents of this file are subject to the terms of the
5033f9833Sek  * Common Development and Distribution License (the "License").
6033f9833Sek  * You may not use this file except in compliance with the License.
7fa9e4066Sahrens  *
8fa9e4066Sahrens  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9fa9e4066Sahrens  * or http://www.opensolaris.org/os/licensing.
10fa9e4066Sahrens  * See the License for the specific language governing permissions
11fa9e4066Sahrens  * and limitations under the License.
12fa9e4066Sahrens  *
13fa9e4066Sahrens  * When distributing Covered Code, include this CDDL HEADER in each
14fa9e4066Sahrens  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15fa9e4066Sahrens  * If applicable, add the following below this CDDL HEADER, with the
16fa9e4066Sahrens  * fields enclosed by brackets "[]" replaced with your own identifying
17fa9e4066Sahrens  * information: Portions Copyright [yyyy] [name of copyright owner]
18fa9e4066Sahrens  *
19fa9e4066Sahrens  * CDDL HEADER END
20fa9e4066Sahrens  */
21fa9e4066Sahrens /*
223f9d6ad7SLin Ling  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23cf746768SBryan Cantrill  * Copyright (c) 2012, Joyent, Inc. All rights reserved.
2410fbdecbSMatthew Ahrens  * Copyright (c) 2011, 2017 by Delphix. All rights reserved.
2571cb1b74SSaso Kiselkov  * Copyright (c) 2014 by Saso Kiselkov. All rights reserved.
2631c46cf2SAlek Pinchuk  * Copyright 2015 Nexenta Systems, Inc.  All rights reserved.
27fa9e4066Sahrens  */
28fa9e4066Sahrens 
29fa9e4066Sahrens /*
3044cb6abcSbmc  * DVA-based Adjustable Replacement Cache
31fa9e4066Sahrens  *
32ea8dc4b6Seschrock  * While much of the theory of operation used here is
33ea8dc4b6Seschrock  * based on the self-tuning, low overhead replacement cache
34fa9e4066Sahrens  * presented by Megiddo and Modha at FAST 2003, there are some
35fa9e4066Sahrens  * significant differences:
36fa9e4066Sahrens  *
37fa9e4066Sahrens  * 1. The Megiddo and Modha model assumes any page is evictable.
38fa9e4066Sahrens  * Pages in its cache cannot be "locked" into memory.  This makes
39fa9e4066Sahrens  * the eviction algorithm simple: evict the last page in the list.
40fa9e4066Sahrens  * This also make the performance characteristics easy to reason
41fa9e4066Sahrens  * about.  Our cache is not so simple.  At any given moment, some
42fa9e4066Sahrens  * subset of the blocks in the cache are un-evictable because we
43fa9e4066Sahrens  * have handed out a reference to them.  Blocks are only evictable
44fa9e4066Sahrens  * when there are no external references active.  This makes
45fa9e4066Sahrens  * eviction far more problematic:  we choose to evict the evictable
46fa9e4066Sahrens  * blocks that are the "lowest" in the list.
47fa9e4066Sahrens  *
48fa9e4066Sahrens  * There are times when it is not possible to evict the requested
49fa9e4066Sahrens  * space.  In these circumstances we are unable to adjust the cache
50fa9e4066Sahrens  * size.  To prevent the cache growing unbounded at these times we
51fa94a07fSbrendan  * implement a "cache throttle" that slows the flow of new data
52fa94a07fSbrendan  * into the cache until we can make space available.
53fa9e4066Sahrens  *
54fa9e4066Sahrens  * 2. The Megiddo and Modha model assumes a fixed cache size.
55fa9e4066Sahrens  * Pages are evicted when the cache is full and there is a cache
56fa9e4066Sahrens  * miss.  Our model has a variable sized cache.  It grows with
57fa94a07fSbrendan  * high use, but also tries to react to memory pressure from the
58fa9e4066Sahrens  * operating system: decreasing its size when system memory is
59fa9e4066Sahrens  * tight.
60fa9e4066Sahrens  *
61fa9e4066Sahrens  * 3. The Megiddo and Modha model assumes a fixed page size. All
62f7170741SWill Andrews  * elements of the cache are therefore exactly the same size.  So
63fa9e4066Sahrens  * when adjusting the cache size following a cache miss, its simply
64fa9e4066Sahrens  * a matter of choosing a single page to evict.  In our model, we
65fa9e4066Sahrens  * have variable sized cache blocks (rangeing from 512 bytes to
66f7170741SWill Andrews  * 128K bytes).  We therefore choose a set of blocks to evict to make
67fa9e4066Sahrens  * space for a cache miss that approximates as closely as possible
68fa9e4066Sahrens  * the space used by the new block.
69fa9e4066Sahrens  *
70fa9e4066Sahrens  * See also:  "ARC: A Self-Tuning, Low Overhead Replacement Cache"
71fa9e4066Sahrens  * by N. Megiddo & D. Modha, FAST 2003
72fa9e4066Sahrens  */
73fa9e4066Sahrens 
74fa9e4066Sahrens /*
75fa9e4066Sahrens  * The locking model:
76fa9e4066Sahrens  *
77fa9e4066Sahrens  * A new reference to a cache buffer can be obtained in two
78fa9e4066Sahrens  * ways: 1) via a hash table lookup using the DVA as a key,
79fa94a07fSbrendan  * or 2) via one of the ARC lists.  The arc_read() interface
805602294fSDan Kimmel  * uses method 1, while the internal ARC algorithms for
81f7170741SWill Andrews  * adjusting the cache use method 2.  We therefore provide two
82fa9e4066Sahrens  * types of locks: 1) the hash table lock array, and 2) the
835602294fSDan Kimmel  * ARC list locks.
84fa9e4066Sahrens  *
85fc98fea5SBart Coddens  * Buffers do not have their own mutexes, rather they rely on the
86fc98fea5SBart Coddens  * hash table mutexes for the bulk of their protection (i.e. most
87fc98fea5SBart Coddens  * fields in the arc_buf_hdr_t are protected by these mutexes).
88fa9e4066Sahrens  *
89fa9e4066Sahrens  * buf_hash_find() returns the appropriate mutex (held) when it
90fa9e4066Sahrens  * locates the requested buffer in the hash table.  It returns
91fa9e4066Sahrens  * NULL for the mutex if the buffer was not in the table.
92fa9e4066Sahrens  *
93fa9e4066Sahrens  * buf_hash_remove() expects the appropriate hash mutex to be
94fa9e4066Sahrens  * already held before it is invoked.
95fa9e4066Sahrens  *
965602294fSDan Kimmel  * Each ARC state also has a mutex which is used to protect the
97fa9e4066Sahrens  * buffer list associated with the state.  When attempting to
985602294fSDan Kimmel  * obtain a hash table lock while holding an ARC list lock you
99fa9e4066Sahrens  * must use: mutex_tryenter() to avoid deadlock.  Also note that
10044eda4d7Smaybee  * the active state mutex must be held before the ghost state mutex.
101fa9e4066Sahrens  *
102fa9e4066Sahrens  * Note that the majority of the performance stats are manipulated
103fa9e4066Sahrens  * with atomic operations.
104fa94a07fSbrendan  *
10589c86e32SChris Williamson  * The L2ARC uses the l2ad_mtx on each vdev for the following:
106fa94a07fSbrendan  *
107fa94a07fSbrendan  *	- L2ARC buflist creation
108fa94a07fSbrendan  *	- L2ARC buflist eviction
109fa94a07fSbrendan  *	- L2ARC write completion, which walks L2ARC buflists
110fa94a07fSbrendan  *	- ARC header destruction, as it removes from L2ARC buflists
111fa94a07fSbrendan  *	- ARC header release, as it removes from L2ARC buflists
112fa9e4066Sahrens  */
113fa9e4066Sahrens 
114dcbf3bd6SGeorge Wilson /*
115dcbf3bd6SGeorge Wilson  * ARC operation:
116dcbf3bd6SGeorge Wilson  *
117dcbf3bd6SGeorge Wilson  * Every block that is in the ARC is tracked by an arc_buf_hdr_t structure.
118dcbf3bd6SGeorge Wilson  * This structure can point either to a block that is still in the cache or to
119dcbf3bd6SGeorge Wilson  * one that is only accessible in an L2 ARC device, or it can provide
120dcbf3bd6SGeorge Wilson  * information about a block that was recently evicted. If a block is
121dcbf3bd6SGeorge Wilson  * only accessible in the L2ARC, then the arc_buf_hdr_t only has enough
122dcbf3bd6SGeorge Wilson  * information to retrieve it from the L2ARC device. This information is
123dcbf3bd6SGeorge Wilson  * stored in the l2arc_buf_hdr_t sub-structure of the arc_buf_hdr_t. A block
124dcbf3bd6SGeorge Wilson  * that is in this state cannot access the data directly.
125dcbf3bd6SGeorge Wilson  *
126dcbf3bd6SGeorge Wilson  * Blocks that are actively being referenced or have not been evicted
127dcbf3bd6SGeorge Wilson  * are cached in the L1ARC. The L1ARC (l1arc_buf_hdr_t) is a structure within
128dcbf3bd6SGeorge Wilson  * the arc_buf_hdr_t that will point to the data block in memory. A block can
129dcbf3bd6SGeorge Wilson  * only be read by a consumer if it has an l1arc_buf_hdr_t. The L1ARC
1305602294fSDan Kimmel  * caches data in two ways -- in a list of ARC buffers (arc_buf_t) and
131dcbf3bd6SGeorge Wilson  * also in the arc_buf_hdr_t's private physical data block pointer (b_pdata).
1325602294fSDan Kimmel  *
1335602294fSDan Kimmel  * The L1ARC's data pointer may or may not be uncompressed. The ARC has the
1345602294fSDan Kimmel  * ability to store the physical data (b_pdata) associated with the DVA of the
1355602294fSDan Kimmel  * arc_buf_hdr_t. Since the b_pdata 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
1385602294fSDan Kimmel  * compressed ARC functionality is disabled, the b_pdata 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
1775602294fSDan Kimmel  *   | b_pdata   +-+           |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
1945602294fSDan Kimmel  * existing uncompressed arc_buf_t, decompresses the hdr's b_pdata buffer into a
1955602294fSDan Kimmel  * new data buffer, or shares the hdr's b_pdata 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   +---->+---------+
219dcbf3bd6SGeorge Wilson  *                |  b_pdata  +-+           |---------|     |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  *
2335602294fSDan Kimmel  * Writing to the ARC requires that the ARC first discard the hdr's b_pdata
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
2385602294fSDan Kimmel  * a newly allocated b_pdata. 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  *
244dcbf3bd6SGeorge Wilson  * When the L2ARC is in use, it will also take advantage of the b_pdata. The
245dcbf3bd6SGeorge Wilson  * L2ARC will always write the contents of b_pdata 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>
266244781f1SPrakash Surya #include <sys/multilist.h>
267fa9e4066Sahrens #ifdef _KERNEL
268fa9e4066Sahrens #include <sys/vmsystm.h>
269fa9e4066Sahrens #include <vm/anon.h>
270fa9e4066Sahrens #include <sys/fs/swapnode.h>
271033f9833Sek #include <sys/dnlc.h>
272fa9e4066Sahrens #endif
273fa9e4066Sahrens #include <sys/callb.h>
27444cb6abcSbmc #include <sys/kstat.h>
275b24ab676SJeff Bonwick #include <zfs_fletcher.h>
276fa9e4066Sahrens 
277cd1c8b85SMatthew Ahrens #ifndef _KERNEL
278cd1c8b85SMatthew Ahrens /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
279cd1c8b85SMatthew Ahrens boolean_t arc_watch = B_FALSE;
280cd1c8b85SMatthew Ahrens int arc_procfd;
281cd1c8b85SMatthew Ahrens #endif
282cd1c8b85SMatthew Ahrens 
283244781f1SPrakash Surya static kmutex_t		arc_reclaim_lock;
284244781f1SPrakash Surya static kcondvar_t	arc_reclaim_thread_cv;
285244781f1SPrakash Surya static boolean_t	arc_reclaim_thread_exit;
286244781f1SPrakash Surya static kcondvar_t	arc_reclaim_waiters_cv;
287244781f1SPrakash Surya 
2882ec99e3eSMatthew Ahrens uint_t arc_reduce_dnlc_percent = 3;
289fa9e4066Sahrens 
29069962b56SMatthew Ahrens /*
291244781f1SPrakash Surya  * The number of headers to evict in arc_evict_state_impl() before
292244781f1SPrakash Surya  * dropping the sublist lock and evicting from another sublist. A lower
293244781f1SPrakash Surya  * value means we're more likely to evict the "correct" header (i.e. the
294244781f1SPrakash Surya  * oldest header in the arc state), but comes with higher overhead
295244781f1SPrakash Surya  * (i.e. more invocations of arc_evict_state_impl()).
296244781f1SPrakash Surya  */
297244781f1SPrakash Surya int zfs_arc_evict_batch_limit = 10;
298244781f1SPrakash Surya 
299fa9e4066Sahrens /* number of seconds before growing cache again */
300fa9e4066Sahrens static int		arc_grow_retry = 60;
301fa9e4066Sahrens 
302244781f1SPrakash Surya /* shift of arc_c for calculating overflow limit in arc_get_data_buf */
303244781f1SPrakash Surya int		zfs_arc_overflow_shift = 8;
304244781f1SPrakash Surya 
3055a98e54bSBrendan Gregg - Sun Microsystems /* shift of arc_c for calculating both min and max arc_p */
3065a98e54bSBrendan Gregg - Sun Microsystems static int		arc_p_min_shift = 4;
3075a98e54bSBrendan Gregg - Sun Microsystems 
3085a98e54bSBrendan Gregg - Sun Microsystems /* log2(fraction of arc to reclaim) */
3092ec99e3eSMatthew Ahrens static int		arc_shrink_shift = 7;
3102ec99e3eSMatthew Ahrens 
3112ec99e3eSMatthew Ahrens /*
3122ec99e3eSMatthew Ahrens  * log2(fraction of ARC which must be free to allow growing).
3132ec99e3eSMatthew Ahrens  * I.e. If there is less than arc_c >> arc_no_grow_shift free memory,
3142ec99e3eSMatthew Ahrens  * when reading a new block into the ARC, we will evict an equal-sized block
3152ec99e3eSMatthew Ahrens  * from the ARC.
3162ec99e3eSMatthew Ahrens  *
3172ec99e3eSMatthew Ahrens  * This must be less than arc_shrink_shift, so that when we shrink the ARC,
3182ec99e3eSMatthew Ahrens  * we will still not allow it to grow.
3192ec99e3eSMatthew Ahrens  */
3202ec99e3eSMatthew Ahrens int			arc_no_grow_shift = 5;
3212ec99e3eSMatthew Ahrens 
3225a98e54bSBrendan Gregg - Sun Microsystems 
32313506d1eSmaybee /*
324b19a79ecSperrin  * minimum lifespan of a prefetch block in clock ticks
325b19a79ecSperrin  * (initialized in arc_init())
32613506d1eSmaybee  */
327b19a79ecSperrin static int		arc_min_prefetch_lifespan;
32813506d1eSmaybee 
32969962b56SMatthew Ahrens /*
33069962b56SMatthew Ahrens  * If this percent of memory is free, don't throttle.
33169962b56SMatthew Ahrens  */
33269962b56SMatthew Ahrens int arc_lotsfree_percent = 10;
33369962b56SMatthew Ahrens 
334fa9e4066Sahrens static int arc_dead;
335fa9e4066Sahrens 
3363a737e0dSbrendan /*
3373a737e0dSbrendan  * The arc has filled available memory and has now warmed up.
3383a737e0dSbrendan  */
3393a737e0dSbrendan static boolean_t arc_warm;
3403a737e0dSbrendan 
3410dd053d7SPrakash Surya /*
3420dd053d7SPrakash Surya  * log2 fraction of the zio arena to keep free.
3430dd053d7SPrakash Surya  */
3440dd053d7SPrakash Surya int arc_zio_arena_free_shift = 2;
3450dd053d7SPrakash Surya 
346a2eea2e1Sahrens /*
347a2eea2e1Sahrens  * These tunables are for performance analysis.
348a2eea2e1Sahrens  */
349a2eea2e1Sahrens uint64_t zfs_arc_max;
350a2eea2e1Sahrens uint64_t zfs_arc_min;
3511116048bSek uint64_t zfs_arc_meta_limit = 0;
3523a5286a1SMatthew Ahrens uint64_t zfs_arc_meta_min = 0;
3535a98e54bSBrendan Gregg - Sun Microsystems int zfs_arc_grow_retry = 0;
3545a98e54bSBrendan Gregg - Sun Microsystems int zfs_arc_shrink_shift = 0;
3555a98e54bSBrendan Gregg - Sun Microsystems int zfs_arc_p_min_shift = 0;
35663e911b6SMatthew Ahrens int zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
357a2eea2e1Sahrens 
358dcbf3bd6SGeorge Wilson boolean_t zfs_compressed_arc_enabled = B_TRUE;
359dcbf3bd6SGeorge Wilson 
360fa9e4066Sahrens /*
361fa94a07fSbrendan  * Note that buffers can be in one of 6 states:
362fa9e4066Sahrens  *	ARC_anon	- anonymous (discussed below)
363ea8dc4b6Seschrock  *	ARC_mru		- recently used, currently cached
364ea8dc4b6Seschrock  *	ARC_mru_ghost	- recentely used, no longer in cache
365ea8dc4b6Seschrock  *	ARC_mfu		- frequently used, currently cached
366ea8dc4b6Seschrock  *	ARC_mfu_ghost	- frequently used, no longer in cache
367fa94a07fSbrendan  *	ARC_l2c_only	- exists in L2ARC but not other states
3680e8c6158Smaybee  * When there are no active references to the buffer, they are
3690e8c6158Smaybee  * are linked onto a list in one of these arc states.  These are
3700e8c6158Smaybee  * the only buffers that can be evicted or deleted.  Within each
3710e8c6158Smaybee  * state there are multiple lists, one for meta-data and one for
3720e8c6158Smaybee  * non-meta-data.  Meta-data (indirect blocks, blocks of dnodes,
3730e8c6158Smaybee  * etc.) is tracked separately so that it can be managed more
374fa94a07fSbrendan  * explicitly: favored over data, limited explicitly.
375fa9e4066Sahrens  *
376fa9e4066Sahrens  * Anonymous buffers are buffers that are not associated with
377fa9e4066Sahrens  * a DVA.  These are buffers that hold dirty block copies
378fa9e4066Sahrens  * before they are written to stable storage.  By definition,
379ea8dc4b6Seschrock  * they are "ref'd" and are considered part of arc_mru
380fa9e4066Sahrens  * that cannot be freed.  Generally, they will aquire a DVA
381ea8dc4b6Seschrock  * as they are written and migrate onto the arc_mru list.
382fa94a07fSbrendan  *
383fa94a07fSbrendan  * The ARC_l2c_only state is for buffers that are in the second
384fa94a07fSbrendan  * level ARC but no longer in any of the ARC_m* lists.  The second
385fa94a07fSbrendan  * level ARC itself may also contain buffers that are in any of
386fa94a07fSbrendan  * the ARC_m* states - meaning that a buffer can exist in two
387fa94a07fSbrendan  * places.  The reason for the ARC_l2c_only state is to keep the
388fa94a07fSbrendan  * buffer header in the hash table, so that reads that hit the
389fa94a07fSbrendan  * second level ARC benefit from these fast lookups.
390fa9e4066Sahrens  */
391fa9e4066Sahrens 
392fa9e4066Sahrens typedef struct arc_state {
393244781f1SPrakash Surya 	/*
394244781f1SPrakash Surya 	 * list of evictable buffers
395244781f1SPrakash Surya 	 */
396*94c2d0ebSMatthew Ahrens 	multilist_t *arcs_list[ARC_BUFC_NUMTYPES];
397244781f1SPrakash Surya 	/*
398244781f1SPrakash Surya 	 * total amount of evictable data in this state
399244781f1SPrakash Surya 	 */
400dcbf3bd6SGeorge Wilson 	refcount_t arcs_esize[ARC_BUFC_NUMTYPES];
401244781f1SPrakash Surya 	/*
402244781f1SPrakash Surya 	 * total amount of data in this state; this includes: evictable,
403244781f1SPrakash Surya 	 * non-evictable, ARC_BUFC_DATA, and ARC_BUFC_METADATA.
404244781f1SPrakash Surya 	 */
4052fd872a7SPrakash Surya 	refcount_t arcs_size;
406fa9e4066Sahrens } arc_state_t;
407fa9e4066Sahrens 
408fa94a07fSbrendan /* The 6 states: */
409fa9e4066Sahrens static arc_state_t ARC_anon;
410ea8dc4b6Seschrock static arc_state_t ARC_mru;
411ea8dc4b6Seschrock static arc_state_t ARC_mru_ghost;
412ea8dc4b6Seschrock static arc_state_t ARC_mfu;
413ea8dc4b6Seschrock static arc_state_t ARC_mfu_ghost;
414fa94a07fSbrendan static arc_state_t ARC_l2c_only;
415fa9e4066Sahrens 
41644cb6abcSbmc typedef struct arc_stats {
41744cb6abcSbmc 	kstat_named_t arcstat_hits;
41844cb6abcSbmc 	kstat_named_t arcstat_misses;
41944cb6abcSbmc 	kstat_named_t arcstat_demand_data_hits;
42044cb6abcSbmc 	kstat_named_t arcstat_demand_data_misses;
42144cb6abcSbmc 	kstat_named_t arcstat_demand_metadata_hits;
42244cb6abcSbmc 	kstat_named_t arcstat_demand_metadata_misses;
42344cb6abcSbmc 	kstat_named_t arcstat_prefetch_data_hits;
42444cb6abcSbmc 	kstat_named_t arcstat_prefetch_data_misses;
42544cb6abcSbmc 	kstat_named_t arcstat_prefetch_metadata_hits;
42644cb6abcSbmc 	kstat_named_t arcstat_prefetch_metadata_misses;
42744cb6abcSbmc 	kstat_named_t arcstat_mru_hits;
42844cb6abcSbmc 	kstat_named_t arcstat_mru_ghost_hits;
42944cb6abcSbmc 	kstat_named_t arcstat_mfu_hits;
43044cb6abcSbmc 	kstat_named_t arcstat_mfu_ghost_hits;
43144cb6abcSbmc 	kstat_named_t arcstat_deleted;
4323e30c24aSWill Andrews 	/*
4333e30c24aSWill Andrews 	 * Number of buffers that could not be evicted because the hash lock
4343e30c24aSWill Andrews 	 * was held by another thread.  The lock may not necessarily be held
4353e30c24aSWill Andrews 	 * by something using the same buffer, since hash locks are shared
4363e30c24aSWill Andrews 	 * by multiple buffers.
4373e30c24aSWill Andrews 	 */
43844cb6abcSbmc 	kstat_named_t arcstat_mutex_miss;
4393e30c24aSWill Andrews 	/*
4403e30c24aSWill Andrews 	 * Number of buffers skipped because they have I/O in progress, are
4413e30c24aSWill Andrews 	 * indrect prefetch buffers that have not lived long enough, or are
4423e30c24aSWill Andrews 	 * not from the spa we're trying to evict from.
4433e30c24aSWill Andrews 	 */
44444cb6abcSbmc 	kstat_named_t arcstat_evict_skip;
445244781f1SPrakash Surya 	/*
446244781f1SPrakash Surya 	 * Number of times arc_evict_state() was unable to evict enough
447244781f1SPrakash Surya 	 * buffers to reach it's target amount.
448244781f1SPrakash Surya 	 */
449244781f1SPrakash Surya 	kstat_named_t arcstat_evict_not_enough;
4505ea40c06SBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_evict_l2_cached;
4515ea40c06SBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_evict_l2_eligible;
4525ea40c06SBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_evict_l2_ineligible;
453244781f1SPrakash Surya 	kstat_named_t arcstat_evict_l2_skip;
45444cb6abcSbmc 	kstat_named_t arcstat_hash_elements;
45544cb6abcSbmc 	kstat_named_t arcstat_hash_elements_max;
45644cb6abcSbmc 	kstat_named_t arcstat_hash_collisions;
45744cb6abcSbmc 	kstat_named_t arcstat_hash_chains;
45844cb6abcSbmc 	kstat_named_t arcstat_hash_chain_max;
45944cb6abcSbmc 	kstat_named_t arcstat_p;
46044cb6abcSbmc 	kstat_named_t arcstat_c;
46144cb6abcSbmc 	kstat_named_t arcstat_c_min;
46244cb6abcSbmc 	kstat_named_t arcstat_c_max;
46344cb6abcSbmc 	kstat_named_t arcstat_size;
464dcbf3bd6SGeorge Wilson 	/*
465dcbf3bd6SGeorge Wilson 	 * Number of compressed bytes stored in the arc_buf_hdr_t's b_pdata.
466dcbf3bd6SGeorge Wilson 	 * Note that the compressed bytes may match the uncompressed bytes
467dcbf3bd6SGeorge Wilson 	 * if the block is either not compressed or compressed arc is disabled.
468dcbf3bd6SGeorge Wilson 	 */
469dcbf3bd6SGeorge Wilson 	kstat_named_t arcstat_compressed_size;
470dcbf3bd6SGeorge Wilson 	/*
471dcbf3bd6SGeorge Wilson 	 * Uncompressed size of the data stored in b_pdata. If compressed
472dcbf3bd6SGeorge Wilson 	 * arc is disabled then this value will be identical to the stat
473dcbf3bd6SGeorge Wilson 	 * above.
474dcbf3bd6SGeorge Wilson 	 */
475dcbf3bd6SGeorge Wilson 	kstat_named_t arcstat_uncompressed_size;
476dcbf3bd6SGeorge Wilson 	/*
477dcbf3bd6SGeorge Wilson 	 * Number of bytes stored in all the arc_buf_t's. This is classified
478dcbf3bd6SGeorge Wilson 	 * as "overhead" since this data is typically short-lived and will
479dcbf3bd6SGeorge Wilson 	 * be evicted from the arc when it becomes unreferenced unless the
480dcbf3bd6SGeorge Wilson 	 * zfs_keep_uncompressed_metadata or zfs_keep_uncompressed_level
481dcbf3bd6SGeorge Wilson 	 * values have been set (see comment in dbuf.c for more information).
482dcbf3bd6SGeorge Wilson 	 */
483dcbf3bd6SGeorge Wilson 	kstat_named_t arcstat_overhead_size;
4844076b1bfSPrakash Surya 	/*
4854076b1bfSPrakash Surya 	 * Number of bytes consumed by internal ARC structures necessary
4864076b1bfSPrakash Surya 	 * for tracking purposes; these structures are not actually
4874076b1bfSPrakash Surya 	 * backed by ARC buffers. This includes arc_buf_hdr_t structures
4884076b1bfSPrakash Surya 	 * (allocated via arc_buf_hdr_t_full and arc_buf_hdr_t_l2only
4894076b1bfSPrakash Surya 	 * caches), and arc_buf_t structures (allocated via arc_buf_t
4904076b1bfSPrakash Surya 	 * cache).
4914076b1bfSPrakash Surya 	 */
492fa94a07fSbrendan 	kstat_named_t arcstat_hdr_size;
4934076b1bfSPrakash Surya 	/*
4944076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers of type equal to
4954076b1bfSPrakash Surya 	 * ARC_BUFC_DATA. This is generally consumed by buffers backing
4964076b1bfSPrakash Surya 	 * on disk user data (e.g. plain file contents).
4974076b1bfSPrakash Surya 	 */
4985a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_data_size;
4994076b1bfSPrakash Surya 	/*
5004076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers of type equal to
5014076b1bfSPrakash Surya 	 * ARC_BUFC_METADATA. This is generally consumed by buffers
5024076b1bfSPrakash Surya 	 * backing on disk data that is used for internal ZFS
5034076b1bfSPrakash Surya 	 * structures (e.g. ZAP, dnode, indirect blocks, etc).
5044076b1bfSPrakash Surya 	 */
5054076b1bfSPrakash Surya 	kstat_named_t arcstat_metadata_size;
5064076b1bfSPrakash Surya 	/*
5074076b1bfSPrakash Surya 	 * Number of bytes consumed by various buffers and structures
5084076b1bfSPrakash Surya 	 * not actually backed with ARC buffers. This includes bonus
5094076b1bfSPrakash Surya 	 * buffers (allocated directly via zio_buf_* functions),
5104076b1bfSPrakash Surya 	 * dmu_buf_impl_t structures (allocated via dmu_buf_impl_t
5114076b1bfSPrakash Surya 	 * cache), and dnode_t structures (allocated via dnode_t cache).
5124076b1bfSPrakash Surya 	 */
5135a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_other_size;
5144076b1bfSPrakash Surya 	/*
5154076b1bfSPrakash Surya 	 * Total number of bytes consumed by ARC buffers residing in the
5164076b1bfSPrakash Surya 	 * arc_anon state. This includes *all* buffers in the arc_anon
5174076b1bfSPrakash Surya 	 * state; e.g. data, metadata, evictable, and unevictable buffers
5184076b1bfSPrakash Surya 	 * are all included in this value.
5194076b1bfSPrakash Surya 	 */
5204076b1bfSPrakash Surya 	kstat_named_t arcstat_anon_size;
5214076b1bfSPrakash Surya 	/*
5224076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
5234076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_DATA,
5244076b1bfSPrakash Surya 	 * residing in the arc_anon state, and are eligible for eviction
5254076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
5264076b1bfSPrakash Surya 	 */
5274076b1bfSPrakash Surya 	kstat_named_t arcstat_anon_evictable_data;
5284076b1bfSPrakash Surya 	/*
5294076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
5304076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_METADATA,
5314076b1bfSPrakash Surya 	 * residing in the arc_anon state, and are eligible for eviction
5324076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
5334076b1bfSPrakash Surya 	 */
5344076b1bfSPrakash Surya 	kstat_named_t arcstat_anon_evictable_metadata;
5354076b1bfSPrakash Surya 	/*
5364076b1bfSPrakash Surya 	 * Total number of bytes consumed by ARC buffers residing in the
5374076b1bfSPrakash Surya 	 * arc_mru state. This includes *all* buffers in the arc_mru
5384076b1bfSPrakash Surya 	 * state; e.g. data, metadata, evictable, and unevictable buffers
5394076b1bfSPrakash Surya 	 * are all included in this value.
5404076b1bfSPrakash Surya 	 */
5414076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_size;
5424076b1bfSPrakash Surya 	/*
5434076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
5444076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_DATA,
5454076b1bfSPrakash Surya 	 * residing in the arc_mru state, and are eligible for eviction
5464076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
5474076b1bfSPrakash Surya 	 */
5484076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_evictable_data;
5494076b1bfSPrakash Surya 	/*
5504076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
5514076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_METADATA,
5524076b1bfSPrakash Surya 	 * residing in the arc_mru state, and are eligible for eviction
5534076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
5544076b1bfSPrakash Surya 	 */
5554076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_evictable_metadata;
5564076b1bfSPrakash Surya 	/*
5574076b1bfSPrakash Surya 	 * Total number of bytes that *would have been* consumed by ARC
5584076b1bfSPrakash Surya 	 * buffers in the arc_mru_ghost state. The key thing to note
5594076b1bfSPrakash Surya 	 * here, is the fact that this size doesn't actually indicate
5604076b1bfSPrakash Surya 	 * RAM consumption. The ghost lists only consist of headers and
5614076b1bfSPrakash Surya 	 * don't actually have ARC buffers linked off of these headers.
5624076b1bfSPrakash Surya 	 * Thus, *if* the headers had associated ARC buffers, these
5634076b1bfSPrakash Surya 	 * buffers *would have* consumed this number of bytes.
5644076b1bfSPrakash Surya 	 */
5654076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_ghost_size;
5664076b1bfSPrakash Surya 	/*
5674076b1bfSPrakash Surya 	 * Number of bytes that *would have been* consumed by ARC
5684076b1bfSPrakash Surya 	 * buffers that are eligible for eviction, of type
5694076b1bfSPrakash Surya 	 * ARC_BUFC_DATA, and linked off the arc_mru_ghost state.
5704076b1bfSPrakash Surya 	 */
5714076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_ghost_evictable_data;
5724076b1bfSPrakash Surya 	/*
5734076b1bfSPrakash Surya 	 * Number of bytes that *would have been* consumed by ARC
5744076b1bfSPrakash Surya 	 * buffers that are eligible for eviction, of type
5754076b1bfSPrakash Surya 	 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
5764076b1bfSPrakash Surya 	 */
5774076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_ghost_evictable_metadata;
5784076b1bfSPrakash Surya 	/*
5794076b1bfSPrakash Surya 	 * Total number of bytes consumed by ARC buffers residing in the
5804076b1bfSPrakash Surya 	 * arc_mfu state. This includes *all* buffers in the arc_mfu
5814076b1bfSPrakash Surya 	 * state; e.g. data, metadata, evictable, and unevictable buffers
5824076b1bfSPrakash Surya 	 * are all included in this value.
5834076b1bfSPrakash Surya 	 */
5844076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_size;
5854076b1bfSPrakash Surya 	/*
5864076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that are eligible for
5874076b1bfSPrakash Surya 	 * eviction, of type ARC_BUFC_DATA, and reside in the arc_mfu
5884076b1bfSPrakash Surya 	 * state.
5894076b1bfSPrakash Surya 	 */
5904076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_evictable_data;
5914076b1bfSPrakash Surya 	/*
5924076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that are eligible for
5934076b1bfSPrakash Surya 	 * eviction, of type ARC_BUFC_METADATA, and reside in the
5944076b1bfSPrakash Surya 	 * arc_mfu state.
5954076b1bfSPrakash Surya 	 */
5964076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_evictable_metadata;
5974076b1bfSPrakash Surya 	/*
5984076b1bfSPrakash Surya 	 * Total number of bytes that *would have been* consumed by ARC
5994076b1bfSPrakash Surya 	 * buffers in the arc_mfu_ghost state. See the comment above
6004076b1bfSPrakash Surya 	 * arcstat_mru_ghost_size for more details.
6014076b1bfSPrakash Surya 	 */
6024076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_ghost_size;
6034076b1bfSPrakash Surya 	/*
6044076b1bfSPrakash Surya 	 * Number of bytes that *would have been* consumed by ARC
6054076b1bfSPrakash Surya 	 * buffers that are eligible for eviction, of type
6064076b1bfSPrakash Surya 	 * ARC_BUFC_DATA, and linked off the arc_mfu_ghost state.
6074076b1bfSPrakash Surya 	 */
6084076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_ghost_evictable_data;
6094076b1bfSPrakash Surya 	/*
6104076b1bfSPrakash Surya 	 * Number of bytes that *would have been* consumed by ARC
6114076b1bfSPrakash Surya 	 * buffers that are eligible for eviction, of type
6124076b1bfSPrakash Surya 	 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
6134076b1bfSPrakash Surya 	 */
6144076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_ghost_evictable_metadata;
615fa94a07fSbrendan 	kstat_named_t arcstat_l2_hits;
616fa94a07fSbrendan 	kstat_named_t arcstat_l2_misses;
617fa94a07fSbrendan 	kstat_named_t arcstat_l2_feeds;
618fa94a07fSbrendan 	kstat_named_t arcstat_l2_rw_clash;
6195a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_l2_read_bytes;
6205a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_l2_write_bytes;
621fa94a07fSbrendan 	kstat_named_t arcstat_l2_writes_sent;
622fa94a07fSbrendan 	kstat_named_t arcstat_l2_writes_done;
623fa94a07fSbrendan 	kstat_named_t arcstat_l2_writes_error;
624244781f1SPrakash Surya 	kstat_named_t arcstat_l2_writes_lock_retry;
625fa94a07fSbrendan 	kstat_named_t arcstat_l2_evict_lock_retry;
626fa94a07fSbrendan 	kstat_named_t arcstat_l2_evict_reading;
62789c86e32SChris Williamson 	kstat_named_t arcstat_l2_evict_l1cached;
628fa94a07fSbrendan 	kstat_named_t arcstat_l2_free_on_write;
629fa94a07fSbrendan 	kstat_named_t arcstat_l2_abort_lowmem;
630fa94a07fSbrendan 	kstat_named_t arcstat_l2_cksum_bad;
631fa94a07fSbrendan 	kstat_named_t arcstat_l2_io_error;
632fa94a07fSbrendan 	kstat_named_t arcstat_l2_size;
633aad02571SSaso Kiselkov 	kstat_named_t arcstat_l2_asize;
634fa94a07fSbrendan 	kstat_named_t arcstat_l2_hdr_size;
6351ab7f2deSmaybee 	kstat_named_t arcstat_memory_throttle_count;
63620128a08SGeorge Wilson 	kstat_named_t arcstat_meta_used;
63720128a08SGeorge Wilson 	kstat_named_t arcstat_meta_limit;
63820128a08SGeorge Wilson 	kstat_named_t arcstat_meta_max;
6393a5286a1SMatthew Ahrens 	kstat_named_t arcstat_meta_min;
640cf6106c8SMatthew Ahrens 	kstat_named_t arcstat_sync_wait_for_async;
641cf6106c8SMatthew Ahrens 	kstat_named_t arcstat_demand_hit_predictive_prefetch;
64244cb6abcSbmc } arc_stats_t;
64344cb6abcSbmc 
64444cb6abcSbmc static arc_stats_t arc_stats = {
64544cb6abcSbmc 	{ "hits",			KSTAT_DATA_UINT64 },
64644cb6abcSbmc 	{ "misses",			KSTAT_DATA_UINT64 },
64744cb6abcSbmc 	{ "demand_data_hits",		KSTAT_DATA_UINT64 },
64844cb6abcSbmc 	{ "demand_data_misses",		KSTAT_DATA_UINT64 },
64944cb6abcSbmc 	{ "demand_metadata_hits",	KSTAT_DATA_UINT64 },
65044cb6abcSbmc 	{ "demand_metadata_misses",	KSTAT_DATA_UINT64 },
65144cb6abcSbmc 	{ "prefetch_data_hits",		KSTAT_DATA_UINT64 },
65244cb6abcSbmc 	{ "prefetch_data_misses",	KSTAT_DATA_UINT64 },
65344cb6abcSbmc 	{ "prefetch_metadata_hits",	KSTAT_DATA_UINT64 },
65444cb6abcSbmc 	{ "prefetch_metadata_misses",	KSTAT_DATA_UINT64 },
65544cb6abcSbmc 	{ "mru_hits",			KSTAT_DATA_UINT64 },
65644cb6abcSbmc 	{ "mru_ghost_hits",		KSTAT_DATA_UINT64 },
65744cb6abcSbmc 	{ "mfu_hits",			KSTAT_DATA_UINT64 },
65844cb6abcSbmc 	{ "mfu_ghost_hits",		KSTAT_DATA_UINT64 },
65944cb6abcSbmc 	{ "deleted",			KSTAT_DATA_UINT64 },
66044cb6abcSbmc 	{ "mutex_miss",			KSTAT_DATA_UINT64 },
66144cb6abcSbmc 	{ "evict_skip",			KSTAT_DATA_UINT64 },
662244781f1SPrakash Surya 	{ "evict_not_enough",		KSTAT_DATA_UINT64 },
6635ea40c06SBrendan Gregg - Sun Microsystems 	{ "evict_l2_cached",		KSTAT_DATA_UINT64 },
6645ea40c06SBrendan Gregg - Sun Microsystems 	{ "evict_l2_eligible",		KSTAT_DATA_UINT64 },
6655ea40c06SBrendan Gregg - Sun Microsystems 	{ "evict_l2_ineligible",	KSTAT_DATA_UINT64 },
666244781f1SPrakash Surya 	{ "evict_l2_skip",		KSTAT_DATA_UINT64 },
66744cb6abcSbmc 	{ "hash_elements",		KSTAT_DATA_UINT64 },
66844cb6abcSbmc 	{ "hash_elements_max",		KSTAT_DATA_UINT64 },
66944cb6abcSbmc 	{ "hash_collisions",		KSTAT_DATA_UINT64 },
67044cb6abcSbmc 	{ "hash_chains",		KSTAT_DATA_UINT64 },
67144cb6abcSbmc 	{ "hash_chain_max",		KSTAT_DATA_UINT64 },
67244cb6abcSbmc 	{ "p",				KSTAT_DATA_UINT64 },
67344cb6abcSbmc 	{ "c",				KSTAT_DATA_UINT64 },
67444cb6abcSbmc 	{ "c_min",			KSTAT_DATA_UINT64 },
67544cb6abcSbmc 	{ "c_max",			KSTAT_DATA_UINT64 },
676fa94a07fSbrendan 	{ "size",			KSTAT_DATA_UINT64 },
677dcbf3bd6SGeorge Wilson 	{ "compressed_size",		KSTAT_DATA_UINT64 },
678dcbf3bd6SGeorge Wilson 	{ "uncompressed_size",		KSTAT_DATA_UINT64 },
679dcbf3bd6SGeorge Wilson 	{ "overhead_size",		KSTAT_DATA_UINT64 },
680fa94a07fSbrendan 	{ "hdr_size",			KSTAT_DATA_UINT64 },
6815a98e54bSBrendan Gregg - Sun Microsystems 	{ "data_size",			KSTAT_DATA_UINT64 },
6824076b1bfSPrakash Surya 	{ "metadata_size",		KSTAT_DATA_UINT64 },
6835a98e54bSBrendan Gregg - Sun Microsystems 	{ "other_size",			KSTAT_DATA_UINT64 },
6844076b1bfSPrakash Surya 	{ "anon_size",			KSTAT_DATA_UINT64 },
6854076b1bfSPrakash Surya 	{ "anon_evictable_data",	KSTAT_DATA_UINT64 },
6864076b1bfSPrakash Surya 	{ "anon_evictable_metadata",	KSTAT_DATA_UINT64 },
6874076b1bfSPrakash Surya 	{ "mru_size",			KSTAT_DATA_UINT64 },
6884076b1bfSPrakash Surya 	{ "mru_evictable_data",		KSTAT_DATA_UINT64 },
6894076b1bfSPrakash Surya 	{ "mru_evictable_metadata",	KSTAT_DATA_UINT64 },
6904076b1bfSPrakash Surya 	{ "mru_ghost_size",		KSTAT_DATA_UINT64 },
6914076b1bfSPrakash Surya 	{ "mru_ghost_evictable_data",	KSTAT_DATA_UINT64 },
6924076b1bfSPrakash Surya 	{ "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
6934076b1bfSPrakash Surya 	{ "mfu_size",			KSTAT_DATA_UINT64 },
6944076b1bfSPrakash Surya 	{ "mfu_evictable_data",		KSTAT_DATA_UINT64 },
6954076b1bfSPrakash Surya 	{ "mfu_evictable_metadata",	KSTAT_DATA_UINT64 },
6964076b1bfSPrakash Surya 	{ "mfu_ghost_size",		KSTAT_DATA_UINT64 },
6974076b1bfSPrakash Surya 	{ "mfu_ghost_evictable_data",	KSTAT_DATA_UINT64 },
6984076b1bfSPrakash Surya 	{ "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
699fa94a07fSbrendan 	{ "l2_hits",			KSTAT_DATA_UINT64 },
700fa94a07fSbrendan 	{ "l2_misses",			KSTAT_DATA_UINT64 },
701fa94a07fSbrendan 	{ "l2_feeds",			KSTAT_DATA_UINT64 },
702fa94a07fSbrendan 	{ "l2_rw_clash",		KSTAT_DATA_UINT64 },
7035a98e54bSBrendan Gregg - Sun Microsystems 	{ "l2_read_bytes",		KSTAT_DATA_UINT64 },
7045a98e54bSBrendan Gregg - Sun Microsystems 	{ "l2_write_bytes",		KSTAT_DATA_UINT64 },
705fa94a07fSbrendan 	{ "l2_writes_sent",		KSTAT_DATA_UINT64 },
706fa94a07fSbrendan 	{ "l2_writes_done",		KSTAT_DATA_UINT64 },
707fa94a07fSbrendan 	{ "l2_writes_error",		KSTAT_DATA_UINT64 },
708244781f1SPrakash Surya 	{ "l2_writes_lock_retry",	KSTAT_DATA_UINT64 },
709fa94a07fSbrendan 	{ "l2_evict_lock_retry",	KSTAT_DATA_UINT64 },
710fa94a07fSbrendan 	{ "l2_evict_reading",		KSTAT_DATA_UINT64 },
71189c86e32SChris Williamson 	{ "l2_evict_l1cached",		KSTAT_DATA_UINT64 },
712fa94a07fSbrendan 	{ "l2_free_on_write",		KSTAT_DATA_UINT64 },
713fa94a07fSbrendan 	{ "l2_abort_lowmem",		KSTAT_DATA_UINT64 },
714fa94a07fSbrendan 	{ "l2_cksum_bad",		KSTAT_DATA_UINT64 },
715fa94a07fSbrendan 	{ "l2_io_error",		KSTAT_DATA_UINT64 },
716fa94a07fSbrendan 	{ "l2_size",			KSTAT_DATA_UINT64 },
717aad02571SSaso Kiselkov 	{ "l2_asize",			KSTAT_DATA_UINT64 },
7181ab7f2deSmaybee 	{ "l2_hdr_size",		KSTAT_DATA_UINT64 },
7199253d63dSGeorge Wilson 	{ "memory_throttle_count",	KSTAT_DATA_UINT64 },
72020128a08SGeorge Wilson 	{ "arc_meta_used",		KSTAT_DATA_UINT64 },
72120128a08SGeorge Wilson 	{ "arc_meta_limit",		KSTAT_DATA_UINT64 },
7223a5286a1SMatthew Ahrens 	{ "arc_meta_max",		KSTAT_DATA_UINT64 },
723cf6106c8SMatthew Ahrens 	{ "arc_meta_min",		KSTAT_DATA_UINT64 },
724cf6106c8SMatthew Ahrens 	{ "sync_wait_for_async",	KSTAT_DATA_UINT64 },
725cf6106c8SMatthew Ahrens 	{ "demand_hit_predictive_prefetch", KSTAT_DATA_UINT64 },
72644cb6abcSbmc };
72744cb6abcSbmc 
72844cb6abcSbmc #define	ARCSTAT(stat)	(arc_stats.stat.value.ui64)
72944cb6abcSbmc 
73044cb6abcSbmc #define	ARCSTAT_INCR(stat, val) \
731f7170741SWill Andrews 	atomic_add_64(&arc_stats.stat.value.ui64, (val))
73244cb6abcSbmc 
733b24ab676SJeff Bonwick #define	ARCSTAT_BUMP(stat)	ARCSTAT_INCR(stat, 1)
73444cb6abcSbmc #define	ARCSTAT_BUMPDOWN(stat)	ARCSTAT_INCR(stat, -1)
73544cb6abcSbmc 
73644cb6abcSbmc #define	ARCSTAT_MAX(stat, val) {					\
73744cb6abcSbmc 	uint64_t m;							\
73844cb6abcSbmc 	while ((val) > (m = arc_stats.stat.value.ui64) &&		\
73944cb6abcSbmc 	    (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val))))	\
74044cb6abcSbmc 		continue;						\
74144cb6abcSbmc }
74244cb6abcSbmc 
74344cb6abcSbmc #define	ARCSTAT_MAXSTAT(stat) \
74444cb6abcSbmc 	ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
74544cb6abcSbmc 
74644cb6abcSbmc /*
74744cb6abcSbmc  * We define a macro to allow ARC hits/misses to be easily broken down by
74844cb6abcSbmc  * two separate conditions, giving a total of four different subtypes for
74944cb6abcSbmc  * each of hits and misses (so eight statistics total).
75044cb6abcSbmc  */
75144cb6abcSbmc #define	ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
75244cb6abcSbmc 	if (cond1) {							\
75344cb6abcSbmc 		if (cond2) {						\
75444cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
75544cb6abcSbmc 		} else {						\
75644cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
75744cb6abcSbmc 		}							\
75844cb6abcSbmc 	} else {							\
75944cb6abcSbmc 		if (cond2) {						\
76044cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
76144cb6abcSbmc 		} else {						\
76244cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
76344cb6abcSbmc 		}							\
76444cb6abcSbmc 	}
76544cb6abcSbmc 
76644cb6abcSbmc kstat_t			*arc_ksp;
767b24ab676SJeff Bonwick static arc_state_t	*arc_anon;
76844cb6abcSbmc static arc_state_t	*arc_mru;
76944cb6abcSbmc static arc_state_t	*arc_mru_ghost;
77044cb6abcSbmc static arc_state_t	*arc_mfu;
77144cb6abcSbmc static arc_state_t	*arc_mfu_ghost;
772fa94a07fSbrendan static arc_state_t	*arc_l2c_only;
77344cb6abcSbmc 
77444cb6abcSbmc /*
77544cb6abcSbmc  * There are several ARC variables that are critical to export as kstats --
77644cb6abcSbmc  * but we don't want to have to grovel around in the kstat whenever we wish to
77744cb6abcSbmc  * manipulate them.  For these variables, we therefore define them to be in
77844cb6abcSbmc  * terms of the statistic variable.  This assures that we are not introducing
77944cb6abcSbmc  * the possibility of inconsistency by having shadow copies of the variables,
78044cb6abcSbmc  * while still allowing the code to be readable.
78144cb6abcSbmc  */
78244cb6abcSbmc #define	arc_size	ARCSTAT(arcstat_size)	/* actual total arc size */
78344cb6abcSbmc #define	arc_p		ARCSTAT(arcstat_p)	/* target size of MRU */
78444cb6abcSbmc #define	arc_c		ARCSTAT(arcstat_c)	/* target size of cache */
78544cb6abcSbmc #define	arc_c_min	ARCSTAT(arcstat_c_min)	/* min target cache size */
78644cb6abcSbmc #define	arc_c_max	ARCSTAT(arcstat_c_max)	/* max target cache size */
78720128a08SGeorge Wilson #define	arc_meta_limit	ARCSTAT(arcstat_meta_limit) /* max size for metadata */
7883a5286a1SMatthew Ahrens #define	arc_meta_min	ARCSTAT(arcstat_meta_min) /* min size for metadata */
78920128a08SGeorge Wilson #define	arc_meta_used	ARCSTAT(arcstat_meta_used) /* size of metadata */
79020128a08SGeorge Wilson #define	arc_meta_max	ARCSTAT(arcstat_meta_max) /* max size of metadata */
79144cb6abcSbmc 
792dcbf3bd6SGeorge Wilson /* compressed size of entire arc */
793dcbf3bd6SGeorge Wilson #define	arc_compressed_size	ARCSTAT(arcstat_compressed_size)
794dcbf3bd6SGeorge Wilson /* uncompressed size of entire arc */
795dcbf3bd6SGeorge Wilson #define	arc_uncompressed_size	ARCSTAT(arcstat_uncompressed_size)
796dcbf3bd6SGeorge Wilson /* number of bytes in the arc from arc_buf_t's */
797dcbf3bd6SGeorge Wilson #define	arc_overhead_size	ARCSTAT(arcstat_overhead_size)
798aad02571SSaso Kiselkov 
79944cb6abcSbmc static int		arc_no_grow;	/* Don't try to grow cache size */
80044cb6abcSbmc static uint64_t		arc_tempreserve;
8012fdbea25SAleksandr Guzovskiy static uint64_t		arc_loaned_bytes;
802fa9e4066Sahrens 
803fa9e4066Sahrens typedef struct arc_callback arc_callback_t;
804fa9e4066Sahrens 
805fa9e4066Sahrens struct arc_callback {
806fa9e4066Sahrens 	void			*acb_private;
807c717a561Smaybee 	arc_done_func_t		*acb_done;
808fa9e4066Sahrens 	arc_buf_t		*acb_buf;
8095602294fSDan Kimmel 	boolean_t		acb_compressed;
810fa9e4066Sahrens 	zio_t			*acb_zio_dummy;
811fa9e4066Sahrens 	arc_callback_t		*acb_next;
812fa9e4066Sahrens };
813fa9e4066Sahrens 
814c717a561Smaybee typedef struct arc_write_callback arc_write_callback_t;
815c717a561Smaybee 
816c717a561Smaybee struct arc_write_callback {
817c717a561Smaybee 	void		*awcb_private;
818c717a561Smaybee 	arc_done_func_t	*awcb_ready;
8198df0bcf0SPaul Dagnelie 	arc_done_func_t	*awcb_children_ready;
82069962b56SMatthew Ahrens 	arc_done_func_t	*awcb_physdone;
821c717a561Smaybee 	arc_done_func_t	*awcb_done;
822c717a561Smaybee 	arc_buf_t	*awcb_buf;
823c717a561Smaybee };
824c717a561Smaybee 
82589c86e32SChris Williamson /*
82689c86e32SChris Williamson  * ARC buffers are separated into multiple structs as a memory saving measure:
82789c86e32SChris Williamson  *   - Common fields struct, always defined, and embedded within it:
82889c86e32SChris Williamson  *       - L2-only fields, always allocated but undefined when not in L2ARC
82989c86e32SChris Williamson  *       - L1-only fields, only allocated when in L1ARC
83089c86e32SChris Williamson  *
83189c86e32SChris Williamson  *           Buffer in L1                     Buffer only in L2
83289c86e32SChris Williamson  *    +------------------------+          +------------------------+
83389c86e32SChris Williamson  *    | arc_buf_hdr_t          |          | arc_buf_hdr_t          |
83489c86e32SChris Williamson  *    |                        |          |                        |
83589c86e32SChris Williamson  *    |                        |          |                        |
83689c86e32SChris Williamson  *    |                        |          |                        |
83789c86e32SChris Williamson  *    +------------------------+          +------------------------+
83889c86e32SChris Williamson  *    | l2arc_buf_hdr_t        |          | l2arc_buf_hdr_t        |
83989c86e32SChris Williamson  *    | (undefined if L1-only) |          |                        |
84089c86e32SChris Williamson  *    +------------------------+          +------------------------+
84189c86e32SChris Williamson  *    | l1arc_buf_hdr_t        |
84289c86e32SChris Williamson  *    |                        |
84389c86e32SChris Williamson  *    |                        |
84489c86e32SChris Williamson  *    |                        |
84589c86e32SChris Williamson  *    |                        |
84689c86e32SChris Williamson  *    +------------------------+
84789c86e32SChris Williamson  *
84889c86e32SChris Williamson  * Because it's possible for the L2ARC to become extremely large, we can wind
84989c86e32SChris Williamson  * up eating a lot of memory in L2ARC buffer headers, so the size of a header
85089c86e32SChris Williamson  * is minimized by only allocating the fields necessary for an L1-cached buffer
85189c86e32SChris Williamson  * when a header is actually in the L1 cache. The sub-headers (l1arc_buf_hdr and
85289c86e32SChris Williamson  * l2arc_buf_hdr) are embedded rather than allocated separately to save a couple
85389c86e32SChris Williamson  * words in pointers. arc_hdr_realloc() is used to switch a header between
85489c86e32SChris Williamson  * these two allocation states.
85589c86e32SChris Williamson  */
85689c86e32SChris Williamson typedef struct l1arc_buf_hdr {
8576b4acc8bSahrens 	kmutex_t		b_freeze_lock;
858dcbf3bd6SGeorge Wilson 	zio_cksum_t		*b_freeze_cksum;
85989c86e32SChris Williamson #ifdef ZFS_DEBUG
86089c86e32SChris Williamson 	/*
8615602294fSDan Kimmel 	 * Used for debugging with kmem_flags - by allocating and freeing
86289c86e32SChris Williamson 	 * b_thawed when the buffer is thawed, we get a record of the stack
86389c86e32SChris Williamson 	 * trace that thawed it.
86489c86e32SChris Williamson 	 */
8653f9d6ad7SLin Ling 	void			*b_thawed;
86689c86e32SChris Williamson #endif
8676b4acc8bSahrens 
868fa9e4066Sahrens 	arc_buf_t		*b_buf;
869dcbf3bd6SGeorge Wilson 	uint32_t		b_bufcnt;
87089c86e32SChris Williamson 	/* for waiting on writes to complete */
871ad23a2dbSjohansen 	kcondvar_t		b_cv;
872dcbf3bd6SGeorge Wilson 	uint8_t			b_byteswap;
873ad23a2dbSjohansen 
874fa9e4066Sahrens 	/* protected by arc state mutex */
875fa9e4066Sahrens 	arc_state_t		*b_state;
876244781f1SPrakash Surya 	multilist_node_t	b_arc_node;
877fa9e4066Sahrens 
878fa9e4066Sahrens 	/* updated atomically */
879fa9e4066Sahrens 	clock_t			b_arc_access;
880fa9e4066Sahrens 
881fa9e4066Sahrens 	/* self protecting */
882fa9e4066Sahrens 	refcount_t		b_refcnt;
883fa94a07fSbrendan 
88489c86e32SChris Williamson 	arc_callback_t		*b_acb;
885dcbf3bd6SGeorge Wilson 	void			*b_pdata;
88689c86e32SChris Williamson } l1arc_buf_hdr_t;
88789c86e32SChris Williamson 
88889c86e32SChris Williamson typedef struct l2arc_dev l2arc_dev_t;
88989c86e32SChris Williamson 
89089c86e32SChris Williamson typedef struct l2arc_buf_hdr {
89189c86e32SChris Williamson 	/* protected by arc_buf_hdr mutex */
89289c86e32SChris Williamson 	l2arc_dev_t		*b_dev;		/* L2ARC device */
89389c86e32SChris Williamson 	uint64_t		b_daddr;	/* disk address, offset byte */
89489c86e32SChris Williamson 
895fa94a07fSbrendan 	list_node_t		b_l2node;
89689c86e32SChris Williamson } l2arc_buf_hdr_t;
89789c86e32SChris Williamson 
89889c86e32SChris Williamson struct arc_buf_hdr {
89989c86e32SChris Williamson 	/* protected by hash lock */
90089c86e32SChris Williamson 	dva_t			b_dva;
90189c86e32SChris Williamson 	uint64_t		b_birth;
90289c86e32SChris Williamson 
903dcbf3bd6SGeorge Wilson 	arc_buf_contents_t	b_type;
90489c86e32SChris Williamson 	arc_buf_hdr_t		*b_hash_next;
90589c86e32SChris Williamson 	arc_flags_t		b_flags;
90689c86e32SChris Williamson 
907dcbf3bd6SGeorge Wilson 	/*
908dcbf3bd6SGeorge Wilson 	 * This field stores the size of the data buffer after
909dcbf3bd6SGeorge Wilson 	 * compression, and is set in the arc's zio completion handlers.
910dcbf3bd6SGeorge Wilson 	 * It is in units of SPA_MINBLOCKSIZE (e.g. 1 == 512 bytes).
911dcbf3bd6SGeorge Wilson 	 *
912dcbf3bd6SGeorge Wilson 	 * While the block pointers can store up to 32MB in their psize
913dcbf3bd6SGeorge Wilson 	 * field, we can only store up to 32MB minus 512B. This is due
914dcbf3bd6SGeorge Wilson 	 * to the bp using a bias of 1, whereas we use a bias of 0 (i.e.
915dcbf3bd6SGeorge Wilson 	 * a field of zeros represents 512B in the bp). We can't use a
916dcbf3bd6SGeorge Wilson 	 * bias of 1 since we need to reserve a psize of zero, here, to
917dcbf3bd6SGeorge Wilson 	 * represent holes and embedded blocks.
918dcbf3bd6SGeorge Wilson 	 *
919dcbf3bd6SGeorge Wilson 	 * This isn't a problem in practice, since the maximum size of a
920dcbf3bd6SGeorge Wilson 	 * buffer is limited to 16MB, so we never need to store 32MB in
921dcbf3bd6SGeorge Wilson 	 * this field. Even in the upstream illumos code base, the
922dcbf3bd6SGeorge Wilson 	 * maximum size of a buffer is limited to 16MB.
923dcbf3bd6SGeorge Wilson 	 */
924dcbf3bd6SGeorge Wilson 	uint16_t		b_psize;
925dcbf3bd6SGeorge Wilson 
926dcbf3bd6SGeorge Wilson 	/*
927dcbf3bd6SGeorge Wilson 	 * This field stores the size of the data buffer before
928dcbf3bd6SGeorge Wilson 	 * compression, and cannot change once set. It is in units
929dcbf3bd6SGeorge Wilson 	 * of SPA_MINBLOCKSIZE (e.g. 2 == 1024 bytes)
930dcbf3bd6SGeorge Wilson 	 */
931dcbf3bd6SGeorge Wilson 	uint16_t		b_lsize;	/* immutable */
932dcbf3bd6SGeorge Wilson 	uint64_t		b_spa;		/* immutable */
93389c86e32SChris Williamson 
93489c86e32SChris Williamson 	/* L2ARC fields. Undefined when not in L2ARC. */
93589c86e32SChris Williamson 	l2arc_buf_hdr_t		b_l2hdr;
93689c86e32SChris Williamson 	/* L1ARC fields. Undefined when in l2arc_only state */
93789c86e32SChris Williamson 	l1arc_buf_hdr_t		b_l1hdr;
938fa9e4066Sahrens };
939fa9e4066Sahrens 
940ea8dc4b6Seschrock #define	GHOST_STATE(state)	\
941fa94a07fSbrendan 	((state) == arc_mru_ghost || (state) == arc_mfu_ghost ||	\
942fa94a07fSbrendan 	(state) == arc_l2c_only)
943ea8dc4b6Seschrock 
9447adb730bSGeorge Wilson #define	HDR_IN_HASH_TABLE(hdr)	((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
9457adb730bSGeorge Wilson #define	HDR_IO_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
9467adb730bSGeorge Wilson #define	HDR_IO_ERROR(hdr)	((hdr)->b_flags & ARC_FLAG_IO_ERROR)
9477adb730bSGeorge Wilson #define	HDR_PREFETCH(hdr)	((hdr)->b_flags & ARC_FLAG_PREFETCH)
948dcbf3bd6SGeorge Wilson #define	HDR_COMPRESSION_ENABLED(hdr)	\
949dcbf3bd6SGeorge Wilson 	((hdr)->b_flags & ARC_FLAG_COMPRESSED_ARC)
95089c86e32SChris Williamson 
9517adb730bSGeorge Wilson #define	HDR_L2CACHE(hdr)	((hdr)->b_flags & ARC_FLAG_L2CACHE)
9527adb730bSGeorge Wilson #define	HDR_L2_READING(hdr)	\
953dcbf3bd6SGeorge Wilson 	(((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) &&	\
954dcbf3bd6SGeorge Wilson 	((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
9557adb730bSGeorge Wilson #define	HDR_L2_WRITING(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITING)
9567adb730bSGeorge Wilson #define	HDR_L2_EVICTED(hdr)	((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
9577adb730bSGeorge Wilson #define	HDR_L2_WRITE_HEAD(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
958dcbf3bd6SGeorge Wilson #define	HDR_SHARED_DATA(hdr)	((hdr)->b_flags & ARC_FLAG_SHARED_DATA)
959fa9e4066Sahrens 
96089c86e32SChris Williamson #define	HDR_ISTYPE_METADATA(hdr)	\
961dcbf3bd6SGeorge Wilson 	((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
96289c86e32SChris Williamson #define	HDR_ISTYPE_DATA(hdr)	(!HDR_ISTYPE_METADATA(hdr))
96389c86e32SChris Williamson 
96489c86e32SChris Williamson #define	HDR_HAS_L1HDR(hdr)	((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
96589c86e32SChris Williamson #define	HDR_HAS_L2HDR(hdr)	((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
96689c86e32SChris Williamson 
967dcbf3bd6SGeorge Wilson /* For storing compression mode in b_flags */
968dcbf3bd6SGeorge Wilson #define	HDR_COMPRESS_OFFSET	(highbit64(ARC_FLAG_COMPRESS_0) - 1)
969dcbf3bd6SGeorge Wilson 
970dcbf3bd6SGeorge Wilson #define	HDR_GET_COMPRESS(hdr)	((enum zio_compress)BF32_GET((hdr)->b_flags, \
971dcbf3bd6SGeorge Wilson 	HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS))
972dcbf3bd6SGeorge Wilson #define	HDR_SET_COMPRESS(hdr, cmp) BF32_SET((hdr)->b_flags, \
973dcbf3bd6SGeorge Wilson 	HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS, (cmp));
974dcbf3bd6SGeorge Wilson 
975dcbf3bd6SGeorge Wilson #define	ARC_BUF_LAST(buf)	((buf)->b_next == NULL)
9765602294fSDan Kimmel #define	ARC_BUF_SHARED(buf)	((buf)->b_flags & ARC_BUF_FLAG_SHARED)
9775602294fSDan Kimmel #define	ARC_BUF_COMPRESSED(buf)	((buf)->b_flags & ARC_BUF_FLAG_COMPRESSED)
978dcbf3bd6SGeorge Wilson 
979e6c728e1Sbrendan /*
980e6c728e1Sbrendan  * Other sizes
981e6c728e1Sbrendan  */
982e6c728e1Sbrendan 
98389c86e32SChris Williamson #define	HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
98489c86e32SChris Williamson #define	HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
985e6c728e1Sbrendan 
986fa9e4066Sahrens /*
987fa9e4066Sahrens  * Hash table routines
988fa9e4066Sahrens  */
989fa9e4066Sahrens 
990fa9e4066Sahrens #define	HT_LOCK_PAD	64
991fa9e4066Sahrens 
992fa9e4066Sahrens struct ht_lock {
993fa9e4066Sahrens 	kmutex_t	ht_lock;
994fa9e4066Sahrens #ifdef _KERNEL
995fa9e4066Sahrens 	unsigned char	pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
996fa9e4066Sahrens #endif
997fa9e4066Sahrens };
998fa9e4066Sahrens 
999fa9e4066Sahrens #define	BUF_LOCKS 256
1000fa9e4066Sahrens typedef struct buf_hash_table {
1001fa9e4066Sahrens 	uint64_t ht_mask;
1002fa9e4066Sahrens 	arc_buf_hdr_t **ht_table;
1003fa9e4066Sahrens 	struct ht_lock ht_locks[BUF_LOCKS];
1004fa9e4066Sahrens } buf_hash_table_t;
1005fa9e4066Sahrens 
1006fa9e4066Sahrens static buf_hash_table_t buf_hash_table;
1007fa9e4066Sahrens 
1008fa9e4066Sahrens #define	BUF_HASH_INDEX(spa, dva, birth) \
1009fa9e4066Sahrens 	(buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
1010fa9e4066Sahrens #define	BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
1011fa9e4066Sahrens #define	BUF_HASH_LOCK(idx)	(&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
10123f9d6ad7SLin Ling #define	HDR_LOCK(hdr) \
10133f9d6ad7SLin Ling 	(BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
1014fa9e4066Sahrens 
1015fa9e4066Sahrens uint64_t zfs_crc64_table[256];
1016fa9e4066Sahrens 
1017fa94a07fSbrendan /*
1018fa94a07fSbrendan  * Level 2 ARC
1019fa94a07fSbrendan  */
1020fa94a07fSbrendan 
1021fa94a07fSbrendan #define	L2ARC_WRITE_SIZE	(8 * 1024 * 1024)	/* initial write max */
1022aad02571SSaso Kiselkov #define	L2ARC_HEADROOM		2			/* num of writes */
1023aad02571SSaso Kiselkov /*
1024aad02571SSaso Kiselkov  * If we discover during ARC scan any buffers to be compressed, we boost
1025aad02571SSaso Kiselkov  * our headroom for the next scanning cycle by this percentage multiple.
1026aad02571SSaso Kiselkov  */
1027aad02571SSaso Kiselkov #define	L2ARC_HEADROOM_BOOST	200
10285a98e54bSBrendan Gregg - Sun Microsystems #define	L2ARC_FEED_SECS		1		/* caching interval secs */
10295a98e54bSBrendan Gregg - Sun Microsystems #define	L2ARC_FEED_MIN_MS	200		/* min caching interval ms */
1030fa94a07fSbrendan 
1031fa94a07fSbrendan #define	l2arc_writes_sent	ARCSTAT(arcstat_l2_writes_sent)
1032fa94a07fSbrendan #define	l2arc_writes_done	ARCSTAT(arcstat_l2_writes_done)
1033fa94a07fSbrendan 
1034f7170741SWill Andrews /* L2ARC Performance Tunables */
1035fa94a07fSbrendan uint64_t l2arc_write_max = L2ARC_WRITE_SIZE;	/* default max write size */
10363a737e0dSbrendan uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE;	/* extra write during warmup */
1037fa94a07fSbrendan uint64_t l2arc_headroom = L2ARC_HEADROOM;	/* number of dev writes */
1038aad02571SSaso Kiselkov uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
1039fa94a07fSbrendan uint64_t l2arc_feed_secs = L2ARC_FEED_SECS;	/* interval seconds */
10405a98e54bSBrendan Gregg - Sun Microsystems uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS;	/* min interval milliseconds */
1041fa94a07fSbrendan boolean_t l2arc_noprefetch = B_TRUE;		/* don't cache prefetch bufs */
10425a98e54bSBrendan Gregg - Sun Microsystems boolean_t l2arc_feed_again = B_TRUE;		/* turbo warmup */
10435a98e54bSBrendan Gregg - Sun Microsystems boolean_t l2arc_norw = B_TRUE;			/* no reads during writes */
1044fa94a07fSbrendan 
1045fa94a07fSbrendan /*
1046fa94a07fSbrendan  * L2ARC Internals
1047fa94a07fSbrendan  */
104889c86e32SChris Williamson struct l2arc_dev {
1049fa94a07fSbrendan 	vdev_t			*l2ad_vdev;	/* vdev */
1050fa94a07fSbrendan 	spa_t			*l2ad_spa;	/* spa */
1051fa94a07fSbrendan 	uint64_t		l2ad_hand;	/* next write location */
1052fa94a07fSbrendan 	uint64_t		l2ad_start;	/* first addr on device */
1053fa94a07fSbrendan 	uint64_t		l2ad_end;	/* last addr on device */
1054fa94a07fSbrendan 	boolean_t		l2ad_first;	/* first sweep through */
10555a98e54bSBrendan Gregg - Sun Microsystems 	boolean_t		l2ad_writing;	/* currently writing */
105689c86e32SChris Williamson 	kmutex_t		l2ad_mtx;	/* lock for buffer list */
105789c86e32SChris Williamson 	list_t			l2ad_buflist;	/* buffer list */
1058fa94a07fSbrendan 	list_node_t		l2ad_node;	/* device list node */
1059a52fc310SPrakash Surya 	refcount_t		l2ad_alloc;	/* allocated bytes */
106089c86e32SChris Williamson };
1061fa94a07fSbrendan 
1062fa94a07fSbrendan static list_t L2ARC_dev_list;			/* device list */
1063fa94a07fSbrendan static list_t *l2arc_dev_list;			/* device list pointer */
1064fa94a07fSbrendan static kmutex_t l2arc_dev_mtx;			/* device list mutex */
1065fa94a07fSbrendan static l2arc_dev_t *l2arc_dev_last;		/* last device used */
1066fa94a07fSbrendan static list_t L2ARC_free_on_write;		/* free after write buf list */
1067fa94a07fSbrendan static list_t *l2arc_free_on_write;		/* free after write list ptr */
1068fa94a07fSbrendan static kmutex_t l2arc_free_on_write_mtx;	/* mutex for list */
1069fa94a07fSbrendan static uint64_t l2arc_ndev;			/* number of devices */
1070fa94a07fSbrendan 
1071fa94a07fSbrendan typedef struct l2arc_read_callback {
10725602294fSDan Kimmel 	arc_buf_hdr_t		*l2rcb_hdr;		/* read header */
1073aad02571SSaso Kiselkov 	blkptr_t		l2rcb_bp;		/* original blkptr */
10747802d7bfSMatthew Ahrens 	zbookmark_phys_t	l2rcb_zb;		/* original bookmark */
1075aad02571SSaso Kiselkov 	int			l2rcb_flags;		/* original flags */
1076fa94a07fSbrendan } l2arc_read_callback_t;
1077fa94a07fSbrendan 
1078fa94a07fSbrendan typedef struct l2arc_write_callback {
1079fa94a07fSbrendan 	l2arc_dev_t	*l2wcb_dev;		/* device info */
1080fa94a07fSbrendan 	arc_buf_hdr_t	*l2wcb_head;		/* head of write buflist */
1081fa94a07fSbrendan } l2arc_write_callback_t;
1082fa94a07fSbrendan 
1083fa94a07fSbrendan typedef struct l2arc_data_free {
1084fa94a07fSbrendan 	/* protected by l2arc_free_on_write_mtx */
1085fa94a07fSbrendan 	void		*l2df_data;
1086fa94a07fSbrendan 	size_t		l2df_size;
1087dcbf3bd6SGeorge Wilson 	arc_buf_contents_t l2df_type;
1088fa94a07fSbrendan 	list_node_t	l2df_list_node;
1089fa94a07fSbrendan } l2arc_data_free_t;
1090fa94a07fSbrendan 
1091fa94a07fSbrendan static kmutex_t l2arc_feed_thr_lock;
1092fa94a07fSbrendan static kcondvar_t l2arc_feed_thr_cv;
1093fa94a07fSbrendan static uint8_t l2arc_thread_exit;
1094fa94a07fSbrendan 
1095dcbf3bd6SGeorge Wilson static void *arc_get_data_buf(arc_buf_hdr_t *, uint64_t, void *);
1096dcbf3bd6SGeorge Wilson static void arc_free_data_buf(arc_buf_hdr_t *, void *, uint64_t, void *);
1097dcbf3bd6SGeorge Wilson static void arc_hdr_free_pdata(arc_buf_hdr_t *hdr);
1098dcbf3bd6SGeorge Wilson static void arc_hdr_alloc_pdata(arc_buf_hdr_t *);
10997adb730bSGeorge Wilson static void arc_access(arc_buf_hdr_t *, kmutex_t *);
1100244781f1SPrakash Surya static boolean_t arc_is_overflowing();
11017adb730bSGeorge Wilson static void arc_buf_watch(arc_buf_t *);
11027adb730bSGeorge Wilson 
110389c86e32SChris Williamson static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
110489c86e32SChris Williamson static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
1105dcbf3bd6SGeorge Wilson static inline void arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
1106dcbf3bd6SGeorge Wilson static inline void arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
110789c86e32SChris Williamson 
11087adb730bSGeorge Wilson static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
11097adb730bSGeorge Wilson static void l2arc_read_done(zio_t *);
1110fa94a07fSbrendan 
1111fa9e4066Sahrens static uint64_t
1112ac05c741SMark Maybee buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
1113fa9e4066Sahrens {
1114fa9e4066Sahrens 	uint8_t *vdva = (uint8_t *)dva;
1115fa9e4066Sahrens 	uint64_t crc = -1ULL;
1116fa9e4066Sahrens 	int i;
1117fa9e4066Sahrens 
1118fa9e4066Sahrens 	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
1119fa9e4066Sahrens 
1120fa9e4066Sahrens 	for (i = 0; i < sizeof (dva_t); i++)
1121fa9e4066Sahrens 		crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
1122fa9e4066Sahrens 
1123ac05c741SMark Maybee 	crc ^= (spa>>8) ^ birth;
1124fa9e4066Sahrens 
1125fa9e4066Sahrens 	return (crc);
1126fa9e4066Sahrens }
1127fa9e4066Sahrens 
1128dcbf3bd6SGeorge Wilson #define	HDR_EMPTY(hdr)						\
1129dcbf3bd6SGeorge Wilson 	((hdr)->b_dva.dva_word[0] == 0 &&			\
1130dcbf3bd6SGeorge Wilson 	(hdr)->b_dva.dva_word[1] == 0)
1131fa9e4066Sahrens 
1132dcbf3bd6SGeorge Wilson #define	HDR_EQUAL(spa, dva, birth, hdr)				\
1133dcbf3bd6SGeorge Wilson 	((hdr)->b_dva.dva_word[0] == (dva)->dva_word[0]) &&	\
1134dcbf3bd6SGeorge Wilson 	((hdr)->b_dva.dva_word[1] == (dva)->dva_word[1]) &&	\
1135dcbf3bd6SGeorge Wilson 	((hdr)->b_birth == birth) && ((hdr)->b_spa == spa)
1136fa9e4066Sahrens 
11373f9d6ad7SLin Ling static void
11383f9d6ad7SLin Ling buf_discard_identity(arc_buf_hdr_t *hdr)
11393f9d6ad7SLin Ling {
11403f9d6ad7SLin Ling 	hdr->b_dva.dva_word[0] = 0;
11413f9d6ad7SLin Ling 	hdr->b_dva.dva_word[1] = 0;
11423f9d6ad7SLin Ling 	hdr->b_birth = 0;
11433f9d6ad7SLin Ling }
11443f9d6ad7SLin Ling 
1145fa9e4066Sahrens static arc_buf_hdr_t *
11465d7b4d43SMatthew Ahrens buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
1147fa9e4066Sahrens {
11485d7b4d43SMatthew Ahrens 	const dva_t *dva = BP_IDENTITY(bp);
11495d7b4d43SMatthew Ahrens 	uint64_t birth = BP_PHYSICAL_BIRTH(bp);
1150fa9e4066Sahrens 	uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1151fa9e4066Sahrens 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
11527adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr;
1153fa9e4066Sahrens 
1154fa9e4066Sahrens 	mutex_enter(hash_lock);
11557adb730bSGeorge Wilson 	for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
11567adb730bSGeorge Wilson 	    hdr = hdr->b_hash_next) {
1157dcbf3bd6SGeorge Wilson 		if (HDR_EQUAL(spa, dva, birth, hdr)) {
1158fa9e4066Sahrens 			*lockp = hash_lock;
11597adb730bSGeorge Wilson 			return (hdr);
1160fa9e4066Sahrens 		}
1161fa9e4066Sahrens 	}
1162fa9e4066Sahrens 	mutex_exit(hash_lock);
1163fa9e4066Sahrens 	*lockp = NULL;
1164fa9e4066Sahrens 	return (NULL);
1165fa9e4066Sahrens }
1166fa9e4066Sahrens 
1167fa9e4066Sahrens /*
1168fa9e4066Sahrens  * Insert an entry into the hash table.  If there is already an element
1169fa9e4066Sahrens  * equal to elem in the hash table, then the already existing element
1170fa9e4066Sahrens  * will be returned and the new element will not be inserted.
1171fa9e4066Sahrens  * Otherwise returns NULL.
117289c86e32SChris Williamson  * If lockp == NULL, the caller is assumed to already hold the hash lock.
1173fa9e4066Sahrens  */
1174fa9e4066Sahrens static arc_buf_hdr_t *
11757adb730bSGeorge Wilson buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1176fa9e4066Sahrens {
11777adb730bSGeorge Wilson 	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1178fa9e4066Sahrens 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
11797adb730bSGeorge Wilson 	arc_buf_hdr_t *fhdr;
118044cb6abcSbmc 	uint32_t i;
1181fa9e4066Sahrens 
11827adb730bSGeorge Wilson 	ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
11837adb730bSGeorge Wilson 	ASSERT(hdr->b_birth != 0);
11847adb730bSGeorge Wilson 	ASSERT(!HDR_IN_HASH_TABLE(hdr));
118589c86e32SChris Williamson 
118689c86e32SChris Williamson 	if (lockp != NULL) {
118789c86e32SChris Williamson 		*lockp = hash_lock;
118889c86e32SChris Williamson 		mutex_enter(hash_lock);
118989c86e32SChris Williamson 	} else {
119089c86e32SChris Williamson 		ASSERT(MUTEX_HELD(hash_lock));
119189c86e32SChris Williamson 	}
119289c86e32SChris Williamson 
11937adb730bSGeorge Wilson 	for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
11947adb730bSGeorge Wilson 	    fhdr = fhdr->b_hash_next, i++) {
1195dcbf3bd6SGeorge Wilson 		if (HDR_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
11967adb730bSGeorge Wilson 			return (fhdr);
1197fa9e4066Sahrens 	}
1198fa9e4066Sahrens 
11997adb730bSGeorge Wilson 	hdr->b_hash_next = buf_hash_table.ht_table[idx];
12007adb730bSGeorge Wilson 	buf_hash_table.ht_table[idx] = hdr;
1201dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1202fa9e4066Sahrens 
1203fa9e4066Sahrens 	/* collect some hash table performance data */
1204fa9e4066Sahrens 	if (i > 0) {
120544cb6abcSbmc 		ARCSTAT_BUMP(arcstat_hash_collisions);
1206fa9e4066Sahrens 		if (i == 1)
120744cb6abcSbmc 			ARCSTAT_BUMP(arcstat_hash_chains);
120844cb6abcSbmc 
120944cb6abcSbmc 		ARCSTAT_MAX(arcstat_hash_chain_max, i);
1210fa9e4066Sahrens 	}
121144cb6abcSbmc 
121244cb6abcSbmc 	ARCSTAT_BUMP(arcstat_hash_elements);
121344cb6abcSbmc 	ARCSTAT_MAXSTAT(arcstat_hash_elements);
1214fa9e4066Sahrens 
1215fa9e4066Sahrens 	return (NULL);
1216fa9e4066Sahrens }
1217fa9e4066Sahrens 
1218fa9e4066Sahrens static void
12197adb730bSGeorge Wilson buf_hash_remove(arc_buf_hdr_t *hdr)
1220fa9e4066Sahrens {
12217adb730bSGeorge Wilson 	arc_buf_hdr_t *fhdr, **hdrp;
12227adb730bSGeorge Wilson 	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1223fa9e4066Sahrens 
1224fa9e4066Sahrens 	ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
12257adb730bSGeorge Wilson 	ASSERT(HDR_IN_HASH_TABLE(hdr));
1226fa9e4066Sahrens 
12277adb730bSGeorge Wilson 	hdrp = &buf_hash_table.ht_table[idx];
12287adb730bSGeorge Wilson 	while ((fhdr = *hdrp) != hdr) {
1229dcbf3bd6SGeorge Wilson 		ASSERT3P(fhdr, !=, NULL);
12307adb730bSGeorge Wilson 		hdrp = &fhdr->b_hash_next;
1231fa9e4066Sahrens 	}
12327adb730bSGeorge Wilson 	*hdrp = hdr->b_hash_next;
12337adb730bSGeorge Wilson 	hdr->b_hash_next = NULL;
1234dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1235fa9e4066Sahrens 
1236fa9e4066Sahrens 	/* collect some hash table performance data */
123744cb6abcSbmc 	ARCSTAT_BUMPDOWN(arcstat_hash_elements);
123844cb6abcSbmc 
1239fa9e4066Sahrens 	if (buf_hash_table.ht_table[idx] &&
1240fa9e4066Sahrens 	    buf_hash_table.ht_table[idx]->b_hash_next == NULL)
124144cb6abcSbmc 		ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1242fa9e4066Sahrens }
1243fa9e4066Sahrens 
1244fa9e4066Sahrens /*
1245fa9e4066Sahrens  * Global data structures and functions for the buf kmem cache.
1246fa9e4066Sahrens  */
124789c86e32SChris Williamson static kmem_cache_t *hdr_full_cache;
124889c86e32SChris Williamson static kmem_cache_t *hdr_l2only_cache;
1249fa9e4066Sahrens static kmem_cache_t *buf_cache;
1250fa9e4066Sahrens 
1251fa9e4066Sahrens static void
1252fa9e4066Sahrens buf_fini(void)
1253fa9e4066Sahrens {
1254fa9e4066Sahrens 	int i;
1255fa9e4066Sahrens 
1256fa9e4066Sahrens 	kmem_free(buf_hash_table.ht_table,
1257fa9e4066Sahrens 	    (buf_hash_table.ht_mask + 1) * sizeof (void *));
1258fa9e4066Sahrens 	for (i = 0; i < BUF_LOCKS; i++)
1259fa9e4066Sahrens 		mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
126089c86e32SChris Williamson 	kmem_cache_destroy(hdr_full_cache);
126189c86e32SChris Williamson 	kmem_cache_destroy(hdr_l2only_cache);
1262fa9e4066Sahrens 	kmem_cache_destroy(buf_cache);
1263fa9e4066Sahrens }
1264fa9e4066Sahrens 
1265fa9e4066Sahrens /*
1266fa9e4066Sahrens  * Constructor callback - called when the cache is empty
1267fa9e4066Sahrens  * and a new buf is requested.
1268fa9e4066Sahrens  */
1269fa9e4066Sahrens /* ARGSUSED */
1270fa9e4066Sahrens static int
127189c86e32SChris Williamson hdr_full_cons(void *vbuf, void *unused, int kmflag)
1272fa9e4066Sahrens {
12737adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr = vbuf;
1274fa9e4066Sahrens 
127589c86e32SChris Williamson 	bzero(hdr, HDR_FULL_SIZE);
127689c86e32SChris Williamson 	cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
127789c86e32SChris Williamson 	refcount_create(&hdr->b_l1hdr.b_refcnt);
127889c86e32SChris Williamson 	mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1279244781f1SPrakash Surya 	multilist_link_init(&hdr->b_l1hdr.b_arc_node);
128089c86e32SChris Williamson 	arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
128189c86e32SChris Williamson 
128289c86e32SChris Williamson 	return (0);
128389c86e32SChris Williamson }
128489c86e32SChris Williamson 
128589c86e32SChris Williamson /* ARGSUSED */
128689c86e32SChris Williamson static int
128789c86e32SChris Williamson hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
128889c86e32SChris Williamson {
128989c86e32SChris Williamson 	arc_buf_hdr_t *hdr = vbuf;
129089c86e32SChris Williamson 
129189c86e32SChris Williamson 	bzero(hdr, HDR_L2ONLY_SIZE);
129289c86e32SChris Williamson 	arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1293fa94a07fSbrendan 
1294fa9e4066Sahrens 	return (0);
1295fa9e4066Sahrens }
1296fa9e4066Sahrens 
12976f83844dSMark Maybee /* ARGSUSED */
12986f83844dSMark Maybee static int
12996f83844dSMark Maybee buf_cons(void *vbuf, void *unused, int kmflag)
13006f83844dSMark Maybee {
13016f83844dSMark Maybee 	arc_buf_t *buf = vbuf;
13026f83844dSMark Maybee 
13036f83844dSMark Maybee 	bzero(buf, sizeof (arc_buf_t));
13043f9d6ad7SLin Ling 	mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
13055a98e54bSBrendan Gregg - Sun Microsystems 	arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
13065a98e54bSBrendan Gregg - Sun Microsystems 
13076f83844dSMark Maybee 	return (0);
13086f83844dSMark Maybee }
13096f83844dSMark Maybee 
1310fa9e4066Sahrens /*
1311fa9e4066Sahrens  * Destructor callback - called when a cached buf is
1312fa9e4066Sahrens  * no longer required.
1313fa9e4066Sahrens  */
1314fa9e4066Sahrens /* ARGSUSED */
1315fa9e4066Sahrens static void
131689c86e32SChris Williamson hdr_full_dest(void *vbuf, void *unused)
131789c86e32SChris Williamson {
131889c86e32SChris Williamson 	arc_buf_hdr_t *hdr = vbuf;
131989c86e32SChris Williamson 
1320dcbf3bd6SGeorge Wilson 	ASSERT(HDR_EMPTY(hdr));
132189c86e32SChris Williamson 	cv_destroy(&hdr->b_l1hdr.b_cv);
132289c86e32SChris Williamson 	refcount_destroy(&hdr->b_l1hdr.b_refcnt);
132389c86e32SChris Williamson 	mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1324244781f1SPrakash Surya 	ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
132589c86e32SChris Williamson 	arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
132689c86e32SChris Williamson }
132789c86e32SChris Williamson 
132889c86e32SChris Williamson /* ARGSUSED */
132989c86e32SChris Williamson static void
133089c86e32SChris Williamson hdr_l2only_dest(void *vbuf, void *unused)
1331fa9e4066Sahrens {
13327adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr = vbuf;
1333fa9e4066Sahrens 
1334dcbf3bd6SGeorge Wilson 	ASSERT(HDR_EMPTY(hdr));
133589c86e32SChris Williamson 	arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1336fa9e4066Sahrens }
1337fa9e4066Sahrens 
13386f83844dSMark Maybee /* ARGSUSED */
13396f83844dSMark Maybee static void
13406f83844dSMark Maybee buf_dest(void *vbuf, void *unused)
13416f83844dSMark Maybee {
13426f83844dSMark Maybee 	arc_buf_t *buf = vbuf;
13436f83844dSMark Maybee 
13443f9d6ad7SLin Ling 	mutex_destroy(&buf->b_evict_lock);
13455a98e54bSBrendan Gregg - Sun Microsystems 	arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
13466f83844dSMark Maybee }
13476f83844dSMark Maybee 
1348fa9e4066Sahrens /*
1349fa9e4066Sahrens  * Reclaim callback -- invoked when memory is low.
1350fa9e4066Sahrens  */
1351fa9e4066Sahrens /* ARGSUSED */
1352fa9e4066Sahrens static void
1353fa9e4066Sahrens hdr_recl(void *unused)
1354fa9e4066Sahrens {
1355fa9e4066Sahrens 	dprintf("hdr_recl called\n");
135649e3519aSmaybee 	/*
135749e3519aSmaybee 	 * umem calls the reclaim func when we destroy the buf cache,
135849e3519aSmaybee 	 * which is after we do arc_fini().
135949e3519aSmaybee 	 */
136049e3519aSmaybee 	if (!arc_dead)
1361244781f1SPrakash Surya 		cv_signal(&arc_reclaim_thread_cv);
1362fa9e4066Sahrens }
1363fa9e4066Sahrens 
1364fa9e4066Sahrens static void
1365fa9e4066Sahrens buf_init(void)
1366fa9e4066Sahrens {
1367fa9e4066Sahrens 	uint64_t *ct;
1368ea8dc4b6Seschrock 	uint64_t hsize = 1ULL << 12;
1369fa9e4066Sahrens 	int i, j;
1370fa9e4066Sahrens 
1371fa9e4066Sahrens 	/*
1372fa9e4066Sahrens 	 * The hash table is big enough to fill all of physical memory
137363e911b6SMatthew Ahrens 	 * with an average block size of zfs_arc_average_blocksize (default 8K).
137463e911b6SMatthew Ahrens 	 * By default, the table will take up
137563e911b6SMatthew Ahrens 	 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1376fa9e4066Sahrens 	 */
137763e911b6SMatthew Ahrens 	while (hsize * zfs_arc_average_blocksize < physmem * PAGESIZE)
1378fa9e4066Sahrens 		hsize <<= 1;
1379ea8dc4b6Seschrock retry:
1380fa9e4066Sahrens 	buf_hash_table.ht_mask = hsize - 1;
1381ea8dc4b6Seschrock 	buf_hash_table.ht_table =
1382ea8dc4b6Seschrock 	    kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1383ea8dc4b6Seschrock 	if (buf_hash_table.ht_table == NULL) {
1384ea8dc4b6Seschrock 		ASSERT(hsize > (1ULL << 8));
1385ea8dc4b6Seschrock 		hsize >>= 1;
1386ea8dc4b6Seschrock 		goto retry;
1387ea8dc4b6Seschrock 	}
1388fa9e4066Sahrens 
138989c86e32SChris Williamson 	hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
139089c86e32SChris Williamson 	    0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
139189c86e32SChris Williamson 	hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
139289c86e32SChris Williamson 	    HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
139389c86e32SChris Williamson 	    NULL, NULL, 0);
1394fa9e4066Sahrens 	buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
13956f83844dSMark Maybee 	    0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1396fa9e4066Sahrens 
1397fa9e4066Sahrens 	for (i = 0; i < 256; i++)
1398fa9e4066Sahrens 		for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1399fa9e4066Sahrens 			*ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1400fa9e4066Sahrens 
1401fa9e4066Sahrens 	for (i = 0; i < BUF_LOCKS; i++) {
1402fa9e4066Sahrens 		mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1403fa9e4066Sahrens 		    NULL, MUTEX_DEFAULT, NULL);
1404fa9e4066Sahrens 	}
1405fa9e4066Sahrens }
1406fa9e4066Sahrens 
14075602294fSDan Kimmel /*
14085602294fSDan Kimmel  * This is the size that the buf occupies in memory. If the buf is compressed,
14095602294fSDan Kimmel  * it will correspond to the compressed size. You should use this method of
14105602294fSDan Kimmel  * getting the buf size unless you explicitly need the logical size.
14115602294fSDan Kimmel  */
14125602294fSDan Kimmel int32_t
14135602294fSDan Kimmel arc_buf_size(arc_buf_t *buf)
14145602294fSDan Kimmel {
14155602294fSDan Kimmel 	return (ARC_BUF_COMPRESSED(buf) ?
14165602294fSDan Kimmel 	    HDR_GET_PSIZE(buf->b_hdr) : HDR_GET_LSIZE(buf->b_hdr));
14175602294fSDan Kimmel }
14185602294fSDan Kimmel 
14195602294fSDan Kimmel int32_t
14205602294fSDan Kimmel arc_buf_lsize(arc_buf_t *buf)
14215602294fSDan Kimmel {
14225602294fSDan Kimmel 	return (HDR_GET_LSIZE(buf->b_hdr));
14235602294fSDan Kimmel }
14245602294fSDan Kimmel 
14255602294fSDan Kimmel enum zio_compress
14265602294fSDan Kimmel arc_get_compression(arc_buf_t *buf)
14275602294fSDan Kimmel {
14285602294fSDan Kimmel 	return (ARC_BUF_COMPRESSED(buf) ?
14295602294fSDan Kimmel 	    HDR_GET_COMPRESS(buf->b_hdr) : ZIO_COMPRESS_OFF);
14305602294fSDan Kimmel }
14315602294fSDan Kimmel 
1432dcbf3bd6SGeorge Wilson #define	ARC_MINTIME	(hz>>4) /* 62 ms */
1433244781f1SPrakash Surya 
1434dcbf3bd6SGeorge Wilson static inline boolean_t
1435dcbf3bd6SGeorge Wilson arc_buf_is_shared(arc_buf_t *buf)
1436dcbf3bd6SGeorge Wilson {
1437dcbf3bd6SGeorge Wilson 	boolean_t shared = (buf->b_data != NULL &&
1438dcbf3bd6SGeorge Wilson 	    buf->b_data == buf->b_hdr->b_l1hdr.b_pdata);
1439dcbf3bd6SGeorge Wilson 	IMPLY(shared, HDR_SHARED_DATA(buf->b_hdr));
14405602294fSDan Kimmel 	IMPLY(shared, ARC_BUF_SHARED(buf));
14415602294fSDan Kimmel 	IMPLY(shared, ARC_BUF_COMPRESSED(buf) || ARC_BUF_LAST(buf));
14425602294fSDan Kimmel 
14435602294fSDan Kimmel 	/*
14445602294fSDan Kimmel 	 * It would be nice to assert arc_can_share() too, but the "hdr isn't
14455602294fSDan Kimmel 	 * already being shared" requirement prevents us from doing that.
14465602294fSDan Kimmel 	 */
14475602294fSDan Kimmel 
1448dcbf3bd6SGeorge Wilson 	return (shared);
1449dcbf3bd6SGeorge Wilson }
1450c546f36aSArne Jansen 
14515602294fSDan Kimmel /*
14525602294fSDan Kimmel  * Free the checksum associated with this header. If there is no checksum, this
14535602294fSDan Kimmel  * is a no-op.
14545602294fSDan Kimmel  */
1455dcbf3bd6SGeorge Wilson static inline void
1456dcbf3bd6SGeorge Wilson arc_cksum_free(arc_buf_hdr_t *hdr)
1457dcbf3bd6SGeorge Wilson {
1458dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
1459dcbf3bd6SGeorge Wilson 	mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1460dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
1461dcbf3bd6SGeorge Wilson 		kmem_free(hdr->b_l1hdr.b_freeze_cksum, sizeof (zio_cksum_t));
1462dcbf3bd6SGeorge Wilson 		hdr->b_l1hdr.b_freeze_cksum = NULL;
146389c86e32SChris Williamson 	}
1464dcbf3bd6SGeorge Wilson 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
146589c86e32SChris Williamson }
146689c86e32SChris Williamson 
14675602294fSDan Kimmel /*
14685602294fSDan Kimmel  * Return true iff at least one of the bufs on hdr is not compressed.
14695602294fSDan Kimmel  */
14705602294fSDan Kimmel static boolean_t
14715602294fSDan Kimmel arc_hdr_has_uncompressed_buf(arc_buf_hdr_t *hdr)
14725602294fSDan Kimmel {
14735602294fSDan Kimmel 	for (arc_buf_t *b = hdr->b_l1hdr.b_buf; b != NULL; b = b->b_next) {
14745602294fSDan Kimmel 		if (!ARC_BUF_COMPRESSED(b)) {
14755602294fSDan Kimmel 			return (B_TRUE);
14765602294fSDan Kimmel 		}
14775602294fSDan Kimmel 	}
14785602294fSDan Kimmel 	return (B_FALSE);
14795602294fSDan Kimmel }
14805602294fSDan Kimmel 
14815602294fSDan Kimmel /*
14825602294fSDan Kimmel  * If we've turned on the ZFS_DEBUG_MODIFY flag, verify that the buf's data
14835602294fSDan Kimmel  * matches the checksum that is stored in the hdr. If there is no checksum,
14845602294fSDan Kimmel  * or if the buf is compressed, this is a no-op.
14855602294fSDan Kimmel  */
14866b4acc8bSahrens static void
14876b4acc8bSahrens arc_cksum_verify(arc_buf_t *buf)
14886b4acc8bSahrens {
1489dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
14906b4acc8bSahrens 	zio_cksum_t zc;
14916b4acc8bSahrens 
1492cc60fd72Sahrens 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
14936b4acc8bSahrens 		return;
14946b4acc8bSahrens 
14955602294fSDan Kimmel 	if (ARC_BUF_COMPRESSED(buf)) {
14965602294fSDan Kimmel 		ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
14975602294fSDan Kimmel 		    arc_hdr_has_uncompressed_buf(hdr));
14985602294fSDan Kimmel 		return;
14995602294fSDan Kimmel 	}
15005602294fSDan Kimmel 
1501dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
1502dcbf3bd6SGeorge Wilson 
1503dcbf3bd6SGeorge Wilson 	mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1504dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_freeze_cksum == NULL || HDR_IO_ERROR(hdr)) {
1505dcbf3bd6SGeorge Wilson 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
15066b4acc8bSahrens 		return;
15076b4acc8bSahrens 	}
15085602294fSDan Kimmel 
15095602294fSDan Kimmel 	fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL, &zc);
1510dcbf3bd6SGeorge Wilson 	if (!ZIO_CHECKSUM_EQUAL(*hdr->b_l1hdr.b_freeze_cksum, zc))
15116b4acc8bSahrens 		panic("buffer modified while frozen!");
1512dcbf3bd6SGeorge Wilson 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
15136b4acc8bSahrens }
15146b4acc8bSahrens 
1515dcbf3bd6SGeorge Wilson static boolean_t
1516dcbf3bd6SGeorge Wilson arc_cksum_is_equal(arc_buf_hdr_t *hdr, zio_t *zio)
1517fa94a07fSbrendan {
1518dcbf3bd6SGeorge Wilson 	enum zio_compress compress = BP_GET_COMPRESS(zio->io_bp);
1519dcbf3bd6SGeorge Wilson 	boolean_t valid_cksum;
1520fa94a07fSbrendan 
1521dcbf3bd6SGeorge Wilson 	ASSERT(!BP_IS_EMBEDDED(zio->io_bp));
1522dcbf3bd6SGeorge Wilson 	VERIFY3U(BP_GET_PSIZE(zio->io_bp), ==, HDR_GET_PSIZE(hdr));
1523dcbf3bd6SGeorge Wilson 
1524dcbf3bd6SGeorge Wilson 	/*
1525dcbf3bd6SGeorge Wilson 	 * We rely on the blkptr's checksum to determine if the block
1526dcbf3bd6SGeorge Wilson 	 * is valid or not. When compressed arc is enabled, the l2arc
1527dcbf3bd6SGeorge Wilson 	 * writes the block to the l2arc just as it appears in the pool.
1528dcbf3bd6SGeorge Wilson 	 * This allows us to use the blkptr's checksum to validate the
1529dcbf3bd6SGeorge Wilson 	 * data that we just read off of the l2arc without having to store
1530dcbf3bd6SGeorge Wilson 	 * a separate checksum in the arc_buf_hdr_t. However, if compressed
1531dcbf3bd6SGeorge Wilson 	 * arc is disabled, then the data written to the l2arc is always
1532dcbf3bd6SGeorge Wilson 	 * uncompressed and won't match the block as it exists in the main
1533dcbf3bd6SGeorge Wilson 	 * pool. When this is the case, we must first compress it if it is
1534dcbf3bd6SGeorge Wilson 	 * compressed on the main pool before we can validate the checksum.
1535dcbf3bd6SGeorge Wilson 	 */
1536dcbf3bd6SGeorge Wilson 	if (!HDR_COMPRESSION_ENABLED(hdr) && compress != ZIO_COMPRESS_OFF) {
1537dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
1538dcbf3bd6SGeorge Wilson 		uint64_t lsize = HDR_GET_LSIZE(hdr);
1539dcbf3bd6SGeorge Wilson 		uint64_t csize;
1540dcbf3bd6SGeorge Wilson 
1541dcbf3bd6SGeorge Wilson 		void *cbuf = zio_buf_alloc(HDR_GET_PSIZE(hdr));
1542dcbf3bd6SGeorge Wilson 		csize = zio_compress_data(compress, zio->io_data, cbuf, lsize);
1543dcbf3bd6SGeorge Wilson 		ASSERT3U(csize, <=, HDR_GET_PSIZE(hdr));
1544dcbf3bd6SGeorge Wilson 		if (csize < HDR_GET_PSIZE(hdr)) {
1545dcbf3bd6SGeorge Wilson 			/*
1546dcbf3bd6SGeorge Wilson 			 * Compressed blocks are always a multiple of the
1547dcbf3bd6SGeorge Wilson 			 * smallest ashift in the pool. Ideally, we would
1548dcbf3bd6SGeorge Wilson 			 * like to round up the csize to the next
1549dcbf3bd6SGeorge Wilson 			 * spa_min_ashift but that value may have changed
1550dcbf3bd6SGeorge Wilson 			 * since the block was last written. Instead,
1551dcbf3bd6SGeorge Wilson 			 * we rely on the fact that the hdr's psize
1552dcbf3bd6SGeorge Wilson 			 * was set to the psize of the block when it was
1553dcbf3bd6SGeorge Wilson 			 * last written. We set the csize to that value
1554dcbf3bd6SGeorge Wilson 			 * and zero out any part that should not contain
1555dcbf3bd6SGeorge Wilson 			 * data.
1556dcbf3bd6SGeorge Wilson 			 */
1557dcbf3bd6SGeorge Wilson 			bzero((char *)cbuf + csize, HDR_GET_PSIZE(hdr) - csize);
1558dcbf3bd6SGeorge Wilson 			csize = HDR_GET_PSIZE(hdr);
1559dcbf3bd6SGeorge Wilson 		}
1560dcbf3bd6SGeorge Wilson 		zio_push_transform(zio, cbuf, csize, HDR_GET_PSIZE(hdr), NULL);
1561dcbf3bd6SGeorge Wilson 	}
1562fa94a07fSbrendan 
1563dcbf3bd6SGeorge Wilson 	/*
1564dcbf3bd6SGeorge Wilson 	 * Block pointers always store the checksum for the logical data.
1565dcbf3bd6SGeorge Wilson 	 * If the block pointer has the gang bit set, then the checksum
1566dcbf3bd6SGeorge Wilson 	 * it represents is for the reconstituted data and not for an
1567dcbf3bd6SGeorge Wilson 	 * individual gang member. The zio pipeline, however, must be able to
1568dcbf3bd6SGeorge Wilson 	 * determine the checksum of each of the gang constituents so it
1569dcbf3bd6SGeorge Wilson 	 * treats the checksum comparison differently than what we need
1570dcbf3bd6SGeorge Wilson 	 * for l2arc blocks. This prevents us from using the
1571dcbf3bd6SGeorge Wilson 	 * zio_checksum_error() interface directly. Instead we must call the
1572dcbf3bd6SGeorge Wilson 	 * zio_checksum_error_impl() so that we can ensure the checksum is
1573dcbf3bd6SGeorge Wilson 	 * generated using the correct checksum algorithm and accounts for the
1574dcbf3bd6SGeorge Wilson 	 * logical I/O size and not just a gang fragment.
1575dcbf3bd6SGeorge Wilson 	 */
1576dcbf3bd6SGeorge Wilson 	valid_cksum = (zio_checksum_error_impl(zio->io_spa, zio->io_bp,
1577dcbf3bd6SGeorge Wilson 	    BP_GET_CHECKSUM(zio->io_bp), zio->io_data, zio->io_size,
1578dcbf3bd6SGeorge Wilson 	    zio->io_offset, NULL) == 0);
1579dcbf3bd6SGeorge Wilson 	zio_pop_transforms(zio);
1580dcbf3bd6SGeorge Wilson 	return (valid_cksum);
1581fa94a07fSbrendan }
1582fa94a07fSbrendan 
15835602294fSDan Kimmel /*
15845602294fSDan Kimmel  * Given a buf full of data, if ZFS_DEBUG_MODIFY is enabled this computes a
15855602294fSDan Kimmel  * checksum and attaches it to the buf's hdr so that we can ensure that the buf
15865602294fSDan Kimmel  * isn't modified later on. If buf is compressed or there is already a checksum
15875602294fSDan Kimmel  * on the hdr, this is a no-op (we only checksum uncompressed bufs).
15885602294fSDan Kimmel  */
15896b4acc8bSahrens static void
1590dcbf3bd6SGeorge Wilson arc_cksum_compute(arc_buf_t *buf)
15916b4acc8bSahrens {
1592dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
1593dcbf3bd6SGeorge Wilson 
1594dcbf3bd6SGeorge Wilson 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
15956b4acc8bSahrens 		return;
15966b4acc8bSahrens 
1597dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
15985602294fSDan Kimmel 
159989c86e32SChris Williamson 	mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1600dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
16015602294fSDan Kimmel 		ASSERT(arc_hdr_has_uncompressed_buf(hdr));
16025602294fSDan Kimmel 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
16035602294fSDan Kimmel 		return;
16045602294fSDan Kimmel 	} else if (ARC_BUF_COMPRESSED(buf)) {
1605dcbf3bd6SGeorge Wilson 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
16066b4acc8bSahrens 		return;
16076b4acc8bSahrens 	}
16085602294fSDan Kimmel 
16095602294fSDan Kimmel 	ASSERT(!ARC_BUF_COMPRESSED(buf));
1610dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t),
1611dcbf3bd6SGeorge Wilson 	    KM_SLEEP);
16125602294fSDan Kimmel 	fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL,
1613dcbf3bd6SGeorge Wilson 	    hdr->b_l1hdr.b_freeze_cksum);
1614dcbf3bd6SGeorge Wilson 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1615cd1c8b85SMatthew Ahrens 	arc_buf_watch(buf);
1616cd1c8b85SMatthew Ahrens }
1617cd1c8b85SMatthew Ahrens 
1618cd1c8b85SMatthew Ahrens #ifndef _KERNEL
1619cd1c8b85SMatthew Ahrens typedef struct procctl {
1620cd1c8b85SMatthew Ahrens 	long cmd;
1621cd1c8b85SMatthew Ahrens 	prwatch_t prwatch;
1622cd1c8b85SMatthew Ahrens } procctl_t;
1623cd1c8b85SMatthew Ahrens #endif
1624cd1c8b85SMatthew Ahrens 
1625cd1c8b85SMatthew Ahrens /* ARGSUSED */
1626cd1c8b85SMatthew Ahrens static void
1627cd1c8b85SMatthew Ahrens arc_buf_unwatch(arc_buf_t *buf)
1628cd1c8b85SMatthew Ahrens {
1629cd1c8b85SMatthew Ahrens #ifndef _KERNEL
1630cd1c8b85SMatthew Ahrens 	if (arc_watch) {
1631cd1c8b85SMatthew Ahrens 		int result;
1632cd1c8b85SMatthew Ahrens 		procctl_t ctl;
1633cd1c8b85SMatthew Ahrens 		ctl.cmd = PCWATCH;
1634cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1635cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_size = 0;
1636cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_wflags = 0;
1637cd1c8b85SMatthew Ahrens 		result = write(arc_procfd, &ctl, sizeof (ctl));
1638cd1c8b85SMatthew Ahrens 		ASSERT3U(result, ==, sizeof (ctl));
1639cd1c8b85SMatthew Ahrens 	}
1640cd1c8b85SMatthew Ahrens #endif
1641cd1c8b85SMatthew Ahrens }
1642cd1c8b85SMatthew Ahrens 
1643cd1c8b85SMatthew Ahrens /* ARGSUSED */
1644cd1c8b85SMatthew Ahrens static void
1645cd1c8b85SMatthew Ahrens arc_buf_watch(arc_buf_t *buf)
1646cd1c8b85SMatthew Ahrens {
1647cd1c8b85SMatthew Ahrens #ifndef _KERNEL
1648cd1c8b85SMatthew Ahrens 	if (arc_watch) {
1649cd1c8b85SMatthew Ahrens 		int result;
1650cd1c8b85SMatthew Ahrens 		procctl_t ctl;
1651cd1c8b85SMatthew Ahrens 		ctl.cmd = PCWATCH;
1652cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
16535602294fSDan Kimmel 		ctl.prwatch.pr_size = arc_buf_size(buf);
1654cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_wflags = WA_WRITE;
1655cd1c8b85SMatthew Ahrens 		result = write(arc_procfd, &ctl, sizeof (ctl));
1656cd1c8b85SMatthew Ahrens 		ASSERT3U(result, ==, sizeof (ctl));
1657cd1c8b85SMatthew Ahrens 	}
1658cd1c8b85SMatthew Ahrens #endif
16596b4acc8bSahrens }
16606b4acc8bSahrens 
166189c86e32SChris Williamson static arc_buf_contents_t
166289c86e32SChris Williamson arc_buf_type(arc_buf_hdr_t *hdr)
166389c86e32SChris Williamson {
1664dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type;
166589c86e32SChris Williamson 	if (HDR_ISTYPE_METADATA(hdr)) {
1666dcbf3bd6SGeorge Wilson 		type = ARC_BUFC_METADATA;
166789c86e32SChris Williamson 	} else {
1668dcbf3bd6SGeorge Wilson 		type = ARC_BUFC_DATA;
166989c86e32SChris Williamson 	}
1670dcbf3bd6SGeorge Wilson 	VERIFY3U(hdr->b_type, ==, type);
1671dcbf3bd6SGeorge Wilson 	return (type);
167289c86e32SChris Williamson }
167389c86e32SChris Williamson 
16745602294fSDan Kimmel boolean_t
16755602294fSDan Kimmel arc_is_metadata(arc_buf_t *buf)
16765602294fSDan Kimmel {
16775602294fSDan Kimmel 	return (HDR_ISTYPE_METADATA(buf->b_hdr) != 0);
16785602294fSDan Kimmel }
16795602294fSDan Kimmel 
168089c86e32SChris Williamson static uint32_t
168189c86e32SChris Williamson arc_bufc_to_flags(arc_buf_contents_t type)
168289c86e32SChris Williamson {
168389c86e32SChris Williamson 	switch (type) {
168489c86e32SChris Williamson 	case ARC_BUFC_DATA:
168589c86e32SChris Williamson 		/* metadata field is 0 if buffer contains normal data */
168689c86e32SChris Williamson 		return (0);
168789c86e32SChris Williamson 	case ARC_BUFC_METADATA:
168889c86e32SChris Williamson 		return (ARC_FLAG_BUFC_METADATA);
168989c86e32SChris Williamson 	default:
169089c86e32SChris Williamson 		break;
169189c86e32SChris Williamson 	}
169289c86e32SChris Williamson 	panic("undefined ARC buffer type!");
169389c86e32SChris Williamson 	return ((uint32_t)-1);
169489c86e32SChris Williamson }
169589c86e32SChris Williamson 
16966b4acc8bSahrens void
16976b4acc8bSahrens arc_buf_thaw(arc_buf_t *buf)
16986b4acc8bSahrens {
1699dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
1700dcbf3bd6SGeorge Wilson 
17015602294fSDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
17025602294fSDan Kimmel 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
17035602294fSDan Kimmel 
17045602294fSDan Kimmel 	arc_cksum_verify(buf);
17055602294fSDan Kimmel 
17065602294fSDan Kimmel 	/*
17075602294fSDan Kimmel 	 * Compressed buffers do not manipulate the b_freeze_cksum or
17085602294fSDan Kimmel 	 * allocate b_thawed.
17095602294fSDan Kimmel 	 */
17105602294fSDan Kimmel 	if (ARC_BUF_COMPRESSED(buf)) {
17115602294fSDan Kimmel 		ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
17125602294fSDan Kimmel 		    arc_hdr_has_uncompressed_buf(hdr));
17135602294fSDan Kimmel 		return;
1714fa94a07fSbrendan 	}
17156b4acc8bSahrens 
1716dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
1717dcbf3bd6SGeorge Wilson 	arc_cksum_free(hdr);
17183f9d6ad7SLin Ling 
1719dcbf3bd6SGeorge Wilson 	mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
172089c86e32SChris Williamson #ifdef ZFS_DEBUG
17213f9d6ad7SLin Ling 	if (zfs_flags & ZFS_DEBUG_MODIFY) {
1722dcbf3bd6SGeorge Wilson 		if (hdr->b_l1hdr.b_thawed != NULL)
1723dcbf3bd6SGeorge Wilson 			kmem_free(hdr->b_l1hdr.b_thawed, 1);
1724dcbf3bd6SGeorge Wilson 		hdr->b_l1hdr.b_thawed = kmem_alloc(1, KM_SLEEP);
17253f9d6ad7SLin Ling 	}
172689c86e32SChris Williamson #endif
17273f9d6ad7SLin Ling 
1728dcbf3bd6SGeorge Wilson 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1729cd1c8b85SMatthew Ahrens 
1730cd1c8b85SMatthew Ahrens 	arc_buf_unwatch(buf);
17316b4acc8bSahrens }
17326b4acc8bSahrens 
17336b4acc8bSahrens void
17346b4acc8bSahrens arc_buf_freeze(arc_buf_t *buf)
17356b4acc8bSahrens {
1736dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
17373f9d6ad7SLin Ling 	kmutex_t *hash_lock;
17383f9d6ad7SLin Ling 
1739cc60fd72Sahrens 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1740cc60fd72Sahrens 		return;
1741cc60fd72Sahrens 
17425602294fSDan Kimmel 	if (ARC_BUF_COMPRESSED(buf)) {
17435602294fSDan Kimmel 		ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
17445602294fSDan Kimmel 		    arc_hdr_has_uncompressed_buf(hdr));
17455602294fSDan Kimmel 		return;
17465602294fSDan Kimmel 	}
17475602294fSDan Kimmel 
1748dcbf3bd6SGeorge Wilson 	hash_lock = HDR_LOCK(hdr);
17493f9d6ad7SLin Ling 	mutex_enter(hash_lock);
17503f9d6ad7SLin Ling 
1751dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
1752dcbf3bd6SGeorge Wilson 	ASSERT(hdr->b_l1hdr.b_freeze_cksum != NULL ||
1753dcbf3bd6SGeorge Wilson 	    hdr->b_l1hdr.b_state == arc_anon);
1754dcbf3bd6SGeorge Wilson 	arc_cksum_compute(buf);
17553f9d6ad7SLin Ling 	mutex_exit(hash_lock);
17566b4acc8bSahrens }
17576b4acc8bSahrens 
1758dcbf3bd6SGeorge Wilson /*
1759dcbf3bd6SGeorge Wilson  * The arc_buf_hdr_t's b_flags should never be modified directly. Instead,
1760dcbf3bd6SGeorge Wilson  * the following functions should be used to ensure that the flags are
1761dcbf3bd6SGeorge Wilson  * updated in a thread-safe way. When manipulating the flags either
1762dcbf3bd6SGeorge Wilson  * the hash_lock must be held or the hdr must be undiscoverable. This
1763dcbf3bd6SGeorge Wilson  * ensures that we're not racing with any other threads when updating
1764dcbf3bd6SGeorge Wilson  * the flags.
1765dcbf3bd6SGeorge Wilson  */
1766dcbf3bd6SGeorge Wilson static inline void
1767dcbf3bd6SGeorge Wilson arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
1768dcbf3bd6SGeorge Wilson {
1769dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
1770dcbf3bd6SGeorge Wilson 	hdr->b_flags |= flags;
1771dcbf3bd6SGeorge Wilson }
1772dcbf3bd6SGeorge Wilson 
1773dcbf3bd6SGeorge Wilson static inline void
1774dcbf3bd6SGeorge Wilson arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
1775dcbf3bd6SGeorge Wilson {
1776dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
1777dcbf3bd6SGeorge Wilson 	hdr->b_flags &= ~flags;
1778dcbf3bd6SGeorge Wilson }
1779dcbf3bd6SGeorge Wilson 
1780dcbf3bd6SGeorge Wilson /*
1781dcbf3bd6SGeorge Wilson  * Setting the compression bits in the arc_buf_hdr_t's b_flags is
1782dcbf3bd6SGeorge Wilson  * done in a special way since we have to clear and set bits
1783dcbf3bd6SGeorge Wilson  * at the same time. Consumers that wish to set the compression bits
1784dcbf3bd6SGeorge Wilson  * must use this function to ensure that the flags are updated in
1785dcbf3bd6SGeorge Wilson  * thread-safe manner.
1786dcbf3bd6SGeorge Wilson  */
1787fa9e4066Sahrens static void
1788dcbf3bd6SGeorge Wilson arc_hdr_set_compress(arc_buf_hdr_t *hdr, enum zio_compress cmp)
1789fa9e4066Sahrens {
1790dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
1791fa9e4066Sahrens 
1792dcbf3bd6SGeorge Wilson 	/*
1793dcbf3bd6SGeorge Wilson 	 * Holes and embedded blocks will always have a psize = 0 so
1794dcbf3bd6SGeorge Wilson 	 * we ignore the compression of the blkptr and set the
1795dcbf3bd6SGeorge Wilson 	 * arc_buf_hdr_t's compression to ZIO_COMPRESS_OFF.
1796dcbf3bd6SGeorge Wilson 	 * Holes and embedded blocks remain anonymous so we don't
1797dcbf3bd6SGeorge Wilson 	 * want to uncompress them. Mark them as uncompressed.
1798dcbf3bd6SGeorge Wilson 	 */
1799dcbf3bd6SGeorge Wilson 	if (!zfs_compressed_arc_enabled || HDR_GET_PSIZE(hdr) == 0) {
1800dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
1801dcbf3bd6SGeorge Wilson 		HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_OFF);
1802dcbf3bd6SGeorge Wilson 		ASSERT(!HDR_COMPRESSION_ENABLED(hdr));
1803dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
1804dcbf3bd6SGeorge Wilson 	} else {
1805dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
1806dcbf3bd6SGeorge Wilson 		HDR_SET_COMPRESS(hdr, cmp);
1807dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, cmp);
1808dcbf3bd6SGeorge Wilson 		ASSERT(HDR_COMPRESSION_ENABLED(hdr));
1809dcbf3bd6SGeorge Wilson 	}
1810dcbf3bd6SGeorge Wilson }
1811244781f1SPrakash Surya 
18125602294fSDan Kimmel /*
18135602294fSDan Kimmel  * Looks for another buf on the same hdr which has the data decompressed, copies
18145602294fSDan Kimmel  * from it, and returns true. If no such buf exists, returns false.
18155602294fSDan Kimmel  */
18165602294fSDan Kimmel static boolean_t
18175602294fSDan Kimmel arc_buf_try_copy_decompressed_data(arc_buf_t *buf)
18185602294fSDan Kimmel {
18195602294fSDan Kimmel 	arc_buf_hdr_t *hdr = buf->b_hdr;
18205602294fSDan Kimmel 	boolean_t copied = B_FALSE;
18215602294fSDan Kimmel 
18225602294fSDan Kimmel 	ASSERT(HDR_HAS_L1HDR(hdr));
18235602294fSDan Kimmel 	ASSERT3P(buf->b_data, !=, NULL);
18245602294fSDan Kimmel 	ASSERT(!ARC_BUF_COMPRESSED(buf));
18255602294fSDan Kimmel 
18265602294fSDan Kimmel 	for (arc_buf_t *from = hdr->b_l1hdr.b_buf; from != NULL;
18275602294fSDan Kimmel 	    from = from->b_next) {
18285602294fSDan Kimmel 		/* can't use our own data buffer */
18295602294fSDan Kimmel 		if (from == buf) {
18305602294fSDan Kimmel 			continue;
18315602294fSDan Kimmel 		}
18325602294fSDan Kimmel 
18335602294fSDan Kimmel 		if (!ARC_BUF_COMPRESSED(from)) {
18345602294fSDan Kimmel 			bcopy(from->b_data, buf->b_data, arc_buf_size(buf));
18355602294fSDan Kimmel 			copied = B_TRUE;
18365602294fSDan Kimmel 			break;
18375602294fSDan Kimmel 		}
18385602294fSDan Kimmel 	}
18395602294fSDan Kimmel 
18405602294fSDan Kimmel 	/*
18415602294fSDan Kimmel 	 * There were no decompressed bufs, so there should not be a
18425602294fSDan Kimmel 	 * checksum on the hdr either.
18435602294fSDan Kimmel 	 */
18445602294fSDan Kimmel 	EQUIV(!copied, hdr->b_l1hdr.b_freeze_cksum == NULL);
18455602294fSDan Kimmel 
18465602294fSDan Kimmel 	return (copied);
18475602294fSDan Kimmel }
18485602294fSDan Kimmel 
18495602294fSDan Kimmel /*
18505602294fSDan Kimmel  * Given a buf that has a data buffer attached to it, this function will
18515602294fSDan Kimmel  * efficiently fill the buf with data of the specified compression setting from
18525602294fSDan Kimmel  * the hdr and update the hdr's b_freeze_cksum if necessary. If the buf and hdr
18535602294fSDan Kimmel  * are already sharing a data buf, no copy is performed.
18545602294fSDan Kimmel  *
18555602294fSDan Kimmel  * If the buf is marked as compressed but uncompressed data was requested, this
18565602294fSDan Kimmel  * will allocate a new data buffer for the buf, remove that flag, and fill the
18575602294fSDan Kimmel  * buf with uncompressed data. You can't request a compressed buf on a hdr with
18585602294fSDan Kimmel  * uncompressed data, and (since we haven't added support for it yet) if you
18595602294fSDan Kimmel  * want compressed data your buf must already be marked as compressed and have
18605602294fSDan Kimmel  * the correct-sized data buffer.
18615602294fSDan Kimmel  */
1862dcbf3bd6SGeorge Wilson static int
18635602294fSDan Kimmel arc_buf_fill(arc_buf_t *buf, boolean_t compressed)
1864dcbf3bd6SGeorge Wilson {
1865dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
18665602294fSDan Kimmel 	boolean_t hdr_compressed = (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
1867dcbf3bd6SGeorge Wilson 	dmu_object_byteswap_t bswap = hdr->b_l1hdr.b_byteswap;
186889c86e32SChris Williamson 
18695602294fSDan Kimmel 	ASSERT3P(buf->b_data, !=, NULL);
18705602294fSDan Kimmel 	IMPLY(compressed, hdr_compressed);
18715602294fSDan Kimmel 	IMPLY(compressed, ARC_BUF_COMPRESSED(buf));
18725602294fSDan Kimmel 
18735602294fSDan Kimmel 	if (hdr_compressed == compressed) {
18745602294fSDan Kimmel 		if (!arc_buf_is_shared(buf)) {
18755602294fSDan Kimmel 			bcopy(hdr->b_l1hdr.b_pdata, buf->b_data,
18765602294fSDan Kimmel 			    arc_buf_size(buf));
18775602294fSDan Kimmel 		}
1878dcbf3bd6SGeorge Wilson 	} else {
18795602294fSDan Kimmel 		ASSERT(hdr_compressed);
18805602294fSDan Kimmel 		ASSERT(!compressed);
1881dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, HDR_GET_PSIZE(hdr));
18825602294fSDan Kimmel 
18835602294fSDan Kimmel 		/*
18845602294fSDan Kimmel 		 * If the buf is sharing its data with the hdr, unlink it and
18855602294fSDan Kimmel 		 * allocate a new data buffer for the buf.
18865602294fSDan Kimmel 		 */
18875602294fSDan Kimmel 		if (arc_buf_is_shared(buf)) {
18885602294fSDan Kimmel 			ASSERT(ARC_BUF_COMPRESSED(buf));
18895602294fSDan Kimmel 
18905602294fSDan Kimmel 			/* We need to give the buf it's own b_data */
18915602294fSDan Kimmel 			buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
18925602294fSDan Kimmel 			buf->b_data =
18935602294fSDan Kimmel 			    arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
18945602294fSDan Kimmel 			arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
18955602294fSDan Kimmel 
18965602294fSDan Kimmel 			/* Previously overhead was 0; just add new overhead */
18975602294fSDan Kimmel 			ARCSTAT_INCR(arcstat_overhead_size, HDR_GET_LSIZE(hdr));
18985602294fSDan Kimmel 		} else if (ARC_BUF_COMPRESSED(buf)) {
18995602294fSDan Kimmel 			/* We need to reallocate the buf's b_data */
19005602294fSDan Kimmel 			arc_free_data_buf(hdr, buf->b_data, HDR_GET_PSIZE(hdr),
19015602294fSDan Kimmel 			    buf);
19025602294fSDan Kimmel 			buf->b_data =
19035602294fSDan Kimmel 			    arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
19045602294fSDan Kimmel 
19055602294fSDan Kimmel 			/* We increased the size of b_data; update overhead */
19065602294fSDan Kimmel 			ARCSTAT_INCR(arcstat_overhead_size,
19075602294fSDan Kimmel 			    HDR_GET_LSIZE(hdr) - HDR_GET_PSIZE(hdr));
19085602294fSDan Kimmel 		}
19095602294fSDan Kimmel 
19105602294fSDan Kimmel 		/*
19115602294fSDan Kimmel 		 * Regardless of the buf's previous compression settings, it
19125602294fSDan Kimmel 		 * should not be compressed at the end of this function.
19135602294fSDan Kimmel 		 */
19145602294fSDan Kimmel 		buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
19155602294fSDan Kimmel 
19165602294fSDan Kimmel 		/*
19175602294fSDan Kimmel 		 * Try copying the data from another buf which already has a
19185602294fSDan Kimmel 		 * decompressed version. If that's not possible, it's time to
19195602294fSDan Kimmel 		 * bite the bullet and decompress the data from the hdr.
19205602294fSDan Kimmel 		 */
19215602294fSDan Kimmel 		if (arc_buf_try_copy_decompressed_data(buf)) {
19225602294fSDan Kimmel 			/* Skip byteswapping and checksumming (already done) */
19235602294fSDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, !=, NULL);
19245602294fSDan Kimmel 			return (0);
19255602294fSDan Kimmel 		} else {
19265602294fSDan Kimmel 			int error = zio_decompress_data(HDR_GET_COMPRESS(hdr),
19275602294fSDan Kimmel 			    hdr->b_l1hdr.b_pdata, buf->b_data,
19285602294fSDan Kimmel 			    HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
19295602294fSDan Kimmel 
19305602294fSDan Kimmel 			/*
19315602294fSDan Kimmel 			 * Absent hardware errors or software bugs, this should
19325602294fSDan Kimmel 			 * be impossible, but log it anyway so we can debug it.
19335602294fSDan Kimmel 			 */
19345602294fSDan Kimmel 			if (error != 0) {
19355602294fSDan Kimmel 				zfs_dbgmsg(
19365602294fSDan Kimmel 				    "hdr %p, compress %d, psize %d, lsize %d",
19375602294fSDan Kimmel 				    hdr, HDR_GET_COMPRESS(hdr),
19385602294fSDan Kimmel 				    HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
19395602294fSDan Kimmel 				return (SET_ERROR(EIO));
19405602294fSDan Kimmel 			}
1941ea8dc4b6Seschrock 		}
1942fa9e4066Sahrens 	}
19435602294fSDan Kimmel 
19445602294fSDan Kimmel 	/* Byteswap the buf's data if necessary */
1945dcbf3bd6SGeorge Wilson 	if (bswap != DMU_BSWAP_NUMFUNCS) {
1946dcbf3bd6SGeorge Wilson 		ASSERT(!HDR_SHARED_DATA(hdr));
1947dcbf3bd6SGeorge Wilson 		ASSERT3U(bswap, <, DMU_BSWAP_NUMFUNCS);
1948dcbf3bd6SGeorge Wilson 		dmu_ot_byteswap[bswap].ob_func(buf->b_data, HDR_GET_LSIZE(hdr));
1949dcbf3bd6SGeorge Wilson 	}
19505602294fSDan Kimmel 
19515602294fSDan Kimmel 	/* Compute the hdr's checksum if necessary */
1952dcbf3bd6SGeorge Wilson 	arc_cksum_compute(buf);
19535602294fSDan Kimmel 
1954dcbf3bd6SGeorge Wilson 	return (0);
1955fa9e4066Sahrens }
1956fa9e4066Sahrens 
19575602294fSDan Kimmel int
19585602294fSDan Kimmel arc_decompress(arc_buf_t *buf)
19595602294fSDan Kimmel {
19605602294fSDan Kimmel 	return (arc_buf_fill(buf, B_FALSE));
19615602294fSDan Kimmel }
19625602294fSDan Kimmel 
1963dcbf3bd6SGeorge Wilson /*
1964dcbf3bd6SGeorge Wilson  * Return the size of the block, b_pdata, that is stored in the arc_buf_hdr_t.
1965dcbf3bd6SGeorge Wilson  */
1966dcbf3bd6SGeorge Wilson static uint64_t
1967dcbf3bd6SGeorge Wilson arc_hdr_size(arc_buf_hdr_t *hdr)
1968fa9e4066Sahrens {
1969dcbf3bd6SGeorge Wilson 	uint64_t size;
1970fa9e4066Sahrens 
1971dcbf3bd6SGeorge Wilson 	if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
1972dcbf3bd6SGeorge Wilson 	    HDR_GET_PSIZE(hdr) > 0) {
1973dcbf3bd6SGeorge Wilson 		size = HDR_GET_PSIZE(hdr);
1974dcbf3bd6SGeorge Wilson 	} else {
1975dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, 0);
1976dcbf3bd6SGeorge Wilson 		size = HDR_GET_LSIZE(hdr);
1977dcbf3bd6SGeorge Wilson 	}
1978dcbf3bd6SGeorge Wilson 	return (size);
1979dcbf3bd6SGeorge Wilson }
1980fa9e4066Sahrens 
1981dcbf3bd6SGeorge Wilson /*
1982dcbf3bd6SGeorge Wilson  * Increment the amount of evictable space in the arc_state_t's refcount.
1983dcbf3bd6SGeorge Wilson  * We account for the space used by the hdr and the arc buf individually
1984dcbf3bd6SGeorge Wilson  * so that we can add and remove them from the refcount individually.
1985dcbf3bd6SGeorge Wilson  */
1986dcbf3bd6SGeorge Wilson static void
1987dcbf3bd6SGeorge Wilson arc_evictable_space_increment(arc_buf_hdr_t *hdr, arc_state_t *state)
1988dcbf3bd6SGeorge Wilson {
1989dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type = arc_buf_type(hdr);
1990244781f1SPrakash Surya 
1991dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
19920e8c6158Smaybee 
1993dcbf3bd6SGeorge Wilson 	if (GHOST_STATE(state)) {
1994dcbf3bd6SGeorge Wilson 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
1995dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
1996dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
19975602294fSDan Kimmel 		(void) refcount_add_many(&state->arcs_esize[type],
19985602294fSDan Kimmel 		    HDR_GET_LSIZE(hdr), hdr);
1999dcbf3bd6SGeorge Wilson 		return;
2000dcbf3bd6SGeorge Wilson 	}
2001dcbf3bd6SGeorge Wilson 
2002dcbf3bd6SGeorge Wilson 	ASSERT(!GHOST_STATE(state));
2003dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_pdata != NULL) {
2004dcbf3bd6SGeorge Wilson 		(void) refcount_add_many(&state->arcs_esize[type],
2005dcbf3bd6SGeorge Wilson 		    arc_hdr_size(hdr), hdr);
2006dcbf3bd6SGeorge Wilson 	}
2007dcbf3bd6SGeorge Wilson 	for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2008dcbf3bd6SGeorge Wilson 	    buf = buf->b_next) {
20095602294fSDan Kimmel 		if (arc_buf_is_shared(buf))
2010dcbf3bd6SGeorge Wilson 			continue;
20115602294fSDan Kimmel 		(void) refcount_add_many(&state->arcs_esize[type],
20125602294fSDan Kimmel 		    arc_buf_size(buf), buf);
2013fa9e4066Sahrens 	}
2014fa9e4066Sahrens }
2015fa9e4066Sahrens 
2016fa9e4066Sahrens /*
2017dcbf3bd6SGeorge Wilson  * Decrement the amount of evictable space in the arc_state_t's refcount.
2018dcbf3bd6SGeorge Wilson  * We account for the space used by the hdr and the arc buf individually
2019dcbf3bd6SGeorge Wilson  * so that we can add and remove them from the refcount individually.
2020fa9e4066Sahrens  */
2021fa9e4066Sahrens static void
20225602294fSDan Kimmel arc_evictable_space_decrement(arc_buf_hdr_t *hdr, arc_state_t *state)
2023fa9e4066Sahrens {
2024dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type = arc_buf_type(hdr);
2025dcbf3bd6SGeorge Wilson 
2026dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2027dcbf3bd6SGeorge Wilson 
2028dcbf3bd6SGeorge Wilson 	if (GHOST_STATE(state)) {
2029dcbf3bd6SGeorge Wilson 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
2030dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2031dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
2032dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_esize[type],
20335602294fSDan Kimmel 		    HDR_GET_LSIZE(hdr), hdr);
2034dcbf3bd6SGeorge Wilson 		return;
2035dcbf3bd6SGeorge Wilson 	}
2036dcbf3bd6SGeorge Wilson 
2037dcbf3bd6SGeorge Wilson 	ASSERT(!GHOST_STATE(state));
2038dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_pdata != NULL) {
2039dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_esize[type],
2040dcbf3bd6SGeorge Wilson 		    arc_hdr_size(hdr), hdr);
2041dcbf3bd6SGeorge Wilson 	}
2042dcbf3bd6SGeorge Wilson 	for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2043dcbf3bd6SGeorge Wilson 	    buf = buf->b_next) {
20445602294fSDan Kimmel 		if (arc_buf_is_shared(buf))
2045dcbf3bd6SGeorge Wilson 			continue;
2046dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_esize[type],
20475602294fSDan Kimmel 		    arc_buf_size(buf), buf);
2048dcbf3bd6SGeorge Wilson 	}
2049dcbf3bd6SGeorge Wilson }
2050dcbf3bd6SGeorge Wilson 
2051dcbf3bd6SGeorge Wilson /*
2052dcbf3bd6SGeorge Wilson  * Add a reference to this hdr indicating that someone is actively
2053dcbf3bd6SGeorge Wilson  * referencing that memory. When the refcount transitions from 0 to 1,
2054dcbf3bd6SGeorge Wilson  * we remove it from the respective arc_state_t list to indicate that
2055dcbf3bd6SGeorge Wilson  * it is not evictable.
2056dcbf3bd6SGeorge Wilson  */
2057dcbf3bd6SGeorge Wilson static void
2058dcbf3bd6SGeorge Wilson add_reference(arc_buf_hdr_t *hdr, void *tag)
2059dcbf3bd6SGeorge Wilson {
2060dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2061dcbf3bd6SGeorge Wilson 	if (!MUTEX_HELD(HDR_LOCK(hdr))) {
2062dcbf3bd6SGeorge Wilson 		ASSERT(hdr->b_l1hdr.b_state == arc_anon);
2063dcbf3bd6SGeorge Wilson 		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2064dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2065dcbf3bd6SGeorge Wilson 	}
2066dcbf3bd6SGeorge Wilson 
2067dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
2068dcbf3bd6SGeorge Wilson 
2069dcbf3bd6SGeorge Wilson 	if ((refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
2070dcbf3bd6SGeorge Wilson 	    (state != arc_anon)) {
2071dcbf3bd6SGeorge Wilson 		/* We don't use the L2-only state list. */
2072dcbf3bd6SGeorge Wilson 		if (state != arc_l2c_only) {
2073*94c2d0ebSMatthew Ahrens 			multilist_remove(state->arcs_list[arc_buf_type(hdr)],
2074dcbf3bd6SGeorge Wilson 			    hdr);
20755602294fSDan Kimmel 			arc_evictable_space_decrement(hdr, state);
2076dcbf3bd6SGeorge Wilson 		}
2077dcbf3bd6SGeorge Wilson 		/* remove the prefetch flag if we get a reference */
2078dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
2079dcbf3bd6SGeorge Wilson 	}
2080dcbf3bd6SGeorge Wilson }
2081dcbf3bd6SGeorge Wilson 
2082dcbf3bd6SGeorge Wilson /*
2083dcbf3bd6SGeorge Wilson  * Remove a reference from this hdr. When the reference transitions from
2084dcbf3bd6SGeorge Wilson  * 1 to 0 and we're not anonymous, then we add this hdr to the arc_state_t's
2085dcbf3bd6SGeorge Wilson  * list making it eligible for eviction.
2086dcbf3bd6SGeorge Wilson  */
2087dcbf3bd6SGeorge Wilson static int
2088dcbf3bd6SGeorge Wilson remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
2089dcbf3bd6SGeorge Wilson {
2090dcbf3bd6SGeorge Wilson 	int cnt;
2091dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
2092dcbf3bd6SGeorge Wilson 
2093dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2094dcbf3bd6SGeorge Wilson 	ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
2095dcbf3bd6SGeorge Wilson 	ASSERT(!GHOST_STATE(state));
2096dcbf3bd6SGeorge Wilson 
2097dcbf3bd6SGeorge Wilson 	/*
2098dcbf3bd6SGeorge Wilson 	 * arc_l2c_only counts as a ghost state so we don't need to explicitly
2099dcbf3bd6SGeorge Wilson 	 * check to prevent usage of the arc_l2c_only list.
2100dcbf3bd6SGeorge Wilson 	 */
2101dcbf3bd6SGeorge Wilson 	if (((cnt = refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
2102dcbf3bd6SGeorge Wilson 	    (state != arc_anon)) {
2103*94c2d0ebSMatthew Ahrens 		multilist_insert(state->arcs_list[arc_buf_type(hdr)], hdr);
2104dcbf3bd6SGeorge Wilson 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
2105dcbf3bd6SGeorge Wilson 		arc_evictable_space_increment(hdr, state);
2106dcbf3bd6SGeorge Wilson 	}
2107dcbf3bd6SGeorge Wilson 	return (cnt);
2108dcbf3bd6SGeorge Wilson }
2109dcbf3bd6SGeorge Wilson 
2110dcbf3bd6SGeorge Wilson /*
2111dcbf3bd6SGeorge Wilson  * Move the supplied buffer to the indicated state. The hash lock
2112dcbf3bd6SGeorge Wilson  * for the buffer must be held by the caller.
2113dcbf3bd6SGeorge Wilson  */
2114dcbf3bd6SGeorge Wilson static void
2115dcbf3bd6SGeorge Wilson arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
2116dcbf3bd6SGeorge Wilson     kmutex_t *hash_lock)
2117dcbf3bd6SGeorge Wilson {
2118dcbf3bd6SGeorge Wilson 	arc_state_t *old_state;
2119dcbf3bd6SGeorge Wilson 	int64_t refcnt;
2120dcbf3bd6SGeorge Wilson 	uint32_t bufcnt;
2121dcbf3bd6SGeorge Wilson 	boolean_t update_old, update_new;
2122dcbf3bd6SGeorge Wilson 	arc_buf_contents_t buftype = arc_buf_type(hdr);
212389c86e32SChris Williamson 
212489c86e32SChris Williamson 	/*
212589c86e32SChris Williamson 	 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
212689c86e32SChris Williamson 	 * in arc_read() when bringing a buffer out of the L2ARC.  However, the
212789c86e32SChris Williamson 	 * L1 hdr doesn't always exist when we change state to arc_anon before
212889c86e32SChris Williamson 	 * destroying a header, in which case reallocating to add the L1 hdr is
212989c86e32SChris Williamson 	 * pointless.
213089c86e32SChris Williamson 	 */
213189c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr)) {
213289c86e32SChris Williamson 		old_state = hdr->b_l1hdr.b_state;
213389c86e32SChris Williamson 		refcnt = refcount_count(&hdr->b_l1hdr.b_refcnt);
2134dcbf3bd6SGeorge Wilson 		bufcnt = hdr->b_l1hdr.b_bufcnt;
2135dcbf3bd6SGeorge Wilson 		update_old = (bufcnt > 0 || hdr->b_l1hdr.b_pdata != NULL);
213689c86e32SChris Williamson 	} else {
213789c86e32SChris Williamson 		old_state = arc_l2c_only;
213889c86e32SChris Williamson 		refcnt = 0;
2139dcbf3bd6SGeorge Wilson 		bufcnt = 0;
2140dcbf3bd6SGeorge Wilson 		update_old = B_FALSE;
214189c86e32SChris Williamson 	}
2142dcbf3bd6SGeorge Wilson 	update_new = update_old;
2143fa9e4066Sahrens 
2144fa9e4066Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
214569962b56SMatthew Ahrens 	ASSERT3P(new_state, !=, old_state);
2146dcbf3bd6SGeorge Wilson 	ASSERT(!GHOST_STATE(new_state) || bufcnt == 0);
2147dcbf3bd6SGeorge Wilson 	ASSERT(old_state != arc_anon || bufcnt <= 1);
2148fa9e4066Sahrens 
2149fa9e4066Sahrens 	/*
2150fa9e4066Sahrens 	 * If this buffer is evictable, transfer it from the
2151fa9e4066Sahrens 	 * old state list to the new state list.
2152fa9e4066Sahrens 	 */
2153ea8dc4b6Seschrock 	if (refcnt == 0) {
215489c86e32SChris Williamson 		if (old_state != arc_anon && old_state != arc_l2c_only) {
215589c86e32SChris Williamson 			ASSERT(HDR_HAS_L1HDR(hdr));
2156*94c2d0ebSMatthew Ahrens 			multilist_remove(old_state->arcs_list[buftype], hdr);
2157ea8dc4b6Seschrock 
2158dcbf3bd6SGeorge Wilson 			if (GHOST_STATE(old_state)) {
2159dcbf3bd6SGeorge Wilson 				ASSERT0(bufcnt);
2160dcbf3bd6SGeorge Wilson 				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2161dcbf3bd6SGeorge Wilson 				update_old = B_TRUE;
2162ea8dc4b6Seschrock 			}
21635602294fSDan Kimmel 			arc_evictable_space_decrement(hdr, old_state);
2164fa9e4066Sahrens 		}
216589c86e32SChris Williamson 		if (new_state != arc_anon && new_state != arc_l2c_only) {
2166fa9e4066Sahrens 
216789c86e32SChris Williamson 			/*
216889c86e32SChris Williamson 			 * An L1 header always exists here, since if we're
216989c86e32SChris Williamson 			 * moving to some L1-cached state (i.e. not l2c_only or
217089c86e32SChris Williamson 			 * anonymous), we realloc the header to add an L1hdr
217189c86e32SChris Williamson 			 * beforehand.
217289c86e32SChris Williamson 			 */
217389c86e32SChris Williamson 			ASSERT(HDR_HAS_L1HDR(hdr));
2174*94c2d0ebSMatthew Ahrens 			multilist_insert(new_state->arcs_list[buftype], hdr);
2175ea8dc4b6Seschrock 
2176ea8dc4b6Seschrock 			if (GHOST_STATE(new_state)) {
2177dcbf3bd6SGeorge Wilson 				ASSERT0(bufcnt);
2178dcbf3bd6SGeorge Wilson 				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2179dcbf3bd6SGeorge Wilson 				update_new = B_TRUE;
2180ea8dc4b6Seschrock 			}
2181dcbf3bd6SGeorge Wilson 			arc_evictable_space_increment(hdr, new_state);
2182fa9e4066Sahrens 		}
2183fa9e4066Sahrens 	}
2184fa9e4066Sahrens 
2185dcbf3bd6SGeorge Wilson 	ASSERT(!HDR_EMPTY(hdr));
21867adb730bSGeorge Wilson 	if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
21877adb730bSGeorge Wilson 		buf_hash_remove(hdr);
2188fa9e4066Sahrens 
218989c86e32SChris Williamson 	/* adjust state sizes (ignore arc_l2c_only) */
21902fd872a7SPrakash Surya 
2191dcbf3bd6SGeorge Wilson 	if (update_new && new_state != arc_l2c_only) {
21922fd872a7SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(hdr));
21932fd872a7SPrakash Surya 		if (GHOST_STATE(new_state)) {
2194dcbf3bd6SGeorge Wilson 			ASSERT0(bufcnt);
21952fd872a7SPrakash Surya 
21962fd872a7SPrakash Surya 			/*
2197dcbf3bd6SGeorge Wilson 			 * When moving a header to a ghost state, we first
21982fd872a7SPrakash Surya 			 * remove all arc buffers. Thus, we'll have a
2199dcbf3bd6SGeorge Wilson 			 * bufcnt of zero, and no arc buffer to use for
22002fd872a7SPrakash Surya 			 * the reference. As a result, we use the arc
22012fd872a7SPrakash Surya 			 * header pointer for the reference.
22022fd872a7SPrakash Surya 			 */
22032fd872a7SPrakash Surya 			(void) refcount_add_many(&new_state->arcs_size,
2204dcbf3bd6SGeorge Wilson 			    HDR_GET_LSIZE(hdr), hdr);
2205dcbf3bd6SGeorge Wilson 			ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
22062fd872a7SPrakash Surya 		} else {
2207dcbf3bd6SGeorge Wilson 			uint32_t buffers = 0;
22082fd872a7SPrakash Surya 
22092fd872a7SPrakash Surya 			/*
22102fd872a7SPrakash Surya 			 * Each individual buffer holds a unique reference,
22112fd872a7SPrakash Surya 			 * thus we must remove each of these references one
22122fd872a7SPrakash Surya 			 * at a time.
22132fd872a7SPrakash Surya 			 */
22142fd872a7SPrakash Surya 			for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
22152fd872a7SPrakash Surya 			    buf = buf->b_next) {
2216dcbf3bd6SGeorge Wilson 				ASSERT3U(bufcnt, !=, 0);
2217dcbf3bd6SGeorge Wilson 				buffers++;
2218dcbf3bd6SGeorge Wilson 
2219dcbf3bd6SGeorge Wilson 				/*
2220dcbf3bd6SGeorge Wilson 				 * When the arc_buf_t is sharing the data
2221dcbf3bd6SGeorge Wilson 				 * block with the hdr, the owner of the
2222dcbf3bd6SGeorge Wilson 				 * reference belongs to the hdr. Only
2223dcbf3bd6SGeorge Wilson 				 * add to the refcount if the arc_buf_t is
2224dcbf3bd6SGeorge Wilson 				 * not shared.
2225dcbf3bd6SGeorge Wilson 				 */
22265602294fSDan Kimmel 				if (arc_buf_is_shared(buf))
2227dcbf3bd6SGeorge Wilson 					continue;
2228dcbf3bd6SGeorge Wilson 
22292fd872a7SPrakash Surya 				(void) refcount_add_many(&new_state->arcs_size,
22305602294fSDan Kimmel 				    arc_buf_size(buf), buf);
2231dcbf3bd6SGeorge Wilson 			}
2232dcbf3bd6SGeorge Wilson 			ASSERT3U(bufcnt, ==, buffers);
2233dcbf3bd6SGeorge Wilson 
2234dcbf3bd6SGeorge Wilson 			if (hdr->b_l1hdr.b_pdata != NULL) {
2235dcbf3bd6SGeorge Wilson 				(void) refcount_add_many(&new_state->arcs_size,
2236dcbf3bd6SGeorge Wilson 				    arc_hdr_size(hdr), hdr);
2237dcbf3bd6SGeorge Wilson 			} else {
2238dcbf3bd6SGeorge Wilson 				ASSERT(GHOST_STATE(old_state));
22392fd872a7SPrakash Surya 			}
22402fd872a7SPrakash Surya 		}
22412fd872a7SPrakash Surya 	}
22422fd872a7SPrakash Surya 
2243dcbf3bd6SGeorge Wilson 	if (update_old && old_state != arc_l2c_only) {
22442fd872a7SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(hdr));
22452fd872a7SPrakash Surya 		if (GHOST_STATE(old_state)) {
2246dcbf3bd6SGeorge Wilson 			ASSERT0(bufcnt);
22475602294fSDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
2248dcbf3bd6SGeorge Wilson 
22492fd872a7SPrakash Surya 			/*
22502fd872a7SPrakash Surya 			 * When moving a header off of a ghost state,
2251dcbf3bd6SGeorge Wilson 			 * the header will not contain any arc buffers.
2252dcbf3bd6SGeorge Wilson 			 * We use the arc header pointer for the reference
2253dcbf3bd6SGeorge Wilson 			 * which is exactly what we did when we put the
2254dcbf3bd6SGeorge Wilson 			 * header on the ghost state.
22552fd872a7SPrakash Surya 			 */
22562fd872a7SPrakash Surya 
22572fd872a7SPrakash Surya 			(void) refcount_remove_many(&old_state->arcs_size,
2258dcbf3bd6SGeorge Wilson 			    HDR_GET_LSIZE(hdr), hdr);
22592fd872a7SPrakash Surya 		} else {
2260dcbf3bd6SGeorge Wilson 			uint32_t buffers = 0;
22612fd872a7SPrakash Surya 
22622fd872a7SPrakash Surya 			/*
22632fd872a7SPrakash Surya 			 * Each individual buffer holds a unique reference,
22642fd872a7SPrakash Surya 			 * thus we must remove each of these references one
22652fd872a7SPrakash Surya 			 * at a time.
22662fd872a7SPrakash Surya 			 */
22672fd872a7SPrakash Surya 			for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
22682fd872a7SPrakash Surya 			    buf = buf->b_next) {
22695602294fSDan Kimmel 				ASSERT3U(bufcnt, !=, 0);
2270dcbf3bd6SGeorge Wilson 				buffers++;
2271dcbf3bd6SGeorge Wilson 
2272dcbf3bd6SGeorge Wilson 				/*
2273dcbf3bd6SGeorge Wilson 				 * When the arc_buf_t is sharing the data
2274dcbf3bd6SGeorge Wilson 				 * block with the hdr, the owner of the
2275dcbf3bd6SGeorge Wilson 				 * reference belongs to the hdr. Only
2276dcbf3bd6SGeorge Wilson 				 * add to the refcount if the arc_buf_t is
2277dcbf3bd6SGeorge Wilson 				 * not shared.
2278dcbf3bd6SGeorge Wilson 				 */
22795602294fSDan Kimmel 				if (arc_buf_is_shared(buf))
2280dcbf3bd6SGeorge Wilson 					continue;
2281dcbf3bd6SGeorge Wilson 
22822fd872a7SPrakash Surya 				(void) refcount_remove_many(
22835602294fSDan Kimmel 				    &old_state->arcs_size, arc_buf_size(buf),
2284dcbf3bd6SGeorge Wilson 				    buf);
22852fd872a7SPrakash Surya 			}
2286dcbf3bd6SGeorge Wilson 			ASSERT3U(bufcnt, ==, buffers);
2287dcbf3bd6SGeorge Wilson 			ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
2288dcbf3bd6SGeorge Wilson 			(void) refcount_remove_many(
2289dcbf3bd6SGeorge Wilson 			    &old_state->arcs_size, arc_hdr_size(hdr), hdr);
22902fd872a7SPrakash Surya 		}
2291fa9e4066Sahrens 	}
22922fd872a7SPrakash Surya 
229389c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr))
229489c86e32SChris Williamson 		hdr->b_l1hdr.b_state = new_state;
2295fa94a07fSbrendan 
229689c86e32SChris Williamson 	/*
229789c86e32SChris Williamson 	 * L2 headers should never be on the L2 state list since they don't
229889c86e32SChris Williamson 	 * have L1 headers allocated.
229989c86e32SChris Williamson 	 */
2300*94c2d0ebSMatthew Ahrens 	ASSERT(multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
2301*94c2d0ebSMatthew Ahrens 	    multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
2302fa9e4066Sahrens }
2303fa9e4066Sahrens 
23040e8c6158Smaybee void
23055a98e54bSBrendan Gregg - Sun Microsystems arc_space_consume(uint64_t space, arc_space_type_t type)
23060e8c6158Smaybee {
23075a98e54bSBrendan Gregg - Sun Microsystems 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
23085a98e54bSBrendan Gregg - Sun Microsystems 
23095a98e54bSBrendan Gregg - Sun Microsystems 	switch (type) {
23105a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_DATA:
23115a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_data_size, space);
23125a98e54bSBrendan Gregg - Sun Microsystems 		break;
23134076b1bfSPrakash Surya 	case ARC_SPACE_META:
23144076b1bfSPrakash Surya 		ARCSTAT_INCR(arcstat_metadata_size, space);
23154076b1bfSPrakash Surya 		break;
23165a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_OTHER:
23175a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_other_size, space);
23185a98e54bSBrendan Gregg - Sun Microsystems 		break;
23195a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_HDRS:
23205a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_hdr_size, space);
23215a98e54bSBrendan Gregg - Sun Microsystems 		break;
23225a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_L2HDRS:
23235a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_l2_hdr_size, space);
23245a98e54bSBrendan Gregg - Sun Microsystems 		break;
23255a98e54bSBrendan Gregg - Sun Microsystems 	}
23265a98e54bSBrendan Gregg - Sun Microsystems 
23274076b1bfSPrakash Surya 	if (type != ARC_SPACE_DATA)
23284076b1bfSPrakash Surya 		ARCSTAT_INCR(arcstat_meta_used, space);
23294076b1bfSPrakash Surya 
23300e8c6158Smaybee 	atomic_add_64(&arc_size, space);
23310e8c6158Smaybee }
23320e8c6158Smaybee 
23330e8c6158Smaybee void
23345a98e54bSBrendan Gregg - Sun Microsystems arc_space_return(uint64_t space, arc_space_type_t type)
23350e8c6158Smaybee {
23365a98e54bSBrendan Gregg - Sun Microsystems 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
23375a98e54bSBrendan Gregg - Sun Microsystems 
23385a98e54bSBrendan Gregg - Sun Microsystems 	switch (type) {
23395a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_DATA:
23405a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_data_size, -space);
23415a98e54bSBrendan Gregg - Sun Microsystems 		break;
23424076b1bfSPrakash Surya 	case ARC_SPACE_META:
23434076b1bfSPrakash Surya 		ARCSTAT_INCR(arcstat_metadata_size, -space);
23444076b1bfSPrakash Surya 		break;
23455a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_OTHER:
23465a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_other_size, -space);
23475a98e54bSBrendan Gregg - Sun Microsystems 		break;
23485a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_HDRS:
23495a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_hdr_size, -space);
23505a98e54bSBrendan Gregg - Sun Microsystems 		break;
23515a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_L2HDRS:
23525a98e54bSBrendan Gregg - Sun Microsystems 		ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
23535a98e54bSBrendan Gregg - Sun Microsystems 		break;
23545a98e54bSBrendan Gregg - Sun Microsystems 	}
23555a98e54bSBrendan Gregg - Sun Microsystems 
23564076b1bfSPrakash Surya 	if (type != ARC_SPACE_DATA) {
23574076b1bfSPrakash Surya 		ASSERT(arc_meta_used >= space);
23584076b1bfSPrakash Surya 		if (arc_meta_max < arc_meta_used)
23594076b1bfSPrakash Surya 			arc_meta_max = arc_meta_used;
23604076b1bfSPrakash Surya 		ARCSTAT_INCR(arcstat_meta_used, -space);
23614076b1bfSPrakash Surya 	}
23624076b1bfSPrakash Surya 
23630e8c6158Smaybee 	ASSERT(arc_size >= space);
23640e8c6158Smaybee 	atomic_add_64(&arc_size, -space);
23650e8c6158Smaybee }
23660e8c6158Smaybee 
2367dcbf3bd6SGeorge Wilson /*
23685602294fSDan Kimmel  * Given a hdr and a buf, returns whether that buf can share its b_data buffer
23695602294fSDan Kimmel  * with the hdr's b_pdata.
2370dcbf3bd6SGeorge Wilson  */
23715602294fSDan Kimmel static boolean_t
23725602294fSDan Kimmel arc_can_share(arc_buf_hdr_t *hdr, arc_buf_t *buf)
23735602294fSDan Kimmel {
23745602294fSDan Kimmel 	/*
23755602294fSDan Kimmel 	 * The criteria for sharing a hdr's data are:
23765602294fSDan Kimmel 	 * 1. the hdr's compression matches the buf's compression
23775602294fSDan Kimmel 	 * 2. the hdr doesn't need to be byteswapped
23785602294fSDan Kimmel 	 * 3. the hdr isn't already being shared
23795602294fSDan Kimmel 	 * 4. the buf is either compressed or it is the last buf in the hdr list
23805602294fSDan Kimmel 	 *
23815602294fSDan Kimmel 	 * Criterion #4 maintains the invariant that shared uncompressed
23825602294fSDan Kimmel 	 * bufs must be the final buf in the hdr's b_buf list. Reading this, you
23835602294fSDan Kimmel 	 * might ask, "if a compressed buf is allocated first, won't that be the
23845602294fSDan Kimmel 	 * last thing in the list?", but in that case it's impossible to create
23855602294fSDan Kimmel 	 * a shared uncompressed buf anyway (because the hdr must be compressed
23865602294fSDan Kimmel 	 * to have the compressed buf). You might also think that #3 is
23875602294fSDan Kimmel 	 * sufficient to make this guarantee, however it's possible
23885602294fSDan Kimmel 	 * (specifically in the rare L2ARC write race mentioned in
23895602294fSDan Kimmel 	 * arc_buf_alloc_impl()) there will be an existing uncompressed buf that
23905602294fSDan Kimmel 	 * is sharable, but wasn't at the time of its allocation. Rather than
23915602294fSDan Kimmel 	 * allow a new shared uncompressed buf to be created and then shuffle
23925602294fSDan Kimmel 	 * the list around to make it the last element, this simply disallows
23935602294fSDan Kimmel 	 * sharing if the new buf isn't the first to be added.
23945602294fSDan Kimmel 	 */
23955602294fSDan Kimmel 	ASSERT3P(buf->b_hdr, ==, hdr);
23965602294fSDan Kimmel 	boolean_t hdr_compressed = HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF;
23975602294fSDan Kimmel 	boolean_t buf_compressed = ARC_BUF_COMPRESSED(buf) != 0;
23985602294fSDan Kimmel 	return (buf_compressed == hdr_compressed &&
23995602294fSDan Kimmel 	    hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS &&
24005602294fSDan Kimmel 	    !HDR_SHARED_DATA(hdr) &&
24015602294fSDan Kimmel 	    (ARC_BUF_LAST(buf) || ARC_BUF_COMPRESSED(buf)));
24025602294fSDan Kimmel }
24035602294fSDan Kimmel 
24045602294fSDan Kimmel /*
24055602294fSDan Kimmel  * Allocate a buf for this hdr. If you care about the data that's in the hdr,
24065602294fSDan Kimmel  * or if you want a compressed buffer, pass those flags in. Returns 0 if the
24075602294fSDan Kimmel  * copy was made successfully, or an error code otherwise.
24085602294fSDan Kimmel  */
24095602294fSDan Kimmel static int
24105602294fSDan Kimmel arc_buf_alloc_impl(arc_buf_hdr_t *hdr, void *tag, boolean_t compressed,
24115602294fSDan Kimmel     boolean_t fill, arc_buf_t **ret)
2412fa9e4066Sahrens {
2413fa9e4066Sahrens 	arc_buf_t *buf;
2414fa9e4066Sahrens 
2415dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2416dcbf3bd6SGeorge Wilson 	ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
2417dcbf3bd6SGeorge Wilson 	VERIFY(hdr->b_type == ARC_BUFC_DATA ||
2418dcbf3bd6SGeorge Wilson 	    hdr->b_type == ARC_BUFC_METADATA);
24195602294fSDan Kimmel 	ASSERT3P(ret, !=, NULL);
24205602294fSDan Kimmel 	ASSERT3P(*ret, ==, NULL);
2421dcbf3bd6SGeorge Wilson 
24225602294fSDan Kimmel 	buf = *ret = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2423fa9e4066Sahrens 	buf->b_hdr = hdr;
242444eda4d7Smaybee 	buf->b_data = NULL;
24255602294fSDan Kimmel 	buf->b_next = hdr->b_l1hdr.b_buf;
24265602294fSDan Kimmel 	buf->b_flags = 0;
242789c86e32SChris Williamson 
2428dcbf3bd6SGeorge Wilson 	add_reference(hdr, tag);
2429dcbf3bd6SGeorge Wilson 
2430dcbf3bd6SGeorge Wilson 	/*
2431dcbf3bd6SGeorge Wilson 	 * We're about to change the hdr's b_flags. We must either
2432dcbf3bd6SGeorge Wilson 	 * hold the hash_lock or be undiscoverable.
2433dcbf3bd6SGeorge Wilson 	 */
2434dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2435dcbf3bd6SGeorge Wilson 
2436dcbf3bd6SGeorge Wilson 	/*
24375602294fSDan Kimmel 	 * Only honor requests for compressed bufs if the hdr is actually
24385602294fSDan Kimmel 	 * compressed.
24395602294fSDan Kimmel 	 */
24405602294fSDan Kimmel 	if (compressed && HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF)
24415602294fSDan Kimmel 		buf->b_flags |= ARC_BUF_FLAG_COMPRESSED;
24425602294fSDan Kimmel 
24435602294fSDan Kimmel 	/*
24445602294fSDan Kimmel 	 * If the hdr's data can be shared then we share the data buffer and
24455602294fSDan Kimmel 	 * set the appropriate bit in the hdr's b_flags to indicate the hdr is
24465602294fSDan Kimmel 	 * sharing it's b_pdata with the arc_buf_t. Otherwise, we allocate a new
24475602294fSDan Kimmel 	 * buffer to store the buf's data.
24485602294fSDan Kimmel 	 *
24495602294fSDan Kimmel 	 * There is one additional restriction here because we're sharing
24505602294fSDan Kimmel 	 * hdr -> buf instead of the usual buf -> hdr: the hdr can't be actively
24515602294fSDan Kimmel 	 * involved in an L2ARC write, because if this buf is used by an
24525602294fSDan Kimmel 	 * arc_write() then the hdr's data buffer will be released when the
24535602294fSDan Kimmel 	 * write completes, even though the L2ARC write might still be using it.
2454dcbf3bd6SGeorge Wilson 	 */
24555602294fSDan Kimmel 	boolean_t can_share = arc_can_share(hdr, buf) && !HDR_L2_WRITING(hdr);
24565602294fSDan Kimmel 
24575602294fSDan Kimmel 	/* Set up b_data and sharing */
24585602294fSDan Kimmel 	if (can_share) {
2459dcbf3bd6SGeorge Wilson 		buf->b_data = hdr->b_l1hdr.b_pdata;
24605602294fSDan Kimmel 		buf->b_flags |= ARC_BUF_FLAG_SHARED;
2461dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
2462dcbf3bd6SGeorge Wilson 	} else {
24635602294fSDan Kimmel 		buf->b_data =
24645602294fSDan Kimmel 		    arc_get_data_buf(hdr, arc_buf_size(buf), buf);
24655602294fSDan Kimmel 		ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
2466dcbf3bd6SGeorge Wilson 	}
2467dcbf3bd6SGeorge Wilson 	VERIFY3P(buf->b_data, !=, NULL);
246889c86e32SChris Williamson 
246989c86e32SChris Williamson 	hdr->b_l1hdr.b_buf = buf;
2470dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_bufcnt += 1;
247189c86e32SChris Williamson 
24725602294fSDan Kimmel 	/*
24735602294fSDan Kimmel 	 * If the user wants the data from the hdr, we need to either copy or
24745602294fSDan Kimmel 	 * decompress the data.
24755602294fSDan Kimmel 	 */
24765602294fSDan Kimmel 	if (fill) {
24775602294fSDan Kimmel 		return (arc_buf_fill(buf, ARC_BUF_COMPRESSED(buf) != 0));
24785602294fSDan Kimmel 	}
2479dcbf3bd6SGeorge Wilson 
24805602294fSDan Kimmel 	return (0);
24815602294fSDan Kimmel }
2482dcbf3bd6SGeorge Wilson 
24835602294fSDan Kimmel static char *arc_onloan_tag = "onloan";
2484fa9e4066Sahrens 
24855602294fSDan Kimmel static inline void
24865602294fSDan Kimmel arc_loaned_bytes_update(int64_t delta)
24875602294fSDan Kimmel {
24885602294fSDan Kimmel 	atomic_add_64(&arc_loaned_bytes, delta);
2489dcbf3bd6SGeorge Wilson 
24905602294fSDan Kimmel 	/* assert that it did not wrap around */
24915602294fSDan Kimmel 	ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
2492fa9e4066Sahrens }
2493fa9e4066Sahrens 
24942fdbea25SAleksandr Guzovskiy /*
24952fdbea25SAleksandr Guzovskiy  * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
24962fdbea25SAleksandr Guzovskiy  * flight data by arc_tempreserve_space() until they are "returned". Loaned
24972fdbea25SAleksandr Guzovskiy  * buffers must be returned to the arc before they can be used by the DMU or
24982fdbea25SAleksandr Guzovskiy  * freed.
24992fdbea25SAleksandr Guzovskiy  */
25002fdbea25SAleksandr Guzovskiy arc_buf_t *
25015602294fSDan Kimmel arc_loan_buf(spa_t *spa, boolean_t is_metadata, int size)
25022fdbea25SAleksandr Guzovskiy {
25035602294fSDan Kimmel 	arc_buf_t *buf = arc_alloc_buf(spa, arc_onloan_tag,
25045602294fSDan Kimmel 	    is_metadata ? ARC_BUFC_METADATA : ARC_BUFC_DATA, size);
25055602294fSDan Kimmel 
25065602294fSDan Kimmel 	arc_loaned_bytes_update(size);
25075602294fSDan Kimmel 
25085602294fSDan Kimmel 	return (buf);
25095602294fSDan Kimmel }
25102fdbea25SAleksandr Guzovskiy 
25115602294fSDan Kimmel arc_buf_t *
25125602294fSDan Kimmel arc_loan_compressed_buf(spa_t *spa, uint64_t psize, uint64_t lsize,
25135602294fSDan Kimmel     enum zio_compress compression_type)
25145602294fSDan Kimmel {
25155602294fSDan Kimmel 	arc_buf_t *buf = arc_alloc_compressed_buf(spa, arc_onloan_tag,
25165602294fSDan Kimmel 	    psize, lsize, compression_type);
25175602294fSDan Kimmel 
25185602294fSDan Kimmel 	arc_loaned_bytes_update(psize);
25192fdbea25SAleksandr Guzovskiy 
25202fdbea25SAleksandr Guzovskiy 	return (buf);
25212fdbea25SAleksandr Guzovskiy }
25222fdbea25SAleksandr Guzovskiy 
25235602294fSDan Kimmel 
25242fdbea25SAleksandr Guzovskiy /*
25252fdbea25SAleksandr Guzovskiy  * Return a loaned arc buffer to the arc.
25262fdbea25SAleksandr Guzovskiy  */
25272fdbea25SAleksandr Guzovskiy void
25282fdbea25SAleksandr Guzovskiy arc_return_buf(arc_buf_t *buf, void *tag)
25292fdbea25SAleksandr Guzovskiy {
25302fdbea25SAleksandr Guzovskiy 	arc_buf_hdr_t *hdr = buf->b_hdr;
25312fdbea25SAleksandr Guzovskiy 
2532dcbf3bd6SGeorge Wilson 	ASSERT3P(buf->b_data, !=, NULL);
253389c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
253489c86e32SChris Williamson 	(void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
253589c86e32SChris Williamson 	(void) refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
25362fdbea25SAleksandr Guzovskiy 
25375602294fSDan Kimmel 	arc_loaned_bytes_update(-arc_buf_size(buf));
25382fdbea25SAleksandr Guzovskiy }
25392fdbea25SAleksandr Guzovskiy 
2540c242f9a0Schunli zhang - Sun Microsystems - Irvine United States /* Detach an arc_buf from a dbuf (tag) */
2541c242f9a0Schunli zhang - Sun Microsystems - Irvine United States void
2542c242f9a0Schunli zhang - Sun Microsystems - Irvine United States arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
2543c242f9a0Schunli zhang - Sun Microsystems - Irvine United States {
254489c86e32SChris Williamson 	arc_buf_hdr_t *hdr = buf->b_hdr;
2545c242f9a0Schunli zhang - Sun Microsystems - Irvine United States 
2546dcbf3bd6SGeorge Wilson 	ASSERT3P(buf->b_data, !=, NULL);
254789c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
254889c86e32SChris Williamson 	(void) refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
254989c86e32SChris Williamson 	(void) refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
2550c242f9a0Schunli zhang - Sun Microsystems - Irvine United States 
25515602294fSDan Kimmel 	arc_loaned_bytes_update(arc_buf_size(buf));
2552c242f9a0Schunli zhang - Sun Microsystems - Irvine United States }
2553c242f9a0Schunli zhang - Sun Microsystems - Irvine United States 
2554dcbf3bd6SGeorge Wilson static void
2555dcbf3bd6SGeorge Wilson l2arc_free_data_on_write(void *data, size_t size, arc_buf_contents_t type)
2556ea8dc4b6Seschrock {
2557dcbf3bd6SGeorge Wilson 	l2arc_data_free_t *df = kmem_alloc(sizeof (*df), KM_SLEEP);
2558ea8dc4b6Seschrock 
2559dcbf3bd6SGeorge Wilson 	df->l2df_data = data;
2560dcbf3bd6SGeorge Wilson 	df->l2df_size = size;
2561dcbf3bd6SGeorge Wilson 	df->l2df_type = type;
2562dcbf3bd6SGeorge Wilson 	mutex_enter(&l2arc_free_on_write_mtx);
2563dcbf3bd6SGeorge Wilson 	list_insert_head(l2arc_free_on_write, df);
2564dcbf3bd6SGeorge Wilson 	mutex_exit(&l2arc_free_on_write_mtx);
2565dcbf3bd6SGeorge Wilson }
2566b24ab676SJeff Bonwick 
2567dcbf3bd6SGeorge Wilson static void
2568dcbf3bd6SGeorge Wilson arc_hdr_free_on_write(arc_buf_hdr_t *hdr)
2569dcbf3bd6SGeorge Wilson {
2570dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
2571dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type = arc_buf_type(hdr);
2572dcbf3bd6SGeorge Wilson 	uint64_t size = arc_hdr_size(hdr);
2573dcbf3bd6SGeorge Wilson 
2574dcbf3bd6SGeorge Wilson 	/* protected by hash lock, if in the hash table */
2575dcbf3bd6SGeorge Wilson 	if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
2576dcbf3bd6SGeorge Wilson 		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2577dcbf3bd6SGeorge Wilson 		ASSERT(state != arc_anon && state != arc_l2c_only);
2578dcbf3bd6SGeorge Wilson 
2579dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_esize[type],
2580dcbf3bd6SGeorge Wilson 		    size, hdr);
2581dcbf3bd6SGeorge Wilson 	}
2582dcbf3bd6SGeorge Wilson 	(void) refcount_remove_many(&state->arcs_size, size, hdr);
25836de76ce2SAndriy Gapon 	if (type == ARC_BUFC_METADATA) {
25846de76ce2SAndriy Gapon 		arc_space_return(size, ARC_SPACE_META);
25856de76ce2SAndriy Gapon 	} else {
25866de76ce2SAndriy Gapon 		ASSERT(type == ARC_BUFC_DATA);
25876de76ce2SAndriy Gapon 		arc_space_return(size, ARC_SPACE_DATA);
25886de76ce2SAndriy Gapon 	}
2589dcbf3bd6SGeorge Wilson 
2590dcbf3bd6SGeorge Wilson 	l2arc_free_data_on_write(hdr->b_l1hdr.b_pdata, size, type);
2591dcbf3bd6SGeorge Wilson }
2592dcbf3bd6SGeorge Wilson 
2593dcbf3bd6SGeorge Wilson /*
2594dcbf3bd6SGeorge Wilson  * Share the arc_buf_t's data with the hdr. Whenever we are sharing the
2595dcbf3bd6SGeorge Wilson  * data buffer, we transfer the refcount ownership to the hdr and update
2596dcbf3bd6SGeorge Wilson  * the appropriate kstats.
2597dcbf3bd6SGeorge Wilson  */
2598dcbf3bd6SGeorge Wilson static void
2599dcbf3bd6SGeorge Wilson arc_share_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2600dcbf3bd6SGeorge Wilson {
2601dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
2602dcbf3bd6SGeorge Wilson 
26035602294fSDan Kimmel 	ASSERT(arc_can_share(hdr, buf));
2604dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
2605dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
26069253d63dSGeorge Wilson 
26079253d63dSGeorge Wilson 	/*
2608dcbf3bd6SGeorge Wilson 	 * Start sharing the data buffer. We transfer the
2609dcbf3bd6SGeorge Wilson 	 * refcount ownership to the hdr since it always owns
2610dcbf3bd6SGeorge Wilson 	 * the refcount whenever an arc_buf_t is shared.
26119253d63dSGeorge Wilson 	 */
2612dcbf3bd6SGeorge Wilson 	refcount_transfer_ownership(&state->arcs_size, buf, hdr);
2613dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_pdata = buf->b_data;
2614dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
26155602294fSDan Kimmel 	buf->b_flags |= ARC_BUF_FLAG_SHARED;
2616dcbf3bd6SGeorge Wilson 
2617dcbf3bd6SGeorge Wilson 	/*
2618dcbf3bd6SGeorge Wilson 	 * Since we've transferred ownership to the hdr we need
2619dcbf3bd6SGeorge Wilson 	 * to increment its compressed and uncompressed kstats and
2620dcbf3bd6SGeorge Wilson 	 * decrement the overhead size.
2621dcbf3bd6SGeorge Wilson 	 */
2622dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
2623dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
26245602294fSDan Kimmel 	ARCSTAT_INCR(arcstat_overhead_size, -arc_buf_size(buf));
2625ea8dc4b6Seschrock }
2626ea8dc4b6Seschrock 
2627dcbf3bd6SGeorge Wilson static void
2628dcbf3bd6SGeorge Wilson arc_unshare_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2629ea8dc4b6Seschrock {
2630dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
2631dcbf3bd6SGeorge Wilson 
2632dcbf3bd6SGeorge Wilson 	ASSERT(arc_buf_is_shared(buf));
2633dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
2634dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2635ea8dc4b6Seschrock 
26369b23f181Smaybee 	/*
2637dcbf3bd6SGeorge Wilson 	 * We are no longer sharing this buffer so we need
2638dcbf3bd6SGeorge Wilson 	 * to transfer its ownership to the rightful owner.
26399b23f181Smaybee 	 */
2640dcbf3bd6SGeorge Wilson 	refcount_transfer_ownership(&state->arcs_size, hdr, buf);
2641dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2642dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_pdata = NULL;
26435602294fSDan Kimmel 	buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
2644dcbf3bd6SGeorge Wilson 
2645dcbf3bd6SGeorge Wilson 	/*
2646dcbf3bd6SGeorge Wilson 	 * Since the buffer is no longer shared between
2647dcbf3bd6SGeorge Wilson 	 * the arc buf and the hdr, count it as overhead.
2648dcbf3bd6SGeorge Wilson 	 */
2649dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
2650dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
26515602294fSDan Kimmel 	ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
2652dcbf3bd6SGeorge Wilson }
2653dcbf3bd6SGeorge Wilson 
2654dcbf3bd6SGeorge Wilson /*
26555602294fSDan Kimmel  * Remove an arc_buf_t from the hdr's buf list and return the last
26565602294fSDan Kimmel  * arc_buf_t on the list. If no buffers remain on the list then return
26575602294fSDan Kimmel  * NULL.
26585602294fSDan Kimmel  */
26595602294fSDan Kimmel static arc_buf_t *
26605602294fSDan Kimmel arc_buf_remove(arc_buf_hdr_t *hdr, arc_buf_t *buf)
26615602294fSDan Kimmel {
26625602294fSDan Kimmel 	ASSERT(HDR_HAS_L1HDR(hdr));
26635602294fSDan Kimmel 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
26645602294fSDan Kimmel 
26655602294fSDan Kimmel 	arc_buf_t **bufp = &hdr->b_l1hdr.b_buf;
26665602294fSDan Kimmel 	arc_buf_t *lastbuf = NULL;
26675602294fSDan Kimmel 
26685602294fSDan Kimmel 	/*
26695602294fSDan Kimmel 	 * Remove the buf from the hdr list and locate the last
26705602294fSDan Kimmel 	 * remaining buffer on the list.
26715602294fSDan Kimmel 	 */
26725602294fSDan Kimmel 	while (*bufp != NULL) {
26735602294fSDan Kimmel 		if (*bufp == buf)
26745602294fSDan Kimmel 			*bufp = buf->b_next;
26755602294fSDan Kimmel 
26765602294fSDan Kimmel 		/*
26775602294fSDan Kimmel 		 * If we've removed a buffer in the middle of
26785602294fSDan Kimmel 		 * the list then update the lastbuf and update
26795602294fSDan Kimmel 		 * bufp.
26805602294fSDan Kimmel 		 */
26815602294fSDan Kimmel 		if (*bufp != NULL) {
26825602294fSDan Kimmel 			lastbuf = *bufp;
26835602294fSDan Kimmel 			bufp = &(*bufp)->b_next;
26845602294fSDan Kimmel 		}
26855602294fSDan Kimmel 	}
26865602294fSDan Kimmel 	buf->b_next = NULL;
26875602294fSDan Kimmel 	ASSERT3P(lastbuf, !=, buf);
26885602294fSDan Kimmel 	IMPLY(hdr->b_l1hdr.b_bufcnt > 0, lastbuf != NULL);
26895602294fSDan Kimmel 	IMPLY(hdr->b_l1hdr.b_bufcnt > 0, hdr->b_l1hdr.b_buf != NULL);
26905602294fSDan Kimmel 	IMPLY(lastbuf != NULL, ARC_BUF_LAST(lastbuf));
26915602294fSDan Kimmel 
26925602294fSDan Kimmel 	return (lastbuf);
26935602294fSDan Kimmel }
26945602294fSDan Kimmel 
26955602294fSDan Kimmel /*
26965602294fSDan Kimmel  * Free up buf->b_data and pull the arc_buf_t off of the the arc_buf_hdr_t's
26975602294fSDan Kimmel  * list and free it.
2698dcbf3bd6SGeorge Wilson  */
2699dcbf3bd6SGeorge Wilson static void
27005602294fSDan Kimmel arc_buf_destroy_impl(arc_buf_t *buf)
2701dcbf3bd6SGeorge Wilson {
2702dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
2703dcbf3bd6SGeorge Wilson 
2704dcbf3bd6SGeorge Wilson 	/*
27055602294fSDan Kimmel 	 * Free up the data associated with the buf but only if we're not
27065602294fSDan Kimmel 	 * sharing this with the hdr. If we are sharing it with the hdr, the
27075602294fSDan Kimmel 	 * hdr is responsible for doing the free.
2708dcbf3bd6SGeorge Wilson 	 */
2709dcbf3bd6SGeorge Wilson 	if (buf->b_data != NULL) {
2710dcbf3bd6SGeorge Wilson 		/*
2711dcbf3bd6SGeorge Wilson 		 * We're about to change the hdr's b_flags. We must either
2712dcbf3bd6SGeorge Wilson 		 * hold the hash_lock or be undiscoverable.
2713dcbf3bd6SGeorge Wilson 		 */
2714dcbf3bd6SGeorge Wilson 		ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2715dcbf3bd6SGeorge Wilson 
2716dcbf3bd6SGeorge Wilson 		arc_cksum_verify(buf);
2717dcbf3bd6SGeorge Wilson 		arc_buf_unwatch(buf);
2718dcbf3bd6SGeorge Wilson 
27195602294fSDan Kimmel 		if (arc_buf_is_shared(buf)) {
2720dcbf3bd6SGeorge Wilson 			arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2721dcbf3bd6SGeorge Wilson 		} else {
27225602294fSDan Kimmel 			uint64_t size = arc_buf_size(buf);
2723dcbf3bd6SGeorge Wilson 			arc_free_data_buf(hdr, buf->b_data, size, buf);
2724dcbf3bd6SGeorge Wilson 			ARCSTAT_INCR(arcstat_overhead_size, -size);
2725dcbf3bd6SGeorge Wilson 		}
2726dcbf3bd6SGeorge Wilson 		buf->b_data = NULL;
2727dcbf3bd6SGeorge Wilson 
2728dcbf3bd6SGeorge Wilson 		ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
2729dcbf3bd6SGeorge Wilson 		hdr->b_l1hdr.b_bufcnt -= 1;
2730dcbf3bd6SGeorge Wilson 	}
2731dcbf3bd6SGeorge Wilson 
27325602294fSDan Kimmel 	arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
2733dcbf3bd6SGeorge Wilson 
27345602294fSDan Kimmel 	if (ARC_BUF_SHARED(buf) && !ARC_BUF_COMPRESSED(buf)) {
2735dcbf3bd6SGeorge Wilson 		/*
27365602294fSDan Kimmel 		 * If the current arc_buf_t is sharing its data buffer with the
27375602294fSDan Kimmel 		 * hdr, then reassign the hdr's b_pdata to share it with the new
27385602294fSDan Kimmel 		 * buffer at the end of the list. The shared buffer is always
27395602294fSDan Kimmel 		 * the last one on the hdr's buffer list.
27405602294fSDan Kimmel 		 *
27415602294fSDan Kimmel 		 * There is an equivalent case for compressed bufs, but since
27425602294fSDan Kimmel 		 * they aren't guaranteed to be the last buf in the list and
27435602294fSDan Kimmel 		 * that is an exceedingly rare case, we just allow that space be
27445602294fSDan Kimmel 		 * wasted temporarily.
2745dcbf3bd6SGeorge Wilson 		 */
27465602294fSDan Kimmel 		if (lastbuf != NULL) {
27475602294fSDan Kimmel 			/* Only one buf can be shared at once */
27485602294fSDan Kimmel 			VERIFY(!arc_buf_is_shared(lastbuf));
27495602294fSDan Kimmel 			/* hdr is uncompressed so can't have compressed buf */
27505602294fSDan Kimmel 			VERIFY(!ARC_BUF_COMPRESSED(lastbuf));
2751dcbf3bd6SGeorge Wilson 
27525602294fSDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
27535602294fSDan Kimmel 			arc_hdr_free_pdata(hdr);
2754dcbf3bd6SGeorge Wilson 
27555602294fSDan Kimmel 			/*
27565602294fSDan Kimmel 			 * We must setup a new shared block between the
27575602294fSDan Kimmel 			 * last buffer and the hdr. The data would have
27585602294fSDan Kimmel 			 * been allocated by the arc buf so we need to transfer
27595602294fSDan Kimmel 			 * ownership to the hdr since it's now being shared.
27605602294fSDan Kimmel 			 */
27615602294fSDan Kimmel 			arc_share_buf(hdr, lastbuf);
27625602294fSDan Kimmel 		}
27635602294fSDan Kimmel 	} else if (HDR_SHARED_DATA(hdr)) {
2764dcbf3bd6SGeorge Wilson 		/*
27655602294fSDan Kimmel 		 * Uncompressed shared buffers are always at the end
27665602294fSDan Kimmel 		 * of the list. Compressed buffers don't have the
27675602294fSDan Kimmel 		 * same requirements. This makes it hard to
27685602294fSDan Kimmel 		 * simply assert that the lastbuf is shared so
27695602294fSDan Kimmel 		 * we rely on the hdr's compression flags to determine
27705602294fSDan Kimmel 		 * if we have a compressed, shared buffer.
2771dcbf3bd6SGeorge Wilson 		 */
27725602294fSDan Kimmel 		ASSERT3P(lastbuf, !=, NULL);
27735602294fSDan Kimmel 		ASSERT(arc_buf_is_shared(lastbuf) ||
27745602294fSDan Kimmel 		    HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
2775dcbf3bd6SGeorge Wilson 	}
2776dcbf3bd6SGeorge Wilson 
27775602294fSDan Kimmel 	/*
27785602294fSDan Kimmel 	 * Free the checksum if we're removing the last uncompressed buf from
27795602294fSDan Kimmel 	 * this hdr.
27805602294fSDan Kimmel 	 */
27815602294fSDan Kimmel 	if (!arc_hdr_has_uncompressed_buf(hdr)) {
2782dcbf3bd6SGeorge Wilson 		arc_cksum_free(hdr);
27835602294fSDan Kimmel 	}
2784dcbf3bd6SGeorge Wilson 
2785dcbf3bd6SGeorge Wilson 	/* clean up the buf */
2786dcbf3bd6SGeorge Wilson 	buf->b_hdr = NULL;
2787dcbf3bd6SGeorge Wilson 	kmem_cache_free(buf_cache, buf);
2788dcbf3bd6SGeorge Wilson }
2789dcbf3bd6SGeorge Wilson 
2790dcbf3bd6SGeorge Wilson static void
2791dcbf3bd6SGeorge Wilson arc_hdr_alloc_pdata(arc_buf_hdr_t *hdr)
2792dcbf3bd6SGeorge Wilson {
2793dcbf3bd6SGeorge Wilson 	ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
279489c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
2795dcbf3bd6SGeorge Wilson 	ASSERT(!HDR_SHARED_DATA(hdr));
2796ea8dc4b6Seschrock 
2797dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
2798dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_pdata = arc_get_data_buf(hdr, arc_hdr_size(hdr), hdr);
2799dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
2800dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
280189c86e32SChris Williamson 
2802dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
2803dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
2804ea8dc4b6Seschrock }
2805ea8dc4b6Seschrock 
2806244781f1SPrakash Surya static void
2807dcbf3bd6SGeorge Wilson arc_hdr_free_pdata(arc_buf_hdr_t *hdr)
2808244781f1SPrakash Surya {
2809dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2810dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
2811244781f1SPrakash Surya 
2812dcbf3bd6SGeorge Wilson 	/*
2813dcbf3bd6SGeorge Wilson 	 * If the hdr is currently being written to the l2arc then
2814dcbf3bd6SGeorge Wilson 	 * we defer freeing the data by adding it to the l2arc_free_on_write
2815dcbf3bd6SGeorge Wilson 	 * list. The l2arc will free the data once it's finished
2816dcbf3bd6SGeorge Wilson 	 * writing it to the l2arc device.
2817dcbf3bd6SGeorge Wilson 	 */
2818dcbf3bd6SGeorge Wilson 	if (HDR_L2_WRITING(hdr)) {
2819dcbf3bd6SGeorge Wilson 		arc_hdr_free_on_write(hdr);
2820dcbf3bd6SGeorge Wilson 		ARCSTAT_BUMP(arcstat_l2_free_on_write);
2821dcbf3bd6SGeorge Wilson 	} else {
2822dcbf3bd6SGeorge Wilson 		arc_free_data_buf(hdr, hdr->b_l1hdr.b_pdata,
2823dcbf3bd6SGeorge Wilson 		    arc_hdr_size(hdr), hdr);
2824dcbf3bd6SGeorge Wilson 	}
2825dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_pdata = NULL;
2826dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
2827dcbf3bd6SGeorge Wilson 
2828dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
2829dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
2830dcbf3bd6SGeorge Wilson }
2831dcbf3bd6SGeorge Wilson 
2832dcbf3bd6SGeorge Wilson static arc_buf_hdr_t *
2833dcbf3bd6SGeorge Wilson arc_hdr_alloc(uint64_t spa, int32_t psize, int32_t lsize,
28345602294fSDan Kimmel     enum zio_compress compression_type, arc_buf_contents_t type)
2835dcbf3bd6SGeorge Wilson {
2836dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr;
2837dcbf3bd6SGeorge Wilson 
2838dcbf3bd6SGeorge Wilson 	VERIFY(type == ARC_BUFC_DATA || type == ARC_BUFC_METADATA);
2839dcbf3bd6SGeorge Wilson 
2840dcbf3bd6SGeorge Wilson 	hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
2841dcbf3bd6SGeorge Wilson 	ASSERT(HDR_EMPTY(hdr));
2842dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
2843dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_thawed, ==, NULL);
2844dcbf3bd6SGeorge Wilson 	HDR_SET_PSIZE(hdr, psize);
2845dcbf3bd6SGeorge Wilson 	HDR_SET_LSIZE(hdr, lsize);
2846dcbf3bd6SGeorge Wilson 	hdr->b_spa = spa;
2847dcbf3bd6SGeorge Wilson 	hdr->b_type = type;
2848dcbf3bd6SGeorge Wilson 	hdr->b_flags = 0;
2849dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(hdr, arc_bufc_to_flags(type) | ARC_FLAG_HAS_L1HDR);
28505602294fSDan Kimmel 	arc_hdr_set_compress(hdr, compression_type);
2851dcbf3bd6SGeorge Wilson 
2852dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_state = arc_anon;
2853dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_arc_access = 0;
2854dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_bufcnt = 0;
2855dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_buf = NULL;
2856dcbf3bd6SGeorge Wilson 
2857dcbf3bd6SGeorge Wilson 	/*
2858dcbf3bd6SGeorge Wilson 	 * Allocate the hdr's buffer. This will contain either
2859dcbf3bd6SGeorge Wilson 	 * the compressed or uncompressed data depending on the block
2860dcbf3bd6SGeorge Wilson 	 * it references and compressed arc enablement.
2861dcbf3bd6SGeorge Wilson 	 */
2862dcbf3bd6SGeorge Wilson 	arc_hdr_alloc_pdata(hdr);
2863dcbf3bd6SGeorge Wilson 	ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2864dcbf3bd6SGeorge Wilson 
2865dcbf3bd6SGeorge Wilson 	return (hdr);
2866244781f1SPrakash Surya }
2867244781f1SPrakash Surya 
2868fa94a07fSbrendan /*
2869dcbf3bd6SGeorge Wilson  * Transition between the two allocation states for the arc_buf_hdr struct.
2870dcbf3bd6SGeorge Wilson  * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
2871dcbf3bd6SGeorge Wilson  * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
2872dcbf3bd6SGeorge Wilson  * version is used when a cache buffer is only in the L2ARC in order to reduce
2873dcbf3bd6SGeorge Wilson  * memory usage.
2874fa94a07fSbrendan  */
2875dcbf3bd6SGeorge Wilson static arc_buf_hdr_t *
2876dcbf3bd6SGeorge Wilson arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
2877fa94a07fSbrendan {
2878dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L2HDR(hdr));
2879dcbf3bd6SGeorge Wilson 
2880dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *nhdr;
2881dcbf3bd6SGeorge Wilson 	l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
2882dcbf3bd6SGeorge Wilson 
2883dcbf3bd6SGeorge Wilson 	ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
2884dcbf3bd6SGeorge Wilson 	    (old == hdr_l2only_cache && new == hdr_full_cache));
2885dcbf3bd6SGeorge Wilson 
2886dcbf3bd6SGeorge Wilson 	nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
2887dcbf3bd6SGeorge Wilson 
2888dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
2889dcbf3bd6SGeorge Wilson 	buf_hash_remove(hdr);
2890dcbf3bd6SGeorge Wilson 
2891dcbf3bd6SGeorge Wilson 	bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
2892dcbf3bd6SGeorge Wilson 
2893dcbf3bd6SGeorge Wilson 	if (new == hdr_full_cache) {
2894dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(nhdr, ARC_FLAG_HAS_L1HDR);
2895dcbf3bd6SGeorge Wilson 		/*
2896dcbf3bd6SGeorge Wilson 		 * arc_access and arc_change_state need to be aware that a
2897dcbf3bd6SGeorge Wilson 		 * header has just come out of L2ARC, so we set its state to
2898dcbf3bd6SGeorge Wilson 		 * l2c_only even though it's about to change.
2899dcbf3bd6SGeorge Wilson 		 */
2900dcbf3bd6SGeorge Wilson 		nhdr->b_l1hdr.b_state = arc_l2c_only;
2901dcbf3bd6SGeorge Wilson 
2902dcbf3bd6SGeorge Wilson 		/* Verify previous threads set to NULL before freeing */
2903dcbf3bd6SGeorge Wilson 		ASSERT3P(nhdr->b_l1hdr.b_pdata, ==, NULL);
2904dcbf3bd6SGeorge Wilson 	} else {
2905dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2906dcbf3bd6SGeorge Wilson 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
2907dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
2908dcbf3bd6SGeorge Wilson 
2909dcbf3bd6SGeorge Wilson 		/*
2910dcbf3bd6SGeorge Wilson 		 * If we've reached here, We must have been called from
2911dcbf3bd6SGeorge Wilson 		 * arc_evict_hdr(), as such we should have already been
2912dcbf3bd6SGeorge Wilson 		 * removed from any ghost list we were previously on
2913dcbf3bd6SGeorge Wilson 		 * (which protects us from racing with arc_evict_state),
2914dcbf3bd6SGeorge Wilson 		 * thus no locking is needed during this check.
2915dcbf3bd6SGeorge Wilson 		 */
2916dcbf3bd6SGeorge Wilson 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
2917cd1c8b85SMatthew Ahrens 
2918dcbf3bd6SGeorge Wilson 		/*
2919dcbf3bd6SGeorge Wilson 		 * A buffer must not be moved into the arc_l2c_only
2920dcbf3bd6SGeorge Wilson 		 * state if it's not finished being written out to the
2921dcbf3bd6SGeorge Wilson 		 * l2arc device. Otherwise, the b_l1hdr.b_pdata field
2922dcbf3bd6SGeorge Wilson 		 * might try to be accessed, even though it was removed.
2923dcbf3bd6SGeorge Wilson 		 */
2924dcbf3bd6SGeorge Wilson 		VERIFY(!HDR_L2_WRITING(hdr));
2925dcbf3bd6SGeorge Wilson 		VERIFY3P(hdr->b_l1hdr.b_pdata, ==, NULL);
2926fa94a07fSbrendan 
2927dcbf3bd6SGeorge Wilson #ifdef ZFS_DEBUG
2928dcbf3bd6SGeorge Wilson 		if (hdr->b_l1hdr.b_thawed != NULL) {
2929dcbf3bd6SGeorge Wilson 			kmem_free(hdr->b_l1hdr.b_thawed, 1);
2930dcbf3bd6SGeorge Wilson 			hdr->b_l1hdr.b_thawed = NULL;
2931dcbf3bd6SGeorge Wilson 		}
2932dcbf3bd6SGeorge Wilson #endif
2933244781f1SPrakash Surya 
2934dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(nhdr, ARC_FLAG_HAS_L1HDR);
2935dcbf3bd6SGeorge Wilson 	}
2936244781f1SPrakash Surya 	/*
2937dcbf3bd6SGeorge Wilson 	 * The header has been reallocated so we need to re-insert it into any
2938dcbf3bd6SGeorge Wilson 	 * lists it was on.
2939244781f1SPrakash Surya 	 */
2940dcbf3bd6SGeorge Wilson 	(void) buf_hash_insert(nhdr, NULL);
2941244781f1SPrakash Surya 
2942dcbf3bd6SGeorge Wilson 	ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
2943dcbf3bd6SGeorge Wilson 
2944dcbf3bd6SGeorge Wilson 	mutex_enter(&dev->l2ad_mtx);
2945244781f1SPrakash Surya 
2946244781f1SPrakash Surya 	/*
2947dcbf3bd6SGeorge Wilson 	 * We must place the realloc'ed header back into the list at
2948dcbf3bd6SGeorge Wilson 	 * the same spot. Otherwise, if it's placed earlier in the list,
2949dcbf3bd6SGeorge Wilson 	 * l2arc_write_buffers() could find it during the function's
2950dcbf3bd6SGeorge Wilson 	 * write phase, and try to write it out to the l2arc.
2951244781f1SPrakash Surya 	 */
2952dcbf3bd6SGeorge Wilson 	list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
2953dcbf3bd6SGeorge Wilson 	list_remove(&dev->l2ad_buflist, hdr);
2954dcbf3bd6SGeorge Wilson 
2955dcbf3bd6SGeorge Wilson 	mutex_exit(&dev->l2ad_mtx);
2956244781f1SPrakash Surya 
2957244781f1SPrakash Surya 	/*
2958dcbf3bd6SGeorge Wilson 	 * Since we're using the pointer address as the tag when
2959dcbf3bd6SGeorge Wilson 	 * incrementing and decrementing the l2ad_alloc refcount, we
2960dcbf3bd6SGeorge Wilson 	 * must remove the old pointer (that we're about to destroy) and
2961dcbf3bd6SGeorge Wilson 	 * add the new pointer to the refcount. Otherwise we'd remove
2962dcbf3bd6SGeorge Wilson 	 * the wrong pointer address when calling arc_hdr_destroy() later.
2963244781f1SPrakash Surya 	 */
2964244781f1SPrakash Surya 
2965dcbf3bd6SGeorge Wilson 	(void) refcount_remove_many(&dev->l2ad_alloc, arc_hdr_size(hdr), hdr);
2966dcbf3bd6SGeorge Wilson 	(void) refcount_add_many(&dev->l2ad_alloc, arc_hdr_size(nhdr), nhdr);
2967244781f1SPrakash Surya 
2968dcbf3bd6SGeorge Wilson 	buf_discard_identity(hdr);
2969dcbf3bd6SGeorge Wilson 	kmem_cache_free(old, hdr);
2970244781f1SPrakash Surya 
2971dcbf3bd6SGeorge Wilson 	return (nhdr);
2972244781f1SPrakash Surya }
2973244781f1SPrakash Surya 
2974bbfa8ea8SMatthew Ahrens /*
2975dcbf3bd6SGeorge Wilson  * Allocate a new arc_buf_hdr_t and arc_buf_t and return the buf to the caller.
2976dcbf3bd6SGeorge Wilson  * The buf is returned thawed since we expect the consumer to modify it.
2977bbfa8ea8SMatthew Ahrens  */
2978dcbf3bd6SGeorge Wilson arc_buf_t *
29795602294fSDan Kimmel arc_alloc_buf(spa_t *spa, void *tag, arc_buf_contents_t type, int32_t size)
2980ea8dc4b6Seschrock {
2981dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), size, size,
2982dcbf3bd6SGeorge Wilson 	    ZIO_COMPRESS_OFF, type);
2983dcbf3bd6SGeorge Wilson 	ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
29845602294fSDan Kimmel 
29855602294fSDan Kimmel 	arc_buf_t *buf = NULL;
29865602294fSDan Kimmel 	VERIFY0(arc_buf_alloc_impl(hdr, tag, B_FALSE, B_FALSE, &buf));
2987dcbf3bd6SGeorge Wilson 	arc_buf_thaw(buf);
29885602294fSDan Kimmel 
29895602294fSDan Kimmel 	return (buf);
29905602294fSDan Kimmel }
29915602294fSDan Kimmel 
29925602294fSDan Kimmel /*
29935602294fSDan Kimmel  * Allocate a compressed buf in the same manner as arc_alloc_buf. Don't use this
29945602294fSDan Kimmel  * for bufs containing metadata.
29955602294fSDan Kimmel  */
29965602294fSDan Kimmel arc_buf_t *
29975602294fSDan Kimmel arc_alloc_compressed_buf(spa_t *spa, void *tag, uint64_t psize, uint64_t lsize,
29985602294fSDan Kimmel     enum zio_compress compression_type)
29995602294fSDan Kimmel {
30005602294fSDan Kimmel 	ASSERT3U(lsize, >, 0);
30015602294fSDan Kimmel 	ASSERT3U(lsize, >=, psize);
30025602294fSDan Kimmel 	ASSERT(compression_type > ZIO_COMPRESS_OFF);
30035602294fSDan Kimmel 	ASSERT(compression_type < ZIO_COMPRESS_FUNCTIONS);
30045602294fSDan Kimmel 
30055602294fSDan Kimmel 	arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
30065602294fSDan Kimmel 	    compression_type, ARC_BUFC_DATA);
30075602294fSDan Kimmel 	ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
30085602294fSDan Kimmel 
30095602294fSDan Kimmel 	arc_buf_t *buf = NULL;
30105602294fSDan Kimmel 	VERIFY0(arc_buf_alloc_impl(hdr, tag, B_TRUE, B_FALSE, &buf));
30115602294fSDan Kimmel 	arc_buf_thaw(buf);
30125602294fSDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
30135602294fSDan Kimmel 
3014dcbf3bd6SGeorge Wilson 	return (buf);
3015ea8dc4b6Seschrock }
3016ea8dc4b6Seschrock 
3017a52fc310SPrakash Surya static void
3018a52fc310SPrakash Surya arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
3019a52fc310SPrakash Surya {
3020a52fc310SPrakash Surya 	l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
3021a52fc310SPrakash Surya 	l2arc_dev_t *dev = l2hdr->b_dev;
3022dcbf3bd6SGeorge Wilson 	uint64_t asize = arc_hdr_size(hdr);
3023a52fc310SPrakash Surya 
3024a52fc310SPrakash Surya 	ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
3025a52fc310SPrakash Surya 	ASSERT(HDR_HAS_L2HDR(hdr));
3026a52fc310SPrakash Surya 
3027a52fc310SPrakash Surya 	list_remove(&dev->l2ad_buflist, hdr);
3028a52fc310SPrakash Surya 
3029dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_l2_asize, -asize);
3030dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_l2_size, -HDR_GET_LSIZE(hdr));
3031a52fc310SPrakash Surya 
3032dcbf3bd6SGeorge Wilson 	vdev_space_update(dev->l2ad_vdev, -asize, 0, 0);
3033a52fc310SPrakash Surya 
3034dcbf3bd6SGeorge Wilson 	(void) refcount_remove_many(&dev->l2ad_alloc, asize, hdr);
3035dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
3036a52fc310SPrakash Surya }
3037a52fc310SPrakash Surya 
3038fa9e4066Sahrens static void
3039ea8dc4b6Seschrock arc_hdr_destroy(arc_buf_hdr_t *hdr)
3040fa9e4066Sahrens {
304189c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr)) {
304289c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_buf == NULL ||
3043dcbf3bd6SGeorge Wilson 		    hdr->b_l1hdr.b_bufcnt > 0);
304489c86e32SChris Williamson 		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
304589c86e32SChris Williamson 		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
304689c86e32SChris Williamson 	}
3047ea8dc4b6Seschrock 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
304889c86e32SChris Williamson 	ASSERT(!HDR_IN_HASH_TABLE(hdr));
304989c86e32SChris Williamson 
3050dcbf3bd6SGeorge Wilson 	if (!HDR_EMPTY(hdr))
3051dcbf3bd6SGeorge Wilson 		buf_discard_identity(hdr);
3052dcbf3bd6SGeorge Wilson 
305389c86e32SChris Williamson 	if (HDR_HAS_L2HDR(hdr)) {
3054a52fc310SPrakash Surya 		l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3055a52fc310SPrakash Surya 		boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
3056b24ab676SJeff Bonwick 
3057a52fc310SPrakash Surya 		if (!buflist_held)
3058a52fc310SPrakash Surya 			mutex_enter(&dev->l2ad_mtx);
305989c86e32SChris Williamson 
3060244781f1SPrakash Surya 		/*
3061a52fc310SPrakash Surya 		 * Even though we checked this conditional above, we
3062a52fc310SPrakash Surya 		 * need to check this again now that we have the
3063a52fc310SPrakash Surya 		 * l2ad_mtx. This is because we could be racing with
3064a52fc310SPrakash Surya 		 * another thread calling l2arc_evict() which might have
3065a52fc310SPrakash Surya 		 * destroyed this header's L2 portion as we were waiting
3066a52fc310SPrakash Surya 		 * to acquire the l2ad_mtx. If that happens, we don't
3067a52fc310SPrakash Surya 		 * want to re-destroy the header's L2 portion.
3068244781f1SPrakash Surya 		 */
3069a52fc310SPrakash Surya 		if (HDR_HAS_L2HDR(hdr))
3070a52fc310SPrakash Surya 			arc_hdr_l2hdr_destroy(hdr);
3071b24ab676SJeff Bonwick 
3072b24ab676SJeff Bonwick 		if (!buflist_held)
3073a52fc310SPrakash Surya 			mutex_exit(&dev->l2ad_mtx);
3074fa94a07fSbrendan 	}
3075fa94a07fSbrendan 
3076dcbf3bd6SGeorge Wilson 	if (HDR_HAS_L1HDR(hdr)) {
3077dcbf3bd6SGeorge Wilson 		arc_cksum_free(hdr);
307889c86e32SChris Williamson 
3079dcbf3bd6SGeorge Wilson 		while (hdr->b_l1hdr.b_buf != NULL)
30805602294fSDan Kimmel 			arc_buf_destroy_impl(hdr->b_l1hdr.b_buf);
308189c86e32SChris Williamson 
308289c86e32SChris Williamson #ifdef ZFS_DEBUG
308389c86e32SChris Williamson 		if (hdr->b_l1hdr.b_thawed != NULL) {
308489c86e32SChris Williamson 			kmem_free(hdr->b_l1hdr.b_thawed, 1);
308589c86e32SChris Williamson 			hdr->b_l1hdr.b_thawed = NULL;
308689c86e32SChris Williamson 		}
308789c86e32SChris Williamson #endif
3088dcbf3bd6SGeorge Wilson 
3089dcbf3bd6SGeorge Wilson 		if (hdr->b_l1hdr.b_pdata != NULL) {
3090dcbf3bd6SGeorge Wilson 			arc_hdr_free_pdata(hdr);
3091dcbf3bd6SGeorge Wilson 		}
30923f9d6ad7SLin Ling 	}
3093ea8dc4b6Seschrock 
3094fa9e4066Sahrens 	ASSERT3P(hdr->b_hash_next, ==, NULL);
309589c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr)) {
3096244781f1SPrakash Surya 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
309789c86e32SChris Williamson 		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
309889c86e32SChris Williamson 		kmem_cache_free(hdr_full_cache, hdr);
309989c86e32SChris Williamson 	} else {
310089c86e32SChris Williamson 		kmem_cache_free(hdr_l2only_cache, hdr);
310189c86e32SChris Williamson 	}
3102fa9e4066Sahrens }
3103fa9e4066Sahrens 
3104fa9e4066Sahrens void
3105dcbf3bd6SGeorge Wilson arc_buf_destroy(arc_buf_t *buf, void* tag)
3106ea8dc4b6Seschrock {
3107ea8dc4b6Seschrock 	arc_buf_hdr_t *hdr = buf->b_hdr;
3108ea8dc4b6Seschrock 	kmutex_t *hash_lock = HDR_LOCK(hdr);
3109fa9e4066Sahrens 
311089c86e32SChris Williamson 	if (hdr->b_l1hdr.b_state == arc_anon) {
3111dcbf3bd6SGeorge Wilson 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
3112dcbf3bd6SGeorge Wilson 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3113dcbf3bd6SGeorge Wilson 		VERIFY0(remove_reference(hdr, NULL, tag));
3114dcbf3bd6SGeorge Wilson 		arc_hdr_destroy(hdr);
3115dcbf3bd6SGeorge Wilson 		return;
3116ea8dc4b6Seschrock 	}
3117ea8dc4b6Seschrock 
3118ea8dc4b6Seschrock 	mutex_enter(hash_lock);
3119dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr, ==, buf->b_hdr);
3120dcbf3bd6SGeorge Wilson 	ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
31213f9d6ad7SLin Ling 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3122dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_state, !=, arc_anon);
3123dcbf3bd6SGeorge Wilson 	ASSERT3P(buf->b_data, !=, NULL);
3124ea8dc4b6Seschrock 
3125ea8dc4b6Seschrock 	(void) remove_reference(hdr, hash_lock, tag);
31265602294fSDan Kimmel 	arc_buf_destroy_impl(buf);
3127ea8dc4b6Seschrock 	mutex_exit(hash_lock);
3128fa9e4066Sahrens }
3129fa9e4066Sahrens 
3130fa9e4066Sahrens /*
3131244781f1SPrakash Surya  * Evict the arc_buf_hdr that is provided as a parameter. The resultant
3132244781f1SPrakash Surya  * state of the header is dependent on it's state prior to entering this
3133244781f1SPrakash Surya  * function. The following transitions are possible:
3134874395d5Smaybee  *
3135244781f1SPrakash Surya  *    - arc_mru -> arc_mru_ghost
3136244781f1SPrakash Surya  *    - arc_mfu -> arc_mfu_ghost
3137244781f1SPrakash Surya  *    - arc_mru_ghost -> arc_l2c_only
3138244781f1SPrakash Surya  *    - arc_mru_ghost -> deleted
3139244781f1SPrakash Surya  *    - arc_mfu_ghost -> arc_l2c_only
3140244781f1SPrakash Surya  *    - arc_mfu_ghost -> deleted
3141fa9e4066Sahrens  */
3142244781f1SPrakash Surya static int64_t
3143244781f1SPrakash Surya arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3144fa9e4066Sahrens {
3145244781f1SPrakash Surya 	arc_state_t *evicted_state, *state;
3146244781f1SPrakash Surya 	int64_t bytes_evicted = 0;
3147fa9e4066Sahrens 
3148244781f1SPrakash Surya 	ASSERT(MUTEX_HELD(hash_lock));
3149244781f1SPrakash Surya 	ASSERT(HDR_HAS_L1HDR(hdr));
3150fa9e4066Sahrens 
3151244781f1SPrakash Surya 	state = hdr->b_l1hdr.b_state;
3152244781f1SPrakash Surya 	if (GHOST_STATE(state)) {
3153244781f1SPrakash Surya 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3154dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3155fa9e4066Sahrens 
3156244781f1SPrakash Surya 		/*
3157244781f1SPrakash Surya 		 * l2arc_write_buffers() relies on a header's L1 portion
3158dcbf3bd6SGeorge Wilson 		 * (i.e. its b_pdata field) during its write phase.
3159244781f1SPrakash Surya 		 * Thus, we cannot push a header onto the arc_l2c_only
3160244781f1SPrakash Surya 		 * state (removing it's L1 piece) until the header is
3161244781f1SPrakash Surya 		 * done being written to the l2arc.
3162244781f1SPrakash Surya 		 */
3163244781f1SPrakash Surya 		if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
3164244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_evict_l2_skip);
3165244781f1SPrakash Surya 			return (bytes_evicted);
31663a5286a1SMatthew Ahrens 		}
3167244781f1SPrakash Surya 
3168244781f1SPrakash Surya 		ARCSTAT_BUMP(arcstat_deleted);
3169dcbf3bd6SGeorge Wilson 		bytes_evicted += HDR_GET_LSIZE(hdr);
3170244781f1SPrakash Surya 
3171244781f1SPrakash Surya 		DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
3172244781f1SPrakash Surya 
3173dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
3174244781f1SPrakash Surya 		if (HDR_HAS_L2HDR(hdr)) {
3175244781f1SPrakash Surya 			/*
3176244781f1SPrakash Surya 			 * This buffer is cached on the 2nd Level ARC;
3177244781f1SPrakash Surya 			 * don't destroy the header.
3178244781f1SPrakash Surya 			 */
3179244781f1SPrakash Surya 			arc_change_state(arc_l2c_only, hdr, hash_lock);
31803a5286a1SMatthew Ahrens 			/*
3181244781f1SPrakash Surya 			 * dropping from L1+L2 cached to L2-only,
3182244781f1SPrakash Surya 			 * realloc to remove the L1 header.
31833a5286a1SMatthew Ahrens 			 */
3184244781f1SPrakash Surya 			hdr = arc_hdr_realloc(hdr, hdr_full_cache,
3185244781f1SPrakash Surya 			    hdr_l2only_cache);
3186244781f1SPrakash Surya 		} else {
3187244781f1SPrakash Surya 			arc_change_state(arc_anon, hdr, hash_lock);
3188244781f1SPrakash Surya 			arc_hdr_destroy(hdr);
31893a5286a1SMatthew Ahrens 		}
3190244781f1SPrakash Surya 		return (bytes_evicted);
31913a5286a1SMatthew Ahrens 	}
31923a5286a1SMatthew Ahrens 
3193244781f1SPrakash Surya 	ASSERT(state == arc_mru || state == arc_mfu);
3194244781f1SPrakash Surya 	evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
3195244781f1SPrakash Surya 
3196244781f1SPrakash Surya 	/* prefetch buffers have a minimum lifespan */
3197244781f1SPrakash Surya 	if (HDR_IO_IN_PROGRESS(hdr) ||
3198244781f1SPrakash Surya 	    ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
3199244781f1SPrakash Surya 	    ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
3200244781f1SPrakash Surya 	    arc_min_prefetch_lifespan)) {
3201244781f1SPrakash Surya 		ARCSTAT_BUMP(arcstat_evict_skip);
3202244781f1SPrakash Surya 		return (bytes_evicted);
3203244781f1SPrakash Surya 	}
3204244781f1SPrakash Surya 
3205244781f1SPrakash Surya 	ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
3206244781f1SPrakash Surya 	while (hdr->b_l1hdr.b_buf) {
3207244781f1SPrakash Surya 		arc_buf_t *buf = hdr->b_l1hdr.b_buf;
3208244781f1SPrakash Surya 		if (!mutex_tryenter(&buf->b_evict_lock)) {
3209244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_mutex_miss);
3210244781f1SPrakash Surya 			break;
321113506d1eSmaybee 		}
3212244781f1SPrakash Surya 		if (buf->b_data != NULL)
3213dcbf3bd6SGeorge Wilson 			bytes_evicted += HDR_GET_LSIZE(hdr);
3214dcbf3bd6SGeorge Wilson 		mutex_exit(&buf->b_evict_lock);
32155602294fSDan Kimmel 		arc_buf_destroy_impl(buf);
3216244781f1SPrakash Surya 	}
321769962b56SMatthew Ahrens 
3218244781f1SPrakash Surya 	if (HDR_HAS_L2HDR(hdr)) {
3219dcbf3bd6SGeorge Wilson 		ARCSTAT_INCR(arcstat_evict_l2_cached, HDR_GET_LSIZE(hdr));
3220244781f1SPrakash Surya 	} else {
3221dcbf3bd6SGeorge Wilson 		if (l2arc_write_eligible(hdr->b_spa, hdr)) {
3222dcbf3bd6SGeorge Wilson 			ARCSTAT_INCR(arcstat_evict_l2_eligible,
3223dcbf3bd6SGeorge Wilson 			    HDR_GET_LSIZE(hdr));
3224dcbf3bd6SGeorge Wilson 		} else {
3225dcbf3bd6SGeorge Wilson 			ARCSTAT_INCR(arcstat_evict_l2_ineligible,
3226dcbf3bd6SGeorge Wilson 			    HDR_GET_LSIZE(hdr));
3227dcbf3bd6SGeorge Wilson 		}
3228244781f1SPrakash Surya 	}
3229244781f1SPrakash Surya 
3230dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_bufcnt == 0) {
3231dcbf3bd6SGeorge Wilson 		arc_cksum_free(hdr);
3232dcbf3bd6SGeorge Wilson 
3233dcbf3bd6SGeorge Wilson 		bytes_evicted += arc_hdr_size(hdr);
3234dcbf3bd6SGeorge Wilson 
3235dcbf3bd6SGeorge Wilson 		/*
3236dcbf3bd6SGeorge Wilson 		 * If this hdr is being evicted and has a compressed
3237dcbf3bd6SGeorge Wilson 		 * buffer then we discard it here before we change states.
3238dcbf3bd6SGeorge Wilson 		 * This ensures that the accounting is updated correctly
3239dcbf3bd6SGeorge Wilson 		 * in arc_free_data_buf().
3240dcbf3bd6SGeorge Wilson 		 */
3241dcbf3bd6SGeorge Wilson 		arc_hdr_free_pdata(hdr);
3242dcbf3bd6SGeorge Wilson 
3243244781f1SPrakash Surya 		arc_change_state(evicted_state, hdr, hash_lock);
3244244781f1SPrakash Surya 		ASSERT(HDR_IN_HASH_TABLE(hdr));
3245dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
3246244781f1SPrakash Surya 		DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
3247244781f1SPrakash Surya 	}
3248244781f1SPrakash Surya 
3249244781f1SPrakash Surya 	return (bytes_evicted);
3250244781f1SPrakash Surya }
3251244781f1SPrakash Surya 
3252244781f1SPrakash Surya static uint64_t
3253244781f1SPrakash Surya arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
3254244781f1SPrakash Surya     uint64_t spa, int64_t bytes)
3255244781f1SPrakash Surya {
3256244781f1SPrakash Surya 	multilist_sublist_t *mls;
3257244781f1SPrakash Surya 	uint64_t bytes_evicted = 0;
3258244781f1SPrakash Surya 	arc_buf_hdr_t *hdr;
3259244781f1SPrakash Surya 	kmutex_t *hash_lock;
3260244781f1SPrakash Surya 	int evict_count = 0;
3261244781f1SPrakash Surya 
3262244781f1SPrakash Surya 	ASSERT3P(marker, !=, NULL);
3263244781f1SPrakash Surya 	IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3264244781f1SPrakash Surya 
3265244781f1SPrakash Surya 	mls = multilist_sublist_lock(ml, idx);
3266244781f1SPrakash Surya 
3267244781f1SPrakash Surya 	for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
3268244781f1SPrakash Surya 	    hdr = multilist_sublist_prev(mls, marker)) {
3269244781f1SPrakash Surya 		if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
3270244781f1SPrakash Surya 		    (evict_count >= zfs_arc_evict_batch_limit))
3271244781f1SPrakash Surya 			break;
327269962b56SMatthew Ahrens 
327369962b56SMatthew Ahrens 		/*
3274244781f1SPrakash Surya 		 * To keep our iteration location, move the marker
3275244781f1SPrakash Surya 		 * forward. Since we're not holding hdr's hash lock, we
3276244781f1SPrakash Surya 		 * must be very careful and not remove 'hdr' from the
3277244781f1SPrakash Surya 		 * sublist. Otherwise, other consumers might mistake the
3278244781f1SPrakash Surya 		 * 'hdr' as not being on a sublist when they call the
3279244781f1SPrakash Surya 		 * multilist_link_active() function (they all rely on
3280244781f1SPrakash Surya 		 * the hash lock protecting concurrent insertions and
3281244781f1SPrakash Surya 		 * removals). multilist_sublist_move_forward() was
3282244781f1SPrakash Surya 		 * specifically implemented to ensure this is the case
3283244781f1SPrakash Surya 		 * (only 'marker' will be removed and re-inserted).
3284244781f1SPrakash Surya 		 */
3285244781f1SPrakash Surya 		multilist_sublist_move_forward(mls, marker);
3286244781f1SPrakash Surya 
3287244781f1SPrakash Surya 		/*
3288244781f1SPrakash Surya 		 * The only case where the b_spa field should ever be
3289244781f1SPrakash Surya 		 * zero, is the marker headers inserted by
3290244781f1SPrakash Surya 		 * arc_evict_state(). It's possible for multiple threads
3291244781f1SPrakash Surya 		 * to be calling arc_evict_state() concurrently (e.g.
3292244781f1SPrakash Surya 		 * dsl_pool_close() and zio_inject_fault()), so we must
3293244781f1SPrakash Surya 		 * skip any markers we see from these other threads.
329469962b56SMatthew Ahrens 		 */
3295244781f1SPrakash Surya 		if (hdr->b_spa == 0)
3296244781f1SPrakash Surya 			continue;
3297244781f1SPrakash Surya 
3298244781f1SPrakash Surya 		/* we're only interested in evicting buffers of a certain spa */
3299244781f1SPrakash Surya 		if (spa != 0 && hdr->b_spa != spa) {
3300244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_evict_skip);
330169962b56SMatthew Ahrens 			continue;
330269962b56SMatthew Ahrens 		}
330369962b56SMatthew Ahrens 
33047adb730bSGeorge Wilson 		hash_lock = HDR_LOCK(hdr);
33055ea40c06SBrendan Gregg - Sun Microsystems 
3306244781f1SPrakash Surya 		/*
3307244781f1SPrakash Surya 		 * We aren't calling this function from any code path
3308244781f1SPrakash Surya 		 * that would already be holding a hash lock, so we're
3309244781f1SPrakash Surya 		 * asserting on this assumption to be defensive in case
3310244781f1SPrakash Surya 		 * this ever changes. Without this check, it would be
3311244781f1SPrakash Surya 		 * possible to incorrectly increment arcstat_mutex_miss
3312244781f1SPrakash Surya 		 * below (e.g. if the code changed such that we called
3313244781f1SPrakash Surya 		 * this function with a hash lock held).
3314244781f1SPrakash Surya 		 */
3315244781f1SPrakash Surya 		ASSERT(!MUTEX_HELD(hash_lock));
331644cb6abcSbmc 
3317244781f1SPrakash Surya 		if (mutex_tryenter(hash_lock)) {
3318244781f1SPrakash Surya 			uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
3319244781f1SPrakash Surya 			mutex_exit(hash_lock);
3320fa9e4066Sahrens 
3321244781f1SPrakash Surya 			bytes_evicted += evicted;
3322fa9e4066Sahrens 
3323244781f1SPrakash Surya 			/*
3324244781f1SPrakash Surya 			 * If evicted is zero, arc_evict_hdr() must have
3325244781f1SPrakash Surya 			 * decided to skip this header, don't increment
3326244781f1SPrakash Surya 			 * evict_count in this case.
3327244781f1SPrakash Surya 			 */
3328244781f1SPrakash Surya 			if (evicted != 0)
3329244781f1SPrakash Surya 				evict_count++;
333044cb6abcSbmc 
3331244781f1SPrakash Surya 			/*
3332244781f1SPrakash Surya 			 * If arc_size isn't overflowing, signal any
3333244781f1SPrakash Surya 			 * threads that might happen to be waiting.
3334244781f1SPrakash Surya 			 *
3335244781f1SPrakash Surya 			 * For each header evicted, we wake up a single
3336244781f1SPrakash Surya 			 * thread. If we used cv_broadcast, we could
3337244781f1SPrakash Surya 			 * wake up "too many" threads causing arc_size
3338244781f1SPrakash Surya 			 * to significantly overflow arc_c; since
3339244781f1SPrakash Surya 			 * arc_get_data_buf() doesn't check for overflow
3340244781f1SPrakash Surya 			 * when it's woken up (it doesn't because it's
3341244781f1SPrakash Surya 			 * possible for the ARC to be overflowing while
3342244781f1SPrakash Surya 			 * full of un-evictable buffers, and the
3343244781f1SPrakash Surya 			 * function should proceed in this case).
3344244781f1SPrakash Surya 			 *
3345244781f1SPrakash Surya 			 * If threads are left sleeping, due to not
3346244781f1SPrakash Surya 			 * using cv_broadcast, they will be woken up
3347244781f1SPrakash Surya 			 * just before arc_reclaim_thread() sleeps.
3348244781f1SPrakash Surya 			 */
3349244781f1SPrakash Surya 			mutex_enter(&arc_reclaim_lock);
3350244781f1SPrakash Surya 			if (!arc_is_overflowing())
3351244781f1SPrakash Surya 				cv_signal(&arc_reclaim_waiters_cv);
3352244781f1SPrakash Surya 			mutex_exit(&arc_reclaim_lock);
3353244781f1SPrakash Surya 		} else {
3354244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_mutex_miss);
3355244781f1SPrakash Surya 		}
3356244781f1SPrakash Surya 	}
3357f4d2e9e6Smaybee 
3358244781f1SPrakash Surya 	multilist_sublist_unlock(mls);
335944cb6abcSbmc 
3360244781f1SPrakash Surya 	return (bytes_evicted);
3361fa9e4066Sahrens }
3362fa9e4066Sahrens 
3363fa9e4066Sahrens /*
3364244781f1SPrakash Surya  * Evict buffers from the given arc state, until we've removed the
3365244781f1SPrakash Surya  * specified number of bytes. Move the removed buffers to the
3366244781f1SPrakash Surya  * appropriate evict state.
3367244781f1SPrakash Surya  *
3368244781f1SPrakash Surya  * This function makes a "best effort". It skips over any buffers
3369244781f1SPrakash Surya  * it can't get a hash_lock on, and so, may not catch all candidates.
3370244781f1SPrakash Surya  * It may also return without evicting as much space as requested.
3371244781f1SPrakash Surya  *
3372244781f1SPrakash Surya  * If bytes is specified using the special value ARC_EVICT_ALL, this
3373244781f1SPrakash Surya  * will evict all available (i.e. unlocked and evictable) buffers from
3374244781f1SPrakash Surya  * the given arc state; which is used by arc_flush().
3375fa9e4066Sahrens  */
3376244781f1SPrakash Surya static uint64_t
3377244781f1SPrakash Surya arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
3378244781f1SPrakash Surya     arc_buf_contents_t type)
3379fa9e4066Sahrens {
3380244781f1SPrakash Surya 	uint64_t total_evicted = 0;
3381*94c2d0ebSMatthew Ahrens 	multilist_t *ml = state->arcs_list[type];
3382244781f1SPrakash Surya 	int num_sublists;
3383244781f1SPrakash Surya 	arc_buf_hdr_t **markers;
3384fa9e4066Sahrens 
3385244781f1SPrakash Surya 	IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3386b802aa8cSSanjeev Bagewadi 
3387244781f1SPrakash Surya 	num_sublists = multilist_get_num_sublists(ml);
3388b802aa8cSSanjeev Bagewadi 
3389244781f1SPrakash Surya 	/*
3390244781f1SPrakash Surya 	 * If we've tried to evict from each sublist, made some
3391244781f1SPrakash Surya 	 * progress, but still have not hit the target number of bytes
3392244781f1SPrakash Surya 	 * to evict, we want to keep trying. The markers allow us to
3393244781f1SPrakash Surya 	 * pick up where we left off for each individual sublist, rather
3394244781f1SPrakash Surya 	 * than starting from the tail each time.
3395244781f1SPrakash Surya 	 */
3396244781f1SPrakash Surya 	markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
3397244781f1SPrakash Surya 	for (int i = 0; i < num_sublists; i++) {
3398244781f1SPrakash Surya 		markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
339969962b56SMatthew Ahrens 
340069962b56SMatthew Ahrens 		/*
3401244781f1SPrakash Surya 		 * A b_spa of 0 is used to indicate that this header is
3402244781f1SPrakash Surya 		 * a marker. This fact is used in arc_adjust_type() and
3403244781f1SPrakash Surya 		 * arc_evict_state_impl().
340469962b56SMatthew Ahrens 		 */
3405244781f1SPrakash Surya 		markers[i]->b_spa = 0;
3406fa94a07fSbrendan 
3407244781f1SPrakash Surya 		multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3408244781f1SPrakash Surya 		multilist_sublist_insert_tail(mls, markers[i]);
3409244781f1SPrakash Surya 		multilist_sublist_unlock(mls);
3410244781f1SPrakash Surya 	}
3411fa94a07fSbrendan 
3412244781f1SPrakash Surya 	/*
3413244781f1SPrakash Surya 	 * While we haven't hit our target number of bytes to evict, or
3414244781f1SPrakash Surya 	 * we're evicting all available buffers.
3415244781f1SPrakash Surya 	 */
3416244781f1SPrakash Surya 	while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
3417244781f1SPrakash Surya 		/*
3418244781f1SPrakash Surya 		 * Start eviction using a randomly selected sublist,
3419244781f1SPrakash Surya 		 * this is to try and evenly balance eviction across all
3420244781f1SPrakash Surya 		 * sublists. Always starting at the same sublist
3421244781f1SPrakash Surya 		 * (e.g. index 0) would cause evictions to favor certain
3422244781f1SPrakash Surya 		 * sublists over others.
3423244781f1SPrakash Surya 		 */
3424244781f1SPrakash Surya 		int sublist_idx = multilist_get_random_index(ml);
3425244781f1SPrakash Surya 		uint64_t scan_evicted = 0;
3426244781f1SPrakash Surya 
3427244781f1SPrakash Surya 		for (int i = 0; i < num_sublists; i++) {
3428244781f1SPrakash Surya 			uint64_t bytes_remaining;
3429244781f1SPrakash Surya 			uint64_t bytes_evicted;
3430244781f1SPrakash Surya 
3431244781f1SPrakash Surya 			if (bytes == ARC_EVICT_ALL)
3432244781f1SPrakash Surya 				bytes_remaining = ARC_EVICT_ALL;
3433244781f1SPrakash Surya 			else if (total_evicted < bytes)
3434244781f1SPrakash Surya 				bytes_remaining = bytes - total_evicted;
3435244781f1SPrakash Surya 			else
3436fa9e4066Sahrens 				break;
3437244781f1SPrakash Surya 
3438244781f1SPrakash Surya 			bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
3439244781f1SPrakash Surya 			    markers[sublist_idx], spa, bytes_remaining);
3440244781f1SPrakash Surya 
3441244781f1SPrakash Surya 			scan_evicted += bytes_evicted;
3442244781f1SPrakash Surya 			total_evicted += bytes_evicted;
3443244781f1SPrakash Surya 
3444244781f1SPrakash Surya 			/* we've reached the end, wrap to the beginning */
3445244781f1SPrakash Surya 			if (++sublist_idx >= num_sublists)
3446244781f1SPrakash Surya 				sublist_idx = 0;
3447244781f1SPrakash Surya 		}
3448244781f1SPrakash Surya 
3449244781f1SPrakash Surya 		/*
3450244781f1SPrakash Surya 		 * If we didn't evict anything during this scan, we have
3451244781f1SPrakash Surya 		 * no reason to believe we'll evict more during another
3452244781f1SPrakash Surya 		 * scan, so break the loop.
3453244781f1SPrakash Surya 		 */
3454244781f1SPrakash Surya 		if (scan_evicted == 0) {
3455244781f1SPrakash Surya 			/* This isn't possible, let's make that obvious */
3456244781f1SPrakash Surya 			ASSERT3S(bytes, !=, 0);
3457244781f1SPrakash Surya 
3458b802aa8cSSanjeev Bagewadi 			/*
3459244781f1SPrakash Surya 			 * When bytes is ARC_EVICT_ALL, the only way to
3460244781f1SPrakash Surya 			 * break the loop is when scan_evicted is zero.
3461244781f1SPrakash Surya 			 * In that case, we actually have evicted enough,
3462244781f1SPrakash Surya 			 * so we don't want to increment the kstat.
3463b802aa8cSSanjeev Bagewadi 			 */
3464244781f1SPrakash Surya 			if (bytes != ARC_EVICT_ALL) {
3465244781f1SPrakash Surya 				ASSERT3S(total_evicted, <, bytes);
3466244781f1SPrakash Surya 				ARCSTAT_BUMP(arcstat_evict_not_enough);
3467244781f1SPrakash Surya 			}
3468244781f1SPrakash Surya 
3469244781f1SPrakash Surya 			break;
347069962b56SMatthew Ahrens 		}
3471244781f1SPrakash Surya 	}
3472244781f1SPrakash Surya 
3473244781f1SPrakash Surya 	for (int i = 0; i < num_sublists; i++) {
3474244781f1SPrakash Surya 		multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3475244781f1SPrakash Surya 		multilist_sublist_remove(mls, markers[i]);
3476244781f1SPrakash Surya 		multilist_sublist_unlock(mls);
347769962b56SMatthew Ahrens 
3478244781f1SPrakash Surya 		kmem_cache_free(hdr_full_cache, markers[i]);
3479fa9e4066Sahrens 	}
3480244781f1SPrakash Surya 	kmem_free(markers, sizeof (*markers) * num_sublists);
3481fa9e4066Sahrens 
3482244781f1SPrakash Surya 	return (total_evicted);
3483244781f1SPrakash Surya }
3484244781f1SPrakash Surya 
3485244781f1SPrakash Surya /*
3486244781f1SPrakash Surya  * Flush all "evictable" data of the given type from the arc state
3487244781f1SPrakash Surya  * specified. This will not evict any "active" buffers (i.e. referenced).
3488244781f1SPrakash Surya  *
3489dcbf3bd6SGeorge Wilson  * When 'retry' is set to B_FALSE, the function will make a single pass
3490244781f1SPrakash Surya  * over the state and evict any buffers that it can. Since it doesn't
3491244781f1SPrakash Surya  * continually retry the eviction, it might end up leaving some buffers
3492244781f1SPrakash Surya  * in the ARC due to lock misses.
3493244781f1SPrakash Surya  *
3494dcbf3bd6SGeorge Wilson  * When 'retry' is set to B_TRUE, the function will continually retry the
3495244781f1SPrakash Surya  * eviction until *all* evictable buffers have been removed from the
3496244781f1SPrakash Surya  * state. As a result, if concurrent insertions into the state are
3497244781f1SPrakash Surya  * allowed (e.g. if the ARC isn't shutting down), this function might
3498244781f1SPrakash Surya  * wind up in an infinite loop, continually trying to evict buffers.
3499244781f1SPrakash Surya  */
3500244781f1SPrakash Surya static uint64_t
3501244781f1SPrakash Surya arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
3502244781f1SPrakash Surya     boolean_t retry)
3503244781f1SPrakash Surya {
3504244781f1SPrakash Surya 	uint64_t evicted = 0;
3505244781f1SPrakash Surya 
3506dcbf3bd6SGeorge Wilson 	while (refcount_count(&state->arcs_esize[type]) != 0) {
3507244781f1SPrakash Surya 		evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
3508244781f1SPrakash Surya 
3509244781f1SPrakash Surya 		if (!retry)
3510244781f1SPrakash Surya 			break;
35110e8c6158Smaybee 	}
35120e8c6158Smaybee 
3513244781f1SPrakash Surya 	return (evicted);
3514244781f1SPrakash Surya }
3515244781f1SPrakash Surya 
3516244781f1SPrakash Surya /*
3517244781f1SPrakash Surya  * Evict the specified number of bytes from the state specified,
3518244781f1SPrakash Surya  * restricting eviction to the spa and type given. This function
3519244781f1SPrakash Surya  * prevents us from trying to evict more from a state's list than
3520244781f1SPrakash Surya  * is "evictable", and to skip evicting altogether when passed a
3521244781f1SPrakash Surya  * negative value for "bytes". In contrast, arc_evict_state() will
3522244781f1SPrakash Surya  * evict everything it can, when passed a negative value for "bytes".
3523244781f1SPrakash Surya  */
3524244781f1SPrakash Surya static uint64_t
3525244781f1SPrakash Surya arc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
3526244781f1SPrakash Surya     arc_buf_contents_t type)
3527244781f1SPrakash Surya {
3528244781f1SPrakash Surya 	int64_t delta;
3529244781f1SPrakash Surya 
3530dcbf3bd6SGeorge Wilson 	if (bytes > 0 && refcount_count(&state->arcs_esize[type]) > 0) {
3531dcbf3bd6SGeorge Wilson 		delta = MIN(refcount_count(&state->arcs_esize[type]), bytes);
3532244781f1SPrakash Surya 		return (arc_evict_state(state, spa, delta, type));
3533fa9e4066Sahrens 	}
3534fa9e4066Sahrens 
3535244781f1SPrakash Surya 	return (0);
3536fa9e4066Sahrens }
3537fa9e4066Sahrens 
3538244781f1SPrakash Surya /*
3539244781f1SPrakash Surya  * Evict metadata buffers from the cache, such that arc_meta_used is
3540244781f1SPrakash Surya  * capped by the arc_meta_limit tunable.
3541244781f1SPrakash Surya  */
3542244781f1SPrakash Surya static uint64_t
3543244781f1SPrakash Surya arc_adjust_meta(void)
3544244781f1SPrakash Surya {
3545244781f1SPrakash Surya 	uint64_t total_evicted = 0;
3546244781f1SPrakash Surya 	int64_t target;
3547244781f1SPrakash Surya 
3548244781f1SPrakash Surya 	/*
3549244781f1SPrakash Surya 	 * If we're over the meta limit, we want to evict enough
3550244781f1SPrakash Surya 	 * metadata to get back under the meta limit. We don't want to
3551244781f1SPrakash Surya 	 * evict so much that we drop the MRU below arc_p, though. If
3552244781f1SPrakash Surya 	 * we're over the meta limit more than we're over arc_p, we
3553244781f1SPrakash Surya 	 * evict some from the MRU here, and some from the MFU below.
3554244781f1SPrakash Surya 	 */
3555244781f1SPrakash Surya 	target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
35562fd872a7SPrakash Surya 	    (int64_t)(refcount_count(&arc_anon->arcs_size) +
35572fd872a7SPrakash Surya 	    refcount_count(&arc_mru->arcs_size) - arc_p));
3558244781f1SPrakash Surya 
3559244781f1SPrakash Surya 	total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3560244781f1SPrakash Surya 
3561244781f1SPrakash Surya 	/*
3562244781f1SPrakash Surya 	 * Similar to the above, we want to evict enough bytes to get us
3563244781f1SPrakash Surya 	 * below the meta limit, but not so much as to drop us below the
35645602294fSDan Kimmel 	 * space allotted to the MFU (which is defined as arc_c - arc_p).
3565244781f1SPrakash Surya 	 */
3566244781f1SPrakash Surya 	target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
35672fd872a7SPrakash Surya 	    (int64_t)(refcount_count(&arc_mfu->arcs_size) - (arc_c - arc_p)));
3568244781f1SPrakash Surya 
3569244781f1SPrakash Surya 	total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3570244781f1SPrakash Surya 
3571244781f1SPrakash Surya 	return (total_evicted);
3572244781f1SPrakash Surya }
3573244781f1SPrakash Surya 
3574244781f1SPrakash Surya /*
3575244781f1SPrakash Surya  * Return the type of the oldest buffer in the given arc state
3576244781f1SPrakash Surya  *
3577244781f1SPrakash Surya  * This function will select a random sublist of type ARC_BUFC_DATA and
3578244781f1SPrakash Surya  * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
3579244781f1SPrakash Surya  * is compared, and the type which contains the "older" buffer will be
3580244781f1SPrakash Surya  * returned.
3581244781f1SPrakash Surya  */
3582244781f1SPrakash Surya static arc_buf_contents_t
3583244781f1SPrakash Surya arc_adjust_type(arc_state_t *state)
3584244781f1SPrakash Surya {
3585*94c2d0ebSMatthew Ahrens 	multilist_t *data_ml = state->arcs_list[ARC_BUFC_DATA];
3586*94c2d0ebSMatthew Ahrens 	multilist_t *meta_ml = state->arcs_list[ARC_BUFC_METADATA];
3587244781f1SPrakash Surya 	int data_idx = multilist_get_random_index(data_ml);
3588244781f1SPrakash Surya 	int meta_idx = multilist_get_random_index(meta_ml);
3589244781f1SPrakash Surya 	multilist_sublist_t *data_mls;
3590244781f1SPrakash Surya 	multilist_sublist_t *meta_mls;
3591244781f1SPrakash Surya 	arc_buf_contents_t type;
3592244781f1SPrakash Surya 	arc_buf_hdr_t *data_hdr;
3593244781f1SPrakash Surya 	arc_buf_hdr_t *meta_hdr;
3594244781f1SPrakash Surya 
3595244781f1SPrakash Surya 	/*
3596244781f1SPrakash Surya 	 * We keep the sublist lock until we're finished, to prevent
3597244781f1SPrakash Surya 	 * the headers from being destroyed via arc_evict_state().
3598244781f1SPrakash Surya 	 */
3599244781f1SPrakash Surya 	data_mls = multilist_sublist_lock(data_ml, data_idx);
3600244781f1SPrakash Surya 	meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
3601244781f1SPrakash Surya 
3602244781f1SPrakash Surya 	/*
3603244781f1SPrakash Surya 	 * These two loops are to ensure we skip any markers that
3604244781f1SPrakash Surya 	 * might be at the tail of the lists due to arc_evict_state().
3605244781f1SPrakash Surya 	 */
3606244781f1SPrakash Surya 
3607244781f1SPrakash Surya 	for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
3608244781f1SPrakash Surya 	    data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
3609244781f1SPrakash Surya 		if (data_hdr->b_spa != 0)
3610244781f1SPrakash Surya 			break;
3611244781f1SPrakash Surya 	}
3612244781f1SPrakash Surya 
3613244781f1SPrakash Surya 	for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
3614244781f1SPrakash Surya 	    meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
3615244781f1SPrakash Surya 		if (meta_hdr->b_spa != 0)
3616244781f1SPrakash Surya 			break;
3617244781f1SPrakash Surya 	}
3618244781f1SPrakash Surya 
3619244781f1SPrakash Surya 	if (data_hdr == NULL && meta_hdr == NULL) {
3620244781f1SPrakash Surya 		type = ARC_BUFC_DATA;
3621244781f1SPrakash Surya 	} else if (data_hdr == NULL) {
3622244781f1SPrakash Surya 		ASSERT3P(meta_hdr, !=, NULL);
3623244781f1SPrakash Surya 		type = ARC_BUFC_METADATA;
3624244781f1SPrakash Surya 	} else if (meta_hdr == NULL) {
3625244781f1SPrakash Surya 		ASSERT3P(data_hdr, !=, NULL);
3626244781f1SPrakash Surya 		type = ARC_BUFC_DATA;
3627244781f1SPrakash Surya 	} else {
3628244781f1SPrakash Surya 		ASSERT3P(data_hdr, !=, NULL);
3629244781f1SPrakash Surya 		ASSERT3P(meta_hdr, !=, NULL);
3630244781f1SPrakash Surya 
3631244781f1SPrakash Surya 		/* The headers can't be on the sublist without an L1 header */
3632244781f1SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(data_hdr));
3633244781f1SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(meta_hdr));
3634244781f1SPrakash Surya 
3635244781f1SPrakash Surya 		if (data_hdr->b_l1hdr.b_arc_access <
3636244781f1SPrakash Surya 		    meta_hdr->b_l1hdr.b_arc_access) {
3637244781f1SPrakash Surya 			type = ARC_BUFC_DATA;
3638244781f1SPrakash Surya 		} else {
3639244781f1SPrakash Surya 			type = ARC_BUFC_METADATA;
3640244781f1SPrakash Surya 		}
3641244781f1SPrakash Surya 	}
3642244781f1SPrakash Surya 
3643244781f1SPrakash Surya 	multilist_sublist_unlock(meta_mls);
3644244781f1SPrakash Surya 	multilist_sublist_unlock(data_mls);
3645244781f1SPrakash Surya 
3646244781f1SPrakash Surya 	return (type);
3647244781f1SPrakash Surya }
3648244781f1SPrakash Surya 
3649244781f1SPrakash Surya /*
3650244781f1SPrakash Surya  * Evict buffers from the cache, such that arc_size is capped by arc_c.
3651244781f1SPrakash Surya  */
3652244781f1SPrakash Surya static uint64_t
3653fa9e4066Sahrens arc_adjust(void)
3654fa9e4066Sahrens {
3655244781f1SPrakash Surya 	uint64_t total_evicted = 0;
3656244781f1SPrakash Surya 	uint64_t bytes;
3657244781f1SPrakash Surya 	int64_t target;
3658fa9e4066Sahrens 
36595a98e54bSBrendan Gregg - Sun Microsystems 	/*
3660244781f1SPrakash Surya 	 * If we're over arc_meta_limit, we want to correct that before
3661244781f1SPrakash Surya 	 * potentially evicting data buffers below.
36625a98e54bSBrendan Gregg - Sun Microsystems 	 */
3663244781f1SPrakash Surya 	total_evicted += arc_adjust_meta();
36645a98e54bSBrendan Gregg - Sun Microsystems 
3665244781f1SPrakash Surya 	/*
3666244781f1SPrakash Surya 	 * Adjust MRU size
3667244781f1SPrakash Surya 	 *
3668244781f1SPrakash Surya 	 * If we're over the target cache size, we want to evict enough
3669244781f1SPrakash Surya 	 * from the list to get back to our target size. We don't want
3670244781f1SPrakash Surya 	 * to evict too much from the MRU, such that it drops below
3671244781f1SPrakash Surya 	 * arc_p. So, if we're over our target cache size more than
3672244781f1SPrakash Surya 	 * the MRU is over arc_p, we'll evict enough to get back to
3673244781f1SPrakash Surya 	 * arc_p here, and then evict more from the MFU below.
3674244781f1SPrakash Surya 	 */
3675244781f1SPrakash Surya 	target = MIN((int64_t)(arc_size - arc_c),
36762fd872a7SPrakash Surya 	    (int64_t)(refcount_count(&arc_anon->arcs_size) +
36772fd872a7SPrakash Surya 	    refcount_count(&arc_mru->arcs_size) + arc_meta_used - arc_p));
3678fa9e4066Sahrens 
3679244781f1SPrakash Surya 	/*
3680244781f1SPrakash Surya 	 * If we're below arc_meta_min, always prefer to evict data.
3681244781f1SPrakash Surya 	 * Otherwise, try to satisfy the requested number of bytes to
3682244781f1SPrakash Surya 	 * evict from the type which contains older buffers; in an
3683244781f1SPrakash Surya 	 * effort to keep newer buffers in the cache regardless of their
3684244781f1SPrakash Surya 	 * type. If we cannot satisfy the number of bytes from this
3685244781f1SPrakash Surya 	 * type, spill over into the next type.
3686244781f1SPrakash Surya 	 */
3687244781f1SPrakash Surya 	if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
3688244781f1SPrakash Surya 	    arc_meta_used > arc_meta_min) {
3689244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3690244781f1SPrakash Surya 		total_evicted += bytes;
36910e8c6158Smaybee 
3692244781f1SPrakash Surya 		/*
3693244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
3694244781f1SPrakash Surya 		 * metadata, we try to get the rest from data.
3695244781f1SPrakash Surya 		 */
3696244781f1SPrakash Surya 		target -= bytes;
3697244781f1SPrakash Surya 
3698244781f1SPrakash Surya 		total_evicted +=
3699244781f1SPrakash Surya 		    arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3700244781f1SPrakash Surya 	} else {
3701244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3702244781f1SPrakash Surya 		total_evicted += bytes;
3703244781f1SPrakash Surya 
3704244781f1SPrakash Surya 		/*
3705244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
3706244781f1SPrakash Surya 		 * data, we try to get the rest from metadata.
3707244781f1SPrakash Surya 		 */
3708244781f1SPrakash Surya 		target -= bytes;
3709244781f1SPrakash Surya 
3710244781f1SPrakash Surya 		total_evicted +=
3711244781f1SPrakash Surya 		    arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3712fa9e4066Sahrens 	}
3713fa9e4066Sahrens 
37145a98e54bSBrendan Gregg - Sun Microsystems 	/*
37155a98e54bSBrendan Gregg - Sun Microsystems 	 * Adjust MFU size
3716244781f1SPrakash Surya 	 *
3717244781f1SPrakash Surya 	 * Now that we've tried to evict enough from the MRU to get its
3718244781f1SPrakash Surya 	 * size back to arc_p, if we're still above the target cache
3719244781f1SPrakash Surya 	 * size, we evict the rest from the MFU.
37205a98e54bSBrendan Gregg - Sun Microsystems 	 */
3721244781f1SPrakash Surya 	target = arc_size - arc_c;
3722fa9e4066Sahrens 
372331c46cf2SAlek Pinchuk 	if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
3724244781f1SPrakash Surya 	    arc_meta_used > arc_meta_min) {
3725244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3726244781f1SPrakash Surya 		total_evicted += bytes;
37275a98e54bSBrendan Gregg - Sun Microsystems 
3728244781f1SPrakash Surya 		/*
3729244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
3730244781f1SPrakash Surya 		 * metadata, we try to get the rest from data.
3731244781f1SPrakash Surya 		 */
3732244781f1SPrakash Surya 		target -= bytes;
3733244781f1SPrakash Surya 
3734244781f1SPrakash Surya 		total_evicted +=
3735244781f1SPrakash Surya 		    arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3736244781f1SPrakash Surya 	} else {
3737244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3738244781f1SPrakash Surya 		total_evicted += bytes;
3739244781f1SPrakash Surya 
3740244781f1SPrakash Surya 		/*
3741244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
3742244781f1SPrakash Surya 		 * data, we try to get the rest from data.
3743244781f1SPrakash Surya 		 */
3744244781f1SPrakash Surya 		target -= bytes;
3745fa9e4066Sahrens 
3746244781f1SPrakash Surya 		total_evicted +=
3747244781f1SPrakash Surya 		    arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
37485a98e54bSBrendan Gregg - Sun Microsystems 	}
3749fa9e4066Sahrens 
37505a98e54bSBrendan Gregg - Sun Microsystems 	/*
37515a98e54bSBrendan Gregg - Sun Microsystems 	 * Adjust ghost lists
3752244781f1SPrakash Surya 	 *
3753244781f1SPrakash Surya 	 * In addition to the above, the ARC also defines target values
3754244781f1SPrakash Surya 	 * for the ghost lists. The sum of the mru list and mru ghost
3755244781f1SPrakash Surya 	 * list should never exceed the target size of the cache, and
3756244781f1SPrakash Surya 	 * the sum of the mru list, mfu list, mru ghost list, and mfu
3757244781f1SPrakash Surya 	 * ghost list should never exceed twice the target size of the
3758244781f1SPrakash Surya 	 * cache. The following logic enforces these limits on the ghost
3759244781f1SPrakash Surya 	 * caches, and evicts from them as needed.
37605a98e54bSBrendan Gregg - Sun Microsystems 	 */
37612fd872a7SPrakash Surya 	target = refcount_count(&arc_mru->arcs_size) +
37622fd872a7SPrakash Surya 	    refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
3763fa9e4066Sahrens 
3764244781f1SPrakash Surya 	bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
3765244781f1SPrakash Surya 	total_evicted += bytes;
3766fa9e4066Sahrens 
3767244781f1SPrakash Surya 	target -= bytes;
37680e8c6158Smaybee 
3769244781f1SPrakash Surya 	total_evicted +=
3770244781f1SPrakash Surya 	    arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
37715a98e54bSBrendan Gregg - Sun Microsystems 
3772244781f1SPrakash Surya 	/*
3773244781f1SPrakash Surya 	 * We assume the sum of the mru list and mfu list is less than
3774244781f1SPrakash Surya 	 * or equal to arc_c (we enforced this above), which means we
3775244781f1SPrakash Surya 	 * can use the simpler of the two equations below:
3776244781f1SPrakash Surya 	 *
3777244781f1SPrakash Surya 	 *	mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
3778244781f1SPrakash Surya 	 *		    mru ghost + mfu ghost <= arc_c
3779244781f1SPrakash Surya 	 */
37802fd872a7SPrakash Surya 	target = refcount_count(&arc_mru_ghost->arcs_size) +
37812fd872a7SPrakash Surya 	    refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
3782244781f1SPrakash Surya 
3783244781f1SPrakash Surya 	bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
3784244781f1SPrakash Surya 	total_evicted += bytes;
3785244781f1SPrakash Surya 
3786244781f1SPrakash Surya 	target -= bytes;
3787244781f1SPrakash Surya 
3788244781f1SPrakash Surya 	total_evicted +=
3789244781f1SPrakash Surya 	    arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
3790244781f1SPrakash Surya 
3791244781f1SPrakash Surya 	return (total_evicted);
3792fa9e4066Sahrens }
3793fa9e4066Sahrens 
3794fa9e4066Sahrens void
3795244781f1SPrakash Surya arc_flush(spa_t *spa, boolean_t retry)
3796fa9e4066Sahrens {
3797ac05c741SMark Maybee 	uint64_t guid = 0;
3798ac05c741SMark Maybee 
3799244781f1SPrakash Surya 	/*
3800dcbf3bd6SGeorge Wilson 	 * If retry is B_TRUE, a spa must not be specified since we have
3801244781f1SPrakash Surya 	 * no good way to determine if all of a spa's buffers have been
3802244781f1SPrakash Surya 	 * evicted from an arc state.
3803244781f1SPrakash Surya 	 */
3804244781f1SPrakash Surya 	ASSERT(!retry || spa == 0);
3805244781f1SPrakash Surya 
380689c86e32SChris Williamson 	if (spa != NULL)
3807e9103aaeSGarrett D'Amore 		guid = spa_load_guid(spa);
3808ac05c741SMark Maybee 
3809244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
3810244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
3811244781f1SPrakash Surya 
3812244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
3813244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
3814874395d5Smaybee 
3815244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
3816244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
3817244781f1SPrakash Surya 
3818244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
3819244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
3820fa9e4066Sahrens }
3821fa9e4066Sahrens 
3822fa9e4066Sahrens void
38232ec99e3eSMatthew Ahrens arc_shrink(int64_t to_free)
3824fa9e4066Sahrens {
382544cb6abcSbmc 	if (arc_c > arc_c_min) {
3826fa9e4066Sahrens 
382744cb6abcSbmc 		if (arc_c > arc_c_min + to_free)
382844cb6abcSbmc 			atomic_add_64(&arc_c, -to_free);
382949e3519aSmaybee 		else
383044cb6abcSbmc 			arc_c = arc_c_min;
383144cb6abcSbmc 
383244cb6abcSbmc 		atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
383344cb6abcSbmc 		if (arc_c > arc_size)
383444cb6abcSbmc 			arc_c = MAX(arc_size, arc_c_min);
383544cb6abcSbmc 		if (arc_p > arc_c)
383644cb6abcSbmc 			arc_p = (arc_c >> 1);
383744cb6abcSbmc 		ASSERT(arc_c >= arc_c_min);
383844cb6abcSbmc 		ASSERT((int64_t)arc_p >= 0);
383949e3519aSmaybee 	}
3840fa9e4066Sahrens 
384144cb6abcSbmc 	if (arc_size > arc_c)
3842244781f1SPrakash Surya 		(void) arc_adjust();
3843fa9e4066Sahrens }
3844fa9e4066Sahrens 
38452ec99e3eSMatthew Ahrens typedef enum free_memory_reason_t {
38462ec99e3eSMatthew Ahrens 	FMR_UNKNOWN,
38472ec99e3eSMatthew Ahrens 	FMR_NEEDFREE,
38482ec99e3eSMatthew Ahrens 	FMR_LOTSFREE,
38492ec99e3eSMatthew Ahrens 	FMR_SWAPFS_MINFREE,
38502ec99e3eSMatthew Ahrens 	FMR_PAGES_PP_MAXIMUM,
38512ec99e3eSMatthew Ahrens 	FMR_HEAP_ARENA,
38522ec99e3eSMatthew Ahrens 	FMR_ZIO_ARENA,
38532ec99e3eSMatthew Ahrens } free_memory_reason_t;
38542ec99e3eSMatthew Ahrens 
38552ec99e3eSMatthew Ahrens int64_t last_free_memory;
38562ec99e3eSMatthew Ahrens free_memory_reason_t last_free_reason;
38572ec99e3eSMatthew Ahrens 
385894dd93aeSGeorge Wilson /*
38592ec99e3eSMatthew Ahrens  * Additional reserve of pages for pp_reserve.
386094dd93aeSGeorge Wilson  */
38612ec99e3eSMatthew Ahrens int64_t arc_pages_pp_reserve = 64;
3862fa9e4066Sahrens 
38632ec99e3eSMatthew Ahrens /*
38642ec99e3eSMatthew Ahrens  * Additional reserve of pages for swapfs.
38652ec99e3eSMatthew Ahrens  */
38662ec99e3eSMatthew Ahrens int64_t arc_swapfs_reserve = 64;
38673cff2f43Sstans 
38682ec99e3eSMatthew Ahrens /*
38692ec99e3eSMatthew Ahrens  * Return the amount of memory that can be consumed before reclaim will be
38702ec99e3eSMatthew Ahrens  * needed.  Positive if there is sufficient free memory, negative indicates
38712ec99e3eSMatthew Ahrens  * the amount of memory that needs to be freed up.
38722ec99e3eSMatthew Ahrens  */
38732ec99e3eSMatthew Ahrens static int64_t
38742ec99e3eSMatthew Ahrens arc_available_memory(void)
38752ec99e3eSMatthew Ahrens {
38762ec99e3eSMatthew Ahrens 	int64_t lowest = INT64_MAX;
38772ec99e3eSMatthew Ahrens 	int64_t n;
38782ec99e3eSMatthew Ahrens 	free_memory_reason_t r = FMR_UNKNOWN;
38793cff2f43Sstans 
38802ec99e3eSMatthew Ahrens #ifdef _KERNEL
38812ec99e3eSMatthew Ahrens 	if (needfree > 0) {
38822ec99e3eSMatthew Ahrens 		n = PAGESIZE * (-needfree);
38832ec99e3eSMatthew Ahrens 		if (n < lowest) {
38842ec99e3eSMatthew Ahrens 			lowest = n;
38852ec99e3eSMatthew Ahrens 			r = FMR_NEEDFREE;
38862ec99e3eSMatthew Ahrens 		}
38872ec99e3eSMatthew Ahrens 	}
3888fa9e4066Sahrens 
3889fa9e4066Sahrens 	/*
3890fa9e4066Sahrens 	 * check that we're out of range of the pageout scanner.  It starts to
3891fa9e4066Sahrens 	 * schedule paging if freemem is less than lotsfree and needfree.
3892fa9e4066Sahrens 	 * lotsfree is the high-water mark for pageout, and needfree is the
3893fa9e4066Sahrens 	 * number of needed free pages.  We add extra pages here to make sure
3894fa9e4066Sahrens 	 * the scanner doesn't start up while we're freeing memory.
3895fa9e4066Sahrens 	 */
38962ec99e3eSMatthew Ahrens 	n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
38972ec99e3eSMatthew Ahrens 	if (n < lowest) {
38982ec99e3eSMatthew Ahrens 		lowest = n;
38992ec99e3eSMatthew Ahrens 		r = FMR_LOTSFREE;
39002ec99e3eSMatthew Ahrens 	}
3901fa9e4066Sahrens 
3902fa9e4066Sahrens 	/*
3903fa9e4066Sahrens 	 * check to make sure that swapfs has enough space so that anon
3904fa94a07fSbrendan 	 * reservations can still succeed. anon_resvmem() checks that the
3905fa9e4066Sahrens 	 * availrmem is greater than swapfs_minfree, and the number of reserved
3906fa9e4066Sahrens 	 * swap pages.  We also add a bit of extra here just to prevent
3907fa9e4066Sahrens 	 * circumstances from getting really dire.
3908fa9e4066Sahrens 	 */
39092ec99e3eSMatthew Ahrens 	n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
39102ec99e3eSMatthew Ahrens 	    desfree - arc_swapfs_reserve);
39112ec99e3eSMatthew Ahrens 	if (n < lowest) {
39122ec99e3eSMatthew Ahrens 		lowest = n;
39132ec99e3eSMatthew Ahrens 		r = FMR_SWAPFS_MINFREE;
39142ec99e3eSMatthew Ahrens 	}
39152ec99e3eSMatthew Ahrens 
3916fa9e4066Sahrens 
3917cf746768SBryan Cantrill 	/*
3918cf746768SBryan Cantrill 	 * Check that we have enough availrmem that memory locking (e.g., via
3919cf746768SBryan Cantrill 	 * mlock(3C) or memcntl(2)) can still succeed.  (pages_pp_maximum
3920cf746768SBryan Cantrill 	 * stores the number of pages that cannot be locked; when availrmem
3921cf746768SBryan Cantrill 	 * drops below pages_pp_maximum, page locking mechanisms such as
3922cf746768SBryan Cantrill 	 * page_pp_lock() will fail.)
3923cf746768SBryan Cantrill 	 */
39242ec99e3eSMatthew Ahrens 	n = PAGESIZE * (availrmem - pages_pp_maximum -
39252ec99e3eSMatthew Ahrens 	    arc_pages_pp_reserve);
39262ec99e3eSMatthew Ahrens 	if (n < lowest) {
39272ec99e3eSMatthew Ahrens 		lowest = n;
39282ec99e3eSMatthew Ahrens 		r = FMR_PAGES_PP_MAXIMUM;
39292ec99e3eSMatthew Ahrens 	}
3930cf746768SBryan Cantrill 
39315dc8af33Smaybee #if defined(__i386)
3932fa9e4066Sahrens 	/*
3933fa9e4066Sahrens 	 * If we're on an i386 platform, it's possible that we'll exhaust the
3934fa9e4066Sahrens 	 * kernel heap space before we ever run out of available physical
3935fa9e4066Sahrens 	 * memory.  Most checks of the size of the heap_area compare against
3936fa9e4066Sahrens 	 * tune.t_minarmem, which is the minimum available real memory that we
3937fa9e4066Sahrens 	 * can have in the system.  However, this is generally fixed at 25 pages
3938fa9e4066Sahrens 	 * which is so low that it's useless.  In this comparison, we seek to
3939fa9e4066Sahrens 	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
3940fa94a07fSbrendan 	 * heap is allocated.  (Or, in the calculation, if less than 1/4th is
3941fa9e4066Sahrens 	 * free)
3942fa9e4066Sahrens 	 */
39430dd053d7SPrakash Surya 	n = (int64_t)vmem_size(heap_arena, VMEM_FREE) -
39442ec99e3eSMatthew Ahrens 	    (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2);
39452ec99e3eSMatthew Ahrens 	if (n < lowest) {
39462ec99e3eSMatthew Ahrens 		lowest = n;
39472ec99e3eSMatthew Ahrens 		r = FMR_HEAP_ARENA;
39482ec99e3eSMatthew Ahrens 	}
3949fa9e4066Sahrens #endif
3950fa9e4066Sahrens 
395194dd93aeSGeorge Wilson 	/*
395294dd93aeSGeorge Wilson 	 * If zio data pages are being allocated out of a separate heap segment,
395394dd93aeSGeorge Wilson 	 * then enforce that the size of available vmem for this arena remains
39540dd053d7SPrakash Surya 	 * above about 1/4th (1/(2^arc_zio_arena_free_shift)) free.
395594dd93aeSGeorge Wilson 	 *
39560dd053d7SPrakash Surya 	 * Note that reducing the arc_zio_arena_free_shift keeps more virtual
39570dd053d7SPrakash Surya 	 * memory (in the zio_arena) free, which can avoid memory
39580dd053d7SPrakash Surya 	 * fragmentation issues.
395994dd93aeSGeorge Wilson 	 */
39602ec99e3eSMatthew Ahrens 	if (zio_arena != NULL) {
39610dd053d7SPrakash Surya 		n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
39620dd053d7SPrakash Surya 		    (vmem_size(zio_arena, VMEM_ALLOC) >>
39630dd053d7SPrakash Surya 		    arc_zio_arena_free_shift);
39642ec99e3eSMatthew Ahrens 		if (n < lowest) {
39652ec99e3eSMatthew Ahrens 			lowest = n;
39662ec99e3eSMatthew Ahrens 			r = FMR_ZIO_ARENA;
39672ec99e3eSMatthew Ahrens 		}
39682ec99e3eSMatthew Ahrens 	}
3969fa9e4066Sahrens #else
39702ec99e3eSMatthew Ahrens 	/* Every 100 calls, free a small amount */
3971fa9e4066Sahrens 	if (spa_get_random(100) == 0)
39722ec99e3eSMatthew Ahrens 		lowest = -1024;
3973fa9e4066Sahrens #endif
39742ec99e3eSMatthew Ahrens 
39752ec99e3eSMatthew Ahrens 	last_free_memory = lowest;
39762ec99e3eSMatthew Ahrens 	last_free_reason = r;
39772ec99e3eSMatthew Ahrens 
39782ec99e3eSMatthew Ahrens 	return (lowest);
39792ec99e3eSMatthew Ahrens }
39802ec99e3eSMatthew Ahrens 
39812ec99e3eSMatthew Ahrens 
39822ec99e3eSMatthew Ahrens /*
39832ec99e3eSMatthew Ahrens  * Determine if the system is under memory pressure and is asking
3984dcbf3bd6SGeorge Wilson  * to reclaim memory. A return value of B_TRUE indicates that the system
39852ec99e3eSMatthew Ahrens  * is under memory pressure and that the arc should adjust accordingly.
39862ec99e3eSMatthew Ahrens  */
39872ec99e3eSMatthew Ahrens static boolean_t
39882ec99e3eSMatthew Ahrens arc_reclaim_needed(void)
39892ec99e3eSMatthew Ahrens {
39902ec99e3eSMatthew Ahrens 	return (arc_available_memory() < 0);
3991fa9e4066Sahrens }
3992fa9e4066Sahrens 
3993fa9e4066Sahrens static void
39942ec99e3eSMatthew Ahrens arc_kmem_reap_now(void)
3995fa9e4066Sahrens {
3996fa9e4066Sahrens 	size_t			i;
3997fa9e4066Sahrens 	kmem_cache_t		*prev_cache = NULL;
3998ad23a2dbSjohansen 	kmem_cache_t		*prev_data_cache = NULL;
3999fa9e4066Sahrens 	extern kmem_cache_t	*zio_buf_cache[];
4000ad23a2dbSjohansen 	extern kmem_cache_t	*zio_data_buf_cache[];
400183803b51SGeorge Wilson 	extern kmem_cache_t	*range_seg_cache;
4002fa9e4066Sahrens 
4003033f9833Sek #ifdef _KERNEL
40040e8c6158Smaybee 	if (arc_meta_used >= arc_meta_limit) {
40050e8c6158Smaybee 		/*
40060e8c6158Smaybee 		 * We are exceeding our meta-data cache limit.
40070e8c6158Smaybee 		 * Purge some DNLC entries to release holds on meta-data.
40080e8c6158Smaybee 		 */
40090e8c6158Smaybee 		dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
40100e8c6158Smaybee 	}
40115dc8af33Smaybee #if defined(__i386)
40125dc8af33Smaybee 	/*
40135dc8af33Smaybee 	 * Reclaim unused memory from all kmem caches.
40145dc8af33Smaybee 	 */
40155dc8af33Smaybee 	kmem_reap();
40165dc8af33Smaybee #endif
4017033f9833Sek #endif
4018033f9833Sek 
4019fa9e4066Sahrens 	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
4020fa9e4066Sahrens 		if (zio_buf_cache[i] != prev_cache) {
4021fa9e4066Sahrens 			prev_cache = zio_buf_cache[i];
4022fa9e4066Sahrens 			kmem_cache_reap_now(zio_buf_cache[i]);
4023fa9e4066Sahrens 		}
4024ad23a2dbSjohansen 		if (zio_data_buf_cache[i] != prev_data_cache) {
4025ad23a2dbSjohansen 			prev_data_cache = zio_data_buf_cache[i];
4026ad23a2dbSjohansen 			kmem_cache_reap_now(zio_data_buf_cache[i]);
4027ad23a2dbSjohansen 		}
4028fa9e4066Sahrens 	}
4029ea8dc4b6Seschrock 	kmem_cache_reap_now(buf_cache);
403089c86e32SChris Williamson 	kmem_cache_reap_now(hdr_full_cache);
403189c86e32SChris Williamson 	kmem_cache_reap_now(hdr_l2only_cache);
403283803b51SGeorge Wilson 	kmem_cache_reap_now(range_seg_cache);
403394dd93aeSGeorge Wilson 
40342ec99e3eSMatthew Ahrens 	if (zio_arena != NULL) {
40352ec99e3eSMatthew Ahrens 		/*
40362ec99e3eSMatthew Ahrens 		 * Ask the vmem arena to reclaim unused memory from its
40372ec99e3eSMatthew Ahrens 		 * quantum caches.
40382ec99e3eSMatthew Ahrens 		 */
403994dd93aeSGeorge Wilson 		vmem_qcache_reap(zio_arena);
40402ec99e3eSMatthew Ahrens 	}
4041fa9e4066Sahrens }
4042fa9e4066Sahrens 
4043244781f1SPrakash Surya /*
4044244781f1SPrakash Surya  * Threads can block in arc_get_data_buf() waiting for this thread to evict
4045244781f1SPrakash Surya  * enough data and signal them to proceed. When this happens, the threads in
4046244781f1SPrakash Surya  * arc_get_data_buf() are sleeping while holding the hash lock for their
4047244781f1SPrakash Surya  * particular arc header. Thus, we must be careful to never sleep on a
4048244781f1SPrakash Surya  * hash lock in this thread. This is to prevent the following deadlock:
4049244781f1SPrakash Surya  *
4050244781f1SPrakash Surya  *  - Thread A sleeps on CV in arc_get_data_buf() holding hash lock "L",
4051244781f1SPrakash Surya  *    waiting for the reclaim thread to signal it.
4052244781f1SPrakash Surya  *
4053244781f1SPrakash Surya  *  - arc_reclaim_thread() tries to acquire hash lock "L" using mutex_enter,
4054244781f1SPrakash Surya  *    fails, and goes to sleep forever.
4055244781f1SPrakash Surya  *
4056244781f1SPrakash Surya  * This possible deadlock is avoided by always acquiring a hash lock
4057244781f1SPrakash Surya  * using mutex_tryenter() from arc_reclaim_thread().
4058244781f1SPrakash Surya  */
4059fa9e4066Sahrens static void
4060fa9e4066Sahrens arc_reclaim_thread(void)
4061fa9e4066Sahrens {
4062a8f6344fSEli Rosenthal 	hrtime_t		growtime = 0;
4063fa9e4066Sahrens 	callb_cpr_t		cpr;
4064fa9e4066Sahrens 
4065244781f1SPrakash Surya 	CALLB_CPR_INIT(&cpr, &arc_reclaim_lock, callb_generic_cpr, FTAG);
4066fa9e4066Sahrens 
4067244781f1SPrakash Surya 	mutex_enter(&arc_reclaim_lock);
4068244781f1SPrakash Surya 	while (!arc_reclaim_thread_exit) {
4069244781f1SPrakash Surya 		uint64_t evicted = 0;
4070244781f1SPrakash Surya 
4071dcbf3bd6SGeorge Wilson 		/*
4072dcbf3bd6SGeorge Wilson 		 * This is necessary in order for the mdb ::arc dcmd to
4073dcbf3bd6SGeorge Wilson 		 * show up to date information. Since the ::arc command
4074dcbf3bd6SGeorge Wilson 		 * does not call the kstat's update function, without
4075dcbf3bd6SGeorge Wilson 		 * this call, the command may show stale stats for the
4076dcbf3bd6SGeorge Wilson 		 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
4077dcbf3bd6SGeorge Wilson 		 * with this change, the data might be up to 1 second
4078dcbf3bd6SGeorge Wilson 		 * out of date; but that should suffice. The arc_state_t
4079dcbf3bd6SGeorge Wilson 		 * structures can be queried directly if more accurate
4080dcbf3bd6SGeorge Wilson 		 * information is needed.
4081dcbf3bd6SGeorge Wilson 		 */
4082dcbf3bd6SGeorge Wilson 		if (arc_ksp != NULL)
4083dcbf3bd6SGeorge Wilson 			arc_ksp->ks_update(arc_ksp, KSTAT_READ);
4084dcbf3bd6SGeorge Wilson 
4085244781f1SPrakash Surya 		mutex_exit(&arc_reclaim_lock);
4086244781f1SPrakash Surya 
4087405a5a0fSMatthew Ahrens 		/*
4088405a5a0fSMatthew Ahrens 		 * We call arc_adjust() before (possibly) calling
4089405a5a0fSMatthew Ahrens 		 * arc_kmem_reap_now(), so that we can wake up
4090405a5a0fSMatthew Ahrens 		 * arc_get_data_buf() sooner.
4091405a5a0fSMatthew Ahrens 		 */
4092405a5a0fSMatthew Ahrens 		evicted = arc_adjust();
4093405a5a0fSMatthew Ahrens 
4094405a5a0fSMatthew Ahrens 		int64_t free_memory = arc_available_memory();
40952ec99e3eSMatthew Ahrens 		if (free_memory < 0) {
4096fa9e4066Sahrens 
40972ec99e3eSMatthew Ahrens 			arc_no_grow = B_TRUE;
40982ec99e3eSMatthew Ahrens 			arc_warm = B_TRUE;
4099fa9e4066Sahrens 
41002ec99e3eSMatthew Ahrens 			/*
41012ec99e3eSMatthew Ahrens 			 * Wait at least zfs_grow_retry (default 60) seconds
41022ec99e3eSMatthew Ahrens 			 * before considering growing.
41032ec99e3eSMatthew Ahrens 			 */
4104a8f6344fSEli Rosenthal 			growtime = gethrtime() + SEC2NSEC(arc_grow_retry);
4105fa9e4066Sahrens 
41062ec99e3eSMatthew Ahrens 			arc_kmem_reap_now();
4107fa9e4066Sahrens 
41082ec99e3eSMatthew Ahrens 			/*
41092ec99e3eSMatthew Ahrens 			 * If we are still low on memory, shrink the ARC
41102ec99e3eSMatthew Ahrens 			 * so that we have arc_shrink_min free space.
41112ec99e3eSMatthew Ahrens 			 */
41122ec99e3eSMatthew Ahrens 			free_memory = arc_available_memory();
41132ec99e3eSMatthew Ahrens 
41142ec99e3eSMatthew Ahrens 			int64_t to_free =
41152ec99e3eSMatthew Ahrens 			    (arc_c >> arc_shrink_shift) - free_memory;
41162ec99e3eSMatthew Ahrens 			if (to_free > 0) {
41172ec99e3eSMatthew Ahrens #ifdef _KERNEL
41182ec99e3eSMatthew Ahrens 				to_free = MAX(to_free, ptob(needfree));
41192ec99e3eSMatthew Ahrens #endif
41202ec99e3eSMatthew Ahrens 				arc_shrink(to_free);
41212ec99e3eSMatthew Ahrens 			}
41222ec99e3eSMatthew Ahrens 		} else if (free_memory < arc_c >> arc_no_grow_shift) {
41232ec99e3eSMatthew Ahrens 			arc_no_grow = B_TRUE;
4124a8f6344fSEli Rosenthal 		} else if (gethrtime() >= growtime) {
41252ec99e3eSMatthew Ahrens 			arc_no_grow = B_FALSE;
4126fa9e4066Sahrens 		}
4127fa9e4066Sahrens 
4128244781f1SPrakash Surya 		mutex_enter(&arc_reclaim_lock);
4129244781f1SPrakash Surya 
4130244781f1SPrakash Surya 		/*
4131244781f1SPrakash Surya 		 * If evicted is zero, we couldn't evict anything via
4132244781f1SPrakash Surya 		 * arc_adjust(). This could be due to hash lock
4133244781f1SPrakash Surya 		 * collisions, but more likely due to the majority of
4134244781f1SPrakash Surya 		 * arc buffers being unevictable. Therefore, even if
4135244781f1SPrakash Surya 		 * arc_size is above arc_c, another pass is unlikely to
4136244781f1SPrakash Surya 		 * be helpful and could potentially cause us to enter an
4137244781f1SPrakash Surya 		 * infinite loop.
4138244781f1SPrakash Surya 		 */
4139244781f1SPrakash Surya 		if (arc_size <= arc_c || evicted == 0) {
4140244781f1SPrakash Surya 			/*
4141244781f1SPrakash Surya 			 * We're either no longer overflowing, or we
4142244781f1SPrakash Surya 			 * can't evict anything more, so we should wake
4143244781f1SPrakash Surya 			 * up any threads before we go to sleep.
4144244781f1SPrakash Surya 			 */
4145244781f1SPrakash Surya 			cv_broadcast(&arc_reclaim_waiters_cv);
4146244781f1SPrakash Surya 
4147244781f1SPrakash Surya 			/*
4148244781f1SPrakash Surya 			 * Block until signaled, or after one second (we
4149244781f1SPrakash Surya 			 * might need to perform arc_kmem_reap_now()
4150244781f1SPrakash Surya 			 * even if we aren't being signalled)
4151244781f1SPrakash Surya 			 */
4152244781f1SPrakash Surya 			CALLB_CPR_SAFE_BEGIN(&cpr);
4153a8f6344fSEli Rosenthal 			(void) cv_timedwait_hires(&arc_reclaim_thread_cv,
4154a8f6344fSEli Rosenthal 			    &arc_reclaim_lock, SEC2NSEC(1), MSEC2NSEC(1), 0);
4155244781f1SPrakash Surya 			CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_lock);
4156244781f1SPrakash Surya 		}
4157244781f1SPrakash Surya 	}
4158244781f1SPrakash Surya 
4159dcbf3bd6SGeorge Wilson 	arc_reclaim_thread_exit = B_FALSE;
4160244781f1SPrakash Surya 	cv_broadcast(&arc_reclaim_thread_cv);
4161244781f1SPrakash Surya 	CALLB_CPR_EXIT(&cpr);		/* drops arc_reclaim_lock */
4162244781f1SPrakash Surya 	thread_exit();
4163244781f1SPrakash Surya }
4164244781f1SPrakash Surya 
4165ea8dc4b6Seschrock /*
4166ea8dc4b6Seschrock  * Adapt arc info given the number of bytes we are trying to add and
4167ea8dc4b6Seschrock  * the state that we are comming from.  This function is only called
4168ea8dc4b6Seschrock  * when we are adding new content to the cache.
4169ea8dc4b6Seschrock  */
4170fa9e4066Sahrens static void
4171ea8dc4b6Seschrock arc_adapt(int bytes, arc_state_t *state)
4172fa9e4066Sahrens {
4173ea8dc4b6Seschrock 	int mult;
41745a98e54bSBrendan Gregg - Sun Microsystems 	uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
41752fd872a7SPrakash Surya 	int64_t mrug_size = refcount_count(&arc_mru_ghost->arcs_size);
41762fd872a7SPrakash Surya 	int64_t mfug_size = refcount_count(&arc_mfu_ghost->arcs_size);
4177ea8dc4b6Seschrock 
4178fa94a07fSbrendan 	if (state == arc_l2c_only)
4179fa94a07fSbrendan 		return;
4180fa94a07fSbrendan 
4181ea8dc4b6Seschrock 	ASSERT(bytes > 0);
4182fa9e4066Sahrens 	/*
4183ea8dc4b6Seschrock 	 * Adapt the target size of the MRU list:
4184ea8dc4b6Seschrock 	 *	- if we just hit in the MRU ghost list, then increase
4185ea8dc4b6Seschrock 	 *	  the target size of the MRU list.
4186ea8dc4b6Seschrock 	 *	- if we just hit in the MFU ghost list, then increase
4187ea8dc4b6Seschrock 	 *	  the target size of the MFU list by decreasing the
4188ea8dc4b6Seschrock 	 *	  target size of the MRU list.
4189fa9e4066Sahrens 	 */
419044cb6abcSbmc 	if (state == arc_mru_ghost) {
41912fd872a7SPrakash Surya 		mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
41923e4e8481STom Erickson 		mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
4193ea8dc4b6Seschrock 
41945a98e54bSBrendan Gregg - Sun Microsystems 		arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
419544cb6abcSbmc 	} else if (state == arc_mfu_ghost) {
41965a98e54bSBrendan Gregg - Sun Microsystems 		uint64_t delta;
41975a98e54bSBrendan Gregg - Sun Microsystems 
41982fd872a7SPrakash Surya 		mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
41993e4e8481STom Erickson 		mult = MIN(mult, 10);
4200ea8dc4b6Seschrock 
42015a98e54bSBrendan Gregg - Sun Microsystems 		delta = MIN(bytes * mult, arc_p);
42025a98e54bSBrendan Gregg - Sun Microsystems 		arc_p = MAX(arc_p_min, arc_p - delta);
4203ea8dc4b6Seschrock 	}
420444cb6abcSbmc 	ASSERT((int64_t)arc_p >= 0);
4205fa9e4066Sahrens 
4206fa9e4066Sahrens 	if (arc_reclaim_needed()) {
4207244781f1SPrakash Surya 		cv_signal(&arc_reclaim_thread_cv);
4208fa9e4066Sahrens 		return;
4209fa9e4066Sahrens 	}
4210fa9e4066Sahrens 
421144cb6abcSbmc 	if (arc_no_grow)
4212fa9e4066Sahrens 		return;
4213fa9e4066Sahrens 
421444cb6abcSbmc 	if (arc_c >= arc_c_max)
4215ea8dc4b6Seschrock 		return;
4216ea8dc4b6Seschrock 
4217fa9e4066Sahrens 	/*
4218ea8dc4b6Seschrock 	 * If we're within (2 * maxblocksize) bytes of the target
4219ea8dc4b6Seschrock 	 * cache size, increment the target cache size
4220fa9e4066Sahrens 	 */
422144cb6abcSbmc 	if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
422244cb6abcSbmc 		atomic_add_64(&arc_c, (int64_t)bytes);
422344cb6abcSbmc 		if (arc_c > arc_c_max)
422444cb6abcSbmc 			arc_c = arc_c_max;
422544cb6abcSbmc 		else if (state == arc_anon)
422644cb6abcSbmc 			atomic_add_64(&arc_p, (int64_t)bytes);
422744cb6abcSbmc 		if (arc_p > arc_c)
422844cb6abcSbmc 			arc_p = arc_c;
4229fa9e4066Sahrens 	}
423044cb6abcSbmc 	ASSERT((int64_t)arc_p >= 0);
4231fa9e4066Sahrens }
4232fa9e4066Sahrens 
4233fa9e4066Sahrens /*
4234244781f1SPrakash Surya  * Check if arc_size has grown past our upper threshold, determined by
4235244781f1SPrakash Surya  * zfs_arc_overflow_shift.
4236fa9e4066Sahrens  */
4237244781f1SPrakash Surya static boolean_t
4238244781f1SPrakash Surya arc_is_overflowing(void)
4239fa9e4066Sahrens {
4240244781f1SPrakash Surya 	/* Always allow at least one block of overflow */
4241244781f1SPrakash Surya 	uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
4242244781f1SPrakash Surya 	    arc_c >> zfs_arc_overflow_shift);
4243fa9e4066Sahrens 
4244244781f1SPrakash Surya 	return (arc_size >= arc_c + overflow);
4245fa9e4066Sahrens }
4246fa9e4066Sahrens 
4247fa9e4066Sahrens /*
4248dcbf3bd6SGeorge Wilson  * Allocate a block and return it to the caller. If we are hitting the
4249dcbf3bd6SGeorge Wilson  * hard limit for the cache size, we must sleep, waiting for the eviction
4250dcbf3bd6SGeorge Wilson  * thread to catch up. If we're past the target size but below the hard
4251dcbf3bd6SGeorge Wilson  * limit, we'll only signal the reclaim thread and continue on.
4252fa9e4066Sahrens  */
4253dcbf3bd6SGeorge Wilson static void *
4254dcbf3bd6SGeorge Wilson arc_get_data_buf(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4255fa9e4066Sahrens {
4256dcbf3bd6SGeorge Wilson 	void *datap = NULL;
4257dcbf3bd6SGeorge Wilson 	arc_state_t		*state = hdr->b_l1hdr.b_state;
4258dcbf3bd6SGeorge Wilson 	arc_buf_contents_t	type = arc_buf_type(hdr);
4259fa9e4066Sahrens 
426044eda4d7Smaybee 	arc_adapt(size, state);
4261fa9e4066Sahrens 
426244eda4d7Smaybee 	/*
4263244781f1SPrakash Surya 	 * If arc_size is currently overflowing, and has grown past our
4264244781f1SPrakash Surya 	 * upper limit, we must be adding data faster than the evict
4265244781f1SPrakash Surya 	 * thread can evict. Thus, to ensure we don't compound the
4266244781f1SPrakash Surya 	 * problem by adding more data and forcing arc_size to grow even
4267244781f1SPrakash Surya 	 * further past it's target size, we halt and wait for the
4268244781f1SPrakash Surya 	 * eviction thread to catch up.
4269244781f1SPrakash Surya 	 *
4270244781f1SPrakash Surya 	 * It's also possible that the reclaim thread is unable to evict
4271244781f1SPrakash Surya 	 * enough buffers to get arc_size below the overflow limit (e.g.
4272244781f1SPrakash Surya 	 * due to buffers being un-evictable, or hash lock collisions).
4273244781f1SPrakash Surya 	 * In this case, we want to proceed regardless if we're
4274244781f1SPrakash Surya 	 * overflowing; thus we don't use a while loop here.
427544eda4d7Smaybee 	 */
4276244781f1SPrakash Surya 	if (arc_is_overflowing()) {
4277244781f1SPrakash Surya 		mutex_enter(&arc_reclaim_lock);
4278244781f1SPrakash Surya 
4279244781f1SPrakash Surya 		/*
4280244781f1SPrakash Surya 		 * Now that we've acquired the lock, we may no longer be
4281244781f1SPrakash Surya 		 * over the overflow limit, lets check.
4282244781f1SPrakash Surya 		 *
4283244781f1SPrakash Surya 		 * We're ignoring the case of spurious wake ups. If that
4284244781f1SPrakash Surya 		 * were to happen, it'd let this thread consume an ARC
4285244781f1SPrakash Surya 		 * buffer before it should have (i.e. before we're under
4286244781f1SPrakash Surya 		 * the overflow limit and were signalled by the reclaim
4287244781f1SPrakash Surya 		 * thread). As long as that is a rare occurrence, it
4288244781f1SPrakash Surya 		 * shouldn't cause any harm.
4289244781f1SPrakash Surya 		 */
4290244781f1SPrakash Surya 		if (arc_is_overflowing()) {
4291244781f1SPrakash Surya 			cv_signal(&arc_reclaim_thread_cv);
4292244781f1SPrakash Surya 			cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
4293ad23a2dbSjohansen 		}
4294244781f1SPrakash Surya 
4295244781f1SPrakash Surya 		mutex_exit(&arc_reclaim_lock);
429644eda4d7Smaybee 	}
429744eda4d7Smaybee 
4298dcbf3bd6SGeorge Wilson 	VERIFY3U(hdr->b_type, ==, type);
4299244781f1SPrakash Surya 	if (type == ARC_BUFC_METADATA) {
4300dcbf3bd6SGeorge Wilson 		datap = zio_buf_alloc(size);
4301244781f1SPrakash Surya 		arc_space_consume(size, ARC_SPACE_META);
4302fa9e4066Sahrens 	} else {
4303244781f1SPrakash Surya 		ASSERT(type == ARC_BUFC_DATA);
4304dcbf3bd6SGeorge Wilson 		datap = zio_data_buf_alloc(size);
4305244781f1SPrakash Surya 		arc_space_consume(size, ARC_SPACE_DATA);
430644eda4d7Smaybee 	}
4307244781f1SPrakash Surya 
430844eda4d7Smaybee 	/*
430944eda4d7Smaybee 	 * Update the state size.  Note that ghost states have a
431044eda4d7Smaybee 	 * "ghost size" and so don't need to be updated.
431144eda4d7Smaybee 	 */
4312dcbf3bd6SGeorge Wilson 	if (!GHOST_STATE(state)) {
431344eda4d7Smaybee 
4314dcbf3bd6SGeorge Wilson 		(void) refcount_add_many(&state->arcs_size, size, tag);
4315244781f1SPrakash Surya 
4316244781f1SPrakash Surya 		/*
4317244781f1SPrakash Surya 		 * If this is reached via arc_read, the link is
4318244781f1SPrakash Surya 		 * protected by the hash lock. If reached via
4319244781f1SPrakash Surya 		 * arc_buf_alloc, the header should not be accessed by
4320244781f1SPrakash Surya 		 * any other thread. And, if reached via arc_read_done,
4321244781f1SPrakash Surya 		 * the hash lock will protect it if it's found in the
4322244781f1SPrakash Surya 		 * hash table; otherwise no other thread should be
4323244781f1SPrakash Surya 		 * trying to [add|remove]_reference it.
4324244781f1SPrakash Surya 		 */
4325244781f1SPrakash Surya 		if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
432689c86e32SChris Williamson 			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4327dcbf3bd6SGeorge Wilson 			(void) refcount_add_many(&state->arcs_esize[type],
4328dcbf3bd6SGeorge Wilson 			    size, tag);
4329fa9e4066Sahrens 		}
4330dcbf3bd6SGeorge Wilson 
4331641fbdaeSmaybee 		/*
4332641fbdaeSmaybee 		 * If we are growing the cache, and we are adding anonymous
433344cb6abcSbmc 		 * data, and we have outgrown arc_p, update arc_p
4334641fbdaeSmaybee 		 */
433589c86e32SChris Williamson 		if (arc_size < arc_c && hdr->b_l1hdr.b_state == arc_anon &&
43362fd872a7SPrakash Surya 		    (refcount_count(&arc_anon->arcs_size) +
43372fd872a7SPrakash Surya 		    refcount_count(&arc_mru->arcs_size) > arc_p))
433844cb6abcSbmc 			arc_p = MIN(arc_c, arc_p + size);
4339fa9e4066Sahrens 	}
4340dcbf3bd6SGeorge Wilson 	return (datap);
4341dcbf3bd6SGeorge Wilson }
4342dcbf3bd6SGeorge Wilson 
4343dcbf3bd6SGeorge Wilson /*
4344dcbf3bd6SGeorge Wilson  * Free the arc data buffer.
4345dcbf3bd6SGeorge Wilson  */
4346dcbf3bd6SGeorge Wilson static void
4347dcbf3bd6SGeorge Wilson arc_free_data_buf(arc_buf_hdr_t *hdr, void *data, uint64_t size, void *tag)
4348dcbf3bd6SGeorge Wilson {
4349dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
4350dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type = arc_buf_type(hdr);
4351dcbf3bd6SGeorge Wilson 
4352dcbf3bd6SGeorge Wilson 	/* protected by hash lock, if in the hash table */
4353dcbf3bd6SGeorge Wilson 	if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
4354dcbf3bd6SGeorge Wilson 		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4355dcbf3bd6SGeorge Wilson 		ASSERT(state != arc_anon && state != arc_l2c_only);
4356dcbf3bd6SGeorge Wilson 
4357dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_esize[type],
4358dcbf3bd6SGeorge Wilson 		    size, tag);
4359dcbf3bd6SGeorge Wilson 	}
4360dcbf3bd6SGeorge Wilson 	(void) refcount_remove_many(&state->arcs_size, size, tag);
4361dcbf3bd6SGeorge Wilson 
4362dcbf3bd6SGeorge Wilson 	VERIFY3U(hdr->b_type, ==, type);
4363dcbf3bd6SGeorge Wilson 	if (type == ARC_BUFC_METADATA) {
4364dcbf3bd6SGeorge Wilson 		zio_buf_free(data, size);
4365dcbf3bd6SGeorge Wilson 		arc_space_return(size, ARC_SPACE_META);
4366dcbf3bd6SGeorge Wilson 	} else {
4367dcbf3bd6SGeorge Wilson 		ASSERT(type == ARC_BUFC_DATA);
4368dcbf3bd6SGeorge Wilson 		zio_data_buf_free(data, size);
4369dcbf3bd6SGeorge Wilson 		arc_space_return(size, ARC_SPACE_DATA);
4370dcbf3bd6SGeorge Wilson 	}
4371fa9e4066Sahrens }
4372fa9e4066Sahrens 
4373fa9e4066Sahrens /*
4374fa9e4066Sahrens  * This routine is called whenever a buffer is accessed.
4375ea8dc4b6Seschrock  * NOTE: the hash lock is dropped in this function.
4376fa9e4066Sahrens  */
4377fa9e4066Sahrens static void
43787adb730bSGeorge Wilson arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
4379fa9e4066Sahrens {
4380d3d50737SRafael Vanoni 	clock_t now;
4381d3d50737SRafael Vanoni 
4382fa9e4066Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
438389c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
4384fa9e4066Sahrens 
438589c86e32SChris Williamson 	if (hdr->b_l1hdr.b_state == arc_anon) {
4386fa9e4066Sahrens 		/*
4387fa9e4066Sahrens 		 * This buffer is not in the cache, and does not
4388fa9e4066Sahrens 		 * appear in our "ghost" list.  Add the new buffer
4389fa9e4066Sahrens 		 * to the MRU state.
4390fa9e4066Sahrens 		 */
4391fa9e4066Sahrens 
439289c86e32SChris Williamson 		ASSERT0(hdr->b_l1hdr.b_arc_access);
439389c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
43947adb730bSGeorge Wilson 		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
43957adb730bSGeorge Wilson 		arc_change_state(arc_mru, hdr, hash_lock);
4396fa9e4066Sahrens 
439789c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mru) {
4398d3d50737SRafael Vanoni 		now = ddi_get_lbolt();
4399d3d50737SRafael Vanoni 
4400fa9e4066Sahrens 		/*
440113506d1eSmaybee 		 * If this buffer is here because of a prefetch, then either:
440213506d1eSmaybee 		 * - clear the flag if this is a "referencing" read
440313506d1eSmaybee 		 *   (any subsequent access will bump this into the MFU state).
440413506d1eSmaybee 		 * or
440513506d1eSmaybee 		 * - move the buffer to the head of the list if this is
440613506d1eSmaybee 		 *   another prefetch (to make it less likely to be evicted).
4407fa9e4066Sahrens 		 */
440889c86e32SChris Williamson 		if (HDR_PREFETCH(hdr)) {
440989c86e32SChris Williamson 			if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4410244781f1SPrakash Surya 				/* link protected by hash lock */
4411244781f1SPrakash Surya 				ASSERT(multilist_link_active(
441289c86e32SChris Williamson 				    &hdr->b_l1hdr.b_arc_node));
441313506d1eSmaybee 			} else {
4414dcbf3bd6SGeorge Wilson 				arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
441544cb6abcSbmc 				ARCSTAT_BUMP(arcstat_mru_hits);
441613506d1eSmaybee 			}
441789c86e32SChris Williamson 			hdr->b_l1hdr.b_arc_access = now;
4418fa9e4066Sahrens 			return;
4419fa9e4066Sahrens 		}
4420fa9e4066Sahrens 
4421fa9e4066Sahrens 		/*
4422fa9e4066Sahrens 		 * This buffer has been "accessed" only once so far,
4423fa9e4066Sahrens 		 * but it is still in the cache. Move it to the MFU
4424fa9e4066Sahrens 		 * state.
4425fa9e4066Sahrens 		 */
442689c86e32SChris Williamson 		if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
4427fa9e4066Sahrens 			/*
4428fa9e4066Sahrens 			 * More than 125ms have passed since we
4429fa9e4066Sahrens 			 * instantiated this buffer.  Move it to the
4430fa9e4066Sahrens 			 * most frequently used state.
4431fa9e4066Sahrens 			 */
443289c86e32SChris Williamson 			hdr->b_l1hdr.b_arc_access = now;
44337adb730bSGeorge Wilson 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
44347adb730bSGeorge Wilson 			arc_change_state(arc_mfu, hdr, hash_lock);
4435fa9e4066Sahrens 		}
443644cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mru_hits);
443789c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
4438fa9e4066Sahrens 		arc_state_t	*new_state;
4439fa9e4066Sahrens 		/*
4440fa9e4066Sahrens 		 * This buffer has been "accessed" recently, but
4441fa9e4066Sahrens 		 * was evicted from the cache.  Move it to the
4442fa9e4066Sahrens 		 * MFU state.
4443fa9e4066Sahrens 		 */
4444fa9e4066Sahrens 
444589c86e32SChris Williamson 		if (HDR_PREFETCH(hdr)) {
444644cb6abcSbmc 			new_state = arc_mru;
444789c86e32SChris Williamson 			if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0)
4448dcbf3bd6SGeorge Wilson 				arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
44497adb730bSGeorge Wilson 			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
4450fa9e4066Sahrens 		} else {
445144cb6abcSbmc 			new_state = arc_mfu;
44527adb730bSGeorge Wilson 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4453fa9e4066Sahrens 		}
4454fa9e4066Sahrens 
445589c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
44567adb730bSGeorge Wilson 		arc_change_state(new_state, hdr, hash_lock);
4457fa9e4066Sahrens 
445844cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
445989c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mfu) {
4460fa9e4066Sahrens 		/*
4461fa9e4066Sahrens 		 * This buffer has been accessed more than once and is
4462fa9e4066Sahrens 		 * still in the cache.  Keep it in the MFU state.
4463fa9e4066Sahrens 		 *
446413506d1eSmaybee 		 * NOTE: an add_reference() that occurred when we did
446513506d1eSmaybee 		 * the arc_read() will have kicked this off the list.
446613506d1eSmaybee 		 * If it was a prefetch, we will explicitly move it to
446713506d1eSmaybee 		 * the head of the list now.
4468fa9e4066Sahrens 		 */
446989c86e32SChris Williamson 		if ((HDR_PREFETCH(hdr)) != 0) {
447089c86e32SChris Williamson 			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4471244781f1SPrakash Surya 			/* link protected by hash_lock */
4472244781f1SPrakash Surya 			ASSERT(multilist_link_active(&hdr->b_l1hdr.b_arc_node));
447313506d1eSmaybee 		}
447444cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mfu_hits);
447589c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
447689c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
447744cb6abcSbmc 		arc_state_t	*new_state = arc_mfu;
4478fa9e4066Sahrens 		/*
4479fa9e4066Sahrens 		 * This buffer has been accessed more than once but has
4480fa9e4066Sahrens 		 * been evicted from the cache.  Move it back to the
4481fa9e4066Sahrens 		 * MFU state.
4482fa9e4066Sahrens 		 */
4483fa9e4066Sahrens 
448489c86e32SChris Williamson 		if (HDR_PREFETCH(hdr)) {
448513506d1eSmaybee 			/*
448613506d1eSmaybee 			 * This is a prefetch access...
448713506d1eSmaybee 			 * move this block back to the MRU state.
448813506d1eSmaybee 			 */
448989c86e32SChris Williamson 			ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
449044cb6abcSbmc 			new_state = arc_mru;
449113506d1eSmaybee 		}
449213506d1eSmaybee 
449389c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
44947adb730bSGeorge Wilson 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
44957adb730bSGeorge Wilson 		arc_change_state(new_state, hdr, hash_lock);
4496fa9e4066Sahrens 
449744cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
449889c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
4499fa94a07fSbrendan 		/*
4500fa94a07fSbrendan 		 * This buffer is on the 2nd Level ARC.
4501fa94a07fSbrendan 		 */
4502fa94a07fSbrendan 
450389c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
45047adb730bSGeorge Wilson 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
45057adb730bSGeorge Wilson 		arc_change_state(arc_mfu, hdr, hash_lock);
4506fa9e4066Sahrens 	} else {
4507fa9e4066Sahrens 		ASSERT(!"invalid arc state");
4508fa9e4066Sahrens 	}
4509fa9e4066Sahrens }
4510fa9e4066Sahrens 
4511fa9e4066Sahrens /* a generic arc_done_func_t which you can use */
4512fa9e4066Sahrens /* ARGSUSED */
4513fa9e4066Sahrens void
4514fa9e4066Sahrens arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
4515fa9e4066Sahrens {
45163f9d6ad7SLin Ling 	if (zio == NULL || zio->io_error == 0)
45175602294fSDan Kimmel 		bcopy(buf->b_data, arg, arc_buf_size(buf));
4518dcbf3bd6SGeorge Wilson 	arc_buf_destroy(buf, arg);
4519fa9e4066Sahrens }
4520fa9e4066Sahrens 
45210e8c6158Smaybee /* a generic arc_done_func_t */
4522fa9e4066Sahrens void
4523fa9e4066Sahrens arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
4524fa9e4066Sahrens {
4525fa9e4066Sahrens 	arc_buf_t **bufp = arg;
4526fa9e4066Sahrens 	if (zio && zio->io_error) {
4527dcbf3bd6SGeorge Wilson 		arc_buf_destroy(buf, arg);
4528fa9e4066Sahrens 		*bufp = NULL;
4529fa9e4066Sahrens 	} else {
4530fa9e4066Sahrens 		*bufp = buf;
45313f9d6ad7SLin Ling 		ASSERT(buf->b_data);
4532fa9e4066Sahrens 	}
4533fa9e4066Sahrens }
4534fa9e4066Sahrens 
4535dcbf3bd6SGeorge Wilson static void
4536dcbf3bd6SGeorge Wilson arc_hdr_verify(arc_buf_hdr_t *hdr, blkptr_t *bp)
4537dcbf3bd6SGeorge Wilson {
4538dcbf3bd6SGeorge Wilson 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
4539dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_PSIZE(hdr), ==, 0);
4540dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
4541dcbf3bd6SGeorge Wilson 	} else {
4542dcbf3bd6SGeorge Wilson 		if (HDR_COMPRESSION_ENABLED(hdr)) {
4543dcbf3bd6SGeorge Wilson 			ASSERT3U(HDR_GET_COMPRESS(hdr), ==,
4544dcbf3bd6SGeorge Wilson 			    BP_GET_COMPRESS(bp));
4545dcbf3bd6SGeorge Wilson 		}
4546dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
4547dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_PSIZE(hdr), ==, BP_GET_PSIZE(bp));
4548dcbf3bd6SGeorge Wilson 	}
4549dcbf3bd6SGeorge Wilson }
4550dcbf3bd6SGeorge Wilson 
4551fa9e4066Sahrens static void
4552fa9e4066Sahrens arc_read_done(zio_t *zio)
4553fa9e4066Sahrens {
4554dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t	*hdr = zio->io_private;
45555d7b4d43SMatthew Ahrens 	kmutex_t	*hash_lock = NULL;
45565602294fSDan Kimmel 	arc_callback_t	*callback_list;
45575602294fSDan Kimmel 	arc_callback_t	*acb;
45585602294fSDan Kimmel 	boolean_t	freeable = B_FALSE;
45595602294fSDan Kimmel 	boolean_t	no_zio_error = (zio->io_error == 0);
4560fa9e4066Sahrens 
4561bbf4a8dfSmaybee 	/*
4562bbf4a8dfSmaybee 	 * The hdr was inserted into hash-table and removed from lists
4563bbf4a8dfSmaybee 	 * prior to starting I/O.  We should find this header, since
4564bbf4a8dfSmaybee 	 * it's in the hash table, and it should be legit since it's
4565bbf4a8dfSmaybee 	 * not possible to evict it during the I/O.  The only possible
4566bbf4a8dfSmaybee 	 * reason for it not to be found is if we were freed during the
4567bbf4a8dfSmaybee 	 * read.
4568bbf4a8dfSmaybee 	 */
45695d7b4d43SMatthew Ahrens 	if (HDR_IN_HASH_TABLE(hdr)) {
45705d7b4d43SMatthew Ahrens 		ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
45715d7b4d43SMatthew Ahrens 		ASSERT3U(hdr->b_dva.dva_word[0], ==,
45725d7b4d43SMatthew Ahrens 		    BP_IDENTITY(zio->io_bp)->dva_word[0]);
45735d7b4d43SMatthew Ahrens 		ASSERT3U(hdr->b_dva.dva_word[1], ==,
45745d7b4d43SMatthew Ahrens 		    BP_IDENTITY(zio->io_bp)->dva_word[1]);
45755d7b4d43SMatthew Ahrens 
45765d7b4d43SMatthew Ahrens 		arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
45775d7b4d43SMatthew Ahrens 		    &hash_lock);
45785d7b4d43SMatthew Ahrens 
4579dcbf3bd6SGeorge Wilson 		ASSERT((found == hdr &&
45805d7b4d43SMatthew Ahrens 		    DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
45815d7b4d43SMatthew Ahrens 		    (found == hdr && HDR_L2_READING(hdr)));
4582dcbf3bd6SGeorge Wilson 		ASSERT3P(hash_lock, !=, NULL);
4583dcbf3bd6SGeorge Wilson 	}
4584dcbf3bd6SGeorge Wilson 
45855602294fSDan Kimmel 	if (no_zio_error) {
4586dcbf3bd6SGeorge Wilson 		/* byteswap if necessary */
4587dcbf3bd6SGeorge Wilson 		if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
4588dcbf3bd6SGeorge Wilson 			if (BP_GET_LEVEL(zio->io_bp) > 0) {
4589dcbf3bd6SGeorge Wilson 				hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
4590dcbf3bd6SGeorge Wilson 			} else {
4591dcbf3bd6SGeorge Wilson 				hdr->b_l1hdr.b_byteswap =
4592dcbf3bd6SGeorge Wilson 				    DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
4593dcbf3bd6SGeorge Wilson 			}
4594dcbf3bd6SGeorge Wilson 		} else {
4595dcbf3bd6SGeorge Wilson 			hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
4596dcbf3bd6SGeorge Wilson 		}
45975d7b4d43SMatthew Ahrens 	}
4598fa94a07fSbrendan 
4599dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_L2_EVICTED);
460089c86e32SChris Williamson 	if (l2arc_noprefetch && HDR_PREFETCH(hdr))
4601dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_L2CACHE);
4602fa9e4066Sahrens 
460389c86e32SChris Williamson 	callback_list = hdr->b_l1hdr.b_acb;
4604dcbf3bd6SGeorge Wilson 	ASSERT3P(callback_list, !=, NULL);
46056b4acc8bSahrens 
46065602294fSDan Kimmel 	if (hash_lock && no_zio_error && hdr->b_l1hdr.b_state == arc_anon) {
4607b24ab676SJeff Bonwick 		/*
4608b24ab676SJeff Bonwick 		 * Only call arc_access on anonymous buffers.  This is because
4609b24ab676SJeff Bonwick 		 * if we've issued an I/O for an evicted buffer, we've already
4610b24ab676SJeff Bonwick 		 * called arc_access (to prevent any simultaneous readers from
4611b24ab676SJeff Bonwick 		 * getting confused).
4612b24ab676SJeff Bonwick 		 */
4613b24ab676SJeff Bonwick 		arc_access(hdr, hash_lock);
4614b24ab676SJeff Bonwick 	}
4615b24ab676SJeff Bonwick 
46165602294fSDan Kimmel 	/*
46175602294fSDan Kimmel 	 * If a read request has a callback (i.e. acb_done is not NULL), then we
46185602294fSDan Kimmel 	 * make a buf containing the data according to the parameters which were
46195602294fSDan Kimmel 	 * passed in. The implementation of arc_buf_alloc_impl() ensures that we
46205602294fSDan Kimmel 	 * aren't needlessly decompressing the data multiple times.
46215602294fSDan Kimmel 	 */
46225602294fSDan Kimmel 	int callback_cnt = 0;
46235602294fSDan Kimmel 	for (acb = callback_list; acb != NULL; acb = acb->acb_next) {
46245602294fSDan Kimmel 		if (!acb->acb_done)
46255602294fSDan Kimmel 			continue;
46265602294fSDan Kimmel 
46275602294fSDan Kimmel 		/* This is a demand read since prefetches don't use callbacks */
46285602294fSDan Kimmel 		callback_cnt++;
46295602294fSDan Kimmel 
46305602294fSDan Kimmel 		int error = arc_buf_alloc_impl(hdr, acb->acb_private,
46315602294fSDan Kimmel 		    acb->acb_compressed, no_zio_error, &acb->acb_buf);
46325602294fSDan Kimmel 		if (no_zio_error) {
46335602294fSDan Kimmel 			zio->io_error = error;
4634fa9e4066Sahrens 		}
4635fa9e4066Sahrens 	}
463689c86e32SChris Williamson 	hdr->b_l1hdr.b_acb = NULL;
4637dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
46385602294fSDan Kimmel 	if (callback_cnt == 0) {
4639dcbf3bd6SGeorge Wilson 		ASSERT(HDR_PREFETCH(hdr));
4640dcbf3bd6SGeorge Wilson 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
4641dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
4642b24ab676SJeff Bonwick 	}
4643fa9e4066Sahrens 
464489c86e32SChris Williamson 	ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
464589c86e32SChris Williamson 	    callback_list != NULL);
4646fa9e4066Sahrens 
46475602294fSDan Kimmel 	if (no_zio_error) {
4648dcbf3bd6SGeorge Wilson 		arc_hdr_verify(hdr, zio->io_bp);
4649dcbf3bd6SGeorge Wilson 	} else {
4650dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
465189c86e32SChris Williamson 		if (hdr->b_l1hdr.b_state != arc_anon)
465244cb6abcSbmc 			arc_change_state(arc_anon, hdr, hash_lock);
4653ea8dc4b6Seschrock 		if (HDR_IN_HASH_TABLE(hdr))
4654ea8dc4b6Seschrock 			buf_hash_remove(hdr);
465589c86e32SChris Williamson 		freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4656fa9e4066Sahrens 	}
4657fa9e4066Sahrens 
4658ea8dc4b6Seschrock 	/*
465913506d1eSmaybee 	 * Broadcast before we drop the hash_lock to avoid the possibility
466013506d1eSmaybee 	 * that the hdr (and hence the cv) might be freed before we get to
466113506d1eSmaybee 	 * the cv_broadcast().
4662ea8dc4b6Seschrock 	 */
466389c86e32SChris Williamson 	cv_broadcast(&hdr->b_l1hdr.b_cv);
4664ea8dc4b6Seschrock 
466589c86e32SChris Williamson 	if (hash_lock != NULL) {
466644eda4d7Smaybee 		mutex_exit(hash_lock);
4667fa9e4066Sahrens 	} else {
4668fa9e4066Sahrens 		/*
4669fa9e4066Sahrens 		 * This block was freed while we waited for the read to
4670fa9e4066Sahrens 		 * complete.  It has been removed from the hash table and
4671fa9e4066Sahrens 		 * moved to the anonymous state (so that it won't show up
4672fa9e4066Sahrens 		 * in the cache).
4673fa9e4066Sahrens 		 */
467489c86e32SChris Williamson 		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
467589c86e32SChris Williamson 		freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4676fa9e4066Sahrens 	}
4677fa9e4066Sahrens 
4678fa9e4066Sahrens 	/* execute each callback and free its structure */
4679fa9e4066Sahrens 	while ((acb = callback_list) != NULL) {
4680fa9e4066Sahrens 		if (acb->acb_done)
4681fa9e4066Sahrens 			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
4682fa9e4066Sahrens 
4683fa9e4066Sahrens 		if (acb->acb_zio_dummy != NULL) {
4684fa9e4066Sahrens 			acb->acb_zio_dummy->io_error = zio->io_error;
4685fa9e4066Sahrens 			zio_nowait(acb->acb_zio_dummy);
4686fa9e4066Sahrens 		}
4687fa9e4066Sahrens 
4688fa9e4066Sahrens 		callback_list = acb->acb_next;
4689fa9e4066Sahrens 		kmem_free(acb, sizeof (arc_callback_t));
4690fa9e4066Sahrens 	}
4691fa9e4066Sahrens 
4692fa9e4066Sahrens 	if (freeable)
4693ea8dc4b6Seschrock 		arc_hdr_destroy(hdr);
4694fa9e4066Sahrens }
4695fa9e4066Sahrens 
4696fa9e4066Sahrens /*
4697fc98fea5SBart Coddens  * "Read" the block at the specified DVA (in bp) via the
4698fa9e4066Sahrens  * cache.  If the block is found in the cache, invoke the provided
4699fa9e4066Sahrens  * callback immediately and return.  Note that the `zio' parameter
4700fa9e4066Sahrens  * in the callback will be NULL in this case, since no IO was
4701fa9e4066Sahrens  * required.  If the block is not in the cache pass the read request
4702fa9e4066Sahrens  * on to the spa with a substitute callback function, so that the
4703fa9e4066Sahrens  * requested block will be added to the cache.
4704fa9e4066Sahrens  *
4705fa9e4066Sahrens  * If a read request arrives for a block that has a read in-progress,
4706fa9e4066Sahrens  * either wait for the in-progress read to complete (and return the
4707fa9e4066Sahrens  * results); or, if this is a read with a "done" func, add a record
4708fa9e4066Sahrens  * to the read to invoke the "done" func when the read completes,
4709fa9e4066Sahrens  * and return; or just return.
4710fa9e4066Sahrens  *
4711fa9e4066Sahrens  * arc_read_done() will invoke all the requested "done" functions
4712fa9e4066Sahrens  * for readers of this block.
4713fa9e4066Sahrens  */
4714fa9e4066Sahrens int
47151b912ec7SGeorge Wilson arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
47167adb730bSGeorge Wilson     void *private, zio_priority_t priority, int zio_flags,
47177adb730bSGeorge Wilson     arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
4718fa9e4066Sahrens {
47195d7b4d43SMatthew Ahrens 	arc_buf_hdr_t *hdr = NULL;
47205d7b4d43SMatthew Ahrens 	kmutex_t *hash_lock = NULL;
4721fa94a07fSbrendan 	zio_t *rzio;
4722e9103aaeSGarrett D'Amore 	uint64_t guid = spa_load_guid(spa);
47235602294fSDan Kimmel 	boolean_t compressed_read = (zio_flags & ZIO_FLAG_RAW) != 0;
4724fa9e4066Sahrens 
47255d7b4d43SMatthew Ahrens 	ASSERT(!BP_IS_EMBEDDED(bp) ||
47265d7b4d43SMatthew Ahrens 	    BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
47275d7b4d43SMatthew Ahrens 
4728fa9e4066Sahrens top:
47295d7b4d43SMatthew Ahrens 	if (!BP_IS_EMBEDDED(bp)) {
47305d7b4d43SMatthew Ahrens 		/*
47315d7b4d43SMatthew Ahrens 		 * Embedded BP's have no DVA and require no I/O to "read".
47325d7b4d43SMatthew Ahrens 		 * Create an anonymous arc buf to back it.
47335d7b4d43SMatthew Ahrens 		 */
47345d7b4d43SMatthew Ahrens 		hdr = buf_hash_find(guid, bp, &hash_lock);
47355d7b4d43SMatthew Ahrens 	}
47365d7b4d43SMatthew Ahrens 
4737dcbf3bd6SGeorge Wilson 	if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_pdata != NULL) {
4738dcbf3bd6SGeorge Wilson 		arc_buf_t *buf = NULL;
47397adb730bSGeorge Wilson 		*arc_flags |= ARC_FLAG_CACHED;
474013506d1eSmaybee 
4741fa9e4066Sahrens 		if (HDR_IO_IN_PROGRESS(hdr)) {
474213506d1eSmaybee 
4743cf6106c8SMatthew Ahrens 			if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
4744cf6106c8SMatthew Ahrens 			    priority == ZIO_PRIORITY_SYNC_READ) {
4745cf6106c8SMatthew Ahrens 				/*
4746cf6106c8SMatthew Ahrens 				 * This sync read must wait for an
4747cf6106c8SMatthew Ahrens 				 * in-progress async read (e.g. a predictive
4748cf6106c8SMatthew Ahrens 				 * prefetch).  Async reads are queued
4749cf6106c8SMatthew Ahrens 				 * separately at the vdev_queue layer, so
4750cf6106c8SMatthew Ahrens 				 * this is a form of priority inversion.
4751cf6106c8SMatthew Ahrens 				 * Ideally, we would "inherit" the demand
4752cf6106c8SMatthew Ahrens 				 * i/o's priority by moving the i/o from
4753cf6106c8SMatthew Ahrens 				 * the async queue to the synchronous queue,
4754cf6106c8SMatthew Ahrens 				 * but there is currently no mechanism to do
4755cf6106c8SMatthew Ahrens 				 * so.  Track this so that we can evaluate
4756cf6106c8SMatthew Ahrens 				 * the magnitude of this potential performance
4757cf6106c8SMatthew Ahrens 				 * problem.
4758cf6106c8SMatthew Ahrens 				 *
4759cf6106c8SMatthew Ahrens 				 * Note that if the prefetch i/o is already
4760cf6106c8SMatthew Ahrens 				 * active (has been issued to the device),
4761cf6106c8SMatthew Ahrens 				 * the prefetch improved performance, because
4762cf6106c8SMatthew Ahrens 				 * we issued it sooner than we would have
4763cf6106c8SMatthew Ahrens 				 * without the prefetch.
4764cf6106c8SMatthew Ahrens 				 */
4765cf6106c8SMatthew Ahrens 				DTRACE_PROBE1(arc__sync__wait__for__async,
4766cf6106c8SMatthew Ahrens 				    arc_buf_hdr_t *, hdr);
4767cf6106c8SMatthew Ahrens 				ARCSTAT_BUMP(arcstat_sync_wait_for_async);
4768cf6106c8SMatthew Ahrens 			}
4769cf6106c8SMatthew Ahrens 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
4770dcbf3bd6SGeorge Wilson 				arc_hdr_clear_flags(hdr,
4771dcbf3bd6SGeorge Wilson 				    ARC_FLAG_PREDICTIVE_PREFETCH);
4772cf6106c8SMatthew Ahrens 			}
4773cf6106c8SMatthew Ahrens 
47747adb730bSGeorge Wilson 			if (*arc_flags & ARC_FLAG_WAIT) {
477589c86e32SChris Williamson 				cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
477613506d1eSmaybee 				mutex_exit(hash_lock);
477713506d1eSmaybee 				goto top;
477813506d1eSmaybee 			}
47797adb730bSGeorge Wilson 			ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
478013506d1eSmaybee 
478113506d1eSmaybee 			if (done) {
4782cf6106c8SMatthew Ahrens 				arc_callback_t *acb = NULL;
4783fa9e4066Sahrens 
4784fa9e4066Sahrens 				acb = kmem_zalloc(sizeof (arc_callback_t),
4785fa9e4066Sahrens 				    KM_SLEEP);
4786fa9e4066Sahrens 				acb->acb_done = done;
4787fa9e4066Sahrens 				acb->acb_private = private;
47885602294fSDan Kimmel 				acb->acb_compressed = compressed_read;
4789fa9e4066Sahrens 				if (pio != NULL)
4790fa9e4066Sahrens 					acb->acb_zio_dummy = zio_null(pio,
4791a3f829aeSBill Moore 					    spa, NULL, NULL, NULL, zio_flags);
4792fa9e4066Sahrens 
4793dcbf3bd6SGeorge Wilson 				ASSERT3P(acb->acb_done, !=, NULL);
479489c86e32SChris Williamson 				acb->acb_next = hdr->b_l1hdr.b_acb;
479589c86e32SChris Williamson 				hdr->b_l1hdr.b_acb = acb;
4796fa9e4066Sahrens 				mutex_exit(hash_lock);
4797fa9e4066Sahrens 				return (0);
4798fa9e4066Sahrens 			}
4799fa9e4066Sahrens 			mutex_exit(hash_lock);
4800fa9e4066Sahrens 			return (0);
4801fa9e4066Sahrens 		}
4802fa9e4066Sahrens 
480389c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
480489c86e32SChris Williamson 		    hdr->b_l1hdr.b_state == arc_mfu);
4805fa9e4066Sahrens 
4806ea8dc4b6Seschrock 		if (done) {
4807cf6106c8SMatthew Ahrens 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
4808cf6106c8SMatthew Ahrens 				/*
4809cf6106c8SMatthew Ahrens 				 * This is a demand read which does not have to
4810cf6106c8SMatthew Ahrens 				 * wait for i/o because we did a predictive
4811cf6106c8SMatthew Ahrens 				 * prefetch i/o for it, which has completed.
4812cf6106c8SMatthew Ahrens 				 */
4813cf6106c8SMatthew Ahrens 				DTRACE_PROBE1(
4814cf6106c8SMatthew Ahrens 				    arc__demand__hit__predictive__prefetch,
4815cf6106c8SMatthew Ahrens 				    arc_buf_hdr_t *, hdr);
4816cf6106c8SMatthew Ahrens 				ARCSTAT_BUMP(
4817cf6106c8SMatthew Ahrens 				    arcstat_demand_hit_predictive_prefetch);
4818dcbf3bd6SGeorge Wilson 				arc_hdr_clear_flags(hdr,
4819dcbf3bd6SGeorge Wilson 				    ARC_FLAG_PREDICTIVE_PREFETCH);
4820cf6106c8SMatthew Ahrens 			}
4821dcbf3bd6SGeorge Wilson 			ASSERT(!BP_IS_EMBEDDED(bp) || !BP_IS_HOLE(bp));
4822dcbf3bd6SGeorge Wilson 
48235602294fSDan Kimmel 			/* Get a buf with the desired data in it. */
48245602294fSDan Kimmel 			VERIFY0(arc_buf_alloc_impl(hdr, private,
48255602294fSDan Kimmel 			    compressed_read, B_TRUE, &buf));
48267adb730bSGeorge Wilson 		} else if (*arc_flags & ARC_FLAG_PREFETCH &&
482789c86e32SChris Williamson 		    refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4828dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
4829fa9e4066Sahrens 		}
4830fa9e4066Sahrens 		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
483144eda4d7Smaybee 		arc_access(hdr, hash_lock);
48327adb730bSGeorge Wilson 		if (*arc_flags & ARC_FLAG_L2CACHE)
4833dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
483444eda4d7Smaybee 		mutex_exit(hash_lock);
483544cb6abcSbmc 		ARCSTAT_BUMP(arcstat_hits);
483689c86e32SChris Williamson 		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
483789c86e32SChris Williamson 		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
483844cb6abcSbmc 		    data, metadata, hits);
483944cb6abcSbmc 
4840fa9e4066Sahrens 		if (done)
4841fa9e4066Sahrens 			done(NULL, buf, private);
4842fa9e4066Sahrens 	} else {
4843dcbf3bd6SGeorge Wilson 		uint64_t lsize = BP_GET_LSIZE(bp);
4844dcbf3bd6SGeorge Wilson 		uint64_t psize = BP_GET_PSIZE(bp);
48455d7b4d43SMatthew Ahrens 		arc_callback_t *acb;
48463a737e0dSbrendan 		vdev_t *vd = NULL;
4847d5285caeSGeorge Wilson 		uint64_t addr = 0;
48485a98e54bSBrendan Gregg - Sun Microsystems 		boolean_t devw = B_FALSE;
4849dcbf3bd6SGeorge Wilson 		uint64_t size;
4850fa9e4066Sahrens 
4851fa9e4066Sahrens 		if (hdr == NULL) {
4852fa9e4066Sahrens 			/* this block is not in the cache */
48535d7b4d43SMatthew Ahrens 			arc_buf_hdr_t *exists = NULL;
4854ad23a2dbSjohansen 			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
4855dcbf3bd6SGeorge Wilson 			hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
4856dcbf3bd6SGeorge Wilson 			    BP_GET_COMPRESS(bp), type);
4857dcbf3bd6SGeorge Wilson 
48585d7b4d43SMatthew Ahrens 			if (!BP_IS_EMBEDDED(bp)) {
48595d7b4d43SMatthew Ahrens 				hdr->b_dva = *BP_IDENTITY(bp);
48605d7b4d43SMatthew Ahrens 				hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
48615d7b4d43SMatthew Ahrens 				exists = buf_hash_insert(hdr, &hash_lock);
48625d7b4d43SMatthew Ahrens 			}
48635d7b4d43SMatthew Ahrens 			if (exists != NULL) {
4864fa9e4066Sahrens 				/* somebody beat us to the hash insert */
4865fa9e4066Sahrens 				mutex_exit(hash_lock);
48663f9d6ad7SLin Ling 				buf_discard_identity(hdr);
4867dcbf3bd6SGeorge Wilson 				arc_hdr_destroy(hdr);
4868fa9e4066Sahrens 				goto top; /* restart the IO request */
4869fa9e4066Sahrens 			}
4870fa9e4066Sahrens 		} else {
487189c86e32SChris Williamson 			/*
487289c86e32SChris Williamson 			 * This block is in the ghost cache. If it was L2-only
487389c86e32SChris Williamson 			 * (and thus didn't have an L1 hdr), we realloc the
487489c86e32SChris Williamson 			 * header to add an L1 hdr.
487589c86e32SChris Williamson 			 */
487689c86e32SChris Williamson 			if (!HDR_HAS_L1HDR(hdr)) {
487789c86e32SChris Williamson 				hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
487889c86e32SChris Williamson 				    hdr_full_cache);
487989c86e32SChris Williamson 			}
4880dcbf3bd6SGeorge Wilson 			ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
488189c86e32SChris Williamson 			ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
4882ea8dc4b6Seschrock 			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
488389c86e32SChris Williamson 			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4884244781f1SPrakash Surya 			ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
48855602294fSDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
488613506d1eSmaybee 
4887cf6106c8SMatthew Ahrens 			/*
4888dcbf3bd6SGeorge Wilson 			 * This is a delicate dance that we play here.
4889dcbf3bd6SGeorge Wilson 			 * This hdr is in the ghost list so we access it
4890dcbf3bd6SGeorge Wilson 			 * to move it out of the ghost list before we
4891dcbf3bd6SGeorge Wilson 			 * initiate the read. If it's a prefetch then
4892dcbf3bd6SGeorge Wilson 			 * it won't have a callback so we'll remove the
4893dcbf3bd6SGeorge Wilson 			 * reference that arc_buf_alloc_impl() created. We
4894dcbf3bd6SGeorge Wilson 			 * do this after we've called arc_access() to
4895dcbf3bd6SGeorge Wilson 			 * avoid hitting an assert in remove_reference().
4896cf6106c8SMatthew Ahrens 			 */
48977e453561SWilliam Gorrell 			arc_access(hdr, hash_lock);
4898dcbf3bd6SGeorge Wilson 			arc_hdr_alloc_pdata(hdr);
4899dcbf3bd6SGeorge Wilson 		}
4900dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
4901dcbf3bd6SGeorge Wilson 		size = arc_hdr_size(hdr);
4902dcbf3bd6SGeorge Wilson 
4903dcbf3bd6SGeorge Wilson 		/*
4904dcbf3bd6SGeorge Wilson 		 * If compression is enabled on the hdr, then will do
4905dcbf3bd6SGeorge Wilson 		 * RAW I/O and will store the compressed data in the hdr's
4906dcbf3bd6SGeorge Wilson 		 * data block. Otherwise, the hdr's data block will contain
4907dcbf3bd6SGeorge Wilson 		 * the uncompressed data.
4908dcbf3bd6SGeorge Wilson 		 */
4909dcbf3bd6SGeorge Wilson 		if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
4910dcbf3bd6SGeorge Wilson 			zio_flags |= ZIO_FLAG_RAW;
4911fa9e4066Sahrens 		}
4912fa9e4066Sahrens 
4913dcbf3bd6SGeorge Wilson 		if (*arc_flags & ARC_FLAG_PREFETCH)
4914dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
4915dcbf3bd6SGeorge Wilson 		if (*arc_flags & ARC_FLAG_L2CACHE)
4916dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
4917dcbf3bd6SGeorge Wilson 		if (BP_GET_LEVEL(bp) > 0)
4918dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_INDIRECT);
4919cf6106c8SMatthew Ahrens 		if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
4920dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_PREDICTIVE_PREFETCH);
492189c86e32SChris Williamson 		ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
49225614b00aSWilliam Gorrell 
4923fa9e4066Sahrens 		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
4924fa9e4066Sahrens 		acb->acb_done = done;
4925fa9e4066Sahrens 		acb->acb_private = private;
49265602294fSDan Kimmel 		acb->acb_compressed = compressed_read;
4927fa9e4066Sahrens 
4928dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
492989c86e32SChris Williamson 		hdr->b_l1hdr.b_acb = acb;
4930dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
4931fa9e4066Sahrens 
493289c86e32SChris Williamson 		if (HDR_HAS_L2HDR(hdr) &&
493389c86e32SChris Williamson 		    (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
493489c86e32SChris Williamson 			devw = hdr->b_l2hdr.b_dev->l2ad_writing;
493589c86e32SChris Williamson 			addr = hdr->b_l2hdr.b_daddr;
4936e14bb325SJeff Bonwick 			/*
4937e14bb325SJeff Bonwick 			 * Lock out device removal.
4938e14bb325SJeff Bonwick 			 */
4939e14bb325SJeff Bonwick 			if (vdev_is_dead(vd) ||
4940e14bb325SJeff Bonwick 			    !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
4941e14bb325SJeff Bonwick 				vd = NULL;
49423a737e0dSbrendan 		}
49433a737e0dSbrendan 
4944dcbf3bd6SGeorge Wilson 		if (priority == ZIO_PRIORITY_ASYNC_READ)
4945dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
4946dcbf3bd6SGeorge Wilson 		else
4947dcbf3bd6SGeorge Wilson 			arc_hdr_clear_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
4948dcbf3bd6SGeorge Wilson 
49495d7b4d43SMatthew Ahrens 		if (hash_lock != NULL)
49505d7b4d43SMatthew Ahrens 			mutex_exit(hash_lock);
49513a737e0dSbrendan 
49523e30c24aSWill Andrews 		/*
49533e30c24aSWill Andrews 		 * At this point, we have a level 1 cache miss.  Try again in
49543e30c24aSWill Andrews 		 * L2ARC if possible.
49553e30c24aSWill Andrews 		 */
4956dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, lsize);
4957dcbf3bd6SGeorge Wilson 
49585c28183bSBrendan Gregg - Sun Microsystems 		DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
4959dcbf3bd6SGeorge Wilson 		    uint64_t, lsize, zbookmark_phys_t *, zb);
496044cb6abcSbmc 		ARCSTAT_BUMP(arcstat_misses);
496189c86e32SChris Williamson 		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
496289c86e32SChris Williamson 		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
496344cb6abcSbmc 		    data, metadata, misses);
4964ea8dc4b6Seschrock 
49655a98e54bSBrendan Gregg - Sun Microsystems 		if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
4966fa94a07fSbrendan 			/*
4967fa94a07fSbrendan 			 * Read from the L2ARC if the following are true:
49683a737e0dSbrendan 			 * 1. The L2ARC vdev was previously cached.
49693a737e0dSbrendan 			 * 2. This buffer still has L2ARC metadata.
49703a737e0dSbrendan 			 * 3. This buffer isn't currently writing to the L2ARC.
49713a737e0dSbrendan 			 * 4. The L2ARC entry wasn't evicted, which may
49723a737e0dSbrendan 			 *    also have invalidated the vdev.
49735a98e54bSBrendan Gregg - Sun Microsystems 			 * 5. This isn't prefetch and l2arc_noprefetch is set.
4974fa94a07fSbrendan 			 */
497589c86e32SChris Williamson 			if (HDR_HAS_L2HDR(hdr) &&
49765a98e54bSBrendan Gregg - Sun Microsystems 			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
49775a98e54bSBrendan Gregg - Sun Microsystems 			    !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
4978fa94a07fSbrendan 				l2arc_read_callback_t *cb;
4979fa94a07fSbrendan 
4980c5904d13Seschrock 				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
4981c5904d13Seschrock 				ARCSTAT_BUMP(arcstat_l2_hits);
4982c5904d13Seschrock 
4983fa94a07fSbrendan 				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
4984fa94a07fSbrendan 				    KM_SLEEP);
4985dcbf3bd6SGeorge Wilson 				cb->l2rcb_hdr = hdr;
4986fa94a07fSbrendan 				cb->l2rcb_bp = *bp;
4987fa94a07fSbrendan 				cb->l2rcb_zb = *zb;
49883baa08fcSek 				cb->l2rcb_flags = zio_flags;
4989fa94a07fSbrendan 
4990d5285caeSGeorge Wilson 				ASSERT(addr >= VDEV_LABEL_START_SIZE &&
4991dcbf3bd6SGeorge Wilson 				    addr + lsize < vd->vdev_psize -
4992d5285caeSGeorge Wilson 				    VDEV_LABEL_END_SIZE);
4993d5285caeSGeorge Wilson 
4994fa94a07fSbrendan 				/*
4995e14bb325SJeff Bonwick 				 * l2arc read.  The SCL_L2ARC lock will be
4996e14bb325SJeff Bonwick 				 * released by l2arc_read_done().
4997aad02571SSaso Kiselkov 				 * Issue a null zio if the underlying buffer
4998aad02571SSaso Kiselkov 				 * was squashed to zero size by compression.
4999fa94a07fSbrendan 				 */
5000dcbf3bd6SGeorge Wilson 				ASSERT3U(HDR_GET_COMPRESS(hdr), !=,
5001dcbf3bd6SGeorge Wilson 				    ZIO_COMPRESS_EMPTY);
5002dcbf3bd6SGeorge Wilson 				rzio = zio_read_phys(pio, vd, addr,
5003dcbf3bd6SGeorge Wilson 				    size, hdr->b_l1hdr.b_pdata,
5004dcbf3bd6SGeorge Wilson 				    ZIO_CHECKSUM_OFF,
5005dcbf3bd6SGeorge Wilson 				    l2arc_read_done, cb, priority,
5006dcbf3bd6SGeorge Wilson 				    zio_flags | ZIO_FLAG_DONT_CACHE |
5007dcbf3bd6SGeorge Wilson 				    ZIO_FLAG_CANFAIL |
5008dcbf3bd6SGeorge Wilson 				    ZIO_FLAG_DONT_PROPAGATE |
5009dcbf3bd6SGeorge Wilson 				    ZIO_FLAG_DONT_RETRY, B_FALSE);
5010fa94a07fSbrendan 				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
5011fa94a07fSbrendan 				    zio_t *, rzio);
5012dcbf3bd6SGeorge Wilson 				ARCSTAT_INCR(arcstat_l2_read_bytes, size);
5013fa94a07fSbrendan 
50147adb730bSGeorge Wilson 				if (*arc_flags & ARC_FLAG_NOWAIT) {
50153a737e0dSbrendan 					zio_nowait(rzio);
50163a737e0dSbrendan 					return (0);
50173a737e0dSbrendan 				}
5018fa94a07fSbrendan 
50197adb730bSGeorge Wilson 				ASSERT(*arc_flags & ARC_FLAG_WAIT);
50203a737e0dSbrendan 				if (zio_wait(rzio) == 0)
50213a737e0dSbrendan 					return (0);
50223a737e0dSbrendan 
50233a737e0dSbrendan 				/* l2arc read error; goto zio_read() */
5024fa94a07fSbrendan 			} else {
5025fa94a07fSbrendan 				DTRACE_PROBE1(l2arc__miss,
5026fa94a07fSbrendan 				    arc_buf_hdr_t *, hdr);
5027fa94a07fSbrendan 				ARCSTAT_BUMP(arcstat_l2_misses);
5028fa94a07fSbrendan 				if (HDR_L2_WRITING(hdr))
5029fa94a07fSbrendan 					ARCSTAT_BUMP(arcstat_l2_rw_clash);
5030e14bb325SJeff Bonwick 				spa_config_exit(spa, SCL_L2ARC, vd);
5031fa94a07fSbrendan 			}
50325a98e54bSBrendan Gregg - Sun Microsystems 		} else {
503376a25fafSBill Moore 			if (vd != NULL)
503476a25fafSBill Moore 				spa_config_exit(spa, SCL_L2ARC, vd);
50355a98e54bSBrendan Gregg - Sun Microsystems 			if (l2arc_ndev != 0) {
50365a98e54bSBrendan Gregg - Sun Microsystems 				DTRACE_PROBE1(l2arc__miss,
50375a98e54bSBrendan Gregg - Sun Microsystems 				    arc_buf_hdr_t *, hdr);
50385a98e54bSBrendan Gregg - Sun Microsystems 				ARCSTAT_BUMP(arcstat_l2_misses);
50395a98e54bSBrendan Gregg - Sun Microsystems 			}
5040fa94a07fSbrendan 		}
5041c5904d13Seschrock 
5042dcbf3bd6SGeorge Wilson 		rzio = zio_read(pio, spa, bp, hdr->b_l1hdr.b_pdata, size,
5043dcbf3bd6SGeorge Wilson 		    arc_read_done, hdr, priority, zio_flags, zb);
5044fa9e4066Sahrens 
50457adb730bSGeorge Wilson 		if (*arc_flags & ARC_FLAG_WAIT)
5046fa9e4066Sahrens 			return (zio_wait(rzio));
5047fa9e4066Sahrens 
50487adb730bSGeorge Wilson 		ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
5049fa9e4066Sahrens 		zio_nowait(rzio);
5050fa9e4066Sahrens 	}
5051fa9e4066Sahrens 	return (0);
5052fa9e4066Sahrens }
5053fa9e4066Sahrens 
50546e6d5868SMatthew Ahrens /*
50556e6d5868SMatthew Ahrens  * Notify the arc that a block was freed, and thus will never be used again.
50566e6d5868SMatthew Ahrens  */
50576e6d5868SMatthew Ahrens void
50586e6d5868SMatthew Ahrens arc_freed(spa_t *spa, const blkptr_t *bp)
50596e6d5868SMatthew Ahrens {
50606e6d5868SMatthew Ahrens 	arc_buf_hdr_t *hdr;
50616e6d5868SMatthew Ahrens 	kmutex_t *hash_lock;
50626e6d5868SMatthew Ahrens 	uint64_t guid = spa_load_guid(spa);
50636e6d5868SMatthew Ahrens 
50645d7b4d43SMatthew Ahrens 	ASSERT(!BP_IS_EMBEDDED(bp));
50655d7b4d43SMatthew Ahrens 
50665d7b4d43SMatthew Ahrens 	hdr = buf_hash_find(guid, bp, &hash_lock);
50676e6d5868SMatthew Ahrens 	if (hdr == NULL)
50686e6d5868SMatthew Ahrens 		return;
50696e6d5868SMatthew Ahrens 
5070dcbf3bd6SGeorge Wilson 	/*
5071dcbf3bd6SGeorge Wilson 	 * We might be trying to free a block that is still doing I/O
5072dcbf3bd6SGeorge Wilson 	 * (i.e. prefetch) or has a reference (i.e. a dedup-ed,
5073dcbf3bd6SGeorge Wilson 	 * dmu_sync-ed block). If this block is being prefetched, then it
5074dcbf3bd6SGeorge Wilson 	 * would still have the ARC_FLAG_IO_IN_PROGRESS flag set on the hdr
5075dcbf3bd6SGeorge Wilson 	 * until the I/O completes. A block may also have a reference if it is
5076dcbf3bd6SGeorge Wilson 	 * part of a dedup-ed, dmu_synced write. The dmu_sync() function would
5077dcbf3bd6SGeorge Wilson 	 * have written the new block to its final resting place on disk but
5078dcbf3bd6SGeorge Wilson 	 * without the dedup flag set. This would have left the hdr in the MRU
5079dcbf3bd6SGeorge Wilson 	 * state and discoverable. When the txg finally syncs it detects that
5080dcbf3bd6SGeorge Wilson 	 * the block was overridden in open context and issues an override I/O.
5081dcbf3bd6SGeorge Wilson 	 * Since this is a dedup block, the override I/O will determine if the
5082dcbf3bd6SGeorge Wilson 	 * block is already in the DDT. If so, then it will replace the io_bp
5083dcbf3bd6SGeorge Wilson 	 * with the bp from the DDT and allow the I/O to finish. When the I/O
5084dcbf3bd6SGeorge Wilson 	 * reaches the done callback, dbuf_write_override_done, it will
5085dcbf3bd6SGeorge Wilson 	 * check to see if the io_bp and io_bp_override are identical.
5086dcbf3bd6SGeorge Wilson 	 * If they are not, then it indicates that the bp was replaced with
5087dcbf3bd6SGeorge Wilson 	 * the bp in the DDT and the override bp is freed. This allows
5088dcbf3bd6SGeorge Wilson 	 * us to arrive here with a reference on a block that is being
5089dcbf3bd6SGeorge Wilson 	 * freed. So if we have an I/O in progress, or a reference to
5090dcbf3bd6SGeorge Wilson 	 * this hdr, then we don't destroy the hdr.
5091dcbf3bd6SGeorge Wilson 	 */
5092dcbf3bd6SGeorge Wilson 	if (!HDR_HAS_L1HDR(hdr) || (!HDR_IO_IN_PROGRESS(hdr) &&
5093dcbf3bd6SGeorge Wilson 	    refcount_is_zero(&hdr->b_l1hdr.b_refcnt))) {
5094dcbf3bd6SGeorge Wilson 		arc_change_state(arc_anon, hdr, hash_lock);
5095dcbf3bd6SGeorge Wilson 		arc_hdr_destroy(hdr);
50966e6d5868SMatthew Ahrens 		mutex_exit(hash_lock);
5097bbfa8ea8SMatthew Ahrens 	} else {
5098dcbf3bd6SGeorge Wilson 		mutex_exit(hash_lock);
5099ea8dc4b6Seschrock 	}
5100dd6ef538Smaybee 
5101ea8dc4b6Seschrock }
5102ea8dc4b6Seschrock 
5103fa9e4066Sahrens /*
51043e30c24aSWill Andrews  * Release this buffer from the cache, making it an anonymous buffer.  This
51053e30c24aSWill Andrews  * must be done after a read and prior to modifying the buffer contents.
5106fa9e4066Sahrens  * If the buffer has more than one reference, we must make
5107088f3894Sahrens  * a new hdr for the buffer.
5108fa9e4066Sahrens  */
5109fa9e4066Sahrens void
5110fa9e4066Sahrens arc_release(arc_buf_t *buf, void *tag)
5111fa9e4066Sahrens {
511289c86e32SChris Williamson 	arc_buf_hdr_t *hdr = buf->b_hdr;
5113fa9e4066Sahrens 
51143f9d6ad7SLin Ling 	/*
51153f9d6ad7SLin Ling 	 * It would be nice to assert that if it's DMU metadata (level >
51163f9d6ad7SLin Ling 	 * 0 || it's the dnode file), then it must be syncing context.
51173f9d6ad7SLin Ling 	 * But we don't know that information at this level.
51183f9d6ad7SLin Ling 	 */
51193f9d6ad7SLin Ling 
51203f9d6ad7SLin Ling 	mutex_enter(&buf->b_evict_lock);
51216f83844dSMark Maybee 
5122244781f1SPrakash Surya 	ASSERT(HDR_HAS_L1HDR(hdr));
5123244781f1SPrakash Surya 
512489c86e32SChris Williamson 	/*
512589c86e32SChris Williamson 	 * We don't grab the hash lock prior to this check, because if
512689c86e32SChris Williamson 	 * the buffer's header is in the arc_anon state, it won't be
512789c86e32SChris Williamson 	 * linked into the hash table.
512889c86e32SChris Williamson 	 */
512989c86e32SChris Williamson 	if (hdr->b_l1hdr.b_state == arc_anon) {
513089c86e32SChris Williamson 		mutex_exit(&buf->b_evict_lock);
513189c86e32SChris Williamson 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
513289c86e32SChris Williamson 		ASSERT(!HDR_IN_HASH_TABLE(hdr));
513389c86e32SChris Williamson 		ASSERT(!HDR_HAS_L2HDR(hdr));
5134dcbf3bd6SGeorge Wilson 		ASSERT(HDR_EMPTY(hdr));
5135fa9e4066Sahrens 
5136dcbf3bd6SGeorge Wilson 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
513789c86e32SChris Williamson 		ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
513889c86e32SChris Williamson 		ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
513989c86e32SChris Williamson 
514089c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = 0;
5141dcbf3bd6SGeorge Wilson 
5142dcbf3bd6SGeorge Wilson 		/*
5143dcbf3bd6SGeorge Wilson 		 * If the buf is being overridden then it may already
5144dcbf3bd6SGeorge Wilson 		 * have a hdr that is not empty.
5145dcbf3bd6SGeorge Wilson 		 */
5146dcbf3bd6SGeorge Wilson 		buf_discard_identity(hdr);
514789c86e32SChris Williamson 		arc_buf_thaw(buf);
514889c86e32SChris Williamson 
514989c86e32SChris Williamson 		return;
5150fa9e4066Sahrens 	}
5151fa9e4066Sahrens 
515289c86e32SChris Williamson 	kmutex_t *hash_lock = HDR_LOCK(hdr);
515389c86e32SChris Williamson 	mutex_enter(hash_lock);
515489c86e32SChris Williamson 
515589c86e32SChris Williamson 	/*
515689c86e32SChris Williamson 	 * This assignment is only valid as long as the hash_lock is
515789c86e32SChris Williamson 	 * held, we must be careful not to reference state or the
515889c86e32SChris Williamson 	 * b_state field after dropping the lock.
515989c86e32SChris Williamson 	 */
516089c86e32SChris Williamson 	arc_state_t *state = hdr->b_l1hdr.b_state;
516189c86e32SChris Williamson 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
516289c86e32SChris Williamson 	ASSERT3P(state, !=, arc_anon);
516389c86e32SChris Williamson 
516489c86e32SChris Williamson 	/* this buffer is not on any list */
51655602294fSDan Kimmel 	ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), >, 0);
516689c86e32SChris Williamson 
516789c86e32SChris Williamson 	if (HDR_HAS_L2HDR(hdr)) {
516889c86e32SChris Williamson 		mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
5169244781f1SPrakash Surya 
5170244781f1SPrakash Surya 		/*
5171a52fc310SPrakash Surya 		 * We have to recheck this conditional again now that
5172a52fc310SPrakash Surya 		 * we're holding the l2ad_mtx to prevent a race with
5173a52fc310SPrakash Surya 		 * another thread which might be concurrently calling
5174a52fc310SPrakash Surya 		 * l2arc_evict(). In that case, l2arc_evict() might have
5175a52fc310SPrakash Surya 		 * destroyed the header's L2 portion as we were waiting
5176a52fc310SPrakash Surya 		 * to acquire the l2ad_mtx.
5177244781f1SPrakash Surya 		 */
5178a52fc310SPrakash Surya 		if (HDR_HAS_L2HDR(hdr))
5179a52fc310SPrakash Surya 			arc_hdr_l2hdr_destroy(hdr);
5180244781f1SPrakash Surya 
518189c86e32SChris Williamson 		mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
51826f83844dSMark Maybee 	}
51836f83844dSMark Maybee 
5184ea8dc4b6Seschrock 	/*
5185ea8dc4b6Seschrock 	 * Do we have more than one buf?
5186ea8dc4b6Seschrock 	 */
5187dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_bufcnt > 1) {
5188fa9e4066Sahrens 		arc_buf_hdr_t *nhdr;
5189ac05c741SMark Maybee 		uint64_t spa = hdr->b_spa;
5190dcbf3bd6SGeorge Wilson 		uint64_t psize = HDR_GET_PSIZE(hdr);
5191dcbf3bd6SGeorge Wilson 		uint64_t lsize = HDR_GET_LSIZE(hdr);
5192dcbf3bd6SGeorge Wilson 		enum zio_compress compress = HDR_GET_COMPRESS(hdr);
519389c86e32SChris Williamson 		arc_buf_contents_t type = arc_buf_type(hdr);
5194dcbf3bd6SGeorge Wilson 		VERIFY3U(hdr->b_type, ==, type);
5195fa9e4066Sahrens 
519689c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
5197dcbf3bd6SGeorge Wilson 		(void) remove_reference(hdr, hash_lock, tag);
5198dcbf3bd6SGeorge Wilson 
51995602294fSDan Kimmel 		if (arc_buf_is_shared(buf) && !ARC_BUF_COMPRESSED(buf)) {
5200dcbf3bd6SGeorge Wilson 			ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
5201dcbf3bd6SGeorge Wilson 			ASSERT(ARC_BUF_LAST(buf));
5202dcbf3bd6SGeorge Wilson 		}
5203dcbf3bd6SGeorge Wilson 
5204fa9e4066Sahrens 		/*
52053f9d6ad7SLin Ling 		 * Pull the data off of this hdr and attach it to
5206dcbf3bd6SGeorge Wilson 		 * a new anonymous hdr. Also find the last buffer
5207dcbf3bd6SGeorge Wilson 		 * in the hdr's buffer list.
5208fa9e4066Sahrens 		 */
52095602294fSDan Kimmel 		arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
5210dcbf3bd6SGeorge Wilson 		ASSERT3P(lastbuf, !=, NULL);
5211dcbf3bd6SGeorge Wilson 
5212dcbf3bd6SGeorge Wilson 		/*
5213dcbf3bd6SGeorge Wilson 		 * If the current arc_buf_t and the hdr are sharing their data
52145602294fSDan Kimmel 		 * buffer, then we must stop sharing that block.
5215dcbf3bd6SGeorge Wilson 		 */
5216dcbf3bd6SGeorge Wilson 		if (arc_buf_is_shared(buf)) {
5217dcbf3bd6SGeorge Wilson 			VERIFY(!arc_buf_is_shared(lastbuf));
5218ea8dc4b6Seschrock 
5219dcbf3bd6SGeorge Wilson 			/*
5220dcbf3bd6SGeorge Wilson 			 * First, sever the block sharing relationship between
52215602294fSDan Kimmel 			 * buf and the arc_buf_hdr_t.
5222dcbf3bd6SGeorge Wilson 			 */
5223dcbf3bd6SGeorge Wilson 			arc_unshare_buf(hdr, buf);
52245602294fSDan Kimmel 
52255602294fSDan Kimmel 			/*
52265602294fSDan Kimmel 			 * Now we need to recreate the hdr's b_pdata. Since we
52275602294fSDan Kimmel 			 * have lastbuf handy, we try to share with it, but if
52285602294fSDan Kimmel 			 * we can't then we allocate a new b_pdata and copy the
52295602294fSDan Kimmel 			 * data from buf into it.
52305602294fSDan Kimmel 			 */
52315602294fSDan Kimmel 			if (arc_can_share(hdr, lastbuf)) {
52325602294fSDan Kimmel 				arc_share_buf(hdr, lastbuf);
52335602294fSDan Kimmel 			} else {
52345602294fSDan Kimmel 				arc_hdr_alloc_pdata(hdr);
52355602294fSDan Kimmel 				bcopy(buf->b_data, hdr->b_l1hdr.b_pdata, psize);
52365602294fSDan Kimmel 			}
5237dcbf3bd6SGeorge Wilson 			VERIFY3P(lastbuf->b_data, !=, NULL);
5238dcbf3bd6SGeorge Wilson 		} else if (HDR_SHARED_DATA(hdr)) {
52395602294fSDan Kimmel 			/*
52405602294fSDan Kimmel 			 * Uncompressed shared buffers are always at the end
52415602294fSDan Kimmel 			 * of the list. Compressed buffers don't have the
52425602294fSDan Kimmel 			 * same requirements. This makes it hard to
52435602294fSDan Kimmel 			 * simply assert that the lastbuf is shared so
52445602294fSDan Kimmel 			 * we rely on the hdr's compression flags to determine
52455602294fSDan Kimmel 			 * if we have a compressed, shared buffer.
52465602294fSDan Kimmel 			 */
52475602294fSDan Kimmel 			ASSERT(arc_buf_is_shared(lastbuf) ||
52485602294fSDan Kimmel 			    HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
52495602294fSDan Kimmel 			ASSERT(!ARC_BUF_SHARED(buf));
5250dcbf3bd6SGeorge Wilson 		}
5251dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
525289c86e32SChris Williamson 		ASSERT3P(state, !=, arc_l2c_only);
52532fd872a7SPrakash Surya 
5254dcbf3bd6SGeorge Wilson 		(void) refcount_remove_many(&state->arcs_size,
52555602294fSDan Kimmel 		    arc_buf_size(buf), buf);
52562fd872a7SPrakash Surya 
525789c86e32SChris Williamson 		if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
525889c86e32SChris Williamson 			ASSERT3P(state, !=, arc_l2c_only);
5259dcbf3bd6SGeorge Wilson 			(void) refcount_remove_many(&state->arcs_esize[type],
52605602294fSDan Kimmel 			    arc_buf_size(buf), buf);
5261ea8dc4b6Seschrock 		}
52629253d63dSGeorge Wilson 
5263dcbf3bd6SGeorge Wilson 		hdr->b_l1hdr.b_bufcnt -= 1;
5264c717a561Smaybee 		arc_cksum_verify(buf);
5265cd1c8b85SMatthew Ahrens 		arc_buf_unwatch(buf);
5266ea8dc4b6Seschrock 
5267fa9e4066Sahrens 		mutex_exit(hash_lock);
5268fa9e4066Sahrens 
5269dcbf3bd6SGeorge Wilson 		/*
5270dcbf3bd6SGeorge Wilson 		 * Allocate a new hdr. The new hdr will contain a b_pdata
5271dcbf3bd6SGeorge Wilson 		 * buffer which will be freed in arc_write().
5272dcbf3bd6SGeorge Wilson 		 */
5273dcbf3bd6SGeorge Wilson 		nhdr = arc_hdr_alloc(spa, psize, lsize, compress, type);
5274dcbf3bd6SGeorge Wilson 		ASSERT3P(nhdr->b_l1hdr.b_buf, ==, NULL);
5275dcbf3bd6SGeorge Wilson 		ASSERT0(nhdr->b_l1hdr.b_bufcnt);
5276dcbf3bd6SGeorge Wilson 		ASSERT0(refcount_count(&nhdr->b_l1hdr.b_refcnt));
5277dcbf3bd6SGeorge Wilson 		VERIFY3U(nhdr->b_type, ==, type);
5278dcbf3bd6SGeorge Wilson 		ASSERT(!HDR_SHARED_DATA(nhdr));
527989c86e32SChris Williamson 
528089c86e32SChris Williamson 		nhdr->b_l1hdr.b_buf = buf;
5281dcbf3bd6SGeorge Wilson 		nhdr->b_l1hdr.b_bufcnt = 1;
528289c86e32SChris Williamson 		(void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
5283af2c4821Smaybee 		buf->b_hdr = nhdr;
5284dcbf3bd6SGeorge Wilson 
52853f9d6ad7SLin Ling 		mutex_exit(&buf->b_evict_lock);
5286dcbf3bd6SGeorge Wilson 		(void) refcount_add_many(&arc_anon->arcs_size,
52875602294fSDan Kimmel 		    arc_buf_size(buf), buf);
5288fa9e4066Sahrens 	} else {
52893f9d6ad7SLin Ling 		mutex_exit(&buf->b_evict_lock);
529089c86e32SChris Williamson 		ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
5291244781f1SPrakash Surya 		/* protected by hash lock, or hdr is on arc_anon */
5292244781f1SPrakash Surya 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
5293fa9e4066Sahrens 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
529489c86e32SChris Williamson 		arc_change_state(arc_anon, hdr, hash_lock);
529589c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = 0;
529689c86e32SChris Williamson 		mutex_exit(hash_lock);
5297fa94a07fSbrendan 
52983f9d6ad7SLin Ling 		buf_discard_identity(hdr);
5299c717a561Smaybee 		arc_buf_thaw(buf);
5300fa9e4066Sahrens 	}
5301fa9e4066Sahrens }
5302fa9e4066Sahrens 
5303fa9e4066Sahrens int
5304fa9e4066Sahrens arc_released(arc_buf_t *buf)
5305fa9e4066Sahrens {
53066f83844dSMark Maybee 	int released;
53076f83844dSMark Maybee 
53083f9d6ad7SLin Ling 	mutex_enter(&buf->b_evict_lock);
530989c86e32SChris Williamson 	released = (buf->b_data != NULL &&
531089c86e32SChris Williamson 	    buf->b_hdr->b_l1hdr.b_state == arc_anon);
53113f9d6ad7SLin Ling 	mutex_exit(&buf->b_evict_lock);
53126f83844dSMark Maybee 	return (released);
5313ea8dc4b6Seschrock }
5314ea8dc4b6Seschrock 
5315ea8dc4b6Seschrock #ifdef ZFS_DEBUG
5316ea8dc4b6Seschrock int
5317ea8dc4b6Seschrock arc_referenced(arc_buf_t *buf)
5318ea8dc4b6Seschrock {
53196f83844dSMark Maybee 	int referenced;
53206f83844dSMark Maybee 
53213f9d6ad7SLin Ling 	mutex_enter(&buf->b_evict_lock);
532289c86e32SChris Williamson 	referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
53233f9d6ad7SLin Ling 	mutex_exit(&buf->b_evict_lock);
53246f83844dSMark Maybee 	return (referenced);
5325ea8dc4b6Seschrock }
5326ea8dc4b6Seschrock #endif
5327ea8dc4b6Seschrock 
5328c717a561Smaybee static void
5329c717a561Smaybee arc_write_ready(zio_t *zio)
5330c717a561Smaybee {
5331c717a561Smaybee 	arc_write_callback_t *callback = zio->io_private;
5332c717a561Smaybee 	arc_buf_t *buf = callback->awcb_buf;
53330a4e9518Sgw 	arc_buf_hdr_t *hdr = buf->b_hdr;
5334dcbf3bd6SGeorge Wilson 	uint64_t psize = BP_IS_HOLE(zio->io_bp) ? 0 : BP_GET_PSIZE(zio->io_bp);
5335c717a561Smaybee 
533689c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
533789c86e32SChris Williamson 	ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
5338dcbf3bd6SGeorge Wilson 	ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
5339e14bb325SJeff Bonwick 
53400a4e9518Sgw 	/*
5341dcbf3bd6SGeorge Wilson 	 * If we're reexecuting this zio because the pool suspended, then
5342dcbf3bd6SGeorge Wilson 	 * cleanup any state that was previously set the first time the
53435602294fSDan Kimmel 	 * callback was invoked.
53440a4e9518Sgw 	 */
5345dcbf3bd6SGeorge Wilson 	if (zio->io_flags & ZIO_FLAG_REEXECUTED) {
5346dcbf3bd6SGeorge Wilson 		arc_cksum_free(hdr);
5347dcbf3bd6SGeorge Wilson 		arc_buf_unwatch(buf);
5348dcbf3bd6SGeorge Wilson 		if (hdr->b_l1hdr.b_pdata != NULL) {
5349dcbf3bd6SGeorge Wilson 			if (arc_buf_is_shared(buf)) {
5350dcbf3bd6SGeorge Wilson 				arc_unshare_buf(hdr, buf);
5351dcbf3bd6SGeorge Wilson 			} else {
5352dcbf3bd6SGeorge Wilson 				arc_hdr_free_pdata(hdr);
5353dcbf3bd6SGeorge Wilson 			}
53540a4e9518Sgw 		}
53550a4e9518Sgw 	}
5356dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
5357dcbf3bd6SGeorge Wilson 	ASSERT(!HDR_SHARED_DATA(hdr));
5358dcbf3bd6SGeorge Wilson 	ASSERT(!arc_buf_is_shared(buf));
5359dcbf3bd6SGeorge Wilson 
5360dcbf3bd6SGeorge Wilson 	callback->awcb_ready(zio, buf, callback->awcb_private);
5361dcbf3bd6SGeorge Wilson 
5362dcbf3bd6SGeorge Wilson 	if (HDR_IO_IN_PROGRESS(hdr))
5363dcbf3bd6SGeorge Wilson 		ASSERT(zio->io_flags & ZIO_FLAG_REEXECUTED);
5364dcbf3bd6SGeorge Wilson 
5365dcbf3bd6SGeorge Wilson 	arc_cksum_compute(buf);
5366dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5367dcbf3bd6SGeorge Wilson 
5368dcbf3bd6SGeorge Wilson 	enum zio_compress compress;
5369dcbf3bd6SGeorge Wilson 	if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
5370dcbf3bd6SGeorge Wilson 		compress = ZIO_COMPRESS_OFF;
5371dcbf3bd6SGeorge Wilson 	} else {
5372dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(zio->io_bp));
5373dcbf3bd6SGeorge Wilson 		compress = BP_GET_COMPRESS(zio->io_bp);
5374dcbf3bd6SGeorge Wilson 	}
5375dcbf3bd6SGeorge Wilson 	HDR_SET_PSIZE(hdr, psize);
5376dcbf3bd6SGeorge Wilson 	arc_hdr_set_compress(hdr, compress);
5377dcbf3bd6SGeorge Wilson 
5378dcbf3bd6SGeorge Wilson 	/*
5379dcbf3bd6SGeorge Wilson 	 * If the hdr is compressed, then copy the compressed
5380dcbf3bd6SGeorge Wilson 	 * zio contents into arc_buf_hdr_t. Otherwise, copy the original
5381dcbf3bd6SGeorge Wilson 	 * data buf into the hdr. Ideally, we would like to always copy the
5382dcbf3bd6SGeorge Wilson 	 * io_data into b_pdata but the user may have disabled compressed
5383dcbf3bd6SGeorge Wilson 	 * arc thus the on-disk block may or may not match what we maintain
5384dcbf3bd6SGeorge Wilson 	 * in the hdr's b_pdata field.
5385dcbf3bd6SGeorge Wilson 	 */
53865602294fSDan Kimmel 	if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
53875602294fSDan Kimmel 	    !ARC_BUF_COMPRESSED(buf)) {
53885602294fSDan Kimmel 		ASSERT3U(BP_GET_COMPRESS(zio->io_bp), !=, ZIO_COMPRESS_OFF);
5389dcbf3bd6SGeorge Wilson 		ASSERT3U(psize, >, 0);
5390dcbf3bd6SGeorge Wilson 		arc_hdr_alloc_pdata(hdr);
5391dcbf3bd6SGeorge Wilson 		bcopy(zio->io_data, hdr->b_l1hdr.b_pdata, psize);
5392dcbf3bd6SGeorge Wilson 	} else {
5393dcbf3bd6SGeorge Wilson 		ASSERT3P(buf->b_data, ==, zio->io_orig_data);
53945602294fSDan Kimmel 		ASSERT3U(zio->io_orig_size, ==, arc_buf_size(buf));
5395dcbf3bd6SGeorge Wilson 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
5396dcbf3bd6SGeorge Wilson 
5397dcbf3bd6SGeorge Wilson 		/*
5398dcbf3bd6SGeorge Wilson 		 * This hdr is not compressed so we're able to share
5399dcbf3bd6SGeorge Wilson 		 * the arc_buf_t data buffer with the hdr.
5400dcbf3bd6SGeorge Wilson 		 */
5401dcbf3bd6SGeorge Wilson 		arc_share_buf(hdr, buf);
54025602294fSDan Kimmel 		ASSERT0(bcmp(zio->io_orig_data, hdr->b_l1hdr.b_pdata,
5403dcbf3bd6SGeorge Wilson 		    HDR_GET_LSIZE(hdr)));
5404dcbf3bd6SGeorge Wilson 	}
5405dcbf3bd6SGeorge Wilson 	arc_hdr_verify(hdr, zio->io_bp);
5406c717a561Smaybee }
5407c717a561Smaybee 
54088df0bcf0SPaul Dagnelie static void
54098df0bcf0SPaul Dagnelie arc_write_children_ready(zio_t *zio)
54108df0bcf0SPaul Dagnelie {
54118df0bcf0SPaul Dagnelie 	arc_write_callback_t *callback = zio->io_private;
54128df0bcf0SPaul Dagnelie 	arc_buf_t *buf = callback->awcb_buf;
54138df0bcf0SPaul Dagnelie 
54148df0bcf0SPaul Dagnelie 	callback->awcb_children_ready(zio, buf, callback->awcb_private);
54158df0bcf0SPaul Dagnelie }
54168df0bcf0SPaul Dagnelie 
541769962b56SMatthew Ahrens /*
541869962b56SMatthew Ahrens  * The SPA calls this callback for each physical write that happens on behalf
541969962b56SMatthew Ahrens  * of a logical write.  See the comment in dbuf_write_physdone() for details.
542069962b56SMatthew Ahrens  */
542169962b56SMatthew Ahrens static void
542269962b56SMatthew Ahrens arc_write_physdone(zio_t *zio)
542369962b56SMatthew Ahrens {
542469962b56SMatthew Ahrens 	arc_write_callback_t *cb = zio->io_private;
542569962b56SMatthew Ahrens 	if (cb->awcb_physdone != NULL)
542669962b56SMatthew Ahrens 		cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
542769962b56SMatthew Ahrens }
542869962b56SMatthew Ahrens 
5429fa9e4066Sahrens static void
5430fa9e4066Sahrens arc_write_done(zio_t *zio)
5431fa9e4066Sahrens {
5432c717a561Smaybee 	arc_write_callback_t *callback = zio->io_private;
5433c717a561Smaybee 	arc_buf_t *buf = callback->awcb_buf;
5434c717a561Smaybee 	arc_buf_hdr_t *hdr = buf->b_hdr;
5435fa9e4066Sahrens 
5436dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5437b24ab676SJeff Bonwick 
5438b24ab676SJeff Bonwick 	if (zio->io_error == 0) {
5439dcbf3bd6SGeorge Wilson 		arc_hdr_verify(hdr, zio->io_bp);
5440dcbf3bd6SGeorge Wilson 
54415d7b4d43SMatthew Ahrens 		if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
544243466aaeSMax Grossman 			buf_discard_identity(hdr);
544343466aaeSMax Grossman 		} else {
544443466aaeSMax Grossman 			hdr->b_dva = *BP_IDENTITY(zio->io_bp);
544543466aaeSMax Grossman 			hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
544643466aaeSMax Grossman 		}
5447b24ab676SJeff Bonwick 	} else {
5448dcbf3bd6SGeorge Wilson 		ASSERT(HDR_EMPTY(hdr));
5449b24ab676SJeff Bonwick 	}
5450fa9e4066Sahrens 
5451ea8dc4b6Seschrock 	/*
54525d7b4d43SMatthew Ahrens 	 * If the block to be written was all-zero or compressed enough to be
54535d7b4d43SMatthew Ahrens 	 * embedded in the BP, no write was performed so there will be no
54545d7b4d43SMatthew Ahrens 	 * dva/birth/checksum.  The buffer must therefore remain anonymous
54555d7b4d43SMatthew Ahrens 	 * (and uncached).
5456ea8dc4b6Seschrock 	 */
5457dcbf3bd6SGeorge Wilson 	if (!HDR_EMPTY(hdr)) {
5458fa9e4066Sahrens 		arc_buf_hdr_t *exists;
5459fa9e4066Sahrens 		kmutex_t *hash_lock;
5460fa9e4066Sahrens 
54615602294fSDan Kimmel 		ASSERT3U(zio->io_error, ==, 0);
5462b24ab676SJeff Bonwick 
54636b4acc8bSahrens 		arc_cksum_verify(buf);
54646b4acc8bSahrens 
5465fa9e4066Sahrens 		exists = buf_hash_insert(hdr, &hash_lock);
546689c86e32SChris Williamson 		if (exists != NULL) {
5467fa9e4066Sahrens 			/*
5468fa9e4066Sahrens 			 * This can only happen if we overwrite for
5469fa9e4066Sahrens 			 * sync-to-convergence, because we remove
5470fa9e4066Sahrens 			 * buffers from the hash table when we arc_free().
5471fa9e4066Sahrens 			 */
5472b24ab676SJeff Bonwick 			if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
5473b24ab676SJeff Bonwick 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5474b24ab676SJeff Bonwick 					panic("bad overwrite, hdr=%p exists=%p",
5475b24ab676SJeff Bonwick 					    (void *)hdr, (void *)exists);
547689c86e32SChris Williamson 				ASSERT(refcount_is_zero(
547789c86e32SChris Williamson 				    &exists->b_l1hdr.b_refcnt));
5478b24ab676SJeff Bonwick 				arc_change_state(arc_anon, exists, hash_lock);
5479b24ab676SJeff Bonwick 				mutex_exit(hash_lock);
5480b24ab676SJeff Bonwick 				arc_hdr_destroy(exists);
5481b24ab676SJeff Bonwick 				exists = buf_hash_insert(hdr, &hash_lock);
5482b24ab676SJeff Bonwick 				ASSERT3P(exists, ==, NULL);
548380901aeaSGeorge Wilson 			} else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
548480901aeaSGeorge Wilson 				/* nopwrite */
548580901aeaSGeorge Wilson 				ASSERT(zio->io_prop.zp_nopwrite);
548680901aeaSGeorge Wilson 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
548780901aeaSGeorge Wilson 					panic("bad nopwrite, hdr=%p exists=%p",
548880901aeaSGeorge Wilson 					    (void *)hdr, (void *)exists);
5489b24ab676SJeff Bonwick 			} else {
5490b24ab676SJeff Bonwick 				/* Dedup */
5491dcbf3bd6SGeorge Wilson 				ASSERT(hdr->b_l1hdr.b_bufcnt == 1);
549289c86e32SChris Williamson 				ASSERT(hdr->b_l1hdr.b_state == arc_anon);
5493b24ab676SJeff Bonwick 				ASSERT(BP_GET_DEDUP(zio->io_bp));
5494b24ab676SJeff Bonwick 				ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
5495ae46e4c7SMatthew Ahrens 			}
5496fa9e4066Sahrens 		}
5497dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5498088f3894Sahrens 		/* if it's not anon, we are doing a scrub */
549989c86e32SChris Williamson 		if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
5500088f3894Sahrens 			arc_access(hdr, hash_lock);
550144eda4d7Smaybee 		mutex_exit(hash_lock);
5502ea8dc4b6Seschrock 	} else {
5503dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5504fa9e4066Sahrens 	}
5505ea8dc4b6Seschrock 
550689c86e32SChris Williamson 	ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5507b24ab676SJeff Bonwick 	callback->awcb_done(zio, buf, callback->awcb_private);
5508fa9e4066Sahrens 
5509c717a561Smaybee 	kmem_free(callback, sizeof (arc_write_callback_t));
5510fa9e4066Sahrens }
5511fa9e4066Sahrens 
5512c717a561Smaybee zio_t *
5513dcbf3bd6SGeorge Wilson arc_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
5514dcbf3bd6SGeorge Wilson     boolean_t l2arc, const zio_prop_t *zp, arc_done_func_t *ready,
55158df0bcf0SPaul Dagnelie     arc_done_func_t *children_ready, arc_done_func_t *physdone,
551669962b56SMatthew Ahrens     arc_done_func_t *done, void *private, zio_priority_t priority,
55177802d7bfSMatthew Ahrens     int zio_flags, const zbookmark_phys_t *zb)
5518fa9e4066Sahrens {
5519fa9e4066Sahrens 	arc_buf_hdr_t *hdr = buf->b_hdr;
5520c717a561Smaybee 	arc_write_callback_t *callback;
5521e14bb325SJeff Bonwick 	zio_t *zio;
5522fa9e4066Sahrens 
5523dcbf3bd6SGeorge Wilson 	ASSERT3P(ready, !=, NULL);
5524dcbf3bd6SGeorge Wilson 	ASSERT3P(done, !=, NULL);
5525fa9e4066Sahrens 	ASSERT(!HDR_IO_ERROR(hdr));
552689c86e32SChris Williamson 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5527dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5528dcbf3bd6SGeorge Wilson 	ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
55293baa08fcSek 	if (l2arc)
5530dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
55315602294fSDan Kimmel 	if (ARC_BUF_COMPRESSED(buf)) {
55325602294fSDan Kimmel 		ASSERT3U(zp->zp_compress, !=, ZIO_COMPRESS_OFF);
55335602294fSDan Kimmel 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, arc_buf_size(buf));
55345602294fSDan Kimmel 		zio_flags |= ZIO_FLAG_RAW;
55355602294fSDan Kimmel 	}
5536c717a561Smaybee 	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
5537c717a561Smaybee 	callback->awcb_ready = ready;
55388df0bcf0SPaul Dagnelie 	callback->awcb_children_ready = children_ready;
553969962b56SMatthew Ahrens 	callback->awcb_physdone = physdone;
5540c717a561Smaybee 	callback->awcb_done = done;
5541c717a561Smaybee 	callback->awcb_private = private;
5542c717a561Smaybee 	callback->awcb_buf = buf;
5543088f3894Sahrens 
5544dcbf3bd6SGeorge Wilson 	/*
5545dcbf3bd6SGeorge Wilson 	 * The hdr's b_pdata is now stale, free it now. A new data block
5546dcbf3bd6SGeorge Wilson 	 * will be allocated when the zio pipeline calls arc_write_ready().
5547dcbf3bd6SGeorge Wilson 	 */
5548dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_pdata != NULL) {
5549dcbf3bd6SGeorge Wilson 		/*
5550dcbf3bd6SGeorge Wilson 		 * If the buf is currently sharing the data block with
5551dcbf3bd6SGeorge Wilson 		 * the hdr then we need to break that relationship here.
5552dcbf3bd6SGeorge Wilson 		 * The hdr will remain with a NULL data pointer and the
5553dcbf3bd6SGeorge Wilson 		 * buf will take sole ownership of the block.
5554dcbf3bd6SGeorge Wilson 		 */
5555dcbf3bd6SGeorge Wilson 		if (arc_buf_is_shared(buf)) {
5556dcbf3bd6SGeorge Wilson 			arc_unshare_buf(hdr, buf);
5557dcbf3bd6SGeorge Wilson 		} else {
5558dcbf3bd6SGeorge Wilson 			arc_hdr_free_pdata(hdr);
5559dcbf3bd6SGeorge Wilson 		}
5560dcbf3bd6SGeorge Wilson 		VERIFY3P(buf->b_data, !=, NULL);
5561dcbf3bd6SGeorge Wilson 		arc_hdr_set_compress(hdr, ZIO_COMPRESS_OFF);
5562dcbf3bd6SGeorge Wilson 	}
5563dcbf3bd6SGeorge Wilson 	ASSERT(!arc_buf_is_shared(buf));
5564dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
5565dcbf3bd6SGeorge Wilson 
55665602294fSDan Kimmel 	zio = zio_write(pio, spa, txg, bp, buf->b_data,
55675602294fSDan Kimmel 	    HDR_GET_LSIZE(hdr), arc_buf_size(buf), zp, arc_write_ready,
55688df0bcf0SPaul Dagnelie 	    (children_ready != NULL) ? arc_write_children_ready : NULL,
55698df0bcf0SPaul Dagnelie 	    arc_write_physdone, arc_write_done, callback,
557069962b56SMatthew Ahrens 	    priority, zio_flags, zb);
5571fa9e4066Sahrens 
5572c717a561Smaybee 	return (zio);
5573fa9e4066Sahrens }
5574fa9e4066Sahrens 
55751ab7f2deSmaybee static int
557669962b56SMatthew Ahrens arc_memory_throttle(uint64_t reserve, uint64_t txg)
55771ab7f2deSmaybee {
55781ab7f2deSmaybee #ifdef _KERNEL
55791ab7f2deSmaybee 	uint64_t available_memory = ptob(freemem);
55801ab7f2deSmaybee 	static uint64_t page_load = 0;
55811ab7f2deSmaybee 	static uint64_t last_txg = 0;
55821ab7f2deSmaybee 
55831ab7f2deSmaybee #if defined(__i386)
55841ab7f2deSmaybee 	available_memory =
55851ab7f2deSmaybee 	    MIN(available_memory, vmem_size(heap_arena, VMEM_FREE));
55861ab7f2deSmaybee #endif
558769962b56SMatthew Ahrens 
558869962b56SMatthew Ahrens 	if (freemem > physmem * arc_lotsfree_percent / 100)
55891ab7f2deSmaybee 		return (0);
55901ab7f2deSmaybee 
55911ab7f2deSmaybee 	if (txg > last_txg) {
55921ab7f2deSmaybee 		last_txg = txg;
55931ab7f2deSmaybee 		page_load = 0;
55941ab7f2deSmaybee 	}
55951ab7f2deSmaybee 	/*
55961ab7f2deSmaybee 	 * If we are in pageout, we know that memory is already tight,
55971ab7f2deSmaybee 	 * the arc is already going to be evicting, so we just want to
55981ab7f2deSmaybee 	 * continue to let page writes occur as quickly as possible.
55991ab7f2deSmaybee 	 */
56001ab7f2deSmaybee 	if (curproc == proc_pageout) {
56011ab7f2deSmaybee 		if (page_load > MAX(ptob(minfree), available_memory) / 4)
5602be6fd75aSMatthew Ahrens 			return (SET_ERROR(ERESTART));
56031ab7f2deSmaybee 		/* Note: reserve is inflated, so we deflate */
56041ab7f2deSmaybee 		page_load += reserve / 8;
56051ab7f2deSmaybee 		return (0);
56061ab7f2deSmaybee 	} else if (page_load > 0 && arc_reclaim_needed()) {
56071ab7f2deSmaybee 		/* memory is low, delay before restarting */
56081ab7f2deSmaybee 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
5609be6fd75aSMatthew Ahrens 		return (SET_ERROR(EAGAIN));
56101ab7f2deSmaybee 	}
56111ab7f2deSmaybee 	page_load = 0;
56121ab7f2deSmaybee #endif
56131ab7f2deSmaybee 	return (0);
56141ab7f2deSmaybee }
56151ab7f2deSmaybee 
5616fa9e4066Sahrens void
56171ab7f2deSmaybee arc_tempreserve_clear(uint64_t reserve)
5618fa9e4066Sahrens {
56191ab7f2deSmaybee 	atomic_add_64(&arc_tempreserve, -reserve);
5620fa9e4066Sahrens 	ASSERT((int64_t)arc_tempreserve >= 0);
5621fa9e4066Sahrens }
5622fa9e4066Sahrens 
5623fa9e4066Sahrens int
56241ab7f2deSmaybee arc_tempreserve_space(uint64_t reserve, uint64_t txg)
5625fa9e4066Sahrens {
56261ab7f2deSmaybee 	int error;
56272fdbea25SAleksandr Guzovskiy 	uint64_t anon_size;
56281ab7f2deSmaybee 
56291ab7f2deSmaybee 	if (reserve > arc_c/4 && !arc_no_grow)
56301ab7f2deSmaybee 		arc_c = MIN(arc_c_max, reserve * 4);
56311ab7f2deSmaybee 	if (reserve > arc_c)
5632be6fd75aSMatthew Ahrens 		return (SET_ERROR(ENOMEM));
5633112fe045Smaybee 
56342fdbea25SAleksandr Guzovskiy 	/*
56352fdbea25SAleksandr Guzovskiy 	 * Don't count loaned bufs as in flight dirty data to prevent long
56362fdbea25SAleksandr Guzovskiy 	 * network delays from blocking transactions that are ready to be
56372fdbea25SAleksandr Guzovskiy 	 * assigned to a txg.
56382fdbea25SAleksandr Guzovskiy 	 */
56395602294fSDan Kimmel 
56405602294fSDan Kimmel 	/* assert that it has not wrapped around */
56415602294fSDan Kimmel 	ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
56425602294fSDan Kimmel 
56432fd872a7SPrakash Surya 	anon_size = MAX((int64_t)(refcount_count(&arc_anon->arcs_size) -
56442fd872a7SPrakash Surya 	    arc_loaned_bytes), 0);
56452fdbea25SAleksandr Guzovskiy 
56461ab7f2deSmaybee 	/*
56471ab7f2deSmaybee 	 * Writes will, almost always, require additional memory allocations
5648f7170741SWill Andrews 	 * in order to compress/encrypt/etc the data.  We therefore need to
56491ab7f2deSmaybee 	 * make sure that there is sufficient available memory for this.
56501ab7f2deSmaybee 	 */
565169962b56SMatthew Ahrens 	error = arc_memory_throttle(reserve, txg);
565269962b56SMatthew Ahrens 	if (error != 0)
56531ab7f2deSmaybee 		return (error);
56541ab7f2deSmaybee 
5655fa9e4066Sahrens 	/*
5656112fe045Smaybee 	 * Throttle writes when the amount of dirty data in the cache
5657112fe045Smaybee 	 * gets too large.  We try to keep the cache less than half full
5658112fe045Smaybee 	 * of dirty blocks so that our sync times don't grow too large.
5659112fe045Smaybee 	 * Note: if two requests come in concurrently, we might let them
5660112fe045Smaybee 	 * both succeed, when one of them should fail.  Not a huge deal.
5661fa9e4066Sahrens 	 */
56622fdbea25SAleksandr Guzovskiy 
56632fdbea25SAleksandr Guzovskiy 	if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
56642fdbea25SAleksandr Guzovskiy 	    anon_size > arc_c / 4) {
5665dcbf3bd6SGeorge Wilson 		uint64_t meta_esize =
5666dcbf3bd6SGeorge Wilson 		    refcount_count(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
5667dcbf3bd6SGeorge Wilson 		uint64_t data_esize =
5668dcbf3bd6SGeorge Wilson 		    refcount_count(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
56690e8c6158Smaybee 		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
56700e8c6158Smaybee 		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
5671dcbf3bd6SGeorge Wilson 		    arc_tempreserve >> 10, meta_esize >> 10,
5672dcbf3bd6SGeorge Wilson 		    data_esize >> 10, reserve >> 10, arc_c >> 10);
5673be6fd75aSMatthew Ahrens 		return (SET_ERROR(ERESTART));
5674fa9e4066Sahrens 	}
56751ab7f2deSmaybee 	atomic_add_64(&arc_tempreserve, reserve);
5676fa9e4066Sahrens 	return (0);
5677fa9e4066Sahrens }
5678fa9e4066Sahrens 
56794076b1bfSPrakash Surya static void
56804076b1bfSPrakash Surya arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
56814076b1bfSPrakash Surya     kstat_named_t *evict_data, kstat_named_t *evict_metadata)
56824076b1bfSPrakash Surya {
56832fd872a7SPrakash Surya 	size->value.ui64 = refcount_count(&state->arcs_size);
5684dcbf3bd6SGeorge Wilson 	evict_data->value.ui64 =
5685dcbf3bd6SGeorge Wilson 	    refcount_count(&state->arcs_esize[ARC_BUFC_DATA]);
5686dcbf3bd6SGeorge Wilson 	evict_metadata->value.ui64 =
5687dcbf3bd6SGeorge Wilson 	    refcount_count(&state->arcs_esize[ARC_BUFC_METADATA]);
56884076b1bfSPrakash Surya }
56894076b1bfSPrakash Surya 
56904076b1bfSPrakash Surya static int
56914076b1bfSPrakash Surya arc_kstat_update(kstat_t *ksp, int rw)
56924076b1bfSPrakash Surya {
56934076b1bfSPrakash Surya 	arc_stats_t *as = ksp->ks_data;
56944076b1bfSPrakash Surya 
56954076b1bfSPrakash Surya 	if (rw == KSTAT_WRITE) {
56964076b1bfSPrakash Surya 		return (EACCES);
56974076b1bfSPrakash Surya 	} else {
56984076b1bfSPrakash Surya 		arc_kstat_update_state(arc_anon,
56994076b1bfSPrakash Surya 		    &as->arcstat_anon_size,
57004076b1bfSPrakash Surya 		    &as->arcstat_anon_evictable_data,
57014076b1bfSPrakash Surya 		    &as->arcstat_anon_evictable_metadata);
57024076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mru,
57034076b1bfSPrakash Surya 		    &as->arcstat_mru_size,
57044076b1bfSPrakash Surya 		    &as->arcstat_mru_evictable_data,
57054076b1bfSPrakash Surya 		    &as->arcstat_mru_evictable_metadata);
57064076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mru_ghost,
57074076b1bfSPrakash Surya 		    &as->arcstat_mru_ghost_size,
57084076b1bfSPrakash Surya 		    &as->arcstat_mru_ghost_evictable_data,
57094076b1bfSPrakash Surya 		    &as->arcstat_mru_ghost_evictable_metadata);
57104076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mfu,
57114076b1bfSPrakash Surya 		    &as->arcstat_mfu_size,
57124076b1bfSPrakash Surya 		    &as->arcstat_mfu_evictable_data,
57134076b1bfSPrakash Surya 		    &as->arcstat_mfu_evictable_metadata);
57144076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mfu_ghost,
57154076b1bfSPrakash Surya 		    &as->arcstat_mfu_ghost_size,
57164076b1bfSPrakash Surya 		    &as->arcstat_mfu_ghost_evictable_data,
57174076b1bfSPrakash Surya 		    &as->arcstat_mfu_ghost_evictable_metadata);
57184076b1bfSPrakash Surya 	}
57194076b1bfSPrakash Surya 
57204076b1bfSPrakash Surya 	return (0);
57214076b1bfSPrakash Surya }
57224076b1bfSPrakash Surya 
5723dcbf3bd6SGeorge Wilson /*
5724dcbf3bd6SGeorge Wilson  * This function *must* return indices evenly distributed between all
5725dcbf3bd6SGeorge Wilson  * sublists of the multilist. This is needed due to how the ARC eviction
5726dcbf3bd6SGeorge Wilson  * code is laid out; arc_evict_state() assumes ARC buffers are evenly
5727dcbf3bd6SGeorge Wilson  * distributed between all sublists and uses this assumption when
5728dcbf3bd6SGeorge Wilson  * deciding which sublist to evict from and how much to evict from it.
5729dcbf3bd6SGeorge Wilson  */
5730dcbf3bd6SGeorge Wilson unsigned int
5731dcbf3bd6SGeorge Wilson arc_state_multilist_index_func(multilist_t *ml, void *obj)
5732dcbf3bd6SGeorge Wilson {
5733dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = obj;
5734dcbf3bd6SGeorge Wilson 
5735dcbf3bd6SGeorge Wilson 	/*
5736dcbf3bd6SGeorge Wilson 	 * We rely on b_dva to generate evenly distributed index
5737dcbf3bd6SGeorge Wilson 	 * numbers using buf_hash below. So, as an added precaution,
5738dcbf3bd6SGeorge Wilson 	 * let's make sure we never add empty buffers to the arc lists.
5739dcbf3bd6SGeorge Wilson 	 */
5740dcbf3bd6SGeorge Wilson 	ASSERT(!HDR_EMPTY(hdr));
5741dcbf3bd6SGeorge Wilson 
5742dcbf3bd6SGeorge Wilson 	/*
5743dcbf3bd6SGeorge Wilson 	 * The assumption here, is the hash value for a given
5744dcbf3bd6SGeorge Wilson 	 * arc_buf_hdr_t will remain constant throughout it's lifetime
5745dcbf3bd6SGeorge Wilson 	 * (i.e. it's b_spa, b_dva, and b_birth fields don't change).
5746dcbf3bd6SGeorge Wilson 	 * Thus, we don't need to store the header's sublist index
5747dcbf3bd6SGeorge Wilson 	 * on insertion, as this index can be recalculated on removal.
5748dcbf3bd6SGeorge Wilson 	 *
5749dcbf3bd6SGeorge Wilson 	 * Also, the low order bits of the hash value are thought to be
5750dcbf3bd6SGeorge Wilson 	 * distributed evenly. Otherwise, in the case that the multilist
5751dcbf3bd6SGeorge Wilson 	 * has a power of two number of sublists, each sublists' usage
5752dcbf3bd6SGeorge Wilson 	 * would not be evenly distributed.
5753dcbf3bd6SGeorge Wilson 	 */
5754dcbf3bd6SGeorge Wilson 	return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
5755dcbf3bd6SGeorge Wilson 	    multilist_get_num_sublists(ml));
5756dcbf3bd6SGeorge Wilson }
5757dcbf3bd6SGeorge Wilson 
5758dcbf3bd6SGeorge Wilson static void
5759dcbf3bd6SGeorge Wilson arc_state_init(void)
5760dcbf3bd6SGeorge Wilson {
5761dcbf3bd6SGeorge Wilson 	arc_anon = &ARC_anon;
5762dcbf3bd6SGeorge Wilson 	arc_mru = &ARC_mru;
5763dcbf3bd6SGeorge Wilson 	arc_mru_ghost = &ARC_mru_ghost;
5764dcbf3bd6SGeorge Wilson 	arc_mfu = &ARC_mfu;
5765dcbf3bd6SGeorge Wilson 	arc_mfu_ghost = &ARC_mfu_ghost;
5766dcbf3bd6SGeorge Wilson 	arc_l2c_only = &ARC_l2c_only;
5767dcbf3bd6SGeorge Wilson 
5768*94c2d0ebSMatthew Ahrens 	arc_mru->arcs_list[ARC_BUFC_METADATA] =
5769*94c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
5770dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
577110fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
5772*94c2d0ebSMatthew Ahrens 	arc_mru->arcs_list[ARC_BUFC_DATA] =
5773*94c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
5774dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
577510fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
5776*94c2d0ebSMatthew Ahrens 	arc_mru_ghost->arcs_list[ARC_BUFC_METADATA] =
5777*94c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
5778dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
577910fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
5780*94c2d0ebSMatthew Ahrens 	arc_mru_ghost->arcs_list[ARC_BUFC_DATA] =
5781*94c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
5782dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
578310fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
5784*94c2d0ebSMatthew Ahrens 	arc_mfu->arcs_list[ARC_BUFC_METADATA] =
5785*94c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
5786dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
578710fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
5788*94c2d0ebSMatthew Ahrens 	arc_mfu->arcs_list[ARC_BUFC_DATA] =
5789*94c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
5790dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
579110fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
5792*94c2d0ebSMatthew Ahrens 	arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA] =
5793*94c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
5794dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
579510fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
5796*94c2d0ebSMatthew Ahrens 	arc_mfu_ghost->arcs_list[ARC_BUFC_DATA] =
5797*94c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
5798dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
579910fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
5800*94c2d0ebSMatthew Ahrens 	arc_l2c_only->arcs_list[ARC_BUFC_METADATA] =
5801*94c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
5802dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
580310fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
5804*94c2d0ebSMatthew Ahrens 	arc_l2c_only->arcs_list[ARC_BUFC_DATA] =
5805*94c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
5806dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
580710fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
5808dcbf3bd6SGeorge Wilson 
5809dcbf3bd6SGeorge Wilson 	refcount_create(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
5810dcbf3bd6SGeorge Wilson 	refcount_create(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
5811dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
5812dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
5813dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
5814dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
5815dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
5816dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
5817dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
5818dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
5819dcbf3bd6SGeorge Wilson 	refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
5820dcbf3bd6SGeorge Wilson 	refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
5821dcbf3bd6SGeorge Wilson 
5822dcbf3bd6SGeorge Wilson 	refcount_create(&arc_anon->arcs_size);
5823dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru->arcs_size);
5824dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mru_ghost->arcs_size);
5825dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu->arcs_size);
5826dcbf3bd6SGeorge Wilson 	refcount_create(&arc_mfu_ghost->arcs_size);
5827dcbf3bd6SGeorge Wilson 	refcount_create(&arc_l2c_only->arcs_size);
5828dcbf3bd6SGeorge Wilson }
5829dcbf3bd6SGeorge Wilson 
5830dcbf3bd6SGeorge Wilson static void
5831dcbf3bd6SGeorge Wilson arc_state_fini(void)
5832dcbf3bd6SGeorge Wilson {
5833dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
5834dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
5835dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
5836dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
5837dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
5838dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
5839dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
5840dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
5841dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
5842dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
5843dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
5844dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
5845dcbf3bd6SGeorge Wilson 
5846dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_anon->arcs_size);
5847dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru->arcs_size);
5848dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mru_ghost->arcs_size);
5849dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu->arcs_size);
5850dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_mfu_ghost->arcs_size);
5851dcbf3bd6SGeorge Wilson 	refcount_destroy(&arc_l2c_only->arcs_size);
5852dcbf3bd6SGeorge Wilson 
5853*94c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_METADATA]);
5854*94c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
5855*94c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_METADATA]);
5856*94c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
5857*94c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_DATA]);
5858*94c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
5859*94c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_DATA]);
5860*94c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
5861dcbf3bd6SGeorge Wilson }
5862dcbf3bd6SGeorge Wilson 
5863dcbf3bd6SGeorge Wilson uint64_t
5864dcbf3bd6SGeorge Wilson arc_max_bytes(void)
5865244781f1SPrakash Surya {
5866dcbf3bd6SGeorge Wilson 	return (arc_c_max);
5867244781f1SPrakash Surya }
5868244781f1SPrakash Surya 
5869fa9e4066Sahrens void
5870fa9e4066Sahrens arc_init(void)
5871fa9e4066Sahrens {
58722ec99e3eSMatthew Ahrens 	/*
58732ec99e3eSMatthew Ahrens 	 * allmem is "all memory that we could possibly use".
58742ec99e3eSMatthew Ahrens 	 */
58752ec99e3eSMatthew Ahrens #ifdef _KERNEL
58762ec99e3eSMatthew Ahrens 	uint64_t allmem = ptob(physmem - swapfs_minfree);
58772ec99e3eSMatthew Ahrens #else
58782ec99e3eSMatthew Ahrens 	uint64_t allmem = (physmem * PAGESIZE) / 2;
58792ec99e3eSMatthew Ahrens #endif
58802ec99e3eSMatthew Ahrens 
5881244781f1SPrakash Surya 	mutex_init(&arc_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
5882244781f1SPrakash Surya 	cv_init(&arc_reclaim_thread_cv, NULL, CV_DEFAULT, NULL);
5883244781f1SPrakash Surya 	cv_init(&arc_reclaim_waiters_cv, NULL, CV_DEFAULT, NULL);
5884244781f1SPrakash Surya 
588513506d1eSmaybee 	/* Convert seconds to clock ticks */
5886b19a79ecSperrin 	arc_min_prefetch_lifespan = 1 * hz;
588713506d1eSmaybee 
5888112fe045Smaybee 	/* set min cache to 1/32 of all memory, or 64MB, whichever is more */
58892ec99e3eSMatthew Ahrens 	arc_c_min = MAX(allmem / 32, 64 << 20);
5890112fe045Smaybee 	/* set max to 3/4 of all memory, or all but 1GB, whichever is more */
58912ec99e3eSMatthew Ahrens 	if (allmem >= 1 << 30)
58922ec99e3eSMatthew Ahrens 		arc_c_max = allmem - (1 << 30);
5893fa9e4066Sahrens 	else
589444cb6abcSbmc 		arc_c_max = arc_c_min;
58952ec99e3eSMatthew Ahrens 	arc_c_max = MAX(allmem * 3 / 4, arc_c_max);
5896a2eea2e1Sahrens 
58978fe00bfbSMatthew Ahrens 	/*
58988fe00bfbSMatthew Ahrens 	 * In userland, there's only the memory pressure that we artificially
58998fe00bfbSMatthew Ahrens 	 * create (see arc_available_memory()).  Don't let arc_c get too
59008fe00bfbSMatthew Ahrens 	 * small, because it can cause transactions to be larger than
59018fe00bfbSMatthew Ahrens 	 * arc_c, causing arc_tempreserve_space() to fail.
59028fe00bfbSMatthew Ahrens 	 */
59038fe00bfbSMatthew Ahrens #ifndef _KERNEL
59048fe00bfbSMatthew Ahrens 	arc_c_min = arc_c_max / 2;
59058fe00bfbSMatthew Ahrens #endif
59068fe00bfbSMatthew Ahrens 
5907a2eea2e1Sahrens 	/*
5908a2eea2e1Sahrens 	 * Allow the tunables to override our calculations if they are
5909a2eea2e1Sahrens 	 * reasonable (ie. over 64MB)
5910a2eea2e1Sahrens 	 */
5911e5961710SMatthew Ahrens 	if (zfs_arc_max > 64 << 20 && zfs_arc_max < allmem) {
591244cb6abcSbmc 		arc_c_max = zfs_arc_max;
5913e5961710SMatthew Ahrens 		arc_c_min = MIN(arc_c_min, arc_c_max);
5914e5961710SMatthew Ahrens 	}
59152ec99e3eSMatthew Ahrens 	if (zfs_arc_min > 64 << 20 && zfs_arc_min <= arc_c_max)
591644cb6abcSbmc 		arc_c_min = zfs_arc_min;
5917a2eea2e1Sahrens 
591844cb6abcSbmc 	arc_c = arc_c_max;
591944cb6abcSbmc 	arc_p = (arc_c >> 1);
5920dcbf3bd6SGeorge Wilson 	arc_size = 0;
5921fa9e4066Sahrens 
59220e8c6158Smaybee 	/* limit meta-data to 1/4 of the arc capacity */
59230e8c6158Smaybee 	arc_meta_limit = arc_c_max / 4;
59241116048bSek 
5925af868f46SMatthew Ahrens #ifdef _KERNEL
5926af868f46SMatthew Ahrens 	/*
5927af868f46SMatthew Ahrens 	 * Metadata is stored in the kernel's heap.  Don't let us
5928af868f46SMatthew Ahrens 	 * use more than half the heap for the ARC.
5929af868f46SMatthew Ahrens 	 */
5930af868f46SMatthew Ahrens 	arc_meta_limit = MIN(arc_meta_limit,
5931af868f46SMatthew Ahrens 	    vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 2);
5932af868f46SMatthew Ahrens #endif
5933af868f46SMatthew Ahrens 
59341116048bSek 	/* Allow the tunable to override if it is reasonable */
59351116048bSek 	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
59361116048bSek 		arc_meta_limit = zfs_arc_meta_limit;
59371116048bSek 
59380e8c6158Smaybee 	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
59390e8c6158Smaybee 		arc_c_min = arc_meta_limit / 2;
59400e8c6158Smaybee 
59413a5286a1SMatthew Ahrens 	if (zfs_arc_meta_min > 0) {
59423a5286a1SMatthew Ahrens 		arc_meta_min = zfs_arc_meta_min;
59433a5286a1SMatthew Ahrens 	} else {
59443a5286a1SMatthew Ahrens 		arc_meta_min = arc_c_min / 2;
59453a5286a1SMatthew Ahrens 	}
59463a5286a1SMatthew Ahrens 
59475a98e54bSBrendan Gregg - Sun Microsystems 	if (zfs_arc_grow_retry > 0)
59485a98e54bSBrendan Gregg - Sun Microsystems 		arc_grow_retry = zfs_arc_grow_retry;
59495a98e54bSBrendan Gregg - Sun Microsystems 
59505a98e54bSBrendan Gregg - Sun Microsystems 	if (zfs_arc_shrink_shift > 0)
59515a98e54bSBrendan Gregg - Sun Microsystems 		arc_shrink_shift = zfs_arc_shrink_shift;
59525a98e54bSBrendan Gregg - Sun Microsystems 
59532ec99e3eSMatthew Ahrens 	/*
59542ec99e3eSMatthew Ahrens 	 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
59552ec99e3eSMatthew Ahrens 	 */
59562ec99e3eSMatthew Ahrens 	if (arc_no_grow_shift >= arc_shrink_shift)
59572ec99e3eSMatthew Ahrens 		arc_no_grow_shift = arc_shrink_shift - 1;
59582ec99e3eSMatthew Ahrens 
59595a98e54bSBrendan Gregg - Sun Microsystems 	if (zfs_arc_p_min_shift > 0)
59605a98e54bSBrendan Gregg - Sun Microsystems 		arc_p_min_shift = zfs_arc_p_min_shift;
59615a98e54bSBrendan Gregg - Sun Microsystems 
5962fa9e4066Sahrens 	/* if kmem_flags are set, lets try to use less memory */
5963fa9e4066Sahrens 	if (kmem_debugging())
596444cb6abcSbmc 		arc_c = arc_c / 2;
596544cb6abcSbmc 	if (arc_c < arc_c_min)
596644cb6abcSbmc 		arc_c = arc_c_min;
596744cb6abcSbmc 
5968dcbf3bd6SGeorge Wilson 	arc_state_init();
5969fa9e4066Sahrens 	buf_init();
5970fa9e4066Sahrens 
5971dcbf3bd6SGeorge Wilson 	arc_reclaim_thread_exit = B_FALSE;
5972fa9e4066Sahrens 
597344cb6abcSbmc 	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
597444cb6abcSbmc 	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
597544cb6abcSbmc 
597644cb6abcSbmc 	if (arc_ksp != NULL) {
597744cb6abcSbmc 		arc_ksp->ks_data = &arc_stats;
59784076b1bfSPrakash Surya 		arc_ksp->ks_update = arc_kstat_update;
597944cb6abcSbmc 		kstat_install(arc_ksp);
598044cb6abcSbmc 	}
598144cb6abcSbmc 
5982fa9e4066Sahrens 	(void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
5983fa9e4066Sahrens 	    TS_RUN, minclsyspri);
598449e3519aSmaybee 
5985dcbf3bd6SGeorge Wilson 	arc_dead = B_FALSE;
59863a737e0dSbrendan 	arc_warm = B_FALSE;
59871ab7f2deSmaybee 
598869962b56SMatthew Ahrens 	/*
598969962b56SMatthew Ahrens 	 * Calculate maximum amount of dirty data per pool.
599069962b56SMatthew Ahrens 	 *
599169962b56SMatthew Ahrens 	 * If it has been set by /etc/system, take that.
599269962b56SMatthew Ahrens 	 * Otherwise, use a percentage of physical memory defined by
599369962b56SMatthew Ahrens 	 * zfs_dirty_data_max_percent (default 10%) with a cap at
599469962b56SMatthew Ahrens 	 * zfs_dirty_data_max_max (default 4GB).
599569962b56SMatthew Ahrens 	 */
599669962b56SMatthew Ahrens 	if (zfs_dirty_data_max == 0) {
599769962b56SMatthew Ahrens 		zfs_dirty_data_max = physmem * PAGESIZE *
599869962b56SMatthew Ahrens 		    zfs_dirty_data_max_percent / 100;
599969962b56SMatthew Ahrens 		zfs_dirty_data_max = MIN(zfs_dirty_data_max,
600069962b56SMatthew Ahrens 		    zfs_dirty_data_max_max);
600169962b56SMatthew Ahrens 	}
6002fa9e4066Sahrens }
6003fa9e4066Sahrens 
6004fa9e4066Sahrens void
6005fa9e4066Sahrens arc_fini(void)
6006fa9e4066Sahrens {
6007244781f1SPrakash Surya 	mutex_enter(&arc_reclaim_lock);
6008dcbf3bd6SGeorge Wilson 	arc_reclaim_thread_exit = B_TRUE;
6009244781f1SPrakash Surya 	/*
6010244781f1SPrakash Surya 	 * The reclaim thread will set arc_reclaim_thread_exit back to
6011dcbf3bd6SGeorge Wilson 	 * B_FALSE when it is finished exiting; we're waiting for that.
6012244781f1SPrakash Surya 	 */
6013244781f1SPrakash Surya 	while (arc_reclaim_thread_exit) {
6014244781f1SPrakash Surya 		cv_signal(&arc_reclaim_thread_cv);
6015244781f1SPrakash Surya 		cv_wait(&arc_reclaim_thread_cv, &arc_reclaim_lock);
6016244781f1SPrakash Surya 	}
6017244781f1SPrakash Surya 	mutex_exit(&arc_reclaim_lock);
6018fa9e4066Sahrens 
6019dcbf3bd6SGeorge Wilson 	/* Use B_TRUE to ensure *all* buffers are evicted */
6020dcbf3bd6SGeorge Wilson 	arc_flush(NULL, B_TRUE);
6021fa9e4066Sahrens 
6022dcbf3bd6SGeorge Wilson 	arc_dead = B_TRUE;
6023fa9e4066Sahrens 
602444cb6abcSbmc 	if (arc_ksp != NULL) {
602544cb6abcSbmc 		kstat_delete(arc_ksp);
602644cb6abcSbmc 		arc_ksp = NULL;
602744cb6abcSbmc 	}
602844cb6abcSbmc 
6029244781f1SPrakash Surya 	mutex_destroy(&arc_reclaim_lock);
6030244781f1SPrakash Surya 	cv_destroy(&arc_reclaim_thread_cv);
6031244781f1SPrakash Surya 	cv_destroy(&arc_reclaim_waiters_cv);
6032244781f1SPrakash Surya 
6033dcbf3bd6SGeorge Wilson 	arc_state_fini();
6034fa9e4066Sahrens 	buf_fini();
60352fdbea25SAleksandr Guzovskiy 
603689c86e32SChris Williamson 	ASSERT0(arc_loaned_bytes);
6037fa9e4066Sahrens }
6038fa94a07fSbrendan 
6039fa94a07fSbrendan /*
6040fa94a07fSbrendan  * Level 2 ARC
6041fa94a07fSbrendan  *
6042fa94a07fSbrendan  * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
6043fa94a07fSbrendan  * It uses dedicated storage devices to hold cached data, which are populated
6044fa94a07fSbrendan  * using large infrequent writes.  The main role of this cache is to boost
6045fa94a07fSbrendan  * the performance of random read workloads.  The intended L2ARC devices
6046fa94a07fSbrendan  * include short-stroked disks, solid state disks, and other media with
6047fa94a07fSbrendan  * substantially faster read latency than disk.
6048fa94a07fSbrendan  *
6049fa94a07fSbrendan  *                 +-----------------------+
6050fa94a07fSbrendan  *                 |         ARC           |
6051fa94a07fSbrendan  *                 +-----------------------+
6052fa94a07fSbrendan  *                    |         ^     ^
6053fa94a07fSbrendan  *                    |         |     |
6054fa94a07fSbrendan  *      l2arc_feed_thread()    arc_read()
6055fa94a07fSbrendan  *                    |         |     |
6056fa94a07fSbrendan  *                    |  l2arc read   |
6057fa94a07fSbrendan  *                    V         |     |
6058fa94a07fSbrendan  *               +---------------+    |
6059fa94a07fSbrendan  *               |     L2ARC     |    |
6060fa94a07fSbrendan  *               +---------------+    |
6061fa94a07fSbrendan  *                   |    ^           |
6062fa94a07fSbrendan  *          l2arc_write() |           |
6063fa94a07fSbrendan  *                   |    |           |
6064fa94a07fSbrendan  *                   V    |           |
6065fa94a07fSbrendan  *                 +-------+      +-------+
6066fa94a07fSbrendan  *                 | vdev  |      | vdev  |
6067fa94a07fSbrendan  *                 | cache |      | cache |
6068fa94a07fSbrendan  *                 +-------+      +-------+
6069fa94a07fSbrendan  *                 +=========+     .-----.
6070fa94a07fSbrendan  *                 :  L2ARC  :    |-_____-|
6071fa94a07fSbrendan  *                 : devices :    | Disks |
6072fa94a07fSbrendan  *                 +=========+    `-_____-'
6073fa94a07fSbrendan  *
6074fa94a07fSbrendan  * Read requests are satisfied from the following sources, in order:
6075fa94a07fSbrendan  *
6076fa94a07fSbrendan  *	1) ARC
6077fa94a07fSbrendan  *	2) vdev cache of L2ARC devices
6078fa94a07fSbrendan  *	3) L2ARC devices
6079fa94a07fSbrendan  *	4) vdev cache of disks
6080fa94a07fSbrendan  *	5) disks
6081fa94a07fSbrendan  *
6082fa94a07fSbrendan  * Some L2ARC device types exhibit extremely slow write performance.
6083fa94a07fSbrendan  * To accommodate for this there are some significant differences between
6084fa94a07fSbrendan  * the L2ARC and traditional cache design:
6085fa94a07fSbrendan  *
6086fa94a07fSbrendan  * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
6087fa94a07fSbrendan  * the ARC behave as usual, freeing buffers and placing headers on ghost
6088fa94a07fSbrendan  * lists.  The ARC does not send buffers to the L2ARC during eviction as
6089fa94a07fSbrendan  * this would add inflated write latencies for all ARC memory pressure.
6090fa94a07fSbrendan  *
6091fa94a07fSbrendan  * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
6092fa94a07fSbrendan  * It does this by periodically scanning buffers from the eviction-end of
6093fa94a07fSbrendan  * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
6094aad02571SSaso Kiselkov  * not already there. It scans until a headroom of buffers is satisfied,
6095aad02571SSaso Kiselkov  * which itself is a buffer for ARC eviction. If a compressible buffer is
6096aad02571SSaso Kiselkov  * found during scanning and selected for writing to an L2ARC device, we
6097aad02571SSaso Kiselkov  * temporarily boost scanning headroom during the next scan cycle to make
6098aad02571SSaso Kiselkov  * sure we adapt to compression effects (which might significantly reduce
6099aad02571SSaso Kiselkov  * the data volume we write to L2ARC). The thread that does this is
6100fa94a07fSbrendan  * l2arc_feed_thread(), illustrated below; example sizes are included to
6101fa94a07fSbrendan  * provide a better sense of ratio than this diagram:
6102fa94a07fSbrendan  *
6103fa94a07fSbrendan  *	       head -->                        tail
6104fa94a07fSbrendan  *	        +---------------------+----------+
6105fa94a07fSbrendan  *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
6106fa94a07fSbrendan  *	        +---------------------+----------+   |   o L2ARC eligible
6107fa94a07fSbrendan  *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
6108fa94a07fSbrendan  *	        +---------------------+----------+   |
6109fa94a07fSbrendan  *	             15.9 Gbytes      ^ 32 Mbytes    |
6110fa94a07fSbrendan  *	                           headroom          |
6111fa94a07fSbrendan  *	                                      l2arc_feed_thread()
6112fa94a07fSbrendan  *	                                             |
6113fa94a07fSbrendan  *	                 l2arc write hand <--[oooo]--'
6114fa94a07fSbrendan  *	                         |           8 Mbyte
6115fa94a07fSbrendan  *	                         |          write max
6116fa94a07fSbrendan  *	                         V
6117fa94a07fSbrendan  *		  +==============================+
6118fa94a07fSbrendan  *	L2ARC dev |####|#|###|###|    |####| ... |
6119fa94a07fSbrendan  *	          +==============================+
6120fa94a07fSbrendan  *	                     32 Gbytes
6121fa94a07fSbrendan  *
6122fa94a07fSbrendan  * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
6123fa94a07fSbrendan  * evicted, then the L2ARC has cached a buffer much sooner than it probably
6124fa94a07fSbrendan  * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
6125fa94a07fSbrendan  * safe to say that this is an uncommon case, since buffers at the end of
6126fa94a07fSbrendan  * the ARC lists have moved there due to inactivity.
6127fa94a07fSbrendan  *
6128fa94a07fSbrendan  * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
6129fa94a07fSbrendan  * then the L2ARC simply misses copying some buffers.  This serves as a
6130fa94a07fSbrendan  * pressure valve to prevent heavy read workloads from both stalling the ARC
6131fa94a07fSbrendan  * with waits and clogging the L2ARC with writes.  This also helps prevent
6132fa94a07fSbrendan  * the potential for the L2ARC to churn if it attempts to cache content too
6133fa94a07fSbrendan  * quickly, such as during backups of the entire pool.
6134fa94a07fSbrendan  *
61353a737e0dSbrendan  * 5. After system boot and before the ARC has filled main memory, there are
61363a737e0dSbrendan  * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
61373a737e0dSbrendan  * lists can remain mostly static.  Instead of searching from tail of these
61383a737e0dSbrendan  * lists as pictured, the l2arc_feed_thread() will search from the list heads
61393a737e0dSbrendan  * for eligible buffers, greatly increasing its chance of finding them.
61403a737e0dSbrendan  *
61413a737e0dSbrendan  * The L2ARC device write speed is also boosted during this time so that
61423a737e0dSbrendan  * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
61433a737e0dSbrendan  * there are no L2ARC reads, and no fear of degrading read performance
61443a737e0dSbrendan  * through increased writes.
61453a737e0dSbrendan  *
61463a737e0dSbrendan  * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
6147fa94a07fSbrendan  * the vdev queue can aggregate them into larger and fewer writes.  Each
6148fa94a07fSbrendan  * device is written to in a rotor fashion, sweeping writes through
6149fa94a07fSbrendan  * available space then repeating.
6150fa94a07fSbrendan  *
61513a737e0dSbrendan  * 7. The L2ARC does not store dirty content.  It never needs to flush
6152fa94a07fSbrendan  * write buffers back to disk based storage.
6153fa94a07fSbrendan  *
61543a737e0dSbrendan  * 8. If an ARC buffer is written (and dirtied) which also exists in the
6155fa94a07fSbrendan  * L2ARC, the now stale L2ARC buffer is immediately dropped.
6156fa94a07fSbrendan  *
6157fa94a07fSbrendan  * The performance of the L2ARC can be tweaked by a number of tunables, which
6158fa94a07fSbrendan  * may be necessary for different workloads:
6159fa94a07fSbrendan  *
6160fa94a07fSbrendan  *	l2arc_write_max		max write bytes per interval
61613a737e0dSbrendan  *	l2arc_write_boost	extra write bytes during device warmup
6162fa94a07fSbrendan  *	l2arc_noprefetch	skip caching prefetched buffers
6163fa94a07fSbrendan  *	l2arc_headroom		number of max device writes to precache
6164aad02571SSaso Kiselkov  *	l2arc_headroom_boost	when we find compressed buffers during ARC
6165aad02571SSaso Kiselkov  *				scanning, we multiply headroom by this
6166aad02571SSaso Kiselkov  *				percentage factor for the next scan cycle,
6167aad02571SSaso Kiselkov  *				since more compressed buffers are likely to
6168aad02571SSaso Kiselkov  *				be present
6169fa94a07fSbrendan  *	l2arc_feed_secs		seconds between L2ARC writing
6170fa94a07fSbrendan  *
6171fa94a07fSbrendan  * Tunables may be removed or added as future performance improvements are
6172fa94a07fSbrendan  * integrated, and also may become zpool properties.
61735a98e54bSBrendan Gregg - Sun Microsystems  *
61745a98e54bSBrendan Gregg - Sun Microsystems  * There are three key functions that control how the L2ARC warms up:
61755a98e54bSBrendan Gregg - Sun Microsystems  *
61765a98e54bSBrendan Gregg - Sun Microsystems  *	l2arc_write_eligible()	check if a buffer is eligible to cache
61775a98e54bSBrendan Gregg - Sun Microsystems  *	l2arc_write_size()	calculate how much to write
61785a98e54bSBrendan Gregg - Sun Microsystems  *	l2arc_write_interval()	calculate sleep delay between writes
61795a98e54bSBrendan Gregg - Sun Microsystems  *
61805a98e54bSBrendan Gregg - Sun Microsystems  * These three functions determine what to write, how much, and how quickly
61815a98e54bSBrendan Gregg - Sun Microsystems  * to send writes.
6182fa94a07fSbrendan  */
6183fa94a07fSbrendan 
61845a98e54bSBrendan Gregg - Sun Microsystems static boolean_t
61857adb730bSGeorge Wilson l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
61865a98e54bSBrendan Gregg - Sun Microsystems {
61875a98e54bSBrendan Gregg - Sun Microsystems 	/*
61885a98e54bSBrendan Gregg - Sun Microsystems 	 * A buffer is *not* eligible for the L2ARC if it:
61895a98e54bSBrendan Gregg - Sun Microsystems 	 * 1. belongs to a different spa.
61905ea40c06SBrendan Gregg - Sun Microsystems 	 * 2. is already cached on the L2ARC.
61915ea40c06SBrendan Gregg - Sun Microsystems 	 * 3. has an I/O in progress (it may be an incomplete read).
61925ea40c06SBrendan Gregg - Sun Microsystems 	 * 4. is flagged not eligible (zfs property).
61935a98e54bSBrendan Gregg - Sun Microsystems 	 */
619489c86e32SChris Williamson 	if (hdr->b_spa != spa_guid || HDR_HAS_L2HDR(hdr) ||
61957adb730bSGeorge Wilson 	    HDR_IO_IN_PROGRESS(hdr) || !HDR_L2CACHE(hdr))
61965a98e54bSBrendan Gregg - Sun Microsystems 		return (B_FALSE);
61975a98e54bSBrendan Gregg - Sun Microsystems 
61985a98e54bSBrendan Gregg - Sun Microsystems 	return (B_TRUE);
61995a98e54bSBrendan Gregg - Sun Microsystems }
62005a98e54bSBrendan Gregg - Sun Microsystems 
62015a98e54bSBrendan Gregg - Sun Microsystems static uint64_t
6202aad02571SSaso Kiselkov l2arc_write_size(void)
62035a98e54bSBrendan Gregg - Sun Microsystems {
62045a98e54bSBrendan Gregg - Sun Microsystems 	uint64_t size;
62055a98e54bSBrendan Gregg - Sun Microsystems 
6206aad02571SSaso Kiselkov 	/*
6207aad02571SSaso Kiselkov 	 * Make sure our globals have meaningful values in case the user
6208aad02571SSaso Kiselkov 	 * altered them.
6209aad02571SSaso Kiselkov 	 */
6210aad02571SSaso Kiselkov 	size = l2arc_write_max;
6211aad02571SSaso Kiselkov 	if (size == 0) {
6212aad02571SSaso Kiselkov 		cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
6213aad02571SSaso Kiselkov 		    "be greater than zero, resetting it to the default (%d)",
6214aad02571SSaso Kiselkov 		    L2ARC_WRITE_SIZE);
6215aad02571SSaso Kiselkov 		size = l2arc_write_max = L2ARC_WRITE_SIZE;
6216aad02571SSaso Kiselkov 	}
62175a98e54bSBrendan Gregg - Sun Microsystems 
62185a98e54bSBrendan Gregg - Sun Microsystems 	if (arc_warm == B_FALSE)
6219aad02571SSaso Kiselkov 		size += l2arc_write_boost;
62205a98e54bSBrendan Gregg - Sun Microsystems 
62215a98e54bSBrendan Gregg - Sun Microsystems 	return (size);
62225a98e54bSBrendan Gregg - Sun Microsystems 
62235a98e54bSBrendan Gregg - Sun Microsystems }
62245a98e54bSBrendan Gregg - Sun Microsystems 
62255a98e54bSBrendan Gregg - Sun Microsystems static clock_t
62265a98e54bSBrendan Gregg - Sun Microsystems l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
62275a98e54bSBrendan Gregg - Sun Microsystems {
6228d3d50737SRafael Vanoni 	clock_t interval, next, now;
62295a98e54bSBrendan Gregg - Sun Microsystems 
62305a98e54bSBrendan Gregg - Sun Microsystems 	/*
62315a98e54bSBrendan Gregg - Sun Microsystems 	 * If the ARC lists are busy, increase our write rate; if the
62325a98e54bSBrendan Gregg - Sun Microsystems 	 * lists are stale, idle back.  This is achieved by checking
62335a98e54bSBrendan Gregg - Sun Microsystems 	 * how much we previously wrote - if it was more than half of
62345a98e54bSBrendan Gregg - Sun Microsystems 	 * what we wanted, schedule the next write much sooner.
62355a98e54bSBrendan Gregg - Sun Microsystems 	 */
62365a98e54bSBrendan Gregg - Sun Microsystems 	if (l2arc_feed_again && wrote > (wanted / 2))
62375a98e54bSBrendan Gregg - Sun Microsystems 		interval = (hz * l2arc_feed_min_ms) / 1000;
62385a98e54bSBrendan Gregg - Sun Microsystems 	else
62395a98e54bSBrendan Gregg - Sun Microsystems 		interval = hz * l2arc_feed_secs;
62405a98e54bSBrendan Gregg - Sun Microsystems 
6241d3d50737SRafael Vanoni 	now = ddi_get_lbolt();
6242d3d50737SRafael Vanoni 	next = MAX(now, MIN(now + interval, began + interval));
62435a98e54bSBrendan Gregg - Sun Microsystems 
62445a98e54bSBrendan Gregg - Sun Microsystems 	return (next);
62455a98e54bSBrendan Gregg - Sun Microsystems }
62465a98e54bSBrendan Gregg - Sun Microsystems 
6247fa94a07fSbrendan /*
6248fa94a07fSbrendan  * Cycle through L2ARC devices.  This is how L2ARC load balances.
62493a737e0dSbrendan  * If a device is returned, this also returns holding the spa config lock.
6250fa94a07fSbrendan  */
6251fa94a07fSbrendan static l2arc_dev_t *
6252fa94a07fSbrendan l2arc_dev_get_next(void)
6253fa94a07fSbrendan {
62543a737e0dSbrendan 	l2arc_dev_t *first, *next = NULL;
62553a737e0dSbrendan 
62563a737e0dSbrendan 	/*
62573a737e0dSbrendan 	 * Lock out the removal of spas (spa_namespace_lock), then removal
62583a737e0dSbrendan 	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
62593a737e0dSbrendan 	 * both locks will be dropped and a spa config lock held instead.
62603a737e0dSbrendan 	 */
62613a737e0dSbrendan 	mutex_enter(&spa_namespace_lock);
62623a737e0dSbrendan 	mutex_enter(&l2arc_dev_mtx);
6263fa94a07fSbrendan 
6264c5904d13Seschrock 	/* if there are no vdevs, there is nothing to do */
6265c5904d13Seschrock 	if (l2arc_ndev == 0)
62663a737e0dSbrendan 		goto out;
6267c5904d13Seschrock 
6268c5904d13Seschrock 	first = NULL;
6269c5904d13Seschrock 	next = l2arc_dev_last;
6270c5904d13Seschrock 	do {
6271c5904d13Seschrock 		/* loop around the list looking for a non-faulted vdev */
6272c5904d13Seschrock 		if (next == NULL) {
6273fa94a07fSbrendan 			next = list_head(l2arc_dev_list);
6274c5904d13Seschrock 		} else {
6275c5904d13Seschrock 			next = list_next(l2arc_dev_list, next);
6276c5904d13Seschrock 			if (next == NULL)
6277c5904d13Seschrock 				next = list_head(l2arc_dev_list);
6278c5904d13Seschrock 		}
6279c5904d13Seschrock 
6280c5904d13Seschrock 		/* if we have come back to the start, bail out */
6281c5904d13Seschrock 		if (first == NULL)
6282c5904d13Seschrock 			first = next;
6283c5904d13Seschrock 		else if (next == first)
6284c5904d13Seschrock 			break;
6285c5904d13Seschrock 
6286c5904d13Seschrock 	} while (vdev_is_dead(next->l2ad_vdev));
6287c5904d13Seschrock 
6288c5904d13Seschrock 	/* if we were unable to find any usable vdevs, return NULL */
6289c5904d13Seschrock 	if (vdev_is_dead(next->l2ad_vdev))
62903a737e0dSbrendan 		next = NULL;
6291fa94a07fSbrendan 
6292fa94a07fSbrendan 	l2arc_dev_last = next;
6293fa94a07fSbrendan 
62943a737e0dSbrendan out:
62953a737e0dSbrendan 	mutex_exit(&l2arc_dev_mtx);
62963a737e0dSbrendan 
62973a737e0dSbrendan 	/*
62983a737e0dSbrendan 	 * Grab the config lock to prevent the 'next' device from being
62993a737e0dSbrendan 	 * removed while we are writing to it.
63003a737e0dSbrendan 	 */
63013a737e0dSbrendan 	if (next != NULL)
6302e14bb325SJeff Bonwick 		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
63033a737e0dSbrendan 	mutex_exit(&spa_namespace_lock);
63043a737e0dSbrendan 
6305fa94a07fSbrendan 	return (next);
6306fa94a07fSbrendan }
6307fa94a07fSbrendan 
63083a737e0dSbrendan /*
63093a737e0dSbrendan  * Free buffers that were tagged for destruction.
63103a737e0dSbrendan  */
63113a737e0dSbrendan static void
63123a737e0dSbrendan l2arc_do_free_on_write()
63133a737e0dSbrendan {
63143a737e0dSbrendan 	list_t *buflist;
63153a737e0dSbrendan 	l2arc_data_free_t *df, *df_prev;
63163a737e0dSbrendan 
63173a737e0dSbrendan 	mutex_enter(&l2arc_free_on_write_mtx);
63183a737e0dSbrendan 	buflist = l2arc_free_on_write;
63193a737e0dSbrendan 
63203a737e0dSbrendan 	for (df = list_tail(buflist); df; df = df_prev) {
63213a737e0dSbrendan 		df_prev = list_prev(buflist, df);
6322dcbf3bd6SGeorge Wilson 		ASSERT3P(df->l2df_data, !=, NULL);
6323dcbf3bd6SGeorge Wilson 		if (df->l2df_type == ARC_BUFC_METADATA) {
6324dcbf3bd6SGeorge Wilson 			zio_buf_free(df->l2df_data, df->l2df_size);
6325dcbf3bd6SGeorge Wilson 		} else {
6326dcbf3bd6SGeorge Wilson 			ASSERT(df->l2df_type == ARC_BUFC_DATA);
6327dcbf3bd6SGeorge Wilson 			zio_data_buf_free(df->l2df_data, df->l2df_size);
6328dcbf3bd6SGeorge Wilson 		}
63293a737e0dSbrendan 		list_remove(buflist, df);
63303a737e0dSbrendan 		kmem_free(df, sizeof (l2arc_data_free_t));
63313a737e0dSbrendan 	}
63323a737e0dSbrendan 
63333a737e0dSbrendan 	mutex_exit(&l2arc_free_on_write_mtx);
63343a737e0dSbrendan }
63353a737e0dSbrendan 
6336fa94a07fSbrendan /*
6337fa94a07fSbrendan  * A write to a cache device has completed.  Update all headers to allow
6338fa94a07fSbrendan  * reads from these buffers to begin.
6339fa94a07fSbrendan  */
6340fa94a07fSbrendan static void
6341fa94a07fSbrendan l2arc_write_done(zio_t *zio)
6342fa94a07fSbrendan {
6343fa94a07fSbrendan 	l2arc_write_callback_t *cb;
6344fa94a07fSbrendan 	l2arc_dev_t *dev;
6345fa94a07fSbrendan 	list_t *buflist;
63467adb730bSGeorge Wilson 	arc_buf_hdr_t *head, *hdr, *hdr_prev;
6347fa94a07fSbrendan 	kmutex_t *hash_lock;
63483038a2b4SSaso Kiselkov 	int64_t bytes_dropped = 0;
6349fa94a07fSbrendan 
6350fa94a07fSbrendan 	cb = zio->io_private;
6351dcbf3bd6SGeorge Wilson 	ASSERT3P(cb, !=, NULL);
6352fa94a07fSbrendan 	dev = cb->l2wcb_dev;
6353dcbf3bd6SGeorge Wilson 	ASSERT3P(dev, !=, NULL);
6354fa94a07fSbrendan 	head = cb->l2wcb_head;
6355dcbf3bd6SGeorge Wilson 	ASSERT3P(head, !=, NULL);
635689c86e32SChris Williamson 	buflist = &dev->l2ad_buflist;
6357dcbf3bd6SGeorge Wilson 	ASSERT3P(buflist, !=, NULL);
6358fa94a07fSbrendan 	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
6359fa94a07fSbrendan 	    l2arc_write_callback_t *, cb);
6360fa94a07fSbrendan 
6361fa94a07fSbrendan 	if (zio->io_error != 0)
6362fa94a07fSbrendan 		ARCSTAT_BUMP(arcstat_l2_writes_error);
6363fa94a07fSbrendan 
6364fa94a07fSbrendan 	/*
6365fa94a07fSbrendan 	 * All writes completed, or an error was hit.
6366fa94a07fSbrendan 	 */
6367244781f1SPrakash Surya top:
6368244781f1SPrakash Surya 	mutex_enter(&dev->l2ad_mtx);
63697adb730bSGeorge Wilson 	for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
63707adb730bSGeorge Wilson 		hdr_prev = list_prev(buflist, hdr);
6371fa94a07fSbrendan 
63727adb730bSGeorge Wilson 		hash_lock = HDR_LOCK(hdr);
6373244781f1SPrakash Surya 
6374244781f1SPrakash Surya 		/*
6375244781f1SPrakash Surya 		 * We cannot use mutex_enter or else we can deadlock
6376244781f1SPrakash Surya 		 * with l2arc_write_buffers (due to swapping the order
6377244781f1SPrakash Surya 		 * the hash lock and l2ad_mtx are taken).
6378244781f1SPrakash Surya 		 */
6379fa94a07fSbrendan 		if (!mutex_tryenter(hash_lock)) {
6380fa94a07fSbrendan 			/*
6381244781f1SPrakash Surya 			 * Missed the hash lock. We must retry so we
6382244781f1SPrakash Surya 			 * don't leave the ARC_FLAG_L2_WRITING bit set.
6383fa94a07fSbrendan 			 */
6384244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
6385244781f1SPrakash Surya 
6386244781f1SPrakash Surya 			/*
6387244781f1SPrakash Surya 			 * We don't want to rescan the headers we've
6388244781f1SPrakash Surya 			 * already marked as having been written out, so
6389244781f1SPrakash Surya 			 * we reinsert the head node so we can pick up
6390244781f1SPrakash Surya 			 * where we left off.
6391244781f1SPrakash Surya 			 */
6392244781f1SPrakash Surya 			list_remove(buflist, head);
6393244781f1SPrakash Surya 			list_insert_after(buflist, hdr, head);
6394244781f1SPrakash Surya 
6395244781f1SPrakash Surya 			mutex_exit(&dev->l2ad_mtx);
6396244781f1SPrakash Surya 
6397244781f1SPrakash Surya 			/*
6398244781f1SPrakash Surya 			 * We wait for the hash lock to become available
6399244781f1SPrakash Surya 			 * to try and prevent busy waiting, and increase
6400244781f1SPrakash Surya 			 * the chance we'll be able to acquire the lock
6401244781f1SPrakash Surya 			 * the next time around.
6402244781f1SPrakash Surya 			 */
6403244781f1SPrakash Surya 			mutex_enter(hash_lock);
6404244781f1SPrakash Surya 			mutex_exit(hash_lock);
6405244781f1SPrakash Surya 			goto top;
6406fa94a07fSbrendan 		}
6407fa94a07fSbrendan 
640889c86e32SChris Williamson 		/*
6409244781f1SPrakash Surya 		 * We could not have been moved into the arc_l2c_only
6410244781f1SPrakash Surya 		 * state while in-flight due to our ARC_FLAG_L2_WRITING
6411244781f1SPrakash Surya 		 * bit being set. Let's just ensure that's being enforced.
6412244781f1SPrakash Surya 		 */
6413244781f1SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(hdr));
6414244781f1SPrakash Surya 
6415fa94a07fSbrendan 		if (zio->io_error != 0) {
6416fa94a07fSbrendan 			/*
64173a737e0dSbrendan 			 * Error - drop L2ARC entry.
6418fa94a07fSbrendan 			 */
64197adb730bSGeorge Wilson 			list_remove(buflist, hdr);
6420dcbf3bd6SGeorge Wilson 			arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
642189c86e32SChris Williamson 
6422dcbf3bd6SGeorge Wilson 			ARCSTAT_INCR(arcstat_l2_asize, -arc_hdr_size(hdr));
6423dcbf3bd6SGeorge Wilson 			ARCSTAT_INCR(arcstat_l2_size, -HDR_GET_LSIZE(hdr));
6424a52fc310SPrakash Surya 
6425dcbf3bd6SGeorge Wilson 			bytes_dropped += arc_hdr_size(hdr);
6426a52fc310SPrakash Surya 			(void) refcount_remove_many(&dev->l2ad_alloc,
6427dcbf3bd6SGeorge Wilson 			    arc_hdr_size(hdr), hdr);
6428fa94a07fSbrendan 		}
6429fa94a07fSbrendan 
6430fa94a07fSbrendan 		/*
6431244781f1SPrakash Surya 		 * Allow ARC to begin reads and ghost list evictions to
6432244781f1SPrakash Surya 		 * this L2ARC entry.
6433fa94a07fSbrendan 		 */
6434dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_L2_WRITING);
6435fa94a07fSbrendan 
6436fa94a07fSbrendan 		mutex_exit(hash_lock);
6437fa94a07fSbrendan 	}
6438fa94a07fSbrendan 
6439fa94a07fSbrendan 	atomic_inc_64(&l2arc_writes_done);
6440fa94a07fSbrendan 	list_remove(buflist, head);
644189c86e32SChris Williamson 	ASSERT(!HDR_HAS_L1HDR(head));
644289c86e32SChris Williamson 	kmem_cache_free(hdr_l2only_cache, head);
644389c86e32SChris Williamson 	mutex_exit(&dev->l2ad_mtx);
6444fa94a07fSbrendan 
64453038a2b4SSaso Kiselkov 	vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
64463038a2b4SSaso Kiselkov 
64473a737e0dSbrendan 	l2arc_do_free_on_write();
6448fa94a07fSbrendan 
6449fa94a07fSbrendan 	kmem_free(cb, sizeof (l2arc_write_callback_t));
6450fa94a07fSbrendan }
6451fa94a07fSbrendan 
6452fa94a07fSbrendan /*
6453fa94a07fSbrendan  * A read to a cache device completed.  Validate buffer contents before
6454fa94a07fSbrendan  * handing over to the regular ARC routines.
6455fa94a07fSbrendan  */
6456fa94a07fSbrendan static void
6457fa94a07fSbrendan l2arc_read_done(zio_t *zio)
6458fa94a07fSbrendan {
6459fa94a07fSbrendan 	l2arc_read_callback_t *cb;
6460fa94a07fSbrendan 	arc_buf_hdr_t *hdr;
6461fa94a07fSbrendan 	kmutex_t *hash_lock;
6462dcbf3bd6SGeorge Wilson 	boolean_t valid_cksum;
6463fa94a07fSbrendan 
6464dcbf3bd6SGeorge Wilson 	ASSERT3P(zio->io_vd, !=, NULL);
6465e14bb325SJeff Bonwick 	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
6466e14bb325SJeff Bonwick 
6467e14bb325SJeff Bonwick 	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
6468e14bb325SJeff Bonwick 
6469fa94a07fSbrendan 	cb = zio->io_private;
6470dcbf3bd6SGeorge Wilson 	ASSERT3P(cb, !=, NULL);
6471dcbf3bd6SGeorge Wilson 	hdr = cb->l2rcb_hdr;
6472dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr, !=, NULL);
6473fa94a07fSbrendan 
6474dcbf3bd6SGeorge Wilson 	hash_lock = HDR_LOCK(hdr);
6475fa94a07fSbrendan 	mutex_enter(hash_lock);
64763f9d6ad7SLin Ling 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
6477fa94a07fSbrendan 
6478dcbf3bd6SGeorge Wilson 	ASSERT3P(zio->io_data, !=, NULL);
6479aad02571SSaso Kiselkov 
6480fa94a07fSbrendan 	/*
6481fa94a07fSbrendan 	 * Check this survived the L2ARC journey.
6482fa94a07fSbrendan 	 */
6483dcbf3bd6SGeorge Wilson 	ASSERT3P(zio->io_data, ==, hdr->b_l1hdr.b_pdata);
6484dcbf3bd6SGeorge Wilson 	zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
6485dcbf3bd6SGeorge Wilson 	zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
6486dcbf3bd6SGeorge Wilson 
6487dcbf3bd6SGeorge Wilson 	valid_cksum = arc_cksum_is_equal(hdr, zio);
6488dcbf3bd6SGeorge Wilson 	if (valid_cksum && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
6489fa94a07fSbrendan 		mutex_exit(hash_lock);
6490dcbf3bd6SGeorge Wilson 		zio->io_private = hdr;
6491fa94a07fSbrendan 		arc_read_done(zio);
6492fa94a07fSbrendan 	} else {
6493fa94a07fSbrendan 		mutex_exit(hash_lock);
6494fa94a07fSbrendan 		/*
6495fa94a07fSbrendan 		 * Buffer didn't survive caching.  Increment stats and
6496fa94a07fSbrendan 		 * reissue to the original storage device.
6497fa94a07fSbrendan 		 */
64983a737e0dSbrendan 		if (zio->io_error != 0) {
6499fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_io_error);
65003a737e0dSbrendan 		} else {
6501be6fd75aSMatthew Ahrens 			zio->io_error = SET_ERROR(EIO);
65023a737e0dSbrendan 		}
6503dcbf3bd6SGeorge Wilson 		if (!valid_cksum)
6504fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
6505fa94a07fSbrendan 
6506e14bb325SJeff Bonwick 		/*
6507e14bb325SJeff Bonwick 		 * If there's no waiter, issue an async i/o to the primary
6508e14bb325SJeff Bonwick 		 * storage now.  If there *is* a waiter, the caller must
6509e14bb325SJeff Bonwick 		 * issue the i/o in a context where it's OK to block.
6510e14bb325SJeff Bonwick 		 */
6511a3f829aeSBill Moore 		if (zio->io_waiter == NULL) {
6512a3f829aeSBill Moore 			zio_t *pio = zio_unique_parent(zio);
6513a3f829aeSBill Moore 
6514a3f829aeSBill Moore 			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
6515a3f829aeSBill Moore 
6516dcbf3bd6SGeorge Wilson 			zio_nowait(zio_read(pio, zio->io_spa, zio->io_bp,
6517dcbf3bd6SGeorge Wilson 			    hdr->b_l1hdr.b_pdata, zio->io_size, arc_read_done,
6518dcbf3bd6SGeorge Wilson 			    hdr, zio->io_priority, cb->l2rcb_flags,
6519dcbf3bd6SGeorge Wilson 			    &cb->l2rcb_zb));
6520a3f829aeSBill Moore 		}
6521fa94a07fSbrendan 	}
6522fa94a07fSbrendan 
6523fa94a07fSbrendan 	kmem_free(cb, sizeof (l2arc_read_callback_t));
6524fa94a07fSbrendan }
6525fa94a07fSbrendan 
6526fa94a07fSbrendan /*
6527fa94a07fSbrendan  * This is the list priority from which the L2ARC will search for pages to
6528fa94a07fSbrendan  * cache.  This is used within loops (0..3) to cycle through lists in the
6529fa94a07fSbrendan  * desired order.  This order can have a significant effect on cache
6530fa94a07fSbrendan  * performance.
6531fa94a07fSbrendan  *
6532fa94a07fSbrendan  * Currently the metadata lists are hit first, MFU then MRU, followed by
6533fa94a07fSbrendan  * the data lists.  This function returns a locked list, and also returns
6534fa94a07fSbrendan  * the lock pointer.
6535fa94a07fSbrendan  */
6536244781f1SPrakash Surya static multilist_sublist_t *
6537244781f1SPrakash Surya l2arc_sublist_lock(int list_num)
6538fa94a07fSbrendan {
6539244781f1SPrakash Surya 	multilist_t *ml = NULL;
6540244781f1SPrakash Surya 	unsigned int idx;
6541fa94a07fSbrendan 
6542fa94a07fSbrendan 	ASSERT(list_num >= 0 && list_num <= 3);
6543fa94a07fSbrendan 
6544fa94a07fSbrendan 	switch (list_num) {
6545fa94a07fSbrendan 	case 0:
6546*94c2d0ebSMatthew Ahrens 		ml = arc_mfu->arcs_list[ARC_BUFC_METADATA];
6547fa94a07fSbrendan 		break;
6548fa94a07fSbrendan 	case 1:
6549*94c2d0ebSMatthew Ahrens 		ml = arc_mru->arcs_list[ARC_BUFC_METADATA];
6550fa94a07fSbrendan 		break;
6551fa94a07fSbrendan 	case 2:
6552*94c2d0ebSMatthew Ahrens 		ml = arc_mfu->arcs_list[ARC_BUFC_DATA];
6553fa94a07fSbrendan 		break;
6554fa94a07fSbrendan 	case 3:
6555*94c2d0ebSMatthew Ahrens 		ml = arc_mru->arcs_list[ARC_BUFC_DATA];
6556fa94a07fSbrendan 		break;
6557fa94a07fSbrendan 	}
6558fa94a07fSbrendan 
6559244781f1SPrakash Surya 	/*
6560244781f1SPrakash Surya 	 * Return a randomly-selected sublist. This is acceptable
6561244781f1SPrakash Surya 	 * because the caller feeds only a little bit of data for each
6562244781f1SPrakash Surya 	 * call (8MB). Subsequent calls will result in different
6563244781f1SPrakash Surya 	 * sublists being selected.
6564244781f1SPrakash Surya 	 */
6565244781f1SPrakash Surya 	idx = multilist_get_random_index(ml);
6566244781f1SPrakash Surya 	return (multilist_sublist_lock(ml, idx));
6567fa94a07fSbrendan }
6568fa94a07fSbrendan 
6569fa94a07fSbrendan /*
6570fa94a07fSbrendan  * Evict buffers from the device write hand to the distance specified in
6571fa94a07fSbrendan  * bytes.  This distance may span populated buffers, it may span nothing.
6572fa94a07fSbrendan  * This is clearing a region on the L2ARC device ready for writing.
6573fa94a07fSbrendan  * If the 'all' boolean is set, every buffer is evicted.
6574fa94a07fSbrendan  */
6575fa94a07fSbrendan static void
6576fa94a07fSbrendan l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
6577fa94a07fSbrendan {
6578fa94a07fSbrendan 	list_t *buflist;
65797adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr, *hdr_prev;
6580fa94a07fSbrendan 	kmutex_t *hash_lock;
6581fa94a07fSbrendan 	uint64_t taddr;
6582fa94a07fSbrendan 
658389c86e32SChris Williamson 	buflist = &dev->l2ad_buflist;
6584fa94a07fSbrendan 
6585fa94a07fSbrendan 	if (!all && dev->l2ad_first) {
6586fa94a07fSbrendan 		/*
6587fa94a07fSbrendan 		 * This is the first sweep through the device.  There is
6588fa94a07fSbrendan 		 * nothing to evict.
6589fa94a07fSbrendan 		 */
6590fa94a07fSbrendan 		return;
6591fa94a07fSbrendan 	}
6592fa94a07fSbrendan 
65933a737e0dSbrendan 	if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
6594fa94a07fSbrendan 		/*
6595fa94a07fSbrendan 		 * When nearing the end of the device, evict to the end
6596fa94a07fSbrendan 		 * before the device write hand jumps to the start.
6597fa94a07fSbrendan 		 */
6598fa94a07fSbrendan 		taddr = dev->l2ad_end;
6599fa94a07fSbrendan 	} else {
6600fa94a07fSbrendan 		taddr = dev->l2ad_hand + distance;
6601fa94a07fSbrendan 	}
6602fa94a07fSbrendan 	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
6603fa94a07fSbrendan 	    uint64_t, taddr, boolean_t, all);
6604fa94a07fSbrendan 
6605fa94a07fSbrendan top:
660689c86e32SChris Williamson 	mutex_enter(&dev->l2ad_mtx);
66077adb730bSGeorge Wilson 	for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
66087adb730bSGeorge Wilson 		hdr_prev = list_prev(buflist, hdr);
6609fa94a07fSbrendan 
66107adb730bSGeorge Wilson 		hash_lock = HDR_LOCK(hdr);
6611244781f1SPrakash Surya 
6612244781f1SPrakash Surya 		/*
6613244781f1SPrakash Surya 		 * We cannot use mutex_enter or else we can deadlock
6614244781f1SPrakash Surya 		 * with l2arc_write_buffers (due to swapping the order
6615244781f1SPrakash Surya 		 * the hash lock and l2ad_mtx are taken).
6616244781f1SPrakash Surya 		 */
6617fa94a07fSbrendan 		if (!mutex_tryenter(hash_lock)) {
6618fa94a07fSbrendan 			/*
6619fa94a07fSbrendan 			 * Missed the hash lock.  Retry.
6620fa94a07fSbrendan 			 */
6621fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
662289c86e32SChris Williamson 			mutex_exit(&dev->l2ad_mtx);
6623fa94a07fSbrendan 			mutex_enter(hash_lock);
6624fa94a07fSbrendan 			mutex_exit(hash_lock);
6625fa94a07fSbrendan 			goto top;
6626fa94a07fSbrendan 		}
6627fa94a07fSbrendan 
66287adb730bSGeorge Wilson 		if (HDR_L2_WRITE_HEAD(hdr)) {
6629fa94a07fSbrendan 			/*
6630fa94a07fSbrendan 			 * We hit a write head node.  Leave it for
6631fa94a07fSbrendan 			 * l2arc_write_done().
6632fa94a07fSbrendan 			 */
66337adb730bSGeorge Wilson 			list_remove(buflist, hdr);
6634fa94a07fSbrendan 			mutex_exit(hash_lock);
6635fa94a07fSbrendan 			continue;
6636fa94a07fSbrendan 		}
6637fa94a07fSbrendan 
663889c86e32SChris Williamson 		if (!all && HDR_HAS_L2HDR(hdr) &&
663989c86e32SChris Williamson 		    (hdr->b_l2hdr.b_daddr > taddr ||
664089c86e32SChris Williamson 		    hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
6641fa94a07fSbrendan 			/*
6642fa94a07fSbrendan 			 * We've evicted to the target address,
6643fa94a07fSbrendan 			 * or the end of the device.
6644fa94a07fSbrendan 			 */
6645fa94a07fSbrendan 			mutex_exit(hash_lock);
6646fa94a07fSbrendan 			break;
6647fa94a07fSbrendan 		}
6648fa94a07fSbrendan 
664989c86e32SChris Williamson 		ASSERT(HDR_HAS_L2HDR(hdr));
665089c86e32SChris Williamson 		if (!HDR_HAS_L1HDR(hdr)) {
66517adb730bSGeorge Wilson 			ASSERT(!HDR_L2_READING(hdr));
6652fa94a07fSbrendan 			/*
6653fa94a07fSbrendan 			 * This doesn't exist in the ARC.  Destroy.
6654fa94a07fSbrendan 			 * arc_hdr_destroy() will call list_remove()
6655fa94a07fSbrendan 			 * and decrement arcstat_l2_size.
6656fa94a07fSbrendan 			 */
66577adb730bSGeorge Wilson 			arc_change_state(arc_anon, hdr, hash_lock);
66587adb730bSGeorge Wilson 			arc_hdr_destroy(hdr);
6659fa94a07fSbrendan 		} else {
666089c86e32SChris Williamson 			ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
666189c86e32SChris Williamson 			ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
66623a737e0dSbrendan 			/*
66633a737e0dSbrendan 			 * Invalidate issued or about to be issued
66643a737e0dSbrendan 			 * reads, since we may be about to write
66653a737e0dSbrendan 			 * over this location.
66663a737e0dSbrendan 			 */
66677adb730bSGeorge Wilson 			if (HDR_L2_READING(hdr)) {
66683a737e0dSbrendan 				ARCSTAT_BUMP(arcstat_l2_evict_reading);
6669dcbf3bd6SGeorge Wilson 				arc_hdr_set_flags(hdr, ARC_FLAG_L2_EVICTED);
66703a737e0dSbrendan 			}
66713a737e0dSbrendan 
6672244781f1SPrakash Surya 			/* Ensure this header has finished being written */
6673244781f1SPrakash Surya 			ASSERT(!HDR_L2_WRITING(hdr));
6674a52fc310SPrakash Surya 
6675a52fc310SPrakash Surya 			arc_hdr_l2hdr_destroy(hdr);
6676fa94a07fSbrendan 		}
6677fa94a07fSbrendan 		mutex_exit(hash_lock);
6678fa94a07fSbrendan 	}
667989c86e32SChris Williamson 	mutex_exit(&dev->l2ad_mtx);
6680fa94a07fSbrendan }
6681fa94a07fSbrendan 
6682fa94a07fSbrendan /*
6683fa94a07fSbrendan  * Find and write ARC buffers to the L2ARC device.
6684fa94a07fSbrendan  *
66857adb730bSGeorge Wilson  * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
6686fa94a07fSbrendan  * for reading until they have completed writing.
6687aad02571SSaso Kiselkov  * The headroom_boost is an in-out parameter used to maintain headroom boost
6688aad02571SSaso Kiselkov  * state between calls to this function.
6689aad02571SSaso Kiselkov  *
6690aad02571SSaso Kiselkov  * Returns the number of bytes actually written (which may be smaller than
6691aad02571SSaso Kiselkov  * the delta by which the device hand has changed due to alignment).
6692fa94a07fSbrendan  */
66935a98e54bSBrendan Gregg - Sun Microsystems static uint64_t
6694dcbf3bd6SGeorge Wilson l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
6695fa94a07fSbrendan {
66967adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr, *hdr_prev, *head;
6697dcbf3bd6SGeorge Wilson 	uint64_t write_asize, write_psize, write_sz, headroom;
6698aad02571SSaso Kiselkov 	boolean_t full;
6699fa94a07fSbrendan 	l2arc_write_callback_t *cb;
6700fa94a07fSbrendan 	zio_t *pio, *wzio;
6701e9103aaeSGarrett D'Amore 	uint64_t guid = spa_load_guid(spa);
6702fa94a07fSbrendan 
6703dcbf3bd6SGeorge Wilson 	ASSERT3P(dev->l2ad_vdev, !=, NULL);
6704aad02571SSaso Kiselkov 
6705fa94a07fSbrendan 	pio = NULL;
6706dcbf3bd6SGeorge Wilson 	write_sz = write_asize = write_psize = 0;
6707fa94a07fSbrendan 	full = B_FALSE;
670889c86e32SChris Williamson 	head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
6709dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(head, ARC_FLAG_L2_WRITE_HEAD | ARC_FLAG_HAS_L2HDR);
6710aad02571SSaso Kiselkov 
6711fa94a07fSbrendan 	/*
6712fa94a07fSbrendan 	 * Copy buffers for L2ARC writing.
6713fa94a07fSbrendan 	 */
6714fa94a07fSbrendan 	for (int try = 0; try <= 3; try++) {
6715244781f1SPrakash Surya 		multilist_sublist_t *mls = l2arc_sublist_lock(try);
6716aad02571SSaso Kiselkov 		uint64_t passed_sz = 0;
6717aad02571SSaso Kiselkov 
67183a737e0dSbrendan 		/*
67193a737e0dSbrendan 		 * L2ARC fast warmup.
67203a737e0dSbrendan 		 *
67213a737e0dSbrendan 		 * Until the ARC is warm and starts to evict, read from the
67223a737e0dSbrendan 		 * head of the ARC lists rather than the tail.
67233a737e0dSbrendan 		 */
67243a737e0dSbrendan 		if (arc_warm == B_FALSE)
6725244781f1SPrakash Surya 			hdr = multilist_sublist_head(mls);
67263a737e0dSbrendan 		else
6727244781f1SPrakash Surya 			hdr = multilist_sublist_tail(mls);
67283a737e0dSbrendan 
6729aad02571SSaso Kiselkov 		headroom = target_sz * l2arc_headroom;
6730dcbf3bd6SGeorge Wilson 		if (zfs_compressed_arc_enabled)
6731aad02571SSaso Kiselkov 			headroom = (headroom * l2arc_headroom_boost) / 100;
6732aad02571SSaso Kiselkov 
67337adb730bSGeorge Wilson 		for (; hdr; hdr = hdr_prev) {
6734aad02571SSaso Kiselkov 			kmutex_t *hash_lock;
6735aad02571SSaso Kiselkov 
67363a737e0dSbrendan 			if (arc_warm == B_FALSE)
6737244781f1SPrakash Surya 				hdr_prev = multilist_sublist_next(mls, hdr);
67383a737e0dSbrendan 			else
6739244781f1SPrakash Surya 				hdr_prev = multilist_sublist_prev(mls, hdr);
6740fa94a07fSbrendan 
67417adb730bSGeorge Wilson 			hash_lock = HDR_LOCK(hdr);
6742aad02571SSaso Kiselkov 			if (!mutex_tryenter(hash_lock)) {
6743fa94a07fSbrendan 				/*
6744fa94a07fSbrendan 				 * Skip this buffer rather than waiting.
6745fa94a07fSbrendan 				 */
6746fa94a07fSbrendan 				continue;
6747fa94a07fSbrendan 			}
6748fa94a07fSbrendan 
6749dcbf3bd6SGeorge Wilson 			passed_sz += HDR_GET_LSIZE(hdr);
6750fa94a07fSbrendan 			if (passed_sz > headroom) {
6751fa94a07fSbrendan 				/*
6752fa94a07fSbrendan 				 * Searched too far.
6753fa94a07fSbrendan 				 */
6754fa94a07fSbrendan 				mutex_exit(hash_lock);
6755fa94a07fSbrendan 				break;
6756fa94a07fSbrendan 			}
6757fa94a07fSbrendan 
67587adb730bSGeorge Wilson 			if (!l2arc_write_eligible(guid, hdr)) {
6759fa94a07fSbrendan 				mutex_exit(hash_lock);
6760fa94a07fSbrendan 				continue;
6761fa94a07fSbrendan 			}
6762fa94a07fSbrendan 
6763dcbf3bd6SGeorge Wilson 			if ((write_asize + HDR_GET_LSIZE(hdr)) > target_sz) {
6764fa94a07fSbrendan 				full = B_TRUE;
6765fa94a07fSbrendan 				mutex_exit(hash_lock);
6766fa94a07fSbrendan 				break;
6767fa94a07fSbrendan 			}
6768fa94a07fSbrendan 
6769fa94a07fSbrendan 			if (pio == NULL) {
6770fa94a07fSbrendan 				/*
6771fa94a07fSbrendan 				 * Insert a dummy header on the buflist so
6772fa94a07fSbrendan 				 * l2arc_write_done() can find where the
6773fa94a07fSbrendan 				 * write buffers begin without searching.
6774fa94a07fSbrendan 				 */
6775244781f1SPrakash Surya 				mutex_enter(&dev->l2ad_mtx);
677689c86e32SChris Williamson 				list_insert_head(&dev->l2ad_buflist, head);
6777244781f1SPrakash Surya 				mutex_exit(&dev->l2ad_mtx);
6778fa94a07fSbrendan 
6779fa94a07fSbrendan 				cb = kmem_alloc(
6780fa94a07fSbrendan 				    sizeof (l2arc_write_callback_t), KM_SLEEP);
6781fa94a07fSbrendan 				cb->l2wcb_dev = dev;
6782fa94a07fSbrendan 				cb->l2wcb_head = head;
6783fa94a07fSbrendan 				pio = zio_root(spa, l2arc_write_done, cb,
6784fa94a07fSbrendan 				    ZIO_FLAG_CANFAIL);
6785fa94a07fSbrendan 			}
6786fa94a07fSbrendan 
678789c86e32SChris Williamson 			hdr->b_l2hdr.b_dev = dev;
6788dcbf3bd6SGeorge Wilson 			hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
6789dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr,
6790dcbf3bd6SGeorge Wilson 			    ARC_FLAG_L2_WRITING | ARC_FLAG_HAS_L2HDR);
6791dcbf3bd6SGeorge Wilson 
6792dcbf3bd6SGeorge Wilson 			mutex_enter(&dev->l2ad_mtx);
6793dcbf3bd6SGeorge Wilson 			list_insert_head(&dev->l2ad_buflist, hdr);
6794dcbf3bd6SGeorge Wilson 			mutex_exit(&dev->l2ad_mtx);
6795dcbf3bd6SGeorge Wilson 
6796aad02571SSaso Kiselkov 			/*
6797dcbf3bd6SGeorge Wilson 			 * We rely on the L1 portion of the header below, so
6798dcbf3bd6SGeorge Wilson 			 * it's invalid for this header to have been evicted out
6799dcbf3bd6SGeorge Wilson 			 * of the ghost cache, prior to being written out. The
6800dcbf3bd6SGeorge Wilson 			 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
6801aad02571SSaso Kiselkov 			 */
6802dcbf3bd6SGeorge Wilson 			ASSERT(HDR_HAS_L1HDR(hdr));
6803dcbf3bd6SGeorge Wilson 
6804dcbf3bd6SGeorge Wilson 			ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
6805dcbf3bd6SGeorge Wilson 			ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
6806dcbf3bd6SGeorge Wilson 			ASSERT3U(arc_hdr_size(hdr), >, 0);
6807dcbf3bd6SGeorge Wilson 			uint64_t size = arc_hdr_size(hdr);
6808dcbf3bd6SGeorge Wilson 
6809dcbf3bd6SGeorge Wilson 			(void) refcount_add_many(&dev->l2ad_alloc, size, hdr);
6810aad02571SSaso Kiselkov 
6811a52fc310SPrakash Surya 			/*
6812dcbf3bd6SGeorge Wilson 			 * Normally the L2ARC can use the hdr's data, but if
6813dcbf3bd6SGeorge Wilson 			 * we're sharing data between the hdr and one of its
6814dcbf3bd6SGeorge Wilson 			 * bufs, L2ARC needs its own copy of the data so that
6815dcbf3bd6SGeorge Wilson 			 * the ZIO below can't race with the buf consumer. To
6816dcbf3bd6SGeorge Wilson 			 * ensure that this copy will be available for the
6817dcbf3bd6SGeorge Wilson 			 * lifetime of the ZIO and be cleaned up afterwards, we
6818dcbf3bd6SGeorge Wilson 			 * add it to the l2arc_free_on_write queue.
6819a52fc310SPrakash Surya 			 */
6820dcbf3bd6SGeorge Wilson 			void *to_write;
6821dcbf3bd6SGeorge Wilson 			if (!HDR_SHARED_DATA(hdr)) {
6822dcbf3bd6SGeorge Wilson 				to_write = hdr->b_l1hdr.b_pdata;
6823dcbf3bd6SGeorge Wilson 			} else {
6824dcbf3bd6SGeorge Wilson 				arc_buf_contents_t type = arc_buf_type(hdr);
6825dcbf3bd6SGeorge Wilson 				if (type == ARC_BUFC_METADATA) {
6826dcbf3bd6SGeorge Wilson 					to_write = zio_buf_alloc(size);
6827dcbf3bd6SGeorge Wilson 				} else {
6828dcbf3bd6SGeorge Wilson 					ASSERT3U(type, ==, ARC_BUFC_DATA);
6829dcbf3bd6SGeorge Wilson 					to_write = zio_data_buf_alloc(size);
6830dcbf3bd6SGeorge Wilson 				}
6831a52fc310SPrakash Surya 
6832dcbf3bd6SGeorge Wilson 				bcopy(hdr->b_l1hdr.b_pdata, to_write, size);
6833dcbf3bd6SGeorge Wilson 				l2arc_free_data_on_write(to_write, size, type);
6834dcbf3bd6SGeorge Wilson 			}
6835dcbf3bd6SGeorge Wilson 			wzio = zio_write_phys(pio, dev->l2ad_vdev,
6836dcbf3bd6SGeorge Wilson 			    hdr->b_l2hdr.b_daddr, size, to_write,
6837dcbf3bd6SGeorge Wilson 			    ZIO_CHECKSUM_OFF, NULL, hdr,
6838dcbf3bd6SGeorge Wilson 			    ZIO_PRIORITY_ASYNC_WRITE,
6839dcbf3bd6SGeorge Wilson 			    ZIO_FLAG_CANFAIL, B_FALSE);
6840aad02571SSaso Kiselkov 
6841dcbf3bd6SGeorge Wilson 			write_sz += HDR_GET_LSIZE(hdr);
6842dcbf3bd6SGeorge Wilson 			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
6843dcbf3bd6SGeorge Wilson 			    zio_t *, wzio);
6844fa94a07fSbrendan 
6845dcbf3bd6SGeorge Wilson 			write_asize += size;
6846fa94a07fSbrendan 			/*
6847dcbf3bd6SGeorge Wilson 			 * Keep the clock hand suitably device-aligned.
6848fa94a07fSbrendan 			 */
6849dcbf3bd6SGeorge Wilson 			uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev,
6850dcbf3bd6SGeorge Wilson 			    size);
6851dcbf3bd6SGeorge Wilson 			write_psize += asize;
6852dcbf3bd6SGeorge Wilson 			dev->l2ad_hand += asize;
6853fa94a07fSbrendan 
6854fa94a07fSbrendan 			mutex_exit(hash_lock);
6855fa94a07fSbrendan 
6856dcbf3bd6SGeorge Wilson 			(void) zio_nowait(wzio);
6857aad02571SSaso Kiselkov 		}
6858aad02571SSaso Kiselkov 
6859244781f1SPrakash Surya 		multilist_sublist_unlock(mls);
6860aad02571SSaso Kiselkov 
6861aad02571SSaso Kiselkov 		if (full == B_TRUE)
6862aad02571SSaso Kiselkov 			break;
6863aad02571SSaso Kiselkov 	}
6864aad02571SSaso Kiselkov 
6865aad02571SSaso Kiselkov 	/* No buffers selected for writing? */
6866aad02571SSaso Kiselkov 	if (pio == NULL) {
6867aad02571SSaso Kiselkov 		ASSERT0(write_sz);
686889c86e32SChris Williamson 		ASSERT(!HDR_HAS_L1HDR(head));
686989c86e32SChris Williamson 		kmem_cache_free(hdr_l2only_cache, head);
6870aad02571SSaso Kiselkov 		return (0);
6871aad02571SSaso Kiselkov 	}
6872aad02571SSaso Kiselkov 
6873aad02571SSaso Kiselkov 	ASSERT3U(write_asize, <=, target_sz);
6874fa94a07fSbrendan 	ARCSTAT_BUMP(arcstat_l2_writes_sent);
6875aad02571SSaso Kiselkov 	ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
6876fa94a07fSbrendan 	ARCSTAT_INCR(arcstat_l2_size, write_sz);
6877dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_l2_asize, write_asize);
6878dcbf3bd6SGeorge Wilson 	vdev_space_update(dev->l2ad_vdev, write_asize, 0, 0);
6879fa94a07fSbrendan 
6880fa94a07fSbrendan 	/*
6881fa94a07fSbrendan 	 * Bump device hand to the device start if it is approaching the end.
6882fa94a07fSbrendan 	 * l2arc_evict() will already have evicted ahead for this case.
6883fa94a07fSbrendan 	 */
68843a737e0dSbrendan 	if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
6885fa94a07fSbrendan 		dev->l2ad_hand = dev->l2ad_start;
6886fa94a07fSbrendan 		dev->l2ad_first = B_FALSE;
6887fa94a07fSbrendan 	}
6888fa94a07fSbrendan 
68895a98e54bSBrendan Gregg - Sun Microsystems 	dev->l2ad_writing = B_TRUE;
6890fa94a07fSbrendan 	(void) zio_wait(pio);
68915a98e54bSBrendan Gregg - Sun Microsystems 	dev->l2ad_writing = B_FALSE;
68925a98e54bSBrendan Gregg - Sun Microsystems 
6893aad02571SSaso Kiselkov 	return (write_asize);
6894aad02571SSaso Kiselkov }
6895aad02571SSaso Kiselkov 
6896fa94a07fSbrendan /*
6897fa94a07fSbrendan  * This thread feeds the L2ARC at regular intervals.  This is the beating
6898fa94a07fSbrendan  * heart of the L2ARC.
6899fa94a07fSbrendan  */
6900fa94a07fSbrendan static void
6901fa94a07fSbrendan l2arc_feed_thread(void)
6902fa94a07fSbrendan {
6903fa94a07fSbrendan 	callb_cpr_t cpr;
6904fa94a07fSbrendan 	l2arc_dev_t *dev;
6905fa94a07fSbrendan 	spa_t *spa;
69065a98e54bSBrendan Gregg - Sun Microsystems 	uint64_t size, wrote;
6907d3d50737SRafael Vanoni 	clock_t begin, next = ddi_get_lbolt();
6908fa94a07fSbrendan 
6909fa94a07fSbrendan 	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
6910fa94a07fSbrendan 
6911fa94a07fSbrendan 	mutex_enter(&l2arc_feed_thr_lock);
6912fa94a07fSbrendan 
6913fa94a07fSbrendan 	while (l2arc_thread_exit == 0) {
6914fa94a07fSbrendan 		CALLB_CPR_SAFE_BEGIN(&cpr);
6915fa94a07fSbrendan 		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
69165a98e54bSBrendan Gregg - Sun Microsystems 		    next);
6917fa94a07fSbrendan 		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
6918d3d50737SRafael Vanoni 		next = ddi_get_lbolt() + hz;
6919fa94a07fSbrendan 
69203a737e0dSbrendan 		/*
69213a737e0dSbrendan 		 * Quick check for L2ARC devices.
69223a737e0dSbrendan 		 */
6923c5904d13Seschrock 		mutex_enter(&l2arc_dev_mtx);
69243a737e0dSbrendan 		if (l2arc_ndev == 0) {
69253a737e0dSbrendan 			mutex_exit(&l2arc_dev_mtx);
69263a737e0dSbrendan 			continue;
69273a737e0dSbrendan 		}
69283a737e0dSbrendan 		mutex_exit(&l2arc_dev_mtx);
6929d3d50737SRafael Vanoni 		begin = ddi_get_lbolt();
6930c5904d13Seschrock 
6931fa94a07fSbrendan 		/*
6932c5904d13Seschrock 		 * This selects the next l2arc device to write to, and in
6933c5904d13Seschrock 		 * doing so the next spa to feed from: dev->l2ad_spa.   This
69343a737e0dSbrendan 		 * will return NULL if there are now no l2arc devices or if
69353a737e0dSbrendan 		 * they are all faulted.
69363a737e0dSbrendan 		 *
69373a737e0dSbrendan 		 * If a device is returned, its spa's config lock is also
69383a737e0dSbrendan 		 * held to prevent device removal.  l2arc_dev_get_next()
69393a737e0dSbrendan 		 * will grab and release l2arc_dev_mtx.
6940fa94a07fSbrendan 		 */
69413a737e0dSbrendan 		if ((dev = l2arc_dev_get_next()) == NULL)
6942fa94a07fSbrendan 			continue;
69433a737e0dSbrendan 
69443a737e0dSbrendan 		spa = dev->l2ad_spa;
6945dcbf3bd6SGeorge Wilson 		ASSERT3P(spa, !=, NULL);
6946fa94a07fSbrendan 
6947f9af39baSGeorge Wilson 		/*
6948f9af39baSGeorge Wilson 		 * If the pool is read-only then force the feed thread to
6949f9af39baSGeorge Wilson 		 * sleep a little longer.
6950f9af39baSGeorge Wilson 		 */
6951f9af39baSGeorge Wilson 		if (!spa_writeable(spa)) {
6952f9af39baSGeorge Wilson 			next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
6953f9af39baSGeorge Wilson 			spa_config_exit(spa, SCL_L2ARC, dev);
6954f9af39baSGeorge Wilson 			continue;
6955f9af39baSGeorge Wilson 		}
6956f9af39baSGeorge Wilson 
6957fa94a07fSbrendan 		/*
6958fa94a07fSbrendan 		 * Avoid contributing to memory pressure.
6959fa94a07fSbrendan 		 */
6960fa94a07fSbrendan 		if (arc_reclaim_needed()) {
6961fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
6962e14bb325SJeff Bonwick 			spa_config_exit(spa, SCL_L2ARC, dev);
6963fa94a07fSbrendan 			continue;
6964fa94a07fSbrendan 		}
6965fa94a07fSbrendan 
6966fa94a07fSbrendan 		ARCSTAT_BUMP(arcstat_l2_feeds);
6967fa94a07fSbrendan 
6968aad02571SSaso Kiselkov 		size = l2arc_write_size();
69693a737e0dSbrendan 
6970fa94a07fSbrendan 		/*
6971fa94a07fSbrendan 		 * Evict L2ARC buffers that will be overwritten.
6972fa94a07fSbrendan 		 */
69733a737e0dSbrendan 		l2arc_evict(dev, size, B_FALSE);
6974fa94a07fSbrendan 
6975fa94a07fSbrendan 		/*
6976fa94a07fSbrendan 		 * Write ARC buffers.
6977fa94a07fSbrendan 		 */
6978dcbf3bd6SGeorge Wilson 		wrote = l2arc_write_buffers(spa, dev, size);
69795a98e54bSBrendan Gregg - Sun Microsystems 
69805a98e54bSBrendan Gregg - Sun Microsystems 		/*
69815a98e54bSBrendan Gregg - Sun Microsystems 		 * Calculate interval between writes.
69825a98e54bSBrendan Gregg - Sun Microsystems 		 */
69835a98e54bSBrendan Gregg - Sun Microsystems 		next = l2arc_write_interval(begin, size, wrote);
6984e14bb325SJeff Bonwick 		spa_config_exit(spa, SCL_L2ARC, dev);
6985fa94a07fSbrendan 	}
6986fa94a07fSbrendan 
6987fa94a07fSbrendan 	l2arc_thread_exit = 0;
6988fa94a07fSbrendan 	cv_broadcast(&l2arc_feed_thr_cv);
6989fa94a07fSbrendan 	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
6990fa94a07fSbrendan 	thread_exit();
6991fa94a07fSbrendan }
6992fa94a07fSbrendan 
6993c5904d13Seschrock boolean_t
6994c5904d13Seschrock l2arc_vdev_present(vdev_t *vd)
6995c5904d13Seschrock {
6996c5904d13Seschrock 	l2arc_dev_t *dev;
6997c5904d13Seschrock 
6998c5904d13Seschrock 	mutex_enter(&l2arc_dev_mtx);
6999c5904d13Seschrock 	for (dev = list_head(l2arc_dev_list); dev != NULL;
7000c5904d13Seschrock 	    dev = list_next(l2arc_dev_list, dev)) {
7001c5904d13Seschrock 		if (dev->l2ad_vdev == vd)
7002c5904d13Seschrock 			break;
7003c5904d13Seschrock 	}
7004c5904d13Seschrock 	mutex_exit(&l2arc_dev_mtx);
7005c5904d13Seschrock 
7006c5904d13Seschrock 	return (dev != NULL);
7007c5904d13Seschrock }
7008c5904d13Seschrock 
7009fa94a07fSbrendan /*
7010fa94a07fSbrendan  * Add a vdev for use by the L2ARC.  By this point the spa has already
7011fa94a07fSbrendan  * validated the vdev and opened it.
7012fa94a07fSbrendan  */
7013fa94a07fSbrendan void
7014573ca77eSGeorge Wilson l2arc_add_vdev(spa_t *spa, vdev_t *vd)
7015fa94a07fSbrendan {
7016fa94a07fSbrendan 	l2arc_dev_t *adddev;
7017fa94a07fSbrendan 
7018c5904d13Seschrock 	ASSERT(!l2arc_vdev_present(vd));
7019c5904d13Seschrock 
7020fa94a07fSbrendan 	/*
7021fa94a07fSbrendan 	 * Create a new l2arc device entry.
7022fa94a07fSbrendan 	 */
7023fa94a07fSbrendan 	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
7024fa94a07fSbrendan 	adddev->l2ad_spa = spa;
7025fa94a07fSbrendan 	adddev->l2ad_vdev = vd;
7026573ca77eSGeorge Wilson 	adddev->l2ad_start = VDEV_LABEL_START_SIZE;
7027573ca77eSGeorge Wilson 	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
7028fa94a07fSbrendan 	adddev->l2ad_hand = adddev->l2ad_start;
7029fa94a07fSbrendan 	adddev->l2ad_first = B_TRUE;
70305a98e54bSBrendan Gregg - Sun Microsystems 	adddev->l2ad_writing = B_FALSE;
7031fa94a07fSbrendan 
703289c86e32SChris Williamson 	mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
7033fa94a07fSbrendan 	/*
7034fa94a07fSbrendan 	 * This is a list of all ARC buffers that are still valid on the
7035fa94a07fSbrendan 	 * device.
7036fa94a07fSbrendan 	 */
703789c86e32SChris Williamson 	list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
703889c86e32SChris Williamson 	    offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
7039fa94a07fSbrendan 
7040b24ab676SJeff Bonwick 	vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
7041a52fc310SPrakash Surya 	refcount_create(&adddev->l2ad_alloc);
7042fa94a07fSbrendan 
7043fa94a07fSbrendan 	/*
7044fa94a07fSbrendan 	 * Add device to global list
7045fa94a07fSbrendan 	 */
7046fa94a07fSbrendan 	mutex_enter(&l2arc_dev_mtx);
7047fa94a07fSbrendan 	list_insert_head(l2arc_dev_list, adddev);
7048fa94a07fSbrendan 	atomic_inc_64(&l2arc_ndev);
7049fa94a07fSbrendan 	mutex_exit(&l2arc_dev_mtx);
7050fa94a07fSbrendan }
7051fa94a07fSbrendan 
7052fa94a07fSbrendan /*
7053fa94a07fSbrendan  * Remove a vdev from the L2ARC.
7054fa94a07fSbrendan  */
7055fa94a07fSbrendan void
7056fa94a07fSbrendan l2arc_remove_vdev(vdev_t *vd)
7057fa94a07fSbrendan {
7058fa94a07fSbrendan 	l2arc_dev_t *dev, *nextdev, *remdev = NULL;
7059fa94a07fSbrendan 
7060fa94a07fSbrendan 	/*
7061fa94a07fSbrendan 	 * Find the device by vdev
7062fa94a07fSbrendan 	 */
7063fa94a07fSbrendan 	mutex_enter(&l2arc_dev_mtx);
7064fa94a07fSbrendan 	for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
7065fa94a07fSbrendan 		nextdev = list_next(l2arc_dev_list, dev);
7066fa94a07fSbrendan 		if (vd == dev->l2ad_vdev) {
7067fa94a07fSbrendan 			remdev = dev;
7068fa94a07fSbrendan 			break;
7069fa94a07fSbrendan 		}
7070fa94a07fSbrendan 	}
7071dcbf3bd6SGeorge Wilson 	ASSERT3P(remdev, !=, NULL);
7072fa94a07fSbrendan 
7073fa94a07fSbrendan 	/*
7074fa94a07fSbrendan 	 * Remove device from global list
7075fa94a07fSbrendan 	 */
7076fa94a07fSbrendan 	list_remove(l2arc_dev_list, remdev);
7077fa94a07fSbrendan 	l2arc_dev_last = NULL;		/* may have been invalidated */
70783a737e0dSbrendan 	atomic_dec_64(&l2arc_ndev);
70793a737e0dSbrendan 	mutex_exit(&l2arc_dev_mtx);
7080fa94a07fSbrendan 
7081fa94a07fSbrendan 	/*
7082fa94a07fSbrendan 	 * Clear all buflists and ARC references.  L2ARC device flush.
7083fa94a07fSbrendan 	 */
7084fa94a07fSbrendan 	l2arc_evict(remdev, 0, B_TRUE);
708589c86e32SChris Williamson 	list_destroy(&remdev->l2ad_buflist);
708689c86e32SChris Williamson 	mutex_destroy(&remdev->l2ad_mtx);
7087a52fc310SPrakash Surya 	refcount_destroy(&remdev->l2ad_alloc);
7088fa94a07fSbrendan 	kmem_free(remdev, sizeof (l2arc_dev_t));
7089fa94a07fSbrendan }
7090fa94a07fSbrendan 
7091fa94a07fSbrendan void
7092e14bb325SJeff Bonwick l2arc_init(void)
7093fa94a07fSbrendan {
7094fa94a07fSbrendan 	l2arc_thread_exit = 0;
7095fa94a07fSbrendan 	l2arc_ndev = 0;
7096fa94a07fSbrendan 	l2arc_writes_sent = 0;
7097fa94a07fSbrendan 	l2arc_writes_done = 0;
7098fa94a07fSbrendan 
7099fa94a07fSbrendan 	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
7100fa94a07fSbrendan 	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
7101fa94a07fSbrendan 	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
7102fa94a07fSbrendan 	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
7103fa94a07fSbrendan 
7104fa94a07fSbrendan 	l2arc_dev_list = &L2ARC_dev_list;
7105fa94a07fSbrendan 	l2arc_free_on_write = &L2ARC_free_on_write;
7106fa94a07fSbrendan 	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
7107fa94a07fSbrendan 	    offsetof(l2arc_dev_t, l2ad_node));
7108fa94a07fSbrendan 	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
7109fa94a07fSbrendan 	    offsetof(l2arc_data_free_t, l2df_list_node));
7110fa94a07fSbrendan }
7111fa94a07fSbrendan 
7112fa94a07fSbrendan void
7113e14bb325SJeff Bonwick l2arc_fini(void)
7114fa94a07fSbrendan {
71153a737e0dSbrendan 	/*
71163a737e0dSbrendan 	 * This is called from dmu_fini(), which is called from spa_fini();
71173a737e0dSbrendan 	 * Because of this, we can assume that all l2arc devices have
71183a737e0dSbrendan 	 * already been removed when the pools themselves were removed.
71193a737e0dSbrendan 	 */
71203a737e0dSbrendan 
71213a737e0dSbrendan 	l2arc_do_free_on_write();
71223a737e0dSbrendan 
7123fa94a07fSbrendan 	mutex_destroy(&l2arc_feed_thr_lock);
7124fa94a07fSbrendan 	cv_destroy(&l2arc_feed_thr_cv);
7125fa94a07fSbrendan 	mutex_destroy(&l2arc_dev_mtx);
7126fa94a07fSbrendan 	mutex_destroy(&l2arc_free_on_write_mtx);
7127fa94a07fSbrendan 
7128fa94a07fSbrendan 	list_destroy(l2arc_dev_list);
7129fa94a07fSbrendan 	list_destroy(l2arc_free_on_write);
7130fa94a07fSbrendan }
7131e14bb325SJeff Bonwick 
7132e14bb325SJeff Bonwick void
7133e14bb325SJeff Bonwick l2arc_start(void)
7134e14bb325SJeff Bonwick {
71358ad4d6ddSJeff Bonwick 	if (!(spa_mode_global & FWRITE))
7136e14bb325SJeff Bonwick 		return;
7137e14bb325SJeff Bonwick 
7138e14bb325SJeff Bonwick 	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
7139e14bb325SJeff Bonwick 	    TS_RUN, minclsyspri);
7140e14bb325SJeff Bonwick }
7141e14bb325SJeff Bonwick 
7142e14bb325SJeff Bonwick void
7143e14bb325SJeff Bonwick l2arc_stop(void)
7144e14bb325SJeff Bonwick {
71458ad4d6ddSJeff Bonwick 	if (!(spa_mode_global & FWRITE))
7146e14bb325SJeff Bonwick 		return;
7147e14bb325SJeff Bonwick 
7148e14bb325SJeff Bonwick 	mutex_enter(&l2arc_feed_thr_lock);
7149e14bb325SJeff Bonwick 	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
7150e14bb325SJeff Bonwick 	l2arc_thread_exit = 1;
7151e14bb325SJeff Bonwick 	while (l2arc_thread_exit != 0)
7152e14bb325SJeff Bonwick 		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
7153e14bb325SJeff Bonwick 	mutex_exit(&l2arc_feed_thr_lock);
7154e14bb325SJeff Bonwick }
7155