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