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