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