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