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