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