]> git.proxmox.com Git - mirror_zfs.git/blob - module/zfs/arc.c
2661bc8a78b073bab8cb457a8d0f58c4189e6009
[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 (c) 2012, Joyent, Inc. All rights reserved.
24 * Copyright (c) 2011, 2015 by Delphix. All rights reserved.
25 * Copyright (c) 2014 by Saso Kiselkov. All rights reserved.
26 * Copyright 2014 Nexenta Systems, Inc. All rights reserved.
27 */
28
29 /*
30 * DVA-based Adjustable Replacement Cache
31 *
32 * While much of the theory of operation used here is
33 * based on the self-tuning, low overhead replacement cache
34 * presented by Megiddo and Modha at FAST 2003, there are some
35 * significant differences:
36 *
37 * 1. The Megiddo and Modha model assumes any page is evictable.
38 * Pages in its cache cannot be "locked" into memory. This makes
39 * the eviction algorithm simple: evict the last page in the list.
40 * This also make the performance characteristics easy to reason
41 * about. Our cache is not so simple. At any given moment, some
42 * subset of the blocks in the cache are un-evictable because we
43 * have handed out a reference to them. Blocks are only evictable
44 * when there are no external references active. This makes
45 * eviction far more problematic: we choose to evict the evictable
46 * blocks that are the "lowest" in the list.
47 *
48 * There are times when it is not possible to evict the requested
49 * space. In these circumstances we are unable to adjust the cache
50 * size. To prevent the cache growing unbounded at these times we
51 * implement a "cache throttle" that slows the flow of new data
52 * into the cache until we can make space available.
53 *
54 * 2. The Megiddo and Modha model assumes a fixed cache size.
55 * Pages are evicted when the cache is full and there is a cache
56 * miss. Our model has a variable sized cache. It grows with
57 * high use, but also tries to react to memory pressure from the
58 * operating system: decreasing its size when system memory is
59 * tight.
60 *
61 * 3. The Megiddo and Modha model assumes a fixed page size. All
62 * elements of the cache are therefore exactly the same size. So
63 * when adjusting the cache size following a cache miss, its simply
64 * a matter of choosing a single page to evict. In our model, we
65 * have variable sized cache blocks (rangeing from 512 bytes to
66 * 128K bytes). We therefore choose a set of blocks to evict to make
67 * space for a cache miss that approximates as closely as possible
68 * the space used by the new block.
69 *
70 * See also: "ARC: A Self-Tuning, Low Overhead Replacement Cache"
71 * by N. Megiddo & D. Modha, FAST 2003
72 */
73
74 /*
75 * The locking model:
76 *
77 * A new reference to a cache buffer can be obtained in two
78 * ways: 1) via a hash table lookup using the DVA as a key,
79 * or 2) via one of the ARC lists. The arc_read() interface
80 * uses method 1, while the internal arc algorithms for
81 * adjusting the cache use method 2. We therefore provide two
82 * types of locks: 1) the hash table lock array, and 2) the
83 * arc list locks.
84 *
85 * Buffers do not have their own mutexes, rather they rely on the
86 * hash table mutexes for the bulk of their protection (i.e. most
87 * fields in the arc_buf_hdr_t are protected by these mutexes).
88 *
89 * buf_hash_find() returns the appropriate mutex (held) when it
90 * locates the requested buffer in the hash table. It returns
91 * NULL for the mutex if the buffer was not in the table.
92 *
93 * buf_hash_remove() expects the appropriate hash mutex to be
94 * already held before it is invoked.
95 *
96 * Each arc state also has a mutex which is used to protect the
97 * buffer list associated with the state. When attempting to
98 * obtain a hash table lock while holding an arc list lock you
99 * must use: mutex_tryenter() to avoid deadlock. Also note that
100 * the active state mutex must be held before the ghost state mutex.
101 *
102 * Arc buffers may have an associated eviction callback function.
103 * This function will be invoked prior to removing the buffer (e.g.
104 * in arc_do_user_evicts()). Note however that the data associated
105 * with the buffer may be evicted prior to the callback. The callback
106 * must be made with *no locks held* (to prevent deadlock). Additionally,
107 * the users of callbacks must ensure that their private data is
108 * protected from simultaneous callbacks from arc_clear_callback()
109 * and arc_do_user_evicts().
110 *
111 * It as also possible to register a callback which is run when the
112 * arc_meta_limit is reached and no buffers can be safely evicted. In
113 * this case the arc user should drop a reference on some arc buffers so
114 * they can be reclaimed and the arc_meta_limit honored. For example,
115 * when using the ZPL each dentry holds a references on a znode. These
116 * dentries must be pruned before the arc buffer holding the znode can
117 * be safely evicted.
118 *
119 * Note that the majority of the performance stats are manipulated
120 * with atomic operations.
121 *
122 * The L2ARC uses the l2ad_mtx on each vdev for the following:
123 *
124 * - L2ARC buflist creation
125 * - L2ARC buflist eviction
126 * - L2ARC write completion, which walks L2ARC buflists
127 * - ARC header destruction, as it removes from L2ARC buflists
128 * - ARC header release, as it removes from L2ARC buflists
129 */
130
131 #include <sys/spa.h>
132 #include <sys/zio.h>
133 #include <sys/zio_compress.h>
134 #include <sys/zfs_context.h>
135 #include <sys/arc.h>
136 #include <sys/refcount.h>
137 #include <sys/vdev.h>
138 #include <sys/vdev_impl.h>
139 #include <sys/dsl_pool.h>
140 #include <sys/multilist.h>
141 #ifdef _KERNEL
142 #include <sys/vmsystm.h>
143 #include <vm/anon.h>
144 #include <sys/fs/swapnode.h>
145 #include <sys/zpl.h>
146 #include <linux/mm_compat.h>
147 #endif
148 #include <sys/callb.h>
149 #include <sys/kstat.h>
150 #include <sys/dmu_tx.h>
151 #include <zfs_fletcher.h>
152 #include <sys/arc_impl.h>
153 #include <sys/trace_arc.h>
154
155 #ifndef _KERNEL
156 /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
157 boolean_t arc_watch = B_FALSE;
158 #endif
159
160 static kmutex_t arc_reclaim_lock;
161 static kcondvar_t arc_reclaim_thread_cv;
162 static boolean_t arc_reclaim_thread_exit;
163 static kcondvar_t arc_reclaim_waiters_cv;
164
165 static kmutex_t arc_user_evicts_lock;
166 static kcondvar_t arc_user_evicts_cv;
167 static boolean_t arc_user_evicts_thread_exit;
168
169 /*
170 * The number of headers to evict in arc_evict_state_impl() before
171 * dropping the sublist lock and evicting from another sublist. A lower
172 * value means we're more likely to evict the "correct" header (i.e. the
173 * oldest header in the arc state), but comes with higher overhead
174 * (i.e. more invocations of arc_evict_state_impl()).
175 */
176 int zfs_arc_evict_batch_limit = 10;
177
178 /*
179 * The number of sublists used for each of the arc state lists. If this
180 * is not set to a suitable value by the user, it will be configured to
181 * the number of CPUs on the system in arc_init().
182 */
183 int zfs_arc_num_sublists_per_state = 0;
184
185 /* number of seconds before growing cache again */
186 static int arc_grow_retry = 5;
187
188 /* shift of arc_c for calculating overflow limit in arc_get_data_buf */
189 int zfs_arc_overflow_shift = 8;
190
191 /* shift of arc_c for calculating both min and max arc_p */
192 static int arc_p_min_shift = 4;
193
194 /* log2(fraction of arc to reclaim) */
195 static int arc_shrink_shift = 7;
196
197 /*
198 * log2(fraction of ARC which must be free to allow growing).
199 * I.e. If there is less than arc_c >> arc_no_grow_shift free memory,
200 * when reading a new block into the ARC, we will evict an equal-sized block
201 * from the ARC.
202 *
203 * This must be less than arc_shrink_shift, so that when we shrink the ARC,
204 * we will still not allow it to grow.
205 */
206 int arc_no_grow_shift = 5;
207
208
209 /*
210 * minimum lifespan of a prefetch block in clock ticks
211 * (initialized in arc_init())
212 */
213 static int arc_min_prefetch_lifespan;
214
215 /*
216 * If this percent of memory is free, don't throttle.
217 */
218 int arc_lotsfree_percent = 10;
219
220 static int arc_dead;
221
222 /*
223 * The arc has filled available memory and has now warmed up.
224 */
225 static boolean_t arc_warm;
226
227 /*
228 * These tunables are for performance analysis.
229 */
230 unsigned long zfs_arc_max = 0;
231 unsigned long zfs_arc_min = 0;
232 unsigned long zfs_arc_meta_limit = 0;
233 unsigned long zfs_arc_meta_min = 0;
234 int zfs_arc_grow_retry = 0;
235 int zfs_arc_shrink_shift = 0;
236 int zfs_arc_p_min_shift = 0;
237 int zfs_disable_dup_eviction = 0;
238 int zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
239
240 /*
241 * These tunables are Linux specific
242 */
243 int zfs_arc_memory_throttle_disable = 1;
244 int zfs_arc_min_prefetch_lifespan = 0;
245 int zfs_arc_p_aggressive_disable = 1;
246 int zfs_arc_p_dampener_disable = 1;
247 int zfs_arc_meta_prune = 10000;
248 int zfs_arc_meta_strategy = ARC_STRATEGY_META_BALANCED;
249 int zfs_arc_meta_adjust_restarts = 4096;
250
251 /* The 6 states: */
252 static arc_state_t ARC_anon;
253 static arc_state_t ARC_mru;
254 static arc_state_t ARC_mru_ghost;
255 static arc_state_t ARC_mfu;
256 static arc_state_t ARC_mfu_ghost;
257 static arc_state_t ARC_l2c_only;
258
259 typedef struct arc_stats {
260 kstat_named_t arcstat_hits;
261 kstat_named_t arcstat_misses;
262 kstat_named_t arcstat_demand_data_hits;
263 kstat_named_t arcstat_demand_data_misses;
264 kstat_named_t arcstat_demand_metadata_hits;
265 kstat_named_t arcstat_demand_metadata_misses;
266 kstat_named_t arcstat_prefetch_data_hits;
267 kstat_named_t arcstat_prefetch_data_misses;
268 kstat_named_t arcstat_prefetch_metadata_hits;
269 kstat_named_t arcstat_prefetch_metadata_misses;
270 kstat_named_t arcstat_mru_hits;
271 kstat_named_t arcstat_mru_ghost_hits;
272 kstat_named_t arcstat_mfu_hits;
273 kstat_named_t arcstat_mfu_ghost_hits;
274 kstat_named_t arcstat_deleted;
275 /*
276 * Number of buffers that could not be evicted because the hash lock
277 * was held by another thread. The lock may not necessarily be held
278 * by something using the same buffer, since hash locks are shared
279 * by multiple buffers.
280 */
281 kstat_named_t arcstat_mutex_miss;
282 /*
283 * Number of buffers skipped because they have I/O in progress, are
284 * indrect prefetch buffers that have not lived long enough, or are
285 * not from the spa we're trying to evict from.
286 */
287 kstat_named_t arcstat_evict_skip;
288 /*
289 * Number of times arc_evict_state() was unable to evict enough
290 * buffers to reach its target amount.
291 */
292 kstat_named_t arcstat_evict_not_enough;
293 kstat_named_t arcstat_evict_l2_cached;
294 kstat_named_t arcstat_evict_l2_eligible;
295 kstat_named_t arcstat_evict_l2_ineligible;
296 kstat_named_t arcstat_evict_l2_skip;
297 kstat_named_t arcstat_hash_elements;
298 kstat_named_t arcstat_hash_elements_max;
299 kstat_named_t arcstat_hash_collisions;
300 kstat_named_t arcstat_hash_chains;
301 kstat_named_t arcstat_hash_chain_max;
302 kstat_named_t arcstat_p;
303 kstat_named_t arcstat_c;
304 kstat_named_t arcstat_c_min;
305 kstat_named_t arcstat_c_max;
306 kstat_named_t arcstat_size;
307 /*
308 * Number of bytes consumed by internal ARC structures necessary
309 * for tracking purposes; these structures are not actually
310 * backed by ARC buffers. This includes arc_buf_hdr_t structures
311 * (allocated via arc_buf_hdr_t_full and arc_buf_hdr_t_l2only
312 * caches), and arc_buf_t structures (allocated via arc_buf_t
313 * cache).
314 */
315 kstat_named_t arcstat_hdr_size;
316 /*
317 * Number of bytes consumed by ARC buffers of type equal to
318 * ARC_BUFC_DATA. This is generally consumed by buffers backing
319 * on disk user data (e.g. plain file contents).
320 */
321 kstat_named_t arcstat_data_size;
322 /*
323 * Number of bytes consumed by ARC buffers of type equal to
324 * ARC_BUFC_METADATA. This is generally consumed by buffers
325 * backing on disk data that is used for internal ZFS
326 * structures (e.g. ZAP, dnode, indirect blocks, etc).
327 */
328 kstat_named_t arcstat_metadata_size;
329 /*
330 * Number of bytes consumed by various buffers and structures
331 * not actually backed with ARC buffers. This includes bonus
332 * buffers (allocated directly via zio_buf_* functions),
333 * dmu_buf_impl_t structures (allocated via dmu_buf_impl_t
334 * cache), and dnode_t structures (allocated via dnode_t cache).
335 */
336 kstat_named_t arcstat_other_size;
337 /*
338 * Total number of bytes consumed by ARC buffers residing in the
339 * arc_anon state. This includes *all* buffers in the arc_anon
340 * state; e.g. data, metadata, evictable, and unevictable buffers
341 * are all included in this value.
342 */
343 kstat_named_t arcstat_anon_size;
344 /*
345 * Number of bytes consumed by ARC buffers that meet the
346 * following criteria: backing buffers of type ARC_BUFC_DATA,
347 * residing in the arc_anon state, and are eligible for eviction
348 * (e.g. have no outstanding holds on the buffer).
349 */
350 kstat_named_t arcstat_anon_evictable_data;
351 /*
352 * Number of bytes consumed by ARC buffers that meet the
353 * following criteria: backing buffers of type ARC_BUFC_METADATA,
354 * residing in the arc_anon state, and are eligible for eviction
355 * (e.g. have no outstanding holds on the buffer).
356 */
357 kstat_named_t arcstat_anon_evictable_metadata;
358 /*
359 * Total number of bytes consumed by ARC buffers residing in the
360 * arc_mru state. This includes *all* buffers in the arc_mru
361 * state; e.g. data, metadata, evictable, and unevictable buffers
362 * are all included in this value.
363 */
364 kstat_named_t arcstat_mru_size;
365 /*
366 * Number of bytes consumed by ARC buffers that meet the
367 * following criteria: backing buffers of type ARC_BUFC_DATA,
368 * residing in the arc_mru state, and are eligible for eviction
369 * (e.g. have no outstanding holds on the buffer).
370 */
371 kstat_named_t arcstat_mru_evictable_data;
372 /*
373 * Number of bytes consumed by ARC buffers that meet the
374 * following criteria: backing buffers of type ARC_BUFC_METADATA,
375 * residing in the arc_mru state, and are eligible for eviction
376 * (e.g. have no outstanding holds on the buffer).
377 */
378 kstat_named_t arcstat_mru_evictable_metadata;
379 /*
380 * Total number of bytes that *would have been* consumed by ARC
381 * buffers in the arc_mru_ghost state. The key thing to note
382 * here, is the fact that this size doesn't actually indicate
383 * RAM consumption. The ghost lists only consist of headers and
384 * don't actually have ARC buffers linked off of these headers.
385 * Thus, *if* the headers had associated ARC buffers, these
386 * buffers *would have* consumed this number of bytes.
387 */
388 kstat_named_t arcstat_mru_ghost_size;
389 /*
390 * Number of bytes that *would have been* consumed by ARC
391 * buffers that are eligible for eviction, of type
392 * ARC_BUFC_DATA, and linked off the arc_mru_ghost state.
393 */
394 kstat_named_t arcstat_mru_ghost_evictable_data;
395 /*
396 * Number of bytes that *would have been* consumed by ARC
397 * buffers that are eligible for eviction, of type
398 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
399 */
400 kstat_named_t arcstat_mru_ghost_evictable_metadata;
401 /*
402 * Total number of bytes consumed by ARC buffers residing in the
403 * arc_mfu state. This includes *all* buffers in the arc_mfu
404 * state; e.g. data, metadata, evictable, and unevictable buffers
405 * are all included in this value.
406 */
407 kstat_named_t arcstat_mfu_size;
408 /*
409 * Number of bytes consumed by ARC buffers that are eligible for
410 * eviction, of type ARC_BUFC_DATA, and reside in the arc_mfu
411 * state.
412 */
413 kstat_named_t arcstat_mfu_evictable_data;
414 /*
415 * Number of bytes consumed by ARC buffers that are eligible for
416 * eviction, of type ARC_BUFC_METADATA, and reside in the
417 * arc_mfu state.
418 */
419 kstat_named_t arcstat_mfu_evictable_metadata;
420 /*
421 * Total number of bytes that *would have been* consumed by ARC
422 * buffers in the arc_mfu_ghost state. See the comment above
423 * arcstat_mru_ghost_size for more details.
424 */
425 kstat_named_t arcstat_mfu_ghost_size;
426 /*
427 * Number of bytes that *would have been* consumed by ARC
428 * buffers that are eligible for eviction, of type
429 * ARC_BUFC_DATA, and linked off the arc_mfu_ghost state.
430 */
431 kstat_named_t arcstat_mfu_ghost_evictable_data;
432 /*
433 * Number of bytes that *would have been* consumed by ARC
434 * buffers that are eligible for eviction, of type
435 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
436 */
437 kstat_named_t arcstat_mfu_ghost_evictable_metadata;
438 kstat_named_t arcstat_l2_hits;
439 kstat_named_t arcstat_l2_misses;
440 kstat_named_t arcstat_l2_feeds;
441 kstat_named_t arcstat_l2_rw_clash;
442 kstat_named_t arcstat_l2_read_bytes;
443 kstat_named_t arcstat_l2_write_bytes;
444 kstat_named_t arcstat_l2_writes_sent;
445 kstat_named_t arcstat_l2_writes_done;
446 kstat_named_t arcstat_l2_writes_error;
447 kstat_named_t arcstat_l2_writes_lock_retry;
448 kstat_named_t arcstat_l2_evict_lock_retry;
449 kstat_named_t arcstat_l2_evict_reading;
450 kstat_named_t arcstat_l2_evict_l1cached;
451 kstat_named_t arcstat_l2_free_on_write;
452 kstat_named_t arcstat_l2_cdata_free_on_write;
453 kstat_named_t arcstat_l2_abort_lowmem;
454 kstat_named_t arcstat_l2_cksum_bad;
455 kstat_named_t arcstat_l2_io_error;
456 kstat_named_t arcstat_l2_size;
457 kstat_named_t arcstat_l2_asize;
458 kstat_named_t arcstat_l2_hdr_size;
459 kstat_named_t arcstat_l2_compress_successes;
460 kstat_named_t arcstat_l2_compress_zeros;
461 kstat_named_t arcstat_l2_compress_failures;
462 kstat_named_t arcstat_memory_throttle_count;
463 kstat_named_t arcstat_duplicate_buffers;
464 kstat_named_t arcstat_duplicate_buffers_size;
465 kstat_named_t arcstat_duplicate_reads;
466 kstat_named_t arcstat_memory_direct_count;
467 kstat_named_t arcstat_memory_indirect_count;
468 kstat_named_t arcstat_no_grow;
469 kstat_named_t arcstat_tempreserve;
470 kstat_named_t arcstat_loaned_bytes;
471 kstat_named_t arcstat_prune;
472 kstat_named_t arcstat_meta_used;
473 kstat_named_t arcstat_meta_limit;
474 kstat_named_t arcstat_meta_max;
475 kstat_named_t arcstat_meta_min;
476 } arc_stats_t;
477
478 static arc_stats_t arc_stats = {
479 { "hits", KSTAT_DATA_UINT64 },
480 { "misses", KSTAT_DATA_UINT64 },
481 { "demand_data_hits", KSTAT_DATA_UINT64 },
482 { "demand_data_misses", KSTAT_DATA_UINT64 },
483 { "demand_metadata_hits", KSTAT_DATA_UINT64 },
484 { "demand_metadata_misses", KSTAT_DATA_UINT64 },
485 { "prefetch_data_hits", KSTAT_DATA_UINT64 },
486 { "prefetch_data_misses", KSTAT_DATA_UINT64 },
487 { "prefetch_metadata_hits", KSTAT_DATA_UINT64 },
488 { "prefetch_metadata_misses", KSTAT_DATA_UINT64 },
489 { "mru_hits", KSTAT_DATA_UINT64 },
490 { "mru_ghost_hits", KSTAT_DATA_UINT64 },
491 { "mfu_hits", KSTAT_DATA_UINT64 },
492 { "mfu_ghost_hits", KSTAT_DATA_UINT64 },
493 { "deleted", KSTAT_DATA_UINT64 },
494 { "mutex_miss", KSTAT_DATA_UINT64 },
495 { "evict_skip", KSTAT_DATA_UINT64 },
496 { "evict_not_enough", KSTAT_DATA_UINT64 },
497 { "evict_l2_cached", KSTAT_DATA_UINT64 },
498 { "evict_l2_eligible", KSTAT_DATA_UINT64 },
499 { "evict_l2_ineligible", KSTAT_DATA_UINT64 },
500 { "evict_l2_skip", KSTAT_DATA_UINT64 },
501 { "hash_elements", KSTAT_DATA_UINT64 },
502 { "hash_elements_max", KSTAT_DATA_UINT64 },
503 { "hash_collisions", KSTAT_DATA_UINT64 },
504 { "hash_chains", KSTAT_DATA_UINT64 },
505 { "hash_chain_max", KSTAT_DATA_UINT64 },
506 { "p", KSTAT_DATA_UINT64 },
507 { "c", KSTAT_DATA_UINT64 },
508 { "c_min", KSTAT_DATA_UINT64 },
509 { "c_max", KSTAT_DATA_UINT64 },
510 { "size", KSTAT_DATA_UINT64 },
511 { "hdr_size", KSTAT_DATA_UINT64 },
512 { "data_size", KSTAT_DATA_UINT64 },
513 { "metadata_size", KSTAT_DATA_UINT64 },
514 { "other_size", KSTAT_DATA_UINT64 },
515 { "anon_size", KSTAT_DATA_UINT64 },
516 { "anon_evictable_data", KSTAT_DATA_UINT64 },
517 { "anon_evictable_metadata", KSTAT_DATA_UINT64 },
518 { "mru_size", KSTAT_DATA_UINT64 },
519 { "mru_evictable_data", KSTAT_DATA_UINT64 },
520 { "mru_evictable_metadata", KSTAT_DATA_UINT64 },
521 { "mru_ghost_size", KSTAT_DATA_UINT64 },
522 { "mru_ghost_evictable_data", KSTAT_DATA_UINT64 },
523 { "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
524 { "mfu_size", KSTAT_DATA_UINT64 },
525 { "mfu_evictable_data", KSTAT_DATA_UINT64 },
526 { "mfu_evictable_metadata", KSTAT_DATA_UINT64 },
527 { "mfu_ghost_size", KSTAT_DATA_UINT64 },
528 { "mfu_ghost_evictable_data", KSTAT_DATA_UINT64 },
529 { "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
530 { "l2_hits", KSTAT_DATA_UINT64 },
531 { "l2_misses", KSTAT_DATA_UINT64 },
532 { "l2_feeds", KSTAT_DATA_UINT64 },
533 { "l2_rw_clash", KSTAT_DATA_UINT64 },
534 { "l2_read_bytes", KSTAT_DATA_UINT64 },
535 { "l2_write_bytes", KSTAT_DATA_UINT64 },
536 { "l2_writes_sent", KSTAT_DATA_UINT64 },
537 { "l2_writes_done", KSTAT_DATA_UINT64 },
538 { "l2_writes_error", KSTAT_DATA_UINT64 },
539 { "l2_writes_lock_retry", KSTAT_DATA_UINT64 },
540 { "l2_evict_lock_retry", KSTAT_DATA_UINT64 },
541 { "l2_evict_reading", KSTAT_DATA_UINT64 },
542 { "l2_evict_l1cached", KSTAT_DATA_UINT64 },
543 { "l2_free_on_write", KSTAT_DATA_UINT64 },
544 { "l2_cdata_free_on_write", KSTAT_DATA_UINT64 },
545 { "l2_abort_lowmem", KSTAT_DATA_UINT64 },
546 { "l2_cksum_bad", KSTAT_DATA_UINT64 },
547 { "l2_io_error", KSTAT_DATA_UINT64 },
548 { "l2_size", KSTAT_DATA_UINT64 },
549 { "l2_asize", KSTAT_DATA_UINT64 },
550 { "l2_hdr_size", KSTAT_DATA_UINT64 },
551 { "l2_compress_successes", KSTAT_DATA_UINT64 },
552 { "l2_compress_zeros", KSTAT_DATA_UINT64 },
553 { "l2_compress_failures", KSTAT_DATA_UINT64 },
554 { "memory_throttle_count", KSTAT_DATA_UINT64 },
555 { "duplicate_buffers", KSTAT_DATA_UINT64 },
556 { "duplicate_buffers_size", KSTAT_DATA_UINT64 },
557 { "duplicate_reads", KSTAT_DATA_UINT64 },
558 { "memory_direct_count", KSTAT_DATA_UINT64 },
559 { "memory_indirect_count", KSTAT_DATA_UINT64 },
560 { "arc_no_grow", KSTAT_DATA_UINT64 },
561 { "arc_tempreserve", KSTAT_DATA_UINT64 },
562 { "arc_loaned_bytes", KSTAT_DATA_UINT64 },
563 { "arc_prune", KSTAT_DATA_UINT64 },
564 { "arc_meta_used", KSTAT_DATA_UINT64 },
565 { "arc_meta_limit", KSTAT_DATA_UINT64 },
566 { "arc_meta_max", KSTAT_DATA_UINT64 },
567 { "arc_meta_min", KSTAT_DATA_UINT64 }
568 };
569
570 #define ARCSTAT(stat) (arc_stats.stat.value.ui64)
571
572 #define ARCSTAT_INCR(stat, val) \
573 atomic_add_64(&arc_stats.stat.value.ui64, (val))
574
575 #define ARCSTAT_BUMP(stat) ARCSTAT_INCR(stat, 1)
576 #define ARCSTAT_BUMPDOWN(stat) ARCSTAT_INCR(stat, -1)
577
578 #define ARCSTAT_MAX(stat, val) { \
579 uint64_t m; \
580 while ((val) > (m = arc_stats.stat.value.ui64) && \
581 (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val)))) \
582 continue; \
583 }
584
585 #define ARCSTAT_MAXSTAT(stat) \
586 ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
587
588 /*
589 * We define a macro to allow ARC hits/misses to be easily broken down by
590 * two separate conditions, giving a total of four different subtypes for
591 * each of hits and misses (so eight statistics total).
592 */
593 #define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
594 if (cond1) { \
595 if (cond2) { \
596 ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
597 } else { \
598 ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
599 } \
600 } else { \
601 if (cond2) { \
602 ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
603 } else { \
604 ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
605 } \
606 }
607
608 kstat_t *arc_ksp;
609 static arc_state_t *arc_anon;
610 static arc_state_t *arc_mru;
611 static arc_state_t *arc_mru_ghost;
612 static arc_state_t *arc_mfu;
613 static arc_state_t *arc_mfu_ghost;
614 static arc_state_t *arc_l2c_only;
615
616 /*
617 * There are several ARC variables that are critical to export as kstats --
618 * but we don't want to have to grovel around in the kstat whenever we wish to
619 * manipulate them. For these variables, we therefore define them to be in
620 * terms of the statistic variable. This assures that we are not introducing
621 * the possibility of inconsistency by having shadow copies of the variables,
622 * while still allowing the code to be readable.
623 */
624 #define arc_size ARCSTAT(arcstat_size) /* actual total arc size */
625 #define arc_p ARCSTAT(arcstat_p) /* target size of MRU */
626 #define arc_c ARCSTAT(arcstat_c) /* target size of cache */
627 #define arc_c_min ARCSTAT(arcstat_c_min) /* min target cache size */
628 #define arc_c_max ARCSTAT(arcstat_c_max) /* max target cache size */
629 #define arc_no_grow ARCSTAT(arcstat_no_grow)
630 #define arc_tempreserve ARCSTAT(arcstat_tempreserve)
631 #define arc_loaned_bytes ARCSTAT(arcstat_loaned_bytes)
632 #define arc_meta_limit ARCSTAT(arcstat_meta_limit) /* max size for metadata */
633 #define arc_meta_min ARCSTAT(arcstat_meta_min) /* min size for metadata */
634 #define arc_meta_used ARCSTAT(arcstat_meta_used) /* size of metadata */
635 #define arc_meta_max ARCSTAT(arcstat_meta_max) /* max size of metadata */
636
637 #define L2ARC_IS_VALID_COMPRESS(_c_) \
638 ((_c_) == ZIO_COMPRESS_LZ4 || (_c_) == ZIO_COMPRESS_EMPTY)
639
640 static list_t arc_prune_list;
641 static kmutex_t arc_prune_mtx;
642 static taskq_t *arc_prune_taskq;
643 static arc_buf_t *arc_eviction_list;
644 static arc_buf_hdr_t arc_eviction_hdr;
645
646 #define GHOST_STATE(state) \
647 ((state) == arc_mru_ghost || (state) == arc_mfu_ghost || \
648 (state) == arc_l2c_only)
649
650 #define HDR_IN_HASH_TABLE(hdr) ((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
651 #define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
652 #define HDR_IO_ERROR(hdr) ((hdr)->b_flags & ARC_FLAG_IO_ERROR)
653 #define HDR_PREFETCH(hdr) ((hdr)->b_flags & ARC_FLAG_PREFETCH)
654 #define HDR_FREED_IN_READ(hdr) ((hdr)->b_flags & ARC_FLAG_FREED_IN_READ)
655 #define HDR_BUF_AVAILABLE(hdr) ((hdr)->b_flags & ARC_FLAG_BUF_AVAILABLE)
656
657 #define HDR_L2CACHE(hdr) ((hdr)->b_flags & ARC_FLAG_L2CACHE)
658 #define HDR_L2COMPRESS(hdr) ((hdr)->b_flags & ARC_FLAG_L2COMPRESS)
659 #define HDR_L2_READING(hdr) \
660 (((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) && \
661 ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
662 #define HDR_L2_WRITING(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITING)
663 #define HDR_L2_EVICTED(hdr) ((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
664 #define HDR_L2_WRITE_HEAD(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
665
666 #define HDR_ISTYPE_METADATA(hdr) \
667 ((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
668 #define HDR_ISTYPE_DATA(hdr) (!HDR_ISTYPE_METADATA(hdr))
669
670 #define HDR_HAS_L1HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
671 #define HDR_HAS_L2HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
672
673 /* For storing compression mode in b_flags */
674 #define HDR_COMPRESS_OFFSET 24
675 #define HDR_COMPRESS_NBITS 7
676
677 #define HDR_GET_COMPRESS(hdr) ((enum zio_compress)BF32_GET(hdr->b_flags, \
678 HDR_COMPRESS_OFFSET, HDR_COMPRESS_NBITS))
679 #define HDR_SET_COMPRESS(hdr, cmp) BF32_SET(hdr->b_flags, \
680 HDR_COMPRESS_OFFSET, HDR_COMPRESS_NBITS, (cmp))
681
682 /*
683 * Other sizes
684 */
685
686 #define HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
687 #define HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
688
689 /*
690 * Hash table routines
691 */
692
693 #define HT_LOCK_ALIGN 64
694 #define HT_LOCK_PAD (P2NPHASE(sizeof (kmutex_t), (HT_LOCK_ALIGN)))
695
696 struct ht_lock {
697 kmutex_t ht_lock;
698 #ifdef _KERNEL
699 unsigned char pad[HT_LOCK_PAD];
700 #endif
701 };
702
703 #define BUF_LOCKS 8192
704 typedef struct buf_hash_table {
705 uint64_t ht_mask;
706 arc_buf_hdr_t **ht_table;
707 struct ht_lock ht_locks[BUF_LOCKS];
708 } buf_hash_table_t;
709
710 static buf_hash_table_t buf_hash_table;
711
712 #define BUF_HASH_INDEX(spa, dva, birth) \
713 (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
714 #define BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
715 #define BUF_HASH_LOCK(idx) (&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
716 #define HDR_LOCK(hdr) \
717 (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
718
719 uint64_t zfs_crc64_table[256];
720
721 /*
722 * Level 2 ARC
723 */
724
725 #define L2ARC_WRITE_SIZE (8 * 1024 * 1024) /* initial write max */
726 #define L2ARC_HEADROOM 2 /* num of writes */
727 /*
728 * If we discover during ARC scan any buffers to be compressed, we boost
729 * our headroom for the next scanning cycle by this percentage multiple.
730 */
731 #define L2ARC_HEADROOM_BOOST 200
732 #define L2ARC_FEED_SECS 1 /* caching interval secs */
733 #define L2ARC_FEED_MIN_MS 200 /* min caching interval ms */
734
735 /*
736 * Used to distinguish headers that are being process by
737 * l2arc_write_buffers(), but have yet to be assigned to a l2arc disk
738 * address. This can happen when the header is added to the l2arc's list
739 * of buffers to write in the first stage of l2arc_write_buffers(), but
740 * has not yet been written out which happens in the second stage of
741 * l2arc_write_buffers().
742 */
743 #define L2ARC_ADDR_UNSET ((uint64_t)(-1))
744
745 #define l2arc_writes_sent ARCSTAT(arcstat_l2_writes_sent)
746 #define l2arc_writes_done ARCSTAT(arcstat_l2_writes_done)
747
748 /* L2ARC Performance Tunables */
749 unsigned long l2arc_write_max = L2ARC_WRITE_SIZE; /* def max write size */
750 unsigned long l2arc_write_boost = L2ARC_WRITE_SIZE; /* extra warmup write */
751 unsigned long l2arc_headroom = L2ARC_HEADROOM; /* # of dev writes */
752 unsigned long l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
753 unsigned long l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
754 unsigned long l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval msecs */
755 int l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
756 int l2arc_nocompress = B_FALSE; /* don't compress bufs */
757 int l2arc_feed_again = B_TRUE; /* turbo warmup */
758 int l2arc_norw = B_FALSE; /* no reads during writes */
759
760 /*
761 * L2ARC Internals
762 */
763 static list_t L2ARC_dev_list; /* device list */
764 static list_t *l2arc_dev_list; /* device list pointer */
765 static kmutex_t l2arc_dev_mtx; /* device list mutex */
766 static l2arc_dev_t *l2arc_dev_last; /* last device used */
767 static list_t L2ARC_free_on_write; /* free after write buf list */
768 static list_t *l2arc_free_on_write; /* free after write list ptr */
769 static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
770 static uint64_t l2arc_ndev; /* number of devices */
771
772 typedef struct l2arc_read_callback {
773 arc_buf_t *l2rcb_buf; /* read buffer */
774 spa_t *l2rcb_spa; /* spa */
775 blkptr_t l2rcb_bp; /* original blkptr */
776 zbookmark_phys_t l2rcb_zb; /* original bookmark */
777 int l2rcb_flags; /* original flags */
778 enum zio_compress l2rcb_compress; /* applied compress */
779 } l2arc_read_callback_t;
780
781 typedef struct l2arc_data_free {
782 /* protected by l2arc_free_on_write_mtx */
783 void *l2df_data;
784 size_t l2df_size;
785 void (*l2df_func)(void *, size_t);
786 list_node_t l2df_list_node;
787 } l2arc_data_free_t;
788
789 static kmutex_t l2arc_feed_thr_lock;
790 static kcondvar_t l2arc_feed_thr_cv;
791 static uint8_t l2arc_thread_exit;
792
793 static void arc_get_data_buf(arc_buf_t *);
794 static void arc_access(arc_buf_hdr_t *, kmutex_t *);
795 static boolean_t arc_is_overflowing(void);
796 static void arc_buf_watch(arc_buf_t *);
797 static void arc_tuning_update(void);
798
799 static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
800 static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
801
802 static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
803 static void l2arc_read_done(zio_t *);
804
805 static boolean_t l2arc_compress_buf(arc_buf_hdr_t *);
806 static void l2arc_decompress_zio(zio_t *, arc_buf_hdr_t *, enum zio_compress);
807 static void l2arc_release_cdata_buf(arc_buf_hdr_t *);
808
809 static uint64_t
810 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
811 {
812 uint8_t *vdva = (uint8_t *)dva;
813 uint64_t crc = -1ULL;
814 int i;
815
816 ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
817
818 for (i = 0; i < sizeof (dva_t); i++)
819 crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
820
821 crc ^= (spa>>8) ^ birth;
822
823 return (crc);
824 }
825
826 #define BUF_EMPTY(buf) \
827 ((buf)->b_dva.dva_word[0] == 0 && \
828 (buf)->b_dva.dva_word[1] == 0)
829
830 #define BUF_EQUAL(spa, dva, birth, buf) \
831 ((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
832 ((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
833 ((buf)->b_birth == birth) && ((buf)->b_spa == spa)
834
835 static void
836 buf_discard_identity(arc_buf_hdr_t *hdr)
837 {
838 hdr->b_dva.dva_word[0] = 0;
839 hdr->b_dva.dva_word[1] = 0;
840 hdr->b_birth = 0;
841 }
842
843 static arc_buf_hdr_t *
844 buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
845 {
846 const dva_t *dva = BP_IDENTITY(bp);
847 uint64_t birth = BP_PHYSICAL_BIRTH(bp);
848 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
849 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
850 arc_buf_hdr_t *hdr;
851
852 mutex_enter(hash_lock);
853 for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
854 hdr = hdr->b_hash_next) {
855 if (BUF_EQUAL(spa, dva, birth, hdr)) {
856 *lockp = hash_lock;
857 return (hdr);
858 }
859 }
860 mutex_exit(hash_lock);
861 *lockp = NULL;
862 return (NULL);
863 }
864
865 /*
866 * Insert an entry into the hash table. If there is already an element
867 * equal to elem in the hash table, then the already existing element
868 * will be returned and the new element will not be inserted.
869 * Otherwise returns NULL.
870 * If lockp == NULL, the caller is assumed to already hold the hash lock.
871 */
872 static arc_buf_hdr_t *
873 buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
874 {
875 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
876 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
877 arc_buf_hdr_t *fhdr;
878 uint32_t i;
879
880 ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
881 ASSERT(hdr->b_birth != 0);
882 ASSERT(!HDR_IN_HASH_TABLE(hdr));
883
884 if (lockp != NULL) {
885 *lockp = hash_lock;
886 mutex_enter(hash_lock);
887 } else {
888 ASSERT(MUTEX_HELD(hash_lock));
889 }
890
891 for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
892 fhdr = fhdr->b_hash_next, i++) {
893 if (BUF_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
894 return (fhdr);
895 }
896
897 hdr->b_hash_next = buf_hash_table.ht_table[idx];
898 buf_hash_table.ht_table[idx] = hdr;
899 hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
900
901 /* collect some hash table performance data */
902 if (i > 0) {
903 ARCSTAT_BUMP(arcstat_hash_collisions);
904 if (i == 1)
905 ARCSTAT_BUMP(arcstat_hash_chains);
906
907 ARCSTAT_MAX(arcstat_hash_chain_max, i);
908 }
909
910 ARCSTAT_BUMP(arcstat_hash_elements);
911 ARCSTAT_MAXSTAT(arcstat_hash_elements);
912
913 return (NULL);
914 }
915
916 static void
917 buf_hash_remove(arc_buf_hdr_t *hdr)
918 {
919 arc_buf_hdr_t *fhdr, **hdrp;
920 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
921
922 ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
923 ASSERT(HDR_IN_HASH_TABLE(hdr));
924
925 hdrp = &buf_hash_table.ht_table[idx];
926 while ((fhdr = *hdrp) != hdr) {
927 ASSERT(fhdr != NULL);
928 hdrp = &fhdr->b_hash_next;
929 }
930 *hdrp = hdr->b_hash_next;
931 hdr->b_hash_next = NULL;
932 hdr->b_flags &= ~ARC_FLAG_IN_HASH_TABLE;
933
934 /* collect some hash table performance data */
935 ARCSTAT_BUMPDOWN(arcstat_hash_elements);
936
937 if (buf_hash_table.ht_table[idx] &&
938 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
939 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
940 }
941
942 /*
943 * Global data structures and functions for the buf kmem cache.
944 */
945 static kmem_cache_t *hdr_full_cache;
946 static kmem_cache_t *hdr_l2only_cache;
947 static kmem_cache_t *buf_cache;
948
949 static void
950 buf_fini(void)
951 {
952 int i;
953
954 #if defined(_KERNEL) && defined(HAVE_SPL)
955 /*
956 * Large allocations which do not require contiguous pages
957 * should be using vmem_free() in the linux kernel\
958 */
959 vmem_free(buf_hash_table.ht_table,
960 (buf_hash_table.ht_mask + 1) * sizeof (void *));
961 #else
962 kmem_free(buf_hash_table.ht_table,
963 (buf_hash_table.ht_mask + 1) * sizeof (void *));
964 #endif
965 for (i = 0; i < BUF_LOCKS; i++)
966 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
967 kmem_cache_destroy(hdr_full_cache);
968 kmem_cache_destroy(hdr_l2only_cache);
969 kmem_cache_destroy(buf_cache);
970 }
971
972 /*
973 * Constructor callback - called when the cache is empty
974 * and a new buf is requested.
975 */
976 /* ARGSUSED */
977 static int
978 hdr_full_cons(void *vbuf, void *unused, int kmflag)
979 {
980 arc_buf_hdr_t *hdr = vbuf;
981
982 bzero(hdr, HDR_FULL_SIZE);
983 cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
984 refcount_create(&hdr->b_l1hdr.b_refcnt);
985 mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
986 list_link_init(&hdr->b_l1hdr.b_arc_node);
987 list_link_init(&hdr->b_l2hdr.b_l2node);
988 multilist_link_init(&hdr->b_l1hdr.b_arc_node);
989 arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
990
991 return (0);
992 }
993
994 /* ARGSUSED */
995 static int
996 hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
997 {
998 arc_buf_hdr_t *hdr = vbuf;
999
1000 bzero(hdr, HDR_L2ONLY_SIZE);
1001 arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1002
1003 return (0);
1004 }
1005
1006 /* ARGSUSED */
1007 static int
1008 buf_cons(void *vbuf, void *unused, int kmflag)
1009 {
1010 arc_buf_t *buf = vbuf;
1011
1012 bzero(buf, sizeof (arc_buf_t));
1013 mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1014 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1015
1016 return (0);
1017 }
1018
1019 /*
1020 * Destructor callback - called when a cached buf is
1021 * no longer required.
1022 */
1023 /* ARGSUSED */
1024 static void
1025 hdr_full_dest(void *vbuf, void *unused)
1026 {
1027 arc_buf_hdr_t *hdr = vbuf;
1028
1029 ASSERT(BUF_EMPTY(hdr));
1030 cv_destroy(&hdr->b_l1hdr.b_cv);
1031 refcount_destroy(&hdr->b_l1hdr.b_refcnt);
1032 mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1033 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1034 arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1035 }
1036
1037 /* ARGSUSED */
1038 static void
1039 hdr_l2only_dest(void *vbuf, void *unused)
1040 {
1041 ASSERTV(arc_buf_hdr_t *hdr = vbuf);
1042
1043 ASSERT(BUF_EMPTY(hdr));
1044 arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1045 }
1046
1047 /* ARGSUSED */
1048 static void
1049 buf_dest(void *vbuf, void *unused)
1050 {
1051 arc_buf_t *buf = vbuf;
1052
1053 mutex_destroy(&buf->b_evict_lock);
1054 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1055 }
1056
1057 static void
1058 buf_init(void)
1059 {
1060 uint64_t *ct;
1061 uint64_t hsize = 1ULL << 12;
1062 int i, j;
1063
1064 /*
1065 * The hash table is big enough to fill all of physical memory
1066 * with an average block size of zfs_arc_average_blocksize (default 8K).
1067 * By default, the table will take up
1068 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1069 */
1070 while (hsize * zfs_arc_average_blocksize < physmem * PAGESIZE)
1071 hsize <<= 1;
1072 retry:
1073 buf_hash_table.ht_mask = hsize - 1;
1074 #if defined(_KERNEL) && defined(HAVE_SPL)
1075 /*
1076 * Large allocations which do not require contiguous pages
1077 * should be using vmem_alloc() in the linux kernel
1078 */
1079 buf_hash_table.ht_table =
1080 vmem_zalloc(hsize * sizeof (void*), KM_SLEEP);
1081 #else
1082 buf_hash_table.ht_table =
1083 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1084 #endif
1085 if (buf_hash_table.ht_table == NULL) {
1086 ASSERT(hsize > (1ULL << 8));
1087 hsize >>= 1;
1088 goto retry;
1089 }
1090
1091 hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
1092 0, hdr_full_cons, hdr_full_dest, NULL, NULL, NULL, 0);
1093 hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
1094 HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, NULL,
1095 NULL, NULL, 0);
1096 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1097 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1098
1099 for (i = 0; i < 256; i++)
1100 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1101 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1102
1103 for (i = 0; i < BUF_LOCKS; i++) {
1104 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1105 NULL, MUTEX_DEFAULT, NULL);
1106 }
1107 }
1108
1109 /*
1110 * Transition between the two allocation states for the arc_buf_hdr struct.
1111 * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
1112 * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
1113 * version is used when a cache buffer is only in the L2ARC in order to reduce
1114 * memory usage.
1115 */
1116 static arc_buf_hdr_t *
1117 arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
1118 {
1119 arc_buf_hdr_t *nhdr;
1120 l2arc_dev_t *dev;
1121
1122 ASSERT(HDR_HAS_L2HDR(hdr));
1123 ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
1124 (old == hdr_l2only_cache && new == hdr_full_cache));
1125
1126 dev = hdr->b_l2hdr.b_dev;
1127 nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
1128
1129 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
1130 buf_hash_remove(hdr);
1131
1132 bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
1133
1134 if (new == hdr_full_cache) {
1135 nhdr->b_flags |= ARC_FLAG_HAS_L1HDR;
1136 /*
1137 * arc_access and arc_change_state need to be aware that a
1138 * header has just come out of L2ARC, so we set its state to
1139 * l2c_only even though it's about to change.
1140 */
1141 nhdr->b_l1hdr.b_state = arc_l2c_only;
1142
1143 /* Verify previous threads set to NULL before freeing */
1144 ASSERT3P(nhdr->b_l1hdr.b_tmp_cdata, ==, NULL);
1145 } else {
1146 ASSERT(hdr->b_l1hdr.b_buf == NULL);
1147 ASSERT0(hdr->b_l1hdr.b_datacnt);
1148
1149 /*
1150 * If we've reached here, We must have been called from
1151 * arc_evict_hdr(), as such we should have already been
1152 * removed from any ghost list we were previously on
1153 * (which protects us from racing with arc_evict_state),
1154 * thus no locking is needed during this check.
1155 */
1156 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1157
1158 /*
1159 * A buffer must not be moved into the arc_l2c_only
1160 * state if it's not finished being written out to the
1161 * l2arc device. Otherwise, the b_l1hdr.b_tmp_cdata field
1162 * might try to be accessed, even though it was removed.
1163 */
1164 VERIFY(!HDR_L2_WRITING(hdr));
1165 VERIFY3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
1166
1167 nhdr->b_flags &= ~ARC_FLAG_HAS_L1HDR;
1168 }
1169 /*
1170 * The header has been reallocated so we need to re-insert it into any
1171 * lists it was on.
1172 */
1173 (void) buf_hash_insert(nhdr, NULL);
1174
1175 ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
1176
1177 mutex_enter(&dev->l2ad_mtx);
1178
1179 /*
1180 * We must place the realloc'ed header back into the list at
1181 * the same spot. Otherwise, if it's placed earlier in the list,
1182 * l2arc_write_buffers() could find it during the function's
1183 * write phase, and try to write it out to the l2arc.
1184 */
1185 list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
1186 list_remove(&dev->l2ad_buflist, hdr);
1187
1188 mutex_exit(&dev->l2ad_mtx);
1189
1190 /*
1191 * Since we're using the pointer address as the tag when
1192 * incrementing and decrementing the l2ad_alloc refcount, we
1193 * must remove the old pointer (that we're about to destroy) and
1194 * add the new pointer to the refcount. Otherwise we'd remove
1195 * the wrong pointer address when calling arc_hdr_destroy() later.
1196 */
1197
1198 (void) refcount_remove_many(&dev->l2ad_alloc,
1199 hdr->b_l2hdr.b_asize, hdr);
1200
1201 (void) refcount_add_many(&dev->l2ad_alloc,
1202 nhdr->b_l2hdr.b_asize, nhdr);
1203
1204 buf_discard_identity(hdr);
1205 hdr->b_freeze_cksum = NULL;
1206 kmem_cache_free(old, hdr);
1207
1208 return (nhdr);
1209 }
1210
1211
1212 #define ARC_MINTIME (hz>>4) /* 62 ms */
1213
1214 static void
1215 arc_cksum_verify(arc_buf_t *buf)
1216 {
1217 zio_cksum_t zc;
1218
1219 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1220 return;
1221
1222 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1223 if (buf->b_hdr->b_freeze_cksum == NULL || HDR_IO_ERROR(buf->b_hdr)) {
1224 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1225 return;
1226 }
1227 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1228 if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
1229 panic("buffer modified while frozen!");
1230 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1231 }
1232
1233 static int
1234 arc_cksum_equal(arc_buf_t *buf)
1235 {
1236 zio_cksum_t zc;
1237 int equal;
1238
1239 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1240 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1241 equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
1242 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1243
1244 return (equal);
1245 }
1246
1247 static void
1248 arc_cksum_compute(arc_buf_t *buf, boolean_t force)
1249 {
1250 if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
1251 return;
1252
1253 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1254 if (buf->b_hdr->b_freeze_cksum != NULL) {
1255 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1256 return;
1257 }
1258 buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t),
1259 KM_SLEEP);
1260 fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
1261 buf->b_hdr->b_freeze_cksum);
1262 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1263 arc_buf_watch(buf);
1264 }
1265
1266 #ifndef _KERNEL
1267 void
1268 arc_buf_sigsegv(int sig, siginfo_t *si, void *unused)
1269 {
1270 panic("Got SIGSEGV at address: 0x%lx\n", (long) si->si_addr);
1271 }
1272 #endif
1273
1274 /* ARGSUSED */
1275 static void
1276 arc_buf_unwatch(arc_buf_t *buf)
1277 {
1278 #ifndef _KERNEL
1279 if (arc_watch) {
1280 ASSERT0(mprotect(buf->b_data, buf->b_hdr->b_size,
1281 PROT_READ | PROT_WRITE));
1282 }
1283 #endif
1284 }
1285
1286 /* ARGSUSED */
1287 static void
1288 arc_buf_watch(arc_buf_t *buf)
1289 {
1290 #ifndef _KERNEL
1291 if (arc_watch)
1292 ASSERT0(mprotect(buf->b_data, buf->b_hdr->b_size, PROT_READ));
1293 #endif
1294 }
1295
1296 static arc_buf_contents_t
1297 arc_buf_type(arc_buf_hdr_t *hdr)
1298 {
1299 if (HDR_ISTYPE_METADATA(hdr)) {
1300 return (ARC_BUFC_METADATA);
1301 } else {
1302 return (ARC_BUFC_DATA);
1303 }
1304 }
1305
1306 static uint32_t
1307 arc_bufc_to_flags(arc_buf_contents_t type)
1308 {
1309 switch (type) {
1310 case ARC_BUFC_DATA:
1311 /* metadata field is 0 if buffer contains normal data */
1312 return (0);
1313 case ARC_BUFC_METADATA:
1314 return (ARC_FLAG_BUFC_METADATA);
1315 default:
1316 break;
1317 }
1318 panic("undefined ARC buffer type!");
1319 return ((uint32_t)-1);
1320 }
1321
1322 void
1323 arc_buf_thaw(arc_buf_t *buf)
1324 {
1325 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1326 if (buf->b_hdr->b_l1hdr.b_state != arc_anon)
1327 panic("modifying non-anon buffer!");
1328 if (HDR_IO_IN_PROGRESS(buf->b_hdr))
1329 panic("modifying buffer while i/o in progress!");
1330 arc_cksum_verify(buf);
1331 }
1332
1333 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1334 if (buf->b_hdr->b_freeze_cksum != NULL) {
1335 kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1336 buf->b_hdr->b_freeze_cksum = NULL;
1337 }
1338
1339 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1340
1341 arc_buf_unwatch(buf);
1342 }
1343
1344 void
1345 arc_buf_freeze(arc_buf_t *buf)
1346 {
1347 kmutex_t *hash_lock;
1348
1349 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1350 return;
1351
1352 hash_lock = HDR_LOCK(buf->b_hdr);
1353 mutex_enter(hash_lock);
1354
1355 ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
1356 buf->b_hdr->b_l1hdr.b_state == arc_anon);
1357 arc_cksum_compute(buf, B_FALSE);
1358 mutex_exit(hash_lock);
1359
1360 }
1361
1362 static void
1363 add_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1364 {
1365 arc_state_t *state;
1366
1367 ASSERT(HDR_HAS_L1HDR(hdr));
1368 ASSERT(MUTEX_HELD(hash_lock));
1369
1370 state = hdr->b_l1hdr.b_state;
1371
1372 if ((refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
1373 (state != arc_anon)) {
1374 /* We don't use the L2-only state list. */
1375 if (state != arc_l2c_only) {
1376 arc_buf_contents_t type = arc_buf_type(hdr);
1377 uint64_t delta = hdr->b_size * hdr->b_l1hdr.b_datacnt;
1378 multilist_t *list = &state->arcs_list[type];
1379 uint64_t *size = &state->arcs_lsize[type];
1380
1381 multilist_remove(list, hdr);
1382
1383 if (GHOST_STATE(state)) {
1384 ASSERT0(hdr->b_l1hdr.b_datacnt);
1385 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
1386 delta = hdr->b_size;
1387 }
1388 ASSERT(delta > 0);
1389 ASSERT3U(*size, >=, delta);
1390 atomic_add_64(size, -delta);
1391 }
1392 /* remove the prefetch flag if we get a reference */
1393 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
1394 }
1395 }
1396
1397 static int
1398 remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1399 {
1400 int cnt;
1401 arc_state_t *state = hdr->b_l1hdr.b_state;
1402
1403 ASSERT(HDR_HAS_L1HDR(hdr));
1404 ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
1405 ASSERT(!GHOST_STATE(state));
1406
1407 /*
1408 * arc_l2c_only counts as a ghost state so we don't need to explicitly
1409 * check to prevent usage of the arc_l2c_only list.
1410 */
1411 if (((cnt = refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
1412 (state != arc_anon)) {
1413 arc_buf_contents_t type = arc_buf_type(hdr);
1414 multilist_t *list = &state->arcs_list[type];
1415 uint64_t *size = &state->arcs_lsize[type];
1416
1417 multilist_insert(list, hdr);
1418
1419 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
1420 atomic_add_64(size, hdr->b_size *
1421 hdr->b_l1hdr.b_datacnt);
1422 }
1423 return (cnt);
1424 }
1425
1426 /*
1427 * Returns detailed information about a specific arc buffer. When the
1428 * state_index argument is set the function will calculate the arc header
1429 * list position for its arc state. Since this requires a linear traversal
1430 * callers are strongly encourage not to do this. However, it can be helpful
1431 * for targeted analysis so the functionality is provided.
1432 */
1433 void
1434 arc_buf_info(arc_buf_t *ab, arc_buf_info_t *abi, int state_index)
1435 {
1436 arc_buf_hdr_t *hdr = ab->b_hdr;
1437 l1arc_buf_hdr_t *l1hdr = NULL;
1438 l2arc_buf_hdr_t *l2hdr = NULL;
1439 arc_state_t *state = NULL;
1440
1441 if (HDR_HAS_L1HDR(hdr)) {
1442 l1hdr = &hdr->b_l1hdr;
1443 state = l1hdr->b_state;
1444 }
1445 if (HDR_HAS_L2HDR(hdr))
1446 l2hdr = &hdr->b_l2hdr;
1447
1448 memset(abi, 0, sizeof (arc_buf_info_t));
1449 abi->abi_flags = hdr->b_flags;
1450
1451 if (l1hdr) {
1452 abi->abi_datacnt = l1hdr->b_datacnt;
1453 abi->abi_access = l1hdr->b_arc_access;
1454 abi->abi_mru_hits = l1hdr->b_mru_hits;
1455 abi->abi_mru_ghost_hits = l1hdr->b_mru_ghost_hits;
1456 abi->abi_mfu_hits = l1hdr->b_mfu_hits;
1457 abi->abi_mfu_ghost_hits = l1hdr->b_mfu_ghost_hits;
1458 abi->abi_holds = refcount_count(&l1hdr->b_refcnt);
1459 }
1460
1461 if (l2hdr) {
1462 abi->abi_l2arc_dattr = l2hdr->b_daddr;
1463 abi->abi_l2arc_asize = l2hdr->b_asize;
1464 abi->abi_l2arc_compress = HDR_GET_COMPRESS(hdr);
1465 abi->abi_l2arc_hits = l2hdr->b_hits;
1466 }
1467
1468 abi->abi_state_type = state ? state->arcs_state : ARC_STATE_ANON;
1469 abi->abi_state_contents = arc_buf_type(hdr);
1470 abi->abi_size = hdr->b_size;
1471 }
1472
1473 /*
1474 * Move the supplied buffer to the indicated state. The hash lock
1475 * for the buffer must be held by the caller.
1476 */
1477 static void
1478 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
1479 kmutex_t *hash_lock)
1480 {
1481 arc_state_t *old_state;
1482 int64_t refcnt;
1483 uint32_t datacnt;
1484 uint64_t from_delta, to_delta;
1485 arc_buf_contents_t buftype = arc_buf_type(hdr);
1486
1487 /*
1488 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
1489 * in arc_read() when bringing a buffer out of the L2ARC. However, the
1490 * L1 hdr doesn't always exist when we change state to arc_anon before
1491 * destroying a header, in which case reallocating to add the L1 hdr is
1492 * pointless.
1493 */
1494 if (HDR_HAS_L1HDR(hdr)) {
1495 old_state = hdr->b_l1hdr.b_state;
1496 refcnt = refcount_count(&hdr->b_l1hdr.b_refcnt);
1497 datacnt = hdr->b_l1hdr.b_datacnt;
1498 } else {
1499 old_state = arc_l2c_only;
1500 refcnt = 0;
1501 datacnt = 0;
1502 }
1503
1504 ASSERT(MUTEX_HELD(hash_lock));
1505 ASSERT3P(new_state, !=, old_state);
1506 ASSERT(refcnt == 0 || datacnt > 0);
1507 ASSERT(!GHOST_STATE(new_state) || datacnt == 0);
1508 ASSERT(old_state != arc_anon || datacnt <= 1);
1509
1510 from_delta = to_delta = datacnt * hdr->b_size;
1511
1512 /*
1513 * If this buffer is evictable, transfer it from the
1514 * old state list to the new state list.
1515 */
1516 if (refcnt == 0) {
1517 if (old_state != arc_anon && old_state != arc_l2c_only) {
1518 uint64_t *size = &old_state->arcs_lsize[buftype];
1519
1520 ASSERT(HDR_HAS_L1HDR(hdr));
1521 multilist_remove(&old_state->arcs_list[buftype], hdr);
1522
1523 /*
1524 * If prefetching out of the ghost cache,
1525 * we will have a non-zero datacnt.
1526 */
1527 if (GHOST_STATE(old_state) && datacnt == 0) {
1528 /* ghost elements have a ghost size */
1529 ASSERT(hdr->b_l1hdr.b_buf == NULL);
1530 from_delta = hdr->b_size;
1531 }
1532 ASSERT3U(*size, >=, from_delta);
1533 atomic_add_64(size, -from_delta);
1534 }
1535 if (new_state != arc_anon && new_state != arc_l2c_only) {
1536 uint64_t *size = &new_state->arcs_lsize[buftype];
1537
1538 /*
1539 * An L1 header always exists here, since if we're
1540 * moving to some L1-cached state (i.e. not l2c_only or
1541 * anonymous), we realloc the header to add an L1hdr
1542 * beforehand.
1543 */
1544 ASSERT(HDR_HAS_L1HDR(hdr));
1545 multilist_insert(&new_state->arcs_list[buftype], hdr);
1546
1547 /* ghost elements have a ghost size */
1548 if (GHOST_STATE(new_state)) {
1549 ASSERT0(datacnt);
1550 ASSERT(hdr->b_l1hdr.b_buf == NULL);
1551 to_delta = hdr->b_size;
1552 }
1553 atomic_add_64(size, to_delta);
1554 }
1555 }
1556
1557 ASSERT(!BUF_EMPTY(hdr));
1558 if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
1559 buf_hash_remove(hdr);
1560
1561 /* adjust state sizes (ignore arc_l2c_only) */
1562
1563 if (to_delta && new_state != arc_l2c_only) {
1564 ASSERT(HDR_HAS_L1HDR(hdr));
1565 if (GHOST_STATE(new_state)) {
1566 ASSERT0(datacnt);
1567
1568 /*
1569 * We moving a header to a ghost state, we first
1570 * remove all arc buffers. Thus, we'll have a
1571 * datacnt of zero, and no arc buffer to use for
1572 * the reference. As a result, we use the arc
1573 * header pointer for the reference.
1574 */
1575 (void) refcount_add_many(&new_state->arcs_size,
1576 hdr->b_size, hdr);
1577 } else {
1578 arc_buf_t *buf;
1579 ASSERT3U(datacnt, !=, 0);
1580
1581 /*
1582 * Each individual buffer holds a unique reference,
1583 * thus we must remove each of these references one
1584 * at a time.
1585 */
1586 for (buf = hdr->b_l1hdr.b_buf; buf != NULL;
1587 buf = buf->b_next) {
1588 (void) refcount_add_many(&new_state->arcs_size,
1589 hdr->b_size, buf);
1590 }
1591 }
1592 }
1593
1594 if (from_delta && old_state != arc_l2c_only) {
1595 ASSERT(HDR_HAS_L1HDR(hdr));
1596 if (GHOST_STATE(old_state)) {
1597 /*
1598 * When moving a header off of a ghost state,
1599 * there's the possibility for datacnt to be
1600 * non-zero. This is because we first add the
1601 * arc buffer to the header prior to changing
1602 * the header's state. Since we used the header
1603 * for the reference when putting the header on
1604 * the ghost state, we must balance that and use
1605 * the header when removing off the ghost state
1606 * (even though datacnt is non zero).
1607 */
1608
1609 IMPLY(datacnt == 0, new_state == arc_anon ||
1610 new_state == arc_l2c_only);
1611
1612 (void) refcount_remove_many(&old_state->arcs_size,
1613 hdr->b_size, hdr);
1614 } else {
1615 arc_buf_t *buf;
1616 ASSERT3U(datacnt, !=, 0);
1617
1618 /*
1619 * Each individual buffer holds a unique reference,
1620 * thus we must remove each of these references one
1621 * at a time.
1622 */
1623 for (buf = hdr->b_l1hdr.b_buf; buf != NULL;
1624 buf = buf->b_next) {
1625 (void) refcount_remove_many(
1626 &old_state->arcs_size, hdr->b_size, buf);
1627 }
1628 }
1629 }
1630
1631 if (HDR_HAS_L1HDR(hdr))
1632 hdr->b_l1hdr.b_state = new_state;
1633
1634 /*
1635 * L2 headers should never be on the L2 state list since they don't
1636 * have L1 headers allocated.
1637 */
1638 ASSERT(multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
1639 multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
1640 }
1641
1642 void
1643 arc_space_consume(uint64_t space, arc_space_type_t type)
1644 {
1645 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1646
1647 switch (type) {
1648 default:
1649 break;
1650 case ARC_SPACE_DATA:
1651 ARCSTAT_INCR(arcstat_data_size, space);
1652 break;
1653 case ARC_SPACE_META:
1654 ARCSTAT_INCR(arcstat_metadata_size, space);
1655 break;
1656 case ARC_SPACE_OTHER:
1657 ARCSTAT_INCR(arcstat_other_size, space);
1658 break;
1659 case ARC_SPACE_HDRS:
1660 ARCSTAT_INCR(arcstat_hdr_size, space);
1661 break;
1662 case ARC_SPACE_L2HDRS:
1663 ARCSTAT_INCR(arcstat_l2_hdr_size, space);
1664 break;
1665 }
1666
1667 if (type != ARC_SPACE_DATA)
1668 ARCSTAT_INCR(arcstat_meta_used, space);
1669
1670 atomic_add_64(&arc_size, space);
1671 }
1672
1673 void
1674 arc_space_return(uint64_t space, arc_space_type_t type)
1675 {
1676 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1677
1678 switch (type) {
1679 default:
1680 break;
1681 case ARC_SPACE_DATA:
1682 ARCSTAT_INCR(arcstat_data_size, -space);
1683 break;
1684 case ARC_SPACE_META:
1685 ARCSTAT_INCR(arcstat_metadata_size, -space);
1686 break;
1687 case ARC_SPACE_OTHER:
1688 ARCSTAT_INCR(arcstat_other_size, -space);
1689 break;
1690 case ARC_SPACE_HDRS:
1691 ARCSTAT_INCR(arcstat_hdr_size, -space);
1692 break;
1693 case ARC_SPACE_L2HDRS:
1694 ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
1695 break;
1696 }
1697
1698 if (type != ARC_SPACE_DATA) {
1699 ASSERT(arc_meta_used >= space);
1700 if (arc_meta_max < arc_meta_used)
1701 arc_meta_max = arc_meta_used;
1702 ARCSTAT_INCR(arcstat_meta_used, -space);
1703 }
1704
1705 ASSERT(arc_size >= space);
1706 atomic_add_64(&arc_size, -space);
1707 }
1708
1709 arc_buf_t *
1710 arc_buf_alloc(spa_t *spa, uint64_t size, void *tag, arc_buf_contents_t type)
1711 {
1712 arc_buf_hdr_t *hdr;
1713 arc_buf_t *buf;
1714
1715 VERIFY3U(size, <=, spa_maxblocksize(spa));
1716 hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
1717 ASSERT(BUF_EMPTY(hdr));
1718 ASSERT3P(hdr->b_freeze_cksum, ==, NULL);
1719 hdr->b_size = size;
1720 hdr->b_spa = spa_load_guid(spa);
1721 hdr->b_l1hdr.b_mru_hits = 0;
1722 hdr->b_l1hdr.b_mru_ghost_hits = 0;
1723 hdr->b_l1hdr.b_mfu_hits = 0;
1724 hdr->b_l1hdr.b_mfu_ghost_hits = 0;
1725 hdr->b_l1hdr.b_l2_hits = 0;
1726
1727 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1728 buf->b_hdr = hdr;
1729 buf->b_data = NULL;
1730 buf->b_efunc = NULL;
1731 buf->b_private = NULL;
1732 buf->b_next = NULL;
1733
1734 hdr->b_flags = arc_bufc_to_flags(type);
1735 hdr->b_flags |= ARC_FLAG_HAS_L1HDR;
1736
1737 hdr->b_l1hdr.b_buf = buf;
1738 hdr->b_l1hdr.b_state = arc_anon;
1739 hdr->b_l1hdr.b_arc_access = 0;
1740 hdr->b_l1hdr.b_datacnt = 1;
1741 hdr->b_l1hdr.b_tmp_cdata = NULL;
1742
1743 arc_get_data_buf(buf);
1744
1745 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
1746 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
1747
1748 return (buf);
1749 }
1750
1751 static char *arc_onloan_tag = "onloan";
1752
1753 /*
1754 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
1755 * flight data by arc_tempreserve_space() until they are "returned". Loaned
1756 * buffers must be returned to the arc before they can be used by the DMU or
1757 * freed.
1758 */
1759 arc_buf_t *
1760 arc_loan_buf(spa_t *spa, uint64_t size)
1761 {
1762 arc_buf_t *buf;
1763
1764 buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
1765
1766 atomic_add_64(&arc_loaned_bytes, size);
1767 return (buf);
1768 }
1769
1770 /*
1771 * Return a loaned arc buffer to the arc.
1772 */
1773 void
1774 arc_return_buf(arc_buf_t *buf, void *tag)
1775 {
1776 arc_buf_hdr_t *hdr = buf->b_hdr;
1777
1778 ASSERT(buf->b_data != NULL);
1779 ASSERT(HDR_HAS_L1HDR(hdr));
1780 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
1781 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
1782
1783 atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
1784 }
1785
1786 /* Detach an arc_buf from a dbuf (tag) */
1787 void
1788 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
1789 {
1790 arc_buf_hdr_t *hdr = buf->b_hdr;
1791
1792 ASSERT(buf->b_data != NULL);
1793 ASSERT(HDR_HAS_L1HDR(hdr));
1794 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
1795 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
1796 buf->b_efunc = NULL;
1797 buf->b_private = NULL;
1798
1799 atomic_add_64(&arc_loaned_bytes, hdr->b_size);
1800 }
1801
1802 static arc_buf_t *
1803 arc_buf_clone(arc_buf_t *from)
1804 {
1805 arc_buf_t *buf;
1806 arc_buf_hdr_t *hdr = from->b_hdr;
1807 uint64_t size = hdr->b_size;
1808
1809 ASSERT(HDR_HAS_L1HDR(hdr));
1810 ASSERT(hdr->b_l1hdr.b_state != arc_anon);
1811
1812 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1813 buf->b_hdr = hdr;
1814 buf->b_data = NULL;
1815 buf->b_efunc = NULL;
1816 buf->b_private = NULL;
1817 buf->b_next = hdr->b_l1hdr.b_buf;
1818 hdr->b_l1hdr.b_buf = buf;
1819 arc_get_data_buf(buf);
1820 bcopy(from->b_data, buf->b_data, size);
1821
1822 /*
1823 * This buffer already exists in the arc so create a duplicate
1824 * copy for the caller. If the buffer is associated with user data
1825 * then track the size and number of duplicates. These stats will be
1826 * updated as duplicate buffers are created and destroyed.
1827 */
1828 if (HDR_ISTYPE_DATA(hdr)) {
1829 ARCSTAT_BUMP(arcstat_duplicate_buffers);
1830 ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
1831 }
1832 hdr->b_l1hdr.b_datacnt += 1;
1833 return (buf);
1834 }
1835
1836 void
1837 arc_buf_add_ref(arc_buf_t *buf, void* tag)
1838 {
1839 arc_buf_hdr_t *hdr;
1840 kmutex_t *hash_lock;
1841
1842 /*
1843 * Check to see if this buffer is evicted. Callers
1844 * must verify b_data != NULL to know if the add_ref
1845 * was successful.
1846 */
1847 mutex_enter(&buf->b_evict_lock);
1848 if (buf->b_data == NULL) {
1849 mutex_exit(&buf->b_evict_lock);
1850 return;
1851 }
1852 hash_lock = HDR_LOCK(buf->b_hdr);
1853 mutex_enter(hash_lock);
1854 hdr = buf->b_hdr;
1855 ASSERT(HDR_HAS_L1HDR(hdr));
1856 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1857 mutex_exit(&buf->b_evict_lock);
1858
1859 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
1860 hdr->b_l1hdr.b_state == arc_mfu);
1861
1862 add_reference(hdr, hash_lock, tag);
1863 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
1864 arc_access(hdr, hash_lock);
1865 mutex_exit(hash_lock);
1866 ARCSTAT_BUMP(arcstat_hits);
1867 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
1868 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
1869 data, metadata, hits);
1870 }
1871
1872 static void
1873 arc_buf_free_on_write(void *data, size_t size,
1874 void (*free_func)(void *, size_t))
1875 {
1876 l2arc_data_free_t *df;
1877
1878 df = kmem_alloc(sizeof (*df), KM_SLEEP);
1879 df->l2df_data = data;
1880 df->l2df_size = size;
1881 df->l2df_func = free_func;
1882 mutex_enter(&l2arc_free_on_write_mtx);
1883 list_insert_head(l2arc_free_on_write, df);
1884 mutex_exit(&l2arc_free_on_write_mtx);
1885 }
1886
1887 /*
1888 * Free the arc data buffer. If it is an l2arc write in progress,
1889 * the buffer is placed on l2arc_free_on_write to be freed later.
1890 */
1891 static void
1892 arc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
1893 {
1894 arc_buf_hdr_t *hdr = buf->b_hdr;
1895
1896 if (HDR_L2_WRITING(hdr)) {
1897 arc_buf_free_on_write(buf->b_data, hdr->b_size, free_func);
1898 ARCSTAT_BUMP(arcstat_l2_free_on_write);
1899 } else {
1900 free_func(buf->b_data, hdr->b_size);
1901 }
1902 }
1903
1904 static void
1905 arc_buf_l2_cdata_free(arc_buf_hdr_t *hdr)
1906 {
1907 ASSERT(HDR_HAS_L2HDR(hdr));
1908 ASSERT(MUTEX_HELD(&hdr->b_l2hdr.b_dev->l2ad_mtx));
1909
1910 /*
1911 * The b_tmp_cdata field is linked off of the b_l1hdr, so if
1912 * that doesn't exist, the header is in the arc_l2c_only state,
1913 * and there isn't anything to free (it's already been freed).
1914 */
1915 if (!HDR_HAS_L1HDR(hdr))
1916 return;
1917
1918 /*
1919 * The header isn't being written to the l2arc device, thus it
1920 * shouldn't have a b_tmp_cdata to free.
1921 */
1922 if (!HDR_L2_WRITING(hdr)) {
1923 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
1924 return;
1925 }
1926
1927 /*
1928 * The header does not have compression enabled. This can be due
1929 * to the buffer not being compressible, or because we're
1930 * freeing the buffer before the second phase of
1931 * l2arc_write_buffer() has started (which does the compression
1932 * step). In either case, b_tmp_cdata does not point to a
1933 * separately compressed buffer, so there's nothing to free (it
1934 * points to the same buffer as the arc_buf_t's b_data field).
1935 */
1936 if (HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_OFF) {
1937 hdr->b_l1hdr.b_tmp_cdata = NULL;
1938 return;
1939 }
1940
1941 /*
1942 * There's nothing to free since the buffer was all zero's and
1943 * compressed to a zero length buffer.
1944 */
1945 if (HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_EMPTY) {
1946 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
1947 return;
1948 }
1949
1950 ASSERT(L2ARC_IS_VALID_COMPRESS(HDR_GET_COMPRESS(hdr)));
1951
1952 arc_buf_free_on_write(hdr->b_l1hdr.b_tmp_cdata,
1953 hdr->b_size, zio_data_buf_free);
1954
1955 ARCSTAT_BUMP(arcstat_l2_cdata_free_on_write);
1956 hdr->b_l1hdr.b_tmp_cdata = NULL;
1957 }
1958
1959 /*
1960 * Free up buf->b_data and if 'remove' is set, then pull the
1961 * arc_buf_t off of the the arc_buf_hdr_t's list and free it.
1962 */
1963 static void
1964 arc_buf_destroy(arc_buf_t *buf, boolean_t remove)
1965 {
1966 arc_buf_t **bufp;
1967
1968 /* free up data associated with the buf */
1969 if (buf->b_data != NULL) {
1970 arc_state_t *state = buf->b_hdr->b_l1hdr.b_state;
1971 uint64_t size = buf->b_hdr->b_size;
1972 arc_buf_contents_t type = arc_buf_type(buf->b_hdr);
1973
1974 arc_cksum_verify(buf);
1975 arc_buf_unwatch(buf);
1976
1977 if (type == ARC_BUFC_METADATA) {
1978 arc_buf_data_free(buf, zio_buf_free);
1979 arc_space_return(size, ARC_SPACE_META);
1980 } else {
1981 ASSERT(type == ARC_BUFC_DATA);
1982 arc_buf_data_free(buf, zio_data_buf_free);
1983 arc_space_return(size, ARC_SPACE_DATA);
1984 }
1985
1986 /* protected by hash lock, if in the hash table */
1987 if (multilist_link_active(&buf->b_hdr->b_l1hdr.b_arc_node)) {
1988 uint64_t *cnt = &state->arcs_lsize[type];
1989
1990 ASSERT(refcount_is_zero(
1991 &buf->b_hdr->b_l1hdr.b_refcnt));
1992 ASSERT(state != arc_anon && state != arc_l2c_only);
1993
1994 ASSERT3U(*cnt, >=, size);
1995 atomic_add_64(cnt, -size);
1996 }
1997
1998 (void) refcount_remove_many(&state->arcs_size, size, buf);
1999 buf->b_data = NULL;
2000
2001 /*
2002 * If we're destroying a duplicate buffer make sure
2003 * that the appropriate statistics are updated.
2004 */
2005 if (buf->b_hdr->b_l1hdr.b_datacnt > 1 &&
2006 HDR_ISTYPE_DATA(buf->b_hdr)) {
2007 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
2008 ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
2009 }
2010 ASSERT(buf->b_hdr->b_l1hdr.b_datacnt > 0);
2011 buf->b_hdr->b_l1hdr.b_datacnt -= 1;
2012 }
2013
2014 /* only remove the buf if requested */
2015 if (!remove)
2016 return;
2017
2018 /* remove the buf from the hdr list */
2019 for (bufp = &buf->b_hdr->b_l1hdr.b_buf; *bufp != buf;
2020 bufp = &(*bufp)->b_next)
2021 continue;
2022 *bufp = buf->b_next;
2023 buf->b_next = NULL;
2024
2025 ASSERT(buf->b_efunc == NULL);
2026
2027 /* clean up the buf */
2028 buf->b_hdr = NULL;
2029 kmem_cache_free(buf_cache, buf);
2030 }
2031
2032 static void
2033 arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
2034 {
2035 l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
2036 l2arc_dev_t *dev = l2hdr->b_dev;
2037
2038 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
2039 ASSERT(HDR_HAS_L2HDR(hdr));
2040
2041 list_remove(&dev->l2ad_buflist, hdr);
2042
2043 arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
2044
2045 /*
2046 * We don't want to leak the b_tmp_cdata buffer that was
2047 * allocated in l2arc_write_buffers()
2048 */
2049 arc_buf_l2_cdata_free(hdr);
2050
2051 /*
2052 * If the l2hdr's b_daddr is equal to L2ARC_ADDR_UNSET, then
2053 * this header is being processed by l2arc_write_buffers() (i.e.
2054 * it's in the first stage of l2arc_write_buffers()).
2055 * Re-affirming that truth here, just to serve as a reminder. If
2056 * b_daddr does not equal L2ARC_ADDR_UNSET, then the header may or
2057 * may not have its HDR_L2_WRITING flag set. (the write may have
2058 * completed, in which case HDR_L2_WRITING will be false and the
2059 * b_daddr field will point to the address of the buffer on disk).
2060 */
2061 IMPLY(l2hdr->b_daddr == L2ARC_ADDR_UNSET, HDR_L2_WRITING(hdr));
2062
2063 /*
2064 * If b_daddr is equal to L2ARC_ADDR_UNSET, we're racing with
2065 * l2arc_write_buffers(). Since we've just removed this header
2066 * from the l2arc buffer list, this header will never reach the
2067 * second stage of l2arc_write_buffers(), which increments the
2068 * accounting stats for this header. Thus, we must be careful
2069 * not to decrement them for this header either.
2070 */
2071 if (l2hdr->b_daddr != L2ARC_ADDR_UNSET) {
2072 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
2073 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
2074
2075 vdev_space_update(dev->l2ad_vdev,
2076 -l2hdr->b_asize, 0, 0);
2077
2078 (void) refcount_remove_many(&dev->l2ad_alloc,
2079 l2hdr->b_asize, hdr);
2080 }
2081
2082 hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
2083 }
2084
2085 static void
2086 arc_hdr_destroy(arc_buf_hdr_t *hdr)
2087 {
2088 if (HDR_HAS_L1HDR(hdr)) {
2089 ASSERT(hdr->b_l1hdr.b_buf == NULL ||
2090 hdr->b_l1hdr.b_datacnt > 0);
2091 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2092 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
2093 }
2094 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2095 ASSERT(!HDR_IN_HASH_TABLE(hdr));
2096
2097 if (HDR_HAS_L2HDR(hdr)) {
2098 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
2099 boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
2100
2101 if (!buflist_held)
2102 mutex_enter(&dev->l2ad_mtx);
2103
2104 /*
2105 * Even though we checked this conditional above, we
2106 * need to check this again now that we have the
2107 * l2ad_mtx. This is because we could be racing with
2108 * another thread calling l2arc_evict() which might have
2109 * destroyed this header's L2 portion as we were waiting
2110 * to acquire the l2ad_mtx. If that happens, we don't
2111 * want to re-destroy the header's L2 portion.
2112 */
2113 if (HDR_HAS_L2HDR(hdr))
2114 arc_hdr_l2hdr_destroy(hdr);
2115
2116 if (!buflist_held)
2117 mutex_exit(&dev->l2ad_mtx);
2118 }
2119
2120 if (!BUF_EMPTY(hdr))
2121 buf_discard_identity(hdr);
2122
2123 if (hdr->b_freeze_cksum != NULL) {
2124 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
2125 hdr->b_freeze_cksum = NULL;
2126 }
2127
2128 if (HDR_HAS_L1HDR(hdr)) {
2129 while (hdr->b_l1hdr.b_buf) {
2130 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
2131
2132 if (buf->b_efunc != NULL) {
2133 mutex_enter(&arc_user_evicts_lock);
2134 mutex_enter(&buf->b_evict_lock);
2135 ASSERT(buf->b_hdr != NULL);
2136 arc_buf_destroy(hdr->b_l1hdr.b_buf, FALSE);
2137 hdr->b_l1hdr.b_buf = buf->b_next;
2138 buf->b_hdr = &arc_eviction_hdr;
2139 buf->b_next = arc_eviction_list;
2140 arc_eviction_list = buf;
2141 mutex_exit(&buf->b_evict_lock);
2142 cv_signal(&arc_user_evicts_cv);
2143 mutex_exit(&arc_user_evicts_lock);
2144 } else {
2145 arc_buf_destroy(hdr->b_l1hdr.b_buf, TRUE);
2146 }
2147 }
2148 }
2149
2150 ASSERT3P(hdr->b_hash_next, ==, NULL);
2151 if (HDR_HAS_L1HDR(hdr)) {
2152 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
2153 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
2154 kmem_cache_free(hdr_full_cache, hdr);
2155 } else {
2156 kmem_cache_free(hdr_l2only_cache, hdr);
2157 }
2158 }
2159
2160 void
2161 arc_buf_free(arc_buf_t *buf, void *tag)
2162 {
2163 arc_buf_hdr_t *hdr = buf->b_hdr;
2164 int hashed = hdr->b_l1hdr.b_state != arc_anon;
2165
2166 ASSERT(buf->b_efunc == NULL);
2167 ASSERT(buf->b_data != NULL);
2168
2169 if (hashed) {
2170 kmutex_t *hash_lock = HDR_LOCK(hdr);
2171
2172 mutex_enter(hash_lock);
2173 hdr = buf->b_hdr;
2174 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2175
2176 (void) remove_reference(hdr, hash_lock, tag);
2177 if (hdr->b_l1hdr.b_datacnt > 1) {
2178 arc_buf_destroy(buf, TRUE);
2179 } else {
2180 ASSERT(buf == hdr->b_l1hdr.b_buf);
2181 ASSERT(buf->b_efunc == NULL);
2182 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
2183 }
2184 mutex_exit(hash_lock);
2185 } else if (HDR_IO_IN_PROGRESS(hdr)) {
2186 int destroy_hdr;
2187 /*
2188 * We are in the middle of an async write. Don't destroy
2189 * this buffer unless the write completes before we finish
2190 * decrementing the reference count.
2191 */
2192 mutex_enter(&arc_user_evicts_lock);
2193 (void) remove_reference(hdr, NULL, tag);
2194 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2195 destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
2196 mutex_exit(&arc_user_evicts_lock);
2197 if (destroy_hdr)
2198 arc_hdr_destroy(hdr);
2199 } else {
2200 if (remove_reference(hdr, NULL, tag) > 0)
2201 arc_buf_destroy(buf, TRUE);
2202 else
2203 arc_hdr_destroy(hdr);
2204 }
2205 }
2206
2207 boolean_t
2208 arc_buf_remove_ref(arc_buf_t *buf, void* tag)
2209 {
2210 arc_buf_hdr_t *hdr = buf->b_hdr;
2211 kmutex_t *hash_lock = NULL;
2212 boolean_t no_callback = (buf->b_efunc == NULL);
2213
2214 if (hdr->b_l1hdr.b_state == arc_anon) {
2215 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
2216 arc_buf_free(buf, tag);
2217 return (no_callback);
2218 }
2219
2220 hash_lock = HDR_LOCK(hdr);
2221 mutex_enter(hash_lock);
2222 hdr = buf->b_hdr;
2223 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
2224 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2225 ASSERT(hdr->b_l1hdr.b_state != arc_anon);
2226 ASSERT(buf->b_data != NULL);
2227
2228 (void) remove_reference(hdr, hash_lock, tag);
2229 if (hdr->b_l1hdr.b_datacnt > 1) {
2230 if (no_callback)
2231 arc_buf_destroy(buf, TRUE);
2232 } else if (no_callback) {
2233 ASSERT(hdr->b_l1hdr.b_buf == buf && buf->b_next == NULL);
2234 ASSERT(buf->b_efunc == NULL);
2235 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
2236 }
2237 ASSERT(no_callback || hdr->b_l1hdr.b_datacnt > 1 ||
2238 refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2239 mutex_exit(hash_lock);
2240 return (no_callback);
2241 }
2242
2243 uint64_t
2244 arc_buf_size(arc_buf_t *buf)
2245 {
2246 return (buf->b_hdr->b_size);
2247 }
2248
2249 /*
2250 * Called from the DMU to determine if the current buffer should be
2251 * evicted. In order to ensure proper locking, the eviction must be initiated
2252 * from the DMU. Return true if the buffer is associated with user data and
2253 * duplicate buffers still exist.
2254 */
2255 boolean_t
2256 arc_buf_eviction_needed(arc_buf_t *buf)
2257 {
2258 arc_buf_hdr_t *hdr;
2259 boolean_t evict_needed = B_FALSE;
2260
2261 if (zfs_disable_dup_eviction)
2262 return (B_FALSE);
2263
2264 mutex_enter(&buf->b_evict_lock);
2265 hdr = buf->b_hdr;
2266 if (hdr == NULL) {
2267 /*
2268 * We are in arc_do_user_evicts(); let that function
2269 * perform the eviction.
2270 */
2271 ASSERT(buf->b_data == NULL);
2272 mutex_exit(&buf->b_evict_lock);
2273 return (B_FALSE);
2274 } else if (buf->b_data == NULL) {
2275 /*
2276 * We have already been added to the arc eviction list;
2277 * recommend eviction.
2278 */
2279 ASSERT3P(hdr, ==, &arc_eviction_hdr);
2280 mutex_exit(&buf->b_evict_lock);
2281 return (B_TRUE);
2282 }
2283
2284 if (hdr->b_l1hdr.b_datacnt > 1 && HDR_ISTYPE_DATA(hdr))
2285 evict_needed = B_TRUE;
2286
2287 mutex_exit(&buf->b_evict_lock);
2288 return (evict_needed);
2289 }
2290
2291 /*
2292 * Evict the arc_buf_hdr that is provided as a parameter. The resultant
2293 * state of the header is dependent on its state prior to entering this
2294 * function. The following transitions are possible:
2295 *
2296 * - arc_mru -> arc_mru_ghost
2297 * - arc_mfu -> arc_mfu_ghost
2298 * - arc_mru_ghost -> arc_l2c_only
2299 * - arc_mru_ghost -> deleted
2300 * - arc_mfu_ghost -> arc_l2c_only
2301 * - arc_mfu_ghost -> deleted
2302 */
2303 static int64_t
2304 arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
2305 {
2306 arc_state_t *evicted_state, *state;
2307 int64_t bytes_evicted = 0;
2308
2309 ASSERT(MUTEX_HELD(hash_lock));
2310 ASSERT(HDR_HAS_L1HDR(hdr));
2311
2312 state = hdr->b_l1hdr.b_state;
2313 if (GHOST_STATE(state)) {
2314 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2315 ASSERT(hdr->b_l1hdr.b_buf == NULL);
2316
2317 /*
2318 * l2arc_write_buffers() relies on a header's L1 portion
2319 * (i.e. its b_tmp_cdata field) during its write phase.
2320 * Thus, we cannot push a header onto the arc_l2c_only
2321 * state (removing its L1 piece) until the header is
2322 * done being written to the l2arc.
2323 */
2324 if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
2325 ARCSTAT_BUMP(arcstat_evict_l2_skip);
2326 return (bytes_evicted);
2327 }
2328
2329 ARCSTAT_BUMP(arcstat_deleted);
2330 bytes_evicted += hdr->b_size;
2331
2332 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
2333
2334 if (HDR_HAS_L2HDR(hdr)) {
2335 /*
2336 * This buffer is cached on the 2nd Level ARC;
2337 * don't destroy the header.
2338 */
2339 arc_change_state(arc_l2c_only, hdr, hash_lock);
2340 /*
2341 * dropping from L1+L2 cached to L2-only,
2342 * realloc to remove the L1 header.
2343 */
2344 hdr = arc_hdr_realloc(hdr, hdr_full_cache,
2345 hdr_l2only_cache);
2346 } else {
2347 arc_change_state(arc_anon, hdr, hash_lock);
2348 arc_hdr_destroy(hdr);
2349 }
2350 return (bytes_evicted);
2351 }
2352
2353 ASSERT(state == arc_mru || state == arc_mfu);
2354 evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
2355
2356 /* prefetch buffers have a minimum lifespan */
2357 if (HDR_IO_IN_PROGRESS(hdr) ||
2358 ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
2359 ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
2360 arc_min_prefetch_lifespan)) {
2361 ARCSTAT_BUMP(arcstat_evict_skip);
2362 return (bytes_evicted);
2363 }
2364
2365 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
2366 ASSERT3U(hdr->b_l1hdr.b_datacnt, >, 0);
2367 while (hdr->b_l1hdr.b_buf) {
2368 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
2369 if (!mutex_tryenter(&buf->b_evict_lock)) {
2370 ARCSTAT_BUMP(arcstat_mutex_miss);
2371 break;
2372 }
2373 if (buf->b_data != NULL)
2374 bytes_evicted += hdr->b_size;
2375 if (buf->b_efunc != NULL) {
2376 mutex_enter(&arc_user_evicts_lock);
2377 arc_buf_destroy(buf, FALSE);
2378 hdr->b_l1hdr.b_buf = buf->b_next;
2379 buf->b_hdr = &arc_eviction_hdr;
2380 buf->b_next = arc_eviction_list;
2381 arc_eviction_list = buf;
2382 cv_signal(&arc_user_evicts_cv);
2383 mutex_exit(&arc_user_evicts_lock);
2384 mutex_exit(&buf->b_evict_lock);
2385 } else {
2386 mutex_exit(&buf->b_evict_lock);
2387 arc_buf_destroy(buf, TRUE);
2388 }
2389 }
2390
2391 if (HDR_HAS_L2HDR(hdr)) {
2392 ARCSTAT_INCR(arcstat_evict_l2_cached, hdr->b_size);
2393 } else {
2394 if (l2arc_write_eligible(hdr->b_spa, hdr))
2395 ARCSTAT_INCR(arcstat_evict_l2_eligible, hdr->b_size);
2396 else
2397 ARCSTAT_INCR(arcstat_evict_l2_ineligible, hdr->b_size);
2398 }
2399
2400 if (hdr->b_l1hdr.b_datacnt == 0) {
2401 arc_change_state(evicted_state, hdr, hash_lock);
2402 ASSERT(HDR_IN_HASH_TABLE(hdr));
2403 hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
2404 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
2405 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
2406 }
2407
2408 return (bytes_evicted);
2409 }
2410
2411 static uint64_t
2412 arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
2413 uint64_t spa, int64_t bytes)
2414 {
2415 multilist_sublist_t *mls;
2416 uint64_t bytes_evicted = 0;
2417 arc_buf_hdr_t *hdr;
2418 kmutex_t *hash_lock;
2419 int evict_count = 0;
2420
2421 ASSERT3P(marker, !=, NULL);
2422 ASSERTV(if (bytes < 0) ASSERT(bytes == ARC_EVICT_ALL));
2423
2424 mls = multilist_sublist_lock(ml, idx);
2425
2426 for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
2427 hdr = multilist_sublist_prev(mls, marker)) {
2428 if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
2429 (evict_count >= zfs_arc_evict_batch_limit))
2430 break;
2431
2432 /*
2433 * To keep our iteration location, move the marker
2434 * forward. Since we're not holding hdr's hash lock, we
2435 * must be very careful and not remove 'hdr' from the
2436 * sublist. Otherwise, other consumers might mistake the
2437 * 'hdr' as not being on a sublist when they call the
2438 * multilist_link_active() function (they all rely on
2439 * the hash lock protecting concurrent insertions and
2440 * removals). multilist_sublist_move_forward() was
2441 * specifically implemented to ensure this is the case
2442 * (only 'marker' will be removed and re-inserted).
2443 */
2444 multilist_sublist_move_forward(mls, marker);
2445
2446 /*
2447 * The only case where the b_spa field should ever be
2448 * zero, is the marker headers inserted by
2449 * arc_evict_state(). It's possible for multiple threads
2450 * to be calling arc_evict_state() concurrently (e.g.
2451 * dsl_pool_close() and zio_inject_fault()), so we must
2452 * skip any markers we see from these other threads.
2453 */
2454 if (hdr->b_spa == 0)
2455 continue;
2456
2457 /* we're only interested in evicting buffers of a certain spa */
2458 if (spa != 0 && hdr->b_spa != spa) {
2459 ARCSTAT_BUMP(arcstat_evict_skip);
2460 continue;
2461 }
2462
2463 hash_lock = HDR_LOCK(hdr);
2464
2465 /*
2466 * We aren't calling this function from any code path
2467 * that would already be holding a hash lock, so we're
2468 * asserting on this assumption to be defensive in case
2469 * this ever changes. Without this check, it would be
2470 * possible to incorrectly increment arcstat_mutex_miss
2471 * below (e.g. if the code changed such that we called
2472 * this function with a hash lock held).
2473 */
2474 ASSERT(!MUTEX_HELD(hash_lock));
2475
2476 if (mutex_tryenter(hash_lock)) {
2477 uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
2478 mutex_exit(hash_lock);
2479
2480 bytes_evicted += evicted;
2481
2482 /*
2483 * If evicted is zero, arc_evict_hdr() must have
2484 * decided to skip this header, don't increment
2485 * evict_count in this case.
2486 */
2487 if (evicted != 0)
2488 evict_count++;
2489
2490 /*
2491 * If arc_size isn't overflowing, signal any
2492 * threads that might happen to be waiting.
2493 *
2494 * For each header evicted, we wake up a single
2495 * thread. If we used cv_broadcast, we could
2496 * wake up "too many" threads causing arc_size
2497 * to significantly overflow arc_c; since
2498 * arc_get_data_buf() doesn't check for overflow
2499 * when it's woken up (it doesn't because it's
2500 * possible for the ARC to be overflowing while
2501 * full of un-evictable buffers, and the
2502 * function should proceed in this case).
2503 *
2504 * If threads are left sleeping, due to not
2505 * using cv_broadcast, they will be woken up
2506 * just before arc_reclaim_thread() sleeps.
2507 */
2508 mutex_enter(&arc_reclaim_lock);
2509 if (!arc_is_overflowing())
2510 cv_signal(&arc_reclaim_waiters_cv);
2511 mutex_exit(&arc_reclaim_lock);
2512 } else {
2513 ARCSTAT_BUMP(arcstat_mutex_miss);
2514 }
2515 }
2516
2517 multilist_sublist_unlock(mls);
2518
2519 return (bytes_evicted);
2520 }
2521
2522 /*
2523 * Evict buffers from the given arc state, until we've removed the
2524 * specified number of bytes. Move the removed buffers to the
2525 * appropriate evict state.
2526 *
2527 * This function makes a "best effort". It skips over any buffers
2528 * it can't get a hash_lock on, and so, may not catch all candidates.
2529 * It may also return without evicting as much space as requested.
2530 *
2531 * If bytes is specified using the special value ARC_EVICT_ALL, this
2532 * will evict all available (i.e. unlocked and evictable) buffers from
2533 * the given arc state; which is used by arc_flush().
2534 */
2535 static uint64_t
2536 arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
2537 arc_buf_contents_t type)
2538 {
2539 uint64_t total_evicted = 0;
2540 multilist_t *ml = &state->arcs_list[type];
2541 int num_sublists;
2542 arc_buf_hdr_t **markers;
2543 int i;
2544
2545 ASSERTV(if (bytes < 0) ASSERT(bytes == ARC_EVICT_ALL));
2546
2547 num_sublists = multilist_get_num_sublists(ml);
2548
2549 /*
2550 * If we've tried to evict from each sublist, made some
2551 * progress, but still have not hit the target number of bytes
2552 * to evict, we want to keep trying. The markers allow us to
2553 * pick up where we left off for each individual sublist, rather
2554 * than starting from the tail each time.
2555 */
2556 markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
2557 for (i = 0; i < num_sublists; i++) {
2558 multilist_sublist_t *mls;
2559
2560 markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
2561
2562 /*
2563 * A b_spa of 0 is used to indicate that this header is
2564 * a marker. This fact is used in arc_adjust_type() and
2565 * arc_evict_state_impl().
2566 */
2567 markers[i]->b_spa = 0;
2568
2569 mls = multilist_sublist_lock(ml, i);
2570 multilist_sublist_insert_tail(mls, markers[i]);
2571 multilist_sublist_unlock(mls);
2572 }
2573
2574 /*
2575 * While we haven't hit our target number of bytes to evict, or
2576 * we're evicting all available buffers.
2577 */
2578 while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
2579 /*
2580 * Start eviction using a randomly selected sublist,
2581 * this is to try and evenly balance eviction across all
2582 * sublists. Always starting at the same sublist
2583 * (e.g. index 0) would cause evictions to favor certain
2584 * sublists over others.
2585 */
2586 int sublist_idx = multilist_get_random_index(ml);
2587 uint64_t scan_evicted = 0;
2588
2589 for (i = 0; i < num_sublists; i++) {
2590 uint64_t bytes_remaining;
2591 uint64_t bytes_evicted;
2592
2593 if (bytes == ARC_EVICT_ALL)
2594 bytes_remaining = ARC_EVICT_ALL;
2595 else if (total_evicted < bytes)
2596 bytes_remaining = bytes - total_evicted;
2597 else
2598 break;
2599
2600 bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
2601 markers[sublist_idx], spa, bytes_remaining);
2602
2603 scan_evicted += bytes_evicted;
2604 total_evicted += bytes_evicted;
2605
2606 /* we've reached the end, wrap to the beginning */
2607 if (++sublist_idx >= num_sublists)
2608 sublist_idx = 0;
2609 }
2610
2611 /*
2612 * If we didn't evict anything during this scan, we have
2613 * no reason to believe we'll evict more during another
2614 * scan, so break the loop.
2615 */
2616 if (scan_evicted == 0) {
2617 /* This isn't possible, let's make that obvious */
2618 ASSERT3S(bytes, !=, 0);
2619
2620 /*
2621 * When bytes is ARC_EVICT_ALL, the only way to
2622 * break the loop is when scan_evicted is zero.
2623 * In that case, we actually have evicted enough,
2624 * so we don't want to increment the kstat.
2625 */
2626 if (bytes != ARC_EVICT_ALL) {
2627 ASSERT3S(total_evicted, <, bytes);
2628 ARCSTAT_BUMP(arcstat_evict_not_enough);
2629 }
2630
2631 break;
2632 }
2633 }
2634
2635 for (i = 0; i < num_sublists; i++) {
2636 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
2637 multilist_sublist_remove(mls, markers[i]);
2638 multilist_sublist_unlock(mls);
2639
2640 kmem_cache_free(hdr_full_cache, markers[i]);
2641 }
2642 kmem_free(markers, sizeof (*markers) * num_sublists);
2643
2644 return (total_evicted);
2645 }
2646
2647 /*
2648 * Flush all "evictable" data of the given type from the arc state
2649 * specified. This will not evict any "active" buffers (i.e. referenced).
2650 *
2651 * When 'retry' is set to FALSE, the function will make a single pass
2652 * over the state and evict any buffers that it can. Since it doesn't
2653 * continually retry the eviction, it might end up leaving some buffers
2654 * in the ARC due to lock misses.
2655 *
2656 * When 'retry' is set to TRUE, the function will continually retry the
2657 * eviction until *all* evictable buffers have been removed from the
2658 * state. As a result, if concurrent insertions into the state are
2659 * allowed (e.g. if the ARC isn't shutting down), this function might
2660 * wind up in an infinite loop, continually trying to evict buffers.
2661 */
2662 static uint64_t
2663 arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
2664 boolean_t retry)
2665 {
2666 uint64_t evicted = 0;
2667
2668 while (state->arcs_lsize[type] != 0) {
2669 evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
2670
2671 if (!retry)
2672 break;
2673 }
2674
2675 return (evicted);
2676 }
2677
2678 /*
2679 * Helper function for arc_prune() it is responsible for safely handling
2680 * the execution of a registered arc_prune_func_t.
2681 */
2682 static void
2683 arc_prune_task(void *ptr)
2684 {
2685 arc_prune_t *ap = (arc_prune_t *)ptr;
2686 arc_prune_func_t *func = ap->p_pfunc;
2687
2688 if (func != NULL)
2689 func(ap->p_adjust, ap->p_private);
2690
2691 /* Callback unregistered concurrently with execution */
2692 if (refcount_remove(&ap->p_refcnt, func) == 0) {
2693 ASSERT(!list_link_active(&ap->p_node));
2694 refcount_destroy(&ap->p_refcnt);
2695 kmem_free(ap, sizeof (*ap));
2696 }
2697 }
2698
2699 /*
2700 * Notify registered consumers they must drop holds on a portion of the ARC
2701 * buffered they reference. This provides a mechanism to ensure the ARC can
2702 * honor the arc_meta_limit and reclaim otherwise pinned ARC buffers. This
2703 * is analogous to dnlc_reduce_cache() but more generic.
2704 *
2705 * This operation is performed asyncronously so it may be safely called
2706 * in the context of the arc_reclaim_thread(). A reference is taken here
2707 * for each registered arc_prune_t and the arc_prune_task() is responsible
2708 * for releasing it once the registered arc_prune_func_t has completed.
2709 */
2710 static void
2711 arc_prune_async(int64_t adjust)
2712 {
2713 arc_prune_t *ap;
2714
2715 mutex_enter(&arc_prune_mtx);
2716 for (ap = list_head(&arc_prune_list); ap != NULL;
2717 ap = list_next(&arc_prune_list, ap)) {
2718
2719 if (refcount_count(&ap->p_refcnt) >= 2)
2720 continue;
2721
2722 refcount_add(&ap->p_refcnt, ap->p_pfunc);
2723 ap->p_adjust = adjust;
2724 taskq_dispatch(arc_prune_taskq, arc_prune_task, ap, TQ_SLEEP);
2725 ARCSTAT_BUMP(arcstat_prune);
2726 }
2727 mutex_exit(&arc_prune_mtx);
2728 }
2729
2730 static void
2731 arc_prune(int64_t adjust)
2732 {
2733 arc_prune_async(adjust);
2734 taskq_wait_outstanding(arc_prune_taskq, 0);
2735 }
2736
2737 /*
2738 * Evict the specified number of bytes from the state specified,
2739 * restricting eviction to the spa and type given. This function
2740 * prevents us from trying to evict more from a state's list than
2741 * is "evictable", and to skip evicting altogether when passed a
2742 * negative value for "bytes". In contrast, arc_evict_state() will
2743 * evict everything it can, when passed a negative value for "bytes".
2744 */
2745 static uint64_t
2746 arc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
2747 arc_buf_contents_t type)
2748 {
2749 int64_t delta;
2750
2751 if (bytes > 0 && state->arcs_lsize[type] > 0) {
2752 delta = MIN(state->arcs_lsize[type], bytes);
2753 return (arc_evict_state(state, spa, delta, type));
2754 }
2755
2756 return (0);
2757 }
2758
2759 /*
2760 * The goal of this function is to evict enough meta data buffers from the
2761 * ARC in order to enforce the arc_meta_limit. Achieving this is slightly
2762 * more complicated than it appears because it is common for data buffers
2763 * to have holds on meta data buffers. In addition, dnode meta data buffers
2764 * will be held by the dnodes in the block preventing them from being freed.
2765 * This means we can't simply traverse the ARC and expect to always find
2766 * enough unheld meta data buffer to release.
2767 *
2768 * Therefore, this function has been updated to make alternating passes
2769 * over the ARC releasing data buffers and then newly unheld meta data
2770 * buffers. This ensures forward progress is maintained and arc_meta_used
2771 * will decrease. Normally this is sufficient, but if required the ARC
2772 * will call the registered prune callbacks causing dentry and inodes to
2773 * be dropped from the VFS cache. This will make dnode meta data buffers
2774 * available for reclaim.
2775 */
2776 static uint64_t
2777 arc_adjust_meta_balanced(void)
2778 {
2779 int64_t adjustmnt, delta, prune = 0;
2780 uint64_t total_evicted = 0;
2781 arc_buf_contents_t type = ARC_BUFC_DATA;
2782 int restarts = MAX(zfs_arc_meta_adjust_restarts, 0);
2783
2784 restart:
2785 /*
2786 * This slightly differs than the way we evict from the mru in
2787 * arc_adjust because we don't have a "target" value (i.e. no
2788 * "meta" arc_p). As a result, I think we can completely
2789 * cannibalize the metadata in the MRU before we evict the
2790 * metadata from the MFU. I think we probably need to implement a
2791 * "metadata arc_p" value to do this properly.
2792 */
2793 adjustmnt = arc_meta_used - arc_meta_limit;
2794
2795 if (adjustmnt > 0 && arc_mru->arcs_lsize[type] > 0) {
2796 delta = MIN(arc_mru->arcs_lsize[type], adjustmnt);
2797 total_evicted += arc_adjust_impl(arc_mru, 0, delta, type);
2798 adjustmnt -= delta;
2799 }
2800
2801 /*
2802 * We can't afford to recalculate adjustmnt here. If we do,
2803 * new metadata buffers can sneak into the MRU or ANON lists,
2804 * thus penalize the MFU metadata. Although the fudge factor is
2805 * small, it has been empirically shown to be significant for
2806 * certain workloads (e.g. creating many empty directories). As
2807 * such, we use the original calculation for adjustmnt, and
2808 * simply decrement the amount of data evicted from the MRU.
2809 */
2810
2811 if (adjustmnt > 0 && arc_mfu->arcs_lsize[type] > 0) {
2812 delta = MIN(arc_mfu->arcs_lsize[type], adjustmnt);
2813 total_evicted += arc_adjust_impl(arc_mfu, 0, delta, type);
2814 }
2815
2816 adjustmnt = arc_meta_used - arc_meta_limit;
2817
2818 if (adjustmnt > 0 && arc_mru_ghost->arcs_lsize[type] > 0) {
2819 delta = MIN(adjustmnt,
2820 arc_mru_ghost->arcs_lsize[type]);
2821 total_evicted += arc_adjust_impl(arc_mru_ghost, 0, delta, type);
2822 adjustmnt -= delta;
2823 }
2824
2825 if (adjustmnt > 0 && arc_mfu_ghost->arcs_lsize[type] > 0) {
2826 delta = MIN(adjustmnt,
2827 arc_mfu_ghost->arcs_lsize[type]);
2828 total_evicted += arc_adjust_impl(arc_mfu_ghost, 0, delta, type);
2829 }
2830
2831 /*
2832 * If after attempting to make the requested adjustment to the ARC
2833 * the meta limit is still being exceeded then request that the
2834 * higher layers drop some cached objects which have holds on ARC
2835 * meta buffers. Requests to the upper layers will be made with
2836 * increasingly large scan sizes until the ARC is below the limit.
2837 */
2838 if (arc_meta_used > arc_meta_limit) {
2839 if (type == ARC_BUFC_DATA) {
2840 type = ARC_BUFC_METADATA;
2841 } else {
2842 type = ARC_BUFC_DATA;
2843
2844 if (zfs_arc_meta_prune) {
2845 prune += zfs_arc_meta_prune;
2846 arc_prune_async(prune);
2847 }
2848 }
2849
2850 if (restarts > 0) {
2851 restarts--;
2852 goto restart;
2853 }
2854 }
2855 return (total_evicted);
2856 }
2857
2858 /*
2859 * Evict metadata buffers from the cache, such that arc_meta_used is
2860 * capped by the arc_meta_limit tunable.
2861 */
2862 static uint64_t
2863 arc_adjust_meta_only(void)
2864 {
2865 uint64_t total_evicted = 0;
2866 int64_t target;
2867
2868 /*
2869 * If we're over the meta limit, we want to evict enough
2870 * metadata to get back under the meta limit. We don't want to
2871 * evict so much that we drop the MRU below arc_p, though. If
2872 * we're over the meta limit more than we're over arc_p, we
2873 * evict some from the MRU here, and some from the MFU below.
2874 */
2875 target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
2876 (int64_t)(refcount_count(&arc_anon->arcs_size) +
2877 refcount_count(&arc_mru->arcs_size) - arc_p));
2878
2879 total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
2880
2881 /*
2882 * Similar to the above, we want to evict enough bytes to get us
2883 * below the meta limit, but not so much as to drop us below the
2884 * space alloted to the MFU (which is defined as arc_c - arc_p).
2885 */
2886 target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
2887 (int64_t)(refcount_count(&arc_mfu->arcs_size) - (arc_c - arc_p)));
2888
2889 total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
2890
2891 return (total_evicted);
2892 }
2893
2894 static uint64_t
2895 arc_adjust_meta(void)
2896 {
2897 if (zfs_arc_meta_strategy == ARC_STRATEGY_META_ONLY)
2898 return (arc_adjust_meta_only());
2899 else
2900 return (arc_adjust_meta_balanced());
2901 }
2902
2903 /*
2904 * Return the type of the oldest buffer in the given arc state
2905 *
2906 * This function will select a random sublist of type ARC_BUFC_DATA and
2907 * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
2908 * is compared, and the type which contains the "older" buffer will be
2909 * returned.
2910 */
2911 static arc_buf_contents_t
2912 arc_adjust_type(arc_state_t *state)
2913 {
2914 multilist_t *data_ml = &state->arcs_list[ARC_BUFC_DATA];
2915 multilist_t *meta_ml = &state->arcs_list[ARC_BUFC_METADATA];
2916 int data_idx = multilist_get_random_index(data_ml);
2917 int meta_idx = multilist_get_random_index(meta_ml);
2918 multilist_sublist_t *data_mls;
2919 multilist_sublist_t *meta_mls;
2920 arc_buf_contents_t type;
2921 arc_buf_hdr_t *data_hdr;
2922 arc_buf_hdr_t *meta_hdr;
2923
2924 /*
2925 * We keep the sublist lock until we're finished, to prevent
2926 * the headers from being destroyed via arc_evict_state().
2927 */
2928 data_mls = multilist_sublist_lock(data_ml, data_idx);
2929 meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
2930
2931 /*
2932 * These two loops are to ensure we skip any markers that
2933 * might be at the tail of the lists due to arc_evict_state().
2934 */
2935
2936 for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
2937 data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
2938 if (data_hdr->b_spa != 0)
2939 break;
2940 }
2941
2942 for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
2943 meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
2944 if (meta_hdr->b_spa != 0)
2945 break;
2946 }
2947
2948 if (data_hdr == NULL && meta_hdr == NULL) {
2949 type = ARC_BUFC_DATA;
2950 } else if (data_hdr == NULL) {
2951 ASSERT3P(meta_hdr, !=, NULL);
2952 type = ARC_BUFC_METADATA;
2953 } else if (meta_hdr == NULL) {
2954 ASSERT3P(data_hdr, !=, NULL);
2955 type = ARC_BUFC_DATA;
2956 } else {
2957 ASSERT3P(data_hdr, !=, NULL);
2958 ASSERT3P(meta_hdr, !=, NULL);
2959
2960 /* The headers can't be on the sublist without an L1 header */
2961 ASSERT(HDR_HAS_L1HDR(data_hdr));
2962 ASSERT(HDR_HAS_L1HDR(meta_hdr));
2963
2964 if (data_hdr->b_l1hdr.b_arc_access <
2965 meta_hdr->b_l1hdr.b_arc_access) {
2966 type = ARC_BUFC_DATA;
2967 } else {
2968 type = ARC_BUFC_METADATA;
2969 }
2970 }
2971
2972 multilist_sublist_unlock(meta_mls);
2973 multilist_sublist_unlock(data_mls);
2974
2975 return (type);
2976 }
2977
2978 /*
2979 * Evict buffers from the cache, such that arc_size is capped by arc_c.
2980 */
2981 static uint64_t
2982 arc_adjust(void)
2983 {
2984 uint64_t total_evicted = 0;
2985 uint64_t bytes;
2986 int64_t target;
2987
2988 /*
2989 * If we're over arc_meta_limit, we want to correct that before
2990 * potentially evicting data buffers below.
2991 */
2992 total_evicted += arc_adjust_meta();
2993
2994 /*
2995 * Adjust MRU size
2996 *
2997 * If we're over the target cache size, we want to evict enough
2998 * from the list to get back to our target size. We don't want
2999 * to evict too much from the MRU, such that it drops below
3000 * arc_p. So, if we're over our target cache size more than
3001 * the MRU is over arc_p, we'll evict enough to get back to
3002 * arc_p here, and then evict more from the MFU below.
3003 */
3004 target = MIN((int64_t)(arc_size - arc_c),
3005 (int64_t)(refcount_count(&arc_anon->arcs_size) +
3006 refcount_count(&arc_mru->arcs_size) + arc_meta_used - arc_p));
3007
3008 /*
3009 * If we're below arc_meta_min, always prefer to evict data.
3010 * Otherwise, try to satisfy the requested number of bytes to
3011 * evict from the type which contains older buffers; in an
3012 * effort to keep newer buffers in the cache regardless of their
3013 * type. If we cannot satisfy the number of bytes from this
3014 * type, spill over into the next type.
3015 */
3016 if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
3017 arc_meta_used > arc_meta_min) {
3018 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3019 total_evicted += bytes;
3020
3021 /*
3022 * If we couldn't evict our target number of bytes from
3023 * metadata, we try to get the rest from data.
3024 */
3025 target -= bytes;
3026
3027 total_evicted +=
3028 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3029 } else {
3030 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3031 total_evicted += bytes;
3032
3033 /*
3034 * If we couldn't evict our target number of bytes from
3035 * data, we try to get the rest from metadata.
3036 */
3037 target -= bytes;
3038
3039 total_evicted +=
3040 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3041 }
3042
3043 /*
3044 * Adjust MFU size
3045 *
3046 * Now that we've tried to evict enough from the MRU to get its
3047 * size back to arc_p, if we're still above the target cache
3048 * size, we evict the rest from the MFU.
3049 */
3050 target = arc_size - arc_c;
3051
3052 if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
3053 arc_meta_used > arc_meta_min) {
3054 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3055 total_evicted += bytes;
3056
3057 /*
3058 * If we couldn't evict our target number of bytes from
3059 * metadata, we try to get the rest from data.
3060 */
3061 target -= bytes;
3062
3063 total_evicted +=
3064 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3065 } else {
3066 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3067 total_evicted += bytes;
3068
3069 /*
3070 * If we couldn't evict our target number of bytes from
3071 * data, we try to get the rest from data.
3072 */
3073 target -= bytes;
3074
3075 total_evicted +=
3076 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3077 }
3078
3079 /*
3080 * Adjust ghost lists
3081 *
3082 * In addition to the above, the ARC also defines target values
3083 * for the ghost lists. The sum of the mru list and mru ghost
3084 * list should never exceed the target size of the cache, and
3085 * the sum of the mru list, mfu list, mru ghost list, and mfu
3086 * ghost list should never exceed twice the target size of the
3087 * cache. The following logic enforces these limits on the ghost
3088 * caches, and evicts from them as needed.
3089 */
3090 target = refcount_count(&arc_mru->arcs_size) +
3091 refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
3092
3093 bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
3094 total_evicted += bytes;
3095
3096 target -= bytes;
3097
3098 total_evicted +=
3099 arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
3100
3101 /*
3102 * We assume the sum of the mru list and mfu list is less than
3103 * or equal to arc_c (we enforced this above), which means we
3104 * can use the simpler of the two equations below:
3105 *
3106 * mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
3107 * mru ghost + mfu ghost <= arc_c
3108 */
3109 target = refcount_count(&arc_mru_ghost->arcs_size) +
3110 refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
3111
3112 bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
3113 total_evicted += bytes;
3114
3115 target -= bytes;
3116
3117 total_evicted +=
3118 arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
3119
3120 return (total_evicted);
3121 }
3122
3123 static void
3124 arc_do_user_evicts(void)
3125 {
3126 mutex_enter(&arc_user_evicts_lock);
3127 while (arc_eviction_list != NULL) {
3128 arc_buf_t *buf = arc_eviction_list;
3129 arc_eviction_list = buf->b_next;
3130 mutex_enter(&buf->b_evict_lock);
3131 buf->b_hdr = NULL;
3132 mutex_exit(&buf->b_evict_lock);
3133 mutex_exit(&arc_user_evicts_lock);
3134
3135 if (buf->b_efunc != NULL)
3136 VERIFY0(buf->b_efunc(buf->b_private));
3137
3138 buf->b_efunc = NULL;
3139 buf->b_private = NULL;
3140 kmem_cache_free(buf_cache, buf);
3141 mutex_enter(&arc_user_evicts_lock);
3142 }
3143 mutex_exit(&arc_user_evicts_lock);
3144 }
3145
3146 void
3147 arc_flush(spa_t *spa, boolean_t retry)
3148 {
3149 uint64_t guid = 0;
3150
3151 /*
3152 * If retry is TRUE, a spa must not be specified since we have
3153 * no good way to determine if all of a spa's buffers have been
3154 * evicted from an arc state.
3155 */
3156 ASSERT(!retry || spa == 0);
3157
3158 if (spa != NULL)
3159 guid = spa_load_guid(spa);
3160
3161 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
3162 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
3163
3164 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
3165 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
3166
3167 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
3168 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
3169
3170 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
3171 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
3172
3173 arc_do_user_evicts();
3174 ASSERT(spa || arc_eviction_list == NULL);
3175 }
3176
3177 void
3178 arc_shrink(int64_t to_free)
3179 {
3180 if (arc_c > arc_c_min) {
3181
3182 if (arc_c > arc_c_min + to_free)
3183 atomic_add_64(&arc_c, -to_free);
3184 else
3185 arc_c = arc_c_min;
3186
3187 atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
3188 if (arc_c > arc_size)
3189 arc_c = MAX(arc_size, arc_c_min);
3190 if (arc_p > arc_c)
3191 arc_p = (arc_c >> 1);
3192 ASSERT(arc_c >= arc_c_min);
3193 ASSERT((int64_t)arc_p >= 0);
3194 }
3195
3196 if (arc_size > arc_c)
3197 (void) arc_adjust();
3198 }
3199
3200 typedef enum free_memory_reason_t {
3201 FMR_UNKNOWN,
3202 FMR_NEEDFREE,
3203 FMR_LOTSFREE,
3204 FMR_SWAPFS_MINFREE,
3205 FMR_PAGES_PP_MAXIMUM,
3206 FMR_HEAP_ARENA,
3207 FMR_ZIO_ARENA,
3208 } free_memory_reason_t;
3209
3210 int64_t last_free_memory;
3211 free_memory_reason_t last_free_reason;
3212
3213 #ifdef _KERNEL
3214 #ifdef __linux__
3215 /*
3216 * expiration time for arc_no_grow set by direct memory reclaim.
3217 */
3218 static clock_t arc_grow_time = 0;
3219 #else
3220 /*
3221 * Additional reserve of pages for pp_reserve.
3222 */
3223 int64_t arc_pages_pp_reserve = 64;
3224
3225 /*
3226 * Additional reserve of pages for swapfs.
3227 */
3228 int64_t arc_swapfs_reserve = 64;
3229 #endif
3230 #endif /* _KERNEL */
3231
3232 /*
3233 * Return the amount of memory that can be consumed before reclaim will be
3234 * needed. Positive if there is sufficient free memory, negative indicates
3235 * the amount of memory that needs to be freed up.
3236 */
3237 static int64_t
3238 arc_available_memory(void)
3239 {
3240 int64_t lowest = INT64_MAX;
3241 free_memory_reason_t r = FMR_UNKNOWN;
3242
3243 #ifdef _KERNEL
3244 #ifdef __linux__
3245 /*
3246 * Under Linux we are not allowed to directly interrogate the global
3247 * memory state. Instead rely on observing that direct reclaim has
3248 * recently occurred therefore the system must be low on memory. The
3249 * exact values returned are not critical but should be small.
3250 */
3251 if (ddi_time_after_eq(ddi_get_lbolt(), arc_grow_time))
3252 lowest = PAGE_SIZE;
3253 else
3254 lowest = -PAGE_SIZE;
3255 #else
3256 int64_t n;
3257
3258 /*
3259 * Platforms like illumos have greater visibility in to the memory
3260 * subsystem and can return a more detailed analysis of memory.
3261 */
3262 if (needfree > 0) {
3263 n = PAGESIZE * (-needfree);
3264 if (n < lowest) {
3265 lowest = n;
3266 r = FMR_NEEDFREE;
3267 }
3268 }
3269
3270 /*
3271 * check that we're out of range of the pageout scanner. It starts to
3272 * schedule paging if freemem is less than lotsfree and needfree.
3273 * lotsfree is the high-water mark for pageout, and needfree is the
3274 * number of needed free pages. We add extra pages here to make sure
3275 * the scanner doesn't start up while we're freeing memory.
3276 */
3277 n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
3278 if (n < lowest) {
3279 lowest = n;
3280 r = FMR_LOTSFREE;
3281 }
3282
3283 /*
3284 * check to make sure that swapfs has enough space so that anon
3285 * reservations can still succeed. anon_resvmem() checks that the
3286 * availrmem is greater than swapfs_minfree, and the number of reserved
3287 * swap pages. We also add a bit of extra here just to prevent
3288 * circumstances from getting really dire.
3289 */
3290 n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
3291 desfree - arc_swapfs_reserve);
3292 if (n < lowest) {
3293 lowest = n;
3294 r = FMR_SWAPFS_MINFREE;
3295 }
3296
3297
3298 /*
3299 * Check that we have enough availrmem that memory locking (e.g., via
3300 * mlock(3C) or memcntl(2)) can still succeed. (pages_pp_maximum
3301 * stores the number of pages that cannot be locked; when availrmem
3302 * drops below pages_pp_maximum, page locking mechanisms such as
3303 * page_pp_lock() will fail.)
3304 */
3305 n = PAGESIZE * (availrmem - pages_pp_maximum -
3306 arc_pages_pp_reserve);
3307 if (n < lowest) {
3308 lowest = n;
3309 r = FMR_PAGES_PP_MAXIMUM;
3310 }
3311
3312 #if defined(__i386)
3313 /*
3314 * If we're on an i386 platform, it's possible that we'll exhaust the
3315 * kernel heap space before we ever run out of available physical
3316 * memory. Most checks of the size of the heap_area compare against
3317 * tune.t_minarmem, which is the minimum available real memory that we
3318 * can have in the system. However, this is generally fixed at 25 pages
3319 * which is so low that it's useless. In this comparison, we seek to
3320 * calculate the total heap-size, and reclaim if more than 3/4ths of the
3321 * heap is allocated. (Or, in the calculation, if less than 1/4th is
3322 * free)
3323 */
3324 n = vmem_size(heap_arena, VMEM_FREE) -
3325 (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2);
3326 if (n < lowest) {
3327 lowest = n;
3328 r = FMR_HEAP_ARENA;
3329 }
3330 #endif
3331
3332 /*
3333 * If zio data pages are being allocated out of a separate heap segment,
3334 * then enforce that the size of available vmem for this arena remains
3335 * above about 1/16th free.
3336 *
3337 * Note: The 1/16th arena free requirement was put in place
3338 * to aggressively evict memory from the arc in order to avoid
3339 * memory fragmentation issues.
3340 */
3341 if (zio_arena != NULL) {
3342 n = vmem_size(zio_arena, VMEM_FREE) -
3343 (vmem_size(zio_arena, VMEM_ALLOC) >> 4);
3344 if (n < lowest) {
3345 lowest = n;
3346 r = FMR_ZIO_ARENA;
3347 }
3348 }
3349 #endif /* __linux__ */
3350 #else
3351 /* Every 100 calls, free a small amount */
3352 if (spa_get_random(100) == 0)
3353 lowest = -1024;
3354 #endif
3355
3356 last_free_memory = lowest;
3357 last_free_reason = r;
3358
3359 return (lowest);
3360 }
3361
3362 /*
3363 * Determine if the system is under memory pressure and is asking
3364 * to reclaim memory. A return value of TRUE indicates that the system
3365 * is under memory pressure and that the arc should adjust accordingly.
3366 */
3367 static boolean_t
3368 arc_reclaim_needed(void)
3369 {
3370 return (arc_available_memory() < 0);
3371 }
3372
3373 static void
3374 arc_kmem_reap_now(void)
3375 {
3376 size_t i;
3377 kmem_cache_t *prev_cache = NULL;
3378 kmem_cache_t *prev_data_cache = NULL;
3379 extern kmem_cache_t *zio_buf_cache[];
3380 extern kmem_cache_t *zio_data_buf_cache[];
3381 extern kmem_cache_t *range_seg_cache;
3382
3383 if ((arc_meta_used >= arc_meta_limit) && zfs_arc_meta_prune) {
3384 /*
3385 * We are exceeding our meta-data cache limit.
3386 * Prune some entries to release holds on meta-data.
3387 */
3388 arc_prune(zfs_arc_meta_prune);
3389 }
3390
3391 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
3392 if (zio_buf_cache[i] != prev_cache) {
3393 prev_cache = zio_buf_cache[i];
3394 kmem_cache_reap_now(zio_buf_cache[i]);
3395 }
3396 if (zio_data_buf_cache[i] != prev_data_cache) {
3397 prev_data_cache = zio_data_buf_cache[i];
3398 kmem_cache_reap_now(zio_data_buf_cache[i]);
3399 }
3400 }
3401 kmem_cache_reap_now(buf_cache);
3402 kmem_cache_reap_now(hdr_full_cache);
3403 kmem_cache_reap_now(hdr_l2only_cache);
3404 kmem_cache_reap_now(range_seg_cache);
3405
3406 if (zio_arena != NULL) {
3407 /*
3408 * Ask the vmem arena to reclaim unused memory from its
3409 * quantum caches.
3410 */
3411 vmem_qcache_reap(zio_arena);
3412 }
3413 }
3414
3415 /*
3416 * Threads can block in arc_get_data_buf() waiting for this thread to evict
3417 * enough data and signal them to proceed. When this happens, the threads in
3418 * arc_get_data_buf() are sleeping while holding the hash lock for their
3419 * particular arc header. Thus, we must be careful to never sleep on a
3420 * hash lock in this thread. This is to prevent the following deadlock:
3421 *
3422 * - Thread A sleeps on CV in arc_get_data_buf() holding hash lock "L",
3423 * waiting for the reclaim thread to signal it.
3424 *
3425 * - arc_reclaim_thread() tries to acquire hash lock "L" using mutex_enter,
3426 * fails, and goes to sleep forever.
3427 *
3428 * This possible deadlock is avoided by always acquiring a hash lock
3429 * using mutex_tryenter() from arc_reclaim_thread().
3430 */
3431 static void
3432 arc_reclaim_thread(void)
3433 {
3434 fstrans_cookie_t cookie = spl_fstrans_mark();
3435 clock_t growtime = 0;
3436 callb_cpr_t cpr;
3437
3438 CALLB_CPR_INIT(&cpr, &arc_reclaim_lock, callb_generic_cpr, FTAG);
3439
3440 mutex_enter(&arc_reclaim_lock);
3441 while (!arc_reclaim_thread_exit) {
3442 int64_t to_free;
3443 int64_t free_memory = arc_available_memory();
3444 uint64_t evicted = 0;
3445
3446 arc_tuning_update();
3447
3448 mutex_exit(&arc_reclaim_lock);
3449
3450 if (free_memory < 0) {
3451
3452 arc_no_grow = B_TRUE;
3453 arc_warm = B_TRUE;
3454
3455 /*
3456 * Wait at least zfs_grow_retry (default 5) seconds
3457 * before considering growing.
3458 */
3459 growtime = ddi_get_lbolt() + (arc_grow_retry * hz);
3460
3461 arc_kmem_reap_now();
3462
3463 /*
3464 * If we are still low on memory, shrink the ARC
3465 * so that we have arc_shrink_min free space.
3466 */
3467 free_memory = arc_available_memory();
3468
3469 to_free = (arc_c >> arc_shrink_shift) - free_memory;
3470 if (to_free > 0) {
3471 #ifdef _KERNEL
3472 to_free = MAX(to_free, ptob(needfree));
3473 #endif
3474 arc_shrink(to_free);
3475 }
3476 } else if (free_memory < arc_c >> arc_no_grow_shift) {
3477 arc_no_grow = B_TRUE;
3478 } else if (ddi_get_lbolt() >= growtime) {
3479 arc_no_grow = B_FALSE;
3480 }
3481
3482 evicted = arc_adjust();
3483
3484 mutex_enter(&arc_reclaim_lock);
3485
3486 /*
3487 * If evicted is zero, we couldn't evict anything via
3488 * arc_adjust(). This could be due to hash lock
3489 * collisions, but more likely due to the majority of
3490 * arc buffers being unevictable. Therefore, even if
3491 * arc_size is above arc_c, another pass is unlikely to
3492 * be helpful and could potentially cause us to enter an
3493 * infinite loop.
3494 */
3495 if (arc_size <= arc_c || evicted == 0) {
3496 /*
3497 * We're either no longer overflowing, or we
3498 * can't evict anything more, so we should wake
3499 * up any threads before we go to sleep.
3500 */
3501 cv_broadcast(&arc_reclaim_waiters_cv);
3502
3503 /*
3504 * Block until signaled, or after one second (we
3505 * might need to perform arc_kmem_reap_now()
3506 * even if we aren't being signalled)
3507 */
3508 CALLB_CPR_SAFE_BEGIN(&cpr);
3509 (void) cv_timedwait_sig(&arc_reclaim_thread_cv,
3510 &arc_reclaim_lock, ddi_get_lbolt() + hz);
3511 CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_lock);
3512 }
3513 }
3514
3515 arc_reclaim_thread_exit = FALSE;
3516 cv_broadcast(&arc_reclaim_thread_cv);
3517 CALLB_CPR_EXIT(&cpr); /* drops arc_reclaim_lock */
3518 spl_fstrans_unmark(cookie);
3519 thread_exit();
3520 }
3521
3522 static void
3523 arc_user_evicts_thread(void)
3524 {
3525 fstrans_cookie_t cookie = spl_fstrans_mark();
3526 callb_cpr_t cpr;
3527
3528 CALLB_CPR_INIT(&cpr, &arc_user_evicts_lock, callb_generic_cpr, FTAG);
3529
3530 mutex_enter(&arc_user_evicts_lock);
3531 while (!arc_user_evicts_thread_exit) {
3532 mutex_exit(&arc_user_evicts_lock);
3533
3534 arc_do_user_evicts();
3535
3536 /*
3537 * This is necessary in order for the mdb ::arc dcmd to
3538 * show up to date information. Since the ::arc command
3539 * does not call the kstat's update function, without
3540 * this call, the command may show stale stats for the
3541 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
3542 * with this change, the data might be up to 1 second
3543 * out of date; but that should suffice. The arc_state_t
3544 * structures can be queried directly if more accurate
3545 * information is needed.
3546 */
3547 if (arc_ksp != NULL)
3548 arc_ksp->ks_update(arc_ksp, KSTAT_READ);
3549
3550 mutex_enter(&arc_user_evicts_lock);
3551
3552 /*
3553 * Block until signaled, or after one second (we need to
3554 * call the arc's kstat update function regularly).
3555 */
3556 CALLB_CPR_SAFE_BEGIN(&cpr);
3557 (void) cv_timedwait_sig(&arc_user_evicts_cv,
3558 &arc_user_evicts_lock, ddi_get_lbolt() + hz);
3559 CALLB_CPR_SAFE_END(&cpr, &arc_user_evicts_lock);
3560 }
3561
3562 arc_user_evicts_thread_exit = FALSE;
3563 cv_broadcast(&arc_user_evicts_cv);
3564 CALLB_CPR_EXIT(&cpr); /* drops arc_user_evicts_lock */
3565 spl_fstrans_unmark(cookie);
3566 thread_exit();
3567 }
3568
3569 #ifdef _KERNEL
3570 /*
3571 * Determine the amount of memory eligible for eviction contained in the
3572 * ARC. All clean data reported by the ghost lists can always be safely
3573 * evicted. Due to arc_c_min, the same does not hold for all clean data
3574 * contained by the regular mru and mfu lists.
3575 *
3576 * In the case of the regular mru and mfu lists, we need to report as
3577 * much clean data as possible, such that evicting that same reported
3578 * data will not bring arc_size below arc_c_min. Thus, in certain
3579 * circumstances, the total amount of clean data in the mru and mfu
3580 * lists might not actually be evictable.
3581 *
3582 * The following two distinct cases are accounted for:
3583 *
3584 * 1. The sum of the amount of dirty data contained by both the mru and
3585 * mfu lists, plus the ARC's other accounting (e.g. the anon list),
3586 * is greater than or equal to arc_c_min.
3587 * (i.e. amount of dirty data >= arc_c_min)
3588 *
3589 * This is the easy case; all clean data contained by the mru and mfu
3590 * lists is evictable. Evicting all clean data can only drop arc_size
3591 * to the amount of dirty data, which is greater than arc_c_min.
3592 *
3593 * 2. The sum of the amount of dirty data contained by both the mru and
3594 * mfu lists, plus the ARC's other accounting (e.g. the anon list),
3595 * is less than arc_c_min.
3596 * (i.e. arc_c_min > amount of dirty data)
3597 *
3598 * 2.1. arc_size is greater than or equal arc_c_min.
3599 * (i.e. arc_size >= arc_c_min > amount of dirty data)
3600 *
3601 * In this case, not all clean data from the regular mru and mfu
3602 * lists is actually evictable; we must leave enough clean data
3603 * to keep arc_size above arc_c_min. Thus, the maximum amount of
3604 * evictable data from the two lists combined, is exactly the
3605 * difference between arc_size and arc_c_min.
3606 *
3607 * 2.2. arc_size is less than arc_c_min
3608 * (i.e. arc_c_min > arc_size > amount of dirty data)
3609 *
3610 * In this case, none of the data contained in the mru and mfu
3611 * lists is evictable, even if it's clean. Since arc_size is
3612 * already below arc_c_min, evicting any more would only
3613 * increase this negative difference.
3614 */
3615 static uint64_t
3616 arc_evictable_memory(void) {
3617 uint64_t arc_clean =
3618 arc_mru->arcs_lsize[ARC_BUFC_DATA] +
3619 arc_mru->arcs_lsize[ARC_BUFC_METADATA] +
3620 arc_mfu->arcs_lsize[ARC_BUFC_DATA] +
3621 arc_mfu->arcs_lsize[ARC_BUFC_METADATA];
3622 uint64_t ghost_clean =
3623 arc_mru_ghost->arcs_lsize[ARC_BUFC_DATA] +
3624 arc_mru_ghost->arcs_lsize[ARC_BUFC_METADATA] +
3625 arc_mfu_ghost->arcs_lsize[ARC_BUFC_DATA] +
3626 arc_mfu_ghost->arcs_lsize[ARC_BUFC_METADATA];
3627 uint64_t arc_dirty = MAX((int64_t)arc_size - (int64_t)arc_clean, 0);
3628
3629 if (arc_dirty >= arc_c_min)
3630 return (ghost_clean + arc_clean);
3631
3632 return (ghost_clean + MAX((int64_t)arc_size - (int64_t)arc_c_min, 0));
3633 }
3634
3635 /*
3636 * If sc->nr_to_scan is zero, the caller is requesting a query of the
3637 * number of objects which can potentially be freed. If it is nonzero,
3638 * the request is to free that many objects.
3639 *
3640 * Linux kernels >= 3.12 have the count_objects and scan_objects callbacks
3641 * in struct shrinker and also require the shrinker to return the number
3642 * of objects freed.
3643 *
3644 * Older kernels require the shrinker to return the number of freeable
3645 * objects following the freeing of nr_to_free.
3646 */
3647 static spl_shrinker_t
3648 __arc_shrinker_func(struct shrinker *shrink, struct shrink_control *sc)
3649 {
3650 int64_t pages;
3651
3652 /* The arc is considered warm once reclaim has occurred */
3653 if (unlikely(arc_warm == B_FALSE))
3654 arc_warm = B_TRUE;
3655
3656 /* Return the potential number of reclaimable pages */
3657 pages = btop((int64_t)arc_evictable_memory());
3658 if (sc->nr_to_scan == 0)
3659 return (pages);
3660
3661 /* Not allowed to perform filesystem reclaim */
3662 if (!(sc->gfp_mask & __GFP_FS))
3663 return (SHRINK_STOP);
3664
3665 /* Reclaim in progress */
3666 if (mutex_tryenter(&arc_reclaim_lock) == 0)
3667 return (SHRINK_STOP);
3668
3669 mutex_exit(&arc_reclaim_lock);
3670
3671 /*
3672 * Evict the requested number of pages by shrinking arc_c the
3673 * requested amount. If there is nothing left to evict just
3674 * reap whatever we can from the various arc slabs.
3675 */
3676 if (pages > 0) {
3677 arc_shrink(ptob(sc->nr_to_scan));
3678 arc_kmem_reap_now();
3679 #ifdef HAVE_SPLIT_SHRINKER_CALLBACK
3680 pages = MAX(pages - btop(arc_evictable_memory()), 0);
3681 #else
3682 pages = btop(arc_evictable_memory());
3683 #endif
3684 } else {
3685 arc_kmem_reap_now();
3686 pages = SHRINK_STOP;
3687 }
3688
3689 /*
3690 * We've reaped what we can, wake up threads.
3691 */
3692 cv_broadcast(&arc_reclaim_waiters_cv);
3693
3694 /*
3695 * When direct reclaim is observed it usually indicates a rapid
3696 * increase in memory pressure. This occurs because the kswapd
3697 * threads were unable to asynchronously keep enough free memory
3698 * available. In this case set arc_no_grow to briefly pause arc
3699 * growth to avoid compounding the memory pressure.
3700 */
3701 if (current_is_kswapd()) {
3702 ARCSTAT_BUMP(arcstat_memory_indirect_count);
3703 } else {
3704 arc_no_grow = B_TRUE;
3705 arc_grow_time = ddi_get_lbolt() + (zfs_arc_grow_retry * hz);
3706 ARCSTAT_BUMP(arcstat_memory_direct_count);
3707 }
3708
3709 return (pages);
3710 }
3711 SPL_SHRINKER_CALLBACK_WRAPPER(arc_shrinker_func);
3712
3713 SPL_SHRINKER_DECLARE(arc_shrinker, arc_shrinker_func, DEFAULT_SEEKS);
3714 #endif /* _KERNEL */
3715
3716 /*
3717 * Adapt arc info given the number of bytes we are trying to add and
3718 * the state that we are comming from. This function is only called
3719 * when we are adding new content to the cache.
3720 */
3721 static void
3722 arc_adapt(int bytes, arc_state_t *state)
3723 {
3724 int mult;
3725 uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
3726 int64_t mrug_size = refcount_count(&arc_mru_ghost->arcs_size);
3727 int64_t mfug_size = refcount_count(&arc_mfu_ghost->arcs_size);
3728
3729 if (state == arc_l2c_only)
3730 return;
3731
3732 ASSERT(bytes > 0);
3733 /*
3734 * Adapt the target size of the MRU list:
3735 * - if we just hit in the MRU ghost list, then increase
3736 * the target size of the MRU list.
3737 * - if we just hit in the MFU ghost list, then increase
3738 * the target size of the MFU list by decreasing the
3739 * target size of the MRU list.
3740 */
3741 if (state == arc_mru_ghost) {
3742 mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
3743 if (!zfs_arc_p_dampener_disable)
3744 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
3745
3746 arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
3747 } else if (state == arc_mfu_ghost) {
3748 uint64_t delta;
3749
3750 mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
3751 if (!zfs_arc_p_dampener_disable)
3752 mult = MIN(mult, 10);
3753
3754 delta = MIN(bytes * mult, arc_p);
3755 arc_p = MAX(arc_p_min, arc_p - delta);
3756 }
3757 ASSERT((int64_t)arc_p >= 0);
3758
3759 if (arc_reclaim_needed()) {
3760 cv_signal(&arc_reclaim_thread_cv);
3761 return;
3762 }
3763
3764 if (arc_no_grow)
3765 return;
3766
3767 if (arc_c >= arc_c_max)
3768 return;
3769
3770 /*
3771 * If we're within (2 * maxblocksize) bytes of the target
3772 * cache size, increment the target cache size
3773 */
3774 VERIFY3U(arc_c, >=, 2ULL << SPA_MAXBLOCKSHIFT);
3775 if (arc_size >= arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
3776 atomic_add_64(&arc_c, (int64_t)bytes);
3777 if (arc_c > arc_c_max)
3778 arc_c = arc_c_max;
3779 else if (state == arc_anon)
3780 atomic_add_64(&arc_p, (int64_t)bytes);
3781 if (arc_p > arc_c)
3782 arc_p = arc_c;
3783 }
3784 ASSERT((int64_t)arc_p >= 0);
3785 }
3786
3787 /*
3788 * Check if arc_size has grown past our upper threshold, determined by
3789 * zfs_arc_overflow_shift.
3790 */
3791 static boolean_t
3792 arc_is_overflowing(void)
3793 {
3794 /* Always allow at least one block of overflow */
3795 uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
3796 arc_c >> zfs_arc_overflow_shift);
3797
3798 return (arc_size >= arc_c + overflow);
3799 }
3800
3801 /*
3802 * The buffer, supplied as the first argument, needs a data block. If we
3803 * are hitting the hard limit for the cache size, we must sleep, waiting
3804 * for the eviction thread to catch up. If we're past the target size
3805 * but below the hard limit, we'll only signal the reclaim thread and
3806 * continue on.
3807 */
3808 static void
3809 arc_get_data_buf(arc_buf_t *buf)
3810 {
3811 arc_state_t *state = buf->b_hdr->b_l1hdr.b_state;
3812 uint64_t size = buf->b_hdr->b_size;
3813 arc_buf_contents_t type = arc_buf_type(buf->b_hdr);
3814
3815 arc_adapt(size, state);
3816
3817 /*
3818 * If arc_size is currently overflowing, and has grown past our
3819 * upper limit, we must be adding data faster than the evict
3820 * thread can evict. Thus, to ensure we don't compound the
3821 * problem by adding more data and forcing arc_size to grow even
3822 * further past it's target size, we halt and wait for the
3823 * eviction thread to catch up.
3824 *
3825 * It's also possible that the reclaim thread is unable to evict
3826 * enough buffers to get arc_size below the overflow limit (e.g.
3827 * due to buffers being un-evictable, or hash lock collisions).
3828 * In this case, we want to proceed regardless if we're
3829 * overflowing; thus we don't use a while loop here.
3830 */
3831 if (arc_is_overflowing()) {
3832 mutex_enter(&arc_reclaim_lock);
3833
3834 /*
3835 * Now that we've acquired the lock, we may no longer be
3836 * over the overflow limit, lets check.
3837 *
3838 * We're ignoring the case of spurious wake ups. If that
3839 * were to happen, it'd let this thread consume an ARC
3840 * buffer before it should have (i.e. before we're under
3841 * the overflow limit and were signalled by the reclaim
3842 * thread). As long as that is a rare occurrence, it
3843 * shouldn't cause any harm.
3844 */
3845 if (arc_is_overflowing()) {
3846 cv_signal(&arc_reclaim_thread_cv);
3847 cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
3848 }
3849
3850 mutex_exit(&arc_reclaim_lock);
3851 }
3852
3853 if (type == ARC_BUFC_METADATA) {
3854 buf->b_data = zio_buf_alloc(size);
3855 arc_space_consume(size, ARC_SPACE_META);
3856 } else {
3857 ASSERT(type == ARC_BUFC_DATA);
3858 buf->b_data = zio_data_buf_alloc(size);
3859 arc_space_consume(size, ARC_SPACE_DATA);
3860 }
3861
3862 /*
3863 * Update the state size. Note that ghost states have a
3864 * "ghost size" and so don't need to be updated.
3865 */
3866 if (!GHOST_STATE(buf->b_hdr->b_l1hdr.b_state)) {
3867 arc_buf_hdr_t *hdr = buf->b_hdr;
3868 arc_state_t *state = hdr->b_l1hdr.b_state;
3869
3870 (void) refcount_add_many(&state->arcs_size, size, buf);
3871
3872 /*
3873 * If this is reached via arc_read, the link is
3874 * protected by the hash lock. If reached via
3875 * arc_buf_alloc, the header should not be accessed by
3876 * any other thread. And, if reached via arc_read_done,
3877 * the hash lock will protect it if it's found in the
3878 * hash table; otherwise no other thread should be
3879 * trying to [add|remove]_reference it.
3880 */
3881 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
3882 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3883 atomic_add_64(&hdr->b_l1hdr.b_state->arcs_lsize[type],
3884 size);
3885 }
3886 /*
3887 * If we are growing the cache, and we are adding anonymous
3888 * data, and we have outgrown arc_p, update arc_p
3889 */
3890 if (arc_size < arc_c && hdr->b_l1hdr.b_state == arc_anon &&
3891 (refcount_count(&arc_anon->arcs_size) +
3892 refcount_count(&arc_mru->arcs_size) > arc_p))
3893 arc_p = MIN(arc_c, arc_p + size);
3894 }
3895 }
3896
3897 /*
3898 * This routine is called whenever a buffer is accessed.
3899 * NOTE: the hash lock is dropped in this function.
3900 */
3901 static void
3902 arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3903 {
3904 clock_t now;
3905
3906 ASSERT(MUTEX_HELD(hash_lock));
3907 ASSERT(HDR_HAS_L1HDR(hdr));
3908
3909 if (hdr->b_l1hdr.b_state == arc_anon) {
3910 /*
3911 * This buffer is not in the cache, and does not
3912 * appear in our "ghost" list. Add the new buffer
3913 * to the MRU state.
3914 */
3915
3916 ASSERT0(hdr->b_l1hdr.b_arc_access);
3917 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3918 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3919 arc_change_state(arc_mru, hdr, hash_lock);
3920
3921 } else if (hdr->b_l1hdr.b_state == arc_mru) {
3922 now = ddi_get_lbolt();
3923
3924 /*
3925 * If this buffer is here because of a prefetch, then either:
3926 * - clear the flag if this is a "referencing" read
3927 * (any subsequent access will bump this into the MFU state).
3928 * or
3929 * - move the buffer to the head of the list if this is
3930 * another prefetch (to make it less likely to be evicted).
3931 */
3932 if (HDR_PREFETCH(hdr)) {
3933 if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
3934 /* link protected by hash lock */
3935 ASSERT(multilist_link_active(
3936 &hdr->b_l1hdr.b_arc_node));
3937 } else {
3938 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3939 atomic_inc_32(&hdr->b_l1hdr.b_mru_hits);
3940 ARCSTAT_BUMP(arcstat_mru_hits);
3941 }
3942 hdr->b_l1hdr.b_arc_access = now;
3943 return;
3944 }
3945
3946 /*
3947 * This buffer has been "accessed" only once so far,
3948 * but it is still in the cache. Move it to the MFU
3949 * state.
3950 */
3951 if (ddi_time_after(now, hdr->b_l1hdr.b_arc_access +
3952 ARC_MINTIME)) {
3953 /*
3954 * More than 125ms have passed since we
3955 * instantiated this buffer. Move it to the
3956 * most frequently used state.
3957 */
3958 hdr->b_l1hdr.b_arc_access = now;
3959 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3960 arc_change_state(arc_mfu, hdr, hash_lock);
3961 }
3962 atomic_inc_32(&hdr->b_l1hdr.b_mru_hits);
3963 ARCSTAT_BUMP(arcstat_mru_hits);
3964 } else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
3965 arc_state_t *new_state;
3966 /*
3967 * This buffer has been "accessed" recently, but
3968 * was evicted from the cache. Move it to the
3969 * MFU state.
3970 */
3971
3972 if (HDR_PREFETCH(hdr)) {
3973 new_state = arc_mru;
3974 if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0)
3975 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3976 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3977 } else {
3978 new_state = arc_mfu;
3979 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3980 }
3981
3982 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3983 arc_change_state(new_state, hdr, hash_lock);
3984
3985 atomic_inc_32(&hdr->b_l1hdr.b_mru_ghost_hits);
3986 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
3987 } else if (hdr->b_l1hdr.b_state == arc_mfu) {
3988 /*
3989 * This buffer has been accessed more than once and is
3990 * still in the cache. Keep it in the MFU state.
3991 *
3992 * NOTE: an add_reference() that occurred when we did
3993 * the arc_read() will have kicked this off the list.
3994 * If it was a prefetch, we will explicitly move it to
3995 * the head of the list now.
3996 */
3997 if ((HDR_PREFETCH(hdr)) != 0) {
3998 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3999 /* link protected by hash_lock */
4000 ASSERT(multilist_link_active(&hdr->b_l1hdr.b_arc_node));
4001 }
4002 atomic_inc_32(&hdr->b_l1hdr.b_mfu_hits);
4003 ARCSTAT_BUMP(arcstat_mfu_hits);
4004 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4005 } else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
4006 arc_state_t *new_state = arc_mfu;
4007 /*
4008 * This buffer has been accessed more than once but has
4009 * been evicted from the cache. Move it back to the
4010 * MFU state.
4011 */
4012
4013 if (HDR_PREFETCH(hdr)) {
4014 /*
4015 * This is a prefetch access...
4016 * move this block back to the MRU state.
4017 */
4018 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
4019 new_state = arc_mru;
4020 }
4021
4022 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4023 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4024 arc_change_state(new_state, hdr, hash_lock);
4025
4026 atomic_inc_32(&hdr->b_l1hdr.b_mfu_ghost_hits);
4027 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
4028 } else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
4029 /*
4030 * This buffer is on the 2nd Level ARC.
4031 */
4032
4033 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4034 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4035 arc_change_state(arc_mfu, hdr, hash_lock);
4036 } else {
4037 cmn_err(CE_PANIC, "invalid arc state 0x%p",
4038 hdr->b_l1hdr.b_state);
4039 }
4040 }
4041
4042 /* a generic arc_done_func_t which you can use */
4043 /* ARGSUSED */
4044 void
4045 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
4046 {
4047 if (zio == NULL || zio->io_error == 0)
4048 bcopy(buf->b_data, arg, buf->b_hdr->b_size);
4049 VERIFY(arc_buf_remove_ref(buf, arg));
4050 }
4051
4052 /* a generic arc_done_func_t */
4053 void
4054 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
4055 {
4056 arc_buf_t **bufp = arg;
4057 if (zio && zio->io_error) {
4058 VERIFY(arc_buf_remove_ref(buf, arg));
4059 *bufp = NULL;
4060 } else {
4061 *bufp = buf;
4062 ASSERT(buf->b_data);
4063 }
4064 }
4065
4066 static void
4067 arc_read_done(zio_t *zio)
4068 {
4069 arc_buf_hdr_t *hdr;
4070 arc_buf_t *buf;
4071 arc_buf_t *abuf; /* buffer we're assigning to callback */
4072 kmutex_t *hash_lock = NULL;
4073 arc_callback_t *callback_list, *acb;
4074 int freeable = FALSE;
4075
4076 buf = zio->io_private;
4077 hdr = buf->b_hdr;
4078
4079 /*
4080 * The hdr was inserted into hash-table and removed from lists
4081 * prior to starting I/O. We should find this header, since
4082 * it's in the hash table, and it should be legit since it's
4083 * not possible to evict it during the I/O. The only possible
4084 * reason for it not to be found is if we were freed during the
4085 * read.
4086 */
4087 if (HDR_IN_HASH_TABLE(hdr)) {
4088 arc_buf_hdr_t *found;
4089
4090 ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
4091 ASSERT3U(hdr->b_dva.dva_word[0], ==,
4092 BP_IDENTITY(zio->io_bp)->dva_word[0]);
4093 ASSERT3U(hdr->b_dva.dva_word[1], ==,
4094 BP_IDENTITY(zio->io_bp)->dva_word[1]);
4095
4096 found = buf_hash_find(hdr->b_spa, zio->io_bp,
4097 &hash_lock);
4098
4099 ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) &&
4100 hash_lock == NULL) ||
4101 (found == hdr &&
4102 DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
4103 (found == hdr && HDR_L2_READING(hdr)));
4104 }
4105
4106 hdr->b_flags &= ~ARC_FLAG_L2_EVICTED;
4107 if (l2arc_noprefetch && HDR_PREFETCH(hdr))
4108 hdr->b_flags &= ~ARC_FLAG_L2CACHE;
4109
4110 /* byteswap if necessary */
4111 callback_list = hdr->b_l1hdr.b_acb;
4112 ASSERT(callback_list != NULL);
4113 if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
4114 dmu_object_byteswap_t bswap =
4115 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
4116 if (BP_GET_LEVEL(zio->io_bp) > 0)
4117 byteswap_uint64_array(buf->b_data, hdr->b_size);
4118 else
4119 dmu_ot_byteswap[bswap].ob_func(buf->b_data, hdr->b_size);
4120 }
4121
4122 arc_cksum_compute(buf, B_FALSE);
4123 arc_buf_watch(buf);
4124
4125 if (hash_lock && zio->io_error == 0 &&
4126 hdr->b_l1hdr.b_state == arc_anon) {
4127 /*
4128 * Only call arc_access on anonymous buffers. This is because
4129 * if we've issued an I/O for an evicted buffer, we've already
4130 * called arc_access (to prevent any simultaneous readers from
4131 * getting confused).
4132 */
4133 arc_access(hdr, hash_lock);
4134 }
4135
4136 /* create copies of the data buffer for the callers */
4137 abuf = buf;
4138 for (acb = callback_list; acb; acb = acb->acb_next) {
4139 if (acb->acb_done) {
4140 if (abuf == NULL) {
4141 ARCSTAT_BUMP(arcstat_duplicate_reads);
4142 abuf = arc_buf_clone(buf);
4143 }
4144 acb->acb_buf = abuf;
4145 abuf = NULL;
4146 }
4147 }
4148 hdr->b_l1hdr.b_acb = NULL;
4149 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
4150 ASSERT(!HDR_BUF_AVAILABLE(hdr));
4151 if (abuf == buf) {
4152 ASSERT(buf->b_efunc == NULL);
4153 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
4154 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
4155 }
4156
4157 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
4158 callback_list != NULL);
4159
4160 if (zio->io_error != 0) {
4161 hdr->b_flags |= ARC_FLAG_IO_ERROR;
4162 if (hdr->b_l1hdr.b_state != arc_anon)
4163 arc_change_state(arc_anon, hdr, hash_lock);
4164 if (HDR_IN_HASH_TABLE(hdr))
4165 buf_hash_remove(hdr);
4166 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4167 }
4168
4169 /*
4170 * Broadcast before we drop the hash_lock to avoid the possibility
4171 * that the hdr (and hence the cv) might be freed before we get to
4172 * the cv_broadcast().
4173 */
4174 cv_broadcast(&hdr->b_l1hdr.b_cv);
4175
4176 if (hash_lock != NULL) {
4177 mutex_exit(hash_lock);
4178 } else {
4179 /*
4180 * This block was freed while we waited for the read to
4181 * complete. It has been removed from the hash table and
4182 * moved to the anonymous state (so that it won't show up
4183 * in the cache).
4184 */
4185 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
4186 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4187 }
4188
4189 /* execute each callback and free its structure */
4190 while ((acb = callback_list) != NULL) {
4191 if (acb->acb_done)
4192 acb->acb_done(zio, acb->acb_buf, acb->acb_private);
4193
4194 if (acb->acb_zio_dummy != NULL) {
4195 acb->acb_zio_dummy->io_error = zio->io_error;
4196 zio_nowait(acb->acb_zio_dummy);
4197 }
4198
4199 callback_list = acb->acb_next;
4200 kmem_free(acb, sizeof (arc_callback_t));
4201 }
4202
4203 if (freeable)
4204 arc_hdr_destroy(hdr);
4205 }
4206
4207 /*
4208 * "Read" the block at the specified DVA (in bp) via the
4209 * cache. If the block is found in the cache, invoke the provided
4210 * callback immediately and return. Note that the `zio' parameter
4211 * in the callback will be NULL in this case, since no IO was
4212 * required. If the block is not in the cache pass the read request
4213 * on to the spa with a substitute callback function, so that the
4214 * requested block will be added to the cache.
4215 *
4216 * If a read request arrives for a block that has a read in-progress,
4217 * either wait for the in-progress read to complete (and return the
4218 * results); or, if this is a read with a "done" func, add a record
4219 * to the read to invoke the "done" func when the read completes,
4220 * and return; or just return.
4221 *
4222 * arc_read_done() will invoke all the requested "done" functions
4223 * for readers of this block.
4224 */
4225 int
4226 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
4227 void *private, zio_priority_t priority, int zio_flags,
4228 arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
4229 {
4230 arc_buf_hdr_t *hdr = NULL;
4231 arc_buf_t *buf = NULL;
4232 kmutex_t *hash_lock = NULL;
4233 zio_t *rzio;
4234 uint64_t guid = spa_load_guid(spa);
4235 int rc = 0;
4236
4237 ASSERT(!BP_IS_EMBEDDED(bp) ||
4238 BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
4239
4240 top:
4241 if (!BP_IS_EMBEDDED(bp)) {
4242 /*
4243 * Embedded BP's have no DVA and require no I/O to "read".
4244 * Create an anonymous arc buf to back it.
4245 */
4246 hdr = buf_hash_find(guid, bp, &hash_lock);
4247 }
4248
4249 if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_datacnt > 0) {
4250
4251 *arc_flags |= ARC_FLAG_CACHED;
4252
4253 if (HDR_IO_IN_PROGRESS(hdr)) {
4254
4255 if (*arc_flags & ARC_FLAG_WAIT) {
4256 cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
4257 mutex_exit(hash_lock);
4258 goto top;
4259 }
4260 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
4261
4262 if (done) {
4263 arc_callback_t *acb = NULL;
4264
4265 acb = kmem_zalloc(sizeof (arc_callback_t),
4266 KM_SLEEP);
4267 acb->acb_done = done;
4268 acb->acb_private = private;
4269 if (pio != NULL)
4270 acb->acb_zio_dummy = zio_null(pio,
4271 spa, NULL, NULL, NULL, zio_flags);
4272
4273 ASSERT(acb->acb_done != NULL);
4274 acb->acb_next = hdr->b_l1hdr.b_acb;
4275 hdr->b_l1hdr.b_acb = acb;
4276 add_reference(hdr, hash_lock, private);
4277 mutex_exit(hash_lock);
4278 goto out;
4279 }
4280 mutex_exit(hash_lock);
4281 goto out;
4282 }
4283
4284 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
4285 hdr->b_l1hdr.b_state == arc_mfu);
4286
4287 if (done) {
4288 add_reference(hdr, hash_lock, private);
4289 /*
4290 * If this block is already in use, create a new
4291 * copy of the data so that we will be guaranteed
4292 * that arc_release() will always succeed.
4293 */
4294 buf = hdr->b_l1hdr.b_buf;
4295 ASSERT(buf);
4296 ASSERT(buf->b_data);
4297 if (HDR_BUF_AVAILABLE(hdr)) {
4298 ASSERT(buf->b_efunc == NULL);
4299 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
4300 } else {
4301 buf = arc_buf_clone(buf);
4302 }
4303
4304 } else if (*arc_flags & ARC_FLAG_PREFETCH &&
4305 refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4306 hdr->b_flags |= ARC_FLAG_PREFETCH;
4307 }
4308 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
4309 arc_access(hdr, hash_lock);
4310 if (*arc_flags & ARC_FLAG_L2CACHE)
4311 hdr->b_flags |= ARC_FLAG_L2CACHE;
4312 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4313 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4314 mutex_exit(hash_lock);
4315 ARCSTAT_BUMP(arcstat_hits);
4316 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4317 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
4318 data, metadata, hits);
4319
4320 if (done)
4321 done(NULL, buf, private);
4322 } else {
4323 uint64_t size = BP_GET_LSIZE(bp);
4324 arc_callback_t *acb;
4325 vdev_t *vd = NULL;
4326 uint64_t addr = 0;
4327 boolean_t devw = B_FALSE;
4328 enum zio_compress b_compress = ZIO_COMPRESS_OFF;
4329 int32_t b_asize = 0;
4330
4331 /*
4332 * Gracefully handle a damaged logical block size as a
4333 * checksum error by passing a dummy zio to the done callback.
4334 */
4335 if (size > spa_maxblocksize(spa)) {
4336 if (done) {
4337 rzio = zio_null(pio, spa, NULL,
4338 NULL, NULL, zio_flags);
4339 rzio->io_error = ECKSUM;
4340 done(rzio, buf, private);
4341 zio_nowait(rzio);
4342 }
4343 rc = ECKSUM;
4344 goto out;
4345 }
4346
4347 if (hdr == NULL) {
4348 /* this block is not in the cache */
4349 arc_buf_hdr_t *exists = NULL;
4350 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
4351 buf = arc_buf_alloc(spa, size, private, type);
4352 hdr = buf->b_hdr;
4353 if (!BP_IS_EMBEDDED(bp)) {
4354 hdr->b_dva = *BP_IDENTITY(bp);
4355 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
4356 exists = buf_hash_insert(hdr, &hash_lock);
4357 }
4358 if (exists != NULL) {
4359 /* somebody beat us to the hash insert */
4360 mutex_exit(hash_lock);
4361 buf_discard_identity(hdr);
4362 (void) arc_buf_remove_ref(buf, private);
4363 goto top; /* restart the IO request */
4364 }
4365
4366 /* if this is a prefetch, we don't have a reference */
4367 if (*arc_flags & ARC_FLAG_PREFETCH) {
4368 (void) remove_reference(hdr, hash_lock,
4369 private);
4370 hdr->b_flags |= ARC_FLAG_PREFETCH;
4371 }
4372 if (*arc_flags & ARC_FLAG_L2CACHE)
4373 hdr->b_flags |= ARC_FLAG_L2CACHE;
4374 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4375 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4376 if (BP_GET_LEVEL(bp) > 0)
4377 hdr->b_flags |= ARC_FLAG_INDIRECT;
4378 } else {
4379 /*
4380 * This block is in the ghost cache. If it was L2-only
4381 * (and thus didn't have an L1 hdr), we realloc the
4382 * header to add an L1 hdr.
4383 */
4384 if (!HDR_HAS_L1HDR(hdr)) {
4385 hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
4386 hdr_full_cache);
4387 }
4388
4389 ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
4390 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4391 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4392 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
4393
4394 /* if this is a prefetch, we don't have a reference */
4395 if (*arc_flags & ARC_FLAG_PREFETCH)
4396 hdr->b_flags |= ARC_FLAG_PREFETCH;
4397 else
4398 add_reference(hdr, hash_lock, private);
4399 if (*arc_flags & ARC_FLAG_L2CACHE)
4400 hdr->b_flags |= ARC_FLAG_L2CACHE;
4401 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4402 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4403 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
4404 buf->b_hdr = hdr;
4405 buf->b_data = NULL;
4406 buf->b_efunc = NULL;
4407 buf->b_private = NULL;
4408 buf->b_next = NULL;
4409 hdr->b_l1hdr.b_buf = buf;
4410 ASSERT0(hdr->b_l1hdr.b_datacnt);
4411 hdr->b_l1hdr.b_datacnt = 1;
4412 arc_get_data_buf(buf);
4413 arc_access(hdr, hash_lock);
4414 }
4415
4416 ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
4417
4418 acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
4419 acb->acb_done = done;
4420 acb->acb_private = private;
4421
4422 ASSERT(hdr->b_l1hdr.b_acb == NULL);
4423 hdr->b_l1hdr.b_acb = acb;
4424 hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
4425
4426 if (HDR_HAS_L2HDR(hdr) &&
4427 (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
4428 devw = hdr->b_l2hdr.b_dev->l2ad_writing;
4429 addr = hdr->b_l2hdr.b_daddr;
4430 b_compress = HDR_GET_COMPRESS(hdr);
4431 b_asize = hdr->b_l2hdr.b_asize;
4432 /*
4433 * Lock out device removal.
4434 */
4435 if (vdev_is_dead(vd) ||
4436 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
4437 vd = NULL;
4438 }
4439
4440 if (hash_lock != NULL)
4441 mutex_exit(hash_lock);
4442
4443 /*
4444 * At this point, we have a level 1 cache miss. Try again in
4445 * L2ARC if possible.
4446 */
4447 ASSERT3U(hdr->b_size, ==, size);
4448 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
4449 uint64_t, size, zbookmark_phys_t *, zb);
4450 ARCSTAT_BUMP(arcstat_misses);
4451 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4452 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
4453 data, metadata, misses);
4454
4455 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
4456 /*
4457 * Read from the L2ARC if the following are true:
4458 * 1. The L2ARC vdev was previously cached.
4459 * 2. This buffer still has L2ARC metadata.
4460 * 3. This buffer isn't currently writing to the L2ARC.
4461 * 4. The L2ARC entry wasn't evicted, which may
4462 * also have invalidated the vdev.
4463 * 5. This isn't prefetch and l2arc_noprefetch is set.
4464 */
4465 if (HDR_HAS_L2HDR(hdr) &&
4466 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
4467 !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
4468 l2arc_read_callback_t *cb;
4469
4470 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
4471 ARCSTAT_BUMP(arcstat_l2_hits);
4472 atomic_inc_32(&hdr->b_l2hdr.b_hits);
4473
4474 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
4475 KM_SLEEP);
4476 cb->l2rcb_buf = buf;
4477 cb->l2rcb_spa = spa;
4478 cb->l2rcb_bp = *bp;
4479 cb->l2rcb_zb = *zb;
4480 cb->l2rcb_flags = zio_flags;
4481 cb->l2rcb_compress = b_compress;
4482
4483 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
4484 addr + size < vd->vdev_psize -
4485 VDEV_LABEL_END_SIZE);
4486
4487 /*
4488 * l2arc read. The SCL_L2ARC lock will be
4489 * released by l2arc_read_done().
4490 * Issue a null zio if the underlying buffer
4491 * was squashed to zero size by compression.
4492 */
4493 if (b_compress == ZIO_COMPRESS_EMPTY) {
4494 rzio = zio_null(pio, spa, vd,
4495 l2arc_read_done, cb,
4496 zio_flags | ZIO_FLAG_DONT_CACHE |
4497 ZIO_FLAG_CANFAIL |
4498 ZIO_FLAG_DONT_PROPAGATE |
4499 ZIO_FLAG_DONT_RETRY);
4500 } else {
4501 rzio = zio_read_phys(pio, vd, addr,
4502 b_asize, buf->b_data,
4503 ZIO_CHECKSUM_OFF,
4504 l2arc_read_done, cb, priority,
4505 zio_flags | ZIO_FLAG_DONT_CACHE |
4506 ZIO_FLAG_CANFAIL |
4507 ZIO_FLAG_DONT_PROPAGATE |
4508 ZIO_FLAG_DONT_RETRY, B_FALSE);
4509 }
4510 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
4511 zio_t *, rzio);
4512 ARCSTAT_INCR(arcstat_l2_read_bytes, b_asize);
4513
4514 if (*arc_flags & ARC_FLAG_NOWAIT) {
4515 zio_nowait(rzio);
4516 goto out;
4517 }
4518
4519 ASSERT(*arc_flags & ARC_FLAG_WAIT);
4520 if (zio_wait(rzio) == 0)
4521 goto out;
4522
4523 /* l2arc read error; goto zio_read() */
4524 } else {
4525 DTRACE_PROBE1(l2arc__miss,
4526 arc_buf_hdr_t *, hdr);
4527 ARCSTAT_BUMP(arcstat_l2_misses);
4528 if (HDR_L2_WRITING(hdr))
4529 ARCSTAT_BUMP(arcstat_l2_rw_clash);
4530 spa_config_exit(spa, SCL_L2ARC, vd);
4531 }
4532 } else {
4533 if (vd != NULL)
4534 spa_config_exit(spa, SCL_L2ARC, vd);
4535 if (l2arc_ndev != 0) {
4536 DTRACE_PROBE1(l2arc__miss,
4537 arc_buf_hdr_t *, hdr);
4538 ARCSTAT_BUMP(arcstat_l2_misses);
4539 }
4540 }
4541
4542 rzio = zio_read(pio, spa, bp, buf->b_data, size,
4543 arc_read_done, buf, priority, zio_flags, zb);
4544
4545 if (*arc_flags & ARC_FLAG_WAIT) {
4546 rc = zio_wait(rzio);
4547 goto out;
4548 }
4549
4550 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
4551 zio_nowait(rzio);
4552 }
4553
4554 out:
4555 spa_read_history_add(spa, zb, *arc_flags);
4556 return (rc);
4557 }
4558
4559 arc_prune_t *
4560 arc_add_prune_callback(arc_prune_func_t *func, void *private)
4561 {
4562 arc_prune_t *p;
4563
4564 p = kmem_alloc(sizeof (*p), KM_SLEEP);
4565 p->p_pfunc = func;
4566 p->p_private = private;
4567 list_link_init(&p->p_node);
4568 refcount_create(&p->p_refcnt);
4569
4570 mutex_enter(&arc_prune_mtx);
4571 refcount_add(&p->p_refcnt, &arc_prune_list);
4572 list_insert_head(&arc_prune_list, p);
4573 mutex_exit(&arc_prune_mtx);
4574
4575 return (p);
4576 }
4577
4578 void
4579 arc_remove_prune_callback(arc_prune_t *p)
4580 {
4581 mutex_enter(&arc_prune_mtx);
4582 list_remove(&arc_prune_list, p);
4583 if (refcount_remove(&p->p_refcnt, &arc_prune_list) == 0) {
4584 refcount_destroy(&p->p_refcnt);
4585 kmem_free(p, sizeof (*p));
4586 }
4587 mutex_exit(&arc_prune_mtx);
4588 }
4589
4590 void
4591 arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
4592 {
4593 ASSERT(buf->b_hdr != NULL);
4594 ASSERT(buf->b_hdr->b_l1hdr.b_state != arc_anon);
4595 ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt) ||
4596 func == NULL);
4597 ASSERT(buf->b_efunc == NULL);
4598 ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
4599
4600 buf->b_efunc = func;
4601 buf->b_private = private;
4602 }
4603
4604 /*
4605 * Notify the arc that a block was freed, and thus will never be used again.
4606 */
4607 void
4608 arc_freed(spa_t *spa, const blkptr_t *bp)
4609 {
4610 arc_buf_hdr_t *hdr;
4611 kmutex_t *hash_lock;
4612 uint64_t guid = spa_load_guid(spa);
4613
4614 ASSERT(!BP_IS_EMBEDDED(bp));
4615
4616 hdr = buf_hash_find(guid, bp, &hash_lock);
4617 if (hdr == NULL)
4618 return;
4619 if (HDR_BUF_AVAILABLE(hdr)) {
4620 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
4621 add_reference(hdr, hash_lock, FTAG);
4622 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
4623 mutex_exit(hash_lock);
4624
4625 arc_release(buf, FTAG);
4626 (void) arc_buf_remove_ref(buf, FTAG);
4627 } else {
4628 mutex_exit(hash_lock);
4629 }
4630
4631 }
4632
4633 /*
4634 * Clear the user eviction callback set by arc_set_callback(), first calling
4635 * it if it exists. Because the presence of a callback keeps an arc_buf cached
4636 * clearing the callback may result in the arc_buf being destroyed. However,
4637 * it will not result in the *last* arc_buf being destroyed, hence the data
4638 * will remain cached in the ARC. We make a copy of the arc buffer here so
4639 * that we can process the callback without holding any locks.
4640 *
4641 * It's possible that the callback is already in the process of being cleared
4642 * by another thread. In this case we can not clear the callback.
4643 *
4644 * Returns B_TRUE if the callback was successfully called and cleared.
4645 */
4646 boolean_t
4647 arc_clear_callback(arc_buf_t *buf)
4648 {
4649 arc_buf_hdr_t *hdr;
4650 kmutex_t *hash_lock;
4651 arc_evict_func_t *efunc = buf->b_efunc;
4652 void *private = buf->b_private;
4653
4654 mutex_enter(&buf->b_evict_lock);
4655 hdr = buf->b_hdr;
4656 if (hdr == NULL) {
4657 /*
4658 * We are in arc_do_user_evicts().
4659 */
4660 ASSERT(buf->b_data == NULL);
4661 mutex_exit(&buf->b_evict_lock);
4662 return (B_FALSE);
4663 } else if (buf->b_data == NULL) {
4664 /*
4665 * We are on the eviction list; process this buffer now
4666 * but let arc_do_user_evicts() do the reaping.
4667 */
4668 buf->b_efunc = NULL;
4669 mutex_exit(&buf->b_evict_lock);
4670 VERIFY0(efunc(private));
4671 return (B_TRUE);
4672 }
4673 hash_lock = HDR_LOCK(hdr);
4674 mutex_enter(hash_lock);
4675 hdr = buf->b_hdr;
4676 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4677
4678 ASSERT3U(refcount_count(&hdr->b_l1hdr.b_refcnt), <,
4679 hdr->b_l1hdr.b_datacnt);
4680 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
4681 hdr->b_l1hdr.b_state == arc_mfu);
4682
4683 buf->b_efunc = NULL;
4684 buf->b_private = NULL;
4685
4686 if (hdr->b_l1hdr.b_datacnt > 1) {
4687 mutex_exit(&buf->b_evict_lock);
4688 arc_buf_destroy(buf, TRUE);
4689 } else {
4690 ASSERT(buf == hdr->b_l1hdr.b_buf);
4691 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
4692 mutex_exit(&buf->b_evict_lock);
4693 }
4694
4695 mutex_exit(hash_lock);
4696 VERIFY0(efunc(private));
4697 return (B_TRUE);
4698 }
4699
4700 /*
4701 * Release this buffer from the cache, making it an anonymous buffer. This
4702 * must be done after a read and prior to modifying the buffer contents.
4703 * If the buffer has more than one reference, we must make
4704 * a new hdr for the buffer.
4705 */
4706 void
4707 arc_release(arc_buf_t *buf, void *tag)
4708 {
4709 kmutex_t *hash_lock;
4710 arc_state_t *state;
4711 arc_buf_hdr_t *hdr = buf->b_hdr;
4712
4713 /*
4714 * It would be nice to assert that if its DMU metadata (level >
4715 * 0 || it's the dnode file), then it must be syncing context.
4716 * But we don't know that information at this level.
4717 */
4718
4719 mutex_enter(&buf->b_evict_lock);
4720
4721 ASSERT(HDR_HAS_L1HDR(hdr));
4722
4723 /*
4724 * We don't grab the hash lock prior to this check, because if
4725 * the buffer's header is in the arc_anon state, it won't be
4726 * linked into the hash table.
4727 */
4728 if (hdr->b_l1hdr.b_state == arc_anon) {
4729 mutex_exit(&buf->b_evict_lock);
4730 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4731 ASSERT(!HDR_IN_HASH_TABLE(hdr));
4732 ASSERT(!HDR_HAS_L2HDR(hdr));
4733 ASSERT(BUF_EMPTY(hdr));
4734
4735 ASSERT3U(hdr->b_l1hdr.b_datacnt, ==, 1);
4736 ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
4737 ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
4738
4739 ASSERT3P(buf->b_efunc, ==, NULL);
4740 ASSERT3P(buf->b_private, ==, NULL);
4741
4742 hdr->b_l1hdr.b_arc_access = 0;
4743 arc_buf_thaw(buf);
4744
4745 return;
4746 }
4747
4748 hash_lock = HDR_LOCK(hdr);
4749 mutex_enter(hash_lock);
4750
4751 /*
4752 * This assignment is only valid as long as the hash_lock is
4753 * held, we must be careful not to reference state or the
4754 * b_state field after dropping the lock.
4755 */
4756 state = hdr->b_l1hdr.b_state;
4757 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4758 ASSERT3P(state, !=, arc_anon);
4759
4760 /* this buffer is not on any list */
4761 ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) > 0);
4762
4763 if (HDR_HAS_L2HDR(hdr)) {
4764 mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
4765
4766 /*
4767 * We have to recheck this conditional again now that
4768 * we're holding the l2ad_mtx to prevent a race with
4769 * another thread which might be concurrently calling
4770 * l2arc_evict(). In that case, l2arc_evict() might have
4771 * destroyed the header's L2 portion as we were waiting
4772 * to acquire the l2ad_mtx.
4773 */
4774 if (HDR_HAS_L2HDR(hdr))
4775 arc_hdr_l2hdr_destroy(hdr);
4776
4777 mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
4778 }
4779
4780 /*
4781 * Do we have more than one buf?
4782 */
4783 if (hdr->b_l1hdr.b_datacnt > 1) {
4784 arc_buf_hdr_t *nhdr;
4785 arc_buf_t **bufp;
4786 uint64_t blksz = hdr->b_size;
4787 uint64_t spa = hdr->b_spa;
4788 arc_buf_contents_t type = arc_buf_type(hdr);
4789 uint32_t flags = hdr->b_flags;
4790
4791 ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
4792 /*
4793 * Pull the data off of this hdr and attach it to
4794 * a new anonymous hdr.
4795 */
4796 (void) remove_reference(hdr, hash_lock, tag);
4797 bufp = &hdr->b_l1hdr.b_buf;
4798 while (*bufp != buf)
4799 bufp = &(*bufp)->b_next;
4800 *bufp = buf->b_next;
4801 buf->b_next = NULL;
4802
4803 ASSERT3P(state, !=, arc_l2c_only);
4804
4805 (void) refcount_remove_many(
4806 &state->arcs_size, hdr->b_size, buf);
4807
4808 if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
4809 uint64_t *size;
4810
4811 ASSERT3P(state, !=, arc_l2c_only);
4812 size = &state->arcs_lsize[type];
4813 ASSERT3U(*size, >=, hdr->b_size);
4814 atomic_add_64(size, -hdr->b_size);
4815 }
4816
4817 /*
4818 * We're releasing a duplicate user data buffer, update
4819 * our statistics accordingly.
4820 */
4821 if (HDR_ISTYPE_DATA(hdr)) {
4822 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
4823 ARCSTAT_INCR(arcstat_duplicate_buffers_size,
4824 -hdr->b_size);
4825 }
4826 hdr->b_l1hdr.b_datacnt -= 1;
4827 arc_cksum_verify(buf);
4828 arc_buf_unwatch(buf);
4829
4830 mutex_exit(hash_lock);
4831
4832 nhdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
4833 nhdr->b_size = blksz;
4834 nhdr->b_spa = spa;
4835
4836 nhdr->b_l1hdr.b_mru_hits = 0;
4837 nhdr->b_l1hdr.b_mru_ghost_hits = 0;
4838 nhdr->b_l1hdr.b_mfu_hits = 0;
4839 nhdr->b_l1hdr.b_mfu_ghost_hits = 0;
4840 nhdr->b_l1hdr.b_l2_hits = 0;
4841 nhdr->b_flags = flags & ARC_FLAG_L2_WRITING;
4842 nhdr->b_flags |= arc_bufc_to_flags(type);
4843 nhdr->b_flags |= ARC_FLAG_HAS_L1HDR;
4844
4845 nhdr->b_l1hdr.b_buf = buf;
4846 nhdr->b_l1hdr.b_datacnt = 1;
4847 nhdr->b_l1hdr.b_state = arc_anon;
4848 nhdr->b_l1hdr.b_arc_access = 0;
4849 nhdr->b_l1hdr.b_tmp_cdata = NULL;
4850 nhdr->b_freeze_cksum = NULL;
4851
4852 (void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
4853 buf->b_hdr = nhdr;
4854 mutex_exit(&buf->b_evict_lock);
4855 (void) refcount_add_many(&arc_anon->arcs_size, blksz, buf);
4856 } else {
4857 mutex_exit(&buf->b_evict_lock);
4858 ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
4859 /* protected by hash lock, or hdr is on arc_anon */
4860 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
4861 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4862 hdr->b_l1hdr.b_mru_hits = 0;
4863 hdr->b_l1hdr.b_mru_ghost_hits = 0;
4864 hdr->b_l1hdr.b_mfu_hits = 0;
4865 hdr->b_l1hdr.b_mfu_ghost_hits = 0;
4866 hdr->b_l1hdr.b_l2_hits = 0;
4867 arc_change_state(arc_anon, hdr, hash_lock);
4868 hdr->b_l1hdr.b_arc_access = 0;
4869 mutex_exit(hash_lock);
4870
4871 buf_discard_identity(hdr);
4872 arc_buf_thaw(buf);
4873 }
4874 buf->b_efunc = NULL;
4875 buf->b_private = NULL;
4876 }
4877
4878 int
4879 arc_released(arc_buf_t *buf)
4880 {
4881 int released;
4882
4883 mutex_enter(&buf->b_evict_lock);
4884 released = (buf->b_data != NULL &&
4885 buf->b_hdr->b_l1hdr.b_state == arc_anon);
4886 mutex_exit(&buf->b_evict_lock);
4887 return (released);
4888 }
4889
4890 #ifdef ZFS_DEBUG
4891 int
4892 arc_referenced(arc_buf_t *buf)
4893 {
4894 int referenced;
4895
4896 mutex_enter(&buf->b_evict_lock);
4897 referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
4898 mutex_exit(&buf->b_evict_lock);
4899 return (referenced);
4900 }
4901 #endif
4902
4903 static void
4904 arc_write_ready(zio_t *zio)
4905 {
4906 arc_write_callback_t *callback = zio->io_private;
4907 arc_buf_t *buf = callback->awcb_buf;
4908 arc_buf_hdr_t *hdr = buf->b_hdr;
4909
4910 ASSERT(HDR_HAS_L1HDR(hdr));
4911 ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
4912 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
4913 callback->awcb_ready(zio, buf, callback->awcb_private);
4914
4915 /*
4916 * If the IO is already in progress, then this is a re-write
4917 * attempt, so we need to thaw and re-compute the cksum.
4918 * It is the responsibility of the callback to handle the
4919 * accounting for any re-write attempt.
4920 */
4921 if (HDR_IO_IN_PROGRESS(hdr)) {
4922 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
4923 if (hdr->b_freeze_cksum != NULL) {
4924 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
4925 hdr->b_freeze_cksum = NULL;
4926 }
4927 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
4928 }
4929 arc_cksum_compute(buf, B_FALSE);
4930 hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
4931 }
4932
4933 /*
4934 * The SPA calls this callback for each physical write that happens on behalf
4935 * of a logical write. See the comment in dbuf_write_physdone() for details.
4936 */
4937 static void
4938 arc_write_physdone(zio_t *zio)
4939 {
4940 arc_write_callback_t *cb = zio->io_private;
4941 if (cb->awcb_physdone != NULL)
4942 cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
4943 }
4944
4945 static void
4946 arc_write_done(zio_t *zio)
4947 {
4948 arc_write_callback_t *callback = zio->io_private;
4949 arc_buf_t *buf = callback->awcb_buf;
4950 arc_buf_hdr_t *hdr = buf->b_hdr;
4951
4952 ASSERT(hdr->b_l1hdr.b_acb == NULL);
4953
4954 if (zio->io_error == 0) {
4955 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
4956 buf_discard_identity(hdr);
4957 } else {
4958 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
4959 hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
4960 }
4961 } else {
4962 ASSERT(BUF_EMPTY(hdr));
4963 }
4964
4965 /*
4966 * If the block to be written was all-zero or compressed enough to be
4967 * embedded in the BP, no write was performed so there will be no
4968 * dva/birth/checksum. The buffer must therefore remain anonymous
4969 * (and uncached).
4970 */
4971 if (!BUF_EMPTY(hdr)) {
4972 arc_buf_hdr_t *exists;
4973 kmutex_t *hash_lock;
4974
4975 ASSERT(zio->io_error == 0);
4976
4977 arc_cksum_verify(buf);
4978
4979 exists = buf_hash_insert(hdr, &hash_lock);
4980 if (exists != NULL) {
4981 /*
4982 * This can only happen if we overwrite for
4983 * sync-to-convergence, because we remove
4984 * buffers from the hash table when we arc_free().
4985 */
4986 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
4987 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
4988 panic("bad overwrite, hdr=%p exists=%p",
4989 (void *)hdr, (void *)exists);
4990 ASSERT(refcount_is_zero(
4991 &exists->b_l1hdr.b_refcnt));
4992 arc_change_state(arc_anon, exists, hash_lock);
4993 mutex_exit(hash_lock);
4994 arc_hdr_destroy(exists);
4995 exists = buf_hash_insert(hdr, &hash_lock);
4996 ASSERT3P(exists, ==, NULL);
4997 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
4998 /* nopwrite */
4999 ASSERT(zio->io_prop.zp_nopwrite);
5000 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5001 panic("bad nopwrite, hdr=%p exists=%p",
5002 (void *)hdr, (void *)exists);
5003 } else {
5004 /* Dedup */
5005 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
5006 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
5007 ASSERT(BP_GET_DEDUP(zio->io_bp));
5008 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
5009 }
5010 }
5011 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
5012 /* if it's not anon, we are doing a scrub */
5013 if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
5014 arc_access(hdr, hash_lock);
5015 mutex_exit(hash_lock);
5016 } else {
5017 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
5018 }
5019
5020 ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5021 callback->awcb_done(zio, buf, callback->awcb_private);
5022
5023 kmem_free(callback, sizeof (arc_write_callback_t));
5024 }
5025
5026 zio_t *
5027 arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
5028 blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
5029 const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *physdone,
5030 arc_done_func_t *done, void *private, zio_priority_t priority,
5031 int zio_flags, const zbookmark_phys_t *zb)
5032 {
5033 arc_buf_hdr_t *hdr = buf->b_hdr;
5034 arc_write_callback_t *callback;
5035 zio_t *zio;
5036
5037 ASSERT(ready != NULL);
5038 ASSERT(done != NULL);
5039 ASSERT(!HDR_IO_ERROR(hdr));
5040 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5041 ASSERT(hdr->b_l1hdr.b_acb == NULL);
5042 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
5043 if (l2arc)
5044 hdr->b_flags |= ARC_FLAG_L2CACHE;
5045 if (l2arc_compress)
5046 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
5047 callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
5048 callback->awcb_ready = ready;
5049 callback->awcb_physdone = physdone;
5050 callback->awcb_done = done;
5051 callback->awcb_private = private;
5052 callback->awcb_buf = buf;
5053
5054 zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
5055 arc_write_ready, arc_write_physdone, arc_write_done, callback,
5056 priority, zio_flags, zb);
5057
5058 return (zio);
5059 }
5060
5061 static int
5062 arc_memory_throttle(uint64_t reserve, uint64_t txg)
5063 {
5064 #ifdef _KERNEL
5065 if (zfs_arc_memory_throttle_disable)
5066 return (0);
5067
5068 if (freemem > physmem * arc_lotsfree_percent / 100)
5069 return (0);
5070
5071 if (arc_reclaim_needed()) {
5072 /* memory is low, delay before restarting */
5073 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
5074 DMU_TX_STAT_BUMP(dmu_tx_memory_reclaim);
5075 return (SET_ERROR(EAGAIN));
5076 }
5077 #endif
5078 return (0);
5079 }
5080
5081 void
5082 arc_tempreserve_clear(uint64_t reserve)
5083 {
5084 atomic_add_64(&arc_tempreserve, -reserve);
5085 ASSERT((int64_t)arc_tempreserve >= 0);
5086 }
5087
5088 int
5089 arc_tempreserve_space(uint64_t reserve, uint64_t txg)
5090 {
5091 int error;
5092 uint64_t anon_size;
5093
5094 if (reserve > arc_c/4 && !arc_no_grow)
5095 arc_c = MIN(arc_c_max, reserve * 4);
5096
5097 /*
5098 * Throttle when the calculated memory footprint for the TXG
5099 * exceeds the target ARC size.
5100 */
5101 if (reserve > arc_c) {
5102 DMU_TX_STAT_BUMP(dmu_tx_memory_reserve);
5103 return (SET_ERROR(ERESTART));
5104 }
5105
5106 /*
5107 * Don't count loaned bufs as in flight dirty data to prevent long
5108 * network delays from blocking transactions that are ready to be
5109 * assigned to a txg.
5110 */
5111 anon_size = MAX((int64_t)(refcount_count(&arc_anon->arcs_size) -
5112 arc_loaned_bytes), 0);
5113
5114 /*
5115 * Writes will, almost always, require additional memory allocations
5116 * in order to compress/encrypt/etc the data. We therefore need to
5117 * make sure that there is sufficient available memory for this.
5118 */
5119 error = arc_memory_throttle(reserve, txg);
5120 if (error != 0)
5121 return (error);
5122
5123 /*
5124 * Throttle writes when the amount of dirty data in the cache
5125 * gets too large. We try to keep the cache less than half full
5126 * of dirty blocks so that our sync times don't grow too large.
5127 * Note: if two requests come in concurrently, we might let them
5128 * both succeed, when one of them should fail. Not a huge deal.
5129 */
5130
5131 if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
5132 anon_size > arc_c / 4) {
5133 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
5134 "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
5135 arc_tempreserve>>10,
5136 arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
5137 arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
5138 reserve>>10, arc_c>>10);
5139 DMU_TX_STAT_BUMP(dmu_tx_dirty_throttle);
5140 return (SET_ERROR(ERESTART));
5141 }
5142 atomic_add_64(&arc_tempreserve, reserve);
5143 return (0);
5144 }
5145
5146 static void
5147 arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
5148 kstat_named_t *evict_data, kstat_named_t *evict_metadata)
5149 {
5150 size->value.ui64 = refcount_count(&state->arcs_size);
5151 evict_data->value.ui64 = state->arcs_lsize[ARC_BUFC_DATA];
5152 evict_metadata->value.ui64 = state->arcs_lsize[ARC_BUFC_METADATA];
5153 }
5154
5155 static int
5156 arc_kstat_update(kstat_t *ksp, int rw)
5157 {
5158 arc_stats_t *as = ksp->ks_data;
5159
5160 if (rw == KSTAT_WRITE) {
5161 return (EACCES);
5162 } else {
5163 arc_kstat_update_state(arc_anon,
5164 &as->arcstat_anon_size,
5165 &as->arcstat_anon_evictable_data,
5166 &as->arcstat_anon_evictable_metadata);
5167 arc_kstat_update_state(arc_mru,
5168 &as->arcstat_mru_size,
5169 &as->arcstat_mru_evictable_data,
5170 &as->arcstat_mru_evictable_metadata);
5171 arc_kstat_update_state(arc_mru_ghost,
5172 &as->arcstat_mru_ghost_size,
5173 &as->arcstat_mru_ghost_evictable_data,
5174 &as->arcstat_mru_ghost_evictable_metadata);
5175 arc_kstat_update_state(arc_mfu,
5176 &as->arcstat_mfu_size,
5177 &as->arcstat_mfu_evictable_data,
5178 &as->arcstat_mfu_evictable_metadata);
5179 arc_kstat_update_state(arc_mfu_ghost,
5180 &as->arcstat_mfu_ghost_size,
5181 &as->arcstat_mfu_ghost_evictable_data,
5182 &as->arcstat_mfu_ghost_evictable_metadata);
5183 }
5184
5185 return (0);
5186 }
5187
5188 /*
5189 * This function *must* return indices evenly distributed between all
5190 * sublists of the multilist. This is needed due to how the ARC eviction
5191 * code is laid out; arc_evict_state() assumes ARC buffers are evenly
5192 * distributed between all sublists and uses this assumption when
5193 * deciding which sublist to evict from and how much to evict from it.
5194 */
5195 unsigned int
5196 arc_state_multilist_index_func(multilist_t *ml, void *obj)
5197 {
5198 arc_buf_hdr_t *hdr = obj;
5199
5200 /*
5201 * We rely on b_dva to generate evenly distributed index
5202 * numbers using buf_hash below. So, as an added precaution,
5203 * let's make sure we never add empty buffers to the arc lists.
5204 */
5205 ASSERT(!BUF_EMPTY(hdr));
5206
5207 /*
5208 * The assumption here, is the hash value for a given
5209 * arc_buf_hdr_t will remain constant throughout its lifetime
5210 * (i.e. its b_spa, b_dva, and b_birth fields don't change).
5211 * Thus, we don't need to store the header's sublist index
5212 * on insertion, as this index can be recalculated on removal.
5213 *
5214 * Also, the low order bits of the hash value are thought to be
5215 * distributed evenly. Otherwise, in the case that the multilist
5216 * has a power of two number of sublists, each sublists' usage
5217 * would not be evenly distributed.
5218 */
5219 return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
5220 multilist_get_num_sublists(ml));
5221 }
5222
5223 /*
5224 * Called during module initialization and periodically thereafter to
5225 * apply reasonable changes to the exposed performance tunings. Non-zero
5226 * zfs_* values which differ from the currently set values will be applied.
5227 */
5228 static void
5229 arc_tuning_update(void)
5230 {
5231 /* Valid range: 64M - <all physical memory> */
5232 if ((zfs_arc_max) && (zfs_arc_max != arc_c_max) &&
5233 (zfs_arc_max > 64 << 20) && (zfs_arc_max < ptob(physmem)) &&
5234 (zfs_arc_max > arc_c_min)) {
5235 arc_c_max = zfs_arc_max;
5236 arc_c = arc_c_max;
5237 arc_p = (arc_c >> 1);
5238 arc_meta_limit = MIN(arc_meta_limit, arc_c_max);
5239 }
5240
5241 /* Valid range: 32M - <arc_c_max> */
5242 if ((zfs_arc_min) && (zfs_arc_min != arc_c_min) &&
5243 (zfs_arc_min >= 2ULL << SPA_MAXBLOCKSHIFT) &&
5244 (zfs_arc_min <= arc_c_max)) {
5245 arc_c_min = zfs_arc_min;
5246 arc_c = MAX(arc_c, arc_c_min);
5247 }
5248
5249 /* Valid range: 16M - <arc_c_max> */
5250 if ((zfs_arc_meta_min) && (zfs_arc_meta_min != arc_meta_min) &&
5251 (zfs_arc_meta_min >= 1ULL << SPA_MAXBLOCKSHIFT) &&
5252 (zfs_arc_meta_min <= arc_c_max)) {
5253 arc_meta_min = zfs_arc_meta_min;
5254 arc_meta_limit = MAX(arc_meta_limit, arc_meta_min);
5255 }
5256
5257 /* Valid range: <arc_meta_min> - <arc_c_max> */
5258 if ((zfs_arc_meta_limit) && (zfs_arc_meta_limit != arc_meta_limit) &&
5259 (zfs_arc_meta_limit >= zfs_arc_meta_min) &&
5260 (zfs_arc_meta_limit <= arc_c_max))
5261 arc_meta_limit = zfs_arc_meta_limit;
5262
5263 /* Valid range: 1 - N */
5264 if (zfs_arc_grow_retry)
5265 arc_grow_retry = zfs_arc_grow_retry;
5266
5267 /* Valid range: 1 - N */
5268 if (zfs_arc_shrink_shift) {
5269 arc_shrink_shift = zfs_arc_shrink_shift;
5270 arc_no_grow_shift = MIN(arc_no_grow_shift, arc_shrink_shift -1);
5271 }
5272
5273 /* Valid range: 1 - N */
5274 if (zfs_arc_p_min_shift)
5275 arc_p_min_shift = zfs_arc_p_min_shift;
5276
5277 /* Valid range: 1 - N ticks */
5278 if (zfs_arc_min_prefetch_lifespan)
5279 arc_min_prefetch_lifespan = zfs_arc_min_prefetch_lifespan;
5280 }
5281
5282 void
5283 arc_init(void)
5284 {
5285 /*
5286 * allmem is "all memory that we could possibly use".
5287 */
5288 #ifdef _KERNEL
5289 uint64_t allmem = ptob(physmem);
5290 #else
5291 uint64_t allmem = (physmem * PAGESIZE) / 2;
5292 #endif
5293
5294 mutex_init(&arc_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
5295 cv_init(&arc_reclaim_thread_cv, NULL, CV_DEFAULT, NULL);
5296 cv_init(&arc_reclaim_waiters_cv, NULL, CV_DEFAULT, NULL);
5297
5298 mutex_init(&arc_user_evicts_lock, NULL, MUTEX_DEFAULT, NULL);
5299 cv_init(&arc_user_evicts_cv, NULL, CV_DEFAULT, NULL);
5300
5301 /* Convert seconds to clock ticks */
5302 arc_min_prefetch_lifespan = 1 * hz;
5303
5304 /* Start out with 1/8 of all memory */
5305 arc_c = allmem / 8;
5306
5307 #ifdef _KERNEL
5308 /*
5309 * On architectures where the physical memory can be larger
5310 * than the addressable space (intel in 32-bit mode), we may
5311 * need to limit the cache to 1/8 of VM size.
5312 */
5313 arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
5314
5315 /*
5316 * Register a shrinker to support synchronous (direct) memory
5317 * reclaim from the arc. This is done to prevent kswapd from
5318 * swapping out pages when it is preferable to shrink the arc.
5319 */
5320 spl_register_shrinker(&arc_shrinker);
5321 #endif
5322
5323 /* Set min cache to allow safe operation of arc_adapt() */
5324 arc_c_min = 2ULL << SPA_MAXBLOCKSHIFT;
5325 /* Set max to 1/2 of all memory */
5326 arc_c_max = allmem / 2;
5327
5328 arc_c = arc_c_max;
5329 arc_p = (arc_c >> 1);
5330
5331 /* Set min to 1/2 of arc_c_min */
5332 arc_meta_min = 1ULL << SPA_MAXBLOCKSHIFT;
5333 /* Initialize maximum observed usage to zero */
5334 arc_meta_max = 0;
5335 /* Set limit to 3/4 of arc_c_max with a floor of arc_meta_min */
5336 arc_meta_limit = MAX((3 * arc_c_max) / 4, arc_meta_min);
5337
5338 /* Apply user specified tunings */
5339 arc_tuning_update();
5340
5341 if (zfs_arc_num_sublists_per_state < 1)
5342 zfs_arc_num_sublists_per_state = MAX(boot_ncpus, 1);
5343
5344 /* if kmem_flags are set, lets try to use less memory */
5345 if (kmem_debugging())
5346 arc_c = arc_c / 2;
5347 if (arc_c < arc_c_min)
5348 arc_c = arc_c_min;
5349
5350 arc_anon = &ARC_anon;
5351 arc_mru = &ARC_mru;
5352 arc_mru_ghost = &ARC_mru_ghost;
5353 arc_mfu = &ARC_mfu;
5354 arc_mfu_ghost = &ARC_mfu_ghost;
5355 arc_l2c_only = &ARC_l2c_only;
5356 arc_size = 0;
5357
5358 multilist_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
5359 sizeof (arc_buf_hdr_t),
5360 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5361 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5362 multilist_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
5363 sizeof (arc_buf_hdr_t),
5364 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5365 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5366 multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
5367 sizeof (arc_buf_hdr_t),
5368 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5369 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5370 multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
5371 sizeof (arc_buf_hdr_t),
5372 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5373 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5374 multilist_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
5375 sizeof (arc_buf_hdr_t),
5376 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5377 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5378 multilist_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
5379 sizeof (arc_buf_hdr_t),
5380 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5381 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5382 multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
5383 sizeof (arc_buf_hdr_t),
5384 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5385 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5386 multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
5387 sizeof (arc_buf_hdr_t),
5388 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5389 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5390 multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
5391 sizeof (arc_buf_hdr_t),
5392 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5393 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5394 multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
5395 sizeof (arc_buf_hdr_t),
5396 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5397 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5398
5399 arc_anon->arcs_state = ARC_STATE_ANON;
5400 arc_mru->arcs_state = ARC_STATE_MRU;
5401 arc_mru_ghost->arcs_state = ARC_STATE_MRU_GHOST;
5402 arc_mfu->arcs_state = ARC_STATE_MFU;
5403 arc_mfu_ghost->arcs_state = ARC_STATE_MFU_GHOST;
5404 arc_l2c_only->arcs_state = ARC_STATE_L2C_ONLY;
5405
5406 refcount_create(&arc_anon->arcs_size);
5407 refcount_create(&arc_mru->arcs_size);
5408 refcount_create(&arc_mru_ghost->arcs_size);
5409 refcount_create(&arc_mfu->arcs_size);
5410 refcount_create(&arc_mfu_ghost->arcs_size);
5411 refcount_create(&arc_l2c_only->arcs_size);
5412
5413 buf_init();
5414
5415 arc_reclaim_thread_exit = FALSE;
5416 arc_user_evicts_thread_exit = FALSE;
5417 list_create(&arc_prune_list, sizeof (arc_prune_t),
5418 offsetof(arc_prune_t, p_node));
5419 arc_eviction_list = NULL;
5420 mutex_init(&arc_prune_mtx, NULL, MUTEX_DEFAULT, NULL);
5421 bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
5422
5423 arc_prune_taskq = taskq_create("arc_prune", max_ncpus, minclsyspri,
5424 max_ncpus, INT_MAX, TASKQ_PREPOPULATE | TASKQ_DYNAMIC);
5425
5426 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
5427 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
5428
5429 if (arc_ksp != NULL) {
5430 arc_ksp->ks_data = &arc_stats;
5431 arc_ksp->ks_update = arc_kstat_update;
5432 kstat_install(arc_ksp);
5433 }
5434
5435 (void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
5436 TS_RUN, minclsyspri);
5437
5438 (void) thread_create(NULL, 0, arc_user_evicts_thread, NULL, 0, &p0,
5439 TS_RUN, minclsyspri);
5440
5441 arc_dead = FALSE;
5442 arc_warm = B_FALSE;
5443
5444 /*
5445 * Calculate maximum amount of dirty data per pool.
5446 *
5447 * If it has been set by a module parameter, take that.
5448 * Otherwise, use a percentage of physical memory defined by
5449 * zfs_dirty_data_max_percent (default 10%) with a cap at
5450 * zfs_dirty_data_max_max (default 25% of physical memory).
5451 */
5452 if (zfs_dirty_data_max_max == 0)
5453 zfs_dirty_data_max_max = physmem * PAGESIZE *
5454 zfs_dirty_data_max_max_percent / 100;
5455
5456 if (zfs_dirty_data_max == 0) {
5457 zfs_dirty_data_max = physmem * PAGESIZE *
5458 zfs_dirty_data_max_percent / 100;
5459 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
5460 zfs_dirty_data_max_max);
5461 }
5462 }
5463
5464 void
5465 arc_fini(void)
5466 {
5467 arc_prune_t *p;
5468
5469 #ifdef _KERNEL
5470 spl_unregister_shrinker(&arc_shrinker);
5471 #endif /* _KERNEL */
5472
5473 mutex_enter(&arc_reclaim_lock);
5474 arc_reclaim_thread_exit = TRUE;
5475 /*
5476 * The reclaim thread will set arc_reclaim_thread_exit back to
5477 * FALSE when it is finished exiting; we're waiting for that.
5478 */
5479 while (arc_reclaim_thread_exit) {
5480 cv_signal(&arc_reclaim_thread_cv);
5481 cv_wait(&arc_reclaim_thread_cv, &arc_reclaim_lock);
5482 }
5483 mutex_exit(&arc_reclaim_lock);
5484
5485 mutex_enter(&arc_user_evicts_lock);
5486 arc_user_evicts_thread_exit = TRUE;
5487 /*
5488 * The user evicts thread will set arc_user_evicts_thread_exit
5489 * to FALSE when it is finished exiting; we're waiting for that.
5490 */
5491 while (arc_user_evicts_thread_exit) {
5492 cv_signal(&arc_user_evicts_cv);
5493 cv_wait(&arc_user_evicts_cv, &arc_user_evicts_lock);
5494 }
5495 mutex_exit(&arc_user_evicts_lock);
5496
5497 /* Use TRUE to ensure *all* buffers are evicted */
5498 arc_flush(NULL, TRUE);
5499
5500 arc_dead = TRUE;
5501
5502 if (arc_ksp != NULL) {
5503 kstat_delete(arc_ksp);
5504 arc_ksp = NULL;
5505 }
5506
5507 taskq_wait(arc_prune_taskq);
5508 taskq_destroy(arc_prune_taskq);
5509
5510 mutex_enter(&arc_prune_mtx);
5511 while ((p = list_head(&arc_prune_list)) != NULL) {
5512 list_remove(&arc_prune_list, p);
5513 refcount_remove(&p->p_refcnt, &arc_prune_list);
5514 refcount_destroy(&p->p_refcnt);
5515 kmem_free(p, sizeof (*p));
5516 }
5517 mutex_exit(&arc_prune_mtx);
5518
5519 list_destroy(&arc_prune_list);
5520 mutex_destroy(&arc_prune_mtx);
5521 mutex_destroy(&arc_reclaim_lock);
5522 cv_destroy(&arc_reclaim_thread_cv);
5523 cv_destroy(&arc_reclaim_waiters_cv);
5524
5525 mutex_destroy(&arc_user_evicts_lock);
5526 cv_destroy(&arc_user_evicts_cv);
5527
5528 refcount_destroy(&arc_anon->arcs_size);
5529 refcount_destroy(&arc_mru->arcs_size);
5530 refcount_destroy(&arc_mru_ghost->arcs_size);
5531 refcount_destroy(&arc_mfu->arcs_size);
5532 refcount_destroy(&arc_mfu_ghost->arcs_size);
5533 refcount_destroy(&arc_l2c_only->arcs_size);
5534
5535 multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
5536 multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
5537 multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
5538 multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
5539 multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
5540 multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
5541 multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
5542 multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
5543 multilist_destroy(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA]);
5544 multilist_destroy(&arc_l2c_only->arcs_list[ARC_BUFC_DATA]);
5545
5546 buf_fini();
5547
5548 ASSERT0(arc_loaned_bytes);
5549 }
5550
5551 /*
5552 * Level 2 ARC
5553 *
5554 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
5555 * It uses dedicated storage devices to hold cached data, which are populated
5556 * using large infrequent writes. The main role of this cache is to boost
5557 * the performance of random read workloads. The intended L2ARC devices
5558 * include short-stroked disks, solid state disks, and other media with
5559 * substantially faster read latency than disk.
5560 *
5561 * +-----------------------+
5562 * | ARC |
5563 * +-----------------------+
5564 * | ^ ^
5565 * | | |
5566 * l2arc_feed_thread() arc_read()
5567 * | | |
5568 * | l2arc read |
5569 * V | |
5570 * +---------------+ |
5571 * | L2ARC | |
5572 * +---------------+ |
5573 * | ^ |
5574 * l2arc_write() | |
5575 * | | |
5576 * V | |
5577 * +-------+ +-------+
5578 * | vdev | | vdev |
5579 * | cache | | cache |
5580 * +-------+ +-------+
5581 * +=========+ .-----.
5582 * : L2ARC : |-_____-|
5583 * : devices : | Disks |
5584 * +=========+ `-_____-'
5585 *
5586 * Read requests are satisfied from the following sources, in order:
5587 *
5588 * 1) ARC
5589 * 2) vdev cache of L2ARC devices
5590 * 3) L2ARC devices
5591 * 4) vdev cache of disks
5592 * 5) disks
5593 *
5594 * Some L2ARC device types exhibit extremely slow write performance.
5595 * To accommodate for this there are some significant differences between
5596 * the L2ARC and traditional cache design:
5597 *
5598 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
5599 * the ARC behave as usual, freeing buffers and placing headers on ghost
5600 * lists. The ARC does not send buffers to the L2ARC during eviction as
5601 * this would add inflated write latencies for all ARC memory pressure.
5602 *
5603 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
5604 * It does this by periodically scanning buffers from the eviction-end of
5605 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
5606 * not already there. It scans until a headroom of buffers is satisfied,
5607 * which itself is a buffer for ARC eviction. If a compressible buffer is
5608 * found during scanning and selected for writing to an L2ARC device, we
5609 * temporarily boost scanning headroom during the next scan cycle to make
5610 * sure we adapt to compression effects (which might significantly reduce
5611 * the data volume we write to L2ARC). The thread that does this is
5612 * l2arc_feed_thread(), illustrated below; example sizes are included to
5613 * provide a better sense of ratio than this diagram:
5614 *
5615 * head --> tail
5616 * +---------------------+----------+
5617 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
5618 * +---------------------+----------+ | o L2ARC eligible
5619 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
5620 * +---------------------+----------+ |
5621 * 15.9 Gbytes ^ 32 Mbytes |
5622 * headroom |
5623 * l2arc_feed_thread()
5624 * |
5625 * l2arc write hand <--[oooo]--'
5626 * | 8 Mbyte
5627 * | write max
5628 * V
5629 * +==============================+
5630 * L2ARC dev |####|#|###|###| |####| ... |
5631 * +==============================+
5632 * 32 Gbytes
5633 *
5634 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
5635 * evicted, then the L2ARC has cached a buffer much sooner than it probably
5636 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
5637 * safe to say that this is an uncommon case, since buffers at the end of
5638 * the ARC lists have moved there due to inactivity.
5639 *
5640 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
5641 * then the L2ARC simply misses copying some buffers. This serves as a
5642 * pressure valve to prevent heavy read workloads from both stalling the ARC
5643 * with waits and clogging the L2ARC with writes. This also helps prevent
5644 * the potential for the L2ARC to churn if it attempts to cache content too
5645 * quickly, such as during backups of the entire pool.
5646 *
5647 * 5. After system boot and before the ARC has filled main memory, there are
5648 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
5649 * lists can remain mostly static. Instead of searching from tail of these
5650 * lists as pictured, the l2arc_feed_thread() will search from the list heads
5651 * for eligible buffers, greatly increasing its chance of finding them.
5652 *
5653 * The L2ARC device write speed is also boosted during this time so that
5654 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
5655 * there are no L2ARC reads, and no fear of degrading read performance
5656 * through increased writes.
5657 *
5658 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
5659 * the vdev queue can aggregate them into larger and fewer writes. Each
5660 * device is written to in a rotor fashion, sweeping writes through
5661 * available space then repeating.
5662 *
5663 * 7. The L2ARC does not store dirty content. It never needs to flush
5664 * write buffers back to disk based storage.
5665 *
5666 * 8. If an ARC buffer is written (and dirtied) which also exists in the
5667 * L2ARC, the now stale L2ARC buffer is immediately dropped.
5668 *
5669 * The performance of the L2ARC can be tweaked by a number of tunables, which
5670 * may be necessary for different workloads:
5671 *
5672 * l2arc_write_max max write bytes per interval
5673 * l2arc_write_boost extra write bytes during device warmup
5674 * l2arc_noprefetch skip caching prefetched buffers
5675 * l2arc_nocompress skip compressing buffers
5676 * l2arc_headroom number of max device writes to precache
5677 * l2arc_headroom_boost when we find compressed buffers during ARC
5678 * scanning, we multiply headroom by this
5679 * percentage factor for the next scan cycle,
5680 * since more compressed buffers are likely to
5681 * be present
5682 * l2arc_feed_secs seconds between L2ARC writing
5683 *
5684 * Tunables may be removed or added as future performance improvements are
5685 * integrated, and also may become zpool properties.
5686 *
5687 * There are three key functions that control how the L2ARC warms up:
5688 *
5689 * l2arc_write_eligible() check if a buffer is eligible to cache
5690 * l2arc_write_size() calculate how much to write
5691 * l2arc_write_interval() calculate sleep delay between writes
5692 *
5693 * These three functions determine what to write, how much, and how quickly
5694 * to send writes.
5695 */
5696
5697 static boolean_t
5698 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
5699 {
5700 /*
5701 * A buffer is *not* eligible for the L2ARC if it:
5702 * 1. belongs to a different spa.
5703 * 2. is already cached on the L2ARC.
5704 * 3. has an I/O in progress (it may be an incomplete read).
5705 * 4. is flagged not eligible (zfs property).
5706 */
5707 if (hdr->b_spa != spa_guid || HDR_HAS_L2HDR(hdr) ||
5708 HDR_IO_IN_PROGRESS(hdr) || !HDR_L2CACHE(hdr))
5709 return (B_FALSE);
5710
5711 return (B_TRUE);
5712 }
5713
5714 static uint64_t
5715 l2arc_write_size(void)
5716 {
5717 uint64_t size;
5718
5719 /*
5720 * Make sure our globals have meaningful values in case the user
5721 * altered them.
5722 */
5723 size = l2arc_write_max;
5724 if (size == 0) {
5725 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
5726 "be greater than zero, resetting it to the default (%d)",
5727 L2ARC_WRITE_SIZE);
5728 size = l2arc_write_max = L2ARC_WRITE_SIZE;
5729 }
5730
5731 if (arc_warm == B_FALSE)
5732 size += l2arc_write_boost;
5733
5734 return (size);
5735
5736 }
5737
5738 static clock_t
5739 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
5740 {
5741 clock_t interval, next, now;
5742
5743 /*
5744 * If the ARC lists are busy, increase our write rate; if the
5745 * lists are stale, idle back. This is achieved by checking
5746 * how much we previously wrote - if it was more than half of
5747 * what we wanted, schedule the next write much sooner.
5748 */
5749 if (l2arc_feed_again && wrote > (wanted / 2))
5750 interval = (hz * l2arc_feed_min_ms) / 1000;
5751 else
5752 interval = hz * l2arc_feed_secs;
5753
5754 now = ddi_get_lbolt();
5755 next = MAX(now, MIN(now + interval, began + interval));
5756
5757 return (next);
5758 }
5759
5760 /*
5761 * Cycle through L2ARC devices. This is how L2ARC load balances.
5762 * If a device is returned, this also returns holding the spa config lock.
5763 */
5764 static l2arc_dev_t *
5765 l2arc_dev_get_next(void)
5766 {
5767 l2arc_dev_t *first, *next = NULL;
5768
5769 /*
5770 * Lock out the removal of spas (spa_namespace_lock), then removal
5771 * of cache devices (l2arc_dev_mtx). Once a device has been selected,
5772 * both locks will be dropped and a spa config lock held instead.
5773 */
5774 mutex_enter(&spa_namespace_lock);
5775 mutex_enter(&l2arc_dev_mtx);
5776
5777 /* if there are no vdevs, there is nothing to do */
5778 if (l2arc_ndev == 0)
5779 goto out;
5780
5781 first = NULL;
5782 next = l2arc_dev_last;
5783 do {
5784 /* loop around the list looking for a non-faulted vdev */
5785 if (next == NULL) {
5786 next = list_head(l2arc_dev_list);
5787 } else {
5788 next = list_next(l2arc_dev_list, next);
5789 if (next == NULL)
5790 next = list_head(l2arc_dev_list);
5791 }
5792
5793 /* if we have come back to the start, bail out */
5794 if (first == NULL)
5795 first = next;
5796 else if (next == first)
5797 break;
5798
5799 } while (vdev_is_dead(next->l2ad_vdev));
5800
5801 /* if we were unable to find any usable vdevs, return NULL */
5802 if (vdev_is_dead(next->l2ad_vdev))
5803 next = NULL;
5804
5805 l2arc_dev_last = next;
5806
5807 out:
5808 mutex_exit(&l2arc_dev_mtx);
5809
5810 /*
5811 * Grab the config lock to prevent the 'next' device from being
5812 * removed while we are writing to it.
5813 */
5814 if (next != NULL)
5815 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
5816 mutex_exit(&spa_namespace_lock);
5817
5818 return (next);
5819 }
5820
5821 /*
5822 * Free buffers that were tagged for destruction.
5823 */
5824 static void
5825 l2arc_do_free_on_write(void)
5826 {
5827 list_t *buflist;
5828 l2arc_data_free_t *df, *df_prev;
5829
5830 mutex_enter(&l2arc_free_on_write_mtx);
5831 buflist = l2arc_free_on_write;
5832
5833 for (df = list_tail(buflist); df; df = df_prev) {
5834 df_prev = list_prev(buflist, df);
5835 ASSERT(df->l2df_data != NULL);
5836 ASSERT(df->l2df_func != NULL);
5837 df->l2df_func(df->l2df_data, df->l2df_size);
5838 list_remove(buflist, df);
5839 kmem_free(df, sizeof (l2arc_data_free_t));
5840 }
5841
5842 mutex_exit(&l2arc_free_on_write_mtx);
5843 }
5844
5845 /*
5846 * A write to a cache device has completed. Update all headers to allow
5847 * reads from these buffers to begin.
5848 */
5849 static void
5850 l2arc_write_done(zio_t *zio)
5851 {
5852 l2arc_write_callback_t *cb;
5853 l2arc_dev_t *dev;
5854 list_t *buflist;
5855 arc_buf_hdr_t *head, *hdr, *hdr_prev;
5856 kmutex_t *hash_lock;
5857 int64_t bytes_dropped = 0;
5858
5859 cb = zio->io_private;
5860 ASSERT(cb != NULL);
5861 dev = cb->l2wcb_dev;
5862 ASSERT(dev != NULL);
5863 head = cb->l2wcb_head;
5864 ASSERT(head != NULL);
5865 buflist = &dev->l2ad_buflist;
5866 ASSERT(buflist != NULL);
5867 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
5868 l2arc_write_callback_t *, cb);
5869
5870 if (zio->io_error != 0)
5871 ARCSTAT_BUMP(arcstat_l2_writes_error);
5872
5873 /*
5874 * All writes completed, or an error was hit.
5875 */
5876 top:
5877 mutex_enter(&dev->l2ad_mtx);
5878 for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
5879 hdr_prev = list_prev(buflist, hdr);
5880
5881 hash_lock = HDR_LOCK(hdr);
5882
5883 /*
5884 * We cannot use mutex_enter or else we can deadlock
5885 * with l2arc_write_buffers (due to swapping the order
5886 * the hash lock and l2ad_mtx are taken).
5887 */
5888 if (!mutex_tryenter(hash_lock)) {
5889 /*
5890 * Missed the hash lock. We must retry so we
5891 * don't leave the ARC_FLAG_L2_WRITING bit set.
5892 */
5893 ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
5894
5895 /*
5896 * We don't want to rescan the headers we've
5897 * already marked as having been written out, so
5898 * we reinsert the head node so we can pick up
5899 * where we left off.
5900 */
5901 list_remove(buflist, head);
5902 list_insert_after(buflist, hdr, head);
5903
5904 mutex_exit(&dev->l2ad_mtx);
5905
5906 /*
5907 * We wait for the hash lock to become available
5908 * to try and prevent busy waiting, and increase
5909 * the chance we'll be able to acquire the lock
5910 * the next time around.
5911 */
5912 mutex_enter(hash_lock);
5913 mutex_exit(hash_lock);
5914 goto top;
5915 }
5916
5917 /*
5918 * We could not have been moved into the arc_l2c_only
5919 * state while in-flight due to our ARC_FLAG_L2_WRITING
5920 * bit being set. Let's just ensure that's being enforced.
5921 */
5922 ASSERT(HDR_HAS_L1HDR(hdr));
5923
5924 /*
5925 * We may have allocated a buffer for L2ARC compression,
5926 * we must release it to avoid leaking this data.
5927 */
5928 l2arc_release_cdata_buf(hdr);
5929
5930 if (zio->io_error != 0) {
5931 /*
5932 * Error - drop L2ARC entry.
5933 */
5934 list_remove(buflist, hdr);
5935 hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
5936
5937 ARCSTAT_INCR(arcstat_l2_asize, -hdr->b_l2hdr.b_asize);
5938 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
5939
5940 bytes_dropped += hdr->b_l2hdr.b_asize;
5941 (void) refcount_remove_many(&dev->l2ad_alloc,
5942 hdr->b_l2hdr.b_asize, hdr);
5943 }
5944
5945 /*
5946 * Allow ARC to begin reads and ghost list evictions to
5947 * this L2ARC entry.
5948 */
5949 hdr->b_flags &= ~ARC_FLAG_L2_WRITING;
5950
5951 mutex_exit(hash_lock);
5952 }
5953
5954 atomic_inc_64(&l2arc_writes_done);
5955 list_remove(buflist, head);
5956 ASSERT(!HDR_HAS_L1HDR(head));
5957 kmem_cache_free(hdr_l2only_cache, head);
5958 mutex_exit(&dev->l2ad_mtx);
5959
5960 vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
5961
5962 l2arc_do_free_on_write();
5963
5964 kmem_free(cb, sizeof (l2arc_write_callback_t));
5965 }
5966
5967 /*
5968 * A read to a cache device completed. Validate buffer contents before
5969 * handing over to the regular ARC routines.
5970 */
5971 static void
5972 l2arc_read_done(zio_t *zio)
5973 {
5974 l2arc_read_callback_t *cb;
5975 arc_buf_hdr_t *hdr;
5976 arc_buf_t *buf;
5977 kmutex_t *hash_lock;
5978 int equal;
5979
5980 ASSERT(zio->io_vd != NULL);
5981 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
5982
5983 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
5984
5985 cb = zio->io_private;
5986 ASSERT(cb != NULL);
5987 buf = cb->l2rcb_buf;
5988 ASSERT(buf != NULL);
5989
5990 hash_lock = HDR_LOCK(buf->b_hdr);
5991 mutex_enter(hash_lock);
5992 hdr = buf->b_hdr;
5993 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
5994
5995 /*
5996 * If the buffer was compressed, decompress it first.
5997 */
5998 if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
5999 l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
6000 ASSERT(zio->io_data != NULL);
6001
6002 /*
6003 * Check this survived the L2ARC journey.
6004 */
6005 equal = arc_cksum_equal(buf);
6006 if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
6007 mutex_exit(hash_lock);
6008 zio->io_private = buf;
6009 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
6010 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
6011 arc_read_done(zio);
6012 } else {
6013 mutex_exit(hash_lock);
6014 /*
6015 * Buffer didn't survive caching. Increment stats and
6016 * reissue to the original storage device.
6017 */
6018 if (zio->io_error != 0) {
6019 ARCSTAT_BUMP(arcstat_l2_io_error);
6020 } else {
6021 zio->io_error = SET_ERROR(EIO);
6022 }
6023 if (!equal)
6024 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
6025
6026 /*
6027 * If there's no waiter, issue an async i/o to the primary
6028 * storage now. If there *is* a waiter, the caller must
6029 * issue the i/o in a context where it's OK to block.
6030 */
6031 if (zio->io_waiter == NULL) {
6032 zio_t *pio = zio_unique_parent(zio);
6033
6034 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
6035
6036 zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
6037 buf->b_data, zio->io_size, arc_read_done, buf,
6038 zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
6039 }
6040 }
6041
6042 kmem_free(cb, sizeof (l2arc_read_callback_t));
6043 }
6044
6045 /*
6046 * This is the list priority from which the L2ARC will search for pages to
6047 * cache. This is used within loops (0..3) to cycle through lists in the
6048 * desired order. This order can have a significant effect on cache
6049 * performance.
6050 *
6051 * Currently the metadata lists are hit first, MFU then MRU, followed by
6052 * the data lists. This function returns a locked list, and also returns
6053 * the lock pointer.
6054 */
6055 static multilist_sublist_t *
6056 l2arc_sublist_lock(int list_num)
6057 {
6058 multilist_t *ml = NULL;
6059 unsigned int idx;
6060
6061 ASSERT(list_num >= 0 && list_num <= 3);
6062
6063 switch (list_num) {
6064 case 0:
6065 ml = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
6066 break;
6067 case 1:
6068 ml = &arc_mru->arcs_list[ARC_BUFC_METADATA];
6069 break;
6070 case 2:
6071 ml = &arc_mfu->arcs_list[ARC_BUFC_DATA];
6072 break;
6073 case 3:
6074 ml = &arc_mru->arcs_list[ARC_BUFC_DATA];
6075 break;
6076 }
6077
6078 /*
6079 * Return a randomly-selected sublist. This is acceptable
6080 * because the caller feeds only a little bit of data for each
6081 * call (8MB). Subsequent calls will result in different
6082 * sublists being selected.
6083 */
6084 idx = multilist_get_random_index(ml);
6085 return (multilist_sublist_lock(ml, idx));
6086 }
6087
6088 /*
6089 * Evict buffers from the device write hand to the distance specified in
6090 * bytes. This distance may span populated buffers, it may span nothing.
6091 * This is clearing a region on the L2ARC device ready for writing.
6092 * If the 'all' boolean is set, every buffer is evicted.
6093 */
6094 static void
6095 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
6096 {
6097 list_t *buflist;
6098 arc_buf_hdr_t *hdr, *hdr_prev;
6099 kmutex_t *hash_lock;
6100 uint64_t taddr;
6101
6102 buflist = &dev->l2ad_buflist;
6103
6104 if (!all && dev->l2ad_first) {
6105 /*
6106 * This is the first sweep through the device. There is
6107 * nothing to evict.
6108 */
6109 return;
6110 }
6111
6112 if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
6113 /*
6114 * When nearing the end of the device, evict to the end
6115 * before the device write hand jumps to the start.
6116 */
6117 taddr = dev->l2ad_end;
6118 } else {
6119 taddr = dev->l2ad_hand + distance;
6120 }
6121 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
6122 uint64_t, taddr, boolean_t, all);
6123
6124 top:
6125 mutex_enter(&dev->l2ad_mtx);
6126 for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
6127 hdr_prev = list_prev(buflist, hdr);
6128
6129 hash_lock = HDR_LOCK(hdr);
6130
6131 /*
6132 * We cannot use mutex_enter or else we can deadlock
6133 * with l2arc_write_buffers (due to swapping the order
6134 * the hash lock and l2ad_mtx are taken).
6135 */
6136 if (!mutex_tryenter(hash_lock)) {
6137 /*
6138 * Missed the hash lock. Retry.
6139 */
6140 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
6141 mutex_exit(&dev->l2ad_mtx);
6142 mutex_enter(hash_lock);
6143 mutex_exit(hash_lock);
6144 goto top;
6145 }
6146
6147 if (HDR_L2_WRITE_HEAD(hdr)) {
6148 /*
6149 * We hit a write head node. Leave it for
6150 * l2arc_write_done().
6151 */
6152 list_remove(buflist, hdr);
6153 mutex_exit(hash_lock);
6154 continue;
6155 }
6156
6157 if (!all && HDR_HAS_L2HDR(hdr) &&
6158 (hdr->b_l2hdr.b_daddr > taddr ||
6159 hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
6160 /*
6161 * We've evicted to the target address,
6162 * or the end of the device.
6163 */
6164 mutex_exit(hash_lock);
6165 break;
6166 }
6167
6168 ASSERT(HDR_HAS_L2HDR(hdr));
6169 if (!HDR_HAS_L1HDR(hdr)) {
6170 ASSERT(!HDR_L2_READING(hdr));
6171 /*
6172 * This doesn't exist in the ARC. Destroy.
6173 * arc_hdr_destroy() will call list_remove()
6174 * and decrement arcstat_l2_size.
6175 */
6176 arc_change_state(arc_anon, hdr, hash_lock);
6177 arc_hdr_destroy(hdr);
6178 } else {
6179 ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
6180 ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
6181 /*
6182 * Invalidate issued or about to be issued
6183 * reads, since we may be about to write
6184 * over this location.
6185 */
6186 if (HDR_L2_READING(hdr)) {
6187 ARCSTAT_BUMP(arcstat_l2_evict_reading);
6188 hdr->b_flags |= ARC_FLAG_L2_EVICTED;
6189 }
6190
6191 /* Ensure this header has finished being written */
6192 ASSERT(!HDR_L2_WRITING(hdr));
6193 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
6194
6195 arc_hdr_l2hdr_destroy(hdr);
6196 }
6197 mutex_exit(hash_lock);
6198 }
6199 mutex_exit(&dev->l2ad_mtx);
6200 }
6201
6202 /*
6203 * Find and write ARC buffers to the L2ARC device.
6204 *
6205 * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
6206 * for reading until they have completed writing.
6207 * The headroom_boost is an in-out parameter used to maintain headroom boost
6208 * state between calls to this function.
6209 *
6210 * Returns the number of bytes actually written (which may be smaller than
6211 * the delta by which the device hand has changed due to alignment).
6212 */
6213 static uint64_t
6214 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
6215 boolean_t *headroom_boost)
6216 {
6217 arc_buf_hdr_t *hdr, *hdr_prev, *head;
6218 uint64_t write_asize, write_sz, headroom, buf_compress_minsz,
6219 stats_size;
6220 void *buf_data;
6221 boolean_t full;
6222 l2arc_write_callback_t *cb;
6223 zio_t *pio, *wzio;
6224 uint64_t guid = spa_load_guid(spa);
6225 int try;
6226 const boolean_t do_headroom_boost = *headroom_boost;
6227
6228 ASSERT(dev->l2ad_vdev != NULL);
6229
6230 /* Lower the flag now, we might want to raise it again later. */
6231 *headroom_boost = B_FALSE;
6232
6233 pio = NULL;
6234 write_sz = write_asize = 0;
6235 full = B_FALSE;
6236 head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
6237 head->b_flags |= ARC_FLAG_L2_WRITE_HEAD;
6238 head->b_flags |= ARC_FLAG_HAS_L2HDR;
6239
6240 /*
6241 * We will want to try to compress buffers that are at least 2x the
6242 * device sector size.
6243 */
6244 buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
6245
6246 /*
6247 * Copy buffers for L2ARC writing.
6248 */
6249 for (try = 0; try <= 3; try++) {
6250 multilist_sublist_t *mls = l2arc_sublist_lock(try);
6251 uint64_t passed_sz = 0;
6252
6253 /*
6254 * L2ARC fast warmup.
6255 *
6256 * Until the ARC is warm and starts to evict, read from the
6257 * head of the ARC lists rather than the tail.
6258 */
6259 if (arc_warm == B_FALSE)
6260 hdr = multilist_sublist_head(mls);
6261 else
6262 hdr = multilist_sublist_tail(mls);
6263
6264 headroom = target_sz * l2arc_headroom;
6265 if (do_headroom_boost)
6266 headroom = (headroom * l2arc_headroom_boost) / 100;
6267
6268 for (; hdr; hdr = hdr_prev) {
6269 kmutex_t *hash_lock;
6270 uint64_t buf_sz;
6271 uint64_t buf_a_sz;
6272
6273 if (arc_warm == B_FALSE)
6274 hdr_prev = multilist_sublist_next(mls, hdr);
6275 else
6276 hdr_prev = multilist_sublist_prev(mls, hdr);
6277
6278 hash_lock = HDR_LOCK(hdr);
6279 if (!mutex_tryenter(hash_lock)) {
6280 /*
6281 * Skip this buffer rather than waiting.
6282 */
6283 continue;
6284 }
6285
6286 passed_sz += hdr->b_size;
6287 if (passed_sz > headroom) {
6288 /*
6289 * Searched too far.
6290 */
6291 mutex_exit(hash_lock);
6292 break;
6293 }
6294
6295 if (!l2arc_write_eligible(guid, hdr)) {
6296 mutex_exit(hash_lock);
6297 continue;
6298 }
6299
6300 /*
6301 * Assume that the buffer is not going to be compressed
6302 * and could take more space on disk because of a larger
6303 * disk block size.
6304 */
6305 buf_sz = hdr->b_size;
6306 buf_a_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
6307
6308 if ((write_asize + buf_a_sz) > target_sz) {
6309 full = B_TRUE;
6310 mutex_exit(hash_lock);
6311 break;
6312 }
6313
6314 if (pio == NULL) {
6315 /*
6316 * Insert a dummy header on the buflist so
6317 * l2arc_write_done() can find where the
6318 * write buffers begin without searching.
6319 */
6320 mutex_enter(&dev->l2ad_mtx);
6321 list_insert_head(&dev->l2ad_buflist, head);
6322 mutex_exit(&dev->l2ad_mtx);
6323
6324 cb = kmem_alloc(sizeof (l2arc_write_callback_t),
6325 KM_SLEEP);
6326 cb->l2wcb_dev = dev;
6327 cb->l2wcb_head = head;
6328 pio = zio_root(spa, l2arc_write_done, cb,
6329 ZIO_FLAG_CANFAIL);
6330 }
6331
6332 /*
6333 * Create and add a new L2ARC header.
6334 */
6335 hdr->b_l2hdr.b_dev = dev;
6336 arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
6337 hdr->b_flags |= ARC_FLAG_L2_WRITING;
6338 /*
6339 * Temporarily stash the data buffer in b_tmp_cdata.
6340 * The subsequent write step will pick it up from
6341 * there. This is because can't access b_l1hdr.b_buf
6342 * without holding the hash_lock, which we in turn
6343 * can't access without holding the ARC list locks
6344 * (which we want to avoid during compression/writing)
6345 */
6346 HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_OFF);
6347 hdr->b_l2hdr.b_asize = hdr->b_size;
6348 hdr->b_l2hdr.b_hits = 0;
6349 hdr->b_l1hdr.b_tmp_cdata = hdr->b_l1hdr.b_buf->b_data;
6350
6351 /*
6352 * Explicitly set the b_daddr field to a known
6353 * value which means "invalid address". This
6354 * enables us to differentiate which stage of
6355 * l2arc_write_buffers() the particular header
6356 * is in (e.g. this loop, or the one below).
6357 * ARC_FLAG_L2_WRITING is not enough to make
6358 * this distinction, and we need to know in
6359 * order to do proper l2arc vdev accounting in
6360 * arc_release() and arc_hdr_destroy().
6361 *
6362 * Note, we can't use a new flag to distinguish
6363 * the two stages because we don't hold the
6364 * header's hash_lock below, in the second stage
6365 * of this function. Thus, we can't simply
6366 * change the b_flags field to denote that the
6367 * IO has been sent. We can change the b_daddr
6368 * field of the L2 portion, though, since we'll
6369 * be holding the l2ad_mtx; which is why we're
6370 * using it to denote the header's state change.
6371 */
6372 hdr->b_l2hdr.b_daddr = L2ARC_ADDR_UNSET;
6373 hdr->b_flags |= ARC_FLAG_HAS_L2HDR;
6374
6375 mutex_enter(&dev->l2ad_mtx);
6376 list_insert_head(&dev->l2ad_buflist, hdr);
6377 mutex_exit(&dev->l2ad_mtx);
6378
6379 /*
6380 * Compute and store the buffer cksum before
6381 * writing. On debug the cksum is verified first.
6382 */
6383 arc_cksum_verify(hdr->b_l1hdr.b_buf);
6384 arc_cksum_compute(hdr->b_l1hdr.b_buf, B_TRUE);
6385
6386 mutex_exit(hash_lock);
6387
6388 write_sz += buf_sz;
6389 write_asize += buf_a_sz;
6390 }
6391
6392 multilist_sublist_unlock(mls);
6393
6394 if (full == B_TRUE)
6395 break;
6396 }
6397
6398 /* No buffers selected for writing? */
6399 if (pio == NULL) {
6400 ASSERT0(write_sz);
6401 ASSERT(!HDR_HAS_L1HDR(head));
6402 kmem_cache_free(hdr_l2only_cache, head);
6403 return (0);
6404 }
6405
6406 mutex_enter(&dev->l2ad_mtx);
6407
6408 /*
6409 * Note that elsewhere in this file arcstat_l2_asize
6410 * and the used space on l2ad_vdev are updated using b_asize,
6411 * which is not necessarily rounded up to the device block size.
6412 * Too keep accounting consistent we do the same here as well:
6413 * stats_size accumulates the sum of b_asize of the written buffers,
6414 * while write_asize accumulates the sum of b_asize rounded up
6415 * to the device block size.
6416 * The latter sum is used only to validate the corectness of the code.
6417 */
6418 stats_size = 0;
6419 write_asize = 0;
6420
6421 /*
6422 * Now start writing the buffers. We're starting at the write head
6423 * and work backwards, retracing the course of the buffer selector
6424 * loop above.
6425 */
6426 for (hdr = list_prev(&dev->l2ad_buflist, head); hdr;
6427 hdr = list_prev(&dev->l2ad_buflist, hdr)) {
6428 uint64_t buf_sz;
6429
6430 /*
6431 * We rely on the L1 portion of the header below, so
6432 * it's invalid for this header to have been evicted out
6433 * of the ghost cache, prior to being written out. The
6434 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
6435 */
6436 ASSERT(HDR_HAS_L1HDR(hdr));
6437
6438 /*
6439 * We shouldn't need to lock the buffer here, since we flagged
6440 * it as ARC_FLAG_L2_WRITING in the previous step, but we must
6441 * take care to only access its L2 cache parameters. In
6442 * particular, hdr->l1hdr.b_buf may be invalid by now due to
6443 * ARC eviction.
6444 */
6445 hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
6446
6447 if ((!l2arc_nocompress && HDR_L2COMPRESS(hdr)) &&
6448 hdr->b_l2hdr.b_asize >= buf_compress_minsz) {
6449 if (l2arc_compress_buf(hdr)) {
6450 /*
6451 * If compression succeeded, enable headroom
6452 * boost on the next scan cycle.
6453 */
6454 *headroom_boost = B_TRUE;
6455 }
6456 }
6457
6458 /*
6459 * Pick up the buffer data we had previously stashed away
6460 * (and now potentially also compressed).
6461 */
6462 buf_data = hdr->b_l1hdr.b_tmp_cdata;
6463 buf_sz = hdr->b_l2hdr.b_asize;
6464
6465 /*
6466 * We need to do this regardless if buf_sz is zero or
6467 * not, otherwise, when this l2hdr is evicted we'll
6468 * remove a reference that was never added.
6469 */
6470 (void) refcount_add_many(&dev->l2ad_alloc, buf_sz, hdr);
6471
6472 /* Compression may have squashed the buffer to zero length. */
6473 if (buf_sz != 0) {
6474 uint64_t buf_a_sz;
6475
6476 wzio = zio_write_phys(pio, dev->l2ad_vdev,
6477 dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
6478 NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
6479 ZIO_FLAG_CANFAIL, B_FALSE);
6480
6481 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
6482 zio_t *, wzio);
6483 (void) zio_nowait(wzio);
6484
6485 stats_size += buf_sz;
6486
6487 /*
6488 * Keep the clock hand suitably device-aligned.
6489 */
6490 buf_a_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
6491 write_asize += buf_a_sz;
6492 dev->l2ad_hand += buf_a_sz;
6493 }
6494 }
6495
6496 mutex_exit(&dev->l2ad_mtx);
6497
6498 ASSERT3U(write_asize, <=, target_sz);
6499 ARCSTAT_BUMP(arcstat_l2_writes_sent);
6500 ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
6501 ARCSTAT_INCR(arcstat_l2_size, write_sz);
6502 ARCSTAT_INCR(arcstat_l2_asize, stats_size);
6503 vdev_space_update(dev->l2ad_vdev, stats_size, 0, 0);
6504
6505 /*
6506 * Bump device hand to the device start if it is approaching the end.
6507 * l2arc_evict() will already have evicted ahead for this case.
6508 */
6509 if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
6510 dev->l2ad_hand = dev->l2ad_start;
6511 dev->l2ad_first = B_FALSE;
6512 }
6513
6514 dev->l2ad_writing = B_TRUE;
6515 (void) zio_wait(pio);
6516 dev->l2ad_writing = B_FALSE;
6517
6518 return (write_asize);
6519 }
6520
6521 /*
6522 * Compresses an L2ARC buffer.
6523 * The data to be compressed must be prefilled in l1hdr.b_tmp_cdata and its
6524 * size in l2hdr->b_asize. This routine tries to compress the data and
6525 * depending on the compression result there are three possible outcomes:
6526 * *) The buffer was incompressible. The original l2hdr contents were left
6527 * untouched and are ready for writing to an L2 device.
6528 * *) The buffer was all-zeros, so there is no need to write it to an L2
6529 * device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
6530 * set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
6531 * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
6532 * data buffer which holds the compressed data to be written, and b_asize
6533 * tells us how much data there is. b_compress is set to the appropriate
6534 * compression algorithm. Once writing is done, invoke
6535 * l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
6536 *
6537 * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
6538 * buffer was incompressible).
6539 */
6540 static boolean_t
6541 l2arc_compress_buf(arc_buf_hdr_t *hdr)
6542 {
6543 void *cdata;
6544 size_t csize, len, rounded;
6545 l2arc_buf_hdr_t *l2hdr;
6546
6547 ASSERT(HDR_HAS_L2HDR(hdr));
6548
6549 l2hdr = &hdr->b_l2hdr;
6550
6551 ASSERT(HDR_HAS_L1HDR(hdr));
6552 ASSERT(HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_OFF);
6553 ASSERT(hdr->b_l1hdr.b_tmp_cdata != NULL);
6554
6555 len = l2hdr->b_asize;
6556 cdata = zio_data_buf_alloc(len);
6557 ASSERT3P(cdata, !=, NULL);
6558 csize = zio_compress_data(ZIO_COMPRESS_LZ4, hdr->b_l1hdr.b_tmp_cdata,
6559 cdata, l2hdr->b_asize);
6560
6561 rounded = P2ROUNDUP(csize, (size_t)SPA_MINBLOCKSIZE);
6562 if (rounded > csize) {
6563 bzero((char *)cdata + csize, rounded - csize);
6564 csize = rounded;
6565 }
6566
6567 if (csize == 0) {
6568 /* zero block, indicate that there's nothing to write */
6569 zio_data_buf_free(cdata, len);
6570 HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_EMPTY);
6571 l2hdr->b_asize = 0;
6572 hdr->b_l1hdr.b_tmp_cdata = NULL;
6573 ARCSTAT_BUMP(arcstat_l2_compress_zeros);
6574 return (B_TRUE);
6575 } else if (csize > 0 && csize < len) {
6576 /*
6577 * Compression succeeded, we'll keep the cdata around for
6578 * writing and release it afterwards.
6579 */
6580 HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_LZ4);
6581 l2hdr->b_asize = csize;
6582 hdr->b_l1hdr.b_tmp_cdata = cdata;
6583 ARCSTAT_BUMP(arcstat_l2_compress_successes);
6584 return (B_TRUE);
6585 } else {
6586 /*
6587 * Compression failed, release the compressed buffer.
6588 * l2hdr will be left unmodified.
6589 */
6590 zio_data_buf_free(cdata, len);
6591 ARCSTAT_BUMP(arcstat_l2_compress_failures);
6592 return (B_FALSE);
6593 }
6594 }
6595
6596 /*
6597 * Decompresses a zio read back from an l2arc device. On success, the
6598 * underlying zio's io_data buffer is overwritten by the uncompressed
6599 * version. On decompression error (corrupt compressed stream), the
6600 * zio->io_error value is set to signal an I/O error.
6601 *
6602 * Please note that the compressed data stream is not checksummed, so
6603 * if the underlying device is experiencing data corruption, we may feed
6604 * corrupt data to the decompressor, so the decompressor needs to be
6605 * able to handle this situation (LZ4 does).
6606 */
6607 static void
6608 l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
6609 {
6610 uint64_t csize;
6611 void *cdata;
6612
6613 ASSERT(L2ARC_IS_VALID_COMPRESS(c));
6614
6615 if (zio->io_error != 0) {
6616 /*
6617 * An io error has occured, just restore the original io
6618 * size in preparation for a main pool read.
6619 */
6620 zio->io_orig_size = zio->io_size = hdr->b_size;
6621 return;
6622 }
6623
6624 if (c == ZIO_COMPRESS_EMPTY) {
6625 /*
6626 * An empty buffer results in a null zio, which means we
6627 * need to fill its io_data after we're done restoring the
6628 * buffer's contents.
6629 */
6630 ASSERT(hdr->b_l1hdr.b_buf != NULL);
6631 bzero(hdr->b_l1hdr.b_buf->b_data, hdr->b_size);
6632 zio->io_data = zio->io_orig_data = hdr->b_l1hdr.b_buf->b_data;
6633 } else {
6634 ASSERT(zio->io_data != NULL);
6635 /*
6636 * We copy the compressed data from the start of the arc buffer
6637 * (the zio_read will have pulled in only what we need, the
6638 * rest is garbage which we will overwrite at decompression)
6639 * and then decompress back to the ARC data buffer. This way we
6640 * can minimize copying by simply decompressing back over the
6641 * original compressed data (rather than decompressing to an
6642 * aux buffer and then copying back the uncompressed buffer,
6643 * which is likely to be much larger).
6644 */
6645 csize = zio->io_size;
6646 cdata = zio_data_buf_alloc(csize);
6647 bcopy(zio->io_data, cdata, csize);
6648 if (zio_decompress_data(c, cdata, zio->io_data, csize,
6649 hdr->b_size) != 0)
6650 zio->io_error = SET_ERROR(EIO);
6651 zio_data_buf_free(cdata, csize);
6652 }
6653
6654 /* Restore the expected uncompressed IO size. */
6655 zio->io_orig_size = zio->io_size = hdr->b_size;
6656 }
6657
6658 /*
6659 * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
6660 * This buffer serves as a temporary holder of compressed data while
6661 * the buffer entry is being written to an l2arc device. Once that is
6662 * done, we can dispose of it.
6663 */
6664 static void
6665 l2arc_release_cdata_buf(arc_buf_hdr_t *hdr)
6666 {
6667 enum zio_compress comp = HDR_GET_COMPRESS(hdr);
6668
6669 ASSERT(HDR_HAS_L1HDR(hdr));
6670 ASSERT(comp == ZIO_COMPRESS_OFF || L2ARC_IS_VALID_COMPRESS(comp));
6671
6672 if (comp == ZIO_COMPRESS_OFF) {
6673 /*
6674 * In this case, b_tmp_cdata points to the same buffer
6675 * as the arc_buf_t's b_data field. We don't want to
6676 * free it, since the arc_buf_t will handle that.
6677 */
6678 hdr->b_l1hdr.b_tmp_cdata = NULL;
6679 } else if (comp == ZIO_COMPRESS_EMPTY) {
6680 /*
6681 * In this case, b_tmp_cdata was compressed to an empty
6682 * buffer, thus there's nothing to free and b_tmp_cdata
6683 * should have been set to NULL in l2arc_write_buffers().
6684 */
6685 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
6686 } else {
6687 /*
6688 * If the data was compressed, then we've allocated a
6689 * temporary buffer for it, so now we need to release it.
6690 */
6691 ASSERT(hdr->b_l1hdr.b_tmp_cdata != NULL);
6692 zio_data_buf_free(hdr->b_l1hdr.b_tmp_cdata,
6693 hdr->b_size);
6694 hdr->b_l1hdr.b_tmp_cdata = NULL;
6695 }
6696
6697 }
6698
6699 /*
6700 * This thread feeds the L2ARC at regular intervals. This is the beating
6701 * heart of the L2ARC.
6702 */
6703 static void
6704 l2arc_feed_thread(void)
6705 {
6706 callb_cpr_t cpr;
6707 l2arc_dev_t *dev;
6708 spa_t *spa;
6709 uint64_t size, wrote;
6710 clock_t begin, next = ddi_get_lbolt();
6711 boolean_t headroom_boost = B_FALSE;
6712 fstrans_cookie_t cookie;
6713
6714 CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
6715
6716 mutex_enter(&l2arc_feed_thr_lock);
6717
6718 cookie = spl_fstrans_mark();
6719 while (l2arc_thread_exit == 0) {
6720 CALLB_CPR_SAFE_BEGIN(&cpr);
6721 (void) cv_timedwait_sig(&l2arc_feed_thr_cv,
6722 &l2arc_feed_thr_lock, next);
6723 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
6724 next = ddi_get_lbolt() + hz;
6725
6726 /*
6727 * Quick check for L2ARC devices.
6728 */
6729 mutex_enter(&l2arc_dev_mtx);
6730 if (l2arc_ndev == 0) {
6731 mutex_exit(&l2arc_dev_mtx);
6732 continue;
6733 }
6734 mutex_exit(&l2arc_dev_mtx);
6735 begin = ddi_get_lbolt();
6736
6737 /*
6738 * This selects the next l2arc device to write to, and in
6739 * doing so the next spa to feed from: dev->l2ad_spa. This
6740 * will return NULL if there are now no l2arc devices or if
6741 * they are all faulted.
6742 *
6743 * If a device is returned, its spa's config lock is also
6744 * held to prevent device removal. l2arc_dev_get_next()
6745 * will grab and release l2arc_dev_mtx.
6746 */
6747 if ((dev = l2arc_dev_get_next()) == NULL)
6748 continue;
6749
6750 spa = dev->l2ad_spa;
6751 ASSERT(spa != NULL);
6752
6753 /*
6754 * If the pool is read-only then force the feed thread to
6755 * sleep a little longer.
6756 */
6757 if (!spa_writeable(spa)) {
6758 next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
6759 spa_config_exit(spa, SCL_L2ARC, dev);
6760 continue;
6761 }
6762
6763 /*
6764 * Avoid contributing to memory pressure.
6765 */
6766 if (arc_reclaim_needed()) {
6767 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
6768 spa_config_exit(spa, SCL_L2ARC, dev);
6769 continue;
6770 }
6771
6772 ARCSTAT_BUMP(arcstat_l2_feeds);
6773
6774 size = l2arc_write_size();
6775
6776 /*
6777 * Evict L2ARC buffers that will be overwritten.
6778 */
6779 l2arc_evict(dev, size, B_FALSE);
6780
6781 /*
6782 * Write ARC buffers.
6783 */
6784 wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
6785
6786 /*
6787 * Calculate interval between writes.
6788 */
6789 next = l2arc_write_interval(begin, size, wrote);
6790 spa_config_exit(spa, SCL_L2ARC, dev);
6791 }
6792 spl_fstrans_unmark(cookie);
6793
6794 l2arc_thread_exit = 0;
6795 cv_broadcast(&l2arc_feed_thr_cv);
6796 CALLB_CPR_EXIT(&cpr); /* drops l2arc_feed_thr_lock */
6797 thread_exit();
6798 }
6799
6800 boolean_t
6801 l2arc_vdev_present(vdev_t *vd)
6802 {
6803 l2arc_dev_t *dev;
6804
6805 mutex_enter(&l2arc_dev_mtx);
6806 for (dev = list_head(l2arc_dev_list); dev != NULL;
6807 dev = list_next(l2arc_dev_list, dev)) {
6808 if (dev->l2ad_vdev == vd)
6809 break;
6810 }
6811 mutex_exit(&l2arc_dev_mtx);
6812
6813 return (dev != NULL);
6814 }
6815
6816 /*
6817 * Add a vdev for use by the L2ARC. By this point the spa has already
6818 * validated the vdev and opened it.
6819 */
6820 void
6821 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
6822 {
6823 l2arc_dev_t *adddev;
6824
6825 ASSERT(!l2arc_vdev_present(vd));
6826
6827 /*
6828 * Create a new l2arc device entry.
6829 */
6830 adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
6831 adddev->l2ad_spa = spa;
6832 adddev->l2ad_vdev = vd;
6833 adddev->l2ad_start = VDEV_LABEL_START_SIZE;
6834 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
6835 adddev->l2ad_hand = adddev->l2ad_start;
6836 adddev->l2ad_first = B_TRUE;
6837 adddev->l2ad_writing = B_FALSE;
6838 list_link_init(&adddev->l2ad_node);
6839
6840 mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
6841 /*
6842 * This is a list of all ARC buffers that are still valid on the
6843 * device.
6844 */
6845 list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
6846 offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
6847
6848 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
6849 refcount_create(&adddev->l2ad_alloc);
6850
6851 /*
6852 * Add device to global list
6853 */
6854 mutex_enter(&l2arc_dev_mtx);
6855 list_insert_head(l2arc_dev_list, adddev);
6856 atomic_inc_64(&l2arc_ndev);
6857 mutex_exit(&l2arc_dev_mtx);
6858 }
6859
6860 /*
6861 * Remove a vdev from the L2ARC.
6862 */
6863 void
6864 l2arc_remove_vdev(vdev_t *vd)
6865 {
6866 l2arc_dev_t *dev, *nextdev, *remdev = NULL;
6867
6868 /*
6869 * Find the device by vdev
6870 */
6871 mutex_enter(&l2arc_dev_mtx);
6872 for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
6873 nextdev = list_next(l2arc_dev_list, dev);
6874 if (vd == dev->l2ad_vdev) {
6875 remdev = dev;
6876 break;
6877 }
6878 }
6879 ASSERT(remdev != NULL);
6880
6881 /*
6882 * Remove device from global list
6883 */
6884 list_remove(l2arc_dev_list, remdev);
6885 l2arc_dev_last = NULL; /* may have been invalidated */
6886 atomic_dec_64(&l2arc_ndev);
6887 mutex_exit(&l2arc_dev_mtx);
6888
6889 /*
6890 * Clear all buflists and ARC references. L2ARC device flush.
6891 */
6892 l2arc_evict(remdev, 0, B_TRUE);
6893 list_destroy(&remdev->l2ad_buflist);
6894 mutex_destroy(&remdev->l2ad_mtx);
6895 refcount_destroy(&remdev->l2ad_alloc);
6896 kmem_free(remdev, sizeof (l2arc_dev_t));
6897 }
6898
6899 void
6900 l2arc_init(void)
6901 {
6902 l2arc_thread_exit = 0;
6903 l2arc_ndev = 0;
6904 l2arc_writes_sent = 0;
6905 l2arc_writes_done = 0;
6906
6907 mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
6908 cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
6909 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
6910 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
6911
6912 l2arc_dev_list = &L2ARC_dev_list;
6913 l2arc_free_on_write = &L2ARC_free_on_write;
6914 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
6915 offsetof(l2arc_dev_t, l2ad_node));
6916 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
6917 offsetof(l2arc_data_free_t, l2df_list_node));
6918 }
6919
6920 void
6921 l2arc_fini(void)
6922 {
6923 /*
6924 * This is called from dmu_fini(), which is called from spa_fini();
6925 * Because of this, we can assume that all l2arc devices have
6926 * already been removed when the pools themselves were removed.
6927 */
6928
6929 l2arc_do_free_on_write();
6930
6931 mutex_destroy(&l2arc_feed_thr_lock);
6932 cv_destroy(&l2arc_feed_thr_cv);
6933 mutex_destroy(&l2arc_dev_mtx);
6934 mutex_destroy(&l2arc_free_on_write_mtx);
6935
6936 list_destroy(l2arc_dev_list);
6937 list_destroy(l2arc_free_on_write);
6938 }
6939
6940 void
6941 l2arc_start(void)
6942 {
6943 if (!(spa_mode_global & FWRITE))
6944 return;
6945
6946 (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
6947 TS_RUN, minclsyspri);
6948 }
6949
6950 void
6951 l2arc_stop(void)
6952 {
6953 if (!(spa_mode_global & FWRITE))
6954 return;
6955
6956 mutex_enter(&l2arc_feed_thr_lock);
6957 cv_signal(&l2arc_feed_thr_cv); /* kick thread out of startup */
6958 l2arc_thread_exit = 1;
6959 while (l2arc_thread_exit != 0)
6960 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
6961 mutex_exit(&l2arc_feed_thr_lock);
6962 }
6963
6964 #if defined(_KERNEL) && defined(HAVE_SPL)
6965 EXPORT_SYMBOL(arc_buf_size);
6966 EXPORT_SYMBOL(arc_write);
6967 EXPORT_SYMBOL(arc_read);
6968 EXPORT_SYMBOL(arc_buf_remove_ref);
6969 EXPORT_SYMBOL(arc_buf_info);
6970 EXPORT_SYMBOL(arc_getbuf_func);
6971 EXPORT_SYMBOL(arc_add_prune_callback);
6972 EXPORT_SYMBOL(arc_remove_prune_callback);
6973
6974 module_param(zfs_arc_min, ulong, 0644);
6975 MODULE_PARM_DESC(zfs_arc_min, "Min arc size");
6976
6977 module_param(zfs_arc_max, ulong, 0644);
6978 MODULE_PARM_DESC(zfs_arc_max, "Max arc size");
6979
6980 module_param(zfs_arc_meta_limit, ulong, 0644);
6981 MODULE_PARM_DESC(zfs_arc_meta_limit, "Meta limit for arc size");
6982
6983 module_param(zfs_arc_meta_min, ulong, 0644);
6984 MODULE_PARM_DESC(zfs_arc_meta_min, "Min arc metadata");
6985
6986 module_param(zfs_arc_meta_prune, int, 0644);
6987 MODULE_PARM_DESC(zfs_arc_meta_prune, "Meta objects to scan for prune");
6988
6989 module_param(zfs_arc_meta_adjust_restarts, int, 0644);
6990 MODULE_PARM_DESC(zfs_arc_meta_adjust_restarts,
6991 "Limit number of restarts in arc_adjust_meta");
6992
6993 module_param(zfs_arc_meta_strategy, int, 0644);
6994 MODULE_PARM_DESC(zfs_arc_meta_strategy, "Meta reclaim strategy");
6995
6996 module_param(zfs_arc_grow_retry, int, 0644);
6997 MODULE_PARM_DESC(zfs_arc_grow_retry, "Seconds before growing arc size");
6998
6999 module_param(zfs_arc_p_aggressive_disable, int, 0644);
7000 MODULE_PARM_DESC(zfs_arc_p_aggressive_disable, "disable aggressive arc_p grow");
7001
7002 module_param(zfs_arc_p_dampener_disable, int, 0644);
7003 MODULE_PARM_DESC(zfs_arc_p_dampener_disable, "disable arc_p adapt dampener");
7004
7005 module_param(zfs_arc_shrink_shift, int, 0644);
7006 MODULE_PARM_DESC(zfs_arc_shrink_shift, "log2(fraction of arc to reclaim)");
7007
7008 module_param(zfs_arc_p_min_shift, int, 0644);
7009 MODULE_PARM_DESC(zfs_arc_p_min_shift, "arc_c shift to calc min/max arc_p");
7010
7011 module_param(zfs_disable_dup_eviction, int, 0644);
7012 MODULE_PARM_DESC(zfs_disable_dup_eviction, "disable duplicate buffer eviction");
7013
7014 module_param(zfs_arc_average_blocksize, int, 0444);
7015 MODULE_PARM_DESC(zfs_arc_average_blocksize, "Target average block size");
7016
7017 module_param(zfs_arc_memory_throttle_disable, int, 0644);
7018 MODULE_PARM_DESC(zfs_arc_memory_throttle_disable, "disable memory throttle");
7019
7020 module_param(zfs_arc_min_prefetch_lifespan, int, 0644);
7021 MODULE_PARM_DESC(zfs_arc_min_prefetch_lifespan, "Min life of prefetch block");
7022
7023 module_param(zfs_arc_num_sublists_per_state, int, 0644);
7024 MODULE_PARM_DESC(zfs_arc_num_sublists_per_state,
7025 "Number of sublists used in each of the ARC state lists");
7026
7027 module_param(l2arc_write_max, ulong, 0644);
7028 MODULE_PARM_DESC(l2arc_write_max, "Max write bytes per interval");
7029
7030 module_param(l2arc_write_boost, ulong, 0644);
7031 MODULE_PARM_DESC(l2arc_write_boost, "Extra write bytes during device warmup");
7032
7033 module_param(l2arc_headroom, ulong, 0644);
7034 MODULE_PARM_DESC(l2arc_headroom, "Number of max device writes to precache");
7035
7036 module_param(l2arc_headroom_boost, ulong, 0644);
7037 MODULE_PARM_DESC(l2arc_headroom_boost, "Compressed l2arc_headroom multiplier");
7038
7039 module_param(l2arc_feed_secs, ulong, 0644);
7040 MODULE_PARM_DESC(l2arc_feed_secs, "Seconds between L2ARC writing");
7041
7042 module_param(l2arc_feed_min_ms, ulong, 0644);
7043 MODULE_PARM_DESC(l2arc_feed_min_ms, "Min feed interval in milliseconds");
7044
7045 module_param(l2arc_noprefetch, int, 0644);
7046 MODULE_PARM_DESC(l2arc_noprefetch, "Skip caching prefetched buffers");
7047
7048 module_param(l2arc_nocompress, int, 0644);
7049 MODULE_PARM_DESC(l2arc_nocompress, "Skip compressing L2ARC buffers");
7050
7051 module_param(l2arc_feed_again, int, 0644);
7052 MODULE_PARM_DESC(l2arc_feed_again, "Turbo L2ARC warmup");
7053
7054 module_param(l2arc_norw, int, 0644);
7055 MODULE_PARM_DESC(l2arc_norw, "No reads during writes");
7056
7057 #endif