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