xref: /illumos-gate/usr/src/uts/common/fs/zfs/arc.c (revision eb633035)
1fa9e4066Sahrens /*
2fa9e4066Sahrens  * CDDL HEADER START
3fa9e4066Sahrens  *
4fa9e4066Sahrens  * The contents of this file are subject to the terms of the
5033f9833Sek  * Common Development and Distribution License (the "License").
6033f9833Sek  * You may not use this file except in compliance with the License.
7fa9e4066Sahrens  *
8fa9e4066Sahrens  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9fa9e4066Sahrens  * or http://www.opensolaris.org/os/licensing.
10fa9e4066Sahrens  * See the License for the specific language governing permissions
11fa9e4066Sahrens  * and limitations under the License.
12fa9e4066Sahrens  *
13fa9e4066Sahrens  * When distributing Covered Code, include this CDDL HEADER in each
14fa9e4066Sahrens  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15fa9e4066Sahrens  * If applicable, add the following below this CDDL HEADER, with the
16fa9e4066Sahrens  * fields enclosed by brackets "[]" replaced with your own identifying
17fa9e4066Sahrens  * information: Portions Copyright [yyyy] [name of copyright owner]
18fa9e4066Sahrens  *
19fa9e4066Sahrens  * CDDL HEADER END
20fa9e4066Sahrens  */
21fa9e4066Sahrens /*
223f9d6ad7SLin Ling  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
2336a64e62STim Kordas  * Copyright (c) 2018, Joyent, Inc.
24fa98e487SMatthew Ahrens  * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
2571cb1b74SSaso Kiselkov  * Copyright (c) 2014 by Saso Kiselkov. All rights reserved.
2601a059eeSRoman Strashkin  * Copyright 2017 Nexenta Systems, Inc.  All rights reserved.
27fa9e4066Sahrens  */
28fa9e4066Sahrens 
29fa9e4066Sahrens /*
3044cb6abcSbmc  * DVA-based Adjustable Replacement Cache
31fa9e4066Sahrens  *
32ea8dc4b6Seschrock  * While much of the theory of operation used here is
33ea8dc4b6Seschrock  * based on the self-tuning, low overhead replacement cache
34fa9e4066Sahrens  * presented by Megiddo and Modha at FAST 2003, there are some
35fa9e4066Sahrens  * significant differences:
36fa9e4066Sahrens  *
37fa9e4066Sahrens  * 1. The Megiddo and Modha model assumes any page is evictable.
38fa9e4066Sahrens  * Pages in its cache cannot be "locked" into memory.  This makes
39fa9e4066Sahrens  * the eviction algorithm simple: evict the last page in the list.
40fa9e4066Sahrens  * This also make the performance characteristics easy to reason
41fa9e4066Sahrens  * about.  Our cache is not so simple.  At any given moment, some
42fa9e4066Sahrens  * subset of the blocks in the cache are un-evictable because we
43fa9e4066Sahrens  * have handed out a reference to them.  Blocks are only evictable
44fa9e4066Sahrens  * when there are no external references active.  This makes
45fa9e4066Sahrens  * eviction far more problematic:  we choose to evict the evictable
46fa9e4066Sahrens  * blocks that are the "lowest" in the list.
47fa9e4066Sahrens  *
48fa9e4066Sahrens  * There are times when it is not possible to evict the requested
49fa9e4066Sahrens  * space.  In these circumstances we are unable to adjust the cache
50fa9e4066Sahrens  * size.  To prevent the cache growing unbounded at these times we
51fa94a07fSbrendan  * implement a "cache throttle" that slows the flow of new data
52fa94a07fSbrendan  * into the cache until we can make space available.
53fa9e4066Sahrens  *
54fa9e4066Sahrens  * 2. The Megiddo and Modha model assumes a fixed cache size.
55fa9e4066Sahrens  * Pages are evicted when the cache is full and there is a cache
56fa9e4066Sahrens  * miss.  Our model has a variable sized cache.  It grows with
57fa94a07fSbrendan  * high use, but also tries to react to memory pressure from the
58fa9e4066Sahrens  * operating system: decreasing its size when system memory is
59fa9e4066Sahrens  * tight.
60fa9e4066Sahrens  *
61fa9e4066Sahrens  * 3. The Megiddo and Modha model assumes a fixed page size. All
62f7170741SWill Andrews  * elements of the cache are therefore exactly the same size.  So
63fa9e4066Sahrens  * when adjusting the cache size following a cache miss, its simply
64fa9e4066Sahrens  * a matter of choosing a single page to evict.  In our model, we
65fa9e4066Sahrens  * have variable sized cache blocks (rangeing from 512 bytes to
66f7170741SWill Andrews  * 128K bytes).  We therefore choose a set of blocks to evict to make
67fa9e4066Sahrens  * space for a cache miss that approximates as closely as possible
68fa9e4066Sahrens  * the space used by the new block.
69fa9e4066Sahrens  *
70fa9e4066Sahrens  * See also:  "ARC: A Self-Tuning, Low Overhead Replacement Cache"
71fa9e4066Sahrens  * by N. Megiddo & D. Modha, FAST 2003
72fa9e4066Sahrens  */
73fa9e4066Sahrens 
74fa9e4066Sahrens /*
75fa9e4066Sahrens  * The locking model:
76fa9e4066Sahrens  *
77fa9e4066Sahrens  * A new reference to a cache buffer can be obtained in two
78fa9e4066Sahrens  * ways: 1) via a hash table lookup using the DVA as a key,
79fa94a07fSbrendan  * or 2) via one of the ARC lists.  The arc_read() interface
805602294fSDan Kimmel  * uses method 1, while the internal ARC algorithms for
81f7170741SWill Andrews  * adjusting the cache use method 2.  We therefore provide two
82fa9e4066Sahrens  * types of locks: 1) the hash table lock array, and 2) the
835602294fSDan Kimmel  * ARC list locks.
84fa9e4066Sahrens  *
85fc98fea5SBart Coddens  * Buffers do not have their own mutexes, rather they rely on the
86fc98fea5SBart Coddens  * hash table mutexes for the bulk of their protection (i.e. most
87fc98fea5SBart Coddens  * fields in the arc_buf_hdr_t are protected by these mutexes).
88fa9e4066Sahrens  *
89fa9e4066Sahrens  * buf_hash_find() returns the appropriate mutex (held) when it
90fa9e4066Sahrens  * locates the requested buffer in the hash table.  It returns
91fa9e4066Sahrens  * NULL for the mutex if the buffer was not in the table.
92fa9e4066Sahrens  *
93fa9e4066Sahrens  * buf_hash_remove() expects the appropriate hash mutex to be
94fa9e4066Sahrens  * already held before it is invoked.
95fa9e4066Sahrens  *
965602294fSDan Kimmel  * Each ARC state also has a mutex which is used to protect the
97fa9e4066Sahrens  * buffer list associated with the state.  When attempting to
985602294fSDan Kimmel  * obtain a hash table lock while holding an ARC list lock you
99fa9e4066Sahrens  * must use: mutex_tryenter() to avoid deadlock.  Also note that
10044eda4d7Smaybee  * the active state mutex must be held before the ghost state mutex.
101fa9e4066Sahrens  *
102fa9e4066Sahrens  * Note that the majority of the performance stats are manipulated
103fa9e4066Sahrens  * with atomic operations.
104fa94a07fSbrendan  *
10589c86e32SChris Williamson  * The L2ARC uses the l2ad_mtx on each vdev for the following:
106fa94a07fSbrendan  *
107fa94a07fSbrendan  *	- L2ARC buflist creation
108fa94a07fSbrendan  *	- L2ARC buflist eviction
109fa94a07fSbrendan  *	- L2ARC write completion, which walks L2ARC buflists
110fa94a07fSbrendan  *	- ARC header destruction, as it removes from L2ARC buflists
111fa94a07fSbrendan  *	- ARC header release, as it removes from L2ARC buflists
112fa9e4066Sahrens  */
113fa9e4066Sahrens 
114dcbf3bd6SGeorge Wilson /*
115dcbf3bd6SGeorge Wilson  * ARC operation:
116dcbf3bd6SGeorge Wilson  *
117dcbf3bd6SGeorge Wilson  * Every block that is in the ARC is tracked by an arc_buf_hdr_t structure.
118dcbf3bd6SGeorge Wilson  * This structure can point either to a block that is still in the cache or to
119dcbf3bd6SGeorge Wilson  * one that is only accessible in an L2 ARC device, or it can provide
120dcbf3bd6SGeorge Wilson  * information about a block that was recently evicted. If a block is
121dcbf3bd6SGeorge Wilson  * only accessible in the L2ARC, then the arc_buf_hdr_t only has enough
122dcbf3bd6SGeorge Wilson  * information to retrieve it from the L2ARC device. This information is
123dcbf3bd6SGeorge Wilson  * stored in the l2arc_buf_hdr_t sub-structure of the arc_buf_hdr_t. A block
124dcbf3bd6SGeorge Wilson  * that is in this state cannot access the data directly.
125dcbf3bd6SGeorge Wilson  *
126dcbf3bd6SGeorge Wilson  * Blocks that are actively being referenced or have not been evicted
127dcbf3bd6SGeorge Wilson  * are cached in the L1ARC. The L1ARC (l1arc_buf_hdr_t) is a structure within
128dcbf3bd6SGeorge Wilson  * the arc_buf_hdr_t that will point to the data block in memory. A block can
129dcbf3bd6SGeorge Wilson  * only be read by a consumer if it has an l1arc_buf_hdr_t. The L1ARC
1305602294fSDan Kimmel  * caches data in two ways -- in a list of ARC buffers (arc_buf_t) and
131770499e1SDan Kimmel  * also in the arc_buf_hdr_t's private physical data block pointer (b_pabd).
1325602294fSDan Kimmel  *
1335602294fSDan Kimmel  * The L1ARC's data pointer may or may not be uncompressed. The ARC has the
134770499e1SDan Kimmel  * ability to store the physical data (b_pabd) associated with the DVA of the
135770499e1SDan Kimmel  * arc_buf_hdr_t. Since the b_pabd is a copy of the on-disk physical block,
1365602294fSDan Kimmel  * it will match its on-disk compression characteristics. This behavior can be
1375602294fSDan Kimmel  * disabled by setting 'zfs_compressed_arc_enabled' to B_FALSE. When the
138770499e1SDan Kimmel  * compressed ARC functionality is disabled, the b_pabd will point to an
1395602294fSDan Kimmel  * uncompressed version of the on-disk data.
1405602294fSDan Kimmel  *
1415602294fSDan Kimmel  * Data in the L1ARC is not accessed by consumers of the ARC directly. Each
1425602294fSDan Kimmel  * arc_buf_hdr_t can have multiple ARC buffers (arc_buf_t) which reference it.
1435602294fSDan Kimmel  * Each ARC buffer (arc_buf_t) is being actively accessed by a specific ARC
1445602294fSDan Kimmel  * consumer. The ARC will provide references to this data and will keep it
1455602294fSDan Kimmel  * cached until it is no longer in use. The ARC caches only the L1ARC's physical
1465602294fSDan Kimmel  * data block and will evict any arc_buf_t that is no longer referenced. The
1475602294fSDan Kimmel  * amount of memory consumed by the arc_buf_ts' data buffers can be seen via the
148dcbf3bd6SGeorge Wilson  * "overhead_size" kstat.
149dcbf3bd6SGeorge Wilson  *
1505602294fSDan Kimmel  * Depending on the consumer, an arc_buf_t can be requested in uncompressed or
1515602294fSDan Kimmel  * compressed form. The typical case is that consumers will want uncompressed
1525602294fSDan Kimmel  * data, and when that happens a new data buffer is allocated where the data is
1535602294fSDan Kimmel  * decompressed for them to use. Currently the only consumer who wants
1545602294fSDan Kimmel  * compressed arc_buf_t's is "zfs send", when it streams data exactly as it
1555602294fSDan Kimmel  * exists on disk. When this happens, the arc_buf_t's data buffer is shared
1565602294fSDan Kimmel  * with the arc_buf_hdr_t.
157dcbf3bd6SGeorge Wilson  *
1585602294fSDan Kimmel  * Here is a diagram showing an arc_buf_hdr_t referenced by two arc_buf_t's. The
1595602294fSDan Kimmel  * first one is owned by a compressed send consumer (and therefore references
1605602294fSDan Kimmel  * the same compressed data buffer as the arc_buf_hdr_t) and the second could be
1615602294fSDan Kimmel  * used by any other consumer (and has its own uncompressed copy of the data
1625602294fSDan Kimmel  * buffer).
163dcbf3bd6SGeorge Wilson  *
1645602294fSDan Kimmel  *   arc_buf_hdr_t
1655602294fSDan Kimmel  *   +-----------+
1665602294fSDan Kimmel  *   | fields    |
1675602294fSDan Kimmel  *   | common to |
1685602294fSDan Kimmel  *   | L1- and   |
1695602294fSDan Kimmel  *   | L2ARC     |
1705602294fSDan Kimmel  *   +-----------+
1715602294fSDan Kimmel  *   | l2arc_buf_hdr_t
1725602294fSDan Kimmel  *   |           |
1735602294fSDan Kimmel  *   +-----------+
1745602294fSDan Kimmel  *   | l1arc_buf_hdr_t
1755602294fSDan Kimmel  *   |           |              arc_buf_t
1765602294fSDan Kimmel  *   | b_buf     +------------>+-----------+      arc_buf_t
177770499e1SDan Kimmel  *   | b_pabd    +-+           |b_next     +---->+-----------+
1785602294fSDan Kimmel  *   +-----------+ |           |-----------|     |b_next     +-->NULL
1795602294fSDan Kimmel  *                 |           |b_comp = T |     +-----------+
1805602294fSDan Kimmel  *                 |           |b_data     +-+   |b_comp = F |
1815602294fSDan Kimmel  *                 |           +-----------+ |   |b_data     +-+
1825602294fSDan Kimmel  *                 +->+------+               |   +-----------+ |
1835602294fSDan Kimmel  *        compressed  |      |               |                 |
1845602294fSDan Kimmel  *           data     |      |<--------------+                 | uncompressed
1855602294fSDan Kimmel  *                    +------+          compressed,            |     data
1865602294fSDan Kimmel  *                                        shared               +-->+------+
1875602294fSDan Kimmel  *                                         data                    |      |
1885602294fSDan Kimmel  *                                                                 |      |
1895602294fSDan Kimmel  *                                                                 +------+
190dcbf3bd6SGeorge Wilson  *
191dcbf3bd6SGeorge Wilson  * When a consumer reads a block, the ARC must first look to see if the
1925602294fSDan Kimmel  * arc_buf_hdr_t is cached. If the hdr is cached then the ARC allocates a new
1935602294fSDan Kimmel  * arc_buf_t and either copies uncompressed data into a new data buffer from an
194770499e1SDan Kimmel  * existing uncompressed arc_buf_t, decompresses the hdr's b_pabd buffer into a
195770499e1SDan Kimmel  * new data buffer, or shares the hdr's b_pabd buffer, depending on whether the
1965602294fSDan Kimmel  * hdr is compressed and the desired compression characteristics of the
1975602294fSDan Kimmel  * arc_buf_t consumer. If the arc_buf_t ends up sharing data with the
1985602294fSDan Kimmel  * arc_buf_hdr_t and both of them are uncompressed then the arc_buf_t must be
1995602294fSDan Kimmel  * the last buffer in the hdr's b_buf list, however a shared compressed buf can
2005602294fSDan Kimmel  * be anywhere in the hdr's list.
201dcbf3bd6SGeorge Wilson  *
202dcbf3bd6SGeorge Wilson  * The diagram below shows an example of an uncompressed ARC hdr that is
2035602294fSDan Kimmel  * sharing its data with an arc_buf_t (note that the shared uncompressed buf is
2045602294fSDan Kimmel  * the last element in the buf list):
205dcbf3bd6SGeorge Wilson  *
206dcbf3bd6SGeorge Wilson  *                arc_buf_hdr_t
207dcbf3bd6SGeorge Wilson  *                +-----------+
208dcbf3bd6SGeorge Wilson  *                |           |
209dcbf3bd6SGeorge Wilson  *                |           |
210dcbf3bd6SGeorge Wilson  *                |           |
211dcbf3bd6SGeorge Wilson  *                +-----------+
212dcbf3bd6SGeorge Wilson  * l2arc_buf_hdr_t|           |
213dcbf3bd6SGeorge Wilson  *                |           |
214dcbf3bd6SGeorge Wilson  *                +-----------+
215dcbf3bd6SGeorge Wilson  * l1arc_buf_hdr_t|           |
216dcbf3bd6SGeorge Wilson  *                |           |                 arc_buf_t    (shared)
217dcbf3bd6SGeorge Wilson  *                |    b_buf  +------------>+---------+      arc_buf_t
218dcbf3bd6SGeorge Wilson  *                |           |             |b_next   +---->+---------+
219770499e1SDan Kimmel  *                |  b_pabd   +-+           |---------|     |b_next   +-->NULL
220dcbf3bd6SGeorge Wilson  *                +-----------+ |           |         |     +---------+
221dcbf3bd6SGeorge Wilson  *                              |           |b_data   +-+   |         |
222dcbf3bd6SGeorge Wilson  *                              |           +---------+ |   |b_data   +-+
223dcbf3bd6SGeorge Wilson  *                              +->+------+             |   +---------+ |
224dcbf3bd6SGeorge Wilson  *                                 |      |             |               |
225dcbf3bd6SGeorge Wilson  *                   uncompressed  |      |             |               |
226dcbf3bd6SGeorge Wilson  *                        data     +------+             |               |
227dcbf3bd6SGeorge Wilson  *                                    ^                 +->+------+     |
228dcbf3bd6SGeorge Wilson  *                                    |       uncompressed |      |     |
229dcbf3bd6SGeorge Wilson  *                                    |           data     |      |     |
230dcbf3bd6SGeorge Wilson  *                                    |                    +------+     |
231dcbf3bd6SGeorge Wilson  *                                    +---------------------------------+
232dcbf3bd6SGeorge Wilson  *
233770499e1SDan Kimmel  * Writing to the ARC requires that the ARC first discard the hdr's b_pabd
234dcbf3bd6SGeorge Wilson  * since the physical block is about to be rewritten. The new data contents
2355602294fSDan Kimmel  * will be contained in the arc_buf_t. As the I/O pipeline performs the write,
2365602294fSDan Kimmel  * it may compress the data before writing it to disk. The ARC will be called
2375602294fSDan Kimmel  * with the transformed data and will bcopy the transformed on-disk block into
238770499e1SDan Kimmel  * a newly allocated b_pabd. Writes are always done into buffers which have
2395602294fSDan Kimmel  * either been loaned (and hence are new and don't have other readers) or
2405602294fSDan Kimmel  * buffers which have been released (and hence have their own hdr, if there
2415602294fSDan Kimmel  * were originally other readers of the buf's original hdr). This ensures that
2425602294fSDan Kimmel  * the ARC only needs to update a single buf and its hdr after a write occurs.
243dcbf3bd6SGeorge Wilson  *
244770499e1SDan Kimmel  * When the L2ARC is in use, it will also take advantage of the b_pabd. The
245770499e1SDan Kimmel  * L2ARC will always write the contents of b_pabd to the L2ARC. This means
2465602294fSDan Kimmel  * that when compressed ARC is enabled that the L2ARC blocks are identical
247dcbf3bd6SGeorge Wilson  * to the on-disk block in the main data pool. This provides a significant
248dcbf3bd6SGeorge Wilson  * advantage since the ARC can leverage the bp's checksum when reading from the
249dcbf3bd6SGeorge Wilson  * L2ARC to determine if the contents are valid. However, if the compressed
2505602294fSDan Kimmel  * ARC is disabled, then the L2ARC's block must be transformed to look
251dcbf3bd6SGeorge Wilson  * like the physical block in the main data pool before comparing the
252dcbf3bd6SGeorge Wilson  * checksum and determining its validity.
253*eb633035STom Caputi  *
254*eb633035STom Caputi  * The L1ARC has a slightly different system for storing encrypted data.
255*eb633035STom Caputi  * Raw (encrypted + possibly compressed) data has a few subtle differences from
256*eb633035STom Caputi  * data that is just compressed. The biggest difference is that it is not
257*eb633035STom Caputi  * possible to decrypt encrypted data (or visa versa) if the keys aren't loaded.
258*eb633035STom Caputi  * The other difference is that encryption cannot be treated as a suggestion.
259*eb633035STom Caputi  * If a caller would prefer compressed data, but they actually wind up with
260*eb633035STom Caputi  * uncompressed data the worst thing that could happen is there might be a
261*eb633035STom Caputi  * performance hit. If the caller requests encrypted data, however, we must be
262*eb633035STom Caputi  * sure they actually get it or else secret information could be leaked. Raw
263*eb633035STom Caputi  * data is stored in hdr->b_crypt_hdr.b_rabd. An encrypted header, therefore,
264*eb633035STom Caputi  * may have both an encrypted version and a decrypted version of its data at
265*eb633035STom Caputi  * once. When a caller needs a raw arc_buf_t, it is allocated and the data is
266*eb633035STom Caputi  * copied out of this header. To avoid complications with b_pabd, raw buffers
267*eb633035STom Caputi  * cannot be shared.
268dcbf3bd6SGeorge Wilson  */
269dcbf3bd6SGeorge Wilson 
270fa9e4066Sahrens #include <sys/spa.h>
271fa9e4066Sahrens #include <sys/zio.h>
272dcbf3bd6SGeorge Wilson #include <sys/spa_impl.h>
273aad02571SSaso Kiselkov #include <sys/zio_compress.h>
274dcbf3bd6SGeorge Wilson #include <sys/zio_checksum.h>
275fa9e4066Sahrens #include <sys/zfs_context.h>
276fa9e4066Sahrens #include <sys/arc.h>
277fa9e4066Sahrens #include <sys/refcount.h>
278c5904d13Seschrock #include <sys/vdev.h>
279573ca77eSGeorge Wilson #include <sys/vdev_impl.h>
28069962b56SMatthew Ahrens #include <sys/dsl_pool.h>
281770499e1SDan Kimmel #include <sys/zio_checksum.h>
282244781f1SPrakash Surya #include <sys/multilist.h>
283770499e1SDan Kimmel #include <sys/abd.h>
284*eb633035STom Caputi #include <sys/zil.h>
285*eb633035STom Caputi #include <sys/fm/fs/zfs.h>
286fa9e4066Sahrens #ifdef _KERNEL
287fa9e4066Sahrens #include <sys/vmsystm.h>
288fa9e4066Sahrens #include <vm/anon.h>
289fa9e4066Sahrens #include <sys/fs/swapnode.h>
290033f9833Sek #include <sys/dnlc.h>
291fa9e4066Sahrens #endif
292fa9e4066Sahrens #include <sys/callb.h>
29344cb6abcSbmc #include <sys/kstat.h>
294de753e34SBrad Lewis #include <sys/zthr.h>
295b24ab676SJeff Bonwick #include <zfs_fletcher.h>
2963a2d8a1bSPaul Dagnelie #include <sys/aggsum.h>
2973a2d8a1bSPaul Dagnelie #include <sys/cityhash.h>
298fa9e4066Sahrens 
299cd1c8b85SMatthew Ahrens #ifndef _KERNEL
300cd1c8b85SMatthew Ahrens /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
301cd1c8b85SMatthew Ahrens boolean_t arc_watch = B_FALSE;
302cd1c8b85SMatthew Ahrens int arc_procfd;
303cd1c8b85SMatthew Ahrens #endif
304cd1c8b85SMatthew Ahrens 
305de753e34SBrad Lewis /*
306de753e34SBrad Lewis  * This thread's job is to keep enough free memory in the system, by
307de753e34SBrad Lewis  * calling arc_kmem_reap_now() plus arc_shrink(), which improves
308de753e34SBrad Lewis  * arc_available_memory().
309de753e34SBrad Lewis  */
310de753e34SBrad Lewis static zthr_t		*arc_reap_zthr;
311de753e34SBrad Lewis 
312de753e34SBrad Lewis /*
313de753e34SBrad Lewis  * This thread's job is to keep arc_size under arc_c, by calling
314de753e34SBrad Lewis  * arc_adjust(), which improves arc_is_overflowing().
315de753e34SBrad Lewis  */
316de753e34SBrad Lewis static zthr_t		*arc_adjust_zthr;
317de753e34SBrad Lewis 
318de753e34SBrad Lewis static kmutex_t		arc_adjust_lock;
319de753e34SBrad Lewis static kcondvar_t	arc_adjust_waiters_cv;
320de753e34SBrad Lewis static boolean_t	arc_adjust_needed = B_FALSE;
321244781f1SPrakash Surya 
3222ec99e3eSMatthew Ahrens uint_t arc_reduce_dnlc_percent = 3;
323fa9e4066Sahrens 
32469962b56SMatthew Ahrens /*
325244781f1SPrakash Surya  * The number of headers to evict in arc_evict_state_impl() before
326244781f1SPrakash Surya  * dropping the sublist lock and evicting from another sublist. A lower
327244781f1SPrakash Surya  * value means we're more likely to evict the "correct" header (i.e. the
328244781f1SPrakash Surya  * oldest header in the arc state), but comes with higher overhead
329244781f1SPrakash Surya  * (i.e. more invocations of arc_evict_state_impl()).
330244781f1SPrakash Surya  */
331244781f1SPrakash Surya int zfs_arc_evict_batch_limit = 10;
332244781f1SPrakash Surya 
333fa9e4066Sahrens /* number of seconds before growing cache again */
334de753e34SBrad Lewis int arc_grow_retry = 60;
335fa9e4066Sahrens 
336de753e34SBrad Lewis /*
337de753e34SBrad Lewis  * Minimum time between calls to arc_kmem_reap_soon().  Note that this will
338de753e34SBrad Lewis  * be converted to ticks, so with the default hz=100, a setting of 15 ms
339de753e34SBrad Lewis  * will actually wait 2 ticks, or 20ms.
340de753e34SBrad Lewis  */
341de753e34SBrad Lewis int arc_kmem_cache_reap_retry_ms = 1000;
34236a64e62STim Kordas 
343770499e1SDan Kimmel /* shift of arc_c for calculating overflow limit in arc_get_data_impl */
344de753e34SBrad Lewis int zfs_arc_overflow_shift = 8;
345244781f1SPrakash Surya 
3465a98e54bSBrendan Gregg - Sun Microsystems /* shift of arc_c for calculating both min and max arc_p */
347de753e34SBrad Lewis int arc_p_min_shift = 4;
3485a98e54bSBrendan Gregg - Sun Microsystems 
3495a98e54bSBrendan Gregg - Sun Microsystems /* log2(fraction of arc to reclaim) */
350de753e34SBrad Lewis int arc_shrink_shift = 7;
3512ec99e3eSMatthew Ahrens 
3522ec99e3eSMatthew Ahrens /*
3532ec99e3eSMatthew Ahrens  * log2(fraction of ARC which must be free to allow growing).
3542ec99e3eSMatthew Ahrens  * I.e. If there is less than arc_c >> arc_no_grow_shift free memory,
3552ec99e3eSMatthew Ahrens  * when reading a new block into the ARC, we will evict an equal-sized block
3562ec99e3eSMatthew Ahrens  * from the ARC.
3572ec99e3eSMatthew Ahrens  *
3582ec99e3eSMatthew Ahrens  * This must be less than arc_shrink_shift, so that when we shrink the ARC,
3592ec99e3eSMatthew Ahrens  * we will still not allow it to grow.
3602ec99e3eSMatthew Ahrens  */
3612ec99e3eSMatthew Ahrens int			arc_no_grow_shift = 5;
3622ec99e3eSMatthew Ahrens 
3635a98e54bSBrendan Gregg - Sun Microsystems 
36413506d1eSmaybee /*
365b19a79ecSperrin  * minimum lifespan of a prefetch block in clock ticks
366b19a79ecSperrin  * (initialized in arc_init())
36713506d1eSmaybee  */
368a3874b8bSToomas Soome static int		zfs_arc_min_prefetch_ms = 1;
369a3874b8bSToomas Soome static int		zfs_arc_min_prescient_prefetch_ms = 6;
37013506d1eSmaybee 
37169962b56SMatthew Ahrens /*
37269962b56SMatthew Ahrens  * If this percent of memory is free, don't throttle.
37369962b56SMatthew Ahrens  */
37469962b56SMatthew Ahrens int arc_lotsfree_percent = 10;
37569962b56SMatthew Ahrens 
376de753e34SBrad Lewis static boolean_t arc_initialized;
377fa9e4066Sahrens 
3783a737e0dSbrendan /*
3793a737e0dSbrendan  * The arc has filled available memory and has now warmed up.
3803a737e0dSbrendan  */
3813a737e0dSbrendan static boolean_t arc_warm;
3823a737e0dSbrendan 
3830dd053d7SPrakash Surya /*
3840dd053d7SPrakash Surya  * log2 fraction of the zio arena to keep free.
3850dd053d7SPrakash Surya  */
3860dd053d7SPrakash Surya int arc_zio_arena_free_shift = 2;
3870dd053d7SPrakash Surya 
388a2eea2e1Sahrens /*
389a2eea2e1Sahrens  * These tunables are for performance analysis.
390a2eea2e1Sahrens  */
391a2eea2e1Sahrens uint64_t zfs_arc_max;
392a2eea2e1Sahrens uint64_t zfs_arc_min;
3931116048bSek uint64_t zfs_arc_meta_limit = 0;
3943a5286a1SMatthew Ahrens uint64_t zfs_arc_meta_min = 0;
3955a98e54bSBrendan Gregg - Sun Microsystems int zfs_arc_grow_retry = 0;
3965a98e54bSBrendan Gregg - Sun Microsystems int zfs_arc_shrink_shift = 0;
3975a98e54bSBrendan Gregg - Sun Microsystems int zfs_arc_p_min_shift = 0;
39863e911b6SMatthew Ahrens int zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
399a2eea2e1Sahrens 
400abe1fd01SDon Brady /*
401abe1fd01SDon Brady  * ARC dirty data constraints for arc_tempreserve_space() throttle
402abe1fd01SDon Brady  */
403abe1fd01SDon Brady uint_t zfs_arc_dirty_limit_percent = 50;	/* total dirty data limit */
404abe1fd01SDon Brady uint_t zfs_arc_anon_limit_percent = 25;		/* anon block dirty limit */
405abe1fd01SDon Brady uint_t zfs_arc_pool_dirty_percent = 20;		/* each pool's anon allowance */
406abe1fd01SDon Brady 
407dcbf3bd6SGeorge Wilson boolean_t zfs_compressed_arc_enabled = B_TRUE;
408dcbf3bd6SGeorge Wilson 
409fa9e4066Sahrens /*
410fa94a07fSbrendan  * Note that buffers can be in one of 6 states:
411fa9e4066Sahrens  *	ARC_anon	- anonymous (discussed below)
412ea8dc4b6Seschrock  *	ARC_mru		- recently used, currently cached
413ea8dc4b6Seschrock  *	ARC_mru_ghost	- recentely used, no longer in cache
414ea8dc4b6Seschrock  *	ARC_mfu		- frequently used, currently cached
415ea8dc4b6Seschrock  *	ARC_mfu_ghost	- frequently used, no longer in cache
416fa94a07fSbrendan  *	ARC_l2c_only	- exists in L2ARC but not other states
4170e8c6158Smaybee  * When there are no active references to the buffer, they are
4180e8c6158Smaybee  * are linked onto a list in one of these arc states.  These are
4190e8c6158Smaybee  * the only buffers that can be evicted or deleted.  Within each
4200e8c6158Smaybee  * state there are multiple lists, one for meta-data and one for
4210e8c6158Smaybee  * non-meta-data.  Meta-data (indirect blocks, blocks of dnodes,
4220e8c6158Smaybee  * etc.) is tracked separately so that it can be managed more
423fa94a07fSbrendan  * explicitly: favored over data, limited explicitly.
424fa9e4066Sahrens  *
425fa9e4066Sahrens  * Anonymous buffers are buffers that are not associated with
426fa9e4066Sahrens  * a DVA.  These are buffers that hold dirty block copies
427fa9e4066Sahrens  * before they are written to stable storage.  By definition,
428ea8dc4b6Seschrock  * they are "ref'd" and are considered part of arc_mru
429fa9e4066Sahrens  * that cannot be freed.  Generally, they will aquire a DVA
430ea8dc4b6Seschrock  * as they are written and migrate onto the arc_mru list.
431fa94a07fSbrendan  *
432fa94a07fSbrendan  * The ARC_l2c_only state is for buffers that are in the second
433fa94a07fSbrendan  * level ARC but no longer in any of the ARC_m* lists.  The second
434fa94a07fSbrendan  * level ARC itself may also contain buffers that are in any of
435fa94a07fSbrendan  * the ARC_m* states - meaning that a buffer can exist in two
436fa94a07fSbrendan  * places.  The reason for the ARC_l2c_only state is to keep the
437fa94a07fSbrendan  * buffer header in the hash table, so that reads that hit the
438fa94a07fSbrendan  * second level ARC benefit from these fast lookups.
439fa9e4066Sahrens  */
440fa9e4066Sahrens 
441fa9e4066Sahrens typedef struct arc_state {
442244781f1SPrakash Surya 	/*
443244781f1SPrakash Surya 	 * list of evictable buffers
444244781f1SPrakash Surya 	 */
44594c2d0ebSMatthew Ahrens 	multilist_t *arcs_list[ARC_BUFC_NUMTYPES];
446244781f1SPrakash Surya 	/*
447244781f1SPrakash Surya 	 * total amount of evictable data in this state
448244781f1SPrakash Surya 	 */
449e914ace2STim Schumacher 	zfs_refcount_t arcs_esize[ARC_BUFC_NUMTYPES];
450244781f1SPrakash Surya 	/*
451244781f1SPrakash Surya 	 * total amount of data in this state; this includes: evictable,
452244781f1SPrakash Surya 	 * non-evictable, ARC_BUFC_DATA, and ARC_BUFC_METADATA.
453244781f1SPrakash Surya 	 */
454e914ace2STim Schumacher 	zfs_refcount_t arcs_size;
455fa9e4066Sahrens } arc_state_t;
456fa9e4066Sahrens 
457fa94a07fSbrendan /* The 6 states: */
458fa9e4066Sahrens static arc_state_t ARC_anon;
459ea8dc4b6Seschrock static arc_state_t ARC_mru;
460ea8dc4b6Seschrock static arc_state_t ARC_mru_ghost;
461ea8dc4b6Seschrock static arc_state_t ARC_mfu;
462ea8dc4b6Seschrock static arc_state_t ARC_mfu_ghost;
463fa94a07fSbrendan static arc_state_t ARC_l2c_only;
464fa9e4066Sahrens 
46544cb6abcSbmc typedef struct arc_stats {
46644cb6abcSbmc 	kstat_named_t arcstat_hits;
46744cb6abcSbmc 	kstat_named_t arcstat_misses;
46844cb6abcSbmc 	kstat_named_t arcstat_demand_data_hits;
46944cb6abcSbmc 	kstat_named_t arcstat_demand_data_misses;
47044cb6abcSbmc 	kstat_named_t arcstat_demand_metadata_hits;
47144cb6abcSbmc 	kstat_named_t arcstat_demand_metadata_misses;
47244cb6abcSbmc 	kstat_named_t arcstat_prefetch_data_hits;
47344cb6abcSbmc 	kstat_named_t arcstat_prefetch_data_misses;
47444cb6abcSbmc 	kstat_named_t arcstat_prefetch_metadata_hits;
47544cb6abcSbmc 	kstat_named_t arcstat_prefetch_metadata_misses;
47644cb6abcSbmc 	kstat_named_t arcstat_mru_hits;
47744cb6abcSbmc 	kstat_named_t arcstat_mru_ghost_hits;
47844cb6abcSbmc 	kstat_named_t arcstat_mfu_hits;
47944cb6abcSbmc 	kstat_named_t arcstat_mfu_ghost_hits;
48044cb6abcSbmc 	kstat_named_t arcstat_deleted;
4813e30c24aSWill Andrews 	/*
4823e30c24aSWill Andrews 	 * Number of buffers that could not be evicted because the hash lock
4833e30c24aSWill Andrews 	 * was held by another thread.  The lock may not necessarily be held
4843e30c24aSWill Andrews 	 * by something using the same buffer, since hash locks are shared
4853e30c24aSWill Andrews 	 * by multiple buffers.
4863e30c24aSWill Andrews 	 */
48744cb6abcSbmc 	kstat_named_t arcstat_mutex_miss;
4887b38fab6SAlexander Motin 	/*
4897b38fab6SAlexander Motin 	 * Number of buffers skipped when updating the access state due to the
4907b38fab6SAlexander Motin 	 * header having already been released after acquiring the hash lock.
4917b38fab6SAlexander Motin 	 */
4927b38fab6SAlexander Motin 	kstat_named_t arcstat_access_skip;
4933e30c24aSWill Andrews 	/*
4943e30c24aSWill Andrews 	 * Number of buffers skipped because they have I/O in progress, are
4957b38fab6SAlexander Motin 	 * indirect prefetch buffers that have not lived long enough, or are
4963e30c24aSWill Andrews 	 * not from the spa we're trying to evict from.
4973e30c24aSWill Andrews 	 */
49844cb6abcSbmc 	kstat_named_t arcstat_evict_skip;
499244781f1SPrakash Surya 	/*
500244781f1SPrakash Surya 	 * Number of times arc_evict_state() was unable to evict enough
501*eb633035STom Caputi 	 * buffers to reach its target amount.
502244781f1SPrakash Surya 	 */
503244781f1SPrakash Surya 	kstat_named_t arcstat_evict_not_enough;
5045ea40c06SBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_evict_l2_cached;
5055ea40c06SBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_evict_l2_eligible;
5065ea40c06SBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_evict_l2_ineligible;
507244781f1SPrakash Surya 	kstat_named_t arcstat_evict_l2_skip;
50844cb6abcSbmc 	kstat_named_t arcstat_hash_elements;
50944cb6abcSbmc 	kstat_named_t arcstat_hash_elements_max;
51044cb6abcSbmc 	kstat_named_t arcstat_hash_collisions;
51144cb6abcSbmc 	kstat_named_t arcstat_hash_chains;
51244cb6abcSbmc 	kstat_named_t arcstat_hash_chain_max;
51344cb6abcSbmc 	kstat_named_t arcstat_p;
51444cb6abcSbmc 	kstat_named_t arcstat_c;
51544cb6abcSbmc 	kstat_named_t arcstat_c_min;
51644cb6abcSbmc 	kstat_named_t arcstat_c_max;
5173a2d8a1bSPaul Dagnelie 	/* Not updated directly; only synced in arc_kstat_update. */
51844cb6abcSbmc 	kstat_named_t arcstat_size;
519dcbf3bd6SGeorge Wilson 	/*
520770499e1SDan Kimmel 	 * Number of compressed bytes stored in the arc_buf_hdr_t's b_pabd.
521dcbf3bd6SGeorge Wilson 	 * Note that the compressed bytes may match the uncompressed bytes
522dcbf3bd6SGeorge Wilson 	 * if the block is either not compressed or compressed arc is disabled.
523dcbf3bd6SGeorge Wilson 	 */
524dcbf3bd6SGeorge Wilson 	kstat_named_t arcstat_compressed_size;
525dcbf3bd6SGeorge Wilson 	/*
526770499e1SDan Kimmel 	 * Uncompressed size of the data stored in b_pabd. If compressed
527dcbf3bd6SGeorge Wilson 	 * arc is disabled then this value will be identical to the stat
528dcbf3bd6SGeorge Wilson 	 * above.
529dcbf3bd6SGeorge Wilson 	 */
530dcbf3bd6SGeorge Wilson 	kstat_named_t arcstat_uncompressed_size;
531dcbf3bd6SGeorge Wilson 	/*
532dcbf3bd6SGeorge Wilson 	 * Number of bytes stored in all the arc_buf_t's. This is classified
533dcbf3bd6SGeorge Wilson 	 * as "overhead" since this data is typically short-lived and will
534dcbf3bd6SGeorge Wilson 	 * be evicted from the arc when it becomes unreferenced unless the
535dcbf3bd6SGeorge Wilson 	 * zfs_keep_uncompressed_metadata or zfs_keep_uncompressed_level
536dcbf3bd6SGeorge Wilson 	 * values have been set (see comment in dbuf.c for more information).
537dcbf3bd6SGeorge Wilson 	 */
538dcbf3bd6SGeorge Wilson 	kstat_named_t arcstat_overhead_size;
5394076b1bfSPrakash Surya 	/*
5404076b1bfSPrakash Surya 	 * Number of bytes consumed by internal ARC structures necessary
5414076b1bfSPrakash Surya 	 * for tracking purposes; these structures are not actually
5424076b1bfSPrakash Surya 	 * backed by ARC buffers. This includes arc_buf_hdr_t structures
5434076b1bfSPrakash Surya 	 * (allocated via arc_buf_hdr_t_full and arc_buf_hdr_t_l2only
5444076b1bfSPrakash Surya 	 * caches), and arc_buf_t structures (allocated via arc_buf_t
5454076b1bfSPrakash Surya 	 * cache).
5463a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5474076b1bfSPrakash Surya 	 */
548fa94a07fSbrendan 	kstat_named_t arcstat_hdr_size;
5494076b1bfSPrakash Surya 	/*
5504076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers of type equal to
5514076b1bfSPrakash Surya 	 * ARC_BUFC_DATA. This is generally consumed by buffers backing
5524076b1bfSPrakash Surya 	 * on disk user data (e.g. plain file contents).
5533a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5544076b1bfSPrakash Surya 	 */
5555a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_data_size;
5564076b1bfSPrakash Surya 	/*
5574076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers of type equal to
5584076b1bfSPrakash Surya 	 * ARC_BUFC_METADATA. This is generally consumed by buffers
5594076b1bfSPrakash Surya 	 * backing on disk data that is used for internal ZFS
5604076b1bfSPrakash Surya 	 * structures (e.g. ZAP, dnode, indirect blocks, etc).
5613a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5624076b1bfSPrakash Surya 	 */
5634076b1bfSPrakash Surya 	kstat_named_t arcstat_metadata_size;
5644076b1bfSPrakash Surya 	/*
5654076b1bfSPrakash Surya 	 * Number of bytes consumed by various buffers and structures
5664076b1bfSPrakash Surya 	 * not actually backed with ARC buffers. This includes bonus
5674076b1bfSPrakash Surya 	 * buffers (allocated directly via zio_buf_* functions),
5684076b1bfSPrakash Surya 	 * dmu_buf_impl_t structures (allocated via dmu_buf_impl_t
5694076b1bfSPrakash Surya 	 * cache), and dnode_t structures (allocated via dnode_t cache).
5703a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5714076b1bfSPrakash Surya 	 */
5725a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_other_size;
5734076b1bfSPrakash Surya 	/*
5744076b1bfSPrakash Surya 	 * Total number of bytes consumed by ARC buffers residing in the
5754076b1bfSPrakash Surya 	 * arc_anon state. This includes *all* buffers in the arc_anon
5764076b1bfSPrakash Surya 	 * state; e.g. data, metadata, evictable, and unevictable buffers
5774076b1bfSPrakash Surya 	 * are all included in this value.
5783a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5794076b1bfSPrakash Surya 	 */
5804076b1bfSPrakash Surya 	kstat_named_t arcstat_anon_size;
5814076b1bfSPrakash Surya 	/*
5824076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
5834076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_DATA,
5844076b1bfSPrakash Surya 	 * residing in the arc_anon state, and are eligible for eviction
5854076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
5863a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5874076b1bfSPrakash Surya 	 */
5884076b1bfSPrakash Surya 	kstat_named_t arcstat_anon_evictable_data;
5894076b1bfSPrakash Surya 	/*
5904076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
5914076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_METADATA,
5924076b1bfSPrakash Surya 	 * residing in the arc_anon state, and are eligible for eviction
5934076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
5943a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
5954076b1bfSPrakash Surya 	 */
5964076b1bfSPrakash Surya 	kstat_named_t arcstat_anon_evictable_metadata;
5974076b1bfSPrakash Surya 	/*
5984076b1bfSPrakash Surya 	 * Total number of bytes consumed by ARC buffers residing in the
5994076b1bfSPrakash Surya 	 * arc_mru state. This includes *all* buffers in the arc_mru
6004076b1bfSPrakash Surya 	 * state; e.g. data, metadata, evictable, and unevictable buffers
6014076b1bfSPrakash Surya 	 * are all included in this value.
6023a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6034076b1bfSPrakash Surya 	 */
6044076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_size;
6054076b1bfSPrakash Surya 	/*
6064076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
6074076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_DATA,
6084076b1bfSPrakash Surya 	 * residing in the arc_mru state, and are eligible for eviction
6094076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
6103a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6114076b1bfSPrakash Surya 	 */
6124076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_evictable_data;
6134076b1bfSPrakash Surya 	/*
6144076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that meet the
6154076b1bfSPrakash Surya 	 * following criteria: backing buffers of type ARC_BUFC_METADATA,
6164076b1bfSPrakash Surya 	 * residing in the arc_mru state, and are eligible for eviction
6174076b1bfSPrakash Surya 	 * (e.g. have no outstanding holds on the buffer).
6183a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6194076b1bfSPrakash Surya 	 */
6204076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_evictable_metadata;
6214076b1bfSPrakash Surya 	/*
6224076b1bfSPrakash Surya 	 * Total number of bytes that *would have been* consumed by ARC
6234076b1bfSPrakash Surya 	 * buffers in the arc_mru_ghost state. The key thing to note
6244076b1bfSPrakash Surya 	 * here, is the fact that this size doesn't actually indicate
6254076b1bfSPrakash Surya 	 * RAM consumption. The ghost lists only consist of headers and
6264076b1bfSPrakash Surya 	 * don't actually have ARC buffers linked off of these headers.
6274076b1bfSPrakash Surya 	 * Thus, *if* the headers had associated ARC buffers, these
6284076b1bfSPrakash Surya 	 * buffers *would have* consumed this number of bytes.
6293a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6304076b1bfSPrakash Surya 	 */
6314076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_ghost_size;
6324076b1bfSPrakash Surya 	/*
6334076b1bfSPrakash Surya 	 * Number of bytes that *would have been* consumed by ARC
6344076b1bfSPrakash Surya 	 * buffers that are eligible for eviction, of type
6354076b1bfSPrakash Surya 	 * ARC_BUFC_DATA, and linked off the arc_mru_ghost state.
6363a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6374076b1bfSPrakash Surya 	 */
6384076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_ghost_evictable_data;
6394076b1bfSPrakash Surya 	/*
6404076b1bfSPrakash Surya 	 * Number of bytes that *would have been* consumed by ARC
6414076b1bfSPrakash Surya 	 * buffers that are eligible for eviction, of type
6424076b1bfSPrakash Surya 	 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
6433a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6444076b1bfSPrakash Surya 	 */
6454076b1bfSPrakash Surya 	kstat_named_t arcstat_mru_ghost_evictable_metadata;
6464076b1bfSPrakash Surya 	/*
6474076b1bfSPrakash Surya 	 * Total number of bytes consumed by ARC buffers residing in the
6484076b1bfSPrakash Surya 	 * arc_mfu state. This includes *all* buffers in the arc_mfu
6494076b1bfSPrakash Surya 	 * state; e.g. data, metadata, evictable, and unevictable buffers
6504076b1bfSPrakash Surya 	 * are all included in this value.
6513a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6524076b1bfSPrakash Surya 	 */
6534076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_size;
6544076b1bfSPrakash Surya 	/*
6554076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that are eligible for
6564076b1bfSPrakash Surya 	 * eviction, of type ARC_BUFC_DATA, and reside in the arc_mfu
6574076b1bfSPrakash Surya 	 * state.
6583a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6594076b1bfSPrakash Surya 	 */
6604076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_evictable_data;
6614076b1bfSPrakash Surya 	/*
6624076b1bfSPrakash Surya 	 * Number of bytes consumed by ARC buffers that are eligible for
6634076b1bfSPrakash Surya 	 * eviction, of type ARC_BUFC_METADATA, and reside in the
6644076b1bfSPrakash Surya 	 * arc_mfu state.
6653a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6664076b1bfSPrakash Surya 	 */
6674076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_evictable_metadata;
6684076b1bfSPrakash Surya 	/*
6694076b1bfSPrakash Surya 	 * Total number of bytes that *would have been* consumed by ARC
6704076b1bfSPrakash Surya 	 * buffers in the arc_mfu_ghost state. See the comment above
6714076b1bfSPrakash Surya 	 * arcstat_mru_ghost_size for more details.
6723a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6734076b1bfSPrakash Surya 	 */
6744076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_ghost_size;
6754076b1bfSPrakash Surya 	/*
6764076b1bfSPrakash Surya 	 * Number of bytes that *would have been* consumed by ARC
6774076b1bfSPrakash Surya 	 * buffers that are eligible for eviction, of type
6784076b1bfSPrakash Surya 	 * ARC_BUFC_DATA, and linked off the arc_mfu_ghost state.
6793a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6804076b1bfSPrakash Surya 	 */
6814076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_ghost_evictable_data;
6824076b1bfSPrakash Surya 	/*
6834076b1bfSPrakash Surya 	 * Number of bytes that *would have been* consumed by ARC
6844076b1bfSPrakash Surya 	 * buffers that are eligible for eviction, of type
6854076b1bfSPrakash Surya 	 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
6863a2d8a1bSPaul Dagnelie 	 * Not updated directly; only synced in arc_kstat_update.
6874076b1bfSPrakash Surya 	 */
6884076b1bfSPrakash Surya 	kstat_named_t arcstat_mfu_ghost_evictable_metadata;
689fa94a07fSbrendan 	kstat_named_t arcstat_l2_hits;
690fa94a07fSbrendan 	kstat_named_t arcstat_l2_misses;
691fa94a07fSbrendan 	kstat_named_t arcstat_l2_feeds;
692fa94a07fSbrendan 	kstat_named_t arcstat_l2_rw_clash;
6935a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_l2_read_bytes;
6945a98e54bSBrendan Gregg - Sun Microsystems 	kstat_named_t arcstat_l2_write_bytes;
695fa94a07fSbrendan 	kstat_named_t arcstat_l2_writes_sent;
696fa94a07fSbrendan 	kstat_named_t arcstat_l2_writes_done;
697fa94a07fSbrendan 	kstat_named_t arcstat_l2_writes_error;
698244781f1SPrakash Surya 	kstat_named_t arcstat_l2_writes_lock_retry;
699fa94a07fSbrendan 	kstat_named_t arcstat_l2_evict_lock_retry;
700fa94a07fSbrendan 	kstat_named_t arcstat_l2_evict_reading;
70189c86e32SChris Williamson 	kstat_named_t arcstat_l2_evict_l1cached;
702fa94a07fSbrendan 	kstat_named_t arcstat_l2_free_on_write;
703fa94a07fSbrendan 	kstat_named_t arcstat_l2_abort_lowmem;
704fa94a07fSbrendan 	kstat_named_t arcstat_l2_cksum_bad;
705fa94a07fSbrendan 	kstat_named_t arcstat_l2_io_error;
70616a7e5acSAndriy Gapon 	kstat_named_t arcstat_l2_lsize;
70716a7e5acSAndriy Gapon 	kstat_named_t arcstat_l2_psize;
7083a2d8a1bSPaul Dagnelie 	/* Not updated directly; only synced in arc_kstat_update. */
709fa94a07fSbrendan 	kstat_named_t arcstat_l2_hdr_size;
7101ab7f2deSmaybee 	kstat_named_t arcstat_memory_throttle_count;
7113a2d8a1bSPaul Dagnelie 	/* Not updated directly; only synced in arc_kstat_update. */
71220128a08SGeorge Wilson 	kstat_named_t arcstat_meta_used;
71320128a08SGeorge Wilson 	kstat_named_t arcstat_meta_limit;
71420128a08SGeorge Wilson 	kstat_named_t arcstat_meta_max;
7153a5286a1SMatthew Ahrens 	kstat_named_t arcstat_meta_min;
716a3874b8bSToomas Soome 	kstat_named_t arcstat_async_upgrade_sync;
717cf6106c8SMatthew Ahrens 	kstat_named_t arcstat_demand_hit_predictive_prefetch;
718a3874b8bSToomas Soome 	kstat_named_t arcstat_demand_hit_prescient_prefetch;
71944cb6abcSbmc } arc_stats_t;
72044cb6abcSbmc 
72144cb6abcSbmc static arc_stats_t arc_stats = {
72244cb6abcSbmc 	{ "hits",			KSTAT_DATA_UINT64 },
72344cb6abcSbmc 	{ "misses",			KSTAT_DATA_UINT64 },
72444cb6abcSbmc 	{ "demand_data_hits",		KSTAT_DATA_UINT64 },
72544cb6abcSbmc 	{ "demand_data_misses",		KSTAT_DATA_UINT64 },
72644cb6abcSbmc 	{ "demand_metadata_hits",	KSTAT_DATA_UINT64 },
72744cb6abcSbmc 	{ "demand_metadata_misses",	KSTAT_DATA_UINT64 },
72844cb6abcSbmc 	{ "prefetch_data_hits",		KSTAT_DATA_UINT64 },
72944cb6abcSbmc 	{ "prefetch_data_misses",	KSTAT_DATA_UINT64 },
73044cb6abcSbmc 	{ "prefetch_metadata_hits",	KSTAT_DATA_UINT64 },
73144cb6abcSbmc 	{ "prefetch_metadata_misses",	KSTAT_DATA_UINT64 },
73244cb6abcSbmc 	{ "mru_hits",			KSTAT_DATA_UINT64 },
73344cb6abcSbmc 	{ "mru_ghost_hits",		KSTAT_DATA_UINT64 },
73444cb6abcSbmc 	{ "mfu_hits",			KSTAT_DATA_UINT64 },
73544cb6abcSbmc 	{ "mfu_ghost_hits",		KSTAT_DATA_UINT64 },
73644cb6abcSbmc 	{ "deleted",			KSTAT_DATA_UINT64 },
73744cb6abcSbmc 	{ "mutex_miss",			KSTAT_DATA_UINT64 },
7387b38fab6SAlexander Motin 	{ "access_skip",		KSTAT_DATA_UINT64 },
73944cb6abcSbmc 	{ "evict_skip",			KSTAT_DATA_UINT64 },
740244781f1SPrakash Surya 	{ "evict_not_enough",		KSTAT_DATA_UINT64 },
7415ea40c06SBrendan Gregg - Sun Microsystems 	{ "evict_l2_cached",		KSTAT_DATA_UINT64 },
7425ea40c06SBrendan Gregg - Sun Microsystems 	{ "evict_l2_eligible",		KSTAT_DATA_UINT64 },
7435ea40c06SBrendan Gregg - Sun Microsystems 	{ "evict_l2_ineligible",	KSTAT_DATA_UINT64 },
744244781f1SPrakash Surya 	{ "evict_l2_skip",		KSTAT_DATA_UINT64 },
74544cb6abcSbmc 	{ "hash_elements",		KSTAT_DATA_UINT64 },
74644cb6abcSbmc 	{ "hash_elements_max",		KSTAT_DATA_UINT64 },
74744cb6abcSbmc 	{ "hash_collisions",		KSTAT_DATA_UINT64 },
74844cb6abcSbmc 	{ "hash_chains",		KSTAT_DATA_UINT64 },
74944cb6abcSbmc 	{ "hash_chain_max",		KSTAT_DATA_UINT64 },
75044cb6abcSbmc 	{ "p",				KSTAT_DATA_UINT64 },
75144cb6abcSbmc 	{ "c",				KSTAT_DATA_UINT64 },
75244cb6abcSbmc 	{ "c_min",			KSTAT_DATA_UINT64 },
75344cb6abcSbmc 	{ "c_max",			KSTAT_DATA_UINT64 },
754fa94a07fSbrendan 	{ "size",			KSTAT_DATA_UINT64 },
755dcbf3bd6SGeorge Wilson 	{ "compressed_size",		KSTAT_DATA_UINT64 },
756dcbf3bd6SGeorge Wilson 	{ "uncompressed_size",		KSTAT_DATA_UINT64 },
757dcbf3bd6SGeorge Wilson 	{ "overhead_size",		KSTAT_DATA_UINT64 },
758fa94a07fSbrendan 	{ "hdr_size",			KSTAT_DATA_UINT64 },
7595a98e54bSBrendan Gregg - Sun Microsystems 	{ "data_size",			KSTAT_DATA_UINT64 },
7604076b1bfSPrakash Surya 	{ "metadata_size",		KSTAT_DATA_UINT64 },
7615a98e54bSBrendan Gregg - Sun Microsystems 	{ "other_size",			KSTAT_DATA_UINT64 },
7624076b1bfSPrakash Surya 	{ "anon_size",			KSTAT_DATA_UINT64 },
7634076b1bfSPrakash Surya 	{ "anon_evictable_data",	KSTAT_DATA_UINT64 },
7644076b1bfSPrakash Surya 	{ "anon_evictable_metadata",	KSTAT_DATA_UINT64 },
7654076b1bfSPrakash Surya 	{ "mru_size",			KSTAT_DATA_UINT64 },
7664076b1bfSPrakash Surya 	{ "mru_evictable_data",		KSTAT_DATA_UINT64 },
7674076b1bfSPrakash Surya 	{ "mru_evictable_metadata",	KSTAT_DATA_UINT64 },
7684076b1bfSPrakash Surya 	{ "mru_ghost_size",		KSTAT_DATA_UINT64 },
7694076b1bfSPrakash Surya 	{ "mru_ghost_evictable_data",	KSTAT_DATA_UINT64 },
7704076b1bfSPrakash Surya 	{ "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
7714076b1bfSPrakash Surya 	{ "mfu_size",			KSTAT_DATA_UINT64 },
7724076b1bfSPrakash Surya 	{ "mfu_evictable_data",		KSTAT_DATA_UINT64 },
7734076b1bfSPrakash Surya 	{ "mfu_evictable_metadata",	KSTAT_DATA_UINT64 },
7744076b1bfSPrakash Surya 	{ "mfu_ghost_size",		KSTAT_DATA_UINT64 },
7754076b1bfSPrakash Surya 	{ "mfu_ghost_evictable_data",	KSTAT_DATA_UINT64 },
7764076b1bfSPrakash Surya 	{ "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
777fa94a07fSbrendan 	{ "l2_hits",			KSTAT_DATA_UINT64 },
778fa94a07fSbrendan 	{ "l2_misses",			KSTAT_DATA_UINT64 },
779fa94a07fSbrendan 	{ "l2_feeds",			KSTAT_DATA_UINT64 },
780fa94a07fSbrendan 	{ "l2_rw_clash",		KSTAT_DATA_UINT64 },
7815a98e54bSBrendan Gregg - Sun Microsystems 	{ "l2_read_bytes",		KSTAT_DATA_UINT64 },
7825a98e54bSBrendan Gregg - Sun Microsystems 	{ "l2_write_bytes",		KSTAT_DATA_UINT64 },
783fa94a07fSbrendan 	{ "l2_writes_sent",		KSTAT_DATA_UINT64 },
784fa94a07fSbrendan 	{ "l2_writes_done",		KSTAT_DATA_UINT64 },
785fa94a07fSbrendan 	{ "l2_writes_error",		KSTAT_DATA_UINT64 },
786244781f1SPrakash Surya 	{ "l2_writes_lock_retry",	KSTAT_DATA_UINT64 },
787fa94a07fSbrendan 	{ "l2_evict_lock_retry",	KSTAT_DATA_UINT64 },
788fa94a07fSbrendan 	{ "l2_evict_reading",		KSTAT_DATA_UINT64 },
78989c86e32SChris Williamson 	{ "l2_evict_l1cached",		KSTAT_DATA_UINT64 },
790fa94a07fSbrendan 	{ "l2_free_on_write",		KSTAT_DATA_UINT64 },
791fa94a07fSbrendan 	{ "l2_abort_lowmem",		KSTAT_DATA_UINT64 },
792fa94a07fSbrendan 	{ "l2_cksum_bad",		KSTAT_DATA_UINT64 },
793fa94a07fSbrendan 	{ "l2_io_error",		KSTAT_DATA_UINT64 },
794fa94a07fSbrendan 	{ "l2_size",			KSTAT_DATA_UINT64 },
795aad02571SSaso Kiselkov 	{ "l2_asize",			KSTAT_DATA_UINT64 },
7961ab7f2deSmaybee 	{ "l2_hdr_size",		KSTAT_DATA_UINT64 },
7979253d63dSGeorge Wilson 	{ "memory_throttle_count",	KSTAT_DATA_UINT64 },
79820128a08SGeorge Wilson 	{ "arc_meta_used",		KSTAT_DATA_UINT64 },
79920128a08SGeorge Wilson 	{ "arc_meta_limit",		KSTAT_DATA_UINT64 },
8003a5286a1SMatthew Ahrens 	{ "arc_meta_max",		KSTAT_DATA_UINT64 },
801cf6106c8SMatthew Ahrens 	{ "arc_meta_min",		KSTAT_DATA_UINT64 },
802a3874b8bSToomas Soome 	{ "async_upgrade_sync",		KSTAT_DATA_UINT64 },
803cf6106c8SMatthew Ahrens 	{ "demand_hit_predictive_prefetch", KSTAT_DATA_UINT64 },
804a3874b8bSToomas Soome 	{ "demand_hit_prescient_prefetch", KSTAT_DATA_UINT64 },
80544cb6abcSbmc };
80644cb6abcSbmc 
80744cb6abcSbmc #define	ARCSTAT(stat)	(arc_stats.stat.value.ui64)
80844cb6abcSbmc 
80944cb6abcSbmc #define	ARCSTAT_INCR(stat, val) \
810f7170741SWill Andrews 	atomic_add_64(&arc_stats.stat.value.ui64, (val))
81144cb6abcSbmc 
812b24ab676SJeff Bonwick #define	ARCSTAT_BUMP(stat)	ARCSTAT_INCR(stat, 1)
81344cb6abcSbmc #define	ARCSTAT_BUMPDOWN(stat)	ARCSTAT_INCR(stat, -1)
81444cb6abcSbmc 
81544cb6abcSbmc #define	ARCSTAT_MAX(stat, val) {					\
81644cb6abcSbmc 	uint64_t m;							\
81744cb6abcSbmc 	while ((val) > (m = arc_stats.stat.value.ui64) &&		\
81844cb6abcSbmc 	    (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val))))	\
81944cb6abcSbmc 		continue;						\
82044cb6abcSbmc }
82144cb6abcSbmc 
82244cb6abcSbmc #define	ARCSTAT_MAXSTAT(stat) \
82344cb6abcSbmc 	ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
82444cb6abcSbmc 
82544cb6abcSbmc /*
82644cb6abcSbmc  * We define a macro to allow ARC hits/misses to be easily broken down by
82744cb6abcSbmc  * two separate conditions, giving a total of four different subtypes for
82844cb6abcSbmc  * each of hits and misses (so eight statistics total).
82944cb6abcSbmc  */
83044cb6abcSbmc #define	ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
83144cb6abcSbmc 	if (cond1) {							\
83244cb6abcSbmc 		if (cond2) {						\
83344cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
83444cb6abcSbmc 		} else {						\
83544cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
83644cb6abcSbmc 		}							\
83744cb6abcSbmc 	} else {							\
83844cb6abcSbmc 		if (cond2) {						\
83944cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
84044cb6abcSbmc 		} else {						\
84144cb6abcSbmc 			ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
84244cb6abcSbmc 		}							\
84344cb6abcSbmc 	}
84444cb6abcSbmc 
84544cb6abcSbmc kstat_t			*arc_ksp;
846b24ab676SJeff Bonwick static arc_state_t	*arc_anon;
84744cb6abcSbmc static arc_state_t	*arc_mru;
84844cb6abcSbmc static arc_state_t	*arc_mru_ghost;
84944cb6abcSbmc static arc_state_t	*arc_mfu;
85044cb6abcSbmc static arc_state_t	*arc_mfu_ghost;
851fa94a07fSbrendan static arc_state_t	*arc_l2c_only;
85244cb6abcSbmc 
85344cb6abcSbmc /*
85444cb6abcSbmc  * There are several ARC variables that are critical to export as kstats --
85544cb6abcSbmc  * but we don't want to have to grovel around in the kstat whenever we wish to
85644cb6abcSbmc  * manipulate them.  For these variables, we therefore define them to be in
85744cb6abcSbmc  * terms of the statistic variable.  This assures that we are not introducing
85844cb6abcSbmc  * the possibility of inconsistency by having shadow copies of the variables,
85944cb6abcSbmc  * while still allowing the code to be readable.
86044cb6abcSbmc  */
86144cb6abcSbmc #define	arc_p		ARCSTAT(arcstat_p)	/* target size of MRU */
86244cb6abcSbmc #define	arc_c		ARCSTAT(arcstat_c)	/* target size of cache */
86344cb6abcSbmc #define	arc_c_min	ARCSTAT(arcstat_c_min)	/* min target cache size */
86444cb6abcSbmc #define	arc_c_max	ARCSTAT(arcstat_c_max)	/* max target cache size */
86520128a08SGeorge Wilson #define	arc_meta_limit	ARCSTAT(arcstat_meta_limit) /* max size for metadata */
8663a5286a1SMatthew Ahrens #define	arc_meta_min	ARCSTAT(arcstat_meta_min) /* min size for metadata */
86720128a08SGeorge Wilson #define	arc_meta_max	ARCSTAT(arcstat_meta_max) /* max size of metadata */
86844cb6abcSbmc 
869dcbf3bd6SGeorge Wilson /* compressed size of entire arc */
870dcbf3bd6SGeorge Wilson #define	arc_compressed_size	ARCSTAT(arcstat_compressed_size)
871dcbf3bd6SGeorge Wilson /* uncompressed size of entire arc */
872dcbf3bd6SGeorge Wilson #define	arc_uncompressed_size	ARCSTAT(arcstat_uncompressed_size)
873dcbf3bd6SGeorge Wilson /* number of bytes in the arc from arc_buf_t's */
874dcbf3bd6SGeorge Wilson #define	arc_overhead_size	ARCSTAT(arcstat_overhead_size)
875aad02571SSaso Kiselkov 
8763a2d8a1bSPaul Dagnelie /*
8773a2d8a1bSPaul Dagnelie  * There are also some ARC variables that we want to export, but that are
8783a2d8a1bSPaul Dagnelie  * updated so often that having the canonical representation be the statistic
8793a2d8a1bSPaul Dagnelie  * variable causes a performance bottleneck. We want to use aggsum_t's for these
8803a2d8a1bSPaul Dagnelie  * instead, but still be able to export the kstat in the same way as before.
8813a2d8a1bSPaul Dagnelie  * The solution is to always use the aggsum version, except in the kstat update
8823a2d8a1bSPaul Dagnelie  * callback.
8833a2d8a1bSPaul Dagnelie  */
8843a2d8a1bSPaul Dagnelie aggsum_t arc_size;
8853a2d8a1bSPaul Dagnelie aggsum_t arc_meta_used;
8863a2d8a1bSPaul Dagnelie aggsum_t astat_data_size;
8873a2d8a1bSPaul Dagnelie aggsum_t astat_metadata_size;
8883a2d8a1bSPaul Dagnelie aggsum_t astat_hdr_size;
8893a2d8a1bSPaul Dagnelie aggsum_t astat_other_size;
8903a2d8a1bSPaul Dagnelie aggsum_t astat_l2_hdr_size;
8913a2d8a1bSPaul Dagnelie 
89244cb6abcSbmc static int		arc_no_grow;	/* Don't try to grow cache size */
893de753e34SBrad Lewis static hrtime_t		arc_growtime;
89444cb6abcSbmc static uint64_t		arc_tempreserve;
8952fdbea25SAleksandr Guzovskiy static uint64_t		arc_loaned_bytes;
896fa9e4066Sahrens 
897fa9e4066Sahrens typedef struct arc_callback arc_callback_t;
898fa9e4066Sahrens 
899fa9e4066Sahrens struct arc_callback {
900fa9e4066Sahrens 	void			*acb_private;
901a3874b8bSToomas Soome 	arc_read_done_func_t	*acb_done;
902fa9e4066Sahrens 	arc_buf_t		*acb_buf;
903*eb633035STom Caputi 	boolean_t		acb_encrypted;
9045602294fSDan Kimmel 	boolean_t		acb_compressed;
905*eb633035STom Caputi 	boolean_t		acb_noauth;
906*eb633035STom Caputi 	zbookmark_phys_t	acb_zb;
907fa9e4066Sahrens 	zio_t			*acb_zio_dummy;
908a3874b8bSToomas Soome 	zio_t			*acb_zio_head;
909fa9e4066Sahrens 	arc_callback_t		*acb_next;
910fa9e4066Sahrens };
911fa9e4066Sahrens 
912c717a561Smaybee typedef struct arc_write_callback arc_write_callback_t;
913c717a561Smaybee 
914c717a561Smaybee struct arc_write_callback {
915a3874b8bSToomas Soome 	void			*awcb_private;
916a3874b8bSToomas Soome 	arc_write_done_func_t	*awcb_ready;
917a3874b8bSToomas Soome 	arc_write_done_func_t	*awcb_children_ready;
918a3874b8bSToomas Soome 	arc_write_done_func_t	*awcb_physdone;
919a3874b8bSToomas Soome 	arc_write_done_func_t	*awcb_done;
920a3874b8bSToomas Soome 	arc_buf_t		*awcb_buf;
921c717a561Smaybee };
922c717a561Smaybee 
92389c86e32SChris Williamson /*
92489c86e32SChris Williamson  * ARC buffers are separated into multiple structs as a memory saving measure:
92589c86e32SChris Williamson  *   - Common fields struct, always defined, and embedded within it:
92689c86e32SChris Williamson  *       - L2-only fields, always allocated but undefined when not in L2ARC
92789c86e32SChris Williamson  *       - L1-only fields, only allocated when in L1ARC
92889c86e32SChris Williamson  *
92989c86e32SChris Williamson  *           Buffer in L1                     Buffer only in L2
93089c86e32SChris Williamson  *    +------------------------+          +------------------------+
93189c86e32SChris Williamson  *    | arc_buf_hdr_t          |          | arc_buf_hdr_t          |
93289c86e32SChris Williamson  *    |                        |          |                        |
93389c86e32SChris Williamson  *    |                        |          |                        |
93489c86e32SChris Williamson  *    |                        |          |                        |
93589c86e32SChris Williamson  *    +------------------------+          +------------------------+
93689c86e32SChris Williamson  *    | l2arc_buf_hdr_t        |          | l2arc_buf_hdr_t        |
93789c86e32SChris Williamson  *    | (undefined if L1-only) |          |                        |
93889c86e32SChris Williamson  *    +------------------------+          +------------------------+
93989c86e32SChris Williamson  *    | l1arc_buf_hdr_t        |
94089c86e32SChris Williamson  *    |                        |
94189c86e32SChris Williamson  *    |                        |
94289c86e32SChris Williamson  *    |                        |
94389c86e32SChris Williamson  *    |                        |
94489c86e32SChris Williamson  *    +------------------------+
94589c86e32SChris Williamson  *
94689c86e32SChris Williamson  * Because it's possible for the L2ARC to become extremely large, we can wind
94789c86e32SChris Williamson  * up eating a lot of memory in L2ARC buffer headers, so the size of a header
94889c86e32SChris Williamson  * is minimized by only allocating the fields necessary for an L1-cached buffer
94989c86e32SChris Williamson  * when a header is actually in the L1 cache. The sub-headers (l1arc_buf_hdr and
95089c86e32SChris Williamson  * l2arc_buf_hdr) are embedded rather than allocated separately to save a couple
95189c86e32SChris Williamson  * words in pointers. arc_hdr_realloc() is used to switch a header between
95289c86e32SChris Williamson  * these two allocation states.
95389c86e32SChris Williamson  */
95489c86e32SChris Williamson typedef struct l1arc_buf_hdr {
9556b4acc8bSahrens 	kmutex_t		b_freeze_lock;
956dcbf3bd6SGeorge Wilson 	zio_cksum_t		*b_freeze_cksum;
95789c86e32SChris Williamson #ifdef ZFS_DEBUG
95889c86e32SChris Williamson 	/*
9595602294fSDan Kimmel 	 * Used for debugging with kmem_flags - by allocating and freeing
96089c86e32SChris Williamson 	 * b_thawed when the buffer is thawed, we get a record of the stack
96189c86e32SChris Williamson 	 * trace that thawed it.
96289c86e32SChris Williamson 	 */
9633f9d6ad7SLin Ling 	void			*b_thawed;
96489c86e32SChris Williamson #endif
9656b4acc8bSahrens 
966fa9e4066Sahrens 	arc_buf_t		*b_buf;
967dcbf3bd6SGeorge Wilson 	uint32_t		b_bufcnt;
96889c86e32SChris Williamson 	/* for waiting on writes to complete */
969ad23a2dbSjohansen 	kcondvar_t		b_cv;
970dcbf3bd6SGeorge Wilson 	uint8_t			b_byteswap;
971ad23a2dbSjohansen 
972fa9e4066Sahrens 	/* protected by arc state mutex */
973fa9e4066Sahrens 	arc_state_t		*b_state;
974244781f1SPrakash Surya 	multilist_node_t	b_arc_node;
975fa9e4066Sahrens 
976fa9e4066Sahrens 	/* updated atomically */
977fa9e4066Sahrens 	clock_t			b_arc_access;
978fa9e4066Sahrens 
979fa9e4066Sahrens 	/* self protecting */
980e914ace2STim Schumacher 	zfs_refcount_t		b_refcnt;
981fa94a07fSbrendan 
98289c86e32SChris Williamson 	arc_callback_t		*b_acb;
983770499e1SDan Kimmel 	abd_t			*b_pabd;
98489c86e32SChris Williamson } l1arc_buf_hdr_t;
98589c86e32SChris Williamson 
986*eb633035STom Caputi /*
987*eb633035STom Caputi  * Encrypted blocks will need to be stored encrypted on the L2ARC
988*eb633035STom Caputi  * disk as they appear in the main pool. In order for this to work we
989*eb633035STom Caputi  * need to pass around the encryption parameters so they can be used
990*eb633035STom Caputi  * to write data to the L2ARC. This struct is only defined in the
991*eb633035STom Caputi  * arc_buf_hdr_t if the L1 header is defined and has the ARC_FLAG_ENCRYPTED
992*eb633035STom Caputi  * flag set.
993*eb633035STom Caputi  */
994*eb633035STom Caputi typedef struct arc_buf_hdr_crypt {
995*eb633035STom Caputi 	abd_t		*b_rabd;		/* raw encrypted data */
996*eb633035STom Caputi 	dmu_object_type_t	b_ot;		/* object type */
997*eb633035STom Caputi 	uint32_t		b_ebufcnt;	/* number or encryped buffers */
998*eb633035STom Caputi 
999*eb633035STom Caputi 	/* dsobj for looking up encryption key for l2arc encryption */
1000*eb633035STom Caputi 	uint64_t		b_dsobj;	/* for looking up key */
1001*eb633035STom Caputi 
1002*eb633035STom Caputi 	/* encryption parameters */
1003*eb633035STom Caputi 	uint8_t		b_salt[ZIO_DATA_SALT_LEN];
1004*eb633035STom Caputi 	uint8_t		b_iv[ZIO_DATA_IV_LEN];
1005*eb633035STom Caputi 
1006*eb633035STom Caputi 	/*
1007*eb633035STom Caputi 	 * Technically this could be removed since we will always be able to
1008*eb633035STom Caputi 	 * get the mac from the bp when we need it. However, it is inconvenient
1009*eb633035STom Caputi 	 * for callers of arc code to have to pass a bp in all the time. This
1010*eb633035STom Caputi 	 * also allows us to assert that L2ARC data is properly encrypted to
1011*eb633035STom Caputi 	 * match the data in the main storage pool.
1012*eb633035STom Caputi 	 */
1013*eb633035STom Caputi 	uint8_t		b_mac[ZIO_DATA_MAC_LEN];
1014*eb633035STom Caputi } arc_buf_hdr_crypt_t;
1015*eb633035STom Caputi 
101689c86e32SChris Williamson typedef struct l2arc_dev l2arc_dev_t;
101789c86e32SChris Williamson 
101889c86e32SChris Williamson typedef struct l2arc_buf_hdr {
101989c86e32SChris Williamson 	/* protected by arc_buf_hdr mutex */
102089c86e32SChris Williamson 	l2arc_dev_t		*b_dev;		/* L2ARC device */
102189c86e32SChris Williamson 	uint64_t		b_daddr;	/* disk address, offset byte */
102289c86e32SChris Williamson 
1023fa94a07fSbrendan 	list_node_t		b_l2node;
102489c86e32SChris Williamson } l2arc_buf_hdr_t;
102589c86e32SChris Williamson 
102689c86e32SChris Williamson struct arc_buf_hdr {
102789c86e32SChris Williamson 	/* protected by hash lock */
102889c86e32SChris Williamson 	dva_t			b_dva;
102989c86e32SChris Williamson 	uint64_t		b_birth;
103089c86e32SChris Williamson 
1031dcbf3bd6SGeorge Wilson 	arc_buf_contents_t	b_type;
103289c86e32SChris Williamson 	arc_buf_hdr_t		*b_hash_next;
103389c86e32SChris Williamson 	arc_flags_t		b_flags;
103489c86e32SChris Williamson 
1035dcbf3bd6SGeorge Wilson 	/*
1036dcbf3bd6SGeorge Wilson 	 * This field stores the size of the data buffer after
1037dcbf3bd6SGeorge Wilson 	 * compression, and is set in the arc's zio completion handlers.
1038dcbf3bd6SGeorge Wilson 	 * It is in units of SPA_MINBLOCKSIZE (e.g. 1 == 512 bytes).
1039dcbf3bd6SGeorge Wilson 	 *
1040dcbf3bd6SGeorge Wilson 	 * While the block pointers can store up to 32MB in their psize
1041dcbf3bd6SGeorge Wilson 	 * field, we can only store up to 32MB minus 512B. This is due
1042dcbf3bd6SGeorge Wilson 	 * to the bp using a bias of 1, whereas we use a bias of 0 (i.e.
1043dcbf3bd6SGeorge Wilson 	 * a field of zeros represents 512B in the bp). We can't use a
1044dcbf3bd6SGeorge Wilson 	 * bias of 1 since we need to reserve a psize of zero, here, to
1045dcbf3bd6SGeorge Wilson 	 * represent holes and embedded blocks.
1046dcbf3bd6SGeorge Wilson 	 *
1047dcbf3bd6SGeorge Wilson 	 * This isn't a problem in practice, since the maximum size of a
1048dcbf3bd6SGeorge Wilson 	 * buffer is limited to 16MB, so we never need to store 32MB in
1049dcbf3bd6SGeorge Wilson 	 * this field. Even in the upstream illumos code base, the
1050dcbf3bd6SGeorge Wilson 	 * maximum size of a buffer is limited to 16MB.
1051dcbf3bd6SGeorge Wilson 	 */
1052dcbf3bd6SGeorge Wilson 	uint16_t		b_psize;
1053dcbf3bd6SGeorge Wilson 
1054dcbf3bd6SGeorge Wilson 	/*
1055dcbf3bd6SGeorge Wilson 	 * This field stores the size of the data buffer before
1056dcbf3bd6SGeorge Wilson 	 * compression, and cannot change once set. It is in units
1057dcbf3bd6SGeorge Wilson 	 * of SPA_MINBLOCKSIZE (e.g. 2 == 1024 bytes)
1058dcbf3bd6SGeorge Wilson 	 */
1059dcbf3bd6SGeorge Wilson 	uint16_t		b_lsize;	/* immutable */
1060dcbf3bd6SGeorge Wilson 	uint64_t		b_spa;		/* immutable */
106189c86e32SChris Williamson 
106289c86e32SChris Williamson 	/* L2ARC fields. Undefined when not in L2ARC. */
106389c86e32SChris Williamson 	l2arc_buf_hdr_t		b_l2hdr;
106489c86e32SChris Williamson 	/* L1ARC fields. Undefined when in l2arc_only state */
106589c86e32SChris Williamson 	l1arc_buf_hdr_t		b_l1hdr;
1066*eb633035STom Caputi 	/*
1067*eb633035STom Caputi 	 * Encryption parameters. Defined only when ARC_FLAG_ENCRYPTED
1068*eb633035STom Caputi 	 * is set and the L1 header exists.
1069*eb633035STom Caputi 	 */
1070*eb633035STom Caputi 	arc_buf_hdr_crypt_t b_crypt_hdr;
1071fa9e4066Sahrens };
1072fa9e4066Sahrens 
1073ea8dc4b6Seschrock #define	GHOST_STATE(state)	\
1074fa94a07fSbrendan 	((state) == arc_mru_ghost || (state) == arc_mfu_ghost ||	\
1075fa94a07fSbrendan 	(state) == arc_l2c_only)
1076ea8dc4b6Seschrock 
10777adb730bSGeorge Wilson #define	HDR_IN_HASH_TABLE(hdr)	((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
10787adb730bSGeorge Wilson #define	HDR_IO_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
10797adb730bSGeorge Wilson #define	HDR_IO_ERROR(hdr)	((hdr)->b_flags & ARC_FLAG_IO_ERROR)
10807adb730bSGeorge Wilson #define	HDR_PREFETCH(hdr)	((hdr)->b_flags & ARC_FLAG_PREFETCH)
1081a3874b8bSToomas Soome #define	HDR_PRESCIENT_PREFETCH(hdr)	\
1082a3874b8bSToomas Soome 	((hdr)->b_flags & ARC_FLAG_PRESCIENT_PREFETCH)
1083dcbf3bd6SGeorge Wilson #define	HDR_COMPRESSION_ENABLED(hdr)	\
1084dcbf3bd6SGeorge Wilson 	((hdr)->b_flags & ARC_FLAG_COMPRESSED_ARC)
108589c86e32SChris Williamson 
10867adb730bSGeorge Wilson #define	HDR_L2CACHE(hdr)	((hdr)->b_flags & ARC_FLAG_L2CACHE)
10877adb730bSGeorge Wilson #define	HDR_L2_READING(hdr)	\
1088dcbf3bd6SGeorge Wilson 	(((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) &&	\
1089dcbf3bd6SGeorge Wilson 	((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
10907adb730bSGeorge Wilson #define	HDR_L2_WRITING(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITING)
10917adb730bSGeorge Wilson #define	HDR_L2_EVICTED(hdr)	((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
10927adb730bSGeorge Wilson #define	HDR_L2_WRITE_HEAD(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
1093*eb633035STom Caputi #define	HDR_PROTECTED(hdr)	((hdr)->b_flags & ARC_FLAG_PROTECTED)
1094*eb633035STom Caputi #define	HDR_NOAUTH(hdr)		((hdr)->b_flags & ARC_FLAG_NOAUTH)
1095dcbf3bd6SGeorge Wilson #define	HDR_SHARED_DATA(hdr)	((hdr)->b_flags & ARC_FLAG_SHARED_DATA)
1096fa9e4066Sahrens 
109789c86e32SChris Williamson #define	HDR_ISTYPE_METADATA(hdr)	\
1098dcbf3bd6SGeorge Wilson 	((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
109989c86e32SChris Williamson #define	HDR_ISTYPE_DATA(hdr)	(!HDR_ISTYPE_METADATA(hdr))
110089c86e32SChris Williamson 
110189c86e32SChris Williamson #define	HDR_HAS_L1HDR(hdr)	((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
110289c86e32SChris Williamson #define	HDR_HAS_L2HDR(hdr)	((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
1103*eb633035STom Caputi #define	HDR_HAS_RABD(hdr)	\
1104*eb633035STom Caputi 	(HDR_HAS_L1HDR(hdr) && HDR_PROTECTED(hdr) &&	\
1105*eb633035STom Caputi 	(hdr)->b_crypt_hdr.b_rabd != NULL)
1106*eb633035STom Caputi #define	HDR_ENCRYPTED(hdr)	\
1107*eb633035STom Caputi 	(HDR_PROTECTED(hdr) && DMU_OT_IS_ENCRYPTED((hdr)->b_crypt_hdr.b_ot))
1108*eb633035STom Caputi #define	HDR_AUTHENTICATED(hdr)	\
1109*eb633035STom Caputi 	(HDR_PROTECTED(hdr) && !DMU_OT_IS_ENCRYPTED((hdr)->b_crypt_hdr.b_ot))
111089c86e32SChris Williamson 
1111dcbf3bd6SGeorge Wilson /* For storing compression mode in b_flags */
1112dcbf3bd6SGeorge Wilson #define	HDR_COMPRESS_OFFSET	(highbit64(ARC_FLAG_COMPRESS_0) - 1)
1113dcbf3bd6SGeorge Wilson 
1114dcbf3bd6SGeorge Wilson #define	HDR_GET_COMPRESS(hdr)	((enum zio_compress)BF32_GET((hdr)->b_flags, \
1115dcbf3bd6SGeorge Wilson 	HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS))
1116dcbf3bd6SGeorge Wilson #define	HDR_SET_COMPRESS(hdr, cmp) BF32_SET((hdr)->b_flags, \
1117dcbf3bd6SGeorge Wilson 	HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS, (cmp));
1118dcbf3bd6SGeorge Wilson 
1119dcbf3bd6SGeorge Wilson #define	ARC_BUF_LAST(buf)	((buf)->b_next == NULL)
11205602294fSDan Kimmel #define	ARC_BUF_SHARED(buf)	((buf)->b_flags & ARC_BUF_FLAG_SHARED)
11215602294fSDan Kimmel #define	ARC_BUF_COMPRESSED(buf)	((buf)->b_flags & ARC_BUF_FLAG_COMPRESSED)
1122*eb633035STom Caputi #define	ARC_BUF_ENCRYPTED(buf)	((buf)->b_flags & ARC_BUF_FLAG_ENCRYPTED)
1123dcbf3bd6SGeorge Wilson 
1124e6c728e1Sbrendan /*
1125e6c728e1Sbrendan  * Other sizes
1126e6c728e1Sbrendan  */
1127e6c728e1Sbrendan 
1128*eb633035STom Caputi #define	HDR_FULL_CRYPT_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
1129*eb633035STom Caputi #define	HDR_FULL_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_crypt_hdr))
113089c86e32SChris Williamson #define	HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
1131e6c728e1Sbrendan 
1132fa9e4066Sahrens /*
1133fa9e4066Sahrens  * Hash table routines
1134fa9e4066Sahrens  */
1135fa9e4066Sahrens 
1136fa9e4066Sahrens #define	HT_LOCK_PAD	64
1137fa9e4066Sahrens 
1138fa9e4066Sahrens struct ht_lock {
1139fa9e4066Sahrens 	kmutex_t	ht_lock;
1140fa9e4066Sahrens #ifdef _KERNEL
1141fa9e4066Sahrens 	unsigned char	pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
1142fa9e4066Sahrens #endif
1143fa9e4066Sahrens };
1144fa9e4066Sahrens 
1145fa9e4066Sahrens #define	BUF_LOCKS 256
1146fa9e4066Sahrens typedef struct buf_hash_table {
1147fa9e4066Sahrens 	uint64_t ht_mask;
1148fa9e4066Sahrens 	arc_buf_hdr_t **ht_table;
1149fa9e4066Sahrens 	struct ht_lock ht_locks[BUF_LOCKS];
1150fa9e4066Sahrens } buf_hash_table_t;
1151fa9e4066Sahrens 
1152fa9e4066Sahrens static buf_hash_table_t buf_hash_table;
1153fa9e4066Sahrens 
1154fa9e4066Sahrens #define	BUF_HASH_INDEX(spa, dva, birth) \
1155fa9e4066Sahrens 	(buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
1156fa9e4066Sahrens #define	BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
1157fa9e4066Sahrens #define	BUF_HASH_LOCK(idx)	(&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
11583f9d6ad7SLin Ling #define	HDR_LOCK(hdr) \
11593f9d6ad7SLin Ling 	(BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
1160fa9e4066Sahrens 
1161fa9e4066Sahrens uint64_t zfs_crc64_table[256];
1162fa9e4066Sahrens 
1163fa94a07fSbrendan /*
1164fa94a07fSbrendan  * Level 2 ARC
1165fa94a07fSbrendan  */
1166fa94a07fSbrendan 
1167fa94a07fSbrendan #define	L2ARC_WRITE_SIZE	(8 * 1024 * 1024)	/* initial write max */
1168aad02571SSaso Kiselkov #define	L2ARC_HEADROOM		2			/* num of writes */
1169aad02571SSaso Kiselkov /*
1170aad02571SSaso Kiselkov  * If we discover during ARC scan any buffers to be compressed, we boost
1171aad02571SSaso Kiselkov  * our headroom for the next scanning cycle by this percentage multiple.
1172aad02571SSaso Kiselkov  */
1173aad02571SSaso Kiselkov #define	L2ARC_HEADROOM_BOOST	200
11745a98e54bSBrendan Gregg - Sun Microsystems #define	L2ARC_FEED_SECS		1		/* caching interval secs */
11755a98e54bSBrendan Gregg - Sun Microsystems #define	L2ARC_FEED_MIN_MS	200		/* min caching interval ms */
1176fa94a07fSbrendan 
1177fa94a07fSbrendan #define	l2arc_writes_sent	ARCSTAT(arcstat_l2_writes_sent)
1178fa94a07fSbrendan #define	l2arc_writes_done	ARCSTAT(arcstat_l2_writes_done)
1179fa94a07fSbrendan 
1180f7170741SWill Andrews /* L2ARC Performance Tunables */
1181fa94a07fSbrendan uint64_t l2arc_write_max = L2ARC_WRITE_SIZE;	/* default max write size */
11823a737e0dSbrendan uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE;	/* extra write during warmup */
1183fa94a07fSbrendan uint64_t l2arc_headroom = L2ARC_HEADROOM;	/* number of dev writes */
1184aad02571SSaso Kiselkov uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
1185fa94a07fSbrendan uint64_t l2arc_feed_secs = L2ARC_FEED_SECS;	/* interval seconds */
11865a98e54bSBrendan Gregg - Sun Microsystems uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS;	/* min interval milliseconds */
1187fa94a07fSbrendan boolean_t l2arc_noprefetch = B_TRUE;		/* don't cache prefetch bufs */
11885a98e54bSBrendan Gregg - Sun Microsystems boolean_t l2arc_feed_again = B_TRUE;		/* turbo warmup */
11895a98e54bSBrendan Gregg - Sun Microsystems boolean_t l2arc_norw = B_TRUE;			/* no reads during writes */
1190fa94a07fSbrendan 
1191fa94a07fSbrendan /*
1192fa94a07fSbrendan  * L2ARC Internals
1193fa94a07fSbrendan  */
119489c86e32SChris Williamson struct l2arc_dev {
1195fa94a07fSbrendan 	vdev_t			*l2ad_vdev;	/* vdev */
1196fa94a07fSbrendan 	spa_t			*l2ad_spa;	/* spa */
1197fa94a07fSbrendan 	uint64_t		l2ad_hand;	/* next write location */
1198fa94a07fSbrendan 	uint64_t		l2ad_start;	/* first addr on device */
1199fa94a07fSbrendan 	uint64_t		l2ad_end;	/* last addr on device */
1200fa94a07fSbrendan 	boolean_t		l2ad_first;	/* first sweep through */
12015a98e54bSBrendan Gregg - Sun Microsystems 	boolean_t		l2ad_writing;	/* currently writing */
120289c86e32SChris Williamson 	kmutex_t		l2ad_mtx;	/* lock for buffer list */
120389c86e32SChris Williamson 	list_t			l2ad_buflist;	/* buffer list */
1204fa94a07fSbrendan 	list_node_t		l2ad_node;	/* device list node */
1205e914ace2STim Schumacher 	zfs_refcount_t		l2ad_alloc;	/* allocated bytes */
120689c86e32SChris Williamson };
1207fa94a07fSbrendan 
1208fa94a07fSbrendan static list_t L2ARC_dev_list;			/* device list */
1209fa94a07fSbrendan static list_t *l2arc_dev_list;			/* device list pointer */
1210fa94a07fSbrendan static kmutex_t l2arc_dev_mtx;			/* device list mutex */
1211fa94a07fSbrendan static l2arc_dev_t *l2arc_dev_last;		/* last device used */
1212fa94a07fSbrendan static list_t L2ARC_free_on_write;		/* free after write buf list */
1213fa94a07fSbrendan static list_t *l2arc_free_on_write;		/* free after write list ptr */
1214fa94a07fSbrendan static kmutex_t l2arc_free_on_write_mtx;	/* mutex for list */
1215fa94a07fSbrendan static uint64_t l2arc_ndev;			/* number of devices */
1216fa94a07fSbrendan 
1217fa94a07fSbrendan typedef struct l2arc_read_callback {
12185602294fSDan Kimmel 	arc_buf_hdr_t		*l2rcb_hdr;		/* read header */
1219aad02571SSaso Kiselkov 	blkptr_t		l2rcb_bp;		/* original blkptr */
12207802d7bfSMatthew Ahrens 	zbookmark_phys_t	l2rcb_zb;		/* original bookmark */
1221aad02571SSaso Kiselkov 	int			l2rcb_flags;		/* original flags */
1222403a8da7SAndriy Gapon 	abd_t			*l2rcb_abd;		/* temporary buffer */
1223fa94a07fSbrendan } l2arc_read_callback_t;
1224fa94a07fSbrendan 
1225fa94a07fSbrendan typedef struct l2arc_write_callback {
1226fa94a07fSbrendan 	l2arc_dev_t	*l2wcb_dev;		/* device info */
1227fa94a07fSbrendan 	arc_buf_hdr_t	*l2wcb_head;		/* head of write buflist */
1228fa94a07fSbrendan } l2arc_write_callback_t;
1229fa94a07fSbrendan 
1230fa94a07fSbrendan typedef struct l2arc_data_free {
1231fa94a07fSbrendan 	/* protected by l2arc_free_on_write_mtx */
1232770499e1SDan Kimmel 	abd_t		*l2df_abd;
1233fa94a07fSbrendan 	size_t		l2df_size;
1234dcbf3bd6SGeorge Wilson 	arc_buf_contents_t l2df_type;
1235fa94a07fSbrendan 	list_node_t	l2df_list_node;
1236fa94a07fSbrendan } l2arc_data_free_t;
1237fa94a07fSbrendan 
1238fa94a07fSbrendan static kmutex_t l2arc_feed_thr_lock;
1239fa94a07fSbrendan static kcondvar_t l2arc_feed_thr_cv;
1240fa94a07fSbrendan static uint8_t l2arc_thread_exit;
1241fa94a07fSbrendan 
1242770499e1SDan Kimmel static abd_t *arc_get_data_abd(arc_buf_hdr_t *, uint64_t, void *);
1243*eb633035STom Caputi typedef enum arc_fill_flags {
1244*eb633035STom Caputi 	ARC_FILL_LOCKED		= 1 << 0, /* hdr lock is held */
1245*eb633035STom Caputi 	ARC_FILL_COMPRESSED	= 1 << 1, /* fill with compressed data */
1246*eb633035STom Caputi 	ARC_FILL_ENCRYPTED	= 1 << 2, /* fill with encrypted data */
1247*eb633035STom Caputi 	ARC_FILL_NOAUTH		= 1 << 3, /* don't attempt to authenticate */
1248*eb633035STom Caputi 	ARC_FILL_IN_PLACE	= 1 << 4  /* fill in place (special case) */
1249*eb633035STom Caputi } arc_fill_flags_t;
1250*eb633035STom Caputi 
1251dcbf3bd6SGeorge Wilson static void *arc_get_data_buf(arc_buf_hdr_t *, uint64_t, void *);
1252770499e1SDan Kimmel static void arc_get_data_impl(arc_buf_hdr_t *, uint64_t, void *);
1253770499e1SDan Kimmel static void arc_free_data_abd(arc_buf_hdr_t *, abd_t *, uint64_t, void *);
1254dcbf3bd6SGeorge Wilson static void arc_free_data_buf(arc_buf_hdr_t *, void *, uint64_t, void *);
1255770499e1SDan Kimmel static void arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag);
1256*eb633035STom Caputi static void arc_hdr_free_pabd(arc_buf_hdr_t *, boolean_t);
1257*eb633035STom Caputi static void arc_hdr_alloc_pabd(arc_buf_hdr_t *, boolean_t);
12587adb730bSGeorge Wilson static void arc_access(arc_buf_hdr_t *, kmutex_t *);
1259244781f1SPrakash Surya static boolean_t arc_is_overflowing();
12607adb730bSGeorge Wilson static void arc_buf_watch(arc_buf_t *);
12617adb730bSGeorge Wilson 
126289c86e32SChris Williamson static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
126389c86e32SChris Williamson static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
1264dcbf3bd6SGeorge Wilson static inline void arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
1265dcbf3bd6SGeorge Wilson static inline void arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
126689c86e32SChris Williamson 
12677adb730bSGeorge Wilson static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
12687adb730bSGeorge Wilson static void l2arc_read_done(zio_t *);
1269fa94a07fSbrendan 
12703a2d8a1bSPaul Dagnelie 
12713a2d8a1bSPaul Dagnelie /*
12723a2d8a1bSPaul Dagnelie  * We use Cityhash for this. It's fast, and has good hash properties without
12733a2d8a1bSPaul Dagnelie  * requiring any large static buffers.
12743a2d8a1bSPaul Dagnelie  */
1275fa9e4066Sahrens static uint64_t
1276ac05c741SMark Maybee buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
1277fa9e4066Sahrens {
12783a2d8a1bSPaul Dagnelie 	return (cityhash4(spa, dva->dva_word[0], dva->dva_word[1], birth));
1279fa9e4066Sahrens }
1280fa9e4066Sahrens 
1281dcbf3bd6SGeorge Wilson #define	HDR_EMPTY(hdr)						\
1282dcbf3bd6SGeorge Wilson 	((hdr)->b_dva.dva_word[0] == 0 &&			\
1283dcbf3bd6SGeorge Wilson 	(hdr)->b_dva.dva_word[1] == 0)
1284fa9e4066Sahrens 
1285dcbf3bd6SGeorge Wilson #define	HDR_EQUAL(spa, dva, birth, hdr)				\
1286dcbf3bd6SGeorge Wilson 	((hdr)->b_dva.dva_word[0] == (dva)->dva_word[0]) &&	\
1287dcbf3bd6SGeorge Wilson 	((hdr)->b_dva.dva_word[1] == (dva)->dva_word[1]) &&	\
1288dcbf3bd6SGeorge Wilson 	((hdr)->b_birth == birth) && ((hdr)->b_spa == spa)
1289fa9e4066Sahrens 
12903f9d6ad7SLin Ling static void
12913f9d6ad7SLin Ling buf_discard_identity(arc_buf_hdr_t *hdr)
12923f9d6ad7SLin Ling {
12933f9d6ad7SLin Ling 	hdr->b_dva.dva_word[0] = 0;
12943f9d6ad7SLin Ling 	hdr->b_dva.dva_word[1] = 0;
12953f9d6ad7SLin Ling 	hdr->b_birth = 0;
12963f9d6ad7SLin Ling }
12973f9d6ad7SLin Ling 
1298fa9e4066Sahrens static arc_buf_hdr_t *
12995d7b4d43SMatthew Ahrens buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
1300fa9e4066Sahrens {
13015d7b4d43SMatthew Ahrens 	const dva_t *dva = BP_IDENTITY(bp);
13025d7b4d43SMatthew Ahrens 	uint64_t birth = BP_PHYSICAL_BIRTH(bp);
1303fa9e4066Sahrens 	uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1304fa9e4066Sahrens 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
13057adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr;
1306fa9e4066Sahrens 
1307fa9e4066Sahrens 	mutex_enter(hash_lock);
13087adb730bSGeorge Wilson 	for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
13097adb730bSGeorge Wilson 	    hdr = hdr->b_hash_next) {
1310dcbf3bd6SGeorge Wilson 		if (HDR_EQUAL(spa, dva, birth, hdr)) {
1311fa9e4066Sahrens 			*lockp = hash_lock;
13127adb730bSGeorge Wilson 			return (hdr);
1313fa9e4066Sahrens 		}
1314fa9e4066Sahrens 	}
1315fa9e4066Sahrens 	mutex_exit(hash_lock);
1316fa9e4066Sahrens 	*lockp = NULL;
1317fa9e4066Sahrens 	return (NULL);
1318fa9e4066Sahrens }
1319fa9e4066Sahrens 
1320fa9e4066Sahrens /*
1321fa9e4066Sahrens  * Insert an entry into the hash table.  If there is already an element
1322fa9e4066Sahrens  * equal to elem in the hash table, then the already existing element
1323fa9e4066Sahrens  * will be returned and the new element will not be inserted.
1324fa9e4066Sahrens  * Otherwise returns NULL.
132589c86e32SChris Williamson  * If lockp == NULL, the caller is assumed to already hold the hash lock.
1326fa9e4066Sahrens  */
1327fa9e4066Sahrens static arc_buf_hdr_t *
13287adb730bSGeorge Wilson buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1329fa9e4066Sahrens {
13307adb730bSGeorge Wilson 	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1331fa9e4066Sahrens 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
13327adb730bSGeorge Wilson 	arc_buf_hdr_t *fhdr;
133344cb6abcSbmc 	uint32_t i;
1334fa9e4066Sahrens 
13357adb730bSGeorge Wilson 	ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
13367adb730bSGeorge Wilson 	ASSERT(hdr->b_birth != 0);
13377adb730bSGeorge Wilson 	ASSERT(!HDR_IN_HASH_TABLE(hdr));
133889c86e32SChris Williamson 
133989c86e32SChris Williamson 	if (lockp != NULL) {
134089c86e32SChris Williamson 		*lockp = hash_lock;
134189c86e32SChris Williamson 		mutex_enter(hash_lock);
134289c86e32SChris Williamson 	} else {
134389c86e32SChris Williamson 		ASSERT(MUTEX_HELD(hash_lock));
134489c86e32SChris Williamson 	}
134589c86e32SChris Williamson 
13467adb730bSGeorge Wilson 	for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
13477adb730bSGeorge Wilson 	    fhdr = fhdr->b_hash_next, i++) {
1348dcbf3bd6SGeorge Wilson 		if (HDR_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
13497adb730bSGeorge Wilson 			return (fhdr);
1350fa9e4066Sahrens 	}
1351fa9e4066Sahrens 
13527adb730bSGeorge Wilson 	hdr->b_hash_next = buf_hash_table.ht_table[idx];
13537adb730bSGeorge Wilson 	buf_hash_table.ht_table[idx] = hdr;
1354dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1355fa9e4066Sahrens 
1356fa9e4066Sahrens 	/* collect some hash table performance data */
1357fa9e4066Sahrens 	if (i > 0) {
135844cb6abcSbmc 		ARCSTAT_BUMP(arcstat_hash_collisions);
1359fa9e4066Sahrens 		if (i == 1)
136044cb6abcSbmc 			ARCSTAT_BUMP(arcstat_hash_chains);
136144cb6abcSbmc 
136244cb6abcSbmc 		ARCSTAT_MAX(arcstat_hash_chain_max, i);
1363fa9e4066Sahrens 	}
136444cb6abcSbmc 
136544cb6abcSbmc 	ARCSTAT_BUMP(arcstat_hash_elements);
136644cb6abcSbmc 	ARCSTAT_MAXSTAT(arcstat_hash_elements);
1367fa9e4066Sahrens 
1368fa9e4066Sahrens 	return (NULL);
1369fa9e4066Sahrens }
1370fa9e4066Sahrens 
1371fa9e4066Sahrens static void
13727adb730bSGeorge Wilson buf_hash_remove(arc_buf_hdr_t *hdr)
1373fa9e4066Sahrens {
13747adb730bSGeorge Wilson 	arc_buf_hdr_t *fhdr, **hdrp;
13757adb730bSGeorge Wilson 	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1376fa9e4066Sahrens 
1377fa9e4066Sahrens 	ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
13787adb730bSGeorge Wilson 	ASSERT(HDR_IN_HASH_TABLE(hdr));
1379fa9e4066Sahrens 
13807adb730bSGeorge Wilson 	hdrp = &buf_hash_table.ht_table[idx];
13817adb730bSGeorge Wilson 	while ((fhdr = *hdrp) != hdr) {
1382dcbf3bd6SGeorge Wilson 		ASSERT3P(fhdr, !=, NULL);
13837adb730bSGeorge Wilson 		hdrp = &fhdr->b_hash_next;
1384fa9e4066Sahrens 	}
13857adb730bSGeorge Wilson 	*hdrp = hdr->b_hash_next;
13867adb730bSGeorge Wilson 	hdr->b_hash_next = NULL;
1387dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1388fa9e4066Sahrens 
1389fa9e4066Sahrens 	/* collect some hash table performance data */
139044cb6abcSbmc 	ARCSTAT_BUMPDOWN(arcstat_hash_elements);
139144cb6abcSbmc 
1392fa9e4066Sahrens 	if (buf_hash_table.ht_table[idx] &&
1393fa9e4066Sahrens 	    buf_hash_table.ht_table[idx]->b_hash_next == NULL)
139444cb6abcSbmc 		ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1395fa9e4066Sahrens }
1396fa9e4066Sahrens 
1397fa9e4066Sahrens /*
1398fa9e4066Sahrens  * Global data structures and functions for the buf kmem cache.
1399fa9e4066Sahrens  */
1400*eb633035STom Caputi 
140189c86e32SChris Williamson static kmem_cache_t *hdr_full_cache;
1402*eb633035STom Caputi static kmem_cache_t *hdr_full_crypt_cache;
140389c86e32SChris Williamson static kmem_cache_t *hdr_l2only_cache;
1404fa9e4066Sahrens static kmem_cache_t *buf_cache;
1405fa9e4066Sahrens 
1406fa9e4066Sahrens static void
1407fa9e4066Sahrens buf_fini(void)
1408fa9e4066Sahrens {
1409fa9e4066Sahrens 	int i;
1410fa9e4066Sahrens 
1411fa9e4066Sahrens 	kmem_free(buf_hash_table.ht_table,
1412fa9e4066Sahrens 	    (buf_hash_table.ht_mask + 1) * sizeof (void *));
1413fa9e4066Sahrens 	for (i = 0; i < BUF_LOCKS; i++)
1414fa9e4066Sahrens 		mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
141589c86e32SChris Williamson 	kmem_cache_destroy(hdr_full_cache);
1416*eb633035STom Caputi 	kmem_cache_destroy(hdr_full_crypt_cache);
141789c86e32SChris Williamson 	kmem_cache_destroy(hdr_l2only_cache);
1418fa9e4066Sahrens 	kmem_cache_destroy(buf_cache);
1419fa9e4066Sahrens }
1420fa9e4066Sahrens 
1421fa9e4066Sahrens /*
1422fa9e4066Sahrens  * Constructor callback - called when the cache is empty
1423fa9e4066Sahrens  * and a new buf is requested.
1424fa9e4066Sahrens  */
1425fa9e4066Sahrens /* ARGSUSED */
1426fa9e4066Sahrens static int
142789c86e32SChris Williamson hdr_full_cons(void *vbuf, void *unused, int kmflag)
1428fa9e4066Sahrens {
14297adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr = vbuf;
1430fa9e4066Sahrens 
143189c86e32SChris Williamson 	bzero(hdr, HDR_FULL_SIZE);
1432*eb633035STom Caputi 	hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
143389c86e32SChris Williamson 	cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
1434e914ace2STim Schumacher 	zfs_refcount_create(&hdr->b_l1hdr.b_refcnt);
143589c86e32SChris Williamson 	mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1436244781f1SPrakash Surya 	multilist_link_init(&hdr->b_l1hdr.b_arc_node);
143789c86e32SChris Williamson 	arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
143889c86e32SChris Williamson 
143989c86e32SChris Williamson 	return (0);
144089c86e32SChris Williamson }
144189c86e32SChris Williamson 
1442*eb633035STom Caputi /* ARGSUSED */
1443*eb633035STom Caputi static int
1444*eb633035STom Caputi hdr_full_crypt_cons(void *vbuf, void *unused, int kmflag)
1445*eb633035STom Caputi {
1446*eb633035STom Caputi 	arc_buf_hdr_t *hdr = vbuf;
1447*eb633035STom Caputi 
1448*eb633035STom Caputi 	(void) hdr_full_cons(vbuf, unused, kmflag);
1449*eb633035STom Caputi 	bzero(&hdr->b_crypt_hdr, sizeof (hdr->b_crypt_hdr));
1450*eb633035STom Caputi 	arc_space_consume(sizeof (hdr->b_crypt_hdr), ARC_SPACE_HDRS);
1451*eb633035STom Caputi 
1452*eb633035STom Caputi 	return (0);
1453*eb633035STom Caputi }
1454*eb633035STom Caputi 
145589c86e32SChris Williamson /* ARGSUSED */
145689c86e32SChris Williamson static int
145789c86e32SChris Williamson hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
145889c86e32SChris Williamson {
145989c86e32SChris Williamson 	arc_buf_hdr_t *hdr = vbuf;
146089c86e32SChris Williamson 
146189c86e32SChris Williamson 	bzero(hdr, HDR_L2ONLY_SIZE);
146289c86e32SChris Williamson 	arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1463fa94a07fSbrendan 
1464fa9e4066Sahrens 	return (0);
1465fa9e4066Sahrens }
1466fa9e4066Sahrens 
14676f83844dSMark Maybee /* ARGSUSED */
14686f83844dSMark Maybee static int
14696f83844dSMark Maybee buf_cons(void *vbuf, void *unused, int kmflag)
14706f83844dSMark Maybee {
14716f83844dSMark Maybee 	arc_buf_t *buf = vbuf;
14726f83844dSMark Maybee 
14736f83844dSMark Maybee 	bzero(buf, sizeof (arc_buf_t));
14743f9d6ad7SLin Ling 	mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
14755a98e54bSBrendan Gregg - Sun Microsystems 	arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
14765a98e54bSBrendan Gregg - Sun Microsystems 
14776f83844dSMark Maybee 	return (0);
14786f83844dSMark Maybee }
14796f83844dSMark Maybee 
1480fa9e4066Sahrens /*
1481fa9e4066Sahrens  * Destructor callback - called when a cached buf is
1482fa9e4066Sahrens  * no longer required.
1483fa9e4066Sahrens  */
1484fa9e4066Sahrens /* ARGSUSED */
1485fa9e4066Sahrens static void
148689c86e32SChris Williamson hdr_full_dest(void *vbuf, void *unused)
148789c86e32SChris Williamson {
148889c86e32SChris Williamson 	arc_buf_hdr_t *hdr = vbuf;
148989c86e32SChris Williamson 
1490dcbf3bd6SGeorge Wilson 	ASSERT(HDR_EMPTY(hdr));
149189c86e32SChris Williamson 	cv_destroy(&hdr->b_l1hdr.b_cv);
1492e914ace2STim Schumacher 	zfs_refcount_destroy(&hdr->b_l1hdr.b_refcnt);
149389c86e32SChris Williamson 	mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1494244781f1SPrakash Surya 	ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
149589c86e32SChris Williamson 	arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
149689c86e32SChris Williamson }
149789c86e32SChris Williamson 
1498*eb633035STom Caputi /* ARGSUSED */
1499*eb633035STom Caputi static void
1500*eb633035STom Caputi hdr_full_crypt_dest(void *vbuf, void *unused)
1501*eb633035STom Caputi {
1502*eb633035STom Caputi 	arc_buf_hdr_t *hdr = vbuf;
1503*eb633035STom Caputi 
1504*eb633035STom Caputi 	hdr_full_dest(hdr, unused);
1505*eb633035STom Caputi 	arc_space_return(sizeof (hdr->b_crypt_hdr), ARC_SPACE_HDRS);
1506*eb633035STom Caputi }
1507*eb633035STom Caputi 
150889c86e32SChris Williamson /* ARGSUSED */
150989c86e32SChris Williamson static void
151089c86e32SChris Williamson hdr_l2only_dest(void *vbuf, void *unused)
1511fa9e4066Sahrens {
15127adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr = vbuf;
1513fa9e4066Sahrens 
1514dcbf3bd6SGeorge Wilson 	ASSERT(HDR_EMPTY(hdr));
151589c86e32SChris Williamson 	arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1516fa9e4066Sahrens }
1517fa9e4066Sahrens 
15186f83844dSMark Maybee /* ARGSUSED */
15196f83844dSMark Maybee static void
15206f83844dSMark Maybee buf_dest(void *vbuf, void *unused)
15216f83844dSMark Maybee {
15226f83844dSMark Maybee 	arc_buf_t *buf = vbuf;
15236f83844dSMark Maybee 
15243f9d6ad7SLin Ling 	mutex_destroy(&buf->b_evict_lock);
15255a98e54bSBrendan Gregg - Sun Microsystems 	arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
15266f83844dSMark Maybee }
15276f83844dSMark Maybee 
1528fa9e4066Sahrens /*
1529fa9e4066Sahrens  * Reclaim callback -- invoked when memory is low.
1530fa9e4066Sahrens  */
1531fa9e4066Sahrens /* ARGSUSED */
1532fa9e4066Sahrens static void
1533fa9e4066Sahrens hdr_recl(void *unused)
1534fa9e4066Sahrens {
1535fa9e4066Sahrens 	dprintf("hdr_recl called\n");
153649e3519aSmaybee 	/*
153749e3519aSmaybee 	 * umem calls the reclaim func when we destroy the buf cache,
153849e3519aSmaybee 	 * which is after we do arc_fini().
153949e3519aSmaybee 	 */
1540de753e34SBrad Lewis 	if (arc_initialized)
1541de753e34SBrad Lewis 		zthr_wakeup(arc_reap_zthr);
1542fa9e4066Sahrens }
1543fa9e4066Sahrens 
1544fa9e4066Sahrens static void
1545fa9e4066Sahrens buf_init(void)
1546fa9e4066Sahrens {
1547fa9e4066Sahrens 	uint64_t *ct;
1548ea8dc4b6Seschrock 	uint64_t hsize = 1ULL << 12;
1549fa9e4066Sahrens 	int i, j;
1550fa9e4066Sahrens 
1551fa9e4066Sahrens 	/*
1552fa9e4066Sahrens 	 * The hash table is big enough to fill all of physical memory
155363e911b6SMatthew Ahrens 	 * with an average block size of zfs_arc_average_blocksize (default 8K).
155463e911b6SMatthew Ahrens 	 * By default, the table will take up
155563e911b6SMatthew Ahrens 	 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1556fa9e4066Sahrens 	 */
155763e911b6SMatthew Ahrens 	while (hsize * zfs_arc_average_blocksize < physmem * PAGESIZE)
1558fa9e4066Sahrens 		hsize <<= 1;
1559ea8dc4b6Seschrock retry:
1560fa9e4066Sahrens 	buf_hash_table.ht_mask = hsize - 1;
1561ea8dc4b6Seschrock 	buf_hash_table.ht_table =
1562ea8dc4b6Seschrock 	    kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1563ea8dc4b6Seschrock 	if (buf_hash_table.ht_table == NULL) {
1564ea8dc4b6Seschrock 		ASSERT(hsize > (1ULL << 8));
1565ea8dc4b6Seschrock 		hsize >>= 1;
1566ea8dc4b6Seschrock 		goto retry;
1567ea8dc4b6Seschrock 	}
1568fa9e4066Sahrens 
156989c86e32SChris Williamson 	hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
157089c86e32SChris Williamson 	    0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
1571*eb633035STom Caputi 	hdr_full_crypt_cache = kmem_cache_create("arc_buf_hdr_t_full_crypt",
1572*eb633035STom Caputi 	    HDR_FULL_CRYPT_SIZE, 0, hdr_full_crypt_cons, hdr_full_crypt_dest,
1573*eb633035STom Caputi 	    hdr_recl, NULL, NULL, 0);
157489c86e32SChris Williamson 	hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
157589c86e32SChris Williamson 	    HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
157689c86e32SChris Williamson 	    NULL, NULL, 0);
1577fa9e4066Sahrens 	buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
15786f83844dSMark Maybee 	    0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1579fa9e4066Sahrens 
1580fa9e4066Sahrens 	for (i = 0; i < 256; i++)
1581fa9e4066Sahrens 		for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1582fa9e4066Sahrens 			*ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1583fa9e4066Sahrens 
1584fa9e4066Sahrens 	for (i = 0; i < BUF_LOCKS; i++) {
1585fa9e4066Sahrens 		mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1586fa9e4066Sahrens 		    NULL, MUTEX_DEFAULT, NULL);
1587fa9e4066Sahrens 	}
1588fa9e4066Sahrens }
1589fa9e4066Sahrens 
15905602294fSDan Kimmel /*
15915602294fSDan Kimmel  * This is the size that the buf occupies in memory. If the buf is compressed,
15925602294fSDan Kimmel  * it will correspond to the compressed size. You should use this method of
15935602294fSDan Kimmel  * getting the buf size unless you explicitly need the logical size.
15945602294fSDan Kimmel  */
15955602294fSDan Kimmel int32_t
15965602294fSDan Kimmel arc_buf_size(arc_buf_t *buf)
15975602294fSDan Kimmel {
15985602294fSDan Kimmel 	return (ARC_BUF_COMPRESSED(buf) ?
15995602294fSDan Kimmel 	    HDR_GET_PSIZE(buf->b_hdr) : HDR_GET_LSIZE(buf->b_hdr));
16005602294fSDan Kimmel }
16015602294fSDan Kimmel 
16025602294fSDan Kimmel int32_t
16035602294fSDan Kimmel arc_buf_lsize(arc_buf_t *buf)
16045602294fSDan Kimmel {
16055602294fSDan Kimmel 	return (HDR_GET_LSIZE(buf->b_hdr));
16065602294fSDan Kimmel }
16075602294fSDan Kimmel 
1608*eb633035STom Caputi /*
1609*eb633035STom Caputi  * This function will return B_TRUE if the buffer is encrypted in memory.
1610*eb633035STom Caputi  * This buffer can be decrypted by calling arc_untransform().
1611*eb633035STom Caputi  */
1612*eb633035STom Caputi boolean_t
1613*eb633035STom Caputi arc_is_encrypted(arc_buf_t *buf)
1614*eb633035STom Caputi {
1615*eb633035STom Caputi 	return (ARC_BUF_ENCRYPTED(buf) != 0);
1616*eb633035STom Caputi }
1617*eb633035STom Caputi 
1618*eb633035STom Caputi /*
1619*eb633035STom Caputi  * Returns B_TRUE if the buffer represents data that has not had its MAC
1620*eb633035STom Caputi  * verified yet.
1621*eb633035STom Caputi  */
1622*eb633035STom Caputi boolean_t
1623*eb633035STom Caputi arc_is_unauthenticated(arc_buf_t *buf)
1624*eb633035STom Caputi {
1625*eb633035STom Caputi 	return (HDR_NOAUTH(buf->b_hdr) != 0);
1626*eb633035STom Caputi }
1627*eb633035STom Caputi 
1628*eb633035STom Caputi void
1629*eb633035STom Caputi arc_get_raw_params(arc_buf_t *buf, boolean_t *byteorder, uint8_t *salt,
1630*eb633035STom Caputi     uint8_t *iv, uint8_t *mac)
1631*eb633035STom Caputi {
1632*eb633035STom Caputi 	arc_buf_hdr_t *hdr = buf->b_hdr;
1633*eb633035STom Caputi 
1634*eb633035STom Caputi 	ASSERT(HDR_PROTECTED(hdr));
1635*eb633035STom Caputi 
1636*eb633035STom Caputi 	bcopy(hdr->b_crypt_hdr.b_salt, salt, ZIO_DATA_SALT_LEN);
1637*eb633035STom Caputi 	bcopy(hdr->b_crypt_hdr.b_iv, iv, ZIO_DATA_IV_LEN);
1638*eb633035STom Caputi 	bcopy(hdr->b_crypt_hdr.b_mac, mac, ZIO_DATA_MAC_LEN);
1639*eb633035STom Caputi 	*byteorder = (hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS) ?
1640*eb633035STom Caputi 	    /* CONSTCOND */
1641*eb633035STom Caputi 	    ZFS_HOST_BYTEORDER : !ZFS_HOST_BYTEORDER;
1642*eb633035STom Caputi }
1643*eb633035STom Caputi 
1644*eb633035STom Caputi /*
1645*eb633035STom Caputi  * Indicates how this buffer is compressed in memory. If it is not compressed
1646*eb633035STom Caputi  * the value will be ZIO_COMPRESS_OFF. It can be made normally readable with
1647*eb633035STom Caputi  * arc_untransform() as long as it is also unencrypted.
1648*eb633035STom Caputi  */
16495602294fSDan Kimmel enum zio_compress
16505602294fSDan Kimmel arc_get_compression(arc_buf_t *buf)
16515602294fSDan Kimmel {
16525602294fSDan Kimmel 	return (ARC_BUF_COMPRESSED(buf) ?
16535602294fSDan Kimmel 	    HDR_GET_COMPRESS(buf->b_hdr) : ZIO_COMPRESS_OFF);
16545602294fSDan Kimmel }
16555602294fSDan Kimmel 
1656dcbf3bd6SGeorge Wilson #define	ARC_MINTIME	(hz>>4) /* 62 ms */
1657244781f1SPrakash Surya 
1658*eb633035STom Caputi /*
1659*eb633035STom Caputi  * Return the compression algorithm used to store this data in the ARC. If ARC
1660*eb633035STom Caputi  * compression is enabled or this is an encrypted block, this will be the same
1661*eb633035STom Caputi  * as what's used to store it on-disk. Otherwise, this will be ZIO_COMPRESS_OFF.
1662*eb633035STom Caputi  */
1663*eb633035STom Caputi static inline enum zio_compress
1664*eb633035STom Caputi arc_hdr_get_compress(arc_buf_hdr_t *hdr)
1665*eb633035STom Caputi {
1666*eb633035STom Caputi 	return (HDR_COMPRESSION_ENABLED(hdr) ?
1667*eb633035STom Caputi 	    HDR_GET_COMPRESS(hdr) : ZIO_COMPRESS_OFF);
1668*eb633035STom Caputi }
1669*eb633035STom Caputi 
1670dcbf3bd6SGeorge Wilson static inline boolean_t
1671dcbf3bd6SGeorge Wilson arc_buf_is_shared(arc_buf_t *buf)
1672dcbf3bd6SGeorge Wilson {
1673dcbf3bd6SGeorge Wilson 	boolean_t shared = (buf->b_data != NULL &&
1674770499e1SDan Kimmel 	    buf->b_hdr->b_l1hdr.b_pabd != NULL &&
1675770499e1SDan Kimmel 	    abd_is_linear(buf->b_hdr->b_l1hdr.b_pabd) &&
1676770499e1SDan Kimmel 	    buf->b_data == abd_to_buf(buf->b_hdr->b_l1hdr.b_pabd));
1677dcbf3bd6SGeorge Wilson 	IMPLY(shared, HDR_SHARED_DATA(buf->b_hdr));
16785602294fSDan Kimmel 	IMPLY(shared, ARC_BUF_SHARED(buf));
16795602294fSDan Kimmel 	IMPLY(shared, ARC_BUF_COMPRESSED(buf) || ARC_BUF_LAST(buf));
16805602294fSDan Kimmel 
16815602294fSDan Kimmel 	/*
16825602294fSDan Kimmel 	 * It would be nice to assert arc_can_share() too, but the "hdr isn't
16835602294fSDan Kimmel 	 * already being shared" requirement prevents us from doing that.
16845602294fSDan Kimmel 	 */
16855602294fSDan Kimmel 
1686dcbf3bd6SGeorge Wilson 	return (shared);
1687dcbf3bd6SGeorge Wilson }
1688c546f36aSArne Jansen 
16895602294fSDan Kimmel /*
16905602294fSDan Kimmel  * Free the checksum associated with this header. If there is no checksum, this
16915602294fSDan Kimmel  * is a no-op.
16925602294fSDan Kimmel  */
1693dcbf3bd6SGeorge Wilson static inline void
1694dcbf3bd6SGeorge Wilson arc_cksum_free(arc_buf_hdr_t *hdr)
1695dcbf3bd6SGeorge Wilson {
1696dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
1697*eb633035STom Caputi 
1698dcbf3bd6SGeorge Wilson 	mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1699dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
1700dcbf3bd6SGeorge Wilson 		kmem_free(hdr->b_l1hdr.b_freeze_cksum, sizeof (zio_cksum_t));
1701dcbf3bd6SGeorge Wilson 		hdr->b_l1hdr.b_freeze_cksum = NULL;
170289c86e32SChris Williamson 	}
1703dcbf3bd6SGeorge Wilson 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
170489c86e32SChris Williamson }
170589c86e32SChris Williamson 
17065602294fSDan Kimmel /*
17075602294fSDan Kimmel  * Return true iff at least one of the bufs on hdr is not compressed.
1708*eb633035STom Caputi  * Encrypted buffers count as compressed.
17095602294fSDan Kimmel  */
17105602294fSDan Kimmel static boolean_t
17115602294fSDan Kimmel arc_hdr_has_uncompressed_buf(arc_buf_hdr_t *hdr)
17125602294fSDan Kimmel {
17135602294fSDan Kimmel 	for (arc_buf_t *b = hdr->b_l1hdr.b_buf; b != NULL; b = b->b_next) {
17145602294fSDan Kimmel 		if (!ARC_BUF_COMPRESSED(b)) {
17155602294fSDan Kimmel 			return (B_TRUE);
17165602294fSDan Kimmel 		}
17175602294fSDan Kimmel 	}
17185602294fSDan Kimmel 	return (B_FALSE);
17195602294fSDan Kimmel }
17205602294fSDan Kimmel 
17215602294fSDan Kimmel /*
17225602294fSDan Kimmel  * If we've turned on the ZFS_DEBUG_MODIFY flag, verify that the buf's data
17235602294fSDan Kimmel  * matches the checksum that is stored in the hdr. If there is no checksum,
17245602294fSDan Kimmel  * or if the buf is compressed, this is a no-op.
17255602294fSDan Kimmel  */
17266b4acc8bSahrens static void
17276b4acc8bSahrens arc_cksum_verify(arc_buf_t *buf)
17286b4acc8bSahrens {
1729dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
17306b4acc8bSahrens 	zio_cksum_t zc;
17316b4acc8bSahrens 
1732cc60fd72Sahrens 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
17336b4acc8bSahrens 		return;
17346b4acc8bSahrens 
17355602294fSDan Kimmel 	if (ARC_BUF_COMPRESSED(buf)) {
17365602294fSDan Kimmel 		ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
17375602294fSDan Kimmel 		    arc_hdr_has_uncompressed_buf(hdr));
17385602294fSDan Kimmel 		return;
17395602294fSDan Kimmel 	}
17405602294fSDan Kimmel 
1741dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
1742dcbf3bd6SGeorge Wilson 
1743dcbf3bd6SGeorge Wilson 	mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1744dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_freeze_cksum == NULL || HDR_IO_ERROR(hdr)) {
1745dcbf3bd6SGeorge Wilson 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
17466b4acc8bSahrens 		return;
17476b4acc8bSahrens 	}
17485602294fSDan Kimmel 
17495602294fSDan Kimmel 	fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL, &zc);
1750dcbf3bd6SGeorge Wilson 	if (!ZIO_CHECKSUM_EQUAL(*hdr->b_l1hdr.b_freeze_cksum, zc))
17516b4acc8bSahrens 		panic("buffer modified while frozen!");
1752dcbf3bd6SGeorge Wilson 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
17536b4acc8bSahrens }
17546b4acc8bSahrens 
1755*eb633035STom Caputi /*
1756*eb633035STom Caputi  * This function makes the assumption that data stored in the L2ARC
1757*eb633035STom Caputi  * will be transformed exactly as it is in the main pool. Because of
1758*eb633035STom Caputi  * this we can verify the checksum against the reading process's bp.
1759*eb633035STom Caputi  */
1760dcbf3bd6SGeorge Wilson static boolean_t
1761dcbf3bd6SGeorge Wilson arc_cksum_is_equal(arc_buf_hdr_t *hdr, zio_t *zio)
1762fa94a07fSbrendan {
1763dcbf3bd6SGeorge Wilson 	enum zio_compress compress = BP_GET_COMPRESS(zio->io_bp);
1764dcbf3bd6SGeorge Wilson 	boolean_t valid_cksum;
1765fa94a07fSbrendan 
1766dcbf3bd6SGeorge Wilson 	ASSERT(!BP_IS_EMBEDDED(zio->io_bp));
1767dcbf3bd6SGeorge Wilson 	VERIFY3U(BP_GET_PSIZE(zio->io_bp), ==, HDR_GET_PSIZE(hdr));
1768dcbf3bd6SGeorge Wilson 
1769dcbf3bd6SGeorge Wilson 	/*
1770dcbf3bd6SGeorge Wilson 	 * We rely on the blkptr's checksum to determine if the block
1771dcbf3bd6SGeorge Wilson 	 * is valid or not. When compressed arc is enabled, the l2arc
1772dcbf3bd6SGeorge Wilson 	 * writes the block to the l2arc just as it appears in the pool.
1773dcbf3bd6SGeorge Wilson 	 * This allows us to use the blkptr's checksum to validate the
1774dcbf3bd6SGeorge Wilson 	 * data that we just read off of the l2arc without having to store
1775dcbf3bd6SGeorge Wilson 	 * a separate checksum in the arc_buf_hdr_t. However, if compressed
1776dcbf3bd6SGeorge Wilson 	 * arc is disabled, then the data written to the l2arc is always
1777dcbf3bd6SGeorge Wilson 	 * uncompressed and won't match the block as it exists in the main
1778dcbf3bd6SGeorge Wilson 	 * pool. When this is the case, we must first compress it if it is
1779dcbf3bd6SGeorge Wilson 	 * compressed on the main pool before we can validate the checksum.
1780dcbf3bd6SGeorge Wilson 	 */
1781dcbf3bd6SGeorge Wilson 	if (!HDR_COMPRESSION_ENABLED(hdr) && compress != ZIO_COMPRESS_OFF) {
1782dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
1783dcbf3bd6SGeorge Wilson 		uint64_t lsize = HDR_GET_LSIZE(hdr);
1784dcbf3bd6SGeorge Wilson 		uint64_t csize;
1785dcbf3bd6SGeorge Wilson 
178601a059eeSRoman Strashkin 		abd_t *cdata = abd_alloc_linear(HDR_GET_PSIZE(hdr), B_TRUE);
178701a059eeSRoman Strashkin 		csize = zio_compress_data(compress, zio->io_abd,
178801a059eeSRoman Strashkin 		    abd_to_buf(cdata), lsize);
1789770499e1SDan Kimmel 
1790dcbf3bd6SGeorge Wilson 		ASSERT3U(csize, <=, HDR_GET_PSIZE(hdr));
1791dcbf3bd6SGeorge Wilson 		if (csize < HDR_GET_PSIZE(hdr)) {
1792dcbf3bd6SGeorge Wilson 			/*
1793dcbf3bd6SGeorge Wilson 			 * Compressed blocks are always a multiple of the
1794dcbf3bd6SGeorge Wilson 			 * smallest ashift in the pool. Ideally, we would
1795dcbf3bd6SGeorge Wilson 			 * like to round up the csize to the next
1796dcbf3bd6SGeorge Wilson 			 * spa_min_ashift but that value may have changed
1797dcbf3bd6SGeorge Wilson 			 * since the block was last written. Instead,
1798dcbf3bd6SGeorge Wilson 			 * we rely on the fact that the hdr's psize
1799dcbf3bd6SGeorge Wilson 			 * was set to the psize of the block when it was
1800dcbf3bd6SGeorge Wilson 			 * last written. We set the csize to that value
1801dcbf3bd6SGeorge Wilson 			 * and zero out any part that should not contain
1802dcbf3bd6SGeorge Wilson 			 * data.
1803dcbf3bd6SGeorge Wilson 			 */
180401a059eeSRoman Strashkin 			abd_zero_off(cdata, csize, HDR_GET_PSIZE(hdr) - csize);
1805dcbf3bd6SGeorge Wilson 			csize = HDR_GET_PSIZE(hdr);
1806dcbf3bd6SGeorge Wilson 		}
180701a059eeSRoman Strashkin 		zio_push_transform(zio, cdata, csize, HDR_GET_PSIZE(hdr), NULL);
1808dcbf3bd6SGeorge Wilson 	}
1809fa94a07fSbrendan 
1810dcbf3bd6SGeorge Wilson 	/*
1811dcbf3bd6SGeorge Wilson 	 * Block pointers always store the checksum for the logical data.
1812dcbf3bd6SGeorge Wilson 	 * If the block pointer has the gang bit set, then the checksum
1813dcbf3bd6SGeorge Wilson 	 * it represents is for the reconstituted data and not for an
1814dcbf3bd6SGeorge Wilson 	 * individual gang member. The zio pipeline, however, must be able to
1815dcbf3bd6SGeorge Wilson 	 * determine the checksum of each of the gang constituents so it
1816dcbf3bd6SGeorge Wilson 	 * treats the checksum comparison differently than what we need
1817dcbf3bd6SGeorge Wilson 	 * for l2arc blocks. This prevents us from using the
1818dcbf3bd6SGeorge Wilson 	 * zio_checksum_error() interface directly. Instead we must call the
1819dcbf3bd6SGeorge Wilson 	 * zio_checksum_error_impl() so that we can ensure the checksum is
1820dcbf3bd6SGeorge Wilson 	 * generated using the correct checksum algorithm and accounts for the
1821dcbf3bd6SGeorge Wilson 	 * logical I/O size and not just a gang fragment.
1822dcbf3bd6SGeorge Wilson 	 */
1823dcbf3bd6SGeorge Wilson 	valid_cksum = (zio_checksum_error_impl(zio->io_spa, zio->io_bp,
1824770499e1SDan Kimmel 	    BP_GET_CHECKSUM(zio->io_bp), zio->io_abd, zio->io_size,
1825dcbf3bd6SGeorge Wilson 	    zio->io_offset, NULL) == 0);
1826dcbf3bd6SGeorge Wilson 	zio_pop_transforms(zio);
1827dcbf3bd6SGeorge Wilson 	return (valid_cksum);
1828fa94a07fSbrendan }
1829fa94a07fSbrendan 
18305602294fSDan Kimmel /*
18315602294fSDan Kimmel  * Given a buf full of data, if ZFS_DEBUG_MODIFY is enabled this computes a
18325602294fSDan Kimmel  * checksum and attaches it to the buf's hdr so that we can ensure that the buf
18335602294fSDan Kimmel  * isn't modified later on. If buf is compressed or there is already a checksum
18345602294fSDan Kimmel  * on the hdr, this is a no-op (we only checksum uncompressed bufs).
18355602294fSDan Kimmel  */
18366b4acc8bSahrens static void
1837dcbf3bd6SGeorge Wilson arc_cksum_compute(arc_buf_t *buf)
18386b4acc8bSahrens {
1839dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
1840dcbf3bd6SGeorge Wilson 
1841dcbf3bd6SGeorge Wilson 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
18426b4acc8bSahrens 		return;
18436b4acc8bSahrens 
1844dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
18455602294fSDan Kimmel 
184689c86e32SChris Williamson 	mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1847dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
18485602294fSDan Kimmel 		ASSERT(arc_hdr_has_uncompressed_buf(hdr));
18495602294fSDan Kimmel 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
18505602294fSDan Kimmel 		return;
18515602294fSDan Kimmel 	} else if (ARC_BUF_COMPRESSED(buf)) {
1852dcbf3bd6SGeorge Wilson 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
18536b4acc8bSahrens 		return;
18546b4acc8bSahrens 	}
18555602294fSDan Kimmel 
1856*eb633035STom Caputi 	ASSERT(!ARC_BUF_ENCRYPTED(buf));
18575602294fSDan Kimmel 	ASSERT(!ARC_BUF_COMPRESSED(buf));
1858dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t),
1859dcbf3bd6SGeorge Wilson 	    KM_SLEEP);
18605602294fSDan Kimmel 	fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL,
1861dcbf3bd6SGeorge Wilson 	    hdr->b_l1hdr.b_freeze_cksum);
1862dcbf3bd6SGeorge Wilson 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1863cd1c8b85SMatthew Ahrens 	arc_buf_watch(buf);
1864cd1c8b85SMatthew Ahrens }
1865cd1c8b85SMatthew Ahrens 
1866cd1c8b85SMatthew Ahrens #ifndef _KERNEL
1867cd1c8b85SMatthew Ahrens typedef struct procctl {
1868cd1c8b85SMatthew Ahrens 	long cmd;
1869cd1c8b85SMatthew Ahrens 	prwatch_t prwatch;
1870cd1c8b85SMatthew Ahrens } procctl_t;
1871cd1c8b85SMatthew Ahrens #endif
1872cd1c8b85SMatthew Ahrens 
1873cd1c8b85SMatthew Ahrens /* ARGSUSED */
1874cd1c8b85SMatthew Ahrens static void
1875cd1c8b85SMatthew Ahrens arc_buf_unwatch(arc_buf_t *buf)
1876cd1c8b85SMatthew Ahrens {
1877cd1c8b85SMatthew Ahrens #ifndef _KERNEL
1878cd1c8b85SMatthew Ahrens 	if (arc_watch) {
1879cd1c8b85SMatthew Ahrens 		int result;
1880cd1c8b85SMatthew Ahrens 		procctl_t ctl;
1881cd1c8b85SMatthew Ahrens 		ctl.cmd = PCWATCH;
1882cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1883cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_size = 0;
1884cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_wflags = 0;
1885cd1c8b85SMatthew Ahrens 		result = write(arc_procfd, &ctl, sizeof (ctl));
1886cd1c8b85SMatthew Ahrens 		ASSERT3U(result, ==, sizeof (ctl));
1887cd1c8b85SMatthew Ahrens 	}
1888cd1c8b85SMatthew Ahrens #endif
1889cd1c8b85SMatthew Ahrens }
1890cd1c8b85SMatthew Ahrens 
1891cd1c8b85SMatthew Ahrens /* ARGSUSED */
1892cd1c8b85SMatthew Ahrens static void
1893cd1c8b85SMatthew Ahrens arc_buf_watch(arc_buf_t *buf)
1894cd1c8b85SMatthew Ahrens {
1895cd1c8b85SMatthew Ahrens #ifndef _KERNEL
1896cd1c8b85SMatthew Ahrens 	if (arc_watch) {
1897cd1c8b85SMatthew Ahrens 		int result;
1898cd1c8b85SMatthew Ahrens 		procctl_t ctl;
1899cd1c8b85SMatthew Ahrens 		ctl.cmd = PCWATCH;
1900cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
19015602294fSDan Kimmel 		ctl.prwatch.pr_size = arc_buf_size(buf);
1902cd1c8b85SMatthew Ahrens 		ctl.prwatch.pr_wflags = WA_WRITE;
1903cd1c8b85SMatthew Ahrens 		result = write(arc_procfd, &ctl, sizeof (ctl));
1904cd1c8b85SMatthew Ahrens 		ASSERT3U(result, ==, sizeof (ctl));
1905cd1c8b85SMatthew Ahrens 	}
1906cd1c8b85SMatthew Ahrens #endif
19076b4acc8bSahrens }
19086b4acc8bSahrens 
190989c86e32SChris Williamson static arc_buf_contents_t
191089c86e32SChris Williamson arc_buf_type(arc_buf_hdr_t *hdr)
191189c86e32SChris Williamson {
1912dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type;
191389c86e32SChris Williamson 	if (HDR_ISTYPE_METADATA(hdr)) {
1914dcbf3bd6SGeorge Wilson 		type = ARC_BUFC_METADATA;
191589c86e32SChris Williamson 	} else {
1916dcbf3bd6SGeorge Wilson 		type = ARC_BUFC_DATA;
191789c86e32SChris Williamson 	}
1918dcbf3bd6SGeorge Wilson 	VERIFY3U(hdr->b_type, ==, type);
1919dcbf3bd6SGeorge Wilson 	return (type);
192089c86e32SChris Williamson }
192189c86e32SChris Williamson 
19225602294fSDan Kimmel boolean_t
19235602294fSDan Kimmel arc_is_metadata(arc_buf_t *buf)
19245602294fSDan Kimmel {
19255602294fSDan Kimmel 	return (HDR_ISTYPE_METADATA(buf->b_hdr) != 0);
19265602294fSDan Kimmel }
19275602294fSDan Kimmel 
192889c86e32SChris Williamson static uint32_t
192989c86e32SChris Williamson arc_bufc_to_flags(arc_buf_contents_t type)
193089c86e32SChris Williamson {
193189c86e32SChris Williamson 	switch (type) {
193289c86e32SChris Williamson 	case ARC_BUFC_DATA:
193389c86e32SChris Williamson 		/* metadata field is 0 if buffer contains normal data */
193489c86e32SChris Williamson 		return (0);
193589c86e32SChris Williamson 	case ARC_BUFC_METADATA:
193689c86e32SChris Williamson 		return (ARC_FLAG_BUFC_METADATA);
193789c86e32SChris Williamson 	default:
193889c86e32SChris Williamson 		break;
193989c86e32SChris Williamson 	}
194089c86e32SChris Williamson 	panic("undefined ARC buffer type!");
194189c86e32SChris Williamson 	return ((uint32_t)-1);
194289c86e32SChris Williamson }
194389c86e32SChris Williamson 
19446b4acc8bSahrens void
19456b4acc8bSahrens arc_buf_thaw(arc_buf_t *buf)
19466b4acc8bSahrens {
1947dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
1948dcbf3bd6SGeorge Wilson 
19495602294fSDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
19505602294fSDan Kimmel 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
19515602294fSDan Kimmel 
19525602294fSDan Kimmel 	arc_cksum_verify(buf);
19535602294fSDan Kimmel 
19545602294fSDan Kimmel 	/*
19555602294fSDan Kimmel 	 * Compressed buffers do not manipulate the b_freeze_cksum or
19565602294fSDan Kimmel 	 * allocate b_thawed.
19575602294fSDan Kimmel 	 */
19585602294fSDan Kimmel 	if (ARC_BUF_COMPRESSED(buf)) {
19595602294fSDan Kimmel 		ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
19605602294fSDan Kimmel 		    arc_hdr_has_uncompressed_buf(hdr));
19615602294fSDan Kimmel 		return;
1962fa94a07fSbrendan 	}
19636b4acc8bSahrens 
1964dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
1965dcbf3bd6SGeorge Wilson 	arc_cksum_free(hdr);
19663f9d6ad7SLin Ling 
1967dcbf3bd6SGeorge Wilson 	mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
196889c86e32SChris Williamson #ifdef ZFS_DEBUG
19693f9d6ad7SLin Ling 	if (zfs_flags & ZFS_DEBUG_MODIFY) {
1970dcbf3bd6SGeorge Wilson 		if (hdr->b_l1hdr.b_thawed != NULL)
1971dcbf3bd6SGeorge Wilson 			kmem_free(hdr->b_l1hdr.b_thawed, 1);
1972dcbf3bd6SGeorge Wilson 		hdr->b_l1hdr.b_thawed = kmem_alloc(1, KM_SLEEP);
19733f9d6ad7SLin Ling 	}
197489c86e32SChris Williamson #endif
19753f9d6ad7SLin Ling 
1976dcbf3bd6SGeorge Wilson 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1977cd1c8b85SMatthew Ahrens 
1978cd1c8b85SMatthew Ahrens 	arc_buf_unwatch(buf);
19796b4acc8bSahrens }
19806b4acc8bSahrens 
19816b4acc8bSahrens void
19826b4acc8bSahrens arc_buf_freeze(arc_buf_t *buf)
19836b4acc8bSahrens {
1984dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
19853f9d6ad7SLin Ling 	kmutex_t *hash_lock;
19863f9d6ad7SLin Ling 
1987cc60fd72Sahrens 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1988cc60fd72Sahrens 		return;
1989cc60fd72Sahrens 
19905602294fSDan Kimmel 	if (ARC_BUF_COMPRESSED(buf)) {
19915602294fSDan Kimmel 		ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
19925602294fSDan Kimmel 		    arc_hdr_has_uncompressed_buf(hdr));
19935602294fSDan Kimmel 		return;
19945602294fSDan Kimmel 	}
19955602294fSDan Kimmel 
1996dcbf3bd6SGeorge Wilson 	hash_lock = HDR_LOCK(hdr);
19973f9d6ad7SLin Ling 	mutex_enter(hash_lock);
19983f9d6ad7SLin Ling 
1999dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2000dcbf3bd6SGeorge Wilson 	ASSERT(hdr->b_l1hdr.b_freeze_cksum != NULL ||
2001dcbf3bd6SGeorge Wilson 	    hdr->b_l1hdr.b_state == arc_anon);
2002dcbf3bd6SGeorge Wilson 	arc_cksum_compute(buf);
20033f9d6ad7SLin Ling 	mutex_exit(hash_lock);
20046b4acc8bSahrens }
20056b4acc8bSahrens 
2006dcbf3bd6SGeorge Wilson /*
2007dcbf3bd6SGeorge Wilson  * The arc_buf_hdr_t's b_flags should never be modified directly. Instead,
2008dcbf3bd6SGeorge Wilson  * the following functions should be used to ensure that the flags are
2009dcbf3bd6SGeorge Wilson  * updated in a thread-safe way. When manipulating the flags either
2010dcbf3bd6SGeorge Wilson  * the hash_lock must be held or the hdr must be undiscoverable. This
2011dcbf3bd6SGeorge Wilson  * ensures that we're not racing with any other threads when updating
2012dcbf3bd6SGeorge Wilson  * the flags.
2013dcbf3bd6SGeorge Wilson  */
2014dcbf3bd6SGeorge Wilson static inline void
2015dcbf3bd6SGeorge Wilson arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
2016dcbf3bd6SGeorge Wilson {
2017dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2018dcbf3bd6SGeorge Wilson 	hdr->b_flags |= flags;
2019dcbf3bd6SGeorge Wilson }
2020dcbf3bd6SGeorge Wilson 
2021dcbf3bd6SGeorge Wilson static inline void
2022dcbf3bd6SGeorge Wilson arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
2023dcbf3bd6SGeorge Wilson {
2024dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2025dcbf3bd6SGeorge Wilson 	hdr->b_flags &= ~flags;
2026dcbf3bd6SGeorge Wilson }
2027dcbf3bd6SGeorge Wilson 
2028dcbf3bd6SGeorge Wilson /*
2029dcbf3bd6SGeorge Wilson  * Setting the compression bits in the arc_buf_hdr_t's b_flags is
2030dcbf3bd6SGeorge Wilson  * done in a special way since we have to clear and set bits
2031dcbf3bd6SGeorge Wilson  * at the same time. Consumers that wish to set the compression bits
2032dcbf3bd6SGeorge Wilson  * must use this function to ensure that the flags are updated in
2033dcbf3bd6SGeorge Wilson  * thread-safe manner.
2034dcbf3bd6SGeorge Wilson  */
2035fa9e4066Sahrens static void
2036dcbf3bd6SGeorge Wilson arc_hdr_set_compress(arc_buf_hdr_t *hdr, enum zio_compress cmp)
2037fa9e4066Sahrens {
2038dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2039fa9e4066Sahrens 
2040dcbf3bd6SGeorge Wilson 	/*
2041dcbf3bd6SGeorge Wilson 	 * Holes and embedded blocks will always have a psize = 0 so
2042dcbf3bd6SGeorge Wilson 	 * we ignore the compression of the blkptr and set the
2043dcbf3bd6SGeorge Wilson 	 * arc_buf_hdr_t's compression to ZIO_COMPRESS_OFF.
2044dcbf3bd6SGeorge Wilson 	 * Holes and embedded blocks remain anonymous so we don't
2045dcbf3bd6SGeorge Wilson 	 * want to uncompress them. Mark them as uncompressed.
2046dcbf3bd6SGeorge Wilson 	 */
2047dcbf3bd6SGeorge Wilson 	if (!zfs_compressed_arc_enabled || HDR_GET_PSIZE(hdr) == 0) {
2048dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
2049dcbf3bd6SGeorge Wilson 		ASSERT(!HDR_COMPRESSION_ENABLED(hdr));
2050dcbf3bd6SGeorge Wilson 	} else {
2051dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
2052dcbf3bd6SGeorge Wilson 		ASSERT(HDR_COMPRESSION_ENABLED(hdr));
2053dcbf3bd6SGeorge Wilson 	}
2054*eb633035STom Caputi 
2055*eb633035STom Caputi 	HDR_SET_COMPRESS(hdr, cmp);
2056*eb633035STom Caputi 	ASSERT3U(HDR_GET_COMPRESS(hdr), ==, cmp);
2057dcbf3bd6SGeorge Wilson }
2058244781f1SPrakash Surya 
20595602294fSDan Kimmel /*
20605602294fSDan Kimmel  * Looks for another buf on the same hdr which has the data decompressed, copies
20615602294fSDan Kimmel  * from it, and returns true. If no such buf exists, returns false.
20625602294fSDan Kimmel  */
20635602294fSDan Kimmel static boolean_t
20645602294fSDan Kimmel arc_buf_try_copy_decompressed_data(arc_buf_t *buf)
20655602294fSDan Kimmel {
20665602294fSDan Kimmel 	arc_buf_hdr_t *hdr = buf->b_hdr;
20675602294fSDan Kimmel 	boolean_t copied = B_FALSE;
20685602294fSDan Kimmel 
20695602294fSDan Kimmel 	ASSERT(HDR_HAS_L1HDR(hdr));
20705602294fSDan Kimmel 	ASSERT3P(buf->b_data, !=, NULL);
20715602294fSDan Kimmel 	ASSERT(!ARC_BUF_COMPRESSED(buf));
20725602294fSDan Kimmel 
20735602294fSDan Kimmel 	for (arc_buf_t *from = hdr->b_l1hdr.b_buf; from != NULL;
20745602294fSDan Kimmel 	    from = from->b_next) {
20755602294fSDan Kimmel 		/* can't use our own data buffer */
20765602294fSDan Kimmel 		if (from == buf) {
20775602294fSDan Kimmel 			continue;
20785602294fSDan Kimmel 		}
20795602294fSDan Kimmel 
20805602294fSDan Kimmel 		if (!ARC_BUF_COMPRESSED(from)) {
20815602294fSDan Kimmel 			bcopy(from->b_data, buf->b_data, arc_buf_size(buf));
20825602294fSDan Kimmel 			copied = B_TRUE;
20835602294fSDan Kimmel 			break;
20845602294fSDan Kimmel 		}
20855602294fSDan Kimmel 	}
20865602294fSDan Kimmel 
20875602294fSDan Kimmel 	/*
2088*eb633035STom Caputi 	 * Note: With encryption support, the following assertion is no longer
2089*eb633035STom Caputi 	 * necessarily valid. If we receive two back to back raw snapshots
2090*eb633035STom Caputi 	 * (send -w), the second receive can use a hdr with a cksum already
2091*eb633035STom Caputi 	 * calculated. This happens via:
2092*eb633035STom Caputi 	 *    dmu_recv_stream() -> receive_read_record() -> arc_loan_raw_buf()
2093*eb633035STom Caputi 	 * The rsend/send_mixed_raw test case exercises this code path.
2094*eb633035STom Caputi 	 *
20955602294fSDan Kimmel 	 * There were no decompressed bufs, so there should not be a
20965602294fSDan Kimmel 	 * checksum on the hdr either.
2097*eb633035STom Caputi 	 * EQUIV(!copied, hdr->b_l1hdr.b_freeze_cksum == NULL);
20985602294fSDan Kimmel 	 */
20995602294fSDan Kimmel 
21005602294fSDan Kimmel 	return (copied);
21015602294fSDan Kimmel }
21025602294fSDan Kimmel 
2103*eb633035STom Caputi /*
2104*eb633035STom Caputi  * Return the size of the block, b_pabd, that is stored in the arc_buf_hdr_t.
2105*eb633035STom Caputi  */
2106*eb633035STom Caputi static uint64_t
2107*eb633035STom Caputi arc_hdr_size(arc_buf_hdr_t *hdr)
2108*eb633035STom Caputi {
2109*eb633035STom Caputi 	uint64_t size;
2110*eb633035STom Caputi 
2111*eb633035STom Caputi 	if (arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF &&
2112*eb633035STom Caputi 	    HDR_GET_PSIZE(hdr) > 0) {
2113*eb633035STom Caputi 		size = HDR_GET_PSIZE(hdr);
2114*eb633035STom Caputi 	} else {
2115*eb633035STom Caputi 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, 0);
2116*eb633035STom Caputi 		size = HDR_GET_LSIZE(hdr);
2117*eb633035STom Caputi 	}
2118*eb633035STom Caputi 	return (size);
2119*eb633035STom Caputi }
2120*eb633035STom Caputi 
2121*eb633035STom Caputi static int
2122*eb633035STom Caputi arc_hdr_authenticate(arc_buf_hdr_t *hdr, spa_t *spa, uint64_t dsobj)
2123*eb633035STom Caputi {
2124*eb633035STom Caputi 	int ret;
2125*eb633035STom Caputi 	uint64_t csize;
2126*eb633035STom Caputi 	uint64_t lsize = HDR_GET_LSIZE(hdr);
2127*eb633035STom Caputi 	uint64_t psize = HDR_GET_PSIZE(hdr);
2128*eb633035STom Caputi 	void *tmpbuf = NULL;
2129*eb633035STom Caputi 	abd_t *abd = hdr->b_l1hdr.b_pabd;
2130*eb633035STom Caputi 
2131*eb633035STom Caputi 	ASSERT(HDR_LOCK(hdr) == NULL || MUTEX_HELD(HDR_LOCK(hdr)));
2132*eb633035STom Caputi 	ASSERT(HDR_AUTHENTICATED(hdr));
2133*eb633035STom Caputi 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2134*eb633035STom Caputi 
2135*eb633035STom Caputi 	/*
2136*eb633035STom Caputi 	 * The MAC is calculated on the compressed data that is stored on disk.
2137*eb633035STom Caputi 	 * However, if compressed arc is disabled we will only have the
2138*eb633035STom Caputi 	 * decompressed data available to us now. Compress it into a temporary
2139*eb633035STom Caputi 	 * abd so we can verify the MAC. The performance overhead of this will
2140*eb633035STom Caputi 	 * be relatively low, since most objects in an encrypted objset will
2141*eb633035STom Caputi 	 * be encrypted (instead of authenticated) anyway.
2142*eb633035STom Caputi 	 */
2143*eb633035STom Caputi 	if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
2144*eb633035STom Caputi 	    !HDR_COMPRESSION_ENABLED(hdr)) {
2145*eb633035STom Caputi 		tmpbuf = zio_buf_alloc(lsize);
2146*eb633035STom Caputi 		abd = abd_get_from_buf(tmpbuf, lsize);
2147*eb633035STom Caputi 		abd_take_ownership_of_buf(abd, B_TRUE);
2148*eb633035STom Caputi 
2149*eb633035STom Caputi 		csize = zio_compress_data(HDR_GET_COMPRESS(hdr),
2150*eb633035STom Caputi 		    hdr->b_l1hdr.b_pabd, tmpbuf, lsize);
2151*eb633035STom Caputi 		ASSERT3U(csize, <=, psize);
2152*eb633035STom Caputi 		abd_zero_off(abd, csize, psize - csize);
2153*eb633035STom Caputi 	}
2154*eb633035STom Caputi 
2155*eb633035STom Caputi 	/*
2156*eb633035STom Caputi 	 * Authentication is best effort. We authenticate whenever the key is
2157*eb633035STom Caputi 	 * available. If we succeed we clear ARC_FLAG_NOAUTH.
2158*eb633035STom Caputi 	 */
2159*eb633035STom Caputi 	if (hdr->b_crypt_hdr.b_ot == DMU_OT_OBJSET) {
2160*eb633035STom Caputi 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
2161*eb633035STom Caputi 		ASSERT3U(lsize, ==, psize);
2162*eb633035STom Caputi 		ret = spa_do_crypt_objset_mac_abd(B_FALSE, spa, dsobj, abd,
2163*eb633035STom Caputi 		    psize, hdr->b_l1hdr.b_byteswap != DMU_BSWAP_NUMFUNCS);
2164*eb633035STom Caputi 	} else {
2165*eb633035STom Caputi 		ret = spa_do_crypt_mac_abd(B_FALSE, spa, dsobj, abd, psize,
2166*eb633035STom Caputi 		    hdr->b_crypt_hdr.b_mac);
2167*eb633035STom Caputi 	}
2168*eb633035STom Caputi 
2169*eb633035STom Caputi 	if (ret == 0)
2170*eb633035STom Caputi 		arc_hdr_clear_flags(hdr, ARC_FLAG_NOAUTH);
2171*eb633035STom Caputi 	else if (ret != ENOENT)
2172*eb633035STom Caputi 		goto error;
2173*eb633035STom Caputi 
2174*eb633035STom Caputi 	if (tmpbuf != NULL)
2175*eb633035STom Caputi 		abd_free(abd);
2176*eb633035STom Caputi 
2177*eb633035STom Caputi 	return (0);
2178*eb633035STom Caputi 
2179*eb633035STom Caputi error:
2180*eb633035STom Caputi 	if (tmpbuf != NULL)
2181*eb633035STom Caputi 		abd_free(abd);
2182*eb633035STom Caputi 
2183*eb633035STom Caputi 	return (ret);
2184*eb633035STom Caputi }
2185*eb633035STom Caputi 
2186*eb633035STom Caputi /*
2187*eb633035STom Caputi  * This function will take a header that only has raw encrypted data in
2188*eb633035STom Caputi  * b_crypt_hdr.b_rabd and decrypt it into a new buffer which is stored in
2189*eb633035STom Caputi  * b_l1hdr.b_pabd. If designated in the header flags, this function will
2190*eb633035STom Caputi  * also decompress the data.
2191*eb633035STom Caputi  */
2192*eb633035STom Caputi static int
2193*eb633035STom Caputi arc_hdr_decrypt(arc_buf_hdr_t *hdr, spa_t *spa, const zbookmark_phys_t *zb)
2194*eb633035STom Caputi {
2195*eb633035STom Caputi 	int ret;
2196*eb633035STom Caputi 	abd_t *cabd = NULL;
2197*eb633035STom Caputi 	void *tmp = NULL;
2198*eb633035STom Caputi 	boolean_t no_crypt = B_FALSE;
2199*eb633035STom Caputi 	boolean_t bswap = (hdr->b_l1hdr.b_byteswap != DMU_BSWAP_NUMFUNCS);
2200*eb633035STom Caputi 
2201*eb633035STom Caputi 	ASSERT(HDR_LOCK(hdr) == NULL || MUTEX_HELD(HDR_LOCK(hdr)));
2202*eb633035STom Caputi 	ASSERT(HDR_ENCRYPTED(hdr));
2203*eb633035STom Caputi 
2204*eb633035STom Caputi 	arc_hdr_alloc_pabd(hdr, B_FALSE);
2205*eb633035STom Caputi 
2206*eb633035STom Caputi 	ret = spa_do_crypt_abd(B_FALSE, spa, zb, hdr->b_crypt_hdr.b_ot,
2207*eb633035STom Caputi 	    B_FALSE, bswap, hdr->b_crypt_hdr.b_salt, hdr->b_crypt_hdr.b_iv,
2208*eb633035STom Caputi 	    hdr->b_crypt_hdr.b_mac, HDR_GET_PSIZE(hdr), hdr->b_l1hdr.b_pabd,
2209*eb633035STom Caputi 	    hdr->b_crypt_hdr.b_rabd, &no_crypt);
2210*eb633035STom Caputi 	if (ret != 0)
2211*eb633035STom Caputi 		goto error;
2212*eb633035STom Caputi 
2213*eb633035STom Caputi 	if (no_crypt) {
2214*eb633035STom Caputi 		abd_copy(hdr->b_l1hdr.b_pabd, hdr->b_crypt_hdr.b_rabd,
2215*eb633035STom Caputi 		    HDR_GET_PSIZE(hdr));
2216*eb633035STom Caputi 	}
2217*eb633035STom Caputi 
2218*eb633035STom Caputi 	/*
2219*eb633035STom Caputi 	 * If this header has disabled arc compression but the b_pabd is
2220*eb633035STom Caputi 	 * compressed after decrypting it, we need to decompress the newly
2221*eb633035STom Caputi 	 * decrypted data.
2222*eb633035STom Caputi 	 */
2223*eb633035STom Caputi 	if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
2224*eb633035STom Caputi 	    !HDR_COMPRESSION_ENABLED(hdr)) {
2225*eb633035STom Caputi 		/*
2226*eb633035STom Caputi 		 * We want to make sure that we are correctly honoring the
2227*eb633035STom Caputi 		 * zfs_abd_scatter_enabled setting, so we allocate an abd here
2228*eb633035STom Caputi 		 * and then loan a buffer from it, rather than allocating a
2229*eb633035STom Caputi 		 * linear buffer and wrapping it in an abd later.
2230*eb633035STom Caputi 		 */
2231*eb633035STom Caputi 		cabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr);
2232*eb633035STom Caputi 		tmp = abd_borrow_buf(cabd, arc_hdr_size(hdr));
2233*eb633035STom Caputi 
2234*eb633035STom Caputi 		ret = zio_decompress_data(HDR_GET_COMPRESS(hdr),
2235*eb633035STom Caputi 		    hdr->b_l1hdr.b_pabd, tmp, HDR_GET_PSIZE(hdr),
2236*eb633035STom Caputi 		    HDR_GET_LSIZE(hdr));
2237*eb633035STom Caputi 		if (ret != 0) {
2238*eb633035STom Caputi 			abd_return_buf(cabd, tmp, arc_hdr_size(hdr));
2239*eb633035STom Caputi 			goto error;
2240*eb633035STom Caputi 		}
2241*eb633035STom Caputi 
2242*eb633035STom Caputi 		abd_return_buf_copy(cabd, tmp, arc_hdr_size(hdr));
2243*eb633035STom Caputi 		arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
2244*eb633035STom Caputi 		    arc_hdr_size(hdr), hdr);
2245*eb633035STom Caputi 		hdr->b_l1hdr.b_pabd = cabd;
2246*eb633035STom Caputi 	}
2247*eb633035STom Caputi 
2248*eb633035STom Caputi 	return (0);
2249*eb633035STom Caputi 
2250*eb633035STom Caputi error:
2251*eb633035STom Caputi 	arc_hdr_free_pabd(hdr, B_FALSE);
2252*eb633035STom Caputi 	if (cabd != NULL)
2253*eb633035STom Caputi 		arc_free_data_buf(hdr, cabd, arc_hdr_size(hdr), hdr);
2254*eb633035STom Caputi 
2255*eb633035STom Caputi 	return (ret);
2256*eb633035STom Caputi }
2257*eb633035STom Caputi 
2258*eb633035STom Caputi /*
2259*eb633035STom Caputi  * This function is called during arc_buf_fill() to prepare the header's
2260*eb633035STom Caputi  * abd plaintext pointer for use. This involves authenticated protected
2261*eb633035STom Caputi  * data and decrypting encrypted data into the plaintext abd.
2262*eb633035STom Caputi  */
2263*eb633035STom Caputi static int
2264*eb633035STom Caputi arc_fill_hdr_crypt(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, spa_t *spa,
2265*eb633035STom Caputi     const zbookmark_phys_t *zb, boolean_t noauth)
2266*eb633035STom Caputi {
2267*eb633035STom Caputi 	int ret;
2268*eb633035STom Caputi 
2269*eb633035STom Caputi 	ASSERT(HDR_PROTECTED(hdr));
2270*eb633035STom Caputi 
2271*eb633035STom Caputi 	if (hash_lock != NULL)
2272*eb633035STom Caputi 		mutex_enter(hash_lock);
2273*eb633035STom Caputi 
2274*eb633035STom Caputi 	if (HDR_NOAUTH(hdr) && !noauth) {
2275*eb633035STom Caputi 		/*
2276*eb633035STom Caputi 		 * The caller requested authenticated data but our data has
2277*eb633035STom Caputi 		 * not been authenticated yet. Verify the MAC now if we can.
2278*eb633035STom Caputi 		 */
2279*eb633035STom Caputi 		ret = arc_hdr_authenticate(hdr, spa, zb->zb_objset);
2280*eb633035STom Caputi 		if (ret != 0)
2281*eb633035STom Caputi 			goto error;
2282*eb633035STom Caputi 	} else if (HDR_HAS_RABD(hdr) && hdr->b_l1hdr.b_pabd == NULL) {
2283*eb633035STom Caputi 		/*
2284*eb633035STom Caputi 		 * If we only have the encrypted version of the data, but the
2285*eb633035STom Caputi 		 * unencrypted version was requested we take this opportunity
2286*eb633035STom Caputi 		 * to store the decrypted version in the header for future use.
2287*eb633035STom Caputi 		 */
2288*eb633035STom Caputi 		ret = arc_hdr_decrypt(hdr, spa, zb);
2289*eb633035STom Caputi 		if (ret != 0)
2290*eb633035STom Caputi 			goto error;
2291*eb633035STom Caputi 	}
2292*eb633035STom Caputi 
2293*eb633035STom Caputi 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2294*eb633035STom Caputi 
2295*eb633035STom Caputi 	if (hash_lock != NULL)
2296*eb633035STom Caputi 		mutex_exit(hash_lock);
2297*eb633035STom Caputi 
2298*eb633035STom Caputi 	return (0);
2299*eb633035STom Caputi 
2300*eb633035STom Caputi error:
2301*eb633035STom Caputi 	if (hash_lock != NULL)
2302*eb633035STom Caputi 		mutex_exit(hash_lock);
2303*eb633035STom Caputi 
2304*eb633035STom Caputi 	return (ret);
2305*eb633035STom Caputi }
2306*eb633035STom Caputi 
2307*eb633035STom Caputi /*
2308*eb633035STom Caputi  * This function is used by the dbuf code to decrypt bonus buffers in place.
2309*eb633035STom Caputi  * The dbuf code itself doesn't have any locking for decrypting a shared dnode
2310*eb633035STom Caputi  * block, so we use the hash lock here to protect against concurrent calls to
2311*eb633035STom Caputi  * arc_buf_fill().
2312*eb633035STom Caputi  */
2313*eb633035STom Caputi /* ARGSUSED */
2314*eb633035STom Caputi static void
2315*eb633035STom Caputi arc_buf_untransform_in_place(arc_buf_t *buf, kmutex_t *hash_lock)
2316*eb633035STom Caputi {
2317*eb633035STom Caputi 	arc_buf_hdr_t *hdr = buf->b_hdr;
2318*eb633035STom Caputi 
2319*eb633035STom Caputi 	ASSERT(HDR_ENCRYPTED(hdr));
2320*eb633035STom Caputi 	ASSERT3U(hdr->b_crypt_hdr.b_ot, ==, DMU_OT_DNODE);
2321*eb633035STom Caputi 	ASSERT(HDR_LOCK(hdr) == NULL || MUTEX_HELD(HDR_LOCK(hdr)));
2322*eb633035STom Caputi 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2323*eb633035STom Caputi 
2324*eb633035STom Caputi 	zio_crypt_copy_dnode_bonus(hdr->b_l1hdr.b_pabd, buf->b_data,
2325*eb633035STom Caputi 	    arc_buf_size(buf));
2326*eb633035STom Caputi 	buf->b_flags &= ~ARC_BUF_FLAG_ENCRYPTED;
2327*eb633035STom Caputi 	buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
2328*eb633035STom Caputi 	hdr->b_crypt_hdr.b_ebufcnt -= 1;
2329*eb633035STom Caputi }
2330*eb633035STom Caputi 
23315602294fSDan Kimmel /*
23325602294fSDan Kimmel  * Given a buf that has a data buffer attached to it, this function will
23335602294fSDan Kimmel  * efficiently fill the buf with data of the specified compression setting from
23345602294fSDan Kimmel  * the hdr and update the hdr's b_freeze_cksum if necessary. If the buf and hdr
23355602294fSDan Kimmel  * are already sharing a data buf, no copy is performed.
23365602294fSDan Kimmel  *
23375602294fSDan Kimmel  * If the buf is marked as compressed but uncompressed data was requested, this
23385602294fSDan Kimmel  * will allocate a new data buffer for the buf, remove that flag, and fill the
23395602294fSDan Kimmel  * buf with uncompressed data. You can't request a compressed buf on a hdr with
23405602294fSDan Kimmel  * uncompressed data, and (since we haven't added support for it yet) if you
23415602294fSDan Kimmel  * want compressed data your buf must already be marked as compressed and have
23425602294fSDan Kimmel  * the correct-sized data buffer.
23435602294fSDan Kimmel  */
2344dcbf3bd6SGeorge Wilson static int
2345*eb633035STom Caputi arc_buf_fill(arc_buf_t *buf, spa_t *spa, const zbookmark_phys_t *zb,
2346*eb633035STom Caputi     arc_fill_flags_t flags)
2347dcbf3bd6SGeorge Wilson {
2348*eb633035STom Caputi 	int error = 0;
2349dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
2350*eb633035STom Caputi 	boolean_t hdr_compressed =
2351*eb633035STom Caputi 	    (arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF);
2352*eb633035STom Caputi 	boolean_t compressed = (flags & ARC_FILL_COMPRESSED) != 0;
2353*eb633035STom Caputi 	boolean_t encrypted = (flags & ARC_FILL_ENCRYPTED) != 0;
2354dcbf3bd6SGeorge Wilson 	dmu_object_byteswap_t bswap = hdr->b_l1hdr.b_byteswap;
2355*eb633035STom Caputi 	kmutex_t *hash_lock = (flags & ARC_FILL_LOCKED) ? NULL : HDR_LOCK(hdr);
235689c86e32SChris Williamson 
23575602294fSDan Kimmel 	ASSERT3P(buf->b_data, !=, NULL);
2358*eb633035STom Caputi 	IMPLY(compressed, hdr_compressed || ARC_BUF_ENCRYPTED(buf));
23595602294fSDan Kimmel 	IMPLY(compressed, ARC_BUF_COMPRESSED(buf));
2360*eb633035STom Caputi 	IMPLY(encrypted, HDR_ENCRYPTED(hdr));
2361*eb633035STom Caputi 	IMPLY(encrypted, ARC_BUF_ENCRYPTED(buf));
2362*eb633035STom Caputi 	IMPLY(encrypted, ARC_BUF_COMPRESSED(buf));
2363*eb633035STom Caputi 	IMPLY(encrypted, !ARC_BUF_SHARED(buf));
2364*eb633035STom Caputi 
2365*eb633035STom Caputi 	/*
2366*eb633035STom Caputi 	 * If the caller wanted encrypted data we just need to copy it from
2367*eb633035STom Caputi 	 * b_rabd and potentially byteswap it. We won't be able to do any
2368*eb633035STom Caputi 	 * further transforms on it.
2369*eb633035STom Caputi 	 */
2370*eb633035STom Caputi 	if (encrypted) {
2371*eb633035STom Caputi 		ASSERT(HDR_HAS_RABD(hdr));
2372*eb633035STom Caputi 		abd_copy_to_buf(buf->b_data, hdr->b_crypt_hdr.b_rabd,
2373*eb633035STom Caputi 		    HDR_GET_PSIZE(hdr));
2374*eb633035STom Caputi 		goto byteswap;
2375*eb633035STom Caputi 	}
2376*eb633035STom Caputi 
2377*eb633035STom Caputi 	/*
2378*eb633035STom Caputi 	 * Adjust encrypted and authenticated headers to accomodate
2379*eb633035STom Caputi 	 * the request if needed. Dnode blocks (ARC_FILL_IN_PLACE) are
2380*eb633035STom Caputi 	 * allowed to fail decryption due to keys not being loaded
2381*eb633035STom Caputi 	 * without being marked as an IO error.
2382*eb633035STom Caputi 	 */
2383*eb633035STom Caputi 	if (HDR_PROTECTED(hdr)) {
2384*eb633035STom Caputi 		error = arc_fill_hdr_crypt(hdr, hash_lock, spa,
2385*eb633035STom Caputi 		    zb, !!(flags & ARC_FILL_NOAUTH));
2386*eb633035STom Caputi 		if (error == EACCES && (flags & ARC_FILL_IN_PLACE) != 0) {
2387*eb633035STom Caputi 			return (error);
2388*eb633035STom Caputi 		} else if (error != 0) {
2389*eb633035STom Caputi 			if (hash_lock != NULL)
2390*eb633035STom Caputi 				mutex_enter(hash_lock);
2391*eb633035STom Caputi 			arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
2392*eb633035STom Caputi 			if (hash_lock != NULL)
2393*eb633035STom Caputi 				mutex_exit(hash_lock);
2394*eb633035STom Caputi 			return (error);
2395*eb633035STom Caputi 		}
2396*eb633035STom Caputi 	}
2397*eb633035STom Caputi 
2398*eb633035STom Caputi 	/*
2399*eb633035STom Caputi 	 * There is a special case here for dnode blocks which are
2400*eb633035STom Caputi 	 * decrypting their bonus buffers. These blocks may request to
2401*eb633035STom Caputi 	 * be decrypted in-place. This is necessary because there may
2402*eb633035STom Caputi 	 * be many dnodes pointing into this buffer and there is
2403*eb633035STom Caputi 	 * currently no method to synchronize replacing the backing
2404*eb633035STom Caputi 	 * b_data buffer and updating all of the pointers. Here we use
2405*eb633035STom Caputi 	 * the hash lock to ensure there are no races. If the need
2406*eb633035STom Caputi 	 * arises for other types to be decrypted in-place, they must
2407*eb633035STom Caputi 	 * add handling here as well.
2408*eb633035STom Caputi 	 */
2409*eb633035STom Caputi 	if ((flags & ARC_FILL_IN_PLACE) != 0) {
2410*eb633035STom Caputi 		ASSERT(!hdr_compressed);
2411*eb633035STom Caputi 		ASSERT(!compressed);
2412*eb633035STom Caputi 		ASSERT(!encrypted);
2413*eb633035STom Caputi 
2414*eb633035STom Caputi 		if (HDR_ENCRYPTED(hdr) && ARC_BUF_ENCRYPTED(buf)) {
2415*eb633035STom Caputi 			ASSERT3U(hdr->b_crypt_hdr.b_ot, ==, DMU_OT_DNODE);
2416*eb633035STom Caputi 
2417*eb633035STom Caputi 			if (hash_lock != NULL)
2418*eb633035STom Caputi 				mutex_enter(hash_lock);
2419*eb633035STom Caputi 			arc_buf_untransform_in_place(buf, hash_lock);
2420*eb633035STom Caputi 			if (hash_lock != NULL)
2421*eb633035STom Caputi 				mutex_exit(hash_lock);
2422*eb633035STom Caputi 
2423*eb633035STom Caputi 			/* Compute the hdr's checksum if necessary */
2424*eb633035STom Caputi 			arc_cksum_compute(buf);
2425*eb633035STom Caputi 		}
2426*eb633035STom Caputi 
2427*eb633035STom Caputi 		return (0);
2428*eb633035STom Caputi 	}
24295602294fSDan Kimmel 
24305602294fSDan Kimmel 	if (hdr_compressed == compressed) {
24315602294fSDan Kimmel 		if (!arc_buf_is_shared(buf)) {
2432770499e1SDan Kimmel 			abd_copy_to_buf(buf->b_data, hdr->b_l1hdr.b_pabd,
24335602294fSDan Kimmel 			    arc_buf_size(buf));
24345602294fSDan Kimmel 		}
2435dcbf3bd6SGeorge Wilson 	} else {
24365602294fSDan Kimmel 		ASSERT(hdr_compressed);
24375602294fSDan Kimmel 		ASSERT(!compressed);
2438dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, HDR_GET_PSIZE(hdr));
24395602294fSDan Kimmel 
24405602294fSDan Kimmel 		/*
24415602294fSDan Kimmel 		 * If the buf is sharing its data with the hdr, unlink it and
24425602294fSDan Kimmel 		 * allocate a new data buffer for the buf.
24435602294fSDan Kimmel 		 */
24445602294fSDan Kimmel 		if (arc_buf_is_shared(buf)) {
24455602294fSDan Kimmel 			ASSERT(ARC_BUF_COMPRESSED(buf));
24465602294fSDan Kimmel 
2447*eb633035STom Caputi 			/* We need to give the buf its own b_data */
24485602294fSDan Kimmel 			buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
24495602294fSDan Kimmel 			buf->b_data =
24505602294fSDan Kimmel 			    arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
24515602294fSDan Kimmel 			arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
24525602294fSDan Kimmel 
24535602294fSDan Kimmel 			/* Previously overhead was 0; just add new overhead */
24545602294fSDan Kimmel 			ARCSTAT_INCR(arcstat_overhead_size, HDR_GET_LSIZE(hdr));
24555602294fSDan Kimmel 		} else if (ARC_BUF_COMPRESSED(buf)) {
24565602294fSDan Kimmel 			/* We need to reallocate the buf's b_data */
24575602294fSDan Kimmel 			arc_free_data_buf(hdr, buf->b_data, HDR_GET_PSIZE(hdr),
24585602294fSDan Kimmel 			    buf);
24595602294fSDan Kimmel 			buf->b_data =
24605602294fSDan Kimmel 			    arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
24615602294fSDan Kimmel 
24625602294fSDan Kimmel 			/* We increased the size of b_data; update overhead */
24635602294fSDan Kimmel 			ARCSTAT_INCR(arcstat_overhead_size,
24645602294fSDan Kimmel 			    HDR_GET_LSIZE(hdr) - HDR_GET_PSIZE(hdr));
24655602294fSDan Kimmel 		}
24665602294fSDan Kimmel 
24675602294fSDan Kimmel 		/*
24685602294fSDan Kimmel 		 * Regardless of the buf's previous compression settings, it
24695602294fSDan Kimmel 		 * should not be compressed at the end of this function.
24705602294fSDan Kimmel 		 */
24715602294fSDan Kimmel 		buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
24725602294fSDan Kimmel 
24735602294fSDan Kimmel 		/*
24745602294fSDan Kimmel 		 * Try copying the data from another buf which already has a
24755602294fSDan Kimmel 		 * decompressed version. If that's not possible, it's time to
24765602294fSDan Kimmel 		 * bite the bullet and decompress the data from the hdr.
24775602294fSDan Kimmel 		 */
24785602294fSDan Kimmel 		if (arc_buf_try_copy_decompressed_data(buf)) {
24795602294fSDan Kimmel 			/* Skip byteswapping and checksumming (already done) */
24805602294fSDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, !=, NULL);
24815602294fSDan Kimmel 			return (0);
24825602294fSDan Kimmel 		} else {
2483*eb633035STom Caputi 			error = zio_decompress_data(HDR_GET_COMPRESS(hdr),
2484770499e1SDan Kimmel 			    hdr->b_l1hdr.b_pabd, buf->b_data,
24855602294fSDan Kimmel 			    HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
24865602294fSDan Kimmel 
24875602294fSDan Kimmel 			/*
24885602294fSDan Kimmel 			 * Absent hardware errors or software bugs, this should
24895602294fSDan Kimmel 			 * be impossible, but log it anyway so we can debug it.
24905602294fSDan Kimmel 			 */
24915602294fSDan Kimmel 			if (error != 0) {
24925602294fSDan Kimmel 				zfs_dbgmsg(
24935602294fSDan Kimmel 				    "hdr %p, compress %d, psize %d, lsize %d",
2494*eb633035STom Caputi 				    hdr, arc_hdr_get_compress(hdr),
24955602294fSDan Kimmel 				    HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
2496*eb633035STom Caputi 				if (hash_lock != NULL)
2497*eb633035STom Caputi 					mutex_enter(hash_lock);
2498*eb633035STom Caputi 				arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
2499*eb633035STom Caputi 				if (hash_lock != NULL)
2500*eb633035STom Caputi 					mutex_exit(hash_lock);
25015602294fSDan Kimmel 				return (SET_ERROR(EIO));
25025602294fSDan Kimmel 			}
2503ea8dc4b6Seschrock 		}
2504fa9e4066Sahrens 	}
25055602294fSDan Kimmel 
2506*eb633035STom Caputi byteswap:
25075602294fSDan Kimmel 	/* Byteswap the buf's data if necessary */
2508dcbf3bd6SGeorge Wilson 	if (bswap != DMU_BSWAP_NUMFUNCS) {
2509dcbf3bd6SGeorge Wilson 		ASSERT(!HDR_SHARED_DATA(hdr));
2510dcbf3bd6SGeorge Wilson 		ASSERT3U(bswap, <, DMU_BSWAP_NUMFUNCS);
2511dcbf3bd6SGeorge Wilson 		dmu_ot_byteswap[bswap].ob_func(buf->b_data, HDR_GET_LSIZE(hdr));
2512dcbf3bd6SGeorge Wilson 	}
25135602294fSDan Kimmel 
25145602294fSDan Kimmel 	/* Compute the hdr's checksum if necessary */
2515dcbf3bd6SGeorge Wilson 	arc_cksum_compute(buf);
25165602294fSDan Kimmel 
2517dcbf3bd6SGeorge Wilson 	return (0);
2518fa9e4066Sahrens }
2519fa9e4066Sahrens 
2520dcbf3bd6SGeorge Wilson /*
2521*eb633035STom Caputi  * If this function is being called to decrypt an encrypted buffer or verify an
2522*eb633035STom Caputi  * authenticated one, the key must be loaded and a mapping must be made
2523*eb633035STom Caputi  * available in the keystore via spa_keystore_create_mapping() or one of its
2524*eb633035STom Caputi  * callers.
2525dcbf3bd6SGeorge Wilson  */
2526*eb633035STom Caputi int
2527*eb633035STom Caputi arc_untransform(arc_buf_t *buf, spa_t *spa, const zbookmark_phys_t *zb,
2528*eb633035STom Caputi     boolean_t in_place)
2529fa9e4066Sahrens {
2530*eb633035STom Caputi 	int ret;
2531*eb633035STom Caputi 	arc_fill_flags_t flags = 0;
2532fa9e4066Sahrens 
2533*eb633035STom Caputi 	if (in_place)
2534*eb633035STom Caputi 		flags |= ARC_FILL_IN_PLACE;
2535*eb633035STom Caputi 
2536*eb633035STom Caputi 	ret = arc_buf_fill(buf, spa, zb, flags);
2537*eb633035STom Caputi 	if (ret == ECKSUM) {
2538*eb633035STom Caputi 		/*
2539*eb633035STom Caputi 		 * Convert authentication and decryption errors to EIO
2540*eb633035STom Caputi 		 * (and generate an ereport) before leaving the ARC.
2541*eb633035STom Caputi 		 */
2542*eb633035STom Caputi 		ret = SET_ERROR(EIO);
2543*eb633035STom Caputi 		spa_log_error(spa, zb);
2544*eb633035STom Caputi 		zfs_ereport_post(FM_EREPORT_ZFS_AUTHENTICATION,
2545*eb633035STom Caputi 		    spa, NULL, zb, NULL, 0, 0);
2546dcbf3bd6SGeorge Wilson 	}
2547*eb633035STom Caputi 
2548*eb633035STom Caputi 	return (ret);
2549dcbf3bd6SGeorge Wilson }
2550fa9e4066Sahrens 
2551dcbf3bd6SGeorge Wilson /*
2552dcbf3bd6SGeorge Wilson  * Increment the amount of evictable space in the arc_state_t's refcount.
2553dcbf3bd6SGeorge Wilson  * We account for the space used by the hdr and the arc buf individually
2554dcbf3bd6SGeorge Wilson  * so that we can add and remove them from the refcount individually.
2555dcbf3bd6SGeorge Wilson  */
2556dcbf3bd6SGeorge Wilson static void
2557dcbf3bd6SGeorge Wilson arc_evictable_space_increment(arc_buf_hdr_t *hdr, arc_state_t *state)
2558dcbf3bd6SGeorge Wilson {
2559dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type = arc_buf_type(hdr);
2560244781f1SPrakash Surya 
2561dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
25620e8c6158Smaybee 
2563dcbf3bd6SGeorge Wilson 	if (GHOST_STATE(state)) {
2564dcbf3bd6SGeorge Wilson 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
2565dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2566770499e1SDan Kimmel 		ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2567*eb633035STom Caputi 		ASSERT(!HDR_HAS_RABD(hdr));
2568e914ace2STim Schumacher 		(void) zfs_refcount_add_many(&state->arcs_esize[type],
25695602294fSDan Kimmel 		    HDR_GET_LSIZE(hdr), hdr);
2570dcbf3bd6SGeorge Wilson 		return;
2571dcbf3bd6SGeorge Wilson 	}
2572dcbf3bd6SGeorge Wilson 
2573dcbf3bd6SGeorge Wilson 	ASSERT(!GHOST_STATE(state));
2574770499e1SDan Kimmel 	if (hdr->b_l1hdr.b_pabd != NULL) {
2575e914ace2STim Schumacher 		(void) zfs_refcount_add_many(&state->arcs_esize[type],
2576dcbf3bd6SGeorge Wilson 		    arc_hdr_size(hdr), hdr);
2577dcbf3bd6SGeorge Wilson 	}
2578*eb633035STom Caputi 	if (HDR_HAS_RABD(hdr)) {
2579*eb633035STom Caputi 		(void) zfs_refcount_add_many(&state->arcs_esize[type],
2580*eb633035STom Caputi 		    HDR_GET_PSIZE(hdr), hdr);
2581*eb633035STom Caputi 	}
2582dcbf3bd6SGeorge Wilson 	for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2583dcbf3bd6SGeorge Wilson 	    buf = buf->b_next) {
25845602294fSDan Kimmel 		if (arc_buf_is_shared(buf))
2585dcbf3bd6SGeorge Wilson 			continue;
2586e914ace2STim Schumacher 		(void) zfs_refcount_add_many(&state->arcs_esize[type],
25875602294fSDan Kimmel 		    arc_buf_size(buf), buf);
2588fa9e4066Sahrens 	}
2589fa9e4066Sahrens }
2590fa9e4066Sahrens 
2591fa9e4066Sahrens /*
2592dcbf3bd6SGeorge Wilson  * Decrement the amount of evictable space in the arc_state_t's refcount.
2593dcbf3bd6SGeorge Wilson  * We account for the space used by the hdr and the arc buf individually
2594dcbf3bd6SGeorge Wilson  * so that we can add and remove them from the refcount individually.
2595fa9e4066Sahrens  */
2596fa9e4066Sahrens static void
25975602294fSDan Kimmel arc_evictable_space_decrement(arc_buf_hdr_t *hdr, arc_state_t *state)
2598fa9e4066Sahrens {
2599dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type = arc_buf_type(hdr);
2600dcbf3bd6SGeorge Wilson 
2601dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2602dcbf3bd6SGeorge Wilson 
2603dcbf3bd6SGeorge Wilson 	if (GHOST_STATE(state)) {
2604dcbf3bd6SGeorge Wilson 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
2605dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2606770499e1SDan Kimmel 		ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2607*eb633035STom Caputi 		ASSERT(!HDR_HAS_RABD(hdr));
2608e914ace2STim Schumacher 		(void) zfs_refcount_remove_many(&state->arcs_esize[type],
26095602294fSDan Kimmel 		    HDR_GET_LSIZE(hdr), hdr);
2610dcbf3bd6SGeorge Wilson 		return;
2611dcbf3bd6SGeorge Wilson 	}
2612dcbf3bd6SGeorge Wilson 
2613dcbf3bd6SGeorge Wilson 	ASSERT(!GHOST_STATE(state));
2614770499e1SDan Kimmel 	if (hdr->b_l1hdr.b_pabd != NULL) {
2615e914ace2STim Schumacher 		(void) zfs_refcount_remove_many(&state->arcs_esize[type],
2616dcbf3bd6SGeorge Wilson 		    arc_hdr_size(hdr), hdr);
2617dcbf3bd6SGeorge Wilson 	}
2618*eb633035STom Caputi 	if (HDR_HAS_RABD(hdr)) {
2619*eb633035STom Caputi 		(void) zfs_refcount_remove_many(&state->arcs_esize[type],
2620*eb633035STom Caputi 		    HDR_GET_PSIZE(hdr), hdr);
2621*eb633035STom Caputi 	}
2622dcbf3bd6SGeorge Wilson 	for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2623dcbf3bd6SGeorge Wilson 	    buf = buf->b_next) {
26245602294fSDan Kimmel 		if (arc_buf_is_shared(buf))
2625dcbf3bd6SGeorge Wilson 			continue;
2626e914ace2STim Schumacher 		(void) zfs_refcount_remove_many(&state->arcs_esize[type],
26275602294fSDan Kimmel 		    arc_buf_size(buf), buf);
2628dcbf3bd6SGeorge Wilson 	}
2629dcbf3bd6SGeorge Wilson }
2630dcbf3bd6SGeorge Wilson 
2631dcbf3bd6SGeorge Wilson /*
2632dcbf3bd6SGeorge Wilson  * Add a reference to this hdr indicating that someone is actively
2633dcbf3bd6SGeorge Wilson  * referencing that memory. When the refcount transitions from 0 to 1,
2634dcbf3bd6SGeorge Wilson  * we remove it from the respective arc_state_t list to indicate that
2635dcbf3bd6SGeorge Wilson  * it is not evictable.
2636dcbf3bd6SGeorge Wilson  */
2637dcbf3bd6SGeorge Wilson static void
2638dcbf3bd6SGeorge Wilson add_reference(arc_buf_hdr_t *hdr, void *tag)
2639dcbf3bd6SGeorge Wilson {
2640dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2641dcbf3bd6SGeorge Wilson 	if (!MUTEX_HELD(HDR_LOCK(hdr))) {
2642dcbf3bd6SGeorge Wilson 		ASSERT(hdr->b_l1hdr.b_state == arc_anon);
2643e914ace2STim Schumacher 		ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2644dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2645dcbf3bd6SGeorge Wilson 	}
2646dcbf3bd6SGeorge Wilson 
2647dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
2648dcbf3bd6SGeorge Wilson 
2649e914ace2STim Schumacher 	if ((zfs_refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
2650dcbf3bd6SGeorge Wilson 	    (state != arc_anon)) {
2651dcbf3bd6SGeorge Wilson 		/* We don't use the L2-only state list. */
2652dcbf3bd6SGeorge Wilson 		if (state != arc_l2c_only) {
265394c2d0ebSMatthew Ahrens 			multilist_remove(state->arcs_list[arc_buf_type(hdr)],
2654dcbf3bd6SGeorge Wilson 			    hdr);
26555602294fSDan Kimmel 			arc_evictable_space_decrement(hdr, state);
2656dcbf3bd6SGeorge Wilson 		}
2657dcbf3bd6SGeorge Wilson 		/* remove the prefetch flag if we get a reference */
2658dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
2659dcbf3bd6SGeorge Wilson 	}
2660dcbf3bd6SGeorge Wilson }
2661dcbf3bd6SGeorge Wilson 
2662dcbf3bd6SGeorge Wilson /*
2663dcbf3bd6SGeorge Wilson  * Remove a reference from this hdr. When the reference transitions from
2664dcbf3bd6SGeorge Wilson  * 1 to 0 and we're not anonymous, then we add this hdr to the arc_state_t's
2665dcbf3bd6SGeorge Wilson  * list making it eligible for eviction.
2666dcbf3bd6SGeorge Wilson  */
2667dcbf3bd6SGeorge Wilson static int
2668dcbf3bd6SGeorge Wilson remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
2669dcbf3bd6SGeorge Wilson {
2670dcbf3bd6SGeorge Wilson 	int cnt;
2671dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
2672dcbf3bd6SGeorge Wilson 
2673dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
2674dcbf3bd6SGeorge Wilson 	ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
2675dcbf3bd6SGeorge Wilson 	ASSERT(!GHOST_STATE(state));
2676dcbf3bd6SGeorge Wilson 
2677dcbf3bd6SGeorge Wilson 	/*
2678dcbf3bd6SGeorge Wilson 	 * arc_l2c_only counts as a ghost state so we don't need to explicitly
2679dcbf3bd6SGeorge Wilson 	 * check to prevent usage of the arc_l2c_only list.
2680dcbf3bd6SGeorge Wilson 	 */
2681e914ace2STim Schumacher 	if (((cnt = zfs_refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
2682dcbf3bd6SGeorge Wilson 	    (state != arc_anon)) {
268394c2d0ebSMatthew Ahrens 		multilist_insert(state->arcs_list[arc_buf_type(hdr)], hdr);
2684dcbf3bd6SGeorge Wilson 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
2685dcbf3bd6SGeorge Wilson 		arc_evictable_space_increment(hdr, state);
2686dcbf3bd6SGeorge Wilson 	}
2687dcbf3bd6SGeorge Wilson 	return (cnt);
2688dcbf3bd6SGeorge Wilson }
2689dcbf3bd6SGeorge Wilson 
2690dcbf3bd6SGeorge Wilson /*
2691dcbf3bd6SGeorge Wilson  * Move the supplied buffer to the indicated state. The hash lock
2692dcbf3bd6SGeorge Wilson  * for the buffer must be held by the caller.
2693dcbf3bd6SGeorge Wilson  */
2694dcbf3bd6SGeorge Wilson static void
2695dcbf3bd6SGeorge Wilson arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
2696dcbf3bd6SGeorge Wilson     kmutex_t *hash_lock)
2697dcbf3bd6SGeorge Wilson {
2698dcbf3bd6SGeorge Wilson 	arc_state_t *old_state;
2699dcbf3bd6SGeorge Wilson 	int64_t refcnt;
2700dcbf3bd6SGeorge Wilson 	uint32_t bufcnt;
2701dcbf3bd6SGeorge Wilson 	boolean_t update_old, update_new;
2702dcbf3bd6SGeorge Wilson 	arc_buf_contents_t buftype = arc_buf_type(hdr);
270389c86e32SChris Williamson 
270489c86e32SChris Williamson 	/*
270589c86e32SChris Williamson 	 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
270689c86e32SChris Williamson 	 * in arc_read() when bringing a buffer out of the L2ARC.  However, the
270789c86e32SChris Williamson 	 * L1 hdr doesn't always exist when we change state to arc_anon before
270889c86e32SChris Williamson 	 * destroying a header, in which case reallocating to add the L1 hdr is
270989c86e32SChris Williamson 	 * pointless.
271089c86e32SChris Williamson 	 */
271189c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr)) {
271289c86e32SChris Williamson 		old_state = hdr->b_l1hdr.b_state;
2713e914ace2STim Schumacher 		refcnt = zfs_refcount_count(&hdr->b_l1hdr.b_refcnt);
2714dcbf3bd6SGeorge Wilson 		bufcnt = hdr->b_l1hdr.b_bufcnt;
2715*eb633035STom Caputi 
2716*eb633035STom Caputi 		update_old = (bufcnt > 0 || hdr->b_l1hdr.b_pabd != NULL ||
2717*eb633035STom Caputi 		    HDR_HAS_RABD(hdr));
271889c86e32SChris Williamson 	} else {
271989c86e32SChris Williamson 		old_state = arc_l2c_only;
272089c86e32SChris Williamson 		refcnt = 0;
2721dcbf3bd6SGeorge Wilson 		bufcnt = 0;
2722dcbf3bd6SGeorge Wilson 		update_old = B_FALSE;
272389c86e32SChris Williamson 	}
2724dcbf3bd6SGeorge Wilson 	update_new = update_old;
2725fa9e4066Sahrens 
2726fa9e4066Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
272769962b56SMatthew Ahrens 	ASSERT3P(new_state, !=, old_state);
2728dcbf3bd6SGeorge Wilson 	ASSERT(!GHOST_STATE(new_state) || bufcnt == 0);
2729dcbf3bd6SGeorge Wilson 	ASSERT(old_state != arc_anon || bufcnt <= 1);
2730fa9e4066Sahrens 
2731fa9e4066Sahrens 	/*
2732fa9e4066Sahrens 	 * If this buffer is evictable, transfer it from the
2733fa9e4066Sahrens 	 * old state list to the new state list.
2734fa9e4066Sahrens 	 */
2735ea8dc4b6Seschrock 	if (refcnt == 0) {
273689c86e32SChris Williamson 		if (old_state != arc_anon && old_state != arc_l2c_only) {
273789c86e32SChris Williamson 			ASSERT(HDR_HAS_L1HDR(hdr));
273894c2d0ebSMatthew Ahrens 			multilist_remove(old_state->arcs_list[buftype], hdr);
2739ea8dc4b6Seschrock 
2740dcbf3bd6SGeorge Wilson 			if (GHOST_STATE(old_state)) {
2741dcbf3bd6SGeorge Wilson 				ASSERT0(bufcnt);
2742dcbf3bd6SGeorge Wilson 				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2743dcbf3bd6SGeorge Wilson 				update_old = B_TRUE;
2744ea8dc4b6Seschrock 			}
27455602294fSDan Kimmel 			arc_evictable_space_decrement(hdr, old_state);
2746fa9e4066Sahrens 		}
274789c86e32SChris Williamson 		if (new_state != arc_anon && new_state != arc_l2c_only) {
2748fa9e4066Sahrens 
274989c86e32SChris Williamson 			/*
275089c86e32SChris Williamson 			 * An L1 header always exists here, since if we're
275189c86e32SChris Williamson 			 * moving to some L1-cached state (i.e. not l2c_only or
275289c86e32SChris Williamson 			 * anonymous), we realloc the header to add an L1hdr
275389c86e32SChris Williamson 			 * beforehand.
275489c86e32SChris Williamson 			 */
275589c86e32SChris Williamson 			ASSERT(HDR_HAS_L1HDR(hdr));
275694c2d0ebSMatthew Ahrens 			multilist_insert(new_state->arcs_list[buftype], hdr);
2757ea8dc4b6Seschrock 
2758ea8dc4b6Seschrock 			if (GHOST_STATE(new_state)) {
2759dcbf3bd6SGeorge Wilson 				ASSERT0(bufcnt);
2760dcbf3bd6SGeorge Wilson 				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2761dcbf3bd6SGeorge Wilson 				update_new = B_TRUE;
2762ea8dc4b6Seschrock 			}
2763dcbf3bd6SGeorge Wilson 			arc_evictable_space_increment(hdr, new_state);
2764fa9e4066Sahrens 		}
2765fa9e4066Sahrens 	}
2766fa9e4066Sahrens 
2767dcbf3bd6SGeorge Wilson 	ASSERT(!HDR_EMPTY(hdr));
27687adb730bSGeorge Wilson 	if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
27697adb730bSGeorge Wilson 		buf_hash_remove(hdr);
2770fa9e4066Sahrens 
277189c86e32SChris Williamson 	/* adjust state sizes (ignore arc_l2c_only) */
27722fd872a7SPrakash Surya 
2773dcbf3bd6SGeorge Wilson 	if (update_new && new_state != arc_l2c_only) {
27742fd872a7SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(hdr));
27752fd872a7SPrakash Surya 		if (GHOST_STATE(new_state)) {
2776dcbf3bd6SGeorge Wilson 			ASSERT0(bufcnt);
27772fd872a7SPrakash Surya 
27782fd872a7SPrakash Surya 			/*
2779dcbf3bd6SGeorge Wilson 			 * When moving a header to a ghost state, we first
27802fd872a7SPrakash Surya 			 * remove all arc buffers. Thus, we'll have a
2781dcbf3bd6SGeorge Wilson 			 * bufcnt of zero, and no arc buffer to use for
27822fd872a7SPrakash Surya 			 * the reference. As a result, we use the arc
27832fd872a7SPrakash Surya 			 * header pointer for the reference.
27842fd872a7SPrakash Surya 			 */
2785e914ace2STim Schumacher 			(void) zfs_refcount_add_many(&new_state->arcs_size,
2786dcbf3bd6SGeorge Wilson 			    HDR_GET_LSIZE(hdr), hdr);
2787770499e1SDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2788*eb633035STom Caputi 			ASSERT(!HDR_HAS_RABD(hdr));
27892fd872a7SPrakash Surya 		} else {
2790dcbf3bd6SGeorge Wilson 			uint32_t buffers = 0;
27912fd872a7SPrakash Surya 
27922fd872a7SPrakash Surya 			/*
27932fd872a7SPrakash Surya 			 * Each individual buffer holds a unique reference,
27942fd872a7SPrakash Surya 			 * thus we must remove each of these references one
27952fd872a7SPrakash Surya 			 * at a time.
27962fd872a7SPrakash Surya 			 */
27972fd872a7SPrakash Surya 			for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
27982fd872a7SPrakash Surya 			    buf = buf->b_next) {
2799dcbf3bd6SGeorge Wilson 				ASSERT3U(bufcnt, !=, 0);
2800dcbf3bd6SGeorge Wilson 				buffers++;
2801dcbf3bd6SGeorge Wilson 
2802dcbf3bd6SGeorge Wilson 				/*
2803dcbf3bd6SGeorge Wilson 				 * When the arc_buf_t is sharing the data
2804dcbf3bd6SGeorge Wilson 				 * block with the hdr, the owner of the
2805dcbf3bd6SGeorge Wilson 				 * reference belongs to the hdr. Only
2806dcbf3bd6SGeorge Wilson 				 * add to the refcount if the arc_buf_t is
2807dcbf3bd6SGeorge Wilson 				 * not shared.
2808dcbf3bd6SGeorge Wilson 				 */
28095602294fSDan Kimmel 				if (arc_buf_is_shared(buf))
2810dcbf3bd6SGeorge Wilson 					continue;
2811dcbf3bd6SGeorge Wilson 
2812e914ace2STim Schumacher 				(void) zfs_refcount_add_many(
2813e914ace2STim Schumacher 				    &new_state->arcs_size,
28145602294fSDan Kimmel 				    arc_buf_size(buf), buf);
2815dcbf3bd6SGeorge Wilson 			}
2816dcbf3bd6SGeorge Wilson 			ASSERT3U(bufcnt, ==, buffers);
2817dcbf3bd6SGeorge Wilson 
2818770499e1SDan Kimmel 			if (hdr->b_l1hdr.b_pabd != NULL) {
2819e914ace2STim Schumacher 				(void) zfs_refcount_add_many(
2820e914ace2STim Schumacher 				    &new_state->arcs_size,
2821dcbf3bd6SGeorge Wilson 				    arc_hdr_size(hdr), hdr);
2822*eb633035STom Caputi 			}
2823*eb633035STom Caputi 
2824*eb633035STom Caputi 			if (HDR_HAS_RABD(hdr)) {
2825*eb633035STom Caputi 				(void) zfs_refcount_add_many(
2826*eb633035STom Caputi 				    &new_state->arcs_size,
2827*eb633035STom Caputi 				    HDR_GET_PSIZE(hdr), hdr);
28282fd872a7SPrakash Surya 			}
28292fd872a7SPrakash Surya 		}
28302fd872a7SPrakash Surya 	}
28312fd872a7SPrakash Surya 
2832dcbf3bd6SGeorge Wilson 	if (update_old && old_state != arc_l2c_only) {
28332fd872a7SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(hdr));
28342fd872a7SPrakash Surya 		if (GHOST_STATE(old_state)) {
2835dcbf3bd6SGeorge Wilson 			ASSERT0(bufcnt);
2836770499e1SDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2837*eb633035STom Caputi 			ASSERT(!HDR_HAS_RABD(hdr));
2838dcbf3bd6SGeorge Wilson 
28392fd872a7SPrakash Surya 			/*
28402fd872a7SPrakash Surya 			 * When moving a header off of a ghost state,
2841dcbf3bd6SGeorge Wilson 			 * the header will not contain any arc buffers.
2842dcbf3bd6SGeorge Wilson 			 * We use the arc header pointer for the reference
2843dcbf3bd6SGeorge Wilson 			 * which is exactly what we did when we put the
2844dcbf3bd6SGeorge Wilson 			 * header on the ghost state.
28452fd872a7SPrakash Surya 			 */
28462fd872a7SPrakash Surya 
2847e914ace2STim Schumacher 			(void) zfs_refcount_remove_many(&old_state->arcs_size,
2848dcbf3bd6SGeorge Wilson 			    HDR_GET_LSIZE(hdr), hdr);
28492fd872a7SPrakash Surya 		} else {
2850dcbf3bd6SGeorge Wilson 			uint32_t buffers = 0;
28512fd872a7SPrakash Surya 
28522fd872a7SPrakash Surya 			/*
28532fd872a7SPrakash Surya 			 * Each individual buffer holds a unique reference,
28542fd872a7SPrakash Surya 			 * thus we must remove each of these references one
28552fd872a7SPrakash Surya 			 * at a time.
28562fd872a7SPrakash Surya 			 */
28572fd872a7SPrakash Surya 			for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
28582fd872a7SPrakash Surya 			    buf = buf->b_next) {
28595602294fSDan Kimmel 				ASSERT3U(bufcnt, !=, 0);
2860dcbf3bd6SGeorge Wilson 				buffers++;
2861dcbf3bd6SGeorge Wilson 
2862dcbf3bd6SGeorge Wilson 				/*
2863dcbf3bd6SGeorge Wilson 				 * When the arc_buf_t is sharing the data
2864dcbf3bd6SGeorge Wilson 				 * block with the hdr, the owner of the
2865dcbf3bd6SGeorge Wilson 				 * reference belongs to the hdr. Only
2866dcbf3bd6SGeorge Wilson 				 * add to the refcount if the arc_buf_t is
2867dcbf3bd6SGeorge Wilson 				 * not shared.
2868dcbf3bd6SGeorge Wilson 				 */
28695602294fSDan Kimmel 				if (arc_buf_is_shared(buf))
2870dcbf3bd6SGeorge Wilson 					continue;
2871dcbf3bd6SGeorge Wilson 
2872e914ace2STim Schumacher 				(void) zfs_refcount_remove_many(
28735602294fSDan Kimmel 				    &old_state->arcs_size, arc_buf_size(buf),
2874dcbf3bd6SGeorge Wilson 				    buf);
28752fd872a7SPrakash Surya 			}
2876dcbf3bd6SGeorge Wilson 			ASSERT3U(bufcnt, ==, buffers);
2877*eb633035STom Caputi 			ASSERT(hdr->b_l1hdr.b_pabd != NULL ||
2878*eb633035STom Caputi 			    HDR_HAS_RABD(hdr));
2879*eb633035STom Caputi 
2880*eb633035STom Caputi 			if (hdr->b_l1hdr.b_pabd != NULL) {
2881*eb633035STom Caputi 				(void) zfs_refcount_remove_many(
2882*eb633035STom Caputi 				    &old_state->arcs_size, arc_hdr_size(hdr),
2883*eb633035STom Caputi 				    hdr);
2884*eb633035STom Caputi 			}
2885*eb633035STom Caputi 
2886*eb633035STom Caputi 			if (HDR_HAS_RABD(hdr)) {
2887*eb633035STom Caputi 				(void) zfs_refcount_remove_many(
2888*eb633035STom Caputi 				    &old_state->arcs_size, HDR_GET_PSIZE(hdr),
2889*eb633035STom Caputi 				    hdr);
2890*eb633035STom Caputi 			}
28912fd872a7SPrakash Surya 		}
2892fa9e4066Sahrens 	}
28932fd872a7SPrakash Surya 
289489c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr))
289589c86e32SChris Williamson 		hdr->b_l1hdr.b_state = new_state;
2896fa94a07fSbrendan 
289789c86e32SChris Williamson 	/*
289889c86e32SChris Williamson 	 * L2 headers should never be on the L2 state list since they don't
289989c86e32SChris Williamson 	 * have L1 headers allocated.
290089c86e32SChris Williamson 	 */
290194c2d0ebSMatthew Ahrens 	ASSERT(multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
290294c2d0ebSMatthew Ahrens 	    multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
2903fa9e4066Sahrens }
2904fa9e4066Sahrens 
29050e8c6158Smaybee void
29065a98e54bSBrendan Gregg - Sun Microsystems arc_space_consume(uint64_t space, arc_space_type_t type)
29070e8c6158Smaybee {
29085a98e54bSBrendan Gregg - Sun Microsystems 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
29095a98e54bSBrendan Gregg - Sun Microsystems 
29105a98e54bSBrendan Gregg - Sun Microsystems 	switch (type) {
29115a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_DATA:
29123a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_data_size, space);
29135a98e54bSBrendan Gregg - Sun Microsystems 		break;
29144076b1bfSPrakash Surya 	case ARC_SPACE_META:
29153a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_metadata_size, space);
29164076b1bfSPrakash Surya 		break;
29175a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_OTHER:
29183a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_other_size, space);
29195a98e54bSBrendan Gregg - Sun Microsystems 		break;
29205a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_HDRS:
29213a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_hdr_size, space);
29225a98e54bSBrendan Gregg - Sun Microsystems 		break;
29235a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_L2HDRS:
29243a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_l2_hdr_size, space);
29255a98e54bSBrendan Gregg - Sun Microsystems 		break;
29265a98e54bSBrendan Gregg - Sun Microsystems 	}
29275a98e54bSBrendan Gregg - Sun Microsystems 
29284076b1bfSPrakash Surya 	if (type != ARC_SPACE_DATA)
29293a2d8a1bSPaul Dagnelie 		aggsum_add(&arc_meta_used, space);
29304076b1bfSPrakash Surya 
29313a2d8a1bSPaul Dagnelie 	aggsum_add(&arc_size, space);
29320e8c6158Smaybee }
29330e8c6158Smaybee 
29340e8c6158Smaybee void
29355a98e54bSBrendan Gregg - Sun Microsystems arc_space_return(uint64_t space, arc_space_type_t type)
29360e8c6158Smaybee {
29375a98e54bSBrendan Gregg - Sun Microsystems 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
29385a98e54bSBrendan Gregg - Sun Microsystems 
29395a98e54bSBrendan Gregg - Sun Microsystems 	switch (type) {
29405a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_DATA:
29413a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_data_size, -space);
29425a98e54bSBrendan Gregg - Sun Microsystems 		break;
29434076b1bfSPrakash Surya 	case ARC_SPACE_META:
29443a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_metadata_size, -space);
29454076b1bfSPrakash Surya 		break;
29465a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_OTHER:
29473a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_other_size, -space);
29485a98e54bSBrendan Gregg - Sun Microsystems 		break;
29495a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_HDRS:
29503a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_hdr_size, -space);
29515a98e54bSBrendan Gregg - Sun Microsystems 		break;
29525a98e54bSBrendan Gregg - Sun Microsystems 	case ARC_SPACE_L2HDRS:
29533a2d8a1bSPaul Dagnelie 		aggsum_add(&astat_l2_hdr_size, -space);
29545a98e54bSBrendan Gregg - Sun Microsystems 		break;
29555a98e54bSBrendan Gregg - Sun Microsystems 	}
29565a98e54bSBrendan Gregg - Sun Microsystems 
29574076b1bfSPrakash Surya 	if (type != ARC_SPACE_DATA) {
29583a2d8a1bSPaul Dagnelie 		ASSERT(aggsum_compare(&arc_meta_used, space) >= 0);
29593a2d8a1bSPaul Dagnelie 		/*
29603a2d8a1bSPaul Dagnelie 		 * We use the upper bound here rather than the precise value
29613a2d8a1bSPaul Dagnelie 		 * because the arc_meta_max value doesn't need to be
29623a2d8a1bSPaul Dagnelie 		 * precise. It's only consumed by humans via arcstats.
29633a2d8a1bSPaul Dagnelie 		 */
29643a2d8a1bSPaul Dagnelie 		if (arc_meta_max < aggsum_upper_bound(&arc_meta_used))
29653a2d8a1bSPaul Dagnelie 			arc_meta_max = aggsum_upper_bound(&arc_meta_used);
29663a2d8a1bSPaul Dagnelie 		aggsum_add(&arc_meta_used, -space);
29674076b1bfSPrakash Surya 	}
29684076b1bfSPrakash Surya 
29693a2d8a1bSPaul Dagnelie 	ASSERT(aggsum_compare(&arc_size, space) >= 0);
29703a2d8a1bSPaul Dagnelie 	aggsum_add(&arc_size, -space);
29710e8c6158Smaybee }
29720e8c6158Smaybee 
2973dcbf3bd6SGeorge Wilson /*
29745602294fSDan Kimmel  * Given a hdr and a buf, returns whether that buf can share its b_data buffer
2975770499e1SDan Kimmel  * with the hdr's b_pabd.
2976dcbf3bd6SGeorge Wilson  */
29775602294fSDan Kimmel static boolean_t
29785602294fSDan Kimmel arc_can_share(arc_buf_hdr_t *hdr, arc_buf_t *buf)
29795602294fSDan Kimmel {
29805602294fSDan Kimmel 	/*
29815602294fSDan Kimmel 	 * The criteria for sharing a hdr's data are:
2982*eb633035STom Caputi 	 * 1. the buffer is not encrypted
2983*eb633035STom Caputi 	 * 2. the hdr's compression matches the buf's compression
2984*eb633035STom Caputi 	 * 3. the hdr doesn't need to be byteswapped
2985*eb633035STom Caputi 	 * 4. the hdr isn't already being shared
2986*eb633035STom Caputi 	 * 5. the buf is either compressed or it is the last buf in the hdr list
29875602294fSDan Kimmel 	 *
2988*eb633035STom Caputi 	 * Criterion #5 maintains the invariant that shared uncompressed
29895602294fSDan Kimmel 	 * bufs must be the final buf in the hdr's b_buf list. Reading this, you
29905602294fSDan Kimmel 	 * might ask, "if a compressed buf is allocated first, won't that be the
29915602294fSDan Kimmel 	 * last thing in the list?", but in that case it's impossible to create
29925602294fSDan Kimmel 	 * a shared uncompressed buf anyway (because the hdr must be compressed
29935602294fSDan Kimmel 	 * to have the compressed buf). You might also think that #3 is
29945602294fSDan Kimmel 	 * sufficient to make this guarantee, however it's possible
29955602294fSDan Kimmel 	 * (specifically in the rare L2ARC write race mentioned in
29965602294fSDan Kimmel 	 * arc_buf_alloc_impl()) there will be an existing uncompressed buf that
29975602294fSDan Kimmel 	 * is sharable, but wasn't at the time of its allocation. Rather than
29985602294fSDan Kimmel 	 * allow a new shared uncompressed buf to be created and then shuffle
29995602294fSDan Kimmel 	 * the list around to make it the last element, this simply disallows
30005602294fSDan Kimmel 	 * sharing if the new buf isn't the first to be added.
30015602294fSDan Kimmel 	 */
30025602294fSDan Kimmel 	ASSERT3P(buf->b_hdr, ==, hdr);
3003*eb633035STom Caputi 	boolean_t hdr_compressed = arc_hdr_get_compress(hdr) !=
3004*eb633035STom Caputi 	    ZIO_COMPRESS_OFF;
30055602294fSDan Kimmel 	boolean_t buf_compressed = ARC_BUF_COMPRESSED(buf) != 0;
3006*eb633035STom Caputi 	return (!ARC_BUF_ENCRYPTED(buf) &&
3007*eb633035STom Caputi 	    buf_compressed == hdr_compressed &&
30085602294fSDan Kimmel 	    hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS &&
30095602294fSDan Kimmel 	    !HDR_SHARED_DATA(hdr) &&
30105602294fSDan Kimmel 	    (ARC_BUF_LAST(buf) || ARC_BUF_COMPRESSED(buf)));
30115602294fSDan Kimmel }
30125602294fSDan Kimmel 
30135602294fSDan Kimmel /*
30145602294fSDan Kimmel  * Allocate a buf for this hdr. If you care about the data that's in the hdr,
30155602294fSDan Kimmel  * or if you want a compressed buffer, pass those flags in. Returns 0 if the
30165602294fSDan Kimmel  * copy was made successfully, or an error code otherwise.
30175602294fSDan Kimmel  */
30185602294fSDan Kimmel static int
3019*eb633035STom Caputi arc_buf_alloc_impl(arc_buf_hdr_t *hdr, spa_t *spa, const zbookmark_phys_t *zb,
3020*eb633035STom Caputi     void *tag, boolean_t encrypted, boolean_t compressed, boolean_t noauth,
30215602294fSDan Kimmel     boolean_t fill, arc_buf_t **ret)
3022fa9e4066Sahrens {
3023fa9e4066Sahrens 	arc_buf_t *buf;
3024*eb633035STom Caputi 	arc_fill_flags_t flags = ARC_FILL_LOCKED;
3025fa9e4066Sahrens 
3026dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
3027dcbf3bd6SGeorge Wilson 	ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
3028dcbf3bd6SGeorge Wilson 	VERIFY(hdr->b_type == ARC_BUFC_DATA ||
3029dcbf3bd6SGeorge Wilson 	    hdr->b_type == ARC_BUFC_METADATA);
30305602294fSDan Kimmel 	ASSERT3P(ret, !=, NULL);
30315602294fSDan Kimmel 	ASSERT3P(*ret, ==, NULL);
3032*eb633035STom Caputi 	IMPLY(encrypted, compressed);
3033dcbf3bd6SGeorge Wilson 
30345602294fSDan Kimmel 	buf = *ret = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
3035fa9e4066Sahrens 	buf->b_hdr = hdr;
303644eda4d7Smaybee 	buf->b_data = NULL;
30375602294fSDan Kimmel 	buf->b_next = hdr->b_l1hdr.b_buf;
30385602294fSDan Kimmel 	buf->b_flags = 0;
303989c86e32SChris Williamson 
3040dcbf3bd6SGeorge Wilson 	add_reference(hdr, tag);
3041dcbf3bd6SGeorge Wilson 
3042dcbf3bd6SGeorge Wilson 	/*
3043dcbf3bd6SGeorge Wilson 	 * We're about to change the hdr's b_flags. We must either
3044dcbf3bd6SGeorge Wilson 	 * hold the hash_lock or be undiscoverable.
3045dcbf3bd6SGeorge Wilson 	 */
3046dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
3047dcbf3bd6SGeorge Wilson 
3048dcbf3bd6SGeorge Wilson 	/*
30495602294fSDan Kimmel 	 * Only honor requests for compressed bufs if the hdr is actually
3050*eb633035STom Caputi 	 * compressed. This must be overriden if the buffer is encrypted since
3051*eb633035STom Caputi 	 * encrypted buffers cannot be decompressed.
30525602294fSDan Kimmel 	 */
3053*eb633035STom Caputi 	if (encrypted) {
3054*eb633035STom Caputi 		buf->b_flags |= ARC_BUF_FLAG_COMPRESSED;
3055*eb633035STom Caputi 		buf->b_flags |= ARC_BUF_FLAG_ENCRYPTED;
3056*eb633035STom Caputi 		flags |= ARC_FILL_COMPRESSED | ARC_FILL_ENCRYPTED;
3057*eb633035STom Caputi 	} else if (compressed &&
3058*eb633035STom Caputi 	    arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF) {
30595602294fSDan Kimmel 		buf->b_flags |= ARC_BUF_FLAG_COMPRESSED;
3060*eb633035STom Caputi 		flags |= ARC_FILL_COMPRESSED;
3061*eb633035STom Caputi 	}
3062*eb633035STom Caputi 
3063*eb633035STom Caputi 	if (noauth) {
3064*eb633035STom Caputi 		ASSERT0(encrypted);
3065*eb633035STom Caputi 		flags |= ARC_FILL_NOAUTH;
3066*eb633035STom Caputi 	}
30675602294fSDan Kimmel 
30685602294fSDan Kimmel 	/*
30695602294fSDan Kimmel 	 * If the hdr's data can be shared then we share the data buffer and
30705602294fSDan Kimmel 	 * set the appropriate bit in the hdr's b_flags to indicate the hdr is
3071*eb633035STom Caputi 	 * allocate a new buffer to store the buf's data.
30725602294fSDan Kimmel 	 *
3073770499e1SDan Kimmel 	 * There are two additional restrictions here because we're sharing
3074770499e1SDan Kimmel 	 * hdr -> buf instead of the usual buf -> hdr. First, the hdr can't be
3075770499e1SDan Kimmel 	 * actively involved in an L2ARC write, because if this buf is used by
3076770499e1SDan Kimmel 	 * an arc_write() then the hdr's data buffer will be released when the
30775602294fSDan Kimmel 	 * write completes, even though the L2ARC write might still be using it.
3078770499e1SDan Kimmel 	 * Second, the hdr's ABD must be linear so that the buf's user doesn't
3079770499e1SDan Kimmel 	 * need to be ABD-aware.
3080dcbf3bd6SGeorge Wilson 	 */
3081770499e1SDan Kimmel 	boolean_t can_share = arc_can_share(hdr, buf) && !HDR_L2_WRITING(hdr) &&
3082*eb633035STom Caputi 	    hdr->b_l1hdr.b_pabd != NULL && abd_is_linear(hdr->b_l1hdr.b_pabd);
30835602294fSDan Kimmel 
30845602294fSDan Kimmel 	/* Set up b_data and sharing */
30855602294fSDan Kimmel 	if (can_share) {
3086770499e1SDan Kimmel 		buf->b_data = abd_to_buf(hdr->b_l1hdr.b_pabd);
30875602294fSDan Kimmel 		buf->b_flags |= ARC_BUF_FLAG_SHARED;
3088dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
3089dcbf3bd6SGeorge Wilson 	} else {
30905602294fSDan Kimmel 		buf->b_data =
30915602294fSDan Kimmel 		    arc_get_data_buf(hdr, arc_buf_size(buf), buf);
30925602294fSDan Kimmel 		ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
3093dcbf3bd6SGeorge Wilson 	}
3094dcbf3bd6SGeorge Wilson 	VERIFY3P(buf->b_data, !=, NULL);
309589c86e32SChris Williamson 
309689c86e32SChris Williamson 	hdr->b_l1hdr.b_buf = buf;
3097dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_bufcnt += 1;
3098*eb633035STom Caputi 	if (encrypted)
3099*eb633035STom Caputi 		hdr->b_crypt_hdr.b_ebufcnt += 1;
310089c86e32SChris Williamson 
31015602294fSDan Kimmel 	/*
31025602294fSDan Kimmel 	 * If the user wants the data from the hdr, we need to either copy or
31035602294fSDan Kimmel 	 * decompress the data.
31045602294fSDan Kimmel 	 */
31055602294fSDan Kimmel 	if (fill) {
3106*eb633035STom Caputi 		ASSERT3P(zb, !=, NULL);
3107*eb633035STom Caputi 		return (arc_buf_fill(buf, spa, zb, flags));
31085602294fSDan Kimmel 	}
3109dcbf3bd6SGeorge Wilson 
31105602294fSDan Kimmel 	return (0);
31115602294fSDan Kimmel }
3112dcbf3bd6SGeorge Wilson 
31135602294fSDan Kimmel static char *arc_onloan_tag = "onloan";
3114fa9e4066Sahrens 
31155602294fSDan Kimmel static inline void
31165602294fSDan Kimmel arc_loaned_bytes_update(int64_t delta)
31175602294fSDan Kimmel {
31185602294fSDan Kimmel 	atomic_add_64(&arc_loaned_bytes, delta);
3119dcbf3bd6SGeorge Wilson 
31205602294fSDan Kimmel 	/* assert that it did not wrap around */
31215602294fSDan Kimmel 	ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
3122fa9e4066Sahrens }
3123fa9e4066Sahrens 
31242fdbea25SAleksandr Guzovskiy /*
31252fdbea25SAleksandr Guzovskiy  * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
31262fdbea25SAleksandr Guzovskiy  * flight data by arc_tempreserve_space() until they are "returned". Loaned
31272fdbea25SAleksandr Guzovskiy  * buffers must be returned to the arc before they can be used by the DMU or
31282fdbea25SAleksandr Guzovskiy  * freed.
31292fdbea25SAleksandr Guzovskiy  */
31302fdbea25SAleksandr Guzovskiy arc_buf_t *
31315602294fSDan Kimmel arc_loan_buf(spa_t *spa, boolean_t is_metadata, int size)
31322fdbea25SAleksandr Guzovskiy {
31335602294fSDan Kimmel 	arc_buf_t *buf = arc_alloc_buf(spa, arc_onloan_tag,
31345602294fSDan Kimmel 	    is_metadata ? ARC_BUFC_METADATA : ARC_BUFC_DATA, size);
31355602294fSDan Kimmel 
31369be12bd7SAllan Jude 	arc_loaned_bytes_update(arc_buf_size(buf));
31375602294fSDan Kimmel 
31385602294fSDan Kimmel 	return (buf);
31395602294fSDan Kimmel }
31402fdbea25SAleksandr Guzovskiy 
31415602294fSDan Kimmel arc_buf_t *
31425602294fSDan Kimmel arc_loan_compressed_buf(spa_t *spa, uint64_t psize, uint64_t lsize,
31435602294fSDan Kimmel     enum zio_compress compression_type)
31445602294fSDan Kimmel {
31455602294fSDan Kimmel 	arc_buf_t *buf = arc_alloc_compressed_buf(spa, arc_onloan_tag,
31465602294fSDan Kimmel 	    psize, lsize, compression_type);
31475602294fSDan Kimmel 
31489be12bd7SAllan Jude 	arc_loaned_bytes_update(arc_buf_size(buf));
31492fdbea25SAleksandr Guzovskiy 
31502fdbea25SAleksandr Guzovskiy 	return (buf);
31512fdbea25SAleksandr Guzovskiy }
31522fdbea25SAleksandr Guzovskiy 
3153*eb633035STom Caputi arc_buf_t *
3154*eb633035STom Caputi arc_loan_raw_buf(spa_t *spa, uint64_t dsobj, boolean_t byteorder,
3155*eb633035STom Caputi     const uint8_t *salt, const uint8_t *iv, const uint8_t *mac,
3156*eb633035STom Caputi     dmu_object_type_t ot, uint64_t psize, uint64_t lsize,
3157*eb633035STom Caputi     enum zio_compress compression_type)
3158*eb633035STom Caputi {
3159*eb633035STom Caputi 	arc_buf_t *buf = arc_alloc_raw_buf(spa, arc_onloan_tag, dsobj,
3160*eb633035STom Caputi 	    byteorder, salt, iv, mac, ot, psize, lsize, compression_type);
3161*eb633035STom Caputi 
3162*eb633035STom Caputi 	atomic_add_64(&arc_loaned_bytes, psize);
3163*eb633035STom Caputi 	return (buf);
3164*eb633035STom Caputi }
3165*eb633035STom Caputi 
31665602294fSDan Kimmel 
31672fdbea25SAleksandr Guzovskiy /*
31682fdbea25SAleksandr Guzovskiy  * Return a loaned arc buffer to the arc.
31692fdbea25SAleksandr Guzovskiy  */
31702fdbea25SAleksandr Guzovskiy void
31712fdbea25SAleksandr Guzovskiy arc_return_buf(arc_buf_t *buf, void *tag)
31722fdbea25SAleksandr Guzovskiy {
31732fdbea25SAleksandr Guzovskiy 	arc_buf_hdr_t *hdr = buf->b_hdr;
31742fdbea25SAleksandr Guzovskiy 
3175dcbf3bd6SGeorge Wilson 	ASSERT3P(buf->b_data, !=, NULL);
317689c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
3177e914ace2STim Schumacher 	(void) zfs_refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
3178e914ace2STim Schumacher 	(void) zfs_refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
31792fdbea25SAleksandr Guzovskiy 
31805602294fSDan Kimmel 	arc_loaned_bytes_update(-arc_buf_size(buf));
31812fdbea25SAleksandr Guzovskiy }
31822fdbea25SAleksandr Guzovskiy 
3183c242f9a0Schunli zhang - Sun Microsystems - Irvine United States /* Detach an arc_buf from a dbuf (tag) */
3184c242f9a0Schunli zhang - Sun Microsystems - Irvine United States void
3185c242f9a0Schunli zhang - Sun Microsystems - Irvine United States arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
3186c242f9a0Schunli zhang - Sun Microsystems - Irvine United States {
318789c86e32SChris Williamson 	arc_buf_hdr_t *hdr = buf->b_hdr;
3188c242f9a0Schunli zhang - Sun Microsystems - Irvine United States 
3189dcbf3bd6SGeorge Wilson 	ASSERT3P(buf->b_data, !=, NULL);
319089c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
3191e914ace2STim Schumacher 	(void) zfs_refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
3192e914ace2STim Schumacher 	(void) zfs_refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
3193c242f9a0Schunli zhang - Sun Microsystems - Irvine United States 
31945602294fSDan Kimmel 	arc_loaned_bytes_update(arc_buf_size(buf));
3195c242f9a0Schunli zhang - Sun Microsystems - Irvine United States }
3196c242f9a0Schunli zhang - Sun Microsystems - Irvine United States 
3197dcbf3bd6SGeorge Wilson static void
3198770499e1SDan Kimmel l2arc_free_abd_on_write(abd_t *abd, size_t size, arc_buf_contents_t type)
3199ea8dc4b6Seschrock {
3200dcbf3bd6SGeorge Wilson 	l2arc_data_free_t *df = kmem_alloc(sizeof (*df), KM_SLEEP);
3201ea8dc4b6Seschrock 
3202770499e1SDan Kimmel 	df->l2df_abd = abd;
3203dcbf3bd6SGeorge Wilson 	df->l2df_size = size;
3204dcbf3bd6SGeorge Wilson 	df->l2df_type = type;
3205dcbf3bd6SGeorge Wilson 	mutex_enter(&l2arc_free_on_write_mtx);
3206dcbf3bd6SGeorge Wilson 	list_insert_head(l2arc_free_on_write, df);
3207dcbf3bd6SGeorge Wilson 	mutex_exit(&l2arc_free_on_write_mtx);
3208dcbf3bd6SGeorge Wilson }
3209b24ab676SJeff Bonwick 
3210dcbf3bd6SGeorge Wilson static void
3211*eb633035STom Caputi arc_hdr_free_on_write(arc_buf_hdr_t *hdr, boolean_t free_rdata)
3212dcbf3bd6SGeorge Wilson {
3213dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
3214dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type = arc_buf_type(hdr);
3215*eb633035STom Caputi 	uint64_t size = (free_rdata) ? HDR_GET_PSIZE(hdr) : arc_hdr_size(hdr);
3216dcbf3bd6SGeorge Wilson 
3217dcbf3bd6SGeorge Wilson 	/* protected by hash lock, if in the hash table */
3218dcbf3bd6SGeorge Wilson 	if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
3219e914ace2STim Schumacher 		ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3220dcbf3bd6SGeorge Wilson 		ASSERT(state != arc_anon && state != arc_l2c_only);
3221dcbf3bd6SGeorge Wilson 
3222e914ace2STim Schumacher 		(void) zfs_refcount_remove_many(&state->arcs_esize[type],
3223dcbf3bd6SGeorge Wilson 		    size, hdr);
3224dcbf3bd6SGeorge Wilson 	}
3225e914ace2STim Schumacher 	(void) zfs_refcount_remove_many(&state->arcs_size, size, hdr);
32266de76ce2SAndriy Gapon 	if (type == ARC_BUFC_METADATA) {
32276de76ce2SAndriy Gapon 		arc_space_return(size, ARC_SPACE_META);
32286de76ce2SAndriy Gapon 	} else {
32296de76ce2SAndriy Gapon 		ASSERT(type == ARC_BUFC_DATA);
32306de76ce2SAndriy Gapon 		arc_space_return(size, ARC_SPACE_DATA);
32316de76ce2SAndriy Gapon 	}
3232dcbf3bd6SGeorge Wilson 
3233*eb633035STom Caputi 	if (free_rdata) {
3234*eb633035STom Caputi 		l2arc_free_abd_on_write(hdr->b_crypt_hdr.b_rabd, size, type);
3235*eb633035STom Caputi 	} else {
3236*eb633035STom Caputi 		l2arc_free_abd_on_write(hdr->b_l1hdr.b_pabd, size, type);
3237*eb633035STom Caputi 	}
3238dcbf3bd6SGeorge Wilson }
3239dcbf3bd6SGeorge Wilson 
3240dcbf3bd6SGeorge Wilson /*
3241dcbf3bd6SGeorge Wilson  * Share the arc_buf_t's data with the hdr. Whenever we are sharing the
3242dcbf3bd6SGeorge Wilson  * data buffer, we transfer the refcount ownership to the hdr and update
3243dcbf3bd6SGeorge Wilson  * the appropriate kstats.
3244dcbf3bd6SGeorge Wilson  */
3245dcbf3bd6SGeorge Wilson static void
3246dcbf3bd6SGeorge Wilson arc_share_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
3247dcbf3bd6SGeorge Wilson {
3248*eb633035STom Caputi 	/* LINTED */
3249dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
3250dcbf3bd6SGeorge Wilson 
32515602294fSDan Kimmel 	ASSERT(arc_can_share(hdr, buf));
3252770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3253*eb633035STom Caputi 	ASSERT(!ARC_BUF_ENCRYPTED(buf));
3254dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
32559253d63dSGeorge Wilson 
32569253d63dSGeorge Wilson 	/*
3257dcbf3bd6SGeorge Wilson 	 * Start sharing the data buffer. We transfer the
3258dcbf3bd6SGeorge Wilson 	 * refcount ownership to the hdr since it always owns
3259dcbf3bd6SGeorge Wilson 	 * the refcount whenever an arc_buf_t is shared.
32609253d63dSGeorge Wilson 	 */
3261*eb633035STom Caputi 	zfs_refcount_transfer_ownership_many(&hdr->b_l1hdr.b_state->arcs_size,
3262*eb633035STom Caputi 	    arc_hdr_size(hdr), buf, hdr);
3263770499e1SDan Kimmel 	hdr->b_l1hdr.b_pabd = abd_get_from_buf(buf->b_data, arc_buf_size(buf));
3264770499e1SDan Kimmel 	abd_take_ownership_of_buf(hdr->b_l1hdr.b_pabd,
3265770499e1SDan Kimmel 	    HDR_ISTYPE_METADATA(hdr));
3266dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
32675602294fSDan Kimmel 	buf->b_flags |= ARC_BUF_FLAG_SHARED;
3268dcbf3bd6SGeorge Wilson 
3269dcbf3bd6SGeorge Wilson 	/*
3270dcbf3bd6SGeorge Wilson 	 * Since we've transferred ownership to the hdr we need
3271dcbf3bd6SGeorge Wilson 	 * to increment its compressed and uncompressed kstats and
3272dcbf3bd6SGeorge Wilson 	 * decrement the overhead size.
3273dcbf3bd6SGeorge Wilson 	 */
3274dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
3275dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
32765602294fSDan Kimmel 	ARCSTAT_INCR(arcstat_overhead_size, -arc_buf_size(buf));
3277ea8dc4b6Seschrock }
3278ea8dc4b6Seschrock 
3279dcbf3bd6SGeorge Wilson static void
3280dcbf3bd6SGeorge Wilson arc_unshare_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
3281ea8dc4b6Seschrock {
3282*eb633035STom Caputi 	/* LINTED */
3283dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
3284dcbf3bd6SGeorge Wilson 
3285dcbf3bd6SGeorge Wilson 	ASSERT(arc_buf_is_shared(buf));
3286770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3287dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
3288ea8dc4b6Seschrock 
32899b23f181Smaybee 	/*
3290dcbf3bd6SGeorge Wilson 	 * We are no longer sharing this buffer so we need
3291dcbf3bd6SGeorge Wilson 	 * to transfer its ownership to the rightful owner.
32929b23f181Smaybee 	 */
3293*eb633035STom Caputi 	zfs_refcount_transfer_ownership_many(&hdr->b_l1hdr.b_state->arcs_size,
3294*eb633035STom Caputi 	    arc_hdr_size(hdr), hdr, buf);
3295dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
3296770499e1SDan Kimmel 	abd_release_ownership_of_buf(hdr->b_l1hdr.b_pabd);
3297770499e1SDan Kimmel 	abd_put(hdr->b_l1hdr.b_pabd);
3298770499e1SDan Kimmel 	hdr->b_l1hdr.b_pabd = NULL;
32995602294fSDan Kimmel 	buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
3300dcbf3bd6SGeorge Wilson 
3301dcbf3bd6SGeorge Wilson 	/*
3302dcbf3bd6SGeorge Wilson 	 * Since the buffer is no longer shared between
3303dcbf3bd6SGeorge Wilson 	 * the arc buf and the hdr, count it as overhead.
3304dcbf3bd6SGeorge Wilson 	 */
3305dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
3306dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
33075602294fSDan Kimmel 	ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
3308dcbf3bd6SGeorge Wilson }
3309dcbf3bd6SGeorge Wilson 
3310dcbf3bd6SGeorge Wilson /*
33115602294fSDan Kimmel  * Remove an arc_buf_t from the hdr's buf list and return the last
33125602294fSDan Kimmel  * arc_buf_t on the list. If no buffers remain on the list then return
33135602294fSDan Kimmel  * NULL.
33145602294fSDan Kimmel  */
33155602294fSDan Kimmel static arc_buf_t *
33165602294fSDan Kimmel arc_buf_remove(arc_buf_hdr_t *hdr, arc_buf_t *buf)
33175602294fSDan Kimmel {
33185602294fSDan Kimmel 	arc_buf_t **bufp = &hdr->b_l1hdr.b_buf;
33195602294fSDan Kimmel 	arc_buf_t *lastbuf = NULL;
33205602294fSDan Kimmel 
3321*eb633035STom Caputi 	ASSERT(HDR_HAS_L1HDR(hdr));
3322*eb633035STom Caputi 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
3323*eb633035STom Caputi 
33245602294fSDan Kimmel 	/*
33255602294fSDan Kimmel 	 * Remove the buf from the hdr list and locate the last
33265602294fSDan Kimmel 	 * remaining buffer on the list.
33275602294fSDan Kimmel 	 */
33285602294fSDan Kimmel 	while (*bufp != NULL) {
33295602294fSDan Kimmel 		if (*bufp == buf)
33305602294fSDan Kimmel 			*bufp = buf->b_next;
33315602294fSDan Kimmel 
33325602294fSDan Kimmel 		/*
33335602294fSDan Kimmel 		 * If we've removed a buffer in the middle of
33345602294fSDan Kimmel 		 * the list then update the lastbuf and update
33355602294fSDan Kimmel 		 * bufp.
33365602294fSDan Kimmel 		 */
33375602294fSDan Kimmel 		if (*bufp != NULL) {
33385602294fSDan Kimmel 			lastbuf = *bufp;
33395602294fSDan Kimmel 			bufp = &(*bufp)->b_next;
33405602294fSDan Kimmel 		}
33415602294fSDan Kimmel 	}
33425602294fSDan Kimmel 	buf->b_next = NULL;
33435602294fSDan Kimmel 	ASSERT3P(lastbuf, !=, buf);
33445602294fSDan Kimmel 	IMPLY(hdr->b_l1hdr.b_bufcnt > 0, lastbuf != NULL);
33455602294fSDan Kimmel 	IMPLY(hdr->b_l1hdr.b_bufcnt > 0, hdr->b_l1hdr.b_buf != NULL);
33465602294fSDan Kimmel 	IMPLY(lastbuf != NULL, ARC_BUF_LAST(lastbuf));
33475602294fSDan Kimmel 
33485602294fSDan Kimmel 	return (lastbuf);
33495602294fSDan Kimmel }
33505602294fSDan Kimmel 
33515602294fSDan Kimmel /*
33525602294fSDan Kimmel  * Free up buf->b_data and pull the arc_buf_t off of the the arc_buf_hdr_t's
33535602294fSDan Kimmel  * list and free it.
3354dcbf3bd6SGeorge Wilson  */
3355dcbf3bd6SGeorge Wilson static void
33565602294fSDan Kimmel arc_buf_destroy_impl(arc_buf_t *buf)
3357dcbf3bd6SGeorge Wilson {
3358dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = buf->b_hdr;
3359dcbf3bd6SGeorge Wilson 
3360dcbf3bd6SGeorge Wilson 	/*
33615602294fSDan Kimmel 	 * Free up the data associated with the buf but only if we're not
33625602294fSDan Kimmel 	 * sharing this with the hdr. If we are sharing it with the hdr, the
33635602294fSDan Kimmel 	 * hdr is responsible for doing the free.
3364dcbf3bd6SGeorge Wilson 	 */
3365dcbf3bd6SGeorge Wilson 	if (buf->b_data != NULL) {
3366dcbf3bd6SGeorge Wilson 		/*
3367dcbf3bd6SGeorge Wilson 		 * We're about to change the hdr's b_flags. We must either
3368dcbf3bd6SGeorge Wilson 		 * hold the hash_lock or be undiscoverable.
3369dcbf3bd6SGeorge Wilson 		 */
3370dcbf3bd6SGeorge Wilson 		ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
3371dcbf3bd6SGeorge Wilson 
3372dcbf3bd6SGeorge Wilson 		arc_cksum_verify(buf);
3373dcbf3bd6SGeorge Wilson 		arc_buf_unwatch(buf);
3374dcbf3bd6SGeorge Wilson 
33755602294fSDan Kimmel 		if (arc_buf_is_shared(buf)) {
3376dcbf3bd6SGeorge Wilson 			arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
3377dcbf3bd6SGeorge Wilson 		} else {
33785602294fSDan Kimmel 			uint64_t size = arc_buf_size(buf);
3379dcbf3bd6SGeorge Wilson 			arc_free_data_buf(hdr, buf->b_data, size, buf);
3380dcbf3bd6SGeorge Wilson 			ARCSTAT_INCR(arcstat_overhead_size, -size);
3381dcbf3bd6SGeorge Wilson 		}
3382dcbf3bd6SGeorge Wilson 		buf->b_data = NULL;
3383dcbf3bd6SGeorge Wilson 
3384dcbf3bd6SGeorge Wilson 		ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
3385dcbf3bd6SGeorge Wilson 		hdr->b_l1hdr.b_bufcnt -= 1;
3386*eb633035STom Caputi 
3387*eb633035STom Caputi 		if (ARC_BUF_ENCRYPTED(buf)) {
3388*eb633035STom Caputi 			hdr->b_crypt_hdr.b_ebufcnt -= 1;
3389*eb633035STom Caputi 
3390*eb633035STom Caputi 			/*
3391*eb633035STom Caputi 			 * If we have no more encrypted buffers and we've
3392*eb633035STom Caputi 			 * already gotten a copy of the decrypted data we can
3393*eb633035STom Caputi 			 * free b_rabd to save some space.
3394*eb633035STom Caputi 			 */
3395*eb633035STom Caputi 			if (hdr->b_crypt_hdr.b_ebufcnt == 0 &&
3396*eb633035STom Caputi 			    HDR_HAS_RABD(hdr) && hdr->b_l1hdr.b_pabd != NULL &&
3397*eb633035STom Caputi 			    !HDR_IO_IN_PROGRESS(hdr)) {
3398*eb633035STom Caputi 				arc_hdr_free_pabd(hdr, B_TRUE);
3399*eb633035STom Caputi 			}
3400*eb633035STom Caputi 		}
3401dcbf3bd6SGeorge Wilson 	}
3402dcbf3bd6SGeorge Wilson 
34035602294fSDan Kimmel 	arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
3404dcbf3bd6SGeorge Wilson 
34055602294fSDan Kimmel 	if (ARC_BUF_SHARED(buf) && !ARC_BUF_COMPRESSED(buf)) {
3406dcbf3bd6SGeorge Wilson 		/*
34075602294fSDan Kimmel 		 * If the current arc_buf_t is sharing its data buffer with the
3408770499e1SDan Kimmel 		 * hdr, then reassign the hdr's b_pabd to share it with the new
34095602294fSDan Kimmel 		 * buffer at the end of the list. The shared buffer is always
34105602294fSDan Kimmel 		 * the last one on the hdr's buffer list.
34115602294fSDan Kimmel 		 *
34125602294fSDan Kimmel 		 * There is an equivalent case for compressed bufs, but since
34135602294fSDan Kimmel 		 * they aren't guaranteed to be the last buf in the list and
34145602294fSDan Kimmel 		 * that is an exceedingly rare case, we just allow that space be
3415*eb633035STom Caputi 		 * wasted temporarily. We must also be careful not to share
3416*eb633035STom Caputi 		 * encrypted buffers, since they cannot be shared.
3417dcbf3bd6SGeorge Wilson 		 */
3418*eb633035STom Caputi 		if (lastbuf != NULL && !ARC_BUF_ENCRYPTED(lastbuf)) {
34195602294fSDan Kimmel 			/* Only one buf can be shared at once */
34205602294fSDan Kimmel 			VERIFY(!arc_buf_is_shared(lastbuf));
34215602294fSDan Kimmel 			/* hdr is uncompressed so can't have compressed buf */
34225602294fSDan Kimmel 			VERIFY(!ARC_BUF_COMPRESSED(lastbuf));
3423dcbf3bd6SGeorge Wilson 
3424770499e1SDan Kimmel 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3425*eb633035STom Caputi 			arc_hdr_free_pabd(hdr, B_FALSE);
3426dcbf3bd6SGeorge Wilson 
34275602294fSDan Kimmel 			/*
34285602294fSDan Kimmel 			 * We must setup a new shared block between the
34295602294fSDan Kimmel 			 * last buffer and the hdr. The data would have
34305602294fSDan Kimmel 			 * been allocated by the arc buf so we need to transfer
34315602294fSDan Kimmel 			 * ownership to the hdr since it's now being shared.
34325602294fSDan Kimmel 			 */
34335602294fSDan Kimmel 			arc_share_buf(hdr, lastbuf);
34345602294fSDan Kimmel 		}
34355602294fSDan Kimmel 	} else if (HDR_SHARED_DATA(hdr)) {
3436dcbf3bd6SGeorge Wilson 		/*
34375602294fSDan Kimmel 		 * Uncompressed shared buffers are always at the end
34385602294fSDan Kimmel 		 * of the list. Compressed buffers don't have the
34395602294fSDan Kimmel 		 * same requirements. This makes it hard to
34405602294fSDan Kimmel 		 * simply assert that the lastbuf is shared so
34415602294fSDan Kimmel 		 * we rely on the hdr's compression flags to determine
34425602294fSDan Kimmel 		 * if we have a compressed, shared buffer.
3443dcbf3bd6SGeorge Wilson 		 */
34445602294fSDan Kimmel 		ASSERT3P(lastbuf, !=, NULL);
34455602294fSDan Kimmel 		ASSERT(arc_buf_is_shared(lastbuf) ||
3446*eb633035STom Caputi 		    arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF);
3447dcbf3bd6SGeorge Wilson 	}
3448dcbf3bd6SGeorge Wilson 
34495602294fSDan Kimmel 	/*
34505602294fSDan Kimmel 	 * Free the checksum if we're removing the last uncompressed buf from
34515602294fSDan Kimmel 	 * this hdr.
34525602294fSDan Kimmel 	 */
34535602294fSDan Kimmel 	if (!arc_hdr_has_uncompressed_buf(hdr)) {
3454dcbf3bd6SGeorge Wilson 		arc_cksum_free(hdr);
34555602294fSDan Kimmel 	}
3456dcbf3bd6SGeorge Wilson 
3457dcbf3bd6SGeorge Wilson 	/* clean up the buf */
3458dcbf3bd6SGeorge Wilson 	buf->b_hdr = NULL;
3459dcbf3bd6SGeorge Wilson 	kmem_cache_free(buf_cache, buf);
3460dcbf3bd6SGeorge Wilson }
3461dcbf3bd6SGeorge Wilson 
3462dcbf3bd6SGeorge Wilson static void
3463*eb633035STom Caputi arc_hdr_alloc_pabd(arc_buf_hdr_t *hdr, boolean_t alloc_rdata)
3464dcbf3bd6SGeorge Wilson {
3465*eb633035STom Caputi 	uint64_t size;
3466*eb633035STom Caputi 
3467dcbf3bd6SGeorge Wilson 	ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
346889c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
3469*eb633035STom Caputi 	ASSERT(!HDR_SHARED_DATA(hdr) || alloc_rdata);
3470*eb633035STom Caputi 	IMPLY(alloc_rdata, HDR_PROTECTED(hdr));
3471ea8dc4b6Seschrock 
3472*eb633035STom Caputi 	if (alloc_rdata) {
3473*eb633035STom Caputi 		size = HDR_GET_PSIZE(hdr);
3474*eb633035STom Caputi 		ASSERT3P(hdr->b_crypt_hdr.b_rabd, ==, NULL);
3475*eb633035STom Caputi 		hdr->b_crypt_hdr.b_rabd = arc_get_data_abd(hdr, size, hdr);
3476*eb633035STom Caputi 		ASSERT3P(hdr->b_crypt_hdr.b_rabd, !=, NULL);
3477*eb633035STom Caputi 	} else {
3478*eb633035STom Caputi 		size = arc_hdr_size(hdr);
3479*eb633035STom Caputi 		ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3480*eb633035STom Caputi 		hdr->b_l1hdr.b_pabd = arc_get_data_abd(hdr, size, hdr);
3481*eb633035STom Caputi 		ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3482*eb633035STom Caputi 	}
348389c86e32SChris Williamson 
3484*eb633035STom Caputi 	ARCSTAT_INCR(arcstat_compressed_size, size);
3485dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
3486ea8dc4b6Seschrock }
3487ea8dc4b6Seschrock 
3488244781f1SPrakash Surya static void
3489*eb633035STom Caputi arc_hdr_free_pabd(arc_buf_hdr_t *hdr, boolean_t free_rdata)
3490244781f1SPrakash Surya {
3491*eb633035STom Caputi 	uint64_t size = (free_rdata) ? HDR_GET_PSIZE(hdr) : arc_hdr_size(hdr);
3492*eb633035STom Caputi 
3493dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L1HDR(hdr));
3494*eb633035STom Caputi 	ASSERT(hdr->b_l1hdr.b_pabd != NULL || HDR_HAS_RABD(hdr));
3495*eb633035STom Caputi 	IMPLY(free_rdata, HDR_HAS_RABD(hdr));
3496*eb633035STom Caputi 
3497244781f1SPrakash Surya 
3498dcbf3bd6SGeorge Wilson 	/*
3499dcbf3bd6SGeorge Wilson 	 * If the hdr is currently being written to the l2arc then
3500dcbf3bd6SGeorge Wilson 	 * we defer freeing the data by adding it to the l2arc_free_on_write
3501dcbf3bd6SGeorge Wilson 	 * list. The l2arc will free the data once it's finished
3502dcbf3bd6SGeorge Wilson 	 * writing it to the l2arc device.
3503dcbf3bd6SGeorge Wilson 	 */
3504dcbf3bd6SGeorge Wilson 	if (HDR_L2_WRITING(hdr)) {
3505*eb633035STom Caputi 		arc_hdr_free_on_write(hdr, free_rdata);
3506dcbf3bd6SGeorge Wilson 		ARCSTAT_BUMP(arcstat_l2_free_on_write);
3507*eb633035STom Caputi 	} else if (free_rdata) {
3508*eb633035STom Caputi 		arc_free_data_abd(hdr, hdr->b_crypt_hdr.b_rabd, size, hdr);
3509dcbf3bd6SGeorge Wilson 	} else {
3510770499e1SDan Kimmel 		arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
3511*eb633035STom Caputi 		    size, hdr);
3512dcbf3bd6SGeorge Wilson 	}
3513dcbf3bd6SGeorge Wilson 
3514*eb633035STom Caputi 	if (free_rdata) {
3515*eb633035STom Caputi 		hdr->b_crypt_hdr.b_rabd = NULL;
3516*eb633035STom Caputi 	} else {
3517*eb633035STom Caputi 		hdr->b_l1hdr.b_pabd = NULL;
3518*eb633035STom Caputi 	}
3519*eb633035STom Caputi 
3520*eb633035STom Caputi 	if (hdr->b_l1hdr.b_pabd == NULL && !HDR_HAS_RABD(hdr))
3521*eb633035STom Caputi 		hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
3522*eb633035STom Caputi 
3523*eb633035STom Caputi 	ARCSTAT_INCR(arcstat_compressed_size, -size);
3524dcbf3bd6SGeorge Wilson 	ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
3525dcbf3bd6SGeorge Wilson }
3526dcbf3bd6SGeorge Wilson 
3527dcbf3bd6SGeorge Wilson static arc_buf_hdr_t *
3528dcbf3bd6SGeorge Wilson arc_hdr_alloc(uint64_t spa, int32_t psize, int32_t lsize,
3529*eb633035STom Caputi     boolean_t protected, enum zio_compress compression_type,
3530*eb633035STom Caputi     arc_buf_contents_t type, boolean_t alloc_rdata)
3531dcbf3bd6SGeorge Wilson {
3532dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr;
3533dcbf3bd6SGeorge Wilson 
3534dcbf3bd6SGeorge Wilson 	VERIFY(type == ARC_BUFC_DATA || type == ARC_BUFC_METADATA);
3535*eb633035STom Caputi 	if (protected) {
3536*eb633035STom Caputi 		hdr = kmem_cache_alloc(hdr_full_crypt_cache, KM_PUSHPAGE);
3537*eb633035STom Caputi 	} else {
3538*eb633035STom Caputi 		hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
3539*eb633035STom Caputi 	}
3540dcbf3bd6SGeorge Wilson 	ASSERT(HDR_EMPTY(hdr));
3541dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3542dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_thawed, ==, NULL);
3543dcbf3bd6SGeorge Wilson 	HDR_SET_PSIZE(hdr, psize);
3544dcbf3bd6SGeorge Wilson 	HDR_SET_LSIZE(hdr, lsize);
3545dcbf3bd6SGeorge Wilson 	hdr->b_spa = spa;
3546dcbf3bd6SGeorge Wilson 	hdr->b_type = type;
3547dcbf3bd6SGeorge Wilson 	hdr->b_flags = 0;
3548dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(hdr, arc_bufc_to_flags(type) | ARC_FLAG_HAS_L1HDR);
35495602294fSDan Kimmel 	arc_hdr_set_compress(hdr, compression_type);
3550*eb633035STom Caputi 	if (protected)
3551*eb633035STom Caputi 		arc_hdr_set_flags(hdr, ARC_FLAG_PROTECTED);
3552dcbf3bd6SGeorge Wilson 
3553dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_state = arc_anon;
3554dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_arc_access = 0;
3555dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_bufcnt = 0;
3556dcbf3bd6SGeorge Wilson 	hdr->b_l1hdr.b_buf = NULL;
3557dcbf3bd6SGeorge Wilson 
3558dcbf3bd6SGeorge Wilson 	/*
3559dcbf3bd6SGeorge Wilson 	 * Allocate the hdr's buffer. This will contain either
3560dcbf3bd6SGeorge Wilson 	 * the compressed or uncompressed data depending on the block
3561dcbf3bd6SGeorge Wilson 	 * it references and compressed arc enablement.
3562dcbf3bd6SGeorge Wilson 	 */
3563*eb633035STom Caputi 	arc_hdr_alloc_pabd(hdr, alloc_rdata);
3564e914ace2STim Schumacher 	ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3565dcbf3bd6SGeorge Wilson 
3566dcbf3bd6SGeorge Wilson 	return (hdr);
3567244781f1SPrakash Surya }
3568244781f1SPrakash Surya 
3569fa94a07fSbrendan /*
3570dcbf3bd6SGeorge Wilson  * Transition between the two allocation states for the arc_buf_hdr struct.
3571dcbf3bd6SGeorge Wilson  * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
3572dcbf3bd6SGeorge Wilson  * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
3573dcbf3bd6SGeorge Wilson  * version is used when a cache buffer is only in the L2ARC in order to reduce
3574dcbf3bd6SGeorge Wilson  * memory usage.
3575fa94a07fSbrendan  */
3576dcbf3bd6SGeorge Wilson static arc_buf_hdr_t *
3577dcbf3bd6SGeorge Wilson arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
3578fa94a07fSbrendan {
3579dcbf3bd6SGeorge Wilson 	ASSERT(HDR_HAS_L2HDR(hdr));
3580dcbf3bd6SGeorge Wilson 
3581dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *nhdr;
3582dcbf3bd6SGeorge Wilson 	l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3583dcbf3bd6SGeorge Wilson 
3584dcbf3bd6SGeorge Wilson 	ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
3585dcbf3bd6SGeorge Wilson 	    (old == hdr_l2only_cache && new == hdr_full_cache));
3586dcbf3bd6SGeorge Wilson 
3587*eb633035STom Caputi 	/*
3588*eb633035STom Caputi 	 * if the caller wanted a new full header and the header is to be
3589*eb633035STom Caputi 	 * encrypted we will actually allocate the header from the full crypt
3590*eb633035STom Caputi 	 * cache instead. The same applies to freeing from the old cache.
3591*eb633035STom Caputi 	 */
3592*eb633035STom Caputi 	if (HDR_PROTECTED(hdr) && new == hdr_full_cache)
3593*eb633035STom Caputi 		new = hdr_full_crypt_cache;
3594*eb633035STom Caputi 	if (HDR_PROTECTED(hdr) && old == hdr_full_cache)
3595*eb633035STom Caputi 		old = hdr_full_crypt_cache;
3596*eb633035STom Caputi 
3597dcbf3bd6SGeorge Wilson 	nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
3598dcbf3bd6SGeorge Wilson 
3599dcbf3bd6SGeorge Wilson 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
3600dcbf3bd6SGeorge Wilson 	buf_hash_remove(hdr);
3601dcbf3bd6SGeorge Wilson 
3602dcbf3bd6SGeorge Wilson 	bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
3603dcbf3bd6SGeorge Wilson 
3604*eb633035STom Caputi 	if (new == hdr_full_cache || new == hdr_full_crypt_cache) {
3605dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(nhdr, ARC_FLAG_HAS_L1HDR);
3606dcbf3bd6SGeorge Wilson 		/*
3607dcbf3bd6SGeorge Wilson 		 * arc_access and arc_change_state need to be aware that a
3608dcbf3bd6SGeorge Wilson 		 * header has just come out of L2ARC, so we set its state to
3609dcbf3bd6SGeorge Wilson 		 * l2c_only even though it's about to change.
3610dcbf3bd6SGeorge Wilson 		 */
3611dcbf3bd6SGeorge Wilson 		nhdr->b_l1hdr.b_state = arc_l2c_only;
3612dcbf3bd6SGeorge Wilson 
3613dcbf3bd6SGeorge Wilson 		/* Verify previous threads set to NULL before freeing */
3614770499e1SDan Kimmel 		ASSERT3P(nhdr->b_l1hdr.b_pabd, ==, NULL);
3615*eb633035STom Caputi 		ASSERT(!HDR_HAS_RABD(hdr));
3616dcbf3bd6SGeorge Wilson 	} else {
3617dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3618dcbf3bd6SGeorge Wilson 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
3619dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3620dcbf3bd6SGeorge Wilson 
3621dcbf3bd6SGeorge Wilson 		/*
3622dcbf3bd6SGeorge Wilson 		 * If we've reached here, We must have been called from
3623dcbf3bd6SGeorge Wilson 		 * arc_evict_hdr(), as such we should have already been
3624dcbf3bd6SGeorge Wilson 		 * removed from any ghost list we were previously on
3625dcbf3bd6SGeorge Wilson 		 * (which protects us from racing with arc_evict_state),
3626dcbf3bd6SGeorge Wilson 		 * thus no locking is needed during this check.
3627dcbf3bd6SGeorge Wilson 		 */
3628dcbf3bd6SGeorge Wilson 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3629cd1c8b85SMatthew Ahrens 
3630dcbf3bd6SGeorge Wilson 		/*
3631dcbf3bd6SGeorge Wilson 		 * A buffer must not be moved into the arc_l2c_only
3632dcbf3bd6SGeorge Wilson 		 * state if it's not finished being written out to the
3633770499e1SDan Kimmel 		 * l2arc device. Otherwise, the b_l1hdr.b_pabd field
3634dcbf3bd6SGeorge Wilson 		 * might try to be accessed, even though it was removed.
3635dcbf3bd6SGeorge Wilson 		 */
3636dcbf3bd6SGeorge Wilson 		VERIFY(!HDR_L2_WRITING(hdr));
3637770499e1SDan Kimmel 		VERIFY3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3638*eb633035STom Caputi 		ASSERT(!HDR_HAS_RABD(hdr));
3639fa94a07fSbrendan 
3640dcbf3bd6SGeorge Wilson #ifdef ZFS_DEBUG
3641dcbf3bd6SGeorge Wilson 		if (hdr->b_l1hdr.b_thawed != NULL) {
3642dcbf3bd6SGeorge Wilson 			kmem_free(hdr->b_l1hdr.b_thawed, 1);
3643dcbf3bd6SGeorge Wilson 			hdr->b_l1hdr.b_thawed = NULL;
3644dcbf3bd6SGeorge Wilson 		}
3645dcbf3bd6SGeorge Wilson #endif
3646244781f1SPrakash Surya 
3647dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(nhdr, ARC_FLAG_HAS_L1HDR);
3648dcbf3bd6SGeorge Wilson 	}
3649244781f1SPrakash Surya 	/*
3650dcbf3bd6SGeorge Wilson 	 * The header has been reallocated so we need to re-insert it into any
3651dcbf3bd6SGeorge Wilson 	 * lists it was on.
3652244781f1SPrakash Surya 	 */
3653dcbf3bd6SGeorge Wilson 	(void) buf_hash_insert(nhdr, NULL);
3654244781f1SPrakash Surya 
3655dcbf3bd6SGeorge Wilson 	ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
3656dcbf3bd6SGeorge Wilson 
3657dcbf3bd6SGeorge Wilson 	mutex_enter(&dev->l2ad_mtx);
3658244781f1SPrakash Surya 
3659244781f1SPrakash Surya 	/*
3660dcbf3bd6SGeorge Wilson 	 * We must place the realloc'ed header back into the list at
3661dcbf3bd6SGeorge Wilson 	 * the same spot. Otherwise, if it's placed earlier in the list,
3662dcbf3bd6SGeorge Wilson 	 * l2arc_write_buffers() could find it during the function's
3663dcbf3bd6SGeorge Wilson 	 * write phase, and try to write it out to the l2arc.
3664244781f1SPrakash Surya 	 */
3665dcbf3bd6SGeorge Wilson 	list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
3666dcbf3bd6SGeorge Wilson 	list_remove(&dev->l2ad_buflist, hdr);
3667dcbf3bd6SGeorge Wilson 
3668dcbf3bd6SGeorge Wilson 	mutex_exit(&dev->l2ad_mtx);
3669244781f1SPrakash Surya 
3670244781f1SPrakash Surya 	/*
3671dcbf3bd6SGeorge Wilson 	 * Since we're using the pointer address as the tag when
3672dcbf3bd6SGeorge Wilson 	 * incrementing and decrementing the l2ad_alloc refcount, we
3673dcbf3bd6SGeorge Wilson 	 * must remove the old pointer (that we're about to destroy) and
3674dcbf3bd6SGeorge Wilson 	 * add the new pointer to the refcount. Otherwise we'd remove
3675dcbf3bd6SGeorge Wilson 	 * the wrong pointer address when calling arc_hdr_destroy() later.
3676244781f1SPrakash Surya 	 */
3677244781f1SPrakash Surya 
3678e914ace2STim Schumacher 	(void) zfs_refcount_remove_many(&dev->l2ad_alloc, arc_hdr_size(hdr),
3679e914ace2STim Schumacher 	    hdr);
3680e914ace2STim Schumacher 	(void) zfs_refcount_add_many(&dev->l2ad_alloc, arc_hdr_size(nhdr),
3681e914ace2STim Schumacher 	    nhdr);
3682244781f1SPrakash Surya 
3683dcbf3bd6SGeorge Wilson 	buf_discard_identity(hdr);
3684dcbf3bd6SGeorge Wilson 	kmem_cache_free(old, hdr);
3685244781f1SPrakash Surya 
3686dcbf3bd6SGeorge Wilson 	return (nhdr);
3687244781f1SPrakash Surya }
3688244781f1SPrakash Surya 
3689*eb633035STom Caputi /*
3690*eb633035STom Caputi  * This function allows an L1 header to be reallocated as a crypt
3691*eb633035STom Caputi  * header and vice versa. If we are going to a crypt header, the
3692*eb633035STom Caputi  * new fields will be zeroed out.
3693*eb633035STom Caputi  */
3694*eb633035STom Caputi static arc_buf_hdr_t *
3695*eb633035STom Caputi arc_hdr_realloc_crypt(arc_buf_hdr_t *hdr, boolean_t need_crypt)
3696*eb633035STom Caputi {
3697*eb633035STom Caputi 	arc_buf_hdr_t *nhdr;
3698*eb633035STom Caputi 	arc_buf_t *buf;
3699*eb633035STom Caputi 	kmem_cache_t *ncache, *ocache;
3700*eb633035STom Caputi 
3701*eb633035STom Caputi 	ASSERT(HDR_HAS_L1HDR(hdr));
3702*eb633035STom Caputi 	ASSERT3U(!!HDR_PROTECTED(hdr), !=, need_crypt);
3703*eb633035STom Caputi 	ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
3704*eb633035STom Caputi 	ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3705*eb633035STom Caputi 	ASSERT(!list_link_active(&hdr->b_l2hdr.b_l2node));
3706*eb633035STom Caputi 	ASSERT3P(hdr->b_hash_next, ==, NULL);
3707*eb633035STom Caputi 
3708*eb633035STom Caputi 	if (need_crypt) {
3709*eb633035STom Caputi 		ncache = hdr_full_crypt_cache;
3710*eb633035STom Caputi 		ocache = hdr_full_cache;
3711*eb633035STom Caputi 	} else {
3712*eb633035STom Caputi 		ncache = hdr_full_cache;
3713*eb633035STom Caputi 		ocache = hdr_full_crypt_cache;
3714*eb633035STom Caputi 	}
3715*eb633035STom Caputi 
3716*eb633035STom Caputi 	nhdr = kmem_cache_alloc(ncache, KM_PUSHPAGE);
3717*eb633035STom Caputi 
3718*eb633035STom Caputi 	/*
3719*eb633035STom Caputi 	 * Copy all members that aren't locks or condvars to the new header.
3720*eb633035STom Caputi 	 * No lists are pointing to us (as we asserted above), so we don't
3721*eb633035STom Caputi 	 * need to worry about the list nodes.
3722*eb633035STom Caputi 	 */
3723*eb633035STom Caputi 	nhdr->b_dva = hdr->b_dva;
3724*eb633035STom Caputi 	nhdr->b_birth = hdr->b_birth;
3725*eb633035STom Caputi 	nhdr->b_type = hdr->b_type;
3726*eb633035STom Caputi 	nhdr->b_flags = hdr->b_flags;
3727*eb633035STom Caputi 	nhdr->b_psize = hdr->b_psize;
3728*eb633035STom Caputi 	nhdr->b_lsize = hdr->b_lsize;
3729*eb633035STom Caputi 	nhdr->b_spa = hdr->b_spa;
3730*eb633035STom Caputi 	nhdr->b_l2hdr.b_dev = hdr->b_l2hdr.b_dev;
3731*eb633035STom Caputi 	nhdr->b_l2hdr.b_daddr = hdr->b_l2hdr.b_daddr;
3732*eb633035STom Caputi 	nhdr->b_l1hdr.b_freeze_cksum = hdr->b_l1hdr.b_freeze_cksum;
3733*eb633035STom Caputi 	nhdr->b_l1hdr.b_bufcnt = hdr->b_l1hdr.b_bufcnt;
3734*eb633035STom Caputi 	nhdr->b_l1hdr.b_byteswap = hdr->b_l1hdr.b_byteswap;
3735*eb633035STom Caputi 	nhdr->b_l1hdr.b_state = hdr->b_l1hdr.b_state;
3736*eb633035STom Caputi 	nhdr->b_l1hdr.b_arc_access = hdr->b_l1hdr.b_arc_access;
3737*eb633035STom Caputi 	nhdr->b_l1hdr.b_acb = hdr->b_l1hdr.b_acb;
3738*eb633035STom Caputi 	nhdr->b_l1hdr.b_pabd = hdr->b_l1hdr.b_pabd;
3739*eb633035STom Caputi #ifdef ZFS_DEBUG
3740*eb633035STom Caputi 	if (hdr->b_l1hdr.b_thawed != NULL) {
3741*eb633035STom Caputi 		nhdr->b_l1hdr.b_thawed = hdr->b_l1hdr.b_thawed;
3742*eb633035STom Caputi 		hdr->b_l1hdr.b_thawed = NULL;
3743*eb633035STom Caputi 	}
3744*eb633035STom Caputi #endif
3745*eb633035STom Caputi 
3746*eb633035STom Caputi 	/*
3747*eb633035STom Caputi 	 * This refcount_add() exists only to ensure that the individual
3748*eb633035STom Caputi 	 * arc buffers always point to a header that is referenced, avoiding
3749*eb633035STom Caputi 	 * a small race condition that could trigger ASSERTs.
3750*eb633035STom Caputi 	 */
3751*eb633035STom Caputi 	(void) zfs_refcount_add(&nhdr->b_l1hdr.b_refcnt, FTAG);
3752*eb633035STom Caputi 	nhdr->b_l1hdr.b_buf = hdr->b_l1hdr.b_buf;
3753*eb633035STom Caputi 	for (buf = nhdr->b_l1hdr.b_buf; buf != NULL; buf = buf->b_next) {
3754*eb633035STom Caputi 		mutex_enter(&buf->b_evict_lock);
3755*eb633035STom Caputi 		buf->b_hdr = nhdr;
3756*eb633035STom Caputi 		mutex_exit(&buf->b_evict_lock);
3757*eb633035STom Caputi 	}
3758*eb633035STom Caputi 	zfs_refcount_transfer(&nhdr->b_l1hdr.b_refcnt, &hdr->b_l1hdr.b_refcnt);
3759*eb633035STom Caputi 	(void) zfs_refcount_remove(&nhdr->b_l1hdr.b_refcnt, FTAG);
3760*eb633035STom Caputi 	ASSERT0(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt));
3761*eb633035STom Caputi 
3762*eb633035STom Caputi 	if (need_crypt) {
3763*eb633035STom Caputi 		arc_hdr_set_flags(nhdr, ARC_FLAG_PROTECTED);
3764*eb633035STom Caputi 	} else {
3765*eb633035STom Caputi 		arc_hdr_clear_flags(nhdr, ARC_FLAG_PROTECTED);
3766*eb633035STom Caputi 	}
3767*eb633035STom Caputi 
3768*eb633035STom Caputi 	/* unset all members of the original hdr */
3769*eb633035STom Caputi 	bzero(&hdr->b_dva, sizeof (dva_t));
3770*eb633035STom Caputi 	hdr->b_birth = 0;
3771*eb633035STom Caputi 	hdr->b_type = ARC_BUFC_INVALID;
3772*eb633035STom Caputi 	hdr->b_flags = 0;
3773*eb633035STom Caputi 	hdr->b_psize = 0;
3774*eb633035STom Caputi 	hdr->b_lsize = 0;
3775*eb633035STom Caputi 	hdr->b_spa = 0;
3776*eb633035STom Caputi 	hdr->b_l2hdr.b_dev = NULL;
3777*eb633035STom Caputi 	hdr->b_l2hdr.b_daddr = 0;
3778*eb633035STom Caputi 	hdr->b_l1hdr.b_freeze_cksum = NULL;
3779*eb633035STom Caputi 	hdr->b_l1hdr.b_buf = NULL;
3780*eb633035STom Caputi 	hdr->b_l1hdr.b_bufcnt = 0;
3781*eb633035STom Caputi 	hdr->b_l1hdr.b_byteswap = 0;
3782*eb633035STom Caputi 	hdr->b_l1hdr.b_state = NULL;
3783*eb633035STom Caputi 	hdr->b_l1hdr.b_arc_access = 0;
3784*eb633035STom Caputi 	hdr->b_l1hdr.b_acb = NULL;
3785*eb633035STom Caputi 	hdr->b_l1hdr.b_pabd = NULL;
3786*eb633035STom Caputi 
3787*eb633035STom Caputi 	if (ocache == hdr_full_crypt_cache) {
3788*eb633035STom Caputi 		ASSERT(!HDR_HAS_RABD(hdr));
3789*eb633035STom Caputi 		hdr->b_crypt_hdr.b_ot = DMU_OT_NONE;
3790*eb633035STom Caputi 		hdr->b_crypt_hdr.b_ebufcnt = 0;
3791*eb633035STom Caputi 		hdr->b_crypt_hdr.b_dsobj = 0;
3792*eb633035STom Caputi 		bzero(hdr->b_crypt_hdr.b_salt, ZIO_DATA_SALT_LEN);
3793*eb633035STom Caputi 		bzero(hdr->b_crypt_hdr.b_iv, ZIO_DATA_IV_LEN);
3794*eb633035STom Caputi 		bzero(hdr->b_crypt_hdr.b_mac, ZIO_DATA_MAC_LEN);
3795*eb633035STom Caputi 	}
3796*eb633035STom Caputi 
3797*eb633035STom Caputi 	buf_discard_identity(hdr);
3798*eb633035STom Caputi 	kmem_cache_free(ocache, hdr);
3799*eb633035STom Caputi 
3800*eb633035STom Caputi 	return (nhdr);
3801*eb633035STom Caputi }
3802*eb633035STom Caputi 
3803*eb633035STom Caputi /*
3804*eb633035STom Caputi  * This function is used by the send / receive code to convert a newly
3805*eb633035STom Caputi  * allocated arc_buf_t to one that is suitable for a raw encrypted write. It
3806*eb633035STom Caputi  * is also used to allow the root objset block to be uupdated without altering
3807*eb633035STom Caputi  * its embedded MACs. Both block types will always be uncompressed so we do not
3808*eb633035STom Caputi  * have to worry about compression type or psize.
3809*eb633035STom Caputi  */
3810*eb633035STom Caputi void
3811*eb633035STom Caputi arc_convert_to_raw(arc_buf_t *buf, uint64_t dsobj, boolean_t byteorder,
3812*eb633035STom Caputi     dmu_object_type_t ot, const uint8_t *salt, const uint8_t *iv,
3813*eb633035STom Caputi     const uint8_t *mac)
3814*eb633035STom Caputi {
3815*eb633035STom Caputi 	arc_buf_hdr_t *hdr = buf->b_hdr;
3816*eb633035STom Caputi 
3817*eb633035STom Caputi 	ASSERT(ot == DMU_OT_DNODE || ot == DMU_OT_OBJSET);
3818*eb633035STom Caputi 	ASSERT(HDR_HAS_L1HDR(hdr));
3819*eb633035STom Caputi 	ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
3820*eb633035STom Caputi 
3821*eb633035STom Caputi 	buf->b_flags |= (ARC_BUF_FLAG_COMPRESSED | ARC_BUF_FLAG_ENCRYPTED);
3822*eb633035STom Caputi 	if (!HDR_PROTECTED(hdr))
3823*eb633035STom Caputi 		hdr = arc_hdr_realloc_crypt(hdr, B_TRUE);
3824*eb633035STom Caputi 	hdr->b_crypt_hdr.b_dsobj = dsobj;
3825*eb633035STom Caputi 	hdr->b_crypt_hdr.b_ot = ot;
3826*eb633035STom Caputi 	hdr->b_l1hdr.b_byteswap = (byteorder == ZFS_HOST_BYTEORDER) ?
3827*eb633035STom Caputi 	    DMU_BSWAP_NUMFUNCS : DMU_OT_BYTESWAP(ot);
3828*eb633035STom Caputi 	if (!arc_hdr_has_uncompressed_buf(hdr))
3829*eb633035STom Caputi 		arc_cksum_free(hdr);
3830*eb633035STom Caputi 
3831*eb633035STom Caputi 	if (salt != NULL)
3832*eb633035STom Caputi 		bcopy(salt, hdr->b_crypt_hdr.b_salt, ZIO_DATA_SALT_LEN);
3833*eb633035STom Caputi 	if (iv != NULL)
3834*eb633035STom Caputi 		bcopy(iv, hdr->b_crypt_hdr.b_iv, ZIO_DATA_IV_LEN);
3835*eb633035STom Caputi 	if (mac != NULL)
3836*eb633035STom Caputi 		bcopy(mac, hdr->b_crypt_hdr.b_mac, ZIO_DATA_MAC_LEN);
3837*eb633035STom Caputi }
3838*eb633035STom Caputi 
3839bbfa8ea8SMatthew Ahrens /*
3840dcbf3bd6SGeorge Wilson  * Allocate a new arc_buf_hdr_t and arc_buf_t and return the buf to the caller.
3841dcbf3bd6SGeorge Wilson  * The buf is returned thawed since we expect the consumer to modify it.
3842bbfa8ea8SMatthew Ahrens  */
3843dcbf3bd6SGeorge Wilson arc_buf_t *
38445602294fSDan Kimmel arc_alloc_buf(spa_t *spa, void *tag, arc_buf_contents_t type, int32_t size)
3845ea8dc4b6Seschrock {
3846dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), size, size,
3847*eb633035STom Caputi 	    B_FALSE, ZIO_COMPRESS_OFF, type, B_FALSE);
3848dcbf3bd6SGeorge Wilson 	ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
38495602294fSDan Kimmel 
38505602294fSDan Kimmel 	arc_buf_t *buf = NULL;
3851*eb633035STom Caputi 	VERIFY0(arc_buf_alloc_impl(hdr, spa, NULL, tag, B_FALSE, B_FALSE,
3852*eb633035STom Caputi 	    B_FALSE, B_FALSE, &buf));
3853dcbf3bd6SGeorge Wilson 	arc_buf_thaw(buf);
38545602294fSDan Kimmel 
38555602294fSDan Kimmel 	return (buf);
38565602294fSDan Kimmel }
38575602294fSDan Kimmel 
38585602294fSDan Kimmel /*
38595602294fSDan Kimmel  * Allocate a compressed buf in the same manner as arc_alloc_buf. Don't use this
38605602294fSDan Kimmel  * for bufs containing metadata.
38615602294fSDan Kimmel  */
38625602294fSDan Kimmel arc_buf_t *
38635602294fSDan Kimmel arc_alloc_compressed_buf(spa_t *spa, void *tag, uint64_t psize, uint64_t lsize,
38645602294fSDan Kimmel     enum zio_compress compression_type)
38655602294fSDan Kimmel {
38665602294fSDan Kimmel 	ASSERT3U(lsize, >, 0);
38675602294fSDan Kimmel 	ASSERT3U(lsize, >=, psize);
3868*eb633035STom Caputi 	ASSERT3U(compression_type, >, ZIO_COMPRESS_OFF);
3869*eb633035STom Caputi 	ASSERT3U(compression_type, <, ZIO_COMPRESS_FUNCTIONS);
3870*eb633035STom Caputi 
3871*eb633035STom Caputi 	arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
3872*eb633035STom Caputi 	    B_FALSE, compression_type, ARC_BUFC_DATA, B_FALSE);
3873*eb633035STom Caputi 	ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
3874*eb633035STom Caputi 
3875*eb633035STom Caputi 	arc_buf_t *buf = NULL;
3876*eb633035STom Caputi 	VERIFY0(arc_buf_alloc_impl(hdr, spa, NULL, tag, B_FALSE,
3877*eb633035STom Caputi 	    B_TRUE, B_FALSE, B_FALSE, &buf));
3878*eb633035STom Caputi 	arc_buf_thaw(buf);
3879*eb633035STom Caputi 	ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3880*eb633035STom Caputi 
3881*eb633035STom Caputi 	if (!arc_buf_is_shared(buf)) {
3882*eb633035STom Caputi 		/*
3883*eb633035STom Caputi 		 * To ensure that the hdr has the correct data in it if we call
3884*eb633035STom Caputi 		 * arc_untransform() on this buf before it's been written to
3885*eb633035STom Caputi 		 * disk, it's easiest if we just set up sharing between the
3886*eb633035STom Caputi 		 * buf and the hdr.
3887*eb633035STom Caputi 		 */
3888*eb633035STom Caputi 		ASSERT(!abd_is_linear(hdr->b_l1hdr.b_pabd));
3889*eb633035STom Caputi 		arc_hdr_free_pabd(hdr, B_FALSE);
3890*eb633035STom Caputi 		arc_share_buf(hdr, buf);
3891*eb633035STom Caputi 	}
3892*eb633035STom Caputi 
3893*eb633035STom Caputi 	return (buf);
3894*eb633035STom Caputi }
3895*eb633035STom Caputi 
3896*eb633035STom Caputi arc_buf_t *
3897*eb633035STom Caputi arc_alloc_raw_buf(spa_t *spa, void *tag, uint64_t dsobj, boolean_t byteorder,
3898*eb633035STom Caputi     const uint8_t *salt, const uint8_t *iv, const uint8_t *mac,
3899*eb633035STom Caputi     dmu_object_type_t ot, uint64_t psize, uint64_t lsize,
3900*eb633035STom Caputi     enum zio_compress compression_type)
3901*eb633035STom Caputi {
3902*eb633035STom Caputi 	arc_buf_hdr_t *hdr;
3903*eb633035STom Caputi 	arc_buf_t *buf;
3904*eb633035STom Caputi 	arc_buf_contents_t type = DMU_OT_IS_METADATA(ot) ?
3905*eb633035STom Caputi 	    ARC_BUFC_METADATA : ARC_BUFC_DATA;
3906*eb633035STom Caputi 
3907*eb633035STom Caputi 	ASSERT3U(lsize, >, 0);
3908*eb633035STom Caputi 	ASSERT3U(lsize, >=, psize);
3909*eb633035STom Caputi 	ASSERT3U(compression_type, >=, ZIO_COMPRESS_OFF);
3910*eb633035STom Caputi 	ASSERT3U(compression_type, <, ZIO_COMPRESS_FUNCTIONS);
39115602294fSDan Kimmel 
3912*eb633035STom Caputi 	hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize, B_TRUE,
3913*eb633035STom Caputi 	    compression_type, type, B_TRUE);
39145602294fSDan Kimmel 	ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
39155602294fSDan Kimmel 
3916*eb633035STom Caputi 	hdr->b_crypt_hdr.b_dsobj = dsobj;
3917*eb633035STom Caputi 	hdr->b_crypt_hdr.b_ot = ot;
3918*eb633035STom Caputi 	hdr->b_l1hdr.b_byteswap = (byteorder == ZFS_HOST_BYTEORDER) ?
3919*eb633035STom Caputi 	    DMU_BSWAP_NUMFUNCS : DMU_OT_BYTESWAP(ot);
3920*eb633035STom Caputi 	bcopy(salt, hdr->b_crypt_hdr.b_salt, ZIO_DATA_SALT_LEN);
3921*eb633035STom Caputi 	bcopy(iv, hdr->b_crypt_hdr.b_iv, ZIO_DATA_IV_LEN);
3922*eb633035STom Caputi 	bcopy(mac, hdr->b_crypt_hdr.b_mac, ZIO_DATA_MAC_LEN);
3923*eb633035STom Caputi 
3924*eb633035STom Caputi 	/*
3925*eb633035STom Caputi 	 * This buffer will be considered encrypted even if the ot is not an
3926*eb633035STom Caputi 	 * encrypted type. It will become authenticated instead in
3927*eb633035STom Caputi 	 * arc_write_ready().
3928*eb633035STom Caputi 	 */
3929*eb633035STom Caputi 	buf = NULL;
3930*eb633035STom Caputi 	VERIFY0(arc_buf_alloc_impl(hdr, spa, NULL, tag, B_TRUE, B_TRUE,
3931*eb633035STom Caputi 	    B_FALSE, B_FALSE, &buf));
39325602294fSDan Kimmel 	arc_buf_thaw(buf);
39335602294fSDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
39345602294fSDan Kimmel 
3935dcbf3bd6SGeorge Wilson 	return (buf);
3936ea8dc4b6Seschrock }
3937ea8dc4b6Seschrock 
3938a52fc310SPrakash Surya static void
3939a52fc310SPrakash Surya arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
3940a52fc310SPrakash Surya {
3941a52fc310SPrakash Surya 	l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
3942a52fc310SPrakash Surya 	l2arc_dev_t *dev = l2hdr->b_dev;
39439740f25fSSerapheim Dimitropoulos 	uint64_t psize = HDR_GET_PSIZE(hdr);
39449740f25fSSerapheim Dimitropoulos 	uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev, psize);
3945a52fc310SPrakash Surya 
3946a52fc310SPrakash Surya 	ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
3947a52fc310SPrakash Surya 	ASSERT(HDR_HAS_L2HDR(hdr));
3948a52fc310SPrakash Surya 
3949a52fc310SPrakash Surya 	list_remove(&dev->l2ad_buflist, hdr);
3950a52fc310SPrakash Surya 
395116a7e5acSAndriy Gapon 	ARCSTAT_INCR(arcstat_l2_psize, -psize);
395216a7e5acSAndriy Gapon 	ARCSTAT_INCR(arcstat_l2_lsize, -HDR_GET_LSIZE(hdr));
3953a52fc310SPrakash Surya 
39549740f25fSSerapheim Dimitropoulos 	vdev_space_update(dev->l2ad_vdev, -asize, 0, 0);
3955a52fc310SPrakash Surya 
39569740f25fSSerapheim Dimitropoulos 	(void) zfs_refcount_remove_many(&dev->l2ad_alloc, arc_hdr_size(hdr),
39579740f25fSSerapheim Dimitropoulos 	    hdr);
3958dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
3959a52fc310SPrakash Surya }
3960a52fc310SPrakash Surya 
3961fa9e4066Sahrens static void
3962ea8dc4b6Seschrock arc_hdr_destroy(arc_buf_hdr_t *hdr)
3963fa9e4066Sahrens {
396489c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr)) {
396589c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_buf == NULL ||
3966dcbf3bd6SGeorge Wilson 		    hdr->b_l1hdr.b_bufcnt > 0);
3967e914ace2STim Schumacher 		ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
396889c86e32SChris Williamson 		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
396989c86e32SChris Williamson 	}
3970ea8dc4b6Seschrock 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
397189c86e32SChris Williamson 	ASSERT(!HDR_IN_HASH_TABLE(hdr));
397289c86e32SChris Williamson 
3973dcbf3bd6SGeorge Wilson 	if (!HDR_EMPTY(hdr))
3974dcbf3bd6SGeorge Wilson 		buf_discard_identity(hdr);
3975dcbf3bd6SGeorge Wilson 
397689c86e32SChris Williamson 	if (HDR_HAS_L2HDR(hdr)) {
3977a52fc310SPrakash Surya 		l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3978a52fc310SPrakash Surya 		boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
3979b24ab676SJeff Bonwick 
3980a52fc310SPrakash Surya 		if (!buflist_held)
3981a52fc310SPrakash Surya 			mutex_enter(&dev->l2ad_mtx);
398289c86e32SChris Williamson 
3983244781f1SPrakash Surya 		/*
3984a52fc310SPrakash Surya 		 * Even though we checked this conditional above, we
3985a52fc310SPrakash Surya 		 * need to check this again now that we have the
3986a52fc310SPrakash Surya 		 * l2ad_mtx. This is because we could be racing with
3987a52fc310SPrakash Surya 		 * another thread calling l2arc_evict() which might have
3988a52fc310SPrakash Surya 		 * destroyed this header's L2 portion as we were waiting
3989a52fc310SPrakash Surya 		 * to acquire the l2ad_mtx. If that happens, we don't
3990a52fc310SPrakash Surya 		 * want to re-destroy the header's L2 portion.
3991244781f1SPrakash Surya 		 */
3992a52fc310SPrakash Surya 		if (HDR_HAS_L2HDR(hdr))
3993a52fc310SPrakash Surya 			arc_hdr_l2hdr_destroy(hdr);
3994b24ab676SJeff Bonwick 
3995b24ab676SJeff Bonwick 		if (!buflist_held)
3996a52fc310SPrakash Surya 			mutex_exit(&dev->l2ad_mtx);
3997fa94a07fSbrendan 	}
3998fa94a07fSbrendan 
3999dcbf3bd6SGeorge Wilson 	if (HDR_HAS_L1HDR(hdr)) {
4000dcbf3bd6SGeorge Wilson 		arc_cksum_free(hdr);
400189c86e32SChris Williamson 
4002dcbf3bd6SGeorge Wilson 		while (hdr->b_l1hdr.b_buf != NULL)
40035602294fSDan Kimmel 			arc_buf_destroy_impl(hdr->b_l1hdr.b_buf);
400489c86e32SChris Williamson 
400589c86e32SChris Williamson #ifdef ZFS_DEBUG
400689c86e32SChris Williamson 		if (hdr->b_l1hdr.b_thawed != NULL) {
400789c86e32SChris Williamson 			kmem_free(hdr->b_l1hdr.b_thawed, 1);
400889c86e32SChris Williamson 			hdr->b_l1hdr.b_thawed = NULL;
400989c86e32SChris Williamson 		}
401089c86e32SChris Williamson #endif
4011dcbf3bd6SGeorge Wilson 
4012770499e1SDan Kimmel 		if (hdr->b_l1hdr.b_pabd != NULL) {
4013*eb633035STom Caputi 			arc_hdr_free_pabd(hdr, B_FALSE);
4014dcbf3bd6SGeorge Wilson 		}
4015*eb633035STom Caputi 
4016*eb633035STom Caputi 		if (HDR_HAS_RABD(hdr))
4017*eb633035STom Caputi 			arc_hdr_free_pabd(hdr, B_TRUE);
40183f9d6ad7SLin Ling 	}
4019ea8dc4b6Seschrock 
4020fa9e4066Sahrens 	ASSERT3P(hdr->b_hash_next, ==, NULL);
402189c86e32SChris Williamson 	if (HDR_HAS_L1HDR(hdr)) {
4022244781f1SPrakash Surya 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
402389c86e32SChris Williamson 		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
4024*eb633035STom Caputi 
4025*eb633035STom Caputi 		if (!HDR_PROTECTED(hdr)) {
4026*eb633035STom Caputi 			kmem_cache_free(hdr_full_cache, hdr);
4027*eb633035STom Caputi 		} else {
4028*eb633035STom Caputi 			kmem_cache_free(hdr_full_crypt_cache, hdr);
4029*eb633035STom Caputi 		}
403089c86e32SChris Williamson 	} else {
403189c86e32SChris Williamson 		kmem_cache_free(hdr_l2only_cache, hdr);
403289c86e32SChris Williamson 	}
4033fa9e4066Sahrens }
4034fa9e4066Sahrens 
4035fa9e4066Sahrens void
4036dcbf3bd6SGeorge Wilson arc_buf_destroy(arc_buf_t *buf, void* tag)
4037ea8dc4b6Seschrock {
4038ea8dc4b6Seschrock 	arc_buf_hdr_t *hdr = buf->b_hdr;
4039ea8dc4b6Seschrock 	kmutex_t *hash_lock = HDR_LOCK(hdr);
4040fa9e4066Sahrens 
404189c86e32SChris Williamson 	if (hdr->b_l1hdr.b_state == arc_anon) {
4042dcbf3bd6SGeorge Wilson 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
4043dcbf3bd6SGeorge Wilson 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4044dcbf3bd6SGeorge Wilson 		VERIFY0(remove_reference(hdr, NULL, tag));
4045dcbf3bd6SGeorge Wilson 		arc_hdr_destroy(hdr);
4046dcbf3bd6SGeorge Wilson 		return;
4047ea8dc4b6Seschrock 	}
4048ea8dc4b6Seschrock 
4049ea8dc4b6Seschrock 	mutex_enter(hash_lock);
4050dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr, ==, buf->b_hdr);
4051dcbf3bd6SGeorge Wilson 	ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
40523f9d6ad7SLin Ling 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4053dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_state, !=, arc_anon);
4054dcbf3bd6SGeorge Wilson 	ASSERT3P(buf->b_data, !=, NULL);
4055ea8dc4b6Seschrock 
4056ea8dc4b6Seschrock 	(void) remove_reference(hdr, hash_lock, tag);
40575602294fSDan Kimmel 	arc_buf_destroy_impl(buf);
4058ea8dc4b6Seschrock 	mutex_exit(hash_lock);
4059fa9e4066Sahrens }
4060fa9e4066Sahrens 
4061fa9e4066Sahrens /*
4062244781f1SPrakash Surya  * Evict the arc_buf_hdr that is provided as a parameter. The resultant
4063*eb633035STom Caputi  * state of the header is dependent on its state prior to entering this
4064244781f1SPrakash Surya  * function. The following transitions are possible:
4065874395d5Smaybee  *
4066244781f1SPrakash Surya  *    - arc_mru -> arc_mru_ghost
4067244781f1SPrakash Surya  *    - arc_mfu -> arc_mfu_ghost
4068244781f1SPrakash Surya  *    - arc_mru_ghost -> arc_l2c_only
4069244781f1SPrakash Surya  *    - arc_mru_ghost -> deleted
4070244781f1SPrakash Surya  *    - arc_mfu_ghost -> arc_l2c_only
4071244781f1SPrakash Surya  *    - arc_mfu_ghost -> deleted
4072fa9e4066Sahrens  */
4073244781f1SPrakash Surya static int64_t
4074244781f1SPrakash Surya arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
4075fa9e4066Sahrens {
4076244781f1SPrakash Surya 	arc_state_t *evicted_state, *state;
4077244781f1SPrakash Surya 	int64_t bytes_evicted = 0;
4078a3874b8bSToomas Soome 	int min_lifetime = HDR_PRESCIENT_PREFETCH(hdr) ?
4079a3874b8bSToomas Soome 	    zfs_arc_min_prescient_prefetch_ms : zfs_arc_min_prefetch_ms;
4080fa9e4066Sahrens 
4081244781f1SPrakash Surya 	ASSERT(MUTEX_HELD(hash_lock));
4082244781f1SPrakash Surya 	ASSERT(HDR_HAS_L1HDR(hdr));
4083fa9e4066Sahrens 
4084244781f1SPrakash Surya 	state = hdr->b_l1hdr.b_state;
4085244781f1SPrakash Surya 	if (GHOST_STATE(state)) {
4086244781f1SPrakash Surya 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4087dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
4088fa9e4066Sahrens 
4089244781f1SPrakash Surya 		/*
4090244781f1SPrakash Surya 		 * l2arc_write_buffers() relies on a header's L1 portion
4091*eb633035STom Caputi 		 * (i.e. its b_pabd field) during its write phase.
4092244781f1SPrakash Surya 		 * Thus, we cannot push a header onto the arc_l2c_only
4093*eb633035STom Caputi 		 * state (removing its L1 piece) until the header is
4094244781f1SPrakash Surya 		 * done being written to the l2arc.
4095244781f1SPrakash Surya 		 */
4096244781f1SPrakash Surya 		if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
4097244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_evict_l2_skip);
4098244781f1SPrakash Surya 			return (bytes_evicted);
40993a5286a1SMatthew Ahrens 		}
4100244781f1SPrakash Surya 
4101244781f1SPrakash Surya 		ARCSTAT_BUMP(arcstat_deleted);
4102dcbf3bd6SGeorge Wilson 		bytes_evicted += HDR_GET_LSIZE(hdr);
4103244781f1SPrakash Surya 
4104244781f1SPrakash Surya 		DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
4105244781f1SPrakash Surya 
4106244781f1SPrakash Surya 		if (HDR_HAS_L2HDR(hdr)) {
4107*eb633035STom Caputi 			ASSERT(hdr->b_l1hdr.b_pabd == NULL);
4108*eb633035STom Caputi 			ASSERT(!HDR_HAS_RABD(hdr));
4109244781f1SPrakash Surya 			/*
4110244781f1SPrakash Surya 			 * This buffer is cached on the 2nd Level ARC;
4111244781f1SPrakash Surya 			 * don't destroy the header.
4112244781f1SPrakash Surya 			 */
4113244781f1SPrakash Surya 			arc_change_state(arc_l2c_only, hdr, hash_lock);
41143a5286a1SMatthew Ahrens 			/*
4115244781f1SPrakash Surya 			 * dropping from L1+L2 cached to L2-only,
4116244781f1SPrakash Surya 			 * realloc to remove the L1 header.
41173a5286a1SMatthew Ahrens 			 */
4118244781f1SPrakash Surya 			hdr = arc_hdr_realloc(hdr, hdr_full_cache,
4119244781f1SPrakash Surya 			    hdr_l2only_cache);
4120244781f1SPrakash Surya 		} else {
4121244781f1SPrakash Surya 			arc_change_state(arc_anon, hdr, hash_lock);
4122244781f1SPrakash Surya 			arc_hdr_destroy(hdr);
41233a5286a1SMatthew Ahrens 		}
4124244781f1SPrakash Surya 		return (bytes_evicted);
41253a5286a1SMatthew Ahrens 	}
41263a5286a1SMatthew Ahrens 
4127244781f1SPrakash Surya 	ASSERT(state == arc_mru || state == arc_mfu);
4128244781f1SPrakash Surya 	evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
4129244781f1SPrakash Surya 
4130244781f1SPrakash Surya 	/* prefetch buffers have a minimum lifespan */
4131244781f1SPrakash Surya 	if (HDR_IO_IN_PROGRESS(hdr) ||
4132244781f1SPrakash Surya 	    ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
4133a3874b8bSToomas Soome 	    ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access < min_lifetime * hz)) {
4134244781f1SPrakash Surya 		ARCSTAT_BUMP(arcstat_evict_skip);
4135244781f1SPrakash Surya 		return (bytes_evicted);
4136244781f1SPrakash Surya 	}
4137244781f1SPrakash Surya 
4138e914ace2STim Schumacher 	ASSERT0(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt));
4139244781f1SPrakash Surya 	while (hdr->b_l1hdr.b_buf) {
4140244781f1SPrakash Surya 		arc_buf_t *buf = hdr->b_l1hdr.b_buf;
4141244781f1SPrakash Surya 		if (!mutex_tryenter(&buf->b_evict_lock)) {
4142244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_mutex_miss);
4143244781f1SPrakash Surya 			break;
414413506d1eSmaybee 		}
4145244781f1SPrakash Surya 		if (buf->b_data != NULL)
4146dcbf3bd6SGeorge Wilson 			bytes_evicted += HDR_GET_LSIZE(hdr);
4147dcbf3bd6SGeorge Wilson 		mutex_exit(&buf->b_evict_lock);
41485602294fSDan Kimmel 		arc_buf_destroy_impl(buf);
4149244781f1SPrakash Surya 	}
415069962b56SMatthew Ahrens 
4151244781f1SPrakash Surya 	if (HDR_HAS_L2HDR(hdr)) {
4152dcbf3bd6SGeorge Wilson 		ARCSTAT_INCR(arcstat_evict_l2_cached, HDR_GET_LSIZE(hdr));
4153244781f1SPrakash Surya 	} else {
4154dcbf3bd6SGeorge Wilson 		if (l2arc_write_eligible(hdr->b_spa, hdr)) {
4155dcbf3bd6SGeorge Wilson 			ARCSTAT_INCR(arcstat_evict_l2_eligible,
4156dcbf3bd6SGeorge Wilson 			    HDR_GET_LSIZE(hdr));
4157dcbf3bd6SGeorge Wilson 		} else {
4158dcbf3bd6SGeorge Wilson 			ARCSTAT_INCR(arcstat_evict_l2_ineligible,
4159dcbf3bd6SGeorge Wilson 			    HDR_GET_LSIZE(hdr));
4160dcbf3bd6SGeorge Wilson 		}
4161244781f1SPrakash Surya 	}
4162244781f1SPrakash Surya 
4163dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_bufcnt == 0) {
4164dcbf3bd6SGeorge Wilson 		arc_cksum_free(hdr);
4165dcbf3bd6SGeorge Wilson 
4166dcbf3bd6SGeorge Wilson 		bytes_evicted += arc_hdr_size(hdr);
4167dcbf3bd6SGeorge Wilson 
4168dcbf3bd6SGeorge Wilson 		/*
4169dcbf3bd6SGeorge Wilson 		 * If this hdr is being evicted and has a compressed
4170dcbf3bd6SGeorge Wilson 		 * buffer then we discard it here before we change states.
4171dcbf3bd6SGeorge Wilson 		 * This ensures that the accounting is updated correctly
4172770499e1SDan Kimmel 		 * in arc_free_data_impl().
4173dcbf3bd6SGeorge Wilson 		 */
4174*eb633035STom Caputi 		if (hdr->b_l1hdr.b_pabd != NULL)
4175*eb633035STom Caputi 			arc_hdr_free_pabd(hdr, B_FALSE);
4176*eb633035STom Caputi 
4177*eb633035STom Caputi 		if (HDR_HAS_RABD(hdr))
4178*eb633035STom Caputi 			arc_hdr_free_pabd(hdr, B_TRUE);
4179dcbf3bd6SGeorge Wilson 
4180244781f1SPrakash Surya 		arc_change_state(evicted_state, hdr, hash_lock);
4181244781f1SPrakash Surya 		ASSERT(HDR_IN_HASH_TABLE(hdr));
4182dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
4183244781f1SPrakash Surya 		DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
4184244781f1SPrakash Surya 	}
4185244781f1SPrakash Surya 
4186244781f1SPrakash Surya 	return (bytes_evicted);
4187244781f1SPrakash Surya }
4188244781f1SPrakash Surya 
4189244781f1SPrakash Surya static uint64_t
4190244781f1SPrakash Surya arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
4191244781f1SPrakash Surya     uint64_t spa, int64_t bytes)
4192244781f1SPrakash Surya {
4193244781f1SPrakash Surya 	multilist_sublist_t *mls;
4194244781f1SPrakash Surya 	uint64_t bytes_evicted = 0;
4195244781f1SPrakash Surya 	arc_buf_hdr_t *hdr;
4196244781f1SPrakash Surya 	kmutex_t *hash_lock;
4197244781f1SPrakash Surya 	int evict_count = 0;
4198244781f1SPrakash Surya 
4199244781f1SPrakash Surya 	ASSERT3P(marker, !=, NULL);
4200244781f1SPrakash Surya 	IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
4201244781f1SPrakash Surya 
4202244781f1SPrakash Surya 	mls = multilist_sublist_lock(ml, idx);
4203244781f1SPrakash Surya 
4204244781f1SPrakash Surya 	for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
4205244781f1SPrakash Surya 	    hdr = multilist_sublist_prev(mls, marker)) {
4206244781f1SPrakash Surya 		if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
4207244781f1SPrakash Surya 		    (evict_count >= zfs_arc_evict_batch_limit))
4208244781f1SPrakash Surya 			break;
420969962b56SMatthew Ahrens 
421069962b56SMatthew Ahrens 		/*
4211244781f1SPrakash Surya 		 * To keep our iteration location, move the marker
4212244781f1SPrakash Surya 		 * forward. Since we're not holding hdr's hash lock, we
4213244781f1SPrakash Surya 		 * must be very careful and not remove 'hdr' from the
4214244781f1SPrakash Surya 		 * sublist. Otherwise, other consumers might mistake the
4215244781f1SPrakash Surya 		 * 'hdr' as not being on a sublist when they call the
4216244781f1SPrakash Surya 		 * multilist_link_active() function (they all rely on
4217244781f1SPrakash Surya 		 * the hash lock protecting concurrent insertions and
4218244781f1SPrakash Surya 		 * removals). multilist_sublist_move_forward() was
4219244781f1SPrakash Surya 		 * specifically implemented to ensure this is the case
4220244781f1SPrakash Surya 		 * (only 'marker' will be removed and re-inserted).
4221244781f1SPrakash Surya 		 */
4222244781f1SPrakash Surya 		multilist_sublist_move_forward(mls, marker);
4223244781f1SPrakash Surya 
4224244781f1SPrakash Surya 		/*
4225244781f1SPrakash Surya 		 * The only case where the b_spa field should ever be
4226244781f1SPrakash Surya 		 * zero, is the marker headers inserted by
4227244781f1SPrakash Surya 		 * arc_evict_state(). It's possible for multiple threads
4228244781f1SPrakash Surya 		 * to be calling arc_evict_state() concurrently (e.g.
4229244781f1SPrakash Surya 		 * dsl_pool_close() and zio_inject_fault()), so we must
4230244781f1SPrakash Surya 		 * skip any markers we see from these other threads.
423169962b56SMatthew Ahrens 		 */
4232244781f1SPrakash Surya 		if (hdr->b_spa == 0)
4233244781f1SPrakash Surya 			continue;
4234244781f1SPrakash Surya 
4235244781f1SPrakash Surya 		/* we're only interested in evicting buffers of a certain spa */
4236244781f1SPrakash Surya 		if (spa != 0 && hdr->b_spa != spa) {
4237244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_evict_skip);
423869962b56SMatthew Ahrens 			continue;
423969962b56SMatthew Ahrens 		}
424069962b56SMatthew Ahrens 
42417adb730bSGeorge Wilson 		hash_lock = HDR_LOCK(hdr);
42425ea40c06SBrendan Gregg - Sun Microsystems 
4243244781f1SPrakash Surya 		/*
4244244781f1SPrakash Surya 		 * We aren't calling this function from any code path
4245244781f1SPrakash Surya 		 * that would already be holding a hash lock, so we're
4246244781f1SPrakash Surya 		 * asserting on this assumption to be defensive in case
4247244781f1SPrakash Surya 		 * this ever changes. Without this check, it would be
4248244781f1SPrakash Surya 		 * possible to incorrectly increment arcstat_mutex_miss
4249244781f1SPrakash Surya 		 * below (e.g. if the code changed such that we called
4250244781f1SPrakash Surya 		 * this function with a hash lock held).
4251244781f1SPrakash Surya 		 */
4252244781f1SPrakash Surya 		ASSERT(!MUTEX_HELD(hash_lock));
425344cb6abcSbmc 
4254244781f1SPrakash Surya 		if (mutex_tryenter(hash_lock)) {
4255244781f1SPrakash Surya 			uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
4256244781f1SPrakash Surya 			mutex_exit(hash_lock);
4257fa9e4066Sahrens 
4258244781f1SPrakash Surya 			bytes_evicted += evicted;
4259fa9e4066Sahrens 
4260244781f1SPrakash Surya 			/*
4261244781f1SPrakash Surya 			 * If evicted is zero, arc_evict_hdr() must have
4262244781f1SPrakash Surya 			 * decided to skip this header, don't increment
4263244781f1SPrakash Surya 			 * evict_count in this case.
4264244781f1SPrakash Surya 			 */
4265244781f1SPrakash Surya 			if (evicted != 0)
4266244781f1SPrakash Surya 				evict_count++;
426744cb6abcSbmc 
4268244781f1SPrakash Surya 			/*
4269244781f1SPrakash Surya 			 * If arc_size isn't overflowing, signal any
4270244781f1SPrakash Surya 			 * threads that might happen to be waiting.
4271244781f1SPrakash Surya 			 *
4272244781f1SPrakash Surya 			 * For each header evicted, we wake up a single
4273244781f1SPrakash Surya 			 * thread. If we used cv_broadcast, we could
4274244781f1SPrakash Surya 			 * wake up "too many" threads causing arc_size
4275244781f1SPrakash Surya 			 * to significantly overflow arc_c; since
4276770499e1SDan Kimmel 			 * arc_get_data_impl() doesn't check for overflow
4277244781f1SPrakash Surya 			 * when it's woken up (it doesn't because it's
4278244781f1SPrakash Surya 			 * possible for the ARC to be overflowing while
4279244781f1SPrakash Surya 			 * full of un-evictable buffers, and the
4280244781f1SPrakash Surya 			 * function should proceed in this case).
4281244781f1SPrakash Surya 			 *
4282244781f1SPrakash Surya 			 * If threads are left sleeping, due to not
4283de753e34SBrad Lewis 			 * using cv_broadcast here, they will be woken
4284de753e34SBrad Lewis 			 * up via cv_broadcast in arc_adjust_cb() just
4285de753e34SBrad Lewis 			 * before arc_adjust_zthr sleeps.
4286244781f1SPrakash Surya 			 */
4287de753e34SBrad Lewis 			mutex_enter(&arc_adjust_lock);
4288244781f1SPrakash Surya 			if (!arc_is_overflowing())
4289de753e34SBrad Lewis 				cv_signal(&arc_adjust_waiters_cv);
4290de753e34SBrad Lewis 			mutex_exit(&arc_adjust_lock);
4291244781f1SPrakash Surya 		} else {
4292244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_mutex_miss);
4293244781f1SPrakash Surya 		}
4294244781f1SPrakash Surya 	}
4295f4d2e9e6Smaybee 
4296244781f1SPrakash Surya 	multilist_sublist_unlock(mls);
429744cb6abcSbmc 
4298244781f1SPrakash Surya 	return (bytes_evicted);
4299fa9e4066Sahrens }
4300fa9e4066Sahrens 
4301fa9e4066Sahrens /*
4302244781f1SPrakash Surya  * Evict buffers from the given arc state, until we've removed the
4303244781f1SPrakash Surya  * specified number of bytes. Move the removed buffers to the
4304244781f1SPrakash Surya  * appropriate evict state.
4305244781f1SPrakash Surya  *
4306244781f1SPrakash Surya  * This function makes a "best effort". It skips over any buffers
4307244781f1SPrakash Surya  * it can't get a hash_lock on, and so, may not catch all candidates.
4308244781f1SPrakash Surya  * It may also return without evicting as much space as requested.
4309244781f1SPrakash Surya  *
4310244781f1SPrakash Surya  * If bytes is specified using the special value ARC_EVICT_ALL, this
4311244781f1SPrakash Surya  * will evict all available (i.e. unlocked and evictable) buffers from
4312244781f1SPrakash Surya  * the given arc state; which is used by arc_flush().
4313fa9e4066Sahrens  */
4314244781f1SPrakash Surya static uint64_t
4315244781f1SPrakash Surya arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
4316244781f1SPrakash Surya     arc_buf_contents_t type)
4317fa9e4066Sahrens {
4318244781f1SPrakash Surya 	uint64_t total_evicted = 0;
431994c2d0ebSMatthew Ahrens 	multilist_t *ml = state->arcs_list[type];
4320244781f1SPrakash Surya 	int num_sublists;
4321244781f1SPrakash Surya 	arc_buf_hdr_t **markers;
4322fa9e4066Sahrens 
4323244781f1SPrakash Surya 	IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
4324b802aa8cSSanjeev Bagewadi 
4325244781f1SPrakash Surya 	num_sublists = multilist_get_num_sublists(ml);
4326b802aa8cSSanjeev Bagewadi 
4327244781f1SPrakash Surya 	/*
4328244781f1SPrakash Surya 	 * If we've tried to evict from each sublist, made some
4329244781f1SPrakash Surya 	 * progress, but still have not hit the target number of bytes
4330244781f1SPrakash Surya 	 * to evict, we want to keep trying. The markers allow us to
4331244781f1SPrakash Surya 	 * pick up where we left off for each individual sublist, rather
4332244781f1SPrakash Surya 	 * than starting from the tail each time.
4333244781f1SPrakash Surya 	 */
4334244781f1SPrakash Surya 	markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
4335244781f1SPrakash Surya 	for (int i = 0; i < num_sublists; i++) {
4336244781f1SPrakash Surya 		markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
433769962b56SMatthew Ahrens 
433869962b56SMatthew Ahrens 		/*
4339244781f1SPrakash Surya 		 * A b_spa of 0 is used to indicate that this header is
4340244781f1SPrakash Surya 		 * a marker. This fact is used in arc_adjust_type() and
4341244781f1SPrakash Surya 		 * arc_evict_state_impl().
434269962b56SMatthew Ahrens 		 */
4343244781f1SPrakash Surya 		markers[i]->b_spa = 0;
4344fa94a07fSbrendan 
4345244781f1SPrakash Surya 		multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
4346244781f1SPrakash Surya 		multilist_sublist_insert_tail(mls, markers[i]);
4347244781f1SPrakash Surya 		multilist_sublist_unlock(mls);
4348244781f1SPrakash Surya 	}
4349fa94a07fSbrendan 
4350244781f1SPrakash Surya 	/*
4351244781f1SPrakash Surya 	 * While we haven't hit our target number of bytes to evict, or
4352244781f1SPrakash Surya 	 * we're evicting all available buffers.
4353244781f1SPrakash Surya 	 */
4354244781f1SPrakash Surya 	while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
4355244781f1SPrakash Surya 		/*
4356244781f1SPrakash Surya 		 * Start eviction using a randomly selected sublist,
4357244781f1SPrakash Surya 		 * this is to try and evenly balance eviction across all
4358244781f1SPrakash Surya 		 * sublists. Always starting at the same sublist
4359244781f1SPrakash Surya 		 * (e.g. index 0) would cause evictions to favor certain
4360244781f1SPrakash Surya 		 * sublists over others.
4361244781f1SPrakash Surya 		 */
4362244781f1SPrakash Surya 		int sublist_idx = multilist_get_random_index(ml);
4363244781f1SPrakash Surya 		uint64_t scan_evicted = 0;
4364244781f1SPrakash Surya 
4365244781f1SPrakash Surya 		for (int i = 0; i < num_sublists; i++) {
4366244781f1SPrakash Surya 			uint64_t bytes_remaining;
4367244781f1SPrakash Surya 			uint64_t bytes_evicted;
4368244781f1SPrakash Surya 
4369244781f1SPrakash Surya 			if (bytes == ARC_EVICT_ALL)
4370244781f1SPrakash Surya 				bytes_remaining = ARC_EVICT_ALL;
4371244781f1SPrakash Surya 			else if (total_evicted < bytes)
4372244781f1SPrakash Surya 				bytes_remaining = bytes - total_evicted;
4373244781f1SPrakash Surya 			else
4374fa9e4066Sahrens 				break;
4375244781f1SPrakash Surya 
4376244781f1SPrakash Surya 			bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
4377244781f1SPrakash Surya 			    markers[sublist_idx], spa, bytes_remaining);
4378244781f1SPrakash Surya 
4379244781f1SPrakash Surya 			scan_evicted += bytes_evicted;
4380244781f1SPrakash Surya 			total_evicted += bytes_evicted;
4381244781f1SPrakash Surya 
4382244781f1SPrakash Surya 			/* we've reached the end, wrap to the beginning */
4383244781f1SPrakash Surya 			if (++sublist_idx >= num_sublists)
4384244781f1SPrakash Surya 				sublist_idx = 0;
4385244781f1SPrakash Surya 		}
4386244781f1SPrakash Surya 
4387244781f1SPrakash Surya 		/*
4388244781f1SPrakash Surya 		 * If we didn't evict anything during this scan, we have
4389244781f1SPrakash Surya 		 * no reason to believe we'll evict more during another
4390244781f1SPrakash Surya 		 * scan, so break the loop.
4391244781f1SPrakash Surya 		 */
4392244781f1SPrakash Surya 		if (scan_evicted == 0) {
4393244781f1SPrakash Surya 			/* This isn't possible, let's make that obvious */
4394244781f1SPrakash Surya 			ASSERT3S(bytes, !=, 0);
4395244781f1SPrakash Surya 
4396b802aa8cSSanjeev Bagewadi 			/*
4397244781f1SPrakash Surya 			 * When bytes is ARC_EVICT_ALL, the only way to
4398244781f1SPrakash Surya 			 * break the loop is when scan_evicted is zero.
4399244781f1SPrakash Surya 			 * In that case, we actually have evicted enough,
4400244781f1SPrakash Surya 			 * so we don't want to increment the kstat.
4401b802aa8cSSanjeev Bagewadi 			 */
4402244781f1SPrakash Surya 			if (bytes != ARC_EVICT_ALL) {
4403244781f1SPrakash Surya 				ASSERT3S(total_evicted, <, bytes);
4404244781f1SPrakash Surya 				ARCSTAT_BUMP(arcstat_evict_not_enough);
4405244781f1SPrakash Surya 			}
4406244781f1SPrakash Surya 
4407244781f1SPrakash Surya 			break;
440869962b56SMatthew Ahrens 		}
4409244781f1SPrakash Surya 	}
4410244781f1SPrakash Surya 
4411244781f1SPrakash Surya 	for (int i = 0; i < num_sublists; i++) {
4412244781f1SPrakash Surya 		multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
4413244781f1SPrakash Surya 		multilist_sublist_remove(mls, markers[i]);
4414244781f1SPrakash Surya 		multilist_sublist_unlock(mls);
441569962b56SMatthew Ahrens 
4416244781f1SPrakash Surya 		kmem_cache_free(hdr_full_cache, markers[i]);
4417fa9e4066Sahrens 	}
4418244781f1SPrakash Surya 	kmem_free(markers, sizeof (*markers) * num_sublists);
4419fa9e4066Sahrens 
4420244781f1SPrakash Surya 	return (total_evicted);
4421244781f1SPrakash Surya }
4422244781f1SPrakash Surya 
4423244781f1SPrakash Surya /*
4424244781f1SPrakash Surya  * Flush all "evictable" data of the given type from the arc state
4425244781f1SPrakash Surya  * specified. This will not evict any "active" buffers (i.e. referenced).
4426244781f1SPrakash Surya  *
4427dcbf3bd6SGeorge Wilson  * When 'retry' is set to B_FALSE, the function will make a single pass
4428244781f1SPrakash Surya  * over the state and evict any buffers that it can. Since it doesn't
4429244781f1SPrakash Surya  * continually retry the eviction, it might end up leaving some buffers
4430244781f1SPrakash Surya  * in the ARC due to lock misses.
4431244781f1SPrakash Surya  *
4432dcbf3bd6SGeorge Wilson  * When 'retry' is set to B_TRUE, the function will continually retry the
4433244781f1SPrakash Surya  * eviction until *all* evictable buffers have been removed from the
4434244781f1SPrakash Surya  * state. As a result, if concurrent insertions into the state are
4435244781f1SPrakash Surya  * allowed (e.g. if the ARC isn't shutting down), this function might
4436244781f1SPrakash Surya  * wind up in an infinite loop, continually trying to evict buffers.
4437244781f1SPrakash Surya  */
4438244781f1SPrakash Surya static uint64_t
4439244781f1SPrakash Surya arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
4440244781f1SPrakash Surya     boolean_t retry)
4441244781f1SPrakash Surya {
4442244781f1SPrakash Surya 	uint64_t evicted = 0;
4443244781f1SPrakash Surya 
4444e914ace2STim Schumacher 	while (zfs_refcount_count(&state->arcs_esize[type]) != 0) {
4445244781f1SPrakash Surya 		evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
4446244781f1SPrakash Surya 
4447244781f1SPrakash Surya 		if (!retry)
4448244781f1SPrakash Surya 			break;
44490e8c6158Smaybee 	}
44500e8c6158Smaybee 
4451244781f1SPrakash Surya 	return (evicted);
4452244781f1SPrakash Surya }
4453244781f1SPrakash Surya 
4454244781f1SPrakash Surya /*
4455244781f1SPrakash Surya  * Evict the specified number of bytes from the state specified,
4456244781f1SPrakash Surya  * restricting eviction to the spa and type given. This function
4457244781f1SPrakash Surya  * prevents us from trying to evict more from a state's list than
4458244781f1SPrakash Surya  * is "evictable", and to skip evicting altogether when passed a
4459244781f1SPrakash Surya  * negative value for "bytes". In contrast, arc_evict_state() will
4460244781f1SPrakash Surya  * evict everything it can, when passed a negative value for "bytes".
4461244781f1SPrakash Surya  */
4462244781f1SPrakash Surya static uint64_t
4463244781f1SPrakash Surya arc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
4464244781f1SPrakash Surya     arc_buf_contents_t type)
4465244781f1SPrakash Surya {
4466244781f1SPrakash Surya 	int64_t delta;
4467244781f1SPrakash Surya 
4468e914ace2STim Schumacher 	if (bytes > 0 && zfs_refcount_count(&state->arcs_esize[type]) > 0) {
4469e914ace2STim Schumacher 		delta = MIN(zfs_refcount_count(&state->arcs_esize[type]),
4470e914ace2STim Schumacher 		    bytes);
4471244781f1SPrakash Surya 		return (arc_evict_state(state, spa, delta, type));
4472fa9e4066Sahrens 	}
4473fa9e4066Sahrens 
4474244781f1SPrakash Surya 	return (0);
4475fa9e4066Sahrens }
4476fa9e4066Sahrens 
4477244781f1SPrakash Surya /*
4478244781f1SPrakash Surya  * Evict metadata buffers from the cache, such that arc_meta_used is
4479244781f1SPrakash Surya  * capped by the arc_meta_limit tunable.
4480244781f1SPrakash Surya  */
4481244781f1SPrakash Surya static uint64_t
44823a2d8a1bSPaul Dagnelie arc_adjust_meta(uint64_t meta_used)
4483244781f1SPrakash Surya {
4484244781f1SPrakash Surya 	uint64_t total_evicted = 0;
4485244781f1SPrakash Surya 	int64_t target;
4486244781f1SPrakash Surya 
4487244781f1SPrakash Surya 	/*
4488244781f1SPrakash Surya 	 * If we're over the meta limit, we want to evict enough
4489244781f1SPrakash Surya 	 * metadata to get back under the meta limit. We don't want to
4490244781f1SPrakash Surya 	 * evict so much that we drop the MRU below arc_p, though. If
4491244781f1SPrakash Surya 	 * we're over the meta limit more than we're over arc_p, we
4492244781f1SPrakash Surya 	 * evict some from the MRU here, and some from the MFU below.
4493244781f1SPrakash Surya 	 */
44943a2d8a1bSPaul Dagnelie 	target = MIN((int64_t)(meta_used - arc_meta_limit),
4495e914ace2STim Schumacher 	    (int64_t)(zfs_refcount_count(&arc_anon->arcs_size) +
4496e914ace2STim Schumacher 	    zfs_refcount_count(&arc_mru->arcs_size) - arc_p));
4497244781f1SPrakash Surya 
4498244781f1SPrakash Surya 	total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
4499244781f1SPrakash Surya 
4500244781f1SPrakash Surya 	/*
4501244781f1SPrakash Surya 	 * Similar to the above, we want to evict enough bytes to get us
4502244781f1SPrakash Surya 	 * below the meta limit, but not so much as to drop us below the
45035602294fSDan Kimmel 	 * space allotted to the MFU (which is defined as arc_c - arc_p).
4504244781f1SPrakash Surya 	 */
45053a2d8a1bSPaul Dagnelie 	target = MIN((int64_t)(meta_used - arc_meta_limit),
4506e914ace2STim Schumacher 	    (int64_t)(zfs_refcount_count(&arc_mfu->arcs_size) -
45073a2d8a1bSPaul Dagnelie 	    (arc_c - arc_p)));
4508244781f1SPrakash Surya 
4509244781f1SPrakash Surya 	total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4510244781f1SPrakash Surya 
4511244781f1SPrakash Surya 	return (total_evicted);
4512244781f1SPrakash Surya }
4513244781f1SPrakash Surya 
4514244781f1SPrakash Surya /*
4515244781f1SPrakash Surya  * Return the type of the oldest buffer in the given arc state
4516244781f1SPrakash Surya  *
4517244781f1SPrakash Surya  * This function will select a random sublist of type ARC_BUFC_DATA and
4518244781f1SPrakash Surya  * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
4519244781f1SPrakash Surya  * is compared, and the type which contains the "older" buffer will be
4520244781f1SPrakash Surya  * returned.
4521244781f1SPrakash Surya  */
4522244781f1SPrakash Surya static arc_buf_contents_t
4523244781f1SPrakash Surya arc_adjust_type(arc_state_t *state)
4524244781f1SPrakash Surya {
452594c2d0ebSMatthew Ahrens 	multilist_t *data_ml = state->arcs_list[ARC_BUFC_DATA];
452694c2d0ebSMatthew Ahrens 	multilist_t *meta_ml = state->arcs_list[ARC_BUFC_METADATA];
4527244781f1SPrakash Surya 	int data_idx = multilist_get_random_index(data_ml);
4528244781f1SPrakash Surya 	int meta_idx = multilist_get_random_index(meta_ml);
4529244781f1SPrakash Surya 	multilist_sublist_t *data_mls;
4530244781f1SPrakash Surya 	multilist_sublist_t *meta_mls;
4531244781f1SPrakash Surya 	arc_buf_contents_t type;
4532244781f1SPrakash Surya 	arc_buf_hdr_t *data_hdr;
4533244781f1SPrakash Surya 	arc_buf_hdr_t *meta_hdr;
4534244781f1SPrakash Surya 
4535244781f1SPrakash Surya 	/*
4536244781f1SPrakash Surya 	 * We keep the sublist lock until we're finished, to prevent
4537244781f1SPrakash Surya 	 * the headers from being destroyed via arc_evict_state().
4538244781f1SPrakash Surya 	 */
4539244781f1SPrakash Surya 	data_mls = multilist_sublist_lock(data_ml, data_idx);
4540244781f1SPrakash Surya 	meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
4541244781f1SPrakash Surya 
4542244781f1SPrakash Surya 	/*
4543244781f1SPrakash Surya 	 * These two loops are to ensure we skip any markers that
4544244781f1SPrakash Surya 	 * might be at the tail of the lists due to arc_evict_state().
4545244781f1SPrakash Surya 	 */
4546244781f1SPrakash Surya 
4547244781f1SPrakash Surya 	for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
4548244781f1SPrakash Surya 	    data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
4549244781f1SPrakash Surya 		if (data_hdr->b_spa != 0)
4550244781f1SPrakash Surya 			break;
4551244781f1SPrakash Surya 	}
4552244781f1SPrakash Surya 
4553244781f1SPrakash Surya 	for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
4554244781f1SPrakash Surya 	    meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
4555244781f1SPrakash Surya 		if (meta_hdr->b_spa != 0)
4556244781f1SPrakash Surya 			break;
4557244781f1SPrakash Surya 	}
4558244781f1SPrakash Surya 
4559244781f1SPrakash Surya 	if (data_hdr == NULL && meta_hdr == NULL) {
4560244781f1SPrakash Surya 		type = ARC_BUFC_DATA;
4561244781f1SPrakash Surya 	} else if (data_hdr == NULL) {
4562244781f1SPrakash Surya 		ASSERT3P(meta_hdr, !=, NULL);
4563244781f1SPrakash Surya 		type = ARC_BUFC_METADATA;
4564244781f1SPrakash Surya 	} else if (meta_hdr == NULL) {
4565244781f1SPrakash Surya 		ASSERT3P(data_hdr, !=, NULL);
4566244781f1SPrakash Surya 		type = ARC_BUFC_DATA;
4567244781f1SPrakash Surya 	} else {
4568244781f1SPrakash Surya 		ASSERT3P(data_hdr, !=, NULL);
4569244781f1SPrakash Surya 		ASSERT3P(meta_hdr, !=, NULL);
4570244781f1SPrakash Surya 
4571244781f1SPrakash Surya 		/* The headers can't be on the sublist without an L1 header */
4572244781f1SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(data_hdr));
4573244781f1SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(meta_hdr));
4574244781f1SPrakash Surya 
4575244781f1SPrakash Surya 		if (data_hdr->b_l1hdr.b_arc_access <
4576244781f1SPrakash Surya 		    meta_hdr->b_l1hdr.b_arc_access) {
4577244781f1SPrakash Surya 			type = ARC_BUFC_DATA;
4578244781f1SPrakash Surya 		} else {
4579244781f1SPrakash Surya 			type = ARC_BUFC_METADATA;
4580244781f1SPrakash Surya 		}
4581244781f1SPrakash Surya 	}
4582244781f1SPrakash Surya 
4583244781f1SPrakash Surya 	multilist_sublist_unlock(meta_mls);
4584244781f1SPrakash Surya 	multilist_sublist_unlock(data_mls);
4585244781f1SPrakash Surya 
4586244781f1SPrakash Surya 	return (type);
4587244781f1SPrakash Surya }
4588244781f1SPrakash Surya 
4589244781f1SPrakash Surya /*
4590244781f1SPrakash Surya  * Evict buffers from the cache, such that arc_size is capped by arc_c.
4591244781f1SPrakash Surya  */
4592244781f1SPrakash Surya static uint64_t
4593fa9e4066Sahrens arc_adjust(void)
4594fa9e4066Sahrens {
4595244781f1SPrakash Surya 	uint64_t total_evicted = 0;
4596244781f1SPrakash Surya 	uint64_t bytes;
4597244781f1SPrakash Surya 	int64_t target;
45983a2d8a1bSPaul Dagnelie 	uint64_t asize = aggsum_value(&arc_size);
45993a2d8a1bSPaul Dagnelie 	uint64_t ameta = aggsum_value(&arc_meta_used);
4600fa9e4066Sahrens 
46015a98e54bSBrendan Gregg - Sun Microsystems 	/*
4602244781f1SPrakash Surya 	 * If we're over arc_meta_limit, we want to correct that before
4603244781f1SPrakash Surya 	 * potentially evicting data buffers below.
46045a98e54bSBrendan Gregg - Sun Microsystems 	 */
46053a2d8a1bSPaul Dagnelie 	total_evicted += arc_adjust_meta(ameta);
46065a98e54bSBrendan Gregg - Sun Microsystems 
4607244781f1SPrakash Surya 	/*
4608244781f1SPrakash Surya 	 * Adjust MRU size
4609244781f1SPrakash Surya 	 *
4610244781f1SPrakash Surya 	 * If we're over the target cache size, we want to evict enough
4611244781f1SPrakash Surya 	 * from the list to get back to our target size. We don't want
4612244781f1SPrakash Surya 	 * to evict too much from the MRU, such that it drops below
4613244781f1SPrakash Surya 	 * arc_p. So, if we're over our target cache size more than
4614244781f1SPrakash Surya 	 * the MRU is over arc_p, we'll evict enough to get back to
4615244781f1SPrakash Surya 	 * arc_p here, and then evict more from the MFU below.
4616244781f1SPrakash Surya 	 */
46173a2d8a1bSPaul Dagnelie 	target = MIN((int64_t)(asize - arc_c),
4618e914ace2STim Schumacher 	    (int64_t)(zfs_refcount_count(&arc_anon->arcs_size) +
4619e914ace2STim Schumacher 	    zfs_refcount_count(&arc_mru->arcs_size) + ameta - arc_p));
4620fa9e4066Sahrens 
4621244781f1SPrakash Surya 	/*
4622244781f1SPrakash Surya 	 * If we're below arc_meta_min, always prefer to evict data.
4623244781f1SPrakash Surya 	 * Otherwise, try to satisfy the requested number of bytes to
4624244781f1SPrakash Surya 	 * evict from the type which contains older buffers; in an
4625244781f1SPrakash Surya 	 * effort to keep newer buffers in the cache regardless of their
4626244781f1SPrakash Surya 	 * type. If we cannot satisfy the number of bytes from this
4627244781f1SPrakash Surya 	 * type, spill over into the next type.
4628244781f1SPrakash Surya 	 */
4629244781f1SPrakash Surya 	if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
46303a2d8a1bSPaul Dagnelie 	    ameta > arc_meta_min) {
4631244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
4632244781f1SPrakash Surya 		total_evicted += bytes;
46330e8c6158Smaybee 
4634244781f1SPrakash Surya 		/*
4635244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
4636244781f1SPrakash Surya 		 * metadata, we try to get the rest from data.
4637244781f1SPrakash Surya 		 */
4638244781f1SPrakash Surya 		target -= bytes;
4639244781f1SPrakash Surya 
4640244781f1SPrakash Surya 		total_evicted +=
4641244781f1SPrakash Surya 		    arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
4642244781f1SPrakash Surya 	} else {
4643244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
4644244781f1SPrakash Surya 		total_evicted += bytes;
4645244781f1SPrakash Surya 
4646244781f1SPrakash Surya 		/*
4647244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
4648244781f1SPrakash Surya 		 * data, we try to get the rest from metadata.
4649244781f1SPrakash Surya 		 */
4650244781f1SPrakash Surya 		target -= bytes;
4651244781f1SPrakash Surya 
4652244781f1SPrakash Surya 		total_evicted +=
4653244781f1SPrakash Surya 		    arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
4654fa9e4066Sahrens 	}
4655fa9e4066Sahrens 
46565a98e54bSBrendan Gregg - Sun Microsystems 	/*
46575a98e54bSBrendan Gregg - Sun Microsystems 	 * Adjust MFU size
4658244781f1SPrakash Surya 	 *
4659244781f1SPrakash Surya 	 * Now that we've tried to evict enough from the MRU to get its
4660244781f1SPrakash Surya 	 * size back to arc_p, if we're still above the target cache
4661244781f1SPrakash Surya 	 * size, we evict the rest from the MFU.
46625a98e54bSBrendan Gregg - Sun Microsystems 	 */
46633a2d8a1bSPaul Dagnelie 	target = asize - arc_c;
4664fa9e4066Sahrens 
466531c46cf2SAlek Pinchuk 	if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
46663a2d8a1bSPaul Dagnelie 	    ameta > arc_meta_min) {
4667244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4668244781f1SPrakash Surya 		total_evicted += bytes;
46695a98e54bSBrendan Gregg - Sun Microsystems 
4670244781f1SPrakash Surya 		/*
4671244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
4672244781f1SPrakash Surya 		 * metadata, we try to get the rest from data.
4673244781f1SPrakash Surya 		 */
4674244781f1SPrakash Surya 		target -= bytes;
4675244781f1SPrakash Surya 
4676244781f1SPrakash Surya 		total_evicted +=
4677244781f1SPrakash Surya 		    arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
4678244781f1SPrakash Surya 	} else {
4679244781f1SPrakash Surya 		bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
4680244781f1SPrakash Surya 		total_evicted += bytes;
4681244781f1SPrakash Surya 
4682244781f1SPrakash Surya 		/*
4683244781f1SPrakash Surya 		 * If we couldn't evict our target number of bytes from
4684244781f1SPrakash Surya 		 * data, we try to get the rest from data.
4685244781f1SPrakash Surya 		 */
4686244781f1SPrakash Surya 		target -= bytes;
4687fa9e4066Sahrens 
4688244781f1SPrakash Surya 		total_evicted +=
4689244781f1SPrakash Surya 		    arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
46905a98e54bSBrendan Gregg - Sun Microsystems 	}
4691fa9e4066Sahrens 
46925a98e54bSBrendan Gregg - Sun Microsystems 	/*
46935a98e54bSBrendan Gregg - Sun Microsystems 	 * Adjust ghost lists
4694244781f1SPrakash Surya 	 *
4695244781f1SPrakash Surya 	 * In addition to the above, the ARC also defines target values
4696244781f1SPrakash Surya 	 * for the ghost lists. The sum of the mru list and mru ghost
4697244781f1SPrakash Surya 	 * list should never exceed the target size of the cache, and
4698244781f1SPrakash Surya 	 * the sum of the mru list, mfu list, mru ghost list, and mfu
4699244781f1SPrakash Surya 	 * ghost list should never exceed twice the target size of the
4700244781f1SPrakash Surya 	 * cache. The following logic enforces these limits on the ghost
4701244781f1SPrakash Surya 	 * caches, and evicts from them as needed.
47025a98e54bSBrendan Gregg - Sun Microsystems 	 */
4703e914ace2STim Schumacher 	target = zfs_refcount_count(&arc_mru->arcs_size) +
4704e914ace2STim Schumacher 	    zfs_refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
4705fa9e4066Sahrens 
4706244781f1SPrakash Surya 	bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
4707244781f1SPrakash Surya 	total_evicted += bytes;
4708fa9e4066Sahrens 
4709244781f1SPrakash Surya 	target -= bytes;
47100e8c6158Smaybee 
4711244781f1SPrakash Surya 	total_evicted +=
4712244781f1SPrakash Surya 	    arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
47135a98e54bSBrendan Gregg - Sun Microsystems 
4714244781f1SPrakash Surya 	/*
4715244781f1SPrakash Surya 	 * We assume the sum of the mru list and mfu list is less than
4716244781f1SPrakash Surya 	 * or equal to arc_c (we enforced this above), which means we
4717244781f1SPrakash Surya 	 * can use the simpler of the two equations below:
4718244781f1SPrakash Surya 	 *
4719244781f1SPrakash Surya 	 *	mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
4720244781f1SPrakash Surya 	 *		    mru ghost + mfu ghost <= arc_c
4721244781f1SPrakash Surya 	 */
4722e914ace2STim Schumacher 	target = zfs_refcount_count(&arc_mru_ghost->arcs_size) +
4723e914ace2STim Schumacher 	    zfs_refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
4724244781f1SPrakash Surya 
4725244781f1SPrakash Surya 	bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
4726244781f1SPrakash Surya 	total_evicted += bytes;
4727244781f1SPrakash Surya 
4728244781f1SPrakash Surya 	target -= bytes;
4729244781f1SPrakash Surya 
4730244781f1SPrakash Surya 	total_evicted +=
4731244781f1SPrakash Surya 	    arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
4732244781f1SPrakash Surya 
4733244781f1SPrakash Surya 	return (total_evicted);
4734fa9e4066Sahrens }
4735fa9e4066Sahrens 
4736fa9e4066Sahrens void
4737244781f1SPrakash Surya arc_flush(spa_t *spa, boolean_t retry)
4738fa9e4066Sahrens {
4739ac05c741SMark Maybee 	uint64_t guid = 0;
4740ac05c741SMark Maybee 
4741244781f1SPrakash Surya 	/*
4742dcbf3bd6SGeorge Wilson 	 * If retry is B_TRUE, a spa must not be specified since we have
4743244781f1SPrakash Surya 	 * no good way to determine if all of a spa's buffers have been
4744244781f1SPrakash Surya 	 * evicted from an arc state.
4745244781f1SPrakash Surya 	 */
4746244781f1SPrakash Surya 	ASSERT(!retry || spa == 0);
4747244781f1SPrakash Surya 
474889c86e32SChris Williamson 	if (spa != NULL)
4749e9103aaeSGarrett D'Amore 		guid = spa_load_guid(spa);
4750ac05c741SMark Maybee 
4751244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
4752244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
4753244781f1SPrakash Surya 
4754244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
4755244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
4756874395d5Smaybee 
4757244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
4758244781f1SPrakash Surya 	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
4759244781f1SPrakash Surya 
4760244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
4761244781f1SPrakash Surya 	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
4762fa9e4066Sahrens }
4763fa9e4066Sahrens 
4764de753e34SBrad Lewis static void
4765de753e34SBrad Lewis arc_reduce_target_size(int64_t to_free)
4766fa9e4066Sahrens {
47673a2d8a1bSPaul Dagnelie 	uint64_t asize = aggsum_value(&arc_size);
476844cb6abcSbmc 	if (arc_c > arc_c_min) {
4769fa9e4066Sahrens 
477044cb6abcSbmc 		if (arc_c > arc_c_min + to_free)
477144cb6abcSbmc 			atomic_add_64(&arc_c, -to_free);
477249e3519aSmaybee 		else
477344cb6abcSbmc 			arc_c = arc_c_min;
477444cb6abcSbmc 
477544cb6abcSbmc 		atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
47763a2d8a1bSPaul Dagnelie 		if (asize < arc_c)
47773a2d8a1bSPaul Dagnelie 			arc_c = MAX(asize, arc_c_min);
477844cb6abcSbmc 		if (arc_p > arc_c)
477944cb6abcSbmc 			arc_p = (arc_c >> 1);
478044cb6abcSbmc 		ASSERT(arc_c >= arc_c_min);
478144cb6abcSbmc 		ASSERT((int64_t)arc_p >= 0);
478249e3519aSmaybee 	}
4783fa9e4066Sahrens 
4784de753e34SBrad Lewis 	if (asize > arc_c) {
4785de753e34SBrad Lewis 		/* See comment in arc_adjust_cb_check() on why lock+flag */
4786de753e34SBrad Lewis 		mutex_enter(&arc_adjust_lock);
4787de753e34SBrad Lewis 		arc_adjust_needed = B_TRUE;
4788de753e34SBrad Lewis 		mutex_exit(&arc_adjust_lock);
4789de753e34SBrad Lewis 		zthr_wakeup(arc_adjust_zthr);
4790de753e34SBrad Lewis 	}
4791fa9e4066Sahrens }
4792fa9e4066Sahrens 
47932ec99e3eSMatthew Ahrens typedef enum free_memory_reason_t {
47942ec99e3eSMatthew Ahrens 	FMR_UNKNOWN,
47952ec99e3eSMatthew Ahrens 	FMR_NEEDFREE,
47962ec99e3eSMatthew Ahrens 	FMR_LOTSFREE,
47972ec99e3eSMatthew Ahrens 	FMR_SWAPFS_MINFREE,
47982ec99e3eSMatthew Ahrens 	FMR_PAGES_PP_MAXIMUM,
47992ec99e3eSMatthew Ahrens 	FMR_HEAP_ARENA,
48002ec99e3eSMatthew Ahrens 	FMR_ZIO_ARENA,
48012ec99e3eSMatthew Ahrens } free_memory_reason_t;
48022ec99e3eSMatthew Ahrens 
48032ec99e3eSMatthew Ahrens int64_t last_free_memory;
48042ec99e3eSMatthew Ahrens free_memory_reason_t last_free_reason;
48052ec99e3eSMatthew Ahrens 
480694dd93aeSGeorge Wilson /*
48072ec99e3eSMatthew Ahrens  * Additional reserve of pages for pp_reserve.
480894dd93aeSGeorge Wilson  */
48092ec99e3eSMatthew Ahrens int64_t arc_pages_pp_reserve = 64;
4810fa9e4066Sahrens 
48112ec99e3eSMatthew Ahrens /*
48122ec99e3eSMatthew Ahrens  * Additional reserve of pages for swapfs.
48132ec99e3eSMatthew Ahrens  */
48142ec99e3eSMatthew Ahrens int64_t arc_swapfs_reserve = 64;
48153cff2f43Sstans 
48162ec99e3eSMatthew Ahrens /*
48172ec99e3eSMatthew Ahrens  * Return the amount of memory that can be consumed before reclaim will be
48182ec99e3eSMatthew Ahrens  * needed.  Positive if there is sufficient free memory, negative indicates
48192ec99e3eSMatthew Ahrens  * the amount of memory that needs to be freed up.
48202ec99e3eSMatthew Ahrens  */
48212ec99e3eSMatthew Ahrens static int64_t
48222ec99e3eSMatthew Ahrens arc_available_memory(void)
48232ec99e3eSMatthew Ahrens {
48242ec99e3eSMatthew Ahrens 	int64_t lowest = INT64_MAX;
48252ec99e3eSMatthew Ahrens 	int64_t n;
48262ec99e3eSMatthew Ahrens 	free_memory_reason_t r = FMR_UNKNOWN;
48273cff2f43Sstans 
48282ec99e3eSMatthew Ahrens #ifdef _KERNEL
48292ec99e3eSMatthew Ahrens 	if (needfree > 0) {
48302ec99e3eSMatthew Ahrens 		n = PAGESIZE * (-needfree);
48312ec99e3eSMatthew Ahrens 		if (n < lowest) {
48322ec99e3eSMatthew Ahrens 			lowest = n;
48332ec99e3eSMatthew Ahrens 			r = FMR_NEEDFREE;
48342ec99e3eSMatthew Ahrens 		}
48352ec99e3eSMatthew Ahrens 	}
4836fa9e4066Sahrens 
4837fa9e4066Sahrens 	/*
4838fa9e4066Sahrens 	 * check that we're out of range of the pageout scanner.  It starts to
4839fa9e4066Sahrens 	 * schedule paging if freemem is less than lotsfree and needfree.
4840fa9e4066Sahrens 	 * lotsfree is the high-water mark for pageout, and needfree is the
4841fa9e4066Sahrens 	 * number of needed free pages.  We add extra pages here to make sure
4842fa9e4066Sahrens 	 * the scanner doesn't start up while we're freeing memory.
4843fa9e4066Sahrens 	 */
48442ec99e3eSMatthew Ahrens 	n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
48452ec99e3eSMatthew Ahrens 	if (n < lowest) {
48462ec99e3eSMatthew Ahrens 		lowest = n;
48472ec99e3eSMatthew Ahrens 		r = FMR_LOTSFREE;
48482ec99e3eSMatthew Ahrens 	}
4849fa9e4066Sahrens 
4850fa9e4066Sahrens 	/*
4851fa9e4066Sahrens 	 * check to make sure that swapfs has enough space so that anon
4852fa94a07fSbrendan 	 * reservations can still succeed. anon_resvmem() checks that the
4853fa9e4066Sahrens 	 * availrmem is greater than swapfs_minfree, and the number of reserved
4854fa9e4066Sahrens 	 * swap pages.  We also add a bit of extra here just to prevent
4855fa9e4066Sahrens 	 * circumstances from getting really dire.
4856fa9e4066Sahrens 	 */
48572ec99e3eSMatthew Ahrens 	n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
48582ec99e3eSMatthew Ahrens 	    desfree - arc_swapfs_reserve);
48592ec99e3eSMatthew Ahrens 	if (n < lowest) {
48602ec99e3eSMatthew Ahrens 		lowest = n;
48612ec99e3eSMatthew Ahrens 		r = FMR_SWAPFS_MINFREE;
48622ec99e3eSMatthew Ahrens 	}
48632ec99e3eSMatthew Ahrens 
4864fa9e4066Sahrens 
4865cf746768SBryan Cantrill 	/*
4866cf746768SBryan Cantrill 	 * Check that we have enough availrmem that memory locking (e.g., via
4867cf746768SBryan Cantrill 	 * mlock(3C) or memcntl(2)) can still succeed.  (pages_pp_maximum
4868cf746768SBryan Cantrill 	 * stores the number of pages that cannot be locked; when availrmem
4869cf746768SBryan Cantrill 	 * drops below pages_pp_maximum, page locking mechanisms such as
4870cf746768SBryan Cantrill 	 * page_pp_lock() will fail.)
4871cf746768SBryan Cantrill 	 */
48722ec99e3eSMatthew Ahrens 	n = PAGESIZE * (availrmem - pages_pp_maximum -
48732ec99e3eSMatthew Ahrens 	    arc_pages_pp_reserve);
48742ec99e3eSMatthew Ahrens 	if (n < lowest) {
48752ec99e3eSMatthew Ahrens 		lowest = n;
48762ec99e3eSMatthew Ahrens 		r = FMR_PAGES_PP_MAXIMUM;
48772ec99e3eSMatthew Ahrens 	}
4878cf746768SBryan Cantrill 
48795dc8af33Smaybee #if defined(__i386)
4880fa9e4066Sahrens 	/*
4881fa9e4066Sahrens 	 * If we're on an i386 platform, it's possible that we'll exhaust the
4882fa9e4066Sahrens 	 * kernel heap space before we ever run out of available physical
4883fa9e4066Sahrens 	 * memory.  Most checks of the size of the heap_area compare against
4884fa9e4066Sahrens 	 * tune.t_minarmem, which is the minimum available real memory that we
4885fa9e4066Sahrens 	 * can have in the system.  However, this is generally fixed at 25 pages
4886fa9e4066Sahrens 	 * which is so low that it's useless.  In this comparison, we seek to
4887fa9e4066Sahrens 	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
4888fa94a07fSbrendan 	 * heap is allocated.  (Or, in the calculation, if less than 1/4th is
4889fa9e4066Sahrens 	 * free)
4890fa9e4066Sahrens 	 */
48910dd053d7SPrakash Surya 	n = (int64_t)vmem_size(heap_arena, VMEM_FREE) -
48922ec99e3eSMatthew Ahrens 	    (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2);
48932ec99e3eSMatthew Ahrens 	if (n < lowest) {
48942ec99e3eSMatthew Ahrens 		lowest = n;
48952ec99e3eSMatthew Ahrens 		r = FMR_HEAP_ARENA;
48962ec99e3eSMatthew Ahrens 	}
4897fa9e4066Sahrens #endif
4898fa9e4066Sahrens 
489994dd93aeSGeorge Wilson 	/*
490094dd93aeSGeorge Wilson 	 * If zio data pages are being allocated out of a separate heap segment,
490194dd93aeSGeorge Wilson 	 * then enforce that the size of available vmem for this arena remains
49020dd053d7SPrakash Surya 	 * above about 1/4th (1/(2^arc_zio_arena_free_shift)) free.
490394dd93aeSGeorge Wilson 	 *
49040dd053d7SPrakash Surya 	 * Note that reducing the arc_zio_arena_free_shift keeps more virtual
49050dd053d7SPrakash Surya 	 * memory (in the zio_arena) free, which can avoid memory
49060dd053d7SPrakash Surya 	 * fragmentation issues.
490794dd93aeSGeorge Wilson 	 */
49082ec99e3eSMatthew Ahrens 	if (zio_arena != NULL) {
49090dd053d7SPrakash Surya 		n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
49100dd053d7SPrakash Surya 		    (vmem_size(zio_arena, VMEM_ALLOC) >>
49110dd053d7SPrakash Surya 		    arc_zio_arena_free_shift);
49122ec99e3eSMatthew Ahrens 		if (n < lowest) {
49132ec99e3eSMatthew Ahrens 			lowest = n;
49142ec99e3eSMatthew Ahrens 			r = FMR_ZIO_ARENA;
49152ec99e3eSMatthew Ahrens 		}
49162ec99e3eSMatthew Ahrens 	}
4917fa9e4066Sahrens #else
49182ec99e3eSMatthew Ahrens 	/* Every 100 calls, free a small amount */
4919fa9e4066Sahrens 	if (spa_get_random(100) == 0)
49202ec99e3eSMatthew Ahrens 		lowest = -1024;
4921fa9e4066Sahrens #endif
49222ec99e3eSMatthew Ahrens 
49232ec99e3eSMatthew Ahrens 	last_free_memory = lowest;
49242ec99e3eSMatthew Ahrens 	last_free_reason = r;
49252ec99e3eSMatthew Ahrens 
49262ec99e3eSMatthew Ahrens 	return (lowest);
49272ec99e3eSMatthew Ahrens }
49282ec99e3eSMatthew Ahrens 
49292ec99e3eSMatthew Ahrens 
49302ec99e3eSMatthew Ahrens /*
49312ec99e3eSMatthew Ahrens  * Determine if the system is under memory pressure and is asking
4932dcbf3bd6SGeorge Wilson  * to reclaim memory. A return value of B_TRUE indicates that the system
49332ec99e3eSMatthew Ahrens  * is under memory pressure and that the arc should adjust accordingly.
49342ec99e3eSMatthew Ahrens  */
49352ec99e3eSMatthew Ahrens static boolean_t
49362ec99e3eSMatthew Ahrens arc_reclaim_needed(void)
49372ec99e3eSMatthew Ahrens {
49382ec99e3eSMatthew Ahrens 	return (arc_available_memory() < 0);
4939fa9e4066Sahrens }
4940fa9e4066Sahrens 
4941fa9e4066Sahrens static void
4942de753e34SBrad Lewis arc_kmem_reap_soon(void)
4943fa9e4066Sahrens {
4944fa9e4066Sahrens 	size_t			i;
4945fa9e4066Sahrens 	kmem_cache_t		*prev_cache = NULL;
4946ad23a2dbSjohansen 	kmem_cache_t		*prev_data_cache = NULL;
4947fa9e4066Sahrens 	extern kmem_cache_t	*zio_buf_cache[];
4948ad23a2dbSjohansen 	extern kmem_cache_t	*zio_data_buf_cache[];
494983803b51SGeorge Wilson 	extern kmem_cache_t	*range_seg_cache;
4950770499e1SDan Kimmel 	extern kmem_cache_t	*abd_chunk_cache;
4951fa9e4066Sahrens 
4952033f9833Sek #ifdef _KERNEL
49533a2d8a1bSPaul Dagnelie 	if (aggsum_compare(&arc_meta_used, arc_meta_limit) >= 0) {
49540e8c6158Smaybee 		/*
49550e8c6158Smaybee 		 * We are exceeding our meta-data cache limit.
49560e8c6158Smaybee 		 * Purge some DNLC entries to release holds on meta-data.
49570e8c6158Smaybee 		 */
49580e8c6158Smaybee 		dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
49590e8c6158Smaybee 	}
49605dc8af33Smaybee #if defined(__i386)
49615dc8af33Smaybee 	/*
49625dc8af33Smaybee 	 * Reclaim unused memory from all kmem caches.
49635dc8af33Smaybee 	 */
49645dc8af33Smaybee 	kmem_reap();
49655dc8af33Smaybee #endif
4966033f9833Sek #endif
4967033f9833Sek 
4968fa9e4066Sahrens 	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
4969fa9e4066Sahrens 		if (zio_buf_cache[i] != prev_cache) {
4970fa9e4066Sahrens 			prev_cache = zio_buf_cache[i];
497136a64e62STim Kordas 			kmem_cache_reap_soon(zio_buf_cache[i]);
4972fa9e4066Sahrens 		}
4973ad23a2dbSjohansen 		if (zio_data_buf_cache[i] != prev_data_cache) {
4974ad23a2dbSjohansen 			prev_data_cache = zio_data_buf_cache[i];
497536a64e62STim Kordas 			kmem_cache_reap_soon(zio_data_buf_cache[i]);
4976ad23a2dbSjohansen 		}
4977fa9e4066Sahrens 	}
497836a64e62STim Kordas 	kmem_cache_reap_soon(abd_chunk_cache);
497936a64e62STim Kordas 	kmem_cache_reap_soon(buf_cache);
498036a64e62STim Kordas 	kmem_cache_reap_soon(hdr_full_cache);
498136a64e62STim Kordas 	kmem_cache_reap_soon(hdr_l2only_cache);
498236a64e62STim Kordas 	kmem_cache_reap_soon(range_seg_cache);
498394dd93aeSGeorge Wilson 
49842ec99e3eSMatthew Ahrens 	if (zio_arena != NULL) {
49852ec99e3eSMatthew Ahrens 		/*
49862ec99e3eSMatthew Ahrens 		 * Ask the vmem arena to reclaim unused memory from its
49872ec99e3eSMatthew Ahrens 		 * quantum caches.
49882ec99e3eSMatthew Ahrens 		 */
498994dd93aeSGeorge Wilson 		vmem_qcache_reap(zio_arena);
49902ec99e3eSMatthew Ahrens 	}
4991fa9e4066Sahrens }
4992fa9e4066Sahrens 
4993de753e34SBrad Lewis /* ARGSUSED */
4994de753e34SBrad Lewis static boolean_t
4995de753e34SBrad Lewis arc_adjust_cb_check(void *arg, zthr_t *zthr)
4996de753e34SBrad Lewis {
4997de753e34SBrad Lewis 	/*
4998de753e34SBrad Lewis 	 * This is necessary in order for the mdb ::arc dcmd to
4999de753e34SBrad Lewis 	 * show up to date information. Since the ::arc command
5000de753e34SBrad Lewis 	 * does not call the kstat's update function, without
5001de753e34SBrad Lewis 	 * this call, the command may show stale stats for the
5002de753e34SBrad Lewis 	 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
5003de753e34SBrad Lewis 	 * with this change, the data might be up to 1 second
5004de753e34SBrad Lewis 	 * out of date(the arc_adjust_zthr has a maximum sleep
5005de753e34SBrad Lewis 	 * time of 1 second); but that should suffice.  The
5006de753e34SBrad Lewis 	 * arc_state_t structures can be queried directly if more
5007de753e34SBrad Lewis 	 * accurate information is needed.
5008de753e34SBrad Lewis 	 */
5009de753e34SBrad Lewis 	if (arc_ksp != NULL)
5010de753e34SBrad Lewis 		arc_ksp->ks_update(arc_ksp, KSTAT_READ);
5011de753e34SBrad Lewis 
5012de753e34SBrad Lewis 	/*
5013de753e34SBrad Lewis 	 * We have to rely on arc_get_data_impl() to tell us when to adjust,
5014de753e34SBrad Lewis 	 * rather than checking if we are overflowing here, so that we are
5015de753e34SBrad Lewis 	 * sure to not leave arc_get_data_impl() waiting on
5016de753e34SBrad Lewis 	 * arc_adjust_waiters_cv.  If we have become "not overflowing" since
5017de753e34SBrad Lewis 	 * arc_get_data_impl() checked, we need to wake it up.  We could
5018de753e34SBrad Lewis 	 * broadcast the CV here, but arc_get_data_impl() may have not yet
5019de753e34SBrad Lewis 	 * gone to sleep.  We would need to use a mutex to ensure that this
5020de753e34SBrad Lewis 	 * function doesn't broadcast until arc_get_data_impl() has gone to
5021de753e34SBrad Lewis 	 * sleep (e.g. the arc_adjust_lock).  However, the lock ordering of
5022de753e34SBrad Lewis 	 * such a lock would necessarily be incorrect with respect to the
5023de753e34SBrad Lewis 	 * zthr_lock, which is held before this function is called, and is
5024de753e34SBrad Lewis 	 * held by arc_get_data_impl() when it calls zthr_wakeup().
5025de753e34SBrad Lewis 	 */
5026de753e34SBrad Lewis 	return (arc_adjust_needed);
5027de753e34SBrad Lewis }
5028de753e34SBrad Lewis 
5029244781f1SPrakash Surya /*
5030de753e34SBrad Lewis  * Keep arc_size under arc_c by running arc_adjust which evicts data
5031de753e34SBrad Lewis  * from the ARC.
5032244781f1SPrakash Surya  */
50333f7978d0SAlan Somers /* ARGSUSED */
50346a316e1fSSerapheim Dimitropoulos static void
5035de753e34SBrad Lewis arc_adjust_cb(void *arg, zthr_t *zthr)
5036fa9e4066Sahrens {
5037de753e34SBrad Lewis 	uint64_t evicted = 0;
5038fa9e4066Sahrens 
5039de753e34SBrad Lewis 	/* Evict from cache */
5040de753e34SBrad Lewis 	evicted = arc_adjust();
5041244781f1SPrakash Surya 
5042de753e34SBrad Lewis 	/*
5043de753e34SBrad Lewis 	 * If evicted is zero, we couldn't evict anything
5044de753e34SBrad Lewis 	 * via arc_adjust(). This could be due to hash lock
5045de753e34SBrad Lewis 	 * collisions, but more likely due to the majority of
5046de753e34SBrad Lewis 	 * arc buffers being unevictable. Therefore, even if
5047de753e34SBrad Lewis 	 * arc_size is above arc_c, another pass is unlikely to
5048de753e34SBrad Lewis 	 * be helpful and could potentially cause us to enter an
5049de753e34SBrad Lewis 	 * infinite loop.  Additionally, zthr_iscancelled() is
5050de753e34SBrad Lewis 	 * checked here so that if the arc is shutting down, the
5051de753e34SBrad Lewis 	 * broadcast will wake any remaining arc adjust waiters.
5052de753e34SBrad Lewis 	 */
5053de753e34SBrad Lewis 	mutex_enter(&arc_adjust_lock);
5054de753e34SBrad Lewis 	arc_adjust_needed = !zthr_iscancelled(arc_adjust_zthr) &&
5055de753e34SBrad Lewis 	    evicted > 0 && aggsum_compare(&arc_size, arc_c) > 0;
5056de753e34SBrad Lewis 	if (!arc_adjust_needed) {
5057dcbf3bd6SGeorge Wilson 		/*
5058de753e34SBrad Lewis 		 * We're either no longer overflowing, or we
5059de753e34SBrad Lewis 		 * can't evict anything more, so we should wake
5060de753e34SBrad Lewis 		 * up any waiters.
5061dcbf3bd6SGeorge Wilson 		 */
5062de753e34SBrad Lewis 		cv_broadcast(&arc_adjust_waiters_cv);
5063de753e34SBrad Lewis 	}
5064de753e34SBrad Lewis 	mutex_exit(&arc_adjust_lock);
5065de753e34SBrad Lewis }
5066244781f1SPrakash Surya 
5067de753e34SBrad Lewis /* ARGSUSED */
5068de753e34SBrad Lewis static boolean_t
5069de753e34SBrad Lewis arc_reap_cb_check(void *arg, zthr_t *zthr)
5070de753e34SBrad Lewis {
5071de753e34SBrad Lewis 	int64_t free_memory = arc_available_memory();
5072de753e34SBrad Lewis 
5073de753e34SBrad Lewis 	/*
5074de753e34SBrad Lewis 	 * If a kmem reap is already active, don't schedule more.  We must
5075de753e34SBrad Lewis 	 * check for this because kmem_cache_reap_soon() won't actually
5076de753e34SBrad Lewis 	 * block on the cache being reaped (this is to prevent callers from
5077de753e34SBrad Lewis 	 * becoming implicitly blocked by a system-wide kmem reap -- which,
5078de753e34SBrad Lewis 	 * on a system with many, many full magazines, can take minutes).
5079de753e34SBrad Lewis 	 */
5080de753e34SBrad Lewis 	if (!kmem_cache_reap_active() &&
5081de753e34SBrad Lewis 	    free_memory < 0) {
5082de753e34SBrad Lewis 		arc_no_grow = B_TRUE;
5083de753e34SBrad Lewis 		arc_warm = B_TRUE;
5084405a5a0fSMatthew Ahrens 		/*
5085de753e34SBrad Lewis 		 * Wait at least zfs_grow_retry (default 60) seconds
5086de753e34SBrad Lewis 		 * before considering growing.
5087405a5a0fSMatthew Ahrens 		 */
5088de753e34SBrad Lewis 		arc_growtime = gethrtime() + SEC2NSEC(arc_grow_retry);
5089de753e34SBrad Lewis 		return (B_TRUE);
5090de753e34SBrad Lewis 	} else if (free_memory < arc_c >> arc_no_grow_shift) {
5091de753e34SBrad Lewis 		arc_no_grow = B_TRUE;
5092de753e34SBrad Lewis 	} else if (gethrtime() >= arc_growtime) {
5093de753e34SBrad Lewis 		arc_no_grow = B_FALSE;
5094de753e34SBrad Lewis 	}
5095405a5a0fSMatthew Ahrens 
5096de753e34SBrad Lewis 	return (B_FALSE);
5097de753e34SBrad Lewis }
5098fa9e4066Sahrens 
5099de753e34SBrad Lewis /*
5100de753e34SBrad Lewis  * Keep enough free memory in the system by reaping the ARC's kmem
5101de753e34SBrad Lewis  * caches.  To cause more slabs to be reapable, we may reduce the
5102de753e34SBrad Lewis  * target size of the cache (arc_c), causing the arc_adjust_cb()
5103de753e34SBrad Lewis  * to free more buffers.
5104de753e34SBrad Lewis  */
5105de753e34SBrad Lewis /* ARGSUSED */
51066a316e1fSSerapheim Dimitropoulos static void
5107de753e34SBrad Lewis arc_reap_cb(void *arg, zthr_t *zthr)
5108de753e34SBrad Lewis {
5109de753e34SBrad Lewis 	int64_t free_memory;
5110fa9e4066Sahrens 
5111de753e34SBrad Lewis 	/*
5112de753e34SBrad Lewis 	 * Kick off asynchronous kmem_reap()'s of all our caches.
5113de753e34SBrad Lewis 	 */
5114de753e34SBrad Lewis 	arc_kmem_reap_soon();
5115fa9e4066Sahrens 
5116de753e34SBrad Lewis 	/*
5117de753e34SBrad Lewis 	 * Wait at least arc_kmem_cache_reap_retry_ms between
5118de753e34SBrad Lewis 	 * arc_kmem_reap_soon() calls. Without this check it is possible to
5119de753e34SBrad Lewis 	 * end up in a situation where we spend lots of time reaping
5120de753e34SBrad Lewis 	 * caches, while we're near arc_c_min.  Waiting here also gives the
5121de753e34SBrad Lewis 	 * subsequent free memory check a chance of finding that the
5122de753e34SBrad Lewis 	 * asynchronous reap has already freed enough memory, and we don't
5123de753e34SBrad Lewis 	 * need to call arc_reduce_target_size().
5124de753e34SBrad Lewis 	 */
5125de753e34SBrad Lewis 	delay((hz * arc_kmem_cache_reap_retry_ms + 999) / 1000);
5126de753e34SBrad Lewis 
5127de753e34SBrad Lewis 	/*
5128de753e34SBrad Lewis 	 * Reduce the target size as needed to maintain the amount of free
5129de753e34SBrad Lewis 	 * memory in the system at a fraction of the arc_size (1/128th by
5130de753e34SBrad Lewis 	 * default).  If oversubscribed (free_memory < 0) then reduce the
5131de753e34SBrad Lewis 	 * target arc_size by the deficit amount plus the fractional
5132de753e34SBrad Lewis 	 * amount.  If free memory is positive but less then the fractional
5133de753e34SBrad Lewis 	 * amount, reduce by what is needed to hit the fractional amount.
5134de753e34SBrad Lewis 	 */
5135de753e34SBrad Lewis 	free_memory = arc_available_memory();
51362ec99e3eSMatthew Ahrens 
5137de753e34SBrad Lewis 	int64_t to_free =
5138de753e34SBrad Lewis 	    (arc_c >> arc_shrink_shift) - free_memory;
5139de753e34SBrad Lewis 	if (to_free > 0) {
51402ec99e3eSMatthew Ahrens #ifdef _KERNEL
5141de753e34SBrad Lewis 		to_free = MAX(to_free, ptob(needfree));
51422ec99e3eSMatthew Ahrens #endif
5143de753e34SBrad Lewis 		arc_reduce_target_size(to_free);
5144244781f1SPrakash Surya 	}
5145244781f1SPrakash Surya }
5146244781f1SPrakash Surya 
5147ea8dc4b6Seschrock /*
5148ea8dc4b6Seschrock  * Adapt arc info given the number of bytes we are trying to add and
5149*eb633035STom Caputi  * the state that we are coming from.  This function is only called
5150ea8dc4b6Seschrock  * when we are adding new content to the cache.
5151ea8dc4b6Seschrock  */
5152fa9e4066Sahrens static void
5153ea8dc4b6Seschrock arc_adapt(int bytes, arc_state_t *state)
5154fa9e4066Sahrens {
5155ea8dc4b6Seschrock 	int mult;
51565a98e54bSBrendan Gregg - Sun Microsystems 	uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
5157e914ace2STim Schumacher 	int64_t mrug_size = zfs_refcount_count(&arc_mru_ghost->arcs_size);
5158e914ace2STim Schumacher 	int64_t mfug_size = zfs_refcount_count(&arc_mfu_ghost->arcs_size);
5159ea8dc4b6Seschrock 
5160fa94a07fSbrendan 	if (state == arc_l2c_only)
5161fa94a07fSbrendan 		return;
5162fa94a07fSbrendan 
5163ea8dc4b6Seschrock 	ASSERT(bytes > 0);
5164fa9e4066Sahrens 	/*
5165ea8dc4b6Seschrock 	 * Adapt the target size of the MRU list:
5166ea8dc4b6Seschrock 	 *	- if we just hit in the MRU ghost list, then increase
5167ea8dc4b6Seschrock 	 *	  the target size of the MRU list.
5168ea8dc4b6Seschrock 	 *	- if we just hit in the MFU ghost list, then increase
5169ea8dc4b6Seschrock 	 *	  the target size of the MFU list by decreasing the
5170ea8dc4b6Seschrock 	 *	  target size of the MRU list.
5171fa9e4066Sahrens 	 */
517244cb6abcSbmc 	if (state == arc_mru_ghost) {
51732fd872a7SPrakash Surya 		mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
51743e4e8481STom Erickson 		mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
5175ea8dc4b6Seschrock 
51765a98e54bSBrendan Gregg - Sun Microsystems 		arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
517744cb6abcSbmc 	} else if (state == arc_mfu_ghost) {
51785a98e54bSBrendan Gregg - Sun Microsystems 		uint64_t delta;
51795a98e54bSBrendan Gregg - Sun Microsystems 
51802fd872a7SPrakash Surya 		mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
51813e4e8481STom Erickson 		mult = MIN(mult, 10);
5182ea8dc4b6Seschrock 
51835a98e54bSBrendan Gregg - Sun Microsystems 		delta = MIN(bytes * mult, arc_p);
51845a98e54bSBrendan Gregg - Sun Microsystems 		arc_p = MAX(arc_p_min, arc_p - delta);
5185ea8dc4b6Seschrock 	}
518644cb6abcSbmc 	ASSERT((int64_t)arc_p >= 0);
5187fa9e4066Sahrens 
5188de753e34SBrad Lewis 	/*
5189de753e34SBrad Lewis 	 * Wake reap thread if we do not have any available memory
5190de753e34SBrad Lewis 	 */
5191fa9e4066Sahrens 	if (arc_reclaim_needed()) {
5192de753e34SBrad Lewis 		zthr_wakeup(arc_reap_zthr);
5193fa9e4066Sahrens 		return;
5194fa9e4066Sahrens 	}
5195fa9e4066Sahrens 
5196de753e34SBrad Lewis 
519744cb6abcSbmc 	if (arc_no_grow)
5198fa9e4066Sahrens 		return;
5199fa9e4066Sahrens 
520044cb6abcSbmc 	if (arc_c >= arc_c_max)
5201ea8dc4b6Seschrock 		return;
5202ea8dc4b6Seschrock 
5203fa9e4066Sahrens 	/*
5204ea8dc4b6Seschrock 	 * If we're within (2 * maxblocksize) bytes of the target
5205ea8dc4b6Seschrock 	 * cache size, increment the target cache size
5206fa9e4066Sahrens 	 */
52073a2d8a1bSPaul Dagnelie 	if (aggsum_compare(&arc_size, arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) >
52083a2d8a1bSPaul Dagnelie 	    0) {
520944cb6abcSbmc 		atomic_add_64(&arc_c, (int64_t)bytes);
521044cb6abcSbmc 		if (arc_c > arc_c_max)
521144cb6abcSbmc 			arc_c = arc_c_max;
521244cb6abcSbmc 		else if (state == arc_anon)
521344cb6abcSbmc 			atomic_add_64(&arc_p, (int64_t)bytes);
521444cb6abcSbmc 		if (arc_p > arc_c)
521544cb6abcSbmc 			arc_p = arc_c;
5216fa9e4066Sahrens 	}
521744cb6abcSbmc 	ASSERT((int64_t)arc_p >= 0);
5218fa9e4066Sahrens }
5219fa9e4066Sahrens 
5220fa9e4066Sahrens /*
5221244781f1SPrakash Surya  * Check if arc_size has grown past our upper threshold, determined by
5222244781f1SPrakash Surya  * zfs_arc_overflow_shift.
5223fa9e4066Sahrens  */
5224244781f1SPrakash Surya static boolean_t
5225244781f1SPrakash Surya arc_is_overflowing(void)
5226fa9e4066Sahrens {
5227244781f1SPrakash Surya 	/* Always allow at least one block of overflow */
5228244781f1SPrakash Surya 	uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
5229244781f1SPrakash Surya 	    arc_c >> zfs_arc_overflow_shift);
5230fa9e4066Sahrens 
52313a2d8a1bSPaul Dagnelie 	/*
52323a2d8a1bSPaul Dagnelie 	 * We just compare the lower bound here for performance reasons. Our
52333a2d8a1bSPaul Dagnelie 	 * primary goals are to make sure that the arc never grows without
52343a2d8a1bSPaul Dagnelie 	 * bound, and that it can reach its maximum size. This check
52353a2d8a1bSPaul Dagnelie 	 * accomplishes both goals. The maximum amount we could run over by is
52363a2d8a1bSPaul Dagnelie 	 * 2 * aggsum_borrow_multiplier * NUM_CPUS * the average size of a block
52373a2d8a1bSPaul Dagnelie 	 * in the ARC. In practice, that's in the tens of MB, which is low
52383a2d8a1bSPaul Dagnelie 	 * enough to be safe.
52393a2d8a1bSPaul Dagnelie 	 */
52403a2d8a1bSPaul Dagnelie 	return (aggsum_lower_bound(&arc_size) >= arc_c + overflow);
5241fa9e4066Sahrens }
5242fa9e4066Sahrens 
5243770499e1SDan Kimmel static abd_t *
5244770499e1SDan Kimmel arc_get_data_abd(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
5245770499e1SDan Kimmel {
5246770499e1SDan Kimmel 	arc_buf_contents_t type = arc_buf_type(hdr);
5247770499e1SDan Kimmel 
5248770499e1SDan Kimmel 	arc_get_data_impl(hdr, size, tag);
5249770499e1SDan Kimmel 	if (type == ARC_BUFC_METADATA) {
5250770499e1SDan Kimmel 		return (abd_alloc(size, B_TRUE));
5251770499e1SDan Kimmel 	} else {
5252770499e1SDan Kimmel 		ASSERT(type == ARC_BUFC_DATA);
5253770499e1SDan Kimmel 		return (abd_alloc(size, B_FALSE));
5254770499e1SDan Kimmel 	}
5255770499e1SDan Kimmel }
5256770499e1SDan Kimmel 
5257770499e1SDan Kimmel static void *
5258770499e1SDan Kimmel arc_get_data_buf(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
5259770499e1SDan Kimmel {
5260770499e1SDan Kimmel 	arc_buf_contents_t type = arc_buf_type(hdr);
5261770499e1SDan Kimmel 
5262770499e1SDan Kimmel 	arc_get_data_impl(hdr, size, tag);
5263770499e1SDan Kimmel 	if (type == ARC_BUFC_METADATA) {
5264770499e1SDan Kimmel 		return (zio_buf_alloc(size));
5265770499e1SDan Kimmel 	} else {
5266770499e1SDan Kimmel 		ASSERT(type == ARC_BUFC_DATA);
5267770499e1SDan Kimmel 		return (zio_data_buf_alloc(size));
5268770499e1SDan Kimmel 	}
5269770499e1SDan Kimmel }
5270770499e1SDan Kimmel 
5271fa9e4066Sahrens /*
5272dcbf3bd6SGeorge Wilson  * Allocate a block and return it to the caller. If we are hitting the
5273dcbf3bd6SGeorge Wilson  * hard limit for the cache size, we must sleep, waiting for the eviction
5274dcbf3bd6SGeorge Wilson  * thread to catch up. If we're past the target size but below the hard
5275dcbf3bd6SGeorge Wilson  * limit, we'll only signal the reclaim thread and continue on.
5276fa9e4066Sahrens  */
5277770499e1SDan Kimmel static void
5278770499e1SDan Kimmel arc_get_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
5279fa9e4066Sahrens {
5280770499e1SDan Kimmel 	arc_state_t *state = hdr->b_l1hdr.b_state;
5281770499e1SDan Kimmel 	arc_buf_contents_t type = arc_buf_type(hdr);
5282fa9e4066Sahrens 
528344eda4d7Smaybee 	arc_adapt(size, state);
5284fa9e4066Sahrens 
528544eda4d7Smaybee 	/*
5286244781f1SPrakash Surya 	 * If arc_size is currently overflowing, and has grown past our
5287244781f1SPrakash Surya 	 * upper limit, we must be adding data faster than the evict
5288244781f1SPrakash Surya 	 * thread can evict. Thus, to ensure we don't compound the
5289244781f1SPrakash Surya 	 * problem by adding more data and forcing arc_size to grow even
5290*eb633035STom Caputi 	 * further past its target size, we halt and wait for the
5291244781f1SPrakash Surya 	 * eviction thread to catch up.
5292244781f1SPrakash Surya 	 *
5293244781f1SPrakash Surya 	 * It's also possible that the reclaim thread is unable to evict
5294244781f1SPrakash Surya 	 * enough buffers to get arc_size below the overflow limit (e.g.
5295244781f1SPrakash Surya 	 * due to buffers being un-evictable, or hash lock collisions).
5296244781f1SPrakash Surya 	 * In this case, we want to proceed regardless if we're
5297244781f1SPrakash Surya 	 * overflowing; thus we don't use a while loop here.
529844eda4d7Smaybee 	 */
5299244781f1SPrakash Surya 	if (arc_is_overflowing()) {
5300de753e34SBrad Lewis 		mutex_enter(&arc_adjust_lock);
5301244781f1SPrakash Surya 
5302244781f1SPrakash Surya 		/*
5303244781f1SPrakash Surya 		 * Now that we've acquired the lock, we may no longer be
5304244781f1SPrakash Surya 		 * over the overflow limit, lets check.
5305244781f1SPrakash Surya 		 *
5306244781f1SPrakash Surya 		 * We're ignoring the case of spurious wake ups. If that
5307244781f1SPrakash Surya 		 * were to happen, it'd let this thread consume an ARC
5308244781f1SPrakash Surya 		 * buffer before it should have (i.e. before we're under
5309244781f1SPrakash Surya 		 * the overflow limit and were signalled by the reclaim
5310244781f1SPrakash Surya 		 * thread). As long as that is a rare occurrence, it
5311244781f1SPrakash Surya 		 * shouldn't cause any harm.
5312244781f1SPrakash Surya 		 */
5313244781f1SPrakash Surya 		if (arc_is_overflowing()) {
5314de753e34SBrad Lewis 			arc_adjust_needed = B_TRUE;
5315de753e34SBrad Lewis 			zthr_wakeup(arc_adjust_zthr);
5316de753e34SBrad Lewis 			(void) cv_wait(&arc_adjust_waiters_cv,
5317de753e34SBrad Lewis 			    &arc_adjust_lock);
5318ad23a2dbSjohansen 		}
5319de753e34SBrad Lewis 		mutex_exit(&arc_adjust_lock);
532044eda4d7Smaybee 	}
532144eda4d7Smaybee 
5322dcbf3bd6SGeorge Wilson 	VERIFY3U(hdr->b_type, ==, type);
5323244781f1SPrakash Surya 	if (type == ARC_BUFC_METADATA) {
5324244781f1SPrakash Surya 		arc_space_consume(size, ARC_SPACE_META);
5325fa9e4066Sahrens 	} else {
5326244781f1SPrakash Surya 		arc_space_consume(size, ARC_SPACE_DATA);
532744eda4d7Smaybee 	}
5328244781f1SPrakash Surya 
532944eda4d7Smaybee 	/*
533044eda4d7Smaybee 	 * Update the state size.  Note that ghost states have a
533144eda4d7Smaybee 	 * "ghost size" and so don't need to be updated.
533244eda4d7Smaybee 	 */
5333dcbf3bd6SGeorge Wilson 	if (!GHOST_STATE(state)) {
533444eda4d7Smaybee 
5335e914ace2STim Schumacher 		(void) zfs_refcount_add_many(&state->arcs_size, size, tag);
5336244781f1SPrakash Surya 
5337244781f1SPrakash Surya 		/*
5338244781f1SPrakash Surya 		 * If this is reached via arc_read, the link is
5339244781f1SPrakash Surya 		 * protected by the hash lock. If reached via
5340244781f1SPrakash Surya 		 * arc_buf_alloc, the header should not be accessed by
5341244781f1SPrakash Surya 		 * any other thread. And, if reached via arc_read_done,
5342244781f1SPrakash Surya 		 * the hash lock will protect it if it's found in the
5343244781f1SPrakash Surya 		 * hash table; otherwise no other thread should be
5344244781f1SPrakash Surya 		 * trying to [add|remove]_reference it.
5345244781f1SPrakash Surya 		 */
5346244781f1SPrakash Surya 		if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
5347e914ace2STim Schumacher 			ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5348e914ace2STim Schumacher 			(void) zfs_refcount_add_many(&state->arcs_esize[type],
5349dcbf3bd6SGeorge Wilson 			    size, tag);
5350fa9e4066Sahrens 		}
5351dcbf3bd6SGeorge Wilson 
5352641fbdaeSmaybee 		/*
5353641fbdaeSmaybee 		 * If we are growing the cache, and we are adding anonymous
535444cb6abcSbmc 		 * data, and we have outgrown arc_p, update arc_p
5355641fbdaeSmaybee 		 */
53563a2d8a1bSPaul Dagnelie 		if (aggsum_compare(&arc_size, arc_c) < 0 &&
53573a2d8a1bSPaul Dagnelie 		    hdr->b_l1hdr.b_state == arc_anon &&
5358e914ace2STim Schumacher 		    (zfs_refcount_count(&arc_anon->arcs_size) +
5359e914ace2STim Schumacher 		    zfs_refcount_count(&arc_mru->arcs_size) > arc_p))
536044cb6abcSbmc 			arc_p = MIN(arc_c, arc_p + size);
5361fa9e4066Sahrens 	}
5362770499e1SDan Kimmel }
5363770499e1SDan Kimmel 
5364770499e1SDan Kimmel static void
5365770499e1SDan Kimmel arc_free_data_abd(arc_buf_hdr_t *hdr, abd_t *abd, uint64_t size, void *tag)
5366770499e1SDan Kimmel {
5367770499e1SDan Kimmel 	arc_free_data_impl(hdr, size, tag);
5368770499e1SDan Kimmel 	abd_free(abd);
5369770499e1SDan Kimmel }
5370770499e1SDan Kimmel 
5371770499e1SDan Kimmel static void
5372770499e1SDan Kimmel arc_free_data_buf(arc_buf_hdr_t *hdr, void *buf, uint64_t size, void *tag)
5373770499e1SDan Kimmel {
5374770499e1SDan Kimmel 	arc_buf_contents_t type = arc_buf_type(hdr);
5375770499e1SDan Kimmel 
5376770499e1SDan Kimmel 	arc_free_data_impl(hdr, size, tag);
5377770499e1SDan Kimmel 	if (type == ARC_BUFC_METADATA) {
5378770499e1SDan Kimmel 		zio_buf_free(buf, size);
5379770499e1SDan Kimmel 	} else {
5380770499e1SDan Kimmel 		ASSERT(type == ARC_BUFC_DATA);
5381770499e1SDan Kimmel 		zio_data_buf_free(buf, size);
5382770499e1SDan Kimmel 	}
5383dcbf3bd6SGeorge Wilson }
5384dcbf3bd6SGeorge Wilson 
5385dcbf3bd6SGeorge Wilson /*
5386dcbf3bd6SGeorge Wilson  * Free the arc data buffer.
5387dcbf3bd6SGeorge Wilson  */
5388dcbf3bd6SGeorge Wilson static void
5389770499e1SDan Kimmel arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
5390dcbf3bd6SGeorge Wilson {
5391dcbf3bd6SGeorge Wilson 	arc_state_t *state = hdr->b_l1hdr.b_state;
5392dcbf3bd6SGeorge Wilson 	arc_buf_contents_t type = arc_buf_type(hdr);
5393dcbf3bd6SGeorge Wilson 
5394dcbf3bd6SGeorge Wilson 	/* protected by hash lock, if in the hash table */
5395dcbf3bd6SGeorge Wilson 	if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
5396e914ace2STim Schumacher 		ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5397dcbf3bd6SGeorge Wilson 		ASSERT(state != arc_anon && state != arc_l2c_only);
5398dcbf3bd6SGeorge Wilson 
5399e914ace2STim Schumacher 		(void) zfs_refcount_remove_many(&state->arcs_esize[type],
5400dcbf3bd6SGeorge Wilson 		    size, tag);
5401dcbf3bd6SGeorge Wilson 	}
5402e914ace2STim Schumacher 	(void) zfs_refcount_remove_many(&state->arcs_size, size, tag);
5403dcbf3bd6SGeorge Wilson 
5404dcbf3bd6SGeorge Wilson 	VERIFY3U(hdr->b_type, ==, type);
5405dcbf3bd6SGeorge Wilson 	if (type == ARC_BUFC_METADATA) {
5406dcbf3bd6SGeorge Wilson 		arc_space_return(size, ARC_SPACE_META);
5407dcbf3bd6SGeorge Wilson 	} else {
5408dcbf3bd6SGeorge Wilson 		ASSERT(type == ARC_BUFC_DATA);
5409dcbf3bd6SGeorge Wilson 		arc_space_return(size, ARC_SPACE_DATA);
5410dcbf3bd6SGeorge Wilson 	}
5411fa9e4066Sahrens }
5412fa9e4066Sahrens 
5413fa9e4066Sahrens /*
5414fa9e4066Sahrens  * This routine is called whenever a buffer is accessed.
5415ea8dc4b6Seschrock  * NOTE: the hash lock is dropped in this function.
5416fa9e4066Sahrens  */
5417fa9e4066Sahrens static void
54187adb730bSGeorge Wilson arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
5419fa9e4066Sahrens {
5420d3d50737SRafael Vanoni 	clock_t now;
5421d3d50737SRafael Vanoni 
5422fa9e4066Sahrens 	ASSERT(MUTEX_HELD(hash_lock));
542389c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
5424fa9e4066Sahrens 
542589c86e32SChris Williamson 	if (hdr->b_l1hdr.b_state == arc_anon) {
5426fa9e4066Sahrens 		/*
5427fa9e4066Sahrens 		 * This buffer is not in the cache, and does not
5428fa9e4066Sahrens 		 * appear in our "ghost" list.  Add the new buffer
5429fa9e4066Sahrens 		 * to the MRU state.
5430fa9e4066Sahrens 		 */
5431fa9e4066Sahrens 
543289c86e32SChris Williamson 		ASSERT0(hdr->b_l1hdr.b_arc_access);
543389c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
54347adb730bSGeorge Wilson 		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
54357adb730bSGeorge Wilson 		arc_change_state(arc_mru, hdr, hash_lock);
5436fa9e4066Sahrens 
543789c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mru) {
5438d3d50737SRafael Vanoni 		now = ddi_get_lbolt();
5439d3d50737SRafael Vanoni 
5440fa9e4066Sahrens 		/*
544113506d1eSmaybee 		 * If this buffer is here because of a prefetch, then either:
544213506d1eSmaybee 		 * - clear the flag if this is a "referencing" read
544313506d1eSmaybee 		 *   (any subsequent access will bump this into the MFU state).
544413506d1eSmaybee 		 * or
544513506d1eSmaybee 		 * - move the buffer to the head of the list if this is
544613506d1eSmaybee 		 *   another prefetch (to make it less likely to be evicted).
5447fa9e4066Sahrens 		 */
5448a3874b8bSToomas Soome 		if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5449e914ace2STim Schumacher 			if (zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
5450244781f1SPrakash Surya 				/* link protected by hash lock */
5451244781f1SPrakash Surya 				ASSERT(multilist_link_active(
545289c86e32SChris Williamson 				    &hdr->b_l1hdr.b_arc_node));
545313506d1eSmaybee 			} else {
5454a3874b8bSToomas Soome 				arc_hdr_clear_flags(hdr,
5455a3874b8bSToomas Soome 				    ARC_FLAG_PREFETCH |
5456a3874b8bSToomas Soome 				    ARC_FLAG_PRESCIENT_PREFETCH);
545744cb6abcSbmc 				ARCSTAT_BUMP(arcstat_mru_hits);
545813506d1eSmaybee 			}
545989c86e32SChris Williamson 			hdr->b_l1hdr.b_arc_access = now;
5460fa9e4066Sahrens 			return;
5461fa9e4066Sahrens 		}
5462fa9e4066Sahrens 
5463fa9e4066Sahrens 		/*
5464fa9e4066Sahrens 		 * This buffer has been "accessed" only once so far,
5465fa9e4066Sahrens 		 * but it is still in the cache. Move it to the MFU
5466fa9e4066Sahrens 		 * state.
5467fa9e4066Sahrens 		 */
546889c86e32SChris Williamson 		if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
5469fa9e4066Sahrens 			/*
5470fa9e4066Sahrens 			 * More than 125ms have passed since we
5471fa9e4066Sahrens 			 * instantiated this buffer.  Move it to the
5472fa9e4066Sahrens 			 * most frequently used state.
5473fa9e4066Sahrens 			 */
547489c86e32SChris Williamson 			hdr->b_l1hdr.b_arc_access = now;
54757adb730bSGeorge Wilson 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
54767adb730bSGeorge Wilson 			arc_change_state(arc_mfu, hdr, hash_lock);
5477fa9e4066Sahrens 		}
547844cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mru_hits);
547989c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
5480fa9e4066Sahrens 		arc_state_t	*new_state;
5481fa9e4066Sahrens 		/*
5482fa9e4066Sahrens 		 * This buffer has been "accessed" recently, but
5483fa9e4066Sahrens 		 * was evicted from the cache.  Move it to the
5484fa9e4066Sahrens 		 * MFU state.
5485fa9e4066Sahrens 		 */
5486fa9e4066Sahrens 
5487a3874b8bSToomas Soome 		if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
548844cb6abcSbmc 			new_state = arc_mru;
5489a3874b8bSToomas Soome 			if (zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) > 0) {
5490a3874b8bSToomas Soome 				arc_hdr_clear_flags(hdr,
5491a3874b8bSToomas Soome 				    ARC_FLAG_PREFETCH |
5492a3874b8bSToomas Soome 				    ARC_FLAG_PRESCIENT_PREFETCH);
5493a3874b8bSToomas Soome 			}
54947adb730bSGeorge Wilson 			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
5495fa9e4066Sahrens 		} else {
549644cb6abcSbmc 			new_state = arc_mfu;
54977adb730bSGeorge Wilson 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5498fa9e4066Sahrens 		}
5499fa9e4066Sahrens 
550089c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
55017adb730bSGeorge Wilson 		arc_change_state(new_state, hdr, hash_lock);
5502fa9e4066Sahrens 
550344cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
550489c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mfu) {
5505fa9e4066Sahrens 		/*
5506fa9e4066Sahrens 		 * This buffer has been accessed more than once and is
5507fa9e4066Sahrens 		 * still in the cache.  Keep it in the MFU state.
5508fa9e4066Sahrens 		 *
550913506d1eSmaybee 		 * NOTE: an add_reference() that occurred when we did
551013506d1eSmaybee 		 * the arc_read() will have kicked this off the list.
551113506d1eSmaybee 		 * If it was a prefetch, we will explicitly move it to
551213506d1eSmaybee 		 * the head of the list now.
5513fa9e4066Sahrens 		 */
551444cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mfu_hits);
551589c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
551689c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
551744cb6abcSbmc 		arc_state_t	*new_state = arc_mfu;
5518fa9e4066Sahrens 		/*
5519fa9e4066Sahrens 		 * This buffer has been accessed more than once but has
5520fa9e4066Sahrens 		 * been evicted from the cache.  Move it back to the
5521fa9e4066Sahrens 		 * MFU state.
5522fa9e4066Sahrens 		 */
5523fa9e4066Sahrens 
5524a3874b8bSToomas Soome 		if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
552513506d1eSmaybee 			/*
552613506d1eSmaybee 			 * This is a prefetch access...
552713506d1eSmaybee 			 * move this block back to the MRU state.
552813506d1eSmaybee 			 */
552944cb6abcSbmc 			new_state = arc_mru;
553013506d1eSmaybee 		}
553113506d1eSmaybee 
553289c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
55337adb730bSGeorge Wilson 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
55347adb730bSGeorge Wilson 		arc_change_state(new_state, hdr, hash_lock);
5535fa9e4066Sahrens 
553644cb6abcSbmc 		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
553789c86e32SChris Williamson 	} else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
5538fa94a07fSbrendan 		/*
5539fa94a07fSbrendan 		 * This buffer is on the 2nd Level ARC.
5540fa94a07fSbrendan 		 */
5541fa94a07fSbrendan 
554289c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
55437adb730bSGeorge Wilson 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
55447adb730bSGeorge Wilson 		arc_change_state(arc_mfu, hdr, hash_lock);
5545fa9e4066Sahrens 	} else {
5546fa9e4066Sahrens 		ASSERT(!"invalid arc state");
5547fa9e4066Sahrens 	}
5548fa9e4066Sahrens }
5549fa9e4066Sahrens 
55507b38fab6SAlexander Motin /*
55517b38fab6SAlexander Motin  * This routine is called by dbuf_hold() to update the arc_access() state
55527b38fab6SAlexander Motin  * which otherwise would be skipped for entries in the dbuf cache.
55537b38fab6SAlexander Motin  */
55547b38fab6SAlexander Motin void
55557b38fab6SAlexander Motin arc_buf_access(arc_buf_t *buf)
55567b38fab6SAlexander Motin {
55577b38fab6SAlexander Motin 	mutex_enter(&buf->b_evict_lock);
55587b38fab6SAlexander Motin 	arc_buf_hdr_t *hdr = buf->b_hdr;
55597b38fab6SAlexander Motin 
55607b38fab6SAlexander Motin 	/*
55617b38fab6SAlexander Motin 	 * Avoid taking the hash_lock when possible as an optimization.
55627b38fab6SAlexander Motin 	 * The header must be checked again under the hash_lock in order
55637b38fab6SAlexander Motin 	 * to handle the case where it is concurrently being released.
55647b38fab6SAlexander Motin 	 */
55657b38fab6SAlexander Motin 	if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr)) {
55667b38fab6SAlexander Motin 		mutex_exit(&buf->b_evict_lock);
55677b38fab6SAlexander Motin 		return;
55687b38fab6SAlexander Motin 	}
55697b38fab6SAlexander Motin 
55707b38fab6SAlexander Motin 	kmutex_t *hash_lock = HDR_LOCK(hdr);
55717b38fab6SAlexander Motin 	mutex_enter(hash_lock);
55727b38fab6SAlexander Motin 
55737b38fab6SAlexander Motin 	if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr)) {
55747b38fab6SAlexander Motin 		mutex_exit(hash_lock);
55757b38fab6SAlexander Motin 		mutex_exit(&buf->b_evict_lock);
55767b38fab6SAlexander Motin 		ARCSTAT_BUMP(arcstat_access_skip);
55777b38fab6SAlexander Motin 		return;
55787b38fab6SAlexander Motin 	}
55797b38fab6SAlexander Motin 
55807b38fab6SAlexander Motin 	mutex_exit(&buf->b_evict_lock);
55817b38fab6SAlexander Motin 
55827b38fab6SAlexander Motin 	ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
55837b38fab6SAlexander Motin 	    hdr->b_l1hdr.b_state == arc_mfu);
55847b38fab6SAlexander Motin 
55857b38fab6SAlexander Motin 	DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
55867b38fab6SAlexander Motin 	arc_access(hdr, hash_lock);
55877b38fab6SAlexander Motin 	mutex_exit(hash_lock);
55887b38fab6SAlexander Motin 
55897b38fab6SAlexander Motin 	ARCSTAT_BUMP(arcstat_hits);
55907b38fab6SAlexander Motin 	ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
55917b38fab6SAlexander Motin 	    demand, prefetch, !HDR_ISTYPE_METADATA(hdr), data, metadata, hits);
55927b38fab6SAlexander Motin }
55937b38fab6SAlexander Motin 
5594a3874b8bSToomas Soome /* a generic arc_read_done_func_t which you can use */
5595fa9e4066Sahrens /* ARGSUSED */
5596fa9e4066Sahrens void
5597a3874b8bSToomas Soome arc_bcopy_func(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
5598a3874b8bSToomas Soome     arc_buf_t *buf, void *arg)
5599fa9e4066Sahrens {
5600a3874b8bSToomas Soome 	if (buf == NULL)
5601a3874b8bSToomas Soome 		return;
5602a3874b8bSToomas Soome 
5603a3874b8bSToomas Soome 	bcopy(buf->b_data, arg, arc_buf_size(buf));
5604dcbf3bd6SGeorge Wilson 	arc_buf_destroy(buf, arg);
5605fa9e4066Sahrens }
5606fa9e4066Sahrens 
5607a3874b8bSToomas Soome /* a generic arc_read_done_func_t */
5608fa9e4066Sahrens void
5609a3874b8bSToomas Soome arc_getbuf_func(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
5610a3874b8bSToomas Soome     arc_buf_t *buf, void *arg)
5611fa9e4066Sahrens {
5612fa9e4066Sahrens 	arc_buf_t **bufp = arg;
5613a3874b8bSToomas Soome 
5614fa98e487SMatthew Ahrens 	if (buf == NULL) {
5615fa98e487SMatthew Ahrens 		ASSERT(zio == NULL || zio->io_error != 0);
5616fa9e4066Sahrens 		*bufp = NULL;
5617fa9e4066Sahrens 	} else {
5618fa98e487SMatthew Ahrens 		ASSERT(zio == NULL || zio->io_error == 0);
5619fa9e4066Sahrens 		*bufp = buf;
5620fa98e487SMatthew Ahrens 		ASSERT(buf->b_data != NULL);
5621fa9e4066Sahrens 	}
5622fa9e4066Sahrens }
5623fa9e4066Sahrens 
5624dcbf3bd6SGeorge Wilson static void
5625*eb633035STom Caputi arc_hdr_verify(arc_buf_hdr_t *hdr, const blkptr_t *bp)
5626dcbf3bd6SGeorge Wilson {
5627dcbf3bd6SGeorge Wilson 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
5628dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_PSIZE(hdr), ==, 0);
5629*eb633035STom Caputi 		ASSERT3U(arc_hdr_get_compress(hdr), ==, ZIO_COMPRESS_OFF);
5630dcbf3bd6SGeorge Wilson 	} else {
5631dcbf3bd6SGeorge Wilson 		if (HDR_COMPRESSION_ENABLED(hdr)) {
5632*eb633035STom Caputi 			ASSERT3U(arc_hdr_get_compress(hdr), ==,
5633dcbf3bd6SGeorge Wilson 			    BP_GET_COMPRESS(bp));
5634dcbf3bd6SGeorge Wilson 		}
5635dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
5636dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_PSIZE(hdr), ==, BP_GET_PSIZE(bp));
5637*eb633035STom Caputi 		ASSERT3U(!!HDR_PROTECTED(hdr), ==, BP_IS_PROTECTED(bp));
5638*eb633035STom Caputi 	}
5639*eb633035STom Caputi }
5640*eb633035STom Caputi 
5641*eb633035STom Caputi /*
5642*eb633035STom Caputi  * XXX this should be changed to return an error, and callers
5643*eb633035STom Caputi  * re-read from disk on failure (on nondebug bits).
5644*eb633035STom Caputi  */
5645*eb633035STom Caputi static void
5646*eb633035STom Caputi arc_hdr_verify_checksum(spa_t *spa, arc_buf_hdr_t *hdr, const blkptr_t *bp)
5647*eb633035STom Caputi {
5648*eb633035STom Caputi 	arc_hdr_verify(hdr, bp);
5649*eb633035STom Caputi 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
5650*eb633035STom Caputi 		return;
5651*eb633035STom Caputi 	int err = 0;
5652*eb633035STom Caputi 	abd_t *abd = NULL;
5653*eb633035STom Caputi 	if (BP_IS_ENCRYPTED(bp)) {
5654*eb633035STom Caputi 		if (HDR_HAS_RABD(hdr)) {
5655*eb633035STom Caputi 			abd = hdr->b_crypt_hdr.b_rabd;
5656*eb633035STom Caputi 		}
5657*eb633035STom Caputi 	} else if (HDR_COMPRESSION_ENABLED(hdr)) {
5658*eb633035STom Caputi 		abd = hdr->b_l1hdr.b_pabd;
5659*eb633035STom Caputi 	}
5660*eb633035STom Caputi 	if (abd != NULL) {
5661*eb633035STom Caputi 		/*
5662*eb633035STom Caputi 		 * The offset is only used for labels, which are not
5663*eb633035STom Caputi 		 * cached in the ARC, so it doesn't matter what we
5664*eb633035STom Caputi 		 * pass for the offset parameter.
5665*eb633035STom Caputi 		 */
5666*eb633035STom Caputi 		int psize = HDR_GET_PSIZE(hdr);
5667*eb633035STom Caputi 		err = zio_checksum_error_impl(spa, bp,
5668*eb633035STom Caputi 		    BP_GET_CHECKSUM(bp), abd, psize, 0, NULL);
5669*eb633035STom Caputi 		if (err != 0) {
5670*eb633035STom Caputi 			/*
5671*eb633035STom Caputi 			 * Use abd_copy_to_buf() rather than
5672*eb633035STom Caputi 			 * abd_borrow_buf_copy() so that we are sure to
5673*eb633035STom Caputi 			 * include the buf in crash dumps.
5674*eb633035STom Caputi 			 */
5675*eb633035STom Caputi 			void *buf = kmem_alloc(psize, KM_SLEEP);
5676*eb633035STom Caputi 			abd_copy_to_buf(buf, abd, psize);
5677*eb633035STom Caputi 			panic("checksum of cached data doesn't match BP "
5678*eb633035STom Caputi 			    "err=%u hdr=%p bp=%p abd=%p buf=%p",
5679*eb633035STom Caputi 			    err, (void *)hdr, (void *)bp, (void *)abd, buf);
5680*eb633035STom Caputi 		}
5681dcbf3bd6SGeorge Wilson 	}
5682dcbf3bd6SGeorge Wilson }
5683dcbf3bd6SGeorge Wilson 
5684fa9e4066Sahrens static void
5685fa9e4066Sahrens arc_read_done(zio_t *zio)
5686fa9e4066Sahrens {
5687*eb633035STom Caputi 	blkptr_t	*bp = zio->io_bp;
5688dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t	*hdr = zio->io_private;
56895d7b4d43SMatthew Ahrens 	kmutex_t	*hash_lock = NULL;
56905602294fSDan Kimmel 	arc_callback_t	*callback_list;
56915602294fSDan Kimmel 	arc_callback_t	*acb;
56925602294fSDan Kimmel 	boolean_t	freeable = B_FALSE;
5693fa9e4066Sahrens 
5694bbf4a8dfSmaybee 	/*
5695bbf4a8dfSmaybee 	 * The hdr was inserted into hash-table and removed from lists
5696bbf4a8dfSmaybee 	 * prior to starting I/O.  We should find this header, since
5697bbf4a8dfSmaybee 	 * it's in the hash table, and it should be legit since it's
5698bbf4a8dfSmaybee 	 * not possible to evict it during the I/O.  The only possible
5699bbf4a8dfSmaybee 	 * reason for it not to be found is if we were freed during the
5700bbf4a8dfSmaybee 	 * read.
5701bbf4a8dfSmaybee 	 */
57025d7b4d43SMatthew Ahrens 	if (HDR_IN_HASH_TABLE(hdr)) {
57035d7b4d43SMatthew Ahrens 		ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
57045d7b4d43SMatthew Ahrens 		ASSERT3U(hdr->b_dva.dva_word[0], ==,
57055d7b4d43SMatthew Ahrens 		    BP_IDENTITY(zio->io_bp)->dva_word[0]);
57065d7b4d43SMatthew Ahrens 		ASSERT3U(hdr->b_dva.dva_word[1], ==,
57075d7b4d43SMatthew Ahrens 		    BP_IDENTITY(zio->io_bp)->dva_word[1]);
57085d7b4d43SMatthew Ahrens 
57095d7b4d43SMatthew Ahrens 		arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
57105d7b4d43SMatthew Ahrens 		    &hash_lock);
57115d7b4d43SMatthew Ahrens 
5712dcbf3bd6SGeorge Wilson 		ASSERT((found == hdr &&
57135d7b4d43SMatthew Ahrens 		    DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
57145d7b4d43SMatthew Ahrens 		    (found == hdr && HDR_L2_READING(hdr)));
5715dcbf3bd6SGeorge Wilson 		ASSERT3P(hash_lock, !=, NULL);
5716dcbf3bd6SGeorge Wilson 	}
5717dcbf3bd6SGeorge Wilson 
5718*eb633035STom Caputi 	if (BP_IS_PROTECTED(bp)) {
5719*eb633035STom Caputi 		hdr->b_crypt_hdr.b_ot = BP_GET_TYPE(bp);
5720*eb633035STom Caputi 		hdr->b_crypt_hdr.b_dsobj = zio->io_bookmark.zb_objset;
5721*eb633035STom Caputi 		zio_crypt_decode_params_bp(bp, hdr->b_crypt_hdr.b_salt,
5722*eb633035STom Caputi 		    hdr->b_crypt_hdr.b_iv);
5723*eb633035STom Caputi 
5724*eb633035STom Caputi 		if (BP_GET_TYPE(bp) == DMU_OT_INTENT_LOG) {
5725*eb633035STom Caputi 			void *tmpbuf;
5726*eb633035STom Caputi 
5727*eb633035STom Caputi 			tmpbuf = abd_borrow_buf_copy(zio->io_abd,
5728*eb633035STom Caputi 			    sizeof (zil_chain_t));
5729*eb633035STom Caputi 			zio_crypt_decode_mac_zil(tmpbuf,
5730*eb633035STom Caputi 			    hdr->b_crypt_hdr.b_mac);
5731*eb633035STom Caputi 			abd_return_buf(zio->io_abd, tmpbuf,
5732*eb633035STom Caputi 			    sizeof (zil_chain_t));
5733*eb633035STom Caputi 		} else {
5734*eb633035STom Caputi 			zio_crypt_decode_mac_bp(bp, hdr->b_crypt_hdr.b_mac);
5735*eb633035STom Caputi 		}
5736*eb633035STom Caputi 	}
5737*eb633035STom Caputi 
5738a3874b8bSToomas Soome 	if (zio->io_error == 0) {
5739dcbf3bd6SGeorge Wilson 		/* byteswap if necessary */
5740dcbf3bd6SGeorge Wilson 		if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
5741dcbf3bd6SGeorge Wilson 			if (BP_GET_LEVEL(zio->io_bp) > 0) {
5742dcbf3bd6SGeorge Wilson 				hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
5743dcbf3bd6SGeorge Wilson 			} else {
5744dcbf3bd6SGeorge Wilson 				hdr->b_l1hdr.b_byteswap =
5745dcbf3bd6SGeorge Wilson 				    DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
5746dcbf3bd6SGeorge Wilson 			}
5747dcbf3bd6SGeorge Wilson 		} else {
5748dcbf3bd6SGeorge Wilson 			hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
5749dcbf3bd6SGeorge Wilson 		}
57505d7b4d43SMatthew Ahrens 	}
5751fa94a07fSbrendan 
5752dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_L2_EVICTED);
575389c86e32SChris Williamson 	if (l2arc_noprefetch && HDR_PREFETCH(hdr))
5754dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_L2CACHE);
5755fa9e4066Sahrens 
575689c86e32SChris Williamson 	callback_list = hdr->b_l1hdr.b_acb;
5757dcbf3bd6SGeorge Wilson 	ASSERT3P(callback_list, !=, NULL);
57586b4acc8bSahrens 
5759a3874b8bSToomas Soome 	if (hash_lock && zio->io_error == 0 &&
5760a3874b8bSToomas Soome 	    hdr->b_l1hdr.b_state == arc_anon) {
5761b24ab676SJeff Bonwick 		/*
5762b24ab676SJeff Bonwick 		 * Only call arc_access on anonymous buffers.  This is because
5763b24ab676SJeff Bonwick 		 * if we've issued an I/O for an evicted buffer, we've already
5764b24ab676SJeff Bonwick 		 * called arc_access (to prevent any simultaneous readers from
5765b24ab676SJeff Bonwick 		 * getting confused).
5766b24ab676SJeff Bonwick 		 */
5767b24ab676SJeff Bonwick 		arc_access(hdr, hash_lock);
5768b24ab676SJeff Bonwick 	}
5769b24ab676SJeff Bonwick 
57705602294fSDan Kimmel 	/*
57715602294fSDan Kimmel 	 * If a read request has a callback (i.e. acb_done is not NULL), then we
57725602294fSDan Kimmel 	 * make a buf containing the data according to the parameters which were
57735602294fSDan Kimmel 	 * passed in. The implementation of arc_buf_alloc_impl() ensures that we
57745602294fSDan Kimmel 	 * aren't needlessly decompressing the data multiple times.
57755602294fSDan Kimmel 	 */
57765602294fSDan Kimmel 	int callback_cnt = 0;
57775602294fSDan Kimmel 	for (acb = callback_list; acb != NULL; acb = acb->acb_next) {
57785602294fSDan Kimmel 		if (!acb->acb_done)
57795602294fSDan Kimmel 			continue;
57805602294fSDan Kimmel 
57815602294fSDan Kimmel 		callback_cnt++;
57825602294fSDan Kimmel 
5783a3874b8bSToomas Soome 		if (zio->io_error != 0)
5784a3874b8bSToomas Soome 			continue;
5785a3874b8bSToomas Soome 
5786*eb633035STom Caputi 		int error = arc_buf_alloc_impl(hdr, zio->io_spa,
5787*eb633035STom Caputi 		    &acb->acb_zb, acb->acb_private, acb->acb_encrypted,
5788*eb633035STom Caputi 		    acb->acb_compressed, acb->acb_noauth, B_TRUE,
5789*eb633035STom Caputi 		    &acb->acb_buf);
5790*eb633035STom Caputi 
5791*eb633035STom Caputi 		/*
5792*eb633035STom Caputi 		 * Assert non-speculative zios didn't fail because an
5793*eb633035STom Caputi 		 * encryption key wasn't loaded
5794*eb633035STom Caputi 		 */
5795*eb633035STom Caputi 		ASSERT((zio->io_flags & ZIO_FLAG_SPECULATIVE) ||
5796*eb633035STom Caputi 		    error != EACCES);
5797*eb633035STom Caputi 
5798*eb633035STom Caputi 		/*
5799*eb633035STom Caputi 		 * If we failed to decrypt, report an error now (as the zio
5800*eb633035STom Caputi 		 * layer would have done if it had done the transforms).
5801*eb633035STom Caputi 		 */
5802*eb633035STom Caputi 		if (error == ECKSUM) {
5803*eb633035STom Caputi 			ASSERT(BP_IS_PROTECTED(bp));
5804*eb633035STom Caputi 			error = SET_ERROR(EIO);
5805*eb633035STom Caputi 			if ((zio->io_flags & ZIO_FLAG_SPECULATIVE) == 0) {
5806*eb633035STom Caputi 				spa_log_error(zio->io_spa, &acb->acb_zb);
5807*eb633035STom Caputi 				zfs_ereport_post(FM_EREPORT_ZFS_AUTHENTICATION,
5808*eb633035STom Caputi 				    zio->io_spa, NULL, &acb->acb_zb, zio, 0, 0);
5809*eb633035STom Caputi 			}
5810*eb633035STom Caputi 		}
5811*eb633035STom Caputi 
5812a3874b8bSToomas Soome 		if (error != 0) {
5813a3874b8bSToomas Soome 			/*
5814a3874b8bSToomas Soome 			 * Decompression failed.  Set io_error
5815a3874b8bSToomas Soome 			 * so that when we call acb_done (below),
5816a3874b8bSToomas Soome 			 * we will indicate that the read failed.
5817a3874b8bSToomas Soome 			 * Note that in the unusual case where one
5818a3874b8bSToomas Soome 			 * callback is compressed and another
5819a3874b8bSToomas Soome 			 * uncompressed, we will mark all of them
5820a3874b8bSToomas Soome 			 * as failed, even though the uncompressed
5821a3874b8bSToomas Soome 			 * one can't actually fail.  In this case,
5822a3874b8bSToomas Soome 			 * the hdr will not be anonymous, because
5823a3874b8bSToomas Soome 			 * if there are multiple callbacks, it's
5824a3874b8bSToomas Soome 			 * because multiple threads found the same
5825a3874b8bSToomas Soome 			 * arc buf in the hash table.
5826a3874b8bSToomas Soome 			 */
5827a3874b8bSToomas Soome 			zio->io_error = error;
5828fa9e4066Sahrens 		}
5829fa9e4066Sahrens 	}
5830*eb633035STom Caputi 
5831fa98e487SMatthew Ahrens 	/*
5832fa98e487SMatthew Ahrens 	 * If there are multiple callbacks, we must have the hash lock,
5833fa98e487SMatthew Ahrens 	 * because the only way for multiple threads to find this hdr is
5834fa98e487SMatthew Ahrens 	 * in the hash table.  This ensures that if there are multiple
5835fa98e487SMatthew Ahrens 	 * callbacks, the hdr is not anonymous.  If it were anonymous,
5836fa98e487SMatthew Ahrens 	 * we couldn't use arc_buf_destroy() in the error case below.
5837fa98e487SMatthew Ahrens 	 */
5838fa98e487SMatthew Ahrens 	ASSERT(callback_cnt < 2 || hash_lock != NULL);
5839fa98e487SMatthew Ahrens 
584089c86e32SChris Williamson 	hdr->b_l1hdr.b_acb = NULL;
5841dcbf3bd6SGeorge Wilson 	arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5842*eb633035STom Caputi 	if (callback_cnt == 0)
5843*eb633035STom Caputi 		ASSERT(hdr->b_l1hdr.b_pabd != NULL || HDR_HAS_RABD(hdr));
5844fa9e4066Sahrens 
5845e914ace2STim Schumacher 	ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
584689c86e32SChris Williamson 	    callback_list != NULL);
5847fa9e4066Sahrens 
5848a3874b8bSToomas Soome 	if (zio->io_error == 0) {
5849dcbf3bd6SGeorge Wilson 		arc_hdr_verify(hdr, zio->io_bp);
5850dcbf3bd6SGeorge Wilson 	} else {
5851dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
585289c86e32SChris Williamson 		if (hdr->b_l1hdr.b_state != arc_anon)
585344cb6abcSbmc 			arc_change_state(arc_anon, hdr, hash_lock);
5854ea8dc4b6Seschrock 		if (HDR_IN_HASH_TABLE(hdr))
5855ea8dc4b6Seschrock 			buf_hash_remove(hdr);
5856e914ace2STim Schumacher 		freeable = zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5857fa9e4066Sahrens 	}
5858fa9e4066Sahrens 
5859ea8dc4b6Seschrock 	/*
586013506d1eSmaybee 	 * Broadcast before we drop the hash_lock to avoid the possibility
586113506d1eSmaybee 	 * that the hdr (and hence the cv) might be freed before we get to
586213506d1eSmaybee 	 * the cv_broadcast().
5863ea8dc4b6Seschrock 	 */
586489c86e32SChris Williamson 	cv_broadcast(&hdr->b_l1hdr.b_cv);
5865ea8dc4b6Seschrock 
586689c86e32SChris Williamson 	if (hash_lock != NULL) {
586744eda4d7Smaybee 		mutex_exit(hash_lock);
5868fa9e4066Sahrens 	} else {
5869fa9e4066Sahrens 		/*
5870fa9e4066Sahrens 		 * This block was freed while we waited for the read to
5871fa9e4066Sahrens 		 * complete.  It has been removed from the hash table and
5872fa9e4066Sahrens 		 * moved to the anonymous state (so that it won't show up
5873fa9e4066Sahrens 		 * in the cache).
5874fa9e4066Sahrens 		 */
587589c86e32SChris Williamson 		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
5876e914ace2STim Schumacher 		freeable = zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5877fa9e4066Sahrens 	}
5878fa9e4066Sahrens 
5879fa9e4066Sahrens 	/* execute each callback and free its structure */
5880fa9e4066Sahrens 	while ((acb = callback_list) != NULL) {
5881*eb633035STom Caputi 
5882fa98e487SMatthew Ahrens 		if (acb->acb_done != NULL) {
5883fa98e487SMatthew Ahrens 			if (zio->io_error != 0 && acb->acb_buf != NULL) {
5884fa98e487SMatthew Ahrens 				/*
5885fa98e487SMatthew Ahrens 				 * If arc_buf_alloc_impl() fails during
5886fa98e487SMatthew Ahrens 				 * decompression, the buf will still be
5887fa98e487SMatthew Ahrens 				 * allocated, and needs to be freed here.
5888fa98e487SMatthew Ahrens 				 */
5889fa98e487SMatthew Ahrens 				arc_buf_destroy(acb->acb_buf, acb->acb_private);
5890fa98e487SMatthew Ahrens 				acb->acb_buf = NULL;
5891fa98e487SMatthew Ahrens 			}
5892a3874b8bSToomas Soome 			acb->acb_done(zio, &zio->io_bookmark, zio->io_bp,
5893a3874b8bSToomas Soome 			    acb->acb_buf, acb->acb_private);
5894fa98e487SMatthew Ahrens 		}
5895fa9e4066Sahrens 
5896fa9e4066Sahrens 		if (acb->acb_zio_dummy != NULL) {
5897fa9e4066Sahrens 			acb->acb_zio_dummy->io_error = zio->io_error;
5898fa9e4066Sahrens 			zio_nowait(acb->acb_zio_dummy);
5899fa9e4066Sahrens 		}
5900fa9e4066Sahrens 
5901fa9e4066Sahrens 		callback_list = acb->acb_next;
5902fa9e4066Sahrens 		kmem_free(acb, sizeof (arc_callback_t));
5903fa9e4066Sahrens 	}
5904fa9e4066Sahrens 
5905fa9e4066Sahrens 	if (freeable)
5906ea8dc4b6Seschrock 		arc_hdr_destroy(hdr);
5907fa9e4066Sahrens }
5908fa9e4066Sahrens 
5909fa9e4066Sahrens /*
5910fc98fea5SBart Coddens  * "Read" the block at the specified DVA (in bp) via the
5911fa9e4066Sahrens  * cache.  If the block is found in the cache, invoke the provided
5912fa9e4066Sahrens  * callback immediately and return.  Note that the `zio' parameter
5913fa9e4066Sahrens  * in the callback will be NULL in this case, since no IO was
5914fa9e4066Sahrens  * required.  If the block is not in the cache pass the read request
5915fa9e4066Sahrens  * on to the spa with a substitute callback function, so that the
5916fa9e4066Sahrens  * requested block will be added to the cache.
5917fa9e4066Sahrens  *
5918fa9e4066Sahrens  * If a read request arrives for a block that has a read in-progress,
5919fa9e4066Sahrens  * either wait for the in-progress read to complete (and return the
5920fa9e4066Sahrens  * results); or, if this is a read with a "done" func, add a record
5921fa9e4066Sahrens  * to the read to invoke the "done" func when the read completes,
5922fa9e4066Sahrens  * and return; or just return.
5923fa9e4066Sahrens  *
5924fa9e4066Sahrens  * arc_read_done() will invoke all the requested "done" functions
5925fa9e4066Sahrens  * for readers of this block.
5926fa9e4066Sahrens  */
5927fa9e4066Sahrens int
5928a3874b8bSToomas Soome arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_read_done_func_t *done,
59297adb730bSGeorge Wilson     void *private, zio_priority_t priority, int zio_flags,
59307adb730bSGeorge Wilson     arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
5931fa9e4066Sahrens {
59325d7b4d43SMatthew Ahrens 	arc_buf_hdr_t *hdr = NULL;
59335d7b4d43SMatthew Ahrens 	kmutex_t *hash_lock = NULL;
5934fa94a07fSbrendan 	zio_t *rzio;
5935e9103aaeSGarrett D'Amore 	uint64_t guid = spa_load_guid(spa);
5936*eb633035STom Caputi 	boolean_t compressed_read = (zio_flags & ZIO_FLAG_RAW_COMPRESS) != 0;
5937*eb633035STom Caputi 	boolean_t encrypted_read = BP_IS_ENCRYPTED(bp) &&
5938*eb633035STom Caputi 	    (zio_flags & ZIO_FLAG_RAW_ENCRYPT) != 0;
5939*eb633035STom Caputi 	boolean_t noauth_read = BP_IS_AUTHENTICATED(bp) &&
5940*eb633035STom Caputi 	    (zio_flags & ZIO_FLAG_RAW_ENCRYPT) != 0;
5941a3874b8bSToomas Soome 	int rc = 0;
5942fa9e4066Sahrens 
59435d7b4d43SMatthew Ahrens 	ASSERT(!BP_IS_EMBEDDED(bp) ||
59445d7b4d43SMatthew Ahrens 	    BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
59455d7b4d43SMatthew Ahrens 
5946fa9e4066Sahrens top:
59475d7b4d43SMatthew Ahrens 	if (!BP_IS_EMBEDDED(bp)) {
59485d7b4d43SMatthew Ahrens 		/*
59495d7b4d43SMatthew Ahrens 		 * Embedded BP's have no DVA and require no I/O to "read".
59505d7b4d43SMatthew Ahrens 		 * Create an anonymous arc buf to back it.
59515d7b4d43SMatthew Ahrens 		 */
59525d7b4d43SMatthew Ahrens 		hdr = buf_hash_find(guid, bp, &hash_lock);
59535d7b4d43SMatthew Ahrens 	}
59545d7b4d43SMatthew Ahrens 
5955*eb633035STom Caputi 	/*
5956*eb633035STom Caputi 	 * Determine if we have an L1 cache hit or a cache miss. For simplicity
5957*eb633035STom Caputi 	 * we maintain encrypted data seperately from compressed / uncompressed
5958*eb633035STom Caputi 	 * data. If the user is requesting raw encrypted data and we don't have
5959*eb633035STom Caputi 	 * that in the header we will read from disk to guarantee that we can
5960*eb633035STom Caputi 	 * get it even if the encryption keys aren't loaded.
5961*eb633035STom Caputi 	 */
5962*eb633035STom Caputi 	if (hdr != NULL && HDR_HAS_L1HDR(hdr) && (HDR_HAS_RABD(hdr) ||
5963*eb633035STom Caputi 	    (hdr->b_l1hdr.b_pabd != NULL && !encrypted_read))) {
5964dcbf3bd6SGeorge Wilson 		arc_buf_t *buf = NULL;
59657adb730bSGeorge Wilson 		*arc_flags |= ARC_FLAG_CACHED;
596613506d1eSmaybee 
5967fa9e4066Sahrens 		if (HDR_IO_IN_PROGRESS(hdr)) {
5968a3874b8bSToomas Soome 			zio_t *head_zio = hdr->b_l1hdr.b_acb->acb_zio_head;
596913506d1eSmaybee 
5970a3874b8bSToomas Soome 			ASSERT3P(head_zio, !=, NULL);
5971cf6106c8SMatthew Ahrens 			if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
5972cf6106c8SMatthew Ahrens 			    priority == ZIO_PRIORITY_SYNC_READ) {
5973cf6106c8SMatthew Ahrens 				/*
5974a3874b8bSToomas Soome 				 * This is a sync read that needs to wait for
5975a3874b8bSToomas Soome 				 * an in-flight async read. Request that the
5976a3874b8bSToomas Soome 				 * zio have its priority upgraded.
5977cf6106c8SMatthew Ahrens 				 */
5978a3874b8bSToomas Soome 				zio_change_priority(head_zio, priority);
5979a3874b8bSToomas Soome 				DTRACE_PROBE1(arc__async__upgrade__sync,
5980cf6106c8SMatthew Ahrens 				    arc_buf_hdr_t *, hdr);
5981a3874b8bSToomas Soome 				ARCSTAT_BUMP(arcstat_async_upgrade_sync);
5982cf6106c8SMatthew Ahrens 			}
5983cf6106c8SMatthew Ahrens 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5984dcbf3bd6SGeorge Wilson 				arc_hdr_clear_flags(hdr,
5985dcbf3bd6SGeorge Wilson 				    ARC_FLAG_PREDICTIVE_PREFETCH);
5986cf6106c8SMatthew Ahrens 			}
5987cf6106c8SMatthew Ahrens 
59887adb730bSGeorge Wilson 			if (*arc_flags & ARC_FLAG_WAIT) {
598989c86e32SChris Williamson 				cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
599013506d1eSmaybee 				mutex_exit(hash_lock);
599113506d1eSmaybee 				goto top;
599213506d1eSmaybee 			}
59937adb730bSGeorge Wilson 			ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
599413506d1eSmaybee 
599513506d1eSmaybee 			if (done) {
5996cf6106c8SMatthew Ahrens 				arc_callback_t *acb = NULL;
5997fa9e4066Sahrens 
5998fa9e4066Sahrens 				acb = kmem_zalloc(sizeof (arc_callback_t),
5999fa9e4066Sahrens 				    KM_SLEEP);
6000fa9e4066Sahrens 				acb->acb_done = done;
6001fa9e4066Sahrens 				acb->acb_private = private;
60025602294fSDan Kimmel 				acb->acb_compressed = compressed_read;
6003*eb633035STom Caputi 				acb->acb_encrypted = encrypted_read;
6004*eb633035STom Caputi 				acb->acb_noauth = noauth_read;
6005*eb633035STom Caputi 				acb->acb_zb = *zb;
6006fa9e4066Sahrens 				if (pio != NULL)
6007fa9e4066Sahrens 					acb->acb_zio_dummy = zio_null(pio,
6008a3f829aeSBill Moore 					    spa, NULL, NULL, NULL, zio_flags);
6009fa9e4066Sahrens 
6010dcbf3bd6SGeorge Wilson 				ASSERT3P(acb->acb_done, !=, NULL);
6011a3874b8bSToomas Soome 				acb->acb_zio_head = head_zio;
601289c86e32SChris Williamson 				acb->acb_next = hdr->b_l1hdr.b_acb;
601389c86e32SChris Williamson 				hdr->b_l1hdr.b_acb = acb;
6014fa9e4066Sahrens 				mutex_exit(hash_lock);
6015fa9e4066Sahrens 				return (0);
6016fa9e4066Sahrens 			}
6017fa9e4066Sahrens 			mutex_exit(hash_lock);
6018fa9e4066Sahrens 			return (0);
6019fa9e4066Sahrens 		}
6020fa9e4066Sahrens 
602189c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
602289c86e32SChris Williamson 		    hdr->b_l1hdr.b_state == arc_mfu);
6023fa9e4066Sahrens 
6024ea8dc4b6Seschrock 		if (done) {
6025cf6106c8SMatthew Ahrens 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
6026cf6106c8SMatthew Ahrens 				/*
6027cf6106c8SMatthew Ahrens 				 * This is a demand read which does not have to
6028cf6106c8SMatthew Ahrens 				 * wait for i/o because we did a predictive
6029cf6106c8SMatthew Ahrens 				 * prefetch i/o for it, which has completed.
6030cf6106c8SMatthew Ahrens 				 */
6031cf6106c8SMatthew Ahrens 				DTRACE_PROBE1(
6032cf6106c8SMatthew Ahrens 				    arc__demand__hit__predictive__prefetch,
6033cf6106c8SMatthew Ahrens 				    arc_buf_hdr_t *, hdr);
6034cf6106c8SMatthew Ahrens 				ARCSTAT_BUMP(
6035cf6106c8SMatthew Ahrens 				    arcstat_demand_hit_predictive_prefetch);
6036dcbf3bd6SGeorge Wilson 				arc_hdr_clear_flags(hdr,
6037dcbf3bd6SGeorge Wilson 				    ARC_FLAG_PREDICTIVE_PREFETCH);
6038cf6106c8SMatthew Ahrens 			}
6039a3874b8bSToomas Soome 
6040a3874b8bSToomas Soome 			if (hdr->b_flags & ARC_FLAG_PRESCIENT_PREFETCH) {
6041a3874b8bSToomas Soome 				ARCSTAT_BUMP(
6042a3874b8bSToomas Soome 				    arcstat_demand_hit_prescient_prefetch);
6043a3874b8bSToomas Soome 				arc_hdr_clear_flags(hdr,
6044a3874b8bSToomas Soome 				    ARC_FLAG_PRESCIENT_PREFETCH);
6045a3874b8bSToomas Soome 			}
6046a3874b8bSToomas Soome 
6047dcbf3bd6SGeorge Wilson 			ASSERT(!BP_IS_EMBEDDED(bp) || !BP_IS_HOLE(bp));
6048dcbf3bd6SGeorge Wilson 
6049*eb633035STom Caputi 			arc_hdr_verify_checksum(spa, hdr, bp);
6050*eb633035STom Caputi 
60515602294fSDan Kimmel 			/* Get a buf with the desired data in it. */
6052*eb633035STom Caputi 			rc = arc_buf_alloc_impl(hdr, spa, zb, private,
6053*eb633035STom Caputi 			    encrypted_read, compressed_read, noauth_read,
6054*eb633035STom Caputi 			    B_TRUE, &buf);
6055*eb633035STom Caputi 			if (rc == ECKSUM) {
6056*eb633035STom Caputi 				/*
6057*eb633035STom Caputi 				 * Convert authentication and decryption errors
6058*eb633035STom Caputi 				 * to EIO (and generate an ereport if needed)
6059*eb633035STom Caputi 				 * before leaving the ARC.
6060*eb633035STom Caputi 				 */
6061*eb633035STom Caputi 				rc = SET_ERROR(EIO);
6062*eb633035STom Caputi 				if ((zio_flags & ZIO_FLAG_SPECULATIVE) == 0) {
6063*eb633035STom Caputi 					spa_log_error(spa, zb);
6064*eb633035STom Caputi 					zfs_ereport_post(
6065*eb633035STom Caputi 					    FM_EREPORT_ZFS_AUTHENTICATION,
6066*eb633035STom Caputi 					    spa, NULL, zb, NULL, 0, 0);
6067*eb633035STom Caputi 				}
6068*eb633035STom Caputi 			}
6069a3874b8bSToomas Soome 			if (rc != 0) {
6070*eb633035STom Caputi 				(void) remove_reference(hdr, hash_lock,
6071*eb633035STom Caputi 				    private);
6072*eb633035STom Caputi 				arc_buf_destroy_impl(buf);
6073a3874b8bSToomas Soome 				buf = NULL;
6074a3874b8bSToomas Soome 			}
6075*eb633035STom Caputi 			/* assert any errors weren't due to unloaded keys */
6076a3874b8bSToomas Soome 			ASSERT((zio_flags & ZIO_FLAG_SPECULATIVE) ||
6077*eb633035STom Caputi 			    rc != EACCES);
60787adb730bSGeorge Wilson 		} else if (*arc_flags & ARC_FLAG_PREFETCH &&
6079e914ace2STim Schumacher 		    zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
6080dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
6081fa9e4066Sahrens 		}
6082fa9e4066Sahrens 		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
608344eda4d7Smaybee 		arc_access(hdr, hash_lock);
6084a3874b8bSToomas Soome 		if (*arc_flags & ARC_FLAG_PRESCIENT_PREFETCH)
6085a3874b8bSToomas Soome 			arc_hdr_set_flags(hdr, ARC_FLAG_PRESCIENT_PREFETCH);
60867adb730bSGeorge Wilson 		if (*arc_flags & ARC_FLAG_L2CACHE)
6087dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
608844eda4d7Smaybee 		mutex_exit(hash_lock);
608944cb6abcSbmc 		ARCSTAT_BUMP(arcstat_hits);
609089c86e32SChris Williamson 		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
609189c86e32SChris Williamson 		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
609244cb6abcSbmc 		    data, metadata, hits);
609344cb6abcSbmc 
6094fa9e4066Sahrens 		if (done)
6095a3874b8bSToomas Soome 			done(NULL, zb, bp, buf, private);
6096fa9e4066Sahrens 	} else {
6097dcbf3bd6SGeorge Wilson 		uint64_t lsize = BP_GET_LSIZE(bp);
6098dcbf3bd6SGeorge Wilson 		uint64_t psize = BP_GET_PSIZE(bp);
60995d7b4d43SMatthew Ahrens 		arc_callback_t *acb;
61003a737e0dSbrendan 		vdev_t *vd = NULL;
6101d5285caeSGeorge Wilson 		uint64_t addr = 0;
61025a98e54bSBrendan Gregg - Sun Microsystems 		boolean_t devw = B_FALSE;
6103dcbf3bd6SGeorge Wilson 		uint64_t size;
6104*eb633035STom Caputi 		abd_t *hdr_abd;
6105fa9e4066Sahrens 
6106fa9e4066Sahrens 		if (hdr == NULL) {
6107fa9e4066Sahrens 			/* this block is not in the cache */
61085d7b4d43SMatthew Ahrens 			arc_buf_hdr_t *exists = NULL;
6109ad23a2dbSjohansen 			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
6110dcbf3bd6SGeorge Wilson 			hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
6111*eb633035STom Caputi 			    BP_IS_PROTECTED(bp), BP_GET_COMPRESS(bp), type,
6112*eb633035STom Caputi 			    encrypted_read);
6113dcbf3bd6SGeorge Wilson 
61145d7b4d43SMatthew Ahrens 			if (!BP_IS_EMBEDDED(bp)) {
61155d7b4d43SMatthew Ahrens 				hdr->b_dva = *BP_IDENTITY(bp);
61165d7b4d43SMatthew Ahrens 				hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
61175d7b4d43SMatthew Ahrens 				exists = buf_hash_insert(hdr, &hash_lock);
61185d7b4d43SMatthew Ahrens 			}
61195d7b4d43SMatthew Ahrens 			if (exists != NULL) {
6120fa9e4066Sahrens 				/* somebody beat us to the hash insert */
6121fa9e4066Sahrens 				mutex_exit(hash_lock);
61223f9d6ad7SLin Ling 				buf_discard_identity(hdr);
6123dcbf3bd6SGeorge Wilson 				arc_hdr_destroy(hdr);
6124fa9e4066Sahrens 				goto top; /* restart the IO request */
6125fa9e4066Sahrens 			}
6126fa9e4066Sahrens 		} else {
612789c86e32SChris Williamson 			/*
6128*eb633035STom Caputi 			 * This block is in the ghost cache or encrypted data
6129*eb633035STom Caputi 			 * was requested and we didn't have it. If it was
6130*eb633035STom Caputi 			 * L2-only (and thus didn't have an L1 hdr),
6131*eb633035STom Caputi 			 * we realloc the header to add an L1 hdr.
613289c86e32SChris Williamson 			 */
613389c86e32SChris Williamson 			if (!HDR_HAS_L1HDR(hdr)) {
613489c86e32SChris Williamson 				hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
613589c86e32SChris Williamson 				    hdr_full_cache);
613689c86e32SChris Williamson 			}
6137*eb633035STom Caputi 
6138*eb633035STom Caputi 			if (GHOST_STATE(hdr->b_l1hdr.b_state)) {
6139*eb633035STom Caputi 				ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
6140*eb633035STom Caputi 				ASSERT(!HDR_HAS_RABD(hdr));
6141*eb633035STom Caputi 				ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6142*eb633035STom Caputi 				ASSERT0(zfs_refcount_count(
6143*eb633035STom Caputi 				    &hdr->b_l1hdr.b_refcnt));
6144*eb633035STom Caputi 				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
6145*eb633035STom Caputi 				ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
6146*eb633035STom Caputi 			} else if (HDR_IO_IN_PROGRESS(hdr)) {
6147*eb633035STom Caputi 				/*
6148*eb633035STom Caputi 				 * If this header already had an IO in progress
6149*eb633035STom Caputi 				 * and we are performing another IO to fetch
6150*eb633035STom Caputi 				 * encrypted data we must wait until the first
6151*eb633035STom Caputi 				 * IO completes so as not to confuse
6152*eb633035STom Caputi 				 * arc_read_done(). This should be very rare
6153*eb633035STom Caputi 				 * and so the performance impact shouldn't
6154*eb633035STom Caputi 				 * matter.
6155*eb633035STom Caputi 				 */
6156*eb633035STom Caputi 				cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
6157*eb633035STom Caputi 				mutex_exit(hash_lock);
6158*eb633035STom Caputi 				goto top;
6159*eb633035STom Caputi 			}
616013506d1eSmaybee 
6161cf6106c8SMatthew Ahrens 			/*
6162dcbf3bd6SGeorge Wilson 			 * This is a delicate dance that we play here.
6163*eb633035STom Caputi 			 * This hdr might be in the ghost list so we access
6164*eb633035STom Caputi 			 * it to move it out of the ghost list before we
6165dcbf3bd6SGeorge Wilson 			 * initiate the read. If it's a prefetch then
6166dcbf3bd6SGeorge Wilson 			 * it won't have a callback so we'll remove the
6167dcbf3bd6SGeorge Wilson 			 * reference that arc_buf_alloc_impl() created. We
6168dcbf3bd6SGeorge Wilson 			 * do this after we've called arc_access() to
6169dcbf3bd6SGeorge Wilson 			 * avoid hitting an assert in remove_reference().
6170cf6106c8SMatthew Ahrens 			 */
61717e453561SWilliam Gorrell 			arc_access(hdr, hash_lock);
6172*eb633035STom Caputi 			arc_hdr_alloc_pabd(hdr, encrypted_read);
6173dcbf3bd6SGeorge Wilson 		}
6174dcbf3bd6SGeorge Wilson 
6175*eb633035STom Caputi 		if (encrypted_read) {
6176*eb633035STom Caputi 			ASSERT(HDR_HAS_RABD(hdr));
6177*eb633035STom Caputi 			size = HDR_GET_PSIZE(hdr);
6178*eb633035STom Caputi 			hdr_abd = hdr->b_crypt_hdr.b_rabd;
6179dcbf3bd6SGeorge Wilson 			zio_flags |= ZIO_FLAG_RAW;
6180*eb633035STom Caputi 		} else {
6181*eb633035STom Caputi 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
6182*eb633035STom Caputi 			size = arc_hdr_size(hdr);
6183*eb633035STom Caputi 			hdr_abd = hdr->b_l1hdr.b_pabd;
6184*eb633035STom Caputi 
6185*eb633035STom Caputi 			if (arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF) {
6186*eb633035STom Caputi 				zio_flags |= ZIO_FLAG_RAW_COMPRESS;
6187*eb633035STom Caputi 			}
6188*eb633035STom Caputi 
6189*eb633035STom Caputi 			/*
6190*eb633035STom Caputi 			 * For authenticated bp's, we do not ask the ZIO layer
6191*eb633035STom Caputi 			 * to authenticate them since this will cause the entire
6192*eb633035STom Caputi 			 * IO to fail if the key isn't loaded. Instead, we
6193*eb633035STom Caputi 			 * defer authentication until arc_buf_fill(), which will
6194*eb633035STom Caputi 			 * verify the data when the key is available.
6195*eb633035STom Caputi 			 */
6196*eb633035STom Caputi 			if (BP_IS_AUTHENTICATED(bp))
6197*eb633035STom Caputi 				zio_flags |= ZIO_FLAG_RAW_ENCRYPT;
6198fa9e4066Sahrens 		}
6199fa9e4066Sahrens 
6200*eb633035STom Caputi 		if (*arc_flags & ARC_FLAG_PREFETCH &&
6201*eb633035STom Caputi 		    zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt))
6202dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
6203a3874b8bSToomas Soome 		if (*arc_flags & ARC_FLAG_PRESCIENT_PREFETCH)
6204a3874b8bSToomas Soome 			arc_hdr_set_flags(hdr, ARC_FLAG_PRESCIENT_PREFETCH);
6205a3874b8bSToomas Soome 
6206dcbf3bd6SGeorge Wilson 		if (*arc_flags & ARC_FLAG_L2CACHE)
6207dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
6208*eb633035STom Caputi 		if (BP_IS_AUTHENTICATED(bp))
6209*eb633035STom Caputi 			arc_hdr_set_flags(hdr, ARC_FLAG_NOAUTH);
6210dcbf3bd6SGeorge Wilson 		if (BP_GET_LEVEL(bp) > 0)
6211dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_INDIRECT);
6212cf6106c8SMatthew Ahrens 		if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
6213dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_PREDICTIVE_PREFETCH);
621489c86e32SChris Williamson 		ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
62155614b00aSWilliam Gorrell 
6216fa9e4066Sahrens 		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
6217fa9e4066Sahrens 		acb->acb_done = done;
6218fa9e4066Sahrens 		acb->acb_private = private;
62195602294fSDan Kimmel 		acb->acb_compressed = compressed_read;
6220*eb633035STom Caputi 		acb->acb_encrypted = encrypted_read;
6221*eb633035STom Caputi 		acb->acb_noauth = noauth_read;
6222*eb633035STom Caputi 		acb->acb_zb = *zb;
6223fa9e4066Sahrens 
6224dcbf3bd6SGeorge Wilson 		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
622589c86e32SChris Williamson 		hdr->b_l1hdr.b_acb = acb;
6226dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6227fa9e4066Sahrens 
622889c86e32SChris Williamson 		if (HDR_HAS_L2HDR(hdr) &&
622989c86e32SChris Williamson 		    (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
623089c86e32SChris Williamson 			devw = hdr->b_l2hdr.b_dev->l2ad_writing;
623189c86e32SChris Williamson 			addr = hdr->b_l2hdr.b_daddr;
6232e14bb325SJeff Bonwick 			/*
62335cabbc6bSPrashanth Sreenivasa 			 * Lock out L2ARC device removal.
6234e14bb325SJeff Bonwick 			 */
6235e14bb325SJeff Bonwick 			if (vdev_is_dead(vd) ||
6236e14bb325SJeff Bonwick 			    !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
6237e14bb325SJeff Bonwick 				vd = NULL;
62383a737e0dSbrendan 		}
62393a737e0dSbrendan 
6240a3874b8bSToomas Soome 		/*
6241a3874b8bSToomas Soome 		 * We count both async reads and scrub IOs as asynchronous so
6242a3874b8bSToomas Soome 		 * that both can be upgraded in the event of a cache hit while
6243a3874b8bSToomas Soome 		 * the read IO is still in-flight.
6244a3874b8bSToomas Soome 		 */
6245a3874b8bSToomas Soome 		if (priority == ZIO_PRIORITY_ASYNC_READ ||
6246a3874b8bSToomas Soome 		    priority == ZIO_PRIORITY_SCRUB)
6247dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
6248dcbf3bd6SGeorge Wilson 		else
6249dcbf3bd6SGeorge Wilson 			arc_hdr_clear_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
6250dcbf3bd6SGeorge Wilson 
62513e30c24aSWill Andrews 		/*
62523e30c24aSWill Andrews 		 * At this point, we have a level 1 cache miss.  Try again in
62533e30c24aSWill Andrews 		 * L2ARC if possible.
62543e30c24aSWill Andrews 		 */
6255dcbf3bd6SGeorge Wilson 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, lsize);
6256dcbf3bd6SGeorge Wilson 
62575c28183bSBrendan Gregg - Sun Microsystems 		DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
6258dcbf3bd6SGeorge Wilson 		    uint64_t, lsize, zbookmark_phys_t *, zb);
625944cb6abcSbmc 		ARCSTAT_BUMP(arcstat_misses);
626089c86e32SChris Williamson 		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
626189c86e32SChris Williamson 		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
626244cb6abcSbmc 		    data, metadata, misses);
6263ea8dc4b6Seschrock 
62645a98e54bSBrendan Gregg - Sun Microsystems 		if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
6265fa94a07fSbrendan 			/*
6266fa94a07fSbrendan 			 * Read from the L2ARC if the following are true:
62673a737e0dSbrendan 			 * 1. The L2ARC vdev was previously cached.
62683a737e0dSbrendan 			 * 2. This buffer still has L2ARC metadata.
62693a737e0dSbrendan 			 * 3. This buffer isn't currently writing to the L2ARC.
62703a737e0dSbrendan 			 * 4. The L2ARC entry wasn't evicted, which may
62713a737e0dSbrendan 			 *    also have invalidated the vdev.
62725a98e54bSBrendan Gregg - Sun Microsystems 			 * 5. This isn't prefetch and l2arc_noprefetch is set.
6273fa94a07fSbrendan 			 */
627489c86e32SChris Williamson 			if (HDR_HAS_L2HDR(hdr) &&
62755a98e54bSBrendan Gregg - Sun Microsystems 			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
62765a98e54bSBrendan Gregg - Sun Microsystems 			    !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
6277fa94a07fSbrendan 				l2arc_read_callback_t *cb;
6278403a8da7SAndriy Gapon 				abd_t *abd;
6279403a8da7SAndriy Gapon 				uint64_t asize;
6280fa94a07fSbrendan 
6281c5904d13Seschrock 				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
6282c5904d13Seschrock 				ARCSTAT_BUMP(arcstat_l2_hits);
6283c5904d13Seschrock 
6284fa94a07fSbrendan 				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
6285fa94a07fSbrendan 				    KM_SLEEP);
6286dcbf3bd6SGeorge Wilson 				cb->l2rcb_hdr = hdr;
6287fa94a07fSbrendan 				cb->l2rcb_bp = *bp;
6288fa94a07fSbrendan 				cb->l2rcb_zb = *zb;
62893baa08fcSek 				cb->l2rcb_flags = zio_flags;
6290fa94a07fSbrendan 
6291403a8da7SAndriy Gapon 				asize = vdev_psize_to_asize(vd, size);
6292403a8da7SAndriy Gapon 				if (asize != size) {
6293403a8da7SAndriy Gapon 					abd = abd_alloc_for_io(asize,
6294403a8da7SAndriy Gapon 					    HDR_ISTYPE_METADATA(hdr));
6295403a8da7SAndriy Gapon 					cb->l2rcb_abd = abd;
6296403a8da7SAndriy Gapon 				} else {
6297*eb633035STom Caputi 					abd = hdr_abd;
6298403a8da7SAndriy Gapon 				}
6299403a8da7SAndriy Gapon 
6300d5285caeSGeorge Wilson 				ASSERT(addr >= VDEV_LABEL_START_SIZE &&
6301403a8da7SAndriy Gapon 				    addr + asize <= vd->vdev_psize -
6302d5285caeSGeorge Wilson 				    VDEV_LABEL_END_SIZE);
6303d5285caeSGeorge Wilson 
6304fa94a07fSbrendan 				/*
6305e14bb325SJeff Bonwick 				 * l2arc read.  The SCL_L2ARC lock will be
6306e14bb325SJeff Bonwick 				 * released by l2arc_read_done().
6307aad02571SSaso Kiselkov 				 * Issue a null zio if the underlying buffer
6308aad02571SSaso Kiselkov 				 * was squashed to zero size by compression.
6309fa94a07fSbrendan 				 */
6310*eb633035STom Caputi 				ASSERT3U(arc_hdr_get_compress(hdr), !=,
6311dcbf3bd6SGeorge Wilson 				    ZIO_COMPRESS_EMPTY);
6312dcbf3bd6SGeorge Wilson 				rzio = zio_read_phys(pio, vd, addr,
6313403a8da7SAndriy Gapon 				    asize, abd,
6314dcbf3bd6SGeorge Wilson 				    ZIO_CHECKSUM_OFF,
6315dcbf3bd6SGeorge Wilson 				    l2arc_read_done, cb, priority,
6316dcbf3bd6SGeorge Wilson 				    zio_flags | ZIO_FLAG_DONT_CACHE |
6317dcbf3bd6SGeorge Wilson 				    ZIO_FLAG_CANFAIL |
6318dcbf3bd6SGeorge Wilson 				    ZIO_FLAG_DONT_PROPAGATE |
6319dcbf3bd6SGeorge Wilson 				    ZIO_FLAG_DONT_RETRY, B_FALSE);
6320a3874b8bSToomas Soome 				acb->acb_zio_head = rzio;
6321a3874b8bSToomas Soome 
6322a3874b8bSToomas Soome 				if (hash_lock != NULL)
6323a3874b8bSToomas Soome 					mutex_exit(hash_lock);
6324a3874b8bSToomas Soome 
6325fa94a07fSbrendan 				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
6326fa94a07fSbrendan 				    zio_t *, rzio);
6327*eb633035STom Caputi 				ARCSTAT_INCR(arcstat_l2_read_bytes,
6328*eb633035STom Caputi 				    HDR_GET_PSIZE(hdr));
6329fa94a07fSbrendan 
63307adb730bSGeorge Wilson 				if (*arc_flags & ARC_FLAG_NOWAIT) {
63313a737e0dSbrendan 					zio_nowait(rzio);
63323a737e0dSbrendan 					return (0);
63333a737e0dSbrendan 				}
6334fa94a07fSbrendan 
63357adb730bSGeorge Wilson 				ASSERT(*arc_flags & ARC_FLAG_WAIT);
63363a737e0dSbrendan 				if (zio_wait(rzio) == 0)
63373a737e0dSbrendan 					return (0);
63383a737e0dSbrendan 
63393a737e0dSbrendan 				/* l2arc read error; goto zio_read() */
6340a3874b8bSToomas Soome 				if (hash_lock != NULL)
6341a3874b8bSToomas Soome 					mutex_enter(hash_lock);
6342fa94a07fSbrendan 			} else {
6343fa94a07fSbrendan 				DTRACE_PROBE1(l2arc__miss,
6344fa94a07fSbrendan 				    arc_buf_hdr_t *, hdr);
6345fa94a07fSbrendan 				ARCSTAT_BUMP(arcstat_l2_misses);
6346fa94a07fSbrendan 				if (HDR_L2_WRITING(hdr))
6347fa94a07fSbrendan 					ARCSTAT_BUMP(arcstat_l2_rw_clash);
6348e14bb325SJeff Bonwick 				spa_config_exit(spa, SCL_L2ARC, vd);
6349fa94a07fSbrendan 			}
63505a98e54bSBrendan Gregg - Sun Microsystems 		} else {
635176a25fafSBill Moore 			if (vd != NULL)
635276a25fafSBill Moore 				spa_config_exit(spa, SCL_L2ARC, vd);
63535a98e54bSBrendan Gregg - Sun Microsystems 			if (l2arc_ndev != 0) {
63545a98e54bSBrendan Gregg - Sun Microsystems 				DTRACE_PROBE1(l2arc__miss,
63555a98e54bSBrendan Gregg - Sun Microsystems 				    arc_buf_hdr_t *, hdr);
63565a98e54bSBrendan Gregg - Sun Microsystems 				ARCSTAT_BUMP(arcstat_l2_misses);
63575a98e54bSBrendan Gregg - Sun Microsystems 			}
6358fa94a07fSbrendan 		}
6359c5904d13Seschrock 
6360*eb633035STom Caputi 		rzio = zio_read(pio, spa, bp, hdr_abd, size,
6361dcbf3bd6SGeorge Wilson 		    arc_read_done, hdr, priority, zio_flags, zb);
6362a3874b8bSToomas Soome 		acb->acb_zio_head = rzio;
6363a3874b8bSToomas Soome 
6364a3874b8bSToomas Soome 		if (hash_lock != NULL)
6365a3874b8bSToomas Soome 			mutex_exit(hash_lock);
6366fa9e4066Sahrens 
63677adb730bSGeorge Wilson 		if (*arc_flags & ARC_FLAG_WAIT)
6368fa9e4066Sahrens 			return (zio_wait(rzio));
6369fa9e4066Sahrens 
63707adb730bSGeorge Wilson 		ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
6371fa9e4066Sahrens 		zio_nowait(rzio);
6372fa9e4066Sahrens 	}
6373*eb633035STom Caputi 	return (rc);
6374fa9e4066Sahrens }
6375fa9e4066Sahrens 
63766e6d5868SMatthew Ahrens /*
63776e6d5868SMatthew Ahrens  * Notify the arc that a block was freed, and thus will never be used again.
63786e6d5868SMatthew Ahrens  */
63796e6d5868SMatthew Ahrens void
63806e6d5868SMatthew Ahrens arc_freed(spa_t *spa, const blkptr_t *bp)
63816e6d5868SMatthew Ahrens {
63826e6d5868SMatthew Ahrens 	arc_buf_hdr_t *hdr;
63836e6d5868SMatthew Ahrens 	kmutex_t *hash_lock;
63846e6d5868SMatthew Ahrens 	uint64_t guid = spa_load_guid(spa);
63856e6d5868SMatthew Ahrens 
63865d7b4d43SMatthew Ahrens 	ASSERT(!BP_IS_EMBEDDED(bp));
63875d7b4d43SMatthew Ahrens 
63885d7b4d43SMatthew Ahrens 	hdr = buf_hash_find(guid, bp, &hash_lock);
63896e6d5868SMatthew Ahrens 	if (hdr == NULL)
63906e6d5868SMatthew Ahrens 		return;
63916e6d5868SMatthew Ahrens 
6392dcbf3bd6SGeorge Wilson 	/*
6393dcbf3bd6SGeorge Wilson 	 * We might be trying to free a block that is still doing I/O
6394dcbf3bd6SGeorge Wilson 	 * (i.e. prefetch) or has a reference (i.e. a dedup-ed,
6395dcbf3bd6SGeorge Wilson 	 * dmu_sync-ed block). If this block is being prefetched, then it
6396dcbf3bd6SGeorge Wilson 	 * would still have the ARC_FLAG_IO_IN_PROGRESS flag set on the hdr
6397dcbf3bd6SGeorge Wilson 	 * until the I/O completes. A block may also have a reference if it is
6398dcbf3bd6SGeorge Wilson 	 * part of a dedup-ed, dmu_synced write. The dmu_sync() function would
6399dcbf3bd6SGeorge Wilson 	 * have written the new block to its final resting place on disk but
6400dcbf3bd6SGeorge Wilson 	 * without the dedup flag set. This would have left the hdr in the MRU
6401dcbf3bd6SGeorge Wilson 	 * state and discoverable. When the txg finally syncs it detects that
6402dcbf3bd6SGeorge Wilson 	 * the block was overridden in open context and issues an override I/O.
6403dcbf3bd6SGeorge Wilson 	 * Since this is a dedup block, the override I/O will determine if the
6404dcbf3bd6SGeorge Wilson 	 * block is already in the DDT. If so, then it will replace the io_bp
6405dcbf3bd6SGeorge Wilson 	 * with the bp from the DDT and allow the I/O to finish. When the I/O
6406dcbf3bd6SGeorge Wilson 	 * reaches the done callback, dbuf_write_override_done, it will
6407dcbf3bd6SGeorge Wilson 	 * check to see if the io_bp and io_bp_override are identical.
6408dcbf3bd6SGeorge Wilson 	 * If they are not, then it indicates that the bp was replaced with
6409dcbf3bd6SGeorge Wilson 	 * the bp in the DDT and the override bp is freed. This allows
6410dcbf3bd6SGeorge Wilson 	 * us to arrive here with a reference on a block that is being
6411dcbf3bd6SGeorge Wilson 	 * freed. So if we have an I/O in progress, or a reference to
6412dcbf3bd6SGeorge Wilson 	 * this hdr, then we don't destroy the hdr.
6413dcbf3bd6SGeorge Wilson 	 */
6414dcbf3bd6SGeorge Wilson 	if (!HDR_HAS_L1HDR(hdr) || (!HDR_IO_IN_PROGRESS(hdr) &&
6415e914ace2STim Schumacher 	    zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt))) {
6416dcbf3bd6SGeorge Wilson 		arc_change_state(arc_anon, hdr, hash_lock);
6417dcbf3bd6SGeorge Wilson 		arc_hdr_destroy(hdr);
64186e6d5868SMatthew Ahrens 		mutex_exit(hash_lock);
6419bbfa8ea8SMatthew Ahrens 	} else {
6420dcbf3bd6SGeorge Wilson 		mutex_exit(hash_lock);
6421ea8dc4b6Seschrock 	}
6422dd6ef538Smaybee 
6423ea8dc4b6Seschrock }
6424ea8dc4b6Seschrock 
6425fa9e4066Sahrens /*
64263e30c24aSWill Andrews  * Release this buffer from the cache, making it an anonymous buffer.  This
64273e30c24aSWill Andrews  * must be done after a read and prior to modifying the buffer contents.
6428fa9e4066Sahrens  * If the buffer has more than one reference, we must make
6429088f3894Sahrens  * a new hdr for the buffer.
6430fa9e4066Sahrens  */
6431fa9e4066Sahrens void
6432fa9e4066Sahrens arc_release(arc_buf_t *buf, void *tag)
6433fa9e4066Sahrens {
643489c86e32SChris Williamson 	arc_buf_hdr_t *hdr = buf->b_hdr;
6435fa9e4066Sahrens 
64363f9d6ad7SLin Ling 	/*
6437*eb633035STom Caputi 	 * It would be nice to assert that if its DMU metadata (level >
64383f9d6ad7SLin Ling 	 * 0 || it's the dnode file), then it must be syncing context.
64393f9d6ad7SLin Ling 	 * But we don't know that information at this level.
64403f9d6ad7SLin Ling 	 */
64413f9d6ad7SLin Ling 
64423f9d6ad7SLin Ling 	mutex_enter(&buf->b_evict_lock);
64436f83844dSMark Maybee 
6444244781f1SPrakash Surya 	ASSERT(HDR_HAS_L1HDR(hdr));
6445244781f1SPrakash Surya 
644689c86e32SChris Williamson 	/*
644789c86e32SChris Williamson 	 * We don't grab the hash lock prior to this check, because if
644889c86e32SChris Williamson 	 * the buffer's header is in the arc_anon state, it won't be
644989c86e32SChris Williamson 	 * linked into the hash table.
645089c86e32SChris Williamson 	 */
645189c86e32SChris Williamson 	if (hdr->b_l1hdr.b_state == arc_anon) {
645289c86e32SChris Williamson 		mutex_exit(&buf->b_evict_lock);
6453*eb633035STom Caputi 		/*
6454*eb633035STom Caputi 		 * If we are called from dmu_convert_mdn_block_to_raw(),
6455*eb633035STom Caputi 		 * a write might be in progress.  This is OK because
6456*eb633035STom Caputi 		 * the caller won't change the content of this buffer,
6457*eb633035STom Caputi 		 * only the flags (via arc_convert_to_raw()).
6458*eb633035STom Caputi 		 */
6459*eb633035STom Caputi 		/* ASSERT(!HDR_IO_IN_PROGRESS(hdr)); */
646089c86e32SChris Williamson 		ASSERT(!HDR_IN_HASH_TABLE(hdr));
646189c86e32SChris Williamson 		ASSERT(!HDR_HAS_L2HDR(hdr));
6462dcbf3bd6SGeorge Wilson 		ASSERT(HDR_EMPTY(hdr));
6463fa9e4066Sahrens 
6464dcbf3bd6SGeorge Wilson 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
6465e914ace2STim Schumacher 		ASSERT3S(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
646689c86e32SChris Williamson 		ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
646789c86e32SChris Williamson 
646889c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = 0;
6469dcbf3bd6SGeorge Wilson 
6470dcbf3bd6SGeorge Wilson 		/*
6471dcbf3bd6SGeorge Wilson 		 * If the buf is being overridden then it may already
6472dcbf3bd6SGeorge Wilson 		 * have a hdr that is not empty.
6473dcbf3bd6SGeorge Wilson 		 */
6474dcbf3bd6SGeorge Wilson 		buf_discard_identity(hdr);
647589c86e32SChris Williamson 		arc_buf_thaw(buf);
647689c86e32SChris Williamson 
647789c86e32SChris Williamson 		return;
6478fa9e4066Sahrens 	}
6479fa9e4066Sahrens 
648089c86e32SChris Williamson 	kmutex_t *hash_lock = HDR_LOCK(hdr);
648189c86e32SChris Williamson 	mutex_enter(hash_lock);
648289c86e32SChris Williamson 
648389c86e32SChris Williamson 	/*
648489c86e32SChris Williamson 	 * This assignment is only valid as long as the hash_lock is
648589c86e32SChris Williamson 	 * held, we must be careful not to reference state or the
648689c86e32SChris Williamson 	 * b_state field after dropping the lock.
648789c86e32SChris Williamson 	 */
648889c86e32SChris Williamson 	arc_state_t *state = hdr->b_l1hdr.b_state;
648989c86e32SChris Williamson 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
649089c86e32SChris Williamson 	ASSERT3P(state, !=, arc_anon);
649189c86e32SChris Williamson 
649289c86e32SChris Williamson 	/* this buffer is not on any list */
6493e914ace2STim Schumacher 	ASSERT3S(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt), >, 0);
649489c86e32SChris Williamson 
649589c86e32SChris Williamson 	if (HDR_HAS_L2HDR(hdr)) {
649689c86e32SChris Williamson 		mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
6497244781f1SPrakash Surya 
6498244781f1SPrakash Surya 		/*
6499a52fc310SPrakash Surya 		 * We have to recheck this conditional again now that
6500a52fc310SPrakash Surya 		 * we're holding the l2ad_mtx to prevent a race with
6501a52fc310SPrakash Surya 		 * another thread which might be concurrently calling
6502a52fc310SPrakash Surya 		 * l2arc_evict(). In that case, l2arc_evict() might have
6503a52fc310SPrakash Surya 		 * destroyed the header's L2 portion as we were waiting
6504a52fc310SPrakash Surya 		 * to acquire the l2ad_mtx.
6505244781f1SPrakash Surya 		 */
6506a52fc310SPrakash Surya 		if (HDR_HAS_L2HDR(hdr))
6507a52fc310SPrakash Surya 			arc_hdr_l2hdr_destroy(hdr);
6508244781f1SPrakash Surya 
650989c86e32SChris Williamson 		mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
65106f83844dSMark Maybee 	}
65116f83844dSMark Maybee 
6512ea8dc4b6Seschrock 	/*
6513ea8dc4b6Seschrock 	 * Do we have more than one buf?
6514ea8dc4b6Seschrock 	 */
6515dcbf3bd6SGeorge Wilson 	if (hdr->b_l1hdr.b_bufcnt > 1) {
6516fa9e4066Sahrens 		arc_buf_hdr_t *nhdr;
6517ac05c741SMark Maybee 		uint64_t spa = hdr->b_spa;
6518dcbf3bd6SGeorge Wilson 		uint64_t psize = HDR_GET_PSIZE(hdr);
6519dcbf3bd6SGeorge Wilson 		uint64_t lsize = HDR_GET_LSIZE(hdr);
6520*eb633035STom Caputi 		boolean_t protected = HDR_PROTECTED(hdr);
6521*eb633035STom Caputi 		enum zio_compress compress = arc_hdr_get_compress(hdr);
652289c86e32SChris Williamson 		arc_buf_contents_t type = arc_buf_type(hdr);
6523dcbf3bd6SGeorge Wilson 		VERIFY3U(hdr->b_type, ==, type);
6524fa9e4066Sahrens 
652589c86e32SChris Williamson 		ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
6526dcbf3bd6SGeorge Wilson 		(void) remove_reference(hdr, hash_lock, tag);
6527dcbf3bd6SGeorge Wilson 
65285602294fSDan Kimmel 		if (arc_buf_is_shared(buf) && !ARC_BUF_COMPRESSED(buf)) {
6529dcbf3bd6SGeorge Wilson 			ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
6530dcbf3bd6SGeorge Wilson 			ASSERT(ARC_BUF_LAST(buf));
6531dcbf3bd6SGeorge Wilson 		}
6532dcbf3bd6SGeorge Wilson 
6533fa9e4066Sahrens 		/*
65343f9d6ad7SLin Ling 		 * Pull the data off of this hdr and attach it to
6535dcbf3bd6SGeorge Wilson 		 * a new anonymous hdr. Also find the last buffer
6536dcbf3bd6SGeorge Wilson 		 * in the hdr's buffer list.
6537fa9e4066Sahrens 		 */
65385602294fSDan Kimmel 		arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
6539dcbf3bd6SGeorge Wilson 		ASSERT3P(lastbuf, !=, NULL);
6540dcbf3bd6SGeorge Wilson 
6541dcbf3bd6SGeorge Wilson 		/*
6542dcbf3bd6SGeorge Wilson 		 * If the current arc_buf_t and the hdr are sharing their data
65435602294fSDan Kimmel 		 * buffer, then we must stop sharing that block.
6544dcbf3bd6SGeorge Wilson 		 */
6545dcbf3bd6SGeorge Wilson 		if (arc_buf_is_shared(buf)) {
6546*eb633035STom Caputi 			ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
6547dcbf3bd6SGeorge Wilson 			VERIFY(!arc_buf_is_shared(lastbuf));
6548ea8dc4b6Seschrock 
6549dcbf3bd6SGeorge Wilson 			/*
6550dcbf3bd6SGeorge Wilson 			 * First, sever the block sharing relationship between
65515602294fSDan Kimmel 			 * buf and the arc_buf_hdr_t.
6552dcbf3bd6SGeorge Wilson 			 */
6553dcbf3bd6SGeorge Wilson 			arc_unshare_buf(hdr, buf);
65545602294fSDan Kimmel 
65555602294fSDan Kimmel 			/*
6556770499e1SDan Kimmel 			 * Now we need to recreate the hdr's b_pabd. Since we
65575602294fSDan Kimmel 			 * have lastbuf handy, we try to share with it, but if
6558770499e1SDan Kimmel 			 * we can't then we allocate a new b_pabd and copy the
65595602294fSDan Kimmel 			 * data from buf into it.
65605602294fSDan Kimmel 			 */
65615602294fSDan Kimmel 			if (arc_can_share(hdr, lastbuf)) {
65625602294fSDan Kimmel 				arc_share_buf(hdr, lastbuf);
65635602294fSDan Kimmel 			} else {
6564*eb633035STom Caputi 				arc_hdr_alloc_pabd(hdr, B_FALSE);
6565770499e1SDan Kimmel 				abd_copy_from_buf(hdr->b_l1hdr.b_pabd,
6566770499e1SDan Kimmel 				    buf->b_data, psize);
65675602294fSDan Kimmel 			}
6568dcbf3bd6SGeorge Wilson 			VERIFY3P(lastbuf->b_data, !=, NULL);
6569dcbf3bd6SGeorge Wilson 		} else if (HDR_SHARED_DATA(hdr)) {
65705602294fSDan Kimmel 			/*
65715602294fSDan Kimmel 			 * Uncompressed shared buffers are always at the end
65725602294fSDan Kimmel 			 * of the list. Compressed buffers don't have the
65735602294fSDan Kimmel 			 * same requirements. This makes it hard to
65745602294fSDan Kimmel 			 * simply assert that the lastbuf is shared so
65755602294fSDan Kimmel 			 * we rely on the hdr's compression flags to determine
65765602294fSDan Kimmel 			 * if we have a compressed, shared buffer.
65775602294fSDan Kimmel 			 */
65785602294fSDan Kimmel 			ASSERT(arc_buf_is_shared(lastbuf) ||
6579*eb633035STom Caputi 			    arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF);
65805602294fSDan Kimmel 			ASSERT(!ARC_BUF_SHARED(buf));
6581dcbf3bd6SGeorge Wilson 		}
6582*eb633035STom Caputi 		ASSERT(hdr->b_l1hdr.b_pabd != NULL || HDR_HAS_RABD(hdr));
658389c86e32SChris Williamson 		ASSERT3P(state, !=, arc_l2c_only);
65842fd872a7SPrakash Surya 
6585e914ace2STim Schumacher 		(void) zfs_refcount_remove_many(&state->arcs_size,
65865602294fSDan Kimmel 		    arc_buf_size(buf), buf);
65872fd872a7SPrakash Surya 
6588e914ace2STim Schumacher 		if (zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
658989c86e32SChris Williamson 			ASSERT3P(state, !=, arc_l2c_only);
6590e914ace2STim Schumacher 			(void) zfs_refcount_remove_many(
6591e914ace2STim Schumacher 			    &state->arcs_esize[type],
65925602294fSDan Kimmel 			    arc_buf_size(buf), buf);
6593ea8dc4b6Seschrock 		}
65949253d63dSGeorge Wilson 
6595dcbf3bd6SGeorge Wilson 		hdr->b_l1hdr.b_bufcnt -= 1;
6596*eb633035STom Caputi 		if (ARC_BUF_ENCRYPTED(buf))
6597*eb633035STom Caputi 			hdr->b_crypt_hdr.b_ebufcnt -= 1;
6598*eb633035STom Caputi 
6599c717a561Smaybee 		arc_cksum_verify(buf);
6600cd1c8b85SMatthew Ahrens 		arc_buf_unwatch(buf);
6601ea8dc4b6Seschrock 
6602*eb633035STom Caputi 		/* if this is the last uncompressed buf free the checksum */
6603*eb633035STom Caputi 		if (!arc_hdr_has_uncompressed_buf(hdr))
6604*eb633035STom Caputi 			arc_cksum_free(hdr);
6605*eb633035STom Caputi 
6606fa9e4066Sahrens 		mutex_exit(hash_lock);
6607fa9e4066Sahrens 
6608dcbf3bd6SGeorge Wilson 		/*
6609770499e1SDan Kimmel 		 * Allocate a new hdr. The new hdr will contain a b_pabd
6610dcbf3bd6SGeorge Wilson 		 * buffer which will be freed in arc_write().
6611dcbf3bd6SGeorge Wilson 		 */
6612*eb633035STom Caputi 		nhdr = arc_hdr_alloc(spa, psize, lsize, protected,
6613*eb633035STom Caputi 		    compress, type, HDR_HAS_RABD(hdr));
6614dcbf3bd6SGeorge Wilson 		ASSERT3P(nhdr->b_l1hdr.b_buf, ==, NULL);
6615dcbf3bd6SGeorge Wilson 		ASSERT0(nhdr->b_l1hdr.b_bufcnt);
6616e914ace2STim Schumacher 		ASSERT0(zfs_refcount_count(&nhdr->b_l1hdr.b_refcnt));
6617dcbf3bd6SGeorge Wilson 		VERIFY3U(nhdr->b_type, ==, type);
6618dcbf3bd6SGeorge Wilson 		ASSERT(!HDR_SHARED_DATA(nhdr));
661989c86e32SChris Williamson 
662089c86e32SChris Williamson 		nhdr->b_l1hdr.b_buf = buf;
6621dcbf3bd6SGeorge Wilson 		nhdr->b_l1hdr.b_bufcnt = 1;
6622*eb633035STom Caputi 		if (ARC_BUF_ENCRYPTED(buf))
6623*eb633035STom Caputi 			nhdr->b_crypt_hdr.b_ebufcnt = 1;
6624e914ace2STim Schumacher 		(void) zfs_refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
6625af2c4821Smaybee 		buf->b_hdr = nhdr;
6626dcbf3bd6SGeorge Wilson 
66273f9d6ad7SLin Ling 		mutex_exit(&buf->b_evict_lock);
6628e914ace2STim Schumacher 		(void) zfs_refcount_add_many(&arc_anon->arcs_size,
66295602294fSDan Kimmel 		    arc_buf_size(buf), buf);
6630fa9e4066Sahrens 	} else {
66313f9d6ad7SLin Ling 		mutex_exit(&buf->b_evict_lock);
6632e914ace2STim Schumacher 		ASSERT(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
6633244781f1SPrakash Surya 		/* protected by hash lock, or hdr is on arc_anon */
6634244781f1SPrakash Surya 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
6635fa9e4066Sahrens 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
663689c86e32SChris Williamson 		arc_change_state(arc_anon, hdr, hash_lock);
663789c86e32SChris Williamson 		hdr->b_l1hdr.b_arc_access = 0;
6638fa94a07fSbrendan 
6639*eb633035STom Caputi 		mutex_exit(hash_lock);
66403f9d6ad7SLin Ling 		buf_discard_identity(hdr);
6641c717a561Smaybee 		arc_buf_thaw(buf);
6642fa9e4066Sahrens 	}
6643fa9e4066Sahrens }
6644fa9e4066Sahrens 
6645fa9e4066Sahrens int
6646fa9e4066Sahrens arc_released(arc_buf_t *buf)
6647fa9e4066Sahrens {
66486f83844dSMark Maybee 	int released;
66496f83844dSMark Maybee 
66503f9d6ad7SLin Ling 	mutex_enter(&buf->b_evict_lock);
665189c86e32SChris Williamson 	released = (buf->b_data != NULL &&
665289c86e32SChris Williamson 	    buf->b_hdr->b_l1hdr.b_state == arc_anon);
66533f9d6ad7SLin Ling 	mutex_exit(&buf->b_evict_lock);
66546f83844dSMark Maybee 	return (released);
6655ea8dc4b6Seschrock }
6656ea8dc4b6Seschrock 
6657ea8dc4b6Seschrock #ifdef ZFS_DEBUG
6658ea8dc4b6Seschrock int
6659ea8dc4b6Seschrock arc_referenced(arc_buf_t *buf)
6660ea8dc4b6Seschrock {
66616f83844dSMark Maybee 	int referenced;
66626f83844dSMark Maybee 
66633f9d6ad7SLin Ling 	mutex_enter(&buf->b_evict_lock);
6664e914ace2STim Schumacher 	referenced = (zfs_refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
66653f9d6ad7SLin Ling 	mutex_exit(&buf->b_evict_lock);
66666f83844dSMark Maybee 	return (referenced);
6667ea8dc4b6Seschrock }
6668ea8dc4b6Seschrock #endif
6669ea8dc4b6Seschrock 
6670c717a561Smaybee static void
6671c717a561Smaybee arc_write_ready(zio_t *zio)
6672c717a561Smaybee {
6673c717a561Smaybee 	arc_write_callback_t *callback = zio->io_private;
6674c717a561Smaybee 	arc_buf_t *buf = callback->awcb_buf;
66750a4e9518Sgw 	arc_buf_hdr_t *hdr = buf->b_hdr;
6676*eb633035STom Caputi 	blkptr_t *bp = zio->io_bp;
6677*eb633035STom Caputi 	uint64_t psize = BP_IS_HOLE(bp) ? 0 : BP_GET_PSIZE(bp);
6678c717a561Smaybee 
667989c86e32SChris Williamson 	ASSERT(HDR_HAS_L1HDR(hdr));
6680e914ace2STim Schumacher 	ASSERT(!zfs_refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
6681dcbf3bd6SGeorge Wilson 	ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
6682e14bb325SJeff Bonwick 
66830a4e9518Sgw 	/*
6684dcbf3bd6SGeorge Wilson 	 * If we're reexecuting this zio because the pool suspended, then
6685dcbf3bd6SGeorge Wilson 	 * cleanup any state that was previously set the first time the
66865602294fSDan Kimmel 	 * callback was invoked.
66870a4e9518Sgw 	 */
6688dcbf3bd6SGeorge Wilson 	if (zio->io_flags & ZIO_FLAG_REEXECUTED) {
6689dcbf3bd6SGeorge Wilson 		arc_cksum_free(hdr);
6690dcbf3bd6SGeorge Wilson 		arc_buf_unwatch(buf);
6691770499e1SDan Kimmel 		if (hdr->b_l1hdr.b_pabd != NULL) {
6692dcbf3bd6SGeorge Wilson 			if (arc_buf_is_shared(buf)) {
6693dcbf3bd6SGeorge Wilson 				arc_unshare_buf(hdr, buf);
6694dcbf3bd6SGeorge Wilson 			} else {
6695*eb633035STom Caputi 				arc_hdr_free_pabd(hdr, B_FALSE);
6696dcbf3bd6SGeorge Wilson 			}
66970a4e9518Sgw 		}
6698*eb633035STom Caputi 
6699*eb633035STom Caputi 		if (HDR_HAS_RABD(hdr))
6700*eb633035STom Caputi 			arc_hdr_free_pabd(hdr, B_TRUE);
67010a4e9518Sgw 	}
6702770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
6703*eb633035STom Caputi 	ASSERT(!HDR_HAS_RABD(hdr));
6704dcbf3bd6SGeorge Wilson 	ASSERT(!HDR_SHARED_DATA(hdr));
6705dcbf3bd6SGeorge Wilson 	ASSERT(!arc_buf_is_shared(buf));
6706dcbf3bd6SGeorge Wilson 
6707dcbf3bd6SGeorge Wilson 	callback->awcb_ready(zio, buf, callback->awcb_private);
6708dcbf3bd6SGeorge Wilson 
6709dcbf3bd6SGeorge Wilson 	if (HDR_IO_IN_PROGRESS(hdr))
6710dcbf3bd6SGeorge Wilson 		ASSERT(zio->io_flags & ZIO_FLAG_REEXECUTED);
6711dcbf3bd6SGeorge Wilson 
6712dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6713dcbf3bd6SGeorge Wilson 
6714*eb633035STom Caputi 	if (BP_IS_PROTECTED(bp) != !!HDR_PROTECTED(hdr))
6715*eb633035STom Caputi 		hdr = arc_hdr_realloc_crypt(hdr, BP_IS_PROTECTED(bp));
6716*eb633035STom Caputi 
6717*eb633035STom Caputi 	if (BP_IS_PROTECTED(bp)) {
6718*eb633035STom Caputi 		/* ZIL blocks are written through zio_rewrite */
6719*eb633035STom Caputi 		ASSERT3U(BP_GET_TYPE(bp), !=, DMU_OT_INTENT_LOG);
6720*eb633035STom Caputi 		ASSERT(HDR_PROTECTED(hdr));
6721*eb633035STom Caputi 
6722*eb633035STom Caputi 		if (BP_SHOULD_BYTESWAP(bp)) {
6723*eb633035STom Caputi 			if (BP_GET_LEVEL(bp) > 0) {
6724*eb633035STom Caputi 				hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
6725*eb633035STom Caputi 			} else {
6726*eb633035STom Caputi 				hdr->b_l1hdr.b_byteswap =
6727*eb633035STom Caputi 				    DMU_OT_BYTESWAP(BP_GET_TYPE(bp));
6728*eb633035STom Caputi 			}
6729*eb633035STom Caputi 		} else {
6730*eb633035STom Caputi 			hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
6731*eb633035STom Caputi 		}
6732*eb633035STom Caputi 
6733*eb633035STom Caputi 		hdr->b_crypt_hdr.b_ot = BP_GET_TYPE(bp);
6734*eb633035STom Caputi 		hdr->b_crypt_hdr.b_dsobj = zio->io_bookmark.zb_objset;
6735*eb633035STom Caputi 		zio_crypt_decode_params_bp(bp, hdr->b_crypt_hdr.b_salt,
6736*eb633035STom Caputi 		    hdr->b_crypt_hdr.b_iv);
6737*eb633035STom Caputi 		zio_crypt_decode_mac_bp(bp, hdr->b_crypt_hdr.b_mac);
6738*eb633035STom Caputi 	}
6739*eb633035STom Caputi 
6740*eb633035STom Caputi 	/*
6741*eb633035STom Caputi 	 * If this block was written for raw encryption but the zio layer
6742*eb633035STom Caputi 	 * ended up only authenticating it, adjust the buffer flags now.
6743*eb633035STom Caputi 	 */
6744*eb633035STom Caputi 	if (BP_IS_AUTHENTICATED(bp) && ARC_BUF_ENCRYPTED(buf)) {
6745*eb633035STom Caputi 		arc_hdr_set_flags(hdr, ARC_FLAG_NOAUTH);
6746*eb633035STom Caputi 		buf->b_flags &= ~ARC_BUF_FLAG_ENCRYPTED;
6747*eb633035STom Caputi 		if (BP_GET_COMPRESS(bp) == ZIO_COMPRESS_OFF)
6748*eb633035STom Caputi 			buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
6749*eb633035STom Caputi 	} else if (BP_IS_HOLE(bp) && ARC_BUF_ENCRYPTED(buf)) {
6750*eb633035STom Caputi 		buf->b_flags &= ~ARC_BUF_FLAG_ENCRYPTED;
6751*eb633035STom Caputi 		buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
6752*eb633035STom Caputi 	}
6753*eb633035STom Caputi 
6754*eb633035STom Caputi 	/* this must be done after the buffer flags are adjusted */
6755*eb633035STom Caputi 	arc_cksum_compute(buf);
6756*eb633035STom Caputi 
6757dcbf3bd6SGeorge Wilson 	enum zio_compress compress;
6758*eb633035STom Caputi 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
6759dcbf3bd6SGeorge Wilson 		compress = ZIO_COMPRESS_OFF;
6760dcbf3bd6SGeorge Wilson 	} else {
6761*eb633035STom Caputi 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
6762*eb633035STom Caputi 		compress = BP_GET_COMPRESS(bp);
6763dcbf3bd6SGeorge Wilson 	}
6764dcbf3bd6SGeorge Wilson 	HDR_SET_PSIZE(hdr, psize);
6765dcbf3bd6SGeorge Wilson 	arc_hdr_set_compress(hdr, compress);
6766dcbf3bd6SGeorge Wilson 
6767*eb633035STom Caputi 	if (zio->io_error != 0 || psize == 0)
6768*eb633035STom Caputi 		goto out;
6769770499e1SDan Kimmel 
6770dcbf3bd6SGeorge Wilson 	/*
6771*eb633035STom Caputi 	 * Fill the hdr with data. If the buffer is encrypted we have no choice
6772*eb633035STom Caputi 	 * but to copy the data into b_rabd. If the hdr is compressed, the data
6773*eb633035STom Caputi 	 * we want is available from the zio, otherwise we can take it from
6774*eb633035STom Caputi 	 * the buf.
6775770499e1SDan Kimmel 	 *
6776770499e1SDan Kimmel 	 * We might be able to share the buf's data with the hdr here. However,
6777770499e1SDan Kimmel 	 * doing so would cause the ARC to be full of linear ABDs if we write a
6778770499e1SDan Kimmel 	 * lot of shareable data. As a compromise, we check whether scattered
6779770499e1SDan Kimmel 	 * ABDs are allowed, and assume that if they are then the user wants
6780770499e1SDan Kimmel 	 * the ARC to be primarily filled with them regardless of the data being
6781770499e1SDan Kimmel 	 * written. Therefore, if they're allowed then we allocate one and copy
6782770499e1SDan Kimmel 	 * the data into it; otherwise, we share the data directly if we can.
6783dcbf3bd6SGeorge Wilson 	 */
6784*eb633035STom Caputi 	if (ARC_BUF_ENCRYPTED(buf)) {
6785*eb633035STom Caputi 		ASSERT3U(psize, >, 0);
6786*eb633035STom Caputi 		ASSERT(ARC_BUF_COMPRESSED(buf));
6787*eb633035STom Caputi 		arc_hdr_alloc_pabd(hdr, B_TRUE);
6788*eb633035STom Caputi 		abd_copy(hdr->b_crypt_hdr.b_rabd, zio->io_abd, psize);
6789*eb633035STom Caputi 	} else if (zfs_abd_scatter_enabled || !arc_can_share(hdr, buf)) {
6790770499e1SDan Kimmel 		/*
6791770499e1SDan Kimmel 		 * Ideally, we would always copy the io_abd into b_pabd, but the
6792770499e1SDan Kimmel 		 * user may have disabled compressed ARC, thus we must check the
6793770499e1SDan Kimmel 		 * hdr's compression setting rather than the io_bp's.
6794770499e1SDan Kimmel 		 */
6795*eb633035STom Caputi 		if (BP_IS_ENCRYPTED(bp)) {
6796770499e1SDan Kimmel 			ASSERT3U(psize, >, 0);
6797*eb633035STom Caputi 			arc_hdr_alloc_pabd(hdr, B_TRUE);
6798*eb633035STom Caputi 			abd_copy(hdr->b_crypt_hdr.b_rabd, zio->io_abd, psize);
6799*eb633035STom Caputi 		} else if (arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF &&
6800*eb633035STom Caputi 		    !ARC_BUF_COMPRESSED(buf)) {
6801*eb633035STom Caputi 			ASSERT3U(psize, >, 0);
6802*eb633035STom Caputi 			arc_hdr_alloc_pabd(hdr, B_FALSE);
6803770499e1SDan Kimmel 			abd_copy(hdr->b_l1hdr.b_pabd, zio->io_abd, psize);
6804770499e1SDan Kimmel 		} else {
6805770499e1SDan Kimmel 			ASSERT3U(zio->io_orig_size, ==, arc_hdr_size(hdr));
6806*eb633035STom Caputi 			arc_hdr_alloc_pabd(hdr, B_FALSE);
6807770499e1SDan Kimmel 			abd_copy_from_buf(hdr->b_l1hdr.b_pabd, buf->b_data,
6808770499e1SDan Kimmel 			    arc_buf_size(buf));
6809770499e1SDan Kimmel 		}
6810dcbf3bd6SGeorge Wilson 	} else {
6811770499e1SDan Kimmel 		ASSERT3P(buf->b_data, ==, abd_to_buf(zio->io_orig_abd));
68125602294fSDan Kimmel 		ASSERT3U(zio->io_orig_size, ==, arc_buf_size(buf));
6813dcbf3bd6SGeorge Wilson 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
6814dcbf3bd6SGeorge Wilson 		arc_share_buf(hdr, buf);
6815dcbf3bd6SGeorge Wilson 	}
6816770499e1SDan Kimmel 
6817*eb633035STom Caputi out:
6818*eb633035STom Caputi 	arc_hdr_verify(hdr, bp);
6819c717a561Smaybee }
6820c717a561Smaybee 
68218df0bcf0SPaul Dagnelie static void
68228df0bcf0SPaul Dagnelie arc_write_children_ready(zio_t *zio)
68238df0bcf0SPaul Dagnelie {
68248df0bcf0SPaul Dagnelie 	arc_write_callback_t *callback = zio->io_private;
68258df0bcf0SPaul Dagnelie 	arc_buf_t *buf = callback->awcb_buf;
68268df0bcf0SPaul Dagnelie 
68278df0bcf0SPaul Dagnelie 	callback->awcb_children_ready(zio, buf, callback->awcb_private);
68288df0bcf0SPaul Dagnelie }
68298df0bcf0SPaul Dagnelie 
683069962b56SMatthew Ahrens /*
683169962b56SMatthew Ahrens  * The SPA calls this callback for each physical write that happens on behalf
683269962b56SMatthew Ahrens  * of a logical write.  See the comment in dbuf_write_physdone() for details.
683369962b56SMatthew Ahrens  */
683469962b56SMatthew Ahrens static void
683569962b56SMatthew Ahrens arc_write_physdone(zio_t *zio)
683669962b56SMatthew Ahrens {
683769962b56SMatthew Ahrens 	arc_write_callback_t *cb = zio->io_private;
683869962b56SMatthew Ahrens 	if (cb->awcb_physdone != NULL)
683969962b56SMatthew Ahrens 		cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
684069962b56SMatthew Ahrens }
684169962b56SMatthew Ahrens 
6842fa9e4066Sahrens static void
6843fa9e4066Sahrens arc_write_done(zio_t *zio)
6844fa9e4066Sahrens {
6845c717a561Smaybee 	arc_write_callback_t *callback = zio->io_private;
6846c717a561Smaybee 	arc_buf_t *buf = callback->awcb_buf;
6847c717a561Smaybee 	arc_buf_hdr_t *hdr = buf->b_hdr;
6848fa9e4066Sahrens 
6849dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
6850b24ab676SJeff Bonwick 
6851b24ab676SJeff Bonwick 	if (zio->io_error == 0) {
6852dcbf3bd6SGeorge Wilson 		arc_hdr_verify(hdr, zio->io_bp);
6853dcbf3bd6SGeorge Wilson 
68545d7b4d43SMatthew Ahrens 		if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
685543466aaeSMax Grossman 			buf_discard_identity(hdr);
685643466aaeSMax Grossman 		} else {
685743466aaeSMax Grossman 			hdr->b_dva = *BP_IDENTITY(zio->io_bp);
685843466aaeSMax Grossman 			hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
685943466aaeSMax Grossman 		}
6860b24ab676SJeff Bonwick 	} else {
6861dcbf3bd6SGeorge Wilson 		ASSERT(HDR_EMPTY(hdr));
6862b24ab676SJeff Bonwick 	}
6863fa9e4066Sahrens 
6864ea8dc4b6Seschrock 	/*
68655d7b4d43SMatthew Ahrens 	 * If the block to be written was all-zero or compressed enough to be
68665d7b4d43SMatthew Ahrens 	 * embedded in the BP, no write was performed so there will be no
68675d7b4d43SMatthew Ahrens 	 * dva/birth/checksum.  The buffer must therefore remain anonymous
68685d7b4d43SMatthew Ahrens 	 * (and uncached).
6869ea8dc4b6Seschrock 	 */
6870dcbf3bd6SGeorge Wilson 	if (!HDR_EMPTY(hdr)) {
6871fa9e4066Sahrens 		arc_buf_hdr_t *exists;
6872fa9e4066Sahrens 		kmutex_t *hash_lock;
6873fa9e4066Sahrens 
68745602294fSDan Kimmel 		ASSERT3U(zio->io_error, ==, 0);
6875b24ab676SJeff Bonwick 
68766b4acc8bSahrens 		arc_cksum_verify(buf);
68776b4acc8bSahrens 
6878fa9e4066Sahrens 		exists = buf_hash_insert(hdr, &hash_lock);
687989c86e32SChris Williamson 		if (exists != NULL) {
6880fa9e4066Sahrens 			/*
6881fa9e4066Sahrens 			 * This can only happen if we overwrite for
6882fa9e4066Sahrens 			 * sync-to-convergence, because we remove
6883fa9e4066Sahrens 			 * buffers from the hash table when we arc_free().
6884fa9e4066Sahrens 			 */
6885b24ab676SJeff Bonwick 			if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
6886b24ab676SJeff Bonwick 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
6887b24ab676SJeff Bonwick 					panic("bad overwrite, hdr=%p exists=%p",
6888b24ab676SJeff Bonwick 					    (void *)hdr, (void *)exists);
6889e914ace2STim Schumacher 				ASSERT(zfs_refcount_is_zero(
689089c86e32SChris Williamson 				    &exists->b_l1hdr.b_refcnt));
6891b24ab676SJeff Bonwick 				arc_change_state(arc_anon, exists, hash_lock);
6892b24ab676SJeff Bonwick 				mutex_exit(hash_lock);
6893b24ab676SJeff Bonwick 				arc_hdr_destroy(exists);
6894b24ab676SJeff Bonwick 				exists = buf_hash_insert(hdr, &hash_lock);
6895b24ab676SJeff Bonwick 				ASSERT3P(exists, ==, NULL);
689680901aeaSGeorge Wilson 			} else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
689780901aeaSGeorge Wilson 				/* nopwrite */
689880901aeaSGeorge Wilson 				ASSERT(zio->io_prop.zp_nopwrite);
689980901aeaSGeorge Wilson 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
690080901aeaSGeorge Wilson 					panic("bad nopwrite, hdr=%p exists=%p",
690180901aeaSGeorge Wilson 					    (void *)hdr, (void *)exists);
6902b24ab676SJeff Bonwick 			} else {
6903b24ab676SJeff Bonwick 				/* Dedup */
6904dcbf3bd6SGeorge Wilson 				ASSERT(hdr->b_l1hdr.b_bufcnt == 1);
690589c86e32SChris Williamson 				ASSERT(hdr->b_l1hdr.b_state == arc_anon);
6906b24ab676SJeff Bonwick 				ASSERT(BP_GET_DEDUP(zio->io_bp));
6907b24ab676SJeff Bonwick 				ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
6908ae46e4c7SMatthew Ahrens 			}
6909fa9e4066Sahrens 		}
6910dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6911088f3894Sahrens 		/* if it's not anon, we are doing a scrub */
691289c86e32SChris Williamson 		if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
6913088f3894Sahrens 			arc_access(hdr, hash_lock);
691444eda4d7Smaybee 		mutex_exit(hash_lock);
6915ea8dc4b6Seschrock 	} else {
6916dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6917fa9e4066Sahrens 	}
6918ea8dc4b6Seschrock 
6919e914ace2STim Schumacher 	ASSERT(!zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
6920b24ab676SJeff Bonwick 	callback->awcb_done(zio, buf, callback->awcb_private);
6921fa9e4066Sahrens 
6922770499e1SDan Kimmel 	abd_put(zio->io_abd);
6923c717a561Smaybee 	kmem_free(callback, sizeof (arc_write_callback_t));
6924fa9e4066Sahrens }
6925fa9e4066Sahrens 
6926c717a561Smaybee zio_t *
6927dcbf3bd6SGeorge Wilson arc_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
6928a3874b8bSToomas Soome     boolean_t l2arc, const zio_prop_t *zp, arc_write_done_func_t *ready,
6929a3874b8bSToomas Soome     arc_write_done_func_t *children_ready, arc_write_done_func_t *physdone,
6930a3874b8bSToomas Soome     arc_write_done_func_t *done, void *private, zio_priority_t priority,
69317802d7bfSMatthew Ahrens     int zio_flags, const zbookmark_phys_t *zb)
6932fa9e4066Sahrens {
6933fa9e4066Sahrens 	arc_buf_hdr_t *hdr = buf->b_hdr;
6934c717a561Smaybee 	arc_write_callback_t *callback;
6935e14bb325SJeff Bonwick 	zio_t *zio;
6936adaec86aSMatthew Ahrens 	zio_prop_t localprop = *zp;
6937fa9e4066Sahrens 
6938dcbf3bd6SGeorge Wilson 	ASSERT3P(ready, !=, NULL);
6939dcbf3bd6SGeorge Wilson 	ASSERT3P(done, !=, NULL);
6940fa9e4066Sahrens 	ASSERT(!HDR_IO_ERROR(hdr));
694189c86e32SChris Williamson 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6942dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
6943dcbf3bd6SGeorge Wilson 	ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
69443baa08fcSek 	if (l2arc)
6945dcbf3bd6SGeorge Wilson 		arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
6946adaec86aSMatthew Ahrens 
6947*eb633035STom Caputi 	if (ARC_BUF_ENCRYPTED(buf)) {
6948*eb633035STom Caputi 		ASSERT(ARC_BUF_COMPRESSED(buf));
6949*eb633035STom Caputi 		localprop.zp_encrypt = B_TRUE;
6950*eb633035STom Caputi 		localprop.zp_compress = HDR_GET_COMPRESS(hdr);
6951*eb633035STom Caputi 		/* CONSTCOND */
6952*eb633035STom Caputi 		localprop.zp_byteorder =
6953*eb633035STom Caputi 		    (hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS) ?
6954*eb633035STom Caputi 		    ZFS_HOST_BYTEORDER : !ZFS_HOST_BYTEORDER;
6955*eb633035STom Caputi 		bcopy(hdr->b_crypt_hdr.b_salt, localprop.zp_salt,
6956*eb633035STom Caputi 		    ZIO_DATA_SALT_LEN);
6957*eb633035STom Caputi 		bcopy(hdr->b_crypt_hdr.b_iv, localprop.zp_iv,
6958*eb633035STom Caputi 		    ZIO_DATA_IV_LEN);
6959*eb633035STom Caputi 		bcopy(hdr->b_crypt_hdr.b_mac, localprop.zp_mac,
6960*eb633035STom Caputi 		    ZIO_DATA_MAC_LEN);
6961*eb633035STom Caputi 		if (DMU_OT_IS_ENCRYPTED(localprop.zp_type)) {
6962*eb633035STom Caputi 			localprop.zp_nopwrite = B_FALSE;
6963*eb633035STom Caputi 			localprop.zp_copies =
6964*eb633035STom Caputi 			    MIN(localprop.zp_copies, SPA_DVAS_PER_BP - 1);
6965*eb633035STom Caputi 		}
69665602294fSDan Kimmel 		zio_flags |= ZIO_FLAG_RAW;
6967*eb633035STom Caputi 	} else if (ARC_BUF_COMPRESSED(buf)) {
6968*eb633035STom Caputi 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, arc_buf_size(buf));
6969*eb633035STom Caputi 		localprop.zp_compress = HDR_GET_COMPRESS(hdr);
6970*eb633035STom Caputi 		zio_flags |= ZIO_FLAG_RAW_COMPRESS;
69715602294fSDan Kimmel 	}
6972*eb633035STom Caputi 
6973c717a561Smaybee 	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
6974c717a561Smaybee 	callback->awcb_ready = ready;
69758df0bcf0SPaul Dagnelie 	callback->awcb_children_ready = children_ready;
697669962b56SMatthew Ahrens 	callback->awcb_physdone = physdone;
6977c717a561Smaybee 	callback->awcb_done = done;
6978c717a561Smaybee 	callback->awcb_private = private;
6979c717a561Smaybee 	callback->awcb_buf = buf;
6980088f3894Sahrens 
6981dcbf3bd6SGeorge Wilson 	/*
6982770499e1SDan Kimmel 	 * The hdr's b_pabd is now stale, free it now. A new data block
6983dcbf3bd6SGeorge Wilson 	 * will be allocated when the zio pipeline calls arc_write_ready().
6984dcbf3bd6SGeorge Wilson 	 */
6985770499e1SDan Kimmel 	if (hdr->b_l1hdr.b_pabd != NULL) {
6986dcbf3bd6SGeorge Wilson 		/*
6987dcbf3bd6SGeorge Wilson 		 * If the buf is currently sharing the data block with
6988dcbf3bd6SGeorge Wilson 		 * the hdr then we need to break that relationship here.
6989dcbf3bd6SGeorge Wilson 		 * The hdr will remain with a NULL data pointer and the
6990dcbf3bd6SGeorge Wilson 		 * buf will take sole ownership of the block.
6991dcbf3bd6SGeorge Wilson 		 */
6992dcbf3bd6SGeorge Wilson 		if (arc_buf_is_shared(buf)) {
6993dcbf3bd6SGeorge Wilson 			arc_unshare_buf(hdr, buf);
6994dcbf3bd6SGeorge Wilson 		} else {
6995*eb633035STom Caputi 			arc_hdr_free_pabd(hdr, B_FALSE);
6996dcbf3bd6SGeorge Wilson 		}
6997dcbf3bd6SGeorge Wilson 		VERIFY3P(buf->b_data, !=, NULL);
6998dcbf3bd6SGeorge Wilson 	}
6999*eb633035STom Caputi 
7000*eb633035STom Caputi 	if (HDR_HAS_RABD(hdr))
7001*eb633035STom Caputi 		arc_hdr_free_pabd(hdr, B_TRUE);
7002*eb633035STom Caputi 
7003*eb633035STom Caputi 	if (!(zio_flags & ZIO_FLAG_RAW))
7004*eb633035STom Caputi 		arc_hdr_set_compress(hdr, ZIO_COMPRESS_OFF);
7005*eb633035STom Caputi 
7006dcbf3bd6SGeorge Wilson 	ASSERT(!arc_buf_is_shared(buf));
7007770499e1SDan Kimmel 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
7008dcbf3bd6SGeorge Wilson 
7009770499e1SDan Kimmel 	zio = zio_write(pio, spa, txg, bp,
7010770499e1SDan Kimmel 	    abd_get_from_buf(buf->b_data, HDR_GET_LSIZE(hdr)),
7011adaec86aSMatthew Ahrens 	    HDR_GET_LSIZE(hdr), arc_buf_size(buf), &localprop, arc_write_ready,
70128df0bcf0SPaul Dagnelie 	    (children_ready != NULL) ? arc_write_children_ready : NULL,
70138df0bcf0SPaul Dagnelie 	    arc_write_physdone, arc_write_done, callback,
701469962b56SMatthew Ahrens 	    priority, zio_flags, zb);
7015fa9e4066Sahrens 
7016c717a561Smaybee 	return (zio);
7017fa9e4066Sahrens }
7018fa9e4066Sahrens 
70191ab7f2deSmaybee static int
7020abe1fd01SDon Brady arc_memory_throttle(spa_t *spa, uint64_t reserve, uint64_t txg)
70211ab7f2deSmaybee {
70221ab7f2deSmaybee #ifdef _KERNEL
70231ab7f2deSmaybee 	uint64_t available_memory = ptob(freemem);
70241ab7f2deSmaybee 
70251ab7f2deSmaybee #if defined(__i386)
70261ab7f2deSmaybee 	available_memory =
70271ab7f2deSmaybee 	    MIN(available_memory, vmem_size(heap_arena, VMEM_FREE));
70281ab7f2deSmaybee #endif
702969962b56SMatthew Ahrens 
703069962b56SMatthew Ahrens 	if (freemem > physmem * arc_lotsfree_percent / 100)
70311ab7f2deSmaybee 		return (0);
70321ab7f2deSmaybee 
7033abe1fd01SDon Brady 	if (txg > spa->spa_lowmem_last_txg) {
7034abe1fd01SDon Brady 		spa->spa_lowmem_last_txg = txg;
7035abe1fd01SDon Brady 		spa->spa_lowmem_page_load = 0;
70361ab7f2deSmaybee 	}
70371ab7f2deSmaybee 	/*
70381ab7f2deSmaybee 	 * If we are in pageout, we know that memory is already tight,
70391ab7f2deSmaybee 	 * the arc is already going to be evicting, so we just want to
70401ab7f2deSmaybee 	 * continue to let page writes occur as quickly as possible.
70411ab7f2deSmaybee 	 */
70421ab7f2deSmaybee 	if (curproc == proc_pageout) {
7043abe1fd01SDon Brady 		if (spa->spa_lowmem_page_load >
7044abe1fd01SDon Brady 		    MAX(ptob(minfree), available_memory) / 4)
7045be6fd75aSMatthew Ahrens 			return (SET_ERROR(ERESTART));
70461ab7f2deSmaybee 		/* Note: reserve is inflated, so we deflate */
7047abe1fd01SDon Brady 		atomic_add_64(&spa->spa_lowmem_page_load, reserve / 8);
70481ab7f2deSmaybee 		return (0);
7049abe1fd01SDon Brady 	} else if (spa->spa_lowmem_page_load > 0 && arc_reclaim_needed()) {
70501ab7f2deSmaybee 		/* memory is low, delay before restarting */
70511ab7f2deSmaybee 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
7052be6fd75aSMatthew Ahrens 		return (SET_ERROR(EAGAIN));
70531ab7f2deSmaybee 	}
7054abe1fd01SDon Brady 	spa->spa_lowmem_page_load = 0;
7055abe1fd01SDon Brady #endif /* _KERNEL */
70561ab7f2deSmaybee 	return (0);
70571ab7f2deSmaybee }
70581ab7f2deSmaybee 
7059fa9e4066Sahrens void
70601ab7f2deSmaybee arc_tempreserve_clear(uint64_t reserve)
7061fa9e4066Sahrens {
70621ab7f2deSmaybee 	atomic_add_64(&arc_tempreserve, -reserve);
7063fa9e4066Sahrens 	ASSERT((int64_t)arc_tempreserve >= 0);
7064fa9e4066Sahrens }
7065fa9e4066Sahrens 
7066fa9e4066Sahrens int
7067abe1fd01SDon Brady arc_tempreserve_space(spa_t *spa, uint64_t reserve, uint64_t txg)
7068fa9e4066Sahrens {
70691ab7f2deSmaybee 	int error;
70702fdbea25SAleksandr Guzovskiy 	uint64_t anon_size;
70711ab7f2deSmaybee 
70721ab7f2deSmaybee 	if (reserve > arc_c/4 && !arc_no_grow)
70731ab7f2deSmaybee 		arc_c = MIN(arc_c_max, reserve * 4);
70741ab7f2deSmaybee 	if (reserve > arc_c)
7075be6fd75aSMatthew Ahrens 		return (SET_ERROR(ENOMEM));
7076112fe045Smaybee 
70772fdbea25SAleksandr Guzovskiy 	/*
70782fdbea25SAleksandr Guzovskiy 	 * Don't count loaned bufs as in flight dirty data to prevent long
70792fdbea25SAleksandr Guzovskiy 	 * network delays from blocking transactions that are ready to be
70802fdbea25SAleksandr Guzovskiy 	 * assigned to a txg.
70812fdbea25SAleksandr Guzovskiy 	 */
70825602294fSDan Kimmel 
70835602294fSDan Kimmel 	/* assert that it has not wrapped around */
70845602294fSDan Kimmel 	ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
70855602294fSDan Kimmel 
7086e914ace2STim Schumacher 	anon_size = MAX((int64_t)(zfs_refcount_count(&arc_anon->arcs_size) -
70872fd872a7SPrakash Surya 	    arc_loaned_bytes), 0);
70882fdbea25SAleksandr Guzovskiy 
70891ab7f2deSmaybee 	/*
70901ab7f2deSmaybee 	 * Writes will, almost always, require additional memory allocations
7091f7170741SWill Andrews 	 * in order to compress/encrypt/etc the data.  We therefore need to
70921ab7f2deSmaybee 	 * make sure that there is sufficient available memory for this.
70931ab7f2deSmaybee 	 */
7094abe1fd01SDon Brady 	error = arc_memory_throttle(spa, reserve, txg);
709569962b56SMatthew Ahrens 	if (error != 0)
70961ab7f2deSmaybee 		return (error);
70971ab7f2deSmaybee 
7098fa9e4066Sahrens 	/*
7099112fe045Smaybee 	 * Throttle writes when the amount of dirty data in the cache
7100112fe045Smaybee 	 * gets too large.  We try to keep the cache less than half full
7101112fe045Smaybee 	 * of dirty blocks so that our sync times don't grow too large.
7102abe1fd01SDon Brady 	 *
7103abe1fd01SDon Brady 	 * In the case of one pool being built on another pool, we want
7104abe1fd01SDon Brady 	 * to make sure we don't end up throttling the lower (backing)
7105abe1fd01SDon Brady 	 * pool when the upper pool is the majority contributor to dirty
7106abe1fd01SDon Brady 	 * data. To insure we make forward progress during throttling, we
7107abe1fd01SDon Brady 	 * also check the current pool's net dirty data and only throttle
7108abe1fd01SDon Brady 	 * if it exceeds zfs_arc_pool_dirty_percent of the anonymous dirty
7109abe1fd01SDon Brady 	 * data in the cache.
7110abe1fd01SDon Brady 	 *
7111112fe045Smaybee 	 * Note: if two requests come in concurrently, we might let them
7112112fe045Smaybee 	 * both succeed, when one of them should fail.  Not a huge deal.
7113fa9e4066Sahrens 	 */
7114abe1fd01SDon Brady 	uint64_t total_dirty = reserve + arc_tempreserve + anon_size;
7115abe1fd01SDon Brady 	uint64_t spa_dirty_anon = spa_dirty_data(spa);
71162fdbea25SAleksandr Guzovskiy 
7117abe1fd01SDon Brady 	if (total_dirty > arc_c * zfs_arc_dirty_limit_percent / 100 &&
7118abe1fd01SDon Brady 	    anon_size > arc_c * zfs_arc_anon_limit_percent / 100 &&
7119abe1fd01SDon Brady 	    spa_dirty_anon > anon_size * zfs_arc_pool_dirty_percent / 100) {
7120dcbf3bd6SGeorge Wilson 		uint64_t meta_esize =
7121e914ace2STim Schumacher 		    zfs_refcount_count(
7122e914ace2STim Schumacher 		    &arc_anon->arcs_esize[ARC_BUFC_METADATA]);
7123dcbf3bd6SGeorge Wilson 		uint64_t data_esize =
7124e914ace2STim Schumacher 		    zfs_refcount_count(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
71250e8c6158Smaybee 		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
71260e8c6158Smaybee 		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
7127dcbf3bd6SGeorge Wilson 		    arc_tempreserve >> 10, meta_esize >> 10,
7128dcbf3bd6SGeorge Wilson 		    data_esize >> 10, reserve >> 10, arc_c >> 10);
7129be6fd75aSMatthew Ahrens 		return (SET_ERROR(ERESTART));
7130fa9e4066Sahrens 	}
71311ab7f2deSmaybee 	atomic_add_64(&arc_tempreserve, reserve);
7132fa9e4066Sahrens 	return (0);
7133fa9e4066Sahrens }
7134fa9e4066Sahrens 
71354076b1bfSPrakash Surya static void
71364076b1bfSPrakash Surya arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
71374076b1bfSPrakash Surya     kstat_named_t *evict_data, kstat_named_t *evict_metadata)
71384076b1bfSPrakash Surya {
7139e914ace2STim Schumacher 	size->value.ui64 = zfs_refcount_count(&state->arcs_size);
7140dcbf3bd6SGeorge Wilson 	evict_data->value.ui64 =
7141e914ace2STim Schumacher 	    zfs_refcount_count(&state->arcs_esize[ARC_BUFC_DATA]);
7142dcbf3bd6SGeorge Wilson 	evict_metadata->value.ui64 =
7143e914ace2STim Schumacher 	    zfs_refcount_count(&state->arcs_esize[ARC_BUFC_METADATA]);
71444076b1bfSPrakash Surya }
71454076b1bfSPrakash Surya 
71464076b1bfSPrakash Surya static int
71474076b1bfSPrakash Surya arc_kstat_update(kstat_t *ksp, int rw)
71484076b1bfSPrakash Surya {
71494076b1bfSPrakash Surya 	arc_stats_t *as = ksp->ks_data;
71504076b1bfSPrakash Surya 
71514076b1bfSPrakash Surya 	if (rw == KSTAT_WRITE) {
71524076b1bfSPrakash Surya 		return (EACCES);
71534076b1bfSPrakash Surya 	} else {
71544076b1bfSPrakash Surya 		arc_kstat_update_state(arc_anon,
71554076b1bfSPrakash Surya 		    &as->arcstat_anon_size,
71564076b1bfSPrakash Surya 		    &as->arcstat_anon_evictable_data,
71574076b1bfSPrakash Surya 		    &as->arcstat_anon_evictable_metadata);
71584076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mru,
71594076b1bfSPrakash Surya 		    &as->arcstat_mru_size,
71604076b1bfSPrakash Surya 		    &as->arcstat_mru_evictable_data,
71614076b1bfSPrakash Surya 		    &as->arcstat_mru_evictable_metadata);
71624076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mru_ghost,
71634076b1bfSPrakash Surya 		    &as->arcstat_mru_ghost_size,
71644076b1bfSPrakash Surya 		    &as->arcstat_mru_ghost_evictable_data,
71654076b1bfSPrakash Surya 		    &as->arcstat_mru_ghost_evictable_metadata);
71664076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mfu,
71674076b1bfSPrakash Surya 		    &as->arcstat_mfu_size,
71684076b1bfSPrakash Surya 		    &as->arcstat_mfu_evictable_data,
71694076b1bfSPrakash Surya 		    &as->arcstat_mfu_evictable_metadata);
71704076b1bfSPrakash Surya 		arc_kstat_update_state(arc_mfu_ghost,
71714076b1bfSPrakash Surya 		    &as->arcstat_mfu_ghost_size,
71724076b1bfSPrakash Surya 		    &as->arcstat_mfu_ghost_evictable_data,
71734076b1bfSPrakash Surya 		    &as->arcstat_mfu_ghost_evictable_metadata);
71743a2d8a1bSPaul Dagnelie 
71753a2d8a1bSPaul Dagnelie 		ARCSTAT(arcstat_size) = aggsum_value(&arc_size);
71763a2d8a1bSPaul Dagnelie 		ARCSTAT(arcstat_meta_used) = aggsum_value(&arc_meta_used);
71773a2d8a1bSPaul Dagnelie 		ARCSTAT(arcstat_data_size) = aggsum_value(&astat_data_size);
71783a2d8a1bSPaul Dagnelie 		ARCSTAT(arcstat_metadata_size) =
71793a2d8a1bSPaul Dagnelie 		    aggsum_value(&astat_metadata_size);
71803a2d8a1bSPaul Dagnelie 		ARCSTAT(arcstat_hdr_size) = aggsum_value(&astat_hdr_size);
71813a2d8a1bSPaul Dagnelie 		ARCSTAT(arcstat_other_size) = aggsum_value(&astat_other_size);
71823a2d8a1bSPaul Dagnelie 		ARCSTAT(arcstat_l2_hdr_size) = aggsum_value(&astat_l2_hdr_size);
71834076b1bfSPrakash Surya 	}
71844076b1bfSPrakash Surya 
71854076b1bfSPrakash Surya 	return (0);
71864076b1bfSPrakash Surya }
71874076b1bfSPrakash Surya 
7188dcbf3bd6SGeorge Wilson /*
7189dcbf3bd6SGeorge Wilson  * This function *must* return indices evenly distributed between all
7190dcbf3bd6SGeorge Wilson  * sublists of the multilist. This is needed due to how the ARC eviction
7191dcbf3bd6SGeorge Wilson  * code is laid out; arc_evict_state() assumes ARC buffers are evenly
7192dcbf3bd6SGeorge Wilson  * distributed between all sublists and uses this assumption when
7193dcbf3bd6SGeorge Wilson  * deciding which sublist to evict from and how much to evict from it.
7194dcbf3bd6SGeorge Wilson  */
7195dcbf3bd6SGeorge Wilson unsigned int
7196dcbf3bd6SGeorge Wilson arc_state_multilist_index_func(multilist_t *ml, void *obj)
7197dcbf3bd6SGeorge Wilson {
7198dcbf3bd6SGeorge Wilson 	arc_buf_hdr_t *hdr = obj;
7199dcbf3bd6SGeorge Wilson 
7200dcbf3bd6SGeorge Wilson 	/*
7201dcbf3bd6SGeorge Wilson 	 * We rely on b_dva to generate evenly distributed index
7202dcbf3bd6SGeorge Wilson 	 * numbers using buf_hash below. So, as an added precaution,
7203dcbf3bd6SGeorge Wilson 	 * let's make sure we never add empty buffers to the arc lists.
7204dcbf3bd6SGeorge Wilson 	 */
7205dcbf3bd6SGeorge Wilson 	ASSERT(!HDR_EMPTY(hdr));
7206dcbf3bd6SGeorge Wilson 
7207dcbf3bd6SGeorge Wilson 	/*
7208dcbf3bd6SGeorge Wilson 	 * The assumption here, is the hash value for a given
7209*eb633035STom Caputi 	 * arc_buf_hdr_t will remain constant throughout its lifetime
7210*eb633035STom Caputi 	 * (i.e. its b_spa, b_dva, and b_birth fields don't change).
7211dcbf3bd6SGeorge Wilson 	 * Thus, we don't need to store the header's sublist index
7212dcbf3bd6SGeorge Wilson 	 * on insertion, as this index can be recalculated on removal.
7213dcbf3bd6SGeorge Wilson 	 *
7214dcbf3bd6SGeorge Wilson 	 * Also, the low order bits of the hash value are thought to be
7215dcbf3bd6SGeorge Wilson 	 * distributed evenly. Otherwise, in the case that the multilist
7216dcbf3bd6SGeorge Wilson 	 * has a power of two number of sublists, each sublists' usage
7217dcbf3bd6SGeorge Wilson 	 * would not be evenly distributed.
7218dcbf3bd6SGeorge Wilson 	 */
7219dcbf3bd6SGeorge Wilson 	return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
7220dcbf3bd6SGeorge Wilson 	    multilist_get_num_sublists(ml));
7221dcbf3bd6SGeorge Wilson }
7222dcbf3bd6SGeorge Wilson 
7223dcbf3bd6SGeorge Wilson static void
7224dcbf3bd6SGeorge Wilson arc_state_init(void)
7225dcbf3bd6SGeorge Wilson {
7226dcbf3bd6SGeorge Wilson 	arc_anon = &ARC_anon;
7227dcbf3bd6SGeorge Wilson 	arc_mru = &ARC_mru;
7228dcbf3bd6SGeorge Wilson 	arc_mru_ghost = &ARC_mru_ghost;
7229dcbf3bd6SGeorge Wilson 	arc_mfu = &ARC_mfu;
7230dcbf3bd6SGeorge Wilson 	arc_mfu_ghost = &ARC_mfu_ghost;
7231dcbf3bd6SGeorge Wilson 	arc_l2c_only = &ARC_l2c_only;
7232dcbf3bd6SGeorge Wilson 
723394c2d0ebSMatthew Ahrens 	arc_mru->arcs_list[ARC_BUFC_METADATA] =
723494c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
7235dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
723610fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
723794c2d0ebSMatthew Ahrens 	arc_mru->arcs_list[ARC_BUFC_DATA] =
723894c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
7239dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
724010fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
724194c2d0ebSMatthew Ahrens 	arc_mru_ghost->arcs_list[ARC_BUFC_METADATA] =
724294c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
7243dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
724410fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
724594c2d0ebSMatthew Ahrens 	arc_mru_ghost->arcs_list[ARC_BUFC_DATA] =
724694c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
7247dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
724810fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
724994c2d0ebSMatthew Ahrens 	arc_mfu->arcs_list[ARC_BUFC_METADATA] =
725094c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
7251dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
725210fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
725394c2d0ebSMatthew Ahrens 	arc_mfu->arcs_list[ARC_BUFC_DATA] =
725494c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
7255dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
725610fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
725794c2d0ebSMatthew Ahrens 	arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA] =
725894c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
7259dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
726010fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
726194c2d0ebSMatthew Ahrens 	arc_mfu_ghost->arcs_list[ARC_BUFC_DATA] =
726294c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
7263dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
726410fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
726594c2d0ebSMatthew Ahrens 	arc_l2c_only->arcs_list[ARC_BUFC_METADATA] =
726694c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
7267dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
726810fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
726994c2d0ebSMatthew Ahrens 	arc_l2c_only->arcs_list[ARC_BUFC_DATA] =
727094c2d0ebSMatthew Ahrens 	    multilist_create(sizeof (arc_buf_hdr_t),
7271dcbf3bd6SGeorge Wilson 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
727210fbdecbSMatthew Ahrens 	    arc_state_multilist_index_func);
7273dcbf3bd6SGeorge Wilson 
7274e914ace2STim Schumacher 	zfs_refcount_create(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
7275e914ace2STim Schumacher 	zfs_refcount_create(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
7276e914ace2STim Schumacher 	zfs_refcount_create(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
7277e914ace2STim Schumacher 	zfs_refcount_create(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
7278e914ace2STim Schumacher 	zfs_refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
7279e914ace2STim Schumacher 	zfs_refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
7280e914ace2STim Schumacher 	zfs_refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
7281e914ace2STim Schumacher 	zfs_refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
7282e914ace2STim Schumacher 	zfs_refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
7283e914ace2STim Schumacher 	zfs_refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
7284e914ace2STim Schumacher 	zfs_refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
7285e914ace2STim Schumacher 	zfs_refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
7286e914ace2STim Schumacher 
7287e914ace2STim Schumacher 	zfs_refcount_create(&arc_anon->arcs_size);
7288e914ace2STim Schumacher 	zfs_refcount_create(&arc_mru->arcs_size);
7289e914ace2STim Schumacher 	zfs_refcount_create(&arc_mru_ghost->arcs_size);
7290e914ace2STim Schumacher 	zfs_refcount_create(&arc_mfu->arcs_size);
7291e914ace2STim Schumacher 	zfs_refcount_create(&arc_mfu_ghost->arcs_size);
7292e914ace2STim Schumacher 	zfs_refcount_create(&arc_l2c_only->arcs_size);
72933a2d8a1bSPaul Dagnelie 
72943a2d8a1bSPaul Dagnelie 	aggsum_init(&arc_meta_used, 0);
72953a2d8a1bSPaul Dagnelie 	aggsum_init(&arc_size, 0);
72963a2d8a1bSPaul Dagnelie 	aggsum_init(&astat_data_size, 0);
72973a2d8a1bSPaul Dagnelie 	aggsum_init(&astat_metadata_size, 0);
72983a2d8a1bSPaul Dagnelie 	aggsum_init(&astat_hdr_size, 0);
72993a2d8a1bSPaul Dagnelie 	aggsum_init(&astat_other_size, 0);
73003a2d8a1bSPaul Dagnelie 	aggsum_init(&astat_l2_hdr_size, 0);
7301dcbf3bd6SGeorge Wilson }
7302dcbf3bd6SGeorge Wilson 
7303dcbf3bd6SGeorge Wilson static void
7304dcbf3bd6SGeorge Wilson arc_state_fini(void)
7305dcbf3bd6SGeorge Wilson {
7306e914ace2STim Schumacher 	zfs_refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
7307e914ace2STim Schumacher 	zfs_refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
7308e914ace2STim Schumacher 	zfs_refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
7309e914ace2STim Schumacher 	zfs_refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
7310e914ace2STim Schumacher 	zfs_refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
7311e914ace2STim Schumacher 	zfs_refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
7312e914ace2STim Schumacher 	zfs_refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
7313e914ace2STim Schumacher 	zfs_refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
7314e914ace2STim Schumacher 	zfs_refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
7315e914ace2STim Schumacher 	zfs_refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
7316e914ace2STim Schumacher 	zfs_refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
7317e914ace2STim Schumacher 	zfs_refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
7318e914ace2STim Schumacher 
7319e914ace2STim Schumacher 	zfs_refcount_destroy(&arc_anon->arcs_size);
7320e914ace2STim Schumacher 	zfs_refcount_destroy(&arc_mru->arcs_size);
7321e914ace2STim Schumacher 	zfs_refcount_destroy(&arc_mru_ghost->arcs_size);
7322e914ace2STim Schumacher 	zfs_refcount_destroy(&arc_mfu->arcs_size);
7323e914ace2STim Schumacher 	zfs_refcount_destroy(&arc_mfu_ghost->arcs_size);
7324e914ace2STim Schumacher 	zfs_refcount_destroy(&arc_l2c_only->arcs_size);
7325dcbf3bd6SGeorge Wilson 
732694c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_METADATA]);
732794c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
732894c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_METADATA]);
732994c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
733094c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_DATA]);
733194c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
733294c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_DATA]);
733394c2d0ebSMatthew Ahrens 	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
7334*eb633035STom Caputi 	multilist_destroy(arc_l2c_only->arcs_list[ARC_BUFC_METADATA]);
7335*eb633035STom Caputi 	multilist_destroy(arc_l2c_only->arcs_list[ARC_BUFC_DATA]);
733629bf2d68SPaul Dagnelie 
733729bf2d68SPaul Dagnelie 	aggsum_fini(&arc_meta_used);
733829bf2d68SPaul Dagnelie 	aggsum_fini(&arc_size);
733929bf2d68SPaul Dagnelie 	aggsum_fini(&astat_data_size);
734029bf2d68SPaul Dagnelie 	aggsum_fini(&astat_metadata_size);
734129bf2d68SPaul Dagnelie 	aggsum_fini(&astat_hdr_size);
734229bf2d68SPaul Dagnelie 	aggsum_fini(&astat_other_size);
734329bf2d68SPaul Dagnelie 	aggsum_fini(&astat_l2_hdr_size);
7344*eb633035STom Caputi 
7345dcbf3bd6SGeorge Wilson }
7346dcbf3bd6SGeorge Wilson 
7347dcbf3bd6SGeorge Wilson uint64_t
7348dcbf3bd6SGeorge Wilson arc_max_bytes(void)
7349244781f1SPrakash Surya {
7350dcbf3bd6SGeorge Wilson 	return (arc_c_max);
7351244781f1SPrakash Surya }
7352244781f1SPrakash Surya 
7353fa9e4066Sahrens void
7354fa9e4066Sahrens arc_init(void)
7355fa9e4066Sahrens {
73562ec99e3eSMatthew Ahrens 	/*
73572ec99e3eSMatthew Ahrens 	 * allmem is "all memory that we could possibly use".
73582ec99e3eSMatthew Ahrens 	 */
73592ec99e3eSMatthew Ahrens #ifdef _KERNEL
73602ec99e3eSMatthew Ahrens 	uint64_t allmem = ptob(physmem - swapfs_minfree);
73612ec99e3eSMatthew Ahrens #else
73622ec99e3eSMatthew Ahrens 	uint64_t allmem = (physmem * PAGESIZE) / 2;
73632ec99e3eSMatthew Ahrens #endif
7364de753e34SBrad Lewis 	mutex_init(&arc_adjust_lock, NULL, MUTEX_DEFAULT, NULL);
7365de753e34SBrad Lewis 	cv_init(&arc_adjust_waiters_cv, NULL, CV_DEFAULT, NULL);
7366244781f1SPrakash Surya 
7367112fe045Smaybee 	/* set min cache to 1/32 of all memory, or 64MB, whichever is more */
73682ec99e3eSMatthew Ahrens 	arc_c_min = MAX(allmem / 32, 64 << 20);
7369112fe045Smaybee 	/* set max to 3/4 of all memory, or all but 1GB, whichever is more */
73702ec99e3eSMatthew Ahrens 	if (allmem >= 1 << 30)
73712ec99e3eSMatthew Ahrens 		arc_c_max = allmem - (1 << 30);
7372fa9e4066Sahrens 	else
737344cb6abcSbmc 		arc_c_max = arc_c_min;
73742ec99e3eSMatthew Ahrens 	arc_c_max = MAX(allmem * 3 / 4, arc_c_max);
7375a2eea2e1Sahrens 
73768fe00bfbSMatthew Ahrens 	/*
73778fe00bfbSMatthew Ahrens 	 * In userland, there's only the memory pressure that we artificially
73788fe00bfbSMatthew Ahrens 	 * create (see arc_available_memory()).  Don't let arc_c get too
73798fe00bfbSMatthew Ahrens 	 * small, because it can cause transactions to be larger than
73808fe00bfbSMatthew Ahrens 	 * arc_c, causing arc_tempreserve_space() to fail.
73818fe00bfbSMatthew Ahrens 	 */
73828fe00bfbSMatthew Ahrens #ifndef _KERNEL
73838fe00bfbSMatthew Ahrens 	arc_c_min = arc_c_max / 2;
73848fe00bfbSMatthew Ahrens #endif
73858fe00bfbSMatthew Ahrens 
7386a2eea2e1Sahrens 	/*
7387a2eea2e1Sahrens 	 * Allow the tunables to override our calculations if they are
7388a2eea2e1Sahrens 	 * reasonable (ie. over 64MB)
7389a2eea2e1Sahrens 	 */
7390e5961710SMatthew Ahrens 	if (zfs_arc_max > 64 << 20 && zfs_arc_max < allmem) {
739144cb6abcSbmc 		arc_c_max = zfs_arc_max;
7392e5961710SMatthew Ahrens 		arc_c_min = MIN(arc_c_min, arc_c_max);
7393e5961710SMatthew Ahrens 	}
73942ec99e3eSMatthew Ahrens 	if (zfs_arc_min > 64 << 20 && zfs_arc_min <= arc_c_max)
739544cb6abcSbmc 		arc_c_min = zfs_arc_min;
7396a2eea2e1Sahrens 
739744cb6abcSbmc 	arc_c = arc_c_max;
739844cb6abcSbmc 	arc_p = (arc_c >> 1);
7399fa9e4066Sahrens 
74000e8c6158Smaybee 	/* limit meta-data to 1/4 of the arc capacity */
74010e8c6158Smaybee 	arc_meta_limit = arc_c_max / 4;
74021116048bSek 
7403af868f46SMatthew Ahrens #ifdef _KERNEL
7404af868f46SMatthew Ahrens 	/*
7405af868f46SMatthew Ahrens 	 * Metadata is stored in the kernel's heap.  Don't let us
7406af868f46SMatthew Ahrens 	 * use more than half the heap for the ARC.
7407af868f46SMatthew Ahrens 	 */
7408af868f46SMatthew Ahrens 	arc_meta_limit = MIN(arc_meta_limit,
7409af868f46SMatthew Ahrens 	    vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 2);
7410af868f46SMatthew Ahrens #endif
7411af868f46SMatthew Ahrens 
74121116048bSek 	/* Allow the tunable to override if it is reasonable */
74131116048bSek 	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
74141116048bSek 		arc_meta_limit = zfs_arc_meta_limit;
74151116048bSek 
74160e8c6158Smaybee 	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
74170e8c6158Smaybee 		arc_c_min = arc_meta_limit / 2;
74180e8c6158Smaybee 
74193a5286a1SMatthew Ahrens 	if (zfs_arc_meta_min > 0) {
74203a5286a1SMatthew Ahrens 		arc_meta_min = zfs_arc_meta_min;
74213a5286a1SMatthew Ahrens 	} else {
74223a5286a1SMatthew Ahrens 		arc_meta_min = arc_c_min / 2;
74233a5286a1SMatthew Ahrens 	}
74243a5286a1SMatthew Ahrens 
74255a98e54bSBrendan Gregg - Sun Microsystems 	if (zfs_arc_grow_retry > 0)
74265a98e54bSBrendan Gregg - Sun Microsystems 		arc_grow_retry = zfs_arc_grow_retry;
74275a98e54bSBrendan Gregg - Sun Microsystems 
74285a98e54bSBrendan Gregg - Sun Microsystems 	if (zfs_arc_shrink_shift > 0)
74295a98e54bSBrendan Gregg - Sun Microsystems 		arc_shrink_shift = zfs_arc_shrink_shift;
74305a98e54bSBrendan Gregg - Sun Microsystems 
74312ec99e3eSMatthew Ahrens 	/*
74322ec99e3eSMatthew Ahrens 	 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
74332ec99e3eSMatthew Ahrens 	 */
74342ec99e3eSMatthew Ahrens 	if (arc_no_grow_shift >= arc_shrink_shift)
74352ec99e3eSMatthew Ahrens 		arc_no_grow_shift = arc_shrink_shift - 1;
74362ec99e3eSMatthew Ahrens 
74375a98e54bSBrendan Gregg - Sun Microsystems 	if (zfs_arc_p_min_shift > 0)
74385a98e54bSBrendan Gregg - Sun Microsystems 		arc_p_min_shift = zfs_arc_p_min_shift;
74395a98e54bSBrendan Gregg - Sun Microsystems 
7440fa9e4066Sahrens 	/* if kmem_flags are set, lets try to use less memory */
7441fa9e4066Sahrens 	if (kmem_debugging())
744244cb6abcSbmc 		arc_c = arc_c / 2;
744344cb6abcSbmc 	if (arc_c < arc_c_min)
744444cb6abcSbmc 		arc_c = arc_c_min;
744544cb6abcSbmc 
7446dcbf3bd6SGeorge Wilson 	arc_state_init();
7447fa9e4066Sahrens 
7448de753e34SBrad Lewis 	/*
7449de753e34SBrad Lewis 	 * The arc must be "uninitialized", so that hdr_recl() (which is
7450de753e34SBrad Lewis 	 * registered by buf_init()) will not access arc_reap_zthr before
7451de753e34SBrad Lewis 	 * it is created.
7452de753e34SBrad Lewis 	 */
7453de753e34SBrad Lewis 	ASSERT(!arc_initialized);
7454de753e34SBrad Lewis 	buf_init();
7455fa9e4066Sahrens 
745644cb6abcSbmc 	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
745744cb6abcSbmc 	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
745844cb6abcSbmc 
745944cb6abcSbmc 	if (arc_ksp != NULL) {
746044cb6abcSbmc 		arc_ksp->ks_data = &arc_stats;
74614076b1bfSPrakash Surya 		arc_ksp->ks_update = arc_kstat_update;
746244cb6abcSbmc 		kstat_install(arc_ksp);
746344cb6abcSbmc 	}
746444cb6abcSbmc 
7465de753e34SBrad Lewis 	arc_adjust_zthr = zthr_create(arc_adjust_cb_check,
7466de753e34SBrad Lewis 	    arc_adjust_cb, NULL);
7467de753e34SBrad Lewis 	arc_reap_zthr = zthr_create_timer(arc_reap_cb_check,
7468de753e34SBrad Lewis 	    arc_reap_cb, NULL, SEC2NSEC(1));
746949e3519aSmaybee 
7470de753e34SBrad Lewis 	arc_initialized = B_TRUE;
74713a737e0dSbrendan 	arc_warm = B_FALSE;
74721ab7f2deSmaybee 
747369962b56SMatthew Ahrens 	/*
747469962b56SMatthew Ahrens 	 * Calculate maximum amount of dirty data per pool.
747569962b56SMatthew Ahrens 	 *
747669962b56SMatthew Ahrens 	 * If it has been set by /etc/system, take that.
747769962b56SMatthew Ahrens 	 * Otherwise, use a percentage of physical memory defined by
747869962b56SMatthew Ahrens 	 * zfs_dirty_data_max_percent (default 10%) with a cap at
747969962b56SMatthew Ahrens 	 * zfs_dirty_data_max_max (default 4GB).
748069962b56SMatthew Ahrens 	 */
748169962b56SMatthew Ahrens 	if (zfs_dirty_data_max == 0) {
748269962b56SMatthew Ahrens 		zfs_dirty_data_max = physmem * PAGESIZE *
748369962b56SMatthew Ahrens 		    zfs_dirty_data_max_percent / 100;
748469962b56SMatthew Ahrens 		zfs_dirty_data_max = MIN(zfs_dirty_data_max,
748569962b56SMatthew Ahrens 		    zfs_dirty_data_max_max);
748669962b56SMatthew Ahrens 	}
7487fa9e4066Sahrens }
7488fa9e4066Sahrens 
7489fa9e4066Sahrens void
7490fa9e4066Sahrens arc_fini(void)
7491fa9e4066Sahrens {
7492dcbf3bd6SGeorge Wilson 	/* Use B_TRUE to ensure *all* buffers are evicted */
7493dcbf3bd6SGeorge Wilson 	arc_flush(NULL, B_TRUE);
7494fa9e4066Sahrens 
7495de753e34SBrad Lewis 	arc_initialized = B_FALSE;
7496fa9e4066Sahrens 
749744cb6abcSbmc 	if (arc_ksp != NULL) {
749844cb6abcSbmc 		kstat_delete(arc_ksp);
749944cb6abcSbmc 		arc_ksp = NULL;
750044cb6abcSbmc 	}
750144cb6abcSbmc 
7502de753e34SBrad Lewis 	(void) zthr_cancel(arc_adjust_zthr);
7503de753e34SBrad Lewis 	zthr_destroy(arc_adjust_zthr);
7504de753e34SBrad Lewis 
7505de753e34SBrad Lewis 	(void) zthr_cancel(arc_reap_zthr);
7506de753e34SBrad Lewis 	zthr_destroy(arc_reap_zthr);
7507de753e34SBrad Lewis 
7508de753e34SBrad Lewis 	mutex_destroy(&arc_adjust_lock);
7509de753e34SBrad Lewis 	cv_destroy(&arc_adjust_waiters_cv);
7510244781f1SPrakash Surya 
751129bf2d68SPaul Dagnelie 	/*
751229bf2d68SPaul Dagnelie 	 * buf_fini() must proceed arc_state_fini() because buf_fin() may
751329bf2d68SPaul Dagnelie 	 * trigger the release of kmem magazines, which can callback to
751429bf2d68SPaul Dagnelie 	 * arc_space_return() which accesses aggsums freed in act_state_fini().
751529bf2d68SPaul Dagnelie 	 */
7516fa9e4066Sahrens 	buf_fini();
751729bf2d68SPaul Dagnelie 	arc_state_fini();
75182fdbea25SAleksandr Guzovskiy 
751989c86e32SChris Williamson 	ASSERT0(arc_loaned_bytes);
7520fa9e4066Sahrens }
7521fa94a07fSbrendan 
7522fa94a07fSbrendan /*
7523fa94a07fSbrendan  * Level 2 ARC
7524fa94a07fSbrendan  *
7525fa94a07fSbrendan  * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
7526fa94a07fSbrendan  * It uses dedicated storage devices to hold cached data, which are populated
7527fa94a07fSbrendan  * using large infrequent writes.  The main role of this cache is to boost
7528fa94a07fSbrendan  * the performance of random read workloads.  The intended L2ARC devices
7529fa94a07fSbrendan  * include short-stroked disks, solid state disks, and other media with
7530fa94a07fSbrendan  * substantially faster read latency than disk.
7531fa94a07fSbrendan  *
7532fa94a07fSbrendan  *                 +-----------------------+
7533fa94a07fSbrendan  *                 |         ARC           |
7534fa94a07fSbrendan  *                 +-----------------------+
7535fa94a07fSbrendan  *                    |         ^     ^
7536fa94a07fSbrendan  *                    |         |     |
7537fa94a07fSbrendan  *      l2arc_feed_thread()    arc_read()
7538fa94a07fSbrendan  *                    |         |     |
7539fa94a07fSbrendan  *                    |  l2arc read   |
7540fa94a07fSbrendan  *                    V         |     |
7541fa94a07fSbrendan  *               +---------------+    |
7542fa94a07fSbrendan  *               |     L2ARC     |    |
7543fa94a07fSbrendan  *               +---------------+    |
7544fa94a07fSbrendan  *                   |    ^           |
7545fa94a07fSbrendan  *          l2arc_write() |           |
7546fa94a07fSbrendan  *                   |    |           |
7547fa94a07fSbrendan  *                   V    |           |
7548fa94a07fSbrendan  *                 +-------+      +-------+
7549fa94a07fSbrendan  *                 | vdev  |      | vdev  |
7550fa94a07fSbrendan  *                 | cache |      | cache |
7551fa94a07fSbrendan  *                 +-------+      +-------+
7552fa94a07fSbrendan  *                 +=========+     .-----.
7553fa94a07fSbrendan  *                 :  L2ARC  :    |-_____-|
7554fa94a07fSbrendan  *                 : devices :    | Disks |
7555fa94a07fSbrendan  *                 +=========+    `-_____-'
7556fa94a07fSbrendan  *
7557fa94a07fSbrendan  * Read requests are satisfied from the following sources, in order:
7558fa94a07fSbrendan  *
7559fa94a07fSbrendan  *	1) ARC
7560fa94a07fSbrendan  *	2) vdev cache of L2ARC devices
7561fa94a07fSbrendan  *	3) L2ARC devices
7562fa94a07fSbrendan  *	4) vdev cache of disks
7563fa94a07fSbrendan  *	5) disks
7564fa94a07fSbrendan  *
7565fa94a07fSbrendan  * Some L2ARC device types exhibit extremely slow write performance.
7566fa94a07fSbrendan  * To accommodate for this there are some significant differences between
7567fa94a07fSbrendan  * the L2ARC and traditional cache design:
7568fa94a07fSbrendan  *
7569fa94a07fSbrendan  * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
7570fa94a07fSbrendan  * the ARC behave as usual, freeing buffers and placing headers on ghost
7571fa94a07fSbrendan  * lists.  The ARC does not send buffers to the L2ARC during eviction as
7572fa94a07fSbrendan  * this would add inflated write latencies for all ARC memory pressure.
7573fa94a07fSbrendan  *
7574fa94a07fSbrendan  * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
7575fa94a07fSbrendan  * It does this by periodically scanning buffers from the eviction-end of
7576fa94a07fSbrendan  * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
7577aad02571SSaso Kiselkov  * not already there. It scans until a headroom of buffers is satisfied,
7578aad02571SSaso Kiselkov  * which itself is a buffer for ARC eviction. If a compressible buffer is
7579aad02571SSaso Kiselkov  * found during scanning and selected for writing to an L2ARC device, we
7580aad02571SSaso Kiselkov  * temporarily boost scanning headroom during the next scan cycle to make
7581aad02571SSaso Kiselkov  * sure we adapt to compression effects (which might significantly reduce
7582aad02571SSaso Kiselkov  * the data volume we write to L2ARC). The thread that does this is
7583fa94a07fSbrendan  * l2arc_feed_thread(), illustrated below; example sizes are included to
7584fa94a07fSbrendan  * provide a better sense of ratio than this diagram:
7585fa94a07fSbrendan  *
7586fa94a07fSbrendan  *	       head -->                        tail
7587fa94a07fSbrendan  *	        +---------------------+----------+
7588fa94a07fSbrendan  *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
7589fa94a07fSbrendan  *	        +---------------------+----------+   |   o L2ARC eligible
7590fa94a07fSbrendan  *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
7591fa94a07fSbrendan  *	        +---------------------+----------+   |
7592fa94a07fSbrendan  *	             15.9 Gbytes      ^ 32 Mbytes    |
7593fa94a07fSbrendan  *	                           headroom          |
7594fa94a07fSbrendan  *	                                      l2arc_feed_thread()
7595fa94a07fSbrendan  *	                                             |
7596fa94a07fSbrendan  *	                 l2arc write hand <--[oooo]--'
7597fa94a07fSbrendan  *	                         |           8 Mbyte
7598fa94a07fSbrendan  *	                         |          write max
7599fa94a07fSbrendan  *	                         V
7600fa94a07fSbrendan  *		  +==============================+
7601fa94a07fSbrendan  *	L2ARC dev |####|#|###|###|    |####| ... |
7602fa94a07fSbrendan  *	          +==============================+
7603fa94a07fSbrendan  *	                     32 Gbytes
7604fa94a07fSbrendan  *
7605fa94a07fSbrendan  * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
7606fa94a07fSbrendan  * evicted, then the L2ARC has cached a buffer much sooner than it probably
7607fa94a07fSbrendan  * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
7608fa94a07fSbrendan  * safe to say that this is an uncommon case, since buffers at the end of
7609fa94a07fSbrendan  * the ARC lists have moved there due to inactivity.
7610fa94a07fSbrendan  *
7611fa94a07fSbrendan  * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
7612fa94a07fSbrendan  * then the L2ARC simply misses copying some buffers.  This serves as a
7613fa94a07fSbrendan  * pressure valve to prevent heavy read workloads from both stalling the ARC
7614fa94a07fSbrendan  * with waits and clogging the L2ARC with writes.  This also helps prevent
7615fa94a07fSbrendan  * the potential for the L2ARC to churn if it attempts to cache content too
7616fa94a07fSbrendan  * quickly, such as during backups of the entire pool.
7617fa94a07fSbrendan  *
76183a737e0dSbrendan  * 5. After system boot and before the ARC has filled main memory, there are
76193a737e0dSbrendan  * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
76203a737e0dSbrendan  * lists can remain mostly static.  Instead of searching from tail of these
76213a737e0dSbrendan  * lists as pictured, the l2arc_feed_thread() will search from the list heads
76223a737e0dSbrendan  * for eligible buffers, greatly increasing its chance of finding them.
76233a737e0dSbrendan  *
76243a737e0dSbrendan  * The L2ARC device write speed is also boosted during this time so that
76253a737e0dSbrendan  * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
76263a737e0dSbrendan  * there are no L2ARC reads, and no fear of degrading read performance
76273a737e0dSbrendan  * through increased writes.
76283a737e0dSbrendan  *
76293a737e0dSbrendan  * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
7630fa94a07fSbrendan  * the vdev queue can aggregate them into larger and fewer writes.  Each
7631fa94a07fSbrendan  * device is written to in a rotor fashion, sweeping writes through
7632fa94a07fSbrendan  * available space then repeating.
7633fa94a07fSbrendan  *
76343a737e0dSbrendan  * 7. The L2ARC does not store dirty content.  It never needs to flush
7635fa94a07fSbrendan  * write buffers back to disk based storage.
7636fa94a07fSbrendan  *
76373a737e0dSbrendan  * 8. If an ARC buffer is written (and dirtied) which also exists in the
7638fa94a07fSbrendan  * L2ARC, the now stale L2ARC buffer is immediately dropped.
7639fa94a07fSbrendan  *
7640fa94a07fSbrendan  * The performance of the L2ARC can be tweaked by a number of tunables, which
7641fa94a07fSbrendan  * may be necessary for different workloads:
7642fa94a07fSbrendan  *
7643fa94a07fSbrendan  *	l2arc_write_max		max write bytes per interval
76443a737e0dSbrendan  *	l2arc_write_boost	extra write bytes during device warmup
7645fa94a07fSbrendan  *	l2arc_noprefetch	skip caching prefetched buffers
7646fa94a07fSbrendan  *	l2arc_headroom		number of max device writes to precache
7647aad02571SSaso Kiselkov  *	l2arc_headroom_boost	when we find compressed buffers during ARC
7648aad02571SSaso Kiselkov  *				scanning, we multiply headroom by this
7649aad02571SSaso Kiselkov  *				percentage factor for the next scan cycle,
7650aad02571SSaso Kiselkov  *				since more compressed buffers are likely to
7651aad02571SSaso Kiselkov  *				be present
7652fa94a07fSbrendan  *	l2arc_feed_secs		seconds between L2ARC writing
7653fa94a07fSbrendan  *
7654fa94a07fSbrendan  * Tunables may be removed or added as future performance improvements are
7655fa94a07fSbrendan  * integrated, and also may become zpool properties.
76565a98e54bSBrendan Gregg - Sun Microsystems  *
76575a98e54bSBrendan Gregg - Sun Microsystems  * There are three key functions that control how the L2ARC warms up:
76585a98e54bSBrendan Gregg - Sun Microsystems  *
76595a98e54bSBrendan Gregg - Sun Microsystems  *	l2arc_write_eligible()	check if a buffer is eligible to cache
76605a98e54bSBrendan Gregg - Sun Microsystems  *	l2arc_write_size()	calculate how much to write
76615a98e54bSBrendan Gregg - Sun Microsystems  *	l2arc_write_interval()	calculate sleep delay between writes
76625a98e54bSBrendan Gregg - Sun Microsystems  *
76635a98e54bSBrendan Gregg - Sun Microsystems  * These three functions determine what to write, how much, and how quickly
76645a98e54bSBrendan Gregg - Sun Microsystems  * to send writes.
7665fa94a07fSbrendan  */
7666fa94a07fSbrendan 
76675a98e54bSBrendan Gregg - Sun Microsystems static boolean_t
76687adb730bSGeorge Wilson l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
76695a98e54bSBrendan Gregg - Sun Microsystems {
76705a98e54bSBrendan Gregg - Sun Microsystems 	/*
76715a98e54bSBrendan Gregg - Sun Microsystems 	 * A buffer is *not* eligible for the L2ARC if it:
76725a98e54bSBrendan Gregg - Sun Microsystems 	 * 1. belongs to a different spa.
76735ea40c06SBrendan Gregg - Sun Microsystems 	 * 2. is already cached on the L2ARC.
76745ea40c06SBrendan Gregg - Sun Microsystems 	 * 3. has an I/O in progress (it may be an incomplete read).
76755ea40c06SBrendan Gregg - Sun Microsystems 	 * 4. is flagged not eligible (zfs property).
76765a98e54bSBrendan Gregg - Sun Microsystems 	 */
767789c86e32SChris Williamson 	if (hdr->b_spa != spa_guid || HDR_HAS_L2HDR(hdr) ||
76787adb730bSGeorge Wilson 	    HDR_IO_IN_PROGRESS(hdr) || !HDR_L2CACHE(hdr))
76795a98e54bSBrendan Gregg - Sun Microsystems 		return (B_FALSE);
76805a98e54bSBrendan Gregg - Sun Microsystems 
76815a98e54bSBrendan Gregg - Sun Microsystems 	return (B_TRUE);
76825a98e54bSBrendan Gregg - Sun Microsystems }
76835a98e54bSBrendan Gregg - Sun Microsystems 
76845a98e54bSBrendan Gregg - Sun Microsystems static uint64_t
7685aad02571SSaso Kiselkov l2arc_write_size(void)
76865a98e54bSBrendan Gregg - Sun Microsystems {
76875a98e54bSBrendan Gregg - Sun Microsystems 	uint64_t size;
76885a98e54bSBrendan Gregg - Sun Microsystems 
7689aad02571SSaso Kiselkov 	/*
7690aad02571SSaso Kiselkov 	 * Make sure our globals have meaningful values in case the user
7691aad02571SSaso Kiselkov 	 * altered them.
7692aad02571SSaso Kiselkov 	 */
7693aad02571SSaso Kiselkov 	size = l2arc_write_max;
7694aad02571SSaso Kiselkov 	if (size == 0) {
7695aad02571SSaso Kiselkov 		cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
7696aad02571SSaso Kiselkov 		    "be greater than zero, resetting it to the default (%d)",
7697aad02571SSaso Kiselkov 		    L2ARC_WRITE_SIZE);
7698aad02571SSaso Kiselkov 		size = l2arc_write_max = L2ARC_WRITE_SIZE;
7699aad02571SSaso Kiselkov 	}
77005a98e54bSBrendan Gregg - Sun Microsystems 
77015a98e54bSBrendan Gregg - Sun Microsystems 	if (arc_warm == B_FALSE)
7702aad02571SSaso Kiselkov 		size += l2arc_write_boost;
77035a98e54bSBrendan Gregg - Sun Microsystems 
77045a98e54bSBrendan Gregg - Sun Microsystems 	return (size);
77055a98e54bSBrendan Gregg - Sun Microsystems 
77065a98e54bSBrendan Gregg - Sun Microsystems }
77075a98e54bSBrendan Gregg - Sun Microsystems 
77085a98e54bSBrendan Gregg - Sun Microsystems static clock_t
77095a98e54bSBrendan Gregg - Sun Microsystems l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
77105a98e54bSBrendan Gregg - Sun Microsystems {
7711d3d50737SRafael Vanoni 	clock_t interval, next, now;
77125a98e54bSBrendan Gregg - Sun Microsystems 
77135a98e54bSBrendan Gregg - Sun Microsystems 	/*
77145a98e54bSBrendan Gregg - Sun Microsystems 	 * If the ARC lists are busy, increase our write rate; if the
77155a98e54bSBrendan Gregg - Sun Microsystems 	 * lists are stale, idle back.  This is achieved by checking
77165a98e54bSBrendan Gregg - Sun Microsystems 	 * how much we previously wrote - if it was more than half of
77175a98e54bSBrendan Gregg - Sun Microsystems 	 * what we wanted, schedule the next write much sooner.
77185a98e54bSBrendan Gregg - Sun Microsystems 	 */
77195a98e54bSBrendan Gregg - Sun Microsystems 	if (l2arc_feed_again && wrote > (wanted / 2))
77205a98e54bSBrendan Gregg - Sun Microsystems 		interval = (hz * l2arc_feed_min_ms) / 1000;
77215a98e54bSBrendan Gregg - Sun Microsystems 	else
77225a98e54bSBrendan Gregg - Sun Microsystems 		interval = hz * l2arc_feed_secs;
77235a98e54bSBrendan Gregg - Sun Microsystems 
7724d3d50737SRafael Vanoni 	now = ddi_get_lbolt();
7725d3d50737SRafael Vanoni 	next = MAX(now, MIN(now + interval, began + interval));
77265a98e54bSBrendan Gregg - Sun Microsystems 
77275a98e54bSBrendan Gregg - Sun Microsystems 	return (next);
77285a98e54bSBrendan Gregg - Sun Microsystems }
77295a98e54bSBrendan Gregg - Sun Microsystems 
7730fa94a07fSbrendan /*
7731fa94a07fSbrendan  * Cycle through L2ARC devices.  This is how L2ARC load balances.
77323a737e0dSbrendan  * If a device is returned, this also returns holding the spa config lock.
7733fa94a07fSbrendan  */
7734fa94a07fSbrendan static l2arc_dev_t *
7735fa94a07fSbrendan l2arc_dev_get_next(void)
7736fa94a07fSbrendan {
77373a737e0dSbrendan 	l2arc_dev_t *first, *next = NULL;
77383a737e0dSbrendan 
77393a737e0dSbrendan 	/*
77403a737e0dSbrendan 	 * Lock out the removal of spas (spa_namespace_lock), then removal
77413a737e0dSbrendan 	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
77423a737e0dSbrendan 	 * both locks will be dropped and a spa config lock held instead.
77433a737e0dSbrendan 	 */
77443a737e0dSbrendan 	mutex_enter(&spa_namespace_lock);
77453a737e0dSbrendan 	mutex_enter(&l2arc_dev_mtx);
7746fa94a07fSbrendan 
7747c5904d13Seschrock 	/* if there are no vdevs, there is nothing to do */
7748c5904d13Seschrock 	if (l2arc_ndev == 0)
77493a737e0dSbrendan 		goto out;
7750c5904d13Seschrock 
7751c5904d13Seschrock 	first = NULL;
7752c5904d13Seschrock 	next = l2arc_dev_last;
7753c5904d13Seschrock 	do {
7754c5904d13Seschrock 		/* loop around the list looking for a non-faulted vdev */
7755c5904d13Seschrock 		if (next == NULL) {
7756fa94a07fSbrendan 			next = list_head(l2arc_dev_list);
7757c5904d13Seschrock 		} else {
7758c5904d13Seschrock 			next = list_next(l2arc_dev_list, next);
7759c5904d13Seschrock 			if (next == NULL)
7760c5904d13Seschrock 				next = list_head(l2arc_dev_list);
7761c5904d13Seschrock 		}
7762c5904d13Seschrock 
7763c5904d13Seschrock 		/* if we have come back to the start, bail out */
7764c5904d13Seschrock 		if (first == NULL)
7765c5904d13Seschrock 			first = next;
7766c5904d13Seschrock 		else if (next == first)
7767c5904d13Seschrock 			break;
7768c5904d13Seschrock 
7769c5904d13Seschrock 	} while (vdev_is_dead(next->l2ad_vdev));
7770c5904d13Seschrock 
7771c5904d13Seschrock 	/* if we were unable to find any usable vdevs, return NULL */
7772c5904d13Seschrock 	if (vdev_is_dead(next->l2ad_vdev))
77733a737e0dSbrendan 		next = NULL;
7774fa94a07fSbrendan 
7775fa94a07fSbrendan 	l2arc_dev_last = next;
7776fa94a07fSbrendan 
77773a737e0dSbrendan out:
77783a737e0dSbrendan 	mutex_exit(&l2arc_dev_mtx);
77793a737e0dSbrendan 
77803a737e0dSbrendan 	/*
77813a737e0dSbrendan 	 * Grab the config lock to prevent the 'next' device from being
77823a737e0dSbrendan 	 * removed while we are writing to it.
77833a737e0dSbrendan 	 */
77843a737e0dSbrendan 	if (next != NULL)
7785e14bb325SJeff Bonwick 		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
77863a737e0dSbrendan 	mutex_exit(&spa_namespace_lock);
77873a737e0dSbrendan 
7788fa94a07fSbrendan 	return (next);
7789fa94a07fSbrendan }
7790fa94a07fSbrendan 
77913a737e0dSbrendan /*
77923a737e0dSbrendan  * Free buffers that were tagged for destruction.
77933a737e0dSbrendan  */
77943a737e0dSbrendan static void
77953a737e0dSbrendan l2arc_do_free_on_write()
77963a737e0dSbrendan {
77973a737e0dSbrendan 	list_t *buflist;
77983a737e0dSbrendan 	l2arc_data_free_t *df, *df_prev;
77993a737e0dSbrendan 
78003a737e0dSbrendan 	mutex_enter(&l2arc_free_on_write_mtx);
78013a737e0dSbrendan 	buflist = l2arc_free_on_write;
78023a737e0dSbrendan 
78033a737e0dSbrendan 	for (df = list_tail(buflist); df; df = df_prev) {
78043a737e0dSbrendan 		df_prev = list_prev(buflist, df);
7805770499e1SDan Kimmel 		ASSERT3P(df->l2df_abd, !=, NULL);
7806770499e1SDan Kimmel 		abd_free(df->l2df_abd);
78073a737e0dSbrendan 		list_remove(buflist, df);
78083a737e0dSbrendan 		kmem_free(df, sizeof (l2arc_data_free_t));
78093a737e0dSbrendan 	}
78103a737e0dSbrendan 
78113a737e0dSbrendan 	mutex_exit(&l2arc_free_on_write_mtx);
78123a737e0dSbrendan }
78133a737e0dSbrendan 
7814fa94a07fSbrendan /*
7815fa94a07fSbrendan  * A write to a cache device has completed.  Update all headers to allow
7816fa94a07fSbrendan  * reads from these buffers to begin.
7817fa94a07fSbrendan  */
7818fa94a07fSbrendan static void
7819fa94a07fSbrendan l2arc_write_done(zio_t *zio)
7820fa94a07fSbrendan {
7821fa94a07fSbrendan 	l2arc_write_callback_t *cb;
7822fa94a07fSbrendan 	l2arc_dev_t *dev;
7823fa94a07fSbrendan 	list_t *buflist;
78247adb730bSGeorge Wilson 	arc_buf_hdr_t *head, *hdr, *hdr_prev;
7825fa94a07fSbrendan 	kmutex_t *hash_lock;
78263038a2b4SSaso Kiselkov 	int64_t bytes_dropped = 0;
7827fa94a07fSbrendan 
7828fa94a07fSbrendan 	cb = zio->io_private;
7829dcbf3bd6SGeorge Wilson 	ASSERT3P(cb, !=, NULL);
7830fa94a07fSbrendan 	dev = cb->l2wcb_dev;
7831dcbf3bd6SGeorge Wilson 	ASSERT3P(dev, !=, NULL);
7832fa94a07fSbrendan 	head = cb->l2wcb_head;
7833dcbf3bd6SGeorge Wilson 	ASSERT3P(head, !=, NULL);
783489c86e32SChris Williamson 	buflist = &dev->l2ad_buflist;
7835dcbf3bd6SGeorge Wilson 	ASSERT3P(buflist, !=, NULL);
7836fa94a07fSbrendan 	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
7837fa94a07fSbrendan 	    l2arc_write_callback_t *, cb);
7838fa94a07fSbrendan 
7839fa94a07fSbrendan 	if (zio->io_error != 0)
7840fa94a07fSbrendan 		ARCSTAT_BUMP(arcstat_l2_writes_error);
7841fa94a07fSbrendan 
7842fa94a07fSbrendan 	/*
7843fa94a07fSbrendan 	 * All writes completed, or an error was hit.
7844fa94a07fSbrendan 	 */
7845244781f1SPrakash Surya top:
7846244781f1SPrakash Surya 	mutex_enter(&dev->l2ad_mtx);
78477adb730bSGeorge Wilson 	for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
78487adb730bSGeorge Wilson 		hdr_prev = list_prev(buflist, hdr);
7849fa94a07fSbrendan 
78507adb730bSGeorge Wilson 		hash_lock = HDR_LOCK(hdr);
7851244781f1SPrakash Surya 
7852244781f1SPrakash Surya 		/*
7853244781f1SPrakash Surya 		 * We cannot use mutex_enter or else we can deadlock
7854244781f1SPrakash Surya 		 * with l2arc_write_buffers (due to swapping the order
7855244781f1SPrakash Surya 		 * the hash lock and l2ad_mtx are taken).
7856244781f1SPrakash Surya 		 */
7857fa94a07fSbrendan 		if (!mutex_tryenter(hash_lock)) {
7858fa94a07fSbrendan 			/*
7859244781f1SPrakash Surya 			 * Missed the hash lock. We must retry so we
7860244781f1SPrakash Surya 			 * don't leave the ARC_FLAG_L2_WRITING bit set.
7861fa94a07fSbrendan 			 */
7862244781f1SPrakash Surya 			ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
7863244781f1SPrakash Surya 
7864244781f1SPrakash Surya 			/*
7865244781f1SPrakash Surya 			 * We don't want to rescan the headers we've
7866244781f1SPrakash Surya 			 * already marked as having been written out, so
7867244781f1SPrakash Surya 			 * we reinsert the head node so we can pick up
7868244781f1SPrakash Surya 			 * where we left off.
7869244781f1SPrakash Surya 			 */
7870244781f1SPrakash Surya 			list_remove(buflist, head);
7871244781f1SPrakash Surya 			list_insert_after(buflist, hdr, head);
7872244781f1SPrakash Surya 
7873244781f1SPrakash Surya 			mutex_exit(&dev->l2ad_mtx);
7874244781f1SPrakash Surya 
7875244781f1SPrakash Surya 			/*
7876244781f1SPrakash Surya 			 * We wait for the hash lock to become available
7877244781f1SPrakash Surya 			 * to try and prevent busy waiting, and increase
7878244781f1SPrakash Surya 			 * the chance we'll be able to acquire the lock
7879244781f1SPrakash Surya 			 * the next time around.
7880244781f1SPrakash Surya 			 */
7881244781f1SPrakash Surya 			mutex_enter(hash_lock);
7882244781f1SPrakash Surya 			mutex_exit(hash_lock);
7883244781f1SPrakash Surya 			goto top;
7884fa94a07fSbrendan 		}
7885fa94a07fSbrendan 
788689c86e32SChris Williamson 		/*
7887244781f1SPrakash Surya 		 * We could not have been moved into the arc_l2c_only
7888244781f1SPrakash Surya 		 * state while in-flight due to our ARC_FLAG_L2_WRITING
7889244781f1SPrakash Surya 		 * bit being set. Let's just ensure that's being enforced.
7890244781f1SPrakash Surya 		 */
7891244781f1SPrakash Surya 		ASSERT(HDR_HAS_L1HDR(hdr));
7892244781f1SPrakash Surya 
7893fa94a07fSbrendan 		if (zio->io_error != 0) {
7894fa94a07fSbrendan 			/*
78953a737e0dSbrendan 			 * Error - drop L2ARC entry.
7896fa94a07fSbrendan 			 */
78977adb730bSGeorge Wilson 			list_remove(buflist, hdr);
7898dcbf3bd6SGeorge Wilson 			arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
789989c86e32SChris Williamson 
79009740f25fSSerapheim Dimitropoulos 			uint64_t psize = HDR_GET_PSIZE(hdr);
79019740f25fSSerapheim Dimitropoulos 			ARCSTAT_INCR(arcstat_l2_psize, -psize);
790216a7e5acSAndriy Gapon 			ARCSTAT_INCR(arcstat_l2_lsize, -HDR_GET_LSIZE(hdr));
7903a52fc310SPrakash Surya 
79049740f25fSSerapheim Dimitropoulos 			bytes_dropped +=
79059740f25fSSerapheim Dimitropoulos 			    vdev_psize_to_asize(dev->l2ad_vdev, psize);
7906e914ace2STim Schumacher 			(void) zfs_refcount_remove_many(&dev->l2ad_alloc,
7907dcbf3bd6SGeorge Wilson 			    arc_hdr_size(hdr), hdr);
7908fa94a07fSbrendan 		}
7909fa94a07fSbrendan 
7910fa94a07fSbrendan 		/*
7911244781f1SPrakash Surya 		 * Allow ARC to begin reads and ghost list evictions to
7912244781f1SPrakash Surya 		 * this L2ARC entry.
7913fa94a07fSbrendan 		 */
7914dcbf3bd6SGeorge Wilson 		arc_hdr_clear_flags(hdr, ARC_FLAG_L2_WRITING);
7915fa94a07fSbrendan 
7916fa94a07fSbrendan 		mutex_exit(hash_lock);
7917fa94a07fSbrendan 	}
7918fa94a07fSbrendan 
7919fa94a07fSbrendan 	atomic_inc_64(&l2arc_writes_done);
7920fa94a07fSbrendan 	list_remove(buflist, head);
792189c86e32SChris Williamson 	ASSERT(!HDR_HAS_L1HDR(head));
792289c86e32SChris Williamson 	kmem_cache_free(hdr_l2only_cache, head);
792389c86e32SChris Williamson 	mutex_exit(&dev->l2ad_mtx);
7924fa94a07fSbrendan 
79253038a2b4SSaso Kiselkov 	vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
79263038a2b4SSaso Kiselkov 
79273a737e0dSbrendan 	l2arc_do_free_on_write();
7928fa94a07fSbrendan 
7929fa94a07fSbrendan 	kmem_free(cb, sizeof (l2arc_write_callback_t));
7930fa94a07fSbrendan }
7931fa94a07fSbrendan 
7932*eb633035STom Caputi static int
7933*eb633035STom Caputi l2arc_untransform(zio_t *zio, l2arc_read_callback_t *cb)
7934*eb633035STom Caputi {
7935*eb633035STom Caputi 	int ret;
7936*eb633035STom Caputi 	spa_t *spa = zio->io_spa;
7937*eb633035STom Caputi 	arc_buf_hdr_t *hdr = cb->l2rcb_hdr;
7938*eb633035STom Caputi 	blkptr_t *bp = zio->io_bp;
7939*eb633035STom Caputi 	uint8_t salt[ZIO_DATA_SALT_LEN];
7940*eb633035STom Caputi 	uint8_t iv[ZIO_DATA_IV_LEN];
7941*eb633035STom Caputi 	uint8_t mac[ZIO_DATA_MAC_LEN];
7942*eb633035STom Caputi 	boolean_t no_crypt = B_FALSE;
7943*eb633035STom Caputi 
7944*eb633035STom Caputi 	/*
7945*eb633035STom Caputi 	 * ZIL data is never be written to the L2ARC, so we don't need
7946*eb633035STom Caputi 	 * special handling for its unique MAC storage.
7947*eb633035STom Caputi 	 */
7948*eb633035STom Caputi 	ASSERT3U(BP_GET_TYPE(bp), !=, DMU_OT_INTENT_LOG);
7949*eb633035STom Caputi 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
7950*eb633035STom Caputi 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
7951*eb633035STom Caputi 
7952*eb633035STom Caputi 	/*
7953*eb633035STom Caputi 	 * If the data was encrypted, decrypt it now. Note that
7954*eb633035STom Caputi 	 * we must check the bp here and not the hdr, since the
7955*eb633035STom Caputi 	 * hdr does not have its encryption parameters updated
7956*eb633035STom Caputi 	 * until arc_read_done().
7957*eb633035STom Caputi 	 */
7958*eb633035STom Caputi 	if (BP_IS_ENCRYPTED(bp)) {
7959*eb633035STom Caputi 		abd_t *eabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr);
7960*eb633035STom Caputi 
7961*eb633035STom Caputi 		zio_crypt_decode_params_bp(bp, salt, iv);
7962*eb633035STom Caputi 		zio_crypt_decode_mac_bp(bp, mac);
7963*eb633035STom Caputi 
7964*eb633035STom Caputi 		ret = spa_do_crypt_abd(B_FALSE, spa, &cb->l2rcb_zb,
7965*eb633035STom Caputi 		    BP_GET_TYPE(bp), BP_GET_DEDUP(bp), BP_SHOULD_BYTESWAP(bp),
7966*eb633035STom Caputi 		    salt, iv, mac, HDR_GET_PSIZE(hdr), eabd,
7967*eb633035STom Caputi 		    hdr->b_l1hdr.b_pabd, &no_crypt);
7968*eb633035STom Caputi 		if (ret != 0) {
7969*eb633035STom Caputi 			arc_free_data_abd(hdr, eabd, arc_hdr_size(hdr), hdr);
7970*eb633035STom Caputi 			goto error;
7971*eb633035STom Caputi 		}
7972*eb633035STom Caputi 
7973*eb633035STom Caputi 		/*
7974*eb633035STom Caputi 		 * If we actually performed decryption, replace b_pabd
7975*eb633035STom Caputi 		 * with the decrypted data. Otherwise we can just throw
7976*eb633035STom Caputi 		 * our decryption buffer away.
7977*eb633035STom Caputi 		 */
7978*eb633035STom Caputi 		if (!no_crypt) {
7979*eb633035STom Caputi 			arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
7980*eb633035STom Caputi 			    arc_hdr_size(hdr), hdr);
7981*eb633035STom Caputi 			hdr->b_l1hdr.b_pabd = eabd;
7982*eb633035STom Caputi 			zio->io_abd = eabd;
7983*eb633035STom Caputi 		} else {
7984*eb633035STom Caputi 			arc_free_data_abd(hdr, eabd, arc_hdr_size(hdr), hdr);
7985*eb633035STom Caputi 		}
7986*eb633035STom Caputi 	}
7987*eb633035STom Caputi 
7988*eb633035STom Caputi 	/*
7989*eb633035STom Caputi 	 * If the L2ARC block was compressed, but ARC compression
7990*eb633035STom Caputi 	 * is disabled we decompress the data into a new buffer and
7991*eb633035STom Caputi 	 * replace the existing data.
7992*eb633035STom Caputi 	 */
7993*eb633035STom Caputi 	if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
7994*eb633035STom Caputi 	    !HDR_COMPRESSION_ENABLED(hdr)) {
7995*eb633035STom Caputi 		abd_t *cabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr);
7996*eb633035STom Caputi 		void *tmp = abd_borrow_buf(cabd, arc_hdr_size(hdr));
7997*eb633035STom Caputi 
7998*eb633035STom Caputi 		ret = zio_decompress_data(HDR_GET_COMPRESS(hdr),
7999*eb633035STom Caputi 		    hdr->b_l1hdr.b_pabd, tmp, HDR_GET_PSIZE(hdr),
8000*eb633035STom Caputi 		    HDR_GET_LSIZE(hdr));
8001*eb633035STom Caputi 		if (ret != 0) {
8002*eb633035STom Caputi 			abd_return_buf_copy(cabd, tmp, arc_hdr_size(hdr));
8003*eb633035STom Caputi 			arc_free_data_abd(hdr, cabd, arc_hdr_size(hdr), hdr);
8004*eb633035STom Caputi 			goto error;
8005*eb633035STom Caputi 		}
8006*eb633035STom Caputi 
8007*eb633035STom Caputi 		abd_return_buf_copy(cabd, tmp, arc_hdr_size(hdr));
8008*eb633035STom Caputi 		arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
8009*eb633035STom Caputi 		    arc_hdr_size(hdr), hdr);
8010*eb633035STom Caputi 		hdr->b_l1hdr.b_pabd = cabd;
8011*eb633035STom Caputi 		zio->io_abd = cabd;
8012*eb633035STom Caputi 		zio->io_size = HDR_GET_LSIZE(hdr);
8013*eb633035STom Caputi 	}
8014*eb633035STom Caputi 
8015*eb633035STom Caputi 	return (0);
8016*eb633035STom Caputi 
8017*eb633035STom Caputi error:
8018*eb633035STom Caputi 	return (ret);
8019*eb633035STom Caputi }
8020*eb633035STom Caputi 
8021*eb633035STom Caputi 
8022fa94a07fSbrendan /*
8023fa94a07fSbrendan  * A read to a cache device completed.  Validate buffer contents before
8024fa94a07fSbrendan  * handing over to the regular ARC routines.
8025fa94a07fSbrendan  */
8026fa94a07fSbrendan static void
8027fa94a07fSbrendan l2arc_read_done(zio_t *zio)
8028fa94a07fSbrendan {
8029*eb633035STom Caputi 	int tfm_error = 0;
8030*eb633035STom Caputi 	l2arc_read_callback_t *cb = zio->io_private;
8031fa94a07fSbrendan 	arc_buf_hdr_t *hdr;
8032fa94a07fSbrendan 	kmutex_t *hash_lock;
8033dcbf3bd6SGeorge Wilson 	boolean_t valid_cksum;
8034*eb633035STom Caputi 	boolean_t using_rdata = (BP_IS_ENCRYPTED(&cb->l2rcb_bp) &&
8035*eb633035STom Caputi 	    (cb->l2rcb_flags & ZIO_FLAG_RAW_ENCRYPT));
8036fa94a07fSbrendan 
8037dcbf3bd6SGeorge Wilson 	ASSERT3P(zio->io_vd, !=, NULL);
8038e14bb325SJeff Bonwick 	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
8039e14bb325SJeff Bonwick 
8040e14bb325SJeff Bonwick 	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
8041e14bb325SJeff Bonwick 
8042dcbf3bd6SGeorge Wilson 	ASSERT3P(cb, !=, NULL);
8043dcbf3bd6SGeorge Wilson 	hdr = cb->l2rcb_hdr;
8044dcbf3bd6SGeorge Wilson 	ASSERT3P(hdr, !=, NULL);
8045fa94a07fSbrendan 
8046dcbf3bd6SGeorge Wilson 	hash_lock = HDR_LOCK(hdr);
8047fa94a07fSbrendan 	mutex_enter(hash_lock);
80483f9d6ad7SLin Ling 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
8049fa94a07fSbrendan 
8050403a8da7SAndriy Gapon 	/*
8051403a8da7SAndriy Gapon 	 * If the data was read into a temporary buffer,
8052403a8da7SAndriy Gapon 	 * move it and free the buffer.
8053403a8da7SAndriy Gapon 	 */
8054403a8da7SAndriy Gapon 	if (cb->l2rcb_abd != NULL) {
8055403a8da7SAndriy Gapon 		ASSERT3U(arc_hdr_size(hdr), <, zio->io_size);
8056403a8da7SAndriy Gapon 		if (zio->io_error == 0) {
8057*eb633035STom Caputi 			if (using_rdata) {
8058*eb633035STom Caputi 				abd_copy(hdr->b_crypt_hdr.b_rabd,
8059*eb633035STom Caputi 				    cb->l2rcb_abd, arc_hdr_size(hdr));
8060*eb633035STom Caputi 			} else {
8061*eb633035STom Caputi 				abd_copy(hdr->b_l1hdr.b_pabd,
8062*eb633035STom Caputi 				    cb->l2rcb_abd, arc_hdr_size(hdr));
8063*eb633035STom Caputi 			}
8064403a8da7SAndriy Gapon 		}
8065403a8da7SAndriy Gapon 
8066403a8da7SAndriy Gapon 		/*
8067403a8da7SAndriy Gapon 		 * The following must be done regardless of whether
8068403a8da7SAndriy Gapon 		 * there was an error:
8069403a8da7SAndriy Gapon 		 * - free the temporary buffer
8070403a8da7SAndriy Gapon 		 * - point zio to the real ARC buffer
8071403a8da7SAndriy Gapon 		 * - set zio size accordingly
8072403a8da7SAndriy Gapon 		 * These are required because zio is either re-used for
8073403a8da7SAndriy Gapon 		 * an I/O of the block in the case of the error
8074403a8da7SAndriy Gapon 		 * or the zio is passed to arc_read_done() and it
8075403a8da7SAndriy Gapon 		 * needs real data.
8076403a8da7SAndriy Gapon 		 */
8077403a8da7SAndriy Gapon 		abd_free(cb->l2rcb_abd);
8078403a8da7SAndriy Gapon 		zio->io_size = zio->io_orig_size = arc_hdr_size(hdr);
8079*eb633035STom Caputi 
8080*eb633035STom Caputi 		if (using_rdata) {
8081*eb633035STom Caputi 			ASSERT(HDR_HAS_RABD(hdr));
8082*eb633035STom Caputi 			zio->io_abd = zio->io_orig_abd =
8083*eb633035STom Caputi 			    hdr->b_crypt_hdr.b_rabd;
8084*eb633035STom Caputi 		} else {
8085*eb633035STom Caputi 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
8086*eb633035STom Caputi 			zio->io_abd = zio->io_orig_abd = hdr->b_l1hdr.b_pabd;
8087*eb633035STom Caputi 		}
8088403a8da7SAndriy Gapon 	}
8089403a8da7SAndriy Gapon 
8090770499e1SDan Kimmel 	ASSERT3P(zio->io_abd, !=, NULL);
8091aad02571SSaso Kiselkov 
8092fa94a07fSbrendan 	/*
8093fa94a07fSbrendan 	 * Check this survived the L2ARC journey.
8094fa94a07fSbrendan 	 */
8095*eb633035STom Caputi 	ASSERT(zio->io_abd == hdr->b_l1hdr.b_pabd ||
8096*eb633035STom Caputi 	    (HDR_HAS_RABD(hdr) && zio->io_abd == hdr->b_crypt_hdr.b_rabd));
8097dcbf3bd6SGeorge Wilson 	zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
8098dcbf3bd6SGeorge Wilson 	zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
8099dcbf3bd6SGeorge Wilson 
8100dcbf3bd6SGeorge Wilson 	valid_cksum = arc_cksum_is_equal(hdr, zio);
8101*eb633035STom Caputi 
8102*eb633035STom Caputi 	/*
8103*eb633035STom Caputi 	 * b_rabd will always match the data as it exists on disk if it is
8104*eb633035STom Caputi 	 * being used. Therefore if we are reading into b_rabd we do not
8105*eb633035STom Caputi 	 * attempt to untransform the data.
8106*eb633035STom Caputi 	 */
8107*eb633035STom Caputi 	if (valid_cksum && !using_rdata)
8108*eb633035STom Caputi 		tfm_error = l2arc_untransform(zio, cb);
8109*eb633035STom Caputi 
8110*eb633035STom Caputi 	if (valid_cksum && tfm_error == 0 && zio->io_error == 0 &&
8111*eb633035STom Caputi 	    !HDR_L2_EVICTED(hdr)) {
8112fa94a07fSbrendan 		mutex_exit(hash_lock);
8113dcbf3bd6SGeorge Wilson 		zio->io_private = hdr;
8114fa94a07fSbrendan 		arc_read_done(zio);
8115fa94a07fSbrendan 	} else {
8116fa94a07fSbrendan 		mutex_exit(hash_lock);
8117fa94a07fSbrendan 		/*
8118fa94a07fSbrendan 		 * Buffer didn't survive caching.  Increment stats and
8119fa94a07fSbrendan 		 * reissue to the original storage device.
8120fa94a07fSbrendan 		 */
81213a737e0dSbrendan 		if (zio->io_error != 0) {
8122fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_io_error);
81233a737e0dSbrendan 		} else {
8124be6fd75aSMatthew Ahrens 			zio->io_error = SET_ERROR(EIO);
81253a737e0dSbrendan 		}
8126*eb633035STom Caputi 		if (!valid_cksum || tfm_error != 0)
8127fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
8128fa94a07fSbrendan 
8129e14bb325SJeff Bonwick 		/*
8130e14bb325SJeff Bonwick 		 * If there's no waiter, issue an async i/o to the primary
8131e14bb325SJeff Bonwick 		 * storage now.  If there *is* a waiter, the caller must
8132e14bb325SJeff Bonwick 		 * issue the i/o in a context where it's OK to block.
8133e14bb325SJeff Bonwick 		 */
8134a3f829aeSBill Moore 		if (zio->io_waiter == NULL) {
8135a3f829aeSBill Moore 			zio_t *pio = zio_unique_parent(zio);
8136*eb633035STom Caputi 			void *abd = (using_rdata) ?
8137*eb633035STom Caputi 			    hdr->b_crypt_hdr.b_rabd : hdr->b_l1hdr.b_pabd;
8138a3f829aeSBill Moore 
8139a3f829aeSBill Moore 			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
8140a3f829aeSBill Moore 
8141dcbf3bd6SGeorge Wilson 			zio_nowait(zio_read(pio, zio->io_spa, zio->io_bp,
8142*eb633035STom Caputi 			    abd, zio->io_size, arc_read_done,
8143dcbf3bd6SGeorge Wilson 			    hdr, zio->io_priority, cb->l2rcb_flags,
8144dcbf3bd6SGeorge Wilson 			    &cb->l2rcb_zb));
8145a3f829aeSBill Moore 		}
8146fa94a07fSbrendan 	}
8147fa94a07fSbrendan 
8148fa94a07fSbrendan 	kmem_free(cb, sizeof (l2arc_read_callback_t));
8149fa94a07fSbrendan }
8150fa94a07fSbrendan 
8151fa94a07fSbrendan /*
8152fa94a07fSbrendan  * This is the list priority from which the L2ARC will search for pages to
8153fa94a07fSbrendan  * cache.  This is used within loops (0..3) to cycle through lists in the
8154fa94a07fSbrendan  * desired order.  This order can have a significant effect on cache
8155fa94a07fSbrendan  * performance.
8156fa94a07fSbrendan  *
8157fa94a07fSbrendan  * Currently the metadata lists are hit first, MFU then MRU, followed by
8158fa94a07fSbrendan  * the data lists.  This function returns a locked list, and also returns
8159fa94a07fSbrendan  * the lock pointer.
8160fa94a07fSbrendan  */
8161244781f1SPrakash Surya static multilist_sublist_t *
8162244781f1SPrakash Surya l2arc_sublist_lock(int list_num)
8163fa94a07fSbrendan {
8164244781f1SPrakash Surya 	multilist_t *ml = NULL;
8165244781f1SPrakash Surya 	unsigned int idx;
8166fa94a07fSbrendan 
8167fa94a07fSbrendan 	ASSERT(list_num >= 0 && list_num <= 3);
8168fa94a07fSbrendan 
8169fa94a07fSbrendan 	switch (list_num) {
8170fa94a07fSbrendan 	case 0:
817194c2d0ebSMatthew Ahrens 		ml = arc_mfu->arcs_list[ARC_BUFC_METADATA];
8172fa94a07fSbrendan 		break;
8173fa94a07fSbrendan 	case 1:
817494c2d0ebSMatthew Ahrens 		ml = arc_mru->arcs_list[ARC_BUFC_METADATA];
8175fa94a07fSbrendan 		break;
8176fa94a07fSbrendan 	case 2:
817794c2d0ebSMatthew Ahrens 		ml = arc_mfu->arcs_list[ARC_BUFC_DATA];
8178fa94a07fSbrendan 		break;
8179fa94a07fSbrendan 	case 3:
818094c2d0ebSMatthew Ahrens 		ml = arc_mru->arcs_list[ARC_BUFC_DATA];
8181fa94a07fSbrendan 		break;
8182fa94a07fSbrendan 	}
8183fa94a07fSbrendan 
8184244781f1SPrakash Surya 	/*
8185244781f1SPrakash Surya 	 * Return a randomly-selected sublist. This is acceptable
8186244781f1SPrakash Surya 	 * because the caller feeds only a little bit of data for each
8187244781f1SPrakash Surya 	 * call (8MB). Subsequent calls will result in different
8188244781f1SPrakash Surya 	 * sublists being selected.
8189244781f1SPrakash Surya 	 */
8190244781f1SPrakash Surya 	idx = multilist_get_random_index(ml);
8191244781f1SPrakash Surya 	return (multilist_sublist_lock(ml, idx));
8192fa94a07fSbrendan }
8193fa94a07fSbrendan 
8194fa94a07fSbrendan /*
8195fa94a07fSbrendan  * Evict buffers from the device write hand to the distance specified in
8196fa94a07fSbrendan  * bytes.  This distance may span populated buffers, it may span nothing.
8197fa94a07fSbrendan  * This is clearing a region on the L2ARC device ready for writing.
8198fa94a07fSbrendan  * If the 'all' boolean is set, every buffer is evicted.
8199fa94a07fSbrendan  */
8200fa94a07fSbrendan static void
8201fa94a07fSbrendan l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
8202fa94a07fSbrendan {
8203fa94a07fSbrendan 	list_t *buflist;
82047adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr, *hdr_prev;
8205fa94a07fSbrendan 	kmutex_t *hash_lock;
8206fa94a07fSbrendan 	uint64_t taddr;
8207fa94a07fSbrendan 
820889c86e32SChris Williamson 	buflist = &dev->l2ad_buflist;
8209fa94a07fSbrendan 
8210fa94a07fSbrendan 	if (!all && dev->l2ad_first) {
8211fa94a07fSbrendan 		/*
8212fa94a07fSbrendan 		 * This is the first sweep through the device.  There is
8213fa94a07fSbrendan 		 * nothing to evict.
8214fa94a07fSbrendan 		 */
8215fa94a07fSbrendan 		return;
8216fa94a07fSbrendan 	}
8217fa94a07fSbrendan 
82183a737e0dSbrendan 	if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
8219fa94a07fSbrendan 		/*
8220fa94a07fSbrendan 		 * When nearing the end of the device, evict to the end
8221fa94a07fSbrendan 		 * before the device write hand jumps to the start.
8222fa94a07fSbrendan 		 */
8223fa94a07fSbrendan 		taddr = dev->l2ad_end;
8224fa94a07fSbrendan 	} else {
8225fa94a07fSbrendan 		taddr = dev->l2ad_hand + distance;
8226fa94a07fSbrendan 	}
8227fa94a07fSbrendan 	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
8228fa94a07fSbrendan 	    uint64_t, taddr, boolean_t, all);
8229fa94a07fSbrendan 
8230fa94a07fSbrendan top:
823189c86e32SChris Williamson 	mutex_enter(&dev->l2ad_mtx);
82327adb730bSGeorge Wilson 	for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
82337adb730bSGeorge Wilson 		hdr_prev = list_prev(buflist, hdr);
8234fa94a07fSbrendan 
82357adb730bSGeorge Wilson 		hash_lock = HDR_LOCK(hdr);
8236244781f1SPrakash Surya 
8237244781f1SPrakash Surya 		/*
8238244781f1SPrakash Surya 		 * We cannot use mutex_enter or else we can deadlock
8239244781f1SPrakash Surya 		 * with l2arc_write_buffers (due to swapping the order
8240244781f1SPrakash Surya 		 * the hash lock and l2ad_mtx are taken).
8241244781f1SPrakash Surya 		 */
8242fa94a07fSbrendan 		if (!mutex_tryenter(hash_lock)) {
8243fa94a07fSbrendan 			/*
8244fa94a07fSbrendan 			 * Missed the hash lock.  Retry.
8245fa94a07fSbrendan 			 */
8246fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
824789c86e32SChris Williamson 			mutex_exit(&dev->l2ad_mtx);
8248fa94a07fSbrendan 			mutex_enter(hash_lock);
8249fa94a07fSbrendan 			mutex_exit(hash_lock);
8250fa94a07fSbrendan 			goto top;
8251fa94a07fSbrendan 		}
8252fa94a07fSbrendan 
8253267ae6c3SAndriy Gapon 		/*
8254267ae6c3SAndriy Gapon 		 * A header can't be on this list if it doesn't have L2 header.
8255267ae6c3SAndriy Gapon 		 */
8256267ae6c3SAndriy Gapon 		ASSERT(HDR_HAS_L2HDR(hdr));
8257fa94a07fSbrendan 
8258267ae6c3SAndriy Gapon 		/* Ensure this header has finished being written. */
8259267ae6c3SAndriy Gapon 		ASSERT(!HDR_L2_WRITING(hdr));
8260267ae6c3SAndriy Gapon 		ASSERT(!HDR_L2_WRITE_HEAD(hdr));
8261267ae6c3SAndriy Gapon 
8262267ae6c3SAndriy Gapon 		if (!all && (hdr->b_l2hdr.b_daddr >= taddr ||
826389c86e32SChris Williamson 		    hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
8264fa94a07fSbrendan 			/*
8265fa94a07fSbrendan 			 * We've evicted to the target address,
8266fa94a07fSbrendan 			 * or the end of the device.
8267fa94a07fSbrendan 			 */
8268fa94a07fSbrendan 			mutex_exit(hash_lock);
8269fa94a07fSbrendan 			break;
8270fa94a07fSbrendan 		}
8271fa94a07fSbrendan 
827289c86e32SChris Williamson 		if (!HDR_HAS_L1HDR(hdr)) {
82737adb730bSGeorge Wilson 			ASSERT(!HDR_L2_READING(hdr));
8274fa94a07fSbrendan 			/*
8275fa94a07fSbrendan 			 * This doesn't exist in the ARC.  Destroy.
8276fa94a07fSbrendan 			 * arc_hdr_destroy() will call list_remove()
827716a7e5acSAndriy Gapon 			 * and decrement arcstat_l2_lsize.
8278fa94a07fSbrendan 			 */
82797adb730bSGeorge Wilson 			arc_change_state(arc_anon, hdr, hash_lock);
82807adb730bSGeorge Wilson 			arc_hdr_destroy(hdr);
8281fa94a07fSbrendan 		} else {
828289c86e32SChris Williamson 			ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
828389c86e32SChris Williamson 			ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
82843a737e0dSbrendan 			/*
82853a737e0dSbrendan 			 * Invalidate issued or about to be issued
82863a737e0dSbrendan 			 * reads, since we may be about to write
82873a737e0dSbrendan 			 * over this location.
82883a737e0dSbrendan 			 */
82897adb730bSGeorge Wilson 			if (HDR_L2_READING(hdr)) {
82903a737e0dSbrendan 				ARCSTAT_BUMP(arcstat_l2_evict_reading);
8291dcbf3bd6SGeorge Wilson 				arc_hdr_set_flags(hdr, ARC_FLAG_L2_EVICTED);
82923a737e0dSbrendan 			}
82933a737e0dSbrendan 
8294a52fc310SPrakash Surya 			arc_hdr_l2hdr_destroy(hdr);
8295fa94a07fSbrendan 		}
8296fa94a07fSbrendan 		mutex_exit(hash_lock);
8297fa94a07fSbrendan 	}
829889c86e32SChris Williamson 	mutex_exit(&dev->l2ad_mtx);
8299fa94a07fSbrendan }
8300fa94a07fSbrendan 
8301*eb633035STom Caputi /*
8302*eb633035STom Caputi  * Handle any abd transforms that might be required for writing to the L2ARC.
8303*eb633035STom Caputi  * If successful, this function will always return an abd with the data
8304*eb633035STom Caputi  * transformed as it is on disk in a new abd of asize bytes.
8305*eb633035STom Caputi  */
8306*eb633035STom Caputi static int
8307*eb633035STom Caputi l2arc_apply_transforms(spa_t *spa, arc_buf_hdr_t *hdr, uint64_t asize,
8308*eb633035STom Caputi     abd_t **abd_out)
8309*eb633035STom Caputi {
8310*eb633035STom Caputi 	int ret;
8311*eb633035STom Caputi 	void *tmp = NULL;
8312*eb633035STom Caputi 	abd_t *cabd = NULL, *eabd = NULL, *to_write = hdr->b_l1hdr.b_pabd;
8313*eb633035STom Caputi 	enum zio_compress compress = HDR_GET_COMPRESS(hdr);
8314*eb633035STom Caputi 	uint64_t psize = HDR_GET_PSIZE(hdr);
8315*eb633035STom Caputi 	uint64_t size = arc_hdr_size(hdr);
8316*eb633035STom Caputi 	boolean_t ismd = HDR_ISTYPE_METADATA(hdr);
8317*eb633035STom Caputi 	boolean_t bswap = (hdr->b_l1hdr.b_byteswap != DMU_BSWAP_NUMFUNCS);
8318*eb633035STom Caputi 	dsl_crypto_key_t *dck = NULL;
8319*eb633035STom Caputi 	uint8_t mac[ZIO_DATA_MAC_LEN] = { 0 };
8320*eb633035STom Caputi 	boolean_t no_crypt = B_FALSE;
8321*eb633035STom Caputi 
8322*eb633035STom Caputi 	ASSERT((HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
8323*eb633035STom Caputi 	    !HDR_COMPRESSION_ENABLED(hdr)) ||
8324*eb633035STom Caputi 	    HDR_ENCRYPTED(hdr) || HDR_SHARED_DATA(hdr) || psize != asize);
8325*eb633035STom Caputi 	ASSERT3U(psize, <=, asize);
8326*eb633035STom Caputi 
8327*eb633035STom Caputi 	/*
8328*eb633035STom Caputi 	 * If this data simply needs its own buffer, we simply allocate it
8329*eb633035STom Caputi 	 * and copy the data. This may be done to eliminate a dependency on a
8330*eb633035STom Caputi 	 * shared buffer or to reallocate the buffer to match asize.
8331*eb633035STom Caputi 	 */
8332*eb633035STom Caputi 	if (HDR_HAS_RABD(hdr) && asize != psize) {
8333*eb633035STom Caputi 		ASSERT3U(asize, >=, psize);
8334*eb633035STom Caputi 		to_write = abd_alloc_for_io(asize, ismd);
8335*eb633035STom Caputi 		abd_copy(to_write, hdr->b_crypt_hdr.b_rabd, psize);
8336*eb633035STom Caputi 		if (psize != asize)
8337*eb633035STom Caputi 			abd_zero_off(to_write, psize, asize - psize);
8338*eb633035STom Caputi 		goto out;
8339*eb633035STom Caputi 	}
8340*eb633035STom Caputi 
8341*eb633035STom Caputi 	if ((compress == ZIO_COMPRESS_OFF || HDR_COMPRESSION_ENABLED(hdr)) &&
8342*eb633035STom Caputi 	    !HDR_ENCRYPTED(hdr)) {
8343*eb633035STom Caputi 		ASSERT3U(size, ==, psize);
8344*eb633035STom Caputi 		to_write = abd_alloc_for_io(asize, ismd);
8345*eb633035STom Caputi 		abd_copy(to_write, hdr->b_l1hdr.b_pabd, size);
8346*eb633035STom Caputi 		if (size != asize)
8347*eb633035STom Caputi 			abd_zero_off(to_write, size, asize - size);
8348*eb633035STom Caputi 		goto out;
8349*eb633035STom Caputi 	}
8350*eb633035STom Caputi 
8351*eb633035STom Caputi 	if (compress != ZIO_COMPRESS_OFF && !HDR_COMPRESSION_ENABLED(hdr)) {
8352*eb633035STom Caputi 		cabd = abd_alloc_for_io(asize, ismd);
8353*eb633035STom Caputi 		tmp = abd_borrow_buf(cabd, asize);
8354*eb633035STom Caputi 
8355*eb633035STom Caputi 		psize = zio_compress_data(compress, to_write, tmp, size);
8356*eb633035STom Caputi 		ASSERT3U(psize, <=, HDR_GET_PSIZE(hdr));
8357*eb633035STom Caputi 		if (psize < asize)
8358*eb633035STom Caputi 			bzero((char *)tmp + psize, asize - psize);
8359*eb633035STom Caputi 		psize = HDR_GET_PSIZE(hdr);
8360*eb633035STom Caputi 		abd_return_buf_copy(cabd, tmp, asize);
8361*eb633035STom Caputi 		to_write = cabd;
8362*eb633035STom Caputi 	}
8363*eb633035STom Caputi 
8364*eb633035STom Caputi 	if (HDR_ENCRYPTED(hdr)) {
8365*eb633035STom Caputi 		eabd = abd_alloc_for_io(asize, ismd);
8366*eb633035STom Caputi 
8367*eb633035STom Caputi 		/*
8368*eb633035STom Caputi 		 * If the dataset was disowned before the buffer
8369*eb633035STom Caputi 		 * made it to this point, the key to re-encrypt
8370*eb633035STom Caputi 		 * it won't be available. In this case we simply
8371*eb633035STom Caputi 		 * won't write the buffer to the L2ARC.
8372*eb633035STom Caputi 		 */
8373*eb633035STom Caputi 		ret = spa_keystore_lookup_key(spa, hdr->b_crypt_hdr.b_dsobj,
8374*eb633035STom Caputi 		    FTAG, &dck);
8375*eb633035STom Caputi 		if (ret != 0)
8376*eb633035STom Caputi 			goto error;
8377*eb633035STom Caputi 
8378*eb633035STom Caputi 		ret = zio_do_crypt_abd(B_TRUE, &dck->dck_key,
8379*eb633035STom Caputi 		    hdr->b_crypt_hdr.b_ot, bswap, hdr->b_crypt_hdr.b_salt,
8380*eb633035STom Caputi 		    hdr->b_crypt_hdr.b_iv, mac, psize, to_write, eabd,
8381*eb633035STom Caputi 		    &no_crypt);
8382*eb633035STom Caputi 		if (ret != 0)
8383*eb633035STom Caputi 			goto error;
8384*eb633035STom Caputi 
8385*eb633035STom Caputi 		if (no_crypt)
8386*eb633035STom Caputi 			abd_copy(eabd, to_write, psize);
8387*eb633035STom Caputi 
8388*eb633035STom Caputi 		if (psize != asize)
8389*eb633035STom Caputi 			abd_zero_off(eabd, psize, asize - psize);
8390*eb633035STom Caputi 
8391*eb633035STom Caputi 		/* assert that the MAC we got here matches the one we saved */
8392*eb633035STom Caputi 		ASSERT0(bcmp(mac, hdr->b_crypt_hdr.b_mac, ZIO_DATA_MAC_LEN));
8393*eb633035STom Caputi 		spa_keystore_dsl_key_rele(spa, dck, FTAG);
8394*eb633035STom Caputi 
8395*eb633035STom Caputi 		if (to_write == cabd)
8396*eb633035STom Caputi 			abd_free(cabd);
8397*eb633035STom Caputi 
8398*eb633035STom Caputi 		to_write = eabd;
8399*eb633035STom Caputi 	}
8400*eb633035STom Caputi 
8401*eb633035STom Caputi out:
8402*eb633035STom Caputi 	ASSERT3P(to_write, !=, hdr->b_l1hdr.b_pabd);
8403*eb633035STom Caputi 	*abd_out = to_write;
8404*eb633035STom Caputi 	return (0);
8405*eb633035STom Caputi 
8406*eb633035STom Caputi error:
8407*eb633035STom Caputi 	if (dck != NULL)
8408*eb633035STom Caputi 		spa_keystore_dsl_key_rele(spa, dck, FTAG);
8409*eb633035STom Caputi 	if (cabd != NULL)
8410*eb633035STom Caputi 		abd_free(cabd);
8411*eb633035STom Caputi 	if (eabd != NULL)
8412*eb633035STom Caputi 		abd_free(eabd);
8413*eb633035STom Caputi 
8414*eb633035STom Caputi 	*abd_out = NULL;
8415*eb633035STom Caputi 	return (ret);
8416*eb633035STom Caputi }
8417*eb633035STom Caputi 
8418fa94a07fSbrendan /*
8419fa94a07fSbrendan  * Find and write ARC buffers to the L2ARC device.
8420fa94a07fSbrendan  *
84217adb730bSGeorge Wilson  * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
8422fa94a07fSbrendan  * for reading until they have completed writing.
8423aad02571SSaso Kiselkov  * The headroom_boost is an in-out parameter used to maintain headroom boost
8424aad02571SSaso Kiselkov  * state between calls to this function.
8425aad02571SSaso Kiselkov  *
8426aad02571SSaso Kiselkov  * Returns the number of bytes actually written (which may be smaller than
8427aad02571SSaso Kiselkov  * the delta by which the device hand has changed due to alignment).
8428fa94a07fSbrendan  */
84295a98e54bSBrendan Gregg - Sun Microsystems static uint64_t
8430dcbf3bd6SGeorge Wilson l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
8431fa94a07fSbrendan {
84327adb730bSGeorge Wilson 	arc_buf_hdr_t *hdr, *hdr_prev, *head;
843316a7e5acSAndriy Gapon 	uint64_t write_asize, write_psize, write_lsize, headroom;
8434aad02571SSaso Kiselkov 	boolean_t full;
8435fa94a07fSbrendan 	l2arc_write_callback_t *cb;
8436fa94a07fSbrendan 	zio_t *pio, *wzio;
8437e9103aaeSGarrett D'Amore 	uint64_t guid = spa_load_guid(spa);
8438fa94a07fSbrendan 
8439dcbf3bd6SGeorge Wilson 	ASSERT3P(dev->l2ad_vdev, !=, NULL);
8440aad02571SSaso Kiselkov 
8441fa94a07fSbrendan 	pio = NULL;
844216a7e5acSAndriy Gapon 	write_lsize = write_asize = write_psize = 0;
8443fa94a07fSbrendan 	full = B_FALSE;
844489c86e32SChris Williamson 	head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
8445dcbf3bd6SGeorge Wilson 	arc_hdr_set_flags(head, ARC_FLAG_L2_WRITE_HEAD | ARC_FLAG_HAS_L2HDR);
8446aad02571SSaso Kiselkov 
8447fa94a07fSbrendan 	/*
8448fa94a07fSbrendan 	 * Copy buffers for L2ARC writing.
8449fa94a07fSbrendan 	 */
8450fa94a07fSbrendan 	for (int try = 0; try <= 3; try++) {
8451244781f1SPrakash Surya 		multilist_sublist_t *mls = l2arc_sublist_lock(try);
8452aad02571SSaso Kiselkov 		uint64_t passed_sz = 0;
8453aad02571SSaso Kiselkov 
8454*eb633035STom Caputi 		VERIFY3P(mls, !=, NULL);
8455*eb633035STom Caputi 
84563a737e0dSbrendan 		/*
84573a737e0dSbrendan 		 * L2ARC fast warmup.
84583a737e0dSbrendan 		 *
84593a737e0dSbrendan 		 * Until the ARC is warm and starts to evict, read from the
84603a737e0dSbrendan 		 * head of the ARC lists rather than the tail.
84613a737e0dSbrendan 		 */
84623a737e0dSbrendan 		if (arc_warm == B_FALSE)
8463244781f1SPrakash Surya 			hdr = multilist_sublist_head(mls);
84643a737e0dSbrendan 		else
8465244781f1SPrakash Surya 			hdr = multilist_sublist_tail(mls);
84663a737e0dSbrendan 
8467aad02571SSaso Kiselkov 		headroom = target_sz * l2arc_headroom;
8468dcbf3bd6SGeorge Wilson 		if (zfs_compressed_arc_enabled)
8469aad02571SSaso Kiselkov 			headroom = (headroom * l2arc_headroom_boost) / 100;
8470aad02571SSaso Kiselkov 
84717adb730bSGeorge Wilson 		for (; hdr; hdr = hdr_prev) {
8472aad02571SSaso Kiselkov 			kmutex_t *hash_lock;
8473*eb633035STom Caputi 			abd_t *to_write = NULL;
8474aad02571SSaso Kiselkov 
84753a737e0dSbrendan 			if (arc_warm == B_FALSE)
8476244781f1SPrakash Surya 				hdr_prev = multilist_sublist_next(mls, hdr);
84773a737e0dSbrendan 			else
8478244781f1SPrakash Surya 				hdr_prev = multilist_sublist_prev(mls, hdr);
8479fa94a07fSbrendan 
84807adb730bSGeorge Wilson 			hash_lock = HDR_LOCK(hdr);
8481aad02571SSaso Kiselkov 			if (!mutex_tryenter(hash_lock)) {
8482fa94a07fSbrendan 				/*
8483fa94a07fSbrendan 				 * Skip this buffer rather than waiting.
8484fa94a07fSbrendan 				 */
8485fa94a07fSbrendan 				continue;
8486fa94a07fSbrendan 			}
8487fa94a07fSbrendan 
8488dcbf3bd6SGeorge Wilson 			passed_sz += HDR_GET_LSIZE(hdr);
8489fa94a07fSbrendan 			if (passed_sz > headroom) {
8490fa94a07fSbrendan 				/*
8491fa94a07fSbrendan 				 * Searched too far.
8492fa94a07fSbrendan 				 */
8493fa94a07fSbrendan 				mutex_exit(hash_lock);
8494fa94a07fSbrendan 				break;
8495fa94a07fSbrendan 			}
8496fa94a07fSbrendan 
84977adb730bSGeorge Wilson 			if (!l2arc_write_eligible(guid, hdr)) {
8498fa94a07fSbrendan 				mutex_exit(hash_lock);
8499fa94a07fSbrendan 				continue;
8500fa94a07fSbrendan 			}
8501fa94a07fSbrendan 
850216a7e5acSAndriy Gapon 			/*
850316a7e5acSAndriy Gapon 			 * We rely on the L1 portion of the header below, so
850416a7e5acSAndriy Gapon 			 * it's invalid for this header to have been evicted out
850516a7e5acSAndriy Gapon 			 * of the ghost cache, prior to being written out. The
850616a7e5acSAndriy Gapon 			 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
850716a7e5acSAndriy Gapon 			 */
850816a7e5acSAndriy Gapon 			ASSERT(HDR_HAS_L1HDR(hdr));
850916a7e5acSAndriy Gapon 
851016a7e5acSAndriy Gapon 			ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
851116a7e5acSAndriy Gapon 			ASSERT3U(arc_hdr_size(hdr), >, 0);
8512*eb633035STom Caputi 			ASSERT(hdr->b_l1hdr.b_pabd != NULL ||
8513*eb633035STom Caputi 			    HDR_HAS_RABD(hdr));
8514*eb633035STom Caputi 			uint64_t psize = HDR_GET_PSIZE(hdr);
851516a7e5acSAndriy Gapon 			uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev,
851616a7e5acSAndriy Gapon 			    psize);
851716a7e5acSAndriy Gapon 
851816a7e5acSAndriy Gapon 			if ((write_asize + asize) > target_sz) {
8519fa94a07fSbrendan 				full = B_TRUE;
8520fa94a07fSbrendan 				mutex_exit(hash_lock);
8521fa94a07fSbrendan 				break;
8522fa94a07fSbrendan 			}
8523fa94a07fSbrendan 
8524*eb633035STom Caputi 			/*
8525*eb633035STom Caputi 			 * We rely on the L1 portion of the header below, so
8526*eb633035STom Caputi 			 * it's invalid for this header to have been evicted out
8527*eb633035STom Caputi 			 * of the ghost cache, prior to being written out. The
8528*eb633035STom Caputi 			 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
8529*eb633035STom Caputi 			 */
8530*eb633035STom Caputi 			arc_hdr_set_flags(hdr, ARC_FLAG_L2_WRITING);
8531*eb633035STom Caputi 			ASSERT(HDR_HAS_L1HDR(hdr));
8532*eb633035STom Caputi 
8533*eb633035STom Caputi 			ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
8534*eb633035STom Caputi 			ASSERT(hdr->b_l1hdr.b_pabd != NULL ||
8535*eb633035STom Caputi 			    HDR_HAS_RABD(hdr));
8536*eb633035STom Caputi 			ASSERT3U(arc_hdr_size(hdr), >, 0);
8537*eb633035STom Caputi 
8538*eb633035STom Caputi 			/*
8539*eb633035STom Caputi 			 * If this header has b_rabd, we can use this since it
8540*eb633035STom Caputi 			 * must always match the data exactly as it exists on
8541*eb633035STom Caputi 			 * disk. Otherwise, the L2ARC can normally use the
8542*eb633035STom Caputi 			 * hdr's data, but if we're sharing data between the
8543*eb633035STom Caputi 			 * hdr and one of its bufs, L2ARC needs its own copy of
8544*eb633035STom Caputi 			 * the data so that the ZIO below can't race with the
8545*eb633035STom Caputi 			 * buf consumer. To ensure that this copy will be
8546*eb633035STom Caputi 			 * available for the lifetime of the ZIO and be cleaned
8547*eb633035STom Caputi 			 * up afterwards, we add it to the l2arc_free_on_write
8548*eb633035STom Caputi 			 * queue. If we need to apply any transforms to the
8549*eb633035STom Caputi 			 * data (compression, encryption) we will also need the
8550*eb633035STom Caputi 			 * extra buffer.
8551*eb633035STom Caputi 			 */
8552*eb633035STom Caputi 			if (HDR_HAS_RABD(hdr) && psize == asize) {
8553*eb633035STom Caputi 				to_write = hdr->b_crypt_hdr.b_rabd;
8554*eb633035STom Caputi 			} else if ((HDR_COMPRESSION_ENABLED(hdr) ||
8555*eb633035STom Caputi 			    HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_OFF) &&
8556*eb633035STom Caputi 			    !HDR_ENCRYPTED(hdr) && !HDR_SHARED_DATA(hdr) &&
8557*eb633035STom Caputi 			    psize == asize) {
8558*eb633035STom Caputi 				to_write = hdr->b_l1hdr.b_pabd;
8559*eb633035STom Caputi 			} else {
8560*eb633035STom Caputi 				int ret;
8561*eb633035STom Caputi 				arc_buf_contents_t type = arc_buf_type(hdr);
8562*eb633035STom Caputi 
8563*eb633035STom Caputi 				ret = l2arc_apply_transforms(spa, hdr, asize,
8564*eb633035STom Caputi 				    &to_write);
8565*eb633035STom Caputi 				if (ret != 0) {
8566*eb633035STom Caputi 					arc_hdr_clear_flags(hdr,
8567*eb633035STom Caputi 					    ARC_FLAG_L2_WRITING);
8568*eb633035STom Caputi 					mutex_exit(hash_lock);
8569*eb633035STom Caputi 					continue;
8570*eb633035STom Caputi 				}
8571*eb633035STom Caputi 
8572*eb633035STom Caputi 				l2arc_free_abd_on_write(to_write, asize, type);
8573*eb633035STom Caputi 			}
8574*eb633035STom Caputi 
8575fa94a07fSbrendan 			if (pio == NULL) {
8576fa94a07fSbrendan 				/*
8577fa94a07fSbrendan 				 * Insert a dummy header on the buflist so
8578fa94a07fSbrendan 				 * l2arc_write_done() can find where the
8579fa94a07fSbrendan 				 * write buffers begin without searching.
8580fa94a07fSbrendan 				 */
8581244781f1SPrakash Surya 				mutex_enter(&dev->l2ad_mtx);
858289c86e32SChris Williamson 				list_insert_head(&dev->l2ad_buflist, head);
8583244781f1SPrakash Surya 				mutex_exit(&dev->l2ad_mtx);
8584fa94a07fSbrendan 
8585fa94a07fSbrendan 				cb = kmem_alloc(
8586fa94a07fSbrendan 				    sizeof (l2arc_write_callback_t), KM_SLEEP);
8587fa94a07fSbrendan 				cb->l2wcb_dev = dev;
8588fa94a07fSbrendan 				cb->l2wcb_head = head;
8589fa94a07fSbrendan 				pio = zio_root(spa, l2arc_write_done, cb,
8590fa94a07fSbrendan 				    ZIO_FLAG_CANFAIL);
8591fa94a07fSbrendan 			}
8592fa94a07fSbrendan 
859389c86e32SChris Williamson 			hdr->b_l2hdr.b_dev = dev;
8594dcbf3bd6SGeorge Wilson 			hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
8595dcbf3bd6SGeorge Wilson 			arc_hdr_set_flags(hdr,
8596dcbf3bd6SGeorge Wilson 			    ARC_FLAG_L2_WRITING | ARC_FLAG_HAS_L2HDR);
8597dcbf3bd6SGeorge Wilson 
8598dcbf3bd6SGeorge Wilson 			mutex_enter(&dev->l2ad_mtx);
8599dcbf3bd6SGeorge Wilson 			list_insert_head(&dev->l2ad_buflist, hdr);
8600dcbf3bd6SGeorge Wilson 			mutex_exit(&dev->l2ad_mtx);
8601dcbf3bd6SGeorge Wilson 
8602*eb633035STom Caputi 			(void) zfs_refcount_add_many(&dev->l2ad_alloc,
8603*eb633035STom Caputi 			    arc_hdr_size(hdr), hdr);
8604aad02571SSaso Kiselkov 
8605dcbf3bd6SGeorge Wilson 			wzio = zio_write_phys(pio, dev->l2ad_vdev,
8606403a8da7SAndriy Gapon 			    hdr->b_l2hdr.b_daddr, asize, to_write,
8607dcbf3bd6SGeorge Wilson 			    ZIO_CHECKSUM_OFF, NULL, hdr,
8608dcbf3bd6SGeorge Wilson 			    ZIO_PRIORITY_ASYNC_WRITE,
8609dcbf3bd6SGeorge Wilson 			    ZIO_FLAG_CANFAIL, B_FALSE);
8610aad02571SSaso Kiselkov 
861116a7e5acSAndriy Gapon 			write_lsize += HDR_GET_LSIZE(hdr);
8612dcbf3bd6SGeorge Wilson 			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
8613dcbf3bd6SGeorge Wilson 			    zio_t *, wzio);
8614fa94a07fSbrendan 
861516a7e5acSAndriy Gapon 			write_psize += psize;
861616a7e5acSAndriy Gapon 			write_asize += asize;
8617dcbf3bd6SGeorge Wilson 			dev->l2ad_hand += asize;
86189740f25fSSerapheim Dimitropoulos 			vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
8619fa94a07fSbrendan 
8620fa94a07fSbrendan 			mutex_exit(hash_lock);
8621fa94a07fSbrendan 
8622dcbf3bd6SGeorge Wilson 			(void) zio_nowait(wzio);
8623aad02571SSaso Kiselkov 		}
8624aad02571SSaso Kiselkov 
8625244781f1SPrakash Surya 		multilist_sublist_unlock(mls);
8626aad02571SSaso Kiselkov 
8627aad02571SSaso Kiselkov 		if (full == B_TRUE)
8628aad02571SSaso Kiselkov 			break;
8629aad02571SSaso Kiselkov 	}
8630aad02571SSaso Kiselkov 
8631aad02571SSaso Kiselkov 	/* No buffers selected for writing? */
8632aad02571SSaso Kiselkov 	if (pio == NULL) {
863316a7e5acSAndriy Gapon 		ASSERT0(write_lsize);
863489c86e32SChris Williamson 		ASSERT(!HDR_HAS_L1HDR(head));
863589c86e32SChris Williamson 		kmem_cache_free(hdr_l2only_cache, head);
8636aad02571SSaso Kiselkov 		return (0);
8637aad02571SSaso Kiselkov 	}
8638aad02571SSaso Kiselkov 
8639aad02571SSaso Kiselkov 	ASSERT3U(write_asize, <=, target_sz);
8640fa94a07fSbrendan 	ARCSTAT_BUMP(arcstat_l2_writes_sent);
864116a7e5acSAndriy Gapon 	ARCSTAT_INCR(arcstat_l2_write_bytes, write_psize);
864216a7e5acSAndriy Gapon 	ARCSTAT_INCR(arcstat_l2_lsize, write_lsize);
864316a7e5acSAndriy Gapon 	ARCSTAT_INCR(arcstat_l2_psize, write_psize);
8644fa94a07fSbrendan 
8645fa94a07fSbrendan 	/*
8646fa94a07fSbrendan 	 * Bump device hand to the device start if it is approaching the end.
8647fa94a07fSbrendan 	 * l2arc_evict() will already have evicted ahead for this case.
8648fa94a07fSbrendan 	 */
86493a737e0dSbrendan 	if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
8650fa94a07fSbrendan 		dev->l2ad_hand = dev->l2ad_start;
8651fa94a07fSbrendan 		dev->l2ad_first = B_FALSE;
8652fa94a07fSbrendan 	}
8653fa94a07fSbrendan 
86545a98e54bSBrendan Gregg - Sun Microsystems 	dev->l2ad_writing = B_TRUE;
8655fa94a07fSbrendan 	(void) zio_wait(pio);
86565a98e54bSBrendan Gregg - Sun Microsystems 	dev->l2ad_writing = B_FALSE;
86575a98e54bSBrendan Gregg - Sun Microsystems 
8658aad02571SSaso Kiselkov 	return (write_asize);
8659aad02571SSaso Kiselkov }
8660aad02571SSaso Kiselkov 
8661fa94a07fSbrendan /*
8662fa94a07fSbrendan  * This thread feeds the L2ARC at regular intervals.  This is the beating
8663fa94a07fSbrendan  * heart of the L2ARC.
8664fa94a07fSbrendan  */
86653f7978d0SAlan Somers /* ARGSUSED */
8666fa94a07fSbrendan static void
86673f7978d0SAlan Somers l2arc_feed_thread(void *unused)
8668fa94a07fSbrendan {
8669fa94a07fSbrendan 	callb_cpr_t cpr;
8670fa94a07fSbrendan 	l2arc_dev_t *dev;
8671fa94a07fSbrendan 	spa_t *spa;
86725a98e54bSBrendan Gregg - Sun Microsystems 	uint64_t size, wrote;
8673d3d50737SRafael Vanoni 	clock_t begin, next = ddi_get_lbolt();
8674fa94a07fSbrendan 
8675fa94a07fSbrendan 	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
8676fa94a07fSbrendan 
8677fa94a07fSbrendan 	mutex_enter(&l2arc_feed_thr_lock);
8678fa94a07fSbrendan 
8679fa94a07fSbrendan 	while (l2arc_thread_exit == 0) {
8680fa94a07fSbrendan 		CALLB_CPR_SAFE_BEGIN(&cpr);
8681fa94a07fSbrendan 		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
86825a98e54bSBrendan Gregg - Sun Microsystems 		    next);
8683fa94a07fSbrendan 		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
8684d3d50737SRafael Vanoni 		next = ddi_get_lbolt() + hz;
8685fa94a07fSbrendan 
86863a737e0dSbrendan 		/*
86873a737e0dSbrendan 		 * Quick check for L2ARC devices.
86883a737e0dSbrendan 		 */
8689c5904d13Seschrock 		mutex_enter(&l2arc_dev_mtx);
86903a737e0dSbrendan 		if (l2arc_ndev == 0) {
86913a737e0dSbrendan 			mutex_exit(&l2arc_dev_mtx);
86923a737e0dSbrendan 			continue;
86933a737e0dSbrendan 		}
86943a737e0dSbrendan 		mutex_exit(&l2arc_dev_mtx);
8695d3d50737SRafael Vanoni 		begin = ddi_get_lbolt();
8696c5904d13Seschrock 
8697fa94a07fSbrendan 		/*
8698c5904d13Seschrock 		 * This selects the next l2arc device to write to, and in
8699c5904d13Seschrock 		 * doing so the next spa to feed from: dev->l2ad_spa.   This
87003a737e0dSbrendan 		 * will return NULL if there are now no l2arc devices or if
87013a737e0dSbrendan 		 * they are all faulted.
87023a737e0dSbrendan 		 *
87033a737e0dSbrendan 		 * If a device is returned, its spa's config lock is also
87043a737e0dSbrendan 		 * held to prevent device removal.  l2arc_dev_get_next()
87053a737e0dSbrendan 		 * will grab and release l2arc_dev_mtx.
8706fa94a07fSbrendan 		 */
87073a737e0dSbrendan 		if ((dev = l2arc_dev_get_next()) == NULL)
8708fa94a07fSbrendan 			continue;
87093a737e0dSbrendan 
87103a737e0dSbrendan 		spa = dev->l2ad_spa;
8711dcbf3bd6SGeorge Wilson 		ASSERT3P(spa, !=, NULL);
8712fa94a07fSbrendan 
8713f9af39baSGeorge Wilson 		/*
8714f9af39baSGeorge Wilson 		 * If the pool is read-only then force the feed thread to
8715f9af39baSGeorge Wilson 		 * sleep a little longer.
8716f9af39baSGeorge Wilson 		 */
8717f9af39baSGeorge Wilson 		if (!spa_writeable(spa)) {
8718f9af39baSGeorge Wilson 			next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
8719f9af39baSGeorge Wilson 			spa_config_exit(spa, SCL_L2ARC, dev);
8720f9af39baSGeorge Wilson 			continue;
8721f9af39baSGeorge Wilson 		}
8722f9af39baSGeorge Wilson 
8723fa94a07fSbrendan 		/*
8724fa94a07fSbrendan 		 * Avoid contributing to memory pressure.
8725fa94a07fSbrendan 		 */
8726fa94a07fSbrendan 		if (arc_reclaim_needed()) {
8727fa94a07fSbrendan 			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
8728e14bb325SJeff Bonwick 			spa_config_exit(spa, SCL_L2ARC, dev);
8729fa94a07fSbrendan 			continue;
8730fa94a07fSbrendan 		}
8731fa94a07fSbrendan 
8732fa94a07fSbrendan 		ARCSTAT_BUMP(arcstat_l2_feeds);
8733fa94a07fSbrendan 
8734aad02571SSaso Kiselkov 		size = l2arc_write_size();
87353a737e0dSbrendan 
8736fa94a07fSbrendan 		/*
8737fa94a07fSbrendan 		 * Evict L2ARC buffers that will be overwritten.
8738fa94a07fSbrendan 		 */
87393a737e0dSbrendan 		l2arc_evict(dev, size, B_FALSE);
8740fa94a07fSbrendan 
8741fa94a07fSbrendan 		/*
8742fa94a07fSbrendan 		 * Write ARC buffers.
8743fa94a07fSbrendan 		 */
8744dcbf3bd6SGeorge Wilson 		wrote = l2arc_write_buffers(spa, dev, size);
87455a98e54bSBrendan Gregg - Sun Microsystems 
87465a98e54bSBrendan Gregg - Sun Microsystems 		/*
87475a98e54bSBrendan Gregg - Sun Microsystems 		 * Calculate interval between writes.
87485a98e54bSBrendan Gregg - Sun Microsystems 		 */
87495a98e54bSBrendan Gregg - Sun Microsystems 		next = l2arc_write_interval(begin, size, wrote);
8750e14bb325SJeff Bonwick 		spa_config_exit(spa, SCL_L2ARC, dev);
8751fa94a07fSbrendan 	}
8752fa94a07fSbrendan 
8753fa94a07fSbrendan 	l2arc_thread_exit = 0;
8754fa94a07fSbrendan 	cv_broadcast(&l2arc_feed_thr_cv);
8755fa94a07fSbrendan 	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
8756fa94a07fSbrendan 	thread_exit();
8757fa94a07fSbrendan }
8758fa94a07fSbrendan 
8759c5904d13Seschrock boolean_t
8760c5904d13Seschrock l2arc_vdev_present(vdev_t *vd)
8761c5904d13Seschrock {
8762c5904d13Seschrock 	l2arc_dev_t *dev;
8763c5904d13Seschrock 
8764c5904d13Seschrock 	mutex_enter(&l2arc_dev_mtx);
8765c5904d13Seschrock 	for (dev = list_head(l2arc_dev_list); dev != NULL;
8766c5904d13Seschrock 	    dev = list_next(l2arc_dev_list, dev)) {
8767c5904d13Seschrock 		if (dev->l2ad_vdev == vd)
8768c5904d13Seschrock 			break;
8769c5904d13Seschrock 	}
8770c5904d13Seschrock 	mutex_exit(&l2arc_dev_mtx);
8771c5904d13Seschrock 
8772c5904d13Seschrock 	return (dev != NULL);
8773c5904d13Seschrock }
8774c5904d13Seschrock 
8775fa94a07fSbrendan /*
8776fa94a07fSbrendan  * Add a vdev for use by the L2ARC.  By this point the spa has already
8777fa94a07fSbrendan  * validated the vdev and opened it.
8778fa94a07fSbrendan  */
8779fa94a07fSbrendan void
8780573ca77eSGeorge Wilson l2arc_add_vdev(spa_t *spa, vdev_t *vd)
8781fa94a07fSbrendan {
8782fa94a07fSbrendan 	l2arc_dev_t *adddev;
8783fa94a07fSbrendan 
8784c5904d13Seschrock 	ASSERT(!l2arc_vdev_present(vd));
8785c5904d13Seschrock 
8786fa94a07fSbrendan 	/*
8787fa94a07fSbrendan 	 * Create a new l2arc device entry.
8788fa94a07fSbrendan 	 */
8789fa94a07fSbrendan 	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
8790fa94a07fSbrendan 	adddev->l2ad_spa = spa;
8791fa94a07fSbrendan 	adddev->l2ad_vdev = vd;
8792573ca77eSGeorge Wilson 	adddev->l2ad_start = VDEV_LABEL_START_SIZE;
8793573ca77eSGeorge Wilson 	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
8794fa94a07fSbrendan 	adddev->l2ad_hand = adddev->l2ad_start;
8795fa94a07fSbrendan 	adddev->l2ad_first = B_TRUE;
87965a98e54bSBrendan Gregg - Sun Microsystems 	adddev->l2ad_writing = B_FALSE;
8797fa94a07fSbrendan 
879889c86e32SChris Williamson 	mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
8799fa94a07fSbrendan 	/*
8800fa94a07fSbrendan 	 * This is a list of all ARC buffers that are still valid on the
8801fa94a07fSbrendan 	 * device.
8802fa94a07fSbrendan 	 */
880389c86e32SChris Williamson 	list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
880489c86e32SChris Williamson 	    offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
8805fa94a07fSbrendan 
8806b24ab676SJeff Bonwick 	vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
8807e914ace2STim Schumacher 	zfs_refcount_create(&adddev->l2ad_alloc);
8808fa94a07fSbrendan 
8809fa94a07fSbrendan 	/*
8810fa94a07fSbrendan 	 * Add device to global list
8811fa94a07fSbrendan 	 */
8812fa94a07fSbrendan 	mutex_enter(&l2arc_dev_mtx);
8813fa94a07fSbrendan 	list_insert_head(l2arc_dev_list, adddev);
8814fa94a07fSbrendan 	atomic_inc_64(&l2arc_ndev);
8815fa94a07fSbrendan 	mutex_exit(&l2arc_dev_mtx);
8816fa94a07fSbrendan }
8817fa94a07fSbrendan 
8818fa94a07fSbrendan /*
8819fa94a07fSbrendan  * Remove a vdev from the L2ARC.
8820fa94a07fSbrendan  */
8821fa94a07fSbrendan void
8822fa94a07fSbrendan l2arc_remove_vdev(vdev_t *vd)
8823fa94a07fSbrendan {
8824fa94a07fSbrendan 	l2arc_dev_t *dev, *nextdev, *remdev = NULL;
8825fa94a07fSbrendan 
8826fa94a07fSbrendan 	/*
8827fa94a07fSbrendan 	 * Find the device by vdev
8828fa94a07fSbrendan 	 */
8829fa94a07fSbrendan 	mutex_enter(&l2arc_dev_mtx);
8830fa94a07fSbrendan 	for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
8831fa94a07fSbrendan 		nextdev = list_next(l2arc_dev_list, dev);
8832fa94a07fSbrendan 		if (vd == dev->l2ad_vdev) {
8833fa94a07fSbrendan 			remdev = dev;
8834fa94a07fSbrendan 			break;
8835fa94a07fSbrendan 		}
8836fa94a07fSbrendan 	}
8837dcbf3bd6SGeorge Wilson 	ASSERT3P(remdev, !=, NULL);
8838fa94a07fSbrendan 
8839fa94a07fSbrendan 	/*
8840fa94a07fSbrendan 	 * Remove device from global list
8841fa94a07fSbrendan 	 */
8842fa94a07fSbrendan 	list_remove(l2arc_dev_list, remdev);
8843fa94a07fSbrendan 	l2arc_dev_last = NULL;		/* may have been invalidated */
88443a737e0dSbrendan 	atomic_dec_64(&l2arc_ndev);
88453a737e0dSbrendan 	mutex_exit(&l2arc_dev_mtx);
8846fa94a07fSbrendan 
8847fa94a07fSbrendan 	/*
8848fa94a07fSbrendan 	 * Clear all buflists and ARC references.  L2ARC device flush.
8849fa94a07fSbrendan 	 */
8850fa94a07fSbrendan 	l2arc_evict(remdev, 0, B_TRUE);
885189c86e32SChris Williamson 	list_destroy(&remdev->l2ad_buflist);
885289c86e32SChris Williamson 	mutex_destroy(&remdev->l2ad_mtx);
8853e914ace2STim Schumacher 	zfs_refcount_destroy(&remdev->l2ad_alloc);
8854fa94a07fSbrendan 	kmem_free(remdev, sizeof (l2arc_dev_t));
8855fa94a07fSbrendan }
8856fa94a07fSbrendan 
8857fa94a07fSbrendan void
8858e14bb325SJeff Bonwick l2arc_init(void)
8859fa94a07fSbrendan {
8860fa94a07fSbrendan 	l2arc_thread_exit = 0;
8861fa94a07fSbrendan 	l2arc_ndev = 0;
8862fa94a07fSbrendan 	l2arc_writes_sent = 0;
8863fa94a07fSbrendan 	l2arc_writes_done = 0;
8864fa94a07fSbrendan 
8865fa94a07fSbrendan 	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
8866fa94a07fSbrendan 	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
8867fa94a07fSbrendan 	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
8868fa94a07fSbrendan 	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
8869fa94a07fSbrendan 
8870fa94a07fSbrendan 	l2arc_dev_list = &L2ARC_dev_list;
8871fa94a07fSbrendan 	l2arc_free_on_write = &L2ARC_free_on_write;
8872fa94a07fSbrendan 	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
8873fa94a07fSbrendan 	    offsetof(l2arc_dev_t, l2ad_node));
8874fa94a07fSbrendan 	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
8875fa94a07fSbrendan 	    offsetof(l2arc_data_free_t, l2df_list_node));
8876fa94a07fSbrendan }
8877fa94a07fSbrendan 
8878fa94a07fSbrendan void
8879e14bb325SJeff Bonwick l2arc_fini(void)
8880fa94a07fSbrendan {
88813a737e0dSbrendan 	/*
88823a737e0dSbrendan 	 * This is called from dmu_fini(), which is called from spa_fini();
88833a737e0dSbrendan 	 * Because of this, we can assume that all l2arc devices have
88843a737e0dSbrendan 	 * already been removed when the pools themselves were removed.
88853a737e0dSbrendan 	 */
88863a737e0dSbrendan 
88873a737e0dSbrendan 	l2arc_do_free_on_write();
88883a737e0dSbrendan 
8889fa94a07fSbrendan 	mutex_destroy(&l2arc_feed_thr_lock);
8890fa94a07fSbrendan 	cv_destroy(&l2arc_feed_thr_cv);
8891fa94a07fSbrendan 	mutex_destroy(&l2arc_dev_mtx);
8892fa94a07fSbrendan 	mutex_destroy(&l2arc_free_on_write_mtx);
8893fa94a07fSbrendan 
8894fa94a07fSbrendan 	list_destroy(l2arc_dev_list);
8895fa94a07fSbrendan 	list_destroy(l2arc_free_on_write);
8896fa94a07fSbrendan }
8897e14bb325SJeff Bonwick 
8898e14bb325SJeff Bonwick void
8899e14bb325SJeff Bonwick l2arc_start(void)
8900e14bb325SJeff Bonwick {
89018ad4d6ddSJeff Bonwick 	if (!(spa_mode_global & FWRITE))
8902e14bb325SJeff Bonwick 		return;
8903e14bb325SJeff Bonwick 
8904e14bb325SJeff Bonwick 	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
8905e14bb325SJeff Bonwick 	    TS_RUN, minclsyspri);
8906e14bb325SJeff Bonwick }
8907e14bb325SJeff Bonwick 
8908e14bb325SJeff Bonwick void
8909e14bb325SJeff Bonwick l2arc_stop(void)
8910e14bb325SJeff Bonwick {
89118ad4d6ddSJeff Bonwick 	if (!(spa_mode_global & FWRITE))
8912e14bb325SJeff Bonwick 		return;
8913e14bb325SJeff Bonwick 
8914e14bb325SJeff Bonwick 	mutex_enter(&l2arc_feed_thr_lock);
8915e14bb325SJeff Bonwick 	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
8916e14bb325SJeff Bonwick 	l2arc_thread_exit = 1;
8917e14bb325SJeff Bonwick 	while (l2arc_thread_exit != 0)
8918e14bb325SJeff Bonwick 		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
8919e14bb325SJeff Bonwick 	mutex_exit(&l2arc_feed_thr_lock);
8920e14bb325SJeff Bonwick }
8921