]> git.proxmox.com Git - mirror_zfs.git/blame - module/zfs/arc.c
ZIL: Fix race introduced by f63811f0721.
[mirror_zfs.git] / module / zfs / arc.c
CommitLineData
34dc7c2f
BB
1/*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
1d3ba0bf 9 * or https://opensource.org/licenses/CDDL-1.0.
34dc7c2f
BB
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21/*
428870ff 22 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
3ec34e55 23 * Copyright (c) 2018, Joyent, Inc.
4f072827 24 * Copyright (c) 2011, 2020, Delphix. All rights reserved.
77f6826b
GA
25 * Copyright (c) 2014, Saso Kiselkov. All rights reserved.
26 * Copyright (c) 2017, Nexenta Systems, Inc. All rights reserved.
e3570464 27 * Copyright (c) 2019, loli10K <ezomori.nozomu@gmail.com>. All rights reserved.
77f6826b 28 * Copyright (c) 2020, George Amanakis. All rights reserved.
10b3c7f5
MN
29 * Copyright (c) 2019, Klara Inc.
30 * Copyright (c) 2019, Allan Jude
fc34dfba
AJ
31 * Copyright (c) 2020, The FreeBSD Foundation [1]
32 *
33 * [1] Portions of this software were developed by Allan Jude
34 * under sponsorship from the FreeBSD Foundation.
34dc7c2f
BB
35 */
36
34dc7c2f
BB
37/*
38 * DVA-based Adjustable Replacement Cache
39 *
40 * While much of the theory of operation used here is
41 * based on the self-tuning, low overhead replacement cache
42 * presented by Megiddo and Modha at FAST 2003, there are some
43 * significant differences:
44 *
45 * 1. The Megiddo and Modha model assumes any page is evictable.
46 * Pages in its cache cannot be "locked" into memory. This makes
47 * the eviction algorithm simple: evict the last page in the list.
48 * This also make the performance characteristics easy to reason
49 * about. Our cache is not so simple. At any given moment, some
50 * subset of the blocks in the cache are un-evictable because we
51 * have handed out a reference to them. Blocks are only evictable
52 * when there are no external references active. This makes
53 * eviction far more problematic: we choose to evict the evictable
54 * blocks that are the "lowest" in the list.
55 *
56 * There are times when it is not possible to evict the requested
57 * space. In these circumstances we are unable to adjust the cache
58 * size. To prevent the cache growing unbounded at these times we
59 * implement a "cache throttle" that slows the flow of new data
60 * into the cache until we can make space available.
61 *
62 * 2. The Megiddo and Modha model assumes a fixed cache size.
63 * Pages are evicted when the cache is full and there is a cache
64 * miss. Our model has a variable sized cache. It grows with
65 * high use, but also tries to react to memory pressure from the
66 * operating system: decreasing its size when system memory is
67 * tight.
68 *
69 * 3. The Megiddo and Modha model assumes a fixed page size. All
d3cc8b15 70 * elements of the cache are therefore exactly the same size. So
34dc7c2f
BB
71 * when adjusting the cache size following a cache miss, its simply
72 * a matter of choosing a single page to evict. In our model, we
e1cfd73f 73 * have variable sized cache blocks (ranging from 512 bytes to
d3cc8b15 74 * 128K bytes). We therefore choose a set of blocks to evict to make
34dc7c2f
BB
75 * space for a cache miss that approximates as closely as possible
76 * the space used by the new block.
77 *
78 * See also: "ARC: A Self-Tuning, Low Overhead Replacement Cache"
79 * by N. Megiddo & D. Modha, FAST 2003
80 */
81
82/*
83 * The locking model:
84 *
85 * A new reference to a cache buffer can be obtained in two
86 * ways: 1) via a hash table lookup using the DVA as a key,
87 * or 2) via one of the ARC lists. The arc_read() interface
2aa34383 88 * uses method 1, while the internal ARC algorithms for
d3cc8b15 89 * adjusting the cache use method 2. We therefore provide two
34dc7c2f 90 * types of locks: 1) the hash table lock array, and 2) the
2aa34383 91 * ARC list locks.
34dc7c2f 92 *
5c839890
BC
93 * Buffers do not have their own mutexes, rather they rely on the
94 * hash table mutexes for the bulk of their protection (i.e. most
95 * fields in the arc_buf_hdr_t are protected by these mutexes).
34dc7c2f
BB
96 *
97 * buf_hash_find() returns the appropriate mutex (held) when it
98 * locates the requested buffer in the hash table. It returns
99 * NULL for the mutex if the buffer was not in the table.
100 *
101 * buf_hash_remove() expects the appropriate hash mutex to be
102 * already held before it is invoked.
103 *
2aa34383 104 * Each ARC state also has a mutex which is used to protect the
34dc7c2f 105 * buffer list associated with the state. When attempting to
2aa34383 106 * obtain a hash table lock while holding an ARC list lock you
34dc7c2f
BB
107 * must use: mutex_tryenter() to avoid deadlock. Also note that
108 * the active state mutex must be held before the ghost state mutex.
109 *
ab26409d 110 * It as also possible to register a callback which is run when the
a8d83e2a 111 * metadata limit is reached and no buffers can be safely evicted. In
ab26409d 112 * this case the arc user should drop a reference on some arc buffers so
a8d83e2a
AM
113 * they can be reclaimed. For example, when using the ZPL each dentry
114 * holds a references on a znode. These dentries must be pruned before
115 * the arc buffer holding the znode can be safely evicted.
ab26409d 116 *
34dc7c2f
BB
117 * Note that the majority of the performance stats are manipulated
118 * with atomic operations.
119 *
b9541d6b 120 * The L2ARC uses the l2ad_mtx on each vdev for the following:
34dc7c2f
BB
121 *
122 * - L2ARC buflist creation
123 * - L2ARC buflist eviction
124 * - L2ARC write completion, which walks L2ARC buflists
125 * - ARC header destruction, as it removes from L2ARC buflists
126 * - ARC header release, as it removes from L2ARC buflists
127 */
128
d3c2ae1c
GW
129/*
130 * ARC operation:
131 *
132 * Every block that is in the ARC is tracked by an arc_buf_hdr_t structure.
133 * This structure can point either to a block that is still in the cache or to
134 * one that is only accessible in an L2 ARC device, or it can provide
135 * information about a block that was recently evicted. If a block is
136 * only accessible in the L2ARC, then the arc_buf_hdr_t only has enough
137 * information to retrieve it from the L2ARC device. This information is
138 * stored in the l2arc_buf_hdr_t sub-structure of the arc_buf_hdr_t. A block
139 * that is in this state cannot access the data directly.
140 *
141 * Blocks that are actively being referenced or have not been evicted
142 * are cached in the L1ARC. The L1ARC (l1arc_buf_hdr_t) is a structure within
143 * the arc_buf_hdr_t that will point to the data block in memory. A block can
144 * only be read by a consumer if it has an l1arc_buf_hdr_t. The L1ARC
2aa34383 145 * caches data in two ways -- in a list of ARC buffers (arc_buf_t) and
a6255b7f 146 * also in the arc_buf_hdr_t's private physical data block pointer (b_pabd).
2aa34383
DK
147 *
148 * The L1ARC's data pointer may or may not be uncompressed. The ARC has the
a6255b7f
DQ
149 * ability to store the physical data (b_pabd) associated with the DVA of the
150 * arc_buf_hdr_t. Since the b_pabd is a copy of the on-disk physical block,
2aa34383
DK
151 * it will match its on-disk compression characteristics. This behavior can be
152 * disabled by setting 'zfs_compressed_arc_enabled' to B_FALSE. When the
a6255b7f 153 * compressed ARC functionality is disabled, the b_pabd will point to an
2aa34383
DK
154 * uncompressed version of the on-disk data.
155 *
156 * Data in the L1ARC is not accessed by consumers of the ARC directly. Each
157 * arc_buf_hdr_t can have multiple ARC buffers (arc_buf_t) which reference it.
158 * Each ARC buffer (arc_buf_t) is being actively accessed by a specific ARC
159 * consumer. The ARC will provide references to this data and will keep it
160 * cached until it is no longer in use. The ARC caches only the L1ARC's physical
161 * data block and will evict any arc_buf_t that is no longer referenced. The
162 * amount of memory consumed by the arc_buf_ts' data buffers can be seen via the
d3c2ae1c
GW
163 * "overhead_size" kstat.
164 *
2aa34383
DK
165 * Depending on the consumer, an arc_buf_t can be requested in uncompressed or
166 * compressed form. The typical case is that consumers will want uncompressed
167 * data, and when that happens a new data buffer is allocated where the data is
168 * decompressed for them to use. Currently the only consumer who wants
169 * compressed arc_buf_t's is "zfs send", when it streams data exactly as it
170 * exists on disk. When this happens, the arc_buf_t's data buffer is shared
171 * with the arc_buf_hdr_t.
d3c2ae1c 172 *
2aa34383
DK
173 * Here is a diagram showing an arc_buf_hdr_t referenced by two arc_buf_t's. The
174 * first one is owned by a compressed send consumer (and therefore references
175 * the same compressed data buffer as the arc_buf_hdr_t) and the second could be
176 * used by any other consumer (and has its own uncompressed copy of the data
177 * buffer).
d3c2ae1c 178 *
2aa34383
DK
179 * arc_buf_hdr_t
180 * +-----------+
181 * | fields |
182 * | common to |
183 * | L1- and |
184 * | L2ARC |
185 * +-----------+
186 * | l2arc_buf_hdr_t
187 * | |
188 * +-----------+
189 * | l1arc_buf_hdr_t
190 * | | arc_buf_t
191 * | b_buf +------------>+-----------+ arc_buf_t
a6255b7f 192 * | b_pabd +-+ |b_next +---->+-----------+
2aa34383
DK
193 * +-----------+ | |-----------| |b_next +-->NULL
194 * | |b_comp = T | +-----------+
195 * | |b_data +-+ |b_comp = F |
196 * | +-----------+ | |b_data +-+
197 * +->+------+ | +-----------+ |
198 * compressed | | | |
199 * data | |<--------------+ | uncompressed
200 * +------+ compressed, | data
201 * shared +-->+------+
202 * data | |
203 * | |
204 * +------+
d3c2ae1c
GW
205 *
206 * When a consumer reads a block, the ARC must first look to see if the
2aa34383
DK
207 * arc_buf_hdr_t is cached. If the hdr is cached then the ARC allocates a new
208 * arc_buf_t and either copies uncompressed data into a new data buffer from an
a6255b7f
DQ
209 * existing uncompressed arc_buf_t, decompresses the hdr's b_pabd buffer into a
210 * new data buffer, or shares the hdr's b_pabd buffer, depending on whether the
2aa34383
DK
211 * hdr is compressed and the desired compression characteristics of the
212 * arc_buf_t consumer. If the arc_buf_t ends up sharing data with the
213 * arc_buf_hdr_t and both of them are uncompressed then the arc_buf_t must be
214 * the last buffer in the hdr's b_buf list, however a shared compressed buf can
215 * be anywhere in the hdr's list.
d3c2ae1c
GW
216 *
217 * The diagram below shows an example of an uncompressed ARC hdr that is
2aa34383
DK
218 * sharing its data with an arc_buf_t (note that the shared uncompressed buf is
219 * the last element in the buf list):
d3c2ae1c
GW
220 *
221 * arc_buf_hdr_t
222 * +-----------+
223 * | |
224 * | |
225 * | |
226 * +-----------+
227 * l2arc_buf_hdr_t| |
228 * | |
229 * +-----------+
230 * l1arc_buf_hdr_t| |
231 * | | arc_buf_t (shared)
232 * | b_buf +------------>+---------+ arc_buf_t
233 * | | |b_next +---->+---------+
a6255b7f 234 * | b_pabd +-+ |---------| |b_next +-->NULL
d3c2ae1c
GW
235 * +-----------+ | | | +---------+
236 * | |b_data +-+ | |
237 * | +---------+ | |b_data +-+
238 * +->+------+ | +---------+ |
239 * | | | |
240 * uncompressed | | | |
241 * data +------+ | |
242 * ^ +->+------+ |
243 * | uncompressed | | |
244 * | data | | |
245 * | +------+ |
246 * +---------------------------------+
247 *
a6255b7f 248 * Writing to the ARC requires that the ARC first discard the hdr's b_pabd
d3c2ae1c 249 * since the physical block is about to be rewritten. The new data contents
2aa34383
DK
250 * will be contained in the arc_buf_t. As the I/O pipeline performs the write,
251 * it may compress the data before writing it to disk. The ARC will be called
861166b0 252 * with the transformed data and will memcpy the transformed on-disk block into
a6255b7f 253 * a newly allocated b_pabd. Writes are always done into buffers which have
2aa34383
DK
254 * either been loaned (and hence are new and don't have other readers) or
255 * buffers which have been released (and hence have their own hdr, if there
256 * were originally other readers of the buf's original hdr). This ensures that
257 * the ARC only needs to update a single buf and its hdr after a write occurs.
d3c2ae1c 258 *
a6255b7f
DQ
259 * When the L2ARC is in use, it will also take advantage of the b_pabd. The
260 * L2ARC will always write the contents of b_pabd to the L2ARC. This means
2aa34383 261 * that when compressed ARC is enabled that the L2ARC blocks are identical
d3c2ae1c
GW
262 * to the on-disk block in the main data pool. This provides a significant
263 * advantage since the ARC can leverage the bp's checksum when reading from the
264 * L2ARC to determine if the contents are valid. However, if the compressed
2aa34383 265 * ARC is disabled, then the L2ARC's block must be transformed to look
d3c2ae1c
GW
266 * like the physical block in the main data pool before comparing the
267 * checksum and determining its validity.
b5256303
TC
268 *
269 * The L1ARC has a slightly different system for storing encrypted data.
270 * Raw (encrypted + possibly compressed) data has a few subtle differences from
271 * data that is just compressed. The biggest difference is that it is not
e1cfd73f 272 * possible to decrypt encrypted data (or vice-versa) if the keys aren't loaded.
b5256303
TC
273 * The other difference is that encryption cannot be treated as a suggestion.
274 * If a caller would prefer compressed data, but they actually wind up with
275 * uncompressed data the worst thing that could happen is there might be a
276 * performance hit. If the caller requests encrypted data, however, we must be
277 * sure they actually get it or else secret information could be leaked. Raw
278 * data is stored in hdr->b_crypt_hdr.b_rabd. An encrypted header, therefore,
279 * may have both an encrypted version and a decrypted version of its data at
280 * once. When a caller needs a raw arc_buf_t, it is allocated and the data is
281 * copied out of this header. To avoid complications with b_pabd, raw buffers
282 * cannot be shared.
d3c2ae1c
GW
283 */
284
34dc7c2f
BB
285#include <sys/spa.h>
286#include <sys/zio.h>
d3c2ae1c 287#include <sys/spa_impl.h>
3a17a7a9 288#include <sys/zio_compress.h>
d3c2ae1c 289#include <sys/zio_checksum.h>
34dc7c2f
BB
290#include <sys/zfs_context.h>
291#include <sys/arc.h>
27d96d22 292#include <sys/zfs_refcount.h>
b128c09f 293#include <sys/vdev.h>
9babb374 294#include <sys/vdev_impl.h>
e8b96c60 295#include <sys/dsl_pool.h>
ca0bf58d 296#include <sys/multilist.h>
a6255b7f 297#include <sys/abd.h>
b5256303
TC
298#include <sys/zil.h>
299#include <sys/fm/fs/zfs.h>
34dc7c2f
BB
300#include <sys/callb.h>
301#include <sys/kstat.h>
3ec34e55 302#include <sys/zthr.h>
428870ff 303#include <zfs_fletcher.h>
59ec819a 304#include <sys/arc_impl.h>
e5d1c27e 305#include <sys/trace_zfs.h>
37fb3e43 306#include <sys/aggsum.h>
86706441 307#include <sys/wmsum.h>
3f387973 308#include <cityhash.h>
b7654bd7 309#include <sys/vdev_trim.h>
64e0fe14 310#include <sys/zfs_racct.h>
8a171ccd 311#include <sys/zstd/zstd.h>
34dc7c2f 312
498877ba
MA
313#ifndef _KERNEL
314/* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
315boolean_t arc_watch = B_FALSE;
316#endif
317
3ec34e55
BL
318/*
319 * This thread's job is to keep enough free memory in the system, by
320 * calling arc_kmem_reap_soon() plus arc_reduce_target_size(), which improves
321 * arc_available_memory().
322 */
3442c2a0 323static zthr_t *arc_reap_zthr;
3ec34e55
BL
324
325/*
326 * This thread's job is to keep arc_size under arc_c, by calling
5dd92909 327 * arc_evict(), which improves arc_is_overflowing().
3ec34e55 328 */
3442c2a0 329static zthr_t *arc_evict_zthr;
6e2a5918
MJ
330static arc_buf_hdr_t **arc_state_evict_markers;
331static int arc_state_evict_marker_count;
3ec34e55 332
3442c2a0
MA
333static kmutex_t arc_evict_lock;
334static boolean_t arc_evict_needed = B_FALSE;
ed2f7ba0 335static clock_t arc_last_uncached_flush;
3442c2a0
MA
336
337/*
338 * Count of bytes evicted since boot.
339 */
340static uint64_t arc_evict_count;
341
342/*
343 * List of arc_evict_waiter_t's, representing threads waiting for the
344 * arc_evict_count to reach specific values.
345 */
346static list_t arc_evict_waiters;
347
348/*
349 * When arc_is_overflowing(), arc_get_data_impl() waits for this percent of
350 * the requested amount of data to be evicted. For example, by default for
351 * every 2KB that's evicted, 1KB of it may be "reused" by a new allocation.
352 * Since this is above 100%, it ensures that progress is made towards getting
353 * arc_size under arc_c. Since this is finite, it ensures that allocations
354 * can still happen, even during the potentially long time that arc_size is
355 * more than arc_c.
356 */
fdc2d303 357static uint_t zfs_arc_eviction_pct = 200;
ca0bf58d 358
e8b96c60 359/*
ca0bf58d
PS
360 * The number of headers to evict in arc_evict_state_impl() before
361 * dropping the sublist lock and evicting from another sublist. A lower
362 * value means we're more likely to evict the "correct" header (i.e. the
363 * oldest header in the arc state), but comes with higher overhead
364 * (i.e. more invocations of arc_evict_state_impl()).
365 */
fdc2d303 366static uint_t zfs_arc_evict_batch_limit = 10;
ca0bf58d 367
34dc7c2f 368/* number of seconds before growing cache again */
fdc2d303 369uint_t arc_grow_retry = 5;
3ec34e55
BL
370
371/*
372 * Minimum time between calls to arc_kmem_reap_soon().
373 */
18168da7 374static const int arc_kmem_cache_reap_retry_ms = 1000;
34dc7c2f 375
a6255b7f 376/* shift of arc_c for calculating overflow limit in arc_get_data_impl */
18168da7 377static int zfs_arc_overflow_shift = 8;
62422785 378
d164b209 379/* log2(fraction of arc to reclaim) */
fdc2d303 380uint_t arc_shrink_shift = 7;
d164b209 381
03b60eee
DB
382/* percent of pagecache to reclaim arc to */
383#ifdef _KERNEL
c9c9c1e2 384uint_t zfs_arc_pc_percent = 0;
03b60eee
DB
385#endif
386
34dc7c2f 387/*
ca67b33a
MA
388 * log2(fraction of ARC which must be free to allow growing).
389 * I.e. If there is less than arc_c >> arc_no_grow_shift free memory,
390 * when reading a new block into the ARC, we will evict an equal-sized block
391 * from the ARC.
392 *
393 * This must be less than arc_shrink_shift, so that when we shrink the ARC,
394 * we will still not allow it to grow.
34dc7c2f 395 */
fdc2d303 396uint_t arc_no_grow_shift = 5;
bce45ec9 397
49ddb315 398
ca0bf58d
PS
399/*
400 * minimum lifespan of a prefetch block in clock ticks
401 * (initialized in arc_init())
402 */
fdc2d303
RY
403static uint_t arc_min_prefetch_ms;
404static uint_t arc_min_prescient_prefetch_ms;
ca0bf58d 405
e8b96c60
MA
406/*
407 * If this percent of memory is free, don't throttle.
408 */
fdc2d303 409uint_t arc_lotsfree_percent = 10;
e8b96c60 410
b128c09f
BB
411/*
412 * The arc has filled available memory and has now warmed up.
413 */
c9c9c1e2 414boolean_t arc_warm;
b128c09f 415
34dc7c2f
BB
416/*
417 * These tunables are for performance analysis.
418 */
ab8d9c17
RY
419uint64_t zfs_arc_max = 0;
420uint64_t zfs_arc_min = 0;
ab8d9c17
RY
421static uint64_t zfs_arc_dnode_limit = 0;
422static uint_t zfs_arc_dnode_reduce_percent = 10;
fdc2d303
RY
423static uint_t zfs_arc_grow_retry = 0;
424static uint_t zfs_arc_shrink_shift = 0;
fdc2d303 425uint_t zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
34dc7c2f 426
dae3e9ea 427/*
18168da7
AZ
428 * ARC dirty data constraints for arc_tempreserve_space() throttle:
429 * * total dirty data limit
430 * * anon block dirty limit
431 * * each pool's anon allowance
dae3e9ea 432 */
18168da7
AZ
433static const unsigned long zfs_arc_dirty_limit_percent = 50;
434static const unsigned long zfs_arc_anon_limit_percent = 25;
435static const unsigned long zfs_arc_pool_dirty_percent = 20;
dae3e9ea
DB
436
437/*
438 * Enable or disable compressed arc buffers.
439 */
d3c2ae1c
GW
440int zfs_compressed_arc_enabled = B_TRUE;
441
9907cc1c 442/*
a8d83e2a
AM
443 * Balance between metadata and data on ghost hits. Values above 100
444 * increase metadata caching by proportionally reducing effect of ghost
445 * data hits on target data/metadata rate.
9907cc1c 446 */
a8d83e2a 447static uint_t zfs_arc_meta_balance = 500;
9907cc1c
G
448
449/*
450 * Percentage that can be consumed by dnodes of ARC meta buffers.
451 */
ab8d9c17 452static uint_t zfs_arc_dnode_limit_percent = 10;
9907cc1c 453
bc888666 454/*
18168da7 455 * These tunables are Linux-specific
bc888666 456 */
ab8d9c17 457static uint64_t zfs_arc_sys_free = 0;
fdc2d303
RY
458static uint_t zfs_arc_min_prefetch_ms = 0;
459static uint_t zfs_arc_min_prescient_prefetch_ms = 0;
fdc2d303 460static uint_t zfs_arc_lotsfree_percent = 10;
bc888666 461
462217d1
AM
462/*
463 * Number of arc_prune threads
464 */
465static int zfs_arc_prune_task_threads = 1;
466
ed2f7ba0 467/* The 7 states: */
13a4027a
MM
468arc_state_t ARC_anon;
469arc_state_t ARC_mru;
470arc_state_t ARC_mru_ghost;
471arc_state_t ARC_mfu;
472arc_state_t ARC_mfu_ghost;
473arc_state_t ARC_l2c_only;
ed2f7ba0 474arc_state_t ARC_uncached;
34dc7c2f 475
c9c9c1e2 476arc_stats_t arc_stats = {
34dc7c2f 477 { "hits", KSTAT_DATA_UINT64 },
c935fe2e 478 { "iohits", KSTAT_DATA_UINT64 },
34dc7c2f
BB
479 { "misses", KSTAT_DATA_UINT64 },
480 { "demand_data_hits", KSTAT_DATA_UINT64 },
c935fe2e 481 { "demand_data_iohits", KSTAT_DATA_UINT64 },
34dc7c2f
BB
482 { "demand_data_misses", KSTAT_DATA_UINT64 },
483 { "demand_metadata_hits", KSTAT_DATA_UINT64 },
c935fe2e 484 { "demand_metadata_iohits", KSTAT_DATA_UINT64 },
34dc7c2f
BB
485 { "demand_metadata_misses", KSTAT_DATA_UINT64 },
486 { "prefetch_data_hits", KSTAT_DATA_UINT64 },
c935fe2e 487 { "prefetch_data_iohits", KSTAT_DATA_UINT64 },
34dc7c2f
BB
488 { "prefetch_data_misses", KSTAT_DATA_UINT64 },
489 { "prefetch_metadata_hits", KSTAT_DATA_UINT64 },
c935fe2e 490 { "prefetch_metadata_iohits", KSTAT_DATA_UINT64 },
34dc7c2f
BB
491 { "prefetch_metadata_misses", KSTAT_DATA_UINT64 },
492 { "mru_hits", KSTAT_DATA_UINT64 },
493 { "mru_ghost_hits", KSTAT_DATA_UINT64 },
494 { "mfu_hits", KSTAT_DATA_UINT64 },
495 { "mfu_ghost_hits", KSTAT_DATA_UINT64 },
ed2f7ba0 496 { "uncached_hits", KSTAT_DATA_UINT64 },
34dc7c2f 497 { "deleted", KSTAT_DATA_UINT64 },
34dc7c2f 498 { "mutex_miss", KSTAT_DATA_UINT64 },
0873bb63 499 { "access_skip", KSTAT_DATA_UINT64 },
34dc7c2f 500 { "evict_skip", KSTAT_DATA_UINT64 },
ca0bf58d 501 { "evict_not_enough", KSTAT_DATA_UINT64 },
428870ff
BB
502 { "evict_l2_cached", KSTAT_DATA_UINT64 },
503 { "evict_l2_eligible", KSTAT_DATA_UINT64 },
08532162
GA
504 { "evict_l2_eligible_mfu", KSTAT_DATA_UINT64 },
505 { "evict_l2_eligible_mru", KSTAT_DATA_UINT64 },
428870ff 506 { "evict_l2_ineligible", KSTAT_DATA_UINT64 },
ca0bf58d 507 { "evict_l2_skip", KSTAT_DATA_UINT64 },
34dc7c2f
BB
508 { "hash_elements", KSTAT_DATA_UINT64 },
509 { "hash_elements_max", KSTAT_DATA_UINT64 },
510 { "hash_collisions", KSTAT_DATA_UINT64 },
511 { "hash_chains", KSTAT_DATA_UINT64 },
512 { "hash_chain_max", KSTAT_DATA_UINT64 },
a8d83e2a
AM
513 { "meta", KSTAT_DATA_UINT64 },
514 { "pd", KSTAT_DATA_UINT64 },
515 { "pm", KSTAT_DATA_UINT64 },
34dc7c2f
BB
516 { "c", KSTAT_DATA_UINT64 },
517 { "c_min", KSTAT_DATA_UINT64 },
518 { "c_max", KSTAT_DATA_UINT64 },
519 { "size", KSTAT_DATA_UINT64 },
d3c2ae1c
GW
520 { "compressed_size", KSTAT_DATA_UINT64 },
521 { "uncompressed_size", KSTAT_DATA_UINT64 },
522 { "overhead_size", KSTAT_DATA_UINT64 },
34dc7c2f 523 { "hdr_size", KSTAT_DATA_UINT64 },
d164b209 524 { "data_size", KSTAT_DATA_UINT64 },
500445c0 525 { "metadata_size", KSTAT_DATA_UINT64 },
25458cbe
TC
526 { "dbuf_size", KSTAT_DATA_UINT64 },
527 { "dnode_size", KSTAT_DATA_UINT64 },
528 { "bonus_size", KSTAT_DATA_UINT64 },
1c2725a1
MM
529#if defined(COMPAT_FREEBSD11)
530 { "other_size", KSTAT_DATA_UINT64 },
531#endif
13be560d 532 { "anon_size", KSTAT_DATA_UINT64 },
a8d83e2a
AM
533 { "anon_data", KSTAT_DATA_UINT64 },
534 { "anon_metadata", KSTAT_DATA_UINT64 },
500445c0
PS
535 { "anon_evictable_data", KSTAT_DATA_UINT64 },
536 { "anon_evictable_metadata", KSTAT_DATA_UINT64 },
13be560d 537 { "mru_size", KSTAT_DATA_UINT64 },
a8d83e2a
AM
538 { "mru_data", KSTAT_DATA_UINT64 },
539 { "mru_metadata", KSTAT_DATA_UINT64 },
500445c0
PS
540 { "mru_evictable_data", KSTAT_DATA_UINT64 },
541 { "mru_evictable_metadata", KSTAT_DATA_UINT64 },
13be560d 542 { "mru_ghost_size", KSTAT_DATA_UINT64 },
a8d83e2a
AM
543 { "mru_ghost_data", KSTAT_DATA_UINT64 },
544 { "mru_ghost_metadata", KSTAT_DATA_UINT64 },
500445c0
PS
545 { "mru_ghost_evictable_data", KSTAT_DATA_UINT64 },
546 { "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
13be560d 547 { "mfu_size", KSTAT_DATA_UINT64 },
a8d83e2a
AM
548 { "mfu_data", KSTAT_DATA_UINT64 },
549 { "mfu_metadata", KSTAT_DATA_UINT64 },
500445c0
PS
550 { "mfu_evictable_data", KSTAT_DATA_UINT64 },
551 { "mfu_evictable_metadata", KSTAT_DATA_UINT64 },
13be560d 552 { "mfu_ghost_size", KSTAT_DATA_UINT64 },
a8d83e2a
AM
553 { "mfu_ghost_data", KSTAT_DATA_UINT64 },
554 { "mfu_ghost_metadata", KSTAT_DATA_UINT64 },
500445c0
PS
555 { "mfu_ghost_evictable_data", KSTAT_DATA_UINT64 },
556 { "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
ed2f7ba0 557 { "uncached_size", KSTAT_DATA_UINT64 },
a8d83e2a
AM
558 { "uncached_data", KSTAT_DATA_UINT64 },
559 { "uncached_metadata", KSTAT_DATA_UINT64 },
ed2f7ba0
AM
560 { "uncached_evictable_data", KSTAT_DATA_UINT64 },
561 { "uncached_evictable_metadata", KSTAT_DATA_UINT64 },
34dc7c2f
BB
562 { "l2_hits", KSTAT_DATA_UINT64 },
563 { "l2_misses", KSTAT_DATA_UINT64 },
08532162
GA
564 { "l2_prefetch_asize", KSTAT_DATA_UINT64 },
565 { "l2_mru_asize", KSTAT_DATA_UINT64 },
566 { "l2_mfu_asize", KSTAT_DATA_UINT64 },
567 { "l2_bufc_data_asize", KSTAT_DATA_UINT64 },
568 { "l2_bufc_metadata_asize", KSTAT_DATA_UINT64 },
34dc7c2f
BB
569 { "l2_feeds", KSTAT_DATA_UINT64 },
570 { "l2_rw_clash", KSTAT_DATA_UINT64 },
d164b209
BB
571 { "l2_read_bytes", KSTAT_DATA_UINT64 },
572 { "l2_write_bytes", KSTAT_DATA_UINT64 },
34dc7c2f
BB
573 { "l2_writes_sent", KSTAT_DATA_UINT64 },
574 { "l2_writes_done", KSTAT_DATA_UINT64 },
575 { "l2_writes_error", KSTAT_DATA_UINT64 },
ca0bf58d 576 { "l2_writes_lock_retry", KSTAT_DATA_UINT64 },
34dc7c2f
BB
577 { "l2_evict_lock_retry", KSTAT_DATA_UINT64 },
578 { "l2_evict_reading", KSTAT_DATA_UINT64 },
b9541d6b 579 { "l2_evict_l1cached", KSTAT_DATA_UINT64 },
34dc7c2f
BB
580 { "l2_free_on_write", KSTAT_DATA_UINT64 },
581 { "l2_abort_lowmem", KSTAT_DATA_UINT64 },
582 { "l2_cksum_bad", KSTAT_DATA_UINT64 },
583 { "l2_io_error", KSTAT_DATA_UINT64 },
584 { "l2_size", KSTAT_DATA_UINT64 },
3a17a7a9 585 { "l2_asize", KSTAT_DATA_UINT64 },
34dc7c2f 586 { "l2_hdr_size", KSTAT_DATA_UINT64 },
77f6826b 587 { "l2_log_blk_writes", KSTAT_DATA_UINT64 },
657fd33b
GA
588 { "l2_log_blk_avg_asize", KSTAT_DATA_UINT64 },
589 { "l2_log_blk_asize", KSTAT_DATA_UINT64 },
590 { "l2_log_blk_count", KSTAT_DATA_UINT64 },
77f6826b
GA
591 { "l2_data_to_meta_ratio", KSTAT_DATA_UINT64 },
592 { "l2_rebuild_success", KSTAT_DATA_UINT64 },
593 { "l2_rebuild_unsupported", KSTAT_DATA_UINT64 },
594 { "l2_rebuild_io_errors", KSTAT_DATA_UINT64 },
595 { "l2_rebuild_dh_errors", KSTAT_DATA_UINT64 },
596 { "l2_rebuild_cksum_lb_errors", KSTAT_DATA_UINT64 },
597 { "l2_rebuild_lowmem", KSTAT_DATA_UINT64 },
598 { "l2_rebuild_size", KSTAT_DATA_UINT64 },
657fd33b 599 { "l2_rebuild_asize", KSTAT_DATA_UINT64 },
77f6826b
GA
600 { "l2_rebuild_bufs", KSTAT_DATA_UINT64 },
601 { "l2_rebuild_bufs_precached", KSTAT_DATA_UINT64 },
77f6826b 602 { "l2_rebuild_log_blks", KSTAT_DATA_UINT64 },
1834f2d8 603 { "memory_throttle_count", KSTAT_DATA_UINT64 },
7cb67b45
BB
604 { "memory_direct_count", KSTAT_DATA_UINT64 },
605 { "memory_indirect_count", KSTAT_DATA_UINT64 },
70f02287
BB
606 { "memory_all_bytes", KSTAT_DATA_UINT64 },
607 { "memory_free_bytes", KSTAT_DATA_UINT64 },
608 { "memory_available_bytes", KSTAT_DATA_INT64 },
1834f2d8
BB
609 { "arc_no_grow", KSTAT_DATA_UINT64 },
610 { "arc_tempreserve", KSTAT_DATA_UINT64 },
611 { "arc_loaned_bytes", KSTAT_DATA_UINT64 },
ab26409d 612 { "arc_prune", KSTAT_DATA_UINT64 },
1834f2d8 613 { "arc_meta_used", KSTAT_DATA_UINT64 },
25458cbe 614 { "arc_dnode_limit", KSTAT_DATA_UINT64 },
a8b2e306 615 { "async_upgrade_sync", KSTAT_DATA_UINT64 },
c935fe2e 616 { "predictive_prefetch", KSTAT_DATA_UINT64 },
7f60329a 617 { "demand_hit_predictive_prefetch", KSTAT_DATA_UINT64 },
c935fe2e
AM
618 { "demand_iohit_predictive_prefetch", KSTAT_DATA_UINT64 },
619 { "prescient_prefetch", KSTAT_DATA_UINT64 },
d4a72f23 620 { "demand_hit_prescient_prefetch", KSTAT_DATA_UINT64 },
c935fe2e 621 { "demand_iohit_prescient_prefetch", KSTAT_DATA_UINT64 },
11f552fa 622 { "arc_need_free", KSTAT_DATA_UINT64 },
b5256303 623 { "arc_sys_free", KSTAT_DATA_UINT64 },
1dc32a67
MA
624 { "arc_raw_size", KSTAT_DATA_UINT64 },
625 { "cached_only_in_progress", KSTAT_DATA_UINT64 },
85ec5cba 626 { "abd_chunk_waste_size", KSTAT_DATA_UINT64 },
34dc7c2f
BB
627};
628
c4c162c1
AM
629arc_sums_t arc_sums;
630
34dc7c2f
BB
631#define ARCSTAT_MAX(stat, val) { \
632 uint64_t m; \
633 while ((val) > (m = arc_stats.stat.value.ui64) && \
634 (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val)))) \
635 continue; \
636}
637
34dc7c2f
BB
638/*
639 * We define a macro to allow ARC hits/misses to be easily broken down by
640 * two separate conditions, giving a total of four different subtypes for
641 * each of hits and misses (so eight statistics total).
642 */
643#define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
644 if (cond1) { \
645 if (cond2) { \
646 ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
647 } else { \
648 ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
649 } \
650 } else { \
651 if (cond2) { \
652 ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
653 } else { \
654 ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
655 } \
656 }
657
77f6826b
GA
658/*
659 * This macro allows us to use kstats as floating averages. Each time we
660 * update this kstat, we first factor it and the update value by
661 * ARCSTAT_AVG_FACTOR to shrink the new value's contribution to the overall
662 * average. This macro assumes that integer loads and stores are atomic, but
663 * is not safe for multiple writers updating the kstat in parallel (only the
664 * last writer's update will remain).
665 */
666#define ARCSTAT_F_AVG_FACTOR 3
667#define ARCSTAT_F_AVG(stat, value) \
668 do { \
669 uint64_t x = ARCSTAT(stat); \
670 x = x - x / ARCSTAT_F_AVG_FACTOR + \
671 (value) / ARCSTAT_F_AVG_FACTOR; \
672 ARCSTAT(stat) = x; \
77f6826b
GA
673 } while (0)
674
18168da7 675static kstat_t *arc_ksp;
c9c9c1e2 676
34dc7c2f
BB
677/*
678 * There are several ARC variables that are critical to export as kstats --
679 * but we don't want to have to grovel around in the kstat whenever we wish to
680 * manipulate them. For these variables, we therefore define them to be in
681 * terms of the statistic variable. This assures that we are not introducing
682 * the possibility of inconsistency by having shadow copies of the variables,
683 * while still allowing the code to be readable.
684 */
1834f2d8
BB
685#define arc_tempreserve ARCSTAT(arcstat_tempreserve)
686#define arc_loaned_bytes ARCSTAT(arcstat_loaned_bytes)
a8d83e2a 687#define arc_dnode_limit ARCSTAT(arcstat_dnode_limit) /* max size for dnodes */
3442c2a0 688#define arc_need_free ARCSTAT(arcstat_need_free) /* waiting to be evicted */
34dc7c2f 689
c9c9c1e2
MM
690hrtime_t arc_growtime;
691list_t arc_prune_list;
692kmutex_t arc_prune_mtx;
693taskq_t *arc_prune_taskq;
428870ff 694
34dc7c2f
BB
695#define GHOST_STATE(state) \
696 ((state) == arc_mru_ghost || (state) == arc_mfu_ghost || \
697 (state) == arc_l2c_only)
698
2a432414
GW
699#define HDR_IN_HASH_TABLE(hdr) ((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
700#define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
701#define HDR_IO_ERROR(hdr) ((hdr)->b_flags & ARC_FLAG_IO_ERROR)
702#define HDR_PREFETCH(hdr) ((hdr)->b_flags & ARC_FLAG_PREFETCH)
d4a72f23
TC
703#define HDR_PRESCIENT_PREFETCH(hdr) \
704 ((hdr)->b_flags & ARC_FLAG_PRESCIENT_PREFETCH)
d3c2ae1c
GW
705#define HDR_COMPRESSION_ENABLED(hdr) \
706 ((hdr)->b_flags & ARC_FLAG_COMPRESSED_ARC)
b9541d6b 707
2a432414 708#define HDR_L2CACHE(hdr) ((hdr)->b_flags & ARC_FLAG_L2CACHE)
ed2f7ba0 709#define HDR_UNCACHED(hdr) ((hdr)->b_flags & ARC_FLAG_UNCACHED)
2a432414 710#define HDR_L2_READING(hdr) \
d3c2ae1c
GW
711 (((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) && \
712 ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
2a432414
GW
713#define HDR_L2_WRITING(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITING)
714#define HDR_L2_EVICTED(hdr) ((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
715#define HDR_L2_WRITE_HEAD(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
b5256303
TC
716#define HDR_PROTECTED(hdr) ((hdr)->b_flags & ARC_FLAG_PROTECTED)
717#define HDR_NOAUTH(hdr) ((hdr)->b_flags & ARC_FLAG_NOAUTH)
d3c2ae1c 718#define HDR_SHARED_DATA(hdr) ((hdr)->b_flags & ARC_FLAG_SHARED_DATA)
34dc7c2f 719
b9541d6b 720#define HDR_ISTYPE_METADATA(hdr) \
d3c2ae1c 721 ((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
b9541d6b
CW
722#define HDR_ISTYPE_DATA(hdr) (!HDR_ISTYPE_METADATA(hdr))
723
724#define HDR_HAS_L1HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
725#define HDR_HAS_L2HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
b5256303
TC
726#define HDR_HAS_RABD(hdr) \
727 (HDR_HAS_L1HDR(hdr) && HDR_PROTECTED(hdr) && \
728 (hdr)->b_crypt_hdr.b_rabd != NULL)
729#define HDR_ENCRYPTED(hdr) \
730 (HDR_PROTECTED(hdr) && DMU_OT_IS_ENCRYPTED((hdr)->b_crypt_hdr.b_ot))
731#define HDR_AUTHENTICATED(hdr) \
732 (HDR_PROTECTED(hdr) && !DMU_OT_IS_ENCRYPTED((hdr)->b_crypt_hdr.b_ot))
b9541d6b 733
d3c2ae1c
GW
734/* For storing compression mode in b_flags */
735#define HDR_COMPRESS_OFFSET (highbit64(ARC_FLAG_COMPRESS_0) - 1)
736
737#define HDR_GET_COMPRESS(hdr) ((enum zio_compress)BF32_GET((hdr)->b_flags, \
738 HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS))
739#define HDR_SET_COMPRESS(hdr, cmp) BF32_SET((hdr)->b_flags, \
740 HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS, (cmp));
741
742#define ARC_BUF_LAST(buf) ((buf)->b_next == NULL)
524b4217
DK
743#define ARC_BUF_SHARED(buf) ((buf)->b_flags & ARC_BUF_FLAG_SHARED)
744#define ARC_BUF_COMPRESSED(buf) ((buf)->b_flags & ARC_BUF_FLAG_COMPRESSED)
b5256303 745#define ARC_BUF_ENCRYPTED(buf) ((buf)->b_flags & ARC_BUF_FLAG_ENCRYPTED)
d3c2ae1c 746
34dc7c2f
BB
747/*
748 * Other sizes
749 */
750
b5256303
TC
751#define HDR_FULL_CRYPT_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
752#define HDR_FULL_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_crypt_hdr))
b9541d6b 753#define HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
34dc7c2f
BB
754
755/*
756 * Hash table routines
757 */
758
490c845e 759#define BUF_LOCKS 2048
34dc7c2f
BB
760typedef struct buf_hash_table {
761 uint64_t ht_mask;
762 arc_buf_hdr_t **ht_table;
490c845e 763 kmutex_t ht_locks[BUF_LOCKS] ____cacheline_aligned;
34dc7c2f
BB
764} buf_hash_table_t;
765
766static buf_hash_table_t buf_hash_table;
767
768#define BUF_HASH_INDEX(spa, dva, birth) \
769 (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
490c845e 770#define BUF_HASH_LOCK(idx) (&buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
428870ff
BB
771#define HDR_LOCK(hdr) \
772 (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
34dc7c2f
BB
773
774uint64_t zfs_crc64_table[256];
775
776/*
777 * Level 2 ARC
778 */
779
780#define L2ARC_WRITE_SIZE (8 * 1024 * 1024) /* initial write max */
3a17a7a9 781#define L2ARC_HEADROOM 2 /* num of writes */
8a09d5fd 782
3a17a7a9
SK
783/*
784 * If we discover during ARC scan any buffers to be compressed, we boost
785 * our headroom for the next scanning cycle by this percentage multiple.
786 */
787#define L2ARC_HEADROOM_BOOST 200
d164b209
BB
788#define L2ARC_FEED_SECS 1 /* caching interval secs */
789#define L2ARC_FEED_MIN_MS 200 /* min caching interval ms */
34dc7c2f 790
4aafab91
G
791/*
792 * We can feed L2ARC from two states of ARC buffers, mru and mfu,
793 * and each of the state has two types: data and metadata.
794 */
795#define L2ARC_FEED_TYPES 4
796
d3cc8b15 797/* L2ARC Performance Tunables */
ab8d9c17
RY
798uint64_t l2arc_write_max = L2ARC_WRITE_SIZE; /* def max write size */
799uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE; /* extra warmup write */
800uint64_t l2arc_headroom = L2ARC_HEADROOM; /* # of dev writes */
801uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
802uint64_t l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
803uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval msecs */
abd8610c
BB
804int l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
805int l2arc_feed_again = B_TRUE; /* turbo warmup */
c93504f0 806int l2arc_norw = B_FALSE; /* no reads during writes */
fdc2d303 807static uint_t l2arc_meta_percent = 33; /* limit on headers size */
34dc7c2f
BB
808
809/*
810 * L2ARC Internals
811 */
34dc7c2f
BB
812static list_t L2ARC_dev_list; /* device list */
813static list_t *l2arc_dev_list; /* device list pointer */
814static kmutex_t l2arc_dev_mtx; /* device list mutex */
815static l2arc_dev_t *l2arc_dev_last; /* last device used */
34dc7c2f
BB
816static list_t L2ARC_free_on_write; /* free after write buf list */
817static list_t *l2arc_free_on_write; /* free after write list ptr */
818static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
819static uint64_t l2arc_ndev; /* number of devices */
820
821typedef struct l2arc_read_callback {
2aa34383 822 arc_buf_hdr_t *l2rcb_hdr; /* read header */
3a17a7a9 823 blkptr_t l2rcb_bp; /* original blkptr */
5dbd68a3 824 zbookmark_phys_t l2rcb_zb; /* original bookmark */
3a17a7a9 825 int l2rcb_flags; /* original flags */
82710e99 826 abd_t *l2rcb_abd; /* temporary buffer */
34dc7c2f
BB
827} l2arc_read_callback_t;
828
34dc7c2f
BB
829typedef struct l2arc_data_free {
830 /* protected by l2arc_free_on_write_mtx */
a6255b7f 831 abd_t *l2df_abd;
34dc7c2f 832 size_t l2df_size;
d3c2ae1c 833 arc_buf_contents_t l2df_type;
34dc7c2f
BB
834 list_node_t l2df_list_node;
835} l2arc_data_free_t;
836
b5256303
TC
837typedef enum arc_fill_flags {
838 ARC_FILL_LOCKED = 1 << 0, /* hdr lock is held */
839 ARC_FILL_COMPRESSED = 1 << 1, /* fill with compressed data */
840 ARC_FILL_ENCRYPTED = 1 << 2, /* fill with encrypted data */
841 ARC_FILL_NOAUTH = 1 << 3, /* don't attempt to authenticate */
842 ARC_FILL_IN_PLACE = 1 << 4 /* fill in place (special case) */
843} arc_fill_flags_t;
844
f7de776d
AM
845typedef enum arc_ovf_level {
846 ARC_OVF_NONE, /* ARC within target size. */
847 ARC_OVF_SOME, /* ARC is slightly overflowed. */
848 ARC_OVF_SEVERE /* ARC is severely overflowed. */
849} arc_ovf_level_t;
850
34dc7c2f
BB
851static kmutex_t l2arc_feed_thr_lock;
852static kcondvar_t l2arc_feed_thr_cv;
853static uint8_t l2arc_thread_exit;
854
77f6826b
GA
855static kmutex_t l2arc_rebuild_thr_lock;
856static kcondvar_t l2arc_rebuild_thr_cv;
857
e111c802
MM
858enum arc_hdr_alloc_flags {
859 ARC_HDR_ALLOC_RDATA = 0x1,
6b88b4b5 860 ARC_HDR_USE_RESERVE = 0x4,
ed2f7ba0 861 ARC_HDR_ALLOC_LINEAR = 0x8,
e111c802
MM
862};
863
864
dd66857d
AZ
865static abd_t *arc_get_data_abd(arc_buf_hdr_t *, uint64_t, const void *, int);
866static void *arc_get_data_buf(arc_buf_hdr_t *, uint64_t, const void *);
867static void arc_get_data_impl(arc_buf_hdr_t *, uint64_t, const void *, int);
868static void arc_free_data_abd(arc_buf_hdr_t *, abd_t *, uint64_t, const void *);
869static void arc_free_data_buf(arc_buf_hdr_t *, void *, uint64_t, const void *);
870static void arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size,
871 const void *tag);
b5256303 872static void arc_hdr_free_abd(arc_buf_hdr_t *, boolean_t);
e111c802 873static void arc_hdr_alloc_abd(arc_buf_hdr_t *, int);
ed2f7ba0 874static void arc_hdr_destroy(arc_buf_hdr_t *);
c935fe2e 875static void arc_access(arc_buf_hdr_t *, arc_flags_t, boolean_t);
2a432414 876static void arc_buf_watch(arc_buf_t *);
ed2f7ba0 877static void arc_change_state(arc_state_t *, arc_buf_hdr_t *);
2a432414 878
b9541d6b
CW
879static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
880static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
d3c2ae1c
GW
881static inline void arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
882static inline void arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
b9541d6b 883
2a432414
GW
884static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
885static void l2arc_read_done(zio_t *);
cfd59f90 886static void l2arc_do_free_on_write(void);
08532162
GA
887static void l2arc_hdr_arcstats_update(arc_buf_hdr_t *hdr, boolean_t incr,
888 boolean_t state_only);
889
890#define l2arc_hdr_arcstats_increment(hdr) \
891 l2arc_hdr_arcstats_update((hdr), B_TRUE, B_FALSE)
892#define l2arc_hdr_arcstats_decrement(hdr) \
893 l2arc_hdr_arcstats_update((hdr), B_FALSE, B_FALSE)
894#define l2arc_hdr_arcstats_increment_state(hdr) \
895 l2arc_hdr_arcstats_update((hdr), B_TRUE, B_TRUE)
896#define l2arc_hdr_arcstats_decrement_state(hdr) \
897 l2arc_hdr_arcstats_update((hdr), B_FALSE, B_TRUE)
34dc7c2f 898
c9d62d13
GA
899/*
900 * l2arc_exclude_special : A zfs module parameter that controls whether buffers
901 * present on special vdevs are eligibile for caching in L2ARC. If
902 * set to 1, exclude dbufs on special vdevs from being cached to
903 * L2ARC.
904 */
905int l2arc_exclude_special = 0;
906
feb3a7ee
GA
907/*
908 * l2arc_mfuonly : A ZFS module parameter that controls whether only MFU
909 * metadata and data are cached from ARC into L2ARC.
910 */
18168da7 911static int l2arc_mfuonly = 0;
feb3a7ee 912
b7654bd7
GA
913/*
914 * L2ARC TRIM
915 * l2arc_trim_ahead : A ZFS module parameter that controls how much ahead of
916 * the current write size (l2arc_write_max) we should TRIM if we
917 * have filled the device. It is defined as a percentage of the
918 * write size. If set to 100 we trim twice the space required to
919 * accommodate upcoming writes. A minimum of 64MB will be trimmed.
920 * It also enables TRIM of the whole L2ARC device upon creation or
921 * addition to an existing pool or if the header of the device is
922 * invalid upon importing a pool or onlining a cache device. The
923 * default is 0, which disables TRIM on L2ARC altogether as it can
924 * put significant stress on the underlying storage devices. This
925 * will vary depending of how well the specific device handles
926 * these commands.
927 */
ab8d9c17 928static uint64_t l2arc_trim_ahead = 0;
b7654bd7 929
77f6826b
GA
930/*
931 * Performance tuning of L2ARC persistence:
932 *
933 * l2arc_rebuild_enabled : A ZFS module parameter that controls whether adding
934 * an L2ARC device (either at pool import or later) will attempt
935 * to rebuild L2ARC buffer contents.
936 * l2arc_rebuild_blocks_min_l2size : A ZFS module parameter that controls
937 * whether log blocks are written to the L2ARC device. If the L2ARC
938 * device is less than 1GB, the amount of data l2arc_evict()
939 * evicts is significant compared to the amount of restored L2ARC
940 * data. In this case do not write log blocks in L2ARC in order
941 * not to waste space.
942 */
18168da7 943static int l2arc_rebuild_enabled = B_TRUE;
ab8d9c17 944static uint64_t l2arc_rebuild_blocks_min_l2size = 1024 * 1024 * 1024;
77f6826b
GA
945
946/* L2ARC persistence rebuild control routines. */
947void l2arc_rebuild_vdev(vdev_t *vd, boolean_t reopen);
460748d4 948static __attribute__((noreturn)) void l2arc_dev_rebuild_thread(void *arg);
77f6826b
GA
949static int l2arc_rebuild(l2arc_dev_t *dev);
950
951/* L2ARC persistence read I/O routines. */
952static int l2arc_dev_hdr_read(l2arc_dev_t *dev);
953static int l2arc_log_blk_read(l2arc_dev_t *dev,
954 const l2arc_log_blkptr_t *this_lp, const l2arc_log_blkptr_t *next_lp,
955 l2arc_log_blk_phys_t *this_lb, l2arc_log_blk_phys_t *next_lb,
956 zio_t *this_io, zio_t **next_io);
957static zio_t *l2arc_log_blk_fetch(vdev_t *vd,
958 const l2arc_log_blkptr_t *lp, l2arc_log_blk_phys_t *lb);
959static void l2arc_log_blk_fetch_abort(zio_t *zio);
960
961/* L2ARC persistence block restoration routines. */
962static void l2arc_log_blk_restore(l2arc_dev_t *dev,
a76e4e67 963 const l2arc_log_blk_phys_t *lb, uint64_t lb_asize);
77f6826b
GA
964static void l2arc_hdr_restore(const l2arc_log_ent_phys_t *le,
965 l2arc_dev_t *dev);
966
967/* L2ARC persistence write I/O routines. */
bcd53210 968static uint64_t l2arc_log_blk_commit(l2arc_dev_t *dev, zio_t *pio,
77f6826b
GA
969 l2arc_write_callback_t *cb);
970
dd4bc569 971/* L2ARC persistence auxiliary routines. */
77f6826b
GA
972boolean_t l2arc_log_blkptr_valid(l2arc_dev_t *dev,
973 const l2arc_log_blkptr_t *lbp);
974static boolean_t l2arc_log_blk_insert(l2arc_dev_t *dev,
975 const arc_buf_hdr_t *ab);
976boolean_t l2arc_range_check_overlap(uint64_t bottom,
977 uint64_t top, uint64_t check);
978static void l2arc_blk_fetch_done(zio_t *zio);
979static inline uint64_t
980 l2arc_log_blk_overhead(uint64_t write_sz, l2arc_dev_t *dev);
37fb3e43
PD
981
982/*
983 * We use Cityhash for this. It's fast, and has good hash properties without
984 * requiring any large static buffers.
985 */
34dc7c2f 986static uint64_t
d164b209 987buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
34dc7c2f 988{
37fb3e43 989 return (cityhash4(spa, dva->dva_word[0], dva->dva_word[1], birth));
34dc7c2f
BB
990}
991
d3c2ae1c
GW
992#define HDR_EMPTY(hdr) \
993 ((hdr)->b_dva.dva_word[0] == 0 && \
994 (hdr)->b_dva.dva_word[1] == 0)
34dc7c2f 995
ca6c7a94
BB
996#define HDR_EMPTY_OR_LOCKED(hdr) \
997 (HDR_EMPTY(hdr) || MUTEX_HELD(HDR_LOCK(hdr)))
998
d3c2ae1c
GW
999#define HDR_EQUAL(spa, dva, birth, hdr) \
1000 ((hdr)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
1001 ((hdr)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
1002 ((hdr)->b_birth == birth) && ((hdr)->b_spa == spa)
34dc7c2f 1003
428870ff
BB
1004static void
1005buf_discard_identity(arc_buf_hdr_t *hdr)
1006{
1007 hdr->b_dva.dva_word[0] = 0;
1008 hdr->b_dva.dva_word[1] = 0;
1009 hdr->b_birth = 0;
428870ff
BB
1010}
1011
34dc7c2f 1012static arc_buf_hdr_t *
9b67f605 1013buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
34dc7c2f 1014{
9b67f605
MA
1015 const dva_t *dva = BP_IDENTITY(bp);
1016 uint64_t birth = BP_PHYSICAL_BIRTH(bp);
34dc7c2f
BB
1017 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1018 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
2a432414 1019 arc_buf_hdr_t *hdr;
34dc7c2f
BB
1020
1021 mutex_enter(hash_lock);
2a432414
GW
1022 for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
1023 hdr = hdr->b_hash_next) {
d3c2ae1c 1024 if (HDR_EQUAL(spa, dva, birth, hdr)) {
34dc7c2f 1025 *lockp = hash_lock;
2a432414 1026 return (hdr);
34dc7c2f
BB
1027 }
1028 }
1029 mutex_exit(hash_lock);
1030 *lockp = NULL;
1031 return (NULL);
1032}
1033
1034/*
1035 * Insert an entry into the hash table. If there is already an element
1036 * equal to elem in the hash table, then the already existing element
1037 * will be returned and the new element will not be inserted.
1038 * Otherwise returns NULL.
b9541d6b 1039 * If lockp == NULL, the caller is assumed to already hold the hash lock.
34dc7c2f
BB
1040 */
1041static arc_buf_hdr_t *
2a432414 1042buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
34dc7c2f 1043{
2a432414 1044 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
34dc7c2f 1045 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
2a432414 1046 arc_buf_hdr_t *fhdr;
34dc7c2f
BB
1047 uint32_t i;
1048
2a432414
GW
1049 ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
1050 ASSERT(hdr->b_birth != 0);
1051 ASSERT(!HDR_IN_HASH_TABLE(hdr));
b9541d6b
CW
1052
1053 if (lockp != NULL) {
1054 *lockp = hash_lock;
1055 mutex_enter(hash_lock);
1056 } else {
1057 ASSERT(MUTEX_HELD(hash_lock));
1058 }
1059
2a432414
GW
1060 for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
1061 fhdr = fhdr->b_hash_next, i++) {
d3c2ae1c 1062 if (HDR_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
2a432414 1063 return (fhdr);
34dc7c2f
BB
1064 }
1065
2a432414
GW
1066 hdr->b_hash_next = buf_hash_table.ht_table[idx];
1067 buf_hash_table.ht_table[idx] = hdr;
d3c2ae1c 1068 arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
34dc7c2f
BB
1069
1070 /* collect some hash table performance data */
1071 if (i > 0) {
1072 ARCSTAT_BUMP(arcstat_hash_collisions);
1073 if (i == 1)
1074 ARCSTAT_BUMP(arcstat_hash_chains);
1075
1076 ARCSTAT_MAX(arcstat_hash_chain_max, i);
1077 }
c4c162c1
AM
1078 uint64_t he = atomic_inc_64_nv(
1079 &arc_stats.arcstat_hash_elements.value.ui64);
1080 ARCSTAT_MAX(arcstat_hash_elements_max, he);
34dc7c2f
BB
1081
1082 return (NULL);
1083}
1084
1085static void
2a432414 1086buf_hash_remove(arc_buf_hdr_t *hdr)
34dc7c2f 1087{
2a432414
GW
1088 arc_buf_hdr_t *fhdr, **hdrp;
1089 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
34dc7c2f
BB
1090
1091 ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
2a432414 1092 ASSERT(HDR_IN_HASH_TABLE(hdr));
34dc7c2f 1093
2a432414
GW
1094 hdrp = &buf_hash_table.ht_table[idx];
1095 while ((fhdr = *hdrp) != hdr) {
d3c2ae1c 1096 ASSERT3P(fhdr, !=, NULL);
2a432414 1097 hdrp = &fhdr->b_hash_next;
34dc7c2f 1098 }
2a432414
GW
1099 *hdrp = hdr->b_hash_next;
1100 hdr->b_hash_next = NULL;
d3c2ae1c 1101 arc_hdr_clear_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
34dc7c2f
BB
1102
1103 /* collect some hash table performance data */
c4c162c1 1104 atomic_dec_64(&arc_stats.arcstat_hash_elements.value.ui64);
34dc7c2f
BB
1105
1106 if (buf_hash_table.ht_table[idx] &&
1107 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1108 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1109}
1110
1111/*
1112 * Global data structures and functions for the buf kmem cache.
1113 */
b5256303 1114
b9541d6b 1115static kmem_cache_t *hdr_full_cache;
b5256303 1116static kmem_cache_t *hdr_full_crypt_cache;
b9541d6b 1117static kmem_cache_t *hdr_l2only_cache;
34dc7c2f
BB
1118static kmem_cache_t *buf_cache;
1119
1120static void
1121buf_fini(void)
1122{
93ce2b4c 1123#if defined(_KERNEL)
d1d7e268
MK
1124 /*
1125 * Large allocations which do not require contiguous pages
1126 * should be using vmem_free() in the linux kernel\
1127 */
00b46022
BB
1128 vmem_free(buf_hash_table.ht_table,
1129 (buf_hash_table.ht_mask + 1) * sizeof (void *));
1130#else
34dc7c2f
BB
1131 kmem_free(buf_hash_table.ht_table,
1132 (buf_hash_table.ht_mask + 1) * sizeof (void *));
00b46022 1133#endif
14e4e3cb 1134 for (int i = 0; i < BUF_LOCKS; i++)
490c845e 1135 mutex_destroy(BUF_HASH_LOCK(i));
b9541d6b 1136 kmem_cache_destroy(hdr_full_cache);
b5256303 1137 kmem_cache_destroy(hdr_full_crypt_cache);
b9541d6b 1138 kmem_cache_destroy(hdr_l2only_cache);
34dc7c2f
BB
1139 kmem_cache_destroy(buf_cache);
1140}
1141
1142/*
1143 * Constructor callback - called when the cache is empty
1144 * and a new buf is requested.
1145 */
34dc7c2f 1146static int
b9541d6b
CW
1147hdr_full_cons(void *vbuf, void *unused, int kmflag)
1148{
14e4e3cb 1149 (void) unused, (void) kmflag;
b9541d6b
CW
1150 arc_buf_hdr_t *hdr = vbuf;
1151
861166b0 1152 memset(hdr, 0, HDR_FULL_SIZE);
ae76f45c 1153 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
b9541d6b 1154 cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
424fd7c3 1155 zfs_refcount_create(&hdr->b_l1hdr.b_refcnt);
bacf366f 1156#ifdef ZFS_DEBUG
b9541d6b 1157 mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
bacf366f 1158#endif
ca0bf58d 1159 multilist_link_init(&hdr->b_l1hdr.b_arc_node);
c935fe2e 1160 list_link_init(&hdr->b_l2hdr.b_l2node);
b9541d6b
CW
1161 arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1162
1163 return (0);
1164}
1165
b5256303
TC
1166static int
1167hdr_full_crypt_cons(void *vbuf, void *unused, int kmflag)
1168{
14e4e3cb 1169 (void) unused;
b5256303
TC
1170 arc_buf_hdr_t *hdr = vbuf;
1171
1172 hdr_full_cons(vbuf, unused, kmflag);
861166b0 1173 memset(&hdr->b_crypt_hdr, 0, sizeof (hdr->b_crypt_hdr));
b5256303
TC
1174 arc_space_consume(sizeof (hdr->b_crypt_hdr), ARC_SPACE_HDRS);
1175
1176 return (0);
1177}
1178
b9541d6b
CW
1179static int
1180hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
34dc7c2f 1181{
14e4e3cb 1182 (void) unused, (void) kmflag;
2a432414
GW
1183 arc_buf_hdr_t *hdr = vbuf;
1184
861166b0 1185 memset(hdr, 0, HDR_L2ONLY_SIZE);
b9541d6b 1186 arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
34dc7c2f 1187
34dc7c2f
BB
1188 return (0);
1189}
1190
b128c09f
BB
1191static int
1192buf_cons(void *vbuf, void *unused, int kmflag)
1193{
14e4e3cb 1194 (void) unused, (void) kmflag;
b128c09f
BB
1195 arc_buf_t *buf = vbuf;
1196
861166b0 1197 memset(buf, 0, sizeof (arc_buf_t));
d164b209
BB
1198 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1199
b128c09f
BB
1200 return (0);
1201}
1202
34dc7c2f
BB
1203/*
1204 * Destructor callback - called when a cached buf is
1205 * no longer required.
1206 */
34dc7c2f 1207static void
b9541d6b 1208hdr_full_dest(void *vbuf, void *unused)
34dc7c2f 1209{
14e4e3cb 1210 (void) unused;
2a432414 1211 arc_buf_hdr_t *hdr = vbuf;
34dc7c2f 1212
d3c2ae1c 1213 ASSERT(HDR_EMPTY(hdr));
b9541d6b 1214 cv_destroy(&hdr->b_l1hdr.b_cv);
424fd7c3 1215 zfs_refcount_destroy(&hdr->b_l1hdr.b_refcnt);
bacf366f 1216#ifdef ZFS_DEBUG
b9541d6b 1217 mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
bacf366f 1218#endif
ca0bf58d 1219 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
b9541d6b
CW
1220 arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1221}
1222
b5256303
TC
1223static void
1224hdr_full_crypt_dest(void *vbuf, void *unused)
1225{
045aeabc 1226 (void) vbuf, (void) unused;
b5256303
TC
1227
1228 hdr_full_dest(vbuf, unused);
045aeabc
AZ
1229 arc_space_return(sizeof (((arc_buf_hdr_t *)NULL)->b_crypt_hdr),
1230 ARC_SPACE_HDRS);
b5256303
TC
1231}
1232
b9541d6b
CW
1233static void
1234hdr_l2only_dest(void *vbuf, void *unused)
1235{
14e4e3cb
AZ
1236 (void) unused;
1237 arc_buf_hdr_t *hdr = vbuf;
b9541d6b 1238
d3c2ae1c 1239 ASSERT(HDR_EMPTY(hdr));
b9541d6b 1240 arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
34dc7c2f
BB
1241}
1242
b128c09f
BB
1243static void
1244buf_dest(void *vbuf, void *unused)
1245{
14e4e3cb 1246 (void) unused;
289f7e6a 1247 (void) vbuf;
b128c09f 1248
d164b209 1249 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
b128c09f
BB
1250}
1251
34dc7c2f
BB
1252static void
1253buf_init(void)
1254{
2db28197 1255 uint64_t *ct = NULL;
34dc7c2f
BB
1256 uint64_t hsize = 1ULL << 12;
1257 int i, j;
1258
1259 /*
1260 * The hash table is big enough to fill all of physical memory
49ddb315
MA
1261 * with an average block size of zfs_arc_average_blocksize (default 8K).
1262 * By default, the table will take up
1263 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
34dc7c2f 1264 */
9edb3695 1265 while (hsize * zfs_arc_average_blocksize < arc_all_memory())
34dc7c2f
BB
1266 hsize <<= 1;
1267retry:
1268 buf_hash_table.ht_mask = hsize - 1;
93ce2b4c 1269#if defined(_KERNEL)
d1d7e268
MK
1270 /*
1271 * Large allocations which do not require contiguous pages
1272 * should be using vmem_alloc() in the linux kernel
1273 */
00b46022
BB
1274 buf_hash_table.ht_table =
1275 vmem_zalloc(hsize * sizeof (void*), KM_SLEEP);
1276#else
34dc7c2f
BB
1277 buf_hash_table.ht_table =
1278 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
00b46022 1279#endif
34dc7c2f
BB
1280 if (buf_hash_table.ht_table == NULL) {
1281 ASSERT(hsize > (1ULL << 8));
1282 hsize >>= 1;
1283 goto retry;
1284 }
1285
b9541d6b 1286 hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
026e529c 1287 0, hdr_full_cons, hdr_full_dest, NULL, NULL, NULL, 0);
b5256303
TC
1288 hdr_full_crypt_cache = kmem_cache_create("arc_buf_hdr_t_full_crypt",
1289 HDR_FULL_CRYPT_SIZE, 0, hdr_full_crypt_cons, hdr_full_crypt_dest,
026e529c 1290 NULL, NULL, NULL, 0);
b9541d6b 1291 hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
026e529c 1292 HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, NULL,
b9541d6b 1293 NULL, NULL, 0);
34dc7c2f 1294 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
b128c09f 1295 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
34dc7c2f
BB
1296
1297 for (i = 0; i < 256; i++)
1298 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1299 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1300
490c845e
AM
1301 for (i = 0; i < BUF_LOCKS; i++)
1302 mutex_init(BUF_HASH_LOCK(i), NULL, MUTEX_DEFAULT, NULL);
34dc7c2f
BB
1303}
1304
d3c2ae1c 1305#define ARC_MINTIME (hz>>4) /* 62 ms */
ca0bf58d 1306
2aa34383
DK
1307/*
1308 * This is the size that the buf occupies in memory. If the buf is compressed,
1309 * it will correspond to the compressed size. You should use this method of
1310 * getting the buf size unless you explicitly need the logical size.
1311 */
1312uint64_t
1313arc_buf_size(arc_buf_t *buf)
1314{
1315 return (ARC_BUF_COMPRESSED(buf) ?
1316 HDR_GET_PSIZE(buf->b_hdr) : HDR_GET_LSIZE(buf->b_hdr));
1317}
1318
1319uint64_t
1320arc_buf_lsize(arc_buf_t *buf)
1321{
1322 return (HDR_GET_LSIZE(buf->b_hdr));
1323}
1324
b5256303
TC
1325/*
1326 * This function will return B_TRUE if the buffer is encrypted in memory.
1327 * This buffer can be decrypted by calling arc_untransform().
1328 */
1329boolean_t
1330arc_is_encrypted(arc_buf_t *buf)
1331{
1332 return (ARC_BUF_ENCRYPTED(buf) != 0);
1333}
1334
1335/*
1336 * Returns B_TRUE if the buffer represents data that has not had its MAC
1337 * verified yet.
1338 */
1339boolean_t
1340arc_is_unauthenticated(arc_buf_t *buf)
1341{
1342 return (HDR_NOAUTH(buf->b_hdr) != 0);
1343}
1344
1345void
1346arc_get_raw_params(arc_buf_t *buf, boolean_t *byteorder, uint8_t *salt,
1347 uint8_t *iv, uint8_t *mac)
1348{
1349 arc_buf_hdr_t *hdr = buf->b_hdr;
1350
1351 ASSERT(HDR_PROTECTED(hdr));
1352
861166b0
AZ
1353 memcpy(salt, hdr->b_crypt_hdr.b_salt, ZIO_DATA_SALT_LEN);
1354 memcpy(iv, hdr->b_crypt_hdr.b_iv, ZIO_DATA_IV_LEN);
1355 memcpy(mac, hdr->b_crypt_hdr.b_mac, ZIO_DATA_MAC_LEN);
b5256303
TC
1356 *byteorder = (hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS) ?
1357 ZFS_HOST_BYTEORDER : !ZFS_HOST_BYTEORDER;
1358}
1359
1360/*
1361 * Indicates how this buffer is compressed in memory. If it is not compressed
1362 * the value will be ZIO_COMPRESS_OFF. It can be made normally readable with
1363 * arc_untransform() as long as it is also unencrypted.
1364 */
2aa34383
DK
1365enum zio_compress
1366arc_get_compression(arc_buf_t *buf)
1367{
1368 return (ARC_BUF_COMPRESSED(buf) ?
1369 HDR_GET_COMPRESS(buf->b_hdr) : ZIO_COMPRESS_OFF);
1370}
1371
b5256303
TC
1372/*
1373 * Return the compression algorithm used to store this data in the ARC. If ARC
1374 * compression is enabled or this is an encrypted block, this will be the same
1375 * as what's used to store it on-disk. Otherwise, this will be ZIO_COMPRESS_OFF.
1376 */
1377static inline enum zio_compress
1378arc_hdr_get_compress(arc_buf_hdr_t *hdr)
1379{
1380 return (HDR_COMPRESSION_ENABLED(hdr) ?
1381 HDR_GET_COMPRESS(hdr) : ZIO_COMPRESS_OFF);
1382}
1383
10b3c7f5
MN
1384uint8_t
1385arc_get_complevel(arc_buf_t *buf)
1386{
1387 return (buf->b_hdr->b_complevel);
1388}
1389
d3c2ae1c
GW
1390static inline boolean_t
1391arc_buf_is_shared(arc_buf_t *buf)
1392{
1393 boolean_t shared = (buf->b_data != NULL &&
a6255b7f
DQ
1394 buf->b_hdr->b_l1hdr.b_pabd != NULL &&
1395 abd_is_linear(buf->b_hdr->b_l1hdr.b_pabd) &&
1396 buf->b_data == abd_to_buf(buf->b_hdr->b_l1hdr.b_pabd));
d3c2ae1c 1397 IMPLY(shared, HDR_SHARED_DATA(buf->b_hdr));
2aa34383
DK
1398 IMPLY(shared, ARC_BUF_SHARED(buf));
1399 IMPLY(shared, ARC_BUF_COMPRESSED(buf) || ARC_BUF_LAST(buf));
524b4217
DK
1400
1401 /*
1402 * It would be nice to assert arc_can_share() too, but the "hdr isn't
1403 * already being shared" requirement prevents us from doing that.
1404 */
1405
d3c2ae1c
GW
1406 return (shared);
1407}
ca0bf58d 1408
a7004725
DK
1409/*
1410 * Free the checksum associated with this header. If there is no checksum, this
1411 * is a no-op.
1412 */
d3c2ae1c
GW
1413static inline void
1414arc_cksum_free(arc_buf_hdr_t *hdr)
1415{
bacf366f 1416#ifdef ZFS_DEBUG
d3c2ae1c 1417 ASSERT(HDR_HAS_L1HDR(hdr));
b5256303 1418
d3c2ae1c
GW
1419 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1420 if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
1421 kmem_free(hdr->b_l1hdr.b_freeze_cksum, sizeof (zio_cksum_t));
1422 hdr->b_l1hdr.b_freeze_cksum = NULL;
b9541d6b 1423 }
d3c2ae1c 1424 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
bacf366f 1425#endif
b9541d6b
CW
1426}
1427
a7004725
DK
1428/*
1429 * Return true iff at least one of the bufs on hdr is not compressed.
b5256303 1430 * Encrypted buffers count as compressed.
a7004725
DK
1431 */
1432static boolean_t
1433arc_hdr_has_uncompressed_buf(arc_buf_hdr_t *hdr)
1434{
ca6c7a94 1435 ASSERT(hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY_OR_LOCKED(hdr));
149ce888 1436
a7004725
DK
1437 for (arc_buf_t *b = hdr->b_l1hdr.b_buf; b != NULL; b = b->b_next) {
1438 if (!ARC_BUF_COMPRESSED(b)) {
1439 return (B_TRUE);
1440 }
1441 }
1442 return (B_FALSE);
1443}
1444
1445
524b4217
DK
1446/*
1447 * If we've turned on the ZFS_DEBUG_MODIFY flag, verify that the buf's data
1448 * matches the checksum that is stored in the hdr. If there is no checksum,
1449 * or if the buf is compressed, this is a no-op.
1450 */
34dc7c2f
BB
1451static void
1452arc_cksum_verify(arc_buf_t *buf)
1453{
bacf366f 1454#ifdef ZFS_DEBUG
d3c2ae1c 1455 arc_buf_hdr_t *hdr = buf->b_hdr;
34dc7c2f
BB
1456 zio_cksum_t zc;
1457
1458 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1459 return;
1460
149ce888 1461 if (ARC_BUF_COMPRESSED(buf))
524b4217 1462 return;
524b4217 1463
d3c2ae1c
GW
1464 ASSERT(HDR_HAS_L1HDR(hdr));
1465
1466 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
149ce888 1467
d3c2ae1c
GW
1468 if (hdr->b_l1hdr.b_freeze_cksum == NULL || HDR_IO_ERROR(hdr)) {
1469 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
34dc7c2f
BB
1470 return;
1471 }
2aa34383 1472
3c67d83a 1473 fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL, &zc);
d3c2ae1c 1474 if (!ZIO_CHECKSUM_EQUAL(*hdr->b_l1hdr.b_freeze_cksum, zc))
34dc7c2f 1475 panic("buffer modified while frozen!");
d3c2ae1c 1476 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
bacf366f 1477#endif
34dc7c2f
BB
1478}
1479
b5256303
TC
1480/*
1481 * This function makes the assumption that data stored in the L2ARC
1482 * will be transformed exactly as it is in the main pool. Because of
1483 * this we can verify the checksum against the reading process's bp.
1484 */
d3c2ae1c
GW
1485static boolean_t
1486arc_cksum_is_equal(arc_buf_hdr_t *hdr, zio_t *zio)
34dc7c2f 1487{
d3c2ae1c
GW
1488 ASSERT(!BP_IS_EMBEDDED(zio->io_bp));
1489 VERIFY3U(BP_GET_PSIZE(zio->io_bp), ==, HDR_GET_PSIZE(hdr));
34dc7c2f 1490
d3c2ae1c
GW
1491 /*
1492 * Block pointers always store the checksum for the logical data.
1493 * If the block pointer has the gang bit set, then the checksum
1494 * it represents is for the reconstituted data and not for an
1495 * individual gang member. The zio pipeline, however, must be able to
1496 * determine the checksum of each of the gang constituents so it
1497 * treats the checksum comparison differently than what we need
1498 * for l2arc blocks. This prevents us from using the
1499 * zio_checksum_error() interface directly. Instead we must call the
1500 * zio_checksum_error_impl() so that we can ensure the checksum is
1501 * generated using the correct checksum algorithm and accounts for the
1502 * logical I/O size and not just a gang fragment.
1503 */
b5256303 1504 return (zio_checksum_error_impl(zio->io_spa, zio->io_bp,
a6255b7f 1505 BP_GET_CHECKSUM(zio->io_bp), zio->io_abd, zio->io_size,
d3c2ae1c 1506 zio->io_offset, NULL) == 0);
34dc7c2f
BB
1507}
1508
524b4217
DK
1509/*
1510 * Given a buf full of data, if ZFS_DEBUG_MODIFY is enabled this computes a
1511 * checksum and attaches it to the buf's hdr so that we can ensure that the buf
1512 * isn't modified later on. If buf is compressed or there is already a checksum
1513 * on the hdr, this is a no-op (we only checksum uncompressed bufs).
1514 */
34dc7c2f 1515static void
d3c2ae1c 1516arc_cksum_compute(arc_buf_t *buf)
34dc7c2f 1517{
d3c2ae1c 1518 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
34dc7c2f
BB
1519 return;
1520
bacf366f
AM
1521#ifdef ZFS_DEBUG
1522 arc_buf_hdr_t *hdr = buf->b_hdr;
d3c2ae1c 1523 ASSERT(HDR_HAS_L1HDR(hdr));
bacf366f 1524 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
149ce888 1525 if (hdr->b_l1hdr.b_freeze_cksum != NULL || ARC_BUF_COMPRESSED(buf)) {
d3c2ae1c 1526 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
34dc7c2f
BB
1527 return;
1528 }
2aa34383 1529
b5256303 1530 ASSERT(!ARC_BUF_ENCRYPTED(buf));
2aa34383 1531 ASSERT(!ARC_BUF_COMPRESSED(buf));
d3c2ae1c
GW
1532 hdr->b_l1hdr.b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t),
1533 KM_SLEEP);
3c67d83a 1534 fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL,
d3c2ae1c
GW
1535 hdr->b_l1hdr.b_freeze_cksum);
1536 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
bacf366f 1537#endif
498877ba
MA
1538 arc_buf_watch(buf);
1539}
1540
1541#ifndef _KERNEL
1542void
1543arc_buf_sigsegv(int sig, siginfo_t *si, void *unused)
1544{
14e4e3cb 1545 (void) sig, (void) unused;
02730c33 1546 panic("Got SIGSEGV at address: 0x%lx\n", (long)si->si_addr);
498877ba
MA
1547}
1548#endif
1549
498877ba
MA
1550static void
1551arc_buf_unwatch(arc_buf_t *buf)
1552{
1553#ifndef _KERNEL
1554 if (arc_watch) {
a7004725 1555 ASSERT0(mprotect(buf->b_data, arc_buf_size(buf),
498877ba
MA
1556 PROT_READ | PROT_WRITE));
1557 }
14e4e3cb
AZ
1558#else
1559 (void) buf;
498877ba
MA
1560#endif
1561}
1562
498877ba
MA
1563static void
1564arc_buf_watch(arc_buf_t *buf)
1565{
1566#ifndef _KERNEL
1567 if (arc_watch)
2aa34383 1568 ASSERT0(mprotect(buf->b_data, arc_buf_size(buf),
d3c2ae1c 1569 PROT_READ));
14e4e3cb
AZ
1570#else
1571 (void) buf;
498877ba 1572#endif
34dc7c2f
BB
1573}
1574
b9541d6b
CW
1575static arc_buf_contents_t
1576arc_buf_type(arc_buf_hdr_t *hdr)
1577{
d3c2ae1c 1578 arc_buf_contents_t type;
b9541d6b 1579 if (HDR_ISTYPE_METADATA(hdr)) {
d3c2ae1c 1580 type = ARC_BUFC_METADATA;
b9541d6b 1581 } else {
d3c2ae1c 1582 type = ARC_BUFC_DATA;
b9541d6b 1583 }
d3c2ae1c
GW
1584 VERIFY3U(hdr->b_type, ==, type);
1585 return (type);
b9541d6b
CW
1586}
1587
2aa34383
DK
1588boolean_t
1589arc_is_metadata(arc_buf_t *buf)
1590{
1591 return (HDR_ISTYPE_METADATA(buf->b_hdr) != 0);
1592}
1593
b9541d6b
CW
1594static uint32_t
1595arc_bufc_to_flags(arc_buf_contents_t type)
1596{
1597 switch (type) {
1598 case ARC_BUFC_DATA:
1599 /* metadata field is 0 if buffer contains normal data */
1600 return (0);
1601 case ARC_BUFC_METADATA:
1602 return (ARC_FLAG_BUFC_METADATA);
1603 default:
1604 break;
1605 }
1606 panic("undefined ARC buffer type!");
1607 return ((uint32_t)-1);
1608}
1609
34dc7c2f
BB
1610void
1611arc_buf_thaw(arc_buf_t *buf)
1612{
d3c2ae1c
GW
1613 arc_buf_hdr_t *hdr = buf->b_hdr;
1614
2aa34383
DK
1615 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
1616 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1617
524b4217 1618 arc_cksum_verify(buf);
34dc7c2f 1619
2aa34383 1620 /*
149ce888 1621 * Compressed buffers do not manipulate the b_freeze_cksum.
2aa34383 1622 */
149ce888 1623 if (ARC_BUF_COMPRESSED(buf))
2aa34383 1624 return;
2aa34383 1625
d3c2ae1c
GW
1626 ASSERT(HDR_HAS_L1HDR(hdr));
1627 arc_cksum_free(hdr);
498877ba 1628 arc_buf_unwatch(buf);
34dc7c2f
BB
1629}
1630
1631void
1632arc_buf_freeze(arc_buf_t *buf)
1633{
1634 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1635 return;
1636
149ce888 1637 if (ARC_BUF_COMPRESSED(buf))
2aa34383 1638 return;
428870ff 1639
149ce888 1640 ASSERT(HDR_HAS_L1HDR(buf->b_hdr));
d3c2ae1c 1641 arc_cksum_compute(buf);
34dc7c2f
BB
1642}
1643
d3c2ae1c
GW
1644/*
1645 * The arc_buf_hdr_t's b_flags should never be modified directly. Instead,
1646 * the following functions should be used to ensure that the flags are
1647 * updated in a thread-safe way. When manipulating the flags either
1648 * the hash_lock must be held or the hdr must be undiscoverable. This
1649 * ensures that we're not racing with any other threads when updating
1650 * the flags.
1651 */
1652static inline void
1653arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
1654{
ca6c7a94 1655 ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
d3c2ae1c
GW
1656 hdr->b_flags |= flags;
1657}
1658
1659static inline void
1660arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
1661{
ca6c7a94 1662 ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
d3c2ae1c
GW
1663 hdr->b_flags &= ~flags;
1664}
1665
1666/*
1667 * Setting the compression bits in the arc_buf_hdr_t's b_flags is
1668 * done in a special way since we have to clear and set bits
1669 * at the same time. Consumers that wish to set the compression bits
1670 * must use this function to ensure that the flags are updated in
1671 * thread-safe manner.
1672 */
1673static void
1674arc_hdr_set_compress(arc_buf_hdr_t *hdr, enum zio_compress cmp)
1675{
ca6c7a94 1676 ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
d3c2ae1c
GW
1677
1678 /*
1679 * Holes and embedded blocks will always have a psize = 0 so
1680 * we ignore the compression of the blkptr and set the
d3c2ae1c
GW
1681 * want to uncompress them. Mark them as uncompressed.
1682 */
1683 if (!zfs_compressed_arc_enabled || HDR_GET_PSIZE(hdr) == 0) {
1684 arc_hdr_clear_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
d3c2ae1c 1685 ASSERT(!HDR_COMPRESSION_ENABLED(hdr));
d3c2ae1c
GW
1686 } else {
1687 arc_hdr_set_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
d3c2ae1c
GW
1688 ASSERT(HDR_COMPRESSION_ENABLED(hdr));
1689 }
b5256303
TC
1690
1691 HDR_SET_COMPRESS(hdr, cmp);
1692 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, cmp);
d3c2ae1c
GW
1693}
1694
524b4217
DK
1695/*
1696 * Looks for another buf on the same hdr which has the data decompressed, copies
1697 * from it, and returns true. If no such buf exists, returns false.
1698 */
1699static boolean_t
1700arc_buf_try_copy_decompressed_data(arc_buf_t *buf)
1701{
1702 arc_buf_hdr_t *hdr = buf->b_hdr;
524b4217
DK
1703 boolean_t copied = B_FALSE;
1704
1705 ASSERT(HDR_HAS_L1HDR(hdr));
1706 ASSERT3P(buf->b_data, !=, NULL);
1707 ASSERT(!ARC_BUF_COMPRESSED(buf));
1708
a7004725 1709 for (arc_buf_t *from = hdr->b_l1hdr.b_buf; from != NULL;
524b4217
DK
1710 from = from->b_next) {
1711 /* can't use our own data buffer */
1712 if (from == buf) {
1713 continue;
1714 }
1715
1716 if (!ARC_BUF_COMPRESSED(from)) {
861166b0 1717 memcpy(buf->b_data, from->b_data, arc_buf_size(buf));
524b4217
DK
1718 copied = B_TRUE;
1719 break;
1720 }
1721 }
1722
bacf366f 1723#ifdef ZFS_DEBUG
524b4217
DK
1724 /*
1725 * There were no decompressed bufs, so there should not be a
1726 * checksum on the hdr either.
1727 */
46db9d61
BB
1728 if (zfs_flags & ZFS_DEBUG_MODIFY)
1729 EQUIV(!copied, hdr->b_l1hdr.b_freeze_cksum == NULL);
bacf366f 1730#endif
524b4217
DK
1731
1732 return (copied);
1733}
1734
77f6826b
GA
1735/*
1736 * Allocates an ARC buf header that's in an evicted & L2-cached state.
1737 * This is used during l2arc reconstruction to make empty ARC buffers
1738 * which circumvent the regular disk->arc->l2arc path and instead come
1739 * into being in the reverse order, i.e. l2arc->arc.
1740 */
65c7cc49 1741static arc_buf_hdr_t *
77f6826b
GA
1742arc_buf_alloc_l2only(size_t size, arc_buf_contents_t type, l2arc_dev_t *dev,
1743 dva_t dva, uint64_t daddr, int32_t psize, uint64_t birth,
10b3c7f5 1744 enum zio_compress compress, uint8_t complevel, boolean_t protected,
08532162 1745 boolean_t prefetch, arc_state_type_t arcs_state)
77f6826b
GA
1746{
1747 arc_buf_hdr_t *hdr;
1748
1749 ASSERT(size != 0);
1750 hdr = kmem_cache_alloc(hdr_l2only_cache, KM_SLEEP);
1751 hdr->b_birth = birth;
1752 hdr->b_type = type;
1753 hdr->b_flags = 0;
1754 arc_hdr_set_flags(hdr, arc_bufc_to_flags(type) | ARC_FLAG_HAS_L2HDR);
1755 HDR_SET_LSIZE(hdr, size);
1756 HDR_SET_PSIZE(hdr, psize);
1757 arc_hdr_set_compress(hdr, compress);
10b3c7f5 1758 hdr->b_complevel = complevel;
77f6826b
GA
1759 if (protected)
1760 arc_hdr_set_flags(hdr, ARC_FLAG_PROTECTED);
1761 if (prefetch)
1762 arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
1763 hdr->b_spa = spa_load_guid(dev->l2ad_vdev->vdev_spa);
1764
1765 hdr->b_dva = dva;
1766
1767 hdr->b_l2hdr.b_dev = dev;
1768 hdr->b_l2hdr.b_daddr = daddr;
08532162 1769 hdr->b_l2hdr.b_arcs_state = arcs_state;
77f6826b
GA
1770
1771 return (hdr);
1772}
1773
b5256303
TC
1774/*
1775 * Return the size of the block, b_pabd, that is stored in the arc_buf_hdr_t.
1776 */
1777static uint64_t
1778arc_hdr_size(arc_buf_hdr_t *hdr)
1779{
1780 uint64_t size;
1781
1782 if (arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF &&
1783 HDR_GET_PSIZE(hdr) > 0) {
1784 size = HDR_GET_PSIZE(hdr);
1785 } else {
1786 ASSERT3U(HDR_GET_LSIZE(hdr), !=, 0);
1787 size = HDR_GET_LSIZE(hdr);
1788 }
1789 return (size);
1790}
1791
1792static int
1793arc_hdr_authenticate(arc_buf_hdr_t *hdr, spa_t *spa, uint64_t dsobj)
1794{
1795 int ret;
1796 uint64_t csize;
1797 uint64_t lsize = HDR_GET_LSIZE(hdr);
1798 uint64_t psize = HDR_GET_PSIZE(hdr);
1799 void *tmpbuf = NULL;
1800 abd_t *abd = hdr->b_l1hdr.b_pabd;
1801
ca6c7a94 1802 ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
b5256303
TC
1803 ASSERT(HDR_AUTHENTICATED(hdr));
1804 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
1805
1806 /*
1807 * The MAC is calculated on the compressed data that is stored on disk.
1808 * However, if compressed arc is disabled we will only have the
1809 * decompressed data available to us now. Compress it into a temporary
1810 * abd so we can verify the MAC. The performance overhead of this will
1811 * be relatively low, since most objects in an encrypted objset will
1812 * be encrypted (instead of authenticated) anyway.
1813 */
1814 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
1815 !HDR_COMPRESSION_ENABLED(hdr)) {
bff26b02 1816
b5256303 1817 csize = zio_compress_data(HDR_GET_COMPRESS(hdr),
bff26b02
RY
1818 hdr->b_l1hdr.b_pabd, &tmpbuf, lsize, hdr->b_complevel);
1819 ASSERT3P(tmpbuf, !=, NULL);
b5256303 1820 ASSERT3U(csize, <=, psize);
bff26b02
RY
1821 abd = abd_get_from_buf(tmpbuf, lsize);
1822 abd_take_ownership_of_buf(abd, B_TRUE);
b5256303
TC
1823 abd_zero_off(abd, csize, psize - csize);
1824 }
1825
1826 /*
1827 * Authentication is best effort. We authenticate whenever the key is
1828 * available. If we succeed we clear ARC_FLAG_NOAUTH.
1829 */
1830 if (hdr->b_crypt_hdr.b_ot == DMU_OT_OBJSET) {
1831 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
1832 ASSERT3U(lsize, ==, psize);
1833 ret = spa_do_crypt_objset_mac_abd(B_FALSE, spa, dsobj, abd,
1834 psize, hdr->b_l1hdr.b_byteswap != DMU_BSWAP_NUMFUNCS);
1835 } else {
1836 ret = spa_do_crypt_mac_abd(B_FALSE, spa, dsobj, abd, psize,
1837 hdr->b_crypt_hdr.b_mac);
1838 }
1839
1840 if (ret == 0)
1841 arc_hdr_clear_flags(hdr, ARC_FLAG_NOAUTH);
1842 else if (ret != ENOENT)
1843 goto error;
1844
1845 if (tmpbuf != NULL)
1846 abd_free(abd);
1847
1848 return (0);
1849
1850error:
1851 if (tmpbuf != NULL)
1852 abd_free(abd);
1853
1854 return (ret);
1855}
1856
1857/*
1858 * This function will take a header that only has raw encrypted data in
1859 * b_crypt_hdr.b_rabd and decrypt it into a new buffer which is stored in
1860 * b_l1hdr.b_pabd. If designated in the header flags, this function will
1861 * also decompress the data.
1862 */
1863static int
be9a5c35 1864arc_hdr_decrypt(arc_buf_hdr_t *hdr, spa_t *spa, const zbookmark_phys_t *zb)
b5256303
TC
1865{
1866 int ret;
b5256303
TC
1867 abd_t *cabd = NULL;
1868 void *tmp = NULL;
1869 boolean_t no_crypt = B_FALSE;
1870 boolean_t bswap = (hdr->b_l1hdr.b_byteswap != DMU_BSWAP_NUMFUNCS);
1871
ca6c7a94 1872 ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
b5256303
TC
1873 ASSERT(HDR_ENCRYPTED(hdr));
1874
a8d83e2a 1875 arc_hdr_alloc_abd(hdr, 0);
b5256303 1876
be9a5c35
TC
1877 ret = spa_do_crypt_abd(B_FALSE, spa, zb, hdr->b_crypt_hdr.b_ot,
1878 B_FALSE, bswap, hdr->b_crypt_hdr.b_salt, hdr->b_crypt_hdr.b_iv,
1879 hdr->b_crypt_hdr.b_mac, HDR_GET_PSIZE(hdr), hdr->b_l1hdr.b_pabd,
b5256303
TC
1880 hdr->b_crypt_hdr.b_rabd, &no_crypt);
1881 if (ret != 0)
1882 goto error;
1883
1884 if (no_crypt) {
1885 abd_copy(hdr->b_l1hdr.b_pabd, hdr->b_crypt_hdr.b_rabd,
1886 HDR_GET_PSIZE(hdr));
1887 }
1888
1889 /*
1890 * If this header has disabled arc compression but the b_pabd is
1891 * compressed after decrypting it, we need to decompress the newly
1892 * decrypted data.
1893 */
1894 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
1895 !HDR_COMPRESSION_ENABLED(hdr)) {
1896 /*
1897 * We want to make sure that we are correctly honoring the
1898 * zfs_abd_scatter_enabled setting, so we allocate an abd here
1899 * and then loan a buffer from it, rather than allocating a
1900 * linear buffer and wrapping it in an abd later.
1901 */
a8d83e2a 1902 cabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr, 0);
b5256303
TC
1903 tmp = abd_borrow_buf(cabd, arc_hdr_size(hdr));
1904
1905 ret = zio_decompress_data(HDR_GET_COMPRESS(hdr),
1906 hdr->b_l1hdr.b_pabd, tmp, HDR_GET_PSIZE(hdr),
10b3c7f5 1907 HDR_GET_LSIZE(hdr), &hdr->b_complevel);
b5256303
TC
1908 if (ret != 0) {
1909 abd_return_buf(cabd, tmp, arc_hdr_size(hdr));
1910 goto error;
1911 }
1912
1913 abd_return_buf_copy(cabd, tmp, arc_hdr_size(hdr));
1914 arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
1915 arc_hdr_size(hdr), hdr);
1916 hdr->b_l1hdr.b_pabd = cabd;
1917 }
1918
b5256303
TC
1919 return (0);
1920
1921error:
1922 arc_hdr_free_abd(hdr, B_FALSE);
b5256303
TC
1923 if (cabd != NULL)
1924 arc_free_data_buf(hdr, cabd, arc_hdr_size(hdr), hdr);
1925
1926 return (ret);
1927}
1928
1929/*
1930 * This function is called during arc_buf_fill() to prepare the header's
1931 * abd plaintext pointer for use. This involves authenticated protected
1932 * data and decrypting encrypted data into the plaintext abd.
1933 */
1934static int
1935arc_fill_hdr_crypt(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, spa_t *spa,
be9a5c35 1936 const zbookmark_phys_t *zb, boolean_t noauth)
b5256303
TC
1937{
1938 int ret;
1939
1940 ASSERT(HDR_PROTECTED(hdr));
1941
1942 if (hash_lock != NULL)
1943 mutex_enter(hash_lock);
1944
1945 if (HDR_NOAUTH(hdr) && !noauth) {
1946 /*
1947 * The caller requested authenticated data but our data has
1948 * not been authenticated yet. Verify the MAC now if we can.
1949 */
be9a5c35 1950 ret = arc_hdr_authenticate(hdr, spa, zb->zb_objset);
b5256303
TC
1951 if (ret != 0)
1952 goto error;
1953 } else if (HDR_HAS_RABD(hdr) && hdr->b_l1hdr.b_pabd == NULL) {
1954 /*
1955 * If we only have the encrypted version of the data, but the
1956 * unencrypted version was requested we take this opportunity
1957 * to store the decrypted version in the header for future use.
1958 */
be9a5c35 1959 ret = arc_hdr_decrypt(hdr, spa, zb);
b5256303
TC
1960 if (ret != 0)
1961 goto error;
1962 }
1963
1964 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
1965
1966 if (hash_lock != NULL)
1967 mutex_exit(hash_lock);
1968
1969 return (0);
1970
1971error:
1972 if (hash_lock != NULL)
1973 mutex_exit(hash_lock);
1974
1975 return (ret);
1976}
1977
1978/*
1979 * This function is used by the dbuf code to decrypt bonus buffers in place.
1980 * The dbuf code itself doesn't have any locking for decrypting a shared dnode
1981 * block, so we use the hash lock here to protect against concurrent calls to
1982 * arc_buf_fill().
1983 */
1984static void
14e4e3cb 1985arc_buf_untransform_in_place(arc_buf_t *buf)
b5256303
TC
1986{
1987 arc_buf_hdr_t *hdr = buf->b_hdr;
1988
1989 ASSERT(HDR_ENCRYPTED(hdr));
1990 ASSERT3U(hdr->b_crypt_hdr.b_ot, ==, DMU_OT_DNODE);
ca6c7a94 1991 ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
b5256303
TC
1992 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
1993
1994 zio_crypt_copy_dnode_bonus(hdr->b_l1hdr.b_pabd, buf->b_data,
1995 arc_buf_size(buf));
1996 buf->b_flags &= ~ARC_BUF_FLAG_ENCRYPTED;
1997 buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
1998 hdr->b_crypt_hdr.b_ebufcnt -= 1;
1999}
2000
524b4217
DK
2001/*
2002 * Given a buf that has a data buffer attached to it, this function will
2003 * efficiently fill the buf with data of the specified compression setting from
2004 * the hdr and update the hdr's b_freeze_cksum if necessary. If the buf and hdr
2005 * are already sharing a data buf, no copy is performed.
2006 *
2007 * If the buf is marked as compressed but uncompressed data was requested, this
2008 * will allocate a new data buffer for the buf, remove that flag, and fill the
2009 * buf with uncompressed data. You can't request a compressed buf on a hdr with
2010 * uncompressed data, and (since we haven't added support for it yet) if you
2011 * want compressed data your buf must already be marked as compressed and have
2012 * the correct-sized data buffer.
2013 */
2014static int
be9a5c35
TC
2015arc_buf_fill(arc_buf_t *buf, spa_t *spa, const zbookmark_phys_t *zb,
2016 arc_fill_flags_t flags)
d3c2ae1c 2017{
b5256303 2018 int error = 0;
d3c2ae1c 2019 arc_buf_hdr_t *hdr = buf->b_hdr;
b5256303
TC
2020 boolean_t hdr_compressed =
2021 (arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF);
2022 boolean_t compressed = (flags & ARC_FILL_COMPRESSED) != 0;
2023 boolean_t encrypted = (flags & ARC_FILL_ENCRYPTED) != 0;
d3c2ae1c 2024 dmu_object_byteswap_t bswap = hdr->b_l1hdr.b_byteswap;
b5256303 2025 kmutex_t *hash_lock = (flags & ARC_FILL_LOCKED) ? NULL : HDR_LOCK(hdr);
d3c2ae1c 2026
524b4217 2027 ASSERT3P(buf->b_data, !=, NULL);
b5256303 2028 IMPLY(compressed, hdr_compressed || ARC_BUF_ENCRYPTED(buf));
524b4217 2029 IMPLY(compressed, ARC_BUF_COMPRESSED(buf));
b5256303
TC
2030 IMPLY(encrypted, HDR_ENCRYPTED(hdr));
2031 IMPLY(encrypted, ARC_BUF_ENCRYPTED(buf));
2032 IMPLY(encrypted, ARC_BUF_COMPRESSED(buf));
2033 IMPLY(encrypted, !ARC_BUF_SHARED(buf));
2034
2035 /*
2036 * If the caller wanted encrypted data we just need to copy it from
2037 * b_rabd and potentially byteswap it. We won't be able to do any
2038 * further transforms on it.
2039 */
2040 if (encrypted) {
2041 ASSERT(HDR_HAS_RABD(hdr));
2042 abd_copy_to_buf(buf->b_data, hdr->b_crypt_hdr.b_rabd,
2043 HDR_GET_PSIZE(hdr));
2044 goto byteswap;
2045 }
2046
2047 /*
e1cfd73f 2048 * Adjust encrypted and authenticated headers to accommodate
69830602
TC
2049 * the request if needed. Dnode blocks (ARC_FILL_IN_PLACE) are
2050 * allowed to fail decryption due to keys not being loaded
2051 * without being marked as an IO error.
b5256303
TC
2052 */
2053 if (HDR_PROTECTED(hdr)) {
2054 error = arc_fill_hdr_crypt(hdr, hash_lock, spa,
be9a5c35 2055 zb, !!(flags & ARC_FILL_NOAUTH));
69830602
TC
2056 if (error == EACCES && (flags & ARC_FILL_IN_PLACE) != 0) {
2057 return (error);
2058 } else if (error != 0) {
e7504d7a
TC
2059 if (hash_lock != NULL)
2060 mutex_enter(hash_lock);
2c24b5b1 2061 arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
e7504d7a
TC
2062 if (hash_lock != NULL)
2063 mutex_exit(hash_lock);
b5256303 2064 return (error);
2c24b5b1 2065 }
b5256303
TC
2066 }
2067
2068 /*
2069 * There is a special case here for dnode blocks which are
2070 * decrypting their bonus buffers. These blocks may request to
2071 * be decrypted in-place. This is necessary because there may
2072 * be many dnodes pointing into this buffer and there is
2073 * currently no method to synchronize replacing the backing
2074 * b_data buffer and updating all of the pointers. Here we use
2075 * the hash lock to ensure there are no races. If the need
2076 * arises for other types to be decrypted in-place, they must
2077 * add handling here as well.
2078 */
2079 if ((flags & ARC_FILL_IN_PLACE) != 0) {
2080 ASSERT(!hdr_compressed);
2081 ASSERT(!compressed);
2082 ASSERT(!encrypted);
2083
2084 if (HDR_ENCRYPTED(hdr) && ARC_BUF_ENCRYPTED(buf)) {
2085 ASSERT3U(hdr->b_crypt_hdr.b_ot, ==, DMU_OT_DNODE);
2086
2087 if (hash_lock != NULL)
2088 mutex_enter(hash_lock);
14e4e3cb 2089 arc_buf_untransform_in_place(buf);
b5256303
TC
2090 if (hash_lock != NULL)
2091 mutex_exit(hash_lock);
2092
2093 /* Compute the hdr's checksum if necessary */
2094 arc_cksum_compute(buf);
2095 }
2096
2097 return (0);
2098 }
524b4217
DK
2099
2100 if (hdr_compressed == compressed) {
2aa34383 2101 if (!arc_buf_is_shared(buf)) {
a6255b7f 2102 abd_copy_to_buf(buf->b_data, hdr->b_l1hdr.b_pabd,
524b4217 2103 arc_buf_size(buf));
2aa34383 2104 }
d3c2ae1c 2105 } else {
524b4217
DK
2106 ASSERT(hdr_compressed);
2107 ASSERT(!compressed);
2aa34383
DK
2108
2109 /*
524b4217
DK
2110 * If the buf is sharing its data with the hdr, unlink it and
2111 * allocate a new data buffer for the buf.
2aa34383 2112 */
524b4217
DK
2113 if (arc_buf_is_shared(buf)) {
2114 ASSERT(ARC_BUF_COMPRESSED(buf));
2115
e1cfd73f 2116 /* We need to give the buf its own b_data */
524b4217 2117 buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
2aa34383
DK
2118 buf->b_data =
2119 arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
2120 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2121
524b4217 2122 /* Previously overhead was 0; just add new overhead */
2aa34383 2123 ARCSTAT_INCR(arcstat_overhead_size, HDR_GET_LSIZE(hdr));
524b4217
DK
2124 } else if (ARC_BUF_COMPRESSED(buf)) {
2125 /* We need to reallocate the buf's b_data */
2126 arc_free_data_buf(hdr, buf->b_data, HDR_GET_PSIZE(hdr),
2127 buf);
2128 buf->b_data =
2129 arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
2130
2131 /* We increased the size of b_data; update overhead */
2132 ARCSTAT_INCR(arcstat_overhead_size,
2133 HDR_GET_LSIZE(hdr) - HDR_GET_PSIZE(hdr));
2aa34383
DK
2134 }
2135
524b4217
DK
2136 /*
2137 * Regardless of the buf's previous compression settings, it
2138 * should not be compressed at the end of this function.
2139 */
2140 buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
2141
2142 /*
2143 * Try copying the data from another buf which already has a
2144 * decompressed version. If that's not possible, it's time to
2145 * bite the bullet and decompress the data from the hdr.
2146 */
2147 if (arc_buf_try_copy_decompressed_data(buf)) {
2148 /* Skip byteswapping and checksumming (already done) */
524b4217
DK
2149 return (0);
2150 } else {
b5256303 2151 error = zio_decompress_data(HDR_GET_COMPRESS(hdr),
a6255b7f 2152 hdr->b_l1hdr.b_pabd, buf->b_data,
10b3c7f5
MN
2153 HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr),
2154 &hdr->b_complevel);
524b4217
DK
2155
2156 /*
2157 * Absent hardware errors or software bugs, this should
2158 * be impossible, but log it anyway so we can debug it.
2159 */
2160 if (error != 0) {
2161 zfs_dbgmsg(
a887d653 2162 "hdr %px, compress %d, psize %d, lsize %d",
b5256303 2163 hdr, arc_hdr_get_compress(hdr),
524b4217 2164 HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
e7504d7a
TC
2165 if (hash_lock != NULL)
2166 mutex_enter(hash_lock);
2c24b5b1 2167 arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
e7504d7a
TC
2168 if (hash_lock != NULL)
2169 mutex_exit(hash_lock);
524b4217
DK
2170 return (SET_ERROR(EIO));
2171 }
d3c2ae1c
GW
2172 }
2173 }
524b4217 2174
b5256303 2175byteswap:
524b4217 2176 /* Byteswap the buf's data if necessary */
d3c2ae1c
GW
2177 if (bswap != DMU_BSWAP_NUMFUNCS) {
2178 ASSERT(!HDR_SHARED_DATA(hdr));
2179 ASSERT3U(bswap, <, DMU_BSWAP_NUMFUNCS);
2180 dmu_ot_byteswap[bswap].ob_func(buf->b_data, HDR_GET_LSIZE(hdr));
2181 }
524b4217
DK
2182
2183 /* Compute the hdr's checksum if necessary */
d3c2ae1c 2184 arc_cksum_compute(buf);
524b4217 2185
d3c2ae1c
GW
2186 return (0);
2187}
2188
2189/*
b5256303
TC
2190 * If this function is being called to decrypt an encrypted buffer or verify an
2191 * authenticated one, the key must be loaded and a mapping must be made
2192 * available in the keystore via spa_keystore_create_mapping() or one of its
2193 * callers.
d3c2ae1c 2194 */
b5256303 2195int
a2c2ed1b
TC
2196arc_untransform(arc_buf_t *buf, spa_t *spa, const zbookmark_phys_t *zb,
2197 boolean_t in_place)
d3c2ae1c 2198{
a2c2ed1b 2199 int ret;
b5256303 2200 arc_fill_flags_t flags = 0;
d3c2ae1c 2201
b5256303
TC
2202 if (in_place)
2203 flags |= ARC_FILL_IN_PLACE;
2204
be9a5c35 2205 ret = arc_buf_fill(buf, spa, zb, flags);
a2c2ed1b
TC
2206 if (ret == ECKSUM) {
2207 /*
2208 * Convert authentication and decryption errors to EIO
2209 * (and generate an ereport) before leaving the ARC.
2210 */
2211 ret = SET_ERROR(EIO);
431083f7 2212 spa_log_error(spa, zb, &buf->b_hdr->b_birth);
1144586b 2213 (void) zfs_ereport_post(FM_EREPORT_ZFS_AUTHENTICATION,
4f072827 2214 spa, NULL, zb, NULL, 0);
a2c2ed1b
TC
2215 }
2216
2217 return (ret);
d3c2ae1c
GW
2218}
2219
2220/*
2221 * Increment the amount of evictable space in the arc_state_t's refcount.
2222 * We account for the space used by the hdr and the arc buf individually
2223 * so that we can add and remove them from the refcount individually.
2224 */
34dc7c2f 2225static void
d3c2ae1c
GW
2226arc_evictable_space_increment(arc_buf_hdr_t *hdr, arc_state_t *state)
2227{
2228 arc_buf_contents_t type = arc_buf_type(hdr);
d3c2ae1c
GW
2229
2230 ASSERT(HDR_HAS_L1HDR(hdr));
2231
2232 if (GHOST_STATE(state)) {
2233 ASSERT0(hdr->b_l1hdr.b_bufcnt);
2234 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
a6255b7f 2235 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
b5256303 2236 ASSERT(!HDR_HAS_RABD(hdr));
424fd7c3 2237 (void) zfs_refcount_add_many(&state->arcs_esize[type],
2aa34383 2238 HDR_GET_LSIZE(hdr), hdr);
d3c2ae1c
GW
2239 return;
2240 }
2241
a6255b7f 2242 if (hdr->b_l1hdr.b_pabd != NULL) {
424fd7c3 2243 (void) zfs_refcount_add_many(&state->arcs_esize[type],
d3c2ae1c
GW
2244 arc_hdr_size(hdr), hdr);
2245 }
b5256303 2246 if (HDR_HAS_RABD(hdr)) {
424fd7c3 2247 (void) zfs_refcount_add_many(&state->arcs_esize[type],
b5256303
TC
2248 HDR_GET_PSIZE(hdr), hdr);
2249 }
2250
1c27024e
DB
2251 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2252 buf = buf->b_next) {
2aa34383 2253 if (arc_buf_is_shared(buf))
d3c2ae1c 2254 continue;
424fd7c3 2255 (void) zfs_refcount_add_many(&state->arcs_esize[type],
2aa34383 2256 arc_buf_size(buf), buf);
d3c2ae1c
GW
2257 }
2258}
2259
2260/*
2261 * Decrement the amount of evictable space in the arc_state_t's refcount.
2262 * We account for the space used by the hdr and the arc buf individually
2263 * so that we can add and remove them from the refcount individually.
2264 */
2265static void
2aa34383 2266arc_evictable_space_decrement(arc_buf_hdr_t *hdr, arc_state_t *state)
d3c2ae1c
GW
2267{
2268 arc_buf_contents_t type = arc_buf_type(hdr);
d3c2ae1c
GW
2269
2270 ASSERT(HDR_HAS_L1HDR(hdr));
2271
2272 if (GHOST_STATE(state)) {
2273 ASSERT0(hdr->b_l1hdr.b_bufcnt);
2274 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
a6255b7f 2275 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
b5256303 2276 ASSERT(!HDR_HAS_RABD(hdr));
424fd7c3 2277 (void) zfs_refcount_remove_many(&state->arcs_esize[type],
2aa34383 2278 HDR_GET_LSIZE(hdr), hdr);
d3c2ae1c
GW
2279 return;
2280 }
2281
a6255b7f 2282 if (hdr->b_l1hdr.b_pabd != NULL) {
424fd7c3 2283 (void) zfs_refcount_remove_many(&state->arcs_esize[type],
d3c2ae1c
GW
2284 arc_hdr_size(hdr), hdr);
2285 }
b5256303 2286 if (HDR_HAS_RABD(hdr)) {
424fd7c3 2287 (void) zfs_refcount_remove_many(&state->arcs_esize[type],
b5256303
TC
2288 HDR_GET_PSIZE(hdr), hdr);
2289 }
2290
1c27024e
DB
2291 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2292 buf = buf->b_next) {
2aa34383 2293 if (arc_buf_is_shared(buf))
d3c2ae1c 2294 continue;
424fd7c3 2295 (void) zfs_refcount_remove_many(&state->arcs_esize[type],
2aa34383 2296 arc_buf_size(buf), buf);
d3c2ae1c
GW
2297 }
2298}
2299
2300/*
2301 * Add a reference to this hdr indicating that someone is actively
2302 * referencing that memory. When the refcount transitions from 0 to 1,
2303 * we remove it from the respective arc_state_t list to indicate that
2304 * it is not evictable.
2305 */
2306static void
a926aab9 2307add_reference(arc_buf_hdr_t *hdr, const void *tag)
34dc7c2f 2308{
c935fe2e 2309 arc_state_t *state = hdr->b_l1hdr.b_state;
b9541d6b
CW
2310
2311 ASSERT(HDR_HAS_L1HDR(hdr));
ca6c7a94 2312 if (!HDR_EMPTY(hdr) && !MUTEX_HELD(HDR_LOCK(hdr))) {
c935fe2e 2313 ASSERT(state == arc_anon);
424fd7c3 2314 ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
d3c2ae1c
GW
2315 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2316 }
34dc7c2f 2317
c13060e4 2318 if ((zfs_refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
c935fe2e 2319 state != arc_anon && state != arc_l2c_only) {
b9541d6b 2320 /* We don't use the L2-only state list. */
c935fe2e
AM
2321 multilist_remove(&state->arcs_list[arc_buf_type(hdr)], hdr);
2322 arc_evictable_space_decrement(hdr, state);
34dc7c2f
BB
2323 }
2324}
2325
d3c2ae1c
GW
2326/*
2327 * Remove a reference from this hdr. When the reference transitions from
2328 * 1 to 0 and we're not anonymous, then we add this hdr to the arc_state_t's
2329 * list making it eligible for eviction.
2330 */
34dc7c2f 2331static int
c935fe2e 2332remove_reference(arc_buf_hdr_t *hdr, const void *tag)
34dc7c2f
BB
2333{
2334 int cnt;
b9541d6b 2335 arc_state_t *state = hdr->b_l1hdr.b_state;
34dc7c2f 2336
b9541d6b 2337 ASSERT(HDR_HAS_L1HDR(hdr));
c935fe2e 2338 ASSERT(state == arc_anon || MUTEX_HELD(HDR_LOCK(hdr)));
ed2f7ba0 2339 ASSERT(!GHOST_STATE(state)); /* arc_l2c_only counts as a ghost. */
34dc7c2f 2340
ed2f7ba0
AM
2341 if ((cnt = zfs_refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) != 0)
2342 return (cnt);
2343
2344 if (state == arc_anon) {
2345 arc_hdr_destroy(hdr);
2346 return (0);
34dc7c2f 2347 }
ed2f7ba0
AM
2348 if (state == arc_uncached && !HDR_PREFETCH(hdr)) {
2349 arc_change_state(arc_anon, hdr);
2350 arc_hdr_destroy(hdr);
2351 return (0);
2352 }
2353 multilist_insert(&state->arcs_list[arc_buf_type(hdr)], hdr);
2354 arc_evictable_space_increment(hdr, state);
2355 return (0);
34dc7c2f
BB
2356}
2357
e0b0ca98
BB
2358/*
2359 * Returns detailed information about a specific arc buffer. When the
2360 * state_index argument is set the function will calculate the arc header
2361 * list position for its arc state. Since this requires a linear traversal
2362 * callers are strongly encourage not to do this. However, it can be helpful
2363 * for targeted analysis so the functionality is provided.
2364 */
2365void
2366arc_buf_info(arc_buf_t *ab, arc_buf_info_t *abi, int state_index)
2367{
14e4e3cb 2368 (void) state_index;
e0b0ca98 2369 arc_buf_hdr_t *hdr = ab->b_hdr;
b9541d6b
CW
2370 l1arc_buf_hdr_t *l1hdr = NULL;
2371 l2arc_buf_hdr_t *l2hdr = NULL;
2372 arc_state_t *state = NULL;
2373
8887c7d7
TC
2374 memset(abi, 0, sizeof (arc_buf_info_t));
2375
2376 if (hdr == NULL)
2377 return;
2378
2379 abi->abi_flags = hdr->b_flags;
2380
b9541d6b
CW
2381 if (HDR_HAS_L1HDR(hdr)) {
2382 l1hdr = &hdr->b_l1hdr;
2383 state = l1hdr->b_state;
2384 }
2385 if (HDR_HAS_L2HDR(hdr))
2386 l2hdr = &hdr->b_l2hdr;
e0b0ca98 2387
b9541d6b 2388 if (l1hdr) {
d3c2ae1c 2389 abi->abi_bufcnt = l1hdr->b_bufcnt;
b9541d6b
CW
2390 abi->abi_access = l1hdr->b_arc_access;
2391 abi->abi_mru_hits = l1hdr->b_mru_hits;
2392 abi->abi_mru_ghost_hits = l1hdr->b_mru_ghost_hits;
2393 abi->abi_mfu_hits = l1hdr->b_mfu_hits;
2394 abi->abi_mfu_ghost_hits = l1hdr->b_mfu_ghost_hits;
424fd7c3 2395 abi->abi_holds = zfs_refcount_count(&l1hdr->b_refcnt);
b9541d6b
CW
2396 }
2397
2398 if (l2hdr) {
2399 abi->abi_l2arc_dattr = l2hdr->b_daddr;
b9541d6b
CW
2400 abi->abi_l2arc_hits = l2hdr->b_hits;
2401 }
2402
e0b0ca98 2403 abi->abi_state_type = state ? state->arcs_state : ARC_STATE_ANON;
b9541d6b 2404 abi->abi_state_contents = arc_buf_type(hdr);
d3c2ae1c 2405 abi->abi_size = arc_hdr_size(hdr);
e0b0ca98
BB
2406}
2407
34dc7c2f 2408/*
ca0bf58d 2409 * Move the supplied buffer to the indicated state. The hash lock
34dc7c2f
BB
2410 * for the buffer must be held by the caller.
2411 */
2412static void
c935fe2e 2413arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr)
34dc7c2f 2414{
b9541d6b
CW
2415 arc_state_t *old_state;
2416 int64_t refcnt;
d3c2ae1c
GW
2417 uint32_t bufcnt;
2418 boolean_t update_old, update_new;
a8d83e2a 2419 arc_buf_contents_t type = arc_buf_type(hdr);
b9541d6b
CW
2420
2421 /*
2422 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
2423 * in arc_read() when bringing a buffer out of the L2ARC. However, the
2424 * L1 hdr doesn't always exist when we change state to arc_anon before
2425 * destroying a header, in which case reallocating to add the L1 hdr is
2426 * pointless.
2427 */
2428 if (HDR_HAS_L1HDR(hdr)) {
2429 old_state = hdr->b_l1hdr.b_state;
424fd7c3 2430 refcnt = zfs_refcount_count(&hdr->b_l1hdr.b_refcnt);
d3c2ae1c 2431 bufcnt = hdr->b_l1hdr.b_bufcnt;
b5256303
TC
2432 update_old = (bufcnt > 0 || hdr->b_l1hdr.b_pabd != NULL ||
2433 HDR_HAS_RABD(hdr));
c935fe2e
AM
2434
2435 IMPLY(GHOST_STATE(old_state), bufcnt == 0);
2436 IMPLY(GHOST_STATE(new_state), bufcnt == 0);
2437 IMPLY(GHOST_STATE(old_state), hdr->b_l1hdr.b_buf == NULL);
2438 IMPLY(GHOST_STATE(new_state), hdr->b_l1hdr.b_buf == NULL);
2439 IMPLY(old_state == arc_anon, bufcnt <= 1);
b9541d6b
CW
2440 } else {
2441 old_state = arc_l2c_only;
2442 refcnt = 0;
d3c2ae1c
GW
2443 bufcnt = 0;
2444 update_old = B_FALSE;
b9541d6b 2445 }
d3c2ae1c 2446 update_new = update_old;
c935fe2e
AM
2447 if (GHOST_STATE(old_state))
2448 update_old = B_TRUE;
2449 if (GHOST_STATE(new_state))
2450 update_new = B_TRUE;
34dc7c2f 2451
c935fe2e 2452 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
e8b96c60 2453 ASSERT3P(new_state, !=, old_state);
34dc7c2f
BB
2454
2455 /*
2456 * If this buffer is evictable, transfer it from the
2457 * old state list to the new state list.
2458 */
2459 if (refcnt == 0) {
b9541d6b 2460 if (old_state != arc_anon && old_state != arc_l2c_only) {
b9541d6b 2461 ASSERT(HDR_HAS_L1HDR(hdr));
ed2f7ba0
AM
2462 /* remove_reference() saves on insert. */
2463 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
a8d83e2a 2464 multilist_remove(&old_state->arcs_list[type],
ed2f7ba0
AM
2465 hdr);
2466 arc_evictable_space_decrement(hdr, old_state);
2467 }
34dc7c2f 2468 }
b9541d6b 2469 if (new_state != arc_anon && new_state != arc_l2c_only) {
b9541d6b
CW
2470 /*
2471 * An L1 header always exists here, since if we're
2472 * moving to some L1-cached state (i.e. not l2c_only or
2473 * anonymous), we realloc the header to add an L1hdr
2474 * beforehand.
2475 */
2476 ASSERT(HDR_HAS_L1HDR(hdr));
a8d83e2a 2477 multilist_insert(&new_state->arcs_list[type], hdr);
d3c2ae1c 2478 arc_evictable_space_increment(hdr, new_state);
34dc7c2f
BB
2479 }
2480 }
2481
d3c2ae1c 2482 ASSERT(!HDR_EMPTY(hdr));
2a432414
GW
2483 if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
2484 buf_hash_remove(hdr);
34dc7c2f 2485
b9541d6b 2486 /* adjust state sizes (ignore arc_l2c_only) */
36da08ef 2487
d3c2ae1c 2488 if (update_new && new_state != arc_l2c_only) {
36da08ef
PS
2489 ASSERT(HDR_HAS_L1HDR(hdr));
2490 if (GHOST_STATE(new_state)) {
d3c2ae1c 2491 ASSERT0(bufcnt);
36da08ef
PS
2492
2493 /*
d3c2ae1c 2494 * When moving a header to a ghost state, we first
36da08ef 2495 * remove all arc buffers. Thus, we'll have a
d3c2ae1c 2496 * bufcnt of zero, and no arc buffer to use for
36da08ef
PS
2497 * the reference. As a result, we use the arc
2498 * header pointer for the reference.
2499 */
a8d83e2a
AM
2500 (void) zfs_refcount_add_many(
2501 &new_state->arcs_size[type],
d3c2ae1c 2502 HDR_GET_LSIZE(hdr), hdr);
a6255b7f 2503 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
b5256303 2504 ASSERT(!HDR_HAS_RABD(hdr));
36da08ef 2505 } else {
d3c2ae1c 2506 uint32_t buffers = 0;
36da08ef
PS
2507
2508 /*
2509 * Each individual buffer holds a unique reference,
2510 * thus we must remove each of these references one
2511 * at a time.
2512 */
1c27024e 2513 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
36da08ef 2514 buf = buf->b_next) {
d3c2ae1c
GW
2515 ASSERT3U(bufcnt, !=, 0);
2516 buffers++;
2517
2518 /*
2519 * When the arc_buf_t is sharing the data
2520 * block with the hdr, the owner of the
2521 * reference belongs to the hdr. Only
2522 * add to the refcount if the arc_buf_t is
2523 * not shared.
2524 */
2aa34383 2525 if (arc_buf_is_shared(buf))
d3c2ae1c 2526 continue;
d3c2ae1c 2527
424fd7c3 2528 (void) zfs_refcount_add_many(
a8d83e2a 2529 &new_state->arcs_size[type],
2aa34383 2530 arc_buf_size(buf), buf);
d3c2ae1c
GW
2531 }
2532 ASSERT3U(bufcnt, ==, buffers);
2533
a6255b7f 2534 if (hdr->b_l1hdr.b_pabd != NULL) {
424fd7c3 2535 (void) zfs_refcount_add_many(
a8d83e2a 2536 &new_state->arcs_size[type],
d3c2ae1c 2537 arc_hdr_size(hdr), hdr);
b5256303
TC
2538 }
2539
2540 if (HDR_HAS_RABD(hdr)) {
424fd7c3 2541 (void) zfs_refcount_add_many(
a8d83e2a 2542 &new_state->arcs_size[type],
b5256303 2543 HDR_GET_PSIZE(hdr), hdr);
36da08ef
PS
2544 }
2545 }
2546 }
2547
d3c2ae1c 2548 if (update_old && old_state != arc_l2c_only) {
36da08ef
PS
2549 ASSERT(HDR_HAS_L1HDR(hdr));
2550 if (GHOST_STATE(old_state)) {
d3c2ae1c 2551 ASSERT0(bufcnt);
a6255b7f 2552 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
b5256303 2553 ASSERT(!HDR_HAS_RABD(hdr));
d3c2ae1c 2554
36da08ef
PS
2555 /*
2556 * When moving a header off of a ghost state,
d3c2ae1c
GW
2557 * the header will not contain any arc buffers.
2558 * We use the arc header pointer for the reference
2559 * which is exactly what we did when we put the
2560 * header on the ghost state.
36da08ef
PS
2561 */
2562
a8d83e2a
AM
2563 (void) zfs_refcount_remove_many(
2564 &old_state->arcs_size[type],
d3c2ae1c 2565 HDR_GET_LSIZE(hdr), hdr);
36da08ef 2566 } else {
d3c2ae1c 2567 uint32_t buffers = 0;
36da08ef
PS
2568
2569 /*
2570 * Each individual buffer holds a unique reference,
2571 * thus we must remove each of these references one
2572 * at a time.
2573 */
1c27024e 2574 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
36da08ef 2575 buf = buf->b_next) {
d3c2ae1c
GW
2576 ASSERT3U(bufcnt, !=, 0);
2577 buffers++;
2578
2579 /*
2580 * When the arc_buf_t is sharing the data
2581 * block with the hdr, the owner of the
2582 * reference belongs to the hdr. Only
2583 * add to the refcount if the arc_buf_t is
2584 * not shared.
2585 */
2aa34383 2586 if (arc_buf_is_shared(buf))
d3c2ae1c 2587 continue;
d3c2ae1c 2588
424fd7c3 2589 (void) zfs_refcount_remove_many(
a8d83e2a
AM
2590 &old_state->arcs_size[type],
2591 arc_buf_size(buf), buf);
36da08ef 2592 }
d3c2ae1c 2593 ASSERT3U(bufcnt, ==, buffers);
b5256303
TC
2594 ASSERT(hdr->b_l1hdr.b_pabd != NULL ||
2595 HDR_HAS_RABD(hdr));
2596
2597 if (hdr->b_l1hdr.b_pabd != NULL) {
424fd7c3 2598 (void) zfs_refcount_remove_many(
a8d83e2a
AM
2599 &old_state->arcs_size[type],
2600 arc_hdr_size(hdr), hdr);
b5256303
TC
2601 }
2602
2603 if (HDR_HAS_RABD(hdr)) {
424fd7c3 2604 (void) zfs_refcount_remove_many(
a8d83e2a
AM
2605 &old_state->arcs_size[type],
2606 HDR_GET_PSIZE(hdr), hdr);
b5256303 2607 }
36da08ef 2608 }
34dc7c2f 2609 }
36da08ef 2610
08532162 2611 if (HDR_HAS_L1HDR(hdr)) {
b9541d6b 2612 hdr->b_l1hdr.b_state = new_state;
34dc7c2f 2613
08532162
GA
2614 if (HDR_HAS_L2HDR(hdr) && new_state != arc_l2c_only) {
2615 l2arc_hdr_arcstats_decrement_state(hdr);
2616 hdr->b_l2hdr.b_arcs_state = new_state->arcs_state;
2617 l2arc_hdr_arcstats_increment_state(hdr);
2618 }
2619 }
34dc7c2f
BB
2620}
2621
2622void
d164b209 2623arc_space_consume(uint64_t space, arc_space_type_t type)
34dc7c2f 2624{
d164b209
BB
2625 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2626
2627 switch (type) {
e75c13c3
BB
2628 default:
2629 break;
d164b209 2630 case ARC_SPACE_DATA:
c4c162c1 2631 ARCSTAT_INCR(arcstat_data_size, space);
d164b209 2632 break;
cc7f677c 2633 case ARC_SPACE_META:
c4c162c1 2634 ARCSTAT_INCR(arcstat_metadata_size, space);
cc7f677c 2635 break;
25458cbe 2636 case ARC_SPACE_BONUS:
c4c162c1 2637 ARCSTAT_INCR(arcstat_bonus_size, space);
25458cbe
TC
2638 break;
2639 case ARC_SPACE_DNODE:
a8d83e2a 2640 ARCSTAT_INCR(arcstat_dnode_size, space);
25458cbe
TC
2641 break;
2642 case ARC_SPACE_DBUF:
c4c162c1 2643 ARCSTAT_INCR(arcstat_dbuf_size, space);
d164b209
BB
2644 break;
2645 case ARC_SPACE_HDRS:
c4c162c1 2646 ARCSTAT_INCR(arcstat_hdr_size, space);
d164b209
BB
2647 break;
2648 case ARC_SPACE_L2HDRS:
c4c162c1 2649 aggsum_add(&arc_sums.arcstat_l2_hdr_size, space);
d164b209 2650 break;
85ec5cba
MA
2651 case ARC_SPACE_ABD_CHUNK_WASTE:
2652 /*
2653 * Note: this includes space wasted by all scatter ABD's, not
2654 * just those allocated by the ARC. But the vast majority of
2655 * scatter ABD's come from the ARC, because other users are
2656 * very short-lived.
2657 */
c4c162c1 2658 ARCSTAT_INCR(arcstat_abd_chunk_waste_size, space);
85ec5cba 2659 break;
d164b209
BB
2660 }
2661
85ec5cba 2662 if (type != ARC_SPACE_DATA && type != ARC_SPACE_ABD_CHUNK_WASTE)
a8d83e2a 2663 ARCSTAT_INCR(arcstat_meta_used, space);
cc7f677c 2664
c4c162c1 2665 aggsum_add(&arc_sums.arcstat_size, space);
34dc7c2f
BB
2666}
2667
2668void
d164b209 2669arc_space_return(uint64_t space, arc_space_type_t type)
34dc7c2f 2670{
d164b209
BB
2671 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2672
2673 switch (type) {
e75c13c3
BB
2674 default:
2675 break;
d164b209 2676 case ARC_SPACE_DATA:
c4c162c1 2677 ARCSTAT_INCR(arcstat_data_size, -space);
d164b209 2678 break;
cc7f677c 2679 case ARC_SPACE_META:
c4c162c1 2680 ARCSTAT_INCR(arcstat_metadata_size, -space);
cc7f677c 2681 break;
25458cbe 2682 case ARC_SPACE_BONUS:
c4c162c1 2683 ARCSTAT_INCR(arcstat_bonus_size, -space);
25458cbe
TC
2684 break;
2685 case ARC_SPACE_DNODE:
a8d83e2a 2686 ARCSTAT_INCR(arcstat_dnode_size, -space);
25458cbe
TC
2687 break;
2688 case ARC_SPACE_DBUF:
c4c162c1 2689 ARCSTAT_INCR(arcstat_dbuf_size, -space);
d164b209
BB
2690 break;
2691 case ARC_SPACE_HDRS:
c4c162c1 2692 ARCSTAT_INCR(arcstat_hdr_size, -space);
d164b209
BB
2693 break;
2694 case ARC_SPACE_L2HDRS:
c4c162c1 2695 aggsum_add(&arc_sums.arcstat_l2_hdr_size, -space);
d164b209 2696 break;
85ec5cba 2697 case ARC_SPACE_ABD_CHUNK_WASTE:
c4c162c1 2698 ARCSTAT_INCR(arcstat_abd_chunk_waste_size, -space);
85ec5cba 2699 break;
d164b209
BB
2700 }
2701
a8d83e2a
AM
2702 if (type != ARC_SPACE_DATA && type != ARC_SPACE_ABD_CHUNK_WASTE)
2703 ARCSTAT_INCR(arcstat_meta_used, -space);
cc7f677c 2704
c4c162c1
AM
2705 ASSERT(aggsum_compare(&arc_sums.arcstat_size, space) >= 0);
2706 aggsum_add(&arc_sums.arcstat_size, -space);
34dc7c2f
BB
2707}
2708
d3c2ae1c 2709/*
524b4217 2710 * Given a hdr and a buf, returns whether that buf can share its b_data buffer
a6255b7f 2711 * with the hdr's b_pabd.
d3c2ae1c 2712 */
524b4217
DK
2713static boolean_t
2714arc_can_share(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2715{
524b4217
DK
2716 /*
2717 * The criteria for sharing a hdr's data are:
b5256303
TC
2718 * 1. the buffer is not encrypted
2719 * 2. the hdr's compression matches the buf's compression
2720 * 3. the hdr doesn't need to be byteswapped
2721 * 4. the hdr isn't already being shared
2722 * 5. the buf is either compressed or it is the last buf in the hdr list
524b4217 2723 *
b5256303 2724 * Criterion #5 maintains the invariant that shared uncompressed
524b4217
DK
2725 * bufs must be the final buf in the hdr's b_buf list. Reading this, you
2726 * might ask, "if a compressed buf is allocated first, won't that be the
2727 * last thing in the list?", but in that case it's impossible to create
2728 * a shared uncompressed buf anyway (because the hdr must be compressed
2729 * to have the compressed buf). You might also think that #3 is
2730 * sufficient to make this guarantee, however it's possible
2731 * (specifically in the rare L2ARC write race mentioned in
2732 * arc_buf_alloc_impl()) there will be an existing uncompressed buf that
e1cfd73f 2733 * is shareable, but wasn't at the time of its allocation. Rather than
524b4217
DK
2734 * allow a new shared uncompressed buf to be created and then shuffle
2735 * the list around to make it the last element, this simply disallows
2736 * sharing if the new buf isn't the first to be added.
2737 */
2738 ASSERT3P(buf->b_hdr, ==, hdr);
b5256303
TC
2739 boolean_t hdr_compressed =
2740 arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF;
a7004725 2741 boolean_t buf_compressed = ARC_BUF_COMPRESSED(buf) != 0;
b5256303
TC
2742 return (!ARC_BUF_ENCRYPTED(buf) &&
2743 buf_compressed == hdr_compressed &&
524b4217
DK
2744 hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS &&
2745 !HDR_SHARED_DATA(hdr) &&
2746 (ARC_BUF_LAST(buf) || ARC_BUF_COMPRESSED(buf)));
2747}
2748
2749/*
2750 * Allocate a buf for this hdr. If you care about the data that's in the hdr,
2751 * or if you want a compressed buffer, pass those flags in. Returns 0 if the
2752 * copy was made successfully, or an error code otherwise.
2753 */
2754static int
be9a5c35 2755arc_buf_alloc_impl(arc_buf_hdr_t *hdr, spa_t *spa, const zbookmark_phys_t *zb,
a926aab9
AZ
2756 const void *tag, boolean_t encrypted, boolean_t compressed,
2757 boolean_t noauth, boolean_t fill, arc_buf_t **ret)
34dc7c2f 2758{
34dc7c2f 2759 arc_buf_t *buf;
b5256303 2760 arc_fill_flags_t flags = ARC_FILL_LOCKED;
34dc7c2f 2761
d3c2ae1c
GW
2762 ASSERT(HDR_HAS_L1HDR(hdr));
2763 ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
2764 VERIFY(hdr->b_type == ARC_BUFC_DATA ||
2765 hdr->b_type == ARC_BUFC_METADATA);
524b4217
DK
2766 ASSERT3P(ret, !=, NULL);
2767 ASSERT3P(*ret, ==, NULL);
b5256303 2768 IMPLY(encrypted, compressed);
d3c2ae1c 2769
524b4217 2770 buf = *ret = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
34dc7c2f
BB
2771 buf->b_hdr = hdr;
2772 buf->b_data = NULL;
2aa34383 2773 buf->b_next = hdr->b_l1hdr.b_buf;
524b4217 2774 buf->b_flags = 0;
b9541d6b 2775
d3c2ae1c
GW
2776 add_reference(hdr, tag);
2777
2778 /*
2779 * We're about to change the hdr's b_flags. We must either
2780 * hold the hash_lock or be undiscoverable.
2781 */
ca6c7a94 2782 ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
d3c2ae1c
GW
2783
2784 /*
524b4217 2785 * Only honor requests for compressed bufs if the hdr is actually
e1cfd73f 2786 * compressed. This must be overridden if the buffer is encrypted since
b5256303 2787 * encrypted buffers cannot be decompressed.
524b4217 2788 */
b5256303
TC
2789 if (encrypted) {
2790 buf->b_flags |= ARC_BUF_FLAG_COMPRESSED;
2791 buf->b_flags |= ARC_BUF_FLAG_ENCRYPTED;
2792 flags |= ARC_FILL_COMPRESSED | ARC_FILL_ENCRYPTED;
2793 } else if (compressed &&
2794 arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF) {
524b4217 2795 buf->b_flags |= ARC_BUF_FLAG_COMPRESSED;
b5256303
TC
2796 flags |= ARC_FILL_COMPRESSED;
2797 }
2798
2799 if (noauth) {
2800 ASSERT0(encrypted);
2801 flags |= ARC_FILL_NOAUTH;
2802 }
524b4217 2803
524b4217
DK
2804 /*
2805 * If the hdr's data can be shared then we share the data buffer and
2806 * set the appropriate bit in the hdr's b_flags to indicate the hdr is
5662fd57
MA
2807 * sharing it's b_pabd with the arc_buf_t. Otherwise, we allocate a new
2808 * buffer to store the buf's data.
524b4217 2809 *
a6255b7f
DQ
2810 * There are two additional restrictions here because we're sharing
2811 * hdr -> buf instead of the usual buf -> hdr. First, the hdr can't be
2812 * actively involved in an L2ARC write, because if this buf is used by
2813 * an arc_write() then the hdr's data buffer will be released when the
524b4217 2814 * write completes, even though the L2ARC write might still be using it.
a6255b7f 2815 * Second, the hdr's ABD must be linear so that the buf's user doesn't
5662fd57
MA
2816 * need to be ABD-aware. It must be allocated via
2817 * zio_[data_]buf_alloc(), not as a page, because we need to be able
2818 * to abd_release_ownership_of_buf(), which isn't allowed on "linear
2819 * page" buffers because the ABD code needs to handle freeing them
2820 * specially.
2821 */
2822 boolean_t can_share = arc_can_share(hdr, buf) &&
2823 !HDR_L2_WRITING(hdr) &&
2824 hdr->b_l1hdr.b_pabd != NULL &&
2825 abd_is_linear(hdr->b_l1hdr.b_pabd) &&
2826 !abd_is_linear_page(hdr->b_l1hdr.b_pabd);
524b4217
DK
2827
2828 /* Set up b_data and sharing */
2829 if (can_share) {
a6255b7f 2830 buf->b_data = abd_to_buf(hdr->b_l1hdr.b_pabd);
524b4217 2831 buf->b_flags |= ARC_BUF_FLAG_SHARED;
d3c2ae1c
GW
2832 arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
2833 } else {
524b4217
DK
2834 buf->b_data =
2835 arc_get_data_buf(hdr, arc_buf_size(buf), buf);
2836 ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
d3c2ae1c
GW
2837 }
2838 VERIFY3P(buf->b_data, !=, NULL);
b9541d6b
CW
2839
2840 hdr->b_l1hdr.b_buf = buf;
d3c2ae1c 2841 hdr->b_l1hdr.b_bufcnt += 1;
b5256303
TC
2842 if (encrypted)
2843 hdr->b_crypt_hdr.b_ebufcnt += 1;
b9541d6b 2844
524b4217
DK
2845 /*
2846 * If the user wants the data from the hdr, we need to either copy or
2847 * decompress the data.
2848 */
2849 if (fill) {
be9a5c35
TC
2850 ASSERT3P(zb, !=, NULL);
2851 return (arc_buf_fill(buf, spa, zb, flags));
524b4217 2852 }
d3c2ae1c 2853
524b4217 2854 return (0);
34dc7c2f
BB
2855}
2856
a926aab9 2857static const char *arc_onloan_tag = "onloan";
9babb374 2858
a7004725
DK
2859static inline void
2860arc_loaned_bytes_update(int64_t delta)
2861{
2862 atomic_add_64(&arc_loaned_bytes, delta);
2863
2864 /* assert that it did not wrap around */
2865 ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
2866}
2867
9babb374
BB
2868/*
2869 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
2870 * flight data by arc_tempreserve_space() until they are "returned". Loaned
2871 * buffers must be returned to the arc before they can be used by the DMU or
2872 * freed.
2873 */
2874arc_buf_t *
2aa34383 2875arc_loan_buf(spa_t *spa, boolean_t is_metadata, int size)
9babb374 2876{
2aa34383
DK
2877 arc_buf_t *buf = arc_alloc_buf(spa, arc_onloan_tag,
2878 is_metadata ? ARC_BUFC_METADATA : ARC_BUFC_DATA, size);
9babb374 2879
5152a740 2880 arc_loaned_bytes_update(arc_buf_size(buf));
a7004725 2881
9babb374
BB
2882 return (buf);
2883}
2884
2aa34383
DK
2885arc_buf_t *
2886arc_loan_compressed_buf(spa_t *spa, uint64_t psize, uint64_t lsize,
10b3c7f5 2887 enum zio_compress compression_type, uint8_t complevel)
2aa34383
DK
2888{
2889 arc_buf_t *buf = arc_alloc_compressed_buf(spa, arc_onloan_tag,
10b3c7f5 2890 psize, lsize, compression_type, complevel);
2aa34383 2891
5152a740 2892 arc_loaned_bytes_update(arc_buf_size(buf));
a7004725 2893
2aa34383
DK
2894 return (buf);
2895}
2896
b5256303
TC
2897arc_buf_t *
2898arc_loan_raw_buf(spa_t *spa, uint64_t dsobj, boolean_t byteorder,
2899 const uint8_t *salt, const uint8_t *iv, const uint8_t *mac,
2900 dmu_object_type_t ot, uint64_t psize, uint64_t lsize,
10b3c7f5 2901 enum zio_compress compression_type, uint8_t complevel)
b5256303
TC
2902{
2903 arc_buf_t *buf = arc_alloc_raw_buf(spa, arc_onloan_tag, dsobj,
10b3c7f5
MN
2904 byteorder, salt, iv, mac, ot, psize, lsize, compression_type,
2905 complevel);
b5256303
TC
2906
2907 atomic_add_64(&arc_loaned_bytes, psize);
2908 return (buf);
2909}
2910
2aa34383 2911
9babb374
BB
2912/*
2913 * Return a loaned arc buffer to the arc.
2914 */
2915void
dd66857d 2916arc_return_buf(arc_buf_t *buf, const void *tag)
9babb374
BB
2917{
2918 arc_buf_hdr_t *hdr = buf->b_hdr;
2919
d3c2ae1c 2920 ASSERT3P(buf->b_data, !=, NULL);
b9541d6b 2921 ASSERT(HDR_HAS_L1HDR(hdr));
c13060e4 2922 (void) zfs_refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
424fd7c3 2923 (void) zfs_refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
9babb374 2924
a7004725 2925 arc_loaned_bytes_update(-arc_buf_size(buf));
9babb374
BB
2926}
2927
428870ff
BB
2928/* Detach an arc_buf from a dbuf (tag) */
2929void
dd66857d 2930arc_loan_inuse_buf(arc_buf_t *buf, const void *tag)
428870ff 2931{
b9541d6b 2932 arc_buf_hdr_t *hdr = buf->b_hdr;
428870ff 2933
d3c2ae1c 2934 ASSERT3P(buf->b_data, !=, NULL);
b9541d6b 2935 ASSERT(HDR_HAS_L1HDR(hdr));
c13060e4 2936 (void) zfs_refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
424fd7c3 2937 (void) zfs_refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
428870ff 2938
a7004725 2939 arc_loaned_bytes_update(arc_buf_size(buf));
428870ff
BB
2940}
2941
d3c2ae1c 2942static void
a6255b7f 2943l2arc_free_abd_on_write(abd_t *abd, size_t size, arc_buf_contents_t type)
34dc7c2f 2944{
d3c2ae1c 2945 l2arc_data_free_t *df = kmem_alloc(sizeof (*df), KM_SLEEP);
34dc7c2f 2946
a6255b7f 2947 df->l2df_abd = abd;
d3c2ae1c
GW
2948 df->l2df_size = size;
2949 df->l2df_type = type;
2950 mutex_enter(&l2arc_free_on_write_mtx);
2951 list_insert_head(l2arc_free_on_write, df);
2952 mutex_exit(&l2arc_free_on_write_mtx);
2953}
428870ff 2954
d3c2ae1c 2955static void
b5256303 2956arc_hdr_free_on_write(arc_buf_hdr_t *hdr, boolean_t free_rdata)
d3c2ae1c
GW
2957{
2958 arc_state_t *state = hdr->b_l1hdr.b_state;
2959 arc_buf_contents_t type = arc_buf_type(hdr);
b5256303 2960 uint64_t size = (free_rdata) ? HDR_GET_PSIZE(hdr) : arc_hdr_size(hdr);
1eb5bfa3 2961
d3c2ae1c
GW
2962 /* protected by hash lock, if in the hash table */
2963 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
424fd7c3 2964 ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
d3c2ae1c
GW
2965 ASSERT(state != arc_anon && state != arc_l2c_only);
2966
424fd7c3 2967 (void) zfs_refcount_remove_many(&state->arcs_esize[type],
d3c2ae1c 2968 size, hdr);
1eb5bfa3 2969 }
a8d83e2a 2970 (void) zfs_refcount_remove_many(&state->arcs_size[type], size, hdr);
423e7b62
AG
2971 if (type == ARC_BUFC_METADATA) {
2972 arc_space_return(size, ARC_SPACE_META);
2973 } else {
2974 ASSERT(type == ARC_BUFC_DATA);
2975 arc_space_return(size, ARC_SPACE_DATA);
2976 }
d3c2ae1c 2977
b5256303
TC
2978 if (free_rdata) {
2979 l2arc_free_abd_on_write(hdr->b_crypt_hdr.b_rabd, size, type);
2980 } else {
2981 l2arc_free_abd_on_write(hdr->b_l1hdr.b_pabd, size, type);
2982 }
34dc7c2f
BB
2983}
2984
d3c2ae1c
GW
2985/*
2986 * Share the arc_buf_t's data with the hdr. Whenever we are sharing the
2987 * data buffer, we transfer the refcount ownership to the hdr and update
2988 * the appropriate kstats.
2989 */
2990static void
2991arc_share_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
34dc7c2f 2992{
524b4217 2993 ASSERT(arc_can_share(hdr, buf));
a6255b7f 2994 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
b5256303 2995 ASSERT(!ARC_BUF_ENCRYPTED(buf));
ca6c7a94 2996 ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
34dc7c2f
BB
2997
2998 /*
d3c2ae1c
GW
2999 * Start sharing the data buffer. We transfer the
3000 * refcount ownership to the hdr since it always owns
3001 * the refcount whenever an arc_buf_t is shared.
34dc7c2f 3002 */
a8d83e2a
AM
3003 zfs_refcount_transfer_ownership_many(
3004 &hdr->b_l1hdr.b_state->arcs_size[arc_buf_type(hdr)],
d7e4b30a 3005 arc_hdr_size(hdr), buf, hdr);
a6255b7f
DQ
3006 hdr->b_l1hdr.b_pabd = abd_get_from_buf(buf->b_data, arc_buf_size(buf));
3007 abd_take_ownership_of_buf(hdr->b_l1hdr.b_pabd,
3008 HDR_ISTYPE_METADATA(hdr));
d3c2ae1c 3009 arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
524b4217 3010 buf->b_flags |= ARC_BUF_FLAG_SHARED;
34dc7c2f 3011
d3c2ae1c
GW
3012 /*
3013 * Since we've transferred ownership to the hdr we need
3014 * to increment its compressed and uncompressed kstats and
3015 * decrement the overhead size.
3016 */
3017 ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
3018 ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
2aa34383 3019 ARCSTAT_INCR(arcstat_overhead_size, -arc_buf_size(buf));
34dc7c2f
BB
3020}
3021
ca0bf58d 3022static void
d3c2ae1c 3023arc_unshare_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
ca0bf58d 3024{
d3c2ae1c 3025 ASSERT(arc_buf_is_shared(buf));
a6255b7f 3026 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
ca6c7a94 3027 ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
ca0bf58d 3028
d3c2ae1c
GW
3029 /*
3030 * We are no longer sharing this buffer so we need
3031 * to transfer its ownership to the rightful owner.
3032 */
a8d83e2a
AM
3033 zfs_refcount_transfer_ownership_many(
3034 &hdr->b_l1hdr.b_state->arcs_size[arc_buf_type(hdr)],
d7e4b30a 3035 arc_hdr_size(hdr), hdr, buf);
d3c2ae1c 3036 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
a6255b7f 3037 abd_release_ownership_of_buf(hdr->b_l1hdr.b_pabd);
e2af2acc 3038 abd_free(hdr->b_l1hdr.b_pabd);
a6255b7f 3039 hdr->b_l1hdr.b_pabd = NULL;
524b4217 3040 buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
d3c2ae1c
GW
3041
3042 /*
3043 * Since the buffer is no longer shared between
3044 * the arc buf and the hdr, count it as overhead.
3045 */
3046 ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
3047 ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
2aa34383 3048 ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
ca0bf58d
PS
3049}
3050
34dc7c2f 3051/*
2aa34383
DK
3052 * Remove an arc_buf_t from the hdr's buf list and return the last
3053 * arc_buf_t on the list. If no buffers remain on the list then return
3054 * NULL.
3055 */
3056static arc_buf_t *
3057arc_buf_remove(arc_buf_hdr_t *hdr, arc_buf_t *buf)
3058{
2aa34383 3059 ASSERT(HDR_HAS_L1HDR(hdr));
ca6c7a94 3060 ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
2aa34383 3061
a7004725
DK
3062 arc_buf_t **bufp = &hdr->b_l1hdr.b_buf;
3063 arc_buf_t *lastbuf = NULL;
3064
2aa34383
DK
3065 /*
3066 * Remove the buf from the hdr list and locate the last
3067 * remaining buffer on the list.
3068 */
3069 while (*bufp != NULL) {
3070 if (*bufp == buf)
3071 *bufp = buf->b_next;
3072
3073 /*
3074 * If we've removed a buffer in the middle of
3075 * the list then update the lastbuf and update
3076 * bufp.
3077 */
3078 if (*bufp != NULL) {
3079 lastbuf = *bufp;
3080 bufp = &(*bufp)->b_next;
3081 }
3082 }
3083 buf->b_next = NULL;
3084 ASSERT3P(lastbuf, !=, buf);
3085 IMPLY(hdr->b_l1hdr.b_bufcnt > 0, lastbuf != NULL);
3086 IMPLY(hdr->b_l1hdr.b_bufcnt > 0, hdr->b_l1hdr.b_buf != NULL);
3087 IMPLY(lastbuf != NULL, ARC_BUF_LAST(lastbuf));
3088
3089 return (lastbuf);
3090}
3091
3092/*
e1cfd73f 3093 * Free up buf->b_data and pull the arc_buf_t off of the arc_buf_hdr_t's
2aa34383 3094 * list and free it.
34dc7c2f
BB
3095 */
3096static void
2aa34383 3097arc_buf_destroy_impl(arc_buf_t *buf)
34dc7c2f 3098{
498877ba 3099 arc_buf_hdr_t *hdr = buf->b_hdr;
ca0bf58d
PS
3100
3101 /*
524b4217
DK
3102 * Free up the data associated with the buf but only if we're not
3103 * sharing this with the hdr. If we are sharing it with the hdr, the
3104 * hdr is responsible for doing the free.
ca0bf58d 3105 */
d3c2ae1c
GW
3106 if (buf->b_data != NULL) {
3107 /*
3108 * We're about to change the hdr's b_flags. We must either
3109 * hold the hash_lock or be undiscoverable.
3110 */
ca6c7a94 3111 ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
d3c2ae1c 3112
524b4217 3113 arc_cksum_verify(buf);
d3c2ae1c
GW
3114 arc_buf_unwatch(buf);
3115
2aa34383 3116 if (arc_buf_is_shared(buf)) {
d3c2ae1c
GW
3117 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
3118 } else {
2aa34383 3119 uint64_t size = arc_buf_size(buf);
d3c2ae1c
GW
3120 arc_free_data_buf(hdr, buf->b_data, size, buf);
3121 ARCSTAT_INCR(arcstat_overhead_size, -size);
3122 }
3123 buf->b_data = NULL;
3124
3125 ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
3126 hdr->b_l1hdr.b_bufcnt -= 1;
b5256303 3127
da5d4697 3128 if (ARC_BUF_ENCRYPTED(buf)) {
b5256303
TC
3129 hdr->b_crypt_hdr.b_ebufcnt -= 1;
3130
da5d4697
D
3131 /*
3132 * If we have no more encrypted buffers and we've
3133 * already gotten a copy of the decrypted data we can
3134 * free b_rabd to save some space.
3135 */
3136 if (hdr->b_crypt_hdr.b_ebufcnt == 0 &&
3137 HDR_HAS_RABD(hdr) && hdr->b_l1hdr.b_pabd != NULL &&
3138 !HDR_IO_IN_PROGRESS(hdr)) {
3139 arc_hdr_free_abd(hdr, B_TRUE);
3140 }
440a3eb9 3141 }
d3c2ae1c
GW
3142 }
3143
a7004725 3144 arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
d3c2ae1c 3145
524b4217 3146 if (ARC_BUF_SHARED(buf) && !ARC_BUF_COMPRESSED(buf)) {
2aa34383 3147 /*
524b4217 3148 * If the current arc_buf_t is sharing its data buffer with the
a6255b7f 3149 * hdr, then reassign the hdr's b_pabd to share it with the new
524b4217
DK
3150 * buffer at the end of the list. The shared buffer is always
3151 * the last one on the hdr's buffer list.
3152 *
3153 * There is an equivalent case for compressed bufs, but since
3154 * they aren't guaranteed to be the last buf in the list and
3155 * that is an exceedingly rare case, we just allow that space be
b5256303
TC
3156 * wasted temporarily. We must also be careful not to share
3157 * encrypted buffers, since they cannot be shared.
2aa34383 3158 */
b5256303 3159 if (lastbuf != NULL && !ARC_BUF_ENCRYPTED(lastbuf)) {
524b4217 3160 /* Only one buf can be shared at once */
2aa34383 3161 VERIFY(!arc_buf_is_shared(lastbuf));
524b4217
DK
3162 /* hdr is uncompressed so can't have compressed buf */
3163 VERIFY(!ARC_BUF_COMPRESSED(lastbuf));
d3c2ae1c 3164
a6255b7f 3165 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
b5256303 3166 arc_hdr_free_abd(hdr, B_FALSE);
d3c2ae1c 3167
2aa34383
DK
3168 /*
3169 * We must setup a new shared block between the
3170 * last buffer and the hdr. The data would have
3171 * been allocated by the arc buf so we need to transfer
3172 * ownership to the hdr since it's now being shared.
3173 */
3174 arc_share_buf(hdr, lastbuf);
3175 }
3176 } else if (HDR_SHARED_DATA(hdr)) {
d3c2ae1c 3177 /*
2aa34383
DK
3178 * Uncompressed shared buffers are always at the end
3179 * of the list. Compressed buffers don't have the
3180 * same requirements. This makes it hard to
3181 * simply assert that the lastbuf is shared so
3182 * we rely on the hdr's compression flags to determine
3183 * if we have a compressed, shared buffer.
d3c2ae1c 3184 */
2aa34383
DK
3185 ASSERT3P(lastbuf, !=, NULL);
3186 ASSERT(arc_buf_is_shared(lastbuf) ||
b5256303 3187 arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF);
ca0bf58d
PS
3188 }
3189
a7004725
DK
3190 /*
3191 * Free the checksum if we're removing the last uncompressed buf from
3192 * this hdr.
3193 */
3194 if (!arc_hdr_has_uncompressed_buf(hdr)) {
d3c2ae1c 3195 arc_cksum_free(hdr);
a7004725 3196 }
d3c2ae1c
GW
3197
3198 /* clean up the buf */
3199 buf->b_hdr = NULL;
3200 kmem_cache_free(buf_cache, buf);
3201}
3202
3203static void
e111c802 3204arc_hdr_alloc_abd(arc_buf_hdr_t *hdr, int alloc_flags)
d3c2ae1c 3205{
b5256303 3206 uint64_t size;
e111c802 3207 boolean_t alloc_rdata = ((alloc_flags & ARC_HDR_ALLOC_RDATA) != 0);
b5256303 3208
d3c2ae1c
GW
3209 ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
3210 ASSERT(HDR_HAS_L1HDR(hdr));
b5256303
TC
3211 ASSERT(!HDR_SHARED_DATA(hdr) || alloc_rdata);
3212 IMPLY(alloc_rdata, HDR_PROTECTED(hdr));
d3c2ae1c 3213
b5256303
TC
3214 if (alloc_rdata) {
3215 size = HDR_GET_PSIZE(hdr);
3216 ASSERT3P(hdr->b_crypt_hdr.b_rabd, ==, NULL);
e111c802 3217 hdr->b_crypt_hdr.b_rabd = arc_get_data_abd(hdr, size, hdr,
6b88b4b5 3218 alloc_flags);
b5256303
TC
3219 ASSERT3P(hdr->b_crypt_hdr.b_rabd, !=, NULL);
3220 ARCSTAT_INCR(arcstat_raw_size, size);
3221 } else {
3222 size = arc_hdr_size(hdr);
3223 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
e111c802 3224 hdr->b_l1hdr.b_pabd = arc_get_data_abd(hdr, size, hdr,
6b88b4b5 3225 alloc_flags);
b5256303
TC
3226 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3227 }
3228
3229 ARCSTAT_INCR(arcstat_compressed_size, size);
d3c2ae1c
GW
3230 ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
3231}
3232
3233static void
b5256303 3234arc_hdr_free_abd(arc_buf_hdr_t *hdr, boolean_t free_rdata)
d3c2ae1c 3235{
b5256303
TC
3236 uint64_t size = (free_rdata) ? HDR_GET_PSIZE(hdr) : arc_hdr_size(hdr);
3237
d3c2ae1c 3238 ASSERT(HDR_HAS_L1HDR(hdr));
b5256303
TC
3239 ASSERT(hdr->b_l1hdr.b_pabd != NULL || HDR_HAS_RABD(hdr));
3240 IMPLY(free_rdata, HDR_HAS_RABD(hdr));
d3c2ae1c 3241
ca0bf58d 3242 /*
d3c2ae1c
GW
3243 * If the hdr is currently being written to the l2arc then
3244 * we defer freeing the data by adding it to the l2arc_free_on_write
3245 * list. The l2arc will free the data once it's finished
3246 * writing it to the l2arc device.
ca0bf58d 3247 */
d3c2ae1c 3248 if (HDR_L2_WRITING(hdr)) {
b5256303 3249 arc_hdr_free_on_write(hdr, free_rdata);
d3c2ae1c 3250 ARCSTAT_BUMP(arcstat_l2_free_on_write);
b5256303
TC
3251 } else if (free_rdata) {
3252 arc_free_data_abd(hdr, hdr->b_crypt_hdr.b_rabd, size, hdr);
d3c2ae1c 3253 } else {
b5256303 3254 arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd, size, hdr);
ca0bf58d
PS
3255 }
3256
b5256303
TC
3257 if (free_rdata) {
3258 hdr->b_crypt_hdr.b_rabd = NULL;
3259 ARCSTAT_INCR(arcstat_raw_size, -size);
3260 } else {
3261 hdr->b_l1hdr.b_pabd = NULL;
3262 }
3263
3264 if (hdr->b_l1hdr.b_pabd == NULL && !HDR_HAS_RABD(hdr))
3265 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
3266
3267 ARCSTAT_INCR(arcstat_compressed_size, -size);
d3c2ae1c
GW
3268 ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
3269}
3270
6b88b4b5
AM
3271/*
3272 * Allocate empty anonymous ARC header. The header will get its identity
3273 * assigned and buffers attached later as part of read or write operations.
3274 *
3275 * In case of read arc_read() assigns header its identify (b_dva + b_birth),
3276 * inserts it into ARC hash to become globally visible and allocates physical
3277 * (b_pabd) or raw (b_rabd) ABD buffer to read into from disk. On disk read
3278 * completion arc_read_done() allocates ARC buffer(s) as needed, potentially
3279 * sharing one of them with the physical ABD buffer.
3280 *
3281 * In case of write arc_alloc_buf() allocates ARC buffer to be filled with
3282 * data. Then after compression and/or encryption arc_write_ready() allocates
3283 * and fills (or potentially shares) physical (b_pabd) or raw (b_rabd) ABD
3284 * buffer. On disk write completion arc_write_done() assigns the header its
3285 * new identity (b_dva + b_birth) and inserts into ARC hash.
3286 *
3287 * In case of partial overwrite the old data is read first as described. Then
3288 * arc_release() either allocates new anonymous ARC header and moves the ARC
3289 * buffer to it, or reuses the old ARC header by discarding its identity and
3290 * removing it from ARC hash. After buffer modification normal write process
3291 * follows as described.
3292 */
d3c2ae1c
GW
3293static arc_buf_hdr_t *
3294arc_hdr_alloc(uint64_t spa, int32_t psize, int32_t lsize,
10b3c7f5 3295 boolean_t protected, enum zio_compress compression_type, uint8_t complevel,
6b88b4b5 3296 arc_buf_contents_t type)
d3c2ae1c
GW
3297{
3298 arc_buf_hdr_t *hdr;
3299
d3c2ae1c 3300 VERIFY(type == ARC_BUFC_DATA || type == ARC_BUFC_METADATA);
b5256303
TC
3301 if (protected) {
3302 hdr = kmem_cache_alloc(hdr_full_crypt_cache, KM_PUSHPAGE);
3303 } else {
3304 hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
3305 }
d3c2ae1c 3306
d3c2ae1c 3307 ASSERT(HDR_EMPTY(hdr));
bacf366f 3308#ifdef ZFS_DEBUG
d3c2ae1c 3309 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
bacf366f 3310#endif
d3c2ae1c
GW
3311 HDR_SET_PSIZE(hdr, psize);
3312 HDR_SET_LSIZE(hdr, lsize);
3313 hdr->b_spa = spa;
3314 hdr->b_type = type;
3315 hdr->b_flags = 0;
3316 arc_hdr_set_flags(hdr, arc_bufc_to_flags(type) | ARC_FLAG_HAS_L1HDR);
2aa34383 3317 arc_hdr_set_compress(hdr, compression_type);
10b3c7f5 3318 hdr->b_complevel = complevel;
b5256303
TC
3319 if (protected)
3320 arc_hdr_set_flags(hdr, ARC_FLAG_PROTECTED);
ca0bf58d 3321
d3c2ae1c
GW
3322 hdr->b_l1hdr.b_state = arc_anon;
3323 hdr->b_l1hdr.b_arc_access = 0;
cfe8e960
AM
3324 hdr->b_l1hdr.b_mru_hits = 0;
3325 hdr->b_l1hdr.b_mru_ghost_hits = 0;
3326 hdr->b_l1hdr.b_mfu_hits = 0;
3327 hdr->b_l1hdr.b_mfu_ghost_hits = 0;
d3c2ae1c
GW
3328 hdr->b_l1hdr.b_bufcnt = 0;
3329 hdr->b_l1hdr.b_buf = NULL;
ca0bf58d 3330
424fd7c3 3331 ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
ca0bf58d 3332
d3c2ae1c 3333 return (hdr);
ca0bf58d
PS
3334}
3335
bd089c54 3336/*
d3c2ae1c
GW
3337 * Transition between the two allocation states for the arc_buf_hdr struct.
3338 * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
3339 * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
3340 * version is used when a cache buffer is only in the L2ARC in order to reduce
3341 * memory usage.
bd089c54 3342 */
d3c2ae1c
GW
3343static arc_buf_hdr_t *
3344arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
34dc7c2f 3345{
1c27024e
DB
3346 ASSERT(HDR_HAS_L2HDR(hdr));
3347
d3c2ae1c
GW
3348 arc_buf_hdr_t *nhdr;
3349 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
34dc7c2f 3350
d3c2ae1c
GW
3351 ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
3352 (old == hdr_l2only_cache && new == hdr_full_cache));
34dc7c2f 3353
b5256303
TC
3354 /*
3355 * if the caller wanted a new full header and the header is to be
3356 * encrypted we will actually allocate the header from the full crypt
3357 * cache instead. The same applies to freeing from the old cache.
3358 */
3359 if (HDR_PROTECTED(hdr) && new == hdr_full_cache)
3360 new = hdr_full_crypt_cache;
3361 if (HDR_PROTECTED(hdr) && old == hdr_full_cache)
3362 old = hdr_full_crypt_cache;
3363
d3c2ae1c 3364 nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
428870ff 3365
d3c2ae1c
GW
3366 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
3367 buf_hash_remove(hdr);
ca0bf58d 3368
861166b0 3369 memcpy(nhdr, hdr, HDR_L2ONLY_SIZE);
34dc7c2f 3370
b5256303 3371 if (new == hdr_full_cache || new == hdr_full_crypt_cache) {
d3c2ae1c
GW
3372 arc_hdr_set_flags(nhdr, ARC_FLAG_HAS_L1HDR);
3373 /*
3374 * arc_access and arc_change_state need to be aware that a
3375 * header has just come out of L2ARC, so we set its state to
3376 * l2c_only even though it's about to change.
3377 */
3378 nhdr->b_l1hdr.b_state = arc_l2c_only;
34dc7c2f 3379
d3c2ae1c 3380 /* Verify previous threads set to NULL before freeing */
a6255b7f 3381 ASSERT3P(nhdr->b_l1hdr.b_pabd, ==, NULL);
b5256303 3382 ASSERT(!HDR_HAS_RABD(hdr));
d3c2ae1c
GW
3383 } else {
3384 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3385 ASSERT0(hdr->b_l1hdr.b_bufcnt);
bacf366f 3386#ifdef ZFS_DEBUG
d3c2ae1c 3387 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
bacf366f 3388#endif
36da08ef 3389
d3c2ae1c
GW
3390 /*
3391 * If we've reached here, We must have been called from
3392 * arc_evict_hdr(), as such we should have already been
3393 * removed from any ghost list we were previously on
3394 * (which protects us from racing with arc_evict_state),
3395 * thus no locking is needed during this check.
3396 */
3397 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1eb5bfa3
GW
3398
3399 /*
d3c2ae1c
GW
3400 * A buffer must not be moved into the arc_l2c_only
3401 * state if it's not finished being written out to the
a6255b7f 3402 * l2arc device. Otherwise, the b_l1hdr.b_pabd field
d3c2ae1c 3403 * might try to be accessed, even though it was removed.
1eb5bfa3 3404 */
d3c2ae1c 3405 VERIFY(!HDR_L2_WRITING(hdr));
a6255b7f 3406 VERIFY3P(hdr->b_l1hdr.b_pabd, ==, NULL);
b5256303 3407 ASSERT(!HDR_HAS_RABD(hdr));
d3c2ae1c
GW
3408
3409 arc_hdr_clear_flags(nhdr, ARC_FLAG_HAS_L1HDR);
34dc7c2f 3410 }
d3c2ae1c
GW
3411 /*
3412 * The header has been reallocated so we need to re-insert it into any
3413 * lists it was on.
3414 */
3415 (void) buf_hash_insert(nhdr, NULL);
34dc7c2f 3416
d3c2ae1c 3417 ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
34dc7c2f 3418
d3c2ae1c
GW
3419 mutex_enter(&dev->l2ad_mtx);
3420
3421 /*
3422 * We must place the realloc'ed header back into the list at
3423 * the same spot. Otherwise, if it's placed earlier in the list,
3424 * l2arc_write_buffers() could find it during the function's
3425 * write phase, and try to write it out to the l2arc.
3426 */
3427 list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
3428 list_remove(&dev->l2ad_buflist, hdr);
34dc7c2f 3429
d3c2ae1c 3430 mutex_exit(&dev->l2ad_mtx);
34dc7c2f 3431
d3c2ae1c
GW
3432 /*
3433 * Since we're using the pointer address as the tag when
3434 * incrementing and decrementing the l2ad_alloc refcount, we
3435 * must remove the old pointer (that we're about to destroy) and
3436 * add the new pointer to the refcount. Otherwise we'd remove
3437 * the wrong pointer address when calling arc_hdr_destroy() later.
3438 */
3439
424fd7c3
TS
3440 (void) zfs_refcount_remove_many(&dev->l2ad_alloc,
3441 arc_hdr_size(hdr), hdr);
3442 (void) zfs_refcount_add_many(&dev->l2ad_alloc,
3443 arc_hdr_size(nhdr), nhdr);
d3c2ae1c
GW
3444
3445 buf_discard_identity(hdr);
3446 kmem_cache_free(old, hdr);
3447
3448 return (nhdr);
3449}
3450
b5256303
TC
3451/*
3452 * This function allows an L1 header to be reallocated as a crypt
3453 * header and vice versa. If we are going to a crypt header, the
3454 * new fields will be zeroed out.
3455 */
3456static arc_buf_hdr_t *
3457arc_hdr_realloc_crypt(arc_buf_hdr_t *hdr, boolean_t need_crypt)
3458{
3459 arc_buf_hdr_t *nhdr;
3460 arc_buf_t *buf;
3461 kmem_cache_t *ncache, *ocache;
3462
b7ddeaef
TC
3463 /*
3464 * This function requires that hdr is in the arc_anon state.
3465 * Therefore it won't have any L2ARC data for us to worry
3466 * about copying.
3467 */
b5256303 3468 ASSERT(HDR_HAS_L1HDR(hdr));
b7ddeaef 3469 ASSERT(!HDR_HAS_L2HDR(hdr));
b5256303
TC
3470 ASSERT3U(!!HDR_PROTECTED(hdr), !=, need_crypt);
3471 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
3472 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
b7ddeaef
TC
3473 ASSERT(!list_link_active(&hdr->b_l2hdr.b_l2node));
3474 ASSERT3P(hdr->b_hash_next, ==, NULL);
b5256303
TC
3475
3476 if (need_crypt) {
3477 ncache = hdr_full_crypt_cache;
3478 ocache = hdr_full_cache;
3479 } else {
3480 ncache = hdr_full_cache;
3481 ocache = hdr_full_crypt_cache;
3482 }
3483
3484 nhdr = kmem_cache_alloc(ncache, KM_PUSHPAGE);
b7ddeaef
TC
3485
3486 /*
3487 * Copy all members that aren't locks or condvars to the new header.
3488 * No lists are pointing to us (as we asserted above), so we don't
3489 * need to worry about the list nodes.
3490 */
3491 nhdr->b_dva = hdr->b_dva;
3492 nhdr->b_birth = hdr->b_birth;
3493 nhdr->b_type = hdr->b_type;
3494 nhdr->b_flags = hdr->b_flags;
3495 nhdr->b_psize = hdr->b_psize;
3496 nhdr->b_lsize = hdr->b_lsize;
3497 nhdr->b_spa = hdr->b_spa;
bacf366f 3498#ifdef ZFS_DEBUG
b5256303 3499 nhdr->b_l1hdr.b_freeze_cksum = hdr->b_l1hdr.b_freeze_cksum;
bacf366f 3500#endif
b5256303
TC
3501 nhdr->b_l1hdr.b_bufcnt = hdr->b_l1hdr.b_bufcnt;
3502 nhdr->b_l1hdr.b_byteswap = hdr->b_l1hdr.b_byteswap;
3503 nhdr->b_l1hdr.b_state = hdr->b_l1hdr.b_state;
3504 nhdr->b_l1hdr.b_arc_access = hdr->b_l1hdr.b_arc_access;
3505 nhdr->b_l1hdr.b_mru_hits = hdr->b_l1hdr.b_mru_hits;
3506 nhdr->b_l1hdr.b_mru_ghost_hits = hdr->b_l1hdr.b_mru_ghost_hits;
3507 nhdr->b_l1hdr.b_mfu_hits = hdr->b_l1hdr.b_mfu_hits;
3508 nhdr->b_l1hdr.b_mfu_ghost_hits = hdr->b_l1hdr.b_mfu_ghost_hits;
b5256303
TC
3509 nhdr->b_l1hdr.b_acb = hdr->b_l1hdr.b_acb;
3510 nhdr->b_l1hdr.b_pabd = hdr->b_l1hdr.b_pabd;
b5256303
TC
3511
3512 /*
c13060e4 3513 * This zfs_refcount_add() exists only to ensure that the individual
b5256303
TC
3514 * arc buffers always point to a header that is referenced, avoiding
3515 * a small race condition that could trigger ASSERTs.
3516 */
c13060e4 3517 (void) zfs_refcount_add(&nhdr->b_l1hdr.b_refcnt, FTAG);
b7ddeaef 3518 nhdr->b_l1hdr.b_buf = hdr->b_l1hdr.b_buf;
289f7e6a 3519 for (buf = nhdr->b_l1hdr.b_buf; buf != NULL; buf = buf->b_next)
b5256303 3520 buf->b_hdr = nhdr;
b5256303 3521
424fd7c3
TS
3522 zfs_refcount_transfer(&nhdr->b_l1hdr.b_refcnt, &hdr->b_l1hdr.b_refcnt);
3523 (void) zfs_refcount_remove(&nhdr->b_l1hdr.b_refcnt, FTAG);
3524 ASSERT0(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt));
b5256303
TC
3525
3526 if (need_crypt) {
3527 arc_hdr_set_flags(nhdr, ARC_FLAG_PROTECTED);
3528 } else {
3529 arc_hdr_clear_flags(nhdr, ARC_FLAG_PROTECTED);
3530 }
3531
b7ddeaef 3532 /* unset all members of the original hdr */
861166b0 3533 memset(&hdr->b_dva, 0, sizeof (dva_t));
b7ddeaef 3534 hdr->b_birth = 0;
a8d83e2a 3535 hdr->b_type = 0;
b7ddeaef
TC
3536 hdr->b_flags = 0;
3537 hdr->b_psize = 0;
3538 hdr->b_lsize = 0;
3539 hdr->b_spa = 0;
bacf366f 3540#ifdef ZFS_DEBUG
b7ddeaef 3541 hdr->b_l1hdr.b_freeze_cksum = NULL;
bacf366f 3542#endif
b7ddeaef
TC
3543 hdr->b_l1hdr.b_buf = NULL;
3544 hdr->b_l1hdr.b_bufcnt = 0;
3545 hdr->b_l1hdr.b_byteswap = 0;
3546 hdr->b_l1hdr.b_state = NULL;
3547 hdr->b_l1hdr.b_arc_access = 0;
3548 hdr->b_l1hdr.b_mru_hits = 0;
3549 hdr->b_l1hdr.b_mru_ghost_hits = 0;
3550 hdr->b_l1hdr.b_mfu_hits = 0;
3551 hdr->b_l1hdr.b_mfu_ghost_hits = 0;
b7ddeaef
TC
3552 hdr->b_l1hdr.b_acb = NULL;
3553 hdr->b_l1hdr.b_pabd = NULL;
3554
3555 if (ocache == hdr_full_crypt_cache) {
3556 ASSERT(!HDR_HAS_RABD(hdr));
3557 hdr->b_crypt_hdr.b_ot = DMU_OT_NONE;
3558 hdr->b_crypt_hdr.b_ebufcnt = 0;
3559 hdr->b_crypt_hdr.b_dsobj = 0;
861166b0
AZ
3560 memset(hdr->b_crypt_hdr.b_salt, 0, ZIO_DATA_SALT_LEN);
3561 memset(hdr->b_crypt_hdr.b_iv, 0, ZIO_DATA_IV_LEN);
3562 memset(hdr->b_crypt_hdr.b_mac, 0, ZIO_DATA_MAC_LEN);
b7ddeaef
TC
3563 }
3564
b5256303
TC
3565 buf_discard_identity(hdr);
3566 kmem_cache_free(ocache, hdr);
3567
3568 return (nhdr);
3569}
3570
3571/*
3572 * This function is used by the send / receive code to convert a newly
3573 * allocated arc_buf_t to one that is suitable for a raw encrypted write. It
e1cfd73f 3574 * is also used to allow the root objset block to be updated without altering
b5256303
TC
3575 * its embedded MACs. Both block types will always be uncompressed so we do not
3576 * have to worry about compression type or psize.
3577 */
3578void
3579arc_convert_to_raw(arc_buf_t *buf, uint64_t dsobj, boolean_t byteorder,
3580 dmu_object_type_t ot, const uint8_t *salt, const uint8_t *iv,
3581 const uint8_t *mac)
3582{
3583 arc_buf_hdr_t *hdr = buf->b_hdr;
3584
3585 ASSERT(ot == DMU_OT_DNODE || ot == DMU_OT_OBJSET);
3586 ASSERT(HDR_HAS_L1HDR(hdr));
3587 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
3588
3589 buf->b_flags |= (ARC_BUF_FLAG_COMPRESSED | ARC_BUF_FLAG_ENCRYPTED);
3590 if (!HDR_PROTECTED(hdr))
3591 hdr = arc_hdr_realloc_crypt(hdr, B_TRUE);
3592 hdr->b_crypt_hdr.b_dsobj = dsobj;
3593 hdr->b_crypt_hdr.b_ot = ot;
3594 hdr->b_l1hdr.b_byteswap = (byteorder == ZFS_HOST_BYTEORDER) ?
3595 DMU_BSWAP_NUMFUNCS : DMU_OT_BYTESWAP(ot);
3596 if (!arc_hdr_has_uncompressed_buf(hdr))
3597 arc_cksum_free(hdr);
3598
3599 if (salt != NULL)
861166b0 3600 memcpy(hdr->b_crypt_hdr.b_salt, salt, ZIO_DATA_SALT_LEN);
b5256303 3601 if (iv != NULL)
861166b0 3602 memcpy(hdr->b_crypt_hdr.b_iv, iv, ZIO_DATA_IV_LEN);
b5256303 3603 if (mac != NULL)
861166b0 3604 memcpy(hdr->b_crypt_hdr.b_mac, mac, ZIO_DATA_MAC_LEN);
b5256303
TC
3605}
3606
d3c2ae1c
GW
3607/*
3608 * Allocate a new arc_buf_hdr_t and arc_buf_t and return the buf to the caller.
3609 * The buf is returned thawed since we expect the consumer to modify it.
3610 */
3611arc_buf_t *
a926aab9
AZ
3612arc_alloc_buf(spa_t *spa, const void *tag, arc_buf_contents_t type,
3613 int32_t size)
d3c2ae1c 3614{
d3c2ae1c 3615 arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), size, size,
6b88b4b5 3616 B_FALSE, ZIO_COMPRESS_OFF, 0, type);
2aa34383 3617
a7004725 3618 arc_buf_t *buf = NULL;
be9a5c35 3619 VERIFY0(arc_buf_alloc_impl(hdr, spa, NULL, tag, B_FALSE, B_FALSE,
b5256303 3620 B_FALSE, B_FALSE, &buf));
d3c2ae1c 3621 arc_buf_thaw(buf);
2aa34383
DK
3622
3623 return (buf);
3624}
3625
3626/*
3627 * Allocate a compressed buf in the same manner as arc_alloc_buf. Don't use this
3628 * for bufs containing metadata.
3629 */
3630arc_buf_t *
a926aab9
AZ
3631arc_alloc_compressed_buf(spa_t *spa, const void *tag, uint64_t psize,
3632 uint64_t lsize, enum zio_compress compression_type, uint8_t complevel)
2aa34383 3633{
2aa34383
DK
3634 ASSERT3U(lsize, >, 0);
3635 ASSERT3U(lsize, >=, psize);
b5256303
TC
3636 ASSERT3U(compression_type, >, ZIO_COMPRESS_OFF);
3637 ASSERT3U(compression_type, <, ZIO_COMPRESS_FUNCTIONS);
2aa34383 3638
a7004725 3639 arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
6b88b4b5 3640 B_FALSE, compression_type, complevel, ARC_BUFC_DATA);
2aa34383 3641
a7004725 3642 arc_buf_t *buf = NULL;
be9a5c35 3643 VERIFY0(arc_buf_alloc_impl(hdr, spa, NULL, tag, B_FALSE,
b5256303 3644 B_TRUE, B_FALSE, B_FALSE, &buf));
2aa34383 3645 arc_buf_thaw(buf);
2aa34383 3646
6b88b4b5
AM
3647 /*
3648 * To ensure that the hdr has the correct data in it if we call
3649 * arc_untransform() on this buf before it's been written to disk,
3650 * it's easiest if we just set up sharing between the buf and the hdr.
3651 */
3652 arc_share_buf(hdr, buf);
a6255b7f 3653
d3c2ae1c 3654 return (buf);
34dc7c2f
BB
3655}
3656
b5256303 3657arc_buf_t *
a926aab9
AZ
3658arc_alloc_raw_buf(spa_t *spa, const void *tag, uint64_t dsobj,
3659 boolean_t byteorder, const uint8_t *salt, const uint8_t *iv,
3660 const uint8_t *mac, dmu_object_type_t ot, uint64_t psize, uint64_t lsize,
10b3c7f5 3661 enum zio_compress compression_type, uint8_t complevel)
b5256303
TC
3662{
3663 arc_buf_hdr_t *hdr;
3664 arc_buf_t *buf;
3665 arc_buf_contents_t type = DMU_OT_IS_METADATA(ot) ?
3666 ARC_BUFC_METADATA : ARC_BUFC_DATA;
3667
3668 ASSERT3U(lsize, >, 0);
3669 ASSERT3U(lsize, >=, psize);
3670 ASSERT3U(compression_type, >=, ZIO_COMPRESS_OFF);
3671 ASSERT3U(compression_type, <, ZIO_COMPRESS_FUNCTIONS);
3672
3673 hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize, B_TRUE,
6b88b4b5 3674 compression_type, complevel, type);
b5256303
TC
3675
3676 hdr->b_crypt_hdr.b_dsobj = dsobj;
3677 hdr->b_crypt_hdr.b_ot = ot;
3678 hdr->b_l1hdr.b_byteswap = (byteorder == ZFS_HOST_BYTEORDER) ?
3679 DMU_BSWAP_NUMFUNCS : DMU_OT_BYTESWAP(ot);
861166b0
AZ
3680 memcpy(hdr->b_crypt_hdr.b_salt, salt, ZIO_DATA_SALT_LEN);
3681 memcpy(hdr->b_crypt_hdr.b_iv, iv, ZIO_DATA_IV_LEN);
3682 memcpy(hdr->b_crypt_hdr.b_mac, mac, ZIO_DATA_MAC_LEN);
b5256303
TC
3683
3684 /*
3685 * This buffer will be considered encrypted even if the ot is not an
3686 * encrypted type. It will become authenticated instead in
3687 * arc_write_ready().
3688 */
3689 buf = NULL;
be9a5c35 3690 VERIFY0(arc_buf_alloc_impl(hdr, spa, NULL, tag, B_TRUE, B_TRUE,
b5256303
TC
3691 B_FALSE, B_FALSE, &buf));
3692 arc_buf_thaw(buf);
b5256303
TC
3693
3694 return (buf);
3695}
3696
08532162
GA
3697static void
3698l2arc_hdr_arcstats_update(arc_buf_hdr_t *hdr, boolean_t incr,
3699 boolean_t state_only)
3700{
3701 l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
3702 l2arc_dev_t *dev = l2hdr->b_dev;
3703 uint64_t lsize = HDR_GET_LSIZE(hdr);
3704 uint64_t psize = HDR_GET_PSIZE(hdr);
3705 uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev, psize);
3706 arc_buf_contents_t type = hdr->b_type;
3707 int64_t lsize_s;
3708 int64_t psize_s;
3709 int64_t asize_s;
3710
3711 if (incr) {
3712 lsize_s = lsize;
3713 psize_s = psize;
3714 asize_s = asize;
3715 } else {
3716 lsize_s = -lsize;
3717 psize_s = -psize;
3718 asize_s = -asize;
3719 }
3720
3721 /* If the buffer is a prefetch, count it as such. */
3722 if (HDR_PREFETCH(hdr)) {
3723 ARCSTAT_INCR(arcstat_l2_prefetch_asize, asize_s);
3724 } else {
3725 /*
3726 * We use the value stored in the L2 header upon initial
3727 * caching in L2ARC. This value will be updated in case
3728 * an MRU/MRU_ghost buffer transitions to MFU but the L2ARC
3729 * metadata (log entry) cannot currently be updated. Having
3730 * the ARC state in the L2 header solves the problem of a
3731 * possibly absent L1 header (apparent in buffers restored
3732 * from persistent L2ARC).
3733 */
3734 switch (hdr->b_l2hdr.b_arcs_state) {
3735 case ARC_STATE_MRU_GHOST:
3736 case ARC_STATE_MRU:
3737 ARCSTAT_INCR(arcstat_l2_mru_asize, asize_s);
3738 break;
3739 case ARC_STATE_MFU_GHOST:
3740 case ARC_STATE_MFU:
3741 ARCSTAT_INCR(arcstat_l2_mfu_asize, asize_s);
3742 break;
3743 default:
3744 break;
3745 }
3746 }
3747
3748 if (state_only)
3749 return;
3750
3751 ARCSTAT_INCR(arcstat_l2_psize, psize_s);
3752 ARCSTAT_INCR(arcstat_l2_lsize, lsize_s);
3753
3754 switch (type) {
3755 case ARC_BUFC_DATA:
3756 ARCSTAT_INCR(arcstat_l2_bufc_data_asize, asize_s);
3757 break;
3758 case ARC_BUFC_METADATA:
3759 ARCSTAT_INCR(arcstat_l2_bufc_metadata_asize, asize_s);
3760 break;
3761 default:
3762 break;
3763 }
3764}
3765
3766
d962d5da
PS
3767static void
3768arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
3769{
3770 l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
3771 l2arc_dev_t *dev = l2hdr->b_dev;
7558997d
SD
3772 uint64_t psize = HDR_GET_PSIZE(hdr);
3773 uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev, psize);
d962d5da
PS
3774
3775 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
3776 ASSERT(HDR_HAS_L2HDR(hdr));
3777
3778 list_remove(&dev->l2ad_buflist, hdr);
3779
08532162 3780 l2arc_hdr_arcstats_decrement(hdr);
7558997d 3781 vdev_space_update(dev->l2ad_vdev, -asize, 0, 0);
d962d5da 3782
7558997d
SD
3783 (void) zfs_refcount_remove_many(&dev->l2ad_alloc, arc_hdr_size(hdr),
3784 hdr);
d3c2ae1c 3785 arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
d962d5da
PS
3786}
3787
34dc7c2f
BB
3788static void
3789arc_hdr_destroy(arc_buf_hdr_t *hdr)
3790{
b9541d6b
CW
3791 if (HDR_HAS_L1HDR(hdr)) {
3792 ASSERT(hdr->b_l1hdr.b_buf == NULL ||
d3c2ae1c 3793 hdr->b_l1hdr.b_bufcnt > 0);
424fd7c3 3794 ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
b9541d6b
CW
3795 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
3796 }
34dc7c2f 3797 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
b9541d6b
CW
3798 ASSERT(!HDR_IN_HASH_TABLE(hdr));
3799
3800 if (HDR_HAS_L2HDR(hdr)) {
d962d5da
PS
3801 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3802 boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
428870ff 3803
d962d5da
PS
3804 if (!buflist_held)
3805 mutex_enter(&dev->l2ad_mtx);
b9541d6b 3806
ca0bf58d 3807 /*
d962d5da
PS
3808 * Even though we checked this conditional above, we
3809 * need to check this again now that we have the
3810 * l2ad_mtx. This is because we could be racing with
3811 * another thread calling l2arc_evict() which might have
3812 * destroyed this header's L2 portion as we were waiting
3813 * to acquire the l2ad_mtx. If that happens, we don't
3814 * want to re-destroy the header's L2 portion.
ca0bf58d 3815 */
2a49ebbb
GA
3816 if (HDR_HAS_L2HDR(hdr)) {
3817
3818 if (!HDR_EMPTY(hdr))
3819 buf_discard_identity(hdr);
3820
d962d5da 3821 arc_hdr_l2hdr_destroy(hdr);
2a49ebbb 3822 }
428870ff
BB
3823
3824 if (!buflist_held)
d962d5da 3825 mutex_exit(&dev->l2ad_mtx);
34dc7c2f
BB
3826 }
3827
ca6c7a94
BB
3828 /*
3829 * The header's identify can only be safely discarded once it is no
3830 * longer discoverable. This requires removing it from the hash table
3831 * and the l2arc header list. After this point the hash lock can not
3832 * be used to protect the header.
3833 */
3834 if (!HDR_EMPTY(hdr))
3835 buf_discard_identity(hdr);
3836
d3c2ae1c
GW
3837 if (HDR_HAS_L1HDR(hdr)) {
3838 arc_cksum_free(hdr);
b9541d6b 3839
d3c2ae1c 3840 while (hdr->b_l1hdr.b_buf != NULL)
2aa34383 3841 arc_buf_destroy_impl(hdr->b_l1hdr.b_buf);
34dc7c2f 3842
ca6c7a94 3843 if (hdr->b_l1hdr.b_pabd != NULL)
b5256303 3844 arc_hdr_free_abd(hdr, B_FALSE);
b5256303 3845
440a3eb9 3846 if (HDR_HAS_RABD(hdr))
b5256303 3847 arc_hdr_free_abd(hdr, B_TRUE);
b9541d6b
CW
3848 }
3849
34dc7c2f 3850 ASSERT3P(hdr->b_hash_next, ==, NULL);
b9541d6b 3851 if (HDR_HAS_L1HDR(hdr)) {
ca0bf58d 3852 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
b9541d6b 3853 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
bacf366f
AM
3854#ifdef ZFS_DEBUG
3855 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3856#endif
b5256303
TC
3857
3858 if (!HDR_PROTECTED(hdr)) {
3859 kmem_cache_free(hdr_full_cache, hdr);
3860 } else {
3861 kmem_cache_free(hdr_full_crypt_cache, hdr);
3862 }
b9541d6b
CW
3863 } else {
3864 kmem_cache_free(hdr_l2only_cache, hdr);
3865 }
34dc7c2f
BB
3866}
3867
3868void
dd66857d 3869arc_buf_destroy(arc_buf_t *buf, const void *tag)
34dc7c2f
BB
3870{
3871 arc_buf_hdr_t *hdr = buf->b_hdr;
34dc7c2f 3872
b9541d6b 3873 if (hdr->b_l1hdr.b_state == arc_anon) {
d3c2ae1c
GW
3874 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
3875 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
c935fe2e 3876 VERIFY0(remove_reference(hdr, tag));
d3c2ae1c 3877 return;
34dc7c2f
BB
3878 }
3879
ca6c7a94 3880 kmutex_t *hash_lock = HDR_LOCK(hdr);
34dc7c2f 3881 mutex_enter(hash_lock);
ca6c7a94 3882
d3c2ae1c
GW
3883 ASSERT3P(hdr, ==, buf->b_hdr);
3884 ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
428870ff 3885 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
d3c2ae1c
GW
3886 ASSERT3P(hdr->b_l1hdr.b_state, !=, arc_anon);
3887 ASSERT3P(buf->b_data, !=, NULL);
34dc7c2f 3888
2aa34383 3889 arc_buf_destroy_impl(buf);
ed2f7ba0 3890 (void) remove_reference(hdr, tag);
34dc7c2f 3891 mutex_exit(hash_lock);
34dc7c2f
BB
3892}
3893
34dc7c2f 3894/*
ca0bf58d
PS
3895 * Evict the arc_buf_hdr that is provided as a parameter. The resultant
3896 * state of the header is dependent on its state prior to entering this
3897 * function. The following transitions are possible:
34dc7c2f 3898 *
ca0bf58d
PS
3899 * - arc_mru -> arc_mru_ghost
3900 * - arc_mfu -> arc_mfu_ghost
3901 * - arc_mru_ghost -> arc_l2c_only
3902 * - arc_mru_ghost -> deleted
3903 * - arc_mfu_ghost -> arc_l2c_only
3904 * - arc_mfu_ghost -> deleted
ed2f7ba0 3905 * - arc_uncached -> deleted
f7de776d
AM
3906 *
3907 * Return total size of evicted data buffers for eviction progress tracking.
3908 * When evicting from ghost states return logical buffer size to make eviction
3909 * progress at the same (or at least comparable) rate as from non-ghost states.
3910 *
3911 * Return *real_evicted for actual ARC size reduction to wake up threads
3912 * waiting for it. For non-ghost states it includes size of evicted data
3913 * buffers (the headers are not freed there). For ghost states it includes
3914 * only the evicted headers size.
34dc7c2f 3915 */
ca0bf58d 3916static int64_t
c935fe2e 3917arc_evict_hdr(arc_buf_hdr_t *hdr, uint64_t *real_evicted)
34dc7c2f 3918{
ca0bf58d
PS
3919 arc_state_t *evicted_state, *state;
3920 int64_t bytes_evicted = 0;
fdc2d303 3921 uint_t min_lifetime = HDR_PRESCIENT_PREFETCH(hdr) ?
d4a72f23 3922 arc_min_prescient_prefetch_ms : arc_min_prefetch_ms;
34dc7c2f 3923
c935fe2e 3924 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
ca0bf58d 3925 ASSERT(HDR_HAS_L1HDR(hdr));
c935fe2e 3926 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
289f7e6a
AM
3927 ASSERT0(hdr->b_l1hdr.b_bufcnt);
3928 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3929 ASSERT0(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt));
e8b96c60 3930
f7de776d 3931 *real_evicted = 0;
ca0bf58d
PS
3932 state = hdr->b_l1hdr.b_state;
3933 if (GHOST_STATE(state)) {
e8b96c60
MA
3934
3935 /*
ca0bf58d 3936 * l2arc_write_buffers() relies on a header's L1 portion
a6255b7f 3937 * (i.e. its b_pabd field) during it's write phase.
ca0bf58d
PS
3938 * Thus, we cannot push a header onto the arc_l2c_only
3939 * state (removing its L1 piece) until the header is
3940 * done being written to the l2arc.
e8b96c60 3941 */
ca0bf58d
PS
3942 if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
3943 ARCSTAT_BUMP(arcstat_evict_l2_skip);
3944 return (bytes_evicted);
e8b96c60
MA
3945 }
3946
ca0bf58d 3947 ARCSTAT_BUMP(arcstat_deleted);
d3c2ae1c 3948 bytes_evicted += HDR_GET_LSIZE(hdr);
428870ff 3949
ca0bf58d 3950 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
428870ff 3951
ca0bf58d 3952 if (HDR_HAS_L2HDR(hdr)) {
a6255b7f 3953 ASSERT(hdr->b_l1hdr.b_pabd == NULL);
b5256303 3954 ASSERT(!HDR_HAS_RABD(hdr));
ca0bf58d
PS
3955 /*
3956 * This buffer is cached on the 2nd Level ARC;
3957 * don't destroy the header.
3958 */
c935fe2e 3959 arc_change_state(arc_l2c_only, hdr);
ca0bf58d
PS
3960 /*
3961 * dropping from L1+L2 cached to L2-only,
3962 * realloc to remove the L1 header.
3963 */
6a42939f 3964 (void) arc_hdr_realloc(hdr, hdr_full_cache,
ca0bf58d 3965 hdr_l2only_cache);
f7de776d 3966 *real_evicted += HDR_FULL_SIZE - HDR_L2ONLY_SIZE;
34dc7c2f 3967 } else {
c935fe2e 3968 arc_change_state(arc_anon, hdr);
ca0bf58d 3969 arc_hdr_destroy(hdr);
f7de776d 3970 *real_evicted += HDR_FULL_SIZE;
34dc7c2f 3971 }
ca0bf58d 3972 return (bytes_evicted);
34dc7c2f
BB
3973 }
3974
ed2f7ba0
AM
3975 ASSERT(state == arc_mru || state == arc_mfu || state == arc_uncached);
3976 evicted_state = (state == arc_uncached) ? arc_anon :
3977 ((state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost);
34dc7c2f 3978
ca0bf58d 3979 /* prefetch buffers have a minimum lifespan */
c935fe2e 3980 if ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
2b84817f 3981 ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
c935fe2e 3982 MSEC_TO_TICK(min_lifetime)) {
ca0bf58d
PS
3983 ARCSTAT_BUMP(arcstat_evict_skip);
3984 return (bytes_evicted);
da8ccd0e
PS
3985 }
3986
ca0bf58d 3987 if (HDR_HAS_L2HDR(hdr)) {
d3c2ae1c 3988 ARCSTAT_INCR(arcstat_evict_l2_cached, HDR_GET_LSIZE(hdr));
ca0bf58d 3989 } else {
d3c2ae1c
GW
3990 if (l2arc_write_eligible(hdr->b_spa, hdr)) {
3991 ARCSTAT_INCR(arcstat_evict_l2_eligible,
3992 HDR_GET_LSIZE(hdr));
08532162
GA
3993
3994 switch (state->arcs_state) {
3995 case ARC_STATE_MRU:
3996 ARCSTAT_INCR(
3997 arcstat_evict_l2_eligible_mru,
3998 HDR_GET_LSIZE(hdr));
3999 break;
4000 case ARC_STATE_MFU:
4001 ARCSTAT_INCR(
4002 arcstat_evict_l2_eligible_mfu,
4003 HDR_GET_LSIZE(hdr));
4004 break;
4005 default:
4006 break;
4007 }
d3c2ae1c
GW
4008 } else {
4009 ARCSTAT_INCR(arcstat_evict_l2_ineligible,
4010 HDR_GET_LSIZE(hdr));
4011 }
ca0bf58d 4012 }
34dc7c2f 4013
289f7e6a
AM
4014 bytes_evicted += arc_hdr_size(hdr);
4015 *real_evicted += arc_hdr_size(hdr);
d3c2ae1c 4016
289f7e6a
AM
4017 /*
4018 * If this hdr is being evicted and has a compressed buffer then we
4019 * discard it here before we change states. This ensures that the
4020 * accounting is updated correctly in arc_free_data_impl().
4021 */
4022 if (hdr->b_l1hdr.b_pabd != NULL)
4023 arc_hdr_free_abd(hdr, B_FALSE);
b5256303 4024
289f7e6a
AM
4025 if (HDR_HAS_RABD(hdr))
4026 arc_hdr_free_abd(hdr, B_TRUE);
d3c2ae1c 4027
289f7e6a
AM
4028 arc_change_state(evicted_state, hdr);
4029 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
4030 if (evicted_state == arc_anon) {
4031 arc_hdr_destroy(hdr);
4032 *real_evicted += HDR_FULL_SIZE;
4033 } else {
4034 ASSERT(HDR_IN_HASH_TABLE(hdr));
ca0bf58d 4035 }
34dc7c2f 4036
ca0bf58d 4037 return (bytes_evicted);
34dc7c2f
BB
4038}
4039
3442c2a0
MA
4040static void
4041arc_set_need_free(void)
4042{
4043 ASSERT(MUTEX_HELD(&arc_evict_lock));
4044 int64_t remaining = arc_free_memory() - arc_sys_free / 2;
4045 arc_evict_waiter_t *aw = list_tail(&arc_evict_waiters);
4046 if (aw == NULL) {
4047 arc_need_free = MAX(-remaining, 0);
4048 } else {
4049 arc_need_free =
4050 MAX(-remaining, (int64_t)(aw->aew_count - arc_evict_count));
4051 }
4052}
4053
ca0bf58d
PS
4054static uint64_t
4055arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
8172df64 4056 uint64_t spa, uint64_t bytes)
34dc7c2f 4057{
ca0bf58d 4058 multilist_sublist_t *mls;
f7de776d 4059 uint64_t bytes_evicted = 0, real_evicted = 0;
ca0bf58d 4060 arc_buf_hdr_t *hdr;
34dc7c2f 4061 kmutex_t *hash_lock;
fdc2d303 4062 uint_t evict_count = zfs_arc_evict_batch_limit;
34dc7c2f 4063
ca0bf58d 4064 ASSERT3P(marker, !=, NULL);
ca0bf58d
PS
4065
4066 mls = multilist_sublist_lock(ml, idx);
572e2857 4067
8172df64 4068 for (hdr = multilist_sublist_prev(mls, marker); likely(hdr != NULL);
ca0bf58d 4069 hdr = multilist_sublist_prev(mls, marker)) {
fdc2d303 4070 if ((evict_count == 0) || (bytes_evicted >= bytes))
ca0bf58d
PS
4071 break;
4072
4073 /*
4074 * To keep our iteration location, move the marker
4075 * forward. Since we're not holding hdr's hash lock, we
4076 * must be very careful and not remove 'hdr' from the
4077 * sublist. Otherwise, other consumers might mistake the
4078 * 'hdr' as not being on a sublist when they call the
4079 * multilist_link_active() function (they all rely on
4080 * the hash lock protecting concurrent insertions and
4081 * removals). multilist_sublist_move_forward() was
4082 * specifically implemented to ensure this is the case
4083 * (only 'marker' will be removed and re-inserted).
4084 */
4085 multilist_sublist_move_forward(mls, marker);
4086
4087 /*
4088 * The only case where the b_spa field should ever be
4089 * zero, is the marker headers inserted by
4090 * arc_evict_state(). It's possible for multiple threads
4091 * to be calling arc_evict_state() concurrently (e.g.
4092 * dsl_pool_close() and zio_inject_fault()), so we must
4093 * skip any markers we see from these other threads.
4094 */
2a432414 4095 if (hdr->b_spa == 0)
572e2857
BB
4096 continue;
4097
ca0bf58d
PS
4098 /* we're only interested in evicting buffers of a certain spa */
4099 if (spa != 0 && hdr->b_spa != spa) {
4100 ARCSTAT_BUMP(arcstat_evict_skip);
428870ff 4101 continue;
ca0bf58d
PS
4102 }
4103
4104 hash_lock = HDR_LOCK(hdr);
e8b96c60
MA
4105
4106 /*
ca0bf58d
PS
4107 * We aren't calling this function from any code path
4108 * that would already be holding a hash lock, so we're
4109 * asserting on this assumption to be defensive in case
4110 * this ever changes. Without this check, it would be
4111 * possible to incorrectly increment arcstat_mutex_miss
4112 * below (e.g. if the code changed such that we called
4113 * this function with a hash lock held).
e8b96c60 4114 */
ca0bf58d
PS
4115 ASSERT(!MUTEX_HELD(hash_lock));
4116
34dc7c2f 4117 if (mutex_tryenter(hash_lock)) {
f7de776d 4118 uint64_t revicted;
c935fe2e 4119 uint64_t evicted = arc_evict_hdr(hdr, &revicted);
ca0bf58d 4120 mutex_exit(hash_lock);
34dc7c2f 4121
ca0bf58d 4122 bytes_evicted += evicted;
f7de776d 4123 real_evicted += revicted;
34dc7c2f 4124
572e2857 4125 /*
ca0bf58d
PS
4126 * If evicted is zero, arc_evict_hdr() must have
4127 * decided to skip this header, don't increment
4128 * evict_count in this case.
572e2857 4129 */
ca0bf58d 4130 if (evicted != 0)
8172df64 4131 evict_count--;
ca0bf58d 4132
e8b96c60 4133 } else {
ca0bf58d 4134 ARCSTAT_BUMP(arcstat_mutex_miss);
e8b96c60 4135 }
34dc7c2f 4136 }
34dc7c2f 4137
ca0bf58d 4138 multilist_sublist_unlock(mls);
34dc7c2f 4139
3442c2a0
MA
4140 /*
4141 * Increment the count of evicted bytes, and wake up any threads that
4142 * are waiting for the count to reach this value. Since the list is
4143 * ordered by ascending aew_count, we pop off the beginning of the
4144 * list until we reach the end, or a waiter that's past the current
4145 * "count". Doing this outside the loop reduces the number of times
4146 * we need to acquire the global arc_evict_lock.
4147 *
4148 * Only wake when there's sufficient free memory in the system
4149 * (specifically, arc_sys_free/2, which by default is a bit more than
4150 * 1/64th of RAM). See the comments in arc_wait_for_eviction().
4151 */
4152 mutex_enter(&arc_evict_lock);
f7de776d 4153 arc_evict_count += real_evicted;
3442c2a0 4154
dc303dcf 4155 if (arc_free_memory() > arc_sys_free / 2) {
3442c2a0
MA
4156 arc_evict_waiter_t *aw;
4157 while ((aw = list_head(&arc_evict_waiters)) != NULL &&
4158 aw->aew_count <= arc_evict_count) {
4159 list_remove(&arc_evict_waiters, aw);
4160 cv_broadcast(&aw->aew_cv);
4161 }
4162 }
4163 arc_set_need_free();
4164 mutex_exit(&arc_evict_lock);
4165
67c0f0de
MA
4166 /*
4167 * If the ARC size is reduced from arc_c_max to arc_c_min (especially
4168 * if the average cached block is small), eviction can be on-CPU for
4169 * many seconds. To ensure that other threads that may be bound to
4170 * this CPU are able to make progress, make a voluntary preemption
4171 * call here.
4172 */
0e4c830b 4173 kpreempt(KPREEMPT_SYNC);
67c0f0de 4174
ca0bf58d 4175 return (bytes_evicted);
34dc7c2f
BB
4176}
4177
6e2a5918
MJ
4178/*
4179 * Allocate an array of buffer headers used as placeholders during arc state
4180 * eviction.
4181 */
4182static arc_buf_hdr_t **
4183arc_state_alloc_markers(int count)
4184{
4185 arc_buf_hdr_t **markers;
4186
4187 markers = kmem_zalloc(sizeof (*markers) * count, KM_SLEEP);
4188 for (int i = 0; i < count; i++) {
4189 markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
4190
4191 /*
4192 * A b_spa of 0 is used to indicate that this header is
a8d83e2a 4193 * a marker. This fact is used in arc_evict_state_impl().
6e2a5918
MJ
4194 */
4195 markers[i]->b_spa = 0;
4196
4197 }
4198 return (markers);
4199}
4200
4201static void
4202arc_state_free_markers(arc_buf_hdr_t **markers, int count)
4203{
4204 for (int i = 0; i < count; i++)
4205 kmem_cache_free(hdr_full_cache, markers[i]);
4206 kmem_free(markers, sizeof (*markers) * count);
4207}
4208
ca0bf58d
PS
4209/*
4210 * Evict buffers from the given arc state, until we've removed the
4211 * specified number of bytes. Move the removed buffers to the
4212 * appropriate evict state.
4213 *
4214 * This function makes a "best effort". It skips over any buffers
4215 * it can't get a hash_lock on, and so, may not catch all candidates.
4216 * It may also return without evicting as much space as requested.
4217 *
4218 * If bytes is specified using the special value ARC_EVICT_ALL, this
4219 * will evict all available (i.e. unlocked and evictable) buffers from
4220 * the given arc state; which is used by arc_flush().
4221 */
4222static uint64_t
a8d83e2a
AM
4223arc_evict_state(arc_state_t *state, arc_buf_contents_t type, uint64_t spa,
4224 uint64_t bytes)
34dc7c2f 4225{
ca0bf58d 4226 uint64_t total_evicted = 0;
ffdf019c 4227 multilist_t *ml = &state->arcs_list[type];
ca0bf58d
PS
4228 int num_sublists;
4229 arc_buf_hdr_t **markers;
ca0bf58d 4230
ca0bf58d 4231 num_sublists = multilist_get_num_sublists(ml);
d164b209
BB
4232
4233 /*
ca0bf58d
PS
4234 * If we've tried to evict from each sublist, made some
4235 * progress, but still have not hit the target number of bytes
4236 * to evict, we want to keep trying. The markers allow us to
4237 * pick up where we left off for each individual sublist, rather
4238 * than starting from the tail each time.
d164b209 4239 */
6e2a5918
MJ
4240 if (zthr_iscurthread(arc_evict_zthr)) {
4241 markers = arc_state_evict_markers;
4242 ASSERT3S(num_sublists, <=, arc_state_evict_marker_count);
4243 } else {
4244 markers = arc_state_alloc_markers(num_sublists);
4245 }
1c27024e 4246 for (int i = 0; i < num_sublists; i++) {
ca0bf58d 4247 multilist_sublist_t *mls;
34dc7c2f 4248
ca0bf58d
PS
4249 mls = multilist_sublist_lock(ml, i);
4250 multilist_sublist_insert_tail(mls, markers[i]);
4251 multilist_sublist_unlock(mls);
34dc7c2f
BB
4252 }
4253
d164b209 4254 /*
ca0bf58d
PS
4255 * While we haven't hit our target number of bytes to evict, or
4256 * we're evicting all available buffers.
d164b209 4257 */
8172df64 4258 while (total_evicted < bytes) {
25458cbe
TC
4259 int sublist_idx = multilist_get_random_index(ml);
4260 uint64_t scan_evicted = 0;
4261
ca0bf58d
PS
4262 /*
4263 * Start eviction using a randomly selected sublist,
4264 * this is to try and evenly balance eviction across all
4265 * sublists. Always starting at the same sublist
4266 * (e.g. index 0) would cause evictions to favor certain
4267 * sublists over others.
4268 */
1c27024e 4269 for (int i = 0; i < num_sublists; i++) {
ca0bf58d
PS
4270 uint64_t bytes_remaining;
4271 uint64_t bytes_evicted;
d164b209 4272
8172df64 4273 if (total_evicted < bytes)
ca0bf58d
PS
4274 bytes_remaining = bytes - total_evicted;
4275 else
4276 break;
34dc7c2f 4277
ca0bf58d
PS
4278 bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
4279 markers[sublist_idx], spa, bytes_remaining);
4280
4281 scan_evicted += bytes_evicted;
4282 total_evicted += bytes_evicted;
4283
4284 /* we've reached the end, wrap to the beginning */
4285 if (++sublist_idx >= num_sublists)
4286 sublist_idx = 0;
4287 }
4288
4289 /*
4290 * If we didn't evict anything during this scan, we have
4291 * no reason to believe we'll evict more during another
4292 * scan, so break the loop.
4293 */
4294 if (scan_evicted == 0) {
4295 /* This isn't possible, let's make that obvious */
4296 ASSERT3S(bytes, !=, 0);
34dc7c2f 4297
ca0bf58d
PS
4298 /*
4299 * When bytes is ARC_EVICT_ALL, the only way to
4300 * break the loop is when scan_evicted is zero.
4301 * In that case, we actually have evicted enough,
4302 * so we don't want to increment the kstat.
4303 */
4304 if (bytes != ARC_EVICT_ALL) {
4305 ASSERT3S(total_evicted, <, bytes);
4306 ARCSTAT_BUMP(arcstat_evict_not_enough);
4307 }
d164b209 4308
ca0bf58d
PS
4309 break;
4310 }
d164b209 4311 }
34dc7c2f 4312
1c27024e 4313 for (int i = 0; i < num_sublists; i++) {
ca0bf58d
PS
4314 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
4315 multilist_sublist_remove(mls, markers[i]);
4316 multilist_sublist_unlock(mls);
34dc7c2f 4317 }
6e2a5918
MJ
4318 if (markers != arc_state_evict_markers)
4319 arc_state_free_markers(markers, num_sublists);
ca0bf58d
PS
4320
4321 return (total_evicted);
4322}
4323
4324/*
4325 * Flush all "evictable" data of the given type from the arc state
4326 * specified. This will not evict any "active" buffers (i.e. referenced).
4327 *
d3c2ae1c 4328 * When 'retry' is set to B_FALSE, the function will make a single pass
ca0bf58d
PS
4329 * over the state and evict any buffers that it can. Since it doesn't
4330 * continually retry the eviction, it might end up leaving some buffers
4331 * in the ARC due to lock misses.
4332 *
d3c2ae1c 4333 * When 'retry' is set to B_TRUE, the function will continually retry the
ca0bf58d
PS
4334 * eviction until *all* evictable buffers have been removed from the
4335 * state. As a result, if concurrent insertions into the state are
4336 * allowed (e.g. if the ARC isn't shutting down), this function might
4337 * wind up in an infinite loop, continually trying to evict buffers.
4338 */
4339static uint64_t
4340arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
4341 boolean_t retry)
4342{
4343 uint64_t evicted = 0;
4344
424fd7c3 4345 while (zfs_refcount_count(&state->arcs_esize[type]) != 0) {
a8d83e2a 4346 evicted += arc_evict_state(state, type, spa, ARC_EVICT_ALL);
ca0bf58d
PS
4347
4348 if (!retry)
4349 break;
4350 }
4351
4352 return (evicted);
34dc7c2f
BB
4353}
4354
ca0bf58d 4355/*
a8d83e2a
AM
4356 * Evict the specified number of bytes from the state specified. This
4357 * function prevents us from trying to evict more from a state's list
4358 * than is "evictable", and to skip evicting altogether when passed a
ca0bf58d
PS
4359 * negative value for "bytes". In contrast, arc_evict_state() will
4360 * evict everything it can, when passed a negative value for "bytes".
4361 */
4362static uint64_t
a8d83e2a 4363arc_evict_impl(arc_state_t *state, arc_buf_contents_t type, int64_t bytes)
ca0bf58d 4364{
8172df64 4365 uint64_t delta;
ca0bf58d 4366
424fd7c3
TS
4367 if (bytes > 0 && zfs_refcount_count(&state->arcs_esize[type]) > 0) {
4368 delta = MIN(zfs_refcount_count(&state->arcs_esize[type]),
4369 bytes);
a8d83e2a 4370 return (arc_evict_state(state, type, 0, delta));
ca0bf58d
PS
4371 }
4372
4373 return (0);
4374}
4375
4376/*
a8d83e2a
AM
4377 * Adjust specified fraction, taking into account initial ghost state(s) size,
4378 * ghost hit bytes towards increasing the fraction, ghost hit bytes towards
4379 * decreasing it, plus a balance factor, controlling the decrease rate, used
4380 * to balance metadata vs data.
ca0bf58d
PS
4381 */
4382static uint64_t
a8d83e2a
AM
4383arc_evict_adj(uint64_t frac, uint64_t total, uint64_t up, uint64_t down,
4384 uint_t balance)
ca0bf58d 4385{
a8d83e2a
AM
4386 if (total < 8 || up + down == 0)
4387 return (frac);
ca0bf58d
PS
4388
4389 /*
a8d83e2a
AM
4390 * We should not have more ghost hits than ghost size, but they
4391 * may get close. Restrict maximum adjustment in that case.
ca0bf58d 4392 */
a8d83e2a
AM
4393 if (up + down >= total / 4) {
4394 uint64_t scale = (up + down) / (total / 8);
4395 up /= scale;
4396 down /= scale;
ca0bf58d
PS
4397 }
4398
a8d83e2a
AM
4399 /* Get maximal dynamic range by choosing optimal shifts. */
4400 int s = highbit64(total);
4401 s = MIN(64 - s, 32);
ca0bf58d 4402
a8d83e2a 4403 uint64_t ofrac = (1ULL << 32) - frac;
ca0bf58d 4404
a8d83e2a
AM
4405 if (frac >= 4 * ofrac)
4406 up /= frac / (2 * ofrac + 1);
4407 up = (up << s) / (total >> (32 - s));
4408 if (ofrac >= 4 * frac)
4409 down /= ofrac / (2 * frac + 1);
4410 down = (down << s) / (total >> (32 - s));
4411 down = down * 100 / balance;
ca0bf58d 4412
a8d83e2a 4413 return (frac + up - down);
ca0bf58d
PS
4414}
4415
4416/*
c4c162c1 4417 * Evict buffers from the cache, such that arcstat_size is capped by arc_c.
ca0bf58d
PS
4418 */
4419static uint64_t
5dd92909 4420arc_evict(void)
ca0bf58d 4421{
a8d83e2a
AM
4422 uint64_t asize, bytes, total_evicted = 0;
4423 int64_t e, mrud, mrum, mfud, mfum, w;
4424 static uint64_t ogrd, ogrm, ogfd, ogfm;
4425 static uint64_t gsrd, gsrm, gsfd, gsfm;
4426 uint64_t ngrd, ngrm, ngfd, ngfm;
4427
4428 /* Get current size of ARC states we can evict from. */
4429 mrud = zfs_refcount_count(&arc_mru->arcs_size[ARC_BUFC_DATA]) +
4430 zfs_refcount_count(&arc_anon->arcs_size[ARC_BUFC_DATA]);
4431 mrum = zfs_refcount_count(&arc_mru->arcs_size[ARC_BUFC_METADATA]) +
4432 zfs_refcount_count(&arc_anon->arcs_size[ARC_BUFC_METADATA]);
4433 mfud = zfs_refcount_count(&arc_mfu->arcs_size[ARC_BUFC_DATA]);
4434 mfum = zfs_refcount_count(&arc_mfu->arcs_size[ARC_BUFC_METADATA]);
4435 uint64_t d = mrud + mfud;
4436 uint64_t m = mrum + mfum;
4437 uint64_t t = d + m;
4438
4439 /* Get ARC ghost hits since last eviction. */
4440 ngrd = wmsum_value(&arc_mru_ghost->arcs_hits[ARC_BUFC_DATA]);
4441 uint64_t grd = ngrd - ogrd;
4442 ogrd = ngrd;
4443 ngrm = wmsum_value(&arc_mru_ghost->arcs_hits[ARC_BUFC_METADATA]);
4444 uint64_t grm = ngrm - ogrm;
4445 ogrm = ngrm;
4446 ngfd = wmsum_value(&arc_mfu_ghost->arcs_hits[ARC_BUFC_DATA]);
4447 uint64_t gfd = ngfd - ogfd;
4448 ogfd = ngfd;
4449 ngfm = wmsum_value(&arc_mfu_ghost->arcs_hits[ARC_BUFC_METADATA]);
4450 uint64_t gfm = ngfm - ogfm;
4451 ogfm = ngfm;
4452
4453 /* Adjust ARC states balance based on ghost hits. */
4454 arc_meta = arc_evict_adj(arc_meta, gsrd + gsrm + gsfd + gsfm,
4455 grm + gfm, grd + gfd, zfs_arc_meta_balance);
4456 arc_pd = arc_evict_adj(arc_pd, gsrd + gsfd, grd, gfd, 100);
4457 arc_pm = arc_evict_adj(arc_pm, gsrm + gsfm, grm, gfm, 100);
ca0bf58d 4458
c4c162c1 4459 asize = aggsum_value(&arc_sums.arcstat_size);
a8d83e2a
AM
4460 int64_t wt = t - (asize - arc_c);
4461
4462 /*
4463 * Try to reduce pinned dnodes if more than 3/4 of wanted metadata
4464 * target is not evictable or if they go over arc_dnode_limit.
4465 */
4466 int64_t prune = 0;
4467 int64_t dn = wmsum_value(&arc_sums.arcstat_dnode_size);
1038f87c 4468 w = wt * (int64_t)(arc_meta >> 16) >> 16;
a8d83e2a
AM
4469 if (zfs_refcount_count(&arc_mru->arcs_size[ARC_BUFC_METADATA]) +
4470 zfs_refcount_count(&arc_mfu->arcs_size[ARC_BUFC_METADATA]) -
4471 zfs_refcount_count(&arc_mru->arcs_esize[ARC_BUFC_METADATA]) -
4472 zfs_refcount_count(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]) >
4473 w * 3 / 4) {
4474 prune = dn / sizeof (dnode_t) *
4475 zfs_arc_dnode_reduce_percent / 100;
4476 } else if (dn > arc_dnode_limit) {
4477 prune = (dn - arc_dnode_limit) / sizeof (dnode_t) *
4478 zfs_arc_dnode_reduce_percent / 100;
4479 }
4480 if (prune > 0)
4481 arc_prune_async(prune);
4482
4483 /* Evict MRU metadata. */
1038f87c 4484 w = wt * (int64_t)(arc_meta * arc_pm >> 48) >> 16;
a8d83e2a
AM
4485 e = MIN((int64_t)(asize - arc_c), (int64_t)(mrum - w));
4486 bytes = arc_evict_impl(arc_mru, ARC_BUFC_METADATA, e);
ca0bf58d 4487 total_evicted += bytes;
a8d83e2a
AM
4488 mrum -= bytes;
4489 asize -= bytes;
ca0bf58d 4490
a8d83e2a 4491 /* Evict MFU metadata. */
1038f87c 4492 w = wt * (int64_t)(arc_meta >> 16) >> 16;
a8d83e2a
AM
4493 e = MIN((int64_t)(asize - arc_c), (int64_t)(m - w));
4494 bytes = arc_evict_impl(arc_mfu, ARC_BUFC_METADATA, e);
4495 total_evicted += bytes;
4496 mfum -= bytes;
4497 asize -= bytes;
4498
4499 /* Evict MRU data. */
4500 wt -= m - total_evicted;
1038f87c 4501 w = wt * (int64_t)(arc_pd >> 16) >> 16;
a8d83e2a
AM
4502 e = MIN((int64_t)(asize - arc_c), (int64_t)(mrud - w));
4503 bytes = arc_evict_impl(arc_mru, ARC_BUFC_DATA, e);
4504 total_evicted += bytes;
4505 mrud -= bytes;
4506 asize -= bytes;
ca0bf58d 4507
a8d83e2a
AM
4508 /* Evict MFU data. */
4509 e = asize - arc_c;
4510 bytes = arc_evict_impl(arc_mfu, ARC_BUFC_DATA, e);
4511 mfud -= bytes;
4512 total_evicted += bytes;
ca0bf58d
PS
4513
4514 /*
a8d83e2a 4515 * Evict ghost lists
ca0bf58d 4516 *
a8d83e2a
AM
4517 * Size of each state's ghost list represents how much that state
4518 * may grow by shrinking the other states. Would it need to shrink
4519 * other states to zero (that is unlikely), its ghost size would be
4520 * equal to sum of other three state sizes. But excessive ghost
4521 * size may result in false ghost hits (too far back), that may
4522 * never result in real cache hits if several states are competing.
4523 * So choose some arbitraty point of 1/2 of other state sizes.
4524 */
4525 gsrd = (mrum + mfud + mfum) / 2;
4526 e = zfs_refcount_count(&arc_mru_ghost->arcs_size[ARC_BUFC_DATA]) -
4527 gsrd;
4528 (void) arc_evict_impl(arc_mru_ghost, ARC_BUFC_DATA, e);
4529
4530 gsrm = (mrud + mfud + mfum) / 2;
4531 e = zfs_refcount_count(&arc_mru_ghost->arcs_size[ARC_BUFC_METADATA]) -
4532 gsrm;
4533 (void) arc_evict_impl(arc_mru_ghost, ARC_BUFC_METADATA, e);
4534
4535 gsfd = (mrud + mrum + mfum) / 2;
4536 e = zfs_refcount_count(&arc_mfu_ghost->arcs_size[ARC_BUFC_DATA]) -
4537 gsfd;
4538 (void) arc_evict_impl(arc_mfu_ghost, ARC_BUFC_DATA, e);
4539
4540 gsfm = (mrud + mrum + mfud) / 2;
4541 e = zfs_refcount_count(&arc_mfu_ghost->arcs_size[ARC_BUFC_METADATA]) -
4542 gsfm;
4543 (void) arc_evict_impl(arc_mfu_ghost, ARC_BUFC_METADATA, e);
ca0bf58d
PS
4544
4545 return (total_evicted);
4546}
4547
ca0bf58d
PS
4548void
4549arc_flush(spa_t *spa, boolean_t retry)
ab26409d 4550{
ca0bf58d 4551 uint64_t guid = 0;
94520ca4 4552
bc888666 4553 /*
d3c2ae1c 4554 * If retry is B_TRUE, a spa must not be specified since we have
ca0bf58d
PS
4555 * no good way to determine if all of a spa's buffers have been
4556 * evicted from an arc state.
bc888666 4557 */
4ef69de3 4558 ASSERT(!retry || spa == NULL);
d164b209 4559
b9541d6b 4560 if (spa != NULL)
3541dc6d 4561 guid = spa_load_guid(spa);
d164b209 4562
ca0bf58d
PS
4563 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
4564 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
4565
4566 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
4567 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
4568
4569 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
4570 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
34dc7c2f 4571
ca0bf58d
PS
4572 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
4573 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
ed2f7ba0
AM
4574
4575 (void) arc_flush_state(arc_uncached, guid, ARC_BUFC_DATA, retry);
4576 (void) arc_flush_state(arc_uncached, guid, ARC_BUFC_METADATA, retry);
34dc7c2f
BB
4577}
4578
c9c9c1e2 4579void
3ec34e55 4580arc_reduce_target_size(int64_t to_free)
34dc7c2f 4581{
a8d83e2a
AM
4582 uint64_t c = arc_c;
4583
4584 if (c <= arc_c_min)
4585 return;
3442c2a0
MA
4586
4587 /*
4588 * All callers want the ARC to actually evict (at least) this much
4589 * memory. Therefore we reduce from the lower of the current size and
4590 * the target size. This way, even if arc_c is much higher than
4591 * arc_size (as can be the case after many calls to arc_freed(), we will
4592 * immediately have arc_c < arc_size and therefore the arc_evict_zthr
4593 * will evict.
4594 */
a8d83e2a
AM
4595 uint64_t asize = aggsum_value(&arc_sums.arcstat_size);
4596 if (asize < c)
4597 to_free += c - asize;
4598 arc_c = MAX((int64_t)c - to_free, (int64_t)arc_c_min);
34dc7c2f 4599
a8d83e2a
AM
4600 /* See comment in arc_evict_cb_check() on why lock+flag */
4601 mutex_enter(&arc_evict_lock);
4602 arc_evict_needed = B_TRUE;
4603 mutex_exit(&arc_evict_lock);
4604 zthr_wakeup(arc_evict_zthr);
34dc7c2f 4605}
ca67b33a
MA
4606
4607/*
4608 * Determine if the system is under memory pressure and is asking
d3c2ae1c 4609 * to reclaim memory. A return value of B_TRUE indicates that the system
ca67b33a
MA
4610 * is under memory pressure and that the arc should adjust accordingly.
4611 */
c9c9c1e2 4612boolean_t
ca67b33a
MA
4613arc_reclaim_needed(void)
4614{
4615 return (arc_available_memory() < 0);
4616}
4617
c9c9c1e2 4618void
3ec34e55 4619arc_kmem_reap_soon(void)
34dc7c2f
BB
4620{
4621 size_t i;
4622 kmem_cache_t *prev_cache = NULL;
4623 kmem_cache_t *prev_data_cache = NULL;
34dc7c2f 4624
70f02287 4625#ifdef _KERNEL
70f02287
BB
4626#if defined(_ILP32)
4627 /*
4628 * Reclaim unused memory from all kmem caches.
4629 */
4630 kmem_reap();
4631#endif
4632#endif
f6046738 4633
34dc7c2f 4634 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
70f02287 4635#if defined(_ILP32)
d0c614ec 4636 /* reach upper limit of cache size on 32-bit */
4637 if (zio_buf_cache[i] == NULL)
4638 break;
4639#endif
34dc7c2f
BB
4640 if (zio_buf_cache[i] != prev_cache) {
4641 prev_cache = zio_buf_cache[i];
4642 kmem_cache_reap_now(zio_buf_cache[i]);
4643 }
4644 if (zio_data_buf_cache[i] != prev_data_cache) {
4645 prev_data_cache = zio_data_buf_cache[i];
4646 kmem_cache_reap_now(zio_data_buf_cache[i]);
4647 }
4648 }
ca0bf58d 4649 kmem_cache_reap_now(buf_cache);
b9541d6b
CW
4650 kmem_cache_reap_now(hdr_full_cache);
4651 kmem_cache_reap_now(hdr_l2only_cache);
ca577779 4652 kmem_cache_reap_now(zfs_btree_leaf_cache);
7564073e 4653 abd_cache_reap_now();
34dc7c2f
BB
4654}
4655
3ec34e55 4656static boolean_t
5dd92909 4657arc_evict_cb_check(void *arg, zthr_t *zthr)
3ec34e55 4658{
14e4e3cb
AZ
4659 (void) arg, (void) zthr;
4660
1531506d 4661#ifdef ZFS_DEBUG
3ec34e55
BL
4662 /*
4663 * This is necessary in order to keep the kstat information
4664 * up to date for tools that display kstat data such as the
4665 * mdb ::arc dcmd and the Linux crash utility. These tools
4666 * typically do not call kstat's update function, but simply
4667 * dump out stats from the most recent update. Without
4668 * this call, these commands may show stale stats for the
1531506d
RM
4669 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
4670 * with this call, the data might be out of date if the
4671 * evict thread hasn't been woken recently; but that should
4672 * suffice. The arc_state_t structures can be queried
4673 * directly if more accurate information is needed.
3ec34e55
BL
4674 */
4675 if (arc_ksp != NULL)
4676 arc_ksp->ks_update(arc_ksp, KSTAT_READ);
1531506d 4677#endif
3ec34e55
BL
4678
4679 /*
3442c2a0
MA
4680 * We have to rely on arc_wait_for_eviction() to tell us when to
4681 * evict, rather than checking if we are overflowing here, so that we
4682 * are sure to not leave arc_wait_for_eviction() waiting on aew_cv.
4683 * If we have become "not overflowing" since arc_wait_for_eviction()
4684 * checked, we need to wake it up. We could broadcast the CV here,
4685 * but arc_wait_for_eviction() may have not yet gone to sleep. We
4686 * would need to use a mutex to ensure that this function doesn't
4687 * broadcast until arc_wait_for_eviction() has gone to sleep (e.g.
4688 * the arc_evict_lock). However, the lock ordering of such a lock
4689 * would necessarily be incorrect with respect to the zthr_lock,
4690 * which is held before this function is called, and is held by
4691 * arc_wait_for_eviction() when it calls zthr_wakeup().
3ec34e55 4692 */
ed2f7ba0
AM
4693 if (arc_evict_needed)
4694 return (B_TRUE);
4695
4696 /*
4697 * If we have buffers in uncached state, evict them periodically.
4698 */
4699 return ((zfs_refcount_count(&arc_uncached->arcs_esize[ARC_BUFC_DATA]) +
4700 zfs_refcount_count(&arc_uncached->arcs_esize[ARC_BUFC_METADATA]) &&
4701 ddi_get_lbolt() - arc_last_uncached_flush >
4702 MSEC_TO_TICK(arc_min_prefetch_ms / 2)));
3ec34e55
BL
4703}
4704
302f753f 4705/*
5dd92909 4706 * Keep arc_size under arc_c by running arc_evict which evicts data
3ec34e55 4707 * from the ARC.
302f753f 4708 */
61c3391a 4709static void
5dd92909 4710arc_evict_cb(void *arg, zthr_t *zthr)
34dc7c2f 4711{
14e4e3cb
AZ
4712 (void) arg, (void) zthr;
4713
3ec34e55
BL
4714 uint64_t evicted = 0;
4715 fstrans_cookie_t cookie = spl_fstrans_mark();
34dc7c2f 4716
ed2f7ba0
AM
4717 /* Always try to evict from uncached state. */
4718 arc_last_uncached_flush = ddi_get_lbolt();
4719 evicted += arc_flush_state(arc_uncached, 0, ARC_BUFC_DATA, B_FALSE);
4720 evicted += arc_flush_state(arc_uncached, 0, ARC_BUFC_METADATA, B_FALSE);
4721
4722 /* Evict from other states only if told to. */
4723 if (arc_evict_needed)
4724 evicted += arc_evict();
34dc7c2f 4725
3ec34e55
BL
4726 /*
4727 * If evicted is zero, we couldn't evict anything
5dd92909 4728 * via arc_evict(). This could be due to hash lock
3ec34e55
BL
4729 * collisions, but more likely due to the majority of
4730 * arc buffers being unevictable. Therefore, even if
4731 * arc_size is above arc_c, another pass is unlikely to
4732 * be helpful and could potentially cause us to enter an
4733 * infinite loop. Additionally, zthr_iscancelled() is
4734 * checked here so that if the arc is shutting down, the
5dd92909 4735 * broadcast will wake any remaining arc evict waiters.
3ec34e55 4736 */
5dd92909
MA
4737 mutex_enter(&arc_evict_lock);
4738 arc_evict_needed = !zthr_iscancelled(arc_evict_zthr) &&
c4c162c1 4739 evicted > 0 && aggsum_compare(&arc_sums.arcstat_size, arc_c) > 0;
5dd92909 4740 if (!arc_evict_needed) {
d3c2ae1c 4741 /*
3ec34e55
BL
4742 * We're either no longer overflowing, or we
4743 * can't evict anything more, so we should wake
4744 * arc_get_data_impl() sooner.
d3c2ae1c 4745 */
3442c2a0
MA
4746 arc_evict_waiter_t *aw;
4747 while ((aw = list_remove_head(&arc_evict_waiters)) != NULL) {
4748 cv_broadcast(&aw->aew_cv);
4749 }
4750 arc_set_need_free();
3ec34e55 4751 }
5dd92909 4752 mutex_exit(&arc_evict_lock);
3ec34e55 4753 spl_fstrans_unmark(cookie);
3ec34e55
BL
4754}
4755
3ec34e55
BL
4756static boolean_t
4757arc_reap_cb_check(void *arg, zthr_t *zthr)
4758{
14e4e3cb
AZ
4759 (void) arg, (void) zthr;
4760
3ec34e55 4761 int64_t free_memory = arc_available_memory();
8a171ccd 4762 static int reap_cb_check_counter = 0;
3ec34e55
BL
4763
4764 /*
4765 * If a kmem reap is already active, don't schedule more. We must
4766 * check for this because kmem_cache_reap_soon() won't actually
4767 * block on the cache being reaped (this is to prevent callers from
4768 * becoming implicitly blocked by a system-wide kmem reap -- which,
4769 * on a system with many, many full magazines, can take minutes).
4770 */
4771 if (!kmem_cache_reap_active() && free_memory < 0) {
34dc7c2f 4772
3ec34e55
BL
4773 arc_no_grow = B_TRUE;
4774 arc_warm = B_TRUE;
0a252dae 4775 /*
3ec34e55
BL
4776 * Wait at least zfs_grow_retry (default 5) seconds
4777 * before considering growing.
0a252dae 4778 */
3ec34e55
BL
4779 arc_growtime = gethrtime() + SEC2NSEC(arc_grow_retry);
4780 return (B_TRUE);
4781 } else if (free_memory < arc_c >> arc_no_grow_shift) {
4782 arc_no_grow = B_TRUE;
4783 } else if (gethrtime() >= arc_growtime) {
4784 arc_no_grow = B_FALSE;
4785 }
0a252dae 4786
8a171ccd
SG
4787 /*
4788 * Called unconditionally every 60 seconds to reclaim unused
4789 * zstd compression and decompression context. This is done
4790 * here to avoid the need for an independent thread.
4791 */
4792 if (!((reap_cb_check_counter++) % 60))
4793 zfs_zstd_cache_reap_now();
4794
3ec34e55
BL
4795 return (B_FALSE);
4796}
34dc7c2f 4797
3ec34e55
BL
4798/*
4799 * Keep enough free memory in the system by reaping the ARC's kmem
4800 * caches. To cause more slabs to be reapable, we may reduce the
5dd92909 4801 * target size of the cache (arc_c), causing the arc_evict_cb()
3ec34e55
BL
4802 * to free more buffers.
4803 */
61c3391a 4804static void
3ec34e55
BL
4805arc_reap_cb(void *arg, zthr_t *zthr)
4806{
14e4e3cb
AZ
4807 (void) arg, (void) zthr;
4808
3ec34e55
BL
4809 int64_t free_memory;
4810 fstrans_cookie_t cookie = spl_fstrans_mark();
34dc7c2f 4811
3ec34e55
BL
4812 /*
4813 * Kick off asynchronous kmem_reap()'s of all our caches.
4814 */
4815 arc_kmem_reap_soon();
6a8f9b6b 4816
3ec34e55
BL
4817 /*
4818 * Wait at least arc_kmem_cache_reap_retry_ms between
4819 * arc_kmem_reap_soon() calls. Without this check it is possible to
4820 * end up in a situation where we spend lots of time reaping
4821 * caches, while we're near arc_c_min. Waiting here also gives the
4822 * subsequent free memory check a chance of finding that the
4823 * asynchronous reap has already freed enough memory, and we don't
4824 * need to call arc_reduce_target_size().
4825 */
4826 delay((hz * arc_kmem_cache_reap_retry_ms + 999) / 1000);
34dc7c2f 4827
3ec34e55
BL
4828 /*
4829 * Reduce the target size as needed to maintain the amount of free
4830 * memory in the system at a fraction of the arc_size (1/128th by
4831 * default). If oversubscribed (free_memory < 0) then reduce the
4832 * target arc_size by the deficit amount plus the fractional
bf169e9f 4833 * amount. If free memory is positive but less than the fractional
3ec34e55
BL
4834 * amount, reduce by what is needed to hit the fractional amount.
4835 */
4836 free_memory = arc_available_memory();
34dc7c2f 4837
f933b3fd
AM
4838 int64_t can_free = arc_c - arc_c_min;
4839 if (can_free > 0) {
4840 int64_t to_free = (can_free >> arc_shrink_shift) - free_memory;
4841 if (to_free > 0)
4842 arc_reduce_target_size(to_free);
ca0bf58d 4843 }
ca0bf58d 4844 spl_fstrans_unmark(cookie);
ca0bf58d
PS
4845}
4846
7cb67b45
BB
4847#ifdef _KERNEL
4848/*
302f753f
BB
4849 * Determine the amount of memory eligible for eviction contained in the
4850 * ARC. All clean data reported by the ghost lists can always be safely
4851 * evicted. Due to arc_c_min, the same does not hold for all clean data
4852 * contained by the regular mru and mfu lists.
4853 *
4854 * In the case of the regular mru and mfu lists, we need to report as
4855 * much clean data as possible, such that evicting that same reported
4856 * data will not bring arc_size below arc_c_min. Thus, in certain
4857 * circumstances, the total amount of clean data in the mru and mfu
4858 * lists might not actually be evictable.
4859 *
4860 * The following two distinct cases are accounted for:
4861 *
4862 * 1. The sum of the amount of dirty data contained by both the mru and
4863 * mfu lists, plus the ARC's other accounting (e.g. the anon list),
4864 * is greater than or equal to arc_c_min.
4865 * (i.e. amount of dirty data >= arc_c_min)
4866 *
4867 * This is the easy case; all clean data contained by the mru and mfu
4868 * lists is evictable. Evicting all clean data can only drop arc_size
4869 * to the amount of dirty data, which is greater than arc_c_min.
4870 *
4871 * 2. The sum of the amount of dirty data contained by both the mru and
4872 * mfu lists, plus the ARC's other accounting (e.g. the anon list),
4873 * is less than arc_c_min.
4874 * (i.e. arc_c_min > amount of dirty data)
4875 *
4876 * 2.1. arc_size is greater than or equal arc_c_min.
4877 * (i.e. arc_size >= arc_c_min > amount of dirty data)
4878 *
4879 * In this case, not all clean data from the regular mru and mfu
4880 * lists is actually evictable; we must leave enough clean data
4881 * to keep arc_size above arc_c_min. Thus, the maximum amount of
4882 * evictable data from the two lists combined, is exactly the
4883 * difference between arc_size and arc_c_min.
4884 *
4885 * 2.2. arc_size is less than arc_c_min
4886 * (i.e. arc_c_min > arc_size > amount of dirty data)
4887 *
4888 * In this case, none of the data contained in the mru and mfu
4889 * lists is evictable, even if it's clean. Since arc_size is
4890 * already below arc_c_min, evicting any more would only
4891 * increase this negative difference.
7cb67b45 4892 */
7cb67b45 4893
7cb67b45
BB
4894#endif /* _KERNEL */
4895
34dc7c2f
BB
4896/*
4897 * Adapt arc info given the number of bytes we are trying to add and
4e33ba4c 4898 * the state that we are coming from. This function is only called
34dc7c2f
BB
4899 * when we are adding new content to the cache.
4900 */
4901static void
a8d83e2a 4902arc_adapt(uint64_t bytes)
34dc7c2f 4903{
3ec34e55
BL
4904 /*
4905 * Wake reap thread if we do not have any available memory
4906 */
ca67b33a 4907 if (arc_reclaim_needed()) {
3ec34e55 4908 zthr_wakeup(arc_reap_zthr);
ca67b33a
MA
4909 return;
4910 }
4911
34dc7c2f
BB
4912 if (arc_no_grow)
4913 return;
4914
4915 if (arc_c >= arc_c_max)
4916 return;
4917
4918 /*
4919 * If we're within (2 * maxblocksize) bytes of the target
4920 * cache size, increment the target cache size
4921 */
a8d83e2a
AM
4922 if (aggsum_upper_bound(&arc_sums.arcstat_size) +
4923 2 * SPA_MAXBLOCKSIZE >= arc_c) {
4924 uint64_t dc = MAX(bytes, SPA_OLD_MAXBLOCKSIZE);
4925 if (atomic_add_64_nv(&arc_c, dc) > arc_c_max)
34dc7c2f 4926 arc_c = arc_c_max;
34dc7c2f 4927 }
34dc7c2f
BB
4928}
4929
4930/*
ca0bf58d
PS
4931 * Check if arc_size has grown past our upper threshold, determined by
4932 * zfs_arc_overflow_shift.
34dc7c2f 4933 */
f7de776d 4934static arc_ovf_level_t
6b88b4b5 4935arc_is_overflowing(boolean_t use_reserve)
34dc7c2f 4936{
ca0bf58d 4937 /* Always allow at least one block of overflow */
5a902f5a 4938 int64_t overflow = MAX(SPA_MAXBLOCKSIZE,
ca0bf58d 4939 arc_c >> zfs_arc_overflow_shift);
34dc7c2f 4940
37fb3e43
PD
4941 /*
4942 * We just compare the lower bound here for performance reasons. Our
4943 * primary goals are to make sure that the arc never grows without
4944 * bound, and that it can reach its maximum size. This check
4945 * accomplishes both goals. The maximum amount we could run over by is
4946 * 2 * aggsum_borrow_multiplier * NUM_CPUS * the average size of a block
4947 * in the ARC. In practice, that's in the tens of MB, which is low
4948 * enough to be safe.
4949 */
f7de776d
AM
4950 int64_t over = aggsum_lower_bound(&arc_sums.arcstat_size) -
4951 arc_c - overflow / 2;
6b88b4b5
AM
4952 if (!use_reserve)
4953 overflow /= 2;
f7de776d
AM
4954 return (over < 0 ? ARC_OVF_NONE :
4955 over < overflow ? ARC_OVF_SOME : ARC_OVF_SEVERE);
34dc7c2f
BB
4956}
4957
a6255b7f 4958static abd_t *
dd66857d 4959arc_get_data_abd(arc_buf_hdr_t *hdr, uint64_t size, const void *tag,
6b88b4b5 4960 int alloc_flags)
a6255b7f
DQ
4961{
4962 arc_buf_contents_t type = arc_buf_type(hdr);
4963
6b88b4b5 4964 arc_get_data_impl(hdr, size, tag, alloc_flags);
ed2f7ba0
AM
4965 if (alloc_flags & ARC_HDR_ALLOC_LINEAR)
4966 return (abd_alloc_linear(size, type == ARC_BUFC_METADATA));
4967 else
4968 return (abd_alloc(size, type == ARC_BUFC_METADATA));
a6255b7f
DQ
4969}
4970
4971static void *
dd66857d 4972arc_get_data_buf(arc_buf_hdr_t *hdr, uint64_t size, const void *tag)
a6255b7f
DQ
4973{
4974 arc_buf_contents_t type = arc_buf_type(hdr);
4975
a8d83e2a 4976 arc_get_data_impl(hdr, size, tag, 0);
a6255b7f
DQ
4977 if (type == ARC_BUFC_METADATA) {
4978 return (zio_buf_alloc(size));
4979 } else {
4980 ASSERT(type == ARC_BUFC_DATA);
4981 return (zio_data_buf_alloc(size));
4982 }
4983}
4984
3442c2a0
MA
4985/*
4986 * Wait for the specified amount of data (in bytes) to be evicted from the
4987 * ARC, and for there to be sufficient free memory in the system. Waiting for
4988 * eviction ensures that the memory used by the ARC decreases. Waiting for
4989 * free memory ensures that the system won't run out of free pages, regardless
4990 * of ARC behavior and settings. See arc_lowmem_init().
4991 */
4992void
6b88b4b5 4993arc_wait_for_eviction(uint64_t amount, boolean_t use_reserve)
3442c2a0 4994{
6b88b4b5 4995 switch (arc_is_overflowing(use_reserve)) {
f7de776d
AM
4996 case ARC_OVF_NONE:
4997 return;
4998 case ARC_OVF_SOME:
4999 /*
5000 * This is a bit racy without taking arc_evict_lock, but the
5001 * worst that can happen is we either call zthr_wakeup() extra
5002 * time due to race with other thread here, or the set flag
5003 * get cleared by arc_evict_cb(), which is unlikely due to
5004 * big hysteresis, but also not important since at this level
5005 * of overflow the eviction is purely advisory. Same time
5006 * taking the global lock here every time without waiting for
5007 * the actual eviction creates a significant lock contention.
5008 */
5009 if (!arc_evict_needed) {
5010 arc_evict_needed = B_TRUE;
5011 zthr_wakeup(arc_evict_zthr);
5012 }
5013 return;
5014 case ARC_OVF_SEVERE:
5015 default:
5016 {
5017 arc_evict_waiter_t aw;
5018 list_link_init(&aw.aew_node);
5019 cv_init(&aw.aew_cv, NULL, CV_DEFAULT, NULL);
3442c2a0 5020
f7de776d
AM
5021 uint64_t last_count = 0;
5022 mutex_enter(&arc_evict_lock);
5023 if (!list_is_empty(&arc_evict_waiters)) {
5024 arc_evict_waiter_t *last =
5025 list_tail(&arc_evict_waiters);
5026 last_count = last->aew_count;
5027 } else if (!arc_evict_needed) {
5028 arc_evict_needed = B_TRUE;
5029 zthr_wakeup(arc_evict_zthr);
5030 }
5031 /*
5032 * Note, the last waiter's count may be less than
5033 * arc_evict_count if we are low on memory in which
5034 * case arc_evict_state_impl() may have deferred
5035 * wakeups (but still incremented arc_evict_count).
5036 */
5037 aw.aew_count = MAX(last_count, arc_evict_count) + amount;
3442c2a0 5038
f7de776d 5039 list_insert_tail(&arc_evict_waiters, &aw);
3442c2a0 5040
f7de776d 5041 arc_set_need_free();
3442c2a0 5042
f7de776d
AM
5043 DTRACE_PROBE3(arc__wait__for__eviction,
5044 uint64_t, amount,
5045 uint64_t, arc_evict_count,
5046 uint64_t, aw.aew_count);
3442c2a0 5047
f7de776d
AM
5048 /*
5049 * We will be woken up either when arc_evict_count reaches
5050 * aew_count, or when the ARC is no longer overflowing and
5051 * eviction completes.
5052 * In case of "false" wakeup, we will still be on the list.
5053 */
5054 do {
3442c2a0 5055 cv_wait(&aw.aew_cv, &arc_evict_lock);
f7de776d
AM
5056 } while (list_link_active(&aw.aew_node));
5057 mutex_exit(&arc_evict_lock);
3442c2a0 5058
f7de776d
AM
5059 cv_destroy(&aw.aew_cv);
5060 }
3442c2a0 5061 }
3442c2a0
MA
5062}
5063
34dc7c2f 5064/*
d3c2ae1c
GW
5065 * Allocate a block and return it to the caller. If we are hitting the
5066 * hard limit for the cache size, we must sleep, waiting for the eviction
5067 * thread to catch up. If we're past the target size but below the hard
5068 * limit, we'll only signal the reclaim thread and continue on.
34dc7c2f 5069 */
a6255b7f 5070static void
dd66857d 5071arc_get_data_impl(arc_buf_hdr_t *hdr, uint64_t size, const void *tag,
6b88b4b5 5072 int alloc_flags)
34dc7c2f 5073{
a8d83e2a 5074 arc_adapt(size);
34dc7c2f
BB
5075
5076 /*
3442c2a0
MA
5077 * If arc_size is currently overflowing, we must be adding data
5078 * faster than we are evicting. To ensure we don't compound the
ca0bf58d 5079 * problem by adding more data and forcing arc_size to grow even
3442c2a0
MA
5080 * further past it's target size, we wait for the eviction thread to
5081 * make some progress. We also wait for there to be sufficient free
5082 * memory in the system, as measured by arc_free_memory().
5083 *
5084 * Specifically, we wait for zfs_arc_eviction_pct percent of the
5085 * requested size to be evicted. This should be more than 100%, to
5086 * ensure that that progress is also made towards getting arc_size
5087 * under arc_c. See the comment above zfs_arc_eviction_pct.
34dc7c2f 5088 */
6b88b4b5
AM
5089 arc_wait_for_eviction(size * zfs_arc_eviction_pct / 100,
5090 alloc_flags & ARC_HDR_USE_RESERVE);
ab26409d 5091
a8d83e2a 5092 arc_buf_contents_t type = arc_buf_type(hdr);
da8ccd0e 5093 if (type == ARC_BUFC_METADATA) {
ca0bf58d
PS
5094 arc_space_consume(size, ARC_SPACE_META);
5095 } else {
ca0bf58d 5096 arc_space_consume(size, ARC_SPACE_DATA);
da8ccd0e
PS
5097 }
5098
34dc7c2f
BB
5099 /*
5100 * Update the state size. Note that ghost states have a
5101 * "ghost size" and so don't need to be updated.
5102 */
a8d83e2a 5103 arc_state_t *state = hdr->b_l1hdr.b_state;
d3c2ae1c 5104 if (!GHOST_STATE(state)) {
34dc7c2f 5105
a8d83e2a
AM
5106 (void) zfs_refcount_add_many(&state->arcs_size[type], size,
5107 tag);
ca0bf58d
PS
5108
5109 /*
5110 * If this is reached via arc_read, the link is
5111 * protected by the hash lock. If reached via
5112 * arc_buf_alloc, the header should not be accessed by
5113 * any other thread. And, if reached via arc_read_done,
5114 * the hash lock will protect it if it's found in the
5115 * hash table; otherwise no other thread should be
5116 * trying to [add|remove]_reference it.
5117 */
5118 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
424fd7c3
TS
5119 ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5120 (void) zfs_refcount_add_many(&state->arcs_esize[type],
d3c2ae1c 5121 size, tag);
34dc7c2f 5122 }
34dc7c2f 5123 }
a6255b7f
DQ
5124}
5125
5126static void
dd66857d
AZ
5127arc_free_data_abd(arc_buf_hdr_t *hdr, abd_t *abd, uint64_t size,
5128 const void *tag)
a6255b7f
DQ
5129{
5130 arc_free_data_impl(hdr, size, tag);
5131 abd_free(abd);
5132}
5133
5134static void
dd66857d 5135arc_free_data_buf(arc_buf_hdr_t *hdr, void *buf, uint64_t size, const void *tag)
a6255b7f
DQ
5136{
5137 arc_buf_contents_t type = arc_buf_type(hdr);
5138
5139 arc_free_data_impl(hdr, size, tag);
5140 if (type == ARC_BUFC_METADATA) {
5141 zio_buf_free(buf, size);
5142 } else {
5143 ASSERT(type == ARC_BUFC_DATA);
5144 zio_data_buf_free(buf, size);
5145 }
d3c2ae1c
GW
5146}
5147
5148/*
5149 * Free the arc data buffer.
5150 */
5151static void
dd66857d 5152arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, const void *tag)
d3c2ae1c
GW
5153{
5154 arc_state_t *state = hdr->b_l1hdr.b_state;
5155 arc_buf_contents_t type = arc_buf_type(hdr);
5156
5157 /* protected by hash lock, if in the hash table */
5158 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
424fd7c3 5159 ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
d3c2ae1c
GW
5160 ASSERT(state != arc_anon && state != arc_l2c_only);
5161
424fd7c3 5162 (void) zfs_refcount_remove_many(&state->arcs_esize[type],
d3c2ae1c
GW
5163 size, tag);
5164 }
a8d83e2a 5165 (void) zfs_refcount_remove_many(&state->arcs_size[type], size, tag);
d3c2ae1c
GW
5166
5167 VERIFY3U(hdr->b_type, ==, type);
5168 if (type == ARC_BUFC_METADATA) {
d3c2ae1c
GW
5169 arc_space_return(size, ARC_SPACE_META);
5170 } else {
5171 ASSERT(type == ARC_BUFC_DATA);
d3c2ae1c
GW
5172 arc_space_return(size, ARC_SPACE_DATA);
5173 }
34dc7c2f
BB
5174}
5175
5176/*
5177 * This routine is called whenever a buffer is accessed.
34dc7c2f
BB
5178 */
5179static void
c935fe2e 5180arc_access(arc_buf_hdr_t *hdr, arc_flags_t arc_flags, boolean_t hit)
34dc7c2f 5181{
c935fe2e 5182 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
b9541d6b 5183 ASSERT(HDR_HAS_L1HDR(hdr));
34dc7c2f 5184
c935fe2e
AM
5185 /*
5186 * Update buffer prefetch status.
5187 */
5188 boolean_t was_prefetch = HDR_PREFETCH(hdr);
5189 boolean_t now_prefetch = arc_flags & ARC_FLAG_PREFETCH;
5190 if (was_prefetch != now_prefetch) {
5191 if (was_prefetch) {
5192 ARCSTAT_CONDSTAT(hit, demand_hit, demand_iohit,
5193 HDR_PRESCIENT_PREFETCH(hdr), prescient, predictive,
5194 prefetch);
5195 }
5196 if (HDR_HAS_L2HDR(hdr))
5197 l2arc_hdr_arcstats_decrement_state(hdr);
5198 if (was_prefetch) {
5199 arc_hdr_clear_flags(hdr,
5200 ARC_FLAG_PREFETCH | ARC_FLAG_PRESCIENT_PREFETCH);
5201 } else {
5202 arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5203 }
5204 if (HDR_HAS_L2HDR(hdr))
5205 l2arc_hdr_arcstats_increment_state(hdr);
5206 }
5207 if (now_prefetch) {
5208 if (arc_flags & ARC_FLAG_PRESCIENT_PREFETCH) {
5209 arc_hdr_set_flags(hdr, ARC_FLAG_PRESCIENT_PREFETCH);
5210 ARCSTAT_BUMP(arcstat_prescient_prefetch);
5211 } else {
5212 ARCSTAT_BUMP(arcstat_predictive_prefetch);
5213 }
5214 }
5215 if (arc_flags & ARC_FLAG_L2CACHE)
5216 arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5217
5218 clock_t now = ddi_get_lbolt();
b9541d6b 5219 if (hdr->b_l1hdr.b_state == arc_anon) {
ed2f7ba0 5220 arc_state_t *new_state;
34dc7c2f 5221 /*
ed2f7ba0
AM
5222 * This buffer is not in the cache, and does not appear in
5223 * our "ghost" lists. Add it to the MRU or uncached state.
34dc7c2f 5224 */
b9541d6b 5225 ASSERT0(hdr->b_l1hdr.b_arc_access);
c935fe2e 5226 hdr->b_l1hdr.b_arc_access = now;
ed2f7ba0
AM
5227 if (HDR_UNCACHED(hdr)) {
5228 new_state = arc_uncached;
5229 DTRACE_PROBE1(new_state__uncached, arc_buf_hdr_t *,
5230 hdr);
5231 } else {
5232 new_state = arc_mru;
5233 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
5234 }
5235 arc_change_state(new_state, hdr);
b9541d6b 5236 } else if (hdr->b_l1hdr.b_state == arc_mru) {
c935fe2e
AM
5237 /*
5238 * This buffer has been accessed once recently and either
5239 * its read is still in progress or it is in the cache.
5240 */
5241 if (HDR_IO_IN_PROGRESS(hdr)) {
5242 hdr->b_l1hdr.b_arc_access = now;
5243 return;
5244 }
5245 hdr->b_l1hdr.b_mru_hits++;
5246 ARCSTAT_BUMP(arcstat_mru_hits);
428870ff 5247
34dc7c2f 5248 /*
c935fe2e
AM
5249 * If the previous access was a prefetch, then it already
5250 * handled possible promotion, so nothing more to do for now.
34dc7c2f 5251 */
c935fe2e 5252 if (was_prefetch) {
b9541d6b 5253 hdr->b_l1hdr.b_arc_access = now;
34dc7c2f
BB
5254 return;
5255 }
5256
5257 /*
c935fe2e
AM
5258 * If more than ARC_MINTIME have passed from the previous
5259 * hit, promote the buffer to the MFU state.
34dc7c2f 5260 */
b9541d6b
CW
5261 if (ddi_time_after(now, hdr->b_l1hdr.b_arc_access +
5262 ARC_MINTIME)) {
b9541d6b 5263 hdr->b_l1hdr.b_arc_access = now;
2a432414 5264 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
c935fe2e 5265 arc_change_state(arc_mfu, hdr);
34dc7c2f 5266 }
b9541d6b 5267 } else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
34dc7c2f
BB
5268 arc_state_t *new_state;
5269 /*
c935fe2e
AM
5270 * This buffer has been accessed once recently, but was
5271 * evicted from the cache. Would we have bigger MRU, it
5272 * would be an MRU hit, so handle it the same way, except
5273 * we don't need to check the previous access time.
34dc7c2f 5274 */
c935fe2e
AM
5275 hdr->b_l1hdr.b_mru_ghost_hits++;
5276 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
5277 hdr->b_l1hdr.b_arc_access = now;
a8d83e2a
AM
5278 wmsum_add(&arc_mru_ghost->arcs_hits[arc_buf_type(hdr)],
5279 arc_hdr_size(hdr));
c935fe2e 5280 if (was_prefetch) {
34dc7c2f 5281 new_state = arc_mru;
2a432414 5282 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
34dc7c2f
BB
5283 } else {
5284 new_state = arc_mfu;
2a432414 5285 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
34dc7c2f 5286 }
c935fe2e 5287 arc_change_state(new_state, hdr);
b9541d6b 5288 } else if (hdr->b_l1hdr.b_state == arc_mfu) {
34dc7c2f 5289 /*
c935fe2e
AM
5290 * This buffer has been accessed more than once and either
5291 * still in the cache or being restored from one of ghosts.
34dc7c2f 5292 */
c935fe2e
AM
5293 if (!HDR_IO_IN_PROGRESS(hdr)) {
5294 hdr->b_l1hdr.b_mfu_hits++;
5295 ARCSTAT_BUMP(arcstat_mfu_hits);
5296 }
5297 hdr->b_l1hdr.b_arc_access = now;
b9541d6b 5298 } else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
34dc7c2f 5299 /*
c935fe2e
AM
5300 * This buffer has been accessed more than once recently, but
5301 * has been evicted from the cache. Would we have bigger MFU
5302 * it would stay in cache, so move it back to MFU state.
34dc7c2f 5303 */
cfe8e960 5304 hdr->b_l1hdr.b_mfu_ghost_hits++;
34dc7c2f 5305 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
c935fe2e 5306 hdr->b_l1hdr.b_arc_access = now;
a8d83e2a
AM
5307 wmsum_add(&arc_mfu_ghost->arcs_hits[arc_buf_type(hdr)],
5308 arc_hdr_size(hdr));
c935fe2e
AM
5309 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5310 arc_change_state(arc_mfu, hdr);
ed2f7ba0
AM
5311 } else if (hdr->b_l1hdr.b_state == arc_uncached) {
5312 /*
5313 * This buffer is uncacheable, but we got a hit. Probably
5314 * a demand read after prefetch. Nothing more to do here.
5315 */
5316 if (!HDR_IO_IN_PROGRESS(hdr))
5317 ARCSTAT_BUMP(arcstat_uncached_hits);
5318 hdr->b_l1hdr.b_arc_access = now;
b9541d6b 5319 } else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
34dc7c2f 5320 /*
c935fe2e
AM
5321 * This buffer is on the 2nd Level ARC and was not accessed
5322 * for a long time, so treat it as new and put into MRU.
34dc7c2f 5323 */
c935fe2e
AM
5324 hdr->b_l1hdr.b_arc_access = now;
5325 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
5326 arc_change_state(arc_mru, hdr);
34dc7c2f 5327 } else {
b9541d6b
CW
5328 cmn_err(CE_PANIC, "invalid arc state 0x%p",
5329 hdr->b_l1hdr.b_state);
34dc7c2f
BB
5330 }
5331}
5332
0873bb63
BB
5333/*
5334 * This routine is called by dbuf_hold() to update the arc_access() state
5335 * which otherwise would be skipped for entries in the dbuf cache.
5336 */
5337void
5338arc_buf_access(arc_buf_t *buf)
5339{
0873bb63
BB
5340 arc_buf_hdr_t *hdr = buf->b_hdr;
5341
5342 /*
5343 * Avoid taking the hash_lock when possible as an optimization.
5344 * The header must be checked again under the hash_lock in order
5345 * to handle the case where it is concurrently being released.
5346 */
289f7e6a 5347 if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr))
0873bb63 5348 return;
0873bb63
BB
5349
5350 kmutex_t *hash_lock = HDR_LOCK(hdr);
5351 mutex_enter(hash_lock);
5352
5353 if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr)) {
5354 mutex_exit(hash_lock);
0873bb63
BB
5355 ARCSTAT_BUMP(arcstat_access_skip);
5356 return;
5357 }
5358
0873bb63 5359 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
ed2f7ba0
AM
5360 hdr->b_l1hdr.b_state == arc_mfu ||
5361 hdr->b_l1hdr.b_state == arc_uncached);
0873bb63
BB
5362
5363 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
c935fe2e 5364 arc_access(hdr, 0, B_TRUE);
0873bb63
BB
5365 mutex_exit(hash_lock);
5366
5367 ARCSTAT_BUMP(arcstat_hits);
c935fe2e
AM
5368 ARCSTAT_CONDSTAT(B_TRUE /* demand */, demand, prefetch,
5369 !HDR_ISTYPE_METADATA(hdr), data, metadata, hits);
0873bb63
BB
5370}
5371
b5256303 5372/* a generic arc_read_done_func_t which you can use */
34dc7c2f 5373void
d4a72f23
TC
5374arc_bcopy_func(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
5375 arc_buf_t *buf, void *arg)
34dc7c2f 5376{
14e4e3cb
AZ
5377 (void) zio, (void) zb, (void) bp;
5378
d4a72f23
TC
5379 if (buf == NULL)
5380 return;
5381
861166b0 5382 memcpy(arg, buf->b_data, arc_buf_size(buf));
d3c2ae1c 5383 arc_buf_destroy(buf, arg);
34dc7c2f
BB
5384}
5385
b5256303 5386/* a generic arc_read_done_func_t */
34dc7c2f 5387void
d4a72f23
TC
5388arc_getbuf_func(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
5389 arc_buf_t *buf, void *arg)
34dc7c2f 5390{
14e4e3cb 5391 (void) zb, (void) bp;
34dc7c2f 5392 arc_buf_t **bufp = arg;
d4a72f23
TC
5393
5394 if (buf == NULL) {
c3bd3fb4 5395 ASSERT(zio == NULL || zio->io_error != 0);
34dc7c2f
BB
5396 *bufp = NULL;
5397 } else {
c3bd3fb4 5398 ASSERT(zio == NULL || zio->io_error == 0);
34dc7c2f 5399 *bufp = buf;
c3bd3fb4 5400 ASSERT(buf->b_data != NULL);
34dc7c2f
BB
5401 }
5402}
5403
d3c2ae1c
GW
5404static void
5405arc_hdr_verify(arc_buf_hdr_t *hdr, blkptr_t *bp)
5406{
5407 if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
5408 ASSERT3U(HDR_GET_PSIZE(hdr), ==, 0);
b5256303 5409 ASSERT3U(arc_hdr_get_compress(hdr), ==, ZIO_COMPRESS_OFF);
d3c2ae1c
GW
5410 } else {
5411 if (HDR_COMPRESSION_ENABLED(hdr)) {
b5256303 5412 ASSERT3U(arc_hdr_get_compress(hdr), ==,
d3c2ae1c
GW
5413 BP_GET_COMPRESS(bp));
5414 }
5415 ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
5416 ASSERT3U(HDR_GET_PSIZE(hdr), ==, BP_GET_PSIZE(bp));
b5256303 5417 ASSERT3U(!!HDR_PROTECTED(hdr), ==, BP_IS_PROTECTED(bp));
d3c2ae1c
GW
5418 }
5419}
5420
34dc7c2f
BB
5421static void
5422arc_read_done(zio_t *zio)
5423{
b5256303 5424 blkptr_t *bp = zio->io_bp;
d3c2ae1c 5425 arc_buf_hdr_t *hdr = zio->io_private;
9b67f605 5426 kmutex_t *hash_lock = NULL;
524b4217
DK
5427 arc_callback_t *callback_list;
5428 arc_callback_t *acb;
a7004725 5429
34dc7c2f
BB
5430 /*
5431 * The hdr was inserted into hash-table and removed from lists
5432 * prior to starting I/O. We should find this header, since
5433 * it's in the hash table, and it should be legit since it's
5434 * not possible to evict it during the I/O. The only possible
5435 * reason for it not to be found is if we were freed during the
5436 * read.
5437 */
9b67f605 5438 if (HDR_IN_HASH_TABLE(hdr)) {
31df97cd
DB
5439 arc_buf_hdr_t *found;
5440
9b67f605
MA
5441 ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
5442 ASSERT3U(hdr->b_dva.dva_word[0], ==,
5443 BP_IDENTITY(zio->io_bp)->dva_word[0]);
5444 ASSERT3U(hdr->b_dva.dva_word[1], ==,
5445 BP_IDENTITY(zio->io_bp)->dva_word[1]);
5446
31df97cd 5447 found = buf_hash_find(hdr->b_spa, zio->io_bp, &hash_lock);
9b67f605 5448
d3c2ae1c 5449 ASSERT((found == hdr &&
9b67f605
MA
5450 DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
5451 (found == hdr && HDR_L2_READING(hdr)));
d3c2ae1c
GW
5452 ASSERT3P(hash_lock, !=, NULL);
5453 }
5454
b5256303
TC
5455 if (BP_IS_PROTECTED(bp)) {
5456 hdr->b_crypt_hdr.b_ot = BP_GET_TYPE(bp);
5457 hdr->b_crypt_hdr.b_dsobj = zio->io_bookmark.zb_objset;
5458 zio_crypt_decode_params_bp(bp, hdr->b_crypt_hdr.b_salt,
5459 hdr->b_crypt_hdr.b_iv);
5460
df42e20a
RE
5461 if (zio->io_error == 0) {
5462 if (BP_GET_TYPE(bp) == DMU_OT_INTENT_LOG) {
5463 void *tmpbuf;
5464
5465 tmpbuf = abd_borrow_buf_copy(zio->io_abd,
5466 sizeof (zil_chain_t));
5467 zio_crypt_decode_mac_zil(tmpbuf,
5468 hdr->b_crypt_hdr.b_mac);
5469 abd_return_buf(zio->io_abd, tmpbuf,
5470 sizeof (zil_chain_t));
5471 } else {
5472 zio_crypt_decode_mac_bp(bp,
5473 hdr->b_crypt_hdr.b_mac);
5474 }
b5256303
TC
5475 }
5476 }
5477
d4a72f23 5478 if (zio->io_error == 0) {
d3c2ae1c
GW
5479 /* byteswap if necessary */
5480 if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
5481 if (BP_GET_LEVEL(zio->io_bp) > 0) {
5482 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
5483 } else {
5484 hdr->b_l1hdr.b_byteswap =
5485 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
5486 }
5487 } else {
5488 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
5489 }
10b3c7f5
MN
5490 if (!HDR_L2_READING(hdr)) {
5491 hdr->b_complevel = zio->io_prop.zp_complevel;
5492 }
9b67f605 5493 }
34dc7c2f 5494
d3c2ae1c 5495 arc_hdr_clear_flags(hdr, ARC_FLAG_L2_EVICTED);
c6f5e9d9
GA
5496 if (l2arc_noprefetch && HDR_PREFETCH(hdr))
5497 arc_hdr_clear_flags(hdr, ARC_FLAG_L2CACHE);
34dc7c2f 5498
b9541d6b 5499 callback_list = hdr->b_l1hdr.b_acb;
d3c2ae1c 5500 ASSERT3P(callback_list, !=, NULL);
c935fe2e 5501 hdr->b_l1hdr.b_acb = NULL;
428870ff 5502
524b4217
DK
5503 /*
5504 * If a read request has a callback (i.e. acb_done is not NULL), then we
5505 * make a buf containing the data according to the parameters which were
5506 * passed in. The implementation of arc_buf_alloc_impl() ensures that we
5507 * aren't needlessly decompressing the data multiple times.
5508 */
a7004725 5509 int callback_cnt = 0;
2aa34383 5510 for (acb = callback_list; acb != NULL; acb = acb->acb_next) {
c935fe2e
AM
5511
5512 /* We need the last one to call below in original order. */
5513 callback_list = acb;
5514
923d7303 5515 if (!acb->acb_done || acb->acb_nobuf)
2aa34383
DK
5516 continue;
5517
2aa34383 5518 callback_cnt++;
524b4217 5519
d4a72f23
TC
5520 if (zio->io_error != 0)
5521 continue;
5522
b5256303 5523 int error = arc_buf_alloc_impl(hdr, zio->io_spa,
be9a5c35 5524 &acb->acb_zb, acb->acb_private, acb->acb_encrypted,
d4a72f23 5525 acb->acb_compressed, acb->acb_noauth, B_TRUE,
440a3eb9 5526 &acb->acb_buf);
b5256303
TC
5527
5528 /*
440a3eb9 5529 * Assert non-speculative zios didn't fail because an
b5256303
TC
5530 * encryption key wasn't loaded
5531 */
a2c2ed1b 5532 ASSERT((zio->io_flags & ZIO_FLAG_SPECULATIVE) ||
be9a5c35 5533 error != EACCES);
b5256303
TC
5534
5535 /*
5536 * If we failed to decrypt, report an error now (as the zio
5537 * layer would have done if it had done the transforms).
5538 */
5539 if (error == ECKSUM) {
5540 ASSERT(BP_IS_PROTECTED(bp));
5541 error = SET_ERROR(EIO);
b5256303 5542 if ((zio->io_flags & ZIO_FLAG_SPECULATIVE) == 0) {
431083f7
GA
5543 spa_log_error(zio->io_spa, &acb->acb_zb,
5544 &zio->io_bp->blk_birth);
1144586b
TS
5545 (void) zfs_ereport_post(
5546 FM_EREPORT_ZFS_AUTHENTICATION,
4f072827 5547 zio->io_spa, NULL, &acb->acb_zb, zio, 0);
b5256303
TC
5548 }
5549 }
5550
c3bd3fb4
TC
5551 if (error != 0) {
5552 /*
5553 * Decompression or decryption failed. Set
5554 * io_error so that when we call acb_done
5555 * (below), we will indicate that the read
5556 * failed. Note that in the unusual case
5557 * where one callback is compressed and another
5558 * uncompressed, we will mark all of them
5559 * as failed, even though the uncompressed
5560 * one can't actually fail. In this case,
5561 * the hdr will not be anonymous, because
5562 * if there are multiple callbacks, it's
5563 * because multiple threads found the same
5564 * arc buf in the hash table.
5565 */
524b4217 5566 zio->io_error = error;
c3bd3fb4 5567 }
34dc7c2f 5568 }
c3bd3fb4
TC
5569
5570 /*
5571 * If there are multiple callbacks, we must have the hash lock,
5572 * because the only way for multiple threads to find this hdr is
5573 * in the hash table. This ensures that if there are multiple
5574 * callbacks, the hdr is not anonymous. If it were anonymous,
5575 * we couldn't use arc_buf_destroy() in the error case below.
5576 */
5577 ASSERT(callback_cnt < 2 || hash_lock != NULL);
5578
d4a72f23 5579 if (zio->io_error == 0) {
d3c2ae1c
GW
5580 arc_hdr_verify(hdr, zio->io_bp);
5581 } else {
5582 arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
b9541d6b 5583 if (hdr->b_l1hdr.b_state != arc_anon)
c935fe2e 5584 arc_change_state(arc_anon, hdr);
34dc7c2f
BB
5585 if (HDR_IN_HASH_TABLE(hdr))
5586 buf_hash_remove(hdr);
34dc7c2f
BB
5587 }
5588
5589 /*
5590 * Broadcast before we drop the hash_lock to avoid the possibility
5591 * that the hdr (and hence the cv) might be freed before we get to
5592 * the cv_broadcast().
5593 */
b9541d6b 5594 cv_broadcast(&hdr->b_l1hdr.b_cv);
34dc7c2f 5595
ed2f7ba0
AM
5596 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5597 (void) remove_reference(hdr, hdr);
5598
5599 if (hash_lock != NULL)
34dc7c2f 5600 mutex_exit(hash_lock);
34dc7c2f
BB
5601
5602 /* execute each callback and free its structure */
5603 while ((acb = callback_list) != NULL) {
c3bd3fb4
TC
5604 if (acb->acb_done != NULL) {
5605 if (zio->io_error != 0 && acb->acb_buf != NULL) {
5606 /*
5607 * If arc_buf_alloc_impl() fails during
5608 * decompression, the buf will still be
5609 * allocated, and needs to be freed here.
5610 */
5611 arc_buf_destroy(acb->acb_buf,
5612 acb->acb_private);
5613 acb->acb_buf = NULL;
5614 }
d4a72f23
TC
5615 acb->acb_done(zio, &zio->io_bookmark, zio->io_bp,
5616 acb->acb_buf, acb->acb_private);
b5256303 5617 }
34dc7c2f
BB
5618
5619 if (acb->acb_zio_dummy != NULL) {
5620 acb->acb_zio_dummy->io_error = zio->io_error;
5621 zio_nowait(acb->acb_zio_dummy);
5622 }
5623
c935fe2e
AM
5624 callback_list = acb->acb_prev;
5625 if (acb->acb_wait) {
5626 mutex_enter(&acb->acb_wait_lock);
5627 acb->acb_wait_error = zio->io_error;
5628 acb->acb_wait = B_FALSE;
5629 cv_signal(&acb->acb_wait_cv);
5630 mutex_exit(&acb->acb_wait_lock);
5631 /* acb will be freed by the waiting thread. */
5632 } else {
5633 kmem_free(acb, sizeof (arc_callback_t));
5634 }
34dc7c2f 5635 }
34dc7c2f
BB
5636}
5637
5638/*
5c839890 5639 * "Read" the block at the specified DVA (in bp) via the
34dc7c2f
BB
5640 * cache. If the block is found in the cache, invoke the provided
5641 * callback immediately and return. Note that the `zio' parameter
5642 * in the callback will be NULL in this case, since no IO was
5643 * required. If the block is not in the cache pass the read request
5644 * on to the spa with a substitute callback function, so that the
5645 * requested block will be added to the cache.
5646 *
5647 * If a read request arrives for a block that has a read in-progress,
5648 * either wait for the in-progress read to complete (and return the
5649 * results); or, if this is a read with a "done" func, add a record
5650 * to the read to invoke the "done" func when the read completes,
5651 * and return; or just return.
5652 *
5653 * arc_read_done() will invoke all the requested "done" functions
5654 * for readers of this block.
5655 */
5656int
b5256303
TC
5657arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp,
5658 arc_read_done_func_t *done, void *private, zio_priority_t priority,
5659 int zio_flags, arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
34dc7c2f 5660{
9b67f605 5661 arc_buf_hdr_t *hdr = NULL;
9b67f605 5662 kmutex_t *hash_lock = NULL;
34dc7c2f 5663 zio_t *rzio;
3541dc6d 5664 uint64_t guid = spa_load_guid(spa);
b5256303
TC
5665 boolean_t compressed_read = (zio_flags & ZIO_FLAG_RAW_COMPRESS) != 0;
5666 boolean_t encrypted_read = BP_IS_ENCRYPTED(bp) &&
5667 (zio_flags & ZIO_FLAG_RAW_ENCRYPT) != 0;
5668 boolean_t noauth_read = BP_IS_AUTHENTICATED(bp) &&
5669 (zio_flags & ZIO_FLAG_RAW_ENCRYPT) != 0;
0902c457 5670 boolean_t embedded_bp = !!BP_IS_EMBEDDED(bp);
1e4732cb 5671 boolean_t no_buf = *arc_flags & ARC_FLAG_NO_BUF;
87a4dfa5 5672 arc_buf_t *buf = NULL;
1421c891 5673 int rc = 0;
34dc7c2f 5674
0902c457 5675 ASSERT(!embedded_bp ||
9b67f605 5676 BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
30af21b0
PD
5677 ASSERT(!BP_IS_HOLE(bp));
5678 ASSERT(!BP_IS_REDACTED(bp));
9b67f605 5679
1e9231ad
MR
5680 /*
5681 * Normally SPL_FSTRANS will already be set since kernel threads which
5682 * expect to call the DMU interfaces will set it when created. System
5683 * calls are similarly handled by setting/cleaning the bit in the
5684 * registered callback (module/os/.../zfs/zpl_*).
5685 *
5686 * External consumers such as Lustre which call the exported DMU
5687 * interfaces may not have set SPL_FSTRANS. To avoid a deadlock
5688 * on the hash_lock always set and clear the bit.
5689 */
5690 fstrans_cookie_t cookie = spl_fstrans_mark();
34dc7c2f 5691top:
b9ec4a15
BB
5692 /*
5693 * Verify the block pointer contents are reasonable. This should
5694 * always be the case since the blkptr is protected by a checksum.
5695 * However, if there is damage it's desirable to detect this early
5696 * and treat it as a checksum error. This allows an alternate blkptr
5697 * to be tried when one is available (e.g. ditto blocks).
5698 */
3095ca91
MA
5699 if (!zfs_blkptr_verify(spa, bp, (zio_flags & ZIO_FLAG_CONFIG_WRITER) ?
5700 BLK_CONFIG_HELD : BLK_CONFIG_NEEDED, BLK_VERIFY_LOG)) {
b9ec4a15 5701 rc = SET_ERROR(ECKSUM);
87a4dfa5 5702 goto done;
b9ec4a15
BB
5703 }
5704
0902c457 5705 if (!embedded_bp) {
9b67f605
MA
5706 /*
5707 * Embedded BP's have no DVA and require no I/O to "read".
5708 * Create an anonymous arc buf to back it.
5709 */
5710 hdr = buf_hash_find(guid, bp, &hash_lock);
5711 }
5712
b5256303
TC
5713 /*
5714 * Determine if we have an L1 cache hit or a cache miss. For simplicity
e1cfd73f 5715 * we maintain encrypted data separately from compressed / uncompressed
b5256303
TC
5716 * data. If the user is requesting raw encrypted data and we don't have
5717 * that in the header we will read from disk to guarantee that we can
5718 * get it even if the encryption keys aren't loaded.
5719 */
5720 if (hdr != NULL && HDR_HAS_L1HDR(hdr) && (HDR_HAS_RABD(hdr) ||
5721 (hdr->b_l1hdr.b_pabd != NULL && !encrypted_read))) {
c935fe2e 5722 boolean_t is_data = !HDR_ISTYPE_METADATA(hdr);
34dc7c2f
BB
5723
5724 if (HDR_IO_IN_PROGRESS(hdr)) {
1dc32a67
MA
5725 if (*arc_flags & ARC_FLAG_CACHED_ONLY) {
5726 mutex_exit(hash_lock);
5727 ARCSTAT_BUMP(arcstat_cached_only_in_progress);
5728 rc = SET_ERROR(ENOENT);
87a4dfa5 5729 goto done;
1dc32a67
MA
5730 }
5731
c935fe2e 5732 zio_t *head_zio = hdr->b_l1hdr.b_acb->acb_zio_head;
a8b2e306 5733 ASSERT3P(head_zio, !=, NULL);
7f60329a
MA
5734 if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
5735 priority == ZIO_PRIORITY_SYNC_READ) {
5736 /*
a8b2e306
TC
5737 * This is a sync read that needs to wait for
5738 * an in-flight async read. Request that the
5739 * zio have its priority upgraded.
7f60329a 5740 */
a8b2e306
TC
5741 zio_change_priority(head_zio, priority);
5742 DTRACE_PROBE1(arc__async__upgrade__sync,
7f60329a 5743 arc_buf_hdr_t *, hdr);
a8b2e306 5744 ARCSTAT_BUMP(arcstat_async_upgrade_sync);
7f60329a 5745 }
c935fe2e
AM
5746
5747 DTRACE_PROBE1(arc__iohit, arc_buf_hdr_t *, hdr);
5748 arc_access(hdr, *arc_flags, B_FALSE);
7f60329a 5749
91983265
CS
5750 /*
5751 * If there are multiple threads reading the same block
5752 * and that block is not yet in the ARC, then only one
5753 * thread will do the physical I/O and all other
5754 * threads will wait until that I/O completes.
c935fe2e
AM
5755 * Synchronous reads use the acb_wait_cv whereas nowait
5756 * reads register a callback. Both are signalled/called
5757 * in arc_read_done.
91983265 5758 *
c935fe2e
AM
5759 * Errors of the physical I/O may need to be propagated.
5760 * Synchronous read errors are returned here from
5761 * arc_read_done via acb_wait_error. Nowait reads
91983265
CS
5762 * attach the acb_zio_dummy zio to pio and
5763 * arc_read_done propagates the physical I/O's io_error
5764 * to acb_zio_dummy, and thereby to pio.
5765 */
c935fe2e
AM
5766 arc_callback_t *acb = NULL;
5767 if (done || pio || *arc_flags & ARC_FLAG_WAIT) {
34dc7c2f 5768 acb = kmem_zalloc(sizeof (arc_callback_t),
79c76d5b 5769 KM_SLEEP);
34dc7c2f
BB
5770 acb->acb_done = done;
5771 acb->acb_private = private;
a7004725 5772 acb->acb_compressed = compressed_read;
440a3eb9
TC
5773 acb->acb_encrypted = encrypted_read;
5774 acb->acb_noauth = noauth_read;
923d7303 5775 acb->acb_nobuf = no_buf;
c935fe2e
AM
5776 if (*arc_flags & ARC_FLAG_WAIT) {
5777 acb->acb_wait = B_TRUE;
5778 mutex_init(&acb->acb_wait_lock, NULL,
5779 MUTEX_DEFAULT, NULL);
5780 cv_init(&acb->acb_wait_cv, NULL,
5781 CV_DEFAULT, NULL);
5782 }
be9a5c35 5783 acb->acb_zb = *zb;
c935fe2e 5784 if (pio != NULL) {
34dc7c2f 5785 acb->acb_zio_dummy = zio_null(pio,
d164b209 5786 spa, NULL, NULL, NULL, zio_flags);
c935fe2e 5787 }
a8b2e306 5788 acb->acb_zio_head = head_zio;
b9541d6b 5789 acb->acb_next = hdr->b_l1hdr.b_acb;
c935fe2e
AM
5790 if (hdr->b_l1hdr.b_acb)
5791 hdr->b_l1hdr.b_acb->acb_prev = acb;
b9541d6b 5792 hdr->b_l1hdr.b_acb = acb;
34dc7c2f
BB
5793 }
5794 mutex_exit(hash_lock);
c935fe2e
AM
5795
5796 ARCSTAT_BUMP(arcstat_iohits);
5797 ARCSTAT_CONDSTAT(!(*arc_flags & ARC_FLAG_PREFETCH),
5798 demand, prefetch, is_data, data, metadata, iohits);
5799
5800 if (*arc_flags & ARC_FLAG_WAIT) {
5801 mutex_enter(&acb->acb_wait_lock);
5802 while (acb->acb_wait) {
5803 cv_wait(&acb->acb_wait_cv,
5804 &acb->acb_wait_lock);
5805 }
5806 rc = acb->acb_wait_error;
5807 mutex_exit(&acb->acb_wait_lock);
5808 mutex_destroy(&acb->acb_wait_lock);
5809 cv_destroy(&acb->acb_wait_cv);
5810 kmem_free(acb, sizeof (arc_callback_t));
5811 }
1421c891 5812 goto out;
34dc7c2f
BB
5813 }
5814
b9541d6b 5815 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
ed2f7ba0
AM
5816 hdr->b_l1hdr.b_state == arc_mfu ||
5817 hdr->b_l1hdr.b_state == arc_uncached);
34dc7c2f 5818
c935fe2e
AM
5819 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
5820 arc_access(hdr, *arc_flags, B_TRUE);
d4a72f23 5821
c935fe2e 5822 if (done && !no_buf) {
0902c457 5823 ASSERT(!embedded_bp || !BP_IS_HOLE(bp));
d3c2ae1c 5824
524b4217 5825 /* Get a buf with the desired data in it. */
be9a5c35
TC
5826 rc = arc_buf_alloc_impl(hdr, spa, zb, private,
5827 encrypted_read, compressed_read, noauth_read,
5828 B_TRUE, &buf);
a2c2ed1b
TC
5829 if (rc == ECKSUM) {
5830 /*
5831 * Convert authentication and decryption errors
be9a5c35
TC
5832 * to EIO (and generate an ereport if needed)
5833 * before leaving the ARC.
a2c2ed1b
TC
5834 */
5835 rc = SET_ERROR(EIO);
be9a5c35 5836 if ((zio_flags & ZIO_FLAG_SPECULATIVE) == 0) {
431083f7 5837 spa_log_error(spa, zb, &hdr->b_birth);
1144586b 5838 (void) zfs_ereport_post(
be9a5c35 5839 FM_EREPORT_ZFS_AUTHENTICATION,
4f072827 5840 spa, NULL, zb, NULL, 0);
be9a5c35 5841 }
a2c2ed1b 5842 }
d4a72f23 5843 if (rc != 0) {
2c24b5b1 5844 arc_buf_destroy_impl(buf);
d4a72f23 5845 buf = NULL;
ed2f7ba0 5846 (void) remove_reference(hdr, private);
d4a72f23
TC
5847 }
5848
a2c2ed1b
TC
5849 /* assert any errors weren't due to unloaded keys */
5850 ASSERT((zio_flags & ZIO_FLAG_SPECULATIVE) ||
be9a5c35 5851 rc != EACCES);
34dc7c2f 5852 }
34dc7c2f
BB
5853 mutex_exit(hash_lock);
5854 ARCSTAT_BUMP(arcstat_hits);
c935fe2e
AM
5855 ARCSTAT_CONDSTAT(!(*arc_flags & ARC_FLAG_PREFETCH),
5856 demand, prefetch, is_data, data, metadata, hits);
5857 *arc_flags |= ARC_FLAG_CACHED;
87a4dfa5 5858 goto done;
34dc7c2f 5859 } else {
d3c2ae1c
GW
5860 uint64_t lsize = BP_GET_LSIZE(bp);
5861 uint64_t psize = BP_GET_PSIZE(bp);
9b67f605 5862 arc_callback_t *acb;
b128c09f 5863 vdev_t *vd = NULL;
a117a6d6 5864 uint64_t addr = 0;
d164b209 5865 boolean_t devw = B_FALSE;
d3c2ae1c 5866 uint64_t size;
440a3eb9 5867 abd_t *hdr_abd;
e111c802 5868 int alloc_flags = encrypted_read ? ARC_HDR_ALLOC_RDATA : 0;
a8d83e2a 5869 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
34dc7c2f 5870
1dc32a67 5871 if (*arc_flags & ARC_FLAG_CACHED_ONLY) {
1dc32a67
MA
5872 if (hash_lock != NULL)
5873 mutex_exit(hash_lock);
87a4dfa5
AM
5874 rc = SET_ERROR(ENOENT);
5875 goto done;
1dc32a67
MA
5876 }
5877
34dc7c2f 5878 if (hdr == NULL) {
0902c457
TC
5879 /*
5880 * This block is not in the cache or it has
5881 * embedded data.
5882 */
9b67f605 5883 arc_buf_hdr_t *exists = NULL;
d3c2ae1c 5884 hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
6b88b4b5 5885 BP_IS_PROTECTED(bp), BP_GET_COMPRESS(bp), 0, type);
d3c2ae1c 5886
0902c457 5887 if (!embedded_bp) {
9b67f605
MA
5888 hdr->b_dva = *BP_IDENTITY(bp);
5889 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
9b67f605
MA
5890 exists = buf_hash_insert(hdr, &hash_lock);
5891 }
5892 if (exists != NULL) {
34dc7c2f
BB
5893 /* somebody beat us to the hash insert */
5894 mutex_exit(hash_lock);
428870ff 5895 buf_discard_identity(hdr);
d3c2ae1c 5896 arc_hdr_destroy(hdr);
34dc7c2f
BB
5897 goto top; /* restart the IO request */
5898 }
34dc7c2f 5899 } else {
b9541d6b 5900 /*
b5256303
TC
5901 * This block is in the ghost cache or encrypted data
5902 * was requested and we didn't have it. If it was
5903 * L2-only (and thus didn't have an L1 hdr),
5904 * we realloc the header to add an L1 hdr.
b9541d6b
CW
5905 */
5906 if (!HDR_HAS_L1HDR(hdr)) {
5907 hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
5908 hdr_full_cache);
5909 }
5910
b5256303
TC
5911 if (GHOST_STATE(hdr->b_l1hdr.b_state)) {
5912 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
5913 ASSERT(!HDR_HAS_RABD(hdr));
5914 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
424fd7c3
TS
5915 ASSERT0(zfs_refcount_count(
5916 &hdr->b_l1hdr.b_refcnt));
b5256303 5917 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
bacf366f 5918#ifdef ZFS_DEBUG
b5256303 5919 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
bacf366f 5920#endif
b5256303
TC
5921 } else if (HDR_IO_IN_PROGRESS(hdr)) {
5922 /*
5923 * If this header already had an IO in progress
5924 * and we are performing another IO to fetch
5925 * encrypted data we must wait until the first
5926 * IO completes so as not to confuse
5927 * arc_read_done(). This should be very rare
5928 * and so the performance impact shouldn't
5929 * matter.
5930 */
5931 cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
5932 mutex_exit(hash_lock);
5933 goto top;
5934 }
d3c2ae1c 5935 }
ed2f7ba0
AM
5936 if (*arc_flags & ARC_FLAG_UNCACHED) {
5937 arc_hdr_set_flags(hdr, ARC_FLAG_UNCACHED);
5938 if (!encrypted_read)
5939 alloc_flags |= ARC_HDR_ALLOC_LINEAR;
5940 }
d3c2ae1c 5941
c935fe2e
AM
5942 /*
5943 * Take additional reference for IO_IN_PROGRESS. It stops
5944 * arc_access() from putting this header without any buffers
5945 * and so other references but obviously nonevictable onto
5946 * the evictable list of MRU or MFU state.
5947 */
5948 add_reference(hdr, hdr);
5949 if (!embedded_bp)
5950 arc_access(hdr, *arc_flags, B_FALSE);
5951 arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6b88b4b5 5952 arc_hdr_alloc_abd(hdr, alloc_flags);
b5256303
TC
5953 if (encrypted_read) {
5954 ASSERT(HDR_HAS_RABD(hdr));
5955 size = HDR_GET_PSIZE(hdr);
5956 hdr_abd = hdr->b_crypt_hdr.b_rabd;
d3c2ae1c 5957 zio_flags |= ZIO_FLAG_RAW;
b5256303
TC
5958 } else {
5959 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
5960 size = arc_hdr_size(hdr);
5961 hdr_abd = hdr->b_l1hdr.b_pabd;
5962
5963 if (arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF) {
5964 zio_flags |= ZIO_FLAG_RAW_COMPRESS;
5965 }
5966
5967 /*
5968 * For authenticated bp's, we do not ask the ZIO layer
5969 * to authenticate them since this will cause the entire
5970 * IO to fail if the key isn't loaded. Instead, we
5971 * defer authentication until arc_buf_fill(), which will
5972 * verify the data when the key is available.
5973 */
5974 if (BP_IS_AUTHENTICATED(bp))
5975 zio_flags |= ZIO_FLAG_RAW_ENCRYPT;
34dc7c2f
BB
5976 }
5977
b5256303
TC
5978 if (BP_IS_AUTHENTICATED(bp))
5979 arc_hdr_set_flags(hdr, ARC_FLAG_NOAUTH);
d3c2ae1c
GW
5980 if (BP_GET_LEVEL(bp) > 0)
5981 arc_hdr_set_flags(hdr, ARC_FLAG_INDIRECT);
b9541d6b 5982 ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
428870ff 5983
79c76d5b 5984 acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
34dc7c2f
BB
5985 acb->acb_done = done;
5986 acb->acb_private = private;
2aa34383 5987 acb->acb_compressed = compressed_read;
b5256303
TC
5988 acb->acb_encrypted = encrypted_read;
5989 acb->acb_noauth = noauth_read;
be9a5c35 5990 acb->acb_zb = *zb;
34dc7c2f 5991
d3c2ae1c 5992 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
b9541d6b 5993 hdr->b_l1hdr.b_acb = acb;
34dc7c2f 5994
b9541d6b
CW
5995 if (HDR_HAS_L2HDR(hdr) &&
5996 (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
5997 devw = hdr->b_l2hdr.b_dev->l2ad_writing;
5998 addr = hdr->b_l2hdr.b_daddr;
b128c09f 5999 /*
a1d477c2 6000 * Lock out L2ARC device removal.
b128c09f
BB
6001 */
6002 if (vdev_is_dead(vd) ||
6003 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
6004 vd = NULL;
6005 }
6006
a8b2e306
TC
6007 /*
6008 * We count both async reads and scrub IOs as asynchronous so
6009 * that both can be upgraded in the event of a cache hit while
6010 * the read IO is still in-flight.
6011 */
6012 if (priority == ZIO_PRIORITY_ASYNC_READ ||
6013 priority == ZIO_PRIORITY_SCRUB)
d3c2ae1c
GW
6014 arc_hdr_set_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
6015 else
6016 arc_hdr_clear_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
6017
e49f1e20 6018 /*
0902c457
TC
6019 * At this point, we have a level 1 cache miss or a blkptr
6020 * with embedded data. Try again in L2ARC if possible.
e49f1e20 6021 */
d3c2ae1c
GW
6022 ASSERT3U(HDR_GET_LSIZE(hdr), ==, lsize);
6023
0902c457
TC
6024 /*
6025 * Skip ARC stat bump for block pointers with embedded
6026 * data. The data are read from the blkptr itself via
6027 * decode_embedded_bp_compressed().
6028 */
6029 if (!embedded_bp) {
6030 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr,
6031 blkptr_t *, bp, uint64_t, lsize,
6032 zbookmark_phys_t *, zb);
6033 ARCSTAT_BUMP(arcstat_misses);
c935fe2e 6034 ARCSTAT_CONDSTAT(!(*arc_flags & ARC_FLAG_PREFETCH),
0902c457
TC
6035 demand, prefetch, !HDR_ISTYPE_METADATA(hdr), data,
6036 metadata, misses);
64e0fe14 6037 zfs_racct_read(size, 1);
0902c457 6038 }
34dc7c2f 6039
666aa69f
AM
6040 /* Check if the spa even has l2 configured */
6041 const boolean_t spa_has_l2 = l2arc_ndev != 0 &&
6042 spa->spa_l2cache.sav_count > 0;
6043
6044 if (vd != NULL && spa_has_l2 && !(l2arc_norw && devw)) {
34dc7c2f
BB
6045 /*
6046 * Read from the L2ARC if the following are true:
b128c09f
BB
6047 * 1. The L2ARC vdev was previously cached.
6048 * 2. This buffer still has L2ARC metadata.
6049 * 3. This buffer isn't currently writing to the L2ARC.
6050 * 4. The L2ARC entry wasn't evicted, which may
6051 * also have invalidated the vdev.
08532162 6052 * 5. This isn't prefetch or l2arc_noprefetch is 0.
34dc7c2f 6053 */
b9541d6b 6054 if (HDR_HAS_L2HDR(hdr) &&
d164b209 6055 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
c935fe2e
AM
6056 !(l2arc_noprefetch &&
6057 (*arc_flags & ARC_FLAG_PREFETCH))) {
34dc7c2f 6058 l2arc_read_callback_t *cb;
82710e99
GDN
6059 abd_t *abd;
6060 uint64_t asize;
34dc7c2f
BB
6061
6062 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
6063 ARCSTAT_BUMP(arcstat_l2_hits);
cfe8e960 6064 hdr->b_l2hdr.b_hits++;
34dc7c2f 6065
34dc7c2f 6066 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
79c76d5b 6067 KM_SLEEP);
d3c2ae1c 6068 cb->l2rcb_hdr = hdr;
34dc7c2f
BB
6069 cb->l2rcb_bp = *bp;
6070 cb->l2rcb_zb = *zb;
b128c09f 6071 cb->l2rcb_flags = zio_flags;
34dc7c2f 6072
fc34dfba
AJ
6073 /*
6074 * When Compressed ARC is disabled, but the
6075 * L2ARC block is compressed, arc_hdr_size()
6076 * will have returned LSIZE rather than PSIZE.
6077 */
6078 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
6079 !HDR_COMPRESSION_ENABLED(hdr) &&
6080 HDR_GET_PSIZE(hdr) != 0) {
6081 size = HDR_GET_PSIZE(hdr);
6082 }
6083
82710e99
GDN
6084 asize = vdev_psize_to_asize(vd, size);
6085 if (asize != size) {
6086 abd = abd_alloc_for_io(asize,
6087 HDR_ISTYPE_METADATA(hdr));
6088 cb->l2rcb_abd = abd;
6089 } else {
b5256303 6090 abd = hdr_abd;
82710e99
GDN
6091 }
6092
a117a6d6 6093 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
82710e99 6094 addr + asize <= vd->vdev_psize -
a117a6d6
GW
6095 VDEV_LABEL_END_SIZE);
6096
34dc7c2f 6097 /*
b128c09f
BB
6098 * l2arc read. The SCL_L2ARC lock will be
6099 * released by l2arc_read_done().
3a17a7a9
SK
6100 * Issue a null zio if the underlying buffer
6101 * was squashed to zero size by compression.
34dc7c2f 6102 */
b5256303 6103 ASSERT3U(arc_hdr_get_compress(hdr), !=,
d3c2ae1c
GW
6104 ZIO_COMPRESS_EMPTY);
6105 rzio = zio_read_phys(pio, vd, addr,
82710e99 6106 asize, abd,
d3c2ae1c
GW
6107 ZIO_CHECKSUM_OFF,
6108 l2arc_read_done, cb, priority,
6109 zio_flags | ZIO_FLAG_DONT_CACHE |
6110 ZIO_FLAG_CANFAIL |
6111 ZIO_FLAG_DONT_PROPAGATE |
6112 ZIO_FLAG_DONT_RETRY, B_FALSE);
a8b2e306
TC
6113 acb->acb_zio_head = rzio;
6114
6115 if (hash_lock != NULL)
6116 mutex_exit(hash_lock);
d3c2ae1c 6117
34dc7c2f
BB
6118 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
6119 zio_t *, rzio);
b5256303
TC
6120 ARCSTAT_INCR(arcstat_l2_read_bytes,
6121 HDR_GET_PSIZE(hdr));
34dc7c2f 6122
2a432414 6123 if (*arc_flags & ARC_FLAG_NOWAIT) {
b128c09f 6124 zio_nowait(rzio);
1421c891 6125 goto out;
b128c09f 6126 }
34dc7c2f 6127
2a432414 6128 ASSERT(*arc_flags & ARC_FLAG_WAIT);
b128c09f 6129 if (zio_wait(rzio) == 0)
1421c891 6130 goto out;
b128c09f
BB
6131
6132 /* l2arc read error; goto zio_read() */
a8b2e306
TC
6133 if (hash_lock != NULL)
6134 mutex_enter(hash_lock);
34dc7c2f
BB
6135 } else {
6136 DTRACE_PROBE1(l2arc__miss,
6137 arc_buf_hdr_t *, hdr);
6138 ARCSTAT_BUMP(arcstat_l2_misses);
6139 if (HDR_L2_WRITING(hdr))
6140 ARCSTAT_BUMP(arcstat_l2_rw_clash);
b128c09f 6141 spa_config_exit(spa, SCL_L2ARC, vd);
34dc7c2f 6142 }
d164b209
BB
6143 } else {
6144 if (vd != NULL)
6145 spa_config_exit(spa, SCL_L2ARC, vd);
666aa69f 6146
0902c457 6147 /*
666aa69f
AM
6148 * Only a spa with l2 should contribute to l2
6149 * miss stats. (Including the case of having a
6150 * faulted cache device - that's also a miss.)
0902c457 6151 */
666aa69f
AM
6152 if (spa_has_l2) {
6153 /*
6154 * Skip ARC stat bump for block pointers with
6155 * embedded data. The data are read from the
6156 * blkptr itself via
6157 * decode_embedded_bp_compressed().
6158 */
6159 if (!embedded_bp) {
6160 DTRACE_PROBE1(l2arc__miss,
6161 arc_buf_hdr_t *, hdr);
6162 ARCSTAT_BUMP(arcstat_l2_misses);
6163 }
d164b209 6164 }
34dc7c2f 6165 }
34dc7c2f 6166
b5256303 6167 rzio = zio_read(pio, spa, bp, hdr_abd, size,
d3c2ae1c 6168 arc_read_done, hdr, priority, zio_flags, zb);
a8b2e306
TC
6169 acb->acb_zio_head = rzio;
6170
6171 if (hash_lock != NULL)
6172 mutex_exit(hash_lock);
34dc7c2f 6173
2a432414 6174 if (*arc_flags & ARC_FLAG_WAIT) {
1421c891
PS
6175 rc = zio_wait(rzio);
6176 goto out;
6177 }
34dc7c2f 6178
2a432414 6179 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
34dc7c2f
BB
6180 zio_nowait(rzio);
6181 }
1421c891
PS
6182
6183out:
157ef7f6 6184 /* embedded bps don't actually go to disk */
0902c457 6185 if (!embedded_bp)
157ef7f6 6186 spa_read_history_add(spa, zb, *arc_flags);
1e9231ad 6187 spl_fstrans_unmark(cookie);
1421c891 6188 return (rc);
87a4dfa5
AM
6189
6190done:
6191 if (done)
6192 done(NULL, zb, bp, buf, private);
6193 if (pio && rc != 0) {
6194 zio_t *zio = zio_null(pio, spa, NULL, NULL, NULL, zio_flags);
6195 zio->io_error = rc;
6196 zio_nowait(zio);
6197 }
6198 goto out;
34dc7c2f
BB
6199}
6200
ab26409d
BB
6201arc_prune_t *
6202arc_add_prune_callback(arc_prune_func_t *func, void *private)
6203{
6204 arc_prune_t *p;
6205
d1d7e268 6206 p = kmem_alloc(sizeof (*p), KM_SLEEP);
ab26409d
BB
6207 p->p_pfunc = func;
6208 p->p_private = private;
6209 list_link_init(&p->p_node);
424fd7c3 6210 zfs_refcount_create(&p->p_refcnt);
ab26409d
BB
6211
6212 mutex_enter(&arc_prune_mtx);
c13060e4 6213 zfs_refcount_add(&p->p_refcnt, &arc_prune_list);
ab26409d
BB
6214 list_insert_head(&arc_prune_list, p);
6215 mutex_exit(&arc_prune_mtx);
6216
6217 return (p);
6218}
6219
6220void
6221arc_remove_prune_callback(arc_prune_t *p)
6222{
4442f60d 6223 boolean_t wait = B_FALSE;
ab26409d
BB
6224 mutex_enter(&arc_prune_mtx);
6225 list_remove(&arc_prune_list, p);
424fd7c3 6226 if (zfs_refcount_remove(&p->p_refcnt, &arc_prune_list) > 0)
4442f60d 6227 wait = B_TRUE;
ab26409d 6228 mutex_exit(&arc_prune_mtx);
4442f60d
CC
6229
6230 /* wait for arc_prune_task to finish */
6231 if (wait)
6232 taskq_wait_outstanding(arc_prune_taskq, 0);
424fd7c3
TS
6233 ASSERT0(zfs_refcount_count(&p->p_refcnt));
6234 zfs_refcount_destroy(&p->p_refcnt);
4442f60d 6235 kmem_free(p, sizeof (*p));
ab26409d
BB
6236}
6237
df4474f9
MA
6238/*
6239 * Notify the arc that a block was freed, and thus will never be used again.
6240 */
6241void
6242arc_freed(spa_t *spa, const blkptr_t *bp)
6243{
6244 arc_buf_hdr_t *hdr;
6245 kmutex_t *hash_lock;
6246 uint64_t guid = spa_load_guid(spa);
6247
9b67f605
MA
6248 ASSERT(!BP_IS_EMBEDDED(bp));
6249
6250 hdr = buf_hash_find(guid, bp, &hash_lock);
df4474f9
MA
6251 if (hdr == NULL)
6252 return;
df4474f9 6253
d3c2ae1c
GW
6254 /*
6255 * We might be trying to free a block that is still doing I/O
c935fe2e
AM
6256 * (i.e. prefetch) or has some other reference (i.e. a dedup-ed,
6257 * dmu_sync-ed block). A block may also have a reference if it is
d3c2ae1c
GW
6258 * part of a dedup-ed, dmu_synced write. The dmu_sync() function would
6259 * have written the new block to its final resting place on disk but
6260 * without the dedup flag set. This would have left the hdr in the MRU
6261 * state and discoverable. When the txg finally syncs it detects that
6262 * the block was overridden in open context and issues an override I/O.
6263 * Since this is a dedup block, the override I/O will determine if the
6264 * block is already in the DDT. If so, then it will replace the io_bp
6265 * with the bp from the DDT and allow the I/O to finish. When the I/O
6266 * reaches the done callback, dbuf_write_override_done, it will
6267 * check to see if the io_bp and io_bp_override are identical.
6268 * If they are not, then it indicates that the bp was replaced with
6269 * the bp in the DDT and the override bp is freed. This allows
6270 * us to arrive here with a reference on a block that is being
6271 * freed. So if we have an I/O in progress, or a reference to
6272 * this hdr, then we don't destroy the hdr.
6273 */
c935fe2e
AM
6274 if (!HDR_HAS_L1HDR(hdr) ||
6275 zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
6276 arc_change_state(arc_anon, hdr);
d3c2ae1c 6277 arc_hdr_destroy(hdr);
df4474f9 6278 mutex_exit(hash_lock);
bd089c54 6279 } else {
d3c2ae1c 6280 mutex_exit(hash_lock);
34dc7c2f 6281 }
34dc7c2f 6282
34dc7c2f
BB
6283}
6284
6285/*
e49f1e20
WA
6286 * Release this buffer from the cache, making it an anonymous buffer. This
6287 * must be done after a read and prior to modifying the buffer contents.
34dc7c2f 6288 * If the buffer has more than one reference, we must make
b128c09f 6289 * a new hdr for the buffer.
34dc7c2f
BB
6290 */
6291void
dd66857d 6292arc_release(arc_buf_t *buf, const void *tag)
34dc7c2f 6293{
b9541d6b 6294 arc_buf_hdr_t *hdr = buf->b_hdr;
34dc7c2f 6295
428870ff 6296 /*
ca0bf58d 6297 * It would be nice to assert that if its DMU metadata (level >
428870ff
BB
6298 * 0 || it's the dnode file), then it must be syncing context.
6299 * But we don't know that information at this level.
6300 */
6301
ca0bf58d
PS
6302 ASSERT(HDR_HAS_L1HDR(hdr));
6303
b9541d6b
CW
6304 /*
6305 * We don't grab the hash lock prior to this check, because if
6306 * the buffer's header is in the arc_anon state, it won't be
6307 * linked into the hash table.
6308 */
6309 if (hdr->b_l1hdr.b_state == arc_anon) {
b9541d6b
CW
6310 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6311 ASSERT(!HDR_IN_HASH_TABLE(hdr));
6312 ASSERT(!HDR_HAS_L2HDR(hdr));
34dc7c2f 6313
d3c2ae1c 6314 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
424fd7c3 6315 ASSERT3S(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
c935fe2e 6316 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
b9541d6b 6317
b9541d6b 6318 hdr->b_l1hdr.b_arc_access = 0;
d3c2ae1c
GW
6319
6320 /*
6321 * If the buf is being overridden then it may already
6322 * have a hdr that is not empty.
6323 */
6324 buf_discard_identity(hdr);
b9541d6b
CW
6325 arc_buf_thaw(buf);
6326
6327 return;
34dc7c2f
BB
6328 }
6329
1c27024e 6330 kmutex_t *hash_lock = HDR_LOCK(hdr);
b9541d6b
CW
6331 mutex_enter(hash_lock);
6332
6333 /*
6334 * This assignment is only valid as long as the hash_lock is
6335 * held, we must be careful not to reference state or the
6336 * b_state field after dropping the lock.
6337 */
1c27024e 6338 arc_state_t *state = hdr->b_l1hdr.b_state;
b9541d6b
CW
6339 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
6340 ASSERT3P(state, !=, arc_anon);
6341
6342 /* this buffer is not on any list */
424fd7c3 6343 ASSERT3S(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt), >, 0);
b9541d6b
CW
6344
6345 if (HDR_HAS_L2HDR(hdr)) {
b9541d6b 6346 mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
ca0bf58d
PS
6347
6348 /*
d962d5da
PS
6349 * We have to recheck this conditional again now that
6350 * we're holding the l2ad_mtx to prevent a race with
6351 * another thread which might be concurrently calling
6352 * l2arc_evict(). In that case, l2arc_evict() might have
6353 * destroyed the header's L2 portion as we were waiting
6354 * to acquire the l2ad_mtx.
ca0bf58d 6355 */
d962d5da
PS
6356 if (HDR_HAS_L2HDR(hdr))
6357 arc_hdr_l2hdr_destroy(hdr);
ca0bf58d 6358
b9541d6b 6359 mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
b128c09f
BB
6360 }
6361
34dc7c2f
BB
6362 /*
6363 * Do we have more than one buf?
6364 */
d3c2ae1c 6365 if (hdr->b_l1hdr.b_bufcnt > 1) {
34dc7c2f 6366 arc_buf_hdr_t *nhdr;
d164b209 6367 uint64_t spa = hdr->b_spa;
d3c2ae1c
GW
6368 uint64_t psize = HDR_GET_PSIZE(hdr);
6369 uint64_t lsize = HDR_GET_LSIZE(hdr);
b5256303
TC
6370 boolean_t protected = HDR_PROTECTED(hdr);
6371 enum zio_compress compress = arc_hdr_get_compress(hdr);
b9541d6b 6372 arc_buf_contents_t type = arc_buf_type(hdr);
d3c2ae1c 6373 VERIFY3U(hdr->b_type, ==, type);
34dc7c2f 6374
b9541d6b 6375 ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
ed2f7ba0 6376 VERIFY3S(remove_reference(hdr, tag), >, 0);
d3c2ae1c 6377
524b4217 6378 if (arc_buf_is_shared(buf) && !ARC_BUF_COMPRESSED(buf)) {
d3c2ae1c 6379 ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
524b4217
DK
6380 ASSERT(ARC_BUF_LAST(buf));
6381 }
d3c2ae1c 6382
34dc7c2f 6383 /*
428870ff 6384 * Pull the data off of this hdr and attach it to
d3c2ae1c
GW
6385 * a new anonymous hdr. Also find the last buffer
6386 * in the hdr's buffer list.
34dc7c2f 6387 */
a7004725 6388 arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
d3c2ae1c 6389 ASSERT3P(lastbuf, !=, NULL);
34dc7c2f 6390
d3c2ae1c
GW
6391 /*
6392 * If the current arc_buf_t and the hdr are sharing their data
524b4217 6393 * buffer, then we must stop sharing that block.
d3c2ae1c
GW
6394 */
6395 if (arc_buf_is_shared(buf)) {
6396 ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
d3c2ae1c
GW
6397 VERIFY(!arc_buf_is_shared(lastbuf));
6398
6399 /*
6400 * First, sever the block sharing relationship between
a7004725 6401 * buf and the arc_buf_hdr_t.
d3c2ae1c
GW
6402 */
6403 arc_unshare_buf(hdr, buf);
2aa34383
DK
6404
6405 /*
a6255b7f 6406 * Now we need to recreate the hdr's b_pabd. Since we
524b4217 6407 * have lastbuf handy, we try to share with it, but if
a6255b7f 6408 * we can't then we allocate a new b_pabd and copy the
524b4217 6409 * data from buf into it.
2aa34383 6410 */
524b4217
DK
6411 if (arc_can_share(hdr, lastbuf)) {
6412 arc_share_buf(hdr, lastbuf);
6413 } else {
a8d83e2a 6414 arc_hdr_alloc_abd(hdr, 0);
a6255b7f
DQ
6415 abd_copy_from_buf(hdr->b_l1hdr.b_pabd,
6416 buf->b_data, psize);
2aa34383 6417 }
d3c2ae1c
GW
6418 VERIFY3P(lastbuf->b_data, !=, NULL);
6419 } else if (HDR_SHARED_DATA(hdr)) {
2aa34383
DK
6420 /*
6421 * Uncompressed shared buffers are always at the end
6422 * of the list. Compressed buffers don't have the
6423 * same requirements. This makes it hard to
6424 * simply assert that the lastbuf is shared so
6425 * we rely on the hdr's compression flags to determine
6426 * if we have a compressed, shared buffer.
6427 */
6428 ASSERT(arc_buf_is_shared(lastbuf) ||
b5256303 6429 arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF);
2aa34383 6430 ASSERT(!ARC_BUF_SHARED(buf));
d3c2ae1c 6431 }
b5256303
TC
6432
6433 ASSERT(hdr->b_l1hdr.b_pabd != NULL || HDR_HAS_RABD(hdr));
b9541d6b 6434 ASSERT3P(state, !=, arc_l2c_only);
36da08ef 6435
a8d83e2a 6436 (void) zfs_refcount_remove_many(&state->arcs_size[type],
2aa34383 6437 arc_buf_size(buf), buf);
36da08ef 6438
424fd7c3 6439 if (zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
b9541d6b 6440 ASSERT3P(state, !=, arc_l2c_only);
424fd7c3
TS
6441 (void) zfs_refcount_remove_many(
6442 &state->arcs_esize[type],
2aa34383 6443 arc_buf_size(buf), buf);
34dc7c2f 6444 }
1eb5bfa3 6445
d3c2ae1c 6446 hdr->b_l1hdr.b_bufcnt -= 1;
b5256303
TC
6447 if (ARC_BUF_ENCRYPTED(buf))
6448 hdr->b_crypt_hdr.b_ebufcnt -= 1;
6449
34dc7c2f 6450 arc_cksum_verify(buf);
498877ba 6451 arc_buf_unwatch(buf);
34dc7c2f 6452
f486f584
TC
6453 /* if this is the last uncompressed buf free the checksum */
6454 if (!arc_hdr_has_uncompressed_buf(hdr))
6455 arc_cksum_free(hdr);
6456
34dc7c2f
BB
6457 mutex_exit(hash_lock);
6458
b5256303 6459 nhdr = arc_hdr_alloc(spa, psize, lsize, protected,
6b88b4b5 6460 compress, hdr->b_complevel, type);
d3c2ae1c
GW
6461 ASSERT3P(nhdr->b_l1hdr.b_buf, ==, NULL);
6462 ASSERT0(nhdr->b_l1hdr.b_bufcnt);
424fd7c3 6463 ASSERT0(zfs_refcount_count(&nhdr->b_l1hdr.b_refcnt));
d3c2ae1c
GW
6464 VERIFY3U(nhdr->b_type, ==, type);
6465 ASSERT(!HDR_SHARED_DATA(nhdr));
b9541d6b 6466
d3c2ae1c
GW
6467 nhdr->b_l1hdr.b_buf = buf;
6468 nhdr->b_l1hdr.b_bufcnt = 1;
b5256303
TC
6469 if (ARC_BUF_ENCRYPTED(buf))
6470 nhdr->b_crypt_hdr.b_ebufcnt = 1;
c13060e4 6471 (void) zfs_refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
34dc7c2f 6472 buf->b_hdr = nhdr;
d3c2ae1c 6473
a8d83e2a 6474 (void) zfs_refcount_add_many(&arc_anon->arcs_size[type],
5e8ff256 6475 arc_buf_size(buf), buf);
34dc7c2f 6476 } else {
424fd7c3 6477 ASSERT(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
ca0bf58d
PS
6478 /* protected by hash lock, or hdr is on arc_anon */
6479 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
34dc7c2f 6480 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
b9541d6b
CW
6481 hdr->b_l1hdr.b_mru_hits = 0;
6482 hdr->b_l1hdr.b_mru_ghost_hits = 0;
6483 hdr->b_l1hdr.b_mfu_hits = 0;
6484 hdr->b_l1hdr.b_mfu_ghost_hits = 0;
c935fe2e 6485 arc_change_state(arc_anon, hdr);
b9541d6b 6486 hdr->b_l1hdr.b_arc_access = 0;
34dc7c2f 6487
b5256303 6488 mutex_exit(hash_lock);
428870ff 6489 buf_discard_identity(hdr);
34dc7c2f
BB
6490 arc_buf_thaw(buf);
6491 }
34dc7c2f
BB
6492}
6493
6494int
6495arc_released(arc_buf_t *buf)
6496{
289f7e6a 6497 return (buf->b_data != NULL &&
b9541d6b 6498 buf->b_hdr->b_l1hdr.b_state == arc_anon);
34dc7c2f
BB
6499}
6500
34dc7c2f
BB
6501#ifdef ZFS_DEBUG
6502int
6503arc_referenced(arc_buf_t *buf)
6504{
289f7e6a 6505 return (zfs_refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
34dc7c2f
BB
6506}
6507#endif
6508
6509static void
6510arc_write_ready(zio_t *zio)
6511{
6512 arc_write_callback_t *callback = zio->io_private;
6513 arc_buf_t *buf = callback->awcb_buf;
6514 arc_buf_hdr_t *hdr = buf->b_hdr;
b5256303
TC
6515 blkptr_t *bp = zio->io_bp;
6516 uint64_t psize = BP_IS_HOLE(bp) ? 0 : BP_GET_PSIZE(bp);
a6255b7f 6517 fstrans_cookie_t cookie = spl_fstrans_mark();
34dc7c2f 6518
b9541d6b 6519 ASSERT(HDR_HAS_L1HDR(hdr));
424fd7c3 6520 ASSERT(!zfs_refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
d3c2ae1c 6521 ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
b128c09f 6522
34dc7c2f 6523 /*
d3c2ae1c
GW
6524 * If we're reexecuting this zio because the pool suspended, then
6525 * cleanup any state that was previously set the first time the
2aa34383 6526 * callback was invoked.
34dc7c2f 6527 */
d3c2ae1c
GW
6528 if (zio->io_flags & ZIO_FLAG_REEXECUTED) {
6529 arc_cksum_free(hdr);
6530 arc_buf_unwatch(buf);
a6255b7f 6531 if (hdr->b_l1hdr.b_pabd != NULL) {
d3c2ae1c 6532 if (arc_buf_is_shared(buf)) {
d3c2ae1c
GW
6533 arc_unshare_buf(hdr, buf);
6534 } else {
b5256303 6535 arc_hdr_free_abd(hdr, B_FALSE);
d3c2ae1c 6536 }
34dc7c2f 6537 }
b5256303
TC
6538
6539 if (HDR_HAS_RABD(hdr))
6540 arc_hdr_free_abd(hdr, B_TRUE);
34dc7c2f 6541 }
a6255b7f 6542 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
b5256303 6543 ASSERT(!HDR_HAS_RABD(hdr));
d3c2ae1c
GW
6544 ASSERT(!HDR_SHARED_DATA(hdr));
6545 ASSERT(!arc_buf_is_shared(buf));
6546
6547 callback->awcb_ready(zio, buf, callback->awcb_private);
6548
c935fe2e 6549 if (HDR_IO_IN_PROGRESS(hdr)) {
d3c2ae1c 6550 ASSERT(zio->io_flags & ZIO_FLAG_REEXECUTED);
c935fe2e
AM
6551 } else {
6552 arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6553 add_reference(hdr, hdr); /* For IO_IN_PROGRESS. */
6554 }
d3c2ae1c 6555
b5256303
TC
6556 if (BP_IS_PROTECTED(bp) != !!HDR_PROTECTED(hdr))
6557 hdr = arc_hdr_realloc_crypt(hdr, BP_IS_PROTECTED(bp));
6558
6559 if (BP_IS_PROTECTED(bp)) {
6560 /* ZIL blocks are written through zio_rewrite */
6561 ASSERT3U(BP_GET_TYPE(bp), !=, DMU_OT_INTENT_LOG);
6562 ASSERT(HDR_PROTECTED(hdr));
6563
ae76f45c
TC
6564 if (BP_SHOULD_BYTESWAP(bp)) {
6565 if (BP_GET_LEVEL(bp) > 0) {
6566 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
6567 } else {
6568 hdr->b_l1hdr.b_byteswap =
6569 DMU_OT_BYTESWAP(BP_GET_TYPE(bp));
6570 }
6571 } else {
6572 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
6573 }
6574
b5256303
TC
6575 hdr->b_crypt_hdr.b_ot = BP_GET_TYPE(bp);
6576 hdr->b_crypt_hdr.b_dsobj = zio->io_bookmark.zb_objset;
6577 zio_crypt_decode_params_bp(bp, hdr->b_crypt_hdr.b_salt,
6578 hdr->b_crypt_hdr.b_iv);
6579 zio_crypt_decode_mac_bp(bp, hdr->b_crypt_hdr.b_mac);
6580 }
6581
6582 /*
6583 * If this block was written for raw encryption but the zio layer
6584 * ended up only authenticating it, adjust the buffer flags now.
6585 */
6586 if (BP_IS_AUTHENTICATED(bp) && ARC_BUF_ENCRYPTED(buf)) {
6587 arc_hdr_set_flags(hdr, ARC_FLAG_NOAUTH);
6588 buf->b_flags &= ~ARC_BUF_FLAG_ENCRYPTED;
6589 if (BP_GET_COMPRESS(bp) == ZIO_COMPRESS_OFF)
6590 buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
b1d21733
TC
6591 } else if (BP_IS_HOLE(bp) && ARC_BUF_ENCRYPTED(buf)) {
6592 buf->b_flags &= ~ARC_BUF_FLAG_ENCRYPTED;
6593 buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
b5256303
TC
6594 }
6595
6596 /* this must be done after the buffer flags are adjusted */
6597 arc_cksum_compute(buf);
6598
1c27024e 6599 enum zio_compress compress;
b5256303 6600 if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
d3c2ae1c
GW
6601 compress = ZIO_COMPRESS_OFF;
6602 } else {
b5256303
TC
6603 ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
6604 compress = BP_GET_COMPRESS(bp);
d3c2ae1c
GW
6605 }
6606 HDR_SET_PSIZE(hdr, psize);
6607 arc_hdr_set_compress(hdr, compress);
10b3c7f5 6608 hdr->b_complevel = zio->io_prop.zp_complevel;
d3c2ae1c 6609
4807c0ba
TC
6610 if (zio->io_error != 0 || psize == 0)
6611 goto out;
6612
d3c2ae1c 6613 /*
b5256303
TC
6614 * Fill the hdr with data. If the buffer is encrypted we have no choice
6615 * but to copy the data into b_radb. If the hdr is compressed, the data
6616 * we want is available from the zio, otherwise we can take it from
6617 * the buf.
a6255b7f
DQ
6618 *
6619 * We might be able to share the buf's data with the hdr here. However,
6620 * doing so would cause the ARC to be full of linear ABDs if we write a
6621 * lot of shareable data. As a compromise, we check whether scattered
6622 * ABDs are allowed, and assume that if they are then the user wants
6623 * the ARC to be primarily filled with them regardless of the data being
6624 * written. Therefore, if they're allowed then we allocate one and copy
6625 * the data into it; otherwise, we share the data directly if we can.
d3c2ae1c 6626 */
b5256303 6627 if (ARC_BUF_ENCRYPTED(buf)) {
4807c0ba 6628 ASSERT3U(psize, >, 0);
b5256303 6629 ASSERT(ARC_BUF_COMPRESSED(buf));
a8d83e2a 6630 arc_hdr_alloc_abd(hdr, ARC_HDR_ALLOC_RDATA |
6b88b4b5 6631 ARC_HDR_USE_RESERVE);
b5256303 6632 abd_copy(hdr->b_crypt_hdr.b_rabd, zio->io_abd, psize);
ed2f7ba0
AM
6633 } else if (!(HDR_UNCACHED(hdr) ||
6634 abd_size_alloc_linear(arc_buf_size(buf))) ||
7eebcd2b 6635 !arc_can_share(hdr, buf)) {
a6255b7f
DQ
6636 /*
6637 * Ideally, we would always copy the io_abd into b_pabd, but the
6638 * user may have disabled compressed ARC, thus we must check the
6639 * hdr's compression setting rather than the io_bp's.
6640 */
b5256303 6641 if (BP_IS_ENCRYPTED(bp)) {
a6255b7f 6642 ASSERT3U(psize, >, 0);
a8d83e2a
AM
6643 arc_hdr_alloc_abd(hdr, ARC_HDR_ALLOC_RDATA |
6644 ARC_HDR_USE_RESERVE);
b5256303
TC
6645 abd_copy(hdr->b_crypt_hdr.b_rabd, zio->io_abd, psize);
6646 } else if (arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF &&
6647 !ARC_BUF_COMPRESSED(buf)) {
6648 ASSERT3U(psize, >, 0);
a8d83e2a 6649 arc_hdr_alloc_abd(hdr, ARC_HDR_USE_RESERVE);
a6255b7f
DQ
6650 abd_copy(hdr->b_l1hdr.b_pabd, zio->io_abd, psize);
6651 } else {
6652 ASSERT3U(zio->io_orig_size, ==, arc_hdr_size(hdr));
a8d83e2a 6653 arc_hdr_alloc_abd(hdr, ARC_HDR_USE_RESERVE);
a6255b7f
DQ
6654 abd_copy_from_buf(hdr->b_l1hdr.b_pabd, buf->b_data,
6655 arc_buf_size(buf));
6656 }
d3c2ae1c 6657 } else {
a6255b7f 6658 ASSERT3P(buf->b_data, ==, abd_to_buf(zio->io_orig_abd));
2aa34383 6659 ASSERT3U(zio->io_orig_size, ==, arc_buf_size(buf));
d3c2ae1c 6660 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
d3c2ae1c 6661
d3c2ae1c 6662 arc_share_buf(hdr, buf);
d3c2ae1c 6663 }
a6255b7f 6664
4807c0ba 6665out:
b5256303 6666 arc_hdr_verify(hdr, bp);
a6255b7f 6667 spl_fstrans_unmark(cookie);
34dc7c2f
BB
6668}
6669
bc77ba73
PD
6670static void
6671arc_write_children_ready(zio_t *zio)
6672{
6673 arc_write_callback_t *callback = zio->io_private;
6674 arc_buf_t *buf = callback->awcb_buf;
6675
6676 callback->awcb_children_ready(zio, buf, callback->awcb_private);
6677}
6678
e8b96c60
MA
6679/*
6680 * The SPA calls this callback for each physical write that happens on behalf
6681 * of a logical write. See the comment in dbuf_write_physdone() for details.
6682 */
6683static void
6684arc_write_physdone(zio_t *zio)
6685{
6686 arc_write_callback_t *cb = zio->io_private;
6687 if (cb->awcb_physdone != NULL)
6688 cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
6689}
6690
34dc7c2f
BB
6691static void
6692arc_write_done(zio_t *zio)
6693{
6694 arc_write_callback_t *callback = zio->io_private;
6695 arc_buf_t *buf = callback->awcb_buf;
6696 arc_buf_hdr_t *hdr = buf->b_hdr;
6697
d3c2ae1c 6698 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
428870ff
BB
6699
6700 if (zio->io_error == 0) {
d3c2ae1c
GW
6701 arc_hdr_verify(hdr, zio->io_bp);
6702
9b67f605 6703 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
b0bc7a84
MG
6704 buf_discard_identity(hdr);
6705 } else {
6706 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
6707 hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
b0bc7a84 6708 }
428870ff 6709 } else {
d3c2ae1c 6710 ASSERT(HDR_EMPTY(hdr));
428870ff 6711 }
34dc7c2f 6712
34dc7c2f 6713 /*
9b67f605
MA
6714 * If the block to be written was all-zero or compressed enough to be
6715 * embedded in the BP, no write was performed so there will be no
6716 * dva/birth/checksum. The buffer must therefore remain anonymous
6717 * (and uncached).
34dc7c2f 6718 */
d3c2ae1c 6719 if (!HDR_EMPTY(hdr)) {
34dc7c2f
BB
6720 arc_buf_hdr_t *exists;
6721 kmutex_t *hash_lock;
6722
524b4217 6723 ASSERT3U(zio->io_error, ==, 0);
428870ff 6724
34dc7c2f
BB
6725 arc_cksum_verify(buf);
6726
6727 exists = buf_hash_insert(hdr, &hash_lock);
b9541d6b 6728 if (exists != NULL) {
34dc7c2f
BB
6729 /*
6730 * This can only happen if we overwrite for
6731 * sync-to-convergence, because we remove
6732 * buffers from the hash table when we arc_free().
6733 */
428870ff
BB
6734 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
6735 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
6736 panic("bad overwrite, hdr=%p exists=%p",
6737 (void *)hdr, (void *)exists);
424fd7c3 6738 ASSERT(zfs_refcount_is_zero(
b9541d6b 6739 &exists->b_l1hdr.b_refcnt));
c935fe2e 6740 arc_change_state(arc_anon, exists);
428870ff 6741 arc_hdr_destroy(exists);
ca6c7a94 6742 mutex_exit(hash_lock);
428870ff
BB
6743 exists = buf_hash_insert(hdr, &hash_lock);
6744 ASSERT3P(exists, ==, NULL);
03c6040b
GW
6745 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
6746 /* nopwrite */
6747 ASSERT(zio->io_prop.zp_nopwrite);
6748 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
6749 panic("bad nopwrite, hdr=%p exists=%p",
6750 (void *)hdr, (void *)exists);
428870ff
BB
6751 } else {
6752 /* Dedup */
d3c2ae1c 6753 ASSERT(hdr->b_l1hdr.b_bufcnt == 1);
b9541d6b 6754 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
428870ff
BB
6755 ASSERT(BP_GET_DEDUP(zio->io_bp));
6756 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
6757 }
34dc7c2f 6758 }
d3c2ae1c 6759 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
ed2f7ba0 6760 VERIFY3S(remove_reference(hdr, hdr), >, 0);
b128c09f 6761 /* if it's not anon, we are doing a scrub */
b9541d6b 6762 if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
c935fe2e 6763 arc_access(hdr, 0, B_FALSE);
34dc7c2f 6764 mutex_exit(hash_lock);
34dc7c2f 6765 } else {
d3c2ae1c 6766 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
ed2f7ba0 6767 VERIFY3S(remove_reference(hdr, hdr), >, 0);
34dc7c2f
BB
6768 }
6769
428870ff 6770 callback->awcb_done(zio, buf, callback->awcb_private);
34dc7c2f 6771
e2af2acc 6772 abd_free(zio->io_abd);
34dc7c2f
BB
6773 kmem_free(callback, sizeof (arc_write_callback_t));
6774}
6775
6776zio_t *
428870ff 6777arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
ed2f7ba0 6778 blkptr_t *bp, arc_buf_t *buf, boolean_t uncached, boolean_t l2arc,
b5256303
TC
6779 const zio_prop_t *zp, arc_write_done_func_t *ready,
6780 arc_write_done_func_t *children_ready, arc_write_done_func_t *physdone,
6781 arc_write_done_func_t *done, void *private, zio_priority_t priority,
5dbd68a3 6782 int zio_flags, const zbookmark_phys_t *zb)
34dc7c2f
BB
6783{
6784 arc_buf_hdr_t *hdr = buf->b_hdr;
6785 arc_write_callback_t *callback;
b128c09f 6786 zio_t *zio;
82644107 6787 zio_prop_t localprop = *zp;
34dc7c2f 6788
d3c2ae1c
GW
6789 ASSERT3P(ready, !=, NULL);
6790 ASSERT3P(done, !=, NULL);
34dc7c2f 6791 ASSERT(!HDR_IO_ERROR(hdr));
b9541d6b 6792 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
d3c2ae1c
GW
6793 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
6794 ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
ed2f7ba0
AM
6795 if (uncached)
6796 arc_hdr_set_flags(hdr, ARC_FLAG_UNCACHED);
6797 else if (l2arc)
d3c2ae1c 6798 arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
82644107 6799
b5256303
TC
6800 if (ARC_BUF_ENCRYPTED(buf)) {
6801 ASSERT(ARC_BUF_COMPRESSED(buf));
6802 localprop.zp_encrypt = B_TRUE;
6803 localprop.zp_compress = HDR_GET_COMPRESS(hdr);
10b3c7f5 6804 localprop.zp_complevel = hdr->b_complevel;
b5256303
TC
6805 localprop.zp_byteorder =
6806 (hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS) ?
6807 ZFS_HOST_BYTEORDER : !ZFS_HOST_BYTEORDER;
861166b0 6808 memcpy(localprop.zp_salt, hdr->b_crypt_hdr.b_salt,
b5256303 6809 ZIO_DATA_SALT_LEN);
861166b0 6810 memcpy(localprop.zp_iv, hdr->b_crypt_hdr.b_iv,
b5256303 6811 ZIO_DATA_IV_LEN);
861166b0 6812 memcpy(localprop.zp_mac, hdr->b_crypt_hdr.b_mac,
b5256303
TC
6813 ZIO_DATA_MAC_LEN);
6814 if (DMU_OT_IS_ENCRYPTED(localprop.zp_type)) {
6815 localprop.zp_nopwrite = B_FALSE;
6816 localprop.zp_copies =
6817 MIN(localprop.zp_copies, SPA_DVAS_PER_BP - 1);
6818 }
2aa34383 6819 zio_flags |= ZIO_FLAG_RAW;
b5256303
TC
6820 } else if (ARC_BUF_COMPRESSED(buf)) {
6821 ASSERT3U(HDR_GET_LSIZE(hdr), !=, arc_buf_size(buf));
6822 localprop.zp_compress = HDR_GET_COMPRESS(hdr);
10b3c7f5 6823 localprop.zp_complevel = hdr->b_complevel;
b5256303 6824 zio_flags |= ZIO_FLAG_RAW_COMPRESS;
2aa34383 6825 }
79c76d5b 6826 callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
34dc7c2f 6827 callback->awcb_ready = ready;
bc77ba73 6828 callback->awcb_children_ready = children_ready;
e8b96c60 6829 callback->awcb_physdone = physdone;
34dc7c2f
BB
6830 callback->awcb_done = done;
6831 callback->awcb_private = private;
6832 callback->awcb_buf = buf;
b128c09f 6833
d3c2ae1c 6834 /*
a6255b7f 6835 * The hdr's b_pabd is now stale, free it now. A new data block
d3c2ae1c
GW
6836 * will be allocated when the zio pipeline calls arc_write_ready().
6837 */
a6255b7f 6838 if (hdr->b_l1hdr.b_pabd != NULL) {
d3c2ae1c
GW
6839 /*
6840 * If the buf is currently sharing the data block with
6841 * the hdr then we need to break that relationship here.
6842 * The hdr will remain with a NULL data pointer and the
6843 * buf will take sole ownership of the block.
6844 */
6845 if (arc_buf_is_shared(buf)) {
d3c2ae1c
GW
6846 arc_unshare_buf(hdr, buf);
6847 } else {
b5256303 6848 arc_hdr_free_abd(hdr, B_FALSE);
d3c2ae1c
GW
6849 }
6850 VERIFY3P(buf->b_data, !=, NULL);
d3c2ae1c 6851 }
b5256303
TC
6852
6853 if (HDR_HAS_RABD(hdr))
6854 arc_hdr_free_abd(hdr, B_TRUE);
6855
71a24c3c
TC
6856 if (!(zio_flags & ZIO_FLAG_RAW))
6857 arc_hdr_set_compress(hdr, ZIO_COMPRESS_OFF);
b5256303 6858
d3c2ae1c 6859 ASSERT(!arc_buf_is_shared(buf));
a6255b7f 6860 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
d3c2ae1c 6861
a6255b7f
DQ
6862 zio = zio_write(pio, spa, txg, bp,
6863 abd_get_from_buf(buf->b_data, HDR_GET_LSIZE(hdr)),
82644107 6864 HDR_GET_LSIZE(hdr), arc_buf_size(buf), &localprop, arc_write_ready,
bc77ba73
PD
6865 (children_ready != NULL) ? arc_write_children_ready : NULL,
6866 arc_write_physdone, arc_write_done, callback,
e8b96c60 6867 priority, zio_flags, zb);
34dc7c2f
BB
6868
6869 return (zio);
6870}
6871
34dc7c2f
BB
6872void
6873arc_tempreserve_clear(uint64_t reserve)
6874{
6875 atomic_add_64(&arc_tempreserve, -reserve);
6876 ASSERT((int64_t)arc_tempreserve >= 0);
6877}
6878
6879int
dae3e9ea 6880arc_tempreserve_space(spa_t *spa, uint64_t reserve, uint64_t txg)
34dc7c2f
BB
6881{
6882 int error;
9babb374 6883 uint64_t anon_size;
34dc7c2f 6884
1b8951b3
TC
6885 if (!arc_no_grow &&
6886 reserve > arc_c/4 &&
6887 reserve * 4 > (2ULL << SPA_MAXBLOCKSHIFT))
34dc7c2f 6888 arc_c = MIN(arc_c_max, reserve * 4);
12f9a6a3
BB
6889
6890 /*
6891 * Throttle when the calculated memory footprint for the TXG
6892 * exceeds the target ARC size.
6893 */
570827e1
BB
6894 if (reserve > arc_c) {
6895 DMU_TX_STAT_BUMP(dmu_tx_memory_reserve);
12f9a6a3 6896 return (SET_ERROR(ERESTART));
570827e1 6897 }
34dc7c2f 6898
9babb374
BB
6899 /*
6900 * Don't count loaned bufs as in flight dirty data to prevent long
6901 * network delays from blocking transactions that are ready to be
6902 * assigned to a txg.
6903 */
a7004725
DK
6904
6905 /* assert that it has not wrapped around */
6906 ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
6907
a8d83e2a
AM
6908 anon_size = MAX((int64_t)
6909 (zfs_refcount_count(&arc_anon->arcs_size[ARC_BUFC_DATA]) +
6910 zfs_refcount_count(&arc_anon->arcs_size[ARC_BUFC_METADATA]) -
36da08ef 6911 arc_loaned_bytes), 0);
9babb374 6912
34dc7c2f
BB
6913 /*
6914 * Writes will, almost always, require additional memory allocations
d3cc8b15 6915 * in order to compress/encrypt/etc the data. We therefore need to
34dc7c2f
BB
6916 * make sure that there is sufficient available memory for this.
6917 */
dae3e9ea 6918 error = arc_memory_throttle(spa, reserve, txg);
e8b96c60 6919 if (error != 0)
34dc7c2f
BB
6920 return (error);
6921
6922 /*
6923 * Throttle writes when the amount of dirty data in the cache
6924 * gets too large. We try to keep the cache less than half full
6925 * of dirty blocks so that our sync times don't grow too large.
dae3e9ea
DB
6926 *
6927 * In the case of one pool being built on another pool, we want
6928 * to make sure we don't end up throttling the lower (backing)
6929 * pool when the upper pool is the majority contributor to dirty
6930 * data. To insure we make forward progress during throttling, we
6931 * also check the current pool's net dirty data and only throttle
6932 * if it exceeds zfs_arc_pool_dirty_percent of the anonymous dirty
6933 * data in the cache.
6934 *
34dc7c2f
BB
6935 * Note: if two requests come in concurrently, we might let them
6936 * both succeed, when one of them should fail. Not a huge deal.
6937 */
dae3e9ea
DB
6938 uint64_t total_dirty = reserve + arc_tempreserve + anon_size;
6939 uint64_t spa_dirty_anon = spa_dirty_data(spa);
daabddaa
AM
6940 uint64_t rarc_c = arc_warm ? arc_c : arc_c_max;
6941 if (total_dirty > rarc_c * zfs_arc_dirty_limit_percent / 100 &&
6942 anon_size > rarc_c * zfs_arc_anon_limit_percent / 100 &&
dae3e9ea 6943 spa_dirty_anon > anon_size * zfs_arc_pool_dirty_percent / 100) {
2fd92c3d 6944#ifdef ZFS_DEBUG
424fd7c3
TS
6945 uint64_t meta_esize = zfs_refcount_count(
6946 &arc_anon->arcs_esize[ARC_BUFC_METADATA]);
d3c2ae1c 6947 uint64_t data_esize =
424fd7c3 6948 zfs_refcount_count(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
34dc7c2f 6949 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
daabddaa 6950 "anon_data=%lluK tempreserve=%lluK rarc_c=%lluK\n",
8e739b2c
RE
6951 (u_longlong_t)arc_tempreserve >> 10,
6952 (u_longlong_t)meta_esize >> 10,
6953 (u_longlong_t)data_esize >> 10,
6954 (u_longlong_t)reserve >> 10,
6955 (u_longlong_t)rarc_c >> 10);
2fd92c3d 6956#endif
570827e1 6957 DMU_TX_STAT_BUMP(dmu_tx_dirty_throttle);
2e528b49 6958 return (SET_ERROR(ERESTART));
34dc7c2f
BB
6959 }
6960 atomic_add_64(&arc_tempreserve, reserve);
6961 return (0);
6962}
6963
13be560d
BB
6964static void
6965arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
a8d83e2a 6966 kstat_named_t *data, kstat_named_t *metadata,
13be560d
BB
6967 kstat_named_t *evict_data, kstat_named_t *evict_metadata)
6968{
a8d83e2a
AM
6969 data->value.ui64 =
6970 zfs_refcount_count(&state->arcs_size[ARC_BUFC_DATA]);
6971 metadata->value.ui64 =
6972 zfs_refcount_count(&state->arcs_size[ARC_BUFC_METADATA]);
6973 size->value.ui64 = data->value.ui64 + metadata->value.ui64;
d3c2ae1c 6974 evict_data->value.ui64 =
424fd7c3 6975 zfs_refcount_count(&state->arcs_esize[ARC_BUFC_DATA]);
d3c2ae1c 6976 evict_metadata->value.ui64 =
424fd7c3 6977 zfs_refcount_count(&state->arcs_esize[ARC_BUFC_METADATA]);
13be560d
BB
6978}
6979
6980static int
6981arc_kstat_update(kstat_t *ksp, int rw)
6982{
6983 arc_stats_t *as = ksp->ks_data;
6984
c4c162c1 6985 if (rw == KSTAT_WRITE)
ecb2b7dc 6986 return (SET_ERROR(EACCES));
c4c162c1
AM
6987
6988 as->arcstat_hits.value.ui64 =
6989 wmsum_value(&arc_sums.arcstat_hits);
c935fe2e
AM
6990 as->arcstat_iohits.value.ui64 =
6991 wmsum_value(&arc_sums.arcstat_iohits);
c4c162c1
AM
6992 as->arcstat_misses.value.ui64 =
6993 wmsum_value(&arc_sums.arcstat_misses);
6994 as->arcstat_demand_data_hits.value.ui64 =
6995 wmsum_value(&arc_sums.arcstat_demand_data_hits);
c935fe2e
AM
6996 as->arcstat_demand_data_iohits.value.ui64 =
6997 wmsum_value(&arc_sums.arcstat_demand_data_iohits);
c4c162c1
AM
6998 as->arcstat_demand_data_misses.value.ui64 =
6999 wmsum_value(&arc_sums.arcstat_demand_data_misses);
7000 as->arcstat_demand_metadata_hits.value.ui64 =
7001 wmsum_value(&arc_sums.arcstat_demand_metadata_hits);
c935fe2e
AM
7002 as->arcstat_demand_metadata_iohits.value.ui64 =
7003 wmsum_value(&arc_sums.arcstat_demand_metadata_iohits);
c4c162c1
AM
7004 as->arcstat_demand_metadata_misses.value.ui64 =
7005 wmsum_value(&arc_sums.arcstat_demand_metadata_misses);
7006 as->arcstat_prefetch_data_hits.value.ui64 =
7007 wmsum_value(&arc_sums.arcstat_prefetch_data_hits);
c935fe2e
AM
7008 as->arcstat_prefetch_data_iohits.value.ui64 =
7009 wmsum_value(&arc_sums.arcstat_prefetch_data_iohits);
c4c162c1
AM
7010 as->arcstat_prefetch_data_misses.value.ui64 =
7011 wmsum_value(&arc_sums.arcstat_prefetch_data_misses);
7012 as->arcstat_prefetch_metadata_hits.value.ui64 =
7013 wmsum_value(&arc_sums.arcstat_prefetch_metadata_hits);
c935fe2e
AM
7014 as->arcstat_prefetch_metadata_iohits.value.ui64 =
7015 wmsum_value(&arc_sums.arcstat_prefetch_metadata_iohits);
c4c162c1
AM
7016 as->arcstat_prefetch_metadata_misses.value.ui64 =
7017 wmsum_value(&arc_sums.arcstat_prefetch_metadata_misses);
7018 as->arcstat_mru_hits.value.ui64 =
7019 wmsum_value(&arc_sums.arcstat_mru_hits);
7020 as->arcstat_mru_ghost_hits.value.ui64 =
7021 wmsum_value(&arc_sums.arcstat_mru_ghost_hits);
7022 as->arcstat_mfu_hits.value.ui64 =
7023 wmsum_value(&arc_sums.arcstat_mfu_hits);
7024 as->arcstat_mfu_ghost_hits.value.ui64 =
7025 wmsum_value(&arc_sums.arcstat_mfu_ghost_hits);
ed2f7ba0
AM
7026 as->arcstat_uncached_hits.value.ui64 =
7027 wmsum_value(&arc_sums.arcstat_uncached_hits);
c4c162c1
AM
7028 as->arcstat_deleted.value.ui64 =
7029 wmsum_value(&arc_sums.arcstat_deleted);
7030 as->arcstat_mutex_miss.value.ui64 =
7031 wmsum_value(&arc_sums.arcstat_mutex_miss);
7032 as->arcstat_access_skip.value.ui64 =
7033 wmsum_value(&arc_sums.arcstat_access_skip);
7034 as->arcstat_evict_skip.value.ui64 =
7035 wmsum_value(&arc_sums.arcstat_evict_skip);
7036 as->arcstat_evict_not_enough.value.ui64 =
7037 wmsum_value(&arc_sums.arcstat_evict_not_enough);
7038 as->arcstat_evict_l2_cached.value.ui64 =
7039 wmsum_value(&arc_sums.arcstat_evict_l2_cached);
7040 as->arcstat_evict_l2_eligible.value.ui64 =
7041 wmsum_value(&arc_sums.arcstat_evict_l2_eligible);
7042 as->arcstat_evict_l2_eligible_mfu.value.ui64 =
7043 wmsum_value(&arc_sums.arcstat_evict_l2_eligible_mfu);
7044 as->arcstat_evict_l2_eligible_mru.value.ui64 =
7045 wmsum_value(&arc_sums.arcstat_evict_l2_eligible_mru);
7046 as->arcstat_evict_l2_ineligible.value.ui64 =
7047 wmsum_value(&arc_sums.arcstat_evict_l2_ineligible);
7048 as->arcstat_evict_l2_skip.value.ui64 =
7049 wmsum_value(&arc_sums.arcstat_evict_l2_skip);
7050 as->arcstat_hash_collisions.value.ui64 =
7051 wmsum_value(&arc_sums.arcstat_hash_collisions);
7052 as->arcstat_hash_chains.value.ui64 =
7053 wmsum_value(&arc_sums.arcstat_hash_chains);
7054 as->arcstat_size.value.ui64 =
7055 aggsum_value(&arc_sums.arcstat_size);
7056 as->arcstat_compressed_size.value.ui64 =
7057 wmsum_value(&arc_sums.arcstat_compressed_size);
7058 as->arcstat_uncompressed_size.value.ui64 =
7059 wmsum_value(&arc_sums.arcstat_uncompressed_size);
7060 as->arcstat_overhead_size.value.ui64 =
7061 wmsum_value(&arc_sums.arcstat_overhead_size);
7062 as->arcstat_hdr_size.value.ui64 =
7063 wmsum_value(&arc_sums.arcstat_hdr_size);
7064 as->arcstat_data_size.value.ui64 =
7065 wmsum_value(&arc_sums.arcstat_data_size);
7066 as->arcstat_metadata_size.value.ui64 =
7067 wmsum_value(&arc_sums.arcstat_metadata_size);
7068 as->arcstat_dbuf_size.value.ui64 =
7069 wmsum_value(&arc_sums.arcstat_dbuf_size);
1c2725a1 7070#if defined(COMPAT_FREEBSD11)
c4c162c1
AM
7071 as->arcstat_other_size.value.ui64 =
7072 wmsum_value(&arc_sums.arcstat_bonus_size) +
a8d83e2a 7073 wmsum_value(&arc_sums.arcstat_dnode_size) +
c4c162c1 7074 wmsum_value(&arc_sums.arcstat_dbuf_size);
1c2725a1 7075#endif
37fb3e43 7076
c4c162c1
AM
7077 arc_kstat_update_state(arc_anon,
7078 &as->arcstat_anon_size,
a8d83e2a
AM
7079 &as->arcstat_anon_data,
7080 &as->arcstat_anon_metadata,
c4c162c1
AM
7081 &as->arcstat_anon_evictable_data,
7082 &as->arcstat_anon_evictable_metadata);
7083 arc_kstat_update_state(arc_mru,
7084 &as->arcstat_mru_size,
a8d83e2a
AM
7085 &as->arcstat_mru_data,
7086 &as->arcstat_mru_metadata,
c4c162c1
AM
7087 &as->arcstat_mru_evictable_data,
7088 &as->arcstat_mru_evictable_metadata);
7089 arc_kstat_update_state(arc_mru_ghost,
7090 &as->arcstat_mru_ghost_size,
a8d83e2a
AM
7091 &as->arcstat_mru_ghost_data,
7092 &as->arcstat_mru_ghost_metadata,
c4c162c1
AM
7093 &as->arcstat_mru_ghost_evictable_data,
7094 &as->arcstat_mru_ghost_evictable_metadata);
7095 arc_kstat_update_state(arc_mfu,
7096 &as->arcstat_mfu_size,
a8d83e2a
AM
7097 &as->arcstat_mfu_data,
7098 &as->arcstat_mfu_metadata,
c4c162c1
AM
7099 &as->arcstat_mfu_evictable_data,
7100 &as->arcstat_mfu_evictable_metadata);
7101 arc_kstat_update_state(arc_mfu_ghost,
7102 &as->arcstat_mfu_ghost_size,
a8d83e2a
AM
7103 &as->arcstat_mfu_ghost_data,
7104 &as->arcstat_mfu_ghost_metadata,
c4c162c1
AM
7105 &as->arcstat_mfu_ghost_evictable_data,
7106 &as->arcstat_mfu_ghost_evictable_metadata);
ed2f7ba0
AM
7107 arc_kstat_update_state(arc_uncached,
7108 &as->arcstat_uncached_size,
a8d83e2a
AM
7109 &as->arcstat_uncached_data,
7110 &as->arcstat_uncached_metadata,
ed2f7ba0
AM
7111 &as->arcstat_uncached_evictable_data,
7112 &as->arcstat_uncached_evictable_metadata);
c4c162c1
AM
7113
7114 as->arcstat_dnode_size.value.ui64 =
a8d83e2a 7115 wmsum_value(&arc_sums.arcstat_dnode_size);
c4c162c1
AM
7116 as->arcstat_bonus_size.value.ui64 =
7117 wmsum_value(&arc_sums.arcstat_bonus_size);
7118 as->arcstat_l2_hits.value.ui64 =
7119 wmsum_value(&arc_sums.arcstat_l2_hits);
7120 as->arcstat_l2_misses.value.ui64 =
7121 wmsum_value(&arc_sums.arcstat_l2_misses);
7122 as->arcstat_l2_prefetch_asize.value.ui64 =
7123 wmsum_value(&arc_sums.arcstat_l2_prefetch_asize);
7124 as->arcstat_l2_mru_asize.value.ui64 =
7125 wmsum_value(&arc_sums.arcstat_l2_mru_asize);
7126 as->arcstat_l2_mfu_asize.value.ui64 =
7127 wmsum_value(&arc_sums.arcstat_l2_mfu_asize);
7128 as->arcstat_l2_bufc_data_asize.value.ui64 =
7129 wmsum_value(&arc_sums.arcstat_l2_bufc_data_asize);
7130 as->arcstat_l2_bufc_metadata_asize.value.ui64 =
7131 wmsum_value(&arc_sums.arcstat_l2_bufc_metadata_asize);
7132 as->arcstat_l2_feeds.value.ui64 =
7133 wmsum_value(&arc_sums.arcstat_l2_feeds);
7134 as->arcstat_l2_rw_clash.value.ui64 =
7135 wmsum_value(&arc_sums.arcstat_l2_rw_clash);
7136 as->arcstat_l2_read_bytes.value.ui64 =
7137 wmsum_value(&arc_sums.arcstat_l2_read_bytes);
7138 as->arcstat_l2_write_bytes.value.ui64 =
7139 wmsum_value(&arc_sums.arcstat_l2_write_bytes);
7140 as->arcstat_l2_writes_sent.value.ui64 =
7141 wmsum_value(&arc_sums.arcstat_l2_writes_sent);
7142 as->arcstat_l2_writes_done.value.ui64 =
7143 wmsum_value(&arc_sums.arcstat_l2_writes_done);
7144 as->arcstat_l2_writes_error.value.ui64 =
7145 wmsum_value(&arc_sums.arcstat_l2_writes_error);
7146 as->arcstat_l2_writes_lock_retry.value.ui64 =
7147 wmsum_value(&arc_sums.arcstat_l2_writes_lock_retry);
7148 as->arcstat_l2_evict_lock_retry.value.ui64 =
7149 wmsum_value(&arc_sums.arcstat_l2_evict_lock_retry);
7150 as->arcstat_l2_evict_reading.value.ui64 =
7151 wmsum_value(&arc_sums.arcstat_l2_evict_reading);
7152 as->arcstat_l2_evict_l1cached.value.ui64 =
7153 wmsum_value(&arc_sums.arcstat_l2_evict_l1cached);
7154 as->arcstat_l2_free_on_write.value.ui64 =
7155 wmsum_value(&arc_sums.arcstat_l2_free_on_write);
7156 as->arcstat_l2_abort_lowmem.value.ui64 =
7157 wmsum_value(&arc_sums.arcstat_l2_abort_lowmem);
7158 as->arcstat_l2_cksum_bad.value.ui64 =
7159 wmsum_value(&arc_sums.arcstat_l2_cksum_bad);
7160 as->arcstat_l2_io_error.value.ui64 =
7161 wmsum_value(&arc_sums.arcstat_l2_io_error);
7162 as->arcstat_l2_lsize.value.ui64 =
7163 wmsum_value(&arc_sums.arcstat_l2_lsize);
7164 as->arcstat_l2_psize.value.ui64 =
7165 wmsum_value(&arc_sums.arcstat_l2_psize);
7166 as->arcstat_l2_hdr_size.value.ui64 =
7167 aggsum_value(&arc_sums.arcstat_l2_hdr_size);
7168 as->arcstat_l2_log_blk_writes.value.ui64 =
7169 wmsum_value(&arc_sums.arcstat_l2_log_blk_writes);
7170 as->arcstat_l2_log_blk_asize.value.ui64 =
7171 wmsum_value(&arc_sums.arcstat_l2_log_blk_asize);
7172 as->arcstat_l2_log_blk_count.value.ui64 =
7173 wmsum_value(&arc_sums.arcstat_l2_log_blk_count);
7174 as->arcstat_l2_rebuild_success.value.ui64 =
7175 wmsum_value(&arc_sums.arcstat_l2_rebuild_success);
7176 as->arcstat_l2_rebuild_abort_unsupported.value.ui64 =
7177 wmsum_value(&arc_sums.arcstat_l2_rebuild_abort_unsupported);
7178 as->arcstat_l2_rebuild_abort_io_errors.value.ui64 =
7179 wmsum_value(&arc_sums.arcstat_l2_rebuild_abort_io_errors);
7180 as->arcstat_l2_rebuild_abort_dh_errors.value.ui64 =
7181 wmsum_value(&arc_sums.arcstat_l2_rebuild_abort_dh_errors);
7182 as->arcstat_l2_rebuild_abort_cksum_lb_errors.value.ui64 =
7183 wmsum_value(&arc_sums.arcstat_l2_rebuild_abort_cksum_lb_errors);
7184 as->arcstat_l2_rebuild_abort_lowmem.value.ui64 =
7185 wmsum_value(&arc_sums.arcstat_l2_rebuild_abort_lowmem);
7186 as->arcstat_l2_rebuild_size.value.ui64 =
7187 wmsum_value(&arc_sums.arcstat_l2_rebuild_size);
7188 as->arcstat_l2_rebuild_asize.value.ui64 =
7189 wmsum_value(&arc_sums.arcstat_l2_rebuild_asize);
7190 as->arcstat_l2_rebuild_bufs.value.ui64 =
7191 wmsum_value(&arc_sums.arcstat_l2_rebuild_bufs);
7192 as->arcstat_l2_rebuild_bufs_precached.value.ui64 =
7193 wmsum_value(&arc_sums.arcstat_l2_rebuild_bufs_precached);
7194 as->arcstat_l2_rebuild_log_blks.value.ui64 =
7195 wmsum_value(&arc_sums.arcstat_l2_rebuild_log_blks);
7196 as->arcstat_memory_throttle_count.value.ui64 =
7197 wmsum_value(&arc_sums.arcstat_memory_throttle_count);
7198 as->arcstat_memory_direct_count.value.ui64 =
7199 wmsum_value(&arc_sums.arcstat_memory_direct_count);
7200 as->arcstat_memory_indirect_count.value.ui64 =
7201 wmsum_value(&arc_sums.arcstat_memory_indirect_count);
7202
7203 as->arcstat_memory_all_bytes.value.ui64 =
7204 arc_all_memory();
7205 as->arcstat_memory_free_bytes.value.ui64 =
7206 arc_free_memory();
7207 as->arcstat_memory_available_bytes.value.i64 =
7208 arc_available_memory();
7209
7210 as->arcstat_prune.value.ui64 =
7211 wmsum_value(&arc_sums.arcstat_prune);
7212 as->arcstat_meta_used.value.ui64 =
a8d83e2a 7213 wmsum_value(&arc_sums.arcstat_meta_used);
c4c162c1
AM
7214 as->arcstat_async_upgrade_sync.value.ui64 =
7215 wmsum_value(&arc_sums.arcstat_async_upgrade_sync);
c935fe2e
AM
7216 as->arcstat_predictive_prefetch.value.ui64 =
7217 wmsum_value(&arc_sums.arcstat_predictive_prefetch);
c4c162c1
AM
7218 as->arcstat_demand_hit_predictive_prefetch.value.ui64 =
7219 wmsum_value(&arc_sums.arcstat_demand_hit_predictive_prefetch);
c935fe2e
AM
7220 as->arcstat_demand_iohit_predictive_prefetch.value.ui64 =
7221 wmsum_value(&arc_sums.arcstat_demand_iohit_predictive_prefetch);
7222 as->arcstat_prescient_prefetch.value.ui64 =
7223 wmsum_value(&arc_sums.arcstat_prescient_prefetch);
c4c162c1
AM
7224 as->arcstat_demand_hit_prescient_prefetch.value.ui64 =
7225 wmsum_value(&arc_sums.arcstat_demand_hit_prescient_prefetch);
c935fe2e
AM
7226 as->arcstat_demand_iohit_prescient_prefetch.value.ui64 =
7227 wmsum_value(&arc_sums.arcstat_demand_iohit_prescient_prefetch);
c4c162c1
AM
7228 as->arcstat_raw_size.value.ui64 =
7229 wmsum_value(&arc_sums.arcstat_raw_size);
7230 as->arcstat_cached_only_in_progress.value.ui64 =
7231 wmsum_value(&arc_sums.arcstat_cached_only_in_progress);
7232 as->arcstat_abd_chunk_waste_size.value.ui64 =
7233 wmsum_value(&arc_sums.arcstat_abd_chunk_waste_size);
13be560d
BB
7234
7235 return (0);
7236}
7237
ca0bf58d
PS
7238/*
7239 * This function *must* return indices evenly distributed between all
7240 * sublists of the multilist. This is needed due to how the ARC eviction
7241 * code is laid out; arc_evict_state() assumes ARC buffers are evenly
7242 * distributed between all sublists and uses this assumption when
7243 * deciding which sublist to evict from and how much to evict from it.
7244 */
65c7cc49 7245static unsigned int
ca0bf58d
PS
7246arc_state_multilist_index_func(multilist_t *ml, void *obj)
7247{
7248 arc_buf_hdr_t *hdr = obj;
7249
7250 /*
7251 * We rely on b_dva to generate evenly distributed index
7252 * numbers using buf_hash below. So, as an added precaution,
7253 * let's make sure we never add empty buffers to the arc lists.
7254 */
d3c2ae1c 7255 ASSERT(!HDR_EMPTY(hdr));
ca0bf58d
PS
7256
7257 /*
7258 * The assumption here, is the hash value for a given
7259 * arc_buf_hdr_t will remain constant throughout its lifetime
7260 * (i.e. its b_spa, b_dva, and b_birth fields don't change).
7261 * Thus, we don't need to store the header's sublist index
7262 * on insertion, as this index can be recalculated on removal.
7263 *
7264 * Also, the low order bits of the hash value are thought to be
7265 * distributed evenly. Otherwise, in the case that the multilist
7266 * has a power of two number of sublists, each sublists' usage
5b7053a9
AM
7267 * would not be evenly distributed. In this context full 64bit
7268 * division would be a waste of time, so limit it to 32 bits.
ca0bf58d 7269 */
5b7053a9 7270 return ((unsigned int)buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
ca0bf58d
PS
7271 multilist_get_num_sublists(ml));
7272}
7273
bb7ad5d3
AM
7274static unsigned int
7275arc_state_l2c_multilist_index_func(multilist_t *ml, void *obj)
7276{
7277 panic("Header %p insert into arc_l2c_only %p", obj, ml);
7278}
7279
36a6e233
RM
7280#define WARN_IF_TUNING_IGNORED(tuning, value, do_warn) do { \
7281 if ((do_warn) && (tuning) && ((tuning) != (value))) { \
7282 cmn_err(CE_WARN, \
7283 "ignoring tunable %s (using %llu instead)", \
5dbf6c5a 7284 (#tuning), (u_longlong_t)(value)); \
36a6e233
RM
7285 } \
7286} while (0)
7287
ca67b33a
MA
7288/*
7289 * Called during module initialization and periodically thereafter to
e3570464 7290 * apply reasonable changes to the exposed performance tunings. Can also be
7291 * called explicitly by param_set_arc_*() functions when ARC tunables are
7292 * updated manually. Non-zero zfs_* values which differ from the currently set
7293 * values will be applied.
ca67b33a 7294 */
e3570464 7295void
36a6e233 7296arc_tuning_update(boolean_t verbose)
ca67b33a 7297{
b8a97fb1 7298 uint64_t allmem = arc_all_memory();
9edb3695 7299
36a6e233
RM
7300 /* Valid range: 32M - <arc_c_max> */
7301 if ((zfs_arc_min) && (zfs_arc_min != arc_c_min) &&
7302 (zfs_arc_min >= 2ULL << SPA_MAXBLOCKSHIFT) &&
7303 (zfs_arc_min <= arc_c_max)) {
7304 arc_c_min = zfs_arc_min;
7305 arc_c = MAX(arc_c, arc_c_min);
7306 }
7307 WARN_IF_TUNING_IGNORED(zfs_arc_min, arc_c_min, verbose);
7308
ca67b33a
MA
7309 /* Valid range: 64M - <all physical memory> */
7310 if ((zfs_arc_max) && (zfs_arc_max != arc_c_max) &&
e945e8d7 7311 (zfs_arc_max >= MIN_ARC_MAX) && (zfs_arc_max < allmem) &&
ca67b33a
MA
7312 (zfs_arc_max > arc_c_min)) {
7313 arc_c_max = zfs_arc_max;
17ca3018 7314 arc_c = MIN(arc_c, arc_c_max);
a8d83e2a
AM
7315 if (arc_dnode_limit > arc_c_max)
7316 arc_dnode_limit = arc_c_max;
ca67b33a 7317 }
36a6e233 7318 WARN_IF_TUNING_IGNORED(zfs_arc_max, arc_c_max, verbose);
ca67b33a 7319
a8d83e2a
AM
7320 /* Valid range: 0 - <all physical memory> */
7321 arc_dnode_limit = zfs_arc_dnode_limit ? zfs_arc_dnode_limit :
7322 MIN(zfs_arc_dnode_limit_percent, 100) * arc_c_max / 100;
7323 WARN_IF_TUNING_IGNORED(zfs_arc_dnode_limit, arc_dnode_limit, verbose);
25458cbe 7324
ca67b33a
MA
7325 /* Valid range: 1 - N */
7326 if (zfs_arc_grow_retry)
7327 arc_grow_retry = zfs_arc_grow_retry;
7328
7329 /* Valid range: 1 - N */
7330 if (zfs_arc_shrink_shift) {
7331 arc_shrink_shift = zfs_arc_shrink_shift;
7332 arc_no_grow_shift = MIN(arc_no_grow_shift, arc_shrink_shift -1);
7333 }
7334
d4a72f23
TC
7335 /* Valid range: 1 - N ms */
7336 if (zfs_arc_min_prefetch_ms)
7337 arc_min_prefetch_ms = zfs_arc_min_prefetch_ms;
7338
7339 /* Valid range: 1 - N ms */
7340 if (zfs_arc_min_prescient_prefetch_ms) {
7341 arc_min_prescient_prefetch_ms =
7342 zfs_arc_min_prescient_prefetch_ms;
7343 }
11f552fa 7344
7e8bddd0 7345 /* Valid range: 0 - 100 */
fdc2d303 7346 if (zfs_arc_lotsfree_percent <= 100)
7e8bddd0 7347 arc_lotsfree_percent = zfs_arc_lotsfree_percent;
36a6e233
RM
7348 WARN_IF_TUNING_IGNORED(zfs_arc_lotsfree_percent, arc_lotsfree_percent,
7349 verbose);
7e8bddd0 7350
11f552fa
BB
7351 /* Valid range: 0 - <all physical memory> */
7352 if ((zfs_arc_sys_free) && (zfs_arc_sys_free != arc_sys_free))
8ef15f93 7353 arc_sys_free = MIN(zfs_arc_sys_free, allmem);
36a6e233 7354 WARN_IF_TUNING_IGNORED(zfs_arc_sys_free, arc_sys_free, verbose);
ca67b33a
MA
7355}
7356
6e2a5918
MJ
7357static void
7358arc_state_multilist_init(multilist_t *ml,
7359 multilist_sublist_index_func_t *index_func, int *maxcountp)
7360{
7361 multilist_create(ml, sizeof (arc_buf_hdr_t),
7362 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node), index_func);
7363 *maxcountp = MAX(*maxcountp, multilist_get_num_sublists(ml));
7364}
7365
d3c2ae1c
GW
7366static void
7367arc_state_init(void)
7368{
6e2a5918
MJ
7369 int num_sublists = 0;
7370
7371 arc_state_multilist_init(&arc_mru->arcs_list[ARC_BUFC_METADATA],
7372 arc_state_multilist_index_func, &num_sublists);
7373 arc_state_multilist_init(&arc_mru->arcs_list[ARC_BUFC_DATA],
7374 arc_state_multilist_index_func, &num_sublists);
7375 arc_state_multilist_init(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
7376 arc_state_multilist_index_func, &num_sublists);
7377 arc_state_multilist_init(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
7378 arc_state_multilist_index_func, &num_sublists);
7379 arc_state_multilist_init(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
7380 arc_state_multilist_index_func, &num_sublists);
7381 arc_state_multilist_init(&arc_mfu->arcs_list[ARC_BUFC_DATA],
7382 arc_state_multilist_index_func, &num_sublists);
7383 arc_state_multilist_init(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
7384 arc_state_multilist_index_func, &num_sublists);
7385 arc_state_multilist_init(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
7386 arc_state_multilist_index_func, &num_sublists);
ed2f7ba0
AM
7387 arc_state_multilist_init(&arc_uncached->arcs_list[ARC_BUFC_METADATA],
7388 arc_state_multilist_index_func, &num_sublists);
7389 arc_state_multilist_init(&arc_uncached->arcs_list[ARC_BUFC_DATA],
7390 arc_state_multilist_index_func, &num_sublists);
6e2a5918 7391
bb7ad5d3
AM
7392 /*
7393 * L2 headers should never be on the L2 state list since they don't
7394 * have L1 headers allocated. Special index function asserts that.
7395 */
6e2a5918
MJ
7396 arc_state_multilist_init(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
7397 arc_state_l2c_multilist_index_func, &num_sublists);
7398 arc_state_multilist_init(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
7399 arc_state_l2c_multilist_index_func, &num_sublists);
7400
7401 /*
7402 * Keep track of the number of markers needed to reclaim buffers from
7403 * any ARC state. The markers will be pre-allocated so as to minimize
7404 * the number of memory allocations performed by the eviction thread.
7405 */
7406 arc_state_evict_marker_count = num_sublists;
d3c2ae1c 7407
424fd7c3
TS
7408 zfs_refcount_create(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
7409 zfs_refcount_create(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
7410 zfs_refcount_create(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
7411 zfs_refcount_create(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
7412 zfs_refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
7413 zfs_refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
7414 zfs_refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
7415 zfs_refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
7416 zfs_refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
7417 zfs_refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
7418 zfs_refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
7419 zfs_refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
ed2f7ba0
AM
7420 zfs_refcount_create(&arc_uncached->arcs_esize[ARC_BUFC_METADATA]);
7421 zfs_refcount_create(&arc_uncached->arcs_esize[ARC_BUFC_DATA]);
424fd7c3 7422
a8d83e2a
AM
7423 zfs_refcount_create(&arc_anon->arcs_size[ARC_BUFC_DATA]);
7424 zfs_refcount_create(&arc_anon->arcs_size[ARC_BUFC_METADATA]);
7425 zfs_refcount_create(&arc_mru->arcs_size[ARC_BUFC_DATA]);
7426 zfs_refcount_create(&arc_mru->arcs_size[ARC_BUFC_METADATA]);
7427 zfs_refcount_create(&arc_mru_ghost->arcs_size[ARC_BUFC_DATA]);
7428 zfs_refcount_create(&arc_mru_ghost->arcs_size[ARC_BUFC_METADATA]);
7429 zfs_refcount_create(&arc_mfu->arcs_size[ARC_BUFC_DATA]);
7430 zfs_refcount_create(&arc_mfu->arcs_size[ARC_BUFC_METADATA]);
7431 zfs_refcount_create(&arc_mfu_ghost->arcs_size[ARC_BUFC_DATA]);
7432 zfs_refcount_create(&arc_mfu_ghost->arcs_size[ARC_BUFC_METADATA]);
7433 zfs_refcount_create(&arc_l2c_only->arcs_size[ARC_BUFC_DATA]);
7434 zfs_refcount_create(&arc_l2c_only->arcs_size[ARC_BUFC_METADATA]);
7435 zfs_refcount_create(&arc_uncached->arcs_size[ARC_BUFC_DATA]);
7436 zfs_refcount_create(&arc_uncached->arcs_size[ARC_BUFC_METADATA]);
7437
7438 wmsum_init(&arc_mru_ghost->arcs_hits[ARC_BUFC_DATA], 0);
7439 wmsum_init(&arc_mru_ghost->arcs_hits[ARC_BUFC_METADATA], 0);
7440 wmsum_init(&arc_mfu_ghost->arcs_hits[ARC_BUFC_DATA], 0);
7441 wmsum_init(&arc_mfu_ghost->arcs_hits[ARC_BUFC_METADATA], 0);
d3c2ae1c 7442
c4c162c1 7443 wmsum_init(&arc_sums.arcstat_hits, 0);
c935fe2e 7444 wmsum_init(&arc_sums.arcstat_iohits, 0);
c4c162c1
AM
7445 wmsum_init(&arc_sums.arcstat_misses, 0);
7446 wmsum_init(&arc_sums.arcstat_demand_data_hits, 0);
c935fe2e 7447 wmsum_init(&arc_sums.arcstat_demand_data_iohits, 0);
c4c162c1
AM
7448 wmsum_init(&arc_sums.arcstat_demand_data_misses, 0);
7449 wmsum_init(&arc_sums.arcstat_demand_metadata_hits, 0);
c935fe2e 7450 wmsum_init(&arc_sums.arcstat_demand_metadata_iohits, 0);
c4c162c1
AM
7451 wmsum_init(&arc_sums.arcstat_demand_metadata_misses, 0);
7452 wmsum_init(&arc_sums.arcstat_prefetch_data_hits, 0);
c935fe2e 7453 wmsum_init(&arc_sums.arcstat_prefetch_data_iohits, 0);
c4c162c1
AM
7454 wmsum_init(&arc_sums.arcstat_prefetch_data_misses, 0);
7455 wmsum_init(&arc_sums.arcstat_prefetch_metadata_hits, 0);
c935fe2e 7456 wmsum_init(&arc_sums.arcstat_prefetch_metadata_iohits, 0);
c4c162c1
AM
7457 wmsum_init(&arc_sums.arcstat_prefetch_metadata_misses, 0);
7458 wmsum_init(&arc_sums.arcstat_mru_hits, 0);
7459 wmsum_init(&arc_sums.arcstat_mru_ghost_hits, 0);
7460 wmsum_init(&arc_sums.arcstat_mfu_hits, 0);
7461 wmsum_init(&arc_sums.arcstat_mfu_ghost_hits, 0);
ed2f7ba0 7462 wmsum_init(&arc_sums.arcstat_uncached_hits, 0);
c4c162c1
AM
7463 wmsum_init(&arc_sums.arcstat_deleted, 0);
7464 wmsum_init(&arc_sums.arcstat_mutex_miss, 0);
7465 wmsum_init(&arc_sums.arcstat_access_skip, 0);
7466 wmsum_init(&arc_sums.arcstat_evict_skip, 0);
7467 wmsum_init(&arc_sums.arcstat_evict_not_enough, 0);
7468 wmsum_init(&arc_sums.arcstat_evict_l2_cached, 0);
7469 wmsum_init(&arc_sums.arcstat_evict_l2_eligible, 0);
7470 wmsum_init(&arc_sums.arcstat_evict_l2_eligible_mfu, 0);
7471 wmsum_init(&arc_sums.arcstat_evict_l2_eligible_mru, 0);
7472 wmsum_init(&arc_sums.arcstat_evict_l2_ineligible, 0);
7473 wmsum_init(&arc_sums.arcstat_evict_l2_skip, 0);
7474 wmsum_init(&arc_sums.arcstat_hash_collisions, 0);
7475 wmsum_init(&arc_sums.arcstat_hash_chains, 0);
7476 aggsum_init(&arc_sums.arcstat_size, 0);
7477 wmsum_init(&arc_sums.arcstat_compressed_size, 0);
7478 wmsum_init(&arc_sums.arcstat_uncompressed_size, 0);
7479 wmsum_init(&arc_sums.arcstat_overhead_size, 0);
7480 wmsum_init(&arc_sums.arcstat_hdr_size, 0);
7481 wmsum_init(&arc_sums.arcstat_data_size, 0);
7482 wmsum_init(&arc_sums.arcstat_metadata_size, 0);
7483 wmsum_init(&arc_sums.arcstat_dbuf_size, 0);
a8d83e2a 7484 wmsum_init(&arc_sums.arcstat_dnode_size, 0);
c4c162c1
AM
7485 wmsum_init(&arc_sums.arcstat_bonus_size, 0);
7486 wmsum_init(&arc_sums.arcstat_l2_hits, 0);
7487 wmsum_init(&arc_sums.arcstat_l2_misses, 0);
7488 wmsum_init(&arc_sums.arcstat_l2_prefetch_asize, 0);
7489 wmsum_init(&arc_sums.arcstat_l2_mru_asize, 0);
7490 wmsum_init(&arc_sums.arcstat_l2_mfu_asize, 0);
7491 wmsum_init(&arc_sums.arcstat_l2_bufc_data_asize, 0);
7492 wmsum_init(&arc_sums.arcstat_l2_bufc_metadata_asize, 0);
7493 wmsum_init(&arc_sums.arcstat_l2_feeds, 0);
7494 wmsum_init(&arc_sums.arcstat_l2_rw_clash, 0);
7495 wmsum_init(&arc_sums.arcstat_l2_read_bytes, 0);
7496 wmsum_init(&arc_sums.arcstat_l2_write_bytes, 0);
7497 wmsum_init(&arc_sums.arcstat_l2_writes_sent, 0);
7498 wmsum_init(&arc_sums.arcstat_l2_writes_done, 0);
7499 wmsum_init(&arc_sums.arcstat_l2_writes_error, 0);
7500 wmsum_init(&arc_sums.arcstat_l2_writes_lock_retry, 0);
7501 wmsum_init(&arc_sums.arcstat_l2_evict_lock_retry, 0);
7502 wmsum_init(&arc_sums.arcstat_l2_evict_reading, 0);
7503 wmsum_init(&arc_sums.arcstat_l2_evict_l1cached, 0);
7504 wmsum_init(&arc_sums.arcstat_l2_free_on_write, 0);
7505 wmsum_init(&arc_sums.arcstat_l2_abort_lowmem, 0);
7506 wmsum_init(&arc_sums.arcstat_l2_cksum_bad, 0);
7507 wmsum_init(&arc_sums.arcstat_l2_io_error, 0);
7508 wmsum_init(&arc_sums.arcstat_l2_lsize, 0);
7509 wmsum_init(&arc_sums.arcstat_l2_psize, 0);
7510 aggsum_init(&arc_sums.arcstat_l2_hdr_size, 0);
7511 wmsum_init(&arc_sums.arcstat_l2_log_blk_writes, 0);
7512 wmsum_init(&arc_sums.arcstat_l2_log_blk_asize, 0);
7513 wmsum_init(&arc_sums.arcstat_l2_log_blk_count, 0);
7514 wmsum_init(&arc_sums.arcstat_l2_rebuild_success, 0);
7515 wmsum_init(&arc_sums.arcstat_l2_rebuild_abort_unsupported, 0);
7516 wmsum_init(&arc_sums.arcstat_l2_rebuild_abort_io_errors, 0);
7517 wmsum_init(&arc_sums.arcstat_l2_rebuild_abort_dh_errors, 0);
7518 wmsum_init(&arc_sums.arcstat_l2_rebuild_abort_cksum_lb_errors, 0);
7519 wmsum_init(&arc_sums.arcstat_l2_rebuild_abort_lowmem, 0);
7520 wmsum_init(&arc_sums.arcstat_l2_rebuild_size, 0);
7521 wmsum_init(&arc_sums.arcstat_l2_rebuild_asize, 0);
7522 wmsum_init(&arc_sums.arcstat_l2_rebuild_bufs, 0);
7523 wmsum_init(&arc_sums.arcstat_l2_rebuild_bufs_precached, 0);
7524 wmsum_init(&arc_sums.arcstat_l2_rebuild_log_blks, 0);
7525 wmsum_init(&arc_sums.arcstat_memory_throttle_count, 0);
7526 wmsum_init(&arc_sums.arcstat_memory_direct_count, 0);
7527 wmsum_init(&arc_sums.arcstat_memory_indirect_count, 0);
7528 wmsum_init(&arc_sums.arcstat_prune, 0);
a8d83e2a 7529 wmsum_init(&arc_sums.arcstat_meta_used, 0);
c4c162c1 7530 wmsum_init(&arc_sums.arcstat_async_upgrade_sync, 0);
c935fe2e 7531 wmsum_init(&arc_sums.arcstat_predictive_prefetch, 0);
c4c162c1 7532 wmsum_init(&arc_sums.arcstat_demand_hit_predictive_prefetch, 0);
c935fe2e
AM
7533 wmsum_init(&arc_sums.arcstat_demand_iohit_predictive_prefetch, 0);
7534 wmsum_init(&arc_sums.arcstat_prescient_prefetch, 0);
c4c162c1 7535 wmsum_init(&arc_sums.arcstat_demand_hit_prescient_prefetch, 0);
c935fe2e 7536 wmsum_init(&arc_sums.arcstat_demand_iohit_prescient_prefetch, 0);
c4c162c1
AM
7537 wmsum_init(&arc_sums.arcstat_raw_size, 0);
7538 wmsum_init(&arc_sums.arcstat_cached_only_in_progress, 0);
7539 wmsum_init(&arc_sums.arcstat_abd_chunk_waste_size, 0);
37fb3e43 7540
d3c2ae1c
GW
7541 arc_anon->arcs_state = ARC_STATE_ANON;
7542 arc_mru->arcs_state = ARC_STATE_MRU;
7543 arc_mru_ghost->arcs_state = ARC_STATE_MRU_GHOST;
7544 arc_mfu->arcs_state = ARC_STATE_MFU;
7545 arc_mfu_ghost->arcs_state = ARC_STATE_MFU_GHOST;
7546 arc_l2c_only->arcs_state = ARC_STATE_L2C_ONLY;
ed2f7ba0 7547 arc_uncached->arcs_state = ARC_STATE_UNCACHED;
d3c2ae1c
GW
7548}
7549
7550static void
7551arc_state_fini(void)
7552{
424fd7c3
TS
7553 zfs_refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
7554 zfs_refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
7555 zfs_refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
7556 zfs_refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
7557 zfs_refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
7558 zfs_refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
7559 zfs_refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
7560 zfs_refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
7561 zfs_refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
7562 zfs_refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
7563 zfs_refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
7564 zfs_refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
ed2f7ba0
AM
7565 zfs_refcount_destroy(&arc_uncached->arcs_esize[ARC_BUFC_METADATA]);
7566 zfs_refcount_destroy(&arc_uncached->arcs_esize[ARC_BUFC_DATA]);
424fd7c3 7567
a8d83e2a
AM
7568 zfs_refcount_destroy(&arc_anon->arcs_size[ARC_BUFC_DATA]);
7569 zfs_refcount_destroy(&arc_anon->arcs_size[ARC_BUFC_METADATA]);
7570 zfs_refcount_destroy(&arc_mru->arcs_size[ARC_BUFC_DATA]);
7571 zfs_refcount_destroy(&arc_mru->arcs_size[ARC_BUFC_METADATA]);
7572 zfs_refcount_destroy(&arc_mru_ghost->arcs_size[ARC_BUFC_DATA]);
7573 zfs_refcount_destroy(&arc_mru_ghost->arcs_size[ARC_BUFC_METADATA]);
7574 zfs_refcount_destroy(&arc_mfu->arcs_size[ARC_BUFC_DATA]);
7575 zfs_refcount_destroy(&arc_mfu->arcs_size[ARC_BUFC_METADATA]);
7576 zfs_refcount_destroy(&arc_mfu_ghost->arcs_size[ARC_BUFC_DATA]);
7577 zfs_refcount_destroy(&arc_mfu_ghost->arcs_size[ARC_BUFC_METADATA]);
7578 zfs_refcount_destroy(&arc_l2c_only->arcs_size[ARC_BUFC_DATA]);
7579 zfs_refcount_destroy(&arc_l2c_only->arcs_size[ARC_BUFC_METADATA]);
7580 zfs_refcount_destroy(&arc_uncached->arcs_size[ARC_BUFC_DATA]);
7581 zfs_refcount_destroy(&arc_uncached->arcs_size[ARC_BUFC_METADATA]);
d3c2ae1c 7582
ffdf019c
AM
7583 multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
7584 multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
7585 multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
7586 multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
7587 multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
7588 multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
7589 multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
7590 multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
7591 multilist_destroy(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA]);
7592 multilist_destroy(&arc_l2c_only->arcs_list[ARC_BUFC_DATA]);
ed2f7ba0
AM
7593 multilist_destroy(&arc_uncached->arcs_list[ARC_BUFC_METADATA]);
7594 multilist_destroy(&arc_uncached->arcs_list[ARC_BUFC_DATA]);
37fb3e43 7595
a8d83e2a
AM
7596 wmsum_fini(&arc_mru_ghost->arcs_hits[ARC_BUFC_DATA]);
7597 wmsum_fini(&arc_mru_ghost->arcs_hits[ARC_BUFC_METADATA]);
7598 wmsum_fini(&arc_mfu_ghost->arcs_hits[ARC_BUFC_DATA]);
7599 wmsum_fini(&arc_mfu_ghost->arcs_hits[ARC_BUFC_METADATA]);
7600
c4c162c1 7601 wmsum_fini(&arc_sums.arcstat_hits);
c935fe2e 7602 wmsum_fini(&arc_sums.arcstat_iohits);
c4c162c1
AM
7603 wmsum_fini(&arc_sums.arcstat_misses);
7604 wmsum_fini(&arc_sums.arcstat_demand_data_hits);
c935fe2e 7605 wmsum_fini(&arc_sums.arcstat_demand_data_iohits);
c4c162c1
AM
7606 wmsum_fini(&arc_sums.arcstat_demand_data_misses);
7607 wmsum_fini(&arc_sums.arcstat_demand_metadata_hits);
c935fe2e 7608 wmsum_fini(&arc_sums.arcstat_demand_metadata_iohits);
c4c162c1
AM
7609 wmsum_fini(&arc_sums.arcstat_demand_metadata_misses);
7610 wmsum_fini(&arc_sums.arcstat_prefetch_data_hits);
c935fe2e 7611 wmsum_fini(&arc_sums.arcstat_prefetch_data_iohits);
c4c162c1
AM
7612 wmsum_fini(&arc_sums.arcstat_prefetch_data_misses);
7613 wmsum_fini(&arc_sums.arcstat_prefetch_metadata_hits);
c935fe2e 7614 wmsum_fini(&arc_sums.arcstat_prefetch_metadata_iohits);
c4c162c1
AM
7615 wmsum_fini(&arc_sums.arcstat_prefetch_metadata_misses);
7616 wmsum_fini(&arc_sums.arcstat_mru_hits);
7617 wmsum_fini(&arc_sums.arcstat_mru_ghost_hits);
7618 wmsum_fini(&arc_sums.arcstat_mfu_hits);
7619 wmsum_fini(&arc_sums.arcstat_mfu_ghost_hits);
ed2f7ba0 7620 wmsum_fini(&arc_sums.arcstat_uncached_hits);
c4c162c1
AM
7621 wmsum_fini(&arc_sums.arcstat_deleted);
7622 wmsum_fini(&arc_sums.arcstat_mutex_miss);
7623 wmsum_fini(&arc_sums.arcstat_access_skip);
7624 wmsum_fini(&arc_sums.arcstat_evict_skip);
7625 wmsum_fini(&arc_sums.arcstat_evict_not_enough);
7626 wmsum_fini(&arc_sums.arcstat_evict_l2_cached);
7627 wmsum_fini(&arc_sums.arcstat_evict_l2_eligible);
7628 wmsum_fini(&arc_sums.arcstat_evict_l2_eligible_mfu);
7629 wmsum_fini(&arc_sums.arcstat_evict_l2_eligible_mru);
7630 wmsum_fini(&arc_sums.arcstat_evict_l2_ineligible);
7631 wmsum_fini(&arc_sums.arcstat_evict_l2_skip);
7632 wmsum_fini(&arc_sums.arcstat_hash_collisions);
7633 wmsum_fini(&arc_sums.arcstat_hash_chains);
7634 aggsum_fini(&arc_sums.arcstat_size);
7635 wmsum_fini(&arc_sums.arcstat_compressed_size);
7636 wmsum_fini(&arc_sums.arcstat_uncompressed_size);
7637 wmsum_fini(&arc_sums.arcstat_overhead_size);
7638 wmsum_fini(&arc_sums.arcstat_hdr_size);
7639 wmsum_fini(&arc_sums.arcstat_data_size);
7640 wmsum_fini(&arc_sums.arcstat_metadata_size);
7641 wmsum_fini(&arc_sums.arcstat_dbuf_size);
a8d83e2a 7642 wmsum_fini(&arc_sums.arcstat_dnode_size);
c4c162c1
AM
7643 wmsum_fini(&arc_sums.arcstat_bonus_size);
7644 wmsum_fini(&arc_sums.arcstat_l2_hits);
7645 wmsum_fini(&arc_sums.arcstat_l2_misses);
7646 wmsum_fini(&arc_sums.arcstat_l2_prefetch_asize);
7647 wmsum_fini(&arc_sums.arcstat_l2_mru_asize);
7648 wmsum_fini(&arc_sums.arcstat_l2_mfu_asize);
7649 wmsum_fini(&arc_sums.arcstat_l2_bufc_data_asize);
7650 wmsum_fini(&arc_sums.arcstat_l2_bufc_metadata_asize);
7651 wmsum_fini(&arc_sums.arcstat_l2_feeds);
7652 wmsum_fini(&arc_sums.arcstat_l2_rw_clash);
7653 wmsum_fini(&arc_sums.arcstat_l2_read_bytes);
7654 wmsum_fini(&arc_sums.arcstat_l2_write_bytes);
7655 wmsum_fini(&arc_sums.arcstat_l2_writes_sent);
7656 wmsum_fini(&arc_sums.arcstat_l2_writes_done);
7657 wmsum_fini(&arc_sums.arcstat_l2_writes_error);
7658 wmsum_fini(&arc_sums.arcstat_l2_writes_lock_retry);
7659 wmsum_fini(&arc_sums.arcstat_l2_evict_lock_retry);
7660 wmsum_fini(&arc_sums.arcstat_l2_evict_reading);
7661 wmsum_fini(&arc_sums.arcstat_l2_evict_l1cached);
7662 wmsum_fini(&arc_sums.arcstat_l2_free_on_write);
7663 wmsum_fini(&arc_sums.arcstat_l2_abort_lowmem);
7664 wmsum_fini(&arc_sums.arcstat_l2_cksum_bad);
7665 wmsum_fini(&arc_sums.arcstat_l2_io_error);
7666 wmsum_fini(&arc_sums.arcstat_l2_lsize);
7667 wmsum_fini(&arc_sums.arcstat_l2_psize);
7668 aggsum_fini(&arc_sums.arcstat_l2_hdr_size);
7669 wmsum_fini(&arc_sums.arcstat_l2_log_blk_writes);
7670 wmsum_fini(&arc_sums.arcstat_l2_log_blk_asize);
7671 wmsum_fini(&arc_sums.arcstat_l2_log_blk_count);
7672 wmsum_fini(&arc_sums.arcstat_l2_rebuild_success);
7673 wmsum_fini(&arc_sums.arcstat_l2_rebuild_abort_unsupported);
7674 wmsum_fini(&arc_sums.arcstat_l2_rebuild_abort_io_errors);
7675 wmsum_fini(&arc_sums.arcstat_l2_rebuild_abort_dh_errors);
7676 wmsum_fini(&arc_sums.arcstat_l2_rebuild_abort_cksum_lb_errors);
7677 wmsum_fini(&arc_sums.arcstat_l2_rebuild_abort_lowmem);
7678 wmsum_fini(&arc_sums.arcstat_l2_rebuild_size);
7679 wmsum_fini(&arc_sums.arcstat_l2_rebuild_asize);
7680 wmsum_fini(&arc_sums.arcstat_l2_rebuild_bufs);
7681 wmsum_fini(&arc_sums.arcstat_l2_rebuild_bufs_precached);
7682 wmsum_fini(&arc_sums.arcstat_l2_rebuild_log_blks);
7683 wmsum_fini(&arc_sums.arcstat_memory_throttle_count);
7684 wmsum_fini(&arc_sums.arcstat_memory_direct_count);
7685 wmsum_fini(&arc_sums.arcstat_memory_indirect_count);
7686 wmsum_fini(&arc_sums.arcstat_prune);
a8d83e2a 7687 wmsum_fini(&arc_sums.arcstat_meta_used);
c4c162c1 7688 wmsum_fini(&arc_sums.arcstat_async_upgrade_sync);
c935fe2e 7689 wmsum_fini(&arc_sums.arcstat_predictive_prefetch);
c4c162c1 7690 wmsum_fini(&arc_sums.arcstat_demand_hit_predictive_prefetch);
c935fe2e
AM
7691 wmsum_fini(&arc_sums.arcstat_demand_iohit_predictive_prefetch);
7692 wmsum_fini(&arc_sums.arcstat_prescient_prefetch);
c4c162c1 7693 wmsum_fini(&arc_sums.arcstat_demand_hit_prescient_prefetch);
c935fe2e 7694 wmsum_fini(&arc_sums.arcstat_demand_iohit_prescient_prefetch);
c4c162c1
AM
7695 wmsum_fini(&arc_sums.arcstat_raw_size);
7696 wmsum_fini(&arc_sums.arcstat_cached_only_in_progress);
7697 wmsum_fini(&arc_sums.arcstat_abd_chunk_waste_size);
d3c2ae1c
GW
7698}
7699
7700uint64_t
e71cade6 7701arc_target_bytes(void)
d3c2ae1c 7702{
e71cade6 7703 return (arc_c);
d3c2ae1c
GW
7704}
7705
60a4c7d2
PD
7706void
7707arc_set_limits(uint64_t allmem)
7708{
7709 /* Set min cache to 1/32 of all memory, or 32MB, whichever is more. */
7710 arc_c_min = MAX(allmem / 32, 2ULL << SPA_MAXBLOCKSHIFT);
7711
7712 /* How to set default max varies by platform. */
7713 arc_c_max = arc_default_max(arc_c_min, allmem);
7714}
34dc7c2f
BB
7715void
7716arc_init(void)
7717{
9edb3695 7718 uint64_t percent, allmem = arc_all_memory();
5dd92909 7719 mutex_init(&arc_evict_lock, NULL, MUTEX_DEFAULT, NULL);
3442c2a0
MA
7720 list_create(&arc_evict_waiters, sizeof (arc_evict_waiter_t),
7721 offsetof(arc_evict_waiter_t, aew_node));
ca0bf58d 7722
2b84817f
TC
7723 arc_min_prefetch_ms = 1000;
7724 arc_min_prescient_prefetch_ms = 6000;
34dc7c2f 7725
c9c9c1e2
MM
7726#if defined(_KERNEL)
7727 arc_lowmem_init();
34dc7c2f
BB
7728#endif
7729
60a4c7d2 7730 arc_set_limits(allmem);
9a51738b 7731
e945e8d7
AJ
7732#ifdef _KERNEL
7733 /*
7734 * If zfs_arc_max is non-zero at init, meaning it was set in the kernel
7735 * environment before the module was loaded, don't block setting the
7736 * maximum because it is less than arc_c_min, instead, reset arc_c_min
7737 * to a lower value.
7738 * zfs_arc_min will be handled by arc_tuning_update().
7739 */
7740 if (zfs_arc_max != 0 && zfs_arc_max >= MIN_ARC_MAX &&
7741 zfs_arc_max < allmem) {
7742 arc_c_max = zfs_arc_max;
7743 if (arc_c_min >= arc_c_max) {
7744 arc_c_min = MAX(zfs_arc_max / 2,
7745 2ULL << SPA_MAXBLOCKSHIFT);
7746 }
7747 }
7748#else
ab5cbbd1
BB
7749 /*
7750 * In userland, there's only the memory pressure that we artificially
7751 * create (see arc_available_memory()). Don't let arc_c get too
7752 * small, because it can cause transactions to be larger than
7753 * arc_c, causing arc_tempreserve_space() to fail.
7754 */
0a1f8cd9 7755 arc_c_min = MAX(arc_c_max / 2, 2ULL << SPA_MAXBLOCKSHIFT);
ab5cbbd1
BB
7756#endif
7757
17ca3018 7758 arc_c = arc_c_min;
9907cc1c 7759 /*
a8d83e2a
AM
7760 * 32-bit fixed point fractions of metadata from total ARC size,
7761 * MRU data from all data and MRU metadata from all metadata.
9907cc1c 7762 */
a8d83e2a
AM
7763 arc_meta = (1ULL << 32) / 4; /* Metadata is 25% of arc_c. */
7764 arc_pd = (1ULL << 32) / 2; /* Data MRU is 50% of data. */
7765 arc_pm = (1ULL << 32) / 2; /* Metadata MRU is 50% of metadata. */
7766
9907cc1c 7767 percent = MIN(zfs_arc_dnode_limit_percent, 100);
a8d83e2a 7768 arc_dnode_limit = arc_c_max * percent / 100;
34dc7c2f 7769
ca67b33a 7770 /* Apply user specified tunings */
36a6e233 7771 arc_tuning_update(B_TRUE);
c52fca13 7772
34dc7c2f
BB
7773 /* if kmem_flags are set, lets try to use less memory */
7774 if (kmem_debugging())
7775 arc_c = arc_c / 2;
7776 if (arc_c < arc_c_min)
7777 arc_c = arc_c_min;
7778
60a4c7d2
PD
7779 arc_register_hotplug();
7780
d3c2ae1c 7781 arc_state_init();
3ec34e55 7782
34dc7c2f
BB
7783 buf_init();
7784
ab26409d
BB
7785 list_create(&arc_prune_list, sizeof (arc_prune_t),
7786 offsetof(arc_prune_t, p_node));
ab26409d 7787 mutex_init(&arc_prune_mtx, NULL, MUTEX_DEFAULT, NULL);
34dc7c2f 7788
462217d1
AM
7789 arc_prune_taskq = taskq_create("arc_prune", zfs_arc_prune_task_threads,
7790 defclsyspri, 100, INT_MAX, TASKQ_PREPOPULATE | TASKQ_DYNAMIC);
f6046738 7791
34dc7c2f
BB
7792 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
7793 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
7794
7795 if (arc_ksp != NULL) {
7796 arc_ksp->ks_data = &arc_stats;
13be560d 7797 arc_ksp->ks_update = arc_kstat_update;
34dc7c2f
BB
7798 kstat_install(arc_ksp);
7799 }
7800
6e2a5918
MJ
7801 arc_state_evict_markers =
7802 arc_state_alloc_markers(arc_state_evict_marker_count);
ed2f7ba0
AM
7803 arc_evict_zthr = zthr_create_timer("arc_evict",
7804 arc_evict_cb_check, arc_evict_cb, NULL, SEC2NSEC(1), defclsyspri);
843e9ca2 7805 arc_reap_zthr = zthr_create_timer("arc_reap",
6bc61d22 7806 arc_reap_cb_check, arc_reap_cb, NULL, SEC2NSEC(1), minclsyspri);
34dc7c2f 7807
b128c09f 7808 arc_warm = B_FALSE;
34dc7c2f 7809
e8b96c60
MA
7810 /*
7811 * Calculate maximum amount of dirty data per pool.
7812 *
7813 * If it has been set by a module parameter, take that.
7814 * Otherwise, use a percentage of physical memory defined by
7815 * zfs_dirty_data_max_percent (default 10%) with a cap at
e99932f7 7816 * zfs_dirty_data_max_max (default 4G or 25% of physical memory).
e8b96c60 7817 */
47ed79ff 7818#ifdef __LP64__
e8b96c60 7819 if (zfs_dirty_data_max_max == 0)
e99932f7
BB
7820 zfs_dirty_data_max_max = MIN(4ULL * 1024 * 1024 * 1024,
7821 allmem * zfs_dirty_data_max_max_percent / 100);
47ed79ff
MM
7822#else
7823 if (zfs_dirty_data_max_max == 0)
7824 zfs_dirty_data_max_max = MIN(1ULL * 1024 * 1024 * 1024,
7825 allmem * zfs_dirty_data_max_max_percent / 100);
7826#endif
e8b96c60
MA
7827
7828 if (zfs_dirty_data_max == 0) {
9edb3695 7829 zfs_dirty_data_max = allmem *
e8b96c60
MA
7830 zfs_dirty_data_max_percent / 100;
7831 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
7832 zfs_dirty_data_max_max);
7833 }
a7bd20e3
KJ
7834
7835 if (zfs_wrlog_data_max == 0) {
7836
7837 /*
7838 * dp_wrlog_total is reduced for each txg at the end of
7839 * spa_sync(). However, dp_dirty_total is reduced every time
7840 * a block is written out. Thus under normal operation,
7841 * dp_wrlog_total could grow 2 times as big as
7842 * zfs_dirty_data_max.
7843 */
7844 zfs_wrlog_data_max = zfs_dirty_data_max * 2;
7845 }
34dc7c2f
BB
7846}
7847
7848void
7849arc_fini(void)
7850{
ab26409d
BB
7851 arc_prune_t *p;
7852
7cb67b45 7853#ifdef _KERNEL
c9c9c1e2 7854 arc_lowmem_fini();
7cb67b45
BB
7855#endif /* _KERNEL */
7856
d3c2ae1c
GW
7857 /* Use B_TRUE to ensure *all* buffers are evicted */
7858 arc_flush(NULL, B_TRUE);
34dc7c2f 7859
34dc7c2f
BB
7860 if (arc_ksp != NULL) {
7861 kstat_delete(arc_ksp);
7862 arc_ksp = NULL;
7863 }
7864
f6046738
BB
7865 taskq_wait(arc_prune_taskq);
7866 taskq_destroy(arc_prune_taskq);
7867
ab26409d
BB
7868 mutex_enter(&arc_prune_mtx);
7869 while ((p = list_head(&arc_prune_list)) != NULL) {
7870 list_remove(&arc_prune_list, p);
424fd7c3
TS
7871 zfs_refcount_remove(&p->p_refcnt, &arc_prune_list);
7872 zfs_refcount_destroy(&p->p_refcnt);
ab26409d
BB
7873 kmem_free(p, sizeof (*p));
7874 }
7875 mutex_exit(&arc_prune_mtx);
7876
7877 list_destroy(&arc_prune_list);
7878 mutex_destroy(&arc_prune_mtx);
3ec34e55 7879
5dd92909 7880 (void) zthr_cancel(arc_evict_zthr);
3ec34e55 7881 (void) zthr_cancel(arc_reap_zthr);
6e2a5918
MJ
7882 arc_state_free_markers(arc_state_evict_markers,
7883 arc_state_evict_marker_count);
3ec34e55 7884
5dd92909 7885 mutex_destroy(&arc_evict_lock);
3442c2a0 7886 list_destroy(&arc_evict_waiters);
ca0bf58d 7887
cfd59f90
BB
7888 /*
7889 * Free any buffers that were tagged for destruction. This needs
7890 * to occur before arc_state_fini() runs and destroys the aggsum
7891 * values which are updated when freeing scatter ABDs.
7892 */
7893 l2arc_do_free_on_write();
7894
ae3d8491
PD
7895 /*
7896 * buf_fini() must proceed arc_state_fini() because buf_fin() may
7897 * trigger the release of kmem magazines, which can callback to
7898 * arc_space_return() which accesses aggsums freed in act_state_fini().
7899 */
34dc7c2f 7900 buf_fini();
ae3d8491 7901 arc_state_fini();
9babb374 7902
60a4c7d2
PD
7903 arc_unregister_hotplug();
7904
1c44a5c9
SD
7905 /*
7906 * We destroy the zthrs after all the ARC state has been
7907 * torn down to avoid the case of them receiving any
7908 * wakeup() signals after they are destroyed.
7909 */
5dd92909 7910 zthr_destroy(arc_evict_zthr);
1c44a5c9
SD
7911 zthr_destroy(arc_reap_zthr);
7912
b9541d6b 7913 ASSERT0(arc_loaned_bytes);
34dc7c2f
BB
7914}
7915
7916/*
7917 * Level 2 ARC
7918 *
7919 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
7920 * It uses dedicated storage devices to hold cached data, which are populated
7921 * using large infrequent writes. The main role of this cache is to boost
7922 * the performance of random read workloads. The intended L2ARC devices
7923 * include short-stroked disks, solid state disks, and other media with
7924 * substantially faster read latency than disk.
7925 *
7926 * +-----------------------+
7927 * | ARC |
7928 * +-----------------------+
7929 * | ^ ^
7930 * | | |
7931 * l2arc_feed_thread() arc_read()
7932 * | | |
7933 * | l2arc read |
7934 * V | |
7935 * +---------------+ |
7936 * | L2ARC | |
7937 * +---------------+ |
7938 * | ^ |
7939 * l2arc_write() | |
7940 * | | |
7941 * V | |
7942 * +-------+ +-------+
7943 * | vdev | | vdev |
7944 * | cache | | cache |
7945 * +-------+ +-------+
7946 * +=========+ .-----.
7947 * : L2ARC : |-_____-|
7948 * : devices : | Disks |
7949 * +=========+ `-_____-'
7950 *
7951 * Read requests are satisfied from the following sources, in order:
7952 *
7953 * 1) ARC
7954 * 2) vdev cache of L2ARC devices
7955 * 3) L2ARC devices
7956 * 4) vdev cache of disks
7957 * 5) disks
7958 *
7959 * Some L2ARC device types exhibit extremely slow write performance.
7960 * To accommodate for this there are some significant differences between
7961 * the L2ARC and traditional cache design:
7962 *
7963 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
7964 * the ARC behave as usual, freeing buffers and placing headers on ghost
7965 * lists. The ARC does not send buffers to the L2ARC during eviction as
7966 * this would add inflated write latencies for all ARC memory pressure.
7967 *
7968 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
7969 * It does this by periodically scanning buffers from the eviction-end of
7970 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
3a17a7a9
SK
7971 * not already there. It scans until a headroom of buffers is satisfied,
7972 * which itself is a buffer for ARC eviction. If a compressible buffer is
7973 * found during scanning and selected for writing to an L2ARC device, we
7974 * temporarily boost scanning headroom during the next scan cycle to make
7975 * sure we adapt to compression effects (which might significantly reduce
7976 * the data volume we write to L2ARC). The thread that does this is
34dc7c2f
BB
7977 * l2arc_feed_thread(), illustrated below; example sizes are included to
7978 * provide a better sense of ratio than this diagram:
7979 *
7980 * head --> tail
7981 * +---------------------+----------+
7982 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
7983 * +---------------------+----------+ | o L2ARC eligible
7984 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
7985 * +---------------------+----------+ |
7986 * 15.9 Gbytes ^ 32 Mbytes |
7987 * headroom |
7988 * l2arc_feed_thread()
7989 * |
7990 * l2arc write hand <--[oooo]--'
7991 * | 8 Mbyte
7992 * | write max
7993 * V
7994 * +==============================+
7995 * L2ARC dev |####|#|###|###| |####| ... |
7996 * +==============================+
7997 * 32 Gbytes
7998 *
7999 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
8000 * evicted, then the L2ARC has cached a buffer much sooner than it probably
8001 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
8002 * safe to say that this is an uncommon case, since buffers at the end of
8003 * the ARC lists have moved there due to inactivity.
8004 *
8005 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
8006 * then the L2ARC simply misses copying some buffers. This serves as a
8007 * pressure valve to prevent heavy read workloads from both stalling the ARC
8008 * with waits and clogging the L2ARC with writes. This also helps prevent
8009 * the potential for the L2ARC to churn if it attempts to cache content too
8010 * quickly, such as during backups of the entire pool.
8011 *
b128c09f
BB
8012 * 5. After system boot and before the ARC has filled main memory, there are
8013 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
8014 * lists can remain mostly static. Instead of searching from tail of these
8015 * lists as pictured, the l2arc_feed_thread() will search from the list heads
8016 * for eligible buffers, greatly increasing its chance of finding them.
8017 *
8018 * The L2ARC device write speed is also boosted during this time so that
8019 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
8020 * there are no L2ARC reads, and no fear of degrading read performance
8021 * through increased writes.
8022 *
8023 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
34dc7c2f
BB
8024 * the vdev queue can aggregate them into larger and fewer writes. Each
8025 * device is written to in a rotor fashion, sweeping writes through
8026 * available space then repeating.
8027 *
b128c09f 8028 * 7. The L2ARC does not store dirty content. It never needs to flush
34dc7c2f
BB
8029 * write buffers back to disk based storage.
8030 *
b128c09f 8031 * 8. If an ARC buffer is written (and dirtied) which also exists in the
34dc7c2f
BB
8032 * L2ARC, the now stale L2ARC buffer is immediately dropped.
8033 *
8034 * The performance of the L2ARC can be tweaked by a number of tunables, which
8035 * may be necessary for different workloads:
8036 *
8037 * l2arc_write_max max write bytes per interval
b128c09f 8038 * l2arc_write_boost extra write bytes during device warmup
34dc7c2f
BB
8039 * l2arc_noprefetch skip caching prefetched buffers
8040 * l2arc_headroom number of max device writes to precache
3a17a7a9
SK
8041 * l2arc_headroom_boost when we find compressed buffers during ARC
8042 * scanning, we multiply headroom by this
8043 * percentage factor for the next scan cycle,
8044 * since more compressed buffers are likely to
8045 * be present
34dc7c2f
BB
8046 * l2arc_feed_secs seconds between L2ARC writing
8047 *
8048 * Tunables may be removed or added as future performance improvements are
8049 * integrated, and also may become zpool properties.
d164b209
BB
8050 *
8051 * There are three key functions that control how the L2ARC warms up:
8052 *
8053 * l2arc_write_eligible() check if a buffer is eligible to cache
8054 * l2arc_write_size() calculate how much to write
8055 * l2arc_write_interval() calculate sleep delay between writes
8056 *
8057 * These three functions determine what to write, how much, and how quickly
8058 * to send writes.
77f6826b
GA
8059 *
8060 * L2ARC persistence:
8061 *
8062 * When writing buffers to L2ARC, we periodically add some metadata to
8063 * make sure we can pick them up after reboot, thus dramatically reducing
8064 * the impact that any downtime has on the performance of storage systems
8065 * with large caches.
8066 *
8067 * The implementation works fairly simply by integrating the following two
8068 * modifications:
8069 *
8070 * *) When writing to the L2ARC, we occasionally write a "l2arc log block",
8071 * which is an additional piece of metadata which describes what's been
8072 * written. This allows us to rebuild the arc_buf_hdr_t structures of the
8073 * main ARC buffers. There are 2 linked-lists of log blocks headed by
8074 * dh_start_lbps[2]. We alternate which chain we append to, so they are
8075 * time-wise and offset-wise interleaved, but that is an optimization rather
8076 * than for correctness. The log block also includes a pointer to the
8077 * previous block in its chain.
8078 *
8079 * *) We reserve SPA_MINBLOCKSIZE of space at the start of each L2ARC device
8080 * for our header bookkeeping purposes. This contains a device header,
8081 * which contains our top-level reference structures. We update it each
8082 * time we write a new log block, so that we're able to locate it in the
8083 * L2ARC device. If this write results in an inconsistent device header
8084 * (e.g. due to power failure), we detect this by verifying the header's
8085 * checksum and simply fail to reconstruct the L2ARC after reboot.
8086 *
8087 * Implementation diagram:
8088 *
8089 * +=== L2ARC device (not to scale) ======================================+
8090 * | ___two newest log block pointers__.__________ |
8091 * | / \dh_start_lbps[1] |
8092 * | / \ \dh_start_lbps[0]|
8093 * |.___/__. V V |
8094 * ||L2 dev|....|lb |bufs |lb |bufs |lb |bufs |lb |bufs |lb |---(empty)---|
8095 * || hdr| ^ /^ /^ / / |
8096 * |+------+ ...--\-------/ \-----/--\------/ / |
8097 * | \--------------/ \--------------/ |
8098 * +======================================================================+
8099 *
8100 * As can be seen on the diagram, rather than using a simple linked list,
8101 * we use a pair of linked lists with alternating elements. This is a
8102 * performance enhancement due to the fact that we only find out the
8103 * address of the next log block access once the current block has been
8104 * completely read in. Obviously, this hurts performance, because we'd be
8105 * keeping the device's I/O queue at only a 1 operation deep, thus
8106 * incurring a large amount of I/O round-trip latency. Having two lists
8107 * allows us to fetch two log blocks ahead of where we are currently
8108 * rebuilding L2ARC buffers.
8109 *
8110 * On-device data structures:
8111 *
8112 * L2ARC device header: l2arc_dev_hdr_phys_t
8113 * L2ARC log block: l2arc_log_blk_phys_t
8114 *
8115 * L2ARC reconstruction:
8116 *
8117 * When writing data, we simply write in the standard rotary fashion,
8118 * evicting buffers as we go and simply writing new data over them (writing
8119 * a new log block every now and then). This obviously means that once we
8120 * loop around the end of the device, we will start cutting into an already
8121 * committed log block (and its referenced data buffers), like so:
8122 *
8123 * current write head__ __old tail
8124 * \ /
8125 * V V
8126 * <--|bufs |lb |bufs |lb | |bufs |lb |bufs |lb |-->
8127 * ^ ^^^^^^^^^___________________________________
8128 * | \
8129 * <<nextwrite>> may overwrite this blk and/or its bufs --'
8130 *
8131 * When importing the pool, we detect this situation and use it to stop
8132 * our scanning process (see l2arc_rebuild).
8133 *
8134 * There is one significant caveat to consider when rebuilding ARC contents
8135 * from an L2ARC device: what about invalidated buffers? Given the above
8136 * construction, we cannot update blocks which we've already written to amend
8137 * them to remove buffers which were invalidated. Thus, during reconstruction,
8138 * we might be populating the cache with buffers for data that's not on the
8139 * main pool anymore, or may have been overwritten!
8140 *
8141 * As it turns out, this isn't a problem. Every arc_read request includes
8142 * both the DVA and, crucially, the birth TXG of the BP the caller is
8143 * looking for. So even if the cache were populated by completely rotten
8144 * blocks for data that had been long deleted and/or overwritten, we'll
8145 * never actually return bad data from the cache, since the DVA with the
8146 * birth TXG uniquely identify a block in space and time - once created,
8147 * a block is immutable on disk. The worst thing we have done is wasted
8148 * some time and memory at l2arc rebuild to reconstruct outdated ARC
8149 * entries that will get dropped from the l2arc as it is being updated
8150 * with new blocks.
8151 *
8152 * L2ARC buffers that have been evicted by l2arc_evict() ahead of the write
8153 * hand are not restored. This is done by saving the offset (in bytes)
8154 * l2arc_evict() has evicted to in the L2ARC device header and taking it
8155 * into account when restoring buffers.
34dc7c2f
BB
8156 */
8157
d164b209 8158static boolean_t
2a432414 8159l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
d164b209
BB
8160{
8161 /*
8162 * A buffer is *not* eligible for the L2ARC if it:
8163 * 1. belongs to a different spa.
428870ff
BB
8164 * 2. is already cached on the L2ARC.
8165 * 3. has an I/O in progress (it may be an incomplete read).
8166 * 4. is flagged not eligible (zfs property).
d164b209 8167 */
b9541d6b 8168 if (hdr->b_spa != spa_guid || HDR_HAS_L2HDR(hdr) ||
c6f5e9d9 8169 HDR_IO_IN_PROGRESS(hdr) || !HDR_L2CACHE(hdr))
d164b209
BB
8170 return (B_FALSE);
8171
8172 return (B_TRUE);
8173}
8174
8175static uint64_t
37c22948 8176l2arc_write_size(l2arc_dev_t *dev)
d164b209 8177{
bcd53210 8178 uint64_t size;
d164b209 8179
3a17a7a9
SK
8180 /*
8181 * Make sure our globals have meaningful values in case the user
8182 * altered them.
8183 */
8184 size = l2arc_write_max;
8185 if (size == 0) {
8186 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
8187 "be greater than zero, resetting it to the default (%d)",
8188 L2ARC_WRITE_SIZE);
8189 size = l2arc_write_max = L2ARC_WRITE_SIZE;
8190 }
d164b209
BB
8191
8192 if (arc_warm == B_FALSE)
3a17a7a9 8193 size += l2arc_write_boost;
d164b209 8194
d38c815f 8195 /* We need to add in the worst case scenario of log block overhead. */
bcd53210 8196 size += l2arc_log_blk_overhead(size, dev);
d38c815f
GA
8197 if (dev->l2ad_vdev->vdev_has_trim && l2arc_trim_ahead > 0) {
8198 /*
8199 * Trim ahead of the write size 64MB or (l2arc_trim_ahead/100)
8200 * times the writesize, whichever is greater.
8201 */
bcd53210
GA
8202 size += MAX(64 * 1024 * 1024,
8203 (size * l2arc_trim_ahead) / 100);
d38c815f 8204 }
b7654bd7 8205
bcd53210
GA
8206 /*
8207 * Make sure the write size does not exceed the size of the cache
8208 * device. This is important in l2arc_evict(), otherwise infinite
8209 * iteration can occur.
8210 */
8211 if (size >= dev->l2ad_end - dev->l2ad_start) {
37c22948 8212 cmn_err(CE_NOTE, "l2arc_write_max or l2arc_write_boost "
77f6826b
GA
8213 "plus the overhead of log blocks (persistent L2ARC, "
8214 "%llu bytes) exceeds the size of the cache device "
8215 "(guid %llu), resetting them to the default (%d)",
b72611f0
BB
8216 (u_longlong_t)l2arc_log_blk_overhead(size, dev),
8217 (u_longlong_t)dev->l2ad_vdev->vdev_guid, L2ARC_WRITE_SIZE);
bcd53210 8218
37c22948
GA
8219 size = l2arc_write_max = l2arc_write_boost = L2ARC_WRITE_SIZE;
8220
8221 if (arc_warm == B_FALSE)
8222 size += l2arc_write_boost;
bcd53210
GA
8223
8224 size += l2arc_log_blk_overhead(size, dev);
8225 if (dev->l2ad_vdev->vdev_has_trim && l2arc_trim_ahead > 0) {
8226 size += MAX(64 * 1024 * 1024,
8227 (size * l2arc_trim_ahead) / 100);
8228 }
37c22948
GA
8229 }
8230
d164b209
BB
8231 return (size);
8232
8233}
8234
8235static clock_t
8236l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
8237{
428870ff 8238 clock_t interval, next, now;
d164b209
BB
8239
8240 /*
8241 * If the ARC lists are busy, increase our write rate; if the
8242 * lists are stale, idle back. This is achieved by checking
8243 * how much we previously wrote - if it was more than half of
8244 * what we wanted, schedule the next write much sooner.
8245 */
8246 if (l2arc_feed_again && wrote > (wanted / 2))
8247 interval = (hz * l2arc_feed_min_ms) / 1000;
8248 else
8249 interval = hz * l2arc_feed_secs;
8250
428870ff
BB
8251 now = ddi_get_lbolt();
8252 next = MAX(now, MIN(now + interval, began + interval));
d164b209
BB
8253
8254 return (next);
8255}
8256
34dc7c2f
BB
8257/*
8258 * Cycle through L2ARC devices. This is how L2ARC load balances.
b128c09f 8259 * If a device is returned, this also returns holding the spa config lock.
34dc7c2f
BB
8260 */
8261static l2arc_dev_t *
8262l2arc_dev_get_next(void)
8263{
b128c09f 8264 l2arc_dev_t *first, *next = NULL;
34dc7c2f 8265
b128c09f
BB
8266 /*
8267 * Lock out the removal of spas (spa_namespace_lock), then removal
8268 * of cache devices (l2arc_dev_mtx). Once a device has been selected,
8269 * both locks will be dropped and a spa config lock held instead.
8270 */
8271 mutex_enter(&spa_namespace_lock);
8272 mutex_enter(&l2arc_dev_mtx);
8273
8274 /* if there are no vdevs, there is nothing to do */
8275 if (l2arc_ndev == 0)
8276 goto out;
8277
8278 first = NULL;
8279 next = l2arc_dev_last;
8280 do {
8281 /* loop around the list looking for a non-faulted vdev */
8282 if (next == NULL) {
34dc7c2f 8283 next = list_head(l2arc_dev_list);
b128c09f
BB
8284 } else {
8285 next = list_next(l2arc_dev_list, next);
8286 if (next == NULL)
8287 next = list_head(l2arc_dev_list);
8288 }
8289
8290 /* if we have come back to the start, bail out */
8291 if (first == NULL)
8292 first = next;
8293 else if (next == first)
8294 break;
8295
a6ccb36b 8296 ASSERT3P(next, !=, NULL);
b7654bd7
GA
8297 } while (vdev_is_dead(next->l2ad_vdev) || next->l2ad_rebuild ||
8298 next->l2ad_trim_all);
b128c09f
BB
8299
8300 /* if we were unable to find any usable vdevs, return NULL */
b7654bd7
GA
8301 if (vdev_is_dead(next->l2ad_vdev) || next->l2ad_rebuild ||
8302 next->l2ad_trim_all)
b128c09f 8303 next = NULL;
34dc7c2f
BB
8304
8305 l2arc_dev_last = next;
8306
b128c09f
BB
8307out:
8308 mutex_exit(&l2arc_dev_mtx);
8309
8310 /*
8311 * Grab the config lock to prevent the 'next' device from being
8312 * removed while we are writing to it.
8313 */
8314 if (next != NULL)
8315 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
8316 mutex_exit(&spa_namespace_lock);
8317
34dc7c2f
BB
8318 return (next);
8319}
8320
b128c09f
BB
8321/*
8322 * Free buffers that were tagged for destruction.
8323 */
8324static void
0bc8fd78 8325l2arc_do_free_on_write(void)
b128c09f
BB
8326{
8327 list_t *buflist;
8328 l2arc_data_free_t *df, *df_prev;
8329
8330 mutex_enter(&l2arc_free_on_write_mtx);
8331 buflist = l2arc_free_on_write;
8332
8333 for (df = list_tail(buflist); df; df = df_prev) {
8334 df_prev = list_prev(buflist, df);
a6255b7f
DQ
8335 ASSERT3P(df->l2df_abd, !=, NULL);
8336 abd_free(df->l2df_abd);
b128c09f
BB
8337 list_remove(buflist, df);
8338 kmem_free(df, sizeof (l2arc_data_free_t));
8339 }
8340
8341 mutex_exit(&l2arc_free_on_write_mtx);
8342}
8343
34dc7c2f
BB
8344/*
8345 * A write to a cache device has completed. Update all headers to allow
8346 * reads from these buffers to begin.
8347 */
8348static void
8349l2arc_write_done(zio_t *zio)
8350{
77f6826b
GA
8351 l2arc_write_callback_t *cb;
8352 l2arc_lb_abd_buf_t *abd_buf;
8353 l2arc_lb_ptr_buf_t *lb_ptr_buf;
8354 l2arc_dev_t *dev;
657fd33b 8355 l2arc_dev_hdr_phys_t *l2dhdr;
77f6826b
GA
8356 list_t *buflist;
8357 arc_buf_hdr_t *head, *hdr, *hdr_prev;
8358 kmutex_t *hash_lock;
8359 int64_t bytes_dropped = 0;
34dc7c2f
BB
8360
8361 cb = zio->io_private;
d3c2ae1c 8362 ASSERT3P(cb, !=, NULL);
34dc7c2f 8363 dev = cb->l2wcb_dev;
657fd33b 8364 l2dhdr = dev->l2ad_dev_hdr;
d3c2ae1c 8365 ASSERT3P(dev, !=, NULL);
34dc7c2f 8366 head = cb->l2wcb_head;
d3c2ae1c 8367 ASSERT3P(head, !=, NULL);
b9541d6b 8368 buflist = &dev->l2ad_buflist;
d3c2ae1c 8369 ASSERT3P(buflist, !=, NULL);
34dc7c2f
BB
8370 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
8371 l2arc_write_callback_t *, cb);
8372
34dc7c2f
BB
8373 /*
8374 * All writes completed, or an error was hit.
8375 */
ca0bf58d
PS
8376top:
8377 mutex_enter(&dev->l2ad_mtx);
2a432414
GW
8378 for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
8379 hdr_prev = list_prev(buflist, hdr);
34dc7c2f 8380
2a432414 8381 hash_lock = HDR_LOCK(hdr);
ca0bf58d
PS
8382
8383 /*
8384 * We cannot use mutex_enter or else we can deadlock
8385 * with l2arc_write_buffers (due to swapping the order
8386 * the hash lock and l2ad_mtx are taken).
8387 */
34dc7c2f
BB
8388 if (!mutex_tryenter(hash_lock)) {
8389 /*
ca0bf58d
PS
8390 * Missed the hash lock. We must retry so we
8391 * don't leave the ARC_FLAG_L2_WRITING bit set.
34dc7c2f 8392 */
ca0bf58d
PS
8393 ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
8394
8395 /*
8396 * We don't want to rescan the headers we've
8397 * already marked as having been written out, so
8398 * we reinsert the head node so we can pick up
8399 * where we left off.
8400 */
8401 list_remove(buflist, head);
8402 list_insert_after(buflist, hdr, head);
8403
8404 mutex_exit(&dev->l2ad_mtx);
8405
8406 /*
8407 * We wait for the hash lock to become available
8408 * to try and prevent busy waiting, and increase
8409 * the chance we'll be able to acquire the lock
8410 * the next time around.
8411 */
8412 mutex_enter(hash_lock);
8413 mutex_exit(hash_lock);
8414 goto top;
34dc7c2f
BB
8415 }
8416
b9541d6b 8417 /*
ca0bf58d
PS
8418 * We could not have been moved into the arc_l2c_only
8419 * state while in-flight due to our ARC_FLAG_L2_WRITING
8420 * bit being set. Let's just ensure that's being enforced.
8421 */
8422 ASSERT(HDR_HAS_L1HDR(hdr));
8423
8a09d5fd
BB
8424 /*
8425 * Skipped - drop L2ARC entry and mark the header as no
8426 * longer L2 eligibile.
8427 */
d3c2ae1c 8428 if (zio->io_error != 0) {
34dc7c2f 8429 /*
b128c09f 8430 * Error - drop L2ARC entry.
34dc7c2f 8431 */
2a432414 8432 list_remove(buflist, hdr);
d3c2ae1c 8433 arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
b9541d6b 8434
7558997d 8435 uint64_t psize = HDR_GET_PSIZE(hdr);
08532162 8436 l2arc_hdr_arcstats_decrement(hdr);
d962d5da 8437
7558997d
SD
8438 bytes_dropped +=
8439 vdev_psize_to_asize(dev->l2ad_vdev, psize);
424fd7c3 8440 (void) zfs_refcount_remove_many(&dev->l2ad_alloc,
d3c2ae1c 8441 arc_hdr_size(hdr), hdr);
34dc7c2f
BB
8442 }
8443
8444 /*
ca0bf58d
PS
8445 * Allow ARC to begin reads and ghost list evictions to
8446 * this L2ARC entry.
34dc7c2f 8447 */
d3c2ae1c 8448 arc_hdr_clear_flags(hdr, ARC_FLAG_L2_WRITING);
34dc7c2f
BB
8449
8450 mutex_exit(hash_lock);
8451 }
8452
77f6826b
GA
8453 /*
8454 * Free the allocated abd buffers for writing the log blocks.
8455 * If the zio failed reclaim the allocated space and remove the
8456 * pointers to these log blocks from the log block pointer list
8457 * of the L2ARC device.
8458 */
8459 while ((abd_buf = list_remove_tail(&cb->l2wcb_abd_list)) != NULL) {
8460 abd_free(abd_buf->abd);
8461 zio_buf_free(abd_buf, sizeof (*abd_buf));
8462 if (zio->io_error != 0) {
8463 lb_ptr_buf = list_remove_head(&dev->l2ad_lbptr_list);
657fd33b
GA
8464 /*
8465 * L2BLK_GET_PSIZE returns aligned size for log
8466 * blocks.
8467 */
8468 uint64_t asize =
77f6826b 8469 L2BLK_GET_PSIZE((lb_ptr_buf->lb_ptr)->lbp_prop);
657fd33b
GA
8470 bytes_dropped += asize;
8471 ARCSTAT_INCR(arcstat_l2_log_blk_asize, -asize);
8472 ARCSTAT_BUMPDOWN(arcstat_l2_log_blk_count);
8473 zfs_refcount_remove_many(&dev->l2ad_lb_asize, asize,
8474 lb_ptr_buf);
8475 zfs_refcount_remove(&dev->l2ad_lb_count, lb_ptr_buf);
77f6826b
GA
8476 kmem_free(lb_ptr_buf->lb_ptr,
8477 sizeof (l2arc_log_blkptr_t));
8478 kmem_free(lb_ptr_buf, sizeof (l2arc_lb_ptr_buf_t));
8479 }
8480 }
8481 list_destroy(&cb->l2wcb_abd_list);
8482
657fd33b 8483 if (zio->io_error != 0) {
08532162
GA
8484 ARCSTAT_BUMP(arcstat_l2_writes_error);
8485
2054f35e
GA
8486 /*
8487 * Restore the lbps array in the header to its previous state.
8488 * If the list of log block pointers is empty, zero out the
8489 * log block pointers in the device header.
8490 */
657fd33b
GA
8491 lb_ptr_buf = list_head(&dev->l2ad_lbptr_list);
8492 for (int i = 0; i < 2; i++) {
2054f35e
GA
8493 if (lb_ptr_buf == NULL) {
8494 /*
8495 * If the list is empty zero out the device
8496 * header. Otherwise zero out the second log
8497 * block pointer in the header.
8498 */
8499 if (i == 0) {
861166b0
AZ
8500 memset(l2dhdr, 0,
8501 dev->l2ad_dev_hdr_asize);
2054f35e 8502 } else {
861166b0 8503 memset(&l2dhdr->dh_start_lbps[i], 0,
2054f35e
GA
8504 sizeof (l2arc_log_blkptr_t));
8505 }
8506 break;
8507 }
861166b0 8508 memcpy(&l2dhdr->dh_start_lbps[i], lb_ptr_buf->lb_ptr,
657fd33b
GA
8509 sizeof (l2arc_log_blkptr_t));
8510 lb_ptr_buf = list_next(&dev->l2ad_lbptr_list,
8511 lb_ptr_buf);
8512 }
8513 }
8514
c4c162c1 8515 ARCSTAT_BUMP(arcstat_l2_writes_done);
34dc7c2f 8516 list_remove(buflist, head);
b9541d6b
CW
8517 ASSERT(!HDR_HAS_L1HDR(head));
8518 kmem_cache_free(hdr_l2only_cache, head);
8519 mutex_exit(&dev->l2ad_mtx);
34dc7c2f 8520
77f6826b 8521 ASSERT(dev->l2ad_vdev != NULL);
3bec585e
SK
8522 vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
8523
b128c09f 8524 l2arc_do_free_on_write();
34dc7c2f
BB
8525
8526 kmem_free(cb, sizeof (l2arc_write_callback_t));
8527}
8528
b5256303
TC
8529static int
8530l2arc_untransform(zio_t *zio, l2arc_read_callback_t *cb)
8531{
8532 int ret;
8533 spa_t *spa = zio->io_spa;
8534 arc_buf_hdr_t *hdr = cb->l2rcb_hdr;
8535 blkptr_t *bp = zio->io_bp;
b5256303
TC
8536 uint8_t salt[ZIO_DATA_SALT_LEN];
8537 uint8_t iv[ZIO_DATA_IV_LEN];
8538 uint8_t mac[ZIO_DATA_MAC_LEN];
8539 boolean_t no_crypt = B_FALSE;
8540
8541 /*
8542 * ZIL data is never be written to the L2ARC, so we don't need
8543 * special handling for its unique MAC storage.
8544 */
8545 ASSERT3U(BP_GET_TYPE(bp), !=, DMU_OT_INTENT_LOG);
8546 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
440a3eb9 8547 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
b5256303 8548
440a3eb9
TC
8549 /*
8550 * If the data was encrypted, decrypt it now. Note that
8551 * we must check the bp here and not the hdr, since the
8552 * hdr does not have its encryption parameters updated
8553 * until arc_read_done().
8554 */
8555 if (BP_IS_ENCRYPTED(bp)) {
e111c802 8556 abd_t *eabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr,
a8d83e2a 8557 ARC_HDR_USE_RESERVE);
b5256303
TC
8558
8559 zio_crypt_decode_params_bp(bp, salt, iv);
8560 zio_crypt_decode_mac_bp(bp, mac);
8561
be9a5c35
TC
8562 ret = spa_do_crypt_abd(B_FALSE, spa, &cb->l2rcb_zb,
8563 BP_GET_TYPE(bp), BP_GET_DEDUP(bp), BP_SHOULD_BYTESWAP(bp),
8564 salt, iv, mac, HDR_GET_PSIZE(hdr), eabd,
8565 hdr->b_l1hdr.b_pabd, &no_crypt);
b5256303
TC
8566 if (ret != 0) {
8567 arc_free_data_abd(hdr, eabd, arc_hdr_size(hdr), hdr);
b5256303
TC
8568 goto error;
8569 }
8570
b5256303
TC
8571 /*
8572 * If we actually performed decryption, replace b_pabd
8573 * with the decrypted data. Otherwise we can just throw
8574 * our decryption buffer away.
8575 */
8576 if (!no_crypt) {
8577 arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
8578 arc_hdr_size(hdr), hdr);
8579 hdr->b_l1hdr.b_pabd = eabd;
8580 zio->io_abd = eabd;
8581 } else {
8582 arc_free_data_abd(hdr, eabd, arc_hdr_size(hdr), hdr);
8583 }
8584 }
8585
8586 /*
8587 * If the L2ARC block was compressed, but ARC compression
8588 * is disabled we decompress the data into a new buffer and
8589 * replace the existing data.
8590 */
8591 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
8592 !HDR_COMPRESSION_ENABLED(hdr)) {
e111c802 8593 abd_t *cabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr,
a8d83e2a 8594 ARC_HDR_USE_RESERVE);
b5256303
TC
8595 void *tmp = abd_borrow_buf(cabd, arc_hdr_size(hdr));
8596
8597 ret = zio_decompress_data(HDR_GET_COMPRESS(hdr),
8598 hdr->b_l1hdr.b_pabd, tmp, HDR_GET_PSIZE(hdr),
10b3c7f5 8599 HDR_GET_LSIZE(hdr), &hdr->b_complevel);
b5256303
TC
8600 if (ret != 0) {
8601 abd_return_buf_copy(cabd, tmp, arc_hdr_size(hdr));
8602 arc_free_data_abd(hdr, cabd, arc_hdr_size(hdr), hdr);
8603 goto error;
8604 }
8605
8606 abd_return_buf_copy(cabd, tmp, arc_hdr_size(hdr));
8607 arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
8608 arc_hdr_size(hdr), hdr);
8609 hdr->b_l1hdr.b_pabd = cabd;
8610 zio->io_abd = cabd;
8611 zio->io_size = HDR_GET_LSIZE(hdr);
8612 }
8613
8614 return (0);
8615
8616error:
8617 return (ret);
8618}
8619
8620
34dc7c2f
BB
8621/*
8622 * A read to a cache device completed. Validate buffer contents before
8623 * handing over to the regular ARC routines.
8624 */
8625static void
8626l2arc_read_done(zio_t *zio)
8627{
b5256303 8628 int tfm_error = 0;
b405837a 8629 l2arc_read_callback_t *cb = zio->io_private;
34dc7c2f 8630 arc_buf_hdr_t *hdr;
34dc7c2f 8631 kmutex_t *hash_lock;
b405837a
TC
8632 boolean_t valid_cksum;
8633 boolean_t using_rdata = (BP_IS_ENCRYPTED(&cb->l2rcb_bp) &&
8634 (cb->l2rcb_flags & ZIO_FLAG_RAW_ENCRYPT));
b128c09f 8635
d3c2ae1c 8636 ASSERT3P(zio->io_vd, !=, NULL);
b128c09f
BB
8637 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
8638
8639 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
34dc7c2f 8640
d3c2ae1c
GW
8641 ASSERT3P(cb, !=, NULL);
8642 hdr = cb->l2rcb_hdr;
8643 ASSERT3P(hdr, !=, NULL);
34dc7c2f 8644
d3c2ae1c 8645 hash_lock = HDR_LOCK(hdr);
34dc7c2f 8646 mutex_enter(hash_lock);
428870ff 8647 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
34dc7c2f 8648
82710e99
GDN
8649 /*
8650 * If the data was read into a temporary buffer,
8651 * move it and free the buffer.
8652 */
8653 if (cb->l2rcb_abd != NULL) {
8654 ASSERT3U(arc_hdr_size(hdr), <, zio->io_size);
8655 if (zio->io_error == 0) {
b405837a
TC
8656 if (using_rdata) {
8657 abd_copy(hdr->b_crypt_hdr.b_rabd,
8658 cb->l2rcb_abd, arc_hdr_size(hdr));
8659 } else {
8660 abd_copy(hdr->b_l1hdr.b_pabd,
8661 cb->l2rcb_abd, arc_hdr_size(hdr));
8662 }
82710e99
GDN
8663 }
8664
8665 /*
8666 * The following must be done regardless of whether
8667 * there was an error:
8668 * - free the temporary buffer
8669 * - point zio to the real ARC buffer
8670 * - set zio size accordingly
8671 * These are required because zio is either re-used for
8672 * an I/O of the block in the case of the error
8673 * or the zio is passed to arc_read_done() and it
8674 * needs real data.
8675 */
8676 abd_free(cb->l2rcb_abd);
8677 zio->io_size = zio->io_orig_size = arc_hdr_size(hdr);
440a3eb9 8678
b405837a 8679 if (using_rdata) {
440a3eb9
TC
8680 ASSERT(HDR_HAS_RABD(hdr));
8681 zio->io_abd = zio->io_orig_abd =
8682 hdr->b_crypt_hdr.b_rabd;
8683 } else {
8684 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
8685 zio->io_abd = zio->io_orig_abd = hdr->b_l1hdr.b_pabd;
8686 }
82710e99
GDN
8687 }
8688
a6255b7f 8689 ASSERT3P(zio->io_abd, !=, NULL);
3a17a7a9 8690
34dc7c2f
BB
8691 /*
8692 * Check this survived the L2ARC journey.
8693 */
b5256303
TC
8694 ASSERT(zio->io_abd == hdr->b_l1hdr.b_pabd ||
8695 (HDR_HAS_RABD(hdr) && zio->io_abd == hdr->b_crypt_hdr.b_rabd));
d3c2ae1c
GW
8696 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
8697 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
10b3c7f5 8698 zio->io_prop.zp_complevel = hdr->b_complevel;
d3c2ae1c
GW
8699
8700 valid_cksum = arc_cksum_is_equal(hdr, zio);
b5256303
TC
8701
8702 /*
8703 * b_rabd will always match the data as it exists on disk if it is
8704 * being used. Therefore if we are reading into b_rabd we do not
8705 * attempt to untransform the data.
8706 */
8707 if (valid_cksum && !using_rdata)
8708 tfm_error = l2arc_untransform(zio, cb);
8709
8710 if (valid_cksum && tfm_error == 0 && zio->io_error == 0 &&
8711 !HDR_L2_EVICTED(hdr)) {
34dc7c2f 8712 mutex_exit(hash_lock);
d3c2ae1c 8713 zio->io_private = hdr;
34dc7c2f
BB
8714 arc_read_done(zio);
8715 } else {
34dc7c2f
BB
8716 /*
8717 * Buffer didn't survive caching. Increment stats and
8718 * reissue to the original storage device.
8719 */
b128c09f 8720 if (zio->io_error != 0) {
34dc7c2f 8721 ARCSTAT_BUMP(arcstat_l2_io_error);
b128c09f 8722 } else {
2e528b49 8723 zio->io_error = SET_ERROR(EIO);
b128c09f 8724 }
b5256303 8725 if (!valid_cksum || tfm_error != 0)
34dc7c2f
BB
8726 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
8727
34dc7c2f 8728 /*
b128c09f
BB
8729 * If there's no waiter, issue an async i/o to the primary
8730 * storage now. If there *is* a waiter, the caller must
8731 * issue the i/o in a context where it's OK to block.
34dc7c2f 8732 */
d164b209
BB
8733 if (zio->io_waiter == NULL) {
8734 zio_t *pio = zio_unique_parent(zio);
b5256303
TC
8735 void *abd = (using_rdata) ?
8736 hdr->b_crypt_hdr.b_rabd : hdr->b_l1hdr.b_pabd;
d164b209
BB
8737
8738 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
8739
5ff2249f 8740 zio = zio_read(pio, zio->io_spa, zio->io_bp,
b5256303 8741 abd, zio->io_size, arc_read_done,
d3c2ae1c 8742 hdr, zio->io_priority, cb->l2rcb_flags,
5ff2249f
AM
8743 &cb->l2rcb_zb);
8744
8745 /*
8746 * Original ZIO will be freed, so we need to update
8747 * ARC header with the new ZIO pointer to be used
8748 * by zio_change_priority() in arc_read().
8749 */
8750 for (struct arc_callback *acb = hdr->b_l1hdr.b_acb;
8751 acb != NULL; acb = acb->acb_next)
8752 acb->acb_zio_head = zio;
8753
8754 mutex_exit(hash_lock);
8755 zio_nowait(zio);
8756 } else {
8757 mutex_exit(hash_lock);
d164b209 8758 }
34dc7c2f
BB
8759 }
8760
8761 kmem_free(cb, sizeof (l2arc_read_callback_t));
8762}
8763
8764/*
8765 * This is the list priority from which the L2ARC will search for pages to
8766 * cache. This is used within loops (0..3) to cycle through lists in the
8767 * desired order. This order can have a significant effect on cache
8768 * performance.
8769 *
8770 * Currently the metadata lists are hit first, MFU then MRU, followed by
8771 * the data lists. This function returns a locked list, and also returns
8772 * the lock pointer.
8773 */
ca0bf58d
PS
8774static multilist_sublist_t *
8775l2arc_sublist_lock(int list_num)
34dc7c2f 8776{
ca0bf58d
PS
8777 multilist_t *ml = NULL;
8778 unsigned int idx;
34dc7c2f 8779
4aafab91 8780 ASSERT(list_num >= 0 && list_num < L2ARC_FEED_TYPES);
34dc7c2f
BB
8781
8782 switch (list_num) {
8783 case 0:
ffdf019c 8784 ml = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
34dc7c2f
BB
8785 break;
8786 case 1:
ffdf019c 8787 ml = &arc_mru->arcs_list[ARC_BUFC_METADATA];
34dc7c2f
BB
8788 break;
8789 case 2:
ffdf019c 8790 ml = &arc_mfu->arcs_list[ARC_BUFC_DATA];
34dc7c2f
BB
8791 break;
8792 case 3:
ffdf019c 8793 ml = &arc_mru->arcs_list[ARC_BUFC_DATA];
34dc7c2f 8794 break;
4aafab91
G
8795 default:
8796 return (NULL);
34dc7c2f
BB
8797 }
8798
ca0bf58d
PS
8799 /*
8800 * Return a randomly-selected sublist. This is acceptable
8801 * because the caller feeds only a little bit of data for each
8802 * call (8MB). Subsequent calls will result in different
8803 * sublists being selected.
8804 */
8805 idx = multilist_get_random_index(ml);
8806 return (multilist_sublist_lock(ml, idx));
34dc7c2f
BB
8807}
8808
77f6826b
GA
8809/*
8810 * Calculates the maximum overhead of L2ARC metadata log blocks for a given
657fd33b 8811 * L2ARC write size. l2arc_evict and l2arc_write_size need to include this
77f6826b
GA
8812 * overhead in processing to make sure there is enough headroom available
8813 * when writing buffers.
8814 */
8815static inline uint64_t
8816l2arc_log_blk_overhead(uint64_t write_sz, l2arc_dev_t *dev)
8817{
657fd33b 8818 if (dev->l2ad_log_entries == 0) {
77f6826b
GA
8819 return (0);
8820 } else {
8821 uint64_t log_entries = write_sz >> SPA_MINBLOCKSHIFT;
8822
8823 uint64_t log_blocks = (log_entries +
657fd33b
GA
8824 dev->l2ad_log_entries - 1) /
8825 dev->l2ad_log_entries;
77f6826b
GA
8826
8827 return (vdev_psize_to_asize(dev->l2ad_vdev,
8828 sizeof (l2arc_log_blk_phys_t)) * log_blocks);
8829 }
8830}
8831
34dc7c2f
BB
8832/*
8833 * Evict buffers from the device write hand to the distance specified in
77f6826b 8834 * bytes. This distance may span populated buffers, it may span nothing.
34dc7c2f
BB
8835 * This is clearing a region on the L2ARC device ready for writing.
8836 * If the 'all' boolean is set, every buffer is evicted.
8837 */
8838static void
8839l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
8840{
8841 list_t *buflist;
2a432414 8842 arc_buf_hdr_t *hdr, *hdr_prev;
34dc7c2f
BB
8843 kmutex_t *hash_lock;
8844 uint64_t taddr;
77f6826b 8845 l2arc_lb_ptr_buf_t *lb_ptr_buf, *lb_ptr_buf_prev;
b7654bd7
GA
8846 vdev_t *vd = dev->l2ad_vdev;
8847 boolean_t rerun;
34dc7c2f 8848
b9541d6b 8849 buflist = &dev->l2ad_buflist;
34dc7c2f 8850
37c22948
GA
8851top:
8852 rerun = B_FALSE;
8853 if (dev->l2ad_hand >= (dev->l2ad_end - distance)) {
34dc7c2f 8854 /*
dd4bc569 8855 * When there is no space to accommodate upcoming writes,
77f6826b
GA
8856 * evict to the end. Then bump the write and evict hands
8857 * to the start and iterate. This iteration does not
8858 * happen indefinitely as we make sure in
8859 * l2arc_write_size() that when the write hand is reset,
8860 * the write size does not exceed the end of the device.
34dc7c2f 8861 */
37c22948 8862 rerun = B_TRUE;
34dc7c2f
BB
8863 taddr = dev->l2ad_end;
8864 } else {
8865 taddr = dev->l2ad_hand + distance;
8866 }
8867 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
8868 uint64_t, taddr, boolean_t, all);
8869
b7654bd7 8870 if (!all) {
37c22948 8871 /*
b7654bd7
GA
8872 * This check has to be placed after deciding whether to
8873 * iterate (rerun).
37c22948 8874 */
b7654bd7
GA
8875 if (dev->l2ad_first) {
8876 /*
8877 * This is the first sweep through the device. There is
8878 * nothing to evict. We have already trimmmed the
8879 * whole device.
8880 */
8881 goto out;
8882 } else {
8883 /*
8884 * Trim the space to be evicted.
8885 */
8886 if (vd->vdev_has_trim && dev->l2ad_evict < taddr &&
8887 l2arc_trim_ahead > 0) {
8888 /*
8889 * We have to drop the spa_config lock because
8890 * vdev_trim_range() will acquire it.
8891 * l2ad_evict already accounts for the label
8892 * size. To prevent vdev_trim_ranges() from
8893 * adding it again, we subtract it from
8894 * l2ad_evict.
8895 */
8896 spa_config_exit(dev->l2ad_spa, SCL_L2ARC, dev);
8897 vdev_trim_simple(vd,
8898 dev->l2ad_evict - VDEV_LABEL_START_SIZE,
8899 taddr - dev->l2ad_evict);
8900 spa_config_enter(dev->l2ad_spa, SCL_L2ARC, dev,
8901 RW_READER);
8902 }
37c22948 8903
b7654bd7
GA
8904 /*
8905 * When rebuilding L2ARC we retrieve the evict hand
8906 * from the header of the device. Of note, l2arc_evict()
8907 * does not actually delete buffers from the cache
8908 * device, but trimming may do so depending on the
8909 * hardware implementation. Thus keeping track of the
8910 * evict hand is useful.
8911 */
8912 dev->l2ad_evict = MAX(dev->l2ad_evict, taddr);
8913 }
8914 }
77f6826b 8915
37c22948 8916retry:
b9541d6b 8917 mutex_enter(&dev->l2ad_mtx);
77f6826b
GA
8918 /*
8919 * We have to account for evicted log blocks. Run vdev_space_update()
8920 * on log blocks whose offset (in bytes) is before the evicted offset
8921 * (in bytes) by searching in the list of pointers to log blocks
8922 * present in the L2ARC device.
8923 */
8924 for (lb_ptr_buf = list_tail(&dev->l2ad_lbptr_list); lb_ptr_buf;
8925 lb_ptr_buf = lb_ptr_buf_prev) {
8926
8927 lb_ptr_buf_prev = list_prev(&dev->l2ad_lbptr_list, lb_ptr_buf);
8928
657fd33b
GA
8929 /* L2BLK_GET_PSIZE returns aligned size for log blocks */
8930 uint64_t asize = L2BLK_GET_PSIZE(
8931 (lb_ptr_buf->lb_ptr)->lbp_prop);
8932
77f6826b
GA
8933 /*
8934 * We don't worry about log blocks left behind (ie
657fd33b 8935 * lbp_payload_start < l2ad_hand) because l2arc_write_buffers()
77f6826b
GA
8936 * will never write more than l2arc_evict() evicts.
8937 */
8938 if (!all && l2arc_log_blkptr_valid(dev, lb_ptr_buf->lb_ptr)) {
8939 break;
8940 } else {
b7654bd7 8941 vdev_space_update(vd, -asize, 0, 0);
657fd33b
GA
8942 ARCSTAT_INCR(arcstat_l2_log_blk_asize, -asize);
8943 ARCSTAT_BUMPDOWN(arcstat_l2_log_blk_count);
8944 zfs_refcount_remove_many(&dev->l2ad_lb_asize, asize,
8945 lb_ptr_buf);
8946 zfs_refcount_remove(&dev->l2ad_lb_count, lb_ptr_buf);
77f6826b
GA
8947 list_remove(&dev->l2ad_lbptr_list, lb_ptr_buf);
8948 kmem_free(lb_ptr_buf->lb_ptr,
8949 sizeof (l2arc_log_blkptr_t));
8950 kmem_free(lb_ptr_buf, sizeof (l2arc_lb_ptr_buf_t));
8951 }
8952 }
8953
2a432414
GW
8954 for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
8955 hdr_prev = list_prev(buflist, hdr);
34dc7c2f 8956
ca6c7a94 8957 ASSERT(!HDR_EMPTY(hdr));
2a432414 8958 hash_lock = HDR_LOCK(hdr);
ca0bf58d
PS
8959
8960 /*
8961 * We cannot use mutex_enter or else we can deadlock
8962 * with l2arc_write_buffers (due to swapping the order
8963 * the hash lock and l2ad_mtx are taken).
8964 */
34dc7c2f
BB
8965 if (!mutex_tryenter(hash_lock)) {
8966 /*
8967 * Missed the hash lock. Retry.
8968 */
8969 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
b9541d6b 8970 mutex_exit(&dev->l2ad_mtx);
34dc7c2f
BB
8971 mutex_enter(hash_lock);
8972 mutex_exit(hash_lock);
37c22948 8973 goto retry;
34dc7c2f
BB
8974 }
8975
f06f53fa
AG
8976 /*
8977 * A header can't be on this list if it doesn't have L2 header.
8978 */
8979 ASSERT(HDR_HAS_L2HDR(hdr));
34dc7c2f 8980
f06f53fa
AG
8981 /* Ensure this header has finished being written. */
8982 ASSERT(!HDR_L2_WRITING(hdr));
8983 ASSERT(!HDR_L2_WRITE_HEAD(hdr));
8984
77f6826b 8985 if (!all && (hdr->b_l2hdr.b_daddr >= dev->l2ad_evict ||
b9541d6b 8986 hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
34dc7c2f
BB
8987 /*
8988 * We've evicted to the target address,
8989 * or the end of the device.
8990 */
8991 mutex_exit(hash_lock);
8992 break;
8993 }
8994
b9541d6b 8995 if (!HDR_HAS_L1HDR(hdr)) {
2a432414 8996 ASSERT(!HDR_L2_READING(hdr));
34dc7c2f
BB
8997 /*
8998 * This doesn't exist in the ARC. Destroy.
8999 * arc_hdr_destroy() will call list_remove()
01850391 9000 * and decrement arcstat_l2_lsize.
34dc7c2f 9001 */
c935fe2e 9002 arc_change_state(arc_anon, hdr);
2a432414 9003 arc_hdr_destroy(hdr);
34dc7c2f 9004 } else {
b9541d6b
CW
9005 ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
9006 ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
b128c09f
BB
9007 /*
9008 * Invalidate issued or about to be issued
9009 * reads, since we may be about to write
9010 * over this location.
9011 */
2a432414 9012 if (HDR_L2_READING(hdr)) {
b128c09f 9013 ARCSTAT_BUMP(arcstat_l2_evict_reading);
d3c2ae1c 9014 arc_hdr_set_flags(hdr, ARC_FLAG_L2_EVICTED);
b128c09f
BB
9015 }
9016
d962d5da 9017 arc_hdr_l2hdr_destroy(hdr);
34dc7c2f
BB
9018 }
9019 mutex_exit(hash_lock);
9020 }
b9541d6b 9021 mutex_exit(&dev->l2ad_mtx);
37c22948
GA
9022
9023out:
77f6826b
GA
9024 /*
9025 * We need to check if we evict all buffers, otherwise we may iterate
9026 * unnecessarily.
9027 */
9028 if (!all && rerun) {
37c22948
GA
9029 /*
9030 * Bump device hand to the device start if it is approaching the
9031 * end. l2arc_evict() has already evicted ahead for this case.
9032 */
9033 dev->l2ad_hand = dev->l2ad_start;
77f6826b 9034 dev->l2ad_evict = dev->l2ad_start;
37c22948
GA
9035 dev->l2ad_first = B_FALSE;
9036 goto top;
9037 }
657fd33b 9038
2c210f68
GA
9039 if (!all) {
9040 /*
9041 * In case of cache device removal (all) the following
9042 * assertions may be violated without functional consequences
9043 * as the device is about to be removed.
9044 */
9045 ASSERT3U(dev->l2ad_hand + distance, <, dev->l2ad_end);
9046 if (!dev->l2ad_first)
9047 ASSERT3U(dev->l2ad_hand, <, dev->l2ad_evict);
9048 }
34dc7c2f
BB
9049}
9050
b5256303
TC
9051/*
9052 * Handle any abd transforms that might be required for writing to the L2ARC.
9053 * If successful, this function will always return an abd with the data
9054 * transformed as it is on disk in a new abd of asize bytes.
9055 */
9056static int
9057l2arc_apply_transforms(spa_t *spa, arc_buf_hdr_t *hdr, uint64_t asize,
9058 abd_t **abd_out)
9059{
9060 int ret;
9061 void *tmp = NULL;
9062 abd_t *cabd = NULL, *eabd = NULL, *to_write = hdr->b_l1hdr.b_pabd;
9063 enum zio_compress compress = HDR_GET_COMPRESS(hdr);
9064 uint64_t psize = HDR_GET_PSIZE(hdr);
9065 uint64_t size = arc_hdr_size(hdr);
9066 boolean_t ismd = HDR_ISTYPE_METADATA(hdr);
9067 boolean_t bswap = (hdr->b_l1hdr.b_byteswap != DMU_BSWAP_NUMFUNCS);
9068 dsl_crypto_key_t *dck = NULL;
9069 uint8_t mac[ZIO_DATA_MAC_LEN] = { 0 };
4807c0ba 9070 boolean_t no_crypt = B_FALSE;
b5256303
TC
9071
9072 ASSERT((HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
9073 !HDR_COMPRESSION_ENABLED(hdr)) ||
9074 HDR_ENCRYPTED(hdr) || HDR_SHARED_DATA(hdr) || psize != asize);
9075 ASSERT3U(psize, <=, asize);
9076
9077 /*
9078 * If this data simply needs its own buffer, we simply allocate it
b7109a41 9079 * and copy the data. This may be done to eliminate a dependency on a
b5256303
TC
9080 * shared buffer or to reallocate the buffer to match asize.
9081 */
4807c0ba 9082 if (HDR_HAS_RABD(hdr) && asize != psize) {
10adee27 9083 ASSERT3U(asize, >=, psize);
4807c0ba 9084 to_write = abd_alloc_for_io(asize, ismd);
10adee27
TC
9085 abd_copy(to_write, hdr->b_crypt_hdr.b_rabd, psize);
9086 if (psize != asize)
9087 abd_zero_off(to_write, psize, asize - psize);
4807c0ba
TC
9088 goto out;
9089 }
9090
b5256303
TC
9091 if ((compress == ZIO_COMPRESS_OFF || HDR_COMPRESSION_ENABLED(hdr)) &&
9092 !HDR_ENCRYPTED(hdr)) {
9093 ASSERT3U(size, ==, psize);
9094 to_write = abd_alloc_for_io(asize, ismd);
9095 abd_copy(to_write, hdr->b_l1hdr.b_pabd, size);
9096 if (size != asize)
9097 abd_zero_off(to_write, size, asize - size);
9098 goto out;
9099 }
9100
9101 if (compress != ZIO_COMPRESS_OFF && !HDR_COMPRESSION_ENABLED(hdr)) {
7bf06f72
RE
9102 /*
9103 * In some cases, we can wind up with size > asize, so
9104 * we need to opt for the larger allocation option here.
9105 *
9106 * (We also need abd_return_buf_copy in all cases because
9107 * it's an ASSERT() to modify the buffer before returning it
9108 * with arc_return_buf(), and all the compressors
9109 * write things before deciding to fail compression in nearly
9110 * every case.)
9111 */
9112 cabd = abd_alloc_for_io(size, ismd);
9113 tmp = abd_borrow_buf(cabd, size);
b5256303 9114
bff26b02 9115 psize = zio_compress_data(compress, to_write, &tmp, size,
10b3c7f5
MN
9116 hdr->b_complevel);
9117
7bf06f72
RE
9118 if (psize >= asize) {
9119 psize = HDR_GET_PSIZE(hdr);
9120 abd_return_buf_copy(cabd, tmp, size);
10b3c7f5
MN
9121 HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_OFF);
9122 to_write = cabd;
7bf06f72
RE
9123 abd_copy(to_write, hdr->b_l1hdr.b_pabd, psize);
9124 if (psize != asize)
9125 abd_zero_off(to_write, psize, asize - psize);
10b3c7f5
MN
9126 goto encrypt;
9127 }
b5256303
TC
9128 ASSERT3U(psize, <=, HDR_GET_PSIZE(hdr));
9129 if (psize < asize)
861166b0 9130 memset((char *)tmp + psize, 0, asize - psize);
b5256303 9131 psize = HDR_GET_PSIZE(hdr);
7bf06f72 9132 abd_return_buf_copy(cabd, tmp, size);
b5256303
TC
9133 to_write = cabd;
9134 }
9135
10b3c7f5 9136encrypt:
b5256303
TC
9137 if (HDR_ENCRYPTED(hdr)) {
9138 eabd = abd_alloc_for_io(asize, ismd);
9139
9140 /*
9141 * If the dataset was disowned before the buffer
9142 * made it to this point, the key to re-encrypt
9143 * it won't be available. In this case we simply
9144 * won't write the buffer to the L2ARC.
9145 */
9146 ret = spa_keystore_lookup_key(spa, hdr->b_crypt_hdr.b_dsobj,
9147 FTAG, &dck);
9148 if (ret != 0)
9149 goto error;
9150
10fa2545 9151 ret = zio_do_crypt_abd(B_TRUE, &dck->dck_key,
be9a5c35
TC
9152 hdr->b_crypt_hdr.b_ot, bswap, hdr->b_crypt_hdr.b_salt,
9153 hdr->b_crypt_hdr.b_iv, mac, psize, to_write, eabd,
9154 &no_crypt);
b5256303
TC
9155 if (ret != 0)
9156 goto error;
9157
4807c0ba
TC
9158 if (no_crypt)
9159 abd_copy(eabd, to_write, psize);
b5256303
TC
9160
9161 if (psize != asize)
9162 abd_zero_off(eabd, psize, asize - psize);
9163
9164 /* assert that the MAC we got here matches the one we saved */
861166b0 9165 ASSERT0(memcmp(mac, hdr->b_crypt_hdr.b_mac, ZIO_DATA_MAC_LEN));
b5256303
TC
9166 spa_keystore_dsl_key_rele(spa, dck, FTAG);
9167
9168 if (to_write == cabd)
9169 abd_free(cabd);
9170
9171 to_write = eabd;
9172 }
9173
9174out:
9175 ASSERT3P(to_write, !=, hdr->b_l1hdr.b_pabd);
9176 *abd_out = to_write;
9177 return (0);
9178
9179error:
9180 if (dck != NULL)
9181 spa_keystore_dsl_key_rele(spa, dck, FTAG);
9182 if (cabd != NULL)
9183 abd_free(cabd);
9184 if (eabd != NULL)
9185 abd_free(eabd);
9186
9187 *abd_out = NULL;
9188 return (ret);
9189}
9190
77f6826b
GA
9191static void
9192l2arc_blk_fetch_done(zio_t *zio)
9193{
9194 l2arc_read_callback_t *cb;
9195
9196 cb = zio->io_private;
9197 if (cb->l2rcb_abd != NULL)
e2af2acc 9198 abd_free(cb->l2rcb_abd);
77f6826b
GA
9199 kmem_free(cb, sizeof (l2arc_read_callback_t));
9200}
9201
34dc7c2f
BB
9202/*
9203 * Find and write ARC buffers to the L2ARC device.
9204 *
2a432414 9205 * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
34dc7c2f 9206 * for reading until they have completed writing.
3a17a7a9
SK
9207 * The headroom_boost is an in-out parameter used to maintain headroom boost
9208 * state between calls to this function.
9209 *
9210 * Returns the number of bytes actually written (which may be smaller than
77f6826b
GA
9211 * the delta by which the device hand has changed due to alignment and the
9212 * writing of log blocks).
34dc7c2f 9213 */
d164b209 9214static uint64_t
d3c2ae1c 9215l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
34dc7c2f 9216{
77f6826b
GA
9217 arc_buf_hdr_t *hdr, *hdr_prev, *head;
9218 uint64_t write_asize, write_psize, write_lsize, headroom;
9219 boolean_t full;
9220 l2arc_write_callback_t *cb = NULL;
9221 zio_t *pio, *wzio;
9222 uint64_t guid = spa_load_guid(spa);
0ae184a6 9223 l2arc_dev_hdr_phys_t *l2dhdr = dev->l2ad_dev_hdr;
34dc7c2f 9224
d3c2ae1c 9225 ASSERT3P(dev->l2ad_vdev, !=, NULL);
3a17a7a9 9226
34dc7c2f 9227 pio = NULL;
01850391 9228 write_lsize = write_asize = write_psize = 0;
34dc7c2f 9229 full = B_FALSE;
b9541d6b 9230 head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
d3c2ae1c 9231 arc_hdr_set_flags(head, ARC_FLAG_L2_WRITE_HEAD | ARC_FLAG_HAS_L2HDR);
3a17a7a9 9232
34dc7c2f
BB
9233 /*
9234 * Copy buffers for L2ARC writing.
9235 */
4a90d4d6 9236 for (int pass = 0; pass < L2ARC_FEED_TYPES; pass++) {
feb3a7ee 9237 /*
4a90d4d6 9238 * If pass == 1 or 3, we cache MRU metadata and data
feb3a7ee
GA
9239 * respectively.
9240 */
9241 if (l2arc_mfuonly) {
4a90d4d6 9242 if (pass == 1 || pass == 3)
feb3a7ee
GA
9243 continue;
9244 }
9245
4a90d4d6 9246 multilist_sublist_t *mls = l2arc_sublist_lock(pass);
3a17a7a9
SK
9247 uint64_t passed_sz = 0;
9248
4aafab91
G
9249 VERIFY3P(mls, !=, NULL);
9250
b128c09f
BB
9251 /*
9252 * L2ARC fast warmup.
9253 *
9254 * Until the ARC is warm and starts to evict, read from the
9255 * head of the ARC lists rather than the tail.
9256 */
b128c09f 9257 if (arc_warm == B_FALSE)
ca0bf58d 9258 hdr = multilist_sublist_head(mls);
b128c09f 9259 else
ca0bf58d 9260 hdr = multilist_sublist_tail(mls);
b128c09f 9261
3a17a7a9 9262 headroom = target_sz * l2arc_headroom;
d3c2ae1c 9263 if (zfs_compressed_arc_enabled)
3a17a7a9
SK
9264 headroom = (headroom * l2arc_headroom_boost) / 100;
9265
2a432414 9266 for (; hdr; hdr = hdr_prev) {
3a17a7a9 9267 kmutex_t *hash_lock;
b5256303 9268 abd_t *to_write = NULL;
3a17a7a9 9269
b128c09f 9270 if (arc_warm == B_FALSE)
ca0bf58d 9271 hdr_prev = multilist_sublist_next(mls, hdr);
b128c09f 9272 else
ca0bf58d 9273 hdr_prev = multilist_sublist_prev(mls, hdr);
34dc7c2f 9274
2a432414 9275 hash_lock = HDR_LOCK(hdr);
3a17a7a9 9276 if (!mutex_tryenter(hash_lock)) {
34dc7c2f
BB
9277 /*
9278 * Skip this buffer rather than waiting.
9279 */
9280 continue;
9281 }
9282
d3c2ae1c 9283 passed_sz += HDR_GET_LSIZE(hdr);
77f6826b 9284 if (l2arc_headroom != 0 && passed_sz > headroom) {
34dc7c2f
BB
9285 /*
9286 * Searched too far.
9287 */
9288 mutex_exit(hash_lock);
9289 break;
9290 }
9291
2a432414 9292 if (!l2arc_write_eligible(guid, hdr)) {
34dc7c2f
BB
9293 mutex_exit(hash_lock);
9294 continue;
9295 }
9296
01850391
AG
9297 ASSERT(HDR_HAS_L1HDR(hdr));
9298
9299 ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
01850391 9300 ASSERT3U(arc_hdr_size(hdr), >, 0);
b5256303
TC
9301 ASSERT(hdr->b_l1hdr.b_pabd != NULL ||
9302 HDR_HAS_RABD(hdr));
9303 uint64_t psize = HDR_GET_PSIZE(hdr);
01850391
AG
9304 uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev,
9305 psize);
9306
9307 if ((write_asize + asize) > target_sz) {
34dc7c2f
BB
9308 full = B_TRUE;
9309 mutex_exit(hash_lock);
9310 break;
9311 }
9312
b5256303
TC
9313 /*
9314 * We rely on the L1 portion of the header below, so
9315 * it's invalid for this header to have been evicted out
9316 * of the ghost cache, prior to being written out. The
9317 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
9318 */
9319 arc_hdr_set_flags(hdr, ARC_FLAG_L2_WRITING);
b5256303
TC
9320
9321 /*
9322 * If this header has b_rabd, we can use this since it
9323 * must always match the data exactly as it exists on
9777044f 9324 * disk. Otherwise, the L2ARC can normally use the
b5256303
TC
9325 * hdr's data, but if we're sharing data between the
9326 * hdr and one of its bufs, L2ARC needs its own copy of
9327 * the data so that the ZIO below can't race with the
9328 * buf consumer. To ensure that this copy will be
9329 * available for the lifetime of the ZIO and be cleaned
9330 * up afterwards, we add it to the l2arc_free_on_write
9331 * queue. If we need to apply any transforms to the
9332 * data (compression, encryption) we will also need the
9333 * extra buffer.
9334 */
9335 if (HDR_HAS_RABD(hdr) && psize == asize) {
9336 to_write = hdr->b_crypt_hdr.b_rabd;
9337 } else if ((HDR_COMPRESSION_ENABLED(hdr) ||
9338 HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_OFF) &&
9339 !HDR_ENCRYPTED(hdr) && !HDR_SHARED_DATA(hdr) &&
9340 psize == asize) {
9341 to_write = hdr->b_l1hdr.b_pabd;
9342 } else {
9343 int ret;
9344 arc_buf_contents_t type = arc_buf_type(hdr);
9345
9346 ret = l2arc_apply_transforms(spa, hdr, asize,
9347 &to_write);
9348 if (ret != 0) {
9349 arc_hdr_clear_flags(hdr,
9350 ARC_FLAG_L2_WRITING);
9351 mutex_exit(hash_lock);
9352 continue;
9353 }
9354
9355 l2arc_free_abd_on_write(to_write, asize, type);
9356 }
9357
34dc7c2f
BB
9358 if (pio == NULL) {
9359 /*
9360 * Insert a dummy header on the buflist so
9361 * l2arc_write_done() can find where the
9362 * write buffers begin without searching.
9363 */
ca0bf58d 9364 mutex_enter(&dev->l2ad_mtx);
b9541d6b 9365 list_insert_head(&dev->l2ad_buflist, head);
ca0bf58d 9366 mutex_exit(&dev->l2ad_mtx);
34dc7c2f 9367
96c080cb
BB
9368 cb = kmem_alloc(
9369 sizeof (l2arc_write_callback_t), KM_SLEEP);
34dc7c2f
BB
9370 cb->l2wcb_dev = dev;
9371 cb->l2wcb_head = head;
657fd33b
GA
9372 /*
9373 * Create a list to save allocated abd buffers
9374 * for l2arc_log_blk_commit().
9375 */
77f6826b
GA
9376 list_create(&cb->l2wcb_abd_list,
9377 sizeof (l2arc_lb_abd_buf_t),
9378 offsetof(l2arc_lb_abd_buf_t, node));
34dc7c2f
BB
9379 pio = zio_root(spa, l2arc_write_done, cb,
9380 ZIO_FLAG_CANFAIL);
9381 }
9382
b9541d6b 9383 hdr->b_l2hdr.b_dev = dev;
b9541d6b 9384 hdr->b_l2hdr.b_hits = 0;
3a17a7a9 9385
d3c2ae1c 9386 hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
08532162
GA
9387 hdr->b_l2hdr.b_arcs_state =
9388 hdr->b_l1hdr.b_state->arcs_state;
b5256303 9389 arc_hdr_set_flags(hdr, ARC_FLAG_HAS_L2HDR);
3a17a7a9 9390
ca0bf58d 9391 mutex_enter(&dev->l2ad_mtx);
b9541d6b 9392 list_insert_head(&dev->l2ad_buflist, hdr);
ca0bf58d 9393 mutex_exit(&dev->l2ad_mtx);
34dc7c2f 9394
424fd7c3 9395 (void) zfs_refcount_add_many(&dev->l2ad_alloc,
b5256303 9396 arc_hdr_size(hdr), hdr);
3a17a7a9 9397
34dc7c2f 9398 wzio = zio_write_phys(pio, dev->l2ad_vdev,
82710e99 9399 hdr->b_l2hdr.b_daddr, asize, to_write,
d3c2ae1c
GW
9400 ZIO_CHECKSUM_OFF, NULL, hdr,
9401 ZIO_PRIORITY_ASYNC_WRITE,
34dc7c2f
BB
9402 ZIO_FLAG_CANFAIL, B_FALSE);
9403
01850391 9404 write_lsize += HDR_GET_LSIZE(hdr);
34dc7c2f
BB
9405 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
9406 zio_t *, wzio);
d962d5da 9407
01850391
AG
9408 write_psize += psize;
9409 write_asize += asize;
d3c2ae1c 9410 dev->l2ad_hand += asize;
08532162 9411 l2arc_hdr_arcstats_increment(hdr);
7558997d 9412 vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
d3c2ae1c
GW
9413
9414 mutex_exit(hash_lock);
9415
77f6826b
GA
9416 /*
9417 * Append buf info to current log and commit if full.
9418 * arcstat_l2_{size,asize} kstats are updated
9419 * internally.
9420 */
bcd53210
GA
9421 if (l2arc_log_blk_insert(dev, hdr)) {
9422 /*
9423 * l2ad_hand has been accounted for in
9424 * l2arc_log_blk_commit().
9425 */
9426 write_asize +=
9427 l2arc_log_blk_commit(dev, pio, cb);
9428 }
77f6826b 9429
9cdf7b1f 9430 zio_nowait(wzio);
34dc7c2f 9431 }
d3c2ae1c
GW
9432
9433 multilist_sublist_unlock(mls);
9434
9435 if (full == B_TRUE)
9436 break;
34dc7c2f 9437 }
34dc7c2f 9438
d3c2ae1c
GW
9439 /* No buffers selected for writing? */
9440 if (pio == NULL) {
01850391 9441 ASSERT0(write_lsize);
d3c2ae1c
GW
9442 ASSERT(!HDR_HAS_L1HDR(head));
9443 kmem_cache_free(hdr_l2only_cache, head);
77f6826b
GA
9444
9445 /*
9446 * Although we did not write any buffers l2ad_evict may
9447 * have advanced.
9448 */
0ae184a6
GA
9449 if (dev->l2ad_evict != l2dhdr->dh_evict)
9450 l2arc_dev_hdr_update(dev);
77f6826b 9451
d3c2ae1c
GW
9452 return (0);
9453 }
34dc7c2f 9454
657fd33b
GA
9455 if (!dev->l2ad_first)
9456 ASSERT3U(dev->l2ad_hand, <=, dev->l2ad_evict);
9457
3a17a7a9 9458 ASSERT3U(write_asize, <=, target_sz);
34dc7c2f 9459 ARCSTAT_BUMP(arcstat_l2_writes_sent);
01850391 9460 ARCSTAT_INCR(arcstat_l2_write_bytes, write_psize);
34dc7c2f 9461
d164b209 9462 dev->l2ad_writing = B_TRUE;
34dc7c2f 9463 (void) zio_wait(pio);
d164b209
BB
9464 dev->l2ad_writing = B_FALSE;
9465
2054f35e
GA
9466 /*
9467 * Update the device header after the zio completes as
9468 * l2arc_write_done() may have updated the memory holding the log block
9469 * pointers in the device header.
9470 */
9471 l2arc_dev_hdr_update(dev);
9472
3a17a7a9
SK
9473 return (write_asize);
9474}
9475
523e1295
AM
9476static boolean_t
9477l2arc_hdr_limit_reached(void)
9478{
c4c162c1 9479 int64_t s = aggsum_upper_bound(&arc_sums.arcstat_l2_hdr_size);
523e1295 9480
a8d83e2a 9481 return (arc_reclaim_needed() ||
523e1295
AM
9482 (s > (arc_warm ? arc_c : arc_c_max) * l2arc_meta_percent / 100));
9483}
9484
34dc7c2f
BB
9485/*
9486 * This thread feeds the L2ARC at regular intervals. This is the beating
9487 * heart of the L2ARC.
9488 */
460748d4 9489static __attribute__((noreturn)) void
c25b8f99 9490l2arc_feed_thread(void *unused)
34dc7c2f 9491{
14e4e3cb 9492 (void) unused;
34dc7c2f
BB
9493 callb_cpr_t cpr;
9494 l2arc_dev_t *dev;
9495 spa_t *spa;
d164b209 9496 uint64_t size, wrote;
428870ff 9497 clock_t begin, next = ddi_get_lbolt();
40d06e3c 9498 fstrans_cookie_t cookie;
34dc7c2f
BB
9499
9500 CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
9501
9502 mutex_enter(&l2arc_feed_thr_lock);
9503
40d06e3c 9504 cookie = spl_fstrans_mark();
34dc7c2f 9505 while (l2arc_thread_exit == 0) {
34dc7c2f 9506 CALLB_CPR_SAFE_BEGIN(&cpr);
ac6e5fb2 9507 (void) cv_timedwait_idle(&l2arc_feed_thr_cv,
5b63b3eb 9508 &l2arc_feed_thr_lock, next);
34dc7c2f 9509 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
428870ff 9510 next = ddi_get_lbolt() + hz;
34dc7c2f
BB
9511
9512 /*
b128c09f 9513 * Quick check for L2ARC devices.
34dc7c2f
BB
9514 */
9515 mutex_enter(&l2arc_dev_mtx);
9516 if (l2arc_ndev == 0) {
9517 mutex_exit(&l2arc_dev_mtx);
9518 continue;
9519 }
b128c09f 9520 mutex_exit(&l2arc_dev_mtx);
428870ff 9521 begin = ddi_get_lbolt();
34dc7c2f
BB
9522
9523 /*
b128c09f
BB
9524 * This selects the next l2arc device to write to, and in
9525 * doing so the next spa to feed from: dev->l2ad_spa. This
9526 * will return NULL if there are now no l2arc devices or if
9527 * they are all faulted.
9528 *
9529 * If a device is returned, its spa's config lock is also
9530 * held to prevent device removal. l2arc_dev_get_next()
9531 * will grab and release l2arc_dev_mtx.
34dc7c2f 9532 */
b128c09f 9533 if ((dev = l2arc_dev_get_next()) == NULL)
34dc7c2f 9534 continue;
b128c09f
BB
9535
9536 spa = dev->l2ad_spa;
d3c2ae1c 9537 ASSERT3P(spa, !=, NULL);
34dc7c2f 9538
572e2857
BB
9539 /*
9540 * If the pool is read-only then force the feed thread to
9541 * sleep a little longer.
9542 */
9543 if (!spa_writeable(spa)) {
9544 next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
9545 spa_config_exit(spa, SCL_L2ARC, dev);
9546 continue;
9547 }
9548
34dc7c2f 9549 /*
b128c09f 9550 * Avoid contributing to memory pressure.
34dc7c2f 9551 */
523e1295 9552 if (l2arc_hdr_limit_reached()) {
b128c09f
BB
9553 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
9554 spa_config_exit(spa, SCL_L2ARC, dev);
34dc7c2f
BB
9555 continue;
9556 }
b128c09f 9557
34dc7c2f
BB
9558 ARCSTAT_BUMP(arcstat_l2_feeds);
9559
37c22948 9560 size = l2arc_write_size(dev);
b128c09f 9561
34dc7c2f
BB
9562 /*
9563 * Evict L2ARC buffers that will be overwritten.
9564 */
b128c09f 9565 l2arc_evict(dev, size, B_FALSE);
34dc7c2f
BB
9566
9567 /*
9568 * Write ARC buffers.
9569 */
d3c2ae1c 9570 wrote = l2arc_write_buffers(spa, dev, size);
d164b209
BB
9571
9572 /*
9573 * Calculate interval between writes.
9574 */
9575 next = l2arc_write_interval(begin, size, wrote);
b128c09f 9576 spa_config_exit(spa, SCL_L2ARC, dev);
34dc7c2f 9577 }
40d06e3c 9578 spl_fstrans_unmark(cookie);
34dc7c2f
BB
9579
9580 l2arc_thread_exit = 0;
9581 cv_broadcast(&l2arc_feed_thr_cv);
9582 CALLB_CPR_EXIT(&cpr); /* drops l2arc_feed_thr_lock */
9583 thread_exit();
9584}
9585
b128c09f
BB
9586boolean_t
9587l2arc_vdev_present(vdev_t *vd)
9588{
77f6826b
GA
9589 return (l2arc_vdev_get(vd) != NULL);
9590}
9591
9592/*
9593 * Returns the l2arc_dev_t associated with a particular vdev_t or NULL if
9594 * the vdev_t isn't an L2ARC device.
9595 */
b7654bd7 9596l2arc_dev_t *
77f6826b
GA
9597l2arc_vdev_get(vdev_t *vd)
9598{
9599 l2arc_dev_t *dev;
b128c09f
BB
9600
9601 mutex_enter(&l2arc_dev_mtx);
9602 for (dev = list_head(l2arc_dev_list); dev != NULL;
9603 dev = list_next(l2arc_dev_list, dev)) {
9604 if (dev->l2ad_vdev == vd)
9605 break;
9606 }
9607 mutex_exit(&l2arc_dev_mtx);
9608
77f6826b 9609 return (dev);
b128c09f
BB
9610}
9611
ab8a8f07
GA
9612static void
9613l2arc_rebuild_dev(l2arc_dev_t *dev, boolean_t reopen)
9614{
9615 l2arc_dev_hdr_phys_t *l2dhdr = dev->l2ad_dev_hdr;
9616 uint64_t l2dhdr_asize = dev->l2ad_dev_hdr_asize;
9617 spa_t *spa = dev->l2ad_spa;
9618
9619 /*
9620 * The L2ARC has to hold at least the payload of one log block for
9621 * them to be restored (persistent L2ARC). The payload of a log block
9622 * depends on the amount of its log entries. We always write log blocks
9623 * with 1022 entries. How many of them are committed or restored depends
9624 * on the size of the L2ARC device. Thus the maximum payload of
9625 * one log block is 1022 * SPA_MAXBLOCKSIZE = 16GB. If the L2ARC device
9626 * is less than that, we reduce the amount of committed and restored
9627 * log entries per block so as to enable persistence.
9628 */
9629 if (dev->l2ad_end < l2arc_rebuild_blocks_min_l2size) {
9630 dev->l2ad_log_entries = 0;
9631 } else {
9632 dev->l2ad_log_entries = MIN((dev->l2ad_end -
9633 dev->l2ad_start) >> SPA_MAXBLOCKSHIFT,
9634 L2ARC_LOG_BLK_MAX_ENTRIES);
9635 }
9636
9637 /*
9638 * Read the device header, if an error is returned do not rebuild L2ARC.
9639 */
9640 if (l2arc_dev_hdr_read(dev) == 0 && dev->l2ad_log_entries > 0) {
9641 /*
9642 * If we are onlining a cache device (vdev_reopen) that was
9643 * still present (l2arc_vdev_present()) and rebuild is enabled,
9644 * we should evict all ARC buffers and pointers to log blocks
9645 * and reclaim their space before restoring its contents to
9646 * L2ARC.
9647 */
9648 if (reopen) {
9649 if (!l2arc_rebuild_enabled) {
9650 return;
9651 } else {
9652 l2arc_evict(dev, 0, B_TRUE);
9653 /* start a new log block */
9654 dev->l2ad_log_ent_idx = 0;
9655 dev->l2ad_log_blk_payload_asize = 0;
9656 dev->l2ad_log_blk_payload_start = 0;
9657 }
9658 }
9659 /*
9660 * Just mark the device as pending for a rebuild. We won't
9661 * be starting a rebuild in line here as it would block pool
9662 * import. Instead spa_load_impl will hand that off to an
9663 * async task which will call l2arc_spa_rebuild_start.
9664 */
9665 dev->l2ad_rebuild = B_TRUE;
9666 } else if (spa_writeable(spa)) {
9667 /*
9668 * In this case TRIM the whole device if l2arc_trim_ahead > 0,
9669 * otherwise create a new header. We zero out the memory holding
9670 * the header to reset dh_start_lbps. If we TRIM the whole
9671 * device the new header will be written by
9672 * vdev_trim_l2arc_thread() at the end of the TRIM to update the
9673 * trim_state in the header too. When reading the header, if
9674 * trim_state is not VDEV_TRIM_COMPLETE and l2arc_trim_ahead > 0
9675 * we opt to TRIM the whole device again.
9676 */
9677 if (l2arc_trim_ahead > 0) {
9678 dev->l2ad_trim_all = B_TRUE;
9679 } else {
861166b0 9680 memset(l2dhdr, 0, l2dhdr_asize);
ab8a8f07
GA
9681 l2arc_dev_hdr_update(dev);
9682 }
9683 }
9684}
9685
34dc7c2f
BB
9686/*
9687 * Add a vdev for use by the L2ARC. By this point the spa has already
9688 * validated the vdev and opened it.
9689 */
9690void
9babb374 9691l2arc_add_vdev(spa_t *spa, vdev_t *vd)
34dc7c2f 9692{
77f6826b
GA
9693 l2arc_dev_t *adddev;
9694 uint64_t l2dhdr_asize;
34dc7c2f 9695
b128c09f
BB
9696 ASSERT(!l2arc_vdev_present(vd));
9697
34dc7c2f
BB
9698 /*
9699 * Create a new l2arc device entry.
9700 */
77f6826b 9701 adddev = vmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
34dc7c2f
BB
9702 adddev->l2ad_spa = spa;
9703 adddev->l2ad_vdev = vd;
77f6826b
GA
9704 /* leave extra size for an l2arc device header */
9705 l2dhdr_asize = adddev->l2ad_dev_hdr_asize =
9706 MAX(sizeof (*adddev->l2ad_dev_hdr), 1 << vd->vdev_ashift);
9707 adddev->l2ad_start = VDEV_LABEL_START_SIZE + l2dhdr_asize;
9babb374 9708 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
77f6826b 9709 ASSERT3U(adddev->l2ad_start, <, adddev->l2ad_end);
34dc7c2f 9710 adddev->l2ad_hand = adddev->l2ad_start;
77f6826b 9711 adddev->l2ad_evict = adddev->l2ad_start;
34dc7c2f 9712 adddev->l2ad_first = B_TRUE;
d164b209 9713 adddev->l2ad_writing = B_FALSE;
b7654bd7 9714 adddev->l2ad_trim_all = B_FALSE;
98f72a53 9715 list_link_init(&adddev->l2ad_node);
77f6826b 9716 adddev->l2ad_dev_hdr = kmem_zalloc(l2dhdr_asize, KM_SLEEP);
34dc7c2f 9717
b9541d6b 9718 mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
34dc7c2f
BB
9719 /*
9720 * This is a list of all ARC buffers that are still valid on the
9721 * device.
9722 */
b9541d6b
CW
9723 list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
9724 offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
34dc7c2f 9725
77f6826b
GA
9726 /*
9727 * This is a list of pointers to log blocks that are still present
9728 * on the device.
9729 */
9730 list_create(&adddev->l2ad_lbptr_list, sizeof (l2arc_lb_ptr_buf_t),
9731 offsetof(l2arc_lb_ptr_buf_t, node));
9732
428870ff 9733 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
424fd7c3 9734 zfs_refcount_create(&adddev->l2ad_alloc);
657fd33b
GA
9735 zfs_refcount_create(&adddev->l2ad_lb_asize);
9736 zfs_refcount_create(&adddev->l2ad_lb_count);
34dc7c2f 9737
ab8a8f07
GA
9738 /*
9739 * Decide if dev is eligible for L2ARC rebuild or whole device
9740 * trimming. This has to happen before the device is added in the
9741 * cache device list and l2arc_dev_mtx is released. Otherwise
9742 * l2arc_feed_thread() might already start writing on the
9743 * device.
9744 */
9745 l2arc_rebuild_dev(adddev, B_FALSE);
9746
34dc7c2f
BB
9747 /*
9748 * Add device to global list
9749 */
9750 mutex_enter(&l2arc_dev_mtx);
9751 list_insert_head(l2arc_dev_list, adddev);
9752 atomic_inc_64(&l2arc_ndev);
9753 mutex_exit(&l2arc_dev_mtx);
77f6826b
GA
9754}
9755
ab8a8f07
GA
9756/*
9757 * Decide if a vdev is eligible for L2ARC rebuild, called from vdev_reopen()
9758 * in case of onlining a cache device.
9759 */
77f6826b
GA
9760void
9761l2arc_rebuild_vdev(vdev_t *vd, boolean_t reopen)
9762{
9763 l2arc_dev_t *dev = NULL;
77f6826b
GA
9764
9765 dev = l2arc_vdev_get(vd);
9766 ASSERT3P(dev, !=, NULL);
77f6826b
GA
9767
9768 /*
ab8a8f07
GA
9769 * In contrast to l2arc_add_vdev() we do not have to worry about
9770 * l2arc_feed_thread() invalidating previous content when onlining a
9771 * cache device. The device parameters (l2ad*) are not cleared when
9772 * offlining the device and writing new buffers will not invalidate
9773 * all previous content. In worst case only buffers that have not had
9774 * their log block written to the device will be lost.
9775 * When onlining the cache device (ie offline->online without exporting
9776 * the pool in between) this happens:
9777 * vdev_reopen() -> vdev_open() -> l2arc_rebuild_vdev()
9778 * | |
9779 * vdev_is_dead() = B_FALSE l2ad_rebuild = B_TRUE
9780 * During the time where vdev_is_dead = B_FALSE and until l2ad_rebuild
9781 * is set to B_TRUE we might write additional buffers to the device.
9782 */
9783 l2arc_rebuild_dev(dev, reopen);
34dc7c2f
BB
9784}
9785
9786/*
9787 * Remove a vdev from the L2ARC.
9788 */
9789void
9790l2arc_remove_vdev(vdev_t *vd)
9791{
77f6826b 9792 l2arc_dev_t *remdev = NULL;
34dc7c2f 9793
34dc7c2f
BB
9794 /*
9795 * Find the device by vdev
9796 */
77f6826b 9797 remdev = l2arc_vdev_get(vd);
d3c2ae1c 9798 ASSERT3P(remdev, !=, NULL);
34dc7c2f 9799
77f6826b
GA
9800 /*
9801 * Cancel any ongoing or scheduled rebuild.
9802 */
9803 mutex_enter(&l2arc_rebuild_thr_lock);
9804 if (remdev->l2ad_rebuild_began == B_TRUE) {
9805 remdev->l2ad_rebuild_cancel = B_TRUE;
9806 while (remdev->l2ad_rebuild == B_TRUE)
9807 cv_wait(&l2arc_rebuild_thr_cv, &l2arc_rebuild_thr_lock);
9808 }
9809 mutex_exit(&l2arc_rebuild_thr_lock);
9810
34dc7c2f
BB
9811 /*
9812 * Remove device from global list
9813 */
77f6826b 9814 mutex_enter(&l2arc_dev_mtx);
34dc7c2f
BB
9815 list_remove(l2arc_dev_list, remdev);
9816 l2arc_dev_last = NULL; /* may have been invalidated */
b128c09f
BB
9817 atomic_dec_64(&l2arc_ndev);
9818 mutex_exit(&l2arc_dev_mtx);
34dc7c2f
BB
9819
9820 /*
9821 * Clear all buflists and ARC references. L2ARC device flush.
9822 */
9823 l2arc_evict(remdev, 0, B_TRUE);
b9541d6b 9824 list_destroy(&remdev->l2ad_buflist);
77f6826b
GA
9825 ASSERT(list_is_empty(&remdev->l2ad_lbptr_list));
9826 list_destroy(&remdev->l2ad_lbptr_list);
b9541d6b 9827 mutex_destroy(&remdev->l2ad_mtx);
424fd7c3 9828 zfs_refcount_destroy(&remdev->l2ad_alloc);
657fd33b
GA
9829 zfs_refcount_destroy(&remdev->l2ad_lb_asize);
9830 zfs_refcount_destroy(&remdev->l2ad_lb_count);
77f6826b
GA
9831 kmem_free(remdev->l2ad_dev_hdr, remdev->l2ad_dev_hdr_asize);
9832 vmem_free(remdev, sizeof (l2arc_dev_t));
34dc7c2f
BB
9833}
9834
9835void
b128c09f 9836l2arc_init(void)
34dc7c2f
BB
9837{
9838 l2arc_thread_exit = 0;
9839 l2arc_ndev = 0;
34dc7c2f
BB
9840
9841 mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
9842 cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
77f6826b
GA
9843 mutex_init(&l2arc_rebuild_thr_lock, NULL, MUTEX_DEFAULT, NULL);
9844 cv_init(&l2arc_rebuild_thr_cv, NULL, CV_DEFAULT, NULL);
34dc7c2f 9845 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
34dc7c2f
BB
9846 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
9847
9848 l2arc_dev_list = &L2ARC_dev_list;
9849 l2arc_free_on_write = &L2ARC_free_on_write;
9850 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
9851 offsetof(l2arc_dev_t, l2ad_node));
9852 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
9853 offsetof(l2arc_data_free_t, l2df_list_node));
34dc7c2f
BB
9854}
9855
9856void
b128c09f 9857l2arc_fini(void)
34dc7c2f 9858{
34dc7c2f
BB
9859 mutex_destroy(&l2arc_feed_thr_lock);
9860 cv_destroy(&l2arc_feed_thr_cv);
77f6826b
GA
9861 mutex_destroy(&l2arc_rebuild_thr_lock);
9862 cv_destroy(&l2arc_rebuild_thr_cv);
34dc7c2f 9863 mutex_destroy(&l2arc_dev_mtx);
34dc7c2f
BB
9864 mutex_destroy(&l2arc_free_on_write_mtx);
9865
9866 list_destroy(l2arc_dev_list);
9867 list_destroy(l2arc_free_on_write);
9868}
b128c09f
BB
9869
9870void
9871l2arc_start(void)
9872{
da92d5cb 9873 if (!(spa_mode_global & SPA_MODE_WRITE))
b128c09f
BB
9874 return;
9875
9876 (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
1229323d 9877 TS_RUN, defclsyspri);
b128c09f
BB
9878}
9879
9880void
9881l2arc_stop(void)
9882{
da92d5cb 9883 if (!(spa_mode_global & SPA_MODE_WRITE))
b128c09f
BB
9884 return;
9885
9886 mutex_enter(&l2arc_feed_thr_lock);
9887 cv_signal(&l2arc_feed_thr_cv); /* kick thread out of startup */
9888 l2arc_thread_exit = 1;
9889 while (l2arc_thread_exit != 0)
9890 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
9891 mutex_exit(&l2arc_feed_thr_lock);
9892}
c28b2279 9893
77f6826b
GA
9894/*
9895 * Punches out rebuild threads for the L2ARC devices in a spa. This should
9896 * be called after pool import from the spa async thread, since starting
9897 * these threads directly from spa_import() will make them part of the
9898 * "zpool import" context and delay process exit (and thus pool import).
9899 */
9900void
9901l2arc_spa_rebuild_start(spa_t *spa)
9902{
9903 ASSERT(MUTEX_HELD(&spa_namespace_lock));
9904
9905 /*
9906 * Locate the spa's l2arc devices and kick off rebuild threads.
9907 */
9908 for (int i = 0; i < spa->spa_l2cache.sav_count; i++) {
9909 l2arc_dev_t *dev =
9910 l2arc_vdev_get(spa->spa_l2cache.sav_vdevs[i]);
9911 if (dev == NULL) {
9912 /* Don't attempt a rebuild if the vdev is UNAVAIL */
9913 continue;
9914 }
9915 mutex_enter(&l2arc_rebuild_thr_lock);
9916 if (dev->l2ad_rebuild && !dev->l2ad_rebuild_cancel) {
9917 dev->l2ad_rebuild_began = B_TRUE;
3eaf76a8 9918 (void) thread_create(NULL, 0, l2arc_dev_rebuild_thread,
77f6826b
GA
9919 dev, 0, &p0, TS_RUN, minclsyspri);
9920 }
9921 mutex_exit(&l2arc_rebuild_thr_lock);
9922 }
9923}
9924
9925/*
9926 * Main entry point for L2ARC rebuilding.
9927 */
460748d4 9928static __attribute__((noreturn)) void
3eaf76a8 9929l2arc_dev_rebuild_thread(void *arg)
77f6826b 9930{
3eaf76a8
RM
9931 l2arc_dev_t *dev = arg;
9932
77f6826b
GA
9933 VERIFY(!dev->l2ad_rebuild_cancel);
9934 VERIFY(dev->l2ad_rebuild);
9935 (void) l2arc_rebuild(dev);
9936 mutex_enter(&l2arc_rebuild_thr_lock);
9937 dev->l2ad_rebuild_began = B_FALSE;
9938 dev->l2ad_rebuild = B_FALSE;
9939 mutex_exit(&l2arc_rebuild_thr_lock);
9940
9941 thread_exit();
9942}
9943
9944/*
9945 * This function implements the actual L2ARC metadata rebuild. It:
9946 * starts reading the log block chain and restores each block's contents
9947 * to memory (reconstructing arc_buf_hdr_t's).
9948 *
9949 * Operation stops under any of the following conditions:
9950 *
9951 * 1) We reach the end of the log block chain.
9952 * 2) We encounter *any* error condition (cksum errors, io errors)
9953 */
9954static int
9955l2arc_rebuild(l2arc_dev_t *dev)
9956{
9957 vdev_t *vd = dev->l2ad_vdev;
9958 spa_t *spa = vd->vdev_spa;
657fd33b 9959 int err = 0;
77f6826b
GA
9960 l2arc_dev_hdr_phys_t *l2dhdr = dev->l2ad_dev_hdr;
9961 l2arc_log_blk_phys_t *this_lb, *next_lb;
9962 zio_t *this_io = NULL, *next_io = NULL;
9963 l2arc_log_blkptr_t lbps[2];
9964 l2arc_lb_ptr_buf_t *lb_ptr_buf;
9965 boolean_t lock_held;
9966
9967 this_lb = vmem_zalloc(sizeof (*this_lb), KM_SLEEP);
9968 next_lb = vmem_zalloc(sizeof (*next_lb), KM_SLEEP);
9969
9970 /*
9971 * We prevent device removal while issuing reads to the device,
9972 * then during the rebuilding phases we drop this lock again so
9973 * that a spa_unload or device remove can be initiated - this is
9974 * safe, because the spa will signal us to stop before removing
9975 * our device and wait for us to stop.
9976 */
9977 spa_config_enter(spa, SCL_L2ARC, vd, RW_READER);
9978 lock_held = B_TRUE;
9979
9980 /*
9981 * Retrieve the persistent L2ARC device state.
657fd33b 9982 * L2BLK_GET_PSIZE returns aligned size for log blocks.
77f6826b
GA
9983 */
9984 dev->l2ad_evict = MAX(l2dhdr->dh_evict, dev->l2ad_start);
9985 dev->l2ad_hand = MAX(l2dhdr->dh_start_lbps[0].lbp_daddr +
9986 L2BLK_GET_PSIZE((&l2dhdr->dh_start_lbps[0])->lbp_prop),
9987 dev->l2ad_start);
9988 dev->l2ad_first = !!(l2dhdr->dh_flags & L2ARC_DEV_HDR_EVICT_FIRST);
9989
b7654bd7
GA
9990 vd->vdev_trim_action_time = l2dhdr->dh_trim_action_time;
9991 vd->vdev_trim_state = l2dhdr->dh_trim_state;
9992
77f6826b
GA
9993 /*
9994 * In case the zfs module parameter l2arc_rebuild_enabled is false
9995 * we do not start the rebuild process.
9996 */
9997 if (!l2arc_rebuild_enabled)
9998 goto out;
9999
10000 /* Prepare the rebuild process */
861166b0 10001 memcpy(lbps, l2dhdr->dh_start_lbps, sizeof (lbps));
77f6826b
GA
10002
10003 /* Start the rebuild process */
10004 for (;;) {
10005 if (!l2arc_log_blkptr_valid(dev, &lbps[0]))
10006 break;
10007
10008 if ((err = l2arc_log_blk_read(dev, &lbps[0], &lbps[1],
10009 this_lb, next_lb, this_io, &next_io)) != 0)
10010 goto out;
10011
10012 /*
10013 * Our memory pressure valve. If the system is running low
10014 * on memory, rather than swamping memory with new ARC buf
10015 * hdrs, we opt not to rebuild the L2ARC. At this point,
10016 * however, we have already set up our L2ARC dev to chain in
10017 * new metadata log blocks, so the user may choose to offline/
10018 * online the L2ARC dev at a later time (or re-import the pool)
10019 * to reconstruct it (when there's less memory pressure).
10020 */
523e1295 10021 if (l2arc_hdr_limit_reached()) {
77f6826b
GA
10022 ARCSTAT_BUMP(arcstat_l2_rebuild_abort_lowmem);
10023 cmn_err(CE_NOTE, "System running low on memory, "
10024 "aborting L2ARC rebuild.");
10025 err = SET_ERROR(ENOMEM);
10026 goto out;
10027 }
10028
10029 spa_config_exit(spa, SCL_L2ARC, vd);
10030 lock_held = B_FALSE;
10031
10032 /*
10033 * Now that we know that the next_lb checks out alright, we
10034 * can start reconstruction from this log block.
657fd33b 10035 * L2BLK_GET_PSIZE returns aligned size for log blocks.
77f6826b 10036 */
657fd33b 10037 uint64_t asize = L2BLK_GET_PSIZE((&lbps[0])->lbp_prop);
a76e4e67 10038 l2arc_log_blk_restore(dev, this_lb, asize);
77f6826b
GA
10039
10040 /*
10041 * log block restored, include its pointer in the list of
10042 * pointers to log blocks present in the L2ARC device.
10043 */
10044 lb_ptr_buf = kmem_zalloc(sizeof (l2arc_lb_ptr_buf_t), KM_SLEEP);
10045 lb_ptr_buf->lb_ptr = kmem_zalloc(sizeof (l2arc_log_blkptr_t),
10046 KM_SLEEP);
861166b0 10047 memcpy(lb_ptr_buf->lb_ptr, &lbps[0],
77f6826b
GA
10048 sizeof (l2arc_log_blkptr_t));
10049 mutex_enter(&dev->l2ad_mtx);
10050 list_insert_tail(&dev->l2ad_lbptr_list, lb_ptr_buf);
657fd33b
GA
10051 ARCSTAT_INCR(arcstat_l2_log_blk_asize, asize);
10052 ARCSTAT_BUMP(arcstat_l2_log_blk_count);
10053 zfs_refcount_add_many(&dev->l2ad_lb_asize, asize, lb_ptr_buf);
10054 zfs_refcount_add(&dev->l2ad_lb_count, lb_ptr_buf);
77f6826b 10055 mutex_exit(&dev->l2ad_mtx);
657fd33b 10056 vdev_space_update(vd, asize, 0, 0);
77f6826b
GA
10057
10058 /*
10059 * Protection against loops of log blocks:
10060 *
10061 * l2ad_hand l2ad_evict
10062 * V V
10063 * l2ad_start |=======================================| l2ad_end
10064 * -----|||----|||---|||----|||
10065 * (3) (2) (1) (0)
10066 * ---|||---|||----|||---|||
10067 * (7) (6) (5) (4)
10068 *
10069 * In this situation the pointer of log block (4) passes
10070 * l2arc_log_blkptr_valid() but the log block should not be
10071 * restored as it is overwritten by the payload of log block
10072 * (0). Only log blocks (0)-(3) should be restored. We check
657fd33b
GA
10073 * whether l2ad_evict lies in between the payload starting
10074 * offset of the next log block (lbps[1].lbp_payload_start)
10075 * and the payload starting offset of the present log block
10076 * (lbps[0].lbp_payload_start). If true and this isn't the
10077 * first pass, we are looping from the beginning and we should
10078 * stop.
77f6826b 10079 */
657fd33b
GA
10080 if (l2arc_range_check_overlap(lbps[1].lbp_payload_start,
10081 lbps[0].lbp_payload_start, dev->l2ad_evict) &&
10082 !dev->l2ad_first)
77f6826b
GA
10083 goto out;
10084
0e4c830b 10085 kpreempt(KPREEMPT_SYNC);
77f6826b
GA
10086 for (;;) {
10087 mutex_enter(&l2arc_rebuild_thr_lock);
10088 if (dev->l2ad_rebuild_cancel) {
10089 dev->l2ad_rebuild = B_FALSE;
10090 cv_signal(&l2arc_rebuild_thr_cv);
10091 mutex_exit(&l2arc_rebuild_thr_lock);
10092 err = SET_ERROR(ECANCELED);
10093 goto out;
10094 }
10095 mutex_exit(&l2arc_rebuild_thr_lock);
10096 if (spa_config_tryenter(spa, SCL_L2ARC, vd,
10097 RW_READER)) {
10098 lock_held = B_TRUE;
10099 break;
10100 }
10101 /*
10102 * L2ARC config lock held by somebody in writer,
10103 * possibly due to them trying to remove us. They'll
10104 * likely to want us to shut down, so after a little
10105 * delay, we check l2ad_rebuild_cancel and retry
10106 * the lock again.
10107 */
10108 delay(1);
10109 }
10110
10111 /*
10112 * Continue with the next log block.
10113 */
10114 lbps[0] = lbps[1];
10115 lbps[1] = this_lb->lb_prev_lbp;
10116 PTR_SWAP(this_lb, next_lb);
10117 this_io = next_io;
10118 next_io = NULL;
a76e4e67 10119 }
77f6826b
GA
10120
10121 if (this_io != NULL)
10122 l2arc_log_blk_fetch_abort(this_io);
10123out:
10124 if (next_io != NULL)
10125 l2arc_log_blk_fetch_abort(next_io);
10126 vmem_free(this_lb, sizeof (*this_lb));
10127 vmem_free(next_lb, sizeof (*next_lb));
10128
10129 if (!l2arc_rebuild_enabled) {
657fd33b
GA
10130 spa_history_log_internal(spa, "L2ARC rebuild", NULL,
10131 "disabled");
10132 } else if (err == 0 && zfs_refcount_count(&dev->l2ad_lb_count) > 0) {
77f6826b 10133 ARCSTAT_BUMP(arcstat_l2_rebuild_success);
657fd33b
GA
10134 spa_history_log_internal(spa, "L2ARC rebuild", NULL,
10135 "successful, restored %llu blocks",
10136 (u_longlong_t)zfs_refcount_count(&dev->l2ad_lb_count));
10137 } else if (err == 0 && zfs_refcount_count(&dev->l2ad_lb_count) == 0) {
10138 /*
10139 * No error but also nothing restored, meaning the lbps array
10140 * in the device header points to invalid/non-present log
10141 * blocks. Reset the header.
10142 */
10143 spa_history_log_internal(spa, "L2ARC rebuild", NULL,
10144 "no valid log blocks");
861166b0 10145 memset(l2dhdr, 0, dev->l2ad_dev_hdr_asize);
657fd33b 10146 l2arc_dev_hdr_update(dev);
da60484d
GA
10147 } else if (err == ECANCELED) {
10148 /*
10149 * In case the rebuild was canceled do not log to spa history
10150 * log as the pool may be in the process of being removed.
10151 */
10152 zfs_dbgmsg("L2ARC rebuild aborted, restored %llu blocks",
8e739b2c 10153 (u_longlong_t)zfs_refcount_count(&dev->l2ad_lb_count));
77f6826b 10154 } else if (err != 0) {
657fd33b
GA
10155 spa_history_log_internal(spa, "L2ARC rebuild", NULL,
10156 "aborted, restored %llu blocks",
10157 (u_longlong_t)zfs_refcount_count(&dev->l2ad_lb_count));
77f6826b
GA
10158 }
10159
10160 if (lock_held)
10161 spa_config_exit(spa, SCL_L2ARC, vd);
10162
10163 return (err);
10164}
10165
10166/*
10167 * Attempts to read the device header on the provided L2ARC device and writes
10168 * it to `hdr'. On success, this function returns 0, otherwise the appropriate
10169 * error code is returned.
10170 */
10171static int
10172l2arc_dev_hdr_read(l2arc_dev_t *dev)
10173{
10174 int err;
10175 uint64_t guid;
10176 l2arc_dev_hdr_phys_t *l2dhdr = dev->l2ad_dev_hdr;
10177 const uint64_t l2dhdr_asize = dev->l2ad_dev_hdr_asize;
10178 abd_t *abd;
10179
10180 guid = spa_guid(dev->l2ad_vdev->vdev_spa);
10181
10182 abd = abd_get_from_buf(l2dhdr, l2dhdr_asize);
10183
10184 err = zio_wait(zio_read_phys(NULL, dev->l2ad_vdev,
10185 VDEV_LABEL_START_SIZE, l2dhdr_asize, abd,
a76e4e67 10186 ZIO_CHECKSUM_LABEL, NULL, NULL, ZIO_PRIORITY_SYNC_READ,
77f6826b
GA
10187 ZIO_FLAG_DONT_CACHE | ZIO_FLAG_CANFAIL |
10188 ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY |
10189 ZIO_FLAG_SPECULATIVE, B_FALSE));
10190
e2af2acc 10191 abd_free(abd);
77f6826b
GA
10192
10193 if (err != 0) {
10194 ARCSTAT_BUMP(arcstat_l2_rebuild_abort_dh_errors);
10195 zfs_dbgmsg("L2ARC IO error (%d) while reading device header, "
8e739b2c
RE
10196 "vdev guid: %llu", err,
10197 (u_longlong_t)dev->l2ad_vdev->vdev_guid);
77f6826b
GA
10198 return (err);
10199 }
10200
10201 if (l2dhdr->dh_magic == BSWAP_64(L2ARC_DEV_HDR_MAGIC))
10202 byteswap_uint64_array(l2dhdr, sizeof (*l2dhdr));
10203
10204 if (l2dhdr->dh_magic != L2ARC_DEV_HDR_MAGIC ||
10205 l2dhdr->dh_spa_guid != guid ||
10206 l2dhdr->dh_vdev_guid != dev->l2ad_vdev->vdev_guid ||
10207 l2dhdr->dh_version != L2ARC_PERSISTENT_VERSION ||
657fd33b 10208 l2dhdr->dh_log_entries != dev->l2ad_log_entries ||
77f6826b
GA
10209 l2dhdr->dh_end != dev->l2ad_end ||
10210 !l2arc_range_check_overlap(dev->l2ad_start, dev->l2ad_end,
b7654bd7
GA
10211 l2dhdr->dh_evict) ||
10212 (l2dhdr->dh_trim_state != VDEV_TRIM_COMPLETE &&
10213 l2arc_trim_ahead > 0)) {
77f6826b
GA
10214 /*
10215 * Attempt to rebuild a device containing no actual dev hdr
10216 * or containing a header from some other pool or from another
10217 * version of persistent L2ARC.
10218 */
10219 ARCSTAT_BUMP(arcstat_l2_rebuild_abort_unsupported);
10220 return (SET_ERROR(ENOTSUP));
10221 }
10222
10223 return (0);
10224}
10225
10226/*
10227 * Reads L2ARC log blocks from storage and validates their contents.
10228 *
10229 * This function implements a simple fetcher to make sure that while
10230 * we're processing one buffer the L2ARC is already fetching the next
10231 * one in the chain.
10232 *
10233 * The arguments this_lp and next_lp point to the current and next log block
10234 * address in the block chain. Similarly, this_lb and next_lb hold the
10235 * l2arc_log_blk_phys_t's of the current and next L2ARC blk.
10236 *
10237 * The `this_io' and `next_io' arguments are used for block fetching.
10238 * When issuing the first blk IO during rebuild, you should pass NULL for
10239 * `this_io'. This function will then issue a sync IO to read the block and
10240 * also issue an async IO to fetch the next block in the block chain. The
10241 * fetched IO is returned in `next_io'. On subsequent calls to this
10242 * function, pass the value returned in `next_io' from the previous call
10243 * as `this_io' and a fresh `next_io' pointer to hold the next fetch IO.
10244 * Prior to the call, you should initialize your `next_io' pointer to be
10245 * NULL. If no fetch IO was issued, the pointer is left set at NULL.
10246 *
10247 * On success, this function returns 0, otherwise it returns an appropriate
10248 * error code. On error the fetching IO is aborted and cleared before
10249 * returning from this function. Therefore, if we return `success', the
10250 * caller can assume that we have taken care of cleanup of fetch IOs.
10251 */
10252static int
10253l2arc_log_blk_read(l2arc_dev_t *dev,
10254 const l2arc_log_blkptr_t *this_lbp, const l2arc_log_blkptr_t *next_lbp,
10255 l2arc_log_blk_phys_t *this_lb, l2arc_log_blk_phys_t *next_lb,
10256 zio_t *this_io, zio_t **next_io)
10257{
10258 int err = 0;
10259 zio_cksum_t cksum;
10260 abd_t *abd = NULL;
657fd33b 10261 uint64_t asize;
77f6826b
GA
10262
10263 ASSERT(this_lbp != NULL && next_lbp != NULL);
10264 ASSERT(this_lb != NULL && next_lb != NULL);
10265 ASSERT(next_io != NULL && *next_io == NULL);
10266 ASSERT(l2arc_log_blkptr_valid(dev, this_lbp));
10267
10268 /*
10269 * Check to see if we have issued the IO for this log block in a
10270 * previous run. If not, this is the first call, so issue it now.
10271 */
10272 if (this_io == NULL) {
10273 this_io = l2arc_log_blk_fetch(dev->l2ad_vdev, this_lbp,
10274 this_lb);
10275 }
10276
10277 /*
10278 * Peek to see if we can start issuing the next IO immediately.
10279 */
10280 if (l2arc_log_blkptr_valid(dev, next_lbp)) {
10281 /*
10282 * Start issuing IO for the next log block early - this
10283 * should help keep the L2ARC device busy while we
10284 * decompress and restore this log block.
10285 */
10286 *next_io = l2arc_log_blk_fetch(dev->l2ad_vdev, next_lbp,
10287 next_lb);
10288 }
10289
10290 /* Wait for the IO to read this log block to complete */
10291 if ((err = zio_wait(this_io)) != 0) {
10292 ARCSTAT_BUMP(arcstat_l2_rebuild_abort_io_errors);
10293 zfs_dbgmsg("L2ARC IO error (%d) while reading log block, "
8e739b2c
RE
10294 "offset: %llu, vdev guid: %llu", err,
10295 (u_longlong_t)this_lbp->lbp_daddr,
10296 (u_longlong_t)dev->l2ad_vdev->vdev_guid);
77f6826b
GA
10297 goto cleanup;
10298 }
10299
657fd33b
GA
10300 /*
10301 * Make sure the buffer checks out.
10302 * L2BLK_GET_PSIZE returns aligned size for log blocks.
10303 */
10304 asize = L2BLK_GET_PSIZE((this_lbp)->lbp_prop);
10305 fletcher_4_native(this_lb, asize, NULL, &cksum);
77f6826b
GA
10306 if (!ZIO_CHECKSUM_EQUAL(cksum, this_lbp->lbp_cksum)) {
10307 ARCSTAT_BUMP(arcstat_l2_rebuild_abort_cksum_lb_errors);
10308 zfs_dbgmsg("L2ARC log block cksum failed, offset: %llu, "
10309 "vdev guid: %llu, l2ad_hand: %llu, l2ad_evict: %llu",
8e739b2c
RE
10310 (u_longlong_t)this_lbp->lbp_daddr,
10311 (u_longlong_t)dev->l2ad_vdev->vdev_guid,
10312 (u_longlong_t)dev->l2ad_hand,
10313 (u_longlong_t)dev->l2ad_evict);
77f6826b
GA
10314 err = SET_ERROR(ECKSUM);
10315 goto cleanup;
10316 }
10317
10318 /* Now we can take our time decoding this buffer */
10319 switch (L2BLK_GET_COMPRESS((this_lbp)->lbp_prop)) {
10320 case ZIO_COMPRESS_OFF:
10321 break;
10322 case ZIO_COMPRESS_LZ4:
657fd33b
GA
10323 abd = abd_alloc_for_io(asize, B_TRUE);
10324 abd_copy_from_buf_off(abd, this_lb, 0, asize);
77f6826b
GA
10325 if ((err = zio_decompress_data(
10326 L2BLK_GET_COMPRESS((this_lbp)->lbp_prop),
10b3c7f5 10327 abd, this_lb, asize, sizeof (*this_lb), NULL)) != 0) {
77f6826b
GA
10328 err = SET_ERROR(EINVAL);
10329 goto cleanup;
10330 }
10331 break;
10332 default:
10333 err = SET_ERROR(EINVAL);
10334 goto cleanup;
10335 }
10336 if (this_lb->lb_magic == BSWAP_64(L2ARC_LOG_BLK_MAGIC))
10337 byteswap_uint64_array(this_lb, sizeof (*this_lb));
10338 if (this_lb->lb_magic != L2ARC_LOG_BLK_MAGIC) {
10339 err = SET_ERROR(EINVAL);
10340 goto cleanup;
10341 }
10342cleanup:
10343 /* Abort an in-flight fetch I/O in case of error */
10344 if (err != 0 && *next_io != NULL) {
10345 l2arc_log_blk_fetch_abort(*next_io);
10346 *next_io = NULL;
10347 }
10348 if (abd != NULL)
10349 abd_free(abd);
10350 return (err);
10351}
10352
10353/*
10354 * Restores the payload of a log block to ARC. This creates empty ARC hdr
10355 * entries which only contain an l2arc hdr, essentially restoring the
10356 * buffers to their L2ARC evicted state. This function also updates space
10357 * usage on the L2ARC vdev to make sure it tracks restored buffers.
10358 */
10359static void
10360l2arc_log_blk_restore(l2arc_dev_t *dev, const l2arc_log_blk_phys_t *lb,
a76e4e67 10361 uint64_t lb_asize)
77f6826b 10362{
657fd33b
GA
10363 uint64_t size = 0, asize = 0;
10364 uint64_t log_entries = dev->l2ad_log_entries;
77f6826b 10365
523e1295
AM
10366 /*
10367 * Usually arc_adapt() is called only for data, not headers, but
10368 * since we may allocate significant amount of memory here, let ARC
10369 * grow its arc_c.
10370 */
a8d83e2a 10371 arc_adapt(log_entries * HDR_L2ONLY_SIZE);
523e1295 10372
77f6826b
GA
10373 for (int i = log_entries - 1; i >= 0; i--) {
10374 /*
10375 * Restore goes in the reverse temporal direction to preserve
10376 * correct temporal ordering of buffers in the l2ad_buflist.
10377 * l2arc_hdr_restore also does a list_insert_tail instead of
10378 * list_insert_head on the l2ad_buflist:
10379 *
10380 * LIST l2ad_buflist LIST
10381 * HEAD <------ (time) ------ TAIL
10382 * direction +-----+-----+-----+-----+-----+ direction
10383 * of l2arc <== | buf | buf | buf | buf | buf | ===> of rebuild
10384 * fill +-----+-----+-----+-----+-----+
10385 * ^ ^
10386 * | |
10387 * | |
657fd33b
GA
10388 * l2arc_feed_thread l2arc_rebuild
10389 * will place new bufs here restores bufs here
77f6826b 10390 *
657fd33b
GA
10391 * During l2arc_rebuild() the device is not used by
10392 * l2arc_feed_thread() as dev->l2ad_rebuild is set to true.
77f6826b
GA
10393 */
10394 size += L2BLK_GET_LSIZE((&lb->lb_entries[i])->le_prop);
657fd33b
GA
10395 asize += vdev_psize_to_asize(dev->l2ad_vdev,
10396 L2BLK_GET_PSIZE((&lb->lb_entries[i])->le_prop));
77f6826b
GA
10397 l2arc_hdr_restore(&lb->lb_entries[i], dev);
10398 }
10399
10400 /*
10401 * Record rebuild stats:
10402 * size Logical size of restored buffers in the L2ARC
657fd33b 10403 * asize Aligned size of restored buffers in the L2ARC
77f6826b
GA
10404 */
10405 ARCSTAT_INCR(arcstat_l2_rebuild_size, size);
657fd33b 10406 ARCSTAT_INCR(arcstat_l2_rebuild_asize, asize);
77f6826b 10407 ARCSTAT_INCR(arcstat_l2_rebuild_bufs, log_entries);
657fd33b
GA
10408 ARCSTAT_F_AVG(arcstat_l2_log_blk_avg_asize, lb_asize);
10409 ARCSTAT_F_AVG(arcstat_l2_data_to_meta_ratio, asize / lb_asize);
77f6826b
GA
10410 ARCSTAT_BUMP(arcstat_l2_rebuild_log_blks);
10411}
10412
10413/*
10414 * Restores a single ARC buf hdr from a log entry. The ARC buffer is put
10415 * into a state indicating that it has been evicted to L2ARC.
10416 */
10417static void
10418l2arc_hdr_restore(const l2arc_log_ent_phys_t *le, l2arc_dev_t *dev)
10419{
10420 arc_buf_hdr_t *hdr, *exists;
10421 kmutex_t *hash_lock;
10422 arc_buf_contents_t type = L2BLK_GET_TYPE((le)->le_prop);
10423 uint64_t asize;
10424
10425 /*
10426 * Do all the allocation before grabbing any locks, this lets us
10427 * sleep if memory is full and we don't have to deal with failed
10428 * allocations.
10429 */
10430 hdr = arc_buf_alloc_l2only(L2BLK_GET_LSIZE((le)->le_prop), type,
10431 dev, le->le_dva, le->le_daddr,
10432 L2BLK_GET_PSIZE((le)->le_prop), le->le_birth,
10b3c7f5 10433 L2BLK_GET_COMPRESS((le)->le_prop), le->le_complevel,
77f6826b 10434 L2BLK_GET_PROTECTED((le)->le_prop),
08532162
GA
10435 L2BLK_GET_PREFETCH((le)->le_prop),
10436 L2BLK_GET_STATE((le)->le_prop));
77f6826b
GA
10437 asize = vdev_psize_to_asize(dev->l2ad_vdev,
10438 L2BLK_GET_PSIZE((le)->le_prop));
10439
10440 /*
10441 * vdev_space_update() has to be called before arc_hdr_destroy() to
08532162 10442 * avoid underflow since the latter also calls vdev_space_update().
77f6826b 10443 */
08532162 10444 l2arc_hdr_arcstats_increment(hdr);
77f6826b
GA
10445 vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
10446
77f6826b
GA
10447 mutex_enter(&dev->l2ad_mtx);
10448 list_insert_tail(&dev->l2ad_buflist, hdr);
10449 (void) zfs_refcount_add_many(&dev->l2ad_alloc, arc_hdr_size(hdr), hdr);
10450 mutex_exit(&dev->l2ad_mtx);
10451
10452 exists = buf_hash_insert(hdr, &hash_lock);
10453 if (exists) {
10454 /* Buffer was already cached, no need to restore it. */
10455 arc_hdr_destroy(hdr);
10456 /*
10457 * If the buffer is already cached, check whether it has
10458 * L2ARC metadata. If not, enter them and update the flag.
10459 * This is important is case of onlining a cache device, since
10460 * we previously evicted all L2ARC metadata from ARC.
10461 */
10462 if (!HDR_HAS_L2HDR(exists)) {
10463 arc_hdr_set_flags(exists, ARC_FLAG_HAS_L2HDR);
10464 exists->b_l2hdr.b_dev = dev;
10465 exists->b_l2hdr.b_daddr = le->le_daddr;
08532162
GA
10466 exists->b_l2hdr.b_arcs_state =
10467 L2BLK_GET_STATE((le)->le_prop);
77f6826b
GA
10468 mutex_enter(&dev->l2ad_mtx);
10469 list_insert_tail(&dev->l2ad_buflist, exists);
10470 (void) zfs_refcount_add_many(&dev->l2ad_alloc,
10471 arc_hdr_size(exists), exists);
10472 mutex_exit(&dev->l2ad_mtx);
08532162 10473 l2arc_hdr_arcstats_increment(exists);
77f6826b 10474 vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
77f6826b
GA
10475 }
10476 ARCSTAT_BUMP(arcstat_l2_rebuild_bufs_precached);
10477 }
10478
10479 mutex_exit(hash_lock);
10480}
10481
10482/*
10483 * Starts an asynchronous read IO to read a log block. This is used in log
10484 * block reconstruction to start reading the next block before we are done
10485 * decoding and reconstructing the current block, to keep the l2arc device
10486 * nice and hot with read IO to process.
10487 * The returned zio will contain a newly allocated memory buffers for the IO
10488 * data which should then be freed by the caller once the zio is no longer
10489 * needed (i.e. due to it having completed). If you wish to abort this
10490 * zio, you should do so using l2arc_log_blk_fetch_abort, which takes
10491 * care of disposing of the allocated buffers correctly.
10492 */
10493static zio_t *
10494l2arc_log_blk_fetch(vdev_t *vd, const l2arc_log_blkptr_t *lbp,
10495 l2arc_log_blk_phys_t *lb)
10496{
657fd33b 10497 uint32_t asize;
77f6826b
GA
10498 zio_t *pio;
10499 l2arc_read_callback_t *cb;
10500
657fd33b
GA
10501 /* L2BLK_GET_PSIZE returns aligned size for log blocks */
10502 asize = L2BLK_GET_PSIZE((lbp)->lbp_prop);
10503 ASSERT(asize <= sizeof (l2arc_log_blk_phys_t));
10504
77f6826b 10505 cb = kmem_zalloc(sizeof (l2arc_read_callback_t), KM_SLEEP);
657fd33b 10506 cb->l2rcb_abd = abd_get_from_buf(lb, asize);
77f6826b
GA
10507 pio = zio_root(vd->vdev_spa, l2arc_blk_fetch_done, cb,
10508 ZIO_FLAG_DONT_CACHE | ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE |
10509 ZIO_FLAG_DONT_RETRY);
657fd33b 10510 (void) zio_nowait(zio_read_phys(pio, vd, lbp->lbp_daddr, asize,
77f6826b
GA
10511 cb->l2rcb_abd, ZIO_CHECKSUM_OFF, NULL, NULL,
10512 ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_DONT_CACHE | ZIO_FLAG_CANFAIL |
10513 ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY, B_FALSE));
10514
10515 return (pio);
10516}
10517
10518/*
10519 * Aborts a zio returned from l2arc_log_blk_fetch and frees the data
10520 * buffers allocated for it.
10521 */
10522static void
10523l2arc_log_blk_fetch_abort(zio_t *zio)
10524{
10525 (void) zio_wait(zio);
10526}
10527
10528/*
2054f35e 10529 * Creates a zio to update the device header on an l2arc device.
77f6826b 10530 */
b7654bd7 10531void
77f6826b
GA
10532l2arc_dev_hdr_update(l2arc_dev_t *dev)
10533{
10534 l2arc_dev_hdr_phys_t *l2dhdr = dev->l2ad_dev_hdr;
10535 const uint64_t l2dhdr_asize = dev->l2ad_dev_hdr_asize;
10536 abd_t *abd;
10537 int err;
10538
657fd33b
GA
10539 VERIFY(spa_config_held(dev->l2ad_spa, SCL_STATE_ALL, RW_READER));
10540
77f6826b
GA
10541 l2dhdr->dh_magic = L2ARC_DEV_HDR_MAGIC;
10542 l2dhdr->dh_version = L2ARC_PERSISTENT_VERSION;
10543 l2dhdr->dh_spa_guid = spa_guid(dev->l2ad_vdev->vdev_spa);
10544 l2dhdr->dh_vdev_guid = dev->l2ad_vdev->vdev_guid;
657fd33b 10545 l2dhdr->dh_log_entries = dev->l2ad_log_entries;
77f6826b
GA
10546 l2dhdr->dh_evict = dev->l2ad_evict;
10547 l2dhdr->dh_start = dev->l2ad_start;
10548 l2dhdr->dh_end = dev->l2ad_end;
657fd33b
GA
10549 l2dhdr->dh_lb_asize = zfs_refcount_count(&dev->l2ad_lb_asize);
10550 l2dhdr->dh_lb_count = zfs_refcount_count(&dev->l2ad_lb_count);
77f6826b 10551 l2dhdr->dh_flags = 0;
b7654bd7
GA
10552 l2dhdr->dh_trim_action_time = dev->l2ad_vdev->vdev_trim_action_time;
10553 l2dhdr->dh_trim_state = dev->l2ad_vdev->vdev_trim_state;
77f6826b
GA
10554 if (dev->l2ad_first)
10555 l2dhdr->dh_flags |= L2ARC_DEV_HDR_EVICT_FIRST;
10556
10557 abd = abd_get_from_buf(l2dhdr, l2dhdr_asize);
10558
10559 err = zio_wait(zio_write_phys(NULL, dev->l2ad_vdev,
10560 VDEV_LABEL_START_SIZE, l2dhdr_asize, abd, ZIO_CHECKSUM_LABEL, NULL,
10561 NULL, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_CANFAIL, B_FALSE));
10562
e2af2acc 10563 abd_free(abd);
77f6826b
GA
10564
10565 if (err != 0) {
10566 zfs_dbgmsg("L2ARC IO error (%d) while writing device header, "
8e739b2c
RE
10567 "vdev guid: %llu", err,
10568 (u_longlong_t)dev->l2ad_vdev->vdev_guid);
77f6826b
GA
10569 }
10570}
10571
10572/*
10573 * Commits a log block to the L2ARC device. This routine is invoked from
10574 * l2arc_write_buffers when the log block fills up.
10575 * This function allocates some memory to temporarily hold the serialized
10576 * buffer to be written. This is then released in l2arc_write_done.
10577 */
bcd53210 10578static uint64_t
77f6826b
GA
10579l2arc_log_blk_commit(l2arc_dev_t *dev, zio_t *pio, l2arc_write_callback_t *cb)
10580{
10581 l2arc_log_blk_phys_t *lb = &dev->l2ad_log_blk;
10582 l2arc_dev_hdr_phys_t *l2dhdr = dev->l2ad_dev_hdr;
10583 uint64_t psize, asize;
10584 zio_t *wzio;
10585 l2arc_lb_abd_buf_t *abd_buf;
bff26b02 10586 uint8_t *tmpbuf = NULL;
77f6826b
GA
10587 l2arc_lb_ptr_buf_t *lb_ptr_buf;
10588
657fd33b 10589 VERIFY3S(dev->l2ad_log_ent_idx, ==, dev->l2ad_log_entries);
77f6826b 10590
77f6826b
GA
10591 abd_buf = zio_buf_alloc(sizeof (*abd_buf));
10592 abd_buf->abd = abd_get_from_buf(lb, sizeof (*lb));
10593 lb_ptr_buf = kmem_zalloc(sizeof (l2arc_lb_ptr_buf_t), KM_SLEEP);
10594 lb_ptr_buf->lb_ptr = kmem_zalloc(sizeof (l2arc_log_blkptr_t), KM_SLEEP);
10595
10596 /* link the buffer into the block chain */
10597 lb->lb_prev_lbp = l2dhdr->dh_start_lbps[1];
10598 lb->lb_magic = L2ARC_LOG_BLK_MAGIC;
10599
657fd33b
GA
10600 /*
10601 * l2arc_log_blk_commit() may be called multiple times during a single
10602 * l2arc_write_buffers() call. Save the allocated abd buffers in a list
10603 * so we can free them in l2arc_write_done() later on.
10604 */
77f6826b 10605 list_insert_tail(&cb->l2wcb_abd_list, abd_buf);
657fd33b
GA
10606
10607 /* try to compress the buffer */
77f6826b 10608 psize = zio_compress_data(ZIO_COMPRESS_LZ4,
bff26b02 10609 abd_buf->abd, (void **) &tmpbuf, sizeof (*lb), 0);
77f6826b
GA
10610
10611 /* a log block is never entirely zero */
10612 ASSERT(psize != 0);
10613 asize = vdev_psize_to_asize(dev->l2ad_vdev, psize);
10614 ASSERT(asize <= sizeof (*lb));
10615
10616 /*
10617 * Update the start log block pointer in the device header to point
10618 * to the log block we're about to write.
10619 */
10620 l2dhdr->dh_start_lbps[1] = l2dhdr->dh_start_lbps[0];
10621 l2dhdr->dh_start_lbps[0].lbp_daddr = dev->l2ad_hand;
10622 l2dhdr->dh_start_lbps[0].lbp_payload_asize =
10623 dev->l2ad_log_blk_payload_asize;
10624 l2dhdr->dh_start_lbps[0].lbp_payload_start =
10625 dev->l2ad_log_blk_payload_start;
77f6826b
GA
10626 L2BLK_SET_LSIZE(
10627 (&l2dhdr->dh_start_lbps[0])->lbp_prop, sizeof (*lb));
10628 L2BLK_SET_PSIZE(
10629 (&l2dhdr->dh_start_lbps[0])->lbp_prop, asize);
10630 L2BLK_SET_CHECKSUM(
10631 (&l2dhdr->dh_start_lbps[0])->lbp_prop,
10632 ZIO_CHECKSUM_FLETCHER_4);
10633 if (asize < sizeof (*lb)) {
10634 /* compression succeeded */
861166b0 10635 memset(tmpbuf + psize, 0, asize - psize);
77f6826b
GA
10636 L2BLK_SET_COMPRESS(
10637 (&l2dhdr->dh_start_lbps[0])->lbp_prop,
10638 ZIO_COMPRESS_LZ4);
10639 } else {
10640 /* compression failed */
861166b0 10641 memcpy(tmpbuf, lb, sizeof (*lb));
77f6826b
GA
10642 L2BLK_SET_COMPRESS(
10643 (&l2dhdr->dh_start_lbps[0])->lbp_prop,
10644 ZIO_COMPRESS_OFF);
10645 }
10646
10647 /* checksum what we're about to write */
10648 fletcher_4_native(tmpbuf, asize, NULL,
10649 &l2dhdr->dh_start_lbps[0].lbp_cksum);
10650
e2af2acc 10651 abd_free(abd_buf->abd);
77f6826b
GA
10652
10653 /* perform the write itself */
10654 abd_buf->abd = abd_get_from_buf(tmpbuf, sizeof (*lb));
10655 abd_take_ownership_of_buf(abd_buf->abd, B_TRUE);
10656 wzio = zio_write_phys(pio, dev->l2ad_vdev, dev->l2ad_hand,
10657 asize, abd_buf->abd, ZIO_CHECKSUM_OFF, NULL, NULL,
10658 ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_CANFAIL, B_FALSE);
10659 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev, zio_t *, wzio);
10660 (void) zio_nowait(wzio);
10661
10662 dev->l2ad_hand += asize;
10663 /*
10664 * Include the committed log block's pointer in the list of pointers
10665 * to log blocks present in the L2ARC device.
10666 */
861166b0 10667 memcpy(lb_ptr_buf->lb_ptr, &l2dhdr->dh_start_lbps[0],
77f6826b
GA
10668 sizeof (l2arc_log_blkptr_t));
10669 mutex_enter(&dev->l2ad_mtx);
10670 list_insert_head(&dev->l2ad_lbptr_list, lb_ptr_buf);
657fd33b
GA
10671 ARCSTAT_INCR(arcstat_l2_log_blk_asize, asize);
10672 ARCSTAT_BUMP(arcstat_l2_log_blk_count);
10673 zfs_refcount_add_many(&dev->l2ad_lb_asize, asize, lb_ptr_buf);
10674 zfs_refcount_add(&dev->l2ad_lb_count, lb_ptr_buf);
77f6826b
GA
10675 mutex_exit(&dev->l2ad_mtx);
10676 vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
10677
10678 /* bump the kstats */
10679 ARCSTAT_INCR(arcstat_l2_write_bytes, asize);
10680 ARCSTAT_BUMP(arcstat_l2_log_blk_writes);
657fd33b 10681 ARCSTAT_F_AVG(arcstat_l2_log_blk_avg_asize, asize);
77f6826b
GA
10682 ARCSTAT_F_AVG(arcstat_l2_data_to_meta_ratio,
10683 dev->l2ad_log_blk_payload_asize / asize);
10684
10685 /* start a new log block */
10686 dev->l2ad_log_ent_idx = 0;
10687 dev->l2ad_log_blk_payload_asize = 0;
10688 dev->l2ad_log_blk_payload_start = 0;
bcd53210
GA
10689
10690 return (asize);
77f6826b
GA
10691}
10692
10693/*
10694 * Validates an L2ARC log block address to make sure that it can be read
10695 * from the provided L2ARC device.
10696 */
10697boolean_t
10698l2arc_log_blkptr_valid(l2arc_dev_t *dev, const l2arc_log_blkptr_t *lbp)
10699{
657fd33b
GA
10700 /* L2BLK_GET_PSIZE returns aligned size for log blocks */
10701 uint64_t asize = L2BLK_GET_PSIZE((lbp)->lbp_prop);
10702 uint64_t end = lbp->lbp_daddr + asize - 1;
77f6826b
GA
10703 uint64_t start = lbp->lbp_payload_start;
10704 boolean_t evicted = B_FALSE;
10705
10706 /*
10707 * A log block is valid if all of the following conditions are true:
10708 * - it fits entirely (including its payload) between l2ad_start and
10709 * l2ad_end
10710 * - it has a valid size
10711 * - neither the log block itself nor part of its payload was evicted
10712 * by l2arc_evict():
10713 *
10714 * l2ad_hand l2ad_evict
10715 * | | lbp_daddr
10716 * | start | | end
10717 * | | | | |
10718 * V V V V V
10719 * l2ad_start ============================================ l2ad_end
10720 * --------------------------||||
10721 * ^ ^
10722 * | log block
10723 * payload
10724 */
10725
10726 evicted =
10727 l2arc_range_check_overlap(start, end, dev->l2ad_hand) ||
10728 l2arc_range_check_overlap(start, end, dev->l2ad_evict) ||
10729 l2arc_range_check_overlap(dev->l2ad_hand, dev->l2ad_evict, start) ||
10730 l2arc_range_check_overlap(dev->l2ad_hand, dev->l2ad_evict, end);
10731
10732 return (start >= dev->l2ad_start && end <= dev->l2ad_end &&
657fd33b 10733 asize > 0 && asize <= sizeof (l2arc_log_blk_phys_t) &&
77f6826b
GA
10734 (!evicted || dev->l2ad_first));
10735}
10736
10737/*
10738 * Inserts ARC buffer header `hdr' into the current L2ARC log block on
10739 * the device. The buffer being inserted must be present in L2ARC.
10740 * Returns B_TRUE if the L2ARC log block is full and needs to be committed
10741 * to L2ARC, or B_FALSE if it still has room for more ARC buffers.
10742 */
10743static boolean_t
10744l2arc_log_blk_insert(l2arc_dev_t *dev, const arc_buf_hdr_t *hdr)
10745{
10746 l2arc_log_blk_phys_t *lb = &dev->l2ad_log_blk;
10747 l2arc_log_ent_phys_t *le;
77f6826b 10748
657fd33b 10749 if (dev->l2ad_log_entries == 0)
77f6826b
GA
10750 return (B_FALSE);
10751
10752 int index = dev->l2ad_log_ent_idx++;
10753
657fd33b 10754 ASSERT3S(index, <, dev->l2ad_log_entries);
77f6826b
GA
10755 ASSERT(HDR_HAS_L2HDR(hdr));
10756
10757 le = &lb->lb_entries[index];
861166b0 10758 memset(le, 0, sizeof (*le));
77f6826b
GA
10759 le->le_dva = hdr->b_dva;
10760 le->le_birth = hdr->b_birth;
10761 le->le_daddr = hdr->b_l2hdr.b_daddr;
10762 if (index == 0)
10763 dev->l2ad_log_blk_payload_start = le->le_daddr;
10764 L2BLK_SET_LSIZE((le)->le_prop, HDR_GET_LSIZE(hdr));
10765 L2BLK_SET_PSIZE((le)->le_prop, HDR_GET_PSIZE(hdr));
10766 L2BLK_SET_COMPRESS((le)->le_prop, HDR_GET_COMPRESS(hdr));
10b3c7f5 10767 le->le_complevel = hdr->b_complevel;
77f6826b
GA
10768 L2BLK_SET_TYPE((le)->le_prop, hdr->b_type);
10769 L2BLK_SET_PROTECTED((le)->le_prop, !!(HDR_PROTECTED(hdr)));
10770 L2BLK_SET_PREFETCH((le)->le_prop, !!(HDR_PREFETCH(hdr)));
08532162 10771 L2BLK_SET_STATE((le)->le_prop, hdr->b_l1hdr.b_state->arcs_state);
77f6826b
GA
10772
10773 dev->l2ad_log_blk_payload_asize += vdev_psize_to_asize(dev->l2ad_vdev,
10774 HDR_GET_PSIZE(hdr));
10775
657fd33b 10776 return (dev->l2ad_log_ent_idx == dev->l2ad_log_entries);
77f6826b
GA
10777}
10778
10779/*
10780 * Checks whether a given L2ARC device address sits in a time-sequential
10781 * range. The trick here is that the L2ARC is a rotary buffer, so we can't
10782 * just do a range comparison, we need to handle the situation in which the
10783 * range wraps around the end of the L2ARC device. Arguments:
10784 * bottom -- Lower end of the range to check (written to earlier).
10785 * top -- Upper end of the range to check (written to later).
10786 * check -- The address for which we want to determine if it sits in
10787 * between the top and bottom.
10788 *
10789 * The 3-way conditional below represents the following cases:
10790 *
10791 * bottom < top : Sequentially ordered case:
10792 * <check>--------+-------------------+
10793 * | (overlap here?) |
10794 * L2ARC dev V V
10795 * |---------------<bottom>============<top>--------------|
10796 *
10797 * bottom > top: Looped-around case:
10798 * <check>--------+------------------+
10799 * | (overlap here?) |
10800 * L2ARC dev V V
10801 * |===============<top>---------------<bottom>===========|
10802 * ^ ^
10803 * | (or here?) |
10804 * +---------------+---------<check>
10805 *
10806 * top == bottom : Just a single address comparison.
10807 */
10808boolean_t
10809l2arc_range_check_overlap(uint64_t bottom, uint64_t top, uint64_t check)
10810{
10811 if (bottom < top)
10812 return (bottom <= check && check <= top);
10813 else if (bottom > top)
10814 return (check <= top || bottom <= check);
10815 else
10816 return (check == top);
10817}
10818
0f699108
AZ
10819EXPORT_SYMBOL(arc_buf_size);
10820EXPORT_SYMBOL(arc_write);
c28b2279 10821EXPORT_SYMBOL(arc_read);
e0b0ca98 10822EXPORT_SYMBOL(arc_buf_info);
c28b2279 10823EXPORT_SYMBOL(arc_getbuf_func);
ab26409d
BB
10824EXPORT_SYMBOL(arc_add_prune_callback);
10825EXPORT_SYMBOL(arc_remove_prune_callback);
c28b2279 10826
e945e8d7 10827ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, min, param_set_arc_min,
ab8d9c17 10828 spl_param_get_u64, ZMOD_RW, "Minimum ARC size in bytes");
c28b2279 10829
e945e8d7 10830ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, max, param_set_arc_max,
ab8d9c17 10831 spl_param_get_u64, ZMOD_RW, "Maximum ARC size in bytes");
c28b2279 10832
a8d83e2a
AM
10833ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, meta_balance, UINT, ZMOD_RW,
10834 "Balance between metadata and data on ghost hits.");
f6046738 10835
e3570464 10836ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, grow_retry, param_set_arc_int,
fdc2d303 10837 param_get_uint, ZMOD_RW, "Seconds before growing ARC size");
c409e464 10838
e3570464 10839ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, shrink_shift, param_set_arc_int,
fdc2d303 10840 param_get_uint, ZMOD_RW, "log2(fraction of ARC to reclaim)");
c409e464 10841
03fdcb9a 10842ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, pc_percent, UINT, ZMOD_RW,
310ab9d2 10843 "Percent of pagecache to reclaim ARC to");
03b60eee 10844
fdc2d303 10845ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, average_blocksize, UINT, ZMOD_RD,
03fdcb9a 10846 "Target average block size");
49ddb315 10847
03fdcb9a 10848ZFS_MODULE_PARAM(zfs, zfs_, compressed_arc_enabled, INT, ZMOD_RW,
310ab9d2 10849 "Disable compressed ARC buffers");
d3c2ae1c 10850
e3570464 10851ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, min_prefetch_ms, param_set_arc_int,
fdc2d303 10852 param_get_uint, ZMOD_RW, "Min life of prefetch block in ms");
d4a72f23 10853
e3570464 10854ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, min_prescient_prefetch_ms,
fdc2d303 10855 param_set_arc_int, param_get_uint, ZMOD_RW,
d4a72f23 10856 "Min life of prescient prefetched block in ms");
bce45ec9 10857
ab8d9c17 10858ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, write_max, U64, ZMOD_RW,
03fdcb9a 10859 "Max write bytes per interval");
abd8610c 10860
ab8d9c17 10861ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, write_boost, U64, ZMOD_RW,
03fdcb9a 10862 "Extra write bytes during device warmup");
abd8610c 10863
ab8d9c17 10864ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, headroom, U64, ZMOD_RW,
03fdcb9a 10865 "Number of max device writes to precache");
abd8610c 10866
ab8d9c17 10867ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, headroom_boost, U64, ZMOD_RW,
03fdcb9a 10868 "Compressed l2arc_headroom multiplier");
3a17a7a9 10869
ab8d9c17 10870ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, trim_ahead, U64, ZMOD_RW,
b7654bd7
GA
10871 "TRIM ahead L2ARC write size multiplier");
10872
ab8d9c17 10873ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, feed_secs, U64, ZMOD_RW,
03fdcb9a 10874 "Seconds between L2ARC writing");
abd8610c 10875
ab8d9c17 10876ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, feed_min_ms, U64, ZMOD_RW,
03fdcb9a 10877 "Min feed interval in milliseconds");
abd8610c 10878
03fdcb9a
MM
10879ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, noprefetch, INT, ZMOD_RW,
10880 "Skip caching prefetched buffers");
abd8610c 10881
03fdcb9a
MM
10882ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, feed_again, INT, ZMOD_RW,
10883 "Turbo L2ARC warmup");
abd8610c 10884
03fdcb9a
MM
10885ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, norw, INT, ZMOD_RW,
10886 "No reads during writes");
abd8610c 10887
fdc2d303 10888ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, meta_percent, UINT, ZMOD_RW,
523e1295
AM
10889 "Percent of ARC size allowed for L2ARC-only headers");
10890
77f6826b
GA
10891ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, rebuild_enabled, INT, ZMOD_RW,
10892 "Rebuild the L2ARC when importing a pool");
10893
ab8d9c17 10894ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, rebuild_blocks_min_l2size, U64, ZMOD_RW,
77f6826b
GA
10895 "Min size in bytes to write rebuild log blocks in L2ARC");
10896
feb3a7ee
GA
10897ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, mfuonly, INT, ZMOD_RW,
10898 "Cache only MFU data from ARC into L2ARC");
10899
c9d62d13 10900ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, exclude_special, INT, ZMOD_RW,
7ada752a 10901 "Exclude dbufs on special vdevs from being cached to L2ARC if set.");
c9d62d13 10902
e3570464 10903ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, lotsfree_percent, param_set_arc_int,
fdc2d303 10904 param_get_uint, ZMOD_RW, "System free memory I/O throttle in bytes");
7e8bddd0 10905
ab8d9c17
RY
10906ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, sys_free, param_set_arc_u64,
10907 spl_param_get_u64, ZMOD_RW, "System free memory target size in bytes");
11f552fa 10908
ab8d9c17
RY
10909ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, dnode_limit, param_set_arc_u64,
10910 spl_param_get_u64, ZMOD_RW, "Minimum bytes of dnodes in ARC");
25458cbe 10911
e3570464 10912ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, dnode_limit_percent,
ab8d9c17 10913 param_set_arc_int, param_get_uint, ZMOD_RW,
9907cc1c
G
10914 "Percent of ARC meta buffers for dnodes");
10915
ab8d9c17 10916ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, dnode_reduce_percent, UINT, ZMOD_RW,
25458cbe 10917 "Percentage of excess dnodes to try to unpin");
3442c2a0 10918
fdc2d303 10919ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, eviction_pct, UINT, ZMOD_RW,
eb02a4c6
RM
10920 "When full, ARC allocation waits for eviction of this % of alloc size");
10921
fdc2d303 10922ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, evict_batch_limit, UINT, ZMOD_RW,
eb02a4c6 10923 "The number of headers to evict per sublist before moving to the next");
462217d1
AM
10924
10925ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, prune_task_threads, INT, ZMOD_RW,
10926 "Number of arc_prune threads");