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