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