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