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