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