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