]> git.proxmox.com Git - mirror_zfs.git/blame - module/zfs/arc.c
Illumos 4881 - zfs send performance regression with embedded data
[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.
3bec585e 25 * Copyright 2014 Nexenta Systems, Inc. All rights reserved.
34dc7c2f
BB
26 */
27
34dc7c2f
BB
28/*
29 * DVA-based Adjustable Replacement Cache
30 *
31 * While much of the theory of operation used here is
32 * based on the self-tuning, low overhead replacement cache
33 * presented by Megiddo and Modha at FAST 2003, there are some
34 * significant differences:
35 *
36 * 1. The Megiddo and Modha model assumes any page is evictable.
37 * Pages in its cache cannot be "locked" into memory. This makes
38 * the eviction algorithm simple: evict the last page in the list.
39 * This also make the performance characteristics easy to reason
40 * about. Our cache is not so simple. At any given moment, some
41 * subset of the blocks in the cache are un-evictable because we
42 * have handed out a reference to them. Blocks are only evictable
43 * when there are no external references active. This makes
44 * eviction far more problematic: we choose to evict the evictable
45 * blocks that are the "lowest" in the list.
46 *
47 * There are times when it is not possible to evict the requested
48 * space. In these circumstances we are unable to adjust the cache
49 * size. To prevent the cache growing unbounded at these times we
50 * implement a "cache throttle" that slows the flow of new data
51 * into the cache until we can make space available.
52 *
53 * 2. The Megiddo and Modha model assumes a fixed cache size.
54 * Pages are evicted when the cache is full and there is a cache
55 * miss. Our model has a variable sized cache. It grows with
56 * high use, but also tries to react to memory pressure from the
57 * operating system: decreasing its size when system memory is
58 * tight.
59 *
60 * 3. The Megiddo and Modha model assumes a fixed page size. All
d3cc8b15 61 * elements of the cache are therefore exactly the same size. So
34dc7c2f
BB
62 * when adjusting the cache size following a cache miss, its simply
63 * a matter of choosing a single page to evict. In our model, we
64 * have variable sized cache blocks (rangeing from 512 bytes to
d3cc8b15 65 * 128K bytes). We therefore choose a set of blocks to evict to make
34dc7c2f
BB
66 * space for a cache miss that approximates as closely as possible
67 * the space used by the new block.
68 *
69 * See also: "ARC: A Self-Tuning, Low Overhead Replacement Cache"
70 * by N. Megiddo & D. Modha, FAST 2003
71 */
72
73/*
74 * The locking model:
75 *
76 * A new reference to a cache buffer can be obtained in two
77 * ways: 1) via a hash table lookup using the DVA as a key,
78 * or 2) via one of the ARC lists. The arc_read() interface
79 * uses method 1, while the internal arc algorithms for
d3cc8b15 80 * adjusting the cache use method 2. We therefore provide two
34dc7c2f
BB
81 * types of locks: 1) the hash table lock array, and 2) the
82 * arc list locks.
83 *
5c839890
BC
84 * Buffers do not have their own mutexes, rather they rely on the
85 * hash table mutexes for the bulk of their protection (i.e. most
86 * fields in the arc_buf_hdr_t are protected by these mutexes).
34dc7c2f
BB
87 *
88 * buf_hash_find() returns the appropriate mutex (held) when it
89 * locates the requested buffer in the hash table. It returns
90 * NULL for the mutex if the buffer was not in the table.
91 *
92 * buf_hash_remove() expects the appropriate hash mutex to be
93 * already held before it is invoked.
94 *
95 * Each arc state also has a mutex which is used to protect the
96 * buffer list associated with the state. When attempting to
97 * obtain a hash table lock while holding an arc list lock you
98 * must use: mutex_tryenter() to avoid deadlock. Also note that
99 * the active state mutex must be held before the ghost state mutex.
100 *
101 * Arc buffers may have an associated eviction callback function.
102 * This function will be invoked prior to removing the buffer (e.g.
103 * in arc_do_user_evicts()). Note however that the data associated
104 * with the buffer may be evicted prior to the callback. The callback
105 * must be made with *no locks held* (to prevent deadlock). Additionally,
106 * the users of callbacks must ensure that their private data is
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);
3bec585e
SK
1704 vdev_space_update(l2hdr->b_dev->l2ad_vdev,
1705 -l2hdr->b_asize, 0, 0);
ecf3d9b8 1706 kmem_cache_free(l2arc_hdr_cache, l2hdr);
6e1d7276 1707 arc_space_return(L2HDR_SIZE, ARC_SPACE_L2HDRS);
428870ff
BB
1708 if (hdr->b_state == arc_l2c_only)
1709 l2arc_hdr_stat_remove();
1710 hdr->b_l2hdr = NULL;
1711 }
1712
1713 if (!buflist_held)
1714 mutex_exit(&l2arc_buflist_mtx);
34dc7c2f
BB
1715 }
1716
1717 if (!BUF_EMPTY(hdr)) {
1718 ASSERT(!HDR_IN_HASH_TABLE(hdr));
428870ff 1719 buf_discard_identity(hdr);
34dc7c2f
BB
1720 }
1721 while (hdr->b_buf) {
1722 arc_buf_t *buf = hdr->b_buf;
1723
1724 if (buf->b_efunc) {
1725 mutex_enter(&arc_eviction_mtx);
428870ff 1726 mutex_enter(&buf->b_evict_lock);
34dc7c2f
BB
1727 ASSERT(buf->b_hdr != NULL);
1728 arc_buf_destroy(hdr->b_buf, FALSE, FALSE);
1729 hdr->b_buf = buf->b_next;
1730 buf->b_hdr = &arc_eviction_hdr;
1731 buf->b_next = arc_eviction_list;
1732 arc_eviction_list = buf;
428870ff 1733 mutex_exit(&buf->b_evict_lock);
34dc7c2f
BB
1734 mutex_exit(&arc_eviction_mtx);
1735 } else {
1736 arc_buf_destroy(hdr->b_buf, FALSE, TRUE);
1737 }
1738 }
1739 if (hdr->b_freeze_cksum != NULL) {
1740 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1741 hdr->b_freeze_cksum = NULL;
1742 }
1743
1744 ASSERT(!list_link_active(&hdr->b_arc_node));
1745 ASSERT3P(hdr->b_hash_next, ==, NULL);
1746 ASSERT3P(hdr->b_acb, ==, NULL);
1747 kmem_cache_free(hdr_cache, hdr);
1748}
1749
1750void
1751arc_buf_free(arc_buf_t *buf, void *tag)
1752{
1753 arc_buf_hdr_t *hdr = buf->b_hdr;
1754 int hashed = hdr->b_state != arc_anon;
1755
1756 ASSERT(buf->b_efunc == NULL);
1757 ASSERT(buf->b_data != NULL);
1758
1759 if (hashed) {
1760 kmutex_t *hash_lock = HDR_LOCK(hdr);
1761
1762 mutex_enter(hash_lock);
428870ff
BB
1763 hdr = buf->b_hdr;
1764 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1765
34dc7c2f 1766 (void) remove_reference(hdr, hash_lock, tag);
428870ff 1767 if (hdr->b_datacnt > 1) {
34dc7c2f 1768 arc_buf_destroy(buf, FALSE, TRUE);
428870ff
BB
1769 } else {
1770 ASSERT(buf == hdr->b_buf);
1771 ASSERT(buf->b_efunc == NULL);
34dc7c2f 1772 hdr->b_flags |= ARC_BUF_AVAILABLE;
428870ff 1773 }
34dc7c2f
BB
1774 mutex_exit(hash_lock);
1775 } else if (HDR_IO_IN_PROGRESS(hdr)) {
1776 int destroy_hdr;
1777 /*
1778 * We are in the middle of an async write. Don't destroy
1779 * this buffer unless the write completes before we finish
1780 * decrementing the reference count.
1781 */
1782 mutex_enter(&arc_eviction_mtx);
1783 (void) remove_reference(hdr, NULL, tag);
1784 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1785 destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
1786 mutex_exit(&arc_eviction_mtx);
1787 if (destroy_hdr)
1788 arc_hdr_destroy(hdr);
1789 } else {
428870ff 1790 if (remove_reference(hdr, NULL, tag) > 0)
34dc7c2f 1791 arc_buf_destroy(buf, FALSE, TRUE);
428870ff 1792 else
34dc7c2f 1793 arc_hdr_destroy(hdr);
34dc7c2f
BB
1794 }
1795}
1796
13fe0198 1797boolean_t
34dc7c2f
BB
1798arc_buf_remove_ref(arc_buf_t *buf, void* tag)
1799{
1800 arc_buf_hdr_t *hdr = buf->b_hdr;
b4f7f105 1801 kmutex_t *hash_lock = NULL;
13fe0198 1802 boolean_t no_callback = (buf->b_efunc == NULL);
34dc7c2f
BB
1803
1804 if (hdr->b_state == arc_anon) {
428870ff 1805 ASSERT(hdr->b_datacnt == 1);
34dc7c2f
BB
1806 arc_buf_free(buf, tag);
1807 return (no_callback);
1808 }
1809
b4f7f105 1810 hash_lock = HDR_LOCK(hdr);
34dc7c2f 1811 mutex_enter(hash_lock);
428870ff
BB
1812 hdr = buf->b_hdr;
1813 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
34dc7c2f
BB
1814 ASSERT(hdr->b_state != arc_anon);
1815 ASSERT(buf->b_data != NULL);
1816
1817 (void) remove_reference(hdr, hash_lock, tag);
1818 if (hdr->b_datacnt > 1) {
1819 if (no_callback)
1820 arc_buf_destroy(buf, FALSE, TRUE);
1821 } else if (no_callback) {
1822 ASSERT(hdr->b_buf == buf && buf->b_next == NULL);
428870ff 1823 ASSERT(buf->b_efunc == NULL);
34dc7c2f
BB
1824 hdr->b_flags |= ARC_BUF_AVAILABLE;
1825 }
1826 ASSERT(no_callback || hdr->b_datacnt > 1 ||
1827 refcount_is_zero(&hdr->b_refcnt));
1828 mutex_exit(hash_lock);
1829 return (no_callback);
1830}
1831
1832int
1833arc_buf_size(arc_buf_t *buf)
1834{
1835 return (buf->b_hdr->b_size);
1836}
1837
1eb5bfa3
GW
1838/*
1839 * Called from the DMU to determine if the current buffer should be
1840 * evicted. In order to ensure proper locking, the eviction must be initiated
1841 * from the DMU. Return true if the buffer is associated with user data and
1842 * duplicate buffers still exist.
1843 */
1844boolean_t
1845arc_buf_eviction_needed(arc_buf_t *buf)
1846{
1847 arc_buf_hdr_t *hdr;
1848 boolean_t evict_needed = B_FALSE;
1849
1850 if (zfs_disable_dup_eviction)
1851 return (B_FALSE);
1852
1853 mutex_enter(&buf->b_evict_lock);
1854 hdr = buf->b_hdr;
1855 if (hdr == NULL) {
1856 /*
1857 * We are in arc_do_user_evicts(); let that function
1858 * perform the eviction.
1859 */
1860 ASSERT(buf->b_data == NULL);
1861 mutex_exit(&buf->b_evict_lock);
1862 return (B_FALSE);
1863 } else if (buf->b_data == NULL) {
1864 /*
1865 * We have already been added to the arc eviction list;
1866 * recommend eviction.
1867 */
1868 ASSERT3P(hdr, ==, &arc_eviction_hdr);
1869 mutex_exit(&buf->b_evict_lock);
1870 return (B_TRUE);
1871 }
1872
1873 if (hdr->b_datacnt > 1 && hdr->b_type == ARC_BUFC_DATA)
1874 evict_needed = B_TRUE;
1875
1876 mutex_exit(&buf->b_evict_lock);
1877 return (evict_needed);
1878}
1879
34dc7c2f
BB
1880/*
1881 * Evict buffers from list until we've removed the specified number of
1882 * bytes. Move the removed buffers to the appropriate evict state.
1883 * If the recycle flag is set, then attempt to "recycle" a buffer:
1884 * - look for a buffer to evict that is `bytes' long.
1885 * - return the data block from this buffer rather than freeing it.
1886 * This flag is used by callers that are trying to make space for a
1887 * new buffer in a full arc cache.
1888 *
1889 * This function makes a "best effort". It skips over any buffers
1890 * it can't get a hash_lock on, and so may not catch all candidates.
1891 * It may also return without evicting as much space as requested.
1892 */
1893static void *
d164b209 1894arc_evict(arc_state_t *state, uint64_t spa, int64_t bytes, boolean_t recycle,
34dc7c2f
BB
1895 arc_buf_contents_t type)
1896{
1897 arc_state_t *evicted_state;
1898 uint64_t bytes_evicted = 0, skipped = 0, missed = 0;
1899 arc_buf_hdr_t *ab, *ab_prev = NULL;
1900 list_t *list = &state->arcs_list[type];
1901 kmutex_t *hash_lock;
1902 boolean_t have_lock;
1903 void *stolen = NULL;
e8b96c60
MA
1904 arc_buf_hdr_t marker = {{{ 0 }}};
1905 int count = 0;
34dc7c2f
BB
1906
1907 ASSERT(state == arc_mru || state == arc_mfu);
1908
1909 evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
1910
da8ccd0e 1911top:
34dc7c2f
BB
1912 mutex_enter(&state->arcs_mtx);
1913 mutex_enter(&evicted_state->arcs_mtx);
1914
1915 for (ab = list_tail(list); ab; ab = ab_prev) {
1916 ab_prev = list_prev(list, ab);
1917 /* prefetch buffers have a minimum lifespan */
1918 if (HDR_IO_IN_PROGRESS(ab) ||
1919 (spa && ab->b_spa != spa) ||
1920 (ab->b_flags & (ARC_PREFETCH|ARC_INDIRECT) &&
428870ff 1921 ddi_get_lbolt() - ab->b_arc_access <
bce45ec9 1922 zfs_arc_min_prefetch_lifespan)) {
34dc7c2f
BB
1923 skipped++;
1924 continue;
1925 }
1926 /* "lookahead" for better eviction candidate */
1927 if (recycle && ab->b_size != bytes &&
1928 ab_prev && ab_prev->b_size == bytes)
1929 continue;
e8b96c60
MA
1930
1931 /* ignore markers */
1932 if (ab->b_spa == 0)
1933 continue;
1934
1935 /*
1936 * It may take a long time to evict all the bufs requested.
1937 * To avoid blocking all arc activity, periodically drop
1938 * the arcs_mtx and give other threads a chance to run
1939 * before reacquiring the lock.
1940 *
1941 * If we are looking for a buffer to recycle, we are in
1942 * the hot code path, so don't sleep.
1943 */
1944 if (!recycle && count++ > arc_evict_iterations) {
1945 list_insert_after(list, ab, &marker);
1946 mutex_exit(&evicted_state->arcs_mtx);
1947 mutex_exit(&state->arcs_mtx);
1948 kpreempt(KPREEMPT_SYNC);
1949 mutex_enter(&state->arcs_mtx);
1950 mutex_enter(&evicted_state->arcs_mtx);
1951 ab_prev = list_prev(list, &marker);
1952 list_remove(list, &marker);
1953 count = 0;
1954 continue;
1955 }
1956
34dc7c2f
BB
1957 hash_lock = HDR_LOCK(ab);
1958 have_lock = MUTEX_HELD(hash_lock);
1959 if (have_lock || mutex_tryenter(hash_lock)) {
c99c9001 1960 ASSERT0(refcount_count(&ab->b_refcnt));
34dc7c2f
BB
1961 ASSERT(ab->b_datacnt > 0);
1962 while (ab->b_buf) {
1963 arc_buf_t *buf = ab->b_buf;
428870ff 1964 if (!mutex_tryenter(&buf->b_evict_lock)) {
b128c09f
BB
1965 missed += 1;
1966 break;
1967 }
34dc7c2f
BB
1968 if (buf->b_data) {
1969 bytes_evicted += ab->b_size;
1970 if (recycle && ab->b_type == type &&
1971 ab->b_size == bytes &&
1972 !HDR_L2_WRITING(ab)) {
1973 stolen = buf->b_data;
1974 recycle = FALSE;
1975 }
1976 }
1977 if (buf->b_efunc) {
1978 mutex_enter(&arc_eviction_mtx);
1979 arc_buf_destroy(buf,
1980 buf->b_data == stolen, FALSE);
1981 ab->b_buf = buf->b_next;
1982 buf->b_hdr = &arc_eviction_hdr;
1983 buf->b_next = arc_eviction_list;
1984 arc_eviction_list = buf;
1985 mutex_exit(&arc_eviction_mtx);
428870ff 1986 mutex_exit(&buf->b_evict_lock);
34dc7c2f 1987 } else {
428870ff 1988 mutex_exit(&buf->b_evict_lock);
34dc7c2f
BB
1989 arc_buf_destroy(buf,
1990 buf->b_data == stolen, TRUE);
1991 }
1992 }
428870ff
BB
1993
1994 if (ab->b_l2hdr) {
1995 ARCSTAT_INCR(arcstat_evict_l2_cached,
1996 ab->b_size);
1997 } else {
1998 if (l2arc_write_eligible(ab->b_spa, ab)) {
1999 ARCSTAT_INCR(arcstat_evict_l2_eligible,
2000 ab->b_size);
2001 } else {
2002 ARCSTAT_INCR(
2003 arcstat_evict_l2_ineligible,
2004 ab->b_size);
2005 }
2006 }
2007
b128c09f
BB
2008 if (ab->b_datacnt == 0) {
2009 arc_change_state(evicted_state, ab, hash_lock);
2010 ASSERT(HDR_IN_HASH_TABLE(ab));
2011 ab->b_flags |= ARC_IN_HASH_TABLE;
2012 ab->b_flags &= ~ARC_BUF_AVAILABLE;
2013 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, ab);
2014 }
34dc7c2f
BB
2015 if (!have_lock)
2016 mutex_exit(hash_lock);
2017 if (bytes >= 0 && bytes_evicted >= bytes)
2018 break;
2019 } else {
2020 missed += 1;
2021 }
2022 }
2023
2024 mutex_exit(&evicted_state->arcs_mtx);
2025 mutex_exit(&state->arcs_mtx);
2026
da8ccd0e
PS
2027 if (list == &state->arcs_list[ARC_BUFC_DATA] &&
2028 (bytes < 0 || bytes_evicted < bytes)) {
2029 /* Prevent second pass from recycling metadata into data */
2030 recycle = FALSE;
2031 type = ARC_BUFC_METADATA;
2032 list = &state->arcs_list[type];
2033 goto top;
2034 }
2035
34dc7c2f 2036 if (bytes_evicted < bytes)
3f504482 2037 dprintf("only evicted %lld bytes from %x\n",
34dc7c2f
BB
2038 (longlong_t)bytes_evicted, state);
2039
2040 if (skipped)
2041 ARCSTAT_INCR(arcstat_evict_skip, skipped);
2042
2043 if (missed)
2044 ARCSTAT_INCR(arcstat_mutex_miss, missed);
2045
2046 /*
e8b96c60
MA
2047 * Note: we have just evicted some data into the ghost state,
2048 * potentially putting the ghost size over the desired size. Rather
2049 * that evicting from the ghost list in this hot code path, leave
2050 * this chore to the arc_reclaim_thread().
34dc7c2f 2051 */
34dc7c2f
BB
2052
2053 return (stolen);
2054}
2055
2056/*
2057 * Remove buffers from list until we've removed the specified number of
2058 * bytes. Destroy the buffers that are removed.
2059 */
2060static void
68121a03
BB
2061arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes,
2062 arc_buf_contents_t type)
34dc7c2f
BB
2063{
2064 arc_buf_hdr_t *ab, *ab_prev;
2598c001 2065 arc_buf_hdr_t marker;
68121a03 2066 list_t *list = &state->arcs_list[type];
34dc7c2f
BB
2067 kmutex_t *hash_lock;
2068 uint64_t bytes_deleted = 0;
2069 uint64_t bufs_skipped = 0;
e8b96c60 2070 int count = 0;
34dc7c2f
BB
2071
2072 ASSERT(GHOST_STATE(state));
d1d7e268 2073 bzero(&marker, sizeof (marker));
34dc7c2f
BB
2074top:
2075 mutex_enter(&state->arcs_mtx);
2076 for (ab = list_tail(list); ab; ab = ab_prev) {
2077 ab_prev = list_prev(list, ab);
e8b96c60
MA
2078 if (ab->b_type > ARC_BUFC_NUMTYPES)
2079 panic("invalid ab=%p", (void *)ab);
34dc7c2f
BB
2080 if (spa && ab->b_spa != spa)
2081 continue;
572e2857
BB
2082
2083 /* ignore markers */
2084 if (ab->b_spa == 0)
2085 continue;
2086
34dc7c2f 2087 hash_lock = HDR_LOCK(ab);
428870ff
BB
2088 /* caller may be trying to modify this buffer, skip it */
2089 if (MUTEX_HELD(hash_lock))
2090 continue;
e8b96c60
MA
2091
2092 /*
2093 * It may take a long time to evict all the bufs requested.
2094 * To avoid blocking all arc activity, periodically drop
2095 * the arcs_mtx and give other threads a chance to run
2096 * before reacquiring the lock.
2097 */
2098 if (count++ > arc_evict_iterations) {
2099 list_insert_after(list, ab, &marker);
2100 mutex_exit(&state->arcs_mtx);
2101 kpreempt(KPREEMPT_SYNC);
2102 mutex_enter(&state->arcs_mtx);
2103 ab_prev = list_prev(list, &marker);
2104 list_remove(list, &marker);
2105 count = 0;
2106 continue;
2107 }
34dc7c2f
BB
2108 if (mutex_tryenter(hash_lock)) {
2109 ASSERT(!HDR_IO_IN_PROGRESS(ab));
2110 ASSERT(ab->b_buf == NULL);
2111 ARCSTAT_BUMP(arcstat_deleted);
2112 bytes_deleted += ab->b_size;
2113
2114 if (ab->b_l2hdr != NULL) {
2115 /*
2116 * This buffer is cached on the 2nd Level ARC;
2117 * don't destroy the header.
2118 */
2119 arc_change_state(arc_l2c_only, ab, hash_lock);
2120 mutex_exit(hash_lock);
2121 } else {
2122 arc_change_state(arc_anon, ab, hash_lock);
2123 mutex_exit(hash_lock);
2124 arc_hdr_destroy(ab);
2125 }
2126
2127 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, ab);
2128 if (bytes >= 0 && bytes_deleted >= bytes)
2129 break;
572e2857
BB
2130 } else if (bytes < 0) {
2131 /*
2132 * Insert a list marker and then wait for the
2133 * hash lock to become available. Once its
2134 * available, restart from where we left off.
2135 */
2136 list_insert_after(list, ab, &marker);
2137 mutex_exit(&state->arcs_mtx);
2138 mutex_enter(hash_lock);
2139 mutex_exit(hash_lock);
2140 mutex_enter(&state->arcs_mtx);
2141 ab_prev = list_prev(list, &marker);
2142 list_remove(list, &marker);
e8b96c60 2143 } else {
34dc7c2f 2144 bufs_skipped += 1;
e8b96c60 2145 }
34dc7c2f
BB
2146 }
2147 mutex_exit(&state->arcs_mtx);
2148
2149 if (list == &state->arcs_list[ARC_BUFC_DATA] &&
2150 (bytes < 0 || bytes_deleted < bytes)) {
2151 list = &state->arcs_list[ARC_BUFC_METADATA];
2152 goto top;
2153 }
2154
2155 if (bufs_skipped) {
2156 ARCSTAT_INCR(arcstat_mutex_miss, bufs_skipped);
2157 ASSERT(bytes >= 0);
2158 }
2159
2160 if (bytes_deleted < bytes)
3f504482 2161 dprintf("only deleted %lld bytes from %p\n",
34dc7c2f
BB
2162 (longlong_t)bytes_deleted, state);
2163}
2164
2165static void
2166arc_adjust(void)
2167{
d164b209
BB
2168 int64_t adjustment, delta;
2169
2170 /*
2171 * Adjust MRU size
2172 */
34dc7c2f 2173
572e2857 2174 adjustment = MIN((int64_t)(arc_size - arc_c),
77765b54 2175 (int64_t)(arc_anon->arcs_size + arc_mru->arcs_size - arc_p));
34dc7c2f 2176
da8ccd0e
PS
2177 if (adjustment > 0 && arc_mru->arcs_size > 0) {
2178 delta = MIN(arc_mru->arcs_size, adjustment);
b8864a23 2179 (void) arc_evict(arc_mru, 0, delta, FALSE, ARC_BUFC_DATA);
34dc7c2f
BB
2180 }
2181
d164b209
BB
2182 /*
2183 * Adjust MFU size
2184 */
34dc7c2f 2185
d164b209
BB
2186 adjustment = arc_size - arc_c;
2187
da8ccd0e
PS
2188 if (adjustment > 0 && arc_mfu->arcs_size > 0) {
2189 delta = MIN(arc_mfu->arcs_size, adjustment);
b8864a23 2190 (void) arc_evict(arc_mfu, 0, delta, FALSE, ARC_BUFC_DATA);
d164b209 2191 }
34dc7c2f 2192
d164b209
BB
2193 /*
2194 * Adjust ghost lists
2195 */
34dc7c2f 2196
d164b209
BB
2197 adjustment = arc_mru->arcs_size + arc_mru_ghost->arcs_size - arc_c;
2198
2199 if (adjustment > 0 && arc_mru_ghost->arcs_size > 0) {
2200 delta = MIN(arc_mru_ghost->arcs_size, adjustment);
68121a03 2201 arc_evict_ghost(arc_mru_ghost, 0, delta, ARC_BUFC_DATA);
d164b209 2202 }
34dc7c2f 2203
d164b209
BB
2204 adjustment =
2205 arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size - arc_c;
34dc7c2f 2206
d164b209
BB
2207 if (adjustment > 0 && arc_mfu_ghost->arcs_size > 0) {
2208 delta = MIN(arc_mfu_ghost->arcs_size, adjustment);
68121a03 2209 arc_evict_ghost(arc_mfu_ghost, 0, delta, ARC_BUFC_DATA);
34dc7c2f
BB
2210 }
2211}
2212
ab26409d
BB
2213/*
2214 * Request that arc user drop references so that N bytes can be released
2215 * from the cache. This provides a mechanism to ensure the arc can honor
2216 * the arc_meta_limit and reclaim buffers which are pinned in the cache
2217 * by higher layers. (i.e. the zpl)
2218 */
2219static void
2220arc_do_user_prune(int64_t adjustment)
2221{
2222 arc_prune_func_t *func;
2223 void *private;
2224 arc_prune_t *cp, *np;
2225
2226 mutex_enter(&arc_prune_mtx);
2227
2228 cp = list_head(&arc_prune_list);
2229 while (cp != NULL) {
2230 func = cp->p_pfunc;
2231 private = cp->p_private;
2232 np = list_next(&arc_prune_list, cp);
2233 refcount_add(&cp->p_refcnt, func);
2234 mutex_exit(&arc_prune_mtx);
2235
2236 if (func != NULL)
2237 func(adjustment, private);
2238
2239 mutex_enter(&arc_prune_mtx);
2240
2241 /* User removed prune callback concurrently with execution */
2242 if (refcount_remove(&cp->p_refcnt, func) == 0) {
2243 ASSERT(!list_link_active(&cp->p_node));
2244 refcount_destroy(&cp->p_refcnt);
2245 kmem_free(cp, sizeof (*cp));
2246 }
2247
2248 cp = np;
2249 }
2250
2251 ARCSTAT_BUMP(arcstat_prune);
2252 mutex_exit(&arc_prune_mtx);
2253}
2254
34dc7c2f
BB
2255static void
2256arc_do_user_evicts(void)
2257{
2258 mutex_enter(&arc_eviction_mtx);
2259 while (arc_eviction_list != NULL) {
2260 arc_buf_t *buf = arc_eviction_list;
2261 arc_eviction_list = buf->b_next;
428870ff 2262 mutex_enter(&buf->b_evict_lock);
34dc7c2f 2263 buf->b_hdr = NULL;
428870ff 2264 mutex_exit(&buf->b_evict_lock);
34dc7c2f
BB
2265 mutex_exit(&arc_eviction_mtx);
2266
2267 if (buf->b_efunc != NULL)
2268 VERIFY(buf->b_efunc(buf) == 0);
2269
2270 buf->b_efunc = NULL;
2271 buf->b_private = NULL;
2272 kmem_cache_free(buf_cache, buf);
2273 mutex_enter(&arc_eviction_mtx);
2274 }
2275 mutex_exit(&arc_eviction_mtx);
2276}
2277
ab26409d
BB
2278/*
2279 * Evict only meta data objects from the cache leaving the data objects.
2280 * This is only used to enforce the tunable arc_meta_limit, if we are
2281 * unable to evict enough buffers notify the user via the prune callback.
2282 */
94520ca4
PS
2283static void
2284arc_adjust_meta(void)
ab26409d 2285{
94520ca4 2286 int64_t adjustmnt, delta;
ab26409d 2287
94520ca4
PS
2288 /*
2289 * This slightly differs than the way we evict from the mru in
2290 * arc_adjust because we don't have a "target" value (i.e. no
2291 * "meta" arc_p). As a result, I think we can completely
2292 * cannibalize the metadata in the MRU before we evict the
2293 * metadata from the MFU. I think we probably need to implement a
2294 * "metadata arc_p" value to do this properly.
2295 */
2296 adjustmnt = arc_meta_used - arc_meta_limit;
2297
2298 if (adjustmnt > 0 && arc_mru->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2299 delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_METADATA], adjustmnt);
ab26409d 2300 arc_evict(arc_mru, 0, delta, FALSE, ARC_BUFC_METADATA);
94520ca4 2301 adjustmnt -= delta;
ab26409d
BB
2302 }
2303
94520ca4
PS
2304 /*
2305 * We can't afford to recalculate adjustmnt here. If we do,
2306 * new metadata buffers can sneak into the MRU or ANON lists,
2307 * thus penalize the MFU metadata. Although the fudge factor is
2308 * small, it has been empirically shown to be significant for
2309 * certain workloads (e.g. creating many empty directories). As
2310 * such, we use the original calculation for adjustmnt, and
2311 * simply decrement the amount of data evicted from the MRU.
2312 */
2313
2314 if (adjustmnt > 0 && arc_mfu->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2315 delta = MIN(arc_mfu->arcs_lsize[ARC_BUFC_METADATA], adjustmnt);
ab26409d 2316 arc_evict(arc_mfu, 0, delta, FALSE, ARC_BUFC_METADATA);
ab26409d
BB
2317 }
2318
94520ca4
PS
2319 adjustmnt = arc_mru->arcs_lsize[ARC_BUFC_METADATA] +
2320 arc_mru_ghost->arcs_lsize[ARC_BUFC_METADATA] - arc_meta_limit;
2321
2322 if (adjustmnt > 0 && arc_mru_ghost->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2323 delta = MIN(adjustmnt,
2324 arc_mru_ghost->arcs_lsize[ARC_BUFC_METADATA]);
2325 arc_evict_ghost(arc_mru_ghost, 0, delta, ARC_BUFC_METADATA);
2326 }
2327
2328 adjustmnt = arc_mru_ghost->arcs_lsize[ARC_BUFC_METADATA] +
2329 arc_mfu_ghost->arcs_lsize[ARC_BUFC_METADATA] - arc_meta_limit;
2330
2331 if (adjustmnt > 0 && arc_mfu_ghost->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2332 delta = MIN(adjustmnt,
2333 arc_mfu_ghost->arcs_lsize[ARC_BUFC_METADATA]);
2334 arc_evict_ghost(arc_mfu_ghost, 0, delta, ARC_BUFC_METADATA);
2335 }
2336
2337 if (arc_meta_used > arc_meta_limit)
bce45ec9 2338 arc_do_user_prune(zfs_arc_meta_prune);
ab26409d
BB
2339}
2340
34dc7c2f
BB
2341/*
2342 * Flush all *evictable* data from the cache for the given spa.
2343 * NOTE: this will not touch "active" (i.e. referenced) data.
2344 */
2345void
2346arc_flush(spa_t *spa)
2347{
d164b209
BB
2348 uint64_t guid = 0;
2349
2350 if (spa)
3541dc6d 2351 guid = spa_load_guid(spa);
d164b209 2352
34dc7c2f 2353 while (list_head(&arc_mru->arcs_list[ARC_BUFC_DATA])) {
d164b209 2354 (void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_DATA);
34dc7c2f
BB
2355 if (spa)
2356 break;
2357 }
2358 while (list_head(&arc_mru->arcs_list[ARC_BUFC_METADATA])) {
d164b209 2359 (void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_METADATA);
34dc7c2f
BB
2360 if (spa)
2361 break;
2362 }
2363 while (list_head(&arc_mfu->arcs_list[ARC_BUFC_DATA])) {
d164b209 2364 (void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_DATA);
34dc7c2f
BB
2365 if (spa)
2366 break;
2367 }
2368 while (list_head(&arc_mfu->arcs_list[ARC_BUFC_METADATA])) {
d164b209 2369 (void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_METADATA);
34dc7c2f
BB
2370 if (spa)
2371 break;
2372 }
2373
68121a03
BB
2374 arc_evict_ghost(arc_mru_ghost, guid, -1, ARC_BUFC_DATA);
2375 arc_evict_ghost(arc_mfu_ghost, guid, -1, ARC_BUFC_DATA);
34dc7c2f
BB
2376
2377 mutex_enter(&arc_reclaim_thr_lock);
2378 arc_do_user_evicts();
2379 mutex_exit(&arc_reclaim_thr_lock);
2380 ASSERT(spa || arc_eviction_list == NULL);
2381}
2382
34dc7c2f 2383void
302f753f 2384arc_shrink(uint64_t bytes)
34dc7c2f
BB
2385{
2386 if (arc_c > arc_c_min) {
2387 uint64_t to_free;
2388
bce45ec9 2389 to_free = bytes ? bytes : arc_c >> zfs_arc_shrink_shift;
302f753f 2390
34dc7c2f
BB
2391 if (arc_c > arc_c_min + to_free)
2392 atomic_add_64(&arc_c, -to_free);
2393 else
2394 arc_c = arc_c_min;
2395
39e055c4
PS
2396 to_free = bytes ? bytes : arc_p >> zfs_arc_shrink_shift;
2397
f521ce1b 2398 if (arc_p > to_free)
39e055c4
PS
2399 atomic_add_64(&arc_p, -to_free);
2400 else
f521ce1b 2401 arc_p = 0;
39e055c4 2402
34dc7c2f
BB
2403 if (arc_c > arc_size)
2404 arc_c = MAX(arc_size, arc_c_min);
2405 if (arc_p > arc_c)
2406 arc_p = (arc_c >> 1);
2407 ASSERT(arc_c >= arc_c_min);
2408 ASSERT((int64_t)arc_p >= 0);
2409 }
2410
2411 if (arc_size > arc_c)
2412 arc_adjust();
2413}
2414
34dc7c2f 2415static void
302f753f 2416arc_kmem_reap_now(arc_reclaim_strategy_t strat, uint64_t bytes)
34dc7c2f
BB
2417{
2418 size_t i;
2419 kmem_cache_t *prev_cache = NULL;
2420 kmem_cache_t *prev_data_cache = NULL;
2421 extern kmem_cache_t *zio_buf_cache[];
2422 extern kmem_cache_t *zio_data_buf_cache[];
34dc7c2f
BB
2423
2424 /*
2425 * An aggressive reclamation will shrink the cache size as well as
2426 * reap free buffers from the arc kmem caches.
2427 */
2428 if (strat == ARC_RECLAIM_AGGR)
302f753f 2429 arc_shrink(bytes);
34dc7c2f
BB
2430
2431 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
2432 if (zio_buf_cache[i] != prev_cache) {
2433 prev_cache = zio_buf_cache[i];
2434 kmem_cache_reap_now(zio_buf_cache[i]);
2435 }
2436 if (zio_data_buf_cache[i] != prev_data_cache) {
2437 prev_data_cache = zio_data_buf_cache[i];
2438 kmem_cache_reap_now(zio_data_buf_cache[i]);
2439 }
2440 }
ab26409d 2441
34dc7c2f
BB
2442 kmem_cache_reap_now(buf_cache);
2443 kmem_cache_reap_now(hdr_cache);
2444}
2445
302f753f
BB
2446/*
2447 * Unlike other ZFS implementations this thread is only responsible for
2448 * adapting the target ARC size on Linux. The responsibility for memory
2449 * reclamation has been entirely delegated to the arc_shrinker_func()
2450 * which is registered with the VM. To reflect this change in behavior
2451 * the arc_reclaim thread has been renamed to arc_adapt.
2452 */
34dc7c2f 2453static void
302f753f 2454arc_adapt_thread(void)
34dc7c2f 2455{
34dc7c2f
BB
2456 callb_cpr_t cpr;
2457
2458 CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
2459
2460 mutex_enter(&arc_reclaim_thr_lock);
2461 while (arc_thread_exit == 0) {
302f753f
BB
2462#ifndef _KERNEL
2463 arc_reclaim_strategy_t last_reclaim = ARC_RECLAIM_CONS;
2464
2465 if (spa_get_random(100) == 0) {
34dc7c2f
BB
2466
2467 if (arc_no_grow) {
2468 if (last_reclaim == ARC_RECLAIM_CONS) {
2469 last_reclaim = ARC_RECLAIM_AGGR;
2470 } else {
2471 last_reclaim = ARC_RECLAIM_CONS;
2472 }
2473 } else {
2474 arc_no_grow = TRUE;
2475 last_reclaim = ARC_RECLAIM_AGGR;
2476 membar_producer();
2477 }
2478
2479 /* reset the growth delay for every reclaim */
d1d7e268
MK
2480 arc_grow_time = ddi_get_lbolt() +
2481 (zfs_arc_grow_retry * hz);
34dc7c2f 2482
302f753f 2483 arc_kmem_reap_now(last_reclaim, 0);
b128c09f 2484 arc_warm = B_TRUE;
302f753f
BB
2485 }
2486#endif /* !_KERNEL */
34dc7c2f 2487
302f753f 2488 /* No recent memory pressure allow the ARC to grow. */
0b75bdb3
CC
2489 if (arc_no_grow &&
2490 ddi_time_after_eq(ddi_get_lbolt(), arc_grow_time))
34dc7c2f 2491 arc_no_grow = FALSE;
34dc7c2f 2492
94520ca4 2493 arc_adjust_meta();
6a8f9b6b 2494
572e2857 2495 arc_adjust();
34dc7c2f
BB
2496
2497 if (arc_eviction_list != NULL)
2498 arc_do_user_evicts();
2499
2500 /* block until needed, or one second, whichever is shorter */
2501 CALLB_CPR_SAFE_BEGIN(&cpr);
5b63b3eb 2502 (void) cv_timedwait_interruptible(&arc_reclaim_thr_cv,
428870ff 2503 &arc_reclaim_thr_lock, (ddi_get_lbolt() + hz));
34dc7c2f 2504 CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
bce45ec9
BB
2505
2506
2507 /* Allow the module options to be changed */
2508 if (zfs_arc_max > 64 << 20 &&
2509 zfs_arc_max < physmem * PAGESIZE &&
2510 zfs_arc_max != arc_c_max)
2511 arc_c_max = zfs_arc_max;
2512
2513 if (zfs_arc_min > 0 &&
2514 zfs_arc_min < arc_c_max &&
2515 zfs_arc_min != arc_c_min)
2516 arc_c_min = zfs_arc_min;
2517
2518 if (zfs_arc_meta_limit > 0 &&
2519 zfs_arc_meta_limit <= arc_c_max &&
2520 zfs_arc_meta_limit != arc_meta_limit)
2521 arc_meta_limit = zfs_arc_meta_limit;
2522
2523
2524
34dc7c2f
BB
2525 }
2526
2527 arc_thread_exit = 0;
2528 cv_broadcast(&arc_reclaim_thr_cv);
2529 CALLB_CPR_EXIT(&cpr); /* drops arc_reclaim_thr_lock */
2530 thread_exit();
2531}
2532
7cb67b45
BB
2533#ifdef _KERNEL
2534/*
302f753f
BB
2535 * Determine the amount of memory eligible for eviction contained in the
2536 * ARC. All clean data reported by the ghost lists can always be safely
2537 * evicted. Due to arc_c_min, the same does not hold for all clean data
2538 * contained by the regular mru and mfu lists.
2539 *
2540 * In the case of the regular mru and mfu lists, we need to report as
2541 * much clean data as possible, such that evicting that same reported
2542 * data will not bring arc_size below arc_c_min. Thus, in certain
2543 * circumstances, the total amount of clean data in the mru and mfu
2544 * lists might not actually be evictable.
2545 *
2546 * The following two distinct cases are accounted for:
2547 *
2548 * 1. The sum of the amount of dirty data contained by both the mru and
2549 * mfu lists, plus the ARC's other accounting (e.g. the anon list),
2550 * is greater than or equal to arc_c_min.
2551 * (i.e. amount of dirty data >= arc_c_min)
2552 *
2553 * This is the easy case; all clean data contained by the mru and mfu
2554 * lists is evictable. Evicting all clean data can only drop arc_size
2555 * to the amount of dirty data, which is greater than arc_c_min.
2556 *
2557 * 2. The sum of the amount of dirty data contained by both the mru and
2558 * mfu lists, plus the ARC's other accounting (e.g. the anon list),
2559 * is less than arc_c_min.
2560 * (i.e. arc_c_min > amount of dirty data)
2561 *
2562 * 2.1. arc_size is greater than or equal arc_c_min.
2563 * (i.e. arc_size >= arc_c_min > amount of dirty data)
2564 *
2565 * In this case, not all clean data from the regular mru and mfu
2566 * lists is actually evictable; we must leave enough clean data
2567 * to keep arc_size above arc_c_min. Thus, the maximum amount of
2568 * evictable data from the two lists combined, is exactly the
2569 * difference between arc_size and arc_c_min.
2570 *
2571 * 2.2. arc_size is less than arc_c_min
2572 * (i.e. arc_c_min > arc_size > amount of dirty data)
2573 *
2574 * In this case, none of the data contained in the mru and mfu
2575 * lists is evictable, even if it's clean. Since arc_size is
2576 * already below arc_c_min, evicting any more would only
2577 * increase this negative difference.
7cb67b45 2578 */
302f753f
BB
2579static uint64_t
2580arc_evictable_memory(void) {
2581 uint64_t arc_clean =
2582 arc_mru->arcs_lsize[ARC_BUFC_DATA] +
2583 arc_mru->arcs_lsize[ARC_BUFC_METADATA] +
2584 arc_mfu->arcs_lsize[ARC_BUFC_DATA] +
2585 arc_mfu->arcs_lsize[ARC_BUFC_METADATA];
2586 uint64_t ghost_clean =
2587 arc_mru_ghost->arcs_lsize[ARC_BUFC_DATA] +
2588 arc_mru_ghost->arcs_lsize[ARC_BUFC_METADATA] +
2589 arc_mfu_ghost->arcs_lsize[ARC_BUFC_DATA] +
2590 arc_mfu_ghost->arcs_lsize[ARC_BUFC_METADATA];
2591 uint64_t arc_dirty = MAX((int64_t)arc_size - (int64_t)arc_clean, 0);
2592
2593 if (arc_dirty >= arc_c_min)
2594 return (ghost_clean + arc_clean);
2595
2596 return (ghost_clean + MAX((int64_t)arc_size - (int64_t)arc_c_min, 0));
2597}
2598
7e7baeca
BB
2599static int
2600__arc_shrinker_func(struct shrinker *shrink, struct shrink_control *sc)
7cb67b45 2601{
302f753f 2602 uint64_t pages;
7cb67b45 2603
302f753f
BB
2604 /* The arc is considered warm once reclaim has occurred */
2605 if (unlikely(arc_warm == B_FALSE))
2606 arc_warm = B_TRUE;
7cb67b45 2607
302f753f
BB
2608 /* Return the potential number of reclaimable pages */
2609 pages = btop(arc_evictable_memory());
2610 if (sc->nr_to_scan == 0)
2611 return (pages);
3fd70ee6
BB
2612
2613 /* Not allowed to perform filesystem reclaim */
7e7baeca 2614 if (!(sc->gfp_mask & __GFP_FS))
3fd70ee6
BB
2615 return (-1);
2616
7cb67b45
BB
2617 /* Reclaim in progress */
2618 if (mutex_tryenter(&arc_reclaim_thr_lock) == 0)
2619 return (-1);
2620
302f753f
BB
2621 /*
2622 * Evict the requested number of pages by shrinking arc_c the
2623 * requested amount. If there is nothing left to evict just
2624 * reap whatever we can from the various arc slabs.
2625 */
2626 if (pages > 0) {
2627 arc_kmem_reap_now(ARC_RECLAIM_AGGR, ptob(sc->nr_to_scan));
1e3cb67b 2628 pages = btop(arc_evictable_memory());
302f753f
BB
2629 } else {
2630 arc_kmem_reap_now(ARC_RECLAIM_CONS, ptob(sc->nr_to_scan));
1e3cb67b 2631 pages = -1;
302f753f
BB
2632 }
2633
2634 /*
2635 * When direct reclaim is observed it usually indicates a rapid
2636 * increase in memory pressure. This occurs because the kswapd
2637 * threads were unable to asynchronously keep enough free memory
2638 * available. In this case set arc_no_grow to briefly pause arc
2639 * growth to avoid compounding the memory pressure.
2640 */
7cb67b45 2641 if (current_is_kswapd()) {
302f753f 2642 ARCSTAT_BUMP(arcstat_memory_indirect_count);
7cb67b45 2643 } else {
302f753f 2644 arc_no_grow = B_TRUE;
bce45ec9 2645 arc_grow_time = ddi_get_lbolt() + (zfs_arc_grow_retry * hz);
302f753f 2646 ARCSTAT_BUMP(arcstat_memory_direct_count);
7cb67b45
BB
2647 }
2648
7cb67b45
BB
2649 mutex_exit(&arc_reclaim_thr_lock);
2650
1e3cb67b 2651 return (pages);
7cb67b45 2652}
7e7baeca 2653SPL_SHRINKER_CALLBACK_WRAPPER(arc_shrinker_func);
7cb67b45
BB
2654
2655SPL_SHRINKER_DECLARE(arc_shrinker, arc_shrinker_func, DEFAULT_SEEKS);
2656#endif /* _KERNEL */
2657
34dc7c2f
BB
2658/*
2659 * Adapt arc info given the number of bytes we are trying to add and
2660 * the state that we are comming from. This function is only called
2661 * when we are adding new content to the cache.
2662 */
2663static void
2664arc_adapt(int bytes, arc_state_t *state)
2665{
2666 int mult;
2667
2668 if (state == arc_l2c_only)
2669 return;
2670
2671 ASSERT(bytes > 0);
2672 /*
2673 * Adapt the target size of the MRU list:
2674 * - if we just hit in the MRU ghost list, then increase
2675 * the target size of the MRU list.
2676 * - if we just hit in the MFU ghost list, then increase
2677 * the target size of the MFU list by decreasing the
2678 * target size of the MRU list.
2679 */
2680 if (state == arc_mru_ghost) {
2681 mult = ((arc_mru_ghost->arcs_size >= arc_mfu_ghost->arcs_size) ?
2682 1 : (arc_mfu_ghost->arcs_size/arc_mru_ghost->arcs_size));
62422785
PS
2683
2684 if (!zfs_arc_p_dampener_disable)
2685 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
34dc7c2f 2686
f521ce1b 2687 arc_p = MIN(arc_c, arc_p + bytes * mult);
34dc7c2f 2688 } else if (state == arc_mfu_ghost) {
d164b209
BB
2689 uint64_t delta;
2690
34dc7c2f
BB
2691 mult = ((arc_mfu_ghost->arcs_size >= arc_mru_ghost->arcs_size) ?
2692 1 : (arc_mru_ghost->arcs_size/arc_mfu_ghost->arcs_size));
62422785
PS
2693
2694 if (!zfs_arc_p_dampener_disable)
2695 mult = MIN(mult, 10);
34dc7c2f 2696
d164b209 2697 delta = MIN(bytes * mult, arc_p);
f521ce1b 2698 arc_p = MAX(0, arc_p - delta);
34dc7c2f
BB
2699 }
2700 ASSERT((int64_t)arc_p >= 0);
2701
34dc7c2f
BB
2702 if (arc_no_grow)
2703 return;
2704
2705 if (arc_c >= arc_c_max)
2706 return;
2707
2708 /*
2709 * If we're within (2 * maxblocksize) bytes of the target
2710 * cache size, increment the target cache size
2711 */
2712 if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
2713 atomic_add_64(&arc_c, (int64_t)bytes);
2714 if (arc_c > arc_c_max)
2715 arc_c = arc_c_max;
2716 else if (state == arc_anon)
2717 atomic_add_64(&arc_p, (int64_t)bytes);
2718 if (arc_p > arc_c)
2719 arc_p = arc_c;
2720 }
2721 ASSERT((int64_t)arc_p >= 0);
2722}
2723
2724/*
2725 * Check if the cache has reached its limits and eviction is required
2726 * prior to insert.
2727 */
2728static int
2729arc_evict_needed(arc_buf_contents_t type)
2730{
2731 if (type == ARC_BUFC_METADATA && arc_meta_used >= arc_meta_limit)
2732 return (1);
2733
302f753f 2734 if (arc_no_grow)
34dc7c2f
BB
2735 return (1);
2736
2737 return (arc_size > arc_c);
2738}
2739
2740/*
2741 * The buffer, supplied as the first argument, needs a data block.
2742 * So, if we are at cache max, determine which cache should be victimized.
2743 * We have the following cases:
2744 *
2745 * 1. Insert for MRU, p > sizeof(arc_anon + arc_mru) ->
2746 * In this situation if we're out of space, but the resident size of the MFU is
2747 * under the limit, victimize the MFU cache to satisfy this insertion request.
2748 *
2749 * 2. Insert for MRU, p <= sizeof(arc_anon + arc_mru) ->
2750 * Here, we've used up all of the available space for the MRU, so we need to
2751 * evict from our own cache instead. Evict from the set of resident MRU
2752 * entries.
2753 *
2754 * 3. Insert for MFU (c - p) > sizeof(arc_mfu) ->
2755 * c minus p represents the MFU space in the cache, since p is the size of the
2756 * cache that is dedicated to the MRU. In this situation there's still space on
2757 * the MFU side, so the MRU side needs to be victimized.
2758 *
2759 * 4. Insert for MFU (c - p) < sizeof(arc_mfu) ->
2760 * MFU's resident set is consuming more space than it has been allotted. In
2761 * this situation, we must victimize our own cache, the MFU, for this insertion.
2762 */
2763static void
2764arc_get_data_buf(arc_buf_t *buf)
2765{
2766 arc_state_t *state = buf->b_hdr->b_state;
2767 uint64_t size = buf->b_hdr->b_size;
2768 arc_buf_contents_t type = buf->b_hdr->b_type;
da8ccd0e
PS
2769 arc_buf_contents_t evict = ARC_BUFC_DATA;
2770 boolean_t recycle = TRUE;
34dc7c2f
BB
2771
2772 arc_adapt(size, state);
2773
2774 /*
2775 * We have not yet reached cache maximum size,
2776 * just allocate a new buffer.
2777 */
2778 if (!arc_evict_needed(type)) {
2779 if (type == ARC_BUFC_METADATA) {
2780 buf->b_data = zio_buf_alloc(size);
cc7f677c 2781 arc_space_consume(size, ARC_SPACE_META);
34dc7c2f
BB
2782 } else {
2783 ASSERT(type == ARC_BUFC_DATA);
2784 buf->b_data = zio_data_buf_alloc(size);
cc7f677c 2785 arc_space_consume(size, ARC_SPACE_DATA);
34dc7c2f
BB
2786 }
2787 goto out;
2788 }
2789
2790 /*
2791 * If we are prefetching from the mfu ghost list, this buffer
2792 * will end up on the mru list; so steal space from there.
2793 */
2794 if (state == arc_mfu_ghost)
2795 state = buf->b_hdr->b_flags & ARC_PREFETCH ? arc_mru : arc_mfu;
2796 else if (state == arc_mru_ghost)
2797 state = arc_mru;
2798
2799 if (state == arc_mru || state == arc_anon) {
2800 uint64_t mru_used = arc_anon->arcs_size + arc_mru->arcs_size;
d164b209 2801 state = (arc_mfu->arcs_lsize[type] >= size &&
34dc7c2f
BB
2802 arc_p > mru_used) ? arc_mfu : arc_mru;
2803 } else {
2804 /* MFU cases */
2805 uint64_t mfu_space = arc_c - arc_p;
d164b209 2806 state = (arc_mru->arcs_lsize[type] >= size &&
34dc7c2f
BB
2807 mfu_space > arc_mfu->arcs_size) ? arc_mru : arc_mfu;
2808 }
ab26409d 2809
da8ccd0e
PS
2810 /*
2811 * Evict data buffers prior to metadata buffers, unless we're
2812 * over the metadata limit and adding a metadata buffer.
2813 */
2814 if (type == ARC_BUFC_METADATA) {
2815 if (arc_meta_used >= arc_meta_limit)
2816 evict = ARC_BUFC_METADATA;
2817 else
2818 /*
2819 * In this case, we're evicting data while
2820 * adding metadata. Thus, to prevent recycling a
2821 * data buffer into a metadata buffer, recycling
2822 * is disabled in the following arc_evict call.
2823 */
2824 recycle = FALSE;
2825 }
2826
2827 if ((buf->b_data = arc_evict(state, 0, size, recycle, evict)) == NULL) {
34dc7c2f
BB
2828 if (type == ARC_BUFC_METADATA) {
2829 buf->b_data = zio_buf_alloc(size);
cc7f677c 2830 arc_space_consume(size, ARC_SPACE_META);
ab26409d
BB
2831
2832 /*
2833 * If we are unable to recycle an existing meta buffer
2834 * signal the reclaim thread. It will notify users
2835 * via the prune callback to drop references. The
2836 * prune callback in run in the context of the reclaim
2837 * thread to avoid deadlocking on the hash_lock.
da8ccd0e 2838 * Of course, only do this when recycle is true.
ab26409d 2839 */
da8ccd0e
PS
2840 if (recycle)
2841 cv_signal(&arc_reclaim_thr_cv);
34dc7c2f
BB
2842 } else {
2843 ASSERT(type == ARC_BUFC_DATA);
2844 buf->b_data = zio_data_buf_alloc(size);
cc7f677c 2845 arc_space_consume(size, ARC_SPACE_DATA);
34dc7c2f 2846 }
ab26409d 2847
da8ccd0e
PS
2848 /* Only bump this if we tried to recycle and failed */
2849 if (recycle)
2850 ARCSTAT_BUMP(arcstat_recycle_miss);
34dc7c2f
BB
2851 }
2852 ASSERT(buf->b_data != NULL);
2853out:
2854 /*
2855 * Update the state size. Note that ghost states have a
2856 * "ghost size" and so don't need to be updated.
2857 */
2858 if (!GHOST_STATE(buf->b_hdr->b_state)) {
2859 arc_buf_hdr_t *hdr = buf->b_hdr;
2860
2861 atomic_add_64(&hdr->b_state->arcs_size, size);
2862 if (list_link_active(&hdr->b_arc_node)) {
2863 ASSERT(refcount_is_zero(&hdr->b_refcnt));
2864 atomic_add_64(&hdr->b_state->arcs_lsize[type], size);
2865 }
2866 /*
2867 * If we are growing the cache, and we are adding anonymous
2868 * data, and we have outgrown arc_p, update arc_p
2869 */
89c8cac4
PS
2870 if (!zfs_arc_p_aggressive_disable &&
2871 arc_size < arc_c && hdr->b_state == arc_anon &&
34dc7c2f
BB
2872 arc_anon->arcs_size + arc_mru->arcs_size > arc_p)
2873 arc_p = MIN(arc_c, arc_p + size);
2874 }
2875}
2876
2877/*
2878 * This routine is called whenever a buffer is accessed.
2879 * NOTE: the hash lock is dropped in this function.
2880 */
2881static void
2882arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock)
2883{
428870ff
BB
2884 clock_t now;
2885
34dc7c2f
BB
2886 ASSERT(MUTEX_HELD(hash_lock));
2887
2888 if (buf->b_state == arc_anon) {
2889 /*
2890 * This buffer is not in the cache, and does not
2891 * appear in our "ghost" list. Add the new buffer
2892 * to the MRU state.
2893 */
2894
2895 ASSERT(buf->b_arc_access == 0);
428870ff 2896 buf->b_arc_access = ddi_get_lbolt();
34dc7c2f
BB
2897 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2898 arc_change_state(arc_mru, buf, hash_lock);
2899
2900 } else if (buf->b_state == arc_mru) {
428870ff
BB
2901 now = ddi_get_lbolt();
2902
34dc7c2f
BB
2903 /*
2904 * If this buffer is here because of a prefetch, then either:
2905 * - clear the flag if this is a "referencing" read
2906 * (any subsequent access will bump this into the MFU state).
2907 * or
2908 * - move the buffer to the head of the list if this is
2909 * another prefetch (to make it less likely to be evicted).
2910 */
2911 if ((buf->b_flags & ARC_PREFETCH) != 0) {
2912 if (refcount_count(&buf->b_refcnt) == 0) {
2913 ASSERT(list_link_active(&buf->b_arc_node));
2914 } else {
2915 buf->b_flags &= ~ARC_PREFETCH;
e0b0ca98 2916 atomic_inc_32(&buf->b_mru_hits);
34dc7c2f
BB
2917 ARCSTAT_BUMP(arcstat_mru_hits);
2918 }
428870ff 2919 buf->b_arc_access = now;
34dc7c2f
BB
2920 return;
2921 }
2922
2923 /*
2924 * This buffer has been "accessed" only once so far,
2925 * but it is still in the cache. Move it to the MFU
2926 * state.
2927 */
0b75bdb3 2928 if (ddi_time_after(now, buf->b_arc_access + ARC_MINTIME)) {
34dc7c2f
BB
2929 /*
2930 * More than 125ms have passed since we
2931 * instantiated this buffer. Move it to the
2932 * most frequently used state.
2933 */
428870ff 2934 buf->b_arc_access = now;
34dc7c2f
BB
2935 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2936 arc_change_state(arc_mfu, buf, hash_lock);
2937 }
e0b0ca98 2938 atomic_inc_32(&buf->b_mru_hits);
34dc7c2f
BB
2939 ARCSTAT_BUMP(arcstat_mru_hits);
2940 } else if (buf->b_state == arc_mru_ghost) {
2941 arc_state_t *new_state;
2942 /*
2943 * This buffer has been "accessed" recently, but
2944 * was evicted from the cache. Move it to the
2945 * MFU state.
2946 */
2947
2948 if (buf->b_flags & ARC_PREFETCH) {
2949 new_state = arc_mru;
2950 if (refcount_count(&buf->b_refcnt) > 0)
2951 buf->b_flags &= ~ARC_PREFETCH;
2952 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2953 } else {
2954 new_state = arc_mfu;
2955 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2956 }
2957
428870ff 2958 buf->b_arc_access = ddi_get_lbolt();
34dc7c2f
BB
2959 arc_change_state(new_state, buf, hash_lock);
2960
e0b0ca98 2961 atomic_inc_32(&buf->b_mru_ghost_hits);
34dc7c2f
BB
2962 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
2963 } else if (buf->b_state == arc_mfu) {
2964 /*
2965 * This buffer has been accessed more than once and is
2966 * still in the cache. Keep it in the MFU state.
2967 *
2968 * NOTE: an add_reference() that occurred when we did
2969 * the arc_read() will have kicked this off the list.
2970 * If it was a prefetch, we will explicitly move it to
2971 * the head of the list now.
2972 */
2973 if ((buf->b_flags & ARC_PREFETCH) != 0) {
2974 ASSERT(refcount_count(&buf->b_refcnt) == 0);
2975 ASSERT(list_link_active(&buf->b_arc_node));
2976 }
e0b0ca98 2977 atomic_inc_32(&buf->b_mfu_hits);
34dc7c2f 2978 ARCSTAT_BUMP(arcstat_mfu_hits);
428870ff 2979 buf->b_arc_access = ddi_get_lbolt();
34dc7c2f
BB
2980 } else if (buf->b_state == arc_mfu_ghost) {
2981 arc_state_t *new_state = arc_mfu;
2982 /*
2983 * This buffer has been accessed more than once but has
2984 * been evicted from the cache. Move it back to the
2985 * MFU state.
2986 */
2987
2988 if (buf->b_flags & ARC_PREFETCH) {
2989 /*
2990 * This is a prefetch access...
2991 * move this block back to the MRU state.
2992 */
c99c9001 2993 ASSERT0(refcount_count(&buf->b_refcnt));
34dc7c2f
BB
2994 new_state = arc_mru;
2995 }
2996
428870ff 2997 buf->b_arc_access = ddi_get_lbolt();
34dc7c2f
BB
2998 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2999 arc_change_state(new_state, buf, hash_lock);
3000
e0b0ca98 3001 atomic_inc_32(&buf->b_mfu_ghost_hits);
34dc7c2f
BB
3002 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
3003 } else if (buf->b_state == arc_l2c_only) {
3004 /*
3005 * This buffer is on the 2nd Level ARC.
3006 */
3007
428870ff 3008 buf->b_arc_access = ddi_get_lbolt();
34dc7c2f
BB
3009 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
3010 arc_change_state(arc_mfu, buf, hash_lock);
3011 } else {
3012 ASSERT(!"invalid arc state");
3013 }
3014}
3015
3016/* a generic arc_done_func_t which you can use */
3017/* ARGSUSED */
3018void
3019arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
3020{
428870ff
BB
3021 if (zio == NULL || zio->io_error == 0)
3022 bcopy(buf->b_data, arg, buf->b_hdr->b_size);
13fe0198 3023 VERIFY(arc_buf_remove_ref(buf, arg));
34dc7c2f
BB
3024}
3025
3026/* a generic arc_done_func_t */
3027void
3028arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
3029{
3030 arc_buf_t **bufp = arg;
3031 if (zio && zio->io_error) {
13fe0198 3032 VERIFY(arc_buf_remove_ref(buf, arg));
34dc7c2f
BB
3033 *bufp = NULL;
3034 } else {
3035 *bufp = buf;
428870ff 3036 ASSERT(buf->b_data);
34dc7c2f
BB
3037 }
3038}
3039
3040static void
3041arc_read_done(zio_t *zio)
3042{
9b67f605 3043 arc_buf_hdr_t *hdr;
34dc7c2f
BB
3044 arc_buf_t *buf;
3045 arc_buf_t *abuf; /* buffer we're assigning to callback */
9b67f605 3046 kmutex_t *hash_lock = NULL;
34dc7c2f
BB
3047 arc_callback_t *callback_list, *acb;
3048 int freeable = FALSE;
3049
3050 buf = zio->io_private;
3051 hdr = buf->b_hdr;
3052
3053 /*
3054 * The hdr was inserted into hash-table and removed from lists
3055 * prior to starting I/O. We should find this header, since
3056 * it's in the hash table, and it should be legit since it's
3057 * not possible to evict it during the I/O. The only possible
3058 * reason for it not to be found is if we were freed during the
3059 * read.
3060 */
9b67f605
MA
3061 if (HDR_IN_HASH_TABLE(hdr)) {
3062 arc_buf_hdr_t *found;
3063
3064 ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
3065 ASSERT3U(hdr->b_dva.dva_word[0], ==,
3066 BP_IDENTITY(zio->io_bp)->dva_word[0]);
3067 ASSERT3U(hdr->b_dva.dva_word[1], ==,
3068 BP_IDENTITY(zio->io_bp)->dva_word[1]);
3069
3070 found = buf_hash_find(hdr->b_spa, zio->io_bp,
3071 &hash_lock);
3072
3073 ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) &&
3074 hash_lock == NULL) ||
3075 (found == hdr &&
3076 DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
3077 (found == hdr && HDR_L2_READING(hdr)));
3078 }
34dc7c2f 3079
b128c09f 3080 hdr->b_flags &= ~ARC_L2_EVICTED;
34dc7c2f 3081 if (l2arc_noprefetch && (hdr->b_flags & ARC_PREFETCH))
b128c09f 3082 hdr->b_flags &= ~ARC_L2CACHE;
34dc7c2f
BB
3083
3084 /* byteswap if necessary */
3085 callback_list = hdr->b_acb;
3086 ASSERT(callback_list != NULL);
428870ff 3087 if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
9ae529ec
CS
3088 dmu_object_byteswap_t bswap =
3089 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
b01615d5
RY
3090 if (BP_GET_LEVEL(zio->io_bp) > 0)
3091 byteswap_uint64_array(buf->b_data, hdr->b_size);
3092 else
3093 dmu_ot_byteswap[bswap].ob_func(buf->b_data, hdr->b_size);
b128c09f 3094 }
34dc7c2f
BB
3095
3096 arc_cksum_compute(buf, B_FALSE);
498877ba 3097 arc_buf_watch(buf);
34dc7c2f 3098
428870ff
BB
3099 if (hash_lock && zio->io_error == 0 && hdr->b_state == arc_anon) {
3100 /*
3101 * Only call arc_access on anonymous buffers. This is because
3102 * if we've issued an I/O for an evicted buffer, we've already
3103 * called arc_access (to prevent any simultaneous readers from
3104 * getting confused).
3105 */
3106 arc_access(hdr, hash_lock);
3107 }
3108
34dc7c2f
BB
3109 /* create copies of the data buffer for the callers */
3110 abuf = buf;
3111 for (acb = callback_list; acb; acb = acb->acb_next) {
3112 if (acb->acb_done) {
1eb5bfa3
GW
3113 if (abuf == NULL) {
3114 ARCSTAT_BUMP(arcstat_duplicate_reads);
34dc7c2f 3115 abuf = arc_buf_clone(buf);
1eb5bfa3 3116 }
34dc7c2f
BB
3117 acb->acb_buf = abuf;
3118 abuf = NULL;
3119 }
3120 }
3121 hdr->b_acb = NULL;
3122 hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3123 ASSERT(!HDR_BUF_AVAILABLE(hdr));
428870ff
BB
3124 if (abuf == buf) {
3125 ASSERT(buf->b_efunc == NULL);
3126 ASSERT(hdr->b_datacnt == 1);
34dc7c2f 3127 hdr->b_flags |= ARC_BUF_AVAILABLE;
428870ff 3128 }
34dc7c2f
BB
3129
3130 ASSERT(refcount_is_zero(&hdr->b_refcnt) || callback_list != NULL);
3131
3132 if (zio->io_error != 0) {
3133 hdr->b_flags |= ARC_IO_ERROR;
3134 if (hdr->b_state != arc_anon)
3135 arc_change_state(arc_anon, hdr, hash_lock);
3136 if (HDR_IN_HASH_TABLE(hdr))
3137 buf_hash_remove(hdr);
3138 freeable = refcount_is_zero(&hdr->b_refcnt);
34dc7c2f
BB
3139 }
3140
3141 /*
3142 * Broadcast before we drop the hash_lock to avoid the possibility
3143 * that the hdr (and hence the cv) might be freed before we get to
3144 * the cv_broadcast().
3145 */
3146 cv_broadcast(&hdr->b_cv);
3147
3148 if (hash_lock) {
34dc7c2f
BB
3149 mutex_exit(hash_lock);
3150 } else {
3151 /*
3152 * This block was freed while we waited for the read to
3153 * complete. It has been removed from the hash table and
3154 * moved to the anonymous state (so that it won't show up
3155 * in the cache).
3156 */
3157 ASSERT3P(hdr->b_state, ==, arc_anon);
3158 freeable = refcount_is_zero(&hdr->b_refcnt);
3159 }
3160
3161 /* execute each callback and free its structure */
3162 while ((acb = callback_list) != NULL) {
3163 if (acb->acb_done)
3164 acb->acb_done(zio, acb->acb_buf, acb->acb_private);
3165
3166 if (acb->acb_zio_dummy != NULL) {
3167 acb->acb_zio_dummy->io_error = zio->io_error;
3168 zio_nowait(acb->acb_zio_dummy);
3169 }
3170
3171 callback_list = acb->acb_next;
3172 kmem_free(acb, sizeof (arc_callback_t));
3173 }
3174
3175 if (freeable)
3176 arc_hdr_destroy(hdr);
3177}
3178
3179/*
5c839890 3180 * "Read" the block at the specified DVA (in bp) via the
34dc7c2f
BB
3181 * cache. If the block is found in the cache, invoke the provided
3182 * callback immediately and return. Note that the `zio' parameter
3183 * in the callback will be NULL in this case, since no IO was
3184 * required. If the block is not in the cache pass the read request
3185 * on to the spa with a substitute callback function, so that the
3186 * requested block will be added to the cache.
3187 *
3188 * If a read request arrives for a block that has a read in-progress,
3189 * either wait for the in-progress read to complete (and return the
3190 * results); or, if this is a read with a "done" func, add a record
3191 * to the read to invoke the "done" func when the read completes,
3192 * and return; or just return.
3193 *
3194 * arc_read_done() will invoke all the requested "done" functions
3195 * for readers of this block.
3196 */
3197int
294f6806 3198arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
e8b96c60 3199 void *private, zio_priority_t priority, int zio_flags, uint32_t *arc_flags,
294f6806 3200 const zbookmark_t *zb)
34dc7c2f 3201{
9b67f605 3202 arc_buf_hdr_t *hdr = NULL;
d4ed6673 3203 arc_buf_t *buf = NULL;
9b67f605 3204 kmutex_t *hash_lock = NULL;
34dc7c2f 3205 zio_t *rzio;
3541dc6d 3206 uint64_t guid = spa_load_guid(spa);
1421c891 3207 int rc = 0;
34dc7c2f 3208
9b67f605
MA
3209 ASSERT(!BP_IS_EMBEDDED(bp) ||
3210 BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
3211
34dc7c2f 3212top:
9b67f605
MA
3213 if (!BP_IS_EMBEDDED(bp)) {
3214 /*
3215 * Embedded BP's have no DVA and require no I/O to "read".
3216 * Create an anonymous arc buf to back it.
3217 */
3218 hdr = buf_hash_find(guid, bp, &hash_lock);
3219 }
3220
3221 if (hdr != NULL && hdr->b_datacnt > 0) {
34dc7c2f
BB
3222
3223 *arc_flags |= ARC_CACHED;
3224
3225 if (HDR_IO_IN_PROGRESS(hdr)) {
3226
3227 if (*arc_flags & ARC_WAIT) {
3228 cv_wait(&hdr->b_cv, hash_lock);
3229 mutex_exit(hash_lock);
3230 goto top;
3231 }
3232 ASSERT(*arc_flags & ARC_NOWAIT);
3233
3234 if (done) {
3235 arc_callback_t *acb = NULL;
3236
3237 acb = kmem_zalloc(sizeof (arc_callback_t),
691f6ac4 3238 KM_PUSHPAGE);
34dc7c2f
BB
3239 acb->acb_done = done;
3240 acb->acb_private = private;
34dc7c2f
BB
3241 if (pio != NULL)
3242 acb->acb_zio_dummy = zio_null(pio,
d164b209 3243 spa, NULL, NULL, NULL, zio_flags);
34dc7c2f
BB
3244
3245 ASSERT(acb->acb_done != NULL);
3246 acb->acb_next = hdr->b_acb;
3247 hdr->b_acb = acb;
3248 add_reference(hdr, hash_lock, private);
3249 mutex_exit(hash_lock);
1421c891 3250 goto out;
34dc7c2f
BB
3251 }
3252 mutex_exit(hash_lock);
1421c891 3253 goto out;
34dc7c2f
BB
3254 }
3255
3256 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3257
3258 if (done) {
3259 add_reference(hdr, hash_lock, private);
3260 /*
3261 * If this block is already in use, create a new
3262 * copy of the data so that we will be guaranteed
3263 * that arc_release() will always succeed.
3264 */
3265 buf = hdr->b_buf;
3266 ASSERT(buf);
3267 ASSERT(buf->b_data);
3268 if (HDR_BUF_AVAILABLE(hdr)) {
3269 ASSERT(buf->b_efunc == NULL);
3270 hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3271 } else {
3272 buf = arc_buf_clone(buf);
3273 }
428870ff 3274
34dc7c2f
BB
3275 } else if (*arc_flags & ARC_PREFETCH &&
3276 refcount_count(&hdr->b_refcnt) == 0) {
3277 hdr->b_flags |= ARC_PREFETCH;
3278 }
3279 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
3280 arc_access(hdr, hash_lock);
b128c09f
BB
3281 if (*arc_flags & ARC_L2CACHE)
3282 hdr->b_flags |= ARC_L2CACHE;
3a17a7a9
SK
3283 if (*arc_flags & ARC_L2COMPRESS)
3284 hdr->b_flags |= ARC_L2COMPRESS;
34dc7c2f
BB
3285 mutex_exit(hash_lock);
3286 ARCSTAT_BUMP(arcstat_hits);
3287 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
3288 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3289 data, metadata, hits);
3290
3291 if (done)
3292 done(NULL, buf, private);
3293 } else {
3294 uint64_t size = BP_GET_LSIZE(bp);
9b67f605 3295 arc_callback_t *acb;
b128c09f 3296 vdev_t *vd = NULL;
a117a6d6 3297 uint64_t addr = 0;
d164b209 3298 boolean_t devw = B_FALSE;
0ed212dc
BP
3299 enum zio_compress b_compress = ZIO_COMPRESS_OFF;
3300 uint64_t b_asize = 0;
34dc7c2f
BB
3301
3302 if (hdr == NULL) {
3303 /* this block is not in the cache */
9b67f605 3304 arc_buf_hdr_t *exists = NULL;
34dc7c2f
BB
3305 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
3306 buf = arc_buf_alloc(spa, size, private, type);
3307 hdr = buf->b_hdr;
9b67f605
MA
3308 if (!BP_IS_EMBEDDED(bp)) {
3309 hdr->b_dva = *BP_IDENTITY(bp);
3310 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
3311 hdr->b_cksum0 = bp->blk_cksum.zc_word[0];
3312 exists = buf_hash_insert(hdr, &hash_lock);
3313 }
3314 if (exists != NULL) {
34dc7c2f
BB
3315 /* somebody beat us to the hash insert */
3316 mutex_exit(hash_lock);
428870ff 3317 buf_discard_identity(hdr);
34dc7c2f
BB
3318 (void) arc_buf_remove_ref(buf, private);
3319 goto top; /* restart the IO request */
3320 }
3321 /* if this is a prefetch, we don't have a reference */
3322 if (*arc_flags & ARC_PREFETCH) {
3323 (void) remove_reference(hdr, hash_lock,
3324 private);
3325 hdr->b_flags |= ARC_PREFETCH;
3326 }
b128c09f
BB
3327 if (*arc_flags & ARC_L2CACHE)
3328 hdr->b_flags |= ARC_L2CACHE;
3a17a7a9
SK
3329 if (*arc_flags & ARC_L2COMPRESS)
3330 hdr->b_flags |= ARC_L2COMPRESS;
34dc7c2f
BB
3331 if (BP_GET_LEVEL(bp) > 0)
3332 hdr->b_flags |= ARC_INDIRECT;
3333 } else {
3334 /* this block is in the ghost cache */
3335 ASSERT(GHOST_STATE(hdr->b_state));
3336 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
c99c9001 3337 ASSERT0(refcount_count(&hdr->b_refcnt));
34dc7c2f
BB
3338 ASSERT(hdr->b_buf == NULL);
3339
3340 /* if this is a prefetch, we don't have a reference */
3341 if (*arc_flags & ARC_PREFETCH)
3342 hdr->b_flags |= ARC_PREFETCH;
3343 else
3344 add_reference(hdr, hash_lock, private);
b128c09f
BB
3345 if (*arc_flags & ARC_L2CACHE)
3346 hdr->b_flags |= ARC_L2CACHE;
3a17a7a9
SK
3347 if (*arc_flags & ARC_L2COMPRESS)
3348 hdr->b_flags |= ARC_L2COMPRESS;
34dc7c2f
BB
3349 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
3350 buf->b_hdr = hdr;
3351 buf->b_data = NULL;
3352 buf->b_efunc = NULL;
3353 buf->b_private = NULL;
3354 buf->b_next = NULL;
3355 hdr->b_buf = buf;
34dc7c2f
BB
3356 ASSERT(hdr->b_datacnt == 0);
3357 hdr->b_datacnt = 1;
428870ff
BB
3358 arc_get_data_buf(buf);
3359 arc_access(hdr, hash_lock);
34dc7c2f
BB
3360 }
3361
428870ff
BB
3362 ASSERT(!GHOST_STATE(hdr->b_state));
3363
691f6ac4 3364 acb = kmem_zalloc(sizeof (arc_callback_t), KM_PUSHPAGE);
34dc7c2f
BB
3365 acb->acb_done = done;
3366 acb->acb_private = private;
34dc7c2f
BB
3367
3368 ASSERT(hdr->b_acb == NULL);
3369 hdr->b_acb = acb;
3370 hdr->b_flags |= ARC_IO_IN_PROGRESS;
3371
0ed212dc 3372 if (hdr->b_l2hdr != NULL &&
b128c09f 3373 (vd = hdr->b_l2hdr->b_dev->l2ad_vdev) != NULL) {
d164b209 3374 devw = hdr->b_l2hdr->b_dev->l2ad_writing;
b128c09f 3375 addr = hdr->b_l2hdr->b_daddr;
0ed212dc
BP
3376 b_compress = hdr->b_l2hdr->b_compress;
3377 b_asize = hdr->b_l2hdr->b_asize;
b128c09f
BB
3378 /*
3379 * Lock out device removal.
3380 */
3381 if (vdev_is_dead(vd) ||
3382 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
3383 vd = NULL;
3384 }
3385
9b67f605
MA
3386 if (hash_lock != NULL)
3387 mutex_exit(hash_lock);
b128c09f 3388
e49f1e20
WA
3389 /*
3390 * At this point, we have a level 1 cache miss. Try again in
3391 * L2ARC if possible.
3392 */
34dc7c2f 3393 ASSERT3U(hdr->b_size, ==, size);
428870ff
BB
3394 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
3395 uint64_t, size, zbookmark_t *, zb);
34dc7c2f
BB
3396 ARCSTAT_BUMP(arcstat_misses);
3397 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
3398 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3399 data, metadata, misses);
3400
d164b209 3401 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
34dc7c2f
BB
3402 /*
3403 * Read from the L2ARC if the following are true:
b128c09f
BB
3404 * 1. The L2ARC vdev was previously cached.
3405 * 2. This buffer still has L2ARC metadata.
3406 * 3. This buffer isn't currently writing to the L2ARC.
3407 * 4. The L2ARC entry wasn't evicted, which may
3408 * also have invalidated the vdev.
d164b209 3409 * 5. This isn't prefetch and l2arc_noprefetch is set.
34dc7c2f 3410 */
b128c09f 3411 if (hdr->b_l2hdr != NULL &&
d164b209
BB
3412 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
3413 !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
34dc7c2f
BB
3414 l2arc_read_callback_t *cb;
3415
3416 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
3417 ARCSTAT_BUMP(arcstat_l2_hits);
e0b0ca98 3418 atomic_inc_32(&hdr->b_l2hdr->b_hits);
34dc7c2f 3419
34dc7c2f 3420 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
691f6ac4 3421 KM_PUSHPAGE);
34dc7c2f
BB
3422 cb->l2rcb_buf = buf;
3423 cb->l2rcb_spa = spa;
3424 cb->l2rcb_bp = *bp;
3425 cb->l2rcb_zb = *zb;
b128c09f 3426 cb->l2rcb_flags = zio_flags;
0ed212dc 3427 cb->l2rcb_compress = b_compress;
34dc7c2f 3428
a117a6d6
GW
3429 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
3430 addr + size < vd->vdev_psize -
3431 VDEV_LABEL_END_SIZE);
3432
34dc7c2f 3433 /*
b128c09f
BB
3434 * l2arc read. The SCL_L2ARC lock will be
3435 * released by l2arc_read_done().
3a17a7a9
SK
3436 * Issue a null zio if the underlying buffer
3437 * was squashed to zero size by compression.
34dc7c2f 3438 */
0ed212dc 3439 if (b_compress == ZIO_COMPRESS_EMPTY) {
3a17a7a9
SK
3440 rzio = zio_null(pio, spa, vd,
3441 l2arc_read_done, cb,
3442 zio_flags | ZIO_FLAG_DONT_CACHE |
3443 ZIO_FLAG_CANFAIL |
3444 ZIO_FLAG_DONT_PROPAGATE |
3445 ZIO_FLAG_DONT_RETRY);
3446 } else {
3447 rzio = zio_read_phys(pio, vd, addr,
0ed212dc
BP
3448 b_asize, buf->b_data,
3449 ZIO_CHECKSUM_OFF,
3a17a7a9
SK
3450 l2arc_read_done, cb, priority,
3451 zio_flags | ZIO_FLAG_DONT_CACHE |
3452 ZIO_FLAG_CANFAIL |
3453 ZIO_FLAG_DONT_PROPAGATE |
3454 ZIO_FLAG_DONT_RETRY, B_FALSE);
3455 }
34dc7c2f
BB
3456 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
3457 zio_t *, rzio);
0ed212dc 3458 ARCSTAT_INCR(arcstat_l2_read_bytes, b_asize);
34dc7c2f 3459
b128c09f
BB
3460 if (*arc_flags & ARC_NOWAIT) {
3461 zio_nowait(rzio);
1421c891 3462 goto out;
b128c09f 3463 }
34dc7c2f 3464
b128c09f
BB
3465 ASSERT(*arc_flags & ARC_WAIT);
3466 if (zio_wait(rzio) == 0)
1421c891 3467 goto out;
b128c09f
BB
3468
3469 /* l2arc read error; goto zio_read() */
34dc7c2f
BB
3470 } else {
3471 DTRACE_PROBE1(l2arc__miss,
3472 arc_buf_hdr_t *, hdr);
3473 ARCSTAT_BUMP(arcstat_l2_misses);
3474 if (HDR_L2_WRITING(hdr))
3475 ARCSTAT_BUMP(arcstat_l2_rw_clash);
b128c09f 3476 spa_config_exit(spa, SCL_L2ARC, vd);
34dc7c2f 3477 }
d164b209
BB
3478 } else {
3479 if (vd != NULL)
3480 spa_config_exit(spa, SCL_L2ARC, vd);
3481 if (l2arc_ndev != 0) {
3482 DTRACE_PROBE1(l2arc__miss,
3483 arc_buf_hdr_t *, hdr);
3484 ARCSTAT_BUMP(arcstat_l2_misses);
3485 }
34dc7c2f 3486 }
34dc7c2f
BB
3487
3488 rzio = zio_read(pio, spa, bp, buf->b_data, size,
b128c09f 3489 arc_read_done, buf, priority, zio_flags, zb);
34dc7c2f 3490
1421c891
PS
3491 if (*arc_flags & ARC_WAIT) {
3492 rc = zio_wait(rzio);
3493 goto out;
3494 }
34dc7c2f
BB
3495
3496 ASSERT(*arc_flags & ARC_NOWAIT);
3497 zio_nowait(rzio);
3498 }
1421c891
PS
3499
3500out:
3501 spa_read_history_add(spa, zb, *arc_flags);
3502 return (rc);
34dc7c2f
BB
3503}
3504
ab26409d
BB
3505arc_prune_t *
3506arc_add_prune_callback(arc_prune_func_t *func, void *private)
3507{
3508 arc_prune_t *p;
3509
d1d7e268 3510 p = kmem_alloc(sizeof (*p), KM_SLEEP);
ab26409d
BB
3511 p->p_pfunc = func;
3512 p->p_private = private;
3513 list_link_init(&p->p_node);
3514 refcount_create(&p->p_refcnt);
3515
3516 mutex_enter(&arc_prune_mtx);
3517 refcount_add(&p->p_refcnt, &arc_prune_list);
3518 list_insert_head(&arc_prune_list, p);
3519 mutex_exit(&arc_prune_mtx);
3520
3521 return (p);
3522}
3523
3524void
3525arc_remove_prune_callback(arc_prune_t *p)
3526{
3527 mutex_enter(&arc_prune_mtx);
3528 list_remove(&arc_prune_list, p);
3529 if (refcount_remove(&p->p_refcnt, &arc_prune_list) == 0) {
3530 refcount_destroy(&p->p_refcnt);
3531 kmem_free(p, sizeof (*p));
3532 }
3533 mutex_exit(&arc_prune_mtx);
3534}
3535
34dc7c2f
BB
3536void
3537arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
3538{
3539 ASSERT(buf->b_hdr != NULL);
3540 ASSERT(buf->b_hdr->b_state != arc_anon);
3541 ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt) || func == NULL);
428870ff
BB
3542 ASSERT(buf->b_efunc == NULL);
3543 ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
3544
34dc7c2f
BB
3545 buf->b_efunc = func;
3546 buf->b_private = private;
3547}
3548
df4474f9
MA
3549/*
3550 * Notify the arc that a block was freed, and thus will never be used again.
3551 */
3552void
3553arc_freed(spa_t *spa, const blkptr_t *bp)
3554{
3555 arc_buf_hdr_t *hdr;
3556 kmutex_t *hash_lock;
3557 uint64_t guid = spa_load_guid(spa);
3558
9b67f605
MA
3559 ASSERT(!BP_IS_EMBEDDED(bp));
3560
3561 hdr = buf_hash_find(guid, bp, &hash_lock);
df4474f9
MA
3562 if (hdr == NULL)
3563 return;
3564 if (HDR_BUF_AVAILABLE(hdr)) {
3565 arc_buf_t *buf = hdr->b_buf;
3566 add_reference(hdr, hash_lock, FTAG);
3567 hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3568 mutex_exit(hash_lock);
3569
3570 arc_release(buf, FTAG);
3571 (void) arc_buf_remove_ref(buf, FTAG);
3572 } else {
3573 mutex_exit(hash_lock);
3574 }
3575
3576}
3577
34dc7c2f
BB
3578/*
3579 * This is used by the DMU to let the ARC know that a buffer is
3580 * being evicted, so the ARC should clean up. If this arc buf
3581 * is not yet in the evicted state, it will be put there.
3582 */
3583int
3584arc_buf_evict(arc_buf_t *buf)
3585{
3586 arc_buf_hdr_t *hdr;
3587 kmutex_t *hash_lock;
3588 arc_buf_t **bufp;
3589
428870ff 3590 mutex_enter(&buf->b_evict_lock);
34dc7c2f
BB
3591 hdr = buf->b_hdr;
3592 if (hdr == NULL) {
3593 /*
3594 * We are in arc_do_user_evicts().
3595 */
3596 ASSERT(buf->b_data == NULL);
428870ff 3597 mutex_exit(&buf->b_evict_lock);
34dc7c2f 3598 return (0);
b128c09f
BB
3599 } else if (buf->b_data == NULL) {
3600 arc_buf_t copy = *buf; /* structure assignment */
34dc7c2f 3601 /*
b128c09f
BB
3602 * We are on the eviction list; process this buffer now
3603 * but let arc_do_user_evicts() do the reaping.
34dc7c2f 3604 */
b128c09f 3605 buf->b_efunc = NULL;
428870ff 3606 mutex_exit(&buf->b_evict_lock);
b128c09f
BB
3607 VERIFY(copy.b_efunc(&copy) == 0);
3608 return (1);
34dc7c2f 3609 }
b128c09f
BB
3610 hash_lock = HDR_LOCK(hdr);
3611 mutex_enter(hash_lock);
428870ff
BB
3612 hdr = buf->b_hdr;
3613 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
34dc7c2f 3614
34dc7c2f
BB
3615 ASSERT3U(refcount_count(&hdr->b_refcnt), <, hdr->b_datacnt);
3616 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3617
3618 /*
3619 * Pull this buffer off of the hdr
3620 */
3621 bufp = &hdr->b_buf;
3622 while (*bufp != buf)
3623 bufp = &(*bufp)->b_next;
3624 *bufp = buf->b_next;
3625
3626 ASSERT(buf->b_data != NULL);
3627 arc_buf_destroy(buf, FALSE, FALSE);
3628
3629 if (hdr->b_datacnt == 0) {
3630 arc_state_t *old_state = hdr->b_state;
3631 arc_state_t *evicted_state;
3632
428870ff 3633 ASSERT(hdr->b_buf == NULL);
34dc7c2f
BB
3634 ASSERT(refcount_is_zero(&hdr->b_refcnt));
3635
3636 evicted_state =
3637 (old_state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
3638
3639 mutex_enter(&old_state->arcs_mtx);
3640 mutex_enter(&evicted_state->arcs_mtx);
3641
3642 arc_change_state(evicted_state, hdr, hash_lock);
3643 ASSERT(HDR_IN_HASH_TABLE(hdr));
3644 hdr->b_flags |= ARC_IN_HASH_TABLE;
3645 hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3646
3647 mutex_exit(&evicted_state->arcs_mtx);
3648 mutex_exit(&old_state->arcs_mtx);
3649 }
3650 mutex_exit(hash_lock);
428870ff 3651 mutex_exit(&buf->b_evict_lock);
34dc7c2f
BB
3652
3653 VERIFY(buf->b_efunc(buf) == 0);
3654 buf->b_efunc = NULL;
3655 buf->b_private = NULL;
3656 buf->b_hdr = NULL;
428870ff 3657 buf->b_next = NULL;
34dc7c2f
BB
3658 kmem_cache_free(buf_cache, buf);
3659 return (1);
3660}
3661
3662/*
e49f1e20
WA
3663 * Release this buffer from the cache, making it an anonymous buffer. This
3664 * must be done after a read and prior to modifying the buffer contents.
34dc7c2f 3665 * If the buffer has more than one reference, we must make
b128c09f 3666 * a new hdr for the buffer.
34dc7c2f
BB
3667 */
3668void
3669arc_release(arc_buf_t *buf, void *tag)
3670{
b128c09f 3671 arc_buf_hdr_t *hdr;
428870ff 3672 kmutex_t *hash_lock = NULL;
b128c09f 3673 l2arc_buf_hdr_t *l2hdr;
d4ed6673 3674 uint64_t buf_size = 0;
34dc7c2f 3675
428870ff
BB
3676 /*
3677 * It would be nice to assert that if it's DMU metadata (level >
3678 * 0 || it's the dnode file), then it must be syncing context.
3679 * But we don't know that information at this level.
3680 */
3681
3682 mutex_enter(&buf->b_evict_lock);
b128c09f
BB
3683 hdr = buf->b_hdr;
3684
34dc7c2f
BB
3685 /* this buffer is not on any list */
3686 ASSERT(refcount_count(&hdr->b_refcnt) > 0);
3687
3688 if (hdr->b_state == arc_anon) {
3689 /* this buffer is already released */
34dc7c2f 3690 ASSERT(buf->b_efunc == NULL);
9babb374
BB
3691 } else {
3692 hash_lock = HDR_LOCK(hdr);
3693 mutex_enter(hash_lock);
428870ff
BB
3694 hdr = buf->b_hdr;
3695 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
34dc7c2f
BB
3696 }
3697
b128c09f
BB
3698 l2hdr = hdr->b_l2hdr;
3699 if (l2hdr) {
3700 mutex_enter(&l2arc_buflist_mtx);
3701 hdr->b_l2hdr = NULL;
47fe91b5 3702 list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
b128c09f 3703 }
a117a6d6 3704 buf_size = hdr->b_size;
b128c09f 3705
34dc7c2f
BB
3706 /*
3707 * Do we have more than one buf?
3708 */
b128c09f 3709 if (hdr->b_datacnt > 1) {
34dc7c2f
BB
3710 arc_buf_hdr_t *nhdr;
3711 arc_buf_t **bufp;
3712 uint64_t blksz = hdr->b_size;
d164b209 3713 uint64_t spa = hdr->b_spa;
34dc7c2f
BB
3714 arc_buf_contents_t type = hdr->b_type;
3715 uint32_t flags = hdr->b_flags;
3716
b128c09f 3717 ASSERT(hdr->b_buf != buf || buf->b_next != NULL);
34dc7c2f 3718 /*
428870ff
BB
3719 * Pull the data off of this hdr and attach it to
3720 * a new anonymous hdr.
34dc7c2f
BB
3721 */
3722 (void) remove_reference(hdr, hash_lock, tag);
3723 bufp = &hdr->b_buf;
3724 while (*bufp != buf)
3725 bufp = &(*bufp)->b_next;
428870ff 3726 *bufp = buf->b_next;
34dc7c2f
BB
3727 buf->b_next = NULL;
3728
3729 ASSERT3U(hdr->b_state->arcs_size, >=, hdr->b_size);
3730 atomic_add_64(&hdr->b_state->arcs_size, -hdr->b_size);
3731 if (refcount_is_zero(&hdr->b_refcnt)) {
3732 uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
3733 ASSERT3U(*size, >=, hdr->b_size);
3734 atomic_add_64(size, -hdr->b_size);
3735 }
1eb5bfa3
GW
3736
3737 /*
3738 * We're releasing a duplicate user data buffer, update
3739 * our statistics accordingly.
3740 */
3741 if (hdr->b_type == ARC_BUFC_DATA) {
3742 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
3743 ARCSTAT_INCR(arcstat_duplicate_buffers_size,
3744 -hdr->b_size);
3745 }
34dc7c2f 3746 hdr->b_datacnt -= 1;
34dc7c2f 3747 arc_cksum_verify(buf);
498877ba 3748 arc_buf_unwatch(buf);
34dc7c2f
BB
3749
3750 mutex_exit(hash_lock);
3751
3752 nhdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
3753 nhdr->b_size = blksz;
3754 nhdr->b_spa = spa;
3755 nhdr->b_type = type;
3756 nhdr->b_buf = buf;
3757 nhdr->b_state = arc_anon;
3758 nhdr->b_arc_access = 0;
e0b0ca98
BB
3759 nhdr->b_mru_hits = 0;
3760 nhdr->b_mru_ghost_hits = 0;
3761 nhdr->b_mfu_hits = 0;
3762 nhdr->b_mfu_ghost_hits = 0;
3763 nhdr->b_l2_hits = 0;
34dc7c2f
BB
3764 nhdr->b_flags = flags & ARC_L2_WRITING;
3765 nhdr->b_l2hdr = NULL;
3766 nhdr->b_datacnt = 1;
3767 nhdr->b_freeze_cksum = NULL;
3768 (void) refcount_add(&nhdr->b_refcnt, tag);
3769 buf->b_hdr = nhdr;
428870ff 3770 mutex_exit(&buf->b_evict_lock);
34dc7c2f
BB
3771 atomic_add_64(&arc_anon->arcs_size, blksz);
3772 } else {
428870ff 3773 mutex_exit(&buf->b_evict_lock);
34dc7c2f
BB
3774 ASSERT(refcount_count(&hdr->b_refcnt) == 1);
3775 ASSERT(!list_link_active(&hdr->b_arc_node));
3776 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
428870ff
BB
3777 if (hdr->b_state != arc_anon)
3778 arc_change_state(arc_anon, hdr, hash_lock);
34dc7c2f 3779 hdr->b_arc_access = 0;
e0b0ca98
BB
3780 hdr->b_mru_hits = 0;
3781 hdr->b_mru_ghost_hits = 0;
3782 hdr->b_mfu_hits = 0;
3783 hdr->b_mfu_ghost_hits = 0;
3784 hdr->b_l2_hits = 0;
428870ff
BB
3785 if (hash_lock)
3786 mutex_exit(hash_lock);
34dc7c2f 3787
428870ff 3788 buf_discard_identity(hdr);
34dc7c2f
BB
3789 arc_buf_thaw(buf);
3790 }
3791 buf->b_efunc = NULL;
3792 buf->b_private = NULL;
3793
3794 if (l2hdr) {
3a17a7a9 3795 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
3bec585e
SK
3796 vdev_space_update(l2hdr->b_dev->l2ad_vdev,
3797 -l2hdr->b_asize, 0, 0);
ecf3d9b8 3798 kmem_cache_free(l2arc_hdr_cache, l2hdr);
6e1d7276 3799 arc_space_return(L2HDR_SIZE, ARC_SPACE_L2HDRS);
34dc7c2f 3800 ARCSTAT_INCR(arcstat_l2_size, -buf_size);
34dc7c2f 3801 mutex_exit(&l2arc_buflist_mtx);
b128c09f 3802 }
34dc7c2f
BB
3803}
3804
3805int
3806arc_released(arc_buf_t *buf)
3807{
b128c09f
BB
3808 int released;
3809
428870ff 3810 mutex_enter(&buf->b_evict_lock);
b128c09f 3811 released = (buf->b_data != NULL && buf->b_hdr->b_state == arc_anon);
428870ff 3812 mutex_exit(&buf->b_evict_lock);
b128c09f 3813 return (released);
34dc7c2f
BB
3814}
3815
3816int
3817arc_has_callback(arc_buf_t *buf)
3818{
b128c09f
BB
3819 int callback;
3820
428870ff 3821 mutex_enter(&buf->b_evict_lock);
b128c09f 3822 callback = (buf->b_efunc != NULL);
428870ff 3823 mutex_exit(&buf->b_evict_lock);
b128c09f 3824 return (callback);
34dc7c2f
BB
3825}
3826
3827#ifdef ZFS_DEBUG
3828int
3829arc_referenced(arc_buf_t *buf)
3830{
b128c09f
BB
3831 int referenced;
3832
428870ff 3833 mutex_enter(&buf->b_evict_lock);
b128c09f 3834 referenced = (refcount_count(&buf->b_hdr->b_refcnt));
428870ff 3835 mutex_exit(&buf->b_evict_lock);
b128c09f 3836 return (referenced);
34dc7c2f
BB
3837}
3838#endif
3839
3840static void
3841arc_write_ready(zio_t *zio)
3842{
3843 arc_write_callback_t *callback = zio->io_private;
3844 arc_buf_t *buf = callback->awcb_buf;
3845 arc_buf_hdr_t *hdr = buf->b_hdr;
3846
b128c09f
BB
3847 ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt));
3848 callback->awcb_ready(zio, buf, callback->awcb_private);
3849
34dc7c2f
BB
3850 /*
3851 * If the IO is already in progress, then this is a re-write
b128c09f
BB
3852 * attempt, so we need to thaw and re-compute the cksum.
3853 * It is the responsibility of the callback to handle the
3854 * accounting for any re-write attempt.
34dc7c2f
BB
3855 */
3856 if (HDR_IO_IN_PROGRESS(hdr)) {
34dc7c2f
BB
3857 mutex_enter(&hdr->b_freeze_lock);
3858 if (hdr->b_freeze_cksum != NULL) {
3859 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
3860 hdr->b_freeze_cksum = NULL;
3861 }
3862 mutex_exit(&hdr->b_freeze_lock);
3863 }
3864 arc_cksum_compute(buf, B_FALSE);
3865 hdr->b_flags |= ARC_IO_IN_PROGRESS;
3866}
3867
e8b96c60
MA
3868/*
3869 * The SPA calls this callback for each physical write that happens on behalf
3870 * of a logical write. See the comment in dbuf_write_physdone() for details.
3871 */
3872static void
3873arc_write_physdone(zio_t *zio)
3874{
3875 arc_write_callback_t *cb = zio->io_private;
3876 if (cb->awcb_physdone != NULL)
3877 cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
3878}
3879
34dc7c2f
BB
3880static void
3881arc_write_done(zio_t *zio)
3882{
3883 arc_write_callback_t *callback = zio->io_private;
3884 arc_buf_t *buf = callback->awcb_buf;
3885 arc_buf_hdr_t *hdr = buf->b_hdr;
3886
428870ff
BB
3887 ASSERT(hdr->b_acb == NULL);
3888
3889 if (zio->io_error == 0) {
9b67f605 3890 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
b0bc7a84
MG
3891 buf_discard_identity(hdr);
3892 } else {
3893 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
3894 hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
3895 hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
3896 }
428870ff
BB
3897 } else {
3898 ASSERT(BUF_EMPTY(hdr));
3899 }
34dc7c2f 3900
34dc7c2f 3901 /*
9b67f605
MA
3902 * If the block to be written was all-zero or compressed enough to be
3903 * embedded in the BP, no write was performed so there will be no
3904 * dva/birth/checksum. The buffer must therefore remain anonymous
3905 * (and uncached).
34dc7c2f
BB
3906 */
3907 if (!BUF_EMPTY(hdr)) {
3908 arc_buf_hdr_t *exists;
3909 kmutex_t *hash_lock;
3910
428870ff
BB
3911 ASSERT(zio->io_error == 0);
3912
34dc7c2f
BB
3913 arc_cksum_verify(buf);
3914
3915 exists = buf_hash_insert(hdr, &hash_lock);
3916 if (exists) {
3917 /*
3918 * This can only happen if we overwrite for
3919 * sync-to-convergence, because we remove
3920 * buffers from the hash table when we arc_free().
3921 */
428870ff
BB
3922 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
3923 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3924 panic("bad overwrite, hdr=%p exists=%p",
3925 (void *)hdr, (void *)exists);
3926 ASSERT(refcount_is_zero(&exists->b_refcnt));
3927 arc_change_state(arc_anon, exists, hash_lock);
3928 mutex_exit(hash_lock);
3929 arc_hdr_destroy(exists);
3930 exists = buf_hash_insert(hdr, &hash_lock);
3931 ASSERT3P(exists, ==, NULL);
03c6040b
GW
3932 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
3933 /* nopwrite */
3934 ASSERT(zio->io_prop.zp_nopwrite);
3935 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3936 panic("bad nopwrite, hdr=%p exists=%p",
3937 (void *)hdr, (void *)exists);
428870ff
BB
3938 } else {
3939 /* Dedup */
3940 ASSERT(hdr->b_datacnt == 1);
3941 ASSERT(hdr->b_state == arc_anon);
3942 ASSERT(BP_GET_DEDUP(zio->io_bp));
3943 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
3944 }
34dc7c2f
BB
3945 }
3946 hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
b128c09f 3947 /* if it's not anon, we are doing a scrub */
428870ff 3948 if (!exists && hdr->b_state == arc_anon)
b128c09f 3949 arc_access(hdr, hash_lock);
34dc7c2f 3950 mutex_exit(hash_lock);
34dc7c2f
BB
3951 } else {
3952 hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3953 }
3954
428870ff
BB
3955 ASSERT(!refcount_is_zero(&hdr->b_refcnt));
3956 callback->awcb_done(zio, buf, callback->awcb_private);
34dc7c2f
BB
3957
3958 kmem_free(callback, sizeof (arc_write_callback_t));
3959}
3960
3961zio_t *
428870ff 3962arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
3a17a7a9 3963 blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
e8b96c60
MA
3964 const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *physdone,
3965 arc_done_func_t *done, void *private, zio_priority_t priority,
3966 int zio_flags, const zbookmark_t *zb)
34dc7c2f
BB
3967{
3968 arc_buf_hdr_t *hdr = buf->b_hdr;
3969 arc_write_callback_t *callback;
b128c09f 3970 zio_t *zio;
34dc7c2f 3971
b128c09f 3972 ASSERT(ready != NULL);
428870ff 3973 ASSERT(done != NULL);
34dc7c2f
BB
3974 ASSERT(!HDR_IO_ERROR(hdr));
3975 ASSERT((hdr->b_flags & ARC_IO_IN_PROGRESS) == 0);
428870ff 3976 ASSERT(hdr->b_acb == NULL);
b128c09f
BB
3977 if (l2arc)
3978 hdr->b_flags |= ARC_L2CACHE;
3a17a7a9
SK
3979 if (l2arc_compress)
3980 hdr->b_flags |= ARC_L2COMPRESS;
b8d06fca 3981 callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_PUSHPAGE);
34dc7c2f 3982 callback->awcb_ready = ready;
e8b96c60 3983 callback->awcb_physdone = physdone;
34dc7c2f
BB
3984 callback->awcb_done = done;
3985 callback->awcb_private = private;
3986 callback->awcb_buf = buf;
b128c09f 3987
428870ff 3988 zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
e8b96c60
MA
3989 arc_write_ready, arc_write_physdone, arc_write_done, callback,
3990 priority, zio_flags, zb);
34dc7c2f
BB
3991
3992 return (zio);
3993}
3994
34dc7c2f 3995static int
e8b96c60 3996arc_memory_throttle(uint64_t reserve, uint64_t txg)
34dc7c2f
BB
3997{
3998#ifdef _KERNEL
0c5493d4
BB
3999 if (zfs_arc_memory_throttle_disable)
4000 return (0);
4001
e8b96c60 4002 if (freemem <= physmem * arc_lotsfree_percent / 100) {
34dc7c2f 4003 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
570827e1 4004 DMU_TX_STAT_BUMP(dmu_tx_memory_reclaim);
2e528b49 4005 return (SET_ERROR(EAGAIN));
34dc7c2f 4006 }
34dc7c2f
BB
4007#endif
4008 return (0);
4009}
4010
4011void
4012arc_tempreserve_clear(uint64_t reserve)
4013{
4014 atomic_add_64(&arc_tempreserve, -reserve);
4015 ASSERT((int64_t)arc_tempreserve >= 0);
4016}
4017
4018int
4019arc_tempreserve_space(uint64_t reserve, uint64_t txg)
4020{
4021 int error;
9babb374 4022 uint64_t anon_size;
34dc7c2f 4023
34dc7c2f
BB
4024 if (reserve > arc_c/4 && !arc_no_grow)
4025 arc_c = MIN(arc_c_max, reserve * 4);
12f9a6a3
BB
4026
4027 /*
4028 * Throttle when the calculated memory footprint for the TXG
4029 * exceeds the target ARC size.
4030 */
570827e1
BB
4031 if (reserve > arc_c) {
4032 DMU_TX_STAT_BUMP(dmu_tx_memory_reserve);
12f9a6a3 4033 return (SET_ERROR(ERESTART));
570827e1 4034 }
34dc7c2f 4035
9babb374
BB
4036 /*
4037 * Don't count loaned bufs as in flight dirty data to prevent long
4038 * network delays from blocking transactions that are ready to be
4039 * assigned to a txg.
4040 */
4041 anon_size = MAX((int64_t)(arc_anon->arcs_size - arc_loaned_bytes), 0);
4042
34dc7c2f
BB
4043 /*
4044 * Writes will, almost always, require additional memory allocations
d3cc8b15 4045 * in order to compress/encrypt/etc the data. We therefore need to
34dc7c2f
BB
4046 * make sure that there is sufficient available memory for this.
4047 */
e8b96c60
MA
4048 error = arc_memory_throttle(reserve, txg);
4049 if (error != 0)
34dc7c2f
BB
4050 return (error);
4051
4052 /*
4053 * Throttle writes when the amount of dirty data in the cache
4054 * gets too large. We try to keep the cache less than half full
4055 * of dirty blocks so that our sync times don't grow too large.
4056 * Note: if two requests come in concurrently, we might let them
4057 * both succeed, when one of them should fail. Not a huge deal.
4058 */
9babb374
BB
4059
4060 if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
4061 anon_size > arc_c / 4) {
34dc7c2f
BB
4062 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
4063 "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
4064 arc_tempreserve>>10,
4065 arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
4066 arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
4067 reserve>>10, arc_c>>10);
570827e1 4068 DMU_TX_STAT_BUMP(dmu_tx_dirty_throttle);
2e528b49 4069 return (SET_ERROR(ERESTART));
34dc7c2f
BB
4070 }
4071 atomic_add_64(&arc_tempreserve, reserve);
4072 return (0);
4073}
4074
13be560d
BB
4075static void
4076arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
4077 kstat_named_t *evict_data, kstat_named_t *evict_metadata)
4078{
4079 size->value.ui64 = state->arcs_size;
4080 evict_data->value.ui64 = state->arcs_lsize[ARC_BUFC_DATA];
4081 evict_metadata->value.ui64 = state->arcs_lsize[ARC_BUFC_METADATA];
4082}
4083
4084static int
4085arc_kstat_update(kstat_t *ksp, int rw)
4086{
4087 arc_stats_t *as = ksp->ks_data;
4088
4089 if (rw == KSTAT_WRITE) {
2e528b49 4090 return (SET_ERROR(EACCES));
13be560d
BB
4091 } else {
4092 arc_kstat_update_state(arc_anon,
4093 &as->arcstat_anon_size,
4094 &as->arcstat_anon_evict_data,
4095 &as->arcstat_anon_evict_metadata);
4096 arc_kstat_update_state(arc_mru,
4097 &as->arcstat_mru_size,
4098 &as->arcstat_mru_evict_data,
4099 &as->arcstat_mru_evict_metadata);
4100 arc_kstat_update_state(arc_mru_ghost,
4101 &as->arcstat_mru_ghost_size,
4102 &as->arcstat_mru_ghost_evict_data,
4103 &as->arcstat_mru_ghost_evict_metadata);
4104 arc_kstat_update_state(arc_mfu,
4105 &as->arcstat_mfu_size,
4106 &as->arcstat_mfu_evict_data,
4107 &as->arcstat_mfu_evict_metadata);
fc41c640 4108 arc_kstat_update_state(arc_mfu_ghost,
13be560d
BB
4109 &as->arcstat_mfu_ghost_size,
4110 &as->arcstat_mfu_ghost_evict_data,
4111 &as->arcstat_mfu_ghost_evict_metadata);
4112 }
4113
4114 return (0);
4115}
4116
34dc7c2f
BB
4117void
4118arc_init(void)
4119{
4120 mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
4121 cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
4122
4123 /* Convert seconds to clock ticks */
bce45ec9 4124 zfs_arc_min_prefetch_lifespan = 1 * hz;
34dc7c2f
BB
4125
4126 /* Start out with 1/8 of all memory */
4127 arc_c = physmem * PAGESIZE / 8;
4128
4129#ifdef _KERNEL
4130 /*
4131 * On architectures where the physical memory can be larger
4132 * than the addressable space (intel in 32-bit mode), we may
4133 * need to limit the cache to 1/8 of VM size.
4134 */
4135 arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
7cb67b45
BB
4136 /*
4137 * Register a shrinker to support synchronous (direct) memory
4138 * reclaim from the arc. This is done to prevent kswapd from
4139 * swapping out pages when it is preferable to shrink the arc.
4140 */
4141 spl_register_shrinker(&arc_shrinker);
34dc7c2f
BB
4142#endif
4143
91415825
BB
4144 /* set min cache to zero */
4145 arc_c_min = 4<<20;
518b4876 4146 /* set max to 1/2 of all memory */
be5db977 4147 arc_c_max = arc_c * 4;
34dc7c2f
BB
4148
4149 /*
4150 * Allow the tunables to override our calculations if they are
4151 * reasonable (ie. over 64MB)
4152 */
4153 if (zfs_arc_max > 64<<20 && zfs_arc_max < physmem * PAGESIZE)
4154 arc_c_max = zfs_arc_max;
91415825 4155 if (zfs_arc_min > 0 && zfs_arc_min <= arc_c_max)
34dc7c2f
BB
4156 arc_c_min = zfs_arc_min;
4157
4158 arc_c = arc_c_max;
4159 arc_p = (arc_c >> 1);
4160
2b13331d
PS
4161 /* limit meta-data to 3/4 of the arc capacity */
4162 arc_meta_limit = (3 * arc_c_max) / 4;
1834f2d8 4163 arc_meta_max = 0;
34dc7c2f
BB
4164
4165 /* Allow the tunable to override if it is reasonable */
4166 if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
4167 arc_meta_limit = zfs_arc_meta_limit;
4168
34dc7c2f
BB
4169 /* if kmem_flags are set, lets try to use less memory */
4170 if (kmem_debugging())
4171 arc_c = arc_c / 2;
4172 if (arc_c < arc_c_min)
4173 arc_c = arc_c_min;
4174
4175 arc_anon = &ARC_anon;
4176 arc_mru = &ARC_mru;
4177 arc_mru_ghost = &ARC_mru_ghost;
4178 arc_mfu = &ARC_mfu;
4179 arc_mfu_ghost = &ARC_mfu_ghost;
4180 arc_l2c_only = &ARC_l2c_only;
4181 arc_size = 0;
4182
4183 mutex_init(&arc_anon->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
4184 mutex_init(&arc_mru->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
4185 mutex_init(&arc_mru_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
4186 mutex_init(&arc_mfu->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
4187 mutex_init(&arc_mfu_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
4188 mutex_init(&arc_l2c_only->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
4189
4190 list_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
4191 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4192 list_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
4193 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4194 list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
4195 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4196 list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
4197 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4198 list_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
4199 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4200 list_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
4201 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4202 list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
4203 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4204 list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
4205 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4206 list_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
4207 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4208 list_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
4209 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4210
e0b0ca98
BB
4211 arc_anon->arcs_state = ARC_STATE_ANON;
4212 arc_mru->arcs_state = ARC_STATE_MRU;
4213 arc_mru_ghost->arcs_state = ARC_STATE_MRU_GHOST;
4214 arc_mfu->arcs_state = ARC_STATE_MFU;
4215 arc_mfu_ghost->arcs_state = ARC_STATE_MFU_GHOST;
4216 arc_l2c_only->arcs_state = ARC_STATE_L2C_ONLY;
4217
34dc7c2f
BB
4218 buf_init();
4219
4220 arc_thread_exit = 0;
ab26409d
BB
4221 list_create(&arc_prune_list, sizeof (arc_prune_t),
4222 offsetof(arc_prune_t, p_node));
34dc7c2f 4223 arc_eviction_list = NULL;
ab26409d 4224 mutex_init(&arc_prune_mtx, NULL, MUTEX_DEFAULT, NULL);
34dc7c2f
BB
4225 mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
4226 bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
4227
4228 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
4229 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
4230
4231 if (arc_ksp != NULL) {
4232 arc_ksp->ks_data = &arc_stats;
13be560d 4233 arc_ksp->ks_update = arc_kstat_update;
34dc7c2f
BB
4234 kstat_install(arc_ksp);
4235 }
4236
302f753f 4237 (void) thread_create(NULL, 0, arc_adapt_thread, NULL, 0, &p0,
34dc7c2f
BB
4238 TS_RUN, minclsyspri);
4239
4240 arc_dead = FALSE;
b128c09f 4241 arc_warm = B_FALSE;
34dc7c2f 4242
e8b96c60
MA
4243 /*
4244 * Calculate maximum amount of dirty data per pool.
4245 *
4246 * If it has been set by a module parameter, take that.
4247 * Otherwise, use a percentage of physical memory defined by
4248 * zfs_dirty_data_max_percent (default 10%) with a cap at
4249 * zfs_dirty_data_max_max (default 25% of physical memory).
4250 */
4251 if (zfs_dirty_data_max_max == 0)
4252 zfs_dirty_data_max_max = physmem * PAGESIZE *
4253 zfs_dirty_data_max_max_percent / 100;
4254
4255 if (zfs_dirty_data_max == 0) {
4256 zfs_dirty_data_max = physmem * PAGESIZE *
4257 zfs_dirty_data_max_percent / 100;
4258 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
4259 zfs_dirty_data_max_max);
4260 }
34dc7c2f
BB
4261}
4262
4263void
4264arc_fini(void)
4265{
ab26409d
BB
4266 arc_prune_t *p;
4267
34dc7c2f 4268 mutex_enter(&arc_reclaim_thr_lock);
7cb67b45
BB
4269#ifdef _KERNEL
4270 spl_unregister_shrinker(&arc_shrinker);
4271#endif /* _KERNEL */
4272
34dc7c2f
BB
4273 arc_thread_exit = 1;
4274 while (arc_thread_exit != 0)
4275 cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
4276 mutex_exit(&arc_reclaim_thr_lock);
4277
4278 arc_flush(NULL);
4279
4280 arc_dead = TRUE;
4281
4282 if (arc_ksp != NULL) {
4283 kstat_delete(arc_ksp);
4284 arc_ksp = NULL;
4285 }
4286
ab26409d
BB
4287 mutex_enter(&arc_prune_mtx);
4288 while ((p = list_head(&arc_prune_list)) != NULL) {
4289 list_remove(&arc_prune_list, p);
4290 refcount_remove(&p->p_refcnt, &arc_prune_list);
4291 refcount_destroy(&p->p_refcnt);
4292 kmem_free(p, sizeof (*p));
4293 }
4294 mutex_exit(&arc_prune_mtx);
4295
4296 list_destroy(&arc_prune_list);
4297 mutex_destroy(&arc_prune_mtx);
34dc7c2f
BB
4298 mutex_destroy(&arc_eviction_mtx);
4299 mutex_destroy(&arc_reclaim_thr_lock);
4300 cv_destroy(&arc_reclaim_thr_cv);
4301
4302 list_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
4303 list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
4304 list_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
4305 list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
4306 list_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
4307 list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
4308 list_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
4309 list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
4310
4311 mutex_destroy(&arc_anon->arcs_mtx);
4312 mutex_destroy(&arc_mru->arcs_mtx);
4313 mutex_destroy(&arc_mru_ghost->arcs_mtx);
4314 mutex_destroy(&arc_mfu->arcs_mtx);
4315 mutex_destroy(&arc_mfu_ghost->arcs_mtx);
fb5f0bc8 4316 mutex_destroy(&arc_l2c_only->arcs_mtx);
34dc7c2f
BB
4317
4318 buf_fini();
9babb374
BB
4319
4320 ASSERT(arc_loaned_bytes == 0);
34dc7c2f
BB
4321}
4322
4323/*
4324 * Level 2 ARC
4325 *
4326 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
4327 * It uses dedicated storage devices to hold cached data, which are populated
4328 * using large infrequent writes. The main role of this cache is to boost
4329 * the performance of random read workloads. The intended L2ARC devices
4330 * include short-stroked disks, solid state disks, and other media with
4331 * substantially faster read latency than disk.
4332 *
4333 * +-----------------------+
4334 * | ARC |
4335 * +-----------------------+
4336 * | ^ ^
4337 * | | |
4338 * l2arc_feed_thread() arc_read()
4339 * | | |
4340 * | l2arc read |
4341 * V | |
4342 * +---------------+ |
4343 * | L2ARC | |
4344 * +---------------+ |
4345 * | ^ |
4346 * l2arc_write() | |
4347 * | | |
4348 * V | |
4349 * +-------+ +-------+
4350 * | vdev | | vdev |
4351 * | cache | | cache |
4352 * +-------+ +-------+
4353 * +=========+ .-----.
4354 * : L2ARC : |-_____-|
4355 * : devices : | Disks |
4356 * +=========+ `-_____-'
4357 *
4358 * Read requests are satisfied from the following sources, in order:
4359 *
4360 * 1) ARC
4361 * 2) vdev cache of L2ARC devices
4362 * 3) L2ARC devices
4363 * 4) vdev cache of disks
4364 * 5) disks
4365 *
4366 * Some L2ARC device types exhibit extremely slow write performance.
4367 * To accommodate for this there are some significant differences between
4368 * the L2ARC and traditional cache design:
4369 *
4370 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
4371 * the ARC behave as usual, freeing buffers and placing headers on ghost
4372 * lists. The ARC does not send buffers to the L2ARC during eviction as
4373 * this would add inflated write latencies for all ARC memory pressure.
4374 *
4375 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
4376 * It does this by periodically scanning buffers from the eviction-end of
4377 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
3a17a7a9
SK
4378 * not already there. It scans until a headroom of buffers is satisfied,
4379 * which itself is a buffer for ARC eviction. If a compressible buffer is
4380 * found during scanning and selected for writing to an L2ARC device, we
4381 * temporarily boost scanning headroom during the next scan cycle to make
4382 * sure we adapt to compression effects (which might significantly reduce
4383 * the data volume we write to L2ARC). The thread that does this is
34dc7c2f
BB
4384 * l2arc_feed_thread(), illustrated below; example sizes are included to
4385 * provide a better sense of ratio than this diagram:
4386 *
4387 * head --> tail
4388 * +---------------------+----------+
4389 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
4390 * +---------------------+----------+ | o L2ARC eligible
4391 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
4392 * +---------------------+----------+ |
4393 * 15.9 Gbytes ^ 32 Mbytes |
4394 * headroom |
4395 * l2arc_feed_thread()
4396 * |
4397 * l2arc write hand <--[oooo]--'
4398 * | 8 Mbyte
4399 * | write max
4400 * V
4401 * +==============================+
4402 * L2ARC dev |####|#|###|###| |####| ... |
4403 * +==============================+
4404 * 32 Gbytes
4405 *
4406 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
4407 * evicted, then the L2ARC has cached a buffer much sooner than it probably
4408 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
4409 * safe to say that this is an uncommon case, since buffers at the end of
4410 * the ARC lists have moved there due to inactivity.
4411 *
4412 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
4413 * then the L2ARC simply misses copying some buffers. This serves as a
4414 * pressure valve to prevent heavy read workloads from both stalling the ARC
4415 * with waits and clogging the L2ARC with writes. This also helps prevent
4416 * the potential for the L2ARC to churn if it attempts to cache content too
4417 * quickly, such as during backups of the entire pool.
4418 *
b128c09f
BB
4419 * 5. After system boot and before the ARC has filled main memory, there are
4420 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
4421 * lists can remain mostly static. Instead of searching from tail of these
4422 * lists as pictured, the l2arc_feed_thread() will search from the list heads
4423 * for eligible buffers, greatly increasing its chance of finding them.
4424 *
4425 * The L2ARC device write speed is also boosted during this time so that
4426 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
4427 * there are no L2ARC reads, and no fear of degrading read performance
4428 * through increased writes.
4429 *
4430 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
34dc7c2f
BB
4431 * the vdev queue can aggregate them into larger and fewer writes. Each
4432 * device is written to in a rotor fashion, sweeping writes through
4433 * available space then repeating.
4434 *
b128c09f 4435 * 7. The L2ARC does not store dirty content. It never needs to flush
34dc7c2f
BB
4436 * write buffers back to disk based storage.
4437 *
b128c09f 4438 * 8. If an ARC buffer is written (and dirtied) which also exists in the
34dc7c2f
BB
4439 * L2ARC, the now stale L2ARC buffer is immediately dropped.
4440 *
4441 * The performance of the L2ARC can be tweaked by a number of tunables, which
4442 * may be necessary for different workloads:
4443 *
4444 * l2arc_write_max max write bytes per interval
b128c09f 4445 * l2arc_write_boost extra write bytes during device warmup
34dc7c2f 4446 * l2arc_noprefetch skip caching prefetched buffers
3a17a7a9 4447 * l2arc_nocompress skip compressing buffers
34dc7c2f 4448 * l2arc_headroom number of max device writes to precache
3a17a7a9
SK
4449 * l2arc_headroom_boost when we find compressed buffers during ARC
4450 * scanning, we multiply headroom by this
4451 * percentage factor for the next scan cycle,
4452 * since more compressed buffers are likely to
4453 * be present
34dc7c2f
BB
4454 * l2arc_feed_secs seconds between L2ARC writing
4455 *
4456 * Tunables may be removed or added as future performance improvements are
4457 * integrated, and also may become zpool properties.
d164b209
BB
4458 *
4459 * There are three key functions that control how the L2ARC warms up:
4460 *
4461 * l2arc_write_eligible() check if a buffer is eligible to cache
4462 * l2arc_write_size() calculate how much to write
4463 * l2arc_write_interval() calculate sleep delay between writes
4464 *
4465 * These three functions determine what to write, how much, and how quickly
4466 * to send writes.
34dc7c2f
BB
4467 */
4468
d164b209
BB
4469static boolean_t
4470l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *ab)
4471{
4472 /*
4473 * A buffer is *not* eligible for the L2ARC if it:
4474 * 1. belongs to a different spa.
428870ff
BB
4475 * 2. is already cached on the L2ARC.
4476 * 3. has an I/O in progress (it may be an incomplete read).
4477 * 4. is flagged not eligible (zfs property).
d164b209 4478 */
428870ff 4479 if (ab->b_spa != spa_guid || ab->b_l2hdr != NULL ||
d164b209
BB
4480 HDR_IO_IN_PROGRESS(ab) || !HDR_L2CACHE(ab))
4481 return (B_FALSE);
4482
4483 return (B_TRUE);
4484}
4485
4486static uint64_t
3a17a7a9 4487l2arc_write_size(void)
d164b209
BB
4488{
4489 uint64_t size;
4490
3a17a7a9
SK
4491 /*
4492 * Make sure our globals have meaningful values in case the user
4493 * altered them.
4494 */
4495 size = l2arc_write_max;
4496 if (size == 0) {
4497 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
4498 "be greater than zero, resetting it to the default (%d)",
4499 L2ARC_WRITE_SIZE);
4500 size = l2arc_write_max = L2ARC_WRITE_SIZE;
4501 }
d164b209
BB
4502
4503 if (arc_warm == B_FALSE)
3a17a7a9 4504 size += l2arc_write_boost;
d164b209
BB
4505
4506 return (size);
4507
4508}
4509
4510static clock_t
4511l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
4512{
428870ff 4513 clock_t interval, next, now;
d164b209
BB
4514
4515 /*
4516 * If the ARC lists are busy, increase our write rate; if the
4517 * lists are stale, idle back. This is achieved by checking
4518 * how much we previously wrote - if it was more than half of
4519 * what we wanted, schedule the next write much sooner.
4520 */
4521 if (l2arc_feed_again && wrote > (wanted / 2))
4522 interval = (hz * l2arc_feed_min_ms) / 1000;
4523 else
4524 interval = hz * l2arc_feed_secs;
4525
428870ff
BB
4526 now = ddi_get_lbolt();
4527 next = MAX(now, MIN(now + interval, began + interval));
d164b209
BB
4528
4529 return (next);
4530}
4531
34dc7c2f
BB
4532static void
4533l2arc_hdr_stat_add(void)
4534{
6e1d7276 4535 ARCSTAT_INCR(arcstat_l2_hdr_size, HDR_SIZE);
34dc7c2f
BB
4536 ARCSTAT_INCR(arcstat_hdr_size, -HDR_SIZE);
4537}
4538
4539static void
4540l2arc_hdr_stat_remove(void)
4541{
6e1d7276 4542 ARCSTAT_INCR(arcstat_l2_hdr_size, -HDR_SIZE);
34dc7c2f
BB
4543 ARCSTAT_INCR(arcstat_hdr_size, HDR_SIZE);
4544}
4545
4546/*
4547 * Cycle through L2ARC devices. This is how L2ARC load balances.
b128c09f 4548 * If a device is returned, this also returns holding the spa config lock.
34dc7c2f
BB
4549 */
4550static l2arc_dev_t *
4551l2arc_dev_get_next(void)
4552{
b128c09f 4553 l2arc_dev_t *first, *next = NULL;
34dc7c2f 4554
b128c09f
BB
4555 /*
4556 * Lock out the removal of spas (spa_namespace_lock), then removal
4557 * of cache devices (l2arc_dev_mtx). Once a device has been selected,
4558 * both locks will be dropped and a spa config lock held instead.
4559 */
4560 mutex_enter(&spa_namespace_lock);
4561 mutex_enter(&l2arc_dev_mtx);
4562
4563 /* if there are no vdevs, there is nothing to do */
4564 if (l2arc_ndev == 0)
4565 goto out;
4566
4567 first = NULL;
4568 next = l2arc_dev_last;
4569 do {
4570 /* loop around the list looking for a non-faulted vdev */
4571 if (next == NULL) {
34dc7c2f 4572 next = list_head(l2arc_dev_list);
b128c09f
BB
4573 } else {
4574 next = list_next(l2arc_dev_list, next);
4575 if (next == NULL)
4576 next = list_head(l2arc_dev_list);
4577 }
4578
4579 /* if we have come back to the start, bail out */
4580 if (first == NULL)
4581 first = next;
4582 else if (next == first)
4583 break;
4584
4585 } while (vdev_is_dead(next->l2ad_vdev));
4586
4587 /* if we were unable to find any usable vdevs, return NULL */
4588 if (vdev_is_dead(next->l2ad_vdev))
4589 next = NULL;
34dc7c2f
BB
4590
4591 l2arc_dev_last = next;
4592
b128c09f
BB
4593out:
4594 mutex_exit(&l2arc_dev_mtx);
4595
4596 /*
4597 * Grab the config lock to prevent the 'next' device from being
4598 * removed while we are writing to it.
4599 */
4600 if (next != NULL)
4601 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
4602 mutex_exit(&spa_namespace_lock);
4603
34dc7c2f
BB
4604 return (next);
4605}
4606
b128c09f
BB
4607/*
4608 * Free buffers that were tagged for destruction.
4609 */
4610static void
0bc8fd78 4611l2arc_do_free_on_write(void)
b128c09f
BB
4612{
4613 list_t *buflist;
4614 l2arc_data_free_t *df, *df_prev;
4615
4616 mutex_enter(&l2arc_free_on_write_mtx);
4617 buflist = l2arc_free_on_write;
4618
4619 for (df = list_tail(buflist); df; df = df_prev) {
4620 df_prev = list_prev(buflist, df);
4621 ASSERT(df->l2df_data != NULL);
4622 ASSERT(df->l2df_func != NULL);
4623 df->l2df_func(df->l2df_data, df->l2df_size);
4624 list_remove(buflist, df);
4625 kmem_free(df, sizeof (l2arc_data_free_t));
4626 }
4627
4628 mutex_exit(&l2arc_free_on_write_mtx);
4629}
4630
34dc7c2f
BB
4631/*
4632 * A write to a cache device has completed. Update all headers to allow
4633 * reads from these buffers to begin.
4634 */
4635static void
4636l2arc_write_done(zio_t *zio)
4637{
4638 l2arc_write_callback_t *cb;
4639 l2arc_dev_t *dev;
4640 list_t *buflist;
34dc7c2f 4641 arc_buf_hdr_t *head, *ab, *ab_prev;
b128c09f 4642 l2arc_buf_hdr_t *abl2;
34dc7c2f 4643 kmutex_t *hash_lock;
3bec585e 4644 int64_t bytes_dropped = 0;
34dc7c2f
BB
4645
4646 cb = zio->io_private;
4647 ASSERT(cb != NULL);
4648 dev = cb->l2wcb_dev;
4649 ASSERT(dev != NULL);
4650 head = cb->l2wcb_head;
4651 ASSERT(head != NULL);
4652 buflist = dev->l2ad_buflist;
4653 ASSERT(buflist != NULL);
4654 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
4655 l2arc_write_callback_t *, cb);
4656
4657 if (zio->io_error != 0)
4658 ARCSTAT_BUMP(arcstat_l2_writes_error);
4659
4660 mutex_enter(&l2arc_buflist_mtx);
4661
4662 /*
4663 * All writes completed, or an error was hit.
4664 */
4665 for (ab = list_prev(buflist, head); ab; ab = ab_prev) {
4666 ab_prev = list_prev(buflist, ab);
1ca546b3
SK
4667 abl2 = ab->b_l2hdr;
4668
4669 /*
4670 * Release the temporary compressed buffer as soon as possible.
4671 */
4672 if (abl2->b_compress != ZIO_COMPRESS_OFF)
4673 l2arc_release_cdata_buf(ab);
34dc7c2f
BB
4674
4675 hash_lock = HDR_LOCK(ab);
4676 if (!mutex_tryenter(hash_lock)) {
4677 /*
4678 * This buffer misses out. It may be in a stage
4679 * of eviction. Its ARC_L2_WRITING flag will be
4680 * left set, denying reads to this buffer.
4681 */
4682 ARCSTAT_BUMP(arcstat_l2_writes_hdr_miss);
4683 continue;
4684 }
4685
4686 if (zio->io_error != 0) {
4687 /*
b128c09f 4688 * Error - drop L2ARC entry.
34dc7c2f 4689 */
b128c09f 4690 list_remove(buflist, ab);
3a17a7a9 4691 ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
3bec585e 4692 bytes_dropped += abl2->b_asize;
34dc7c2f 4693 ab->b_l2hdr = NULL;
ecf3d9b8 4694 kmem_cache_free(l2arc_hdr_cache, abl2);
6e1d7276 4695 arc_space_return(L2HDR_SIZE, ARC_SPACE_L2HDRS);
b128c09f 4696 ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
34dc7c2f
BB
4697 }
4698
4699 /*
4700 * Allow ARC to begin reads to this L2ARC entry.
4701 */
4702 ab->b_flags &= ~ARC_L2_WRITING;
4703
4704 mutex_exit(hash_lock);
4705 }
4706
4707 atomic_inc_64(&l2arc_writes_done);
4708 list_remove(buflist, head);
4709 kmem_cache_free(hdr_cache, head);
4710 mutex_exit(&l2arc_buflist_mtx);
4711
3bec585e
SK
4712 vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
4713
b128c09f 4714 l2arc_do_free_on_write();
34dc7c2f
BB
4715
4716 kmem_free(cb, sizeof (l2arc_write_callback_t));
4717}
4718
4719/*
4720 * A read to a cache device completed. Validate buffer contents before
4721 * handing over to the regular ARC routines.
4722 */
4723static void
4724l2arc_read_done(zio_t *zio)
4725{
4726 l2arc_read_callback_t *cb;
4727 arc_buf_hdr_t *hdr;
4728 arc_buf_t *buf;
34dc7c2f 4729 kmutex_t *hash_lock;
b128c09f
BB
4730 int equal;
4731
4732 ASSERT(zio->io_vd != NULL);
4733 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
4734
4735 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
34dc7c2f
BB
4736
4737 cb = zio->io_private;
4738 ASSERT(cb != NULL);
4739 buf = cb->l2rcb_buf;
4740 ASSERT(buf != NULL);
34dc7c2f 4741
428870ff 4742 hash_lock = HDR_LOCK(buf->b_hdr);
34dc7c2f 4743 mutex_enter(hash_lock);
428870ff
BB
4744 hdr = buf->b_hdr;
4745 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
34dc7c2f 4746
3a17a7a9
SK
4747 /*
4748 * If the buffer was compressed, decompress it first.
4749 */
4750 if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
4751 l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
4752 ASSERT(zio->io_data != NULL);
4753
34dc7c2f
BB
4754 /*
4755 * Check this survived the L2ARC journey.
4756 */
4757 equal = arc_cksum_equal(buf);
4758 if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
4759 mutex_exit(hash_lock);
4760 zio->io_private = buf;
b128c09f
BB
4761 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
4762 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
34dc7c2f
BB
4763 arc_read_done(zio);
4764 } else {
4765 mutex_exit(hash_lock);
4766 /*
4767 * Buffer didn't survive caching. Increment stats and
4768 * reissue to the original storage device.
4769 */
b128c09f 4770 if (zio->io_error != 0) {
34dc7c2f 4771 ARCSTAT_BUMP(arcstat_l2_io_error);
b128c09f 4772 } else {
2e528b49 4773 zio->io_error = SET_ERROR(EIO);
b128c09f 4774 }
34dc7c2f
BB
4775 if (!equal)
4776 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
4777
34dc7c2f 4778 /*
b128c09f
BB
4779 * If there's no waiter, issue an async i/o to the primary
4780 * storage now. If there *is* a waiter, the caller must
4781 * issue the i/o in a context where it's OK to block.
34dc7c2f 4782 */
d164b209
BB
4783 if (zio->io_waiter == NULL) {
4784 zio_t *pio = zio_unique_parent(zio);
4785
4786 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
4787
4788 zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
b128c09f
BB
4789 buf->b_data, zio->io_size, arc_read_done, buf,
4790 zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
d164b209 4791 }
34dc7c2f
BB
4792 }
4793
4794 kmem_free(cb, sizeof (l2arc_read_callback_t));
4795}
4796
4797/*
4798 * This is the list priority from which the L2ARC will search for pages to
4799 * cache. This is used within loops (0..3) to cycle through lists in the
4800 * desired order. This order can have a significant effect on cache
4801 * performance.
4802 *
4803 * Currently the metadata lists are hit first, MFU then MRU, followed by
4804 * the data lists. This function returns a locked list, and also returns
4805 * the lock pointer.
4806 */
4807static list_t *
4808l2arc_list_locked(int list_num, kmutex_t **lock)
4809{
d4ed6673 4810 list_t *list = NULL;
34dc7c2f
BB
4811
4812 ASSERT(list_num >= 0 && list_num <= 3);
4813
4814 switch (list_num) {
4815 case 0:
4816 list = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
4817 *lock = &arc_mfu->arcs_mtx;
4818 break;
4819 case 1:
4820 list = &arc_mru->arcs_list[ARC_BUFC_METADATA];
4821 *lock = &arc_mru->arcs_mtx;
4822 break;
4823 case 2:
4824 list = &arc_mfu->arcs_list[ARC_BUFC_DATA];
4825 *lock = &arc_mfu->arcs_mtx;
4826 break;
4827 case 3:
4828 list = &arc_mru->arcs_list[ARC_BUFC_DATA];
4829 *lock = &arc_mru->arcs_mtx;
4830 break;
4831 }
4832
4833 ASSERT(!(MUTEX_HELD(*lock)));
4834 mutex_enter(*lock);
4835 return (list);
4836}
4837
4838/*
4839 * Evict buffers from the device write hand to the distance specified in
4840 * bytes. This distance may span populated buffers, it may span nothing.
4841 * This is clearing a region on the L2ARC device ready for writing.
4842 * If the 'all' boolean is set, every buffer is evicted.
4843 */
4844static void
4845l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
4846{
4847 list_t *buflist;
4848 l2arc_buf_hdr_t *abl2;
4849 arc_buf_hdr_t *ab, *ab_prev;
4850 kmutex_t *hash_lock;
4851 uint64_t taddr;
3bec585e 4852 int64_t bytes_evicted = 0;
34dc7c2f 4853
34dc7c2f
BB
4854 buflist = dev->l2ad_buflist;
4855
4856 if (buflist == NULL)
4857 return;
4858
4859 if (!all && dev->l2ad_first) {
4860 /*
4861 * This is the first sweep through the device. There is
4862 * nothing to evict.
4863 */
4864 return;
4865 }
4866
b128c09f 4867 if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
34dc7c2f
BB
4868 /*
4869 * When nearing the end of the device, evict to the end
4870 * before the device write hand jumps to the start.
4871 */
4872 taddr = dev->l2ad_end;
4873 } else {
4874 taddr = dev->l2ad_hand + distance;
4875 }
4876 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
4877 uint64_t, taddr, boolean_t, all);
4878
4879top:
4880 mutex_enter(&l2arc_buflist_mtx);
4881 for (ab = list_tail(buflist); ab; ab = ab_prev) {
4882 ab_prev = list_prev(buflist, ab);
4883
4884 hash_lock = HDR_LOCK(ab);
4885 if (!mutex_tryenter(hash_lock)) {
4886 /*
4887 * Missed the hash lock. Retry.
4888 */
4889 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
4890 mutex_exit(&l2arc_buflist_mtx);
4891 mutex_enter(hash_lock);
4892 mutex_exit(hash_lock);
4893 goto top;
4894 }
4895
4896 if (HDR_L2_WRITE_HEAD(ab)) {
4897 /*
4898 * We hit a write head node. Leave it for
4899 * l2arc_write_done().
4900 */
4901 list_remove(buflist, ab);
4902 mutex_exit(hash_lock);
4903 continue;
4904 }
4905
4906 if (!all && ab->b_l2hdr != NULL &&
4907 (ab->b_l2hdr->b_daddr > taddr ||
4908 ab->b_l2hdr->b_daddr < dev->l2ad_hand)) {
4909 /*
4910 * We've evicted to the target address,
4911 * or the end of the device.
4912 */
4913 mutex_exit(hash_lock);
4914 break;
4915 }
4916
4917 if (HDR_FREE_IN_PROGRESS(ab)) {
4918 /*
4919 * Already on the path to destruction.
4920 */
4921 mutex_exit(hash_lock);
4922 continue;
4923 }
4924
4925 if (ab->b_state == arc_l2c_only) {
4926 ASSERT(!HDR_L2_READING(ab));
4927 /*
4928 * This doesn't exist in the ARC. Destroy.
4929 * arc_hdr_destroy() will call list_remove()
4930 * and decrement arcstat_l2_size.
4931 */
4932 arc_change_state(arc_anon, ab, hash_lock);
4933 arc_hdr_destroy(ab);
4934 } else {
b128c09f
BB
4935 /*
4936 * Invalidate issued or about to be issued
4937 * reads, since we may be about to write
4938 * over this location.
4939 */
4940 if (HDR_L2_READING(ab)) {
4941 ARCSTAT_BUMP(arcstat_l2_evict_reading);
4942 ab->b_flags |= ARC_L2_EVICTED;
4943 }
4944
34dc7c2f
BB
4945 /*
4946 * Tell ARC this no longer exists in L2ARC.
4947 */
4948 if (ab->b_l2hdr != NULL) {
4949 abl2 = ab->b_l2hdr;
3a17a7a9 4950 ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
3bec585e 4951 bytes_evicted += abl2->b_asize;
34dc7c2f 4952 ab->b_l2hdr = NULL;
ecf3d9b8 4953 kmem_cache_free(l2arc_hdr_cache, abl2);
6e1d7276 4954 arc_space_return(L2HDR_SIZE, ARC_SPACE_L2HDRS);
34dc7c2f
BB
4955 ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
4956 }
4957 list_remove(buflist, ab);
4958
4959 /*
4960 * This may have been leftover after a
4961 * failed write.
4962 */
4963 ab->b_flags &= ~ARC_L2_WRITING;
34dc7c2f
BB
4964 }
4965 mutex_exit(hash_lock);
4966 }
4967 mutex_exit(&l2arc_buflist_mtx);
4968
3bec585e 4969 vdev_space_update(dev->l2ad_vdev, -bytes_evicted, 0, 0);
34dc7c2f
BB
4970 dev->l2ad_evict = taddr;
4971}
4972
4973/*
4974 * Find and write ARC buffers to the L2ARC device.
4975 *
4976 * An ARC_L2_WRITING flag is set so that the L2ARC buffers are not valid
4977 * for reading until they have completed writing.
3a17a7a9
SK
4978 * The headroom_boost is an in-out parameter used to maintain headroom boost
4979 * state between calls to this function.
4980 *
4981 * Returns the number of bytes actually written (which may be smaller than
4982 * the delta by which the device hand has changed due to alignment).
34dc7c2f 4983 */
d164b209 4984static uint64_t
3a17a7a9
SK
4985l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
4986 boolean_t *headroom_boost)
34dc7c2f
BB
4987{
4988 arc_buf_hdr_t *ab, *ab_prev, *head;
34dc7c2f 4989 list_t *list;
3a17a7a9
SK
4990 uint64_t write_asize, write_psize, write_sz, headroom,
4991 buf_compress_minsz;
34dc7c2f 4992 void *buf_data;
3a17a7a9
SK
4993 kmutex_t *list_lock = NULL;
4994 boolean_t full;
34dc7c2f
BB
4995 l2arc_write_callback_t *cb;
4996 zio_t *pio, *wzio;
3541dc6d 4997 uint64_t guid = spa_load_guid(spa);
d6320ddb 4998 int try;
3a17a7a9 4999 const boolean_t do_headroom_boost = *headroom_boost;
34dc7c2f 5000
34dc7c2f
BB
5001 ASSERT(dev->l2ad_vdev != NULL);
5002
3a17a7a9
SK
5003 /* Lower the flag now, we might want to raise it again later. */
5004 *headroom_boost = B_FALSE;
5005
34dc7c2f 5006 pio = NULL;
3a17a7a9 5007 write_sz = write_asize = write_psize = 0;
34dc7c2f
BB
5008 full = B_FALSE;
5009 head = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
5010 head->b_flags |= ARC_L2_WRITE_HEAD;
5011
3a17a7a9
SK
5012 /*
5013 * We will want to try to compress buffers that are at least 2x the
5014 * device sector size.
5015 */
5016 buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
5017
34dc7c2f
BB
5018 /*
5019 * Copy buffers for L2ARC writing.
5020 */
5021 mutex_enter(&l2arc_buflist_mtx);
d6320ddb 5022 for (try = 0; try <= 3; try++) {
3a17a7a9
SK
5023 uint64_t passed_sz = 0;
5024
34dc7c2f 5025 list = l2arc_list_locked(try, &list_lock);
34dc7c2f 5026
b128c09f
BB
5027 /*
5028 * L2ARC fast warmup.
5029 *
5030 * Until the ARC is warm and starts to evict, read from the
5031 * head of the ARC lists rather than the tail.
5032 */
b128c09f
BB
5033 if (arc_warm == B_FALSE)
5034 ab = list_head(list);
5035 else
5036 ab = list_tail(list);
5037
3a17a7a9
SK
5038 headroom = target_sz * l2arc_headroom;
5039 if (do_headroom_boost)
5040 headroom = (headroom * l2arc_headroom_boost) / 100;
5041
b128c09f 5042 for (; ab; ab = ab_prev) {
3a17a7a9
SK
5043 l2arc_buf_hdr_t *l2hdr;
5044 kmutex_t *hash_lock;
5045 uint64_t buf_sz;
5046
b128c09f
BB
5047 if (arc_warm == B_FALSE)
5048 ab_prev = list_next(list, ab);
5049 else
5050 ab_prev = list_prev(list, ab);
34dc7c2f
BB
5051
5052 hash_lock = HDR_LOCK(ab);
3a17a7a9 5053 if (!mutex_tryenter(hash_lock)) {
34dc7c2f
BB
5054 /*
5055 * Skip this buffer rather than waiting.
5056 */
5057 continue;
5058 }
5059
5060 passed_sz += ab->b_size;
5061 if (passed_sz > headroom) {
5062 /*
5063 * Searched too far.
5064 */
5065 mutex_exit(hash_lock);
5066 break;
5067 }
5068
d164b209 5069 if (!l2arc_write_eligible(guid, ab)) {
34dc7c2f
BB
5070 mutex_exit(hash_lock);
5071 continue;
5072 }
5073
5074 if ((write_sz + ab->b_size) > target_sz) {
5075 full = B_TRUE;
5076 mutex_exit(hash_lock);
5077 break;
5078 }
5079
34dc7c2f
BB
5080 if (pio == NULL) {
5081 /*
5082 * Insert a dummy header on the buflist so
5083 * l2arc_write_done() can find where the
5084 * write buffers begin without searching.
5085 */
5086 list_insert_head(dev->l2ad_buflist, head);
5087
409dc1a5 5088 cb = kmem_alloc(sizeof (l2arc_write_callback_t),
d1d7e268 5089 KM_PUSHPAGE);
34dc7c2f
BB
5090 cb->l2wcb_dev = dev;
5091 cb->l2wcb_head = head;
5092 pio = zio_root(spa, l2arc_write_done, cb,
5093 ZIO_FLAG_CANFAIL);
5094 }
5095
5096 /*
5097 * Create and add a new L2ARC header.
5098 */
ecf3d9b8 5099 l2hdr = kmem_cache_alloc(l2arc_hdr_cache, KM_PUSHPAGE);
3a17a7a9 5100 l2hdr->b_dev = dev;
ecf3d9b8 5101 l2hdr->b_daddr = 0;
6e1d7276 5102 arc_space_consume(L2HDR_SIZE, ARC_SPACE_L2HDRS);
34dc7c2f
BB
5103
5104 ab->b_flags |= ARC_L2_WRITING;
3a17a7a9
SK
5105
5106 /*
5107 * Temporarily stash the data buffer in b_tmp_cdata.
5108 * The subsequent write step will pick it up from
5109 * there. This is because can't access ab->b_buf
5110 * without holding the hash_lock, which we in turn
5111 * can't access without holding the ARC list locks
5112 * (which we want to avoid during compression/writing)
5113 */
5114 l2hdr->b_compress = ZIO_COMPRESS_OFF;
5115 l2hdr->b_asize = ab->b_size;
5116 l2hdr->b_tmp_cdata = ab->b_buf->b_data;
e0b0ca98 5117 l2hdr->b_hits = 0;
3a17a7a9 5118
34dc7c2f 5119 buf_sz = ab->b_size;
3a17a7a9
SK
5120 ab->b_l2hdr = l2hdr;
5121
5122 list_insert_head(dev->l2ad_buflist, ab);
34dc7c2f
BB
5123
5124 /*
5125 * Compute and store the buffer cksum before
5126 * writing. On debug the cksum is verified first.
5127 */
5128 arc_cksum_verify(ab->b_buf);
5129 arc_cksum_compute(ab->b_buf, B_TRUE);
5130
5131 mutex_exit(hash_lock);
5132
3a17a7a9
SK
5133 write_sz += buf_sz;
5134 }
5135
5136 mutex_exit(list_lock);
5137
5138 if (full == B_TRUE)
5139 break;
5140 }
5141
5142 /* No buffers selected for writing? */
5143 if (pio == NULL) {
5144 ASSERT0(write_sz);
5145 mutex_exit(&l2arc_buflist_mtx);
5146 kmem_cache_free(hdr_cache, head);
5147 return (0);
5148 }
5149
5150 /*
5151 * Now start writing the buffers. We're starting at the write head
5152 * and work backwards, retracing the course of the buffer selector
5153 * loop above.
5154 */
5155 for (ab = list_prev(dev->l2ad_buflist, head); ab;
5156 ab = list_prev(dev->l2ad_buflist, ab)) {
5157 l2arc_buf_hdr_t *l2hdr;
5158 uint64_t buf_sz;
5159
5160 /*
5161 * We shouldn't need to lock the buffer here, since we flagged
5162 * it as ARC_L2_WRITING in the previous step, but we must take
5163 * care to only access its L2 cache parameters. In particular,
5164 * ab->b_buf may be invalid by now due to ARC eviction.
5165 */
5166 l2hdr = ab->b_l2hdr;
5167 l2hdr->b_daddr = dev->l2ad_hand;
5168
5169 if (!l2arc_nocompress && (ab->b_flags & ARC_L2COMPRESS) &&
5170 l2hdr->b_asize >= buf_compress_minsz) {
5171 if (l2arc_compress_buf(l2hdr)) {
5172 /*
5173 * If compression succeeded, enable headroom
5174 * boost on the next scan cycle.
5175 */
5176 *headroom_boost = B_TRUE;
5177 }
5178 }
5179
5180 /*
5181 * Pick up the buffer data we had previously stashed away
5182 * (and now potentially also compressed).
5183 */
5184 buf_data = l2hdr->b_tmp_cdata;
5185 buf_sz = l2hdr->b_asize;
5186
5187 /* Compression may have squashed the buffer to zero length. */
5188 if (buf_sz != 0) {
5189 uint64_t buf_p_sz;
5190
34dc7c2f
BB
5191 wzio = zio_write_phys(pio, dev->l2ad_vdev,
5192 dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
5193 NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
5194 ZIO_FLAG_CANFAIL, B_FALSE);
5195
5196 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
5197 zio_t *, wzio);
5198 (void) zio_nowait(wzio);
5199
3a17a7a9 5200 write_asize += buf_sz;
b128c09f
BB
5201 /*
5202 * Keep the clock hand suitably device-aligned.
5203 */
3a17a7a9
SK
5204 buf_p_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
5205 write_psize += buf_p_sz;
5206 dev->l2ad_hand += buf_p_sz;
34dc7c2f 5207 }
34dc7c2f 5208 }
34dc7c2f 5209
3a17a7a9 5210 mutex_exit(&l2arc_buflist_mtx);
34dc7c2f 5211
3a17a7a9 5212 ASSERT3U(write_asize, <=, target_sz);
34dc7c2f 5213 ARCSTAT_BUMP(arcstat_l2_writes_sent);
3a17a7a9 5214 ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
34dc7c2f 5215 ARCSTAT_INCR(arcstat_l2_size, write_sz);
3a17a7a9 5216 ARCSTAT_INCR(arcstat_l2_asize, write_asize);
3bec585e 5217 vdev_space_update(dev->l2ad_vdev, write_asize, 0, 0);
34dc7c2f
BB
5218
5219 /*
5220 * Bump device hand to the device start if it is approaching the end.
5221 * l2arc_evict() will already have evicted ahead for this case.
5222 */
b128c09f 5223 if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
34dc7c2f
BB
5224 dev->l2ad_hand = dev->l2ad_start;
5225 dev->l2ad_evict = dev->l2ad_start;
5226 dev->l2ad_first = B_FALSE;
5227 }
5228
d164b209 5229 dev->l2ad_writing = B_TRUE;
34dc7c2f 5230 (void) zio_wait(pio);
d164b209
BB
5231 dev->l2ad_writing = B_FALSE;
5232
3a17a7a9
SK
5233 return (write_asize);
5234}
5235
5236/*
5237 * Compresses an L2ARC buffer.
5238 * The data to be compressed must be prefilled in l2hdr->b_tmp_cdata and its
5239 * size in l2hdr->b_asize. This routine tries to compress the data and
5240 * depending on the compression result there are three possible outcomes:
5241 * *) The buffer was incompressible. The original l2hdr contents were left
5242 * untouched and are ready for writing to an L2 device.
5243 * *) The buffer was all-zeros, so there is no need to write it to an L2
5244 * device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
5245 * set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
5246 * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
5247 * data buffer which holds the compressed data to be written, and b_asize
5248 * tells us how much data there is. b_compress is set to the appropriate
5249 * compression algorithm. Once writing is done, invoke
5250 * l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
5251 *
5252 * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
5253 * buffer was incompressible).
5254 */
5255static boolean_t
5256l2arc_compress_buf(l2arc_buf_hdr_t *l2hdr)
5257{
5258 void *cdata;
9b67f605 5259 size_t csize, len, rounded;
3a17a7a9
SK
5260
5261 ASSERT(l2hdr->b_compress == ZIO_COMPRESS_OFF);
5262 ASSERT(l2hdr->b_tmp_cdata != NULL);
5263
5264 len = l2hdr->b_asize;
5265 cdata = zio_data_buf_alloc(len);
5266 csize = zio_compress_data(ZIO_COMPRESS_LZ4, l2hdr->b_tmp_cdata,
5267 cdata, l2hdr->b_asize);
5268
9b67f605
MA
5269 rounded = P2ROUNDUP(csize, (size_t)SPA_MINBLOCKSIZE);
5270 if (rounded > csize) {
5271 bzero((char *)cdata + csize, rounded - csize);
5272 csize = rounded;
5273 }
5274
3a17a7a9
SK
5275 if (csize == 0) {
5276 /* zero block, indicate that there's nothing to write */
5277 zio_data_buf_free(cdata, len);
5278 l2hdr->b_compress = ZIO_COMPRESS_EMPTY;
5279 l2hdr->b_asize = 0;
5280 l2hdr->b_tmp_cdata = NULL;
5281 ARCSTAT_BUMP(arcstat_l2_compress_zeros);
5282 return (B_TRUE);
5283 } else if (csize > 0 && csize < len) {
5284 /*
5285 * Compression succeeded, we'll keep the cdata around for
5286 * writing and release it afterwards.
5287 */
5288 l2hdr->b_compress = ZIO_COMPRESS_LZ4;
5289 l2hdr->b_asize = csize;
5290 l2hdr->b_tmp_cdata = cdata;
5291 ARCSTAT_BUMP(arcstat_l2_compress_successes);
5292 return (B_TRUE);
5293 } else {
5294 /*
5295 * Compression failed, release the compressed buffer.
5296 * l2hdr will be left unmodified.
5297 */
5298 zio_data_buf_free(cdata, len);
5299 ARCSTAT_BUMP(arcstat_l2_compress_failures);
5300 return (B_FALSE);
5301 }
5302}
5303
5304/*
5305 * Decompresses a zio read back from an l2arc device. On success, the
5306 * underlying zio's io_data buffer is overwritten by the uncompressed
5307 * version. On decompression error (corrupt compressed stream), the
5308 * zio->io_error value is set to signal an I/O error.
5309 *
5310 * Please note that the compressed data stream is not checksummed, so
5311 * if the underlying device is experiencing data corruption, we may feed
5312 * corrupt data to the decompressor, so the decompressor needs to be
5313 * able to handle this situation (LZ4 does).
5314 */
5315static void
5316l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
5317{
5318 uint64_t csize;
5319 void *cdata;
5320
5321 ASSERT(L2ARC_IS_VALID_COMPRESS(c));
5322
5323 if (zio->io_error != 0) {
5324 /*
5325 * An io error has occured, just restore the original io
5326 * size in preparation for a main pool read.
5327 */
5328 zio->io_orig_size = zio->io_size = hdr->b_size;
5329 return;
5330 }
5331
5332 if (c == ZIO_COMPRESS_EMPTY) {
5333 /*
5334 * An empty buffer results in a null zio, which means we
5335 * need to fill its io_data after we're done restoring the
5336 * buffer's contents.
5337 */
5338 ASSERT(hdr->b_buf != NULL);
5339 bzero(hdr->b_buf->b_data, hdr->b_size);
5340 zio->io_data = zio->io_orig_data = hdr->b_buf->b_data;
5341 } else {
5342 ASSERT(zio->io_data != NULL);
5343 /*
5344 * We copy the compressed data from the start of the arc buffer
5345 * (the zio_read will have pulled in only what we need, the
5346 * rest is garbage which we will overwrite at decompression)
5347 * and then decompress back to the ARC data buffer. This way we
5348 * can minimize copying by simply decompressing back over the
5349 * original compressed data (rather than decompressing to an
5350 * aux buffer and then copying back the uncompressed buffer,
5351 * which is likely to be much larger).
5352 */
5353 csize = zio->io_size;
5354 cdata = zio_data_buf_alloc(csize);
5355 bcopy(zio->io_data, cdata, csize);
5356 if (zio_decompress_data(c, cdata, zio->io_data, csize,
5357 hdr->b_size) != 0)
2e528b49 5358 zio->io_error = SET_ERROR(EIO);
3a17a7a9
SK
5359 zio_data_buf_free(cdata, csize);
5360 }
5361
5362 /* Restore the expected uncompressed IO size. */
5363 zio->io_orig_size = zio->io_size = hdr->b_size;
5364}
5365
5366/*
5367 * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
5368 * This buffer serves as a temporary holder of compressed data while
5369 * the buffer entry is being written to an l2arc device. Once that is
5370 * done, we can dispose of it.
5371 */
5372static void
5373l2arc_release_cdata_buf(arc_buf_hdr_t *ab)
5374{
5375 l2arc_buf_hdr_t *l2hdr = ab->b_l2hdr;
5376
5377 if (l2hdr->b_compress == ZIO_COMPRESS_LZ4) {
5378 /*
5379 * If the data was compressed, then we've allocated a
5380 * temporary buffer for it, so now we need to release it.
5381 */
5382 ASSERT(l2hdr->b_tmp_cdata != NULL);
5383 zio_data_buf_free(l2hdr->b_tmp_cdata, ab->b_size);
5384 }
5385 l2hdr->b_tmp_cdata = NULL;
34dc7c2f
BB
5386}
5387
5388/*
5389 * This thread feeds the L2ARC at regular intervals. This is the beating
5390 * heart of the L2ARC.
5391 */
5392static void
5393l2arc_feed_thread(void)
5394{
5395 callb_cpr_t cpr;
5396 l2arc_dev_t *dev;
5397 spa_t *spa;
d164b209 5398 uint64_t size, wrote;
428870ff 5399 clock_t begin, next = ddi_get_lbolt();
3a17a7a9 5400 boolean_t headroom_boost = B_FALSE;
34dc7c2f
BB
5401
5402 CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
5403
5404 mutex_enter(&l2arc_feed_thr_lock);
5405
5406 while (l2arc_thread_exit == 0) {
34dc7c2f 5407 CALLB_CPR_SAFE_BEGIN(&cpr);
5b63b3eb
BB
5408 (void) cv_timedwait_interruptible(&l2arc_feed_thr_cv,
5409 &l2arc_feed_thr_lock, next);
34dc7c2f 5410 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
428870ff 5411 next = ddi_get_lbolt() + hz;
34dc7c2f
BB
5412
5413 /*
b128c09f 5414 * Quick check for L2ARC devices.
34dc7c2f
BB
5415 */
5416 mutex_enter(&l2arc_dev_mtx);
5417 if (l2arc_ndev == 0) {
5418 mutex_exit(&l2arc_dev_mtx);
5419 continue;
5420 }
b128c09f 5421 mutex_exit(&l2arc_dev_mtx);
428870ff 5422 begin = ddi_get_lbolt();
34dc7c2f
BB
5423
5424 /*
b128c09f
BB
5425 * This selects the next l2arc device to write to, and in
5426 * doing so the next spa to feed from: dev->l2ad_spa. This
5427 * will return NULL if there are now no l2arc devices or if
5428 * they are all faulted.
5429 *
5430 * If a device is returned, its spa's config lock is also
5431 * held to prevent device removal. l2arc_dev_get_next()
5432 * will grab and release l2arc_dev_mtx.
34dc7c2f 5433 */
b128c09f 5434 if ((dev = l2arc_dev_get_next()) == NULL)
34dc7c2f 5435 continue;
b128c09f
BB
5436
5437 spa = dev->l2ad_spa;
5438 ASSERT(spa != NULL);
34dc7c2f 5439
572e2857
BB
5440 /*
5441 * If the pool is read-only then force the feed thread to
5442 * sleep a little longer.
5443 */
5444 if (!spa_writeable(spa)) {
5445 next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
5446 spa_config_exit(spa, SCL_L2ARC, dev);
5447 continue;
5448 }
5449
34dc7c2f 5450 /*
b128c09f 5451 * Avoid contributing to memory pressure.
34dc7c2f 5452 */
302f753f 5453 if (arc_no_grow) {
b128c09f
BB
5454 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
5455 spa_config_exit(spa, SCL_L2ARC, dev);
34dc7c2f
BB
5456 continue;
5457 }
b128c09f 5458
34dc7c2f
BB
5459 ARCSTAT_BUMP(arcstat_l2_feeds);
5460
3a17a7a9 5461 size = l2arc_write_size();
b128c09f 5462
34dc7c2f
BB
5463 /*
5464 * Evict L2ARC buffers that will be overwritten.
5465 */
b128c09f 5466 l2arc_evict(dev, size, B_FALSE);
34dc7c2f
BB
5467
5468 /*
5469 * Write ARC buffers.
5470 */
3a17a7a9 5471 wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
d164b209
BB
5472
5473 /*
5474 * Calculate interval between writes.
5475 */
5476 next = l2arc_write_interval(begin, size, wrote);
b128c09f 5477 spa_config_exit(spa, SCL_L2ARC, dev);
34dc7c2f
BB
5478 }
5479
5480 l2arc_thread_exit = 0;
5481 cv_broadcast(&l2arc_feed_thr_cv);
5482 CALLB_CPR_EXIT(&cpr); /* drops l2arc_feed_thr_lock */
5483 thread_exit();
5484}
5485
b128c09f
BB
5486boolean_t
5487l2arc_vdev_present(vdev_t *vd)
5488{
5489 l2arc_dev_t *dev;
5490
5491 mutex_enter(&l2arc_dev_mtx);
5492 for (dev = list_head(l2arc_dev_list); dev != NULL;
5493 dev = list_next(l2arc_dev_list, dev)) {
5494 if (dev->l2ad_vdev == vd)
5495 break;
5496 }
5497 mutex_exit(&l2arc_dev_mtx);
5498
5499 return (dev != NULL);
5500}
5501
34dc7c2f
BB
5502/*
5503 * Add a vdev for use by the L2ARC. By this point the spa has already
5504 * validated the vdev and opened it.
5505 */
5506void
9babb374 5507l2arc_add_vdev(spa_t *spa, vdev_t *vd)
34dc7c2f
BB
5508{
5509 l2arc_dev_t *adddev;
5510
b128c09f
BB
5511 ASSERT(!l2arc_vdev_present(vd));
5512
34dc7c2f
BB
5513 /*
5514 * Create a new l2arc device entry.
5515 */
5516 adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
5517 adddev->l2ad_spa = spa;
5518 adddev->l2ad_vdev = vd;
9babb374
BB
5519 adddev->l2ad_start = VDEV_LABEL_START_SIZE;
5520 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
34dc7c2f
BB
5521 adddev->l2ad_hand = adddev->l2ad_start;
5522 adddev->l2ad_evict = adddev->l2ad_start;
5523 adddev->l2ad_first = B_TRUE;
d164b209 5524 adddev->l2ad_writing = B_FALSE;
98f72a53 5525 list_link_init(&adddev->l2ad_node);
34dc7c2f
BB
5526
5527 /*
5528 * This is a list of all ARC buffers that are still valid on the
5529 * device.
5530 */
5531 adddev->l2ad_buflist = kmem_zalloc(sizeof (list_t), KM_SLEEP);
5532 list_create(adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
5533 offsetof(arc_buf_hdr_t, b_l2node));
5534
428870ff 5535 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
34dc7c2f
BB
5536
5537 /*
5538 * Add device to global list
5539 */
5540 mutex_enter(&l2arc_dev_mtx);
5541 list_insert_head(l2arc_dev_list, adddev);
5542 atomic_inc_64(&l2arc_ndev);
5543 mutex_exit(&l2arc_dev_mtx);
5544}
5545
5546/*
5547 * Remove a vdev from the L2ARC.
5548 */
5549void
5550l2arc_remove_vdev(vdev_t *vd)
5551{
5552 l2arc_dev_t *dev, *nextdev, *remdev = NULL;
5553
34dc7c2f
BB
5554 /*
5555 * Find the device by vdev
5556 */
5557 mutex_enter(&l2arc_dev_mtx);
5558 for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
5559 nextdev = list_next(l2arc_dev_list, dev);
5560 if (vd == dev->l2ad_vdev) {
5561 remdev = dev;
5562 break;
5563 }
5564 }
5565 ASSERT(remdev != NULL);
5566
5567 /*
5568 * Remove device from global list
5569 */
5570 list_remove(l2arc_dev_list, remdev);
5571 l2arc_dev_last = NULL; /* may have been invalidated */
b128c09f
BB
5572 atomic_dec_64(&l2arc_ndev);
5573 mutex_exit(&l2arc_dev_mtx);
34dc7c2f
BB
5574
5575 /*
5576 * Clear all buflists and ARC references. L2ARC device flush.
5577 */
5578 l2arc_evict(remdev, 0, B_TRUE);
5579 list_destroy(remdev->l2ad_buflist);
5580 kmem_free(remdev->l2ad_buflist, sizeof (list_t));
5581 kmem_free(remdev, sizeof (l2arc_dev_t));
34dc7c2f
BB
5582}
5583
5584void
b128c09f 5585l2arc_init(void)
34dc7c2f
BB
5586{
5587 l2arc_thread_exit = 0;
5588 l2arc_ndev = 0;
5589 l2arc_writes_sent = 0;
5590 l2arc_writes_done = 0;
5591
5592 mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
5593 cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
5594 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
5595 mutex_init(&l2arc_buflist_mtx, NULL, MUTEX_DEFAULT, NULL);
5596 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
5597
5598 l2arc_dev_list = &L2ARC_dev_list;
5599 l2arc_free_on_write = &L2ARC_free_on_write;
5600 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
5601 offsetof(l2arc_dev_t, l2ad_node));
5602 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
5603 offsetof(l2arc_data_free_t, l2df_list_node));
34dc7c2f
BB
5604}
5605
5606void
b128c09f 5607l2arc_fini(void)
34dc7c2f 5608{
b128c09f
BB
5609 /*
5610 * This is called from dmu_fini(), which is called from spa_fini();
5611 * Because of this, we can assume that all l2arc devices have
5612 * already been removed when the pools themselves were removed.
5613 */
5614
5615 l2arc_do_free_on_write();
34dc7c2f
BB
5616
5617 mutex_destroy(&l2arc_feed_thr_lock);
5618 cv_destroy(&l2arc_feed_thr_cv);
5619 mutex_destroy(&l2arc_dev_mtx);
5620 mutex_destroy(&l2arc_buflist_mtx);
5621 mutex_destroy(&l2arc_free_on_write_mtx);
5622
5623 list_destroy(l2arc_dev_list);
5624 list_destroy(l2arc_free_on_write);
5625}
b128c09f
BB
5626
5627void
5628l2arc_start(void)
5629{
fb5f0bc8 5630 if (!(spa_mode_global & FWRITE))
b128c09f
BB
5631 return;
5632
5633 (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
5634 TS_RUN, minclsyspri);
5635}
5636
5637void
5638l2arc_stop(void)
5639{
fb5f0bc8 5640 if (!(spa_mode_global & FWRITE))
b128c09f
BB
5641 return;
5642
5643 mutex_enter(&l2arc_feed_thr_lock);
5644 cv_signal(&l2arc_feed_thr_cv); /* kick thread out of startup */
5645 l2arc_thread_exit = 1;
5646 while (l2arc_thread_exit != 0)
5647 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
5648 mutex_exit(&l2arc_feed_thr_lock);
5649}
c28b2279
BB
5650
5651#if defined(_KERNEL) && defined(HAVE_SPL)
5652EXPORT_SYMBOL(arc_read);
5653EXPORT_SYMBOL(arc_buf_remove_ref);
e0b0ca98 5654EXPORT_SYMBOL(arc_buf_info);
c28b2279 5655EXPORT_SYMBOL(arc_getbuf_func);
ab26409d
BB
5656EXPORT_SYMBOL(arc_add_prune_callback);
5657EXPORT_SYMBOL(arc_remove_prune_callback);
c28b2279 5658
bce45ec9 5659module_param(zfs_arc_min, ulong, 0644);
c409e464 5660MODULE_PARM_DESC(zfs_arc_min, "Min arc size");
c28b2279 5661
bce45ec9 5662module_param(zfs_arc_max, ulong, 0644);
c409e464 5663MODULE_PARM_DESC(zfs_arc_max, "Max arc size");
c28b2279 5664
bce45ec9 5665module_param(zfs_arc_meta_limit, ulong, 0644);
c28b2279 5666MODULE_PARM_DESC(zfs_arc_meta_limit, "Meta limit for arc size");
6a8f9b6b 5667
bce45ec9 5668module_param(zfs_arc_meta_prune, int, 0644);
ab26409d 5669MODULE_PARM_DESC(zfs_arc_meta_prune, "Bytes of meta data to prune");
c409e464 5670
bce45ec9 5671module_param(zfs_arc_grow_retry, int, 0644);
c409e464
BB
5672MODULE_PARM_DESC(zfs_arc_grow_retry, "Seconds before growing arc size");
5673
89c8cac4
PS
5674module_param(zfs_arc_p_aggressive_disable, int, 0644);
5675MODULE_PARM_DESC(zfs_arc_p_aggressive_disable, "disable aggressive arc_p grow");
5676
62422785
PS
5677module_param(zfs_arc_p_dampener_disable, int, 0644);
5678MODULE_PARM_DESC(zfs_arc_p_dampener_disable, "disable arc_p adapt dampener");
5679
bce45ec9 5680module_param(zfs_arc_shrink_shift, int, 0644);
c409e464
BB
5681MODULE_PARM_DESC(zfs_arc_shrink_shift, "log2(fraction of arc to reclaim)");
5682
1f7c30df
BB
5683module_param(zfs_disable_dup_eviction, int, 0644);
5684MODULE_PARM_DESC(zfs_disable_dup_eviction, "disable duplicate buffer eviction");
5685
0c5493d4
BB
5686module_param(zfs_arc_memory_throttle_disable, int, 0644);
5687MODULE_PARM_DESC(zfs_arc_memory_throttle_disable, "disable memory throttle");
5688
bce45ec9
BB
5689module_param(zfs_arc_min_prefetch_lifespan, int, 0644);
5690MODULE_PARM_DESC(zfs_arc_min_prefetch_lifespan, "Min life of prefetch block");
5691
5692module_param(l2arc_write_max, ulong, 0644);
abd8610c
BB
5693MODULE_PARM_DESC(l2arc_write_max, "Max write bytes per interval");
5694
bce45ec9 5695module_param(l2arc_write_boost, ulong, 0644);
abd8610c
BB
5696MODULE_PARM_DESC(l2arc_write_boost, "Extra write bytes during device warmup");
5697
bce45ec9 5698module_param(l2arc_headroom, ulong, 0644);
abd8610c
BB
5699MODULE_PARM_DESC(l2arc_headroom, "Number of max device writes to precache");
5700
3a17a7a9
SK
5701module_param(l2arc_headroom_boost, ulong, 0644);
5702MODULE_PARM_DESC(l2arc_headroom_boost, "Compressed l2arc_headroom multiplier");
5703
bce45ec9 5704module_param(l2arc_feed_secs, ulong, 0644);
abd8610c
BB
5705MODULE_PARM_DESC(l2arc_feed_secs, "Seconds between L2ARC writing");
5706
bce45ec9 5707module_param(l2arc_feed_min_ms, ulong, 0644);
abd8610c
BB
5708MODULE_PARM_DESC(l2arc_feed_min_ms, "Min feed interval in milliseconds");
5709
bce45ec9 5710module_param(l2arc_noprefetch, int, 0644);
abd8610c
BB
5711MODULE_PARM_DESC(l2arc_noprefetch, "Skip caching prefetched buffers");
5712
3a17a7a9
SK
5713module_param(l2arc_nocompress, int, 0644);
5714MODULE_PARM_DESC(l2arc_nocompress, "Skip compressing L2ARC buffers");
5715
bce45ec9 5716module_param(l2arc_feed_again, int, 0644);
abd8610c
BB
5717MODULE_PARM_DESC(l2arc_feed_again, "Turbo L2ARC warmup");
5718
bce45ec9 5719module_param(l2arc_norw, int, 0644);
abd8610c
BB
5720MODULE_PARM_DESC(l2arc_norw, "No reads during writes");
5721
c28b2279 5722#endif