]> git.proxmox.com Git - mirror_zfs.git/blame - module/zfs/arc.c
Illumos 4757, 4913
[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.
2e528b49 23 * Copyright (c) 2013 by Delphix. All rights reserved.
3a17a7a9 24 * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
0ed212dc 25 * Copyright 2013 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
107 * protected from simultaneous callbacks from arc_buf_evict()
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 *
121 * The L2ARC uses the l2arc_buflist_mtx global mutex for the following:
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>
34dc7c2f
BB
138#ifdef _KERNEL
139#include <sys/vmsystm.h>
140#include <vm/anon.h>
141#include <sys/fs/swapnode.h>
ab26409d 142#include <sys/zpl.h>
34dc7c2f
BB
143#endif
144#include <sys/callb.h>
145#include <sys/kstat.h>
570827e1 146#include <sys/dmu_tx.h>
428870ff 147#include <zfs_fletcher.h>
34dc7c2f 148
498877ba
MA
149#ifndef _KERNEL
150/* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
151boolean_t arc_watch = B_FALSE;
152#endif
153
34dc7c2f
BB
154static kmutex_t arc_reclaim_thr_lock;
155static kcondvar_t arc_reclaim_thr_cv; /* used to signal reclaim thr */
156static uint8_t arc_thread_exit;
157
ab26409d 158/* number of bytes to prune from caches when at arc_meta_limit is reached */
bce45ec9 159int zfs_arc_meta_prune = 1048576;
34dc7c2f
BB
160
161typedef enum arc_reclaim_strategy {
162 ARC_RECLAIM_AGGR, /* Aggressive reclaim strategy */
163 ARC_RECLAIM_CONS /* Conservative reclaim strategy */
164} arc_reclaim_strategy_t;
165
e8b96c60
MA
166/*
167 * The number of iterations through arc_evict_*() before we
168 * drop & reacquire the lock.
169 */
170int arc_evict_iterations = 100;
171
34dc7c2f 172/* number of seconds before growing cache again */
bce45ec9 173int zfs_arc_grow_retry = 5;
34dc7c2f 174
89c8cac4
PS
175/* disable anon data aggressively growing arc_p */
176int zfs_arc_p_aggressive_disable = 1;
177
62422785
PS
178/* disable arc_p adapt dampener in arc_adapt */
179int zfs_arc_p_dampener_disable = 1;
180
d164b209 181/* log2(fraction of arc to reclaim) */
bce45ec9 182int zfs_arc_shrink_shift = 5;
d164b209 183
34dc7c2f
BB
184/*
185 * minimum lifespan of a prefetch block in clock ticks
186 * (initialized in arc_init())
187 */
bce45ec9
BB
188int zfs_arc_min_prefetch_lifespan = HZ;
189
190/* disable arc proactive arc throttle due to low memory */
191int zfs_arc_memory_throttle_disable = 1;
192
193/* disable duplicate buffer eviction */
194int zfs_disable_dup_eviction = 0;
34dc7c2f 195
e8b96c60
MA
196/*
197 * If this percent of memory is free, don't throttle.
198 */
199int arc_lotsfree_percent = 10;
200
34dc7c2f
BB
201static int arc_dead;
202
bce45ec9
BB
203/* expiration time for arc_no_grow */
204static clock_t arc_grow_time = 0;
205
b128c09f
BB
206/*
207 * The arc has filled available memory and has now warmed up.
208 */
209static boolean_t arc_warm;
210
34dc7c2f
BB
211/*
212 * These tunables are for performance analysis.
213 */
c28b2279
BB
214unsigned long zfs_arc_max = 0;
215unsigned long zfs_arc_min = 0;
216unsigned long zfs_arc_meta_limit = 0;
34dc7c2f
BB
217
218/*
219 * Note that buffers can be in one of 6 states:
220 * ARC_anon - anonymous (discussed below)
221 * ARC_mru - recently used, currently cached
222 * ARC_mru_ghost - recentely used, no longer in cache
223 * ARC_mfu - frequently used, currently cached
224 * ARC_mfu_ghost - frequently used, no longer in cache
225 * ARC_l2c_only - exists in L2ARC but not other states
226 * When there are no active references to the buffer, they are
227 * are linked onto a list in one of these arc states. These are
228 * the only buffers that can be evicted or deleted. Within each
229 * state there are multiple lists, one for meta-data and one for
230 * non-meta-data. Meta-data (indirect blocks, blocks of dnodes,
231 * etc.) is tracked separately so that it can be managed more
232 * explicitly: favored over data, limited explicitly.
233 *
234 * Anonymous buffers are buffers that are not associated with
235 * a DVA. These are buffers that hold dirty block copies
236 * before they are written to stable storage. By definition,
237 * they are "ref'd" and are considered part of arc_mru
238 * that cannot be freed. Generally, they will aquire a DVA
239 * as they are written and migrate onto the arc_mru list.
240 *
241 * The ARC_l2c_only state is for buffers that are in the second
242 * level ARC but no longer in any of the ARC_m* lists. The second
243 * level ARC itself may also contain buffers that are in any of
244 * the ARC_m* states - meaning that a buffer can exist in two
245 * places. The reason for the ARC_l2c_only state is to keep the
246 * buffer header in the hash table, so that reads that hit the
247 * second level ARC benefit from these fast lookups.
248 */
249
250typedef struct arc_state {
251 list_t arcs_list[ARC_BUFC_NUMTYPES]; /* list of evictable buffers */
252 uint64_t arcs_lsize[ARC_BUFC_NUMTYPES]; /* amount of evictable data */
253 uint64_t arcs_size; /* total amount of data in this state */
254 kmutex_t arcs_mtx;
e0b0ca98 255 arc_state_type_t arcs_state;
34dc7c2f
BB
256} arc_state_t;
257
258/* The 6 states: */
259static arc_state_t ARC_anon;
260static arc_state_t ARC_mru;
261static arc_state_t ARC_mru_ghost;
262static arc_state_t ARC_mfu;
263static arc_state_t ARC_mfu_ghost;
264static arc_state_t ARC_l2c_only;
265
266typedef struct arc_stats {
267 kstat_named_t arcstat_hits;
268 kstat_named_t arcstat_misses;
269 kstat_named_t arcstat_demand_data_hits;
270 kstat_named_t arcstat_demand_data_misses;
271 kstat_named_t arcstat_demand_metadata_hits;
272 kstat_named_t arcstat_demand_metadata_misses;
273 kstat_named_t arcstat_prefetch_data_hits;
274 kstat_named_t arcstat_prefetch_data_misses;
275 kstat_named_t arcstat_prefetch_metadata_hits;
276 kstat_named_t arcstat_prefetch_metadata_misses;
277 kstat_named_t arcstat_mru_hits;
278 kstat_named_t arcstat_mru_ghost_hits;
279 kstat_named_t arcstat_mfu_hits;
280 kstat_named_t arcstat_mfu_ghost_hits;
281 kstat_named_t arcstat_deleted;
282 kstat_named_t arcstat_recycle_miss;
e49f1e20
WA
283 /*
284 * Number of buffers that could not be evicted because the hash lock
285 * was held by another thread. The lock may not necessarily be held
286 * by something using the same buffer, since hash locks are shared
287 * by multiple buffers.
288 */
34dc7c2f 289 kstat_named_t arcstat_mutex_miss;
e49f1e20
WA
290 /*
291 * Number of buffers skipped because they have I/O in progress, are
292 * indrect prefetch buffers that have not lived long enough, or are
293 * not from the spa we're trying to evict from.
294 */
34dc7c2f 295 kstat_named_t arcstat_evict_skip;
428870ff
BB
296 kstat_named_t arcstat_evict_l2_cached;
297 kstat_named_t arcstat_evict_l2_eligible;
298 kstat_named_t arcstat_evict_l2_ineligible;
34dc7c2f
BB
299 kstat_named_t arcstat_hash_elements;
300 kstat_named_t arcstat_hash_elements_max;
301 kstat_named_t arcstat_hash_collisions;
302 kstat_named_t arcstat_hash_chains;
303 kstat_named_t arcstat_hash_chain_max;
304 kstat_named_t arcstat_p;
305 kstat_named_t arcstat_c;
306 kstat_named_t arcstat_c_min;
307 kstat_named_t arcstat_c_max;
308 kstat_named_t arcstat_size;
309 kstat_named_t arcstat_hdr_size;
d164b209 310 kstat_named_t arcstat_data_size;
cc7f677c 311 kstat_named_t arcstat_meta_size;
d164b209 312 kstat_named_t arcstat_other_size;
13be560d
BB
313 kstat_named_t arcstat_anon_size;
314 kstat_named_t arcstat_anon_evict_data;
315 kstat_named_t arcstat_anon_evict_metadata;
316 kstat_named_t arcstat_mru_size;
317 kstat_named_t arcstat_mru_evict_data;
318 kstat_named_t arcstat_mru_evict_metadata;
319 kstat_named_t arcstat_mru_ghost_size;
320 kstat_named_t arcstat_mru_ghost_evict_data;
321 kstat_named_t arcstat_mru_ghost_evict_metadata;
322 kstat_named_t arcstat_mfu_size;
323 kstat_named_t arcstat_mfu_evict_data;
324 kstat_named_t arcstat_mfu_evict_metadata;
325 kstat_named_t arcstat_mfu_ghost_size;
326 kstat_named_t arcstat_mfu_ghost_evict_data;
327 kstat_named_t arcstat_mfu_ghost_evict_metadata;
34dc7c2f
BB
328 kstat_named_t arcstat_l2_hits;
329 kstat_named_t arcstat_l2_misses;
330 kstat_named_t arcstat_l2_feeds;
331 kstat_named_t arcstat_l2_rw_clash;
d164b209
BB
332 kstat_named_t arcstat_l2_read_bytes;
333 kstat_named_t arcstat_l2_write_bytes;
34dc7c2f
BB
334 kstat_named_t arcstat_l2_writes_sent;
335 kstat_named_t arcstat_l2_writes_done;
336 kstat_named_t arcstat_l2_writes_error;
337 kstat_named_t arcstat_l2_writes_hdr_miss;
338 kstat_named_t arcstat_l2_evict_lock_retry;
339 kstat_named_t arcstat_l2_evict_reading;
340 kstat_named_t arcstat_l2_free_on_write;
341 kstat_named_t arcstat_l2_abort_lowmem;
342 kstat_named_t arcstat_l2_cksum_bad;
343 kstat_named_t arcstat_l2_io_error;
344 kstat_named_t arcstat_l2_size;
3a17a7a9 345 kstat_named_t arcstat_l2_asize;
34dc7c2f 346 kstat_named_t arcstat_l2_hdr_size;
3a17a7a9
SK
347 kstat_named_t arcstat_l2_compress_successes;
348 kstat_named_t arcstat_l2_compress_zeros;
349 kstat_named_t arcstat_l2_compress_failures;
34dc7c2f 350 kstat_named_t arcstat_memory_throttle_count;
1eb5bfa3
GW
351 kstat_named_t arcstat_duplicate_buffers;
352 kstat_named_t arcstat_duplicate_buffers_size;
353 kstat_named_t arcstat_duplicate_reads;
7cb67b45
BB
354 kstat_named_t arcstat_memory_direct_count;
355 kstat_named_t arcstat_memory_indirect_count;
1834f2d8
BB
356 kstat_named_t arcstat_no_grow;
357 kstat_named_t arcstat_tempreserve;
358 kstat_named_t arcstat_loaned_bytes;
ab26409d 359 kstat_named_t arcstat_prune;
1834f2d8
BB
360 kstat_named_t arcstat_meta_used;
361 kstat_named_t arcstat_meta_limit;
362 kstat_named_t arcstat_meta_max;
34dc7c2f
BB
363} arc_stats_t;
364
365static arc_stats_t arc_stats = {
366 { "hits", KSTAT_DATA_UINT64 },
367 { "misses", KSTAT_DATA_UINT64 },
368 { "demand_data_hits", KSTAT_DATA_UINT64 },
369 { "demand_data_misses", KSTAT_DATA_UINT64 },
370 { "demand_metadata_hits", KSTAT_DATA_UINT64 },
371 { "demand_metadata_misses", KSTAT_DATA_UINT64 },
372 { "prefetch_data_hits", KSTAT_DATA_UINT64 },
373 { "prefetch_data_misses", KSTAT_DATA_UINT64 },
374 { "prefetch_metadata_hits", KSTAT_DATA_UINT64 },
375 { "prefetch_metadata_misses", KSTAT_DATA_UINT64 },
376 { "mru_hits", KSTAT_DATA_UINT64 },
377 { "mru_ghost_hits", KSTAT_DATA_UINT64 },
378 { "mfu_hits", KSTAT_DATA_UINT64 },
379 { "mfu_ghost_hits", KSTAT_DATA_UINT64 },
380 { "deleted", KSTAT_DATA_UINT64 },
381 { "recycle_miss", KSTAT_DATA_UINT64 },
382 { "mutex_miss", KSTAT_DATA_UINT64 },
383 { "evict_skip", KSTAT_DATA_UINT64 },
428870ff
BB
384 { "evict_l2_cached", KSTAT_DATA_UINT64 },
385 { "evict_l2_eligible", KSTAT_DATA_UINT64 },
386 { "evict_l2_ineligible", KSTAT_DATA_UINT64 },
34dc7c2f
BB
387 { "hash_elements", KSTAT_DATA_UINT64 },
388 { "hash_elements_max", KSTAT_DATA_UINT64 },
389 { "hash_collisions", KSTAT_DATA_UINT64 },
390 { "hash_chains", KSTAT_DATA_UINT64 },
391 { "hash_chain_max", KSTAT_DATA_UINT64 },
392 { "p", KSTAT_DATA_UINT64 },
393 { "c", KSTAT_DATA_UINT64 },
394 { "c_min", KSTAT_DATA_UINT64 },
395 { "c_max", KSTAT_DATA_UINT64 },
396 { "size", KSTAT_DATA_UINT64 },
397 { "hdr_size", KSTAT_DATA_UINT64 },
d164b209 398 { "data_size", KSTAT_DATA_UINT64 },
cc7f677c 399 { "meta_size", KSTAT_DATA_UINT64 },
d164b209 400 { "other_size", KSTAT_DATA_UINT64 },
13be560d
BB
401 { "anon_size", KSTAT_DATA_UINT64 },
402 { "anon_evict_data", KSTAT_DATA_UINT64 },
403 { "anon_evict_metadata", KSTAT_DATA_UINT64 },
404 { "mru_size", KSTAT_DATA_UINT64 },
405 { "mru_evict_data", KSTAT_DATA_UINT64 },
406 { "mru_evict_metadata", KSTAT_DATA_UINT64 },
407 { "mru_ghost_size", KSTAT_DATA_UINT64 },
408 { "mru_ghost_evict_data", KSTAT_DATA_UINT64 },
409 { "mru_ghost_evict_metadata", KSTAT_DATA_UINT64 },
410 { "mfu_size", KSTAT_DATA_UINT64 },
411 { "mfu_evict_data", KSTAT_DATA_UINT64 },
412 { "mfu_evict_metadata", KSTAT_DATA_UINT64 },
413 { "mfu_ghost_size", KSTAT_DATA_UINT64 },
414 { "mfu_ghost_evict_data", KSTAT_DATA_UINT64 },
415 { "mfu_ghost_evict_metadata", KSTAT_DATA_UINT64 },
34dc7c2f
BB
416 { "l2_hits", KSTAT_DATA_UINT64 },
417 { "l2_misses", KSTAT_DATA_UINT64 },
418 { "l2_feeds", KSTAT_DATA_UINT64 },
419 { "l2_rw_clash", KSTAT_DATA_UINT64 },
d164b209
BB
420 { "l2_read_bytes", KSTAT_DATA_UINT64 },
421 { "l2_write_bytes", KSTAT_DATA_UINT64 },
34dc7c2f
BB
422 { "l2_writes_sent", KSTAT_DATA_UINT64 },
423 { "l2_writes_done", KSTAT_DATA_UINT64 },
424 { "l2_writes_error", KSTAT_DATA_UINT64 },
425 { "l2_writes_hdr_miss", KSTAT_DATA_UINT64 },
426 { "l2_evict_lock_retry", KSTAT_DATA_UINT64 },
427 { "l2_evict_reading", KSTAT_DATA_UINT64 },
428 { "l2_free_on_write", KSTAT_DATA_UINT64 },
429 { "l2_abort_lowmem", KSTAT_DATA_UINT64 },
430 { "l2_cksum_bad", KSTAT_DATA_UINT64 },
431 { "l2_io_error", KSTAT_DATA_UINT64 },
432 { "l2_size", KSTAT_DATA_UINT64 },
3a17a7a9 433 { "l2_asize", KSTAT_DATA_UINT64 },
34dc7c2f 434 { "l2_hdr_size", KSTAT_DATA_UINT64 },
3a17a7a9
SK
435 { "l2_compress_successes", KSTAT_DATA_UINT64 },
436 { "l2_compress_zeros", KSTAT_DATA_UINT64 },
437 { "l2_compress_failures", KSTAT_DATA_UINT64 },
1834f2d8 438 { "memory_throttle_count", KSTAT_DATA_UINT64 },
1eb5bfa3
GW
439 { "duplicate_buffers", KSTAT_DATA_UINT64 },
440 { "duplicate_buffers_size", KSTAT_DATA_UINT64 },
441 { "duplicate_reads", KSTAT_DATA_UINT64 },
7cb67b45
BB
442 { "memory_direct_count", KSTAT_DATA_UINT64 },
443 { "memory_indirect_count", KSTAT_DATA_UINT64 },
1834f2d8
BB
444 { "arc_no_grow", KSTAT_DATA_UINT64 },
445 { "arc_tempreserve", KSTAT_DATA_UINT64 },
446 { "arc_loaned_bytes", KSTAT_DATA_UINT64 },
ab26409d 447 { "arc_prune", KSTAT_DATA_UINT64 },
1834f2d8
BB
448 { "arc_meta_used", KSTAT_DATA_UINT64 },
449 { "arc_meta_limit", KSTAT_DATA_UINT64 },
450 { "arc_meta_max", KSTAT_DATA_UINT64 },
34dc7c2f
BB
451};
452
453#define ARCSTAT(stat) (arc_stats.stat.value.ui64)
454
455#define ARCSTAT_INCR(stat, val) \
d3cc8b15 456 atomic_add_64(&arc_stats.stat.value.ui64, (val))
34dc7c2f 457
428870ff 458#define ARCSTAT_BUMP(stat) ARCSTAT_INCR(stat, 1)
34dc7c2f
BB
459#define ARCSTAT_BUMPDOWN(stat) ARCSTAT_INCR(stat, -1)
460
461#define ARCSTAT_MAX(stat, val) { \
462 uint64_t m; \
463 while ((val) > (m = arc_stats.stat.value.ui64) && \
464 (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val)))) \
465 continue; \
466}
467
468#define ARCSTAT_MAXSTAT(stat) \
469 ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
470
471/*
472 * We define a macro to allow ARC hits/misses to be easily broken down by
473 * two separate conditions, giving a total of four different subtypes for
474 * each of hits and misses (so eight statistics total).
475 */
476#define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
477 if (cond1) { \
478 if (cond2) { \
479 ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
480 } else { \
481 ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
482 } \
483 } else { \
484 if (cond2) { \
485 ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
486 } else { \
487 ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
488 } \
489 }
490
491kstat_t *arc_ksp;
428870ff 492static arc_state_t *arc_anon;
34dc7c2f
BB
493static arc_state_t *arc_mru;
494static arc_state_t *arc_mru_ghost;
495static arc_state_t *arc_mfu;
496static arc_state_t *arc_mfu_ghost;
497static arc_state_t *arc_l2c_only;
498
499/*
500 * There are several ARC variables that are critical to export as kstats --
501 * but we don't want to have to grovel around in the kstat whenever we wish to
502 * manipulate them. For these variables, we therefore define them to be in
503 * terms of the statistic variable. This assures that we are not introducing
504 * the possibility of inconsistency by having shadow copies of the variables,
505 * while still allowing the code to be readable.
506 */
507#define arc_size ARCSTAT(arcstat_size) /* actual total arc size */
508#define arc_p ARCSTAT(arcstat_p) /* target size of MRU */
509#define arc_c ARCSTAT(arcstat_c) /* target size of cache */
510#define arc_c_min ARCSTAT(arcstat_c_min) /* min target cache size */
511#define arc_c_max ARCSTAT(arcstat_c_max) /* max target cache size */
1834f2d8
BB
512#define arc_no_grow ARCSTAT(arcstat_no_grow)
513#define arc_tempreserve ARCSTAT(arcstat_tempreserve)
514#define arc_loaned_bytes ARCSTAT(arcstat_loaned_bytes)
23c0a133
GW
515#define arc_meta_limit ARCSTAT(arcstat_meta_limit) /* max size for metadata */
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
34dc7c2f
BB
522typedef struct l2arc_buf_hdr l2arc_buf_hdr_t;
523
524typedef struct arc_callback arc_callback_t;
525
526struct arc_callback {
527 void *acb_private;
528 arc_done_func_t *acb_done;
34dc7c2f
BB
529 arc_buf_t *acb_buf;
530 zio_t *acb_zio_dummy;
531 arc_callback_t *acb_next;
532};
533
534typedef struct arc_write_callback arc_write_callback_t;
535
536struct arc_write_callback {
537 void *awcb_private;
538 arc_done_func_t *awcb_ready;
e8b96c60 539 arc_done_func_t *awcb_physdone;
34dc7c2f
BB
540 arc_done_func_t *awcb_done;
541 arc_buf_t *awcb_buf;
542};
543
544struct arc_buf_hdr {
545 /* protected by hash lock */
546 dva_t b_dva;
547 uint64_t b_birth;
548 uint64_t b_cksum0;
549
550 kmutex_t b_freeze_lock;
551 zio_cksum_t *b_freeze_cksum;
552
553 arc_buf_hdr_t *b_hash_next;
554 arc_buf_t *b_buf;
555 uint32_t b_flags;
556 uint32_t b_datacnt;
557
558 arc_callback_t *b_acb;
559 kcondvar_t b_cv;
560
561 /* immutable */
562 arc_buf_contents_t b_type;
563 uint64_t b_size;
d164b209 564 uint64_t b_spa;
34dc7c2f
BB
565
566 /* protected by arc state mutex */
567 arc_state_t *b_state;
568 list_node_t b_arc_node;
569
570 /* updated atomically */
571 clock_t b_arc_access;
e0b0ca98
BB
572 uint32_t b_mru_hits;
573 uint32_t b_mru_ghost_hits;
574 uint32_t b_mfu_hits;
575 uint32_t b_mfu_ghost_hits;
576 uint32_t b_l2_hits;
34dc7c2f
BB
577
578 /* self protecting */
579 refcount_t b_refcnt;
580
581 l2arc_buf_hdr_t *b_l2hdr;
582 list_node_t b_l2node;
583};
584
ab26409d
BB
585static list_t arc_prune_list;
586static kmutex_t arc_prune_mtx;
34dc7c2f
BB
587static arc_buf_t *arc_eviction_list;
588static kmutex_t arc_eviction_mtx;
589static arc_buf_hdr_t arc_eviction_hdr;
590static void arc_get_data_buf(arc_buf_t *buf);
591static void arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock);
592static int arc_evict_needed(arc_buf_contents_t type);
68121a03
BB
593static void arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes,
594 arc_buf_contents_t type);
498877ba 595static void arc_buf_watch(arc_buf_t *buf);
34dc7c2f 596
428870ff
BB
597static boolean_t l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *ab);
598
34dc7c2f
BB
599#define GHOST_STATE(state) \
600 ((state) == arc_mru_ghost || (state) == arc_mfu_ghost || \
601 (state) == arc_l2c_only)
602
603/*
604 * Private ARC flags. These flags are private ARC only flags that will show up
605 * in b_flags in the arc_hdr_buf_t. Some flags are publicly declared, and can
606 * be passed in as arc_flags in things like arc_read. However, these flags
607 * should never be passed and should only be set by ARC code. When adding new
608 * public flags, make sure not to smash the private ones.
609 */
610
611#define ARC_IN_HASH_TABLE (1 << 9) /* this buffer is hashed */
612#define ARC_IO_IN_PROGRESS (1 << 10) /* I/O in progress for buf */
613#define ARC_IO_ERROR (1 << 11) /* I/O failed for buf */
614#define ARC_FREED_IN_READ (1 << 12) /* buf freed while in read */
615#define ARC_BUF_AVAILABLE (1 << 13) /* block not in active use */
616#define ARC_INDIRECT (1 << 14) /* this is an indirect block */
617#define ARC_FREE_IN_PROGRESS (1 << 15) /* hdr about to be freed */
b128c09f
BB
618#define ARC_L2_WRITING (1 << 16) /* L2ARC write in progress */
619#define ARC_L2_EVICTED (1 << 17) /* evicted during I/O */
620#define ARC_L2_WRITE_HEAD (1 << 18) /* head of write list */
34dc7c2f
BB
621
622#define HDR_IN_HASH_TABLE(hdr) ((hdr)->b_flags & ARC_IN_HASH_TABLE)
623#define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_IO_IN_PROGRESS)
624#define HDR_IO_ERROR(hdr) ((hdr)->b_flags & ARC_IO_ERROR)
d164b209 625#define HDR_PREFETCH(hdr) ((hdr)->b_flags & ARC_PREFETCH)
34dc7c2f
BB
626#define HDR_FREED_IN_READ(hdr) ((hdr)->b_flags & ARC_FREED_IN_READ)
627#define HDR_BUF_AVAILABLE(hdr) ((hdr)->b_flags & ARC_BUF_AVAILABLE)
628#define HDR_FREE_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_FREE_IN_PROGRESS)
b128c09f
BB
629#define HDR_L2CACHE(hdr) ((hdr)->b_flags & ARC_L2CACHE)
630#define HDR_L2_READING(hdr) ((hdr)->b_flags & ARC_IO_IN_PROGRESS && \
631 (hdr)->b_l2hdr != NULL)
34dc7c2f
BB
632#define HDR_L2_WRITING(hdr) ((hdr)->b_flags & ARC_L2_WRITING)
633#define HDR_L2_EVICTED(hdr) ((hdr)->b_flags & ARC_L2_EVICTED)
634#define HDR_L2_WRITE_HEAD(hdr) ((hdr)->b_flags & ARC_L2_WRITE_HEAD)
635
636/*
637 * Other sizes
638 */
639
640#define HDR_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
641#define L2HDR_SIZE ((int64_t)sizeof (l2arc_buf_hdr_t))
642
643/*
644 * Hash table routines
645 */
646
00b46022
BB
647#define HT_LOCK_ALIGN 64
648#define HT_LOCK_PAD (P2NPHASE(sizeof (kmutex_t), (HT_LOCK_ALIGN)))
34dc7c2f
BB
649
650struct ht_lock {
651 kmutex_t ht_lock;
652#ifdef _KERNEL
00b46022 653 unsigned char pad[HT_LOCK_PAD];
34dc7c2f
BB
654#endif
655};
656
657#define BUF_LOCKS 256
658typedef struct buf_hash_table {
659 uint64_t ht_mask;
660 arc_buf_hdr_t **ht_table;
661 struct ht_lock ht_locks[BUF_LOCKS];
662} buf_hash_table_t;
663
664static buf_hash_table_t buf_hash_table;
665
666#define BUF_HASH_INDEX(spa, dva, birth) \
667 (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
668#define BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
669#define BUF_HASH_LOCK(idx) (&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
428870ff
BB
670#define HDR_LOCK(hdr) \
671 (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
34dc7c2f
BB
672
673uint64_t zfs_crc64_table[256];
674
675/*
676 * Level 2 ARC
677 */
678
679#define L2ARC_WRITE_SIZE (8 * 1024 * 1024) /* initial write max */
3a17a7a9
SK
680#define L2ARC_HEADROOM 2 /* num of writes */
681/*
682 * If we discover during ARC scan any buffers to be compressed, we boost
683 * our headroom for the next scanning cycle by this percentage multiple.
684 */
685#define L2ARC_HEADROOM_BOOST 200
d164b209
BB
686#define L2ARC_FEED_SECS 1 /* caching interval secs */
687#define L2ARC_FEED_MIN_MS 200 /* min caching interval ms */
34dc7c2f
BB
688
689#define l2arc_writes_sent ARCSTAT(arcstat_l2_writes_sent)
690#define l2arc_writes_done ARCSTAT(arcstat_l2_writes_done)
691
d3cc8b15 692/* L2ARC Performance Tunables */
abd8610c
BB
693unsigned long l2arc_write_max = L2ARC_WRITE_SIZE; /* def max write size */
694unsigned long l2arc_write_boost = L2ARC_WRITE_SIZE; /* extra warmup write */
695unsigned long l2arc_headroom = L2ARC_HEADROOM; /* # of dev writes */
3a17a7a9 696unsigned long l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
abd8610c
BB
697unsigned long l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
698unsigned long l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval msecs */
699int l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
3a17a7a9 700int l2arc_nocompress = B_FALSE; /* don't compress bufs */
abd8610c 701int l2arc_feed_again = B_TRUE; /* turbo warmup */
c93504f0 702int l2arc_norw = B_FALSE; /* no reads during writes */
34dc7c2f
BB
703
704/*
705 * L2ARC Internals
706 */
707typedef struct l2arc_dev {
708 vdev_t *l2ad_vdev; /* vdev */
709 spa_t *l2ad_spa; /* spa */
710 uint64_t l2ad_hand; /* next write location */
34dc7c2f
BB
711 uint64_t l2ad_start; /* first addr on device */
712 uint64_t l2ad_end; /* last addr on device */
713 uint64_t l2ad_evict; /* last addr eviction reached */
714 boolean_t l2ad_first; /* first sweep through */
d164b209 715 boolean_t l2ad_writing; /* currently writing */
34dc7c2f
BB
716 list_t *l2ad_buflist; /* buffer list */
717 list_node_t l2ad_node; /* device list node */
718} l2arc_dev_t;
719
720static list_t L2ARC_dev_list; /* device list */
721static list_t *l2arc_dev_list; /* device list pointer */
722static kmutex_t l2arc_dev_mtx; /* device list mutex */
723static l2arc_dev_t *l2arc_dev_last; /* last device used */
724static kmutex_t l2arc_buflist_mtx; /* mutex for all buflists */
725static list_t L2ARC_free_on_write; /* free after write buf list */
726static list_t *l2arc_free_on_write; /* free after write list ptr */
727static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
728static uint64_t l2arc_ndev; /* number of devices */
729
730typedef struct l2arc_read_callback {
3a17a7a9
SK
731 arc_buf_t *l2rcb_buf; /* read buffer */
732 spa_t *l2rcb_spa; /* spa */
733 blkptr_t l2rcb_bp; /* original blkptr */
734 zbookmark_t l2rcb_zb; /* original bookmark */
735 int l2rcb_flags; /* original flags */
736 enum zio_compress l2rcb_compress; /* applied compress */
34dc7c2f
BB
737} l2arc_read_callback_t;
738
739typedef struct l2arc_write_callback {
740 l2arc_dev_t *l2wcb_dev; /* device info */
741 arc_buf_hdr_t *l2wcb_head; /* head of write buflist */
742} l2arc_write_callback_t;
743
744struct l2arc_buf_hdr {
745 /* protected by arc_buf_hdr mutex */
3a17a7a9
SK
746 l2arc_dev_t *b_dev; /* L2ARC device */
747 uint64_t b_daddr; /* disk address, offset byte */
748 /* compression applied to buffer data */
749 enum zio_compress b_compress;
750 /* real alloc'd buffer size depending on b_compress applied */
e0b0ca98 751 uint32_t b_hits;
c5cb66ad 752 uint64_t b_asize;
3a17a7a9
SK
753 /* temporary buffer holder for in-flight compressed data */
754 void *b_tmp_cdata;
34dc7c2f
BB
755};
756
757typedef struct l2arc_data_free {
758 /* protected by l2arc_free_on_write_mtx */
759 void *l2df_data;
760 size_t l2df_size;
761 void (*l2df_func)(void *, size_t);
762 list_node_t l2df_list_node;
763} l2arc_data_free_t;
764
765static kmutex_t l2arc_feed_thr_lock;
766static kcondvar_t l2arc_feed_thr_cv;
767static uint8_t l2arc_thread_exit;
768
769static void l2arc_read_done(zio_t *zio);
770static void l2arc_hdr_stat_add(void);
771static void l2arc_hdr_stat_remove(void);
772
3a17a7a9
SK
773static boolean_t l2arc_compress_buf(l2arc_buf_hdr_t *l2hdr);
774static void l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr,
775 enum zio_compress c);
776static void l2arc_release_cdata_buf(arc_buf_hdr_t *ab);
777
34dc7c2f 778static uint64_t
d164b209 779buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
34dc7c2f 780{
34dc7c2f
BB
781 uint8_t *vdva = (uint8_t *)dva;
782 uint64_t crc = -1ULL;
783 int i;
784
785 ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
786
787 for (i = 0; i < sizeof (dva_t); i++)
788 crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
789
d164b209 790 crc ^= (spa>>8) ^ birth;
34dc7c2f
BB
791
792 return (crc);
793}
794
795#define BUF_EMPTY(buf) \
796 ((buf)->b_dva.dva_word[0] == 0 && \
797 (buf)->b_dva.dva_word[1] == 0 && \
b0bc7a84 798 (buf)->b_cksum0 == 0)
34dc7c2f
BB
799
800#define BUF_EQUAL(spa, dva, birth, buf) \
801 ((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
802 ((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
803 ((buf)->b_birth == birth) && ((buf)->b_spa == spa)
804
428870ff
BB
805static void
806buf_discard_identity(arc_buf_hdr_t *hdr)
807{
808 hdr->b_dva.dva_word[0] = 0;
809 hdr->b_dva.dva_word[1] = 0;
810 hdr->b_birth = 0;
811 hdr->b_cksum0 = 0;
812}
813
34dc7c2f 814static arc_buf_hdr_t *
9b67f605 815buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
34dc7c2f 816{
9b67f605
MA
817 const dva_t *dva = BP_IDENTITY(bp);
818 uint64_t birth = BP_PHYSICAL_BIRTH(bp);
34dc7c2f
BB
819 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
820 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
821 arc_buf_hdr_t *buf;
822
823 mutex_enter(hash_lock);
824 for (buf = buf_hash_table.ht_table[idx]; buf != NULL;
825 buf = buf->b_hash_next) {
826 if (BUF_EQUAL(spa, dva, birth, buf)) {
827 *lockp = hash_lock;
828 return (buf);
829 }
830 }
831 mutex_exit(hash_lock);
832 *lockp = NULL;
833 return (NULL);
834}
835
836/*
837 * Insert an entry into the hash table. If there is already an element
838 * equal to elem in the hash table, then the already existing element
839 * will be returned and the new element will not be inserted.
840 * Otherwise returns NULL.
841 */
842static arc_buf_hdr_t *
843buf_hash_insert(arc_buf_hdr_t *buf, kmutex_t **lockp)
844{
845 uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
846 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
847 arc_buf_hdr_t *fbuf;
848 uint32_t i;
849
9b67f605
MA
850 ASSERT(!DVA_IS_EMPTY(&buf->b_dva));
851 ASSERT(buf->b_birth != 0);
34dc7c2f
BB
852 ASSERT(!HDR_IN_HASH_TABLE(buf));
853 *lockp = hash_lock;
854 mutex_enter(hash_lock);
855 for (fbuf = buf_hash_table.ht_table[idx], i = 0; fbuf != NULL;
856 fbuf = fbuf->b_hash_next, i++) {
857 if (BUF_EQUAL(buf->b_spa, &buf->b_dva, buf->b_birth, fbuf))
858 return (fbuf);
859 }
860
861 buf->b_hash_next = buf_hash_table.ht_table[idx];
862 buf_hash_table.ht_table[idx] = buf;
863 buf->b_flags |= ARC_IN_HASH_TABLE;
864
865 /* collect some hash table performance data */
866 if (i > 0) {
867 ARCSTAT_BUMP(arcstat_hash_collisions);
868 if (i == 1)
869 ARCSTAT_BUMP(arcstat_hash_chains);
870
871 ARCSTAT_MAX(arcstat_hash_chain_max, i);
872 }
873
874 ARCSTAT_BUMP(arcstat_hash_elements);
875 ARCSTAT_MAXSTAT(arcstat_hash_elements);
876
877 return (NULL);
878}
879
880static void
881buf_hash_remove(arc_buf_hdr_t *buf)
882{
883 arc_buf_hdr_t *fbuf, **bufp;
884 uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
885
886 ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
887 ASSERT(HDR_IN_HASH_TABLE(buf));
888
889 bufp = &buf_hash_table.ht_table[idx];
890 while ((fbuf = *bufp) != buf) {
891 ASSERT(fbuf != NULL);
892 bufp = &fbuf->b_hash_next;
893 }
894 *bufp = buf->b_hash_next;
895 buf->b_hash_next = NULL;
896 buf->b_flags &= ~ARC_IN_HASH_TABLE;
897
898 /* collect some hash table performance data */
899 ARCSTAT_BUMPDOWN(arcstat_hash_elements);
900
901 if (buf_hash_table.ht_table[idx] &&
902 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
903 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
904}
905
906/*
907 * Global data structures and functions for the buf kmem cache.
908 */
909static kmem_cache_t *hdr_cache;
910static kmem_cache_t *buf_cache;
ecf3d9b8 911static kmem_cache_t *l2arc_hdr_cache;
34dc7c2f
BB
912
913static void
914buf_fini(void)
915{
916 int i;
917
00b46022 918#if defined(_KERNEL) && defined(HAVE_SPL)
d1d7e268
MK
919 /*
920 * Large allocations which do not require contiguous pages
921 * should be using vmem_free() in the linux kernel\
922 */
00b46022
BB
923 vmem_free(buf_hash_table.ht_table,
924 (buf_hash_table.ht_mask + 1) * sizeof (void *));
925#else
34dc7c2f
BB
926 kmem_free(buf_hash_table.ht_table,
927 (buf_hash_table.ht_mask + 1) * sizeof (void *));
00b46022 928#endif
34dc7c2f
BB
929 for (i = 0; i < BUF_LOCKS; i++)
930 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
931 kmem_cache_destroy(hdr_cache);
932 kmem_cache_destroy(buf_cache);
ecf3d9b8 933 kmem_cache_destroy(l2arc_hdr_cache);
34dc7c2f
BB
934}
935
936/*
937 * Constructor callback - called when the cache is empty
938 * and a new buf is requested.
939 */
940/* ARGSUSED */
941static int
942hdr_cons(void *vbuf, void *unused, int kmflag)
943{
944 arc_buf_hdr_t *buf = vbuf;
945
946 bzero(buf, sizeof (arc_buf_hdr_t));
947 refcount_create(&buf->b_refcnt);
948 cv_init(&buf->b_cv, NULL, CV_DEFAULT, NULL);
949 mutex_init(&buf->b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
98f72a53
BB
950 list_link_init(&buf->b_arc_node);
951 list_link_init(&buf->b_l2node);
d164b209 952 arc_space_consume(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
34dc7c2f 953
34dc7c2f
BB
954 return (0);
955}
956
b128c09f
BB
957/* ARGSUSED */
958static int
959buf_cons(void *vbuf, void *unused, int kmflag)
960{
961 arc_buf_t *buf = vbuf;
962
963 bzero(buf, sizeof (arc_buf_t));
428870ff 964 mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
d164b209
BB
965 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
966
b128c09f
BB
967 return (0);
968}
969
34dc7c2f
BB
970/*
971 * Destructor callback - called when a cached buf is
972 * no longer required.
973 */
974/* ARGSUSED */
975static void
976hdr_dest(void *vbuf, void *unused)
977{
978 arc_buf_hdr_t *buf = vbuf;
979
428870ff 980 ASSERT(BUF_EMPTY(buf));
34dc7c2f
BB
981 refcount_destroy(&buf->b_refcnt);
982 cv_destroy(&buf->b_cv);
983 mutex_destroy(&buf->b_freeze_lock);
d164b209 984 arc_space_return(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
34dc7c2f
BB
985}
986
b128c09f
BB
987/* ARGSUSED */
988static void
989buf_dest(void *vbuf, void *unused)
990{
991 arc_buf_t *buf = vbuf;
992
428870ff 993 mutex_destroy(&buf->b_evict_lock);
d164b209 994 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
b128c09f
BB
995}
996
34dc7c2f
BB
997static void
998buf_init(void)
999{
1000 uint64_t *ct;
1001 uint64_t hsize = 1ULL << 12;
1002 int i, j;
1003
1004 /*
1005 * The hash table is big enough to fill all of physical memory
1006 * with an average 64K block size. The table will take up
1007 * totalmem*sizeof(void*)/64K (eg. 128KB/GB with 8-byte pointers).
1008 */
1009 while (hsize * 65536 < physmem * PAGESIZE)
1010 hsize <<= 1;
1011retry:
1012 buf_hash_table.ht_mask = hsize - 1;
00b46022 1013#if defined(_KERNEL) && defined(HAVE_SPL)
d1d7e268
MK
1014 /*
1015 * Large allocations which do not require contiguous pages
1016 * should be using vmem_alloc() in the linux kernel
1017 */
00b46022
BB
1018 buf_hash_table.ht_table =
1019 vmem_zalloc(hsize * sizeof (void*), KM_SLEEP);
1020#else
34dc7c2f
BB
1021 buf_hash_table.ht_table =
1022 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
00b46022 1023#endif
34dc7c2f
BB
1024 if (buf_hash_table.ht_table == NULL) {
1025 ASSERT(hsize > (1ULL << 8));
1026 hsize >>= 1;
1027 goto retry;
1028 }
1029
1030 hdr_cache = kmem_cache_create("arc_buf_hdr_t", sizeof (arc_buf_hdr_t),
302f753f 1031 0, hdr_cons, hdr_dest, NULL, NULL, NULL, 0);
34dc7c2f 1032 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
b128c09f 1033 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
ecf3d9b8
JL
1034 l2arc_hdr_cache = kmem_cache_create("l2arc_buf_hdr_t", L2HDR_SIZE,
1035 0, NULL, NULL, NULL, NULL, NULL, 0);
34dc7c2f
BB
1036
1037 for (i = 0; i < 256; i++)
1038 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1039 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1040
1041 for (i = 0; i < BUF_LOCKS; i++) {
1042 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1043 NULL, MUTEX_DEFAULT, NULL);
1044 }
1045}
1046
1047#define ARC_MINTIME (hz>>4) /* 62 ms */
1048
1049static void
1050arc_cksum_verify(arc_buf_t *buf)
1051{
1052 zio_cksum_t zc;
1053
1054 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1055 return;
1056
1057 mutex_enter(&buf->b_hdr->b_freeze_lock);
1058 if (buf->b_hdr->b_freeze_cksum == NULL ||
1059 (buf->b_hdr->b_flags & ARC_IO_ERROR)) {
1060 mutex_exit(&buf->b_hdr->b_freeze_lock);
1061 return;
1062 }
1063 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1064 if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
1065 panic("buffer modified while frozen!");
1066 mutex_exit(&buf->b_hdr->b_freeze_lock);
1067}
1068
1069static int
1070arc_cksum_equal(arc_buf_t *buf)
1071{
1072 zio_cksum_t zc;
1073 int equal;
1074
1075 mutex_enter(&buf->b_hdr->b_freeze_lock);
1076 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1077 equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
1078 mutex_exit(&buf->b_hdr->b_freeze_lock);
1079
1080 return (equal);
1081}
1082
1083static void
1084arc_cksum_compute(arc_buf_t *buf, boolean_t force)
1085{
1086 if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
1087 return;
1088
1089 mutex_enter(&buf->b_hdr->b_freeze_lock);
1090 if (buf->b_hdr->b_freeze_cksum != NULL) {
1091 mutex_exit(&buf->b_hdr->b_freeze_lock);
1092 return;
1093 }
409dc1a5 1094 buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t),
d1d7e268 1095 KM_PUSHPAGE);
34dc7c2f
BB
1096 fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
1097 buf->b_hdr->b_freeze_cksum);
1098 mutex_exit(&buf->b_hdr->b_freeze_lock);
498877ba
MA
1099 arc_buf_watch(buf);
1100}
1101
1102#ifndef _KERNEL
1103void
1104arc_buf_sigsegv(int sig, siginfo_t *si, void *unused)
1105{
1106 panic("Got SIGSEGV at address: 0x%lx\n", (long) si->si_addr);
1107}
1108#endif
1109
1110/* ARGSUSED */
1111static void
1112arc_buf_unwatch(arc_buf_t *buf)
1113{
1114#ifndef _KERNEL
1115 if (arc_watch) {
1116 ASSERT0(mprotect(buf->b_data, buf->b_hdr->b_size,
1117 PROT_READ | PROT_WRITE));
1118 }
1119#endif
1120}
1121
1122/* ARGSUSED */
1123static void
1124arc_buf_watch(arc_buf_t *buf)
1125{
1126#ifndef _KERNEL
1127 if (arc_watch)
1128 ASSERT0(mprotect(buf->b_data, buf->b_hdr->b_size, PROT_READ));
1129#endif
34dc7c2f
BB
1130}
1131
1132void
1133arc_buf_thaw(arc_buf_t *buf)
1134{
1135 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1136 if (buf->b_hdr->b_state != arc_anon)
1137 panic("modifying non-anon buffer!");
1138 if (buf->b_hdr->b_flags & ARC_IO_IN_PROGRESS)
1139 panic("modifying buffer while i/o in progress!");
1140 arc_cksum_verify(buf);
1141 }
1142
1143 mutex_enter(&buf->b_hdr->b_freeze_lock);
1144 if (buf->b_hdr->b_freeze_cksum != NULL) {
1145 kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1146 buf->b_hdr->b_freeze_cksum = NULL;
1147 }
428870ff 1148
34dc7c2f 1149 mutex_exit(&buf->b_hdr->b_freeze_lock);
498877ba
MA
1150
1151 arc_buf_unwatch(buf);
34dc7c2f
BB
1152}
1153
1154void
1155arc_buf_freeze(arc_buf_t *buf)
1156{
428870ff
BB
1157 kmutex_t *hash_lock;
1158
34dc7c2f
BB
1159 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1160 return;
1161
428870ff
BB
1162 hash_lock = HDR_LOCK(buf->b_hdr);
1163 mutex_enter(hash_lock);
1164
34dc7c2f
BB
1165 ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
1166 buf->b_hdr->b_state == arc_anon);
1167 arc_cksum_compute(buf, B_FALSE);
428870ff 1168 mutex_exit(hash_lock);
498877ba 1169
34dc7c2f
BB
1170}
1171
1172static void
1173add_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
1174{
1175 ASSERT(MUTEX_HELD(hash_lock));
1176
1177 if ((refcount_add(&ab->b_refcnt, tag) == 1) &&
1178 (ab->b_state != arc_anon)) {
1179 uint64_t delta = ab->b_size * ab->b_datacnt;
1180 list_t *list = &ab->b_state->arcs_list[ab->b_type];
1181 uint64_t *size = &ab->b_state->arcs_lsize[ab->b_type];
1182
1183 ASSERT(!MUTEX_HELD(&ab->b_state->arcs_mtx));
1184 mutex_enter(&ab->b_state->arcs_mtx);
1185 ASSERT(list_link_active(&ab->b_arc_node));
1186 list_remove(list, ab);
1187 if (GHOST_STATE(ab->b_state)) {
c99c9001 1188 ASSERT0(ab->b_datacnt);
34dc7c2f
BB
1189 ASSERT3P(ab->b_buf, ==, NULL);
1190 delta = ab->b_size;
1191 }
1192 ASSERT(delta > 0);
1193 ASSERT3U(*size, >=, delta);
1194 atomic_add_64(size, -delta);
1195 mutex_exit(&ab->b_state->arcs_mtx);
b128c09f 1196 /* remove the prefetch flag if we get a reference */
34dc7c2f
BB
1197 if (ab->b_flags & ARC_PREFETCH)
1198 ab->b_flags &= ~ARC_PREFETCH;
1199 }
1200}
1201
1202static int
1203remove_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
1204{
1205 int cnt;
1206 arc_state_t *state = ab->b_state;
1207
1208 ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
1209 ASSERT(!GHOST_STATE(state));
1210
1211 if (((cnt = refcount_remove(&ab->b_refcnt, tag)) == 0) &&
1212 (state != arc_anon)) {
1213 uint64_t *size = &state->arcs_lsize[ab->b_type];
1214
1215 ASSERT(!MUTEX_HELD(&state->arcs_mtx));
1216 mutex_enter(&state->arcs_mtx);
1217 ASSERT(!list_link_active(&ab->b_arc_node));
1218 list_insert_head(&state->arcs_list[ab->b_type], ab);
1219 ASSERT(ab->b_datacnt > 0);
1220 atomic_add_64(size, ab->b_size * ab->b_datacnt);
1221 mutex_exit(&state->arcs_mtx);
1222 }
1223 return (cnt);
1224}
1225
e0b0ca98
BB
1226/*
1227 * Returns detailed information about a specific arc buffer. When the
1228 * state_index argument is set the function will calculate the arc header
1229 * list position for its arc state. Since this requires a linear traversal
1230 * callers are strongly encourage not to do this. However, it can be helpful
1231 * for targeted analysis so the functionality is provided.
1232 */
1233void
1234arc_buf_info(arc_buf_t *ab, arc_buf_info_t *abi, int state_index)
1235{
1236 arc_buf_hdr_t *hdr = ab->b_hdr;
1237 arc_state_t *state = hdr->b_state;
1238
d1d7e268 1239 memset(abi, 0, sizeof (arc_buf_info_t));
e0b0ca98
BB
1240 abi->abi_flags = hdr->b_flags;
1241 abi->abi_datacnt = hdr->b_datacnt;
1242 abi->abi_state_type = state ? state->arcs_state : ARC_STATE_ANON;
1243 abi->abi_state_contents = hdr->b_type;
1244 abi->abi_state_index = -1;
1245 abi->abi_size = hdr->b_size;
1246 abi->abi_access = hdr->b_arc_access;
1247 abi->abi_mru_hits = hdr->b_mru_hits;
1248 abi->abi_mru_ghost_hits = hdr->b_mru_ghost_hits;
1249 abi->abi_mfu_hits = hdr->b_mfu_hits;
1250 abi->abi_mfu_ghost_hits = hdr->b_mfu_ghost_hits;
1251 abi->abi_holds = refcount_count(&hdr->b_refcnt);
1252
1253 if (hdr->b_l2hdr) {
1254 abi->abi_l2arc_dattr = hdr->b_l2hdr->b_daddr;
1255 abi->abi_l2arc_asize = hdr->b_l2hdr->b_asize;
1256 abi->abi_l2arc_compress = hdr->b_l2hdr->b_compress;
1257 abi->abi_l2arc_hits = hdr->b_l2hdr->b_hits;
1258 }
1259
1260 if (state && state_index && list_link_active(&hdr->b_arc_node)) {
1261 list_t *list = &state->arcs_list[hdr->b_type];
1262 arc_buf_hdr_t *h;
1263
1264 mutex_enter(&state->arcs_mtx);
1265 for (h = list_head(list); h != NULL; h = list_next(list, h)) {
1266 abi->abi_state_index++;
1267 if (h == hdr)
1268 break;
1269 }
1270 mutex_exit(&state->arcs_mtx);
1271 }
1272}
1273
34dc7c2f
BB
1274/*
1275 * Move the supplied buffer to the indicated state. The mutex
1276 * for the buffer must be held by the caller.
1277 */
1278static void
1279arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *ab, kmutex_t *hash_lock)
1280{
1281 arc_state_t *old_state = ab->b_state;
1282 int64_t refcnt = refcount_count(&ab->b_refcnt);
1283 uint64_t from_delta, to_delta;
1284
1285 ASSERT(MUTEX_HELD(hash_lock));
e8b96c60 1286 ASSERT3P(new_state, !=, old_state);
34dc7c2f
BB
1287 ASSERT(refcnt == 0 || ab->b_datacnt > 0);
1288 ASSERT(ab->b_datacnt == 0 || !GHOST_STATE(new_state));
428870ff 1289 ASSERT(ab->b_datacnt <= 1 || old_state != arc_anon);
34dc7c2f
BB
1290
1291 from_delta = to_delta = ab->b_datacnt * ab->b_size;
1292
1293 /*
1294 * If this buffer is evictable, transfer it from the
1295 * old state list to the new state list.
1296 */
1297 if (refcnt == 0) {
1298 if (old_state != arc_anon) {
1299 int use_mutex = !MUTEX_HELD(&old_state->arcs_mtx);
1300 uint64_t *size = &old_state->arcs_lsize[ab->b_type];
1301
1302 if (use_mutex)
1303 mutex_enter(&old_state->arcs_mtx);
1304
1305 ASSERT(list_link_active(&ab->b_arc_node));
1306 list_remove(&old_state->arcs_list[ab->b_type], ab);
1307
1308 /*
1309 * If prefetching out of the ghost cache,
428870ff 1310 * we will have a non-zero datacnt.
34dc7c2f
BB
1311 */
1312 if (GHOST_STATE(old_state) && ab->b_datacnt == 0) {
1313 /* ghost elements have a ghost size */
1314 ASSERT(ab->b_buf == NULL);
1315 from_delta = ab->b_size;
1316 }
1317 ASSERT3U(*size, >=, from_delta);
1318 atomic_add_64(size, -from_delta);
1319
1320 if (use_mutex)
1321 mutex_exit(&old_state->arcs_mtx);
1322 }
1323 if (new_state != arc_anon) {
1324 int use_mutex = !MUTEX_HELD(&new_state->arcs_mtx);
1325 uint64_t *size = &new_state->arcs_lsize[ab->b_type];
1326
1327 if (use_mutex)
1328 mutex_enter(&new_state->arcs_mtx);
1329
1330 list_insert_head(&new_state->arcs_list[ab->b_type], ab);
1331
1332 /* ghost elements have a ghost size */
1333 if (GHOST_STATE(new_state)) {
1334 ASSERT(ab->b_datacnt == 0);
1335 ASSERT(ab->b_buf == NULL);
1336 to_delta = ab->b_size;
1337 }
1338 atomic_add_64(size, to_delta);
1339
1340 if (use_mutex)
1341 mutex_exit(&new_state->arcs_mtx);
1342 }
1343 }
1344
1345 ASSERT(!BUF_EMPTY(ab));
428870ff 1346 if (new_state == arc_anon && HDR_IN_HASH_TABLE(ab))
34dc7c2f 1347 buf_hash_remove(ab);
34dc7c2f
BB
1348
1349 /* adjust state sizes */
1350 if (to_delta)
1351 atomic_add_64(&new_state->arcs_size, to_delta);
1352 if (from_delta) {
1353 ASSERT3U(old_state->arcs_size, >=, from_delta);
1354 atomic_add_64(&old_state->arcs_size, -from_delta);
1355 }
1356 ab->b_state = new_state;
1357
1358 /* adjust l2arc hdr stats */
1359 if (new_state == arc_l2c_only)
1360 l2arc_hdr_stat_add();
1361 else if (old_state == arc_l2c_only)
1362 l2arc_hdr_stat_remove();
1363}
1364
1365void
d164b209 1366arc_space_consume(uint64_t space, arc_space_type_t type)
34dc7c2f 1367{
d164b209
BB
1368 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1369
1370 switch (type) {
e75c13c3
BB
1371 default:
1372 break;
d164b209
BB
1373 case ARC_SPACE_DATA:
1374 ARCSTAT_INCR(arcstat_data_size, space);
1375 break;
cc7f677c
PS
1376 case ARC_SPACE_META:
1377 ARCSTAT_INCR(arcstat_meta_size, space);
1378 break;
d164b209
BB
1379 case ARC_SPACE_OTHER:
1380 ARCSTAT_INCR(arcstat_other_size, space);
1381 break;
1382 case ARC_SPACE_HDRS:
1383 ARCSTAT_INCR(arcstat_hdr_size, space);
1384 break;
1385 case ARC_SPACE_L2HDRS:
1386 ARCSTAT_INCR(arcstat_l2_hdr_size, space);
1387 break;
1388 }
1389
cc7f677c
PS
1390 if (type != ARC_SPACE_DATA)
1391 ARCSTAT_INCR(arcstat_meta_used, space);
1392
34dc7c2f
BB
1393 atomic_add_64(&arc_size, space);
1394}
1395
1396void
d164b209 1397arc_space_return(uint64_t space, arc_space_type_t type)
34dc7c2f 1398{
d164b209
BB
1399 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1400
1401 switch (type) {
e75c13c3
BB
1402 default:
1403 break;
d164b209
BB
1404 case ARC_SPACE_DATA:
1405 ARCSTAT_INCR(arcstat_data_size, -space);
1406 break;
cc7f677c
PS
1407 case ARC_SPACE_META:
1408 ARCSTAT_INCR(arcstat_meta_size, -space);
1409 break;
d164b209
BB
1410 case ARC_SPACE_OTHER:
1411 ARCSTAT_INCR(arcstat_other_size, -space);
1412 break;
1413 case ARC_SPACE_HDRS:
1414 ARCSTAT_INCR(arcstat_hdr_size, -space);
1415 break;
1416 case ARC_SPACE_L2HDRS:
1417 ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
1418 break;
1419 }
1420
cc7f677c
PS
1421 if (type != ARC_SPACE_DATA) {
1422 ASSERT(arc_meta_used >= space);
1423 if (arc_meta_max < arc_meta_used)
1424 arc_meta_max = arc_meta_used;
1425 ARCSTAT_INCR(arcstat_meta_used, -space);
1426 }
1427
34dc7c2f
BB
1428 ASSERT(arc_size >= space);
1429 atomic_add_64(&arc_size, -space);
1430}
1431
34dc7c2f
BB
1432arc_buf_t *
1433arc_buf_alloc(spa_t *spa, int size, void *tag, arc_buf_contents_t type)
1434{
1435 arc_buf_hdr_t *hdr;
1436 arc_buf_t *buf;
1437
1438 ASSERT3U(size, >, 0);
1439 hdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
1440 ASSERT(BUF_EMPTY(hdr));
1441 hdr->b_size = size;
1442 hdr->b_type = type;
3541dc6d 1443 hdr->b_spa = spa_load_guid(spa);
34dc7c2f
BB
1444 hdr->b_state = arc_anon;
1445 hdr->b_arc_access = 0;
e0b0ca98
BB
1446 hdr->b_mru_hits = 0;
1447 hdr->b_mru_ghost_hits = 0;
1448 hdr->b_mfu_hits = 0;
1449 hdr->b_mfu_ghost_hits = 0;
1450 hdr->b_l2_hits = 0;
34dc7c2f
BB
1451 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1452 buf->b_hdr = hdr;
1453 buf->b_data = NULL;
1454 buf->b_efunc = NULL;
1455 buf->b_private = NULL;
1456 buf->b_next = NULL;
1457 hdr->b_buf = buf;
1458 arc_get_data_buf(buf);
1459 hdr->b_datacnt = 1;
1460 hdr->b_flags = 0;
1461 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1462 (void) refcount_add(&hdr->b_refcnt, tag);
1463
1464 return (buf);
1465}
1466
9babb374
BB
1467static char *arc_onloan_tag = "onloan";
1468
1469/*
1470 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
1471 * flight data by arc_tempreserve_space() until they are "returned". Loaned
1472 * buffers must be returned to the arc before they can be used by the DMU or
1473 * freed.
1474 */
1475arc_buf_t *
1476arc_loan_buf(spa_t *spa, int size)
1477{
1478 arc_buf_t *buf;
1479
1480 buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
1481
1482 atomic_add_64(&arc_loaned_bytes, size);
1483 return (buf);
1484}
1485
1486/*
1487 * Return a loaned arc buffer to the arc.
1488 */
1489void
1490arc_return_buf(arc_buf_t *buf, void *tag)
1491{
1492 arc_buf_hdr_t *hdr = buf->b_hdr;
1493
9babb374 1494 ASSERT(buf->b_data != NULL);
428870ff
BB
1495 (void) refcount_add(&hdr->b_refcnt, tag);
1496 (void) refcount_remove(&hdr->b_refcnt, arc_onloan_tag);
9babb374
BB
1497
1498 atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
1499}
1500
428870ff
BB
1501/* Detach an arc_buf from a dbuf (tag) */
1502void
1503arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
1504{
1505 arc_buf_hdr_t *hdr;
1506
1507 ASSERT(buf->b_data != NULL);
1508 hdr = buf->b_hdr;
1509 (void) refcount_add(&hdr->b_refcnt, arc_onloan_tag);
1510 (void) refcount_remove(&hdr->b_refcnt, tag);
1511 buf->b_efunc = NULL;
1512 buf->b_private = NULL;
1513
1514 atomic_add_64(&arc_loaned_bytes, hdr->b_size);
1515}
1516
34dc7c2f
BB
1517static arc_buf_t *
1518arc_buf_clone(arc_buf_t *from)
1519{
1520 arc_buf_t *buf;
1521 arc_buf_hdr_t *hdr = from->b_hdr;
1522 uint64_t size = hdr->b_size;
1523
428870ff
BB
1524 ASSERT(hdr->b_state != arc_anon);
1525
34dc7c2f
BB
1526 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1527 buf->b_hdr = hdr;
1528 buf->b_data = NULL;
1529 buf->b_efunc = NULL;
1530 buf->b_private = NULL;
1531 buf->b_next = hdr->b_buf;
1532 hdr->b_buf = buf;
1533 arc_get_data_buf(buf);
1534 bcopy(from->b_data, buf->b_data, size);
1eb5bfa3
GW
1535
1536 /*
1537 * This buffer already exists in the arc so create a duplicate
1538 * copy for the caller. If the buffer is associated with user data
1539 * then track the size and number of duplicates. These stats will be
1540 * updated as duplicate buffers are created and destroyed.
1541 */
1542 if (hdr->b_type == ARC_BUFC_DATA) {
1543 ARCSTAT_BUMP(arcstat_duplicate_buffers);
1544 ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
1545 }
34dc7c2f
BB
1546 hdr->b_datacnt += 1;
1547 return (buf);
1548}
1549
1550void
1551arc_buf_add_ref(arc_buf_t *buf, void* tag)
1552{
1553 arc_buf_hdr_t *hdr;
1554 kmutex_t *hash_lock;
1555
1556 /*
b128c09f
BB
1557 * Check to see if this buffer is evicted. Callers
1558 * must verify b_data != NULL to know if the add_ref
1559 * was successful.
34dc7c2f 1560 */
428870ff 1561 mutex_enter(&buf->b_evict_lock);
b128c09f 1562 if (buf->b_data == NULL) {
428870ff 1563 mutex_exit(&buf->b_evict_lock);
34dc7c2f
BB
1564 return;
1565 }
428870ff 1566 hash_lock = HDR_LOCK(buf->b_hdr);
34dc7c2f 1567 mutex_enter(hash_lock);
428870ff
BB
1568 hdr = buf->b_hdr;
1569 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1570 mutex_exit(&buf->b_evict_lock);
34dc7c2f 1571
34dc7c2f
BB
1572 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
1573 add_reference(hdr, hash_lock, tag);
d164b209 1574 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
34dc7c2f
BB
1575 arc_access(hdr, hash_lock);
1576 mutex_exit(hash_lock);
1577 ARCSTAT_BUMP(arcstat_hits);
1578 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
1579 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
1580 data, metadata, hits);
1581}
1582
1583/*
1584 * Free the arc data buffer. If it is an l2arc write in progress,
1585 * the buffer is placed on l2arc_free_on_write to be freed later.
1586 */
1587static void
498877ba 1588arc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
34dc7c2f 1589{
498877ba
MA
1590 arc_buf_hdr_t *hdr = buf->b_hdr;
1591
34dc7c2f
BB
1592 if (HDR_L2_WRITING(hdr)) {
1593 l2arc_data_free_t *df;
594b4dd8 1594 df = kmem_alloc(sizeof (l2arc_data_free_t), KM_PUSHPAGE);
498877ba
MA
1595 df->l2df_data = buf->b_data;
1596 df->l2df_size = hdr->b_size;
34dc7c2f
BB
1597 df->l2df_func = free_func;
1598 mutex_enter(&l2arc_free_on_write_mtx);
1599 list_insert_head(l2arc_free_on_write, df);
1600 mutex_exit(&l2arc_free_on_write_mtx);
1601 ARCSTAT_BUMP(arcstat_l2_free_on_write);
1602 } else {
498877ba 1603 free_func(buf->b_data, hdr->b_size);
34dc7c2f
BB
1604 }
1605}
1606
1607static void
1608arc_buf_destroy(arc_buf_t *buf, boolean_t recycle, boolean_t all)
1609{
1610 arc_buf_t **bufp;
1611
1612 /* free up data associated with the buf */
1613 if (buf->b_data) {
1614 arc_state_t *state = buf->b_hdr->b_state;
1615 uint64_t size = buf->b_hdr->b_size;
1616 arc_buf_contents_t type = buf->b_hdr->b_type;
1617
1618 arc_cksum_verify(buf);
498877ba 1619 arc_buf_unwatch(buf);
428870ff 1620
34dc7c2f
BB
1621 if (!recycle) {
1622 if (type == ARC_BUFC_METADATA) {
498877ba 1623 arc_buf_data_free(buf, zio_buf_free);
cc7f677c 1624 arc_space_return(size, ARC_SPACE_META);
34dc7c2f
BB
1625 } else {
1626 ASSERT(type == ARC_BUFC_DATA);
498877ba 1627 arc_buf_data_free(buf, zio_data_buf_free);
cc7f677c 1628 arc_space_return(size, ARC_SPACE_DATA);
34dc7c2f
BB
1629 }
1630 }
1631 if (list_link_active(&buf->b_hdr->b_arc_node)) {
1632 uint64_t *cnt = &state->arcs_lsize[type];
1633
1634 ASSERT(refcount_is_zero(&buf->b_hdr->b_refcnt));
1635 ASSERT(state != arc_anon);
1636
1637 ASSERT3U(*cnt, >=, size);
1638 atomic_add_64(cnt, -size);
1639 }
1640 ASSERT3U(state->arcs_size, >=, size);
1641 atomic_add_64(&state->arcs_size, -size);
1642 buf->b_data = NULL;
1eb5bfa3
GW
1643
1644 /*
1645 * If we're destroying a duplicate buffer make sure
1646 * that the appropriate statistics are updated.
1647 */
1648 if (buf->b_hdr->b_datacnt > 1 &&
1649 buf->b_hdr->b_type == ARC_BUFC_DATA) {
1650 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
1651 ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
1652 }
34dc7c2f
BB
1653 ASSERT(buf->b_hdr->b_datacnt > 0);
1654 buf->b_hdr->b_datacnt -= 1;
1655 }
1656
1657 /* only remove the buf if requested */
1658 if (!all)
1659 return;
1660
1661 /* remove the buf from the hdr list */
1662 for (bufp = &buf->b_hdr->b_buf; *bufp != buf; bufp = &(*bufp)->b_next)
1663 continue;
1664 *bufp = buf->b_next;
428870ff 1665 buf->b_next = NULL;
34dc7c2f
BB
1666
1667 ASSERT(buf->b_efunc == NULL);
1668
1669 /* clean up the buf */
1670 buf->b_hdr = NULL;
1671 kmem_cache_free(buf_cache, buf);
1672}
1673
1674static void
1675arc_hdr_destroy(arc_buf_hdr_t *hdr)
1676{
d6320ddb
BB
1677 l2arc_buf_hdr_t *l2hdr = hdr->b_l2hdr;
1678
34dc7c2f
BB
1679 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1680 ASSERT3P(hdr->b_state, ==, arc_anon);
1681 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1682
428870ff
BB
1683 if (l2hdr != NULL) {
1684 boolean_t buflist_held = MUTEX_HELD(&l2arc_buflist_mtx);
1685 /*
1686 * To prevent arc_free() and l2arc_evict() from
1687 * attempting to free the same buffer at the same time,
1688 * a FREE_IN_PROGRESS flag is given to arc_free() to
1689 * give it priority. l2arc_evict() can't destroy this
1690 * header while we are waiting on l2arc_buflist_mtx.
1691 *
1692 * The hdr may be removed from l2ad_buflist before we
1693 * grab l2arc_buflist_mtx, so b_l2hdr is rechecked.
1694 */
1695 if (!buflist_held) {
34dc7c2f 1696 mutex_enter(&l2arc_buflist_mtx);
428870ff 1697 l2hdr = hdr->b_l2hdr;
34dc7c2f 1698 }
428870ff
BB
1699
1700 if (l2hdr != NULL) {
1701 list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
1702 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
3a17a7a9 1703 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
ecf3d9b8 1704 kmem_cache_free(l2arc_hdr_cache, l2hdr);
6e1d7276 1705 arc_space_return(L2HDR_SIZE, ARC_SPACE_L2HDRS);
428870ff
BB
1706 if (hdr->b_state == arc_l2c_only)
1707 l2arc_hdr_stat_remove();
1708 hdr->b_l2hdr = NULL;
1709 }
1710
1711 if (!buflist_held)
1712 mutex_exit(&l2arc_buflist_mtx);
34dc7c2f
BB
1713 }
1714
1715 if (!BUF_EMPTY(hdr)) {
1716 ASSERT(!HDR_IN_HASH_TABLE(hdr));
428870ff 1717 buf_discard_identity(hdr);
34dc7c2f
BB
1718 }
1719 while (hdr->b_buf) {
1720 arc_buf_t *buf = hdr->b_buf;
1721
1722 if (buf->b_efunc) {
1723 mutex_enter(&arc_eviction_mtx);
428870ff 1724 mutex_enter(&buf->b_evict_lock);
34dc7c2f
BB
1725 ASSERT(buf->b_hdr != NULL);
1726 arc_buf_destroy(hdr->b_buf, FALSE, FALSE);
1727 hdr->b_buf = buf->b_next;
1728 buf->b_hdr = &arc_eviction_hdr;
1729 buf->b_next = arc_eviction_list;
1730 arc_eviction_list = buf;
428870ff 1731 mutex_exit(&buf->b_evict_lock);
34dc7c2f
BB
1732 mutex_exit(&arc_eviction_mtx);
1733 } else {
1734 arc_buf_destroy(hdr->b_buf, FALSE, TRUE);
1735 }
1736 }
1737 if (hdr->b_freeze_cksum != NULL) {
1738 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1739 hdr->b_freeze_cksum = NULL;
1740 }
1741
1742 ASSERT(!list_link_active(&hdr->b_arc_node));
1743 ASSERT3P(hdr->b_hash_next, ==, NULL);
1744 ASSERT3P(hdr->b_acb, ==, NULL);
1745 kmem_cache_free(hdr_cache, hdr);
1746}
1747
1748void
1749arc_buf_free(arc_buf_t *buf, void *tag)
1750{
1751 arc_buf_hdr_t *hdr = buf->b_hdr;
1752 int hashed = hdr->b_state != arc_anon;
1753
1754 ASSERT(buf->b_efunc == NULL);
1755 ASSERT(buf->b_data != NULL);
1756
1757 if (hashed) {
1758 kmutex_t *hash_lock = HDR_LOCK(hdr);
1759
1760 mutex_enter(hash_lock);
428870ff
BB
1761 hdr = buf->b_hdr;
1762 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1763
34dc7c2f 1764 (void) remove_reference(hdr, hash_lock, tag);
428870ff 1765 if (hdr->b_datacnt > 1) {
34dc7c2f 1766 arc_buf_destroy(buf, FALSE, TRUE);
428870ff
BB
1767 } else {
1768 ASSERT(buf == hdr->b_buf);
1769 ASSERT(buf->b_efunc == NULL);
34dc7c2f 1770 hdr->b_flags |= ARC_BUF_AVAILABLE;
428870ff 1771 }
34dc7c2f
BB
1772 mutex_exit(hash_lock);
1773 } else if (HDR_IO_IN_PROGRESS(hdr)) {
1774 int destroy_hdr;
1775 /*
1776 * We are in the middle of an async write. Don't destroy
1777 * this buffer unless the write completes before we finish
1778 * decrementing the reference count.
1779 */
1780 mutex_enter(&arc_eviction_mtx);
1781 (void) remove_reference(hdr, NULL, tag);
1782 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1783 destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
1784 mutex_exit(&arc_eviction_mtx);
1785 if (destroy_hdr)
1786 arc_hdr_destroy(hdr);
1787 } else {
428870ff 1788 if (remove_reference(hdr, NULL, tag) > 0)
34dc7c2f 1789 arc_buf_destroy(buf, FALSE, TRUE);
428870ff 1790 else
34dc7c2f 1791 arc_hdr_destroy(hdr);
34dc7c2f
BB
1792 }
1793}
1794
13fe0198 1795boolean_t
34dc7c2f
BB
1796arc_buf_remove_ref(arc_buf_t *buf, void* tag)
1797{
1798 arc_buf_hdr_t *hdr = buf->b_hdr;
b4f7f105 1799 kmutex_t *hash_lock = NULL;
13fe0198 1800 boolean_t no_callback = (buf->b_efunc == NULL);
34dc7c2f
BB
1801
1802 if (hdr->b_state == arc_anon) {
428870ff 1803 ASSERT(hdr->b_datacnt == 1);
34dc7c2f
BB
1804 arc_buf_free(buf, tag);
1805 return (no_callback);
1806 }
1807
b4f7f105 1808 hash_lock = HDR_LOCK(hdr);
34dc7c2f 1809 mutex_enter(hash_lock);
428870ff
BB
1810 hdr = buf->b_hdr;
1811 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
34dc7c2f
BB
1812 ASSERT(hdr->b_state != arc_anon);
1813 ASSERT(buf->b_data != NULL);
1814
1815 (void) remove_reference(hdr, hash_lock, tag);
1816 if (hdr->b_datacnt > 1) {
1817 if (no_callback)
1818 arc_buf_destroy(buf, FALSE, TRUE);
1819 } else if (no_callback) {
1820 ASSERT(hdr->b_buf == buf && buf->b_next == NULL);
428870ff 1821 ASSERT(buf->b_efunc == NULL);
34dc7c2f
BB
1822 hdr->b_flags |= ARC_BUF_AVAILABLE;
1823 }
1824 ASSERT(no_callback || hdr->b_datacnt > 1 ||
1825 refcount_is_zero(&hdr->b_refcnt));
1826 mutex_exit(hash_lock);
1827 return (no_callback);
1828}
1829
1830int
1831arc_buf_size(arc_buf_t *buf)
1832{
1833 return (buf->b_hdr->b_size);
1834}
1835
1eb5bfa3
GW
1836/*
1837 * Called from the DMU to determine if the current buffer should be
1838 * evicted. In order to ensure proper locking, the eviction must be initiated
1839 * from the DMU. Return true if the buffer is associated with user data and
1840 * duplicate buffers still exist.
1841 */
1842boolean_t
1843arc_buf_eviction_needed(arc_buf_t *buf)
1844{
1845 arc_buf_hdr_t *hdr;
1846 boolean_t evict_needed = B_FALSE;
1847
1848 if (zfs_disable_dup_eviction)
1849 return (B_FALSE);
1850
1851 mutex_enter(&buf->b_evict_lock);
1852 hdr = buf->b_hdr;
1853 if (hdr == NULL) {
1854 /*
1855 * We are in arc_do_user_evicts(); let that function
1856 * perform the eviction.
1857 */
1858 ASSERT(buf->b_data == NULL);
1859 mutex_exit(&buf->b_evict_lock);
1860 return (B_FALSE);
1861 } else if (buf->b_data == NULL) {
1862 /*
1863 * We have already been added to the arc eviction list;
1864 * recommend eviction.
1865 */
1866 ASSERT3P(hdr, ==, &arc_eviction_hdr);
1867 mutex_exit(&buf->b_evict_lock);
1868 return (B_TRUE);
1869 }
1870
1871 if (hdr->b_datacnt > 1 && hdr->b_type == ARC_BUFC_DATA)
1872 evict_needed = B_TRUE;
1873
1874 mutex_exit(&buf->b_evict_lock);
1875 return (evict_needed);
1876}
1877
34dc7c2f
BB
1878/*
1879 * Evict buffers from list until we've removed the specified number of
1880 * bytes. Move the removed buffers to the appropriate evict state.
1881 * If the recycle flag is set, then attempt to "recycle" a buffer:
1882 * - look for a buffer to evict that is `bytes' long.
1883 * - return the data block from this buffer rather than freeing it.
1884 * This flag is used by callers that are trying to make space for a
1885 * new buffer in a full arc cache.
1886 *
1887 * This function makes a "best effort". It skips over any buffers
1888 * it can't get a hash_lock on, and so may not catch all candidates.
1889 * It may also return without evicting as much space as requested.
1890 */
1891static void *
d164b209 1892arc_evict(arc_state_t *state, uint64_t spa, int64_t bytes, boolean_t recycle,
34dc7c2f
BB
1893 arc_buf_contents_t type)
1894{
1895 arc_state_t *evicted_state;
1896 uint64_t bytes_evicted = 0, skipped = 0, missed = 0;
1897 arc_buf_hdr_t *ab, *ab_prev = NULL;
1898 list_t *list = &state->arcs_list[type];
1899 kmutex_t *hash_lock;
1900 boolean_t have_lock;
1901 void *stolen = NULL;
e8b96c60
MA
1902 arc_buf_hdr_t marker = {{{ 0 }}};
1903 int count = 0;
34dc7c2f
BB
1904
1905 ASSERT(state == arc_mru || state == arc_mfu);
1906
1907 evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
1908
da8ccd0e 1909top:
34dc7c2f
BB
1910 mutex_enter(&state->arcs_mtx);
1911 mutex_enter(&evicted_state->arcs_mtx);
1912
1913 for (ab = list_tail(list); ab; ab = ab_prev) {
1914 ab_prev = list_prev(list, ab);
1915 /* prefetch buffers have a minimum lifespan */
1916 if (HDR_IO_IN_PROGRESS(ab) ||
1917 (spa && ab->b_spa != spa) ||
1918 (ab->b_flags & (ARC_PREFETCH|ARC_INDIRECT) &&
428870ff 1919 ddi_get_lbolt() - ab->b_arc_access <
bce45ec9 1920 zfs_arc_min_prefetch_lifespan)) {
34dc7c2f
BB
1921 skipped++;
1922 continue;
1923 }
1924 /* "lookahead" for better eviction candidate */
1925 if (recycle && ab->b_size != bytes &&
1926 ab_prev && ab_prev->b_size == bytes)
1927 continue;
e8b96c60
MA
1928
1929 /* ignore markers */
1930 if (ab->b_spa == 0)
1931 continue;
1932
1933 /*
1934 * It may take a long time to evict all the bufs requested.
1935 * To avoid blocking all arc activity, periodically drop
1936 * the arcs_mtx and give other threads a chance to run
1937 * before reacquiring the lock.
1938 *
1939 * If we are looking for a buffer to recycle, we are in
1940 * the hot code path, so don't sleep.
1941 */
1942 if (!recycle && count++ > arc_evict_iterations) {
1943 list_insert_after(list, ab, &marker);
1944 mutex_exit(&evicted_state->arcs_mtx);
1945 mutex_exit(&state->arcs_mtx);
1946 kpreempt(KPREEMPT_SYNC);
1947 mutex_enter(&state->arcs_mtx);
1948 mutex_enter(&evicted_state->arcs_mtx);
1949 ab_prev = list_prev(list, &marker);
1950 list_remove(list, &marker);
1951 count = 0;
1952 continue;
1953 }
1954
34dc7c2f
BB
1955 hash_lock = HDR_LOCK(ab);
1956 have_lock = MUTEX_HELD(hash_lock);
1957 if (have_lock || mutex_tryenter(hash_lock)) {
c99c9001 1958 ASSERT0(refcount_count(&ab->b_refcnt));
34dc7c2f
BB
1959 ASSERT(ab->b_datacnt > 0);
1960 while (ab->b_buf) {
1961 arc_buf_t *buf = ab->b_buf;
428870ff 1962 if (!mutex_tryenter(&buf->b_evict_lock)) {
b128c09f
BB
1963 missed += 1;
1964 break;
1965 }
34dc7c2f
BB
1966 if (buf->b_data) {
1967 bytes_evicted += ab->b_size;
1968 if (recycle && ab->b_type == type &&
1969 ab->b_size == bytes &&
1970 !HDR_L2_WRITING(ab)) {
1971 stolen = buf->b_data;
1972 recycle = FALSE;
1973 }
1974 }
1975 if (buf->b_efunc) {
1976 mutex_enter(&arc_eviction_mtx);
1977 arc_buf_destroy(buf,
1978 buf->b_data == stolen, FALSE);
1979 ab->b_buf = buf->b_next;
1980 buf->b_hdr = &arc_eviction_hdr;
1981 buf->b_next = arc_eviction_list;
1982 arc_eviction_list = buf;
1983 mutex_exit(&arc_eviction_mtx);
428870ff 1984 mutex_exit(&buf->b_evict_lock);
34dc7c2f 1985 } else {
428870ff 1986 mutex_exit(&buf->b_evict_lock);
34dc7c2f
BB
1987 arc_buf_destroy(buf,
1988 buf->b_data == stolen, TRUE);
1989 }
1990 }
428870ff
BB
1991
1992 if (ab->b_l2hdr) {
1993 ARCSTAT_INCR(arcstat_evict_l2_cached,
1994 ab->b_size);
1995 } else {
1996 if (l2arc_write_eligible(ab->b_spa, ab)) {
1997 ARCSTAT_INCR(arcstat_evict_l2_eligible,
1998 ab->b_size);
1999 } else {
2000 ARCSTAT_INCR(
2001 arcstat_evict_l2_ineligible,
2002 ab->b_size);
2003 }
2004 }
2005
b128c09f
BB
2006 if (ab->b_datacnt == 0) {
2007 arc_change_state(evicted_state, ab, hash_lock);
2008 ASSERT(HDR_IN_HASH_TABLE(ab));
2009 ab->b_flags |= ARC_IN_HASH_TABLE;
2010 ab->b_flags &= ~ARC_BUF_AVAILABLE;
2011 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, ab);
2012 }
34dc7c2f
BB
2013 if (!have_lock)
2014 mutex_exit(hash_lock);
2015 if (bytes >= 0 && bytes_evicted >= bytes)
2016 break;
2017 } else {
2018 missed += 1;
2019 }
2020 }
2021
2022 mutex_exit(&evicted_state->arcs_mtx);
2023 mutex_exit(&state->arcs_mtx);
2024
da8ccd0e
PS
2025 if (list == &state->arcs_list[ARC_BUFC_DATA] &&
2026 (bytes < 0 || bytes_evicted < bytes)) {
2027 /* Prevent second pass from recycling metadata into data */
2028 recycle = FALSE;
2029 type = ARC_BUFC_METADATA;
2030 list = &state->arcs_list[type];
2031 goto top;
2032 }
2033
34dc7c2f 2034 if (bytes_evicted < bytes)
3f504482 2035 dprintf("only evicted %lld bytes from %x\n",
34dc7c2f
BB
2036 (longlong_t)bytes_evicted, state);
2037
2038 if (skipped)
2039 ARCSTAT_INCR(arcstat_evict_skip, skipped);
2040
2041 if (missed)
2042 ARCSTAT_INCR(arcstat_mutex_miss, missed);
2043
2044 /*
e8b96c60
MA
2045 * Note: we have just evicted some data into the ghost state,
2046 * potentially putting the ghost size over the desired size. Rather
2047 * that evicting from the ghost list in this hot code path, leave
2048 * this chore to the arc_reclaim_thread().
34dc7c2f 2049 */
34dc7c2f
BB
2050
2051 return (stolen);
2052}
2053
2054/*
2055 * Remove buffers from list until we've removed the specified number of
2056 * bytes. Destroy the buffers that are removed.
2057 */
2058static void
68121a03
BB
2059arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes,
2060 arc_buf_contents_t type)
34dc7c2f
BB
2061{
2062 arc_buf_hdr_t *ab, *ab_prev;
2598c001 2063 arc_buf_hdr_t marker;
68121a03 2064 list_t *list = &state->arcs_list[type];
34dc7c2f
BB
2065 kmutex_t *hash_lock;
2066 uint64_t bytes_deleted = 0;
2067 uint64_t bufs_skipped = 0;
e8b96c60 2068 int count = 0;
34dc7c2f
BB
2069
2070 ASSERT(GHOST_STATE(state));
d1d7e268 2071 bzero(&marker, sizeof (marker));
34dc7c2f
BB
2072top:
2073 mutex_enter(&state->arcs_mtx);
2074 for (ab = list_tail(list); ab; ab = ab_prev) {
2075 ab_prev = list_prev(list, ab);
e8b96c60
MA
2076 if (ab->b_type > ARC_BUFC_NUMTYPES)
2077 panic("invalid ab=%p", (void *)ab);
34dc7c2f
BB
2078 if (spa && ab->b_spa != spa)
2079 continue;
572e2857
BB
2080
2081 /* ignore markers */
2082 if (ab->b_spa == 0)
2083 continue;
2084
34dc7c2f 2085 hash_lock = HDR_LOCK(ab);
428870ff
BB
2086 /* caller may be trying to modify this buffer, skip it */
2087 if (MUTEX_HELD(hash_lock))
2088 continue;
e8b96c60
MA
2089
2090 /*
2091 * It may take a long time to evict all the bufs requested.
2092 * To avoid blocking all arc activity, periodically drop
2093 * the arcs_mtx and give other threads a chance to run
2094 * before reacquiring the lock.
2095 */
2096 if (count++ > arc_evict_iterations) {
2097 list_insert_after(list, ab, &marker);
2098 mutex_exit(&state->arcs_mtx);
2099 kpreempt(KPREEMPT_SYNC);
2100 mutex_enter(&state->arcs_mtx);
2101 ab_prev = list_prev(list, &marker);
2102 list_remove(list, &marker);
2103 count = 0;
2104 continue;
2105 }
34dc7c2f
BB
2106 if (mutex_tryenter(hash_lock)) {
2107 ASSERT(!HDR_IO_IN_PROGRESS(ab));
2108 ASSERT(ab->b_buf == NULL);
2109 ARCSTAT_BUMP(arcstat_deleted);
2110 bytes_deleted += ab->b_size;
2111
2112 if (ab->b_l2hdr != NULL) {
2113 /*
2114 * This buffer is cached on the 2nd Level ARC;
2115 * don't destroy the header.
2116 */
2117 arc_change_state(arc_l2c_only, ab, hash_lock);
2118 mutex_exit(hash_lock);
2119 } else {
2120 arc_change_state(arc_anon, ab, hash_lock);
2121 mutex_exit(hash_lock);
2122 arc_hdr_destroy(ab);
2123 }
2124
2125 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, ab);
2126 if (bytes >= 0 && bytes_deleted >= bytes)
2127 break;
572e2857
BB
2128 } else if (bytes < 0) {
2129 /*
2130 * Insert a list marker and then wait for the
2131 * hash lock to become available. Once its
2132 * available, restart from where we left off.
2133 */
2134 list_insert_after(list, ab, &marker);
2135 mutex_exit(&state->arcs_mtx);
2136 mutex_enter(hash_lock);
2137 mutex_exit(hash_lock);
2138 mutex_enter(&state->arcs_mtx);
2139 ab_prev = list_prev(list, &marker);
2140 list_remove(list, &marker);
e8b96c60 2141 } else {
34dc7c2f 2142 bufs_skipped += 1;
e8b96c60 2143 }
34dc7c2f
BB
2144 }
2145 mutex_exit(&state->arcs_mtx);
2146
2147 if (list == &state->arcs_list[ARC_BUFC_DATA] &&
2148 (bytes < 0 || bytes_deleted < bytes)) {
2149 list = &state->arcs_list[ARC_BUFC_METADATA];
2150 goto top;
2151 }
2152
2153 if (bufs_skipped) {
2154 ARCSTAT_INCR(arcstat_mutex_miss, bufs_skipped);
2155 ASSERT(bytes >= 0);
2156 }
2157
2158 if (bytes_deleted < bytes)
3f504482 2159 dprintf("only deleted %lld bytes from %p\n",
34dc7c2f
BB
2160 (longlong_t)bytes_deleted, state);
2161}
2162
2163static void
2164arc_adjust(void)
2165{
d164b209
BB
2166 int64_t adjustment, delta;
2167
2168 /*
2169 * Adjust MRU size
2170 */
34dc7c2f 2171
572e2857 2172 adjustment = MIN((int64_t)(arc_size - arc_c),
77765b54 2173 (int64_t)(arc_anon->arcs_size + arc_mru->arcs_size - arc_p));
34dc7c2f 2174
da8ccd0e
PS
2175 if (adjustment > 0 && arc_mru->arcs_size > 0) {
2176 delta = MIN(arc_mru->arcs_size, adjustment);
b8864a23 2177 (void) arc_evict(arc_mru, 0, delta, FALSE, ARC_BUFC_DATA);
34dc7c2f
BB
2178 }
2179
d164b209
BB
2180 /*
2181 * Adjust MFU size
2182 */
34dc7c2f 2183
d164b209
BB
2184 adjustment = arc_size - arc_c;
2185
da8ccd0e
PS
2186 if (adjustment > 0 && arc_mfu->arcs_size > 0) {
2187 delta = MIN(arc_mfu->arcs_size, adjustment);
b8864a23 2188 (void) arc_evict(arc_mfu, 0, delta, FALSE, ARC_BUFC_DATA);
d164b209 2189 }
34dc7c2f 2190
d164b209
BB
2191 /*
2192 * Adjust ghost lists
2193 */
34dc7c2f 2194
d164b209
BB
2195 adjustment = arc_mru->arcs_size + arc_mru_ghost->arcs_size - arc_c;
2196
2197 if (adjustment > 0 && arc_mru_ghost->arcs_size > 0) {
2198 delta = MIN(arc_mru_ghost->arcs_size, adjustment);
68121a03 2199 arc_evict_ghost(arc_mru_ghost, 0, delta, ARC_BUFC_DATA);
d164b209 2200 }
34dc7c2f 2201
d164b209
BB
2202 adjustment =
2203 arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size - arc_c;
34dc7c2f 2204
d164b209
BB
2205 if (adjustment > 0 && arc_mfu_ghost->arcs_size > 0) {
2206 delta = MIN(arc_mfu_ghost->arcs_size, adjustment);
68121a03 2207 arc_evict_ghost(arc_mfu_ghost, 0, delta, ARC_BUFC_DATA);
34dc7c2f
BB
2208 }
2209}
2210
ab26409d
BB
2211/*
2212 * Request that arc user drop references so that N bytes can be released
2213 * from the cache. This provides a mechanism to ensure the arc can honor
2214 * the arc_meta_limit and reclaim buffers which are pinned in the cache
2215 * by higher layers. (i.e. the zpl)
2216 */
2217static void
2218arc_do_user_prune(int64_t adjustment)
2219{
2220 arc_prune_func_t *func;
2221 void *private;
2222 arc_prune_t *cp, *np;
2223
2224 mutex_enter(&arc_prune_mtx);
2225
2226 cp = list_head(&arc_prune_list);
2227 while (cp != NULL) {
2228 func = cp->p_pfunc;
2229 private = cp->p_private;
2230 np = list_next(&arc_prune_list, cp);
2231 refcount_add(&cp->p_refcnt, func);
2232 mutex_exit(&arc_prune_mtx);
2233
2234 if (func != NULL)
2235 func(adjustment, private);
2236
2237 mutex_enter(&arc_prune_mtx);
2238
2239 /* User removed prune callback concurrently with execution */
2240 if (refcount_remove(&cp->p_refcnt, func) == 0) {
2241 ASSERT(!list_link_active(&cp->p_node));
2242 refcount_destroy(&cp->p_refcnt);
2243 kmem_free(cp, sizeof (*cp));
2244 }
2245
2246 cp = np;
2247 }
2248
2249 ARCSTAT_BUMP(arcstat_prune);
2250 mutex_exit(&arc_prune_mtx);
2251}
2252
34dc7c2f
BB
2253static void
2254arc_do_user_evicts(void)
2255{
2256 mutex_enter(&arc_eviction_mtx);
2257 while (arc_eviction_list != NULL) {
2258 arc_buf_t *buf = arc_eviction_list;
2259 arc_eviction_list = buf->b_next;
428870ff 2260 mutex_enter(&buf->b_evict_lock);
34dc7c2f 2261 buf->b_hdr = NULL;
428870ff 2262 mutex_exit(&buf->b_evict_lock);
34dc7c2f
BB
2263 mutex_exit(&arc_eviction_mtx);
2264
2265 if (buf->b_efunc != NULL)
2266 VERIFY(buf->b_efunc(buf) == 0);
2267
2268 buf->b_efunc = NULL;
2269 buf->b_private = NULL;
2270 kmem_cache_free(buf_cache, buf);
2271 mutex_enter(&arc_eviction_mtx);
2272 }
2273 mutex_exit(&arc_eviction_mtx);
2274}
2275
ab26409d
BB
2276/*
2277 * Evict only meta data objects from the cache leaving the data objects.
2278 * This is only used to enforce the tunable arc_meta_limit, if we are
2279 * unable to evict enough buffers notify the user via the prune callback.
2280 */
94520ca4
PS
2281static void
2282arc_adjust_meta(void)
ab26409d 2283{
94520ca4 2284 int64_t adjustmnt, delta;
ab26409d 2285
94520ca4
PS
2286 /*
2287 * This slightly differs than the way we evict from the mru in
2288 * arc_adjust because we don't have a "target" value (i.e. no
2289 * "meta" arc_p). As a result, I think we can completely
2290 * cannibalize the metadata in the MRU before we evict the
2291 * metadata from the MFU. I think we probably need to implement a
2292 * "metadata arc_p" value to do this properly.
2293 */
2294 adjustmnt = arc_meta_used - arc_meta_limit;
2295
2296 if (adjustmnt > 0 && arc_mru->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2297 delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_METADATA], adjustmnt);
ab26409d 2298 arc_evict(arc_mru, 0, delta, FALSE, ARC_BUFC_METADATA);
94520ca4 2299 adjustmnt -= delta;
ab26409d
BB
2300 }
2301
94520ca4
PS
2302 /*
2303 * We can't afford to recalculate adjustmnt here. If we do,
2304 * new metadata buffers can sneak into the MRU or ANON lists,
2305 * thus penalize the MFU metadata. Although the fudge factor is
2306 * small, it has been empirically shown to be significant for
2307 * certain workloads (e.g. creating many empty directories). As
2308 * such, we use the original calculation for adjustmnt, and
2309 * simply decrement the amount of data evicted from the MRU.
2310 */
2311
2312 if (adjustmnt > 0 && arc_mfu->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2313 delta = MIN(arc_mfu->arcs_lsize[ARC_BUFC_METADATA], adjustmnt);
ab26409d 2314 arc_evict(arc_mfu, 0, delta, FALSE, ARC_BUFC_METADATA);
ab26409d
BB
2315 }
2316
94520ca4
PS
2317 adjustmnt = arc_mru->arcs_lsize[ARC_BUFC_METADATA] +
2318 arc_mru_ghost->arcs_lsize[ARC_BUFC_METADATA] - arc_meta_limit;
2319
2320 if (adjustmnt > 0 && arc_mru_ghost->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2321 delta = MIN(adjustmnt,
2322 arc_mru_ghost->arcs_lsize[ARC_BUFC_METADATA]);
2323 arc_evict_ghost(arc_mru_ghost, 0, delta, ARC_BUFC_METADATA);
2324 }
2325
2326 adjustmnt = arc_mru_ghost->arcs_lsize[ARC_BUFC_METADATA] +
2327 arc_mfu_ghost->arcs_lsize[ARC_BUFC_METADATA] - arc_meta_limit;
2328
2329 if (adjustmnt > 0 && arc_mfu_ghost->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2330 delta = MIN(adjustmnt,
2331 arc_mfu_ghost->arcs_lsize[ARC_BUFC_METADATA]);
2332 arc_evict_ghost(arc_mfu_ghost, 0, delta, ARC_BUFC_METADATA);
2333 }
2334
2335 if (arc_meta_used > arc_meta_limit)
bce45ec9 2336 arc_do_user_prune(zfs_arc_meta_prune);
ab26409d
BB
2337}
2338
34dc7c2f
BB
2339/*
2340 * Flush all *evictable* data from the cache for the given spa.
2341 * NOTE: this will not touch "active" (i.e. referenced) data.
2342 */
2343void
2344arc_flush(spa_t *spa)
2345{
d164b209
BB
2346 uint64_t guid = 0;
2347
2348 if (spa)
3541dc6d 2349 guid = spa_load_guid(spa);
d164b209 2350
34dc7c2f 2351 while (list_head(&arc_mru->arcs_list[ARC_BUFC_DATA])) {
d164b209 2352 (void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_DATA);
34dc7c2f
BB
2353 if (spa)
2354 break;
2355 }
2356 while (list_head(&arc_mru->arcs_list[ARC_BUFC_METADATA])) {
d164b209 2357 (void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_METADATA);
34dc7c2f
BB
2358 if (spa)
2359 break;
2360 }
2361 while (list_head(&arc_mfu->arcs_list[ARC_BUFC_DATA])) {
d164b209 2362 (void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_DATA);
34dc7c2f
BB
2363 if (spa)
2364 break;
2365 }
2366 while (list_head(&arc_mfu->arcs_list[ARC_BUFC_METADATA])) {
d164b209 2367 (void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_METADATA);
34dc7c2f
BB
2368 if (spa)
2369 break;
2370 }
2371
68121a03
BB
2372 arc_evict_ghost(arc_mru_ghost, guid, -1, ARC_BUFC_DATA);
2373 arc_evict_ghost(arc_mfu_ghost, guid, -1, ARC_BUFC_DATA);
34dc7c2f
BB
2374
2375 mutex_enter(&arc_reclaim_thr_lock);
2376 arc_do_user_evicts();
2377 mutex_exit(&arc_reclaim_thr_lock);
2378 ASSERT(spa || arc_eviction_list == NULL);
2379}
2380
34dc7c2f 2381void
302f753f 2382arc_shrink(uint64_t bytes)
34dc7c2f
BB
2383{
2384 if (arc_c > arc_c_min) {
2385 uint64_t to_free;
2386
bce45ec9 2387 to_free = bytes ? bytes : arc_c >> zfs_arc_shrink_shift;
302f753f 2388
34dc7c2f
BB
2389 if (arc_c > arc_c_min + to_free)
2390 atomic_add_64(&arc_c, -to_free);
2391 else
2392 arc_c = arc_c_min;
2393
39e055c4
PS
2394 to_free = bytes ? bytes : arc_p >> zfs_arc_shrink_shift;
2395
f521ce1b 2396 if (arc_p > to_free)
39e055c4
PS
2397 atomic_add_64(&arc_p, -to_free);
2398 else
f521ce1b 2399 arc_p = 0;
39e055c4 2400
34dc7c2f
BB
2401 if (arc_c > arc_size)
2402 arc_c = MAX(arc_size, arc_c_min);
2403 if (arc_p > arc_c)
2404 arc_p = (arc_c >> 1);
2405 ASSERT(arc_c >= arc_c_min);
2406 ASSERT((int64_t)arc_p >= 0);
2407 }
2408
2409 if (arc_size > arc_c)
2410 arc_adjust();
2411}
2412
34dc7c2f 2413static void
302f753f 2414arc_kmem_reap_now(arc_reclaim_strategy_t strat, uint64_t bytes)
34dc7c2f
BB
2415{
2416 size_t i;
2417 kmem_cache_t *prev_cache = NULL;
2418 kmem_cache_t *prev_data_cache = NULL;
2419 extern kmem_cache_t *zio_buf_cache[];
2420 extern kmem_cache_t *zio_data_buf_cache[];
34dc7c2f
BB
2421
2422 /*
2423 * An aggressive reclamation will shrink the cache size as well as
2424 * reap free buffers from the arc kmem caches.
2425 */
2426 if (strat == ARC_RECLAIM_AGGR)
302f753f 2427 arc_shrink(bytes);
34dc7c2f
BB
2428
2429 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
2430 if (zio_buf_cache[i] != prev_cache) {
2431 prev_cache = zio_buf_cache[i];
2432 kmem_cache_reap_now(zio_buf_cache[i]);
2433 }
2434 if (zio_data_buf_cache[i] != prev_data_cache) {
2435 prev_data_cache = zio_data_buf_cache[i];
2436 kmem_cache_reap_now(zio_data_buf_cache[i]);
2437 }
2438 }
ab26409d 2439
34dc7c2f
BB
2440 kmem_cache_reap_now(buf_cache);
2441 kmem_cache_reap_now(hdr_cache);
2442}
2443
302f753f
BB
2444/*
2445 * Unlike other ZFS implementations this thread is only responsible for
2446 * adapting the target ARC size on Linux. The responsibility for memory
2447 * reclamation has been entirely delegated to the arc_shrinker_func()
2448 * which is registered with the VM. To reflect this change in behavior
2449 * the arc_reclaim thread has been renamed to arc_adapt.
2450 */
34dc7c2f 2451static void
302f753f 2452arc_adapt_thread(void)
34dc7c2f 2453{
34dc7c2f
BB
2454 callb_cpr_t cpr;
2455
2456 CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
2457
2458 mutex_enter(&arc_reclaim_thr_lock);
2459 while (arc_thread_exit == 0) {
302f753f
BB
2460#ifndef _KERNEL
2461 arc_reclaim_strategy_t last_reclaim = ARC_RECLAIM_CONS;
2462
2463 if (spa_get_random(100) == 0) {
34dc7c2f
BB
2464
2465 if (arc_no_grow) {
2466 if (last_reclaim == ARC_RECLAIM_CONS) {
2467 last_reclaim = ARC_RECLAIM_AGGR;
2468 } else {
2469 last_reclaim = ARC_RECLAIM_CONS;
2470 }
2471 } else {
2472 arc_no_grow = TRUE;
2473 last_reclaim = ARC_RECLAIM_AGGR;
2474 membar_producer();
2475 }
2476
2477 /* reset the growth delay for every reclaim */
d1d7e268
MK
2478 arc_grow_time = ddi_get_lbolt() +
2479 (zfs_arc_grow_retry * hz);
34dc7c2f 2480
302f753f 2481 arc_kmem_reap_now(last_reclaim, 0);
b128c09f 2482 arc_warm = B_TRUE;
302f753f
BB
2483 }
2484#endif /* !_KERNEL */
34dc7c2f 2485
302f753f 2486 /* No recent memory pressure allow the ARC to grow. */
0b75bdb3
CC
2487 if (arc_no_grow &&
2488 ddi_time_after_eq(ddi_get_lbolt(), arc_grow_time))
34dc7c2f 2489 arc_no_grow = FALSE;
34dc7c2f 2490
94520ca4 2491 arc_adjust_meta();
6a8f9b6b 2492
572e2857 2493 arc_adjust();
34dc7c2f
BB
2494
2495 if (arc_eviction_list != NULL)
2496 arc_do_user_evicts();
2497
2498 /* block until needed, or one second, whichever is shorter */
2499 CALLB_CPR_SAFE_BEGIN(&cpr);
5b63b3eb 2500 (void) cv_timedwait_interruptible(&arc_reclaim_thr_cv,
428870ff 2501 &arc_reclaim_thr_lock, (ddi_get_lbolt() + hz));
34dc7c2f 2502 CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
bce45ec9
BB
2503
2504
2505 /* Allow the module options to be changed */
2506 if (zfs_arc_max > 64 << 20 &&
2507 zfs_arc_max < physmem * PAGESIZE &&
2508 zfs_arc_max != arc_c_max)
2509 arc_c_max = zfs_arc_max;
2510
2511 if (zfs_arc_min > 0 &&
2512 zfs_arc_min < arc_c_max &&
2513 zfs_arc_min != arc_c_min)
2514 arc_c_min = zfs_arc_min;
2515
2516 if (zfs_arc_meta_limit > 0 &&
2517 zfs_arc_meta_limit <= arc_c_max &&
2518 zfs_arc_meta_limit != arc_meta_limit)
2519 arc_meta_limit = zfs_arc_meta_limit;
2520
2521
2522
34dc7c2f
BB
2523 }
2524
2525 arc_thread_exit = 0;
2526 cv_broadcast(&arc_reclaim_thr_cv);
2527 CALLB_CPR_EXIT(&cpr); /* drops arc_reclaim_thr_lock */
2528 thread_exit();
2529}
2530
7cb67b45
BB
2531#ifdef _KERNEL
2532/*
302f753f
BB
2533 * Determine the amount of memory eligible for eviction contained in the
2534 * ARC. All clean data reported by the ghost lists can always be safely
2535 * evicted. Due to arc_c_min, the same does not hold for all clean data
2536 * contained by the regular mru and mfu lists.
2537 *
2538 * In the case of the regular mru and mfu lists, we need to report as
2539 * much clean data as possible, such that evicting that same reported
2540 * data will not bring arc_size below arc_c_min. Thus, in certain
2541 * circumstances, the total amount of clean data in the mru and mfu
2542 * lists might not actually be evictable.
2543 *
2544 * The following two distinct cases are accounted for:
2545 *
2546 * 1. The sum of the amount of dirty data contained by both the mru and
2547 * mfu lists, plus the ARC's other accounting (e.g. the anon list),
2548 * is greater than or equal to arc_c_min.
2549 * (i.e. amount of dirty data >= arc_c_min)
2550 *
2551 * This is the easy case; all clean data contained by the mru and mfu
2552 * lists is evictable. Evicting all clean data can only drop arc_size
2553 * to the amount of dirty data, which is greater than arc_c_min.
2554 *
2555 * 2. The sum of the amount of dirty data contained by both the mru and
2556 * mfu lists, plus the ARC's other accounting (e.g. the anon list),
2557 * is less than arc_c_min.
2558 * (i.e. arc_c_min > amount of dirty data)
2559 *
2560 * 2.1. arc_size is greater than or equal arc_c_min.
2561 * (i.e. arc_size >= arc_c_min > amount of dirty data)
2562 *
2563 * In this case, not all clean data from the regular mru and mfu
2564 * lists is actually evictable; we must leave enough clean data
2565 * to keep arc_size above arc_c_min. Thus, the maximum amount of
2566 * evictable data from the two lists combined, is exactly the
2567 * difference between arc_size and arc_c_min.
2568 *
2569 * 2.2. arc_size is less than arc_c_min
2570 * (i.e. arc_c_min > arc_size > amount of dirty data)
2571 *
2572 * In this case, none of the data contained in the mru and mfu
2573 * lists is evictable, even if it's clean. Since arc_size is
2574 * already below arc_c_min, evicting any more would only
2575 * increase this negative difference.
7cb67b45 2576 */
302f753f
BB
2577static uint64_t
2578arc_evictable_memory(void) {
2579 uint64_t arc_clean =
2580 arc_mru->arcs_lsize[ARC_BUFC_DATA] +
2581 arc_mru->arcs_lsize[ARC_BUFC_METADATA] +
2582 arc_mfu->arcs_lsize[ARC_BUFC_DATA] +
2583 arc_mfu->arcs_lsize[ARC_BUFC_METADATA];
2584 uint64_t ghost_clean =
2585 arc_mru_ghost->arcs_lsize[ARC_BUFC_DATA] +
2586 arc_mru_ghost->arcs_lsize[ARC_BUFC_METADATA] +
2587 arc_mfu_ghost->arcs_lsize[ARC_BUFC_DATA] +
2588 arc_mfu_ghost->arcs_lsize[ARC_BUFC_METADATA];
2589 uint64_t arc_dirty = MAX((int64_t)arc_size - (int64_t)arc_clean, 0);
2590
2591 if (arc_dirty >= arc_c_min)
2592 return (ghost_clean + arc_clean);
2593
2594 return (ghost_clean + MAX((int64_t)arc_size - (int64_t)arc_c_min, 0));
2595}
2596
7e7baeca
BB
2597static int
2598__arc_shrinker_func(struct shrinker *shrink, struct shrink_control *sc)
7cb67b45 2599{
302f753f 2600 uint64_t pages;
7cb67b45 2601
302f753f
BB
2602 /* The arc is considered warm once reclaim has occurred */
2603 if (unlikely(arc_warm == B_FALSE))
2604 arc_warm = B_TRUE;
7cb67b45 2605
302f753f
BB
2606 /* Return the potential number of reclaimable pages */
2607 pages = btop(arc_evictable_memory());
2608 if (sc->nr_to_scan == 0)
2609 return (pages);
3fd70ee6
BB
2610
2611 /* Not allowed to perform filesystem reclaim */
7e7baeca 2612 if (!(sc->gfp_mask & __GFP_FS))
3fd70ee6
BB
2613 return (-1);
2614
7cb67b45
BB
2615 /* Reclaim in progress */
2616 if (mutex_tryenter(&arc_reclaim_thr_lock) == 0)
2617 return (-1);
2618
302f753f
BB
2619 /*
2620 * Evict the requested number of pages by shrinking arc_c the
2621 * requested amount. If there is nothing left to evict just
2622 * reap whatever we can from the various arc slabs.
2623 */
2624 if (pages > 0) {
2625 arc_kmem_reap_now(ARC_RECLAIM_AGGR, ptob(sc->nr_to_scan));
1e3cb67b 2626 pages = btop(arc_evictable_memory());
302f753f
BB
2627 } else {
2628 arc_kmem_reap_now(ARC_RECLAIM_CONS, ptob(sc->nr_to_scan));
1e3cb67b 2629 pages = -1;
302f753f
BB
2630 }
2631
2632 /*
2633 * When direct reclaim is observed it usually indicates a rapid
2634 * increase in memory pressure. This occurs because the kswapd
2635 * threads were unable to asynchronously keep enough free memory
2636 * available. In this case set arc_no_grow to briefly pause arc
2637 * growth to avoid compounding the memory pressure.
2638 */
7cb67b45 2639 if (current_is_kswapd()) {
302f753f 2640 ARCSTAT_BUMP(arcstat_memory_indirect_count);
7cb67b45 2641 } else {
302f753f 2642 arc_no_grow = B_TRUE;
bce45ec9 2643 arc_grow_time = ddi_get_lbolt() + (zfs_arc_grow_retry * hz);
302f753f 2644 ARCSTAT_BUMP(arcstat_memory_direct_count);
7cb67b45
BB
2645 }
2646
7cb67b45
BB
2647 mutex_exit(&arc_reclaim_thr_lock);
2648
1e3cb67b 2649 return (pages);
7cb67b45 2650}
7e7baeca 2651SPL_SHRINKER_CALLBACK_WRAPPER(arc_shrinker_func);
7cb67b45
BB
2652
2653SPL_SHRINKER_DECLARE(arc_shrinker, arc_shrinker_func, DEFAULT_SEEKS);
2654#endif /* _KERNEL */
2655
34dc7c2f
BB
2656/*
2657 * Adapt arc info given the number of bytes we are trying to add and
2658 * the state that we are comming from. This function is only called
2659 * when we are adding new content to the cache.
2660 */
2661static void
2662arc_adapt(int bytes, arc_state_t *state)
2663{
2664 int mult;
2665
2666 if (state == arc_l2c_only)
2667 return;
2668
2669 ASSERT(bytes > 0);
2670 /*
2671 * Adapt the target size of the MRU list:
2672 * - if we just hit in the MRU ghost list, then increase
2673 * the target size of the MRU list.
2674 * - if we just hit in the MFU ghost list, then increase
2675 * the target size of the MFU list by decreasing the
2676 * target size of the MRU list.
2677 */
2678 if (state == arc_mru_ghost) {
2679 mult = ((arc_mru_ghost->arcs_size >= arc_mfu_ghost->arcs_size) ?
2680 1 : (arc_mfu_ghost->arcs_size/arc_mru_ghost->arcs_size));
62422785
PS
2681
2682 if (!zfs_arc_p_dampener_disable)
2683 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
34dc7c2f 2684
f521ce1b 2685 arc_p = MIN(arc_c, arc_p + bytes * mult);
34dc7c2f 2686 } else if (state == arc_mfu_ghost) {
d164b209
BB
2687 uint64_t delta;
2688
34dc7c2f
BB
2689 mult = ((arc_mfu_ghost->arcs_size >= arc_mru_ghost->arcs_size) ?
2690 1 : (arc_mru_ghost->arcs_size/arc_mfu_ghost->arcs_size));
62422785
PS
2691
2692 if (!zfs_arc_p_dampener_disable)
2693 mult = MIN(mult, 10);
34dc7c2f 2694
d164b209 2695 delta = MIN(bytes * mult, arc_p);
f521ce1b 2696 arc_p = MAX(0, arc_p - delta);
34dc7c2f
BB
2697 }
2698 ASSERT((int64_t)arc_p >= 0);
2699
34dc7c2f
BB
2700 if (arc_no_grow)
2701 return;
2702
2703 if (arc_c >= arc_c_max)
2704 return;
2705
2706 /*
2707 * If we're within (2 * maxblocksize) bytes of the target
2708 * cache size, increment the target cache size
2709 */
2710 if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
2711 atomic_add_64(&arc_c, (int64_t)bytes);
2712 if (arc_c > arc_c_max)
2713 arc_c = arc_c_max;
2714 else if (state == arc_anon)
2715 atomic_add_64(&arc_p, (int64_t)bytes);
2716 if (arc_p > arc_c)
2717 arc_p = arc_c;
2718 }
2719 ASSERT((int64_t)arc_p >= 0);
2720}
2721
2722/*
2723 * Check if the cache has reached its limits and eviction is required
2724 * prior to insert.
2725 */
2726static int
2727arc_evict_needed(arc_buf_contents_t type)
2728{
2729 if (type == ARC_BUFC_METADATA && arc_meta_used >= arc_meta_limit)
2730 return (1);
2731
302f753f 2732 if (arc_no_grow)
34dc7c2f
BB
2733 return (1);
2734
2735 return (arc_size > arc_c);
2736}
2737
2738/*
2739 * The buffer, supplied as the first argument, needs a data block.
2740 * So, if we are at cache max, determine which cache should be victimized.
2741 * We have the following cases:
2742 *
2743 * 1. Insert for MRU, p > sizeof(arc_anon + arc_mru) ->
2744 * In this situation if we're out of space, but the resident size of the MFU is
2745 * under the limit, victimize the MFU cache to satisfy this insertion request.
2746 *
2747 * 2. Insert for MRU, p <= sizeof(arc_anon + arc_mru) ->
2748 * Here, we've used up all of the available space for the MRU, so we need to
2749 * evict from our own cache instead. Evict from the set of resident MRU
2750 * entries.
2751 *
2752 * 3. Insert for MFU (c - p) > sizeof(arc_mfu) ->
2753 * c minus p represents the MFU space in the cache, since p is the size of the
2754 * cache that is dedicated to the MRU. In this situation there's still space on
2755 * the MFU side, so the MRU side needs to be victimized.
2756 *
2757 * 4. Insert for MFU (c - p) < sizeof(arc_mfu) ->
2758 * MFU's resident set is consuming more space than it has been allotted. In
2759 * this situation, we must victimize our own cache, the MFU, for this insertion.
2760 */
2761static void
2762arc_get_data_buf(arc_buf_t *buf)
2763{
2764 arc_state_t *state = buf->b_hdr->b_state;
2765 uint64_t size = buf->b_hdr->b_size;
2766 arc_buf_contents_t type = buf->b_hdr->b_type;
da8ccd0e
PS
2767 arc_buf_contents_t evict = ARC_BUFC_DATA;
2768 boolean_t recycle = TRUE;
34dc7c2f
BB
2769
2770 arc_adapt(size, state);
2771
2772 /*
2773 * We have not yet reached cache maximum size,
2774 * just allocate a new buffer.
2775 */
2776 if (!arc_evict_needed(type)) {
2777 if (type == ARC_BUFC_METADATA) {
2778 buf->b_data = zio_buf_alloc(size);
cc7f677c 2779 arc_space_consume(size, ARC_SPACE_META);
34dc7c2f
BB
2780 } else {
2781 ASSERT(type == ARC_BUFC_DATA);
2782 buf->b_data = zio_data_buf_alloc(size);
cc7f677c 2783 arc_space_consume(size, ARC_SPACE_DATA);
34dc7c2f
BB
2784 }
2785 goto out;
2786 }
2787
2788 /*
2789 * If we are prefetching from the mfu ghost list, this buffer
2790 * will end up on the mru list; so steal space from there.
2791 */
2792 if (state == arc_mfu_ghost)
2793 state = buf->b_hdr->b_flags & ARC_PREFETCH ? arc_mru : arc_mfu;
2794 else if (state == arc_mru_ghost)
2795 state = arc_mru;
2796
2797 if (state == arc_mru || state == arc_anon) {
2798 uint64_t mru_used = arc_anon->arcs_size + arc_mru->arcs_size;
d164b209 2799 state = (arc_mfu->arcs_lsize[type] >= size &&
34dc7c2f
BB
2800 arc_p > mru_used) ? arc_mfu : arc_mru;
2801 } else {
2802 /* MFU cases */
2803 uint64_t mfu_space = arc_c - arc_p;
d164b209 2804 state = (arc_mru->arcs_lsize[type] >= size &&
34dc7c2f
BB
2805 mfu_space > arc_mfu->arcs_size) ? arc_mru : arc_mfu;
2806 }
ab26409d 2807
da8ccd0e
PS
2808 /*
2809 * Evict data buffers prior to metadata buffers, unless we're
2810 * over the metadata limit and adding a metadata buffer.
2811 */
2812 if (type == ARC_BUFC_METADATA) {
2813 if (arc_meta_used >= arc_meta_limit)
2814 evict = ARC_BUFC_METADATA;
2815 else
2816 /*
2817 * In this case, we're evicting data while
2818 * adding metadata. Thus, to prevent recycling a
2819 * data buffer into a metadata buffer, recycling
2820 * is disabled in the following arc_evict call.
2821 */
2822 recycle = FALSE;
2823 }
2824
2825 if ((buf->b_data = arc_evict(state, 0, size, recycle, evict)) == NULL) {
34dc7c2f
BB
2826 if (type == ARC_BUFC_METADATA) {
2827 buf->b_data = zio_buf_alloc(size);
cc7f677c 2828 arc_space_consume(size, ARC_SPACE_META);
ab26409d
BB
2829
2830 /*
2831 * If we are unable to recycle an existing meta buffer
2832 * signal the reclaim thread. It will notify users
2833 * via the prune callback to drop references. The
2834 * prune callback in run in the context of the reclaim
2835 * thread to avoid deadlocking on the hash_lock.
da8ccd0e 2836 * Of course, only do this when recycle is true.
ab26409d 2837 */
da8ccd0e
PS
2838 if (recycle)
2839 cv_signal(&arc_reclaim_thr_cv);
34dc7c2f
BB
2840 } else {
2841 ASSERT(type == ARC_BUFC_DATA);
2842 buf->b_data = zio_data_buf_alloc(size);
cc7f677c 2843 arc_space_consume(size, ARC_SPACE_DATA);
34dc7c2f 2844 }
ab26409d 2845
da8ccd0e
PS
2846 /* Only bump this if we tried to recycle and failed */
2847 if (recycle)
2848 ARCSTAT_BUMP(arcstat_recycle_miss);
34dc7c2f
BB
2849 }
2850 ASSERT(buf->b_data != NULL);
2851out:
2852 /*
2853 * Update the state size. Note that ghost states have a
2854 * "ghost size" and so don't need to be updated.
2855 */
2856 if (!GHOST_STATE(buf->b_hdr->b_state)) {
2857 arc_buf_hdr_t *hdr = buf->b_hdr;
2858
2859 atomic_add_64(&hdr->b_state->arcs_size, size);
2860 if (list_link_active(&hdr->b_arc_node)) {
2861 ASSERT(refcount_is_zero(&hdr->b_refcnt));
2862 atomic_add_64(&hdr->b_state->arcs_lsize[type], size);
2863 }
2864 /*
2865 * If we are growing the cache, and we are adding anonymous
2866 * data, and we have outgrown arc_p, update arc_p
2867 */
89c8cac4
PS
2868 if (!zfs_arc_p_aggressive_disable &&
2869 arc_size < arc_c && hdr->b_state == arc_anon &&
34dc7c2f
BB
2870 arc_anon->arcs_size + arc_mru->arcs_size > arc_p)
2871 arc_p = MIN(arc_c, arc_p + size);
2872 }
2873}
2874
2875/*
2876 * This routine is called whenever a buffer is accessed.
2877 * NOTE: the hash lock is dropped in this function.
2878 */
2879static void
2880arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock)
2881{
428870ff
BB
2882 clock_t now;
2883
34dc7c2f
BB
2884 ASSERT(MUTEX_HELD(hash_lock));
2885
2886 if (buf->b_state == arc_anon) {
2887 /*
2888 * This buffer is not in the cache, and does not
2889 * appear in our "ghost" list. Add the new buffer
2890 * to the MRU state.
2891 */
2892
2893 ASSERT(buf->b_arc_access == 0);
428870ff 2894 buf->b_arc_access = ddi_get_lbolt();
34dc7c2f
BB
2895 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2896 arc_change_state(arc_mru, buf, hash_lock);
2897
2898 } else if (buf->b_state == arc_mru) {
428870ff
BB
2899 now = ddi_get_lbolt();
2900
34dc7c2f
BB
2901 /*
2902 * If this buffer is here because of a prefetch, then either:
2903 * - clear the flag if this is a "referencing" read
2904 * (any subsequent access will bump this into the MFU state).
2905 * or
2906 * - move the buffer to the head of the list if this is
2907 * another prefetch (to make it less likely to be evicted).
2908 */
2909 if ((buf->b_flags & ARC_PREFETCH) != 0) {
2910 if (refcount_count(&buf->b_refcnt) == 0) {
2911 ASSERT(list_link_active(&buf->b_arc_node));
2912 } else {
2913 buf->b_flags &= ~ARC_PREFETCH;
e0b0ca98 2914 atomic_inc_32(&buf->b_mru_hits);
34dc7c2f
BB
2915 ARCSTAT_BUMP(arcstat_mru_hits);
2916 }
428870ff 2917 buf->b_arc_access = now;
34dc7c2f
BB
2918 return;
2919 }
2920
2921 /*
2922 * This buffer has been "accessed" only once so far,
2923 * but it is still in the cache. Move it to the MFU
2924 * state.
2925 */
0b75bdb3 2926 if (ddi_time_after(now, buf->b_arc_access + ARC_MINTIME)) {
34dc7c2f
BB
2927 /*
2928 * More than 125ms have passed since we
2929 * instantiated this buffer. Move it to the
2930 * most frequently used state.
2931 */
428870ff 2932 buf->b_arc_access = now;
34dc7c2f
BB
2933 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2934 arc_change_state(arc_mfu, buf, hash_lock);
2935 }
e0b0ca98 2936 atomic_inc_32(&buf->b_mru_hits);
34dc7c2f
BB
2937 ARCSTAT_BUMP(arcstat_mru_hits);
2938 } else if (buf->b_state == arc_mru_ghost) {
2939 arc_state_t *new_state;
2940 /*
2941 * This buffer has been "accessed" recently, but
2942 * was evicted from the cache. Move it to the
2943 * MFU state.
2944 */
2945
2946 if (buf->b_flags & ARC_PREFETCH) {
2947 new_state = arc_mru;
2948 if (refcount_count(&buf->b_refcnt) > 0)
2949 buf->b_flags &= ~ARC_PREFETCH;
2950 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2951 } else {
2952 new_state = arc_mfu;
2953 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2954 }
2955
428870ff 2956 buf->b_arc_access = ddi_get_lbolt();
34dc7c2f
BB
2957 arc_change_state(new_state, buf, hash_lock);
2958
e0b0ca98 2959 atomic_inc_32(&buf->b_mru_ghost_hits);
34dc7c2f
BB
2960 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
2961 } else if (buf->b_state == arc_mfu) {
2962 /*
2963 * This buffer has been accessed more than once and is
2964 * still in the cache. Keep it in the MFU state.
2965 *
2966 * NOTE: an add_reference() that occurred when we did
2967 * the arc_read() will have kicked this off the list.
2968 * If it was a prefetch, we will explicitly move it to
2969 * the head of the list now.
2970 */
2971 if ((buf->b_flags & ARC_PREFETCH) != 0) {
2972 ASSERT(refcount_count(&buf->b_refcnt) == 0);
2973 ASSERT(list_link_active(&buf->b_arc_node));
2974 }
e0b0ca98 2975 atomic_inc_32(&buf->b_mfu_hits);
34dc7c2f 2976 ARCSTAT_BUMP(arcstat_mfu_hits);
428870ff 2977 buf->b_arc_access = ddi_get_lbolt();
34dc7c2f
BB
2978 } else if (buf->b_state == arc_mfu_ghost) {
2979 arc_state_t *new_state = arc_mfu;
2980 /*
2981 * This buffer has been accessed more than once but has
2982 * been evicted from the cache. Move it back to the
2983 * MFU state.
2984 */
2985
2986 if (buf->b_flags & ARC_PREFETCH) {
2987 /*
2988 * This is a prefetch access...
2989 * move this block back to the MRU state.
2990 */
c99c9001 2991 ASSERT0(refcount_count(&buf->b_refcnt));
34dc7c2f
BB
2992 new_state = arc_mru;
2993 }
2994
428870ff 2995 buf->b_arc_access = ddi_get_lbolt();
34dc7c2f
BB
2996 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2997 arc_change_state(new_state, buf, hash_lock);
2998
e0b0ca98 2999 atomic_inc_32(&buf->b_mfu_ghost_hits);
34dc7c2f
BB
3000 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
3001 } else if (buf->b_state == arc_l2c_only) {
3002 /*
3003 * This buffer is on the 2nd Level ARC.
3004 */
3005
428870ff 3006 buf->b_arc_access = ddi_get_lbolt();
34dc7c2f
BB
3007 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
3008 arc_change_state(arc_mfu, buf, hash_lock);
3009 } else {
3010 ASSERT(!"invalid arc state");
3011 }
3012}
3013
3014/* a generic arc_done_func_t which you can use */
3015/* ARGSUSED */
3016void
3017arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
3018{
428870ff
BB
3019 if (zio == NULL || zio->io_error == 0)
3020 bcopy(buf->b_data, arg, buf->b_hdr->b_size);
13fe0198 3021 VERIFY(arc_buf_remove_ref(buf, arg));
34dc7c2f
BB
3022}
3023
3024/* a generic arc_done_func_t */
3025void
3026arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
3027{
3028 arc_buf_t **bufp = arg;
3029 if (zio && zio->io_error) {
13fe0198 3030 VERIFY(arc_buf_remove_ref(buf, arg));
34dc7c2f
BB
3031 *bufp = NULL;
3032 } else {
3033 *bufp = buf;
428870ff 3034 ASSERT(buf->b_data);
34dc7c2f
BB
3035 }
3036}
3037
3038static void
3039arc_read_done(zio_t *zio)
3040{
9b67f605 3041 arc_buf_hdr_t *hdr;
34dc7c2f
BB
3042 arc_buf_t *buf;
3043 arc_buf_t *abuf; /* buffer we're assigning to callback */
9b67f605 3044 kmutex_t *hash_lock = NULL;
34dc7c2f
BB
3045 arc_callback_t *callback_list, *acb;
3046 int freeable = FALSE;
3047
3048 buf = zio->io_private;
3049 hdr = buf->b_hdr;
3050
3051 /*
3052 * The hdr was inserted into hash-table and removed from lists
3053 * prior to starting I/O. We should find this header, since
3054 * it's in the hash table, and it should be legit since it's
3055 * not possible to evict it during the I/O. The only possible
3056 * reason for it not to be found is if we were freed during the
3057 * read.
3058 */
9b67f605
MA
3059 if (HDR_IN_HASH_TABLE(hdr)) {
3060 arc_buf_hdr_t *found;
3061
3062 ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
3063 ASSERT3U(hdr->b_dva.dva_word[0], ==,
3064 BP_IDENTITY(zio->io_bp)->dva_word[0]);
3065 ASSERT3U(hdr->b_dva.dva_word[1], ==,
3066 BP_IDENTITY(zio->io_bp)->dva_word[1]);
3067
3068 found = buf_hash_find(hdr->b_spa, zio->io_bp,
3069 &hash_lock);
3070
3071 ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) &&
3072 hash_lock == NULL) ||
3073 (found == hdr &&
3074 DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
3075 (found == hdr && HDR_L2_READING(hdr)));
3076 }
34dc7c2f 3077
b128c09f 3078 hdr->b_flags &= ~ARC_L2_EVICTED;
34dc7c2f 3079 if (l2arc_noprefetch && (hdr->b_flags & ARC_PREFETCH))
b128c09f 3080 hdr->b_flags &= ~ARC_L2CACHE;
34dc7c2f
BB
3081
3082 /* byteswap if necessary */
3083 callback_list = hdr->b_acb;
3084 ASSERT(callback_list != NULL);
428870ff 3085 if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
9ae529ec
CS
3086 dmu_object_byteswap_t bswap =
3087 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
b01615d5
RY
3088 if (BP_GET_LEVEL(zio->io_bp) > 0)
3089 byteswap_uint64_array(buf->b_data, hdr->b_size);
3090 else
3091 dmu_ot_byteswap[bswap].ob_func(buf->b_data, hdr->b_size);
b128c09f 3092 }
34dc7c2f
BB
3093
3094 arc_cksum_compute(buf, B_FALSE);
498877ba 3095 arc_buf_watch(buf);
34dc7c2f 3096
428870ff
BB
3097 if (hash_lock && zio->io_error == 0 && hdr->b_state == arc_anon) {
3098 /*
3099 * Only call arc_access on anonymous buffers. This is because
3100 * if we've issued an I/O for an evicted buffer, we've already
3101 * called arc_access (to prevent any simultaneous readers from
3102 * getting confused).
3103 */
3104 arc_access(hdr, hash_lock);
3105 }
3106
34dc7c2f
BB
3107 /* create copies of the data buffer for the callers */
3108 abuf = buf;
3109 for (acb = callback_list; acb; acb = acb->acb_next) {
3110 if (acb->acb_done) {
1eb5bfa3
GW
3111 if (abuf == NULL) {
3112 ARCSTAT_BUMP(arcstat_duplicate_reads);
34dc7c2f 3113 abuf = arc_buf_clone(buf);
1eb5bfa3 3114 }
34dc7c2f
BB
3115 acb->acb_buf = abuf;
3116 abuf = NULL;
3117 }
3118 }
3119 hdr->b_acb = NULL;
3120 hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3121 ASSERT(!HDR_BUF_AVAILABLE(hdr));
428870ff
BB
3122 if (abuf == buf) {
3123 ASSERT(buf->b_efunc == NULL);
3124 ASSERT(hdr->b_datacnt == 1);
34dc7c2f 3125 hdr->b_flags |= ARC_BUF_AVAILABLE;
428870ff 3126 }
34dc7c2f
BB
3127
3128 ASSERT(refcount_is_zero(&hdr->b_refcnt) || callback_list != NULL);
3129
3130 if (zio->io_error != 0) {
3131 hdr->b_flags |= ARC_IO_ERROR;
3132 if (hdr->b_state != arc_anon)
3133 arc_change_state(arc_anon, hdr, hash_lock);
3134 if (HDR_IN_HASH_TABLE(hdr))
3135 buf_hash_remove(hdr);
3136 freeable = refcount_is_zero(&hdr->b_refcnt);
34dc7c2f
BB
3137 }
3138
3139 /*
3140 * Broadcast before we drop the hash_lock to avoid the possibility
3141 * that the hdr (and hence the cv) might be freed before we get to
3142 * the cv_broadcast().
3143 */
3144 cv_broadcast(&hdr->b_cv);
3145
3146 if (hash_lock) {
34dc7c2f
BB
3147 mutex_exit(hash_lock);
3148 } else {
3149 /*
3150 * This block was freed while we waited for the read to
3151 * complete. It has been removed from the hash table and
3152 * moved to the anonymous state (so that it won't show up
3153 * in the cache).
3154 */
3155 ASSERT3P(hdr->b_state, ==, arc_anon);
3156 freeable = refcount_is_zero(&hdr->b_refcnt);
3157 }
3158
3159 /* execute each callback and free its structure */
3160 while ((acb = callback_list) != NULL) {
3161 if (acb->acb_done)
3162 acb->acb_done(zio, acb->acb_buf, acb->acb_private);
3163
3164 if (acb->acb_zio_dummy != NULL) {
3165 acb->acb_zio_dummy->io_error = zio->io_error;
3166 zio_nowait(acb->acb_zio_dummy);
3167 }
3168
3169 callback_list = acb->acb_next;
3170 kmem_free(acb, sizeof (arc_callback_t));
3171 }
3172
3173 if (freeable)
3174 arc_hdr_destroy(hdr);
3175}
3176
3177/*
5c839890 3178 * "Read" the block at the specified DVA (in bp) via the
34dc7c2f
BB
3179 * cache. If the block is found in the cache, invoke the provided
3180 * callback immediately and return. Note that the `zio' parameter
3181 * in the callback will be NULL in this case, since no IO was
3182 * required. If the block is not in the cache pass the read request
3183 * on to the spa with a substitute callback function, so that the
3184 * requested block will be added to the cache.
3185 *
3186 * If a read request arrives for a block that has a read in-progress,
3187 * either wait for the in-progress read to complete (and return the
3188 * results); or, if this is a read with a "done" func, add a record
3189 * to the read to invoke the "done" func when the read completes,
3190 * and return; or just return.
3191 *
3192 * arc_read_done() will invoke all the requested "done" functions
3193 * for readers of this block.
3194 */
3195int
294f6806 3196arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
e8b96c60 3197 void *private, zio_priority_t priority, int zio_flags, uint32_t *arc_flags,
294f6806 3198 const zbookmark_t *zb)
34dc7c2f 3199{
9b67f605 3200 arc_buf_hdr_t *hdr = NULL;
d4ed6673 3201 arc_buf_t *buf = NULL;
9b67f605 3202 kmutex_t *hash_lock = NULL;
34dc7c2f 3203 zio_t *rzio;
3541dc6d 3204 uint64_t guid = spa_load_guid(spa);
1421c891 3205 int rc = 0;
34dc7c2f 3206
9b67f605
MA
3207 ASSERT(!BP_IS_EMBEDDED(bp) ||
3208 BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
3209
34dc7c2f 3210top:
9b67f605
MA
3211 if (!BP_IS_EMBEDDED(bp)) {
3212 /*
3213 * Embedded BP's have no DVA and require no I/O to "read".
3214 * Create an anonymous arc buf to back it.
3215 */
3216 hdr = buf_hash_find(guid, bp, &hash_lock);
3217 }
3218
3219 if (hdr != NULL && hdr->b_datacnt > 0) {
34dc7c2f
BB
3220
3221 *arc_flags |= ARC_CACHED;
3222
3223 if (HDR_IO_IN_PROGRESS(hdr)) {
3224
3225 if (*arc_flags & ARC_WAIT) {
3226 cv_wait(&hdr->b_cv, hash_lock);
3227 mutex_exit(hash_lock);
3228 goto top;
3229 }
3230 ASSERT(*arc_flags & ARC_NOWAIT);
3231
3232 if (done) {
3233 arc_callback_t *acb = NULL;
3234
3235 acb = kmem_zalloc(sizeof (arc_callback_t),
691f6ac4 3236 KM_PUSHPAGE);
34dc7c2f
BB
3237 acb->acb_done = done;
3238 acb->acb_private = private;
34dc7c2f
BB
3239 if (pio != NULL)
3240 acb->acb_zio_dummy = zio_null(pio,
d164b209 3241 spa, NULL, NULL, NULL, zio_flags);
34dc7c2f
BB
3242
3243 ASSERT(acb->acb_done != NULL);
3244 acb->acb_next = hdr->b_acb;
3245 hdr->b_acb = acb;
3246 add_reference(hdr, hash_lock, private);
3247 mutex_exit(hash_lock);
1421c891 3248 goto out;
34dc7c2f
BB
3249 }
3250 mutex_exit(hash_lock);
1421c891 3251 goto out;
34dc7c2f
BB
3252 }
3253
3254 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3255
3256 if (done) {
3257 add_reference(hdr, hash_lock, private);
3258 /*
3259 * If this block is already in use, create a new
3260 * copy of the data so that we will be guaranteed
3261 * that arc_release() will always succeed.
3262 */
3263 buf = hdr->b_buf;
3264 ASSERT(buf);
3265 ASSERT(buf->b_data);
3266 if (HDR_BUF_AVAILABLE(hdr)) {
3267 ASSERT(buf->b_efunc == NULL);
3268 hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3269 } else {
3270 buf = arc_buf_clone(buf);
3271 }
428870ff 3272
34dc7c2f
BB
3273 } else if (*arc_flags & ARC_PREFETCH &&
3274 refcount_count(&hdr->b_refcnt) == 0) {
3275 hdr->b_flags |= ARC_PREFETCH;
3276 }
3277 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
3278 arc_access(hdr, hash_lock);
b128c09f
BB
3279 if (*arc_flags & ARC_L2CACHE)
3280 hdr->b_flags |= ARC_L2CACHE;
3a17a7a9
SK
3281 if (*arc_flags & ARC_L2COMPRESS)
3282 hdr->b_flags |= ARC_L2COMPRESS;
34dc7c2f
BB
3283 mutex_exit(hash_lock);
3284 ARCSTAT_BUMP(arcstat_hits);
3285 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
3286 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3287 data, metadata, hits);
3288
3289 if (done)
3290 done(NULL, buf, private);
3291 } else {
3292 uint64_t size = BP_GET_LSIZE(bp);
9b67f605 3293 arc_callback_t *acb;
b128c09f 3294 vdev_t *vd = NULL;
a117a6d6 3295 uint64_t addr = 0;
d164b209 3296 boolean_t devw = B_FALSE;
0ed212dc
BP
3297 enum zio_compress b_compress = ZIO_COMPRESS_OFF;
3298 uint64_t b_asize = 0;
34dc7c2f
BB
3299
3300 if (hdr == NULL) {
3301 /* this block is not in the cache */
9b67f605 3302 arc_buf_hdr_t *exists = NULL;
34dc7c2f
BB
3303 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
3304 buf = arc_buf_alloc(spa, size, private, type);
3305 hdr = buf->b_hdr;
9b67f605
MA
3306 if (!BP_IS_EMBEDDED(bp)) {
3307 hdr->b_dva = *BP_IDENTITY(bp);
3308 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
3309 hdr->b_cksum0 = bp->blk_cksum.zc_word[0];
3310 exists = buf_hash_insert(hdr, &hash_lock);
3311 }
3312 if (exists != NULL) {
34dc7c2f
BB
3313 /* somebody beat us to the hash insert */
3314 mutex_exit(hash_lock);
428870ff 3315 buf_discard_identity(hdr);
34dc7c2f
BB
3316 (void) arc_buf_remove_ref(buf, private);
3317 goto top; /* restart the IO request */
3318 }
3319 /* if this is a prefetch, we don't have a reference */
3320 if (*arc_flags & ARC_PREFETCH) {
3321 (void) remove_reference(hdr, hash_lock,
3322 private);
3323 hdr->b_flags |= ARC_PREFETCH;
3324 }
b128c09f
BB
3325 if (*arc_flags & ARC_L2CACHE)
3326 hdr->b_flags |= ARC_L2CACHE;
3a17a7a9
SK
3327 if (*arc_flags & ARC_L2COMPRESS)
3328 hdr->b_flags |= ARC_L2COMPRESS;
34dc7c2f
BB
3329 if (BP_GET_LEVEL(bp) > 0)
3330 hdr->b_flags |= ARC_INDIRECT;
3331 } else {
3332 /* this block is in the ghost cache */
3333 ASSERT(GHOST_STATE(hdr->b_state));
3334 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
c99c9001 3335 ASSERT0(refcount_count(&hdr->b_refcnt));
34dc7c2f
BB
3336 ASSERT(hdr->b_buf == NULL);
3337
3338 /* if this is a prefetch, we don't have a reference */
3339 if (*arc_flags & ARC_PREFETCH)
3340 hdr->b_flags |= ARC_PREFETCH;
3341 else
3342 add_reference(hdr, hash_lock, private);
b128c09f
BB
3343 if (*arc_flags & ARC_L2CACHE)
3344 hdr->b_flags |= ARC_L2CACHE;
3a17a7a9
SK
3345 if (*arc_flags & ARC_L2COMPRESS)
3346 hdr->b_flags |= ARC_L2COMPRESS;
34dc7c2f
BB
3347 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
3348 buf->b_hdr = hdr;
3349 buf->b_data = NULL;
3350 buf->b_efunc = NULL;
3351 buf->b_private = NULL;
3352 buf->b_next = NULL;
3353 hdr->b_buf = buf;
34dc7c2f
BB
3354 ASSERT(hdr->b_datacnt == 0);
3355 hdr->b_datacnt = 1;
428870ff
BB
3356 arc_get_data_buf(buf);
3357 arc_access(hdr, hash_lock);
34dc7c2f
BB
3358 }
3359
428870ff
BB
3360 ASSERT(!GHOST_STATE(hdr->b_state));
3361
691f6ac4 3362 acb = kmem_zalloc(sizeof (arc_callback_t), KM_PUSHPAGE);
34dc7c2f
BB
3363 acb->acb_done = done;
3364 acb->acb_private = private;
34dc7c2f
BB
3365
3366 ASSERT(hdr->b_acb == NULL);
3367 hdr->b_acb = acb;
3368 hdr->b_flags |= ARC_IO_IN_PROGRESS;
3369
0ed212dc 3370 if (hdr->b_l2hdr != NULL &&
b128c09f 3371 (vd = hdr->b_l2hdr->b_dev->l2ad_vdev) != NULL) {
d164b209 3372 devw = hdr->b_l2hdr->b_dev->l2ad_writing;
b128c09f 3373 addr = hdr->b_l2hdr->b_daddr;
0ed212dc
BP
3374 b_compress = hdr->b_l2hdr->b_compress;
3375 b_asize = hdr->b_l2hdr->b_asize;
b128c09f
BB
3376 /*
3377 * Lock out device removal.
3378 */
3379 if (vdev_is_dead(vd) ||
3380 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
3381 vd = NULL;
3382 }
3383
9b67f605
MA
3384 if (hash_lock != NULL)
3385 mutex_exit(hash_lock);
b128c09f 3386
e49f1e20
WA
3387 /*
3388 * At this point, we have a level 1 cache miss. Try again in
3389 * L2ARC if possible.
3390 */
34dc7c2f 3391 ASSERT3U(hdr->b_size, ==, size);
428870ff
BB
3392 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
3393 uint64_t, size, zbookmark_t *, zb);
34dc7c2f
BB
3394 ARCSTAT_BUMP(arcstat_misses);
3395 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
3396 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3397 data, metadata, misses);
3398
d164b209 3399 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
34dc7c2f
BB
3400 /*
3401 * Read from the L2ARC if the following are true:
b128c09f
BB
3402 * 1. The L2ARC vdev was previously cached.
3403 * 2. This buffer still has L2ARC metadata.
3404 * 3. This buffer isn't currently writing to the L2ARC.
3405 * 4. The L2ARC entry wasn't evicted, which may
3406 * also have invalidated the vdev.
d164b209 3407 * 5. This isn't prefetch and l2arc_noprefetch is set.
34dc7c2f 3408 */
b128c09f 3409 if (hdr->b_l2hdr != NULL &&
d164b209
BB
3410 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
3411 !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
34dc7c2f
BB
3412 l2arc_read_callback_t *cb;
3413
3414 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
3415 ARCSTAT_BUMP(arcstat_l2_hits);
e0b0ca98 3416 atomic_inc_32(&hdr->b_l2hdr->b_hits);
34dc7c2f 3417
34dc7c2f 3418 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
691f6ac4 3419 KM_PUSHPAGE);
34dc7c2f
BB
3420 cb->l2rcb_buf = buf;
3421 cb->l2rcb_spa = spa;
3422 cb->l2rcb_bp = *bp;
3423 cb->l2rcb_zb = *zb;
b128c09f 3424 cb->l2rcb_flags = zio_flags;
0ed212dc 3425 cb->l2rcb_compress = b_compress;
34dc7c2f 3426
a117a6d6
GW
3427 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
3428 addr + size < vd->vdev_psize -
3429 VDEV_LABEL_END_SIZE);
3430
34dc7c2f 3431 /*
b128c09f
BB
3432 * l2arc read. The SCL_L2ARC lock will be
3433 * released by l2arc_read_done().
3a17a7a9
SK
3434 * Issue a null zio if the underlying buffer
3435 * was squashed to zero size by compression.
34dc7c2f 3436 */
0ed212dc 3437 if (b_compress == ZIO_COMPRESS_EMPTY) {
3a17a7a9
SK
3438 rzio = zio_null(pio, spa, vd,
3439 l2arc_read_done, cb,
3440 zio_flags | ZIO_FLAG_DONT_CACHE |
3441 ZIO_FLAG_CANFAIL |
3442 ZIO_FLAG_DONT_PROPAGATE |
3443 ZIO_FLAG_DONT_RETRY);
3444 } else {
3445 rzio = zio_read_phys(pio, vd, addr,
0ed212dc
BP
3446 b_asize, buf->b_data,
3447 ZIO_CHECKSUM_OFF,
3a17a7a9
SK
3448 l2arc_read_done, cb, priority,
3449 zio_flags | ZIO_FLAG_DONT_CACHE |
3450 ZIO_FLAG_CANFAIL |
3451 ZIO_FLAG_DONT_PROPAGATE |
3452 ZIO_FLAG_DONT_RETRY, B_FALSE);
3453 }
34dc7c2f
BB
3454 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
3455 zio_t *, rzio);
0ed212dc 3456 ARCSTAT_INCR(arcstat_l2_read_bytes, b_asize);
34dc7c2f 3457
b128c09f
BB
3458 if (*arc_flags & ARC_NOWAIT) {
3459 zio_nowait(rzio);
1421c891 3460 goto out;
b128c09f 3461 }
34dc7c2f 3462
b128c09f
BB
3463 ASSERT(*arc_flags & ARC_WAIT);
3464 if (zio_wait(rzio) == 0)
1421c891 3465 goto out;
b128c09f
BB
3466
3467 /* l2arc read error; goto zio_read() */
34dc7c2f
BB
3468 } else {
3469 DTRACE_PROBE1(l2arc__miss,
3470 arc_buf_hdr_t *, hdr);
3471 ARCSTAT_BUMP(arcstat_l2_misses);
3472 if (HDR_L2_WRITING(hdr))
3473 ARCSTAT_BUMP(arcstat_l2_rw_clash);
b128c09f 3474 spa_config_exit(spa, SCL_L2ARC, vd);
34dc7c2f 3475 }
d164b209
BB
3476 } else {
3477 if (vd != NULL)
3478 spa_config_exit(spa, SCL_L2ARC, vd);
3479 if (l2arc_ndev != 0) {
3480 DTRACE_PROBE1(l2arc__miss,
3481 arc_buf_hdr_t *, hdr);
3482 ARCSTAT_BUMP(arcstat_l2_misses);
3483 }
34dc7c2f 3484 }
34dc7c2f
BB
3485
3486 rzio = zio_read(pio, spa, bp, buf->b_data, size,
b128c09f 3487 arc_read_done, buf, priority, zio_flags, zb);
34dc7c2f 3488
1421c891
PS
3489 if (*arc_flags & ARC_WAIT) {
3490 rc = zio_wait(rzio);
3491 goto out;
3492 }
34dc7c2f
BB
3493
3494 ASSERT(*arc_flags & ARC_NOWAIT);
3495 zio_nowait(rzio);
3496 }
1421c891
PS
3497
3498out:
3499 spa_read_history_add(spa, zb, *arc_flags);
3500 return (rc);
34dc7c2f
BB
3501}
3502
ab26409d
BB
3503arc_prune_t *
3504arc_add_prune_callback(arc_prune_func_t *func, void *private)
3505{
3506 arc_prune_t *p;
3507
d1d7e268 3508 p = kmem_alloc(sizeof (*p), KM_SLEEP);
ab26409d
BB
3509 p->p_pfunc = func;
3510 p->p_private = private;
3511 list_link_init(&p->p_node);
3512 refcount_create(&p->p_refcnt);
3513
3514 mutex_enter(&arc_prune_mtx);
3515 refcount_add(&p->p_refcnt, &arc_prune_list);
3516 list_insert_head(&arc_prune_list, p);
3517 mutex_exit(&arc_prune_mtx);
3518
3519 return (p);
3520}
3521
3522void
3523arc_remove_prune_callback(arc_prune_t *p)
3524{
3525 mutex_enter(&arc_prune_mtx);
3526 list_remove(&arc_prune_list, p);
3527 if (refcount_remove(&p->p_refcnt, &arc_prune_list) == 0) {
3528 refcount_destroy(&p->p_refcnt);
3529 kmem_free(p, sizeof (*p));
3530 }
3531 mutex_exit(&arc_prune_mtx);
3532}
3533
34dc7c2f
BB
3534void
3535arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
3536{
3537 ASSERT(buf->b_hdr != NULL);
3538 ASSERT(buf->b_hdr->b_state != arc_anon);
3539 ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt) || func == NULL);
428870ff
BB
3540 ASSERT(buf->b_efunc == NULL);
3541 ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
3542
34dc7c2f
BB
3543 buf->b_efunc = func;
3544 buf->b_private = private;
3545}
3546
df4474f9
MA
3547/*
3548 * Notify the arc that a block was freed, and thus will never be used again.
3549 */
3550void
3551arc_freed(spa_t *spa, const blkptr_t *bp)
3552{
3553 arc_buf_hdr_t *hdr;
3554 kmutex_t *hash_lock;
3555 uint64_t guid = spa_load_guid(spa);
3556
9b67f605
MA
3557 ASSERT(!BP_IS_EMBEDDED(bp));
3558
3559 hdr = buf_hash_find(guid, bp, &hash_lock);
df4474f9
MA
3560 if (hdr == NULL)
3561 return;
3562 if (HDR_BUF_AVAILABLE(hdr)) {
3563 arc_buf_t *buf = hdr->b_buf;
3564 add_reference(hdr, hash_lock, FTAG);
3565 hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3566 mutex_exit(hash_lock);
3567
3568 arc_release(buf, FTAG);
3569 (void) arc_buf_remove_ref(buf, FTAG);
3570 } else {
3571 mutex_exit(hash_lock);
3572 }
3573
3574}
3575
34dc7c2f
BB
3576/*
3577 * This is used by the DMU to let the ARC know that a buffer is
3578 * being evicted, so the ARC should clean up. If this arc buf
3579 * is not yet in the evicted state, it will be put there.
3580 */
3581int
3582arc_buf_evict(arc_buf_t *buf)
3583{
3584 arc_buf_hdr_t *hdr;
3585 kmutex_t *hash_lock;
3586 arc_buf_t **bufp;
3587
428870ff 3588 mutex_enter(&buf->b_evict_lock);
34dc7c2f
BB
3589 hdr = buf->b_hdr;
3590 if (hdr == NULL) {
3591 /*
3592 * We are in arc_do_user_evicts().
3593 */
3594 ASSERT(buf->b_data == NULL);
428870ff 3595 mutex_exit(&buf->b_evict_lock);
34dc7c2f 3596 return (0);
b128c09f
BB
3597 } else if (buf->b_data == NULL) {
3598 arc_buf_t copy = *buf; /* structure assignment */
34dc7c2f 3599 /*
b128c09f
BB
3600 * We are on the eviction list; process this buffer now
3601 * but let arc_do_user_evicts() do the reaping.
34dc7c2f 3602 */
b128c09f 3603 buf->b_efunc = NULL;
428870ff 3604 mutex_exit(&buf->b_evict_lock);
b128c09f
BB
3605 VERIFY(copy.b_efunc(&copy) == 0);
3606 return (1);
34dc7c2f 3607 }
b128c09f
BB
3608 hash_lock = HDR_LOCK(hdr);
3609 mutex_enter(hash_lock);
428870ff
BB
3610 hdr = buf->b_hdr;
3611 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
34dc7c2f 3612
34dc7c2f
BB
3613 ASSERT3U(refcount_count(&hdr->b_refcnt), <, hdr->b_datacnt);
3614 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3615
3616 /*
3617 * Pull this buffer off of the hdr
3618 */
3619 bufp = &hdr->b_buf;
3620 while (*bufp != buf)
3621 bufp = &(*bufp)->b_next;
3622 *bufp = buf->b_next;
3623
3624 ASSERT(buf->b_data != NULL);
3625 arc_buf_destroy(buf, FALSE, FALSE);
3626
3627 if (hdr->b_datacnt == 0) {
3628 arc_state_t *old_state = hdr->b_state;
3629 arc_state_t *evicted_state;
3630
428870ff 3631 ASSERT(hdr->b_buf == NULL);
34dc7c2f
BB
3632 ASSERT(refcount_is_zero(&hdr->b_refcnt));
3633
3634 evicted_state =
3635 (old_state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
3636
3637 mutex_enter(&old_state->arcs_mtx);
3638 mutex_enter(&evicted_state->arcs_mtx);
3639
3640 arc_change_state(evicted_state, hdr, hash_lock);
3641 ASSERT(HDR_IN_HASH_TABLE(hdr));
3642 hdr->b_flags |= ARC_IN_HASH_TABLE;
3643 hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3644
3645 mutex_exit(&evicted_state->arcs_mtx);
3646 mutex_exit(&old_state->arcs_mtx);
3647 }
3648 mutex_exit(hash_lock);
428870ff 3649 mutex_exit(&buf->b_evict_lock);
34dc7c2f
BB
3650
3651 VERIFY(buf->b_efunc(buf) == 0);
3652 buf->b_efunc = NULL;
3653 buf->b_private = NULL;
3654 buf->b_hdr = NULL;
428870ff 3655 buf->b_next = NULL;
34dc7c2f
BB
3656 kmem_cache_free(buf_cache, buf);
3657 return (1);
3658}
3659
3660/*
e49f1e20
WA
3661 * Release this buffer from the cache, making it an anonymous buffer. This
3662 * must be done after a read and prior to modifying the buffer contents.
34dc7c2f 3663 * If the buffer has more than one reference, we must make
b128c09f 3664 * a new hdr for the buffer.
34dc7c2f
BB
3665 */
3666void
3667arc_release(arc_buf_t *buf, void *tag)
3668{
b128c09f 3669 arc_buf_hdr_t *hdr;
428870ff 3670 kmutex_t *hash_lock = NULL;
b128c09f 3671 l2arc_buf_hdr_t *l2hdr;
d4ed6673 3672 uint64_t buf_size = 0;
34dc7c2f 3673
428870ff
BB
3674 /*
3675 * It would be nice to assert that if it's DMU metadata (level >
3676 * 0 || it's the dnode file), then it must be syncing context.
3677 * But we don't know that information at this level.
3678 */
3679
3680 mutex_enter(&buf->b_evict_lock);
b128c09f
BB
3681 hdr = buf->b_hdr;
3682
34dc7c2f
BB
3683 /* this buffer is not on any list */
3684 ASSERT(refcount_count(&hdr->b_refcnt) > 0);
3685
3686 if (hdr->b_state == arc_anon) {
3687 /* this buffer is already released */
34dc7c2f 3688 ASSERT(buf->b_efunc == NULL);
9babb374
BB
3689 } else {
3690 hash_lock = HDR_LOCK(hdr);
3691 mutex_enter(hash_lock);
428870ff
BB
3692 hdr = buf->b_hdr;
3693 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
34dc7c2f
BB
3694 }
3695
b128c09f
BB
3696 l2hdr = hdr->b_l2hdr;
3697 if (l2hdr) {
3698 mutex_enter(&l2arc_buflist_mtx);
3699 hdr->b_l2hdr = NULL;
47fe91b5 3700 list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
b128c09f 3701 }
a117a6d6 3702 buf_size = hdr->b_size;
b128c09f 3703
34dc7c2f
BB
3704 /*
3705 * Do we have more than one buf?
3706 */
b128c09f 3707 if (hdr->b_datacnt > 1) {
34dc7c2f
BB
3708 arc_buf_hdr_t *nhdr;
3709 arc_buf_t **bufp;
3710 uint64_t blksz = hdr->b_size;
d164b209 3711 uint64_t spa = hdr->b_spa;
34dc7c2f
BB
3712 arc_buf_contents_t type = hdr->b_type;
3713 uint32_t flags = hdr->b_flags;
3714
b128c09f 3715 ASSERT(hdr->b_buf != buf || buf->b_next != NULL);
34dc7c2f 3716 /*
428870ff
BB
3717 * Pull the data off of this hdr and attach it to
3718 * a new anonymous hdr.
34dc7c2f
BB
3719 */
3720 (void) remove_reference(hdr, hash_lock, tag);
3721 bufp = &hdr->b_buf;
3722 while (*bufp != buf)
3723 bufp = &(*bufp)->b_next;
428870ff 3724 *bufp = buf->b_next;
34dc7c2f
BB
3725 buf->b_next = NULL;
3726
3727 ASSERT3U(hdr->b_state->arcs_size, >=, hdr->b_size);
3728 atomic_add_64(&hdr->b_state->arcs_size, -hdr->b_size);
3729 if (refcount_is_zero(&hdr->b_refcnt)) {
3730 uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
3731 ASSERT3U(*size, >=, hdr->b_size);
3732 atomic_add_64(size, -hdr->b_size);
3733 }
1eb5bfa3
GW
3734
3735 /*
3736 * We're releasing a duplicate user data buffer, update
3737 * our statistics accordingly.
3738 */
3739 if (hdr->b_type == ARC_BUFC_DATA) {
3740 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
3741 ARCSTAT_INCR(arcstat_duplicate_buffers_size,
3742 -hdr->b_size);
3743 }
34dc7c2f 3744 hdr->b_datacnt -= 1;
34dc7c2f 3745 arc_cksum_verify(buf);
498877ba 3746 arc_buf_unwatch(buf);
34dc7c2f
BB
3747
3748 mutex_exit(hash_lock);
3749
3750 nhdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
3751 nhdr->b_size = blksz;
3752 nhdr->b_spa = spa;
3753 nhdr->b_type = type;
3754 nhdr->b_buf = buf;
3755 nhdr->b_state = arc_anon;
3756 nhdr->b_arc_access = 0;
e0b0ca98
BB
3757 nhdr->b_mru_hits = 0;
3758 nhdr->b_mru_ghost_hits = 0;
3759 nhdr->b_mfu_hits = 0;
3760 nhdr->b_mfu_ghost_hits = 0;
3761 nhdr->b_l2_hits = 0;
34dc7c2f
BB
3762 nhdr->b_flags = flags & ARC_L2_WRITING;
3763 nhdr->b_l2hdr = NULL;
3764 nhdr->b_datacnt = 1;
3765 nhdr->b_freeze_cksum = NULL;
3766 (void) refcount_add(&nhdr->b_refcnt, tag);
3767 buf->b_hdr = nhdr;
428870ff 3768 mutex_exit(&buf->b_evict_lock);
34dc7c2f
BB
3769 atomic_add_64(&arc_anon->arcs_size, blksz);
3770 } else {
428870ff 3771 mutex_exit(&buf->b_evict_lock);
34dc7c2f
BB
3772 ASSERT(refcount_count(&hdr->b_refcnt) == 1);
3773 ASSERT(!list_link_active(&hdr->b_arc_node));
3774 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
428870ff
BB
3775 if (hdr->b_state != arc_anon)
3776 arc_change_state(arc_anon, hdr, hash_lock);
34dc7c2f 3777 hdr->b_arc_access = 0;
e0b0ca98
BB
3778 hdr->b_mru_hits = 0;
3779 hdr->b_mru_ghost_hits = 0;
3780 hdr->b_mfu_hits = 0;
3781 hdr->b_mfu_ghost_hits = 0;
3782 hdr->b_l2_hits = 0;
428870ff
BB
3783 if (hash_lock)
3784 mutex_exit(hash_lock);
34dc7c2f 3785
428870ff 3786 buf_discard_identity(hdr);
34dc7c2f
BB
3787 arc_buf_thaw(buf);
3788 }
3789 buf->b_efunc = NULL;
3790 buf->b_private = NULL;
3791
3792 if (l2hdr) {
3a17a7a9 3793 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
ecf3d9b8 3794 kmem_cache_free(l2arc_hdr_cache, l2hdr);
6e1d7276 3795 arc_space_return(L2HDR_SIZE, ARC_SPACE_L2HDRS);
34dc7c2f 3796 ARCSTAT_INCR(arcstat_l2_size, -buf_size);
34dc7c2f 3797 mutex_exit(&l2arc_buflist_mtx);
b128c09f 3798 }
34dc7c2f
BB
3799}
3800
3801int
3802arc_released(arc_buf_t *buf)
3803{
b128c09f
BB
3804 int released;
3805
428870ff 3806 mutex_enter(&buf->b_evict_lock);
b128c09f 3807 released = (buf->b_data != NULL && buf->b_hdr->b_state == arc_anon);
428870ff 3808 mutex_exit(&buf->b_evict_lock);
b128c09f 3809 return (released);
34dc7c2f
BB
3810}
3811
3812int
3813arc_has_callback(arc_buf_t *buf)
3814{
b128c09f
BB
3815 int callback;
3816
428870ff 3817 mutex_enter(&buf->b_evict_lock);
b128c09f 3818 callback = (buf->b_efunc != NULL);
428870ff 3819 mutex_exit(&buf->b_evict_lock);
b128c09f 3820 return (callback);
34dc7c2f
BB
3821}
3822
3823#ifdef ZFS_DEBUG
3824int
3825arc_referenced(arc_buf_t *buf)
3826{
b128c09f
BB
3827 int referenced;
3828
428870ff 3829 mutex_enter(&buf->b_evict_lock);
b128c09f 3830 referenced = (refcount_count(&buf->b_hdr->b_refcnt));
428870ff 3831 mutex_exit(&buf->b_evict_lock);
b128c09f 3832 return (referenced);
34dc7c2f
BB
3833}
3834#endif
3835
3836static void
3837arc_write_ready(zio_t *zio)
3838{
3839 arc_write_callback_t *callback = zio->io_private;
3840 arc_buf_t *buf = callback->awcb_buf;
3841 arc_buf_hdr_t *hdr = buf->b_hdr;
3842
b128c09f
BB
3843 ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt));
3844 callback->awcb_ready(zio, buf, callback->awcb_private);
3845
34dc7c2f
BB
3846 /*
3847 * If the IO is already in progress, then this is a re-write
b128c09f
BB
3848 * attempt, so we need to thaw and re-compute the cksum.
3849 * It is the responsibility of the callback to handle the
3850 * accounting for any re-write attempt.
34dc7c2f
BB
3851 */
3852 if (HDR_IO_IN_PROGRESS(hdr)) {
34dc7c2f
BB
3853 mutex_enter(&hdr->b_freeze_lock);
3854 if (hdr->b_freeze_cksum != NULL) {
3855 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
3856 hdr->b_freeze_cksum = NULL;
3857 }
3858 mutex_exit(&hdr->b_freeze_lock);
3859 }
3860 arc_cksum_compute(buf, B_FALSE);
3861 hdr->b_flags |= ARC_IO_IN_PROGRESS;
3862}
3863
e8b96c60
MA
3864/*
3865 * The SPA calls this callback for each physical write that happens on behalf
3866 * of a logical write. See the comment in dbuf_write_physdone() for details.
3867 */
3868static void
3869arc_write_physdone(zio_t *zio)
3870{
3871 arc_write_callback_t *cb = zio->io_private;
3872 if (cb->awcb_physdone != NULL)
3873 cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
3874}
3875
34dc7c2f
BB
3876static void
3877arc_write_done(zio_t *zio)
3878{
3879 arc_write_callback_t *callback = zio->io_private;
3880 arc_buf_t *buf = callback->awcb_buf;
3881 arc_buf_hdr_t *hdr = buf->b_hdr;
3882
428870ff
BB
3883 ASSERT(hdr->b_acb == NULL);
3884
3885 if (zio->io_error == 0) {
9b67f605 3886 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
b0bc7a84
MG
3887 buf_discard_identity(hdr);
3888 } else {
3889 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
3890 hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
3891 hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
3892 }
428870ff
BB
3893 } else {
3894 ASSERT(BUF_EMPTY(hdr));
3895 }
34dc7c2f 3896
34dc7c2f 3897 /*
9b67f605
MA
3898 * If the block to be written was all-zero or compressed enough to be
3899 * embedded in the BP, no write was performed so there will be no
3900 * dva/birth/checksum. The buffer must therefore remain anonymous
3901 * (and uncached).
34dc7c2f
BB
3902 */
3903 if (!BUF_EMPTY(hdr)) {
3904 arc_buf_hdr_t *exists;
3905 kmutex_t *hash_lock;
3906
428870ff
BB
3907 ASSERT(zio->io_error == 0);
3908
34dc7c2f
BB
3909 arc_cksum_verify(buf);
3910
3911 exists = buf_hash_insert(hdr, &hash_lock);
3912 if (exists) {
3913 /*
3914 * This can only happen if we overwrite for
3915 * sync-to-convergence, because we remove
3916 * buffers from the hash table when we arc_free().
3917 */
428870ff
BB
3918 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
3919 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3920 panic("bad overwrite, hdr=%p exists=%p",
3921 (void *)hdr, (void *)exists);
3922 ASSERT(refcount_is_zero(&exists->b_refcnt));
3923 arc_change_state(arc_anon, exists, hash_lock);
3924 mutex_exit(hash_lock);
3925 arc_hdr_destroy(exists);
3926 exists = buf_hash_insert(hdr, &hash_lock);
3927 ASSERT3P(exists, ==, NULL);
03c6040b
GW
3928 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
3929 /* nopwrite */
3930 ASSERT(zio->io_prop.zp_nopwrite);
3931 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3932 panic("bad nopwrite, hdr=%p exists=%p",
3933 (void *)hdr, (void *)exists);
428870ff
BB
3934 } else {
3935 /* Dedup */
3936 ASSERT(hdr->b_datacnt == 1);
3937 ASSERT(hdr->b_state == arc_anon);
3938 ASSERT(BP_GET_DEDUP(zio->io_bp));
3939 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
3940 }
34dc7c2f
BB
3941 }
3942 hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
b128c09f 3943 /* if it's not anon, we are doing a scrub */
428870ff 3944 if (!exists && hdr->b_state == arc_anon)
b128c09f 3945 arc_access(hdr, hash_lock);
34dc7c2f 3946 mutex_exit(hash_lock);
34dc7c2f
BB
3947 } else {
3948 hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3949 }
3950
428870ff
BB
3951 ASSERT(!refcount_is_zero(&hdr->b_refcnt));
3952 callback->awcb_done(zio, buf, callback->awcb_private);
34dc7c2f
BB
3953
3954 kmem_free(callback, sizeof (arc_write_callback_t));
3955}
3956
3957zio_t *
428870ff 3958arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
3a17a7a9 3959 blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
e8b96c60
MA
3960 const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *physdone,
3961 arc_done_func_t *done, void *private, zio_priority_t priority,
3962 int zio_flags, const zbookmark_t *zb)
34dc7c2f
BB
3963{
3964 arc_buf_hdr_t *hdr = buf->b_hdr;
3965 arc_write_callback_t *callback;
b128c09f 3966 zio_t *zio;
34dc7c2f 3967
b128c09f 3968 ASSERT(ready != NULL);
428870ff 3969 ASSERT(done != NULL);
34dc7c2f
BB
3970 ASSERT(!HDR_IO_ERROR(hdr));
3971 ASSERT((hdr->b_flags & ARC_IO_IN_PROGRESS) == 0);
428870ff 3972 ASSERT(hdr->b_acb == NULL);
b128c09f
BB
3973 if (l2arc)
3974 hdr->b_flags |= ARC_L2CACHE;
3a17a7a9
SK
3975 if (l2arc_compress)
3976 hdr->b_flags |= ARC_L2COMPRESS;
b8d06fca 3977 callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_PUSHPAGE);
34dc7c2f 3978 callback->awcb_ready = ready;
e8b96c60 3979 callback->awcb_physdone = physdone;
34dc7c2f
BB
3980 callback->awcb_done = done;
3981 callback->awcb_private = private;
3982 callback->awcb_buf = buf;
b128c09f 3983
428870ff 3984 zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
e8b96c60
MA
3985 arc_write_ready, arc_write_physdone, arc_write_done, callback,
3986 priority, zio_flags, zb);
34dc7c2f
BB
3987
3988 return (zio);
3989}
3990
34dc7c2f 3991static int
e8b96c60 3992arc_memory_throttle(uint64_t reserve, uint64_t txg)
34dc7c2f
BB
3993{
3994#ifdef _KERNEL
0c5493d4
BB
3995 if (zfs_arc_memory_throttle_disable)
3996 return (0);
3997
e8b96c60 3998 if (freemem <= physmem * arc_lotsfree_percent / 100) {
34dc7c2f 3999 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
570827e1 4000 DMU_TX_STAT_BUMP(dmu_tx_memory_reclaim);
2e528b49 4001 return (SET_ERROR(EAGAIN));
34dc7c2f 4002 }
34dc7c2f
BB
4003#endif
4004 return (0);
4005}
4006
4007void
4008arc_tempreserve_clear(uint64_t reserve)
4009{
4010 atomic_add_64(&arc_tempreserve, -reserve);
4011 ASSERT((int64_t)arc_tempreserve >= 0);
4012}
4013
4014int
4015arc_tempreserve_space(uint64_t reserve, uint64_t txg)
4016{
4017 int error;
9babb374 4018 uint64_t anon_size;
34dc7c2f 4019
34dc7c2f
BB
4020 if (reserve > arc_c/4 && !arc_no_grow)
4021 arc_c = MIN(arc_c_max, reserve * 4);
12f9a6a3
BB
4022
4023 /*
4024 * Throttle when the calculated memory footprint for the TXG
4025 * exceeds the target ARC size.
4026 */
570827e1
BB
4027 if (reserve > arc_c) {
4028 DMU_TX_STAT_BUMP(dmu_tx_memory_reserve);
12f9a6a3 4029 return (SET_ERROR(ERESTART));
570827e1 4030 }
34dc7c2f 4031
9babb374
BB
4032 /*
4033 * Don't count loaned bufs as in flight dirty data to prevent long
4034 * network delays from blocking transactions that are ready to be
4035 * assigned to a txg.
4036 */
4037 anon_size = MAX((int64_t)(arc_anon->arcs_size - arc_loaned_bytes), 0);
4038
34dc7c2f
BB
4039 /*
4040 * Writes will, almost always, require additional memory allocations
d3cc8b15 4041 * in order to compress/encrypt/etc the data. We therefore need to
34dc7c2f
BB
4042 * make sure that there is sufficient available memory for this.
4043 */
e8b96c60
MA
4044 error = arc_memory_throttle(reserve, txg);
4045 if (error != 0)
34dc7c2f
BB
4046 return (error);
4047
4048 /*
4049 * Throttle writes when the amount of dirty data in the cache
4050 * gets too large. We try to keep the cache less than half full
4051 * of dirty blocks so that our sync times don't grow too large.
4052 * Note: if two requests come in concurrently, we might let them
4053 * both succeed, when one of them should fail. Not a huge deal.
4054 */
9babb374
BB
4055
4056 if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
4057 anon_size > arc_c / 4) {
34dc7c2f
BB
4058 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
4059 "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
4060 arc_tempreserve>>10,
4061 arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
4062 arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
4063 reserve>>10, arc_c>>10);
570827e1 4064 DMU_TX_STAT_BUMP(dmu_tx_dirty_throttle);
2e528b49 4065 return (SET_ERROR(ERESTART));
34dc7c2f
BB
4066 }
4067 atomic_add_64(&arc_tempreserve, reserve);
4068 return (0);
4069}
4070
13be560d
BB
4071static void
4072arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
4073 kstat_named_t *evict_data, kstat_named_t *evict_metadata)
4074{
4075 size->value.ui64 = state->arcs_size;
4076 evict_data->value.ui64 = state->arcs_lsize[ARC_BUFC_DATA];
4077 evict_metadata->value.ui64 = state->arcs_lsize[ARC_BUFC_METADATA];
4078}
4079
4080static int
4081arc_kstat_update(kstat_t *ksp, int rw)
4082{
4083 arc_stats_t *as = ksp->ks_data;
4084
4085 if (rw == KSTAT_WRITE) {
2e528b49 4086 return (SET_ERROR(EACCES));
13be560d
BB
4087 } else {
4088 arc_kstat_update_state(arc_anon,
4089 &as->arcstat_anon_size,
4090 &as->arcstat_anon_evict_data,
4091 &as->arcstat_anon_evict_metadata);
4092 arc_kstat_update_state(arc_mru,
4093 &as->arcstat_mru_size,
4094 &as->arcstat_mru_evict_data,
4095 &as->arcstat_mru_evict_metadata);
4096 arc_kstat_update_state(arc_mru_ghost,
4097 &as->arcstat_mru_ghost_size,
4098 &as->arcstat_mru_ghost_evict_data,
4099 &as->arcstat_mru_ghost_evict_metadata);
4100 arc_kstat_update_state(arc_mfu,
4101 &as->arcstat_mfu_size,
4102 &as->arcstat_mfu_evict_data,
4103 &as->arcstat_mfu_evict_metadata);
fc41c640 4104 arc_kstat_update_state(arc_mfu_ghost,
13be560d
BB
4105 &as->arcstat_mfu_ghost_size,
4106 &as->arcstat_mfu_ghost_evict_data,
4107 &as->arcstat_mfu_ghost_evict_metadata);
4108 }
4109
4110 return (0);
4111}
4112
34dc7c2f
BB
4113void
4114arc_init(void)
4115{
4116 mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
4117 cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
4118
4119 /* Convert seconds to clock ticks */
bce45ec9 4120 zfs_arc_min_prefetch_lifespan = 1 * hz;
34dc7c2f
BB
4121
4122 /* Start out with 1/8 of all memory */
4123 arc_c = physmem * PAGESIZE / 8;
4124
4125#ifdef _KERNEL
4126 /*
4127 * On architectures where the physical memory can be larger
4128 * than the addressable space (intel in 32-bit mode), we may
4129 * need to limit the cache to 1/8 of VM size.
4130 */
4131 arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
7cb67b45
BB
4132 /*
4133 * Register a shrinker to support synchronous (direct) memory
4134 * reclaim from the arc. This is done to prevent kswapd from
4135 * swapping out pages when it is preferable to shrink the arc.
4136 */
4137 spl_register_shrinker(&arc_shrinker);
34dc7c2f
BB
4138#endif
4139
91415825
BB
4140 /* set min cache to zero */
4141 arc_c_min = 4<<20;
518b4876 4142 /* set max to 1/2 of all memory */
be5db977 4143 arc_c_max = arc_c * 4;
34dc7c2f
BB
4144
4145 /*
4146 * Allow the tunables to override our calculations if they are
4147 * reasonable (ie. over 64MB)
4148 */
4149 if (zfs_arc_max > 64<<20 && zfs_arc_max < physmem * PAGESIZE)
4150 arc_c_max = zfs_arc_max;
91415825 4151 if (zfs_arc_min > 0 && zfs_arc_min <= arc_c_max)
34dc7c2f
BB
4152 arc_c_min = zfs_arc_min;
4153
4154 arc_c = arc_c_max;
4155 arc_p = (arc_c >> 1);
4156
2b13331d
PS
4157 /* limit meta-data to 3/4 of the arc capacity */
4158 arc_meta_limit = (3 * arc_c_max) / 4;
1834f2d8 4159 arc_meta_max = 0;
34dc7c2f
BB
4160
4161 /* Allow the tunable to override if it is reasonable */
4162 if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
4163 arc_meta_limit = zfs_arc_meta_limit;
4164
34dc7c2f
BB
4165 /* if kmem_flags are set, lets try to use less memory */
4166 if (kmem_debugging())
4167 arc_c = arc_c / 2;
4168 if (arc_c < arc_c_min)
4169 arc_c = arc_c_min;
4170
4171 arc_anon = &ARC_anon;
4172 arc_mru = &ARC_mru;
4173 arc_mru_ghost = &ARC_mru_ghost;
4174 arc_mfu = &ARC_mfu;
4175 arc_mfu_ghost = &ARC_mfu_ghost;
4176 arc_l2c_only = &ARC_l2c_only;
4177 arc_size = 0;
4178
4179 mutex_init(&arc_anon->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
4180 mutex_init(&arc_mru->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
4181 mutex_init(&arc_mru_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
4182 mutex_init(&arc_mfu->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
4183 mutex_init(&arc_mfu_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
4184 mutex_init(&arc_l2c_only->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
4185
4186 list_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
4187 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4188 list_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
4189 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4190 list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
4191 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4192 list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
4193 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4194 list_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
4195 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4196 list_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
4197 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4198 list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
4199 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4200 list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
4201 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4202 list_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
4203 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4204 list_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
4205 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4206
e0b0ca98
BB
4207 arc_anon->arcs_state = ARC_STATE_ANON;
4208 arc_mru->arcs_state = ARC_STATE_MRU;
4209 arc_mru_ghost->arcs_state = ARC_STATE_MRU_GHOST;
4210 arc_mfu->arcs_state = ARC_STATE_MFU;
4211 arc_mfu_ghost->arcs_state = ARC_STATE_MFU_GHOST;
4212 arc_l2c_only->arcs_state = ARC_STATE_L2C_ONLY;
4213
34dc7c2f
BB
4214 buf_init();
4215
4216 arc_thread_exit = 0;
ab26409d
BB
4217 list_create(&arc_prune_list, sizeof (arc_prune_t),
4218 offsetof(arc_prune_t, p_node));
34dc7c2f 4219 arc_eviction_list = NULL;
ab26409d 4220 mutex_init(&arc_prune_mtx, NULL, MUTEX_DEFAULT, NULL);
34dc7c2f
BB
4221 mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
4222 bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
4223
4224 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
4225 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
4226
4227 if (arc_ksp != NULL) {
4228 arc_ksp->ks_data = &arc_stats;
13be560d 4229 arc_ksp->ks_update = arc_kstat_update;
34dc7c2f
BB
4230 kstat_install(arc_ksp);
4231 }
4232
302f753f 4233 (void) thread_create(NULL, 0, arc_adapt_thread, NULL, 0, &p0,
34dc7c2f
BB
4234 TS_RUN, minclsyspri);
4235
4236 arc_dead = FALSE;
b128c09f 4237 arc_warm = B_FALSE;
34dc7c2f 4238
e8b96c60
MA
4239 /*
4240 * Calculate maximum amount of dirty data per pool.
4241 *
4242 * If it has been set by a module parameter, take that.
4243 * Otherwise, use a percentage of physical memory defined by
4244 * zfs_dirty_data_max_percent (default 10%) with a cap at
4245 * zfs_dirty_data_max_max (default 25% of physical memory).
4246 */
4247 if (zfs_dirty_data_max_max == 0)
4248 zfs_dirty_data_max_max = physmem * PAGESIZE *
4249 zfs_dirty_data_max_max_percent / 100;
4250
4251 if (zfs_dirty_data_max == 0) {
4252 zfs_dirty_data_max = physmem * PAGESIZE *
4253 zfs_dirty_data_max_percent / 100;
4254 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
4255 zfs_dirty_data_max_max);
4256 }
34dc7c2f
BB
4257}
4258
4259void
4260arc_fini(void)
4261{
ab26409d
BB
4262 arc_prune_t *p;
4263
34dc7c2f 4264 mutex_enter(&arc_reclaim_thr_lock);
7cb67b45
BB
4265#ifdef _KERNEL
4266 spl_unregister_shrinker(&arc_shrinker);
4267#endif /* _KERNEL */
4268
34dc7c2f
BB
4269 arc_thread_exit = 1;
4270 while (arc_thread_exit != 0)
4271 cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
4272 mutex_exit(&arc_reclaim_thr_lock);
4273
4274 arc_flush(NULL);
4275
4276 arc_dead = TRUE;
4277
4278 if (arc_ksp != NULL) {
4279 kstat_delete(arc_ksp);
4280 arc_ksp = NULL;
4281 }
4282
ab26409d
BB
4283 mutex_enter(&arc_prune_mtx);
4284 while ((p = list_head(&arc_prune_list)) != NULL) {
4285 list_remove(&arc_prune_list, p);
4286 refcount_remove(&p->p_refcnt, &arc_prune_list);
4287 refcount_destroy(&p->p_refcnt);
4288 kmem_free(p, sizeof (*p));
4289 }
4290 mutex_exit(&arc_prune_mtx);
4291
4292 list_destroy(&arc_prune_list);
4293 mutex_destroy(&arc_prune_mtx);
34dc7c2f
BB
4294 mutex_destroy(&arc_eviction_mtx);
4295 mutex_destroy(&arc_reclaim_thr_lock);
4296 cv_destroy(&arc_reclaim_thr_cv);
4297
4298 list_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
4299 list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
4300 list_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
4301 list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
4302 list_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
4303 list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
4304 list_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
4305 list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
4306
4307 mutex_destroy(&arc_anon->arcs_mtx);
4308 mutex_destroy(&arc_mru->arcs_mtx);
4309 mutex_destroy(&arc_mru_ghost->arcs_mtx);
4310 mutex_destroy(&arc_mfu->arcs_mtx);
4311 mutex_destroy(&arc_mfu_ghost->arcs_mtx);
fb5f0bc8 4312 mutex_destroy(&arc_l2c_only->arcs_mtx);
34dc7c2f
BB
4313
4314 buf_fini();
9babb374
BB
4315
4316 ASSERT(arc_loaned_bytes == 0);
34dc7c2f
BB
4317}
4318
4319/*
4320 * Level 2 ARC
4321 *
4322 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
4323 * It uses dedicated storage devices to hold cached data, which are populated
4324 * using large infrequent writes. The main role of this cache is to boost
4325 * the performance of random read workloads. The intended L2ARC devices
4326 * include short-stroked disks, solid state disks, and other media with
4327 * substantially faster read latency than disk.
4328 *
4329 * +-----------------------+
4330 * | ARC |
4331 * +-----------------------+
4332 * | ^ ^
4333 * | | |
4334 * l2arc_feed_thread() arc_read()
4335 * | | |
4336 * | l2arc read |
4337 * V | |
4338 * +---------------+ |
4339 * | L2ARC | |
4340 * +---------------+ |
4341 * | ^ |
4342 * l2arc_write() | |
4343 * | | |
4344 * V | |
4345 * +-------+ +-------+
4346 * | vdev | | vdev |
4347 * | cache | | cache |
4348 * +-------+ +-------+
4349 * +=========+ .-----.
4350 * : L2ARC : |-_____-|
4351 * : devices : | Disks |
4352 * +=========+ `-_____-'
4353 *
4354 * Read requests are satisfied from the following sources, in order:
4355 *
4356 * 1) ARC
4357 * 2) vdev cache of L2ARC devices
4358 * 3) L2ARC devices
4359 * 4) vdev cache of disks
4360 * 5) disks
4361 *
4362 * Some L2ARC device types exhibit extremely slow write performance.
4363 * To accommodate for this there are some significant differences between
4364 * the L2ARC and traditional cache design:
4365 *
4366 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
4367 * the ARC behave as usual, freeing buffers and placing headers on ghost
4368 * lists. The ARC does not send buffers to the L2ARC during eviction as
4369 * this would add inflated write latencies for all ARC memory pressure.
4370 *
4371 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
4372 * It does this by periodically scanning buffers from the eviction-end of
4373 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
3a17a7a9
SK
4374 * not already there. It scans until a headroom of buffers is satisfied,
4375 * which itself is a buffer for ARC eviction. If a compressible buffer is
4376 * found during scanning and selected for writing to an L2ARC device, we
4377 * temporarily boost scanning headroom during the next scan cycle to make
4378 * sure we adapt to compression effects (which might significantly reduce
4379 * the data volume we write to L2ARC). The thread that does this is
34dc7c2f
BB
4380 * l2arc_feed_thread(), illustrated below; example sizes are included to
4381 * provide a better sense of ratio than this diagram:
4382 *
4383 * head --> tail
4384 * +---------------------+----------+
4385 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
4386 * +---------------------+----------+ | o L2ARC eligible
4387 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
4388 * +---------------------+----------+ |
4389 * 15.9 Gbytes ^ 32 Mbytes |
4390 * headroom |
4391 * l2arc_feed_thread()
4392 * |
4393 * l2arc write hand <--[oooo]--'
4394 * | 8 Mbyte
4395 * | write max
4396 * V
4397 * +==============================+
4398 * L2ARC dev |####|#|###|###| |####| ... |
4399 * +==============================+
4400 * 32 Gbytes
4401 *
4402 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
4403 * evicted, then the L2ARC has cached a buffer much sooner than it probably
4404 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
4405 * safe to say that this is an uncommon case, since buffers at the end of
4406 * the ARC lists have moved there due to inactivity.
4407 *
4408 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
4409 * then the L2ARC simply misses copying some buffers. This serves as a
4410 * pressure valve to prevent heavy read workloads from both stalling the ARC
4411 * with waits and clogging the L2ARC with writes. This also helps prevent
4412 * the potential for the L2ARC to churn if it attempts to cache content too
4413 * quickly, such as during backups of the entire pool.
4414 *
b128c09f
BB
4415 * 5. After system boot and before the ARC has filled main memory, there are
4416 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
4417 * lists can remain mostly static. Instead of searching from tail of these
4418 * lists as pictured, the l2arc_feed_thread() will search from the list heads
4419 * for eligible buffers, greatly increasing its chance of finding them.
4420 *
4421 * The L2ARC device write speed is also boosted during this time so that
4422 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
4423 * there are no L2ARC reads, and no fear of degrading read performance
4424 * through increased writes.
4425 *
4426 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
34dc7c2f
BB
4427 * the vdev queue can aggregate them into larger and fewer writes. Each
4428 * device is written to in a rotor fashion, sweeping writes through
4429 * available space then repeating.
4430 *
b128c09f 4431 * 7. The L2ARC does not store dirty content. It never needs to flush
34dc7c2f
BB
4432 * write buffers back to disk based storage.
4433 *
b128c09f 4434 * 8. If an ARC buffer is written (and dirtied) which also exists in the
34dc7c2f
BB
4435 * L2ARC, the now stale L2ARC buffer is immediately dropped.
4436 *
4437 * The performance of the L2ARC can be tweaked by a number of tunables, which
4438 * may be necessary for different workloads:
4439 *
4440 * l2arc_write_max max write bytes per interval
b128c09f 4441 * l2arc_write_boost extra write bytes during device warmup
34dc7c2f 4442 * l2arc_noprefetch skip caching prefetched buffers
3a17a7a9 4443 * l2arc_nocompress skip compressing buffers
34dc7c2f 4444 * l2arc_headroom number of max device writes to precache
3a17a7a9
SK
4445 * l2arc_headroom_boost when we find compressed buffers during ARC
4446 * scanning, we multiply headroom by this
4447 * percentage factor for the next scan cycle,
4448 * since more compressed buffers are likely to
4449 * be present
34dc7c2f
BB
4450 * l2arc_feed_secs seconds between L2ARC writing
4451 *
4452 * Tunables may be removed or added as future performance improvements are
4453 * integrated, and also may become zpool properties.
d164b209
BB
4454 *
4455 * There are three key functions that control how the L2ARC warms up:
4456 *
4457 * l2arc_write_eligible() check if a buffer is eligible to cache
4458 * l2arc_write_size() calculate how much to write
4459 * l2arc_write_interval() calculate sleep delay between writes
4460 *
4461 * These three functions determine what to write, how much, and how quickly
4462 * to send writes.
34dc7c2f
BB
4463 */
4464
d164b209
BB
4465static boolean_t
4466l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *ab)
4467{
4468 /*
4469 * A buffer is *not* eligible for the L2ARC if it:
4470 * 1. belongs to a different spa.
428870ff
BB
4471 * 2. is already cached on the L2ARC.
4472 * 3. has an I/O in progress (it may be an incomplete read).
4473 * 4. is flagged not eligible (zfs property).
d164b209 4474 */
428870ff 4475 if (ab->b_spa != spa_guid || ab->b_l2hdr != NULL ||
d164b209
BB
4476 HDR_IO_IN_PROGRESS(ab) || !HDR_L2CACHE(ab))
4477 return (B_FALSE);
4478
4479 return (B_TRUE);
4480}
4481
4482static uint64_t
3a17a7a9 4483l2arc_write_size(void)
d164b209
BB
4484{
4485 uint64_t size;
4486
3a17a7a9
SK
4487 /*
4488 * Make sure our globals have meaningful values in case the user
4489 * altered them.
4490 */
4491 size = l2arc_write_max;
4492 if (size == 0) {
4493 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
4494 "be greater than zero, resetting it to the default (%d)",
4495 L2ARC_WRITE_SIZE);
4496 size = l2arc_write_max = L2ARC_WRITE_SIZE;
4497 }
d164b209
BB
4498
4499 if (arc_warm == B_FALSE)
3a17a7a9 4500 size += l2arc_write_boost;
d164b209
BB
4501
4502 return (size);
4503
4504}
4505
4506static clock_t
4507l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
4508{
428870ff 4509 clock_t interval, next, now;
d164b209
BB
4510
4511 /*
4512 * If the ARC lists are busy, increase our write rate; if the
4513 * lists are stale, idle back. This is achieved by checking
4514 * how much we previously wrote - if it was more than half of
4515 * what we wanted, schedule the next write much sooner.
4516 */
4517 if (l2arc_feed_again && wrote > (wanted / 2))
4518 interval = (hz * l2arc_feed_min_ms) / 1000;
4519 else
4520 interval = hz * l2arc_feed_secs;
4521
428870ff
BB
4522 now = ddi_get_lbolt();
4523 next = MAX(now, MIN(now + interval, began + interval));
d164b209
BB
4524
4525 return (next);
4526}
4527
34dc7c2f
BB
4528static void
4529l2arc_hdr_stat_add(void)
4530{
6e1d7276 4531 ARCSTAT_INCR(arcstat_l2_hdr_size, HDR_SIZE);
34dc7c2f
BB
4532 ARCSTAT_INCR(arcstat_hdr_size, -HDR_SIZE);
4533}
4534
4535static void
4536l2arc_hdr_stat_remove(void)
4537{
6e1d7276 4538 ARCSTAT_INCR(arcstat_l2_hdr_size, -HDR_SIZE);
34dc7c2f
BB
4539 ARCSTAT_INCR(arcstat_hdr_size, HDR_SIZE);
4540}
4541
4542/*
4543 * Cycle through L2ARC devices. This is how L2ARC load balances.
b128c09f 4544 * If a device is returned, this also returns holding the spa config lock.
34dc7c2f
BB
4545 */
4546static l2arc_dev_t *
4547l2arc_dev_get_next(void)
4548{
b128c09f 4549 l2arc_dev_t *first, *next = NULL;
34dc7c2f 4550
b128c09f
BB
4551 /*
4552 * Lock out the removal of spas (spa_namespace_lock), then removal
4553 * of cache devices (l2arc_dev_mtx). Once a device has been selected,
4554 * both locks will be dropped and a spa config lock held instead.
4555 */
4556 mutex_enter(&spa_namespace_lock);
4557 mutex_enter(&l2arc_dev_mtx);
4558
4559 /* if there are no vdevs, there is nothing to do */
4560 if (l2arc_ndev == 0)
4561 goto out;
4562
4563 first = NULL;
4564 next = l2arc_dev_last;
4565 do {
4566 /* loop around the list looking for a non-faulted vdev */
4567 if (next == NULL) {
34dc7c2f 4568 next = list_head(l2arc_dev_list);
b128c09f
BB
4569 } else {
4570 next = list_next(l2arc_dev_list, next);
4571 if (next == NULL)
4572 next = list_head(l2arc_dev_list);
4573 }
4574
4575 /* if we have come back to the start, bail out */
4576 if (first == NULL)
4577 first = next;
4578 else if (next == first)
4579 break;
4580
4581 } while (vdev_is_dead(next->l2ad_vdev));
4582
4583 /* if we were unable to find any usable vdevs, return NULL */
4584 if (vdev_is_dead(next->l2ad_vdev))
4585 next = NULL;
34dc7c2f
BB
4586
4587 l2arc_dev_last = next;
4588
b128c09f
BB
4589out:
4590 mutex_exit(&l2arc_dev_mtx);
4591
4592 /*
4593 * Grab the config lock to prevent the 'next' device from being
4594 * removed while we are writing to it.
4595 */
4596 if (next != NULL)
4597 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
4598 mutex_exit(&spa_namespace_lock);
4599
34dc7c2f
BB
4600 return (next);
4601}
4602
b128c09f
BB
4603/*
4604 * Free buffers that were tagged for destruction.
4605 */
4606static void
0bc8fd78 4607l2arc_do_free_on_write(void)
b128c09f
BB
4608{
4609 list_t *buflist;
4610 l2arc_data_free_t *df, *df_prev;
4611
4612 mutex_enter(&l2arc_free_on_write_mtx);
4613 buflist = l2arc_free_on_write;
4614
4615 for (df = list_tail(buflist); df; df = df_prev) {
4616 df_prev = list_prev(buflist, df);
4617 ASSERT(df->l2df_data != NULL);
4618 ASSERT(df->l2df_func != NULL);
4619 df->l2df_func(df->l2df_data, df->l2df_size);
4620 list_remove(buflist, df);
4621 kmem_free(df, sizeof (l2arc_data_free_t));
4622 }
4623
4624 mutex_exit(&l2arc_free_on_write_mtx);
4625}
4626
34dc7c2f
BB
4627/*
4628 * A write to a cache device has completed. Update all headers to allow
4629 * reads from these buffers to begin.
4630 */
4631static void
4632l2arc_write_done(zio_t *zio)
4633{
4634 l2arc_write_callback_t *cb;
4635 l2arc_dev_t *dev;
4636 list_t *buflist;
34dc7c2f 4637 arc_buf_hdr_t *head, *ab, *ab_prev;
b128c09f 4638 l2arc_buf_hdr_t *abl2;
34dc7c2f
BB
4639 kmutex_t *hash_lock;
4640
4641 cb = zio->io_private;
4642 ASSERT(cb != NULL);
4643 dev = cb->l2wcb_dev;
4644 ASSERT(dev != NULL);
4645 head = cb->l2wcb_head;
4646 ASSERT(head != NULL);
4647 buflist = dev->l2ad_buflist;
4648 ASSERT(buflist != NULL);
4649 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
4650 l2arc_write_callback_t *, cb);
4651
4652 if (zio->io_error != 0)
4653 ARCSTAT_BUMP(arcstat_l2_writes_error);
4654
4655 mutex_enter(&l2arc_buflist_mtx);
4656
4657 /*
4658 * All writes completed, or an error was hit.
4659 */
4660 for (ab = list_prev(buflist, head); ab; ab = ab_prev) {
4661 ab_prev = list_prev(buflist, ab);
1ca546b3
SK
4662 abl2 = ab->b_l2hdr;
4663
4664 /*
4665 * Release the temporary compressed buffer as soon as possible.
4666 */
4667 if (abl2->b_compress != ZIO_COMPRESS_OFF)
4668 l2arc_release_cdata_buf(ab);
34dc7c2f
BB
4669
4670 hash_lock = HDR_LOCK(ab);
4671 if (!mutex_tryenter(hash_lock)) {
4672 /*
4673 * This buffer misses out. It may be in a stage
4674 * of eviction. Its ARC_L2_WRITING flag will be
4675 * left set, denying reads to this buffer.
4676 */
4677 ARCSTAT_BUMP(arcstat_l2_writes_hdr_miss);
4678 continue;
4679 }
4680
4681 if (zio->io_error != 0) {
4682 /*
b128c09f 4683 * Error - drop L2ARC entry.
34dc7c2f 4684 */
b128c09f 4685 list_remove(buflist, ab);
3a17a7a9 4686 ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
34dc7c2f 4687 ab->b_l2hdr = NULL;
ecf3d9b8 4688 kmem_cache_free(l2arc_hdr_cache, abl2);
6e1d7276 4689 arc_space_return(L2HDR_SIZE, ARC_SPACE_L2HDRS);
b128c09f 4690 ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
34dc7c2f
BB
4691 }
4692
4693 /*
4694 * Allow ARC to begin reads to this L2ARC entry.
4695 */
4696 ab->b_flags &= ~ARC_L2_WRITING;
4697
4698 mutex_exit(hash_lock);
4699 }
4700
4701 atomic_inc_64(&l2arc_writes_done);
4702 list_remove(buflist, head);
4703 kmem_cache_free(hdr_cache, head);
4704 mutex_exit(&l2arc_buflist_mtx);
4705
b128c09f 4706 l2arc_do_free_on_write();
34dc7c2f
BB
4707
4708 kmem_free(cb, sizeof (l2arc_write_callback_t));
4709}
4710
4711/*
4712 * A read to a cache device completed. Validate buffer contents before
4713 * handing over to the regular ARC routines.
4714 */
4715static void
4716l2arc_read_done(zio_t *zio)
4717{
4718 l2arc_read_callback_t *cb;
4719 arc_buf_hdr_t *hdr;
4720 arc_buf_t *buf;
34dc7c2f 4721 kmutex_t *hash_lock;
b128c09f
BB
4722 int equal;
4723
4724 ASSERT(zio->io_vd != NULL);
4725 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
4726
4727 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
34dc7c2f
BB
4728
4729 cb = zio->io_private;
4730 ASSERT(cb != NULL);
4731 buf = cb->l2rcb_buf;
4732 ASSERT(buf != NULL);
34dc7c2f 4733
428870ff 4734 hash_lock = HDR_LOCK(buf->b_hdr);
34dc7c2f 4735 mutex_enter(hash_lock);
428870ff
BB
4736 hdr = buf->b_hdr;
4737 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
34dc7c2f 4738
3a17a7a9
SK
4739 /*
4740 * If the buffer was compressed, decompress it first.
4741 */
4742 if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
4743 l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
4744 ASSERT(zio->io_data != NULL);
4745
34dc7c2f
BB
4746 /*
4747 * Check this survived the L2ARC journey.
4748 */
4749 equal = arc_cksum_equal(buf);
4750 if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
4751 mutex_exit(hash_lock);
4752 zio->io_private = buf;
b128c09f
BB
4753 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
4754 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
34dc7c2f
BB
4755 arc_read_done(zio);
4756 } else {
4757 mutex_exit(hash_lock);
4758 /*
4759 * Buffer didn't survive caching. Increment stats and
4760 * reissue to the original storage device.
4761 */
b128c09f 4762 if (zio->io_error != 0) {
34dc7c2f 4763 ARCSTAT_BUMP(arcstat_l2_io_error);
b128c09f 4764 } else {
2e528b49 4765 zio->io_error = SET_ERROR(EIO);
b128c09f 4766 }
34dc7c2f
BB
4767 if (!equal)
4768 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
4769
34dc7c2f 4770 /*
b128c09f
BB
4771 * If there's no waiter, issue an async i/o to the primary
4772 * storage now. If there *is* a waiter, the caller must
4773 * issue the i/o in a context where it's OK to block.
34dc7c2f 4774 */
d164b209
BB
4775 if (zio->io_waiter == NULL) {
4776 zio_t *pio = zio_unique_parent(zio);
4777
4778 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
4779
4780 zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
b128c09f
BB
4781 buf->b_data, zio->io_size, arc_read_done, buf,
4782 zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
d164b209 4783 }
34dc7c2f
BB
4784 }
4785
4786 kmem_free(cb, sizeof (l2arc_read_callback_t));
4787}
4788
4789/*
4790 * This is the list priority from which the L2ARC will search for pages to
4791 * cache. This is used within loops (0..3) to cycle through lists in the
4792 * desired order. This order can have a significant effect on cache
4793 * performance.
4794 *
4795 * Currently the metadata lists are hit first, MFU then MRU, followed by
4796 * the data lists. This function returns a locked list, and also returns
4797 * the lock pointer.
4798 */
4799static list_t *
4800l2arc_list_locked(int list_num, kmutex_t **lock)
4801{
d4ed6673 4802 list_t *list = NULL;
34dc7c2f
BB
4803
4804 ASSERT(list_num >= 0 && list_num <= 3);
4805
4806 switch (list_num) {
4807 case 0:
4808 list = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
4809 *lock = &arc_mfu->arcs_mtx;
4810 break;
4811 case 1:
4812 list = &arc_mru->arcs_list[ARC_BUFC_METADATA];
4813 *lock = &arc_mru->arcs_mtx;
4814 break;
4815 case 2:
4816 list = &arc_mfu->arcs_list[ARC_BUFC_DATA];
4817 *lock = &arc_mfu->arcs_mtx;
4818 break;
4819 case 3:
4820 list = &arc_mru->arcs_list[ARC_BUFC_DATA];
4821 *lock = &arc_mru->arcs_mtx;
4822 break;
4823 }
4824
4825 ASSERT(!(MUTEX_HELD(*lock)));
4826 mutex_enter(*lock);
4827 return (list);
4828}
4829
4830/*
4831 * Evict buffers from the device write hand to the distance specified in
4832 * bytes. This distance may span populated buffers, it may span nothing.
4833 * This is clearing a region on the L2ARC device ready for writing.
4834 * If the 'all' boolean is set, every buffer is evicted.
4835 */
4836static void
4837l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
4838{
4839 list_t *buflist;
4840 l2arc_buf_hdr_t *abl2;
4841 arc_buf_hdr_t *ab, *ab_prev;
4842 kmutex_t *hash_lock;
4843 uint64_t taddr;
4844
34dc7c2f
BB
4845 buflist = dev->l2ad_buflist;
4846
4847 if (buflist == NULL)
4848 return;
4849
4850 if (!all && dev->l2ad_first) {
4851 /*
4852 * This is the first sweep through the device. There is
4853 * nothing to evict.
4854 */
4855 return;
4856 }
4857
b128c09f 4858 if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
34dc7c2f
BB
4859 /*
4860 * When nearing the end of the device, evict to the end
4861 * before the device write hand jumps to the start.
4862 */
4863 taddr = dev->l2ad_end;
4864 } else {
4865 taddr = dev->l2ad_hand + distance;
4866 }
4867 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
4868 uint64_t, taddr, boolean_t, all);
4869
4870top:
4871 mutex_enter(&l2arc_buflist_mtx);
4872 for (ab = list_tail(buflist); ab; ab = ab_prev) {
4873 ab_prev = list_prev(buflist, ab);
4874
4875 hash_lock = HDR_LOCK(ab);
4876 if (!mutex_tryenter(hash_lock)) {
4877 /*
4878 * Missed the hash lock. Retry.
4879 */
4880 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
4881 mutex_exit(&l2arc_buflist_mtx);
4882 mutex_enter(hash_lock);
4883 mutex_exit(hash_lock);
4884 goto top;
4885 }
4886
4887 if (HDR_L2_WRITE_HEAD(ab)) {
4888 /*
4889 * We hit a write head node. Leave it for
4890 * l2arc_write_done().
4891 */
4892 list_remove(buflist, ab);
4893 mutex_exit(hash_lock);
4894 continue;
4895 }
4896
4897 if (!all && ab->b_l2hdr != NULL &&
4898 (ab->b_l2hdr->b_daddr > taddr ||
4899 ab->b_l2hdr->b_daddr < dev->l2ad_hand)) {
4900 /*
4901 * We've evicted to the target address,
4902 * or the end of the device.
4903 */
4904 mutex_exit(hash_lock);
4905 break;
4906 }
4907
4908 if (HDR_FREE_IN_PROGRESS(ab)) {
4909 /*
4910 * Already on the path to destruction.
4911 */
4912 mutex_exit(hash_lock);
4913 continue;
4914 }
4915
4916 if (ab->b_state == arc_l2c_only) {
4917 ASSERT(!HDR_L2_READING(ab));
4918 /*
4919 * This doesn't exist in the ARC. Destroy.
4920 * arc_hdr_destroy() will call list_remove()
4921 * and decrement arcstat_l2_size.
4922 */
4923 arc_change_state(arc_anon, ab, hash_lock);
4924 arc_hdr_destroy(ab);
4925 } else {
b128c09f
BB
4926 /*
4927 * Invalidate issued or about to be issued
4928 * reads, since we may be about to write
4929 * over this location.
4930 */
4931 if (HDR_L2_READING(ab)) {
4932 ARCSTAT_BUMP(arcstat_l2_evict_reading);
4933 ab->b_flags |= ARC_L2_EVICTED;
4934 }
4935
34dc7c2f
BB
4936 /*
4937 * Tell ARC this no longer exists in L2ARC.
4938 */
4939 if (ab->b_l2hdr != NULL) {
4940 abl2 = ab->b_l2hdr;
3a17a7a9 4941 ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
34dc7c2f 4942 ab->b_l2hdr = NULL;
ecf3d9b8 4943 kmem_cache_free(l2arc_hdr_cache, abl2);
6e1d7276 4944 arc_space_return(L2HDR_SIZE, ARC_SPACE_L2HDRS);
34dc7c2f
BB
4945 ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
4946 }
4947 list_remove(buflist, ab);
4948
4949 /*
4950 * This may have been leftover after a
4951 * failed write.
4952 */
4953 ab->b_flags &= ~ARC_L2_WRITING;
34dc7c2f
BB
4954 }
4955 mutex_exit(hash_lock);
4956 }
4957 mutex_exit(&l2arc_buflist_mtx);
4958
428870ff 4959 vdev_space_update(dev->l2ad_vdev, -(taddr - dev->l2ad_evict), 0, 0);
34dc7c2f
BB
4960 dev->l2ad_evict = taddr;
4961}
4962
4963/*
4964 * Find and write ARC buffers to the L2ARC device.
4965 *
4966 * An ARC_L2_WRITING flag is set so that the L2ARC buffers are not valid
4967 * for reading until they have completed writing.
3a17a7a9
SK
4968 * The headroom_boost is an in-out parameter used to maintain headroom boost
4969 * state between calls to this function.
4970 *
4971 * Returns the number of bytes actually written (which may be smaller than
4972 * the delta by which the device hand has changed due to alignment).
34dc7c2f 4973 */
d164b209 4974static uint64_t
3a17a7a9
SK
4975l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
4976 boolean_t *headroom_boost)
34dc7c2f
BB
4977{
4978 arc_buf_hdr_t *ab, *ab_prev, *head;
34dc7c2f 4979 list_t *list;
3a17a7a9
SK
4980 uint64_t write_asize, write_psize, write_sz, headroom,
4981 buf_compress_minsz;
34dc7c2f 4982 void *buf_data;
3a17a7a9
SK
4983 kmutex_t *list_lock = NULL;
4984 boolean_t full;
34dc7c2f
BB
4985 l2arc_write_callback_t *cb;
4986 zio_t *pio, *wzio;
3541dc6d 4987 uint64_t guid = spa_load_guid(spa);
d6320ddb 4988 int try;
3a17a7a9 4989 const boolean_t do_headroom_boost = *headroom_boost;
34dc7c2f 4990
34dc7c2f
BB
4991 ASSERT(dev->l2ad_vdev != NULL);
4992
3a17a7a9
SK
4993 /* Lower the flag now, we might want to raise it again later. */
4994 *headroom_boost = B_FALSE;
4995
34dc7c2f 4996 pio = NULL;
3a17a7a9 4997 write_sz = write_asize = write_psize = 0;
34dc7c2f
BB
4998 full = B_FALSE;
4999 head = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
5000 head->b_flags |= ARC_L2_WRITE_HEAD;
5001
3a17a7a9
SK
5002 /*
5003 * We will want to try to compress buffers that are at least 2x the
5004 * device sector size.
5005 */
5006 buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
5007
34dc7c2f
BB
5008 /*
5009 * Copy buffers for L2ARC writing.
5010 */
5011 mutex_enter(&l2arc_buflist_mtx);
d6320ddb 5012 for (try = 0; try <= 3; try++) {
3a17a7a9
SK
5013 uint64_t passed_sz = 0;
5014
34dc7c2f 5015 list = l2arc_list_locked(try, &list_lock);
34dc7c2f 5016
b128c09f
BB
5017 /*
5018 * L2ARC fast warmup.
5019 *
5020 * Until the ARC is warm and starts to evict, read from the
5021 * head of the ARC lists rather than the tail.
5022 */
b128c09f
BB
5023 if (arc_warm == B_FALSE)
5024 ab = list_head(list);
5025 else
5026 ab = list_tail(list);
5027
3a17a7a9
SK
5028 headroom = target_sz * l2arc_headroom;
5029 if (do_headroom_boost)
5030 headroom = (headroom * l2arc_headroom_boost) / 100;
5031
b128c09f 5032 for (; ab; ab = ab_prev) {
3a17a7a9
SK
5033 l2arc_buf_hdr_t *l2hdr;
5034 kmutex_t *hash_lock;
5035 uint64_t buf_sz;
5036
b128c09f
BB
5037 if (arc_warm == B_FALSE)
5038 ab_prev = list_next(list, ab);
5039 else
5040 ab_prev = list_prev(list, ab);
34dc7c2f
BB
5041
5042 hash_lock = HDR_LOCK(ab);
3a17a7a9 5043 if (!mutex_tryenter(hash_lock)) {
34dc7c2f
BB
5044 /*
5045 * Skip this buffer rather than waiting.
5046 */
5047 continue;
5048 }
5049
5050 passed_sz += ab->b_size;
5051 if (passed_sz > headroom) {
5052 /*
5053 * Searched too far.
5054 */
5055 mutex_exit(hash_lock);
5056 break;
5057 }
5058
d164b209 5059 if (!l2arc_write_eligible(guid, ab)) {
34dc7c2f
BB
5060 mutex_exit(hash_lock);
5061 continue;
5062 }
5063
5064 if ((write_sz + ab->b_size) > target_sz) {
5065 full = B_TRUE;
5066 mutex_exit(hash_lock);
5067 break;
5068 }
5069
34dc7c2f
BB
5070 if (pio == NULL) {
5071 /*
5072 * Insert a dummy header on the buflist so
5073 * l2arc_write_done() can find where the
5074 * write buffers begin without searching.
5075 */
5076 list_insert_head(dev->l2ad_buflist, head);
5077
409dc1a5 5078 cb = kmem_alloc(sizeof (l2arc_write_callback_t),
d1d7e268 5079 KM_PUSHPAGE);
34dc7c2f
BB
5080 cb->l2wcb_dev = dev;
5081 cb->l2wcb_head = head;
5082 pio = zio_root(spa, l2arc_write_done, cb,
5083 ZIO_FLAG_CANFAIL);
5084 }
5085
5086 /*
5087 * Create and add a new L2ARC header.
5088 */
ecf3d9b8 5089 l2hdr = kmem_cache_alloc(l2arc_hdr_cache, KM_PUSHPAGE);
3a17a7a9 5090 l2hdr->b_dev = dev;
ecf3d9b8 5091 l2hdr->b_daddr = 0;
6e1d7276 5092 arc_space_consume(L2HDR_SIZE, ARC_SPACE_L2HDRS);
34dc7c2f
BB
5093
5094 ab->b_flags |= ARC_L2_WRITING;
3a17a7a9
SK
5095
5096 /*
5097 * Temporarily stash the data buffer in b_tmp_cdata.
5098 * The subsequent write step will pick it up from
5099 * there. This is because can't access ab->b_buf
5100 * without holding the hash_lock, which we in turn
5101 * can't access without holding the ARC list locks
5102 * (which we want to avoid during compression/writing)
5103 */
5104 l2hdr->b_compress = ZIO_COMPRESS_OFF;
5105 l2hdr->b_asize = ab->b_size;
5106 l2hdr->b_tmp_cdata = ab->b_buf->b_data;
e0b0ca98 5107 l2hdr->b_hits = 0;
3a17a7a9 5108
34dc7c2f 5109 buf_sz = ab->b_size;
3a17a7a9
SK
5110 ab->b_l2hdr = l2hdr;
5111
5112 list_insert_head(dev->l2ad_buflist, ab);
34dc7c2f
BB
5113
5114 /*
5115 * Compute and store the buffer cksum before
5116 * writing. On debug the cksum is verified first.
5117 */
5118 arc_cksum_verify(ab->b_buf);
5119 arc_cksum_compute(ab->b_buf, B_TRUE);
5120
5121 mutex_exit(hash_lock);
5122
3a17a7a9
SK
5123 write_sz += buf_sz;
5124 }
5125
5126 mutex_exit(list_lock);
5127
5128 if (full == B_TRUE)
5129 break;
5130 }
5131
5132 /* No buffers selected for writing? */
5133 if (pio == NULL) {
5134 ASSERT0(write_sz);
5135 mutex_exit(&l2arc_buflist_mtx);
5136 kmem_cache_free(hdr_cache, head);
5137 return (0);
5138 }
5139
5140 /*
5141 * Now start writing the buffers. We're starting at the write head
5142 * and work backwards, retracing the course of the buffer selector
5143 * loop above.
5144 */
5145 for (ab = list_prev(dev->l2ad_buflist, head); ab;
5146 ab = list_prev(dev->l2ad_buflist, ab)) {
5147 l2arc_buf_hdr_t *l2hdr;
5148 uint64_t buf_sz;
5149
5150 /*
5151 * We shouldn't need to lock the buffer here, since we flagged
5152 * it as ARC_L2_WRITING in the previous step, but we must take
5153 * care to only access its L2 cache parameters. In particular,
5154 * ab->b_buf may be invalid by now due to ARC eviction.
5155 */
5156 l2hdr = ab->b_l2hdr;
5157 l2hdr->b_daddr = dev->l2ad_hand;
5158
5159 if (!l2arc_nocompress && (ab->b_flags & ARC_L2COMPRESS) &&
5160 l2hdr->b_asize >= buf_compress_minsz) {
5161 if (l2arc_compress_buf(l2hdr)) {
5162 /*
5163 * If compression succeeded, enable headroom
5164 * boost on the next scan cycle.
5165 */
5166 *headroom_boost = B_TRUE;
5167 }
5168 }
5169
5170 /*
5171 * Pick up the buffer data we had previously stashed away
5172 * (and now potentially also compressed).
5173 */
5174 buf_data = l2hdr->b_tmp_cdata;
5175 buf_sz = l2hdr->b_asize;
5176
5177 /* Compression may have squashed the buffer to zero length. */
5178 if (buf_sz != 0) {
5179 uint64_t buf_p_sz;
5180
34dc7c2f
BB
5181 wzio = zio_write_phys(pio, dev->l2ad_vdev,
5182 dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
5183 NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
5184 ZIO_FLAG_CANFAIL, B_FALSE);
5185
5186 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
5187 zio_t *, wzio);
5188 (void) zio_nowait(wzio);
5189
3a17a7a9 5190 write_asize += buf_sz;
b128c09f
BB
5191 /*
5192 * Keep the clock hand suitably device-aligned.
5193 */
3a17a7a9
SK
5194 buf_p_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
5195 write_psize += buf_p_sz;
5196 dev->l2ad_hand += buf_p_sz;
34dc7c2f 5197 }
34dc7c2f 5198 }
34dc7c2f 5199
3a17a7a9 5200 mutex_exit(&l2arc_buflist_mtx);
34dc7c2f 5201
3a17a7a9 5202 ASSERT3U(write_asize, <=, target_sz);
34dc7c2f 5203 ARCSTAT_BUMP(arcstat_l2_writes_sent);
3a17a7a9 5204 ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
34dc7c2f 5205 ARCSTAT_INCR(arcstat_l2_size, write_sz);
3a17a7a9
SK
5206 ARCSTAT_INCR(arcstat_l2_asize, write_asize);
5207 vdev_space_update(dev->l2ad_vdev, write_psize, 0, 0);
34dc7c2f
BB
5208
5209 /*
5210 * Bump device hand to the device start if it is approaching the end.
5211 * l2arc_evict() will already have evicted ahead for this case.
5212 */
b128c09f 5213 if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
428870ff
BB
5214 vdev_space_update(dev->l2ad_vdev,
5215 dev->l2ad_end - dev->l2ad_hand, 0, 0);
34dc7c2f
BB
5216 dev->l2ad_hand = dev->l2ad_start;
5217 dev->l2ad_evict = dev->l2ad_start;
5218 dev->l2ad_first = B_FALSE;
5219 }
5220
d164b209 5221 dev->l2ad_writing = B_TRUE;
34dc7c2f 5222 (void) zio_wait(pio);
d164b209
BB
5223 dev->l2ad_writing = B_FALSE;
5224
3a17a7a9
SK
5225 return (write_asize);
5226}
5227
5228/*
5229 * Compresses an L2ARC buffer.
5230 * The data to be compressed must be prefilled in l2hdr->b_tmp_cdata and its
5231 * size in l2hdr->b_asize. This routine tries to compress the data and
5232 * depending on the compression result there are three possible outcomes:
5233 * *) The buffer was incompressible. The original l2hdr contents were left
5234 * untouched and are ready for writing to an L2 device.
5235 * *) The buffer was all-zeros, so there is no need to write it to an L2
5236 * device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
5237 * set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
5238 * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
5239 * data buffer which holds the compressed data to be written, and b_asize
5240 * tells us how much data there is. b_compress is set to the appropriate
5241 * compression algorithm. Once writing is done, invoke
5242 * l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
5243 *
5244 * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
5245 * buffer was incompressible).
5246 */
5247static boolean_t
5248l2arc_compress_buf(l2arc_buf_hdr_t *l2hdr)
5249{
5250 void *cdata;
9b67f605 5251 size_t csize, len, rounded;
3a17a7a9
SK
5252
5253 ASSERT(l2hdr->b_compress == ZIO_COMPRESS_OFF);
5254 ASSERT(l2hdr->b_tmp_cdata != NULL);
5255
5256 len = l2hdr->b_asize;
5257 cdata = zio_data_buf_alloc(len);
5258 csize = zio_compress_data(ZIO_COMPRESS_LZ4, l2hdr->b_tmp_cdata,
5259 cdata, l2hdr->b_asize);
5260
9b67f605
MA
5261 rounded = P2ROUNDUP(csize, (size_t)SPA_MINBLOCKSIZE);
5262 if (rounded > csize) {
5263 bzero((char *)cdata + csize, rounded - csize);
5264 csize = rounded;
5265 }
5266
3a17a7a9
SK
5267 if (csize == 0) {
5268 /* zero block, indicate that there's nothing to write */
5269 zio_data_buf_free(cdata, len);
5270 l2hdr->b_compress = ZIO_COMPRESS_EMPTY;
5271 l2hdr->b_asize = 0;
5272 l2hdr->b_tmp_cdata = NULL;
5273 ARCSTAT_BUMP(arcstat_l2_compress_zeros);
5274 return (B_TRUE);
5275 } else if (csize > 0 && csize < len) {
5276 /*
5277 * Compression succeeded, we'll keep the cdata around for
5278 * writing and release it afterwards.
5279 */
5280 l2hdr->b_compress = ZIO_COMPRESS_LZ4;
5281 l2hdr->b_asize = csize;
5282 l2hdr->b_tmp_cdata = cdata;
5283 ARCSTAT_BUMP(arcstat_l2_compress_successes);
5284 return (B_TRUE);
5285 } else {
5286 /*
5287 * Compression failed, release the compressed buffer.
5288 * l2hdr will be left unmodified.
5289 */
5290 zio_data_buf_free(cdata, len);
5291 ARCSTAT_BUMP(arcstat_l2_compress_failures);
5292 return (B_FALSE);
5293 }
5294}
5295
5296/*
5297 * Decompresses a zio read back from an l2arc device. On success, the
5298 * underlying zio's io_data buffer is overwritten by the uncompressed
5299 * version. On decompression error (corrupt compressed stream), the
5300 * zio->io_error value is set to signal an I/O error.
5301 *
5302 * Please note that the compressed data stream is not checksummed, so
5303 * if the underlying device is experiencing data corruption, we may feed
5304 * corrupt data to the decompressor, so the decompressor needs to be
5305 * able to handle this situation (LZ4 does).
5306 */
5307static void
5308l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
5309{
5310 uint64_t csize;
5311 void *cdata;
5312
5313 ASSERT(L2ARC_IS_VALID_COMPRESS(c));
5314
5315 if (zio->io_error != 0) {
5316 /*
5317 * An io error has occured, just restore the original io
5318 * size in preparation for a main pool read.
5319 */
5320 zio->io_orig_size = zio->io_size = hdr->b_size;
5321 return;
5322 }
5323
5324 if (c == ZIO_COMPRESS_EMPTY) {
5325 /*
5326 * An empty buffer results in a null zio, which means we
5327 * need to fill its io_data after we're done restoring the
5328 * buffer's contents.
5329 */
5330 ASSERT(hdr->b_buf != NULL);
5331 bzero(hdr->b_buf->b_data, hdr->b_size);
5332 zio->io_data = zio->io_orig_data = hdr->b_buf->b_data;
5333 } else {
5334 ASSERT(zio->io_data != NULL);
5335 /*
5336 * We copy the compressed data from the start of the arc buffer
5337 * (the zio_read will have pulled in only what we need, the
5338 * rest is garbage which we will overwrite at decompression)
5339 * and then decompress back to the ARC data buffer. This way we
5340 * can minimize copying by simply decompressing back over the
5341 * original compressed data (rather than decompressing to an
5342 * aux buffer and then copying back the uncompressed buffer,
5343 * which is likely to be much larger).
5344 */
5345 csize = zio->io_size;
5346 cdata = zio_data_buf_alloc(csize);
5347 bcopy(zio->io_data, cdata, csize);
5348 if (zio_decompress_data(c, cdata, zio->io_data, csize,
5349 hdr->b_size) != 0)
2e528b49 5350 zio->io_error = SET_ERROR(EIO);
3a17a7a9
SK
5351 zio_data_buf_free(cdata, csize);
5352 }
5353
5354 /* Restore the expected uncompressed IO size. */
5355 zio->io_orig_size = zio->io_size = hdr->b_size;
5356}
5357
5358/*
5359 * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
5360 * This buffer serves as a temporary holder of compressed data while
5361 * the buffer entry is being written to an l2arc device. Once that is
5362 * done, we can dispose of it.
5363 */
5364static void
5365l2arc_release_cdata_buf(arc_buf_hdr_t *ab)
5366{
5367 l2arc_buf_hdr_t *l2hdr = ab->b_l2hdr;
5368
5369 if (l2hdr->b_compress == ZIO_COMPRESS_LZ4) {
5370 /*
5371 * If the data was compressed, then we've allocated a
5372 * temporary buffer for it, so now we need to release it.
5373 */
5374 ASSERT(l2hdr->b_tmp_cdata != NULL);
5375 zio_data_buf_free(l2hdr->b_tmp_cdata, ab->b_size);
5376 }
5377 l2hdr->b_tmp_cdata = NULL;
34dc7c2f
BB
5378}
5379
5380/*
5381 * This thread feeds the L2ARC at regular intervals. This is the beating
5382 * heart of the L2ARC.
5383 */
5384static void
5385l2arc_feed_thread(void)
5386{
5387 callb_cpr_t cpr;
5388 l2arc_dev_t *dev;
5389 spa_t *spa;
d164b209 5390 uint64_t size, wrote;
428870ff 5391 clock_t begin, next = ddi_get_lbolt();
3a17a7a9 5392 boolean_t headroom_boost = B_FALSE;
34dc7c2f
BB
5393
5394 CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
5395
5396 mutex_enter(&l2arc_feed_thr_lock);
5397
5398 while (l2arc_thread_exit == 0) {
34dc7c2f 5399 CALLB_CPR_SAFE_BEGIN(&cpr);
5b63b3eb
BB
5400 (void) cv_timedwait_interruptible(&l2arc_feed_thr_cv,
5401 &l2arc_feed_thr_lock, next);
34dc7c2f 5402 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
428870ff 5403 next = ddi_get_lbolt() + hz;
34dc7c2f
BB
5404
5405 /*
b128c09f 5406 * Quick check for L2ARC devices.
34dc7c2f
BB
5407 */
5408 mutex_enter(&l2arc_dev_mtx);
5409 if (l2arc_ndev == 0) {
5410 mutex_exit(&l2arc_dev_mtx);
5411 continue;
5412 }
b128c09f 5413 mutex_exit(&l2arc_dev_mtx);
428870ff 5414 begin = ddi_get_lbolt();
34dc7c2f
BB
5415
5416 /*
b128c09f
BB
5417 * This selects the next l2arc device to write to, and in
5418 * doing so the next spa to feed from: dev->l2ad_spa. This
5419 * will return NULL if there are now no l2arc devices or if
5420 * they are all faulted.
5421 *
5422 * If a device is returned, its spa's config lock is also
5423 * held to prevent device removal. l2arc_dev_get_next()
5424 * will grab and release l2arc_dev_mtx.
34dc7c2f 5425 */
b128c09f 5426 if ((dev = l2arc_dev_get_next()) == NULL)
34dc7c2f 5427 continue;
b128c09f
BB
5428
5429 spa = dev->l2ad_spa;
5430 ASSERT(spa != NULL);
34dc7c2f 5431
572e2857
BB
5432 /*
5433 * If the pool is read-only then force the feed thread to
5434 * sleep a little longer.
5435 */
5436 if (!spa_writeable(spa)) {
5437 next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
5438 spa_config_exit(spa, SCL_L2ARC, dev);
5439 continue;
5440 }
5441
34dc7c2f 5442 /*
b128c09f 5443 * Avoid contributing to memory pressure.
34dc7c2f 5444 */
302f753f 5445 if (arc_no_grow) {
b128c09f
BB
5446 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
5447 spa_config_exit(spa, SCL_L2ARC, dev);
34dc7c2f
BB
5448 continue;
5449 }
b128c09f 5450
34dc7c2f
BB
5451 ARCSTAT_BUMP(arcstat_l2_feeds);
5452
3a17a7a9 5453 size = l2arc_write_size();
b128c09f 5454
34dc7c2f
BB
5455 /*
5456 * Evict L2ARC buffers that will be overwritten.
5457 */
b128c09f 5458 l2arc_evict(dev, size, B_FALSE);
34dc7c2f
BB
5459
5460 /*
5461 * Write ARC buffers.
5462 */
3a17a7a9 5463 wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
d164b209
BB
5464
5465 /*
5466 * Calculate interval between writes.
5467 */
5468 next = l2arc_write_interval(begin, size, wrote);
b128c09f 5469 spa_config_exit(spa, SCL_L2ARC, dev);
34dc7c2f
BB
5470 }
5471
5472 l2arc_thread_exit = 0;
5473 cv_broadcast(&l2arc_feed_thr_cv);
5474 CALLB_CPR_EXIT(&cpr); /* drops l2arc_feed_thr_lock */
5475 thread_exit();
5476}
5477
b128c09f
BB
5478boolean_t
5479l2arc_vdev_present(vdev_t *vd)
5480{
5481 l2arc_dev_t *dev;
5482
5483 mutex_enter(&l2arc_dev_mtx);
5484 for (dev = list_head(l2arc_dev_list); dev != NULL;
5485 dev = list_next(l2arc_dev_list, dev)) {
5486 if (dev->l2ad_vdev == vd)
5487 break;
5488 }
5489 mutex_exit(&l2arc_dev_mtx);
5490
5491 return (dev != NULL);
5492}
5493
34dc7c2f
BB
5494/*
5495 * Add a vdev for use by the L2ARC. By this point the spa has already
5496 * validated the vdev and opened it.
5497 */
5498void
9babb374 5499l2arc_add_vdev(spa_t *spa, vdev_t *vd)
34dc7c2f
BB
5500{
5501 l2arc_dev_t *adddev;
5502
b128c09f
BB
5503 ASSERT(!l2arc_vdev_present(vd));
5504
34dc7c2f
BB
5505 /*
5506 * Create a new l2arc device entry.
5507 */
5508 adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
5509 adddev->l2ad_spa = spa;
5510 adddev->l2ad_vdev = vd;
9babb374
BB
5511 adddev->l2ad_start = VDEV_LABEL_START_SIZE;
5512 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
34dc7c2f
BB
5513 adddev->l2ad_hand = adddev->l2ad_start;
5514 adddev->l2ad_evict = adddev->l2ad_start;
5515 adddev->l2ad_first = B_TRUE;
d164b209 5516 adddev->l2ad_writing = B_FALSE;
98f72a53 5517 list_link_init(&adddev->l2ad_node);
34dc7c2f
BB
5518
5519 /*
5520 * This is a list of all ARC buffers that are still valid on the
5521 * device.
5522 */
5523 adddev->l2ad_buflist = kmem_zalloc(sizeof (list_t), KM_SLEEP);
5524 list_create(adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
5525 offsetof(arc_buf_hdr_t, b_l2node));
5526
428870ff 5527 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
34dc7c2f
BB
5528
5529 /*
5530 * Add device to global list
5531 */
5532 mutex_enter(&l2arc_dev_mtx);
5533 list_insert_head(l2arc_dev_list, adddev);
5534 atomic_inc_64(&l2arc_ndev);
5535 mutex_exit(&l2arc_dev_mtx);
5536}
5537
5538/*
5539 * Remove a vdev from the L2ARC.
5540 */
5541void
5542l2arc_remove_vdev(vdev_t *vd)
5543{
5544 l2arc_dev_t *dev, *nextdev, *remdev = NULL;
5545
34dc7c2f
BB
5546 /*
5547 * Find the device by vdev
5548 */
5549 mutex_enter(&l2arc_dev_mtx);
5550 for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
5551 nextdev = list_next(l2arc_dev_list, dev);
5552 if (vd == dev->l2ad_vdev) {
5553 remdev = dev;
5554 break;
5555 }
5556 }
5557 ASSERT(remdev != NULL);
5558
5559 /*
5560 * Remove device from global list
5561 */
5562 list_remove(l2arc_dev_list, remdev);
5563 l2arc_dev_last = NULL; /* may have been invalidated */
b128c09f
BB
5564 atomic_dec_64(&l2arc_ndev);
5565 mutex_exit(&l2arc_dev_mtx);
34dc7c2f
BB
5566
5567 /*
5568 * Clear all buflists and ARC references. L2ARC device flush.
5569 */
5570 l2arc_evict(remdev, 0, B_TRUE);
5571 list_destroy(remdev->l2ad_buflist);
5572 kmem_free(remdev->l2ad_buflist, sizeof (list_t));
5573 kmem_free(remdev, sizeof (l2arc_dev_t));
34dc7c2f
BB
5574}
5575
5576void
b128c09f 5577l2arc_init(void)
34dc7c2f
BB
5578{
5579 l2arc_thread_exit = 0;
5580 l2arc_ndev = 0;
5581 l2arc_writes_sent = 0;
5582 l2arc_writes_done = 0;
5583
5584 mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
5585 cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
5586 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
5587 mutex_init(&l2arc_buflist_mtx, NULL, MUTEX_DEFAULT, NULL);
5588 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
5589
5590 l2arc_dev_list = &L2ARC_dev_list;
5591 l2arc_free_on_write = &L2ARC_free_on_write;
5592 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
5593 offsetof(l2arc_dev_t, l2ad_node));
5594 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
5595 offsetof(l2arc_data_free_t, l2df_list_node));
34dc7c2f
BB
5596}
5597
5598void
b128c09f 5599l2arc_fini(void)
34dc7c2f 5600{
b128c09f
BB
5601 /*
5602 * This is called from dmu_fini(), which is called from spa_fini();
5603 * Because of this, we can assume that all l2arc devices have
5604 * already been removed when the pools themselves were removed.
5605 */
5606
5607 l2arc_do_free_on_write();
34dc7c2f
BB
5608
5609 mutex_destroy(&l2arc_feed_thr_lock);
5610 cv_destroy(&l2arc_feed_thr_cv);
5611 mutex_destroy(&l2arc_dev_mtx);
5612 mutex_destroy(&l2arc_buflist_mtx);
5613 mutex_destroy(&l2arc_free_on_write_mtx);
5614
5615 list_destroy(l2arc_dev_list);
5616 list_destroy(l2arc_free_on_write);
5617}
b128c09f
BB
5618
5619void
5620l2arc_start(void)
5621{
fb5f0bc8 5622 if (!(spa_mode_global & FWRITE))
b128c09f
BB
5623 return;
5624
5625 (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
5626 TS_RUN, minclsyspri);
5627}
5628
5629void
5630l2arc_stop(void)
5631{
fb5f0bc8 5632 if (!(spa_mode_global & FWRITE))
b128c09f
BB
5633 return;
5634
5635 mutex_enter(&l2arc_feed_thr_lock);
5636 cv_signal(&l2arc_feed_thr_cv); /* kick thread out of startup */
5637 l2arc_thread_exit = 1;
5638 while (l2arc_thread_exit != 0)
5639 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
5640 mutex_exit(&l2arc_feed_thr_lock);
5641}
c28b2279
BB
5642
5643#if defined(_KERNEL) && defined(HAVE_SPL)
5644EXPORT_SYMBOL(arc_read);
5645EXPORT_SYMBOL(arc_buf_remove_ref);
e0b0ca98 5646EXPORT_SYMBOL(arc_buf_info);
c28b2279 5647EXPORT_SYMBOL(arc_getbuf_func);
ab26409d
BB
5648EXPORT_SYMBOL(arc_add_prune_callback);
5649EXPORT_SYMBOL(arc_remove_prune_callback);
c28b2279 5650
bce45ec9 5651module_param(zfs_arc_min, ulong, 0644);
c409e464 5652MODULE_PARM_DESC(zfs_arc_min, "Min arc size");
c28b2279 5653
bce45ec9 5654module_param(zfs_arc_max, ulong, 0644);
c409e464 5655MODULE_PARM_DESC(zfs_arc_max, "Max arc size");
c28b2279 5656
bce45ec9 5657module_param(zfs_arc_meta_limit, ulong, 0644);
c28b2279 5658MODULE_PARM_DESC(zfs_arc_meta_limit, "Meta limit for arc size");
6a8f9b6b 5659
bce45ec9 5660module_param(zfs_arc_meta_prune, int, 0644);
ab26409d 5661MODULE_PARM_DESC(zfs_arc_meta_prune, "Bytes of meta data to prune");
c409e464 5662
bce45ec9 5663module_param(zfs_arc_grow_retry, int, 0644);
c409e464
BB
5664MODULE_PARM_DESC(zfs_arc_grow_retry, "Seconds before growing arc size");
5665
89c8cac4
PS
5666module_param(zfs_arc_p_aggressive_disable, int, 0644);
5667MODULE_PARM_DESC(zfs_arc_p_aggressive_disable, "disable aggressive arc_p grow");
5668
62422785
PS
5669module_param(zfs_arc_p_dampener_disable, int, 0644);
5670MODULE_PARM_DESC(zfs_arc_p_dampener_disable, "disable arc_p adapt dampener");
5671
bce45ec9 5672module_param(zfs_arc_shrink_shift, int, 0644);
c409e464
BB
5673MODULE_PARM_DESC(zfs_arc_shrink_shift, "log2(fraction of arc to reclaim)");
5674
1f7c30df
BB
5675module_param(zfs_disable_dup_eviction, int, 0644);
5676MODULE_PARM_DESC(zfs_disable_dup_eviction, "disable duplicate buffer eviction");
5677
0c5493d4
BB
5678module_param(zfs_arc_memory_throttle_disable, int, 0644);
5679MODULE_PARM_DESC(zfs_arc_memory_throttle_disable, "disable memory throttle");
5680
bce45ec9
BB
5681module_param(zfs_arc_min_prefetch_lifespan, int, 0644);
5682MODULE_PARM_DESC(zfs_arc_min_prefetch_lifespan, "Min life of prefetch block");
5683
5684module_param(l2arc_write_max, ulong, 0644);
abd8610c
BB
5685MODULE_PARM_DESC(l2arc_write_max, "Max write bytes per interval");
5686
bce45ec9 5687module_param(l2arc_write_boost, ulong, 0644);
abd8610c
BB
5688MODULE_PARM_DESC(l2arc_write_boost, "Extra write bytes during device warmup");
5689
bce45ec9 5690module_param(l2arc_headroom, ulong, 0644);
abd8610c
BB
5691MODULE_PARM_DESC(l2arc_headroom, "Number of max device writes to precache");
5692
3a17a7a9
SK
5693module_param(l2arc_headroom_boost, ulong, 0644);
5694MODULE_PARM_DESC(l2arc_headroom_boost, "Compressed l2arc_headroom multiplier");
5695
bce45ec9 5696module_param(l2arc_feed_secs, ulong, 0644);
abd8610c
BB
5697MODULE_PARM_DESC(l2arc_feed_secs, "Seconds between L2ARC writing");
5698
bce45ec9 5699module_param(l2arc_feed_min_ms, ulong, 0644);
abd8610c
BB
5700MODULE_PARM_DESC(l2arc_feed_min_ms, "Min feed interval in milliseconds");
5701
bce45ec9 5702module_param(l2arc_noprefetch, int, 0644);
abd8610c
BB
5703MODULE_PARM_DESC(l2arc_noprefetch, "Skip caching prefetched buffers");
5704
3a17a7a9
SK
5705module_param(l2arc_nocompress, int, 0644);
5706MODULE_PARM_DESC(l2arc_nocompress, "Skip compressing L2ARC buffers");
5707
bce45ec9 5708module_param(l2arc_feed_again, int, 0644);
abd8610c
BB
5709MODULE_PARM_DESC(l2arc_feed_again, "Turbo L2ARC warmup");
5710
bce45ec9 5711module_param(l2arc_norw, int, 0644);
abd8610c
BB
5712MODULE_PARM_DESC(l2arc_norw, "No reads during writes");
5713
c28b2279 5714#endif