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