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