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