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