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