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