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