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