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