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