1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3 * This file and its contents are supplied under the terms of the
4 * Common Development and Distribution License ("CDDL"), version 1.0.
5 * You may only use this file in accordance with the terms of version
6 * 1.0 of the CDDL.
7 *
8 * A full copy of the text of the CDDL should have accompanied this
9 * source. A copy of the CDDL is also available via the Internet at
10 * https://opensource.org/license/CDDL-1.0.
11 */
12 /*
13 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
14 * Copyright (c) 2018, Joyent, Inc.
15 * Copyright (c) 2011, 2020, Delphix. All rights reserved.
16 * Copyright (c) 2014, Saso Kiselkov. All rights reserved.
17 * Copyright (c) 2017, Nexenta Systems, Inc. All rights reserved.
18 * Copyright (c) 2019, loli10K <ezomori.nozomu@gmail.com>. All rights reserved.
19 * Copyright (c) 2020, George Amanakis. All rights reserved.
20 * Copyright (c) 2019, 2024, 2025, Klara, Inc.
21 * Copyright (c) 2019, Allan Jude
22 * Copyright (c) 2020, The FreeBSD Foundation [1]
23 * Copyright (c) 2021, 2024 by George Melikov. All rights reserved.
24 *
25 * [1] Portions of this software were developed by Allan Jude
26 * under sponsorship from the FreeBSD Foundation.
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 (ranging 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 * It as also possible to register a callback which is run when the
103 * metadata limit is reached and no buffers can be safely evicted. In
104 * this case the arc user should drop a reference on some arc buffers so
105 * they can be reclaimed. For example, when using the ZPL each dentry
106 * holds a references on a znode. These dentries must be pruned before
107 * the arc buffer holding the znode can be safely evicted.
108 *
109 * Note that the majority of the performance stats are manipulated
110 * with atomic operations.
111 *
112 * The L2ARC uses the l2ad_mtx on each vdev for the following:
113 *
114 * - L2ARC buflist creation
115 * - L2ARC buflist eviction
116 * - L2ARC write completion, which walks L2ARC buflists
117 * - ARC header destruction, as it removes from L2ARC buflists
118 * - ARC header release, as it removes from L2ARC buflists
119 */
120
121 /*
122 * ARC operation:
123 *
124 * Every block that is in the ARC is tracked by an arc_buf_hdr_t structure.
125 * This structure can point either to a block that is still in the cache or to
126 * one that is only accessible in an L2 ARC device, or it can provide
127 * information about a block that was recently evicted. If a block is
128 * only accessible in the L2ARC, then the arc_buf_hdr_t only has enough
129 * information to retrieve it from the L2ARC device. This information is
130 * stored in the l2arc_buf_hdr_t sub-structure of the arc_buf_hdr_t. A block
131 * that is in this state cannot access the data directly.
132 *
133 * Blocks that are actively being referenced or have not been evicted
134 * are cached in the L1ARC. The L1ARC (l1arc_buf_hdr_t) is a structure within
135 * the arc_buf_hdr_t that will point to the data block in memory. A block can
136 * only be read by a consumer if it has an l1arc_buf_hdr_t. The L1ARC
137 * caches data in two ways -- in a list of ARC buffers (arc_buf_t) and
138 * also in the arc_buf_hdr_t's private physical data block pointer (b_pabd).
139 *
140 * The L1ARC's data pointer may or may not be uncompressed. The ARC has the
141 * ability to store the physical data (b_pabd) associated with the DVA of the
142 * arc_buf_hdr_t. Since the b_pabd is a copy of the on-disk physical block,
143 * it will match its on-disk compression characteristics. This behavior can be
144 * disabled by setting 'zfs_compressed_arc_enabled' to B_FALSE. When the
145 * compressed ARC functionality is disabled, the b_pabd will point to an
146 * uncompressed version of the on-disk data.
147 *
148 * Data in the L1ARC is not accessed by consumers of the ARC directly. Each
149 * arc_buf_hdr_t can have multiple ARC buffers (arc_buf_t) which reference it.
150 * Each ARC buffer (arc_buf_t) is being actively accessed by a specific ARC
151 * consumer. The ARC will provide references to this data and will keep it
152 * cached until it is no longer in use. The ARC caches only the L1ARC's physical
153 * data block and will evict any arc_buf_t that is no longer referenced. The
154 * amount of memory consumed by the arc_buf_ts' data buffers can be seen via the
155 * "overhead_size" kstat.
156 *
157 * Depending on the consumer, an arc_buf_t can be requested in uncompressed or
158 * compressed form. The typical case is that consumers will want uncompressed
159 * data, and when that happens a new data buffer is allocated where the data is
160 * decompressed for them to use. Currently the only consumer who wants
161 * compressed arc_buf_t's is "zfs send", when it streams data exactly as it
162 * exists on disk. When this happens, the arc_buf_t's data buffer is shared
163 * with the arc_buf_hdr_t.
164 *
165 * Here is a diagram showing an arc_buf_hdr_t referenced by two arc_buf_t's. The
166 * first one is owned by a compressed send consumer (and therefore references
167 * the same compressed data buffer as the arc_buf_hdr_t) and the second could be
168 * used by any other consumer (and has its own uncompressed copy of the data
169 * buffer).
170 *
171 * arc_buf_hdr_t
172 * +-----------+
173 * | fields |
174 * | common to |
175 * | L1- and |
176 * | L2ARC |
177 * +-----------+
178 * | l2arc_buf_hdr_t
179 * | |
180 * +-----------+
181 * | l1arc_buf_hdr_t
182 * | | arc_buf_t
183 * | b_buf +------------>+-----------+ arc_buf_t
184 * | b_pabd +-+ |b_next +---->+-----------+
185 * +-----------+ | |-----------| |b_next +-->NULL
186 * | |b_comp = T | +-----------+
187 * | |b_data +-+ |b_comp = F |
188 * | +-----------+ | |b_data +-+
189 * +->+------+ | +-----------+ |
190 * compressed | | | |
191 * data | |<--------------+ | uncompressed
192 * +------+ compressed, | data
193 * shared +-->+------+
194 * data | |
195 * | |
196 * +------+
197 *
198 * When a consumer reads a block, the ARC must first look to see if the
199 * arc_buf_hdr_t is cached. If the hdr is cached then the ARC allocates a new
200 * arc_buf_t and either copies uncompressed data into a new data buffer from an
201 * existing uncompressed arc_buf_t, decompresses the hdr's b_pabd buffer into a
202 * new data buffer, or shares the hdr's b_pabd buffer, depending on whether the
203 * hdr is compressed and the desired compression characteristics of the
204 * arc_buf_t consumer. If the arc_buf_t ends up sharing data with the
205 * arc_buf_hdr_t and both of them are uncompressed then the arc_buf_t must be
206 * the last buffer in the hdr's b_buf list, however a shared compressed buf can
207 * be anywhere in the hdr's list.
208 *
209 * The diagram below shows an example of an uncompressed ARC hdr that is
210 * sharing its data with an arc_buf_t (note that the shared uncompressed buf is
211 * the last element in the buf list):
212 *
213 * arc_buf_hdr_t
214 * +-----------+
215 * | |
216 * | |
217 * | |
218 * +-----------+
219 * l2arc_buf_hdr_t| |
220 * | |
221 * +-----------+
222 * l1arc_buf_hdr_t| |
223 * | | arc_buf_t (shared)
224 * | b_buf +------------>+---------+ arc_buf_t
225 * | | |b_next +---->+---------+
226 * | b_pabd +-+ |---------| |b_next +-->NULL
227 * +-----------+ | | | +---------+
228 * | |b_data +-+ | |
229 * | +---------+ | |b_data +-+
230 * +->+------+ | +---------+ |
231 * | | | |
232 * uncompressed | | | |
233 * data +------+ | |
234 * ^ +->+------+ |
235 * | uncompressed | | |
236 * | data | | |
237 * | +------+ |
238 * +---------------------------------+
239 *
240 * Writing to the ARC requires that the ARC first discard the hdr's b_pabd
241 * since the physical block is about to be rewritten. The new data contents
242 * will be contained in the arc_buf_t. As the I/O pipeline performs the write,
243 * it may compress the data before writing it to disk. The ARC will be called
244 * with the transformed data and will memcpy the transformed on-disk block into
245 * a newly allocated b_pabd. Writes are always done into buffers which have
246 * either been loaned (and hence are new and don't have other readers) or
247 * buffers which have been released (and hence have their own hdr, if there
248 * were originally other readers of the buf's original hdr). This ensures that
249 * the ARC only needs to update a single buf and its hdr after a write occurs.
250 *
251 * When the L2ARC is in use, it will also take advantage of the b_pabd. The
252 * L2ARC will always write the contents of b_pabd to the L2ARC. This means
253 * that when compressed ARC is enabled that the L2ARC blocks are identical
254 * to the on-disk block in the main data pool. This provides a significant
255 * advantage since the ARC can leverage the bp's checksum when reading from the
256 * L2ARC to determine if the contents are valid. However, if the compressed
257 * ARC is disabled, then the L2ARC's block must be transformed to look
258 * like the physical block in the main data pool before comparing the
259 * checksum and determining its validity.
260 *
261 * The L1ARC has a slightly different system for storing encrypted data.
262 * Raw (encrypted + possibly compressed) data has a few subtle differences from
263 * data that is just compressed. The biggest difference is that it is not
264 * possible to decrypt encrypted data (or vice-versa) if the keys aren't loaded.
265 * The other difference is that encryption cannot be treated as a suggestion.
266 * If a caller would prefer compressed data, but they actually wind up with
267 * uncompressed data the worst thing that could happen is there might be a
268 * performance hit. If the caller requests encrypted data, however, we must be
269 * sure they actually get it or else secret information could be leaked. Raw
270 * data is stored in hdr->b_crypt_hdr.b_rabd. An encrypted header, therefore,
271 * may have both an encrypted version and a decrypted version of its data at
272 * once. When a caller needs a raw arc_buf_t, it is allocated and the data is
273 * copied out of this header. To avoid complications with b_pabd, raw buffers
274 * cannot be shared.
275 */
276
277 #include <sys/spa.h>
278 #include <sys/zio.h>
279 #include <sys/spa_impl.h>
280 #include <sys/zio_compress.h>
281 #include <sys/zio_checksum.h>
282 #include <sys/zfs_context.h>
283 #include <sys/arc.h>
284 #include <sys/zfs_refcount.h>
285 #include <sys/vdev.h>
286 #include <sys/vdev_impl.h>
287 #include <sys/dsl_pool.h>
288 #include <sys/multilist.h>
289 #include <sys/abd.h>
290 #include <sys/dbuf.h>
291 #include <sys/zil.h>
292 #include <sys/fm/fs/zfs.h>
293 #include <sys/callb.h>
294 #include <sys/kstat.h>
295 #include <sys/zthr.h>
296 #include <zfs_fletcher.h>
297 #include <sys/arc_impl.h>
298 #include <sys/trace_zfs.h>
299 #include <sys/aggsum.h>
300 #include <sys/wmsum.h>
301 #include <cityhash.h>
302 #include <sys/vdev_trim.h>
303 #include <sys/zfs_racct.h>
304 #include <sys/zstd/zstd.h>
305
306 #ifndef _KERNEL
307 /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
308 boolean_t arc_watch = B_FALSE;
309 #endif
310
311 /*
312 * This thread's job is to keep enough free memory in the system, by
313 * calling arc_kmem_reap_soon() plus arc_reduce_target_size(), which improves
314 * arc_available_memory().
315 */
316 static zthr_t *arc_reap_zthr;
317
318 /*
319 * This thread's job is to keep arc_size under arc_c, by calling
320 * arc_evict(), which improves arc_is_overflowing().
321 */
322 static zthr_t *arc_evict_zthr;
323 static arc_buf_hdr_t **arc_state_evict_markers;
324 static int arc_state_evict_marker_count;
325
326 static kmutex_t arc_evict_lock;
327 static boolean_t arc_evict_needed = B_FALSE;
328 static clock_t arc_last_uncached_flush;
329
330 static taskq_t *arc_evict_taskq;
331 static struct evict_arg *arc_evict_arg;
332
333 /*
334 * Count of bytes evicted since boot.
335 */
336 static uint64_t arc_evict_count;
337
338 /*
339 * List of arc_evict_waiter_t's, representing threads waiting for the
340 * arc_evict_count to reach specific values.
341 */
342 static list_t arc_evict_waiters;
343
344 /*
345 * When arc_is_overflowing(), arc_get_data_impl() waits for this percent of
346 * the requested amount of data to be evicted. For example, by default for
347 * every 2KB that's evicted, 1KB of it may be "reused" by a new allocation.
348 * Since this is above 100%, it ensures that progress is made towards getting
349 * arc_size under arc_c. Since this is finite, it ensures that allocations
350 * can still happen, even during the potentially long time that arc_size is
351 * more than arc_c.
352 */
353 static uint_t zfs_arc_eviction_pct = 200;
354
355 /*
356 * The number of headers to evict in arc_evict_state_impl() before
357 * dropping the sublist lock and evicting from another sublist. A lower
358 * value means we're more likely to evict the "correct" header (i.e. the
359 * oldest header in the arc state), but comes with higher overhead
360 * (i.e. more invocations of arc_evict_state_impl()).
361 */
362 static uint_t zfs_arc_evict_batch_limit = 10;
363
364 /*
365 * Number batches to process per parallel eviction task under heavy load to
366 * reduce number of context switches.
367 */
368 static uint_t zfs_arc_evict_batches_limit = 5;
369
370 /* number of seconds before growing cache again */
371 uint_t arc_grow_retry = 5;
372
373 /*
374 * Minimum time between calls to arc_kmem_reap_soon().
375 */
376 static const int arc_kmem_cache_reap_retry_ms = 1000;
377
378 /* shift of arc_c for calculating overflow limit in arc_get_data_impl */
379 static int zfs_arc_overflow_shift = 8;
380
381 /* log2(fraction of arc to reclaim) */
382 uint_t arc_shrink_shift = 7;
383
384 #ifdef _KERNEL
385 /* percent of pagecache to reclaim arc to */
386 uint_t zfs_arc_pc_percent = 0;
387 #endif
388
389 /*
390 * log2(fraction of ARC which must be free to allow growing).
391 * I.e. If there is less than arc_c >> zfs_arc_no_grow_shift free memory,
392 * when reading a new block into the ARC, we will evict an equal-sized block
393 * from the ARC.
394 *
395 * This must be less than arc_shrink_shift, so that when we shrink the ARC,
396 * we will still not allow it to grow.
397 */
398 uint_t zfs_arc_no_grow_shift = 5;
399
400
401 /*
402 * minimum lifespan of a prefetch block in clock ticks
403 * (initialized in arc_init())
404 */
405 static uint_t arc_min_prefetch;
406 static uint_t arc_min_prescient_prefetch;
407
408 /*
409 * If this percent of memory is free, don't throttle.
410 */
411 uint_t arc_lotsfree_percent = 10;
412
413 /*
414 * The arc has filled available memory and has now warmed up.
415 */
416 boolean_t arc_warm;
417
418 /*
419 * These tunables are for performance analysis.
420 */
421 uint64_t zfs_arc_max = 0;
422 uint64_t zfs_arc_min = 0;
423 static uint64_t zfs_arc_dnode_limit = 0;
424 static uint_t zfs_arc_dnode_reduce_percent = 10;
425 static uint_t zfs_arc_grow_retry = 0;
426 static uint_t zfs_arc_shrink_shift = 0;
427 uint_t zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
428
429 /*
430 * ARC dirty data constraints for arc_tempreserve_space() throttle:
431 * * total dirty data limit
432 * * anon block dirty limit
433 * * each pool's anon allowance
434 */
435 static const unsigned long zfs_arc_dirty_limit_percent = 50;
436 static const unsigned long zfs_arc_anon_limit_percent = 25;
437 static const unsigned long zfs_arc_pool_dirty_percent = 20;
438
439 /*
440 * Enable or disable compressed arc buffers.
441 */
442 int zfs_compressed_arc_enabled = B_TRUE;
443
444 /*
445 * Balance between metadata and data on ghost hits. Values above 100
446 * increase metadata caching by proportionally reducing effect of ghost
447 * data hits on target data/metadata rate.
448 */
449 static uint_t zfs_arc_meta_balance = 500;
450
451 /*
452 * Percentage that can be consumed by dnodes of ARC meta buffers.
453 */
454 static uint_t zfs_arc_dnode_limit_percent = 10;
455
456 /*
457 * These tunables are Linux-specific
458 */
459 static uint64_t zfs_arc_sys_free = 0;
460 static uint_t zfs_arc_min_prefetch_ms = 0;
461 static uint_t zfs_arc_min_prescient_prefetch_ms = 0;
462 static uint_t zfs_arc_lotsfree_percent = 10;
463
464 /*
465 * Number of arc_prune threads
466 */
467 static int zfs_arc_prune_task_threads = 1;
468
469 /* Used by spa_export/spa_destroy to flush the arc asynchronously */
470 static taskq_t *arc_flush_taskq;
471
472 /*
473 * Controls the number of ARC eviction threads to dispatch sublists to.
474 *
475 * Possible values:
476 * 0 (auto) compute the number of threads using a logarithmic formula.
477 * 1 (disabled) one thread - parallel eviction is disabled.
478 * 2+ (manual) set the number manually.
479 *
480 * See arc_evict_thread_init() for how "auto" is computed.
481 */
482 static uint_t zfs_arc_evict_threads = 0;
483
484 /* The 7 states: */
485 arc_state_t ARC_anon;
486 arc_state_t ARC_mru;
487 arc_state_t ARC_mru_ghost;
488 arc_state_t ARC_mfu;
489 arc_state_t ARC_mfu_ghost;
490 arc_state_t ARC_l2c_only;
491 arc_state_t ARC_uncached;
492
493 arc_stats_t arc_stats = {
494 { "hits", KSTAT_DATA_UINT64 },
495 { "iohits", KSTAT_DATA_UINT64 },
496 { "misses", KSTAT_DATA_UINT64 },
497 { "demand_data_hits", KSTAT_DATA_UINT64 },
498 { "demand_data_iohits", KSTAT_DATA_UINT64 },
499 { "demand_data_misses", KSTAT_DATA_UINT64 },
500 { "demand_metadata_hits", KSTAT_DATA_UINT64 },
501 { "demand_metadata_iohits", KSTAT_DATA_UINT64 },
502 { "demand_metadata_misses", KSTAT_DATA_UINT64 },
503 { "prefetch_data_hits", KSTAT_DATA_UINT64 },
504 { "prefetch_data_iohits", KSTAT_DATA_UINT64 },
505 { "prefetch_data_misses", KSTAT_DATA_UINT64 },
506 { "prefetch_metadata_hits", KSTAT_DATA_UINT64 },
507 { "prefetch_metadata_iohits", KSTAT_DATA_UINT64 },
508 { "prefetch_metadata_misses", KSTAT_DATA_UINT64 },
509 { "mru_hits", KSTAT_DATA_UINT64 },
510 { "mru_ghost_hits", KSTAT_DATA_UINT64 },
511 { "mfu_hits", KSTAT_DATA_UINT64 },
512 { "mfu_ghost_hits", KSTAT_DATA_UINT64 },
513 { "uncached_hits", KSTAT_DATA_UINT64 },
514 { "deleted", KSTAT_DATA_UINT64 },
515 { "mutex_miss", KSTAT_DATA_UINT64 },
516 { "access_skip", KSTAT_DATA_UINT64 },
517 { "evict_skip", KSTAT_DATA_UINT64 },
518 { "evict_not_enough", KSTAT_DATA_UINT64 },
519 { "evict_l2_cached", KSTAT_DATA_UINT64 },
520 { "evict_l2_eligible", KSTAT_DATA_UINT64 },
521 { "evict_l2_eligible_mfu", KSTAT_DATA_UINT64 },
522 { "evict_l2_eligible_mru", KSTAT_DATA_UINT64 },
523 { "evict_l2_ineligible", KSTAT_DATA_UINT64 },
524 { "evict_l2_skip", KSTAT_DATA_UINT64 },
525 { "hash_elements", KSTAT_DATA_UINT64 },
526 { "hash_elements_max", KSTAT_DATA_UINT64 },
527 { "hash_collisions", KSTAT_DATA_UINT64 },
528 { "hash_chains", KSTAT_DATA_UINT64 },
529 { "hash_chain_max", KSTAT_DATA_UINT64 },
530 { "meta", KSTAT_DATA_UINT64 },
531 { "pd", KSTAT_DATA_UINT64 },
532 { "pm", KSTAT_DATA_UINT64 },
533 { "c", KSTAT_DATA_UINT64 },
534 { "c_min", KSTAT_DATA_UINT64 },
535 { "c_max", KSTAT_DATA_UINT64 },
536 { "size", KSTAT_DATA_UINT64 },
537 { "compressed_size", KSTAT_DATA_UINT64 },
538 { "uncompressed_size", KSTAT_DATA_UINT64 },
539 { "overhead_size", KSTAT_DATA_UINT64 },
540 { "hdr_size", KSTAT_DATA_UINT64 },
541 { "data_size", KSTAT_DATA_UINT64 },
542 { "metadata_size", KSTAT_DATA_UINT64 },
543 { "dbuf_size", KSTAT_DATA_UINT64 },
544 { "dnode_size", KSTAT_DATA_UINT64 },
545 { "bonus_size", KSTAT_DATA_UINT64 },
546 #if defined(COMPAT_FREEBSD11)
547 { "other_size", KSTAT_DATA_UINT64 },
548 #endif
549 { "anon_size", KSTAT_DATA_UINT64 },
550 { "anon_data", KSTAT_DATA_UINT64 },
551 { "anon_metadata", KSTAT_DATA_UINT64 },
552 { "anon_evictable_data", KSTAT_DATA_UINT64 },
553 { "anon_evictable_metadata", KSTAT_DATA_UINT64 },
554 { "mru_size", KSTAT_DATA_UINT64 },
555 { "mru_data", KSTAT_DATA_UINT64 },
556 { "mru_metadata", KSTAT_DATA_UINT64 },
557 { "mru_evictable_data", KSTAT_DATA_UINT64 },
558 { "mru_evictable_metadata", KSTAT_DATA_UINT64 },
559 { "mru_ghost_size", KSTAT_DATA_UINT64 },
560 { "mru_ghost_data", KSTAT_DATA_UINT64 },
561 { "mru_ghost_metadata", KSTAT_DATA_UINT64 },
562 { "mru_ghost_evictable_data", KSTAT_DATA_UINT64 },
563 { "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
564 { "mfu_size", KSTAT_DATA_UINT64 },
565 { "mfu_data", KSTAT_DATA_UINT64 },
566 { "mfu_metadata", KSTAT_DATA_UINT64 },
567 { "mfu_evictable_data", KSTAT_DATA_UINT64 },
568 { "mfu_evictable_metadata", KSTAT_DATA_UINT64 },
569 { "mfu_ghost_size", KSTAT_DATA_UINT64 },
570 { "mfu_ghost_data", KSTAT_DATA_UINT64 },
571 { "mfu_ghost_metadata", KSTAT_DATA_UINT64 },
572 { "mfu_ghost_evictable_data", KSTAT_DATA_UINT64 },
573 { "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
574 { "uncached_size", KSTAT_DATA_UINT64 },
575 { "uncached_data", KSTAT_DATA_UINT64 },
576 { "uncached_metadata", KSTAT_DATA_UINT64 },
577 { "uncached_evictable_data", KSTAT_DATA_UINT64 },
578 { "uncached_evictable_metadata", KSTAT_DATA_UINT64 },
579 { "l2_ndev", KSTAT_DATA_UINT64 },
580 { "l2_hits", KSTAT_DATA_UINT64 },
581 { "l2_misses", KSTAT_DATA_UINT64 },
582 { "l2_prefetch_asize", KSTAT_DATA_UINT64 },
583 { "l2_mru_asize", KSTAT_DATA_UINT64 },
584 { "l2_mfu_asize", KSTAT_DATA_UINT64 },
585 { "l2_bufc_data_asize", KSTAT_DATA_UINT64 },
586 { "l2_bufc_metadata_asize", KSTAT_DATA_UINT64 },
587 { "l2_feeds", KSTAT_DATA_UINT64 },
588 { "l2_rw_clash", KSTAT_DATA_UINT64 },
589 { "l2_read_bytes", KSTAT_DATA_UINT64 },
590 { "l2_write_bytes", KSTAT_DATA_UINT64 },
591 { "l2_writes_sent", KSTAT_DATA_UINT64 },
592 { "l2_writes_done", KSTAT_DATA_UINT64 },
593 { "l2_writes_error", KSTAT_DATA_UINT64 },
594 { "l2_writes_lock_retry", KSTAT_DATA_UINT64 },
595 { "l2_evict_lock_retry", KSTAT_DATA_UINT64 },
596 { "l2_evict_reading", KSTAT_DATA_UINT64 },
597 { "l2_evict_l1cached", KSTAT_DATA_UINT64 },
598 { "l2_free_on_write", KSTAT_DATA_UINT64 },
599 { "l2_abort_lowmem", KSTAT_DATA_UINT64 },
600 { "l2_cksum_bad", KSTAT_DATA_UINT64 },
601 { "l2_io_error", KSTAT_DATA_UINT64 },
602 { "l2_size", KSTAT_DATA_UINT64 },
603 { "l2_asize", KSTAT_DATA_UINT64 },
604 { "l2_hdr_size", KSTAT_DATA_UINT64 },
605 { "l2_log_blk_writes", KSTAT_DATA_UINT64 },
606 { "l2_log_blk_avg_asize", KSTAT_DATA_UINT64 },
607 { "l2_log_blk_asize", KSTAT_DATA_UINT64 },
608 { "l2_log_blk_count", KSTAT_DATA_UINT64 },
609 { "l2_data_to_meta_ratio", KSTAT_DATA_UINT64 },
610 { "l2_rebuild_success", KSTAT_DATA_UINT64 },
611 { "l2_rebuild_unsupported", KSTAT_DATA_UINT64 },
612 { "l2_rebuild_io_errors", KSTAT_DATA_UINT64 },
613 { "l2_rebuild_dh_errors", KSTAT_DATA_UINT64 },
614 { "l2_rebuild_cksum_lb_errors", KSTAT_DATA_UINT64 },
615 { "l2_rebuild_lowmem", KSTAT_DATA_UINT64 },
616 { "l2_rebuild_size", KSTAT_DATA_UINT64 },
617 { "l2_rebuild_asize", KSTAT_DATA_UINT64 },
618 { "l2_rebuild_bufs", KSTAT_DATA_UINT64 },
619 { "l2_rebuild_bufs_precached", KSTAT_DATA_UINT64 },
620 { "l2_rebuild_log_blks", KSTAT_DATA_UINT64 },
621 { "memory_throttle_count", KSTAT_DATA_UINT64 },
622 { "memory_direct_count", KSTAT_DATA_UINT64 },
623 { "memory_indirect_count", KSTAT_DATA_UINT64 },
624 { "memory_all_bytes", KSTAT_DATA_UINT64 },
625 { "memory_free_bytes", KSTAT_DATA_UINT64 },
626 { "memory_available_bytes", KSTAT_DATA_INT64 },
627 { "arc_no_grow", KSTAT_DATA_UINT64 },
628 { "arc_tempreserve", KSTAT_DATA_UINT64 },
629 { "arc_loaned_bytes", KSTAT_DATA_UINT64 },
630 { "arc_prune", KSTAT_DATA_UINT64 },
631 { "arc_meta_used", KSTAT_DATA_UINT64 },
632 { "arc_dnode_limit", KSTAT_DATA_UINT64 },
633 { "async_upgrade_sync", KSTAT_DATA_UINT64 },
634 { "predictive_prefetch", KSTAT_DATA_UINT64 },
635 { "demand_hit_predictive_prefetch", KSTAT_DATA_UINT64 },
636 { "demand_iohit_predictive_prefetch", KSTAT_DATA_UINT64 },
637 { "prescient_prefetch", KSTAT_DATA_UINT64 },
638 { "demand_hit_prescient_prefetch", KSTAT_DATA_UINT64 },
639 { "demand_iohit_prescient_prefetch", KSTAT_DATA_UINT64 },
640 { "arc_need_free", KSTAT_DATA_UINT64 },
641 { "arc_sys_free", KSTAT_DATA_UINT64 },
642 { "arc_raw_size", KSTAT_DATA_UINT64 },
643 { "cached_only_in_progress", KSTAT_DATA_UINT64 },
644 { "abd_chunk_waste_size", KSTAT_DATA_UINT64 },
645 };
646
647 arc_sums_t arc_sums;
648
649 #define ARCSTAT_MAX(stat, val) { \
650 uint64_t m; \
651 while ((val) > (m = arc_stats.stat.value.ui64) && \
652 (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val)))) \
653 continue; \
654 }
655
656 /*
657 * We define a macro to allow ARC hits/misses to be easily broken down by
658 * two separate conditions, giving a total of four different subtypes for
659 * each of hits and misses (so eight statistics total).
660 */
661 #define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
662 if (cond1) { \
663 if (cond2) { \
664 ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
665 } else { \
666 ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
667 } \
668 } else { \
669 if (cond2) { \
670 ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
671 } else { \
672 ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
673 } \
674 }
675
676 /*
677 * This macro allows us to use kstats as floating averages. Each time we
678 * update this kstat, we first factor it and the update value by
679 * ARCSTAT_AVG_FACTOR to shrink the new value's contribution to the overall
680 * average. This macro assumes that integer loads and stores are atomic, but
681 * is not safe for multiple writers updating the kstat in parallel (only the
682 * last writer's update will remain).
683 */
684 #define ARCSTAT_F_AVG_FACTOR 3
685 #define ARCSTAT_F_AVG(stat, value) \
686 do { \
687 uint64_t x = ARCSTAT(stat); \
688 x = x - x / ARCSTAT_F_AVG_FACTOR + \
689 (value) / ARCSTAT_F_AVG_FACTOR; \
690 ARCSTAT(stat) = x; \
691 } while (0)
692
693 static kstat_t *arc_ksp;
694
695 /*
696 * There are several ARC variables that are critical to export as kstats --
697 * but we don't want to have to grovel around in the kstat whenever we wish to
698 * manipulate them. For these variables, we therefore define them to be in
699 * terms of the statistic variable. This assures that we are not introducing
700 * the possibility of inconsistency by having shadow copies of the variables,
701 * while still allowing the code to be readable.
702 */
703 #define arc_tempreserve ARCSTAT(arcstat_tempreserve)
704 #define arc_loaned_bytes ARCSTAT(arcstat_loaned_bytes)
705 #define arc_dnode_limit ARCSTAT(arcstat_dnode_limit) /* max size for dnodes */
706 #define arc_need_free ARCSTAT(arcstat_need_free) /* waiting to be evicted */
707
708 hrtime_t arc_growtime;
709 list_t arc_prune_list;
710 kmutex_t arc_prune_mtx;
711 taskq_t *arc_prune_taskq;
712
713 #define GHOST_STATE(state) \
714 ((state) == arc_mru_ghost || (state) == arc_mfu_ghost || \
715 (state) == arc_l2c_only)
716
717 #define HDR_IN_HASH_TABLE(hdr) ((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
718 #define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
719 #define HDR_IO_ERROR(hdr) ((hdr)->b_flags & ARC_FLAG_IO_ERROR)
720 #define HDR_PREFETCH(hdr) ((hdr)->b_flags & ARC_FLAG_PREFETCH)
721 #define HDR_PRESCIENT_PREFETCH(hdr) \
722 ((hdr)->b_flags & ARC_FLAG_PRESCIENT_PREFETCH)
723 #define HDR_COMPRESSION_ENABLED(hdr) \
724 ((hdr)->b_flags & ARC_FLAG_COMPRESSED_ARC)
725
726 #define HDR_L2CACHE(hdr) ((hdr)->b_flags & ARC_FLAG_L2CACHE)
727 #define HDR_UNCACHED(hdr) ((hdr)->b_flags & ARC_FLAG_UNCACHED)
728 #define HDR_L2_READING(hdr) \
729 (((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) && \
730 ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
731 #define HDR_L2_WRITING(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITING)
732 #define HDR_L2_EVICTED(hdr) ((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
733 #define HDR_L2_WRITE_HEAD(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
734 #define HDR_PROTECTED(hdr) ((hdr)->b_flags & ARC_FLAG_PROTECTED)
735 #define HDR_NOAUTH(hdr) ((hdr)->b_flags & ARC_FLAG_NOAUTH)
736 #define HDR_SHARED_DATA(hdr) ((hdr)->b_flags & ARC_FLAG_SHARED_DATA)
737
738 #define HDR_ISTYPE_METADATA(hdr) \
739 ((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
740 #define HDR_ISTYPE_DATA(hdr) (!HDR_ISTYPE_METADATA(hdr))
741
742 #define HDR_HAS_L1HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
743 #define HDR_HAS_L2HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
744 #define HDR_HAS_RABD(hdr) \
745 (HDR_HAS_L1HDR(hdr) && HDR_PROTECTED(hdr) && \
746 (hdr)->b_crypt_hdr.b_rabd != NULL)
747 #define HDR_ENCRYPTED(hdr) \
748 (HDR_PROTECTED(hdr) && DMU_OT_IS_ENCRYPTED((hdr)->b_crypt_hdr.b_ot))
749 #define HDR_AUTHENTICATED(hdr) \
750 (HDR_PROTECTED(hdr) && !DMU_OT_IS_ENCRYPTED((hdr)->b_crypt_hdr.b_ot))
751
752 /* For storing compression mode in b_flags */
753 #define HDR_COMPRESS_OFFSET (highbit64(ARC_FLAG_COMPRESS_0) - 1)
754
755 #define HDR_GET_COMPRESS(hdr) ((enum zio_compress)BF32_GET((hdr)->b_flags, \
756 HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS))
757 #define HDR_SET_COMPRESS(hdr, cmp) BF32_SET((hdr)->b_flags, \
758 HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS, (cmp));
759
760 #define ARC_BUF_LAST(buf) ((buf)->b_next == NULL)
761 #define ARC_BUF_SHARED(buf) ((buf)->b_flags & ARC_BUF_FLAG_SHARED)
762 #define ARC_BUF_COMPRESSED(buf) ((buf)->b_flags & ARC_BUF_FLAG_COMPRESSED)
763 #define ARC_BUF_ENCRYPTED(buf) ((buf)->b_flags & ARC_BUF_FLAG_ENCRYPTED)
764
765 /*
766 * Other sizes
767 */
768
769 #define HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
770 #define HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
771
772 /*
773 * Hash table routines
774 */
775
776 #define BUF_LOCKS 2048
777 typedef struct buf_hash_table {
778 uint64_t ht_mask;
779 arc_buf_hdr_t **ht_table;
780 kmutex_t ht_locks[BUF_LOCKS] ____cacheline_aligned;
781 } buf_hash_table_t;
782
783 static buf_hash_table_t buf_hash_table;
784
785 #define BUF_HASH_INDEX(spa, dva, birth) \
786 (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
787 #define BUF_HASH_LOCK(idx) (&buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
788 #define HDR_LOCK(hdr) \
789 (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
790
791 uint64_t zfs_crc64_table[256];
792
793 /*
794 * Asynchronous ARC flush
795 *
796 * We track these in a list for arc_async_flush_guid_inuse().
797 * Used for both L1 and L2 async teardown.
798 */
799 static list_t arc_async_flush_list;
800 static kmutex_t arc_async_flush_lock;
801
802 typedef struct arc_async_flush {
803 uint64_t af_spa_guid;
804 taskq_ent_t af_tqent;
805 uint_t af_cache_level; /* 1 or 2 to differentiate node */
806 list_node_t af_node;
807 } arc_async_flush_t;
808
809
810 /*
811 * Level 2 ARC
812 */
813
814 #define L2ARC_WRITE_SIZE (64 * 1024 * 1024) /* initial write max */
815 #define L2ARC_BURST_SIZE_MAX (64 * 1024 * 1024) /* max burst size */
816 #define L2ARC_HEADROOM 8 /* num of writes */
817
818 /*
819 * If we discover during ARC scan any buffers to be compressed, we boost
820 * our headroom for the next scanning cycle by this percentage multiple.
821 */
822 #define L2ARC_HEADROOM_BOOST 200
823 #define L2ARC_FEED_SECS 1 /* caching interval secs */
824 #define L2ARC_FEED_MIN_MS 200 /* min caching interval ms */
825
826 /*
827 * Min L2ARC capacity to enable persistent markers, adaptive intervals, and
828 * DWPD rate limiting. L2ARC must be at least twice arc_c_max to benefit from
829 * inclusive caching - smaller L2ARC would either cyclically overwrite itself
830 * (if L2ARC < ARC) or merely duplicate ARC contents (if L2ARC = ARC).
831 * With L2ARC >= 2*ARC, there's room for ARC duplication plus additional
832 * cached data.
833 */
834 #define L2ARC_PERSIST_THRESHOLD (arc_c_max * 2)
835
836 /* L2ARC Performance Tunables */
837 static uint64_t l2arc_write_max = L2ARC_WRITE_SIZE; /* def max write size */
838 uint64_t l2arc_dwpd_limit = 100; /* 100 = 1.0 DWPD */
839 static uint64_t l2arc_dwpd_bump = 0; /* DWPD reset trigger */
840 static uint64_t l2arc_headroom = L2ARC_HEADROOM; /* # of dev writes */
841 static uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
842 static uint64_t l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
843 static uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval msecs */
844 static int l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
845 static int l2arc_feed_again = B_TRUE; /* turbo warmup */
846 static int l2arc_norw = B_FALSE; /* no reads during writes */
847 static uint_t l2arc_meta_percent = 33; /* limit on headers size */
848
849 /*
850 * L2ARC Internals
851 */
852 static list_t L2ARC_dev_list; /* device list */
853 static list_t *l2arc_dev_list; /* device list pointer */
854 static kmutex_t l2arc_dev_mtx; /* device list mutex */
855 static list_t L2ARC_free_on_write; /* free after write buf list */
856 static list_t *l2arc_free_on_write; /* free after write list ptr */
857 static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
858 static uint64_t l2arc_ndev; /* number of devices */
859
860 typedef struct l2arc_read_callback {
861 arc_buf_hdr_t *l2rcb_hdr; /* read header */
862 blkptr_t l2rcb_bp; /* original blkptr */
863 zbookmark_phys_t l2rcb_zb; /* original bookmark */
864 int l2rcb_flags; /* original flags */
865 abd_t *l2rcb_abd; /* temporary buffer */
866 } l2arc_read_callback_t;
867
868 typedef struct l2arc_data_free {
869 /* protected by l2arc_free_on_write_mtx */
870 abd_t *l2df_abd;
871 l2arc_dev_t *l2df_dev; /* L2ARC device that owns this ABD */
872 list_node_t l2df_list_node;
873 } l2arc_data_free_t;
874
875 typedef enum arc_fill_flags {
876 ARC_FILL_LOCKED = 1 << 0, /* hdr lock is held */
877 ARC_FILL_COMPRESSED = 1 << 1, /* fill with compressed data */
878 ARC_FILL_ENCRYPTED = 1 << 2, /* fill with encrypted data */
879 ARC_FILL_NOAUTH = 1 << 3, /* don't attempt to authenticate */
880 ARC_FILL_IN_PLACE = 1 << 4 /* fill in place (special case) */
881 } arc_fill_flags_t;
882
883 typedef enum arc_ovf_level {
884 ARC_OVF_NONE, /* ARC within target size. */
885 ARC_OVF_SOME, /* ARC is slightly overflowed. */
886 ARC_OVF_SEVERE /* ARC is severely overflowed. */
887 } arc_ovf_level_t;
888
889 static kmutex_t l2arc_rebuild_thr_lock;
890 static kcondvar_t l2arc_rebuild_thr_cv;
891
892 enum arc_hdr_alloc_flags {
893 ARC_HDR_ALLOC_RDATA = 0x1,
894 ARC_HDR_USE_RESERVE = 0x4,
895 ARC_HDR_ALLOC_LINEAR = 0x8,
896 };
897
898
899 static abd_t *arc_get_data_abd(arc_buf_hdr_t *, uint64_t, const void *, int);
900 static void *arc_get_data_buf(arc_buf_hdr_t *, uint64_t, const void *);
901 static void arc_get_data_impl(arc_buf_hdr_t *, uint64_t, const void *, int);
902 static void arc_free_data_abd(arc_buf_hdr_t *, abd_t *, uint64_t, const void *);
903 static void arc_free_data_buf(arc_buf_hdr_t *, void *, uint64_t, const void *);
904 static void arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size,
905 const void *tag);
906 static void arc_hdr_free_abd(arc_buf_hdr_t *, boolean_t);
907 static void arc_hdr_alloc_abd(arc_buf_hdr_t *, int);
908 static void arc_hdr_destroy(arc_buf_hdr_t *);
909 static void arc_access(arc_buf_hdr_t *, arc_flags_t, boolean_t);
910 static void arc_buf_watch(arc_buf_t *);
911 static void arc_change_state(arc_state_t *, arc_buf_hdr_t *);
912
913 static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
914 static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
915 static inline void arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
916 static inline void arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
917
918 static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
919 static void l2arc_read_done(zio_t *);
920 static void l2arc_do_free_on_write(l2arc_dev_t *dev);
921 static void l2arc_hdr_arcstats_update(arc_buf_hdr_t *hdr, boolean_t incr,
922 boolean_t state_only);
923 static uint64_t l2arc_get_write_rate(l2arc_dev_t *dev);
924
925 static void arc_prune_async(uint64_t adjust);
926
927 #define l2arc_hdr_arcstats_increment(hdr) \
928 l2arc_hdr_arcstats_update((hdr), B_TRUE, B_FALSE)
929 #define l2arc_hdr_arcstats_decrement(hdr) \
930 l2arc_hdr_arcstats_update((hdr), B_FALSE, B_FALSE)
931 #define l2arc_hdr_arcstats_increment_state(hdr) \
932 l2arc_hdr_arcstats_update((hdr), B_TRUE, B_TRUE)
933 #define l2arc_hdr_arcstats_decrement_state(hdr) \
934 l2arc_hdr_arcstats_update((hdr), B_FALSE, B_TRUE)
935
936 /*
937 * l2arc_exclude_special : A zfs module parameter that controls whether buffers
938 * present on special vdevs are eligibile for caching in L2ARC. If
939 * set to 1, exclude dbufs on special vdevs from being cached to
940 * L2ARC.
941 */
942 int l2arc_exclude_special = 0;
943
944 /*
945 * l2arc_mfuonly : A ZFS module parameter that controls whether only MFU
946 * metadata and data are cached from ARC into L2ARC.
947 */
948 static int l2arc_mfuonly = 0;
949
950 /*
951 * Depth cap as percentage of state size. Each pass resets its markers
952 * to tail after scanning this fraction of the state. Keeps markers
953 * focused on the tail zone where L2ARC adds the most value.
954 */
955 static uint64_t l2arc_ext_headroom_pct = 25;
956
957 /*
958 * Metadata monopolization limit. When metadata fills the write budget
959 * for this many consecutive cycles while data gets nothing, skip metadata
960 * for one cycle to let data run, then reset the counter.
961 * With N=2, the steady-state pattern under sustained monopolization is
962 * 2 metadata cycles followed by 1 data cycle (67%/33% split).
963 */
964 static uint64_t l2arc_meta_cycles = 2;
965
966 /*
967 * L2ARC TRIM
968 * l2arc_trim_ahead : A ZFS module parameter that controls how much ahead of
969 * the current write size (l2arc_write_max) we should TRIM if we
970 * have filled the device. It is defined as a percentage of the
971 * write size. If set to 100 we trim twice the space required to
972 * accommodate upcoming writes. A minimum of 64MB will be trimmed.
973 * It also enables TRIM of the whole L2ARC device upon creation or
974 * addition to an existing pool or if the header of the device is
975 * invalid upon importing a pool or onlining a cache device. The
976 * default is 0, which disables TRIM on L2ARC altogether as it can
977 * put significant stress on the underlying storage devices. This
978 * will vary depending of how well the specific device handles
979 * these commands.
980 */
981 static uint64_t l2arc_trim_ahead = 0;
982
983 /*
984 * Performance tuning of L2ARC persistence:
985 *
986 * l2arc_rebuild_enabled : A ZFS module parameter that controls whether adding
987 * an L2ARC device (either at pool import or later) will attempt
988 * to rebuild L2ARC buffer contents.
989 * l2arc_rebuild_blocks_min_l2size : A ZFS module parameter that controls
990 * whether log blocks are written to the L2ARC device. If the L2ARC
991 * device is less than 1GB, the amount of data l2arc_evict()
992 * evicts is significant compared to the amount of restored L2ARC
993 * data. In this case do not write log blocks in L2ARC in order
994 * not to waste space.
995 */
996 static int l2arc_rebuild_enabled = B_TRUE;
997 static uint64_t l2arc_rebuild_blocks_min_l2size = 1024 * 1024 * 1024;
998
999 /* L2ARC persistence rebuild control routines. */
1000 void l2arc_rebuild_vdev(vdev_t *vd, boolean_t reopen);
1001 static __attribute__((noreturn)) void l2arc_dev_rebuild_thread(void *arg);
1002 static int l2arc_rebuild(l2arc_dev_t *dev);
1003
1004 /* L2ARC persistence read I/O routines. */
1005 static int l2arc_dev_hdr_read(l2arc_dev_t *dev);
1006 static int l2arc_log_blk_read(l2arc_dev_t *dev,
1007 const l2arc_log_blkptr_t *this_lp, const l2arc_log_blkptr_t *next_lp,
1008 l2arc_log_blk_phys_t *this_lb, l2arc_log_blk_phys_t *next_lb,
1009 zio_t *this_io, zio_t **next_io);
1010 static zio_t *l2arc_log_blk_fetch(vdev_t *vd,
1011 const l2arc_log_blkptr_t *lp, l2arc_log_blk_phys_t *lb);
1012 static void l2arc_log_blk_fetch_abort(zio_t *zio);
1013
1014 /* L2ARC persistence block restoration routines. */
1015 static void l2arc_log_blk_restore(l2arc_dev_t *dev,
1016 const l2arc_log_blk_phys_t *lb, uint64_t lb_asize);
1017 static void l2arc_hdr_restore(const l2arc_log_ent_phys_t *le,
1018 l2arc_dev_t *dev);
1019
1020 /* L2ARC persistence write I/O routines. */
1021 static uint64_t l2arc_log_blk_commit(l2arc_dev_t *dev, zio_t *pio,
1022 l2arc_write_callback_t *cb);
1023
1024 /* L2ARC persistence auxiliary routines. */
1025 boolean_t l2arc_log_blkptr_valid(l2arc_dev_t *dev,
1026 const l2arc_log_blkptr_t *lbp);
1027 static boolean_t l2arc_log_blk_insert(l2arc_dev_t *dev,
1028 const arc_buf_hdr_t *ab);
1029 boolean_t l2arc_range_check_overlap(uint64_t bottom,
1030 uint64_t top, uint64_t check);
1031 static void l2arc_blk_fetch_done(zio_t *zio);
1032 static inline uint64_t
1033 l2arc_log_blk_overhead(uint64_t write_sz, l2arc_dev_t *dev);
1034
1035 /*
1036 * We use Cityhash for this. It's fast, and has good hash properties without
1037 * requiring any large static buffers.
1038 */
1039 static uint64_t
buf_hash(uint64_t spa,const dva_t * dva,uint64_t birth)1040 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
1041 {
1042 return (cityhash4(spa, dva->dva_word[0], dva->dva_word[1], birth));
1043 }
1044
1045 #define HDR_EMPTY(hdr) \
1046 ((hdr)->b_dva.dva_word[0] == 0 && \
1047 (hdr)->b_dva.dva_word[1] == 0)
1048
1049 #define HDR_EMPTY_OR_LOCKED(hdr) \
1050 (HDR_EMPTY(hdr) || MUTEX_HELD(HDR_LOCK(hdr)))
1051
1052 #define HDR_EQUAL(spa, dva, birth, hdr) \
1053 ((hdr)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
1054 ((hdr)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
1055 ((hdr)->b_birth == birth) && ((hdr)->b_spa == spa)
1056
1057 static void
buf_discard_identity(arc_buf_hdr_t * hdr)1058 buf_discard_identity(arc_buf_hdr_t *hdr)
1059 {
1060 VERIFY(!HDR_IN_HASH_TABLE(hdr));
1061 hdr->b_dva.dva_word[0] = 0;
1062 hdr->b_dva.dva_word[1] = 0;
1063 hdr->b_birth = 0;
1064 }
1065
1066 static arc_buf_hdr_t *
buf_hash_find(uint64_t spa,const blkptr_t * bp,kmutex_t ** lockp)1067 buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
1068 {
1069 const dva_t *dva = BP_IDENTITY(bp);
1070 uint64_t birth = BP_GET_PHYSICAL_BIRTH(bp);
1071 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1072 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1073 arc_buf_hdr_t *hdr;
1074
1075 mutex_enter(hash_lock);
1076 for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
1077 hdr = hdr->b_hash_next) {
1078 if (HDR_EQUAL(spa, dva, birth, hdr)) {
1079 *lockp = hash_lock;
1080 return (hdr);
1081 }
1082 }
1083 mutex_exit(hash_lock);
1084 *lockp = NULL;
1085 return (NULL);
1086 }
1087
1088 /*
1089 * Insert an entry into the hash table. If there is already an element
1090 * equal to elem in the hash table, then the already existing element
1091 * will be returned and the new element will not be inserted.
1092 * Otherwise returns NULL.
1093 * If lockp == NULL, the caller is assumed to already hold the hash lock.
1094 */
1095 static arc_buf_hdr_t *
buf_hash_insert(arc_buf_hdr_t * hdr,kmutex_t ** lockp)1096 buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1097 {
1098 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1099 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1100 arc_buf_hdr_t *fhdr;
1101 uint32_t i;
1102
1103 ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
1104 ASSERT(hdr->b_birth != 0);
1105 ASSERT(!HDR_IN_HASH_TABLE(hdr));
1106
1107 if (lockp != NULL) {
1108 *lockp = hash_lock;
1109 mutex_enter(hash_lock);
1110 } else {
1111 ASSERT(MUTEX_HELD(hash_lock));
1112 }
1113
1114 for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
1115 fhdr = fhdr->b_hash_next, i++) {
1116 if (HDR_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
1117 return (fhdr);
1118 }
1119
1120 hdr->b_hash_next = buf_hash_table.ht_table[idx];
1121 buf_hash_table.ht_table[idx] = hdr;
1122 arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1123
1124 /* collect some hash table performance data */
1125 if (i > 0) {
1126 ARCSTAT_BUMP(arcstat_hash_collisions);
1127 if (i == 1)
1128 ARCSTAT_BUMP(arcstat_hash_chains);
1129 ARCSTAT_MAX(arcstat_hash_chain_max, i);
1130 }
1131 ARCSTAT_BUMP(arcstat_hash_elements);
1132
1133 return (NULL);
1134 }
1135
1136 static void
buf_hash_remove(arc_buf_hdr_t * hdr)1137 buf_hash_remove(arc_buf_hdr_t *hdr)
1138 {
1139 arc_buf_hdr_t *fhdr, **hdrp;
1140 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1141
1142 VERIFY(MUTEX_HELD(BUF_HASH_LOCK(idx)));
1143 ASSERT(HDR_IN_HASH_TABLE(hdr));
1144
1145 hdrp = &buf_hash_table.ht_table[idx];
1146 while ((fhdr = *hdrp) != hdr) {
1147 ASSERT3P(fhdr, !=, NULL);
1148 hdrp = &fhdr->b_hash_next;
1149 }
1150 *hdrp = hdr->b_hash_next;
1151 hdr->b_hash_next = NULL;
1152 arc_hdr_clear_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1153
1154 /* collect some hash table performance data */
1155 ARCSTAT_BUMPDOWN(arcstat_hash_elements);
1156 if (buf_hash_table.ht_table[idx] &&
1157 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1158 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1159 }
1160
1161 /*
1162 * Global data structures and functions for the buf kmem cache.
1163 */
1164
1165 static kmem_cache_t *hdr_full_cache;
1166 static kmem_cache_t *hdr_l2only_cache;
1167 static kmem_cache_t *buf_cache;
1168
1169 static void
buf_fini(void)1170 buf_fini(void)
1171 {
1172 #if defined(_KERNEL)
1173 /*
1174 * Large allocations which do not require contiguous pages
1175 * should be using vmem_free() in the linux kernel.
1176 */
1177 vmem_free(buf_hash_table.ht_table,
1178 (buf_hash_table.ht_mask + 1) * sizeof (void *));
1179 #else
1180 kmem_free(buf_hash_table.ht_table,
1181 (buf_hash_table.ht_mask + 1) * sizeof (void *));
1182 #endif
1183 for (int i = 0; i < BUF_LOCKS; i++)
1184 mutex_destroy(BUF_HASH_LOCK(i));
1185 kmem_cache_destroy(hdr_full_cache);
1186 kmem_cache_destroy(hdr_l2only_cache);
1187 kmem_cache_destroy(buf_cache);
1188 }
1189
1190 /*
1191 * Constructor callback - called when the cache is empty
1192 * and a new buf is requested.
1193 */
1194 static int
hdr_full_cons(void * vbuf,void * unused,int kmflag)1195 hdr_full_cons(void *vbuf, void *unused, int kmflag)
1196 {
1197 (void) unused, (void) kmflag;
1198 arc_buf_hdr_t *hdr = vbuf;
1199
1200 memset(hdr, 0, HDR_FULL_SIZE);
1201 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
1202 zfs_refcount_create(&hdr->b_l1hdr.b_refcnt);
1203 #ifdef ZFS_DEBUG
1204 mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1205 #endif
1206 multilist_link_init(&hdr->b_l1hdr.b_arc_node);
1207 list_link_init(&hdr->b_l2hdr.b_l2node);
1208 arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1209
1210 return (0);
1211 }
1212
1213 static int
hdr_l2only_cons(void * vbuf,void * unused,int kmflag)1214 hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
1215 {
1216 (void) unused, (void) kmflag;
1217 arc_buf_hdr_t *hdr = vbuf;
1218
1219 memset(hdr, 0, HDR_L2ONLY_SIZE);
1220 arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1221
1222 return (0);
1223 }
1224
1225 static int
buf_cons(void * vbuf,void * unused,int kmflag)1226 buf_cons(void *vbuf, void *unused, int kmflag)
1227 {
1228 (void) unused, (void) kmflag;
1229 arc_buf_t *buf = vbuf;
1230
1231 memset(buf, 0, sizeof (arc_buf_t));
1232 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1233
1234 return (0);
1235 }
1236
1237 /*
1238 * Destructor callback - called when a cached buf is
1239 * no longer required.
1240 */
1241 static void
hdr_full_dest(void * vbuf,void * unused)1242 hdr_full_dest(void *vbuf, void *unused)
1243 {
1244 (void) unused;
1245 arc_buf_hdr_t *hdr = vbuf;
1246
1247 ASSERT(HDR_EMPTY(hdr));
1248 zfs_refcount_destroy(&hdr->b_l1hdr.b_refcnt);
1249 #ifdef ZFS_DEBUG
1250 mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1251 #endif
1252 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1253 arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1254 }
1255
1256 static void
hdr_l2only_dest(void * vbuf,void * unused)1257 hdr_l2only_dest(void *vbuf, void *unused)
1258 {
1259 (void) unused;
1260 arc_buf_hdr_t *hdr = vbuf;
1261
1262 ASSERT(HDR_EMPTY(hdr));
1263 arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1264 }
1265
1266 static void
buf_dest(void * vbuf,void * unused)1267 buf_dest(void *vbuf, void *unused)
1268 {
1269 (void) unused;
1270 (void) vbuf;
1271
1272 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1273 }
1274
1275 static void
buf_init(void)1276 buf_init(void)
1277 {
1278 uint64_t *ct = NULL;
1279 uint64_t hsize = 1ULL << 12;
1280 int i, j;
1281
1282 /*
1283 * The hash table is big enough to fill all of physical memory
1284 * with an average block size of zfs_arc_average_blocksize (default 8K).
1285 * By default, the table will take up
1286 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1287 */
1288 while (hsize * zfs_arc_average_blocksize < arc_all_memory())
1289 hsize <<= 1;
1290 retry:
1291 buf_hash_table.ht_mask = hsize - 1;
1292 #if defined(_KERNEL)
1293 /*
1294 * Large allocations which do not require contiguous pages
1295 * should be using vmem_alloc() in the linux kernel
1296 */
1297 buf_hash_table.ht_table =
1298 vmem_zalloc(hsize * sizeof (void*), KM_SLEEP);
1299 #else
1300 buf_hash_table.ht_table =
1301 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1302 #endif
1303 if (buf_hash_table.ht_table == NULL) {
1304 ASSERT(hsize > (1ULL << 8));
1305 hsize >>= 1;
1306 goto retry;
1307 }
1308
1309 hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
1310 0, hdr_full_cons, hdr_full_dest, NULL, NULL, NULL, KMC_RECLAIMABLE);
1311 hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
1312 HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, NULL,
1313 NULL, NULL, 0);
1314 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1315 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1316
1317 for (i = 0; i < 256; i++)
1318 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1319 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1320
1321 for (i = 0; i < BUF_LOCKS; i++)
1322 mutex_init(BUF_HASH_LOCK(i), NULL, MUTEX_DEFAULT, NULL);
1323 }
1324
1325 #define ARC_MINTIME (hz>>4) /* 62 ms */
1326
1327 /*
1328 * This is the size that the buf occupies in memory. If the buf is compressed,
1329 * it will correspond to the compressed size. You should use this method of
1330 * getting the buf size unless you explicitly need the logical size.
1331 */
1332 uint64_t
arc_buf_size(arc_buf_t * buf)1333 arc_buf_size(arc_buf_t *buf)
1334 {
1335 return (ARC_BUF_COMPRESSED(buf) ?
1336 HDR_GET_PSIZE(buf->b_hdr) : HDR_GET_LSIZE(buf->b_hdr));
1337 }
1338
1339 uint64_t
arc_buf_lsize(arc_buf_t * buf)1340 arc_buf_lsize(arc_buf_t *buf)
1341 {
1342 return (HDR_GET_LSIZE(buf->b_hdr));
1343 }
1344
1345 /*
1346 * This function will return B_TRUE if the buffer is encrypted in memory.
1347 * This buffer can be decrypted by calling arc_untransform().
1348 */
1349 boolean_t
arc_is_encrypted(arc_buf_t * buf)1350 arc_is_encrypted(arc_buf_t *buf)
1351 {
1352 return (ARC_BUF_ENCRYPTED(buf) != 0);
1353 }
1354
1355 /*
1356 * Returns B_TRUE if the buffer represents data that has not had its MAC
1357 * verified yet.
1358 */
1359 boolean_t
arc_is_unauthenticated(arc_buf_t * buf)1360 arc_is_unauthenticated(arc_buf_t *buf)
1361 {
1362 return (HDR_NOAUTH(buf->b_hdr) != 0);
1363 }
1364
1365 void
arc_get_raw_params(arc_buf_t * buf,boolean_t * byteorder,uint8_t * salt,uint8_t * iv,uint8_t * mac)1366 arc_get_raw_params(arc_buf_t *buf, boolean_t *byteorder, uint8_t *salt,
1367 uint8_t *iv, uint8_t *mac)
1368 {
1369 arc_buf_hdr_t *hdr = buf->b_hdr;
1370
1371 ASSERT(HDR_PROTECTED(hdr));
1372
1373 memcpy(salt, hdr->b_crypt_hdr.b_salt, ZIO_DATA_SALT_LEN);
1374 memcpy(iv, hdr->b_crypt_hdr.b_iv, ZIO_DATA_IV_LEN);
1375 memcpy(mac, hdr->b_crypt_hdr.b_mac, ZIO_DATA_MAC_LEN);
1376 *byteorder = (hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS) ?
1377 ZFS_HOST_BYTEORDER : !ZFS_HOST_BYTEORDER;
1378 }
1379
1380 /*
1381 * Indicates how this buffer is compressed in memory. If it is not compressed
1382 * the value will be ZIO_COMPRESS_OFF. It can be made normally readable with
1383 * arc_untransform() as long as it is also unencrypted.
1384 */
1385 enum zio_compress
arc_get_compression(arc_buf_t * buf)1386 arc_get_compression(arc_buf_t *buf)
1387 {
1388 return (ARC_BUF_COMPRESSED(buf) ?
1389 HDR_GET_COMPRESS(buf->b_hdr) : ZIO_COMPRESS_OFF);
1390 }
1391
1392 /*
1393 * Return the compression algorithm used to store this data in the ARC. If ARC
1394 * compression is enabled or this is an encrypted block, this will be the same
1395 * as what's used to store it on-disk. Otherwise, this will be ZIO_COMPRESS_OFF.
1396 */
1397 static inline enum zio_compress
arc_hdr_get_compress(arc_buf_hdr_t * hdr)1398 arc_hdr_get_compress(arc_buf_hdr_t *hdr)
1399 {
1400 return (HDR_COMPRESSION_ENABLED(hdr) ?
1401 HDR_GET_COMPRESS(hdr) : ZIO_COMPRESS_OFF);
1402 }
1403
1404 uint8_t
arc_get_complevel(arc_buf_t * buf)1405 arc_get_complevel(arc_buf_t *buf)
1406 {
1407 return (buf->b_hdr->b_complevel);
1408 }
1409
1410 __maybe_unused
1411 static inline boolean_t
arc_buf_is_shared(arc_buf_t * buf)1412 arc_buf_is_shared(arc_buf_t *buf)
1413 {
1414 boolean_t shared = (buf->b_data != NULL &&
1415 buf->b_hdr->b_l1hdr.b_pabd != NULL &&
1416 abd_is_linear(buf->b_hdr->b_l1hdr.b_pabd) &&
1417 buf->b_data == abd_to_buf(buf->b_hdr->b_l1hdr.b_pabd));
1418 IMPLY(shared, HDR_SHARED_DATA(buf->b_hdr));
1419 EQUIV(shared, ARC_BUF_SHARED(buf));
1420 IMPLY(shared, ARC_BUF_COMPRESSED(buf) || ARC_BUF_LAST(buf));
1421
1422 /*
1423 * It would be nice to assert arc_can_share() too, but the "hdr isn't
1424 * already being shared" requirement prevents us from doing that.
1425 */
1426
1427 return (shared);
1428 }
1429
1430 /*
1431 * Free the checksum associated with this header. If there is no checksum, this
1432 * is a no-op.
1433 */
1434 static inline void
arc_cksum_free(arc_buf_hdr_t * hdr)1435 arc_cksum_free(arc_buf_hdr_t *hdr)
1436 {
1437 #ifdef ZFS_DEBUG
1438 ASSERT(HDR_HAS_L1HDR(hdr));
1439
1440 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1441 if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
1442 kmem_free(hdr->b_l1hdr.b_freeze_cksum, sizeof (zio_cksum_t));
1443 hdr->b_l1hdr.b_freeze_cksum = NULL;
1444 }
1445 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1446 #endif
1447 }
1448
1449 /*
1450 * Return true iff at least one of the bufs on hdr is not compressed.
1451 * Encrypted buffers count as compressed.
1452 */
1453 static boolean_t
arc_hdr_has_uncompressed_buf(arc_buf_hdr_t * hdr)1454 arc_hdr_has_uncompressed_buf(arc_buf_hdr_t *hdr)
1455 {
1456 ASSERT(hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY_OR_LOCKED(hdr));
1457
1458 for (arc_buf_t *b = hdr->b_l1hdr.b_buf; b != NULL; b = b->b_next) {
1459 if (!ARC_BUF_COMPRESSED(b)) {
1460 return (B_TRUE);
1461 }
1462 }
1463 return (B_FALSE);
1464 }
1465
1466
1467 /*
1468 * If we've turned on the ZFS_DEBUG_MODIFY flag, verify that the buf's data
1469 * matches the checksum that is stored in the hdr. If there is no checksum,
1470 * or if the buf is compressed, this is a no-op.
1471 */
1472 static void
arc_cksum_verify(arc_buf_t * buf)1473 arc_cksum_verify(arc_buf_t *buf)
1474 {
1475 #ifdef ZFS_DEBUG
1476 arc_buf_hdr_t *hdr = buf->b_hdr;
1477 zio_cksum_t zc;
1478
1479 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1480 return;
1481
1482 if (ARC_BUF_COMPRESSED(buf))
1483 return;
1484
1485 ASSERT(HDR_HAS_L1HDR(hdr));
1486
1487 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1488
1489 if (hdr->b_l1hdr.b_freeze_cksum == NULL || HDR_IO_ERROR(hdr)) {
1490 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1491 return;
1492 }
1493
1494 fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL, &zc);
1495 if (!ZIO_CHECKSUM_EQUAL(*hdr->b_l1hdr.b_freeze_cksum, zc))
1496 panic("buffer modified while frozen!");
1497 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1498 #endif
1499 }
1500
1501 /*
1502 * This function makes the assumption that data stored in the L2ARC
1503 * will be transformed exactly as it is in the main pool. Because of
1504 * this we can verify the checksum against the reading process's bp.
1505 */
1506 static boolean_t
arc_cksum_is_equal(arc_buf_hdr_t * hdr,zio_t * zio)1507 arc_cksum_is_equal(arc_buf_hdr_t *hdr, zio_t *zio)
1508 {
1509 ASSERT(!BP_IS_EMBEDDED(zio->io_bp));
1510 VERIFY3U(BP_GET_PSIZE(zio->io_bp), ==, HDR_GET_PSIZE(hdr));
1511
1512 /*
1513 * Block pointers always store the checksum for the logical data.
1514 * If the block pointer has the gang bit set, then the checksum
1515 * it represents is for the reconstituted data and not for an
1516 * individual gang member. The zio pipeline, however, must be able to
1517 * determine the checksum of each of the gang constituents so it
1518 * treats the checksum comparison differently than what we need
1519 * for l2arc blocks. This prevents us from using the
1520 * zio_checksum_error() interface directly. Instead we must call the
1521 * zio_checksum_error_impl() so that we can ensure the checksum is
1522 * generated using the correct checksum algorithm and accounts for the
1523 * logical I/O size and not just a gang fragment.
1524 */
1525 return (zio_checksum_error_impl(zio->io_spa, zio->io_bp,
1526 BP_GET_CHECKSUM(zio->io_bp), zio->io_abd, zio->io_size,
1527 zio->io_offset, NULL) == 0);
1528 }
1529
1530 /*
1531 * Given a buf full of data, if ZFS_DEBUG_MODIFY is enabled this computes a
1532 * checksum and attaches it to the buf's hdr so that we can ensure that the buf
1533 * isn't modified later on. If buf is compressed or there is already a checksum
1534 * on the hdr, this is a no-op (we only checksum uncompressed bufs).
1535 */
1536 static void
arc_cksum_compute(arc_buf_t * buf)1537 arc_cksum_compute(arc_buf_t *buf)
1538 {
1539 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1540 return;
1541
1542 #ifdef ZFS_DEBUG
1543 arc_buf_hdr_t *hdr = buf->b_hdr;
1544 ASSERT(HDR_HAS_L1HDR(hdr));
1545 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1546 if (hdr->b_l1hdr.b_freeze_cksum != NULL || ARC_BUF_COMPRESSED(buf)) {
1547 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1548 return;
1549 }
1550
1551 ASSERT(!ARC_BUF_ENCRYPTED(buf));
1552 ASSERT(!ARC_BUF_COMPRESSED(buf));
1553 hdr->b_l1hdr.b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t),
1554 KM_SLEEP);
1555 fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL,
1556 hdr->b_l1hdr.b_freeze_cksum);
1557 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1558 #endif
1559 arc_buf_watch(buf);
1560 }
1561
1562 #ifndef _KERNEL
1563 void
arc_buf_sigsegv(int sig,siginfo_t * si,void * unused)1564 arc_buf_sigsegv(int sig, siginfo_t *si, void *unused)
1565 {
1566 (void) sig, (void) unused;
1567 panic("Got SIGSEGV at address: 0x%lx\n", (long)si->si_addr);
1568 }
1569 #endif
1570
1571 static void
arc_buf_unwatch(arc_buf_t * buf)1572 arc_buf_unwatch(arc_buf_t *buf)
1573 {
1574 #ifndef _KERNEL
1575 if (arc_watch) {
1576 ASSERT0(mprotect(buf->b_data, arc_buf_size(buf),
1577 PROT_READ | PROT_WRITE));
1578 }
1579 #else
1580 (void) buf;
1581 #endif
1582 }
1583
1584 static void
arc_buf_watch(arc_buf_t * buf)1585 arc_buf_watch(arc_buf_t *buf)
1586 {
1587 #ifndef _KERNEL
1588 if (arc_watch)
1589 ASSERT0(mprotect(buf->b_data, arc_buf_size(buf),
1590 PROT_READ));
1591 #else
1592 (void) buf;
1593 #endif
1594 }
1595
1596 static arc_buf_contents_t
arc_buf_type(arc_buf_hdr_t * hdr)1597 arc_buf_type(arc_buf_hdr_t *hdr)
1598 {
1599 arc_buf_contents_t type;
1600 if (HDR_ISTYPE_METADATA(hdr)) {
1601 type = ARC_BUFC_METADATA;
1602 } else {
1603 type = ARC_BUFC_DATA;
1604 }
1605 VERIFY3U(hdr->b_type, ==, type);
1606 return (type);
1607 }
1608
1609 boolean_t
arc_is_metadata(arc_buf_t * buf)1610 arc_is_metadata(arc_buf_t *buf)
1611 {
1612 return (HDR_ISTYPE_METADATA(buf->b_hdr) != 0);
1613 }
1614
1615 static uint32_t
arc_bufc_to_flags(arc_buf_contents_t type)1616 arc_bufc_to_flags(arc_buf_contents_t type)
1617 {
1618 switch (type) {
1619 case ARC_BUFC_DATA:
1620 /* metadata field is 0 if buffer contains normal data */
1621 return (0);
1622 case ARC_BUFC_METADATA:
1623 return (ARC_FLAG_BUFC_METADATA);
1624 default:
1625 break;
1626 }
1627 panic("undefined ARC buffer type!");
1628 return ((uint32_t)-1);
1629 }
1630
1631 void
arc_buf_thaw(arc_buf_t * buf)1632 arc_buf_thaw(arc_buf_t *buf)
1633 {
1634 arc_buf_hdr_t *hdr = buf->b_hdr;
1635
1636 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
1637 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1638
1639 arc_cksum_verify(buf);
1640
1641 /*
1642 * Compressed buffers do not manipulate the b_freeze_cksum.
1643 */
1644 if (ARC_BUF_COMPRESSED(buf))
1645 return;
1646
1647 ASSERT(HDR_HAS_L1HDR(hdr));
1648 arc_cksum_free(hdr);
1649 arc_buf_unwatch(buf);
1650 }
1651
1652 void
arc_buf_freeze(arc_buf_t * buf)1653 arc_buf_freeze(arc_buf_t *buf)
1654 {
1655 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1656 return;
1657
1658 if (ARC_BUF_COMPRESSED(buf))
1659 return;
1660
1661 ASSERT(HDR_HAS_L1HDR(buf->b_hdr));
1662 arc_cksum_compute(buf);
1663 }
1664
1665 /*
1666 * The arc_buf_hdr_t's b_flags should never be modified directly. Instead,
1667 * the following functions should be used to ensure that the flags are
1668 * updated in a thread-safe way. When manipulating the flags either
1669 * the hash_lock must be held or the hdr must be undiscoverable. This
1670 * ensures that we're not racing with any other threads when updating
1671 * the flags.
1672 */
1673 static inline void
arc_hdr_set_flags(arc_buf_hdr_t * hdr,arc_flags_t flags)1674 arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
1675 {
1676 ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
1677 hdr->b_flags |= flags;
1678 }
1679
1680 static inline void
arc_hdr_clear_flags(arc_buf_hdr_t * hdr,arc_flags_t flags)1681 arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
1682 {
1683 ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
1684 hdr->b_flags &= ~flags;
1685 }
1686
1687 /*
1688 * Setting the compression bits in the arc_buf_hdr_t's b_flags is
1689 * done in a special way since we have to clear and set bits
1690 * at the same time. Consumers that wish to set the compression bits
1691 * must use this function to ensure that the flags are updated in
1692 * thread-safe manner.
1693 */
1694 static void
arc_hdr_set_compress(arc_buf_hdr_t * hdr,enum zio_compress cmp)1695 arc_hdr_set_compress(arc_buf_hdr_t *hdr, enum zio_compress cmp)
1696 {
1697 ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
1698
1699 /*
1700 * Holes and embedded blocks will always have a psize = 0 so
1701 * we ignore the compression of the blkptr and set the
1702 * want to uncompress them. Mark them as uncompressed.
1703 */
1704 if (!zfs_compressed_arc_enabled || HDR_GET_PSIZE(hdr) == 0) {
1705 arc_hdr_clear_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
1706 ASSERT(!HDR_COMPRESSION_ENABLED(hdr));
1707 } else {
1708 arc_hdr_set_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
1709 ASSERT(HDR_COMPRESSION_ENABLED(hdr));
1710 }
1711
1712 HDR_SET_COMPRESS(hdr, cmp);
1713 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, cmp);
1714 }
1715
1716 /*
1717 * Looks for another buf on the same hdr which has the data decompressed, copies
1718 * from it, and returns true. If no such buf exists, returns false.
1719 */
1720 static boolean_t
arc_buf_try_copy_decompressed_data(arc_buf_t * buf)1721 arc_buf_try_copy_decompressed_data(arc_buf_t *buf)
1722 {
1723 arc_buf_hdr_t *hdr = buf->b_hdr;
1724 boolean_t copied = B_FALSE;
1725
1726 ASSERT(HDR_HAS_L1HDR(hdr));
1727 ASSERT3P(buf->b_data, !=, NULL);
1728 ASSERT(!ARC_BUF_COMPRESSED(buf));
1729
1730 for (arc_buf_t *from = hdr->b_l1hdr.b_buf; from != NULL;
1731 from = from->b_next) {
1732 /* can't use our own data buffer */
1733 if (from == buf) {
1734 continue;
1735 }
1736
1737 if (!ARC_BUF_COMPRESSED(from)) {
1738 memcpy(buf->b_data, from->b_data, arc_buf_size(buf));
1739 copied = B_TRUE;
1740 break;
1741 }
1742 }
1743
1744 #ifdef ZFS_DEBUG
1745 /*
1746 * There were no decompressed bufs, so there should not be a
1747 * checksum on the hdr either.
1748 */
1749 if (zfs_flags & ZFS_DEBUG_MODIFY)
1750 EQUIV(!copied, hdr->b_l1hdr.b_freeze_cksum == NULL);
1751 #endif
1752
1753 return (copied);
1754 }
1755
1756 /*
1757 * Allocates an ARC buf header that's in an evicted & L2-cached state.
1758 * This is used during l2arc reconstruction to make empty ARC buffers
1759 * which circumvent the regular disk->arc->l2arc path and instead come
1760 * into being in the reverse order, i.e. l2arc->arc.
1761 */
1762 static arc_buf_hdr_t *
arc_buf_alloc_l2only(size_t size,arc_buf_contents_t type,l2arc_dev_t * dev,dva_t dva,uint64_t daddr,int32_t psize,uint64_t asize,uint64_t birth,enum zio_compress compress,uint8_t complevel,boolean_t protected,boolean_t prefetch,arc_state_type_t arcs_state)1763 arc_buf_alloc_l2only(size_t size, arc_buf_contents_t type, l2arc_dev_t *dev,
1764 dva_t dva, uint64_t daddr, int32_t psize, uint64_t asize, uint64_t birth,
1765 enum zio_compress compress, uint8_t complevel, boolean_t protected,
1766 boolean_t prefetch, arc_state_type_t arcs_state)
1767 {
1768 arc_buf_hdr_t *hdr;
1769
1770 ASSERT(size != 0);
1771 ASSERT(dev->l2ad_vdev != NULL);
1772
1773 hdr = kmem_cache_alloc(hdr_l2only_cache, KM_SLEEP);
1774 hdr->b_birth = birth;
1775 hdr->b_type = type;
1776 hdr->b_flags = 0;
1777 arc_hdr_set_flags(hdr, arc_bufc_to_flags(type) | ARC_FLAG_HAS_L2HDR);
1778 HDR_SET_LSIZE(hdr, size);
1779 HDR_SET_PSIZE(hdr, psize);
1780 HDR_SET_L2SIZE(hdr, asize);
1781 arc_hdr_set_compress(hdr, compress);
1782 hdr->b_complevel = complevel;
1783 if (protected)
1784 arc_hdr_set_flags(hdr, ARC_FLAG_PROTECTED);
1785 if (prefetch)
1786 arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
1787 hdr->b_spa = spa_load_guid(dev->l2ad_vdev->vdev_spa);
1788
1789 hdr->b_dva = dva;
1790
1791 hdr->b_l2hdr.b_dev = dev;
1792 hdr->b_l2hdr.b_daddr = daddr;
1793 hdr->b_l2hdr.b_arcs_state = arcs_state;
1794
1795 return (hdr);
1796 }
1797
1798 /*
1799 * Return the size of the block, b_pabd, that is stored in the arc_buf_hdr_t.
1800 */
1801 static uint64_t
arc_hdr_size(arc_buf_hdr_t * hdr)1802 arc_hdr_size(arc_buf_hdr_t *hdr)
1803 {
1804 uint64_t size;
1805
1806 if (arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF &&
1807 HDR_GET_PSIZE(hdr) > 0) {
1808 size = HDR_GET_PSIZE(hdr);
1809 } else {
1810 ASSERT3U(HDR_GET_LSIZE(hdr), !=, 0);
1811 size = HDR_GET_LSIZE(hdr);
1812 }
1813 return (size);
1814 }
1815
1816 static int
arc_hdr_authenticate(arc_buf_hdr_t * hdr,spa_t * spa,uint64_t dsobj)1817 arc_hdr_authenticate(arc_buf_hdr_t *hdr, spa_t *spa, uint64_t dsobj)
1818 {
1819 int ret;
1820 uint64_t csize;
1821 uint64_t lsize = HDR_GET_LSIZE(hdr);
1822 uint64_t psize = HDR_GET_PSIZE(hdr);
1823 abd_t *abd = hdr->b_l1hdr.b_pabd;
1824 boolean_t free_abd = B_FALSE;
1825
1826 ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
1827 ASSERT(HDR_AUTHENTICATED(hdr));
1828 ASSERT3P(abd, !=, NULL);
1829
1830 /*
1831 * The MAC is calculated on the compressed data that is stored on disk.
1832 * However, if compressed arc is disabled we will only have the
1833 * decompressed data available to us now. Compress it into a temporary
1834 * abd so we can verify the MAC. The performance overhead of this will
1835 * be relatively low, since most objects in an encrypted objset will
1836 * be encrypted (instead of authenticated) anyway.
1837 */
1838 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
1839 !HDR_COMPRESSION_ENABLED(hdr)) {
1840 abd = NULL;
1841 csize = zio_compress_data(HDR_GET_COMPRESS(hdr),
1842 hdr->b_l1hdr.b_pabd, &abd, lsize, MIN(lsize, psize),
1843 hdr->b_complevel);
1844 if (csize >= lsize || csize > psize) {
1845 ret = SET_ERROR(EIO);
1846 return (ret);
1847 }
1848 ASSERT3P(abd, !=, NULL);
1849 abd_zero_off(abd, csize, psize - csize);
1850 free_abd = B_TRUE;
1851 }
1852
1853 /*
1854 * Authentication is best effort. We authenticate whenever the key is
1855 * available. If we succeed we clear ARC_FLAG_NOAUTH.
1856 */
1857 if (hdr->b_crypt_hdr.b_ot == DMU_OT_OBJSET) {
1858 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
1859 ASSERT3U(lsize, ==, psize);
1860 ret = spa_do_crypt_objset_mac_abd(B_FALSE, spa, dsobj, abd,
1861 psize, hdr->b_l1hdr.b_byteswap != DMU_BSWAP_NUMFUNCS);
1862 } else {
1863 ret = spa_do_crypt_mac_abd(B_FALSE, spa, dsobj, abd, psize,
1864 hdr->b_crypt_hdr.b_mac);
1865 }
1866
1867 if (ret == 0)
1868 arc_hdr_clear_flags(hdr, ARC_FLAG_NOAUTH);
1869 else if (ret == EACCES)
1870 ret = 0;
1871
1872 if (free_abd)
1873 abd_free(abd);
1874
1875 return (ret);
1876 }
1877
1878 /*
1879 * This function will take a header that only has raw encrypted data in
1880 * b_crypt_hdr.b_rabd and decrypt it into a new buffer which is stored in
1881 * b_l1hdr.b_pabd. If designated in the header flags, this function will
1882 * also decompress the data.
1883 */
1884 static int
arc_hdr_decrypt(arc_buf_hdr_t * hdr,spa_t * spa,const zbookmark_phys_t * zb)1885 arc_hdr_decrypt(arc_buf_hdr_t *hdr, spa_t *spa, const zbookmark_phys_t *zb)
1886 {
1887 int ret;
1888 abd_t *cabd = NULL;
1889 boolean_t no_crypt = B_FALSE;
1890 boolean_t bswap = (hdr->b_l1hdr.b_byteswap != DMU_BSWAP_NUMFUNCS);
1891
1892 ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
1893 ASSERT(HDR_ENCRYPTED(hdr));
1894
1895 arc_hdr_alloc_abd(hdr, 0);
1896
1897 ret = spa_do_crypt_abd(B_FALSE, spa, zb, hdr->b_crypt_hdr.b_ot,
1898 B_FALSE, bswap, hdr->b_crypt_hdr.b_salt, hdr->b_crypt_hdr.b_iv,
1899 hdr->b_crypt_hdr.b_mac, HDR_GET_PSIZE(hdr), hdr->b_l1hdr.b_pabd,
1900 hdr->b_crypt_hdr.b_rabd, &no_crypt);
1901 if (ret != 0)
1902 goto error;
1903
1904 if (no_crypt) {
1905 abd_copy(hdr->b_l1hdr.b_pabd, hdr->b_crypt_hdr.b_rabd,
1906 HDR_GET_PSIZE(hdr));
1907 }
1908
1909 /*
1910 * If this header has disabled arc compression but the b_pabd is
1911 * compressed after decrypting it, we need to decompress the newly
1912 * decrypted data.
1913 */
1914 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
1915 !HDR_COMPRESSION_ENABLED(hdr)) {
1916 /*
1917 * We want to make sure that we are correctly honoring the
1918 * zfs_abd_scatter_enabled setting, so we allocate an abd here
1919 * and then loan a buffer from it, rather than allocating a
1920 * linear buffer and wrapping it in an abd later.
1921 */
1922 cabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr, 0);
1923
1924 ret = zio_decompress_data(HDR_GET_COMPRESS(hdr),
1925 hdr->b_l1hdr.b_pabd, cabd, HDR_GET_PSIZE(hdr),
1926 HDR_GET_LSIZE(hdr), &hdr->b_complevel);
1927 if (ret != 0) {
1928 goto error;
1929 }
1930
1931 arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
1932 arc_hdr_size(hdr), hdr);
1933 hdr->b_l1hdr.b_pabd = cabd;
1934 }
1935
1936 return (0);
1937
1938 error:
1939 arc_hdr_free_abd(hdr, B_FALSE);
1940 if (cabd != NULL)
1941 arc_free_data_abd(hdr, cabd, arc_hdr_size(hdr), hdr);
1942
1943 return (ret);
1944 }
1945
1946 /*
1947 * This function is called during arc_buf_fill() to prepare the header's
1948 * abd plaintext pointer for use. This involves authenticated protected
1949 * data and decrypting encrypted data into the plaintext abd.
1950 */
1951 static int
arc_fill_hdr_crypt(arc_buf_hdr_t * hdr,kmutex_t * hash_lock,spa_t * spa,const zbookmark_phys_t * zb,boolean_t noauth)1952 arc_fill_hdr_crypt(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, spa_t *spa,
1953 const zbookmark_phys_t *zb, boolean_t noauth)
1954 {
1955 int ret;
1956
1957 ASSERT(HDR_PROTECTED(hdr));
1958
1959 if (hash_lock != NULL)
1960 mutex_enter(hash_lock);
1961
1962 if (HDR_NOAUTH(hdr) && !noauth) {
1963 /*
1964 * The caller requested authenticated data but our data has
1965 * not been authenticated yet. Verify the MAC now if we can.
1966 */
1967 ret = arc_hdr_authenticate(hdr, spa, zb->zb_objset);
1968 if (ret != 0)
1969 goto error;
1970 } else if (HDR_HAS_RABD(hdr) && hdr->b_l1hdr.b_pabd == NULL) {
1971 /*
1972 * If we only have the encrypted version of the data, but the
1973 * unencrypted version was requested we take this opportunity
1974 * to store the decrypted version in the header for future use.
1975 */
1976 ret = arc_hdr_decrypt(hdr, spa, zb);
1977 if (ret != 0)
1978 goto error;
1979 }
1980
1981 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
1982
1983 if (hash_lock != NULL)
1984 mutex_exit(hash_lock);
1985
1986 return (0);
1987
1988 error:
1989 if (hash_lock != NULL)
1990 mutex_exit(hash_lock);
1991
1992 return (ret);
1993 }
1994
1995 /*
1996 * This function is used by the dbuf code to decrypt bonus buffers in place.
1997 * The dbuf code itself doesn't have any locking for decrypting a shared dnode
1998 * block, so we use the hash lock here to protect against concurrent calls to
1999 * arc_buf_fill().
2000 */
2001 static void
arc_buf_untransform_in_place(arc_buf_t * buf)2002 arc_buf_untransform_in_place(arc_buf_t *buf)
2003 {
2004 arc_buf_hdr_t *hdr = buf->b_hdr;
2005
2006 ASSERT(HDR_ENCRYPTED(hdr));
2007 ASSERT3U(hdr->b_crypt_hdr.b_ot, ==, DMU_OT_DNODE);
2008 ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
2009 ASSERT3PF(hdr->b_l1hdr.b_pabd, !=, NULL, "hdr %px buf %px", hdr, buf);
2010
2011 zio_crypt_copy_dnode_bonus(hdr->b_l1hdr.b_pabd, buf->b_data,
2012 arc_buf_size(buf));
2013 buf->b_flags &= ~ARC_BUF_FLAG_ENCRYPTED;
2014 buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
2015 }
2016
2017 /*
2018 * Given a buf that has a data buffer attached to it, this function will
2019 * efficiently fill the buf with data of the specified compression setting from
2020 * the hdr and update the hdr's b_freeze_cksum if necessary. If the buf and hdr
2021 * are already sharing a data buf, no copy is performed.
2022 *
2023 * If the buf is marked as compressed but uncompressed data was requested, this
2024 * will allocate a new data buffer for the buf, remove that flag, and fill the
2025 * buf with uncompressed data. You can't request a compressed buf on a hdr with
2026 * uncompressed data, and (since we haven't added support for it yet) if you
2027 * want compressed data your buf must already be marked as compressed and have
2028 * the correct-sized data buffer.
2029 */
2030 static int
arc_buf_fill(arc_buf_t * buf,spa_t * spa,const zbookmark_phys_t * zb,arc_fill_flags_t flags)2031 arc_buf_fill(arc_buf_t *buf, spa_t *spa, const zbookmark_phys_t *zb,
2032 arc_fill_flags_t flags)
2033 {
2034 int error = 0;
2035 arc_buf_hdr_t *hdr = buf->b_hdr;
2036 boolean_t hdr_compressed =
2037 (arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF);
2038 boolean_t compressed = (flags & ARC_FILL_COMPRESSED) != 0;
2039 boolean_t encrypted = (flags & ARC_FILL_ENCRYPTED) != 0;
2040 dmu_object_byteswap_t bswap = hdr->b_l1hdr.b_byteswap;
2041 kmutex_t *hash_lock = (flags & ARC_FILL_LOCKED) ? NULL : HDR_LOCK(hdr);
2042
2043 ASSERT3P(buf->b_data, !=, NULL);
2044 IMPLY(compressed, hdr_compressed || ARC_BUF_ENCRYPTED(buf));
2045 IMPLY(compressed, ARC_BUF_COMPRESSED(buf));
2046 IMPLY(encrypted, HDR_ENCRYPTED(hdr));
2047 IMPLY(encrypted, ARC_BUF_ENCRYPTED(buf));
2048 IMPLY(encrypted, ARC_BUF_COMPRESSED(buf));
2049 IMPLY(encrypted, !arc_buf_is_shared(buf));
2050
2051 /*
2052 * If the caller wanted encrypted data we just need to copy it from
2053 * b_rabd and potentially byteswap it. We won't be able to do any
2054 * further transforms on it.
2055 */
2056 if (encrypted) {
2057 ASSERT(HDR_HAS_RABD(hdr));
2058 abd_copy_to_buf(buf->b_data, hdr->b_crypt_hdr.b_rabd,
2059 HDR_GET_PSIZE(hdr));
2060 goto byteswap;
2061 }
2062
2063 /*
2064 * Adjust encrypted and authenticated headers to accommodate
2065 * the request if needed. Dnode blocks (ARC_FILL_IN_PLACE) are
2066 * allowed to fail decryption due to keys not being loaded
2067 * without being marked as an IO error.
2068 */
2069 if (HDR_PROTECTED(hdr)) {
2070 error = arc_fill_hdr_crypt(hdr, hash_lock, spa,
2071 zb, !!(flags & ARC_FILL_NOAUTH));
2072 if (error == EACCES && (flags & ARC_FILL_IN_PLACE) != 0) {
2073 return (error);
2074 } else if (error != 0) {
2075 if (hash_lock != NULL)
2076 mutex_enter(hash_lock);
2077 arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
2078 if (hash_lock != NULL)
2079 mutex_exit(hash_lock);
2080 return (error);
2081 }
2082 }
2083
2084 /*
2085 * There is a special case here for dnode blocks which are
2086 * decrypting their bonus buffers. These blocks may request to
2087 * be decrypted in-place. This is necessary because there may
2088 * be many dnodes pointing into this buffer and there is
2089 * currently no method to synchronize replacing the backing
2090 * b_data buffer and updating all of the pointers. Here we use
2091 * the hash lock to ensure there are no races. If the need
2092 * arises for other types to be decrypted in-place, they must
2093 * add handling here as well.
2094 */
2095 if ((flags & ARC_FILL_IN_PLACE) != 0) {
2096 ASSERT(!hdr_compressed);
2097 ASSERT(!compressed);
2098 ASSERT(!encrypted);
2099
2100 if (HDR_ENCRYPTED(hdr) && ARC_BUF_ENCRYPTED(buf)) {
2101 ASSERT3U(hdr->b_crypt_hdr.b_ot, ==, DMU_OT_DNODE);
2102
2103 if (hash_lock != NULL)
2104 mutex_enter(hash_lock);
2105 arc_buf_untransform_in_place(buf);
2106 if (hash_lock != NULL)
2107 mutex_exit(hash_lock);
2108
2109 /* Compute the hdr's checksum if necessary */
2110 arc_cksum_compute(buf);
2111 }
2112
2113 return (0);
2114 }
2115
2116 if (hdr_compressed == compressed) {
2117 if (ARC_BUF_SHARED(buf)) {
2118 ASSERT(arc_buf_is_shared(buf));
2119 } else {
2120 abd_copy_to_buf(buf->b_data, hdr->b_l1hdr.b_pabd,
2121 arc_buf_size(buf));
2122 }
2123 } else {
2124 ASSERT(hdr_compressed);
2125 ASSERT(!compressed);
2126
2127 /*
2128 * If the buf is sharing its data with the hdr, unlink it and
2129 * allocate a new data buffer for the buf.
2130 */
2131 if (ARC_BUF_SHARED(buf)) {
2132 ASSERTF(ARC_BUF_COMPRESSED(buf),
2133 "buf %p was uncompressed", buf);
2134
2135 /* We need to give the buf its own b_data */
2136 buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
2137 buf->b_data =
2138 arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
2139 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2140
2141 /* Previously overhead was 0; just add new overhead */
2142 ARCSTAT_INCR(arcstat_overhead_size, HDR_GET_LSIZE(hdr));
2143 } else if (ARC_BUF_COMPRESSED(buf)) {
2144 ASSERT(!arc_buf_is_shared(buf));
2145
2146 /* We need to reallocate the buf's b_data */
2147 arc_free_data_buf(hdr, buf->b_data, HDR_GET_PSIZE(hdr),
2148 buf);
2149 buf->b_data =
2150 arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
2151
2152 /* We increased the size of b_data; update overhead */
2153 ARCSTAT_INCR(arcstat_overhead_size,
2154 HDR_GET_LSIZE(hdr) - HDR_GET_PSIZE(hdr));
2155 }
2156
2157 /*
2158 * Regardless of the buf's previous compression settings, it
2159 * should not be compressed at the end of this function.
2160 */
2161 buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
2162
2163 /*
2164 * Try copying the data from another buf which already has a
2165 * decompressed version. If that's not possible, it's time to
2166 * bite the bullet and decompress the data from the hdr.
2167 */
2168 if (arc_buf_try_copy_decompressed_data(buf)) {
2169 /* Skip byteswapping and checksumming (already done) */
2170 return (0);
2171 } else {
2172 abd_t dabd;
2173 abd_get_from_buf_struct(&dabd, buf->b_data,
2174 HDR_GET_LSIZE(hdr));
2175 error = zio_decompress_data(HDR_GET_COMPRESS(hdr),
2176 hdr->b_l1hdr.b_pabd, &dabd,
2177 HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr),
2178 &hdr->b_complevel);
2179 abd_free(&dabd);
2180
2181 /*
2182 * Absent hardware errors or software bugs, this should
2183 * be impossible, but log it anyway so we can debug it.
2184 */
2185 if (error != 0) {
2186 zfs_dbgmsg(
2187 "hdr %px, compress %d, psize %d, lsize %d",
2188 hdr, arc_hdr_get_compress(hdr),
2189 HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
2190 if (hash_lock != NULL)
2191 mutex_enter(hash_lock);
2192 arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
2193 if (hash_lock != NULL)
2194 mutex_exit(hash_lock);
2195 return (SET_ERROR(EIO));
2196 }
2197 }
2198 }
2199
2200 byteswap:
2201 /* Byteswap the buf's data if necessary */
2202 if (bswap != DMU_BSWAP_NUMFUNCS) {
2203 ASSERT(!HDR_SHARED_DATA(hdr));
2204 ASSERT3U(bswap, <, DMU_BSWAP_NUMFUNCS);
2205 dmu_ot_byteswap[bswap].ob_func(buf->b_data, HDR_GET_LSIZE(hdr));
2206 }
2207
2208 /* Compute the hdr's checksum if necessary */
2209 arc_cksum_compute(buf);
2210
2211 return (0);
2212 }
2213
2214 /*
2215 * If this function is being called to decrypt an encrypted buffer or verify an
2216 * authenticated one, the key must be loaded and a mapping must be made
2217 * available in the keystore via spa_keystore_create_mapping() or one of its
2218 * callers.
2219 */
2220 int
arc_untransform(arc_buf_t * buf,spa_t * spa,const zbookmark_phys_t * zb,boolean_t in_place)2221 arc_untransform(arc_buf_t *buf, spa_t *spa, const zbookmark_phys_t *zb,
2222 boolean_t in_place)
2223 {
2224 int ret;
2225 arc_fill_flags_t flags = 0;
2226
2227 if (in_place)
2228 flags |= ARC_FILL_IN_PLACE;
2229
2230 ret = arc_buf_fill(buf, spa, zb, flags);
2231 if (ret == ECKSUM) {
2232 /*
2233 * Convert authentication and decryption errors to EIO
2234 * (and generate an ereport) before leaving the ARC.
2235 */
2236 ret = SET_ERROR(EIO);
2237 spa_log_error(spa, zb, buf->b_hdr->b_birth);
2238 (void) zfs_ereport_post(FM_EREPORT_ZFS_AUTHENTICATION,
2239 spa, NULL, zb, NULL, 0);
2240 }
2241
2242 return (ret);
2243 }
2244
2245 /*
2246 * Increment the amount of evictable space in the arc_state_t's refcount.
2247 * We account for the space used by the hdr and the arc buf individually
2248 * so that we can add and remove them from the refcount individually.
2249 */
2250 static void
arc_evictable_space_increment(arc_buf_hdr_t * hdr,arc_state_t * state)2251 arc_evictable_space_increment(arc_buf_hdr_t *hdr, arc_state_t *state)
2252 {
2253 arc_buf_contents_t type = arc_buf_type(hdr);
2254
2255 ASSERT(HDR_HAS_L1HDR(hdr));
2256
2257 if (GHOST_STATE(state)) {
2258 ASSERT0P(hdr->b_l1hdr.b_buf);
2259 ASSERT0P(hdr->b_l1hdr.b_pabd);
2260 ASSERT(!HDR_HAS_RABD(hdr));
2261 (void) zfs_refcount_add_many(&state->arcs_esize[type],
2262 HDR_GET_LSIZE(hdr), hdr);
2263 return;
2264 }
2265
2266 if (hdr->b_l1hdr.b_pabd != NULL) {
2267 (void) zfs_refcount_add_many(&state->arcs_esize[type],
2268 arc_hdr_size(hdr), hdr);
2269 }
2270 if (HDR_HAS_RABD(hdr)) {
2271 (void) zfs_refcount_add_many(&state->arcs_esize[type],
2272 HDR_GET_PSIZE(hdr), hdr);
2273 }
2274
2275 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2276 buf = buf->b_next) {
2277 if (ARC_BUF_SHARED(buf))
2278 continue;
2279 (void) zfs_refcount_add_many(&state->arcs_esize[type],
2280 arc_buf_size(buf), buf);
2281 }
2282 }
2283
2284 /*
2285 * Decrement the amount of evictable space in the arc_state_t's refcount.
2286 * We account for the space used by the hdr and the arc buf individually
2287 * so that we can add and remove them from the refcount individually.
2288 */
2289 static void
arc_evictable_space_decrement(arc_buf_hdr_t * hdr,arc_state_t * state)2290 arc_evictable_space_decrement(arc_buf_hdr_t *hdr, arc_state_t *state)
2291 {
2292 arc_buf_contents_t type = arc_buf_type(hdr);
2293
2294 ASSERT(HDR_HAS_L1HDR(hdr));
2295
2296 if (GHOST_STATE(state)) {
2297 ASSERT0P(hdr->b_l1hdr.b_buf);
2298 ASSERT0P(hdr->b_l1hdr.b_pabd);
2299 ASSERT(!HDR_HAS_RABD(hdr));
2300 (void) zfs_refcount_remove_many(&state->arcs_esize[type],
2301 HDR_GET_LSIZE(hdr), hdr);
2302 return;
2303 }
2304
2305 if (hdr->b_l1hdr.b_pabd != NULL) {
2306 (void) zfs_refcount_remove_many(&state->arcs_esize[type],
2307 arc_hdr_size(hdr), hdr);
2308 }
2309 if (HDR_HAS_RABD(hdr)) {
2310 (void) zfs_refcount_remove_many(&state->arcs_esize[type],
2311 HDR_GET_PSIZE(hdr), hdr);
2312 }
2313
2314 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2315 buf = buf->b_next) {
2316 if (ARC_BUF_SHARED(buf))
2317 continue;
2318 (void) zfs_refcount_remove_many(&state->arcs_esize[type],
2319 arc_buf_size(buf), buf);
2320 }
2321 }
2322
2323 /*
2324 * Add a reference to this hdr indicating that someone is actively
2325 * referencing that memory. When the refcount transitions from 0 to 1,
2326 * we remove it from the respective arc_state_t list to indicate that
2327 * it is not evictable.
2328 */
2329 static void
add_reference(arc_buf_hdr_t * hdr,const void * tag)2330 add_reference(arc_buf_hdr_t *hdr, const void *tag)
2331 {
2332 arc_state_t *state = hdr->b_l1hdr.b_state;
2333
2334 ASSERT(HDR_HAS_L1HDR(hdr));
2335 if (!HDR_EMPTY(hdr) && !MUTEX_HELD(HDR_LOCK(hdr))) {
2336 ASSERT(state == arc_anon);
2337 ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2338 ASSERT0P(hdr->b_l1hdr.b_buf);
2339 }
2340
2341 if ((zfs_refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
2342 state != arc_anon && state != arc_l2c_only) {
2343 /* We don't use the L2-only state list. */
2344 multilist_remove(&state->arcs_list[arc_buf_type(hdr)], hdr);
2345 arc_evictable_space_decrement(hdr, state);
2346 }
2347 }
2348
2349 /*
2350 * Remove a reference from this hdr. When the reference transitions from
2351 * 1 to 0 and we're not anonymous, then we add this hdr to the arc_state_t's
2352 * list making it eligible for eviction.
2353 */
2354 static int
remove_reference(arc_buf_hdr_t * hdr,const void * tag)2355 remove_reference(arc_buf_hdr_t *hdr, const void *tag)
2356 {
2357 int cnt;
2358 arc_state_t *state = hdr->b_l1hdr.b_state;
2359
2360 ASSERT(HDR_HAS_L1HDR(hdr));
2361 ASSERT(state == arc_anon || MUTEX_HELD(HDR_LOCK(hdr)));
2362 ASSERT(!GHOST_STATE(state)); /* arc_l2c_only counts as a ghost. */
2363
2364 if ((cnt = zfs_refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) != 0)
2365 return (cnt);
2366
2367 if (state == arc_anon) {
2368 arc_hdr_destroy(hdr);
2369 return (0);
2370 }
2371 if ((state == arc_uncached && !HDR_PREFETCH(hdr)) ||
2372 HDR_IO_ERROR(hdr)) {
2373 arc_change_state(arc_anon, hdr);
2374 arc_hdr_destroy(hdr);
2375 return (0);
2376 }
2377 multilist_insert(&state->arcs_list[arc_buf_type(hdr)], hdr);
2378 arc_evictable_space_increment(hdr, state);
2379 return (0);
2380 }
2381
2382 /*
2383 * Returns detailed information about a specific arc buffer. When the
2384 * state_index argument is set the function will calculate the arc header
2385 * list position for its arc state. Since this requires a linear traversal
2386 * callers are strongly encourage not to do this. However, it can be helpful
2387 * for targeted analysis so the functionality is provided.
2388 */
2389 void
arc_buf_info(arc_buf_t * ab,arc_buf_info_t * abi,int state_index)2390 arc_buf_info(arc_buf_t *ab, arc_buf_info_t *abi, int state_index)
2391 {
2392 (void) state_index;
2393 arc_buf_hdr_t *hdr = ab->b_hdr;
2394 l1arc_buf_hdr_t *l1hdr = NULL;
2395 l2arc_buf_hdr_t *l2hdr = NULL;
2396 arc_state_t *state = NULL;
2397
2398 memset(abi, 0, sizeof (arc_buf_info_t));
2399
2400 if (hdr == NULL)
2401 return;
2402
2403 abi->abi_flags = hdr->b_flags;
2404
2405 if (HDR_HAS_L1HDR(hdr)) {
2406 l1hdr = &hdr->b_l1hdr;
2407 state = l1hdr->b_state;
2408 }
2409 if (HDR_HAS_L2HDR(hdr))
2410 l2hdr = &hdr->b_l2hdr;
2411
2412 if (l1hdr) {
2413 abi->abi_bufcnt = 0;
2414 for (arc_buf_t *buf = l1hdr->b_buf; buf; buf = buf->b_next)
2415 abi->abi_bufcnt++;
2416 abi->abi_access = l1hdr->b_arc_access;
2417 abi->abi_mru_hits = l1hdr->b_mru_hits;
2418 abi->abi_mru_ghost_hits = l1hdr->b_mru_ghost_hits;
2419 abi->abi_mfu_hits = l1hdr->b_mfu_hits;
2420 abi->abi_mfu_ghost_hits = l1hdr->b_mfu_ghost_hits;
2421 abi->abi_holds = zfs_refcount_count(&l1hdr->b_refcnt);
2422 }
2423
2424 if (l2hdr) {
2425 abi->abi_l2arc_dattr = l2hdr->b_daddr;
2426 abi->abi_l2arc_hits = l2hdr->b_hits;
2427 }
2428
2429 abi->abi_state_type = state ? state->arcs_state : ARC_STATE_ANON;
2430 abi->abi_state_contents = arc_buf_type(hdr);
2431 abi->abi_size = arc_hdr_size(hdr);
2432 }
2433
2434 /*
2435 * Move the supplied buffer to the indicated state. The hash lock
2436 * for the buffer must be held by the caller.
2437 */
2438 static void
arc_change_state(arc_state_t * new_state,arc_buf_hdr_t * hdr)2439 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr)
2440 {
2441 arc_state_t *old_state;
2442 int64_t refcnt;
2443 boolean_t update_old, update_new;
2444 arc_buf_contents_t type = arc_buf_type(hdr);
2445
2446 /*
2447 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
2448 * in arc_read() when bringing a buffer out of the L2ARC. However, the
2449 * L1 hdr doesn't always exist when we change state to arc_anon before
2450 * destroying a header, in which case reallocating to add the L1 hdr is
2451 * pointless.
2452 */
2453 if (HDR_HAS_L1HDR(hdr)) {
2454 old_state = hdr->b_l1hdr.b_state;
2455 refcnt = zfs_refcount_count(&hdr->b_l1hdr.b_refcnt);
2456 update_old = (hdr->b_l1hdr.b_buf != NULL ||
2457 hdr->b_l1hdr.b_pabd != NULL || HDR_HAS_RABD(hdr));
2458
2459 IMPLY(GHOST_STATE(old_state), hdr->b_l1hdr.b_buf == NULL);
2460 IMPLY(GHOST_STATE(new_state), hdr->b_l1hdr.b_buf == NULL);
2461 IMPLY(old_state == arc_anon, hdr->b_l1hdr.b_buf == NULL ||
2462 ARC_BUF_LAST(hdr->b_l1hdr.b_buf));
2463 } else {
2464 old_state = arc_l2c_only;
2465 refcnt = 0;
2466 update_old = B_FALSE;
2467 }
2468 update_new = update_old;
2469 if (GHOST_STATE(old_state))
2470 update_old = B_TRUE;
2471 if (GHOST_STATE(new_state))
2472 update_new = B_TRUE;
2473
2474 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
2475 VERIFY3P(new_state, !=, old_state);
2476
2477 /*
2478 * If this buffer is evictable, transfer it from the
2479 * old state list to the new state list.
2480 */
2481 if (refcnt == 0) {
2482 if (old_state != arc_anon && old_state != arc_l2c_only) {
2483 ASSERT(HDR_HAS_L1HDR(hdr));
2484 /* remove_reference() saves on insert. */
2485 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
2486 multilist_remove(&old_state->arcs_list[type],
2487 hdr);
2488 arc_evictable_space_decrement(hdr, old_state);
2489 }
2490 }
2491 if (new_state != arc_anon && new_state != arc_l2c_only) {
2492 /*
2493 * An L1 header always exists here, since if we're
2494 * moving to some L1-cached state (i.e. not l2c_only or
2495 * anonymous), we realloc the header to add an L1hdr
2496 * beforehand.
2497 */
2498 ASSERT(HDR_HAS_L1HDR(hdr));
2499 multilist_insert(&new_state->arcs_list[type], hdr);
2500 arc_evictable_space_increment(hdr, new_state);
2501 }
2502 }
2503
2504 ASSERT(!HDR_EMPTY(hdr));
2505 if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
2506 buf_hash_remove(hdr);
2507
2508 /* adjust state sizes (ignore arc_l2c_only) */
2509
2510 if (update_new && new_state != arc_l2c_only) {
2511 ASSERT(HDR_HAS_L1HDR(hdr));
2512 if (GHOST_STATE(new_state)) {
2513
2514 /*
2515 * When moving a header to a ghost state, we first
2516 * remove all arc buffers. Thus, we'll have no arc
2517 * buffer to use for the reference. As a result, we
2518 * use the arc header pointer for the reference.
2519 */
2520 (void) zfs_refcount_add_many(
2521 &new_state->arcs_size[type],
2522 HDR_GET_LSIZE(hdr), hdr);
2523 ASSERT0P(hdr->b_l1hdr.b_pabd);
2524 ASSERT(!HDR_HAS_RABD(hdr));
2525 } else {
2526
2527 /*
2528 * Each individual buffer holds a unique reference,
2529 * thus we must remove each of these references one
2530 * at a time.
2531 */
2532 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2533 buf = buf->b_next) {
2534
2535 /*
2536 * When the arc_buf_t is sharing the data
2537 * block with the hdr, the owner of the
2538 * reference belongs to the hdr. Only
2539 * add to the refcount if the arc_buf_t is
2540 * not shared.
2541 */
2542 if (ARC_BUF_SHARED(buf))
2543 continue;
2544
2545 (void) zfs_refcount_add_many(
2546 &new_state->arcs_size[type],
2547 arc_buf_size(buf), buf);
2548 }
2549
2550 if (hdr->b_l1hdr.b_pabd != NULL) {
2551 (void) zfs_refcount_add_many(
2552 &new_state->arcs_size[type],
2553 arc_hdr_size(hdr), hdr);
2554 }
2555
2556 if (HDR_HAS_RABD(hdr)) {
2557 (void) zfs_refcount_add_many(
2558 &new_state->arcs_size[type],
2559 HDR_GET_PSIZE(hdr), hdr);
2560 }
2561 }
2562 }
2563
2564 if (update_old && old_state != arc_l2c_only) {
2565 ASSERT(HDR_HAS_L1HDR(hdr));
2566 if (GHOST_STATE(old_state)) {
2567 ASSERT0P(hdr->b_l1hdr.b_pabd);
2568 ASSERT(!HDR_HAS_RABD(hdr));
2569
2570 /*
2571 * When moving a header off of a ghost state,
2572 * the header will not contain any arc buffers.
2573 * We use the arc header pointer for the reference
2574 * which is exactly what we did when we put the
2575 * header on the ghost state.
2576 */
2577
2578 (void) zfs_refcount_remove_many(
2579 &old_state->arcs_size[type],
2580 HDR_GET_LSIZE(hdr), hdr);
2581 } else {
2582
2583 /*
2584 * Each individual buffer holds a unique reference,
2585 * thus we must remove each of these references one
2586 * at a time.
2587 */
2588 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2589 buf = buf->b_next) {
2590
2591 /*
2592 * When the arc_buf_t is sharing the data
2593 * block with the hdr, the owner of the
2594 * reference belongs to the hdr. Only
2595 * add to the refcount if the arc_buf_t is
2596 * not shared.
2597 */
2598 if (ARC_BUF_SHARED(buf))
2599 continue;
2600
2601 (void) zfs_refcount_remove_many(
2602 &old_state->arcs_size[type],
2603 arc_buf_size(buf), buf);
2604 }
2605 ASSERT(hdr->b_l1hdr.b_pabd != NULL ||
2606 HDR_HAS_RABD(hdr));
2607
2608 if (hdr->b_l1hdr.b_pabd != NULL) {
2609 (void) zfs_refcount_remove_many(
2610 &old_state->arcs_size[type],
2611 arc_hdr_size(hdr), hdr);
2612 }
2613
2614 if (HDR_HAS_RABD(hdr)) {
2615 (void) zfs_refcount_remove_many(
2616 &old_state->arcs_size[type],
2617 HDR_GET_PSIZE(hdr), hdr);
2618 }
2619 }
2620 }
2621
2622 if (HDR_HAS_L1HDR(hdr)) {
2623 hdr->b_l1hdr.b_state = new_state;
2624
2625 if (HDR_HAS_L2HDR(hdr) && new_state != arc_l2c_only) {
2626 l2arc_hdr_arcstats_decrement_state(hdr);
2627 hdr->b_l2hdr.b_arcs_state = new_state->arcs_state;
2628 l2arc_hdr_arcstats_increment_state(hdr);
2629 }
2630 }
2631 }
2632
2633 void
arc_space_consume(uint64_t space,arc_space_type_t type)2634 arc_space_consume(uint64_t space, arc_space_type_t type)
2635 {
2636 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2637
2638 switch (type) {
2639 default:
2640 break;
2641 case ARC_SPACE_DATA:
2642 ARCSTAT_INCR(arcstat_data_size, space);
2643 break;
2644 case ARC_SPACE_META:
2645 ARCSTAT_INCR(arcstat_metadata_size, space);
2646 break;
2647 case ARC_SPACE_BONUS:
2648 ARCSTAT_INCR(arcstat_bonus_size, space);
2649 break;
2650 case ARC_SPACE_DNODE:
2651 aggsum_add(&arc_sums.arcstat_dnode_size, space);
2652 break;
2653 case ARC_SPACE_DBUF:
2654 ARCSTAT_INCR(arcstat_dbuf_size, space);
2655 break;
2656 case ARC_SPACE_HDRS:
2657 ARCSTAT_INCR(arcstat_hdr_size, space);
2658 break;
2659 case ARC_SPACE_L2HDRS:
2660 aggsum_add(&arc_sums.arcstat_l2_hdr_size, space);
2661 break;
2662 case ARC_SPACE_ABD_CHUNK_WASTE:
2663 /*
2664 * Note: this includes space wasted by all scatter ABD's, not
2665 * just those allocated by the ARC. But the vast majority of
2666 * scatter ABD's come from the ARC, because other users are
2667 * very short-lived.
2668 */
2669 ARCSTAT_INCR(arcstat_abd_chunk_waste_size, space);
2670 break;
2671 }
2672
2673 if (type != ARC_SPACE_DATA && type != ARC_SPACE_ABD_CHUNK_WASTE)
2674 ARCSTAT_INCR(arcstat_meta_used, space);
2675
2676 aggsum_add(&arc_sums.arcstat_size, space);
2677 }
2678
2679 void
arc_space_return(uint64_t space,arc_space_type_t type)2680 arc_space_return(uint64_t space, arc_space_type_t type)
2681 {
2682 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2683
2684 switch (type) {
2685 default:
2686 break;
2687 case ARC_SPACE_DATA:
2688 ARCSTAT_INCR(arcstat_data_size, -space);
2689 break;
2690 case ARC_SPACE_META:
2691 ARCSTAT_INCR(arcstat_metadata_size, -space);
2692 break;
2693 case ARC_SPACE_BONUS:
2694 ARCSTAT_INCR(arcstat_bonus_size, -space);
2695 break;
2696 case ARC_SPACE_DNODE:
2697 aggsum_add(&arc_sums.arcstat_dnode_size, -space);
2698 break;
2699 case ARC_SPACE_DBUF:
2700 ARCSTAT_INCR(arcstat_dbuf_size, -space);
2701 break;
2702 case ARC_SPACE_HDRS:
2703 ARCSTAT_INCR(arcstat_hdr_size, -space);
2704 break;
2705 case ARC_SPACE_L2HDRS:
2706 aggsum_add(&arc_sums.arcstat_l2_hdr_size, -space);
2707 break;
2708 case ARC_SPACE_ABD_CHUNK_WASTE:
2709 ARCSTAT_INCR(arcstat_abd_chunk_waste_size, -space);
2710 break;
2711 }
2712
2713 if (type != ARC_SPACE_DATA && type != ARC_SPACE_ABD_CHUNK_WASTE)
2714 ARCSTAT_INCR(arcstat_meta_used, -space);
2715
2716 ASSERT(aggsum_compare(&arc_sums.arcstat_size, space) >= 0);
2717 aggsum_add(&arc_sums.arcstat_size, -space);
2718 }
2719
2720 /*
2721 * Given a hdr and a buf, returns whether that buf can share its b_data buffer
2722 * with the hdr's b_pabd.
2723 */
2724 static boolean_t
arc_can_share(arc_buf_hdr_t * hdr,arc_buf_t * buf)2725 arc_can_share(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2726 {
2727 /*
2728 * The criteria for sharing a hdr's data are:
2729 * 1. the buffer is not encrypted
2730 * 2. the hdr's compression matches the buf's compression
2731 * 3. the hdr doesn't need to be byteswapped
2732 * 4. the hdr isn't already being shared
2733 * 5. the buf is either compressed or it is the last buf in the hdr list
2734 *
2735 * Criterion #5 maintains the invariant that shared uncompressed
2736 * bufs must be the final buf in the hdr's b_buf list. Reading this, you
2737 * might ask, "if a compressed buf is allocated first, won't that be the
2738 * last thing in the list?", but in that case it's impossible to create
2739 * a shared uncompressed buf anyway (because the hdr must be compressed
2740 * to have the compressed buf). You might also think that #3 is
2741 * sufficient to make this guarantee, however it's possible
2742 * (specifically in the rare L2ARC write race mentioned in
2743 * arc_buf_alloc_impl()) there will be an existing uncompressed buf that
2744 * is shareable, but wasn't at the time of its allocation. Rather than
2745 * allow a new shared uncompressed buf to be created and then shuffle
2746 * the list around to make it the last element, this simply disallows
2747 * sharing if the new buf isn't the first to be added.
2748 */
2749 ASSERT3P(buf->b_hdr, ==, hdr);
2750 boolean_t hdr_compressed =
2751 arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF;
2752 boolean_t buf_compressed = ARC_BUF_COMPRESSED(buf) != 0;
2753 return (!ARC_BUF_ENCRYPTED(buf) &&
2754 buf_compressed == hdr_compressed &&
2755 hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS &&
2756 !HDR_SHARED_DATA(hdr) &&
2757 (ARC_BUF_LAST(buf) || ARC_BUF_COMPRESSED(buf)));
2758 }
2759
2760 /*
2761 * Allocate a buf for this hdr. If you care about the data that's in the hdr,
2762 * or if you want a compressed buffer, pass those flags in. Returns 0 if the
2763 * copy was made successfully, or an error code otherwise.
2764 */
2765 static int
arc_buf_alloc_impl(arc_buf_hdr_t * hdr,spa_t * spa,const zbookmark_phys_t * zb,const void * tag,boolean_t encrypted,boolean_t compressed,boolean_t noauth,boolean_t fill,arc_buf_t ** ret)2766 arc_buf_alloc_impl(arc_buf_hdr_t *hdr, spa_t *spa, const zbookmark_phys_t *zb,
2767 const void *tag, boolean_t encrypted, boolean_t compressed,
2768 boolean_t noauth, boolean_t fill, arc_buf_t **ret)
2769 {
2770 arc_buf_t *buf;
2771 arc_fill_flags_t flags = ARC_FILL_LOCKED;
2772
2773 ASSERT(HDR_HAS_L1HDR(hdr));
2774 ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
2775 VERIFY(hdr->b_type == ARC_BUFC_DATA ||
2776 hdr->b_type == ARC_BUFC_METADATA);
2777 ASSERT3P(ret, !=, NULL);
2778 ASSERT0P(*ret);
2779 IMPLY(encrypted, compressed);
2780
2781 buf = *ret = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2782 buf->b_hdr = hdr;
2783 buf->b_data = NULL;
2784 buf->b_next = hdr->b_l1hdr.b_buf;
2785 buf->b_flags = 0;
2786
2787 add_reference(hdr, tag);
2788
2789 /*
2790 * We're about to change the hdr's b_flags. We must either
2791 * hold the hash_lock or be undiscoverable.
2792 */
2793 ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
2794
2795 /*
2796 * Only honor requests for compressed bufs if the hdr is actually
2797 * compressed. This must be overridden if the buffer is encrypted since
2798 * encrypted buffers cannot be decompressed.
2799 */
2800 if (encrypted) {
2801 buf->b_flags |= ARC_BUF_FLAG_COMPRESSED;
2802 buf->b_flags |= ARC_BUF_FLAG_ENCRYPTED;
2803 flags |= ARC_FILL_COMPRESSED | ARC_FILL_ENCRYPTED;
2804 } else if (compressed &&
2805 arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF) {
2806 buf->b_flags |= ARC_BUF_FLAG_COMPRESSED;
2807 flags |= ARC_FILL_COMPRESSED;
2808 }
2809
2810 if (noauth) {
2811 ASSERT0(encrypted);
2812 flags |= ARC_FILL_NOAUTH;
2813 }
2814
2815 /*
2816 * If the hdr's data can be shared then we share the data buffer and
2817 * set the appropriate bit in the hdr's b_flags to indicate the hdr is
2818 * sharing it's b_pabd with the arc_buf_t. Otherwise, we allocate a new
2819 * buffer to store the buf's data.
2820 *
2821 * There are two additional restrictions here because we're sharing
2822 * hdr -> buf instead of the usual buf -> hdr. First, the hdr can't be
2823 * actively involved in an L2ARC write, because if this buf is used by
2824 * an arc_write() then the hdr's data buffer will be released when the
2825 * write completes, even though the L2ARC write might still be using it.
2826 * Second, the hdr's ABD must be linear so that the buf's user doesn't
2827 * need to be ABD-aware. It must be allocated via
2828 * zio_[data_]buf_alloc(), not as a page, because we need to be able
2829 * to abd_release_ownership_of_buf(), which isn't allowed on "linear
2830 * page" buffers because the ABD code needs to handle freeing them
2831 * specially.
2832 */
2833 boolean_t can_share = arc_can_share(hdr, buf) &&
2834 !HDR_L2_WRITING(hdr) &&
2835 hdr->b_l1hdr.b_pabd != NULL &&
2836 abd_is_linear(hdr->b_l1hdr.b_pabd) &&
2837 !abd_is_linear_page(hdr->b_l1hdr.b_pabd);
2838
2839 /* Set up b_data and sharing */
2840 if (can_share) {
2841 buf->b_data = abd_to_buf(hdr->b_l1hdr.b_pabd);
2842 buf->b_flags |= ARC_BUF_FLAG_SHARED;
2843 arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
2844 } else {
2845 buf->b_data =
2846 arc_get_data_buf(hdr, arc_buf_size(buf), buf);
2847 ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
2848 }
2849 VERIFY3P(buf->b_data, !=, NULL);
2850
2851 hdr->b_l1hdr.b_buf = buf;
2852
2853 /*
2854 * If the user wants the data from the hdr, we need to either copy or
2855 * decompress the data.
2856 */
2857 if (fill) {
2858 ASSERT3P(zb, !=, NULL);
2859 return (arc_buf_fill(buf, spa, zb, flags));
2860 }
2861
2862 return (0);
2863 }
2864
2865 static const char *arc_onloan_tag = "onloan";
2866
2867 static inline void
arc_loaned_bytes_update(int64_t delta)2868 arc_loaned_bytes_update(int64_t delta)
2869 {
2870 atomic_add_64(&arc_loaned_bytes, delta);
2871
2872 /* assert that it did not wrap around */
2873 ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
2874 }
2875
2876 /*
2877 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
2878 * flight data by arc_tempreserve_space() until they are "returned". Loaned
2879 * buffers must be returned to the arc before they can be used by the DMU or
2880 * freed.
2881 */
2882 arc_buf_t *
arc_loan_buf(spa_t * spa,boolean_t is_metadata,int size)2883 arc_loan_buf(spa_t *spa, boolean_t is_metadata, int size)
2884 {
2885 arc_buf_t *buf = arc_alloc_buf(spa, arc_onloan_tag,
2886 is_metadata ? ARC_BUFC_METADATA : ARC_BUFC_DATA, size);
2887
2888 arc_loaned_bytes_update(arc_buf_size(buf));
2889
2890 return (buf);
2891 }
2892
2893 arc_buf_t *
arc_loan_compressed_buf(spa_t * spa,uint64_t psize,uint64_t lsize,enum zio_compress compression_type,uint8_t complevel)2894 arc_loan_compressed_buf(spa_t *spa, uint64_t psize, uint64_t lsize,
2895 enum zio_compress compression_type, uint8_t complevel)
2896 {
2897 arc_buf_t *buf = arc_alloc_compressed_buf(spa, arc_onloan_tag,
2898 psize, lsize, compression_type, complevel);
2899
2900 arc_loaned_bytes_update(arc_buf_size(buf));
2901
2902 return (buf);
2903 }
2904
2905 arc_buf_t *
arc_loan_raw_buf(spa_t * spa,uint64_t dsobj,boolean_t byteorder,const uint8_t * salt,const uint8_t * iv,const uint8_t * mac,dmu_object_type_t ot,uint64_t psize,uint64_t lsize,enum zio_compress compression_type,uint8_t complevel)2906 arc_loan_raw_buf(spa_t *spa, uint64_t dsobj, boolean_t byteorder,
2907 const uint8_t *salt, const uint8_t *iv, const uint8_t *mac,
2908 dmu_object_type_t ot, uint64_t psize, uint64_t lsize,
2909 enum zio_compress compression_type, uint8_t complevel)
2910 {
2911 arc_buf_t *buf = arc_alloc_raw_buf(spa, arc_onloan_tag, dsobj,
2912 byteorder, salt, iv, mac, ot, psize, lsize, compression_type,
2913 complevel);
2914
2915 atomic_add_64(&arc_loaned_bytes, psize);
2916 return (buf);
2917 }
2918
2919
2920 /*
2921 * Return a loaned arc buffer to the arc.
2922 */
2923 void
arc_return_buf(arc_buf_t * buf,const void * tag)2924 arc_return_buf(arc_buf_t *buf, const void *tag)
2925 {
2926 arc_buf_hdr_t *hdr = buf->b_hdr;
2927
2928 ASSERT3P(buf->b_data, !=, NULL);
2929 ASSERT(HDR_HAS_L1HDR(hdr));
2930 (void) zfs_refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2931 (void) zfs_refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2932
2933 arc_loaned_bytes_update(-arc_buf_size(buf));
2934 }
2935
2936 /* Detach an arc_buf from a dbuf (tag) */
2937 void
arc_loan_inuse_buf(arc_buf_t * buf,const void * tag)2938 arc_loan_inuse_buf(arc_buf_t *buf, const void *tag)
2939 {
2940 arc_buf_hdr_t *hdr = buf->b_hdr;
2941
2942 ASSERT3P(buf->b_data, !=, NULL);
2943 ASSERT(HDR_HAS_L1HDR(hdr));
2944 (void) zfs_refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2945 (void) zfs_refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
2946
2947 arc_loaned_bytes_update(arc_buf_size(buf));
2948 }
2949
2950 static void
l2arc_free_abd_on_write(abd_t * abd,l2arc_dev_t * dev)2951 l2arc_free_abd_on_write(abd_t *abd, l2arc_dev_t *dev)
2952 {
2953 l2arc_data_free_t *df = kmem_alloc(sizeof (*df), KM_SLEEP);
2954
2955 df->l2df_abd = abd;
2956 df->l2df_dev = dev;
2957 mutex_enter(&l2arc_free_on_write_mtx);
2958 list_insert_head(l2arc_free_on_write, df);
2959 mutex_exit(&l2arc_free_on_write_mtx);
2960 }
2961
2962 static void
arc_hdr_free_on_write(arc_buf_hdr_t * hdr,boolean_t free_rdata)2963 arc_hdr_free_on_write(arc_buf_hdr_t *hdr, boolean_t free_rdata)
2964 {
2965 arc_state_t *state = hdr->b_l1hdr.b_state;
2966 arc_buf_contents_t type = arc_buf_type(hdr);
2967 uint64_t size = (free_rdata) ? HDR_GET_PSIZE(hdr) : arc_hdr_size(hdr);
2968
2969 /* protected by hash lock, if in the hash table */
2970 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
2971 ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2972 ASSERT(state != arc_anon && state != arc_l2c_only);
2973
2974 (void) zfs_refcount_remove_many(&state->arcs_esize[type],
2975 size, hdr);
2976 }
2977 (void) zfs_refcount_remove_many(&state->arcs_size[type], size, hdr);
2978 if (type == ARC_BUFC_METADATA) {
2979 arc_space_return(size, ARC_SPACE_META);
2980 } else {
2981 ASSERT(type == ARC_BUFC_DATA);
2982 arc_space_return(size, ARC_SPACE_DATA);
2983 }
2984
2985 /*
2986 * L2HDR must exist since we're freeing an L2ARC-related ABD.
2987 */
2988 ASSERT(HDR_HAS_L2HDR(hdr));
2989
2990 if (free_rdata) {
2991 l2arc_free_abd_on_write(hdr->b_crypt_hdr.b_rabd,
2992 hdr->b_l2hdr.b_dev);
2993 } else {
2994 l2arc_free_abd_on_write(hdr->b_l1hdr.b_pabd,
2995 hdr->b_l2hdr.b_dev);
2996 }
2997 }
2998
2999 /*
3000 * Share the arc_buf_t's data with the hdr. Whenever we are sharing the
3001 * data buffer, we transfer the refcount ownership to the hdr and update
3002 * the appropriate kstats.
3003 */
3004 static void
arc_share_buf(arc_buf_hdr_t * hdr,arc_buf_t * buf)3005 arc_share_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
3006 {
3007 ASSERT(arc_can_share(hdr, buf));
3008 ASSERT0P(hdr->b_l1hdr.b_pabd);
3009 ASSERT(!ARC_BUF_ENCRYPTED(buf));
3010 ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
3011
3012 /*
3013 * Start sharing the data buffer. We transfer the
3014 * refcount ownership to the hdr since it always owns
3015 * the refcount whenever an arc_buf_t is shared.
3016 */
3017 zfs_refcount_transfer_ownership_many(
3018 &hdr->b_l1hdr.b_state->arcs_size[arc_buf_type(hdr)],
3019 arc_hdr_size(hdr), buf, hdr);
3020 hdr->b_l1hdr.b_pabd = abd_get_from_buf(buf->b_data, arc_buf_size(buf));
3021 abd_take_ownership_of_buf(hdr->b_l1hdr.b_pabd,
3022 HDR_ISTYPE_METADATA(hdr));
3023 arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
3024 buf->b_flags |= ARC_BUF_FLAG_SHARED;
3025
3026 /*
3027 * Since we've transferred ownership to the hdr we need
3028 * to increment its compressed and uncompressed kstats and
3029 * decrement the overhead size.
3030 */
3031 ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
3032 ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
3033 ARCSTAT_INCR(arcstat_overhead_size, -arc_buf_size(buf));
3034 }
3035
3036 static void
arc_unshare_buf(arc_buf_hdr_t * hdr,arc_buf_t * buf)3037 arc_unshare_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
3038 {
3039 ASSERT(arc_buf_is_shared(buf));
3040 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3041 ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
3042
3043 /*
3044 * We are no longer sharing this buffer so we need
3045 * to transfer its ownership to the rightful owner.
3046 */
3047 zfs_refcount_transfer_ownership_many(
3048 &hdr->b_l1hdr.b_state->arcs_size[arc_buf_type(hdr)],
3049 arc_hdr_size(hdr), hdr, buf);
3050 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
3051 abd_release_ownership_of_buf(hdr->b_l1hdr.b_pabd);
3052 abd_free(hdr->b_l1hdr.b_pabd);
3053 hdr->b_l1hdr.b_pabd = NULL;
3054 buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
3055
3056 /*
3057 * Since the buffer is no longer shared between
3058 * the arc buf and the hdr, count it as overhead.
3059 */
3060 ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
3061 ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
3062 ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
3063 }
3064
3065 /*
3066 * Remove an arc_buf_t from the hdr's buf list and return the last
3067 * arc_buf_t on the list. If no buffers remain on the list then return
3068 * NULL.
3069 */
3070 static arc_buf_t *
arc_buf_remove(arc_buf_hdr_t * hdr,arc_buf_t * buf)3071 arc_buf_remove(arc_buf_hdr_t *hdr, arc_buf_t *buf)
3072 {
3073 ASSERT(HDR_HAS_L1HDR(hdr));
3074 ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
3075
3076 arc_buf_t **bufp = &hdr->b_l1hdr.b_buf;
3077 arc_buf_t *lastbuf = NULL;
3078
3079 /*
3080 * Remove the buf from the hdr list and locate the last
3081 * remaining buffer on the list.
3082 */
3083 while (*bufp != NULL) {
3084 if (*bufp == buf)
3085 *bufp = buf->b_next;
3086
3087 /*
3088 * If we've removed a buffer in the middle of
3089 * the list then update the lastbuf and update
3090 * bufp.
3091 */
3092 if (*bufp != NULL) {
3093 lastbuf = *bufp;
3094 bufp = &(*bufp)->b_next;
3095 }
3096 }
3097 buf->b_next = NULL;
3098 ASSERT3P(lastbuf, !=, buf);
3099 IMPLY(lastbuf != NULL, ARC_BUF_LAST(lastbuf));
3100
3101 return (lastbuf);
3102 }
3103
3104 /*
3105 * Free up buf->b_data and pull the arc_buf_t off of the arc_buf_hdr_t's
3106 * list and free it.
3107 */
3108 static void
arc_buf_destroy_impl(arc_buf_t * buf)3109 arc_buf_destroy_impl(arc_buf_t *buf)
3110 {
3111 arc_buf_hdr_t *hdr = buf->b_hdr;
3112
3113 /*
3114 * Free up the data associated with the buf but only if we're not
3115 * sharing this with the hdr. If we are sharing it with the hdr, the
3116 * hdr is responsible for doing the free.
3117 */
3118 if (buf->b_data != NULL) {
3119 /*
3120 * We're about to change the hdr's b_flags. We must either
3121 * hold the hash_lock or be undiscoverable.
3122 */
3123 ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
3124
3125 arc_cksum_verify(buf);
3126 arc_buf_unwatch(buf);
3127
3128 if (ARC_BUF_SHARED(buf)) {
3129 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
3130 } else {
3131 ASSERT(!arc_buf_is_shared(buf));
3132 uint64_t size = arc_buf_size(buf);
3133 arc_free_data_buf(hdr, buf->b_data, size, buf);
3134 ARCSTAT_INCR(arcstat_overhead_size, -size);
3135 }
3136 buf->b_data = NULL;
3137
3138 /*
3139 * If we have no more encrypted buffers and we've already
3140 * gotten a copy of the decrypted data we can free b_rabd
3141 * to save some space.
3142 */
3143 if (ARC_BUF_ENCRYPTED(buf) && HDR_HAS_RABD(hdr) &&
3144 hdr->b_l1hdr.b_pabd != NULL && !HDR_IO_IN_PROGRESS(hdr)) {
3145 arc_buf_t *b;
3146 for (b = hdr->b_l1hdr.b_buf; b; b = b->b_next) {
3147 if (b != buf && ARC_BUF_ENCRYPTED(b))
3148 break;
3149 }
3150 if (b == NULL)
3151 arc_hdr_free_abd(hdr, B_TRUE);
3152 }
3153 }
3154
3155 arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
3156
3157 if (ARC_BUF_SHARED(buf) && !ARC_BUF_COMPRESSED(buf)) {
3158 /*
3159 * If the current arc_buf_t is sharing its data buffer with the
3160 * hdr, then reassign the hdr's b_pabd to share it with the new
3161 * buffer at the end of the list. The shared buffer is always
3162 * the last one on the hdr's buffer list.
3163 *
3164 * There is an equivalent case for compressed bufs, but since
3165 * they aren't guaranteed to be the last buf in the list and
3166 * that is an exceedingly rare case, we just allow that space be
3167 * wasted temporarily. We must also be careful not to share
3168 * encrypted buffers, since they cannot be shared.
3169 */
3170 if (lastbuf != NULL && !ARC_BUF_ENCRYPTED(lastbuf)) {
3171 /* Only one buf can be shared at once */
3172 ASSERT(!arc_buf_is_shared(lastbuf));
3173 /* hdr is uncompressed so can't have compressed buf */
3174 ASSERT(!ARC_BUF_COMPRESSED(lastbuf));
3175
3176 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3177 arc_hdr_free_abd(hdr, B_FALSE);
3178
3179 /*
3180 * We must setup a new shared block between the
3181 * last buffer and the hdr. The data would have
3182 * been allocated by the arc buf so we need to transfer
3183 * ownership to the hdr since it's now being shared.
3184 */
3185 arc_share_buf(hdr, lastbuf);
3186 }
3187 } else if (HDR_SHARED_DATA(hdr)) {
3188 /*
3189 * Uncompressed shared buffers are always at the end
3190 * of the list. Compressed buffers don't have the
3191 * same requirements. This makes it hard to
3192 * simply assert that the lastbuf is shared so
3193 * we rely on the hdr's compression flags to determine
3194 * if we have a compressed, shared buffer.
3195 */
3196 ASSERT3P(lastbuf, !=, NULL);
3197 ASSERT(arc_buf_is_shared(lastbuf) ||
3198 arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF);
3199 }
3200
3201 /*
3202 * Free the checksum if we're removing the last uncompressed buf from
3203 * this hdr.
3204 */
3205 if (!arc_hdr_has_uncompressed_buf(hdr)) {
3206 arc_cksum_free(hdr);
3207 }
3208
3209 /* clean up the buf */
3210 buf->b_hdr = NULL;
3211 kmem_cache_free(buf_cache, buf);
3212 }
3213
3214 static void
arc_hdr_alloc_abd(arc_buf_hdr_t * hdr,int alloc_flags)3215 arc_hdr_alloc_abd(arc_buf_hdr_t *hdr, int alloc_flags)
3216 {
3217 uint64_t size;
3218 boolean_t alloc_rdata = ((alloc_flags & ARC_HDR_ALLOC_RDATA) != 0);
3219
3220 ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
3221 ASSERT(HDR_HAS_L1HDR(hdr));
3222 ASSERT(!HDR_SHARED_DATA(hdr) || alloc_rdata);
3223 IMPLY(alloc_rdata, HDR_PROTECTED(hdr));
3224
3225 if (alloc_rdata) {
3226 size = HDR_GET_PSIZE(hdr);
3227 ASSERT0P(hdr->b_crypt_hdr.b_rabd);
3228 hdr->b_crypt_hdr.b_rabd = arc_get_data_abd(hdr, size, hdr,
3229 alloc_flags);
3230 ASSERT3P(hdr->b_crypt_hdr.b_rabd, !=, NULL);
3231 ARCSTAT_INCR(arcstat_raw_size, size);
3232 } else {
3233 size = arc_hdr_size(hdr);
3234 ASSERT0P(hdr->b_l1hdr.b_pabd);
3235 hdr->b_l1hdr.b_pabd = arc_get_data_abd(hdr, size, hdr,
3236 alloc_flags);
3237 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3238 }
3239
3240 ARCSTAT_INCR(arcstat_compressed_size, size);
3241 ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
3242 }
3243
3244 static void
arc_hdr_free_abd(arc_buf_hdr_t * hdr,boolean_t free_rdata)3245 arc_hdr_free_abd(arc_buf_hdr_t *hdr, boolean_t free_rdata)
3246 {
3247 uint64_t size = (free_rdata) ? HDR_GET_PSIZE(hdr) : arc_hdr_size(hdr);
3248
3249 ASSERT(HDR_HAS_L1HDR(hdr));
3250 ASSERT(hdr->b_l1hdr.b_pabd != NULL || HDR_HAS_RABD(hdr));
3251 IMPLY(free_rdata, HDR_HAS_RABD(hdr));
3252
3253 /*
3254 * If the hdr is currently being written to the l2arc then
3255 * we defer freeing the data by adding it to the l2arc_free_on_write
3256 * list. The l2arc will free the data once it's finished
3257 * writing it to the l2arc device.
3258 */
3259 if (HDR_L2_WRITING(hdr)) {
3260 arc_hdr_free_on_write(hdr, free_rdata);
3261 ARCSTAT_BUMP(arcstat_l2_free_on_write);
3262 } else if (free_rdata) {
3263 arc_free_data_abd(hdr, hdr->b_crypt_hdr.b_rabd, size, hdr);
3264 } else {
3265 arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd, size, hdr);
3266 }
3267
3268 if (free_rdata) {
3269 hdr->b_crypt_hdr.b_rabd = NULL;
3270 ARCSTAT_INCR(arcstat_raw_size, -size);
3271 } else {
3272 hdr->b_l1hdr.b_pabd = NULL;
3273 }
3274
3275 if (hdr->b_l1hdr.b_pabd == NULL && !HDR_HAS_RABD(hdr))
3276 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
3277
3278 ARCSTAT_INCR(arcstat_compressed_size, -size);
3279 ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
3280 }
3281
3282 /*
3283 * Allocate empty anonymous ARC header. The header will get its identity
3284 * assigned and buffers attached later as part of read or write operations.
3285 *
3286 * In case of read arc_read() assigns header its identify (b_dva + b_birth),
3287 * inserts it into ARC hash to become globally visible and allocates physical
3288 * (b_pabd) or raw (b_rabd) ABD buffer to read into from disk. On disk read
3289 * completion arc_read_done() allocates ARC buffer(s) as needed, potentially
3290 * sharing one of them with the physical ABD buffer.
3291 *
3292 * In case of write arc_alloc_buf() allocates ARC buffer to be filled with
3293 * data. Then after compression and/or encryption arc_write_ready() allocates
3294 * and fills (or potentially shares) physical (b_pabd) or raw (b_rabd) ABD
3295 * buffer. On disk write completion arc_write_done() assigns the header its
3296 * new identity (b_dva + b_birth) and inserts into ARC hash.
3297 *
3298 * In case of partial overwrite the old data is read first as described. Then
3299 * arc_release() either allocates new anonymous ARC header and moves the ARC
3300 * buffer to it, or reuses the old ARC header by discarding its identity and
3301 * removing it from ARC hash. After buffer modification normal write process
3302 * follows as described.
3303 */
3304 static arc_buf_hdr_t *
arc_hdr_alloc(uint64_t spa,int32_t psize,int32_t lsize,boolean_t protected,enum zio_compress compression_type,uint8_t complevel,arc_buf_contents_t type)3305 arc_hdr_alloc(uint64_t spa, int32_t psize, int32_t lsize,
3306 boolean_t protected, enum zio_compress compression_type, uint8_t complevel,
3307 arc_buf_contents_t type)
3308 {
3309 arc_buf_hdr_t *hdr;
3310
3311 VERIFY(type == ARC_BUFC_DATA || type == ARC_BUFC_METADATA);
3312 hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
3313
3314 ASSERT(HDR_EMPTY(hdr));
3315 #ifdef ZFS_DEBUG
3316 ASSERT0P(hdr->b_l1hdr.b_freeze_cksum);
3317 #endif
3318 HDR_SET_PSIZE(hdr, psize);
3319 HDR_SET_LSIZE(hdr, lsize);
3320 hdr->b_spa = spa;
3321 hdr->b_type = type;
3322 hdr->b_flags = 0;
3323 arc_hdr_set_flags(hdr, arc_bufc_to_flags(type) | ARC_FLAG_HAS_L1HDR);
3324 arc_hdr_set_compress(hdr, compression_type);
3325 hdr->b_complevel = complevel;
3326 if (protected)
3327 arc_hdr_set_flags(hdr, ARC_FLAG_PROTECTED);
3328
3329 hdr->b_l1hdr.b_state = arc_anon;
3330 hdr->b_l1hdr.b_arc_access = 0;
3331 hdr->b_l1hdr.b_mru_hits = 0;
3332 hdr->b_l1hdr.b_mru_ghost_hits = 0;
3333 hdr->b_l1hdr.b_mfu_hits = 0;
3334 hdr->b_l1hdr.b_mfu_ghost_hits = 0;
3335 hdr->b_l1hdr.b_buf = NULL;
3336
3337 ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3338
3339 return (hdr);
3340 }
3341
3342 /*
3343 * Transition between the two allocation states for the arc_buf_hdr struct.
3344 * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
3345 * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
3346 * version is used when a cache buffer is only in the L2ARC in order to reduce
3347 * memory usage.
3348 */
3349 static arc_buf_hdr_t *
arc_hdr_realloc(arc_buf_hdr_t * hdr,kmem_cache_t * old,kmem_cache_t * new)3350 arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
3351 {
3352 ASSERT(HDR_HAS_L2HDR(hdr));
3353
3354 arc_buf_hdr_t *nhdr;
3355 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3356
3357 ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
3358 (old == hdr_l2only_cache && new == hdr_full_cache));
3359
3360 nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
3361
3362 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
3363 buf_hash_remove(hdr);
3364
3365 memcpy(nhdr, hdr, HDR_L2ONLY_SIZE);
3366
3367 if (new == hdr_full_cache) {
3368 arc_hdr_set_flags(nhdr, ARC_FLAG_HAS_L1HDR);
3369 /*
3370 * arc_access and arc_change_state need to be aware that a
3371 * header has just come out of L2ARC, so we set its state to
3372 * l2c_only even though it's about to change.
3373 */
3374 nhdr->b_l1hdr.b_state = arc_l2c_only;
3375
3376 /* Verify previous threads set to NULL before freeing */
3377 ASSERT0P(nhdr->b_l1hdr.b_pabd);
3378 ASSERT(!HDR_HAS_RABD(hdr));
3379 } else {
3380 ASSERT0P(hdr->b_l1hdr.b_buf);
3381 #ifdef ZFS_DEBUG
3382 ASSERT0P(hdr->b_l1hdr.b_freeze_cksum);
3383 #endif
3384
3385 /*
3386 * If we've reached here, We must have been called from
3387 * arc_evict_hdr(), as such we should have already been
3388 * removed from any ghost list we were previously on
3389 * (which protects us from racing with arc_evict_state),
3390 * thus no locking is needed during this check.
3391 */
3392 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3393
3394 /*
3395 * A buffer must not be moved into the arc_l2c_only
3396 * state if it's not finished being written out to the
3397 * l2arc device. Otherwise, the b_l1hdr.b_pabd field
3398 * might try to be accessed, even though it was removed.
3399 */
3400 VERIFY(!HDR_L2_WRITING(hdr));
3401 VERIFY0P(hdr->b_l1hdr.b_pabd);
3402 ASSERT(!HDR_HAS_RABD(hdr));
3403
3404 arc_hdr_clear_flags(nhdr, ARC_FLAG_HAS_L1HDR);
3405 }
3406 /*
3407 * The header has been reallocated so we need to re-insert it into any
3408 * lists it was on.
3409 */
3410 (void) buf_hash_insert(nhdr, NULL);
3411
3412 ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
3413
3414 mutex_enter(&dev->l2ad_mtx);
3415
3416 /*
3417 * We must place the realloc'ed header back into the list at
3418 * the same spot. Otherwise, if it's placed earlier in the list,
3419 * l2arc_write_buffers() could find it during the function's
3420 * write phase, and try to write it out to the l2arc.
3421 */
3422 list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
3423 list_remove(&dev->l2ad_buflist, hdr);
3424
3425 mutex_exit(&dev->l2ad_mtx);
3426
3427 /*
3428 * Since we're using the pointer address as the tag when
3429 * incrementing and decrementing the l2ad_alloc refcount, we
3430 * must remove the old pointer (that we're about to destroy) and
3431 * add the new pointer to the refcount. Otherwise we'd remove
3432 * the wrong pointer address when calling arc_hdr_destroy() later.
3433 */
3434
3435 (void) zfs_refcount_remove_many(&dev->l2ad_alloc,
3436 arc_hdr_size(hdr), hdr);
3437 (void) zfs_refcount_add_many(&dev->l2ad_alloc,
3438 arc_hdr_size(nhdr), nhdr);
3439
3440 buf_discard_identity(hdr);
3441 kmem_cache_free(old, hdr);
3442
3443 return (nhdr);
3444 }
3445
3446 /*
3447 * This function is used by the send / receive code to convert a newly
3448 * allocated arc_buf_t to one that is suitable for a raw encrypted write. It
3449 * is also used to allow the root objset block to be updated without altering
3450 * its embedded MACs. Both block types will always be uncompressed so we do not
3451 * have to worry about compression type or psize.
3452 */
3453 void
arc_convert_to_raw(arc_buf_t * buf,uint64_t dsobj,boolean_t byteorder,dmu_object_type_t ot,const uint8_t * salt,const uint8_t * iv,const uint8_t * mac)3454 arc_convert_to_raw(arc_buf_t *buf, uint64_t dsobj, boolean_t byteorder,
3455 dmu_object_type_t ot, const uint8_t *salt, const uint8_t *iv,
3456 const uint8_t *mac)
3457 {
3458 arc_buf_hdr_t *hdr = buf->b_hdr;
3459
3460 ASSERT(ot == DMU_OT_DNODE || ot == DMU_OT_OBJSET);
3461 ASSERT(HDR_HAS_L1HDR(hdr));
3462 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
3463
3464 buf->b_flags |= (ARC_BUF_FLAG_COMPRESSED | ARC_BUF_FLAG_ENCRYPTED);
3465 arc_hdr_set_flags(hdr, ARC_FLAG_PROTECTED);
3466 hdr->b_crypt_hdr.b_dsobj = dsobj;
3467 hdr->b_crypt_hdr.b_ot = ot;
3468 hdr->b_l1hdr.b_byteswap = (byteorder == ZFS_HOST_BYTEORDER) ?
3469 DMU_BSWAP_NUMFUNCS : DMU_OT_BYTESWAP(ot);
3470 if (!arc_hdr_has_uncompressed_buf(hdr))
3471 arc_cksum_free(hdr);
3472
3473 if (salt != NULL)
3474 memcpy(hdr->b_crypt_hdr.b_salt, salt, ZIO_DATA_SALT_LEN);
3475 if (iv != NULL)
3476 memcpy(hdr->b_crypt_hdr.b_iv, iv, ZIO_DATA_IV_LEN);
3477 if (mac != NULL)
3478 memcpy(hdr->b_crypt_hdr.b_mac, mac, ZIO_DATA_MAC_LEN);
3479 }
3480
3481 /*
3482 * Allocate a new arc_buf_hdr_t and arc_buf_t and return the buf to the caller.
3483 * The buf is returned thawed since we expect the consumer to modify it.
3484 */
3485 arc_buf_t *
arc_alloc_buf(spa_t * spa,const void * tag,arc_buf_contents_t type,int32_t size)3486 arc_alloc_buf(spa_t *spa, const void *tag, arc_buf_contents_t type,
3487 int32_t size)
3488 {
3489 arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), size, size,
3490 B_FALSE, ZIO_COMPRESS_OFF, 0, type);
3491
3492 arc_buf_t *buf = NULL;
3493 VERIFY0(arc_buf_alloc_impl(hdr, spa, NULL, tag, B_FALSE, B_FALSE,
3494 B_FALSE, B_FALSE, &buf));
3495 arc_buf_thaw(buf);
3496
3497 return (buf);
3498 }
3499
3500 /*
3501 * Allocate a compressed buf in the same manner as arc_alloc_buf. Don't use this
3502 * for bufs containing metadata.
3503 */
3504 arc_buf_t *
arc_alloc_compressed_buf(spa_t * spa,const void * tag,uint64_t psize,uint64_t lsize,enum zio_compress compression_type,uint8_t complevel)3505 arc_alloc_compressed_buf(spa_t *spa, const void *tag, uint64_t psize,
3506 uint64_t lsize, enum zio_compress compression_type, uint8_t complevel)
3507 {
3508 ASSERT3U(lsize, >, 0);
3509 ASSERT3U(lsize, >=, psize);
3510 ASSERT3U(compression_type, >, ZIO_COMPRESS_OFF);
3511 ASSERT3U(compression_type, <, ZIO_COMPRESS_FUNCTIONS);
3512
3513 arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
3514 B_FALSE, compression_type, complevel, ARC_BUFC_DATA);
3515
3516 arc_buf_t *buf = NULL;
3517 VERIFY0(arc_buf_alloc_impl(hdr, spa, NULL, tag, B_FALSE,
3518 B_TRUE, B_FALSE, B_FALSE, &buf));
3519 arc_buf_thaw(buf);
3520
3521 /*
3522 * To ensure that the hdr has the correct data in it if we call
3523 * arc_untransform() on this buf before it's been written to disk,
3524 * it's easiest if we just set up sharing between the buf and the hdr.
3525 */
3526 arc_share_buf(hdr, buf);
3527
3528 return (buf);
3529 }
3530
3531 arc_buf_t *
arc_alloc_raw_buf(spa_t * spa,const void * tag,uint64_t dsobj,boolean_t byteorder,const uint8_t * salt,const uint8_t * iv,const uint8_t * mac,dmu_object_type_t ot,uint64_t psize,uint64_t lsize,enum zio_compress compression_type,uint8_t complevel)3532 arc_alloc_raw_buf(spa_t *spa, const void *tag, uint64_t dsobj,
3533 boolean_t byteorder, const uint8_t *salt, const uint8_t *iv,
3534 const uint8_t *mac, dmu_object_type_t ot, uint64_t psize, uint64_t lsize,
3535 enum zio_compress compression_type, uint8_t complevel)
3536 {
3537 arc_buf_hdr_t *hdr;
3538 arc_buf_t *buf;
3539 arc_buf_contents_t type = DMU_OT_IS_METADATA(ot) ?
3540 ARC_BUFC_METADATA : ARC_BUFC_DATA;
3541
3542 ASSERT3U(lsize, >, 0);
3543 ASSERT3U(lsize, >=, psize);
3544 ASSERT3U(compression_type, >=, ZIO_COMPRESS_OFF);
3545 ASSERT3U(compression_type, <, ZIO_COMPRESS_FUNCTIONS);
3546
3547 hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize, B_TRUE,
3548 compression_type, complevel, type);
3549
3550 hdr->b_crypt_hdr.b_dsobj = dsobj;
3551 hdr->b_crypt_hdr.b_ot = ot;
3552 hdr->b_l1hdr.b_byteswap = (byteorder == ZFS_HOST_BYTEORDER) ?
3553 DMU_BSWAP_NUMFUNCS : DMU_OT_BYTESWAP(ot);
3554 memcpy(hdr->b_crypt_hdr.b_salt, salt, ZIO_DATA_SALT_LEN);
3555 memcpy(hdr->b_crypt_hdr.b_iv, iv, ZIO_DATA_IV_LEN);
3556 memcpy(hdr->b_crypt_hdr.b_mac, mac, ZIO_DATA_MAC_LEN);
3557
3558 /*
3559 * This buffer will be considered encrypted even if the ot is not an
3560 * encrypted type. It will become authenticated instead in
3561 * arc_write_ready().
3562 */
3563 buf = NULL;
3564 VERIFY0(arc_buf_alloc_impl(hdr, spa, NULL, tag, B_TRUE, B_TRUE,
3565 B_FALSE, B_FALSE, &buf));
3566 arc_buf_thaw(buf);
3567
3568 return (buf);
3569 }
3570
3571 static void
l2arc_hdr_arcstats_update(arc_buf_hdr_t * hdr,boolean_t incr,boolean_t state_only)3572 l2arc_hdr_arcstats_update(arc_buf_hdr_t *hdr, boolean_t incr,
3573 boolean_t state_only)
3574 {
3575 uint64_t lsize = HDR_GET_LSIZE(hdr);
3576 uint64_t psize = HDR_GET_PSIZE(hdr);
3577 uint64_t asize = HDR_GET_L2SIZE(hdr);
3578 arc_buf_contents_t type = hdr->b_type;
3579 int64_t lsize_s;
3580 int64_t psize_s;
3581 int64_t asize_s;
3582
3583 /* For L2 we expect the header's b_l2size to be valid */
3584 ASSERT3U(asize, >=, psize);
3585
3586 if (incr) {
3587 lsize_s = lsize;
3588 psize_s = psize;
3589 asize_s = asize;
3590 } else {
3591 lsize_s = -lsize;
3592 psize_s = -psize;
3593 asize_s = -asize;
3594 }
3595
3596 /* If the buffer is a prefetch, count it as such. */
3597 if (HDR_PREFETCH(hdr)) {
3598 ARCSTAT_INCR(arcstat_l2_prefetch_asize, asize_s);
3599 } else {
3600 /*
3601 * We use the value stored in the L2 header upon initial
3602 * caching in L2ARC. This value will be updated in case
3603 * an MRU/MRU_ghost buffer transitions to MFU but the L2ARC
3604 * metadata (log entry) cannot currently be updated. Having
3605 * the ARC state in the L2 header solves the problem of a
3606 * possibly absent L1 header (apparent in buffers restored
3607 * from persistent L2ARC).
3608 */
3609 switch (hdr->b_l2hdr.b_arcs_state) {
3610 case ARC_STATE_MRU_GHOST:
3611 case ARC_STATE_MRU:
3612 ARCSTAT_INCR(arcstat_l2_mru_asize, asize_s);
3613 break;
3614 case ARC_STATE_MFU_GHOST:
3615 case ARC_STATE_MFU:
3616 ARCSTAT_INCR(arcstat_l2_mfu_asize, asize_s);
3617 break;
3618 default:
3619 break;
3620 }
3621 }
3622
3623 if (state_only)
3624 return;
3625
3626 ARCSTAT_INCR(arcstat_l2_psize, psize_s);
3627 ARCSTAT_INCR(arcstat_l2_lsize, lsize_s);
3628
3629 switch (type) {
3630 case ARC_BUFC_DATA:
3631 ARCSTAT_INCR(arcstat_l2_bufc_data_asize, asize_s);
3632 break;
3633 case ARC_BUFC_METADATA:
3634 ARCSTAT_INCR(arcstat_l2_bufc_metadata_asize, asize_s);
3635 break;
3636 default:
3637 break;
3638 }
3639 }
3640
3641
3642 static void
arc_hdr_l2hdr_destroy(arc_buf_hdr_t * hdr)3643 arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
3644 {
3645 l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
3646 l2arc_dev_t *dev = l2hdr->b_dev;
3647
3648 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
3649 ASSERT(HDR_HAS_L2HDR(hdr));
3650
3651 list_remove(&dev->l2ad_buflist, hdr);
3652
3653 l2arc_hdr_arcstats_decrement(hdr);
3654 if (dev->l2ad_vdev != NULL) {
3655 uint64_t asize = HDR_GET_L2SIZE(hdr);
3656 vdev_space_update(dev->l2ad_vdev, -asize, 0, 0);
3657 }
3658
3659 (void) zfs_refcount_remove_many(&dev->l2ad_alloc, arc_hdr_size(hdr),
3660 hdr);
3661 arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
3662 }
3663
3664 static void
arc_hdr_destroy(arc_buf_hdr_t * hdr)3665 arc_hdr_destroy(arc_buf_hdr_t *hdr)
3666 {
3667 if (HDR_HAS_L1HDR(hdr)) {
3668 ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3669 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
3670 }
3671 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3672 ASSERT(!HDR_IN_HASH_TABLE(hdr));
3673 boolean_t l1hdr_destroyed = B_FALSE;
3674
3675 /*
3676 * If L2_WRITING, destroy L1HDR before L2HDR (under mutex) so
3677 * arc_hdr_free_abd() can properly defer ABDs. Otherwise, destroy
3678 * L1HDR outside mutex to minimize contention.
3679 */
3680 if (HDR_HAS_L2HDR(hdr)) {
3681 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3682 boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
3683
3684 if (!buflist_held)
3685 mutex_enter(&dev->l2ad_mtx);
3686
3687 /*
3688 * Even though we checked this conditional above, we
3689 * need to check this again now that we have the
3690 * l2ad_mtx. This is because we could be racing with
3691 * another thread calling l2arc_evict() which might have
3692 * destroyed this header's L2 portion as we were waiting
3693 * to acquire the l2ad_mtx. If that happens, we don't
3694 * want to re-destroy the header's L2 portion.
3695 */
3696 if (HDR_HAS_L2HDR(hdr)) {
3697 if (HDR_L2_WRITING(hdr)) {
3698 l1hdr_destroyed = B_TRUE;
3699
3700 if (!HDR_EMPTY(hdr))
3701 buf_discard_identity(hdr);
3702
3703 if (HDR_HAS_L1HDR(hdr)) {
3704 arc_cksum_free(hdr);
3705
3706 while (hdr->b_l1hdr.b_buf != NULL)
3707 arc_buf_destroy_impl(
3708 hdr->b_l1hdr.b_buf);
3709
3710 if (hdr->b_l1hdr.b_pabd != NULL)
3711 arc_hdr_free_abd(hdr, B_FALSE);
3712
3713 if (HDR_HAS_RABD(hdr))
3714 arc_hdr_free_abd(hdr, B_TRUE);
3715 }
3716 }
3717
3718 arc_hdr_l2hdr_destroy(hdr);
3719 }
3720
3721 if (!buflist_held)
3722 mutex_exit(&dev->l2ad_mtx);
3723 }
3724
3725 if (!l1hdr_destroyed) {
3726 if (!HDR_EMPTY(hdr))
3727 buf_discard_identity(hdr);
3728
3729 if (HDR_HAS_L1HDR(hdr)) {
3730 arc_cksum_free(hdr);
3731
3732 while (hdr->b_l1hdr.b_buf != NULL)
3733 arc_buf_destroy_impl(hdr->b_l1hdr.b_buf);
3734
3735 if (hdr->b_l1hdr.b_pabd != NULL)
3736 arc_hdr_free_abd(hdr, B_FALSE);
3737
3738 if (HDR_HAS_RABD(hdr))
3739 arc_hdr_free_abd(hdr, B_TRUE);
3740 }
3741 }
3742
3743 VERIFY0P(hdr->b_hash_next);
3744 if (HDR_HAS_L1HDR(hdr)) {
3745 VERIFY(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3746 ASSERT0P(hdr->b_l1hdr.b_acb);
3747 #ifdef ZFS_DEBUG
3748 ASSERT0P(hdr->b_l1hdr.b_freeze_cksum);
3749 #endif
3750 kmem_cache_free(hdr_full_cache, hdr);
3751 } else {
3752 kmem_cache_free(hdr_l2only_cache, hdr);
3753 }
3754 }
3755
3756 void
arc_buf_destroy(arc_buf_t * buf,const void * tag)3757 arc_buf_destroy(arc_buf_t *buf, const void *tag)
3758 {
3759 arc_buf_hdr_t *hdr = buf->b_hdr;
3760
3761 if (hdr->b_l1hdr.b_state == arc_anon) {
3762 ASSERT3P(hdr->b_l1hdr.b_buf, ==, buf);
3763 ASSERT(ARC_BUF_LAST(buf));
3764 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3765 VERIFY0(remove_reference(hdr, tag));
3766 return;
3767 }
3768
3769 kmutex_t *hash_lock = HDR_LOCK(hdr);
3770 mutex_enter(hash_lock);
3771
3772 ASSERT3P(hdr, ==, buf->b_hdr);
3773 ASSERT3P(hdr->b_l1hdr.b_buf, !=, NULL);
3774 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3775 ASSERT3P(hdr->b_l1hdr.b_state, !=, arc_anon);
3776 ASSERT3P(buf->b_data, !=, NULL);
3777
3778 arc_buf_destroy_impl(buf);
3779 (void) remove_reference(hdr, tag);
3780 mutex_exit(hash_lock);
3781 }
3782
3783 /*
3784 * Evict the arc_buf_hdr that is provided as a parameter. The resultant
3785 * state of the header is dependent on its state prior to entering this
3786 * function. The following transitions are possible:
3787 *
3788 * - arc_mru -> arc_mru_ghost
3789 * - arc_mfu -> arc_mfu_ghost
3790 * - arc_mru_ghost -> arc_l2c_only
3791 * - arc_mru_ghost -> deleted
3792 * - arc_mfu_ghost -> arc_l2c_only
3793 * - arc_mfu_ghost -> deleted
3794 * - arc_uncached -> deleted
3795 *
3796 * Return total size of evicted data buffers for eviction progress tracking.
3797 * When evicting from ghost states return logical buffer size to make eviction
3798 * progress at the same (or at least comparable) rate as from non-ghost states.
3799 *
3800 * Return *real_evicted for actual ARC size reduction to wake up threads
3801 * waiting for it. For non-ghost states it includes size of evicted data
3802 * buffers (the headers are not freed there). For ghost states it includes
3803 * only the evicted headers size.
3804 */
3805 static int64_t
arc_evict_hdr(arc_buf_hdr_t * hdr,uint64_t * real_evicted)3806 arc_evict_hdr(arc_buf_hdr_t *hdr, uint64_t *real_evicted)
3807 {
3808 arc_state_t *evicted_state, *state;
3809 int64_t bytes_evicted = 0;
3810
3811 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
3812 ASSERT(HDR_HAS_L1HDR(hdr));
3813 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3814 ASSERT0P(hdr->b_l1hdr.b_buf);
3815 ASSERT0(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt));
3816
3817 *real_evicted = 0;
3818 state = hdr->b_l1hdr.b_state;
3819 if (GHOST_STATE(state)) {
3820
3821 /*
3822 * l2arc_write_buffers() relies on a header's L1 portion
3823 * (i.e. its b_pabd field) during it's write phase.
3824 * Thus, we cannot push a header onto the arc_l2c_only
3825 * state (removing its L1 piece) until the header is
3826 * done being written to the l2arc.
3827 */
3828 if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
3829 ARCSTAT_BUMP(arcstat_evict_l2_skip);
3830 return (bytes_evicted);
3831 }
3832
3833 ARCSTAT_BUMP(arcstat_deleted);
3834 bytes_evicted += HDR_GET_LSIZE(hdr);
3835
3836 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
3837
3838 if (HDR_HAS_L2HDR(hdr)) {
3839 ASSERT0P(hdr->b_l1hdr.b_pabd);
3840 ASSERT(!HDR_HAS_RABD(hdr));
3841 /*
3842 * This buffer is cached on the 2nd Level ARC;
3843 * don't destroy the header.
3844 */
3845 arc_change_state(arc_l2c_only, hdr);
3846 /*
3847 * dropping from L1+L2 cached to L2-only,
3848 * realloc to remove the L1 header.
3849 */
3850 (void) arc_hdr_realloc(hdr, hdr_full_cache,
3851 hdr_l2only_cache);
3852 *real_evicted += HDR_FULL_SIZE - HDR_L2ONLY_SIZE;
3853 } else {
3854 arc_change_state(arc_anon, hdr);
3855 arc_hdr_destroy(hdr);
3856 *real_evicted += HDR_FULL_SIZE;
3857 }
3858 return (bytes_evicted);
3859 }
3860
3861 ASSERT(state == arc_mru || state == arc_mfu || state == arc_uncached);
3862 evicted_state = (state == arc_uncached) ? arc_anon :
3863 ((state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost);
3864
3865 /* prefetch buffers have a minimum lifespan */
3866 uint_t min_lifetime = HDR_PRESCIENT_PREFETCH(hdr) ?
3867 arc_min_prescient_prefetch : arc_min_prefetch;
3868 if ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
3869 ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access < min_lifetime) {
3870 ARCSTAT_BUMP(arcstat_evict_skip);
3871 return (bytes_evicted);
3872 }
3873
3874 if (HDR_HAS_L2HDR(hdr)) {
3875 ARCSTAT_INCR(arcstat_evict_l2_cached, HDR_GET_LSIZE(hdr));
3876 } else {
3877 if (l2arc_write_eligible(hdr->b_spa, hdr)) {
3878 ARCSTAT_INCR(arcstat_evict_l2_eligible,
3879 HDR_GET_LSIZE(hdr));
3880
3881 switch (state->arcs_state) {
3882 case ARC_STATE_MRU:
3883 ARCSTAT_INCR(
3884 arcstat_evict_l2_eligible_mru,
3885 HDR_GET_LSIZE(hdr));
3886 break;
3887 case ARC_STATE_MFU:
3888 ARCSTAT_INCR(
3889 arcstat_evict_l2_eligible_mfu,
3890 HDR_GET_LSIZE(hdr));
3891 break;
3892 default:
3893 break;
3894 }
3895 } else {
3896 ARCSTAT_INCR(arcstat_evict_l2_ineligible,
3897 HDR_GET_LSIZE(hdr));
3898 }
3899 }
3900
3901 bytes_evicted += arc_hdr_size(hdr);
3902 *real_evicted += arc_hdr_size(hdr);
3903
3904 /*
3905 * If this hdr is being evicted and has a compressed buffer then we
3906 * discard it here before we change states. This ensures that the
3907 * accounting is updated correctly in arc_free_data_impl().
3908 */
3909 if (hdr->b_l1hdr.b_pabd != NULL)
3910 arc_hdr_free_abd(hdr, B_FALSE);
3911
3912 if (HDR_HAS_RABD(hdr))
3913 arc_hdr_free_abd(hdr, B_TRUE);
3914
3915 arc_change_state(evicted_state, hdr);
3916 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
3917 if (evicted_state == arc_anon) {
3918 arc_hdr_destroy(hdr);
3919 *real_evicted += HDR_FULL_SIZE;
3920 } else {
3921 ASSERT(HDR_IN_HASH_TABLE(hdr));
3922 }
3923
3924 return (bytes_evicted);
3925 }
3926
3927 static void
arc_set_need_free(void)3928 arc_set_need_free(void)
3929 {
3930 ASSERT(MUTEX_HELD(&arc_evict_lock));
3931 int64_t remaining = arc_free_memory() - arc_sys_free / 2;
3932 arc_evict_waiter_t *aw = list_tail(&arc_evict_waiters);
3933 if (aw == NULL) {
3934 arc_need_free = MAX(-remaining, 0);
3935 } else {
3936 arc_need_free =
3937 MAX(-remaining, (int64_t)(aw->aew_count - arc_evict_count));
3938 }
3939 }
3940
3941 static uint64_t
arc_evict_state_impl(multilist_t * ml,int idx,arc_buf_hdr_t * marker,uint64_t spa,uint64_t bytes,boolean_t * more)3942 arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
3943 uint64_t spa, uint64_t bytes, boolean_t *more)
3944 {
3945 multilist_sublist_t *mls;
3946 uint64_t bytes_evicted = 0, real_evicted = 0;
3947 arc_buf_hdr_t *hdr;
3948 kmutex_t *hash_lock;
3949 uint_t evict_count = zfs_arc_evict_batch_limit;
3950
3951 ASSERT3P(marker, !=, NULL);
3952
3953 mls = multilist_sublist_lock_idx(ml, idx);
3954
3955 for (hdr = multilist_sublist_prev(mls, marker); likely(hdr != NULL);
3956 hdr = multilist_sublist_prev(mls, marker)) {
3957 if ((evict_count == 0) || (bytes_evicted >= bytes))
3958 break;
3959
3960 /*
3961 * To keep our iteration location, move the marker
3962 * forward. Since we're not holding hdr's hash lock, we
3963 * must be very careful and not remove 'hdr' from the
3964 * sublist. Otherwise, other consumers might mistake the
3965 * 'hdr' as not being on a sublist when they call the
3966 * multilist_link_active() function (they all rely on
3967 * the hash lock protecting concurrent insertions and
3968 * removals). multilist_sublist_move_forward() was
3969 * specifically implemented to ensure this is the case
3970 * (only 'marker' will be removed and re-inserted).
3971 */
3972 multilist_sublist_move_forward(mls, marker);
3973
3974 /*
3975 * The only case where the b_spa field should ever be
3976 * zero, is the marker headers inserted by
3977 * arc_evict_state(). It's possible for multiple threads
3978 * to be calling arc_evict_state() concurrently (e.g.
3979 * dsl_pool_close() and zio_inject_fault()), so we must
3980 * skip any markers we see from these other threads.
3981 */
3982 if (hdr->b_spa == 0)
3983 continue;
3984
3985 /* we're only interested in evicting buffers of a certain spa */
3986 if (spa != 0 && hdr->b_spa != spa) {
3987 ARCSTAT_BUMP(arcstat_evict_skip);
3988 continue;
3989 }
3990
3991 hash_lock = HDR_LOCK(hdr);
3992
3993 /*
3994 * We aren't calling this function from any code path
3995 * that would already be holding a hash lock, so we're
3996 * asserting on this assumption to be defensive in case
3997 * this ever changes. Without this check, it would be
3998 * possible to incorrectly increment arcstat_mutex_miss
3999 * below (e.g. if the code changed such that we called
4000 * this function with a hash lock held).
4001 */
4002 ASSERT(!MUTEX_HELD(hash_lock));
4003
4004 if (mutex_tryenter(hash_lock)) {
4005 uint64_t revicted;
4006 uint64_t evicted = arc_evict_hdr(hdr, &revicted);
4007 mutex_exit(hash_lock);
4008
4009 bytes_evicted += evicted;
4010 real_evicted += revicted;
4011
4012 /*
4013 * If evicted is zero, arc_evict_hdr() must have
4014 * decided to skip this header, don't increment
4015 * evict_count in this case.
4016 */
4017 if (evicted != 0)
4018 evict_count--;
4019
4020 } else {
4021 ARCSTAT_BUMP(arcstat_mutex_miss);
4022 }
4023 }
4024
4025 multilist_sublist_unlock(mls);
4026
4027 /* Indicate if another iteration may be productive. */
4028 if (more)
4029 *more = (hdr != NULL);
4030
4031 /*
4032 * Increment the count of evicted bytes, and wake up any threads that
4033 * are waiting for the count to reach this value. Since the list is
4034 * ordered by ascending aew_count, we pop off the beginning of the
4035 * list until we reach the end, or a waiter that's past the current
4036 * "count". Doing this outside the loop reduces the number of times
4037 * we need to acquire the global arc_evict_lock.
4038 *
4039 * Only wake when there's sufficient free memory in the system
4040 * (specifically, arc_sys_free/2, which by default is a bit more than
4041 * 1/64th of RAM). See the comments in arc_wait_for_eviction().
4042 */
4043 mutex_enter(&arc_evict_lock);
4044 arc_evict_count += real_evicted;
4045
4046 if (arc_free_memory() > arc_sys_free / 2) {
4047 arc_evict_waiter_t *aw;
4048 while ((aw = list_head(&arc_evict_waiters)) != NULL &&
4049 aw->aew_count <= arc_evict_count) {
4050 list_remove(&arc_evict_waiters, aw);
4051 cv_signal(&aw->aew_cv);
4052 }
4053 }
4054 arc_set_need_free();
4055 mutex_exit(&arc_evict_lock);
4056
4057 return (bytes_evicted);
4058 }
4059
4060 static arc_buf_hdr_t *
arc_state_alloc_marker(void)4061 arc_state_alloc_marker(void)
4062 {
4063 arc_buf_hdr_t *marker = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
4064
4065 /*
4066 * A b_spa of 0 is used to indicate that this header is
4067 * a marker. This fact is used in arc_evict_state_impl().
4068 */
4069 marker->b_spa = 0;
4070
4071 return (marker);
4072 }
4073
4074 static void
arc_state_free_marker(arc_buf_hdr_t * marker)4075 arc_state_free_marker(arc_buf_hdr_t *marker)
4076 {
4077 kmem_cache_free(hdr_full_cache, marker);
4078 }
4079
4080 /*
4081 * Allocate an array of buffer headers used as placeholders during arc state
4082 * eviction.
4083 */
4084 static arc_buf_hdr_t **
arc_state_alloc_markers(int count)4085 arc_state_alloc_markers(int count)
4086 {
4087 arc_buf_hdr_t **markers;
4088
4089 markers = kmem_zalloc(sizeof (*markers) * count, KM_SLEEP);
4090 for (int i = 0; i < count; i++)
4091 markers[i] = arc_state_alloc_marker();
4092 return (markers);
4093 }
4094
4095 static void
arc_state_free_markers(arc_buf_hdr_t ** markers,int count)4096 arc_state_free_markers(arc_buf_hdr_t **markers, int count)
4097 {
4098 for (int i = 0; i < count; i++)
4099 arc_state_free_marker(markers[i]);
4100 kmem_free(markers, sizeof (*markers) * count);
4101 }
4102
4103 typedef struct evict_arg {
4104 taskq_ent_t eva_tqent;
4105 multilist_t *eva_ml;
4106 arc_buf_hdr_t *eva_marker;
4107 int eva_idx;
4108 uint64_t eva_spa;
4109 uint64_t eva_bytes;
4110 uint64_t eva_evicted;
4111 } evict_arg_t;
4112
4113 static void
arc_evict_task(void * arg)4114 arc_evict_task(void *arg)
4115 {
4116 evict_arg_t *eva = arg;
4117 uint64_t total_evicted = 0;
4118 boolean_t more;
4119 uint_t batches = zfs_arc_evict_batches_limit;
4120
4121 /* Process multiple batches to amortize taskq dispatch overhead. */
4122 do {
4123 total_evicted += arc_evict_state_impl(eva->eva_ml,
4124 eva->eva_idx, eva->eva_marker, eva->eva_spa,
4125 eva->eva_bytes - total_evicted, &more);
4126 } while (total_evicted < eva->eva_bytes && --batches > 0 && more);
4127
4128 eva->eva_evicted = total_evicted;
4129 }
4130
4131 static void
arc_evict_thread_init(void)4132 arc_evict_thread_init(void)
4133 {
4134 if (zfs_arc_evict_threads == 0) {
4135 /*
4136 * Compute number of threads we want to use for eviction.
4137 *
4138 * Normally, it's log2(ncpus) + ncpus/32, which gets us to the
4139 * default max of 16 threads at ~256 CPUs.
4140 *
4141 * However, that formula goes to two threads at 4 CPUs, which
4142 * is still rather to low to be really useful, so we just go
4143 * with 1 thread at fewer than 6 cores.
4144 */
4145 if (max_ncpus < 6)
4146 zfs_arc_evict_threads = 1;
4147 else
4148 zfs_arc_evict_threads =
4149 (highbit64(max_ncpus) - 1) + max_ncpus / 32;
4150 } else if (zfs_arc_evict_threads > max_ncpus)
4151 zfs_arc_evict_threads = max_ncpus;
4152
4153 if (zfs_arc_evict_threads > 1) {
4154 arc_evict_taskq = taskq_create("arc_evict",
4155 zfs_arc_evict_threads, defclsyspri, 0, INT_MAX,
4156 TASKQ_PREPOPULATE);
4157 arc_evict_arg = kmem_zalloc(
4158 sizeof (evict_arg_t) * zfs_arc_evict_threads, KM_SLEEP);
4159 }
4160 }
4161
4162 /*
4163 * The minimum number of bytes we can evict at once is a block size.
4164 * So, SPA_MAXBLOCKSIZE is a reasonable minimal value per an eviction task.
4165 * We use this value to compute a scaling factor for the eviction tasks.
4166 */
4167 #define MIN_EVICT_SIZE (SPA_MAXBLOCKSIZE)
4168
4169 /*
4170 * Evict buffers from the given arc state, until we've removed the
4171 * specified number of bytes. Move the removed buffers to the
4172 * appropriate evict state.
4173 *
4174 * This function makes a "best effort". It skips over any buffers
4175 * it can't get a hash_lock on, and so, may not catch all candidates.
4176 * It may also return without evicting as much space as requested.
4177 *
4178 * If bytes is specified using the special value ARC_EVICT_ALL, this
4179 * will evict all available (i.e. unlocked and evictable) buffers from
4180 * the given arc state; which is used by arc_flush().
4181 */
4182 static uint64_t
arc_evict_state(arc_state_t * state,arc_buf_contents_t type,uint64_t spa,uint64_t bytes)4183 arc_evict_state(arc_state_t *state, arc_buf_contents_t type, uint64_t spa,
4184 uint64_t bytes)
4185 {
4186 uint64_t total_evicted = 0;
4187 multilist_t *ml = &state->arcs_list[type];
4188 int num_sublists;
4189 arc_buf_hdr_t **markers;
4190 evict_arg_t *eva = NULL;
4191
4192 num_sublists = multilist_get_num_sublists(ml);
4193
4194 boolean_t use_evcttq = zfs_arc_evict_threads > 1;
4195
4196 /*
4197 * If we've tried to evict from each sublist, made some
4198 * progress, but still have not hit the target number of bytes
4199 * to evict, we want to keep trying. The markers allow us to
4200 * pick up where we left off for each individual sublist, rather
4201 * than starting from the tail each time.
4202 */
4203 if (zthr_iscurthread(arc_evict_zthr)) {
4204 markers = arc_state_evict_markers;
4205 ASSERT3S(num_sublists, <=, arc_state_evict_marker_count);
4206 } else {
4207 markers = arc_state_alloc_markers(num_sublists);
4208 }
4209 for (int i = 0; i < num_sublists; i++) {
4210 multilist_sublist_t *mls;
4211
4212 mls = multilist_sublist_lock_idx(ml, i);
4213 multilist_sublist_insert_tail(mls, markers[i]);
4214 multilist_sublist_unlock(mls);
4215 }
4216
4217 if (use_evcttq) {
4218 if (zthr_iscurthread(arc_evict_zthr))
4219 eva = arc_evict_arg;
4220 else
4221 eva = kmem_alloc(sizeof (evict_arg_t) *
4222 zfs_arc_evict_threads, KM_NOSLEEP);
4223 if (eva) {
4224 for (int i = 0; i < zfs_arc_evict_threads; i++) {
4225 taskq_init_ent(&eva[i].eva_tqent);
4226 eva[i].eva_ml = ml;
4227 eva[i].eva_spa = spa;
4228 }
4229 } else {
4230 /*
4231 * Fall back to the regular single evict if it is not
4232 * possible to allocate memory for the taskq entries.
4233 */
4234 use_evcttq = B_FALSE;
4235 }
4236 }
4237
4238 /*
4239 * Start eviction using a randomly selected sublist, this is to try and
4240 * evenly balance eviction across all sublists. Always starting at the
4241 * same sublist (e.g. index 0) would cause evictions to favor certain
4242 * sublists over others.
4243 */
4244 uint64_t scan_evicted = 0;
4245 int sublists_left = num_sublists;
4246 int sublist_idx = multilist_get_random_index(ml);
4247
4248 /*
4249 * While we haven't hit our target number of bytes to evict, or
4250 * we're evicting all available buffers.
4251 */
4252 while (total_evicted < bytes) {
4253 uint64_t evict = MIN_EVICT_SIZE;
4254 uint_t ntasks = zfs_arc_evict_threads;
4255
4256 if (use_evcttq) {
4257 if (sublists_left < ntasks)
4258 ntasks = sublists_left;
4259
4260 if (ntasks < 2)
4261 use_evcttq = B_FALSE;
4262 }
4263
4264 if (use_evcttq) {
4265 uint64_t left = bytes - total_evicted;
4266
4267 if (bytes == ARC_EVICT_ALL) {
4268 evict = bytes;
4269 } else if (left >= ntasks * MIN_EVICT_SIZE) {
4270 evict = DIV_ROUND_UP(left, ntasks);
4271 } else {
4272 ntasks = left / MIN_EVICT_SIZE;
4273 if (ntasks < 2)
4274 use_evcttq = B_FALSE;
4275 else
4276 evict = DIV_ROUND_UP(left, ntasks);
4277 }
4278 }
4279
4280 for (int i = 0; sublists_left > 0; i++, sublist_idx++,
4281 sublists_left--) {
4282 uint64_t bytes_evicted;
4283
4284 /* we've reached the end, wrap to the beginning */
4285 if (sublist_idx >= num_sublists)
4286 sublist_idx = 0;
4287
4288 if (use_evcttq) {
4289 if (i == ntasks)
4290 break;
4291
4292 eva[i].eva_marker = markers[sublist_idx];
4293 eva[i].eva_idx = sublist_idx;
4294 eva[i].eva_bytes = evict;
4295
4296 taskq_dispatch_ent(arc_evict_taskq,
4297 arc_evict_task, &eva[i], 0,
4298 &eva[i].eva_tqent);
4299
4300 continue;
4301 }
4302
4303 bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
4304 markers[sublist_idx], spa, bytes - total_evicted,
4305 NULL);
4306
4307 scan_evicted += bytes_evicted;
4308 total_evicted += bytes_evicted;
4309
4310 if (total_evicted < bytes)
4311 kpreempt(KPREEMPT_SYNC);
4312 else
4313 break;
4314 }
4315
4316 if (use_evcttq) {
4317 taskq_wait(arc_evict_taskq);
4318
4319 for (int i = 0; i < ntasks; i++) {
4320 scan_evicted += eva[i].eva_evicted;
4321 total_evicted += eva[i].eva_evicted;
4322 }
4323 }
4324
4325 /*
4326 * If we scanned all sublists and didn't evict anything, we
4327 * have no reason to believe we'll evict more during another
4328 * scan, so break the loop.
4329 */
4330 if (scan_evicted == 0 && sublists_left == 0) {
4331 /* This isn't possible, let's make that obvious */
4332 ASSERT3S(bytes, !=, 0);
4333
4334 /*
4335 * When bytes is ARC_EVICT_ALL, the only way to
4336 * break the loop is when scan_evicted is zero.
4337 * In that case, we actually have evicted enough,
4338 * so we don't want to increment the kstat.
4339 */
4340 if (bytes != ARC_EVICT_ALL) {
4341 ASSERT3S(total_evicted, <, bytes);
4342 ARCSTAT_BUMP(arcstat_evict_not_enough);
4343 }
4344
4345 break;
4346 }
4347
4348 /*
4349 * If we scanned all sublists but still have more to do,
4350 * reset the counts so we can go around again.
4351 */
4352 if (sublists_left == 0) {
4353 sublists_left = num_sublists;
4354 sublist_idx = multilist_get_random_index(ml);
4355 scan_evicted = 0;
4356
4357 /*
4358 * Since we're about to reconsider all sublists,
4359 * re-enable use of the evict threads if available.
4360 */
4361 use_evcttq = (zfs_arc_evict_threads > 1 && eva != NULL);
4362 }
4363 }
4364
4365 if (eva != NULL && eva != arc_evict_arg)
4366 kmem_free(eva, sizeof (evict_arg_t) * zfs_arc_evict_threads);
4367
4368 for (int i = 0; i < num_sublists; i++) {
4369 multilist_sublist_t *mls = multilist_sublist_lock_idx(ml, i);
4370 multilist_sublist_remove(mls, markers[i]);
4371 multilist_sublist_unlock(mls);
4372 }
4373
4374 if (markers != arc_state_evict_markers)
4375 arc_state_free_markers(markers, num_sublists);
4376
4377 return (total_evicted);
4378 }
4379
4380 /*
4381 * Flush all "evictable" data of the given type from the arc state
4382 * specified. This will not evict any "active" buffers (i.e. referenced).
4383 *
4384 * When 'retry' is set to B_FALSE, the function will make a single pass
4385 * over the state and evict any buffers that it can. Since it doesn't
4386 * continually retry the eviction, it might end up leaving some buffers
4387 * in the ARC due to lock misses.
4388 *
4389 * When 'retry' is set to B_TRUE, the function will continually retry the
4390 * eviction until *all* evictable buffers have been removed from the
4391 * state. As a result, if concurrent insertions into the state are
4392 * allowed (e.g. if the ARC isn't shutting down), this function might
4393 * wind up in an infinite loop, continually trying to evict buffers.
4394 */
4395 static uint64_t
arc_flush_state(arc_state_t * state,uint64_t spa,arc_buf_contents_t type,boolean_t retry)4396 arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
4397 boolean_t retry)
4398 {
4399 uint64_t evicted = 0;
4400
4401 while (zfs_refcount_count(&state->arcs_esize[type]) != 0) {
4402 evicted += arc_evict_state(state, type, spa, ARC_EVICT_ALL);
4403
4404 if (!retry)
4405 break;
4406 }
4407
4408 return (evicted);
4409 }
4410
4411 /*
4412 * Evict the specified number of bytes from the state specified. This
4413 * function prevents us from trying to evict more from a state's list
4414 * than is "evictable", and to skip evicting altogether when passed a
4415 * negative value for "bytes". In contrast, arc_evict_state() will
4416 * evict everything it can, when passed a negative value for "bytes".
4417 */
4418 static uint64_t
arc_evict_impl(arc_state_t * state,arc_buf_contents_t type,int64_t bytes)4419 arc_evict_impl(arc_state_t *state, arc_buf_contents_t type, int64_t bytes)
4420 {
4421 uint64_t delta;
4422
4423 if (bytes > 0 && zfs_refcount_count(&state->arcs_esize[type]) > 0) {
4424 delta = MIN(zfs_refcount_count(&state->arcs_esize[type]),
4425 bytes);
4426 return (arc_evict_state(state, type, 0, delta));
4427 }
4428
4429 return (0);
4430 }
4431
4432 /*
4433 * Adjust specified fraction, taking into account initial ghost state(s) size,
4434 * ghost hit bytes towards increasing the fraction, ghost hit bytes towards
4435 * decreasing it, plus a balance factor, controlling the decrease rate, used
4436 * to balance metadata vs data.
4437 */
4438 static uint64_t
arc_evict_adj(uint64_t frac,uint64_t total,uint64_t up,uint64_t down,uint_t balance)4439 arc_evict_adj(uint64_t frac, uint64_t total, uint64_t up, uint64_t down,
4440 uint_t balance)
4441 {
4442 if (total < 32 || up + down == 0)
4443 return (frac);
4444
4445 /*
4446 * We should not have more ghost hits than ghost size, but they may
4447 * get close. To avoid overflows below up/down should not be bigger
4448 * than 1/5 of total. But to limit maximum adjustment speed restrict
4449 * it some more.
4450 */
4451 if (up + down >= total / 16) {
4452 uint64_t scale = (up + down) / (total / 32);
4453 up /= scale;
4454 down /= scale;
4455 }
4456
4457 /* Get maximal dynamic range by choosing optimal shifts. */
4458 int s = highbit64(total);
4459 s = MIN(64 - s, 32);
4460
4461 ASSERT3U(frac, <=, 1ULL << 32);
4462 uint64_t ofrac = (1ULL << 32) - frac;
4463
4464 if (frac >= 4 * ofrac)
4465 up /= frac / (2 * ofrac + 1);
4466 up = (up << s) / (total >> (32 - s));
4467 if (ofrac >= 4 * frac)
4468 down /= ofrac / (2 * frac + 1);
4469 down = (down << s) / (total >> (32 - s));
4470 down = down * 100 / balance;
4471
4472 ASSERT3U(up, <=, (1ULL << 32) - frac);
4473 ASSERT3U(down, <=, frac);
4474 return (frac + up - down);
4475 }
4476
4477 /*
4478 * Calculate (x * multiplier / divisor) without unnecesary overflows.
4479 */
4480 static uint64_t
arc_mf(uint64_t x,uint64_t multiplier,uint64_t divisor)4481 arc_mf(uint64_t x, uint64_t multiplier, uint64_t divisor)
4482 {
4483 uint64_t q = (x / divisor);
4484 uint64_t r = (x % divisor);
4485
4486 return ((q * multiplier) + ((r * multiplier) / divisor));
4487 }
4488
4489 /*
4490 * Evict buffers from the cache, such that arcstat_size is capped by arc_c.
4491 */
4492 static uint64_t
arc_evict(void)4493 arc_evict(void)
4494 {
4495 uint64_t bytes, total_evicted = 0;
4496 int64_t e, mrud, mrum, mfud, mfum, w;
4497 static uint64_t ogrd, ogrm, ogfd, ogfm;
4498 static uint64_t gsrd, gsrm, gsfd, gsfm;
4499 uint64_t ngrd, ngrm, ngfd, ngfm;
4500
4501 /* Get current size of ARC states we can evict from. */
4502 mrud = zfs_refcount_count(&arc_mru->arcs_size[ARC_BUFC_DATA]) +
4503 zfs_refcount_count(&arc_anon->arcs_size[ARC_BUFC_DATA]);
4504 mrum = zfs_refcount_count(&arc_mru->arcs_size[ARC_BUFC_METADATA]) +
4505 zfs_refcount_count(&arc_anon->arcs_size[ARC_BUFC_METADATA]);
4506 mfud = zfs_refcount_count(&arc_mfu->arcs_size[ARC_BUFC_DATA]);
4507 mfum = zfs_refcount_count(&arc_mfu->arcs_size[ARC_BUFC_METADATA]);
4508 uint64_t d = mrud + mfud;
4509 uint64_t m = mrum + mfum;
4510 uint64_t t = d + m;
4511
4512 /* Get ARC ghost hits since last eviction. */
4513 ngrd = wmsum_value(&arc_mru_ghost->arcs_hits[ARC_BUFC_DATA]);
4514 uint64_t grd = ngrd - ogrd;
4515 ogrd = ngrd;
4516 ngrm = wmsum_value(&arc_mru_ghost->arcs_hits[ARC_BUFC_METADATA]);
4517 uint64_t grm = ngrm - ogrm;
4518 ogrm = ngrm;
4519 ngfd = wmsum_value(&arc_mfu_ghost->arcs_hits[ARC_BUFC_DATA]);
4520 uint64_t gfd = ngfd - ogfd;
4521 ogfd = ngfd;
4522 ngfm = wmsum_value(&arc_mfu_ghost->arcs_hits[ARC_BUFC_METADATA]);
4523 uint64_t gfm = ngfm - ogfm;
4524 ogfm = ngfm;
4525
4526 /* Adjust ARC states balance based on ghost hits. */
4527 arc_meta = arc_evict_adj(arc_meta, gsrd + gsrm + gsfd + gsfm,
4528 grm + gfm, grd + gfd, zfs_arc_meta_balance);
4529 arc_pd = arc_evict_adj(arc_pd, gsrd + gsfd, grd, gfd, 100);
4530 arc_pm = arc_evict_adj(arc_pm, gsrm + gsfm, grm, gfm, 100);
4531
4532 uint64_t asize = aggsum_value(&arc_sums.arcstat_size);
4533 uint64_t ac = arc_c;
4534 int64_t wt = t - (asize - ac);
4535
4536 /*
4537 * Try to reduce pinned dnodes if more than 3/4 of wanted metadata
4538 * target is not evictable or if they go over arc_dnode_limit.
4539 */
4540 int64_t prune = 0;
4541 int64_t dn = aggsum_value(&arc_sums.arcstat_dnode_size);
4542 int64_t nem = zfs_refcount_count(&arc_mru->arcs_size[ARC_BUFC_METADATA])
4543 + zfs_refcount_count(&arc_mfu->arcs_size[ARC_BUFC_METADATA])
4544 - zfs_refcount_count(&arc_mru->arcs_esize[ARC_BUFC_METADATA])
4545 - zfs_refcount_count(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
4546 w = wt * (int64_t)(arc_meta >> 16) >> 16;
4547 if (nem > w * 3 / 4) {
4548 prune = dn / sizeof (dnode_t) *
4549 zfs_arc_dnode_reduce_percent / 100;
4550 if (nem < w && w > 4)
4551 prune = arc_mf(prune, nem - w * 3 / 4, w / 4);
4552 }
4553 if (dn > arc_dnode_limit) {
4554 prune = MAX(prune, (dn - arc_dnode_limit) / sizeof (dnode_t) *
4555 zfs_arc_dnode_reduce_percent / 100);
4556 }
4557 if (prune > 0)
4558 arc_prune_async(prune);
4559
4560 /* Evict MRU metadata. */
4561 w = wt * (int64_t)(arc_meta * arc_pm >> 48) >> 16;
4562 e = MIN((int64_t)(asize - ac), (int64_t)(mrum - w));
4563 bytes = arc_evict_impl(arc_mru, ARC_BUFC_METADATA, e);
4564 total_evicted += bytes;
4565 mrum -= bytes;
4566 asize -= bytes;
4567
4568 /* Evict MFU metadata. */
4569 w = wt * (int64_t)(arc_meta >> 16) >> 16;
4570 e = MIN((int64_t)(asize - ac), (int64_t)(m - bytes - w));
4571 bytes = arc_evict_impl(arc_mfu, ARC_BUFC_METADATA, e);
4572 total_evicted += bytes;
4573 mfum -= bytes;
4574 asize -= bytes;
4575
4576 /* Evict MRU data. */
4577 wt -= m - total_evicted;
4578 w = wt * (int64_t)(arc_pd >> 16) >> 16;
4579 e = MIN((int64_t)(asize - ac), (int64_t)(mrud - w));
4580 bytes = arc_evict_impl(arc_mru, ARC_BUFC_DATA, e);
4581 total_evicted += bytes;
4582 mrud -= bytes;
4583 asize -= bytes;
4584
4585 /* Evict MFU data. */
4586 e = asize - ac;
4587 bytes = arc_evict_impl(arc_mfu, ARC_BUFC_DATA, e);
4588 mfud -= bytes;
4589 total_evicted += bytes;
4590
4591 /*
4592 * Evict ghost lists
4593 *
4594 * Size of each state's ghost list represents how much that state
4595 * may grow by shrinking the other states. Would it need to shrink
4596 * other states to zero (that is unlikely), its ghost size would be
4597 * equal to sum of other three state sizes. But excessive ghost
4598 * size may result in false ghost hits (too far back), that may
4599 * never result in real cache hits if several states are competing.
4600 * So choose some arbitraty point of 1/2 of other state sizes.
4601 */
4602 gsrd = (mrum + mfud + mfum) / 2;
4603 e = zfs_refcount_count(&arc_mru_ghost->arcs_size[ARC_BUFC_DATA]) -
4604 gsrd;
4605 (void) arc_evict_impl(arc_mru_ghost, ARC_BUFC_DATA, e);
4606
4607 gsrm = (mrud + mfud + mfum) / 2;
4608 e = zfs_refcount_count(&arc_mru_ghost->arcs_size[ARC_BUFC_METADATA]) -
4609 gsrm;
4610 (void) arc_evict_impl(arc_mru_ghost, ARC_BUFC_METADATA, e);
4611
4612 gsfd = (mrud + mrum + mfum) / 2;
4613 e = zfs_refcount_count(&arc_mfu_ghost->arcs_size[ARC_BUFC_DATA]) -
4614 gsfd;
4615 (void) arc_evict_impl(arc_mfu_ghost, ARC_BUFC_DATA, e);
4616
4617 gsfm = (mrud + mrum + mfud) / 2;
4618 e = zfs_refcount_count(&arc_mfu_ghost->arcs_size[ARC_BUFC_METADATA]) -
4619 gsfm;
4620 (void) arc_evict_impl(arc_mfu_ghost, ARC_BUFC_METADATA, e);
4621
4622 return (total_evicted);
4623 }
4624
4625 static void
arc_flush_impl(uint64_t guid,boolean_t retry)4626 arc_flush_impl(uint64_t guid, boolean_t retry)
4627 {
4628 ASSERT(!retry || guid == 0);
4629
4630 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
4631 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
4632
4633 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
4634 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
4635
4636 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
4637 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
4638
4639 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
4640 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
4641
4642 (void) arc_flush_state(arc_uncached, guid, ARC_BUFC_DATA, retry);
4643 (void) arc_flush_state(arc_uncached, guid, ARC_BUFC_METADATA, retry);
4644 }
4645
4646 void
arc_flush(spa_t * spa,boolean_t retry)4647 arc_flush(spa_t *spa, boolean_t retry)
4648 {
4649 /*
4650 * If retry is B_TRUE, a spa must not be specified since we have
4651 * no good way to determine if all of a spa's buffers have been
4652 * evicted from an arc state.
4653 */
4654 ASSERT(!retry || spa == NULL);
4655
4656 arc_flush_impl(spa != NULL ? spa_load_guid(spa) : 0, retry);
4657 }
4658
4659 static arc_async_flush_t *
arc_async_flush_add(uint64_t spa_guid,uint_t level)4660 arc_async_flush_add(uint64_t spa_guid, uint_t level)
4661 {
4662 arc_async_flush_t *af = kmem_alloc(sizeof (*af), KM_SLEEP);
4663 af->af_spa_guid = spa_guid;
4664 af->af_cache_level = level;
4665 taskq_init_ent(&af->af_tqent);
4666 list_link_init(&af->af_node);
4667
4668 mutex_enter(&arc_async_flush_lock);
4669 list_insert_tail(&arc_async_flush_list, af);
4670 mutex_exit(&arc_async_flush_lock);
4671
4672 return (af);
4673 }
4674
4675 static void
arc_async_flush_remove(uint64_t spa_guid,uint_t level)4676 arc_async_flush_remove(uint64_t spa_guid, uint_t level)
4677 {
4678 mutex_enter(&arc_async_flush_lock);
4679 for (arc_async_flush_t *af = list_head(&arc_async_flush_list);
4680 af != NULL; af = list_next(&arc_async_flush_list, af)) {
4681 if (af->af_spa_guid == spa_guid &&
4682 af->af_cache_level == level) {
4683 list_remove(&arc_async_flush_list, af);
4684 kmem_free(af, sizeof (*af));
4685 break;
4686 }
4687 }
4688 mutex_exit(&arc_async_flush_lock);
4689 }
4690
4691 static void
arc_flush_task(void * arg)4692 arc_flush_task(void *arg)
4693 {
4694 arc_async_flush_t *af = arg;
4695 hrtime_t start_time = gethrtime();
4696 uint64_t spa_guid = af->af_spa_guid;
4697
4698 arc_flush_impl(spa_guid, B_FALSE);
4699 arc_async_flush_remove(spa_guid, af->af_cache_level);
4700
4701 uint64_t elapsed = NSEC2MSEC(gethrtime() - start_time);
4702 if (elapsed > 0) {
4703 zfs_dbgmsg("spa %llu arc flushed in %llu ms",
4704 (u_longlong_t)spa_guid, (u_longlong_t)elapsed);
4705 }
4706 }
4707
4708 /*
4709 * ARC buffers use the spa's load guid and can continue to exist after
4710 * the spa_t is gone (exported). The blocks are orphaned since each
4711 * spa import has a different load guid.
4712 *
4713 * It's OK if the spa is re-imported while this asynchronous flush is
4714 * still in progress. The new spa_load_guid will be different.
4715 *
4716 * Also, arc_fini will wait for any arc_flush_task to finish.
4717 */
4718 void
arc_flush_async(spa_t * spa)4719 arc_flush_async(spa_t *spa)
4720 {
4721 uint64_t spa_guid = spa_load_guid(spa);
4722 arc_async_flush_t *af = arc_async_flush_add(spa_guid, 1);
4723
4724 taskq_dispatch_ent(arc_flush_taskq, arc_flush_task,
4725 af, TQ_SLEEP, &af->af_tqent);
4726 }
4727
4728 /*
4729 * Check if a guid is still in-use as part of an async teardown task
4730 */
4731 boolean_t
arc_async_flush_guid_inuse(uint64_t spa_guid)4732 arc_async_flush_guid_inuse(uint64_t spa_guid)
4733 {
4734 mutex_enter(&arc_async_flush_lock);
4735 for (arc_async_flush_t *af = list_head(&arc_async_flush_list);
4736 af != NULL; af = list_next(&arc_async_flush_list, af)) {
4737 if (af->af_spa_guid == spa_guid) {
4738 mutex_exit(&arc_async_flush_lock);
4739 return (B_TRUE);
4740 }
4741 }
4742 mutex_exit(&arc_async_flush_lock);
4743 return (B_FALSE);
4744 }
4745
4746 uint64_t
arc_reduce_target_size(uint64_t to_free)4747 arc_reduce_target_size(uint64_t to_free)
4748 {
4749 /*
4750 * Get the actual arc size. Even if we don't need it, this updates
4751 * the aggsum lower bound estimate for arc_is_overflowing().
4752 */
4753 uint64_t asize = aggsum_value(&arc_sums.arcstat_size);
4754
4755 /*
4756 * All callers want the ARC to actually evict (at least) this much
4757 * memory. Therefore we reduce from the lower of the current size and
4758 * the target size. This way, even if arc_c is much higher than
4759 * arc_size (as can be the case after many calls to arc_freed(), we will
4760 * immediately have arc_c < arc_size and therefore the arc_evict_zthr
4761 * will evict.
4762 */
4763 uint64_t c = arc_c;
4764 if (c > arc_c_min) {
4765 c = MIN(c, MAX(asize, arc_c_min));
4766 to_free = MIN(to_free, c - arc_c_min);
4767 arc_c = c - to_free;
4768 } else {
4769 to_free = 0;
4770 }
4771
4772 /*
4773 * Since dbuf cache size is a fraction of target ARC size, we should
4774 * notify dbuf about the reduction, which might be significant,
4775 * especially if current ARC size was much smaller than the target.
4776 */
4777 dbuf_cache_reduce_target_size();
4778
4779 /*
4780 * Whether or not we reduced the target size, request eviction if the
4781 * current size is over it now, since caller obviously wants some RAM.
4782 */
4783 if (asize > arc_c) {
4784 /* See comment in arc_evict_cb_check() on why lock+flag */
4785 mutex_enter(&arc_evict_lock);
4786 arc_evict_needed = B_TRUE;
4787 mutex_exit(&arc_evict_lock);
4788 zthr_wakeup(arc_evict_zthr);
4789 }
4790
4791 return (to_free);
4792 }
4793
4794 /*
4795 * Determine if the system is under memory pressure and is asking
4796 * to reclaim memory. A return value of B_TRUE indicates that the system
4797 * is under memory pressure and that the arc should adjust accordingly.
4798 */
4799 boolean_t
arc_reclaim_needed(void)4800 arc_reclaim_needed(void)
4801 {
4802 return (arc_available_memory() < 0);
4803 }
4804
4805 void
arc_kmem_reap_soon(void)4806 arc_kmem_reap_soon(void)
4807 {
4808 size_t i;
4809 kmem_cache_t *prev_cache = NULL;
4810 kmem_cache_t *prev_data_cache = NULL;
4811
4812 #ifdef _KERNEL
4813 #if defined(_ILP32)
4814 /*
4815 * Reclaim unused memory from all kmem caches.
4816 */
4817 kmem_reap();
4818 #endif
4819 #endif
4820
4821 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
4822 #if defined(_ILP32)
4823 /* reach upper limit of cache size on 32-bit */
4824 if (zio_buf_cache[i] == NULL)
4825 break;
4826 #endif
4827 if (zio_buf_cache[i] != prev_cache) {
4828 prev_cache = zio_buf_cache[i];
4829 kmem_cache_reap_now(zio_buf_cache[i]);
4830 }
4831 if (zio_data_buf_cache[i] != prev_data_cache) {
4832 prev_data_cache = zio_data_buf_cache[i];
4833 kmem_cache_reap_now(zio_data_buf_cache[i]);
4834 }
4835 }
4836 kmem_cache_reap_now(buf_cache);
4837 kmem_cache_reap_now(hdr_full_cache);
4838 kmem_cache_reap_now(hdr_l2only_cache);
4839 kmem_cache_reap_now(zfs_btree_leaf_cache);
4840 abd_cache_reap_now();
4841 }
4842
4843 static boolean_t
arc_evict_cb_check(void * arg,zthr_t * zthr)4844 arc_evict_cb_check(void *arg, zthr_t *zthr)
4845 {
4846 (void) arg, (void) zthr;
4847
4848 #ifdef ZFS_DEBUG
4849 /*
4850 * This is necessary in order to keep the kstat information
4851 * up to date for tools that display kstat data such as the
4852 * mdb ::arc dcmd and the Linux crash utility. These tools
4853 * typically do not call kstat's update function, but simply
4854 * dump out stats from the most recent update. Without
4855 * this call, these commands may show stale stats for the
4856 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
4857 * with this call, the data might be out of date if the
4858 * evict thread hasn't been woken recently; but that should
4859 * suffice. The arc_state_t structures can be queried
4860 * directly if more accurate information is needed.
4861 */
4862 if (arc_ksp != NULL)
4863 arc_ksp->ks_update(arc_ksp, KSTAT_READ);
4864 #endif
4865
4866 /*
4867 * We have to rely on arc_wait_for_eviction() to tell us when to
4868 * evict, rather than checking if we are overflowing here, so that we
4869 * are sure to not leave arc_wait_for_eviction() waiting on aew_cv.
4870 * If we have become "not overflowing" since arc_wait_for_eviction()
4871 * checked, we need to wake it up. We could broadcast the CV here,
4872 * but arc_wait_for_eviction() may have not yet gone to sleep. We
4873 * would need to use a mutex to ensure that this function doesn't
4874 * broadcast until arc_wait_for_eviction() has gone to sleep (e.g.
4875 * the arc_evict_lock). However, the lock ordering of such a lock
4876 * would necessarily be incorrect with respect to the zthr_lock,
4877 * which is held before this function is called, and is held by
4878 * arc_wait_for_eviction() when it calls zthr_wakeup().
4879 */
4880 if (arc_evict_needed)
4881 return (B_TRUE);
4882
4883 /*
4884 * If we have buffers in uncached state, evict them periodically.
4885 */
4886 return ((zfs_refcount_count(&arc_uncached->arcs_esize[ARC_BUFC_DATA]) +
4887 zfs_refcount_count(&arc_uncached->arcs_esize[ARC_BUFC_METADATA]) &&
4888 ddi_get_lbolt() - arc_last_uncached_flush > arc_min_prefetch / 2));
4889 }
4890
4891 /*
4892 * Keep arc_size under arc_c by running arc_evict which evicts data
4893 * from the ARC.
4894 */
4895 static void
arc_evict_cb(void * arg,zthr_t * zthr)4896 arc_evict_cb(void *arg, zthr_t *zthr)
4897 {
4898 (void) arg;
4899
4900 uint64_t evicted = 0;
4901 fstrans_cookie_t cookie = spl_fstrans_mark();
4902
4903 /* Always try to evict from uncached state. */
4904 arc_last_uncached_flush = ddi_get_lbolt();
4905 evicted += arc_flush_state(arc_uncached, 0, ARC_BUFC_DATA, B_FALSE);
4906 evicted += arc_flush_state(arc_uncached, 0, ARC_BUFC_METADATA, B_FALSE);
4907
4908 /* Evict from other states only if told to. */
4909 if (arc_evict_needed)
4910 evicted += arc_evict();
4911
4912 /*
4913 * If evicted is zero, we couldn't evict anything
4914 * via arc_evict(). This could be due to hash lock
4915 * collisions, but more likely due to the majority of
4916 * arc buffers being unevictable. Therefore, even if
4917 * arc_size is above arc_c, another pass is unlikely to
4918 * be helpful and could potentially cause us to enter an
4919 * infinite loop. Additionally, zthr_iscancelled() is
4920 * checked here so that if the arc is shutting down, the
4921 * broadcast will wake any remaining arc evict waiters.
4922 *
4923 * Note we cancel using zthr instead of arc_evict_zthr
4924 * because the latter may not yet be initializd when the
4925 * callback is first invoked.
4926 */
4927 mutex_enter(&arc_evict_lock);
4928 arc_evict_needed = !zthr_iscancelled(zthr) &&
4929 evicted > 0 && aggsum_compare(&arc_sums.arcstat_size, arc_c) > 0;
4930 if (!arc_evict_needed) {
4931 /*
4932 * We're either no longer overflowing, or we
4933 * can't evict anything more, so we should wake
4934 * arc_get_data_impl() sooner.
4935 */
4936 arc_evict_waiter_t *aw;
4937 while ((aw = list_remove_head(&arc_evict_waiters)) != NULL) {
4938 cv_signal(&aw->aew_cv);
4939 }
4940 arc_set_need_free();
4941 }
4942 mutex_exit(&arc_evict_lock);
4943 spl_fstrans_unmark(cookie);
4944 }
4945
4946 static boolean_t
arc_reap_cb_check(void * arg,zthr_t * zthr)4947 arc_reap_cb_check(void *arg, zthr_t *zthr)
4948 {
4949 (void) arg, (void) zthr;
4950
4951 int64_t free_memory = arc_available_memory();
4952 static int reap_cb_check_counter = 0;
4953
4954 /*
4955 * If a kmem reap is already active, don't schedule more. We must
4956 * check for this because kmem_cache_reap_soon() won't actually
4957 * block on the cache being reaped (this is to prevent callers from
4958 * becoming implicitly blocked by a system-wide kmem reap -- which,
4959 * on a system with many, many full magazines, can take minutes).
4960 */
4961 if (!kmem_cache_reap_active() && free_memory < 0) {
4962
4963 arc_no_grow = B_TRUE;
4964 arc_warm = B_TRUE;
4965 /*
4966 * Wait at least zfs_grow_retry (default 5) seconds
4967 * before considering growing.
4968 */
4969 arc_growtime = gethrtime() + SEC2NSEC(arc_grow_retry);
4970 return (B_TRUE);
4971 } else if (free_memory < arc_c >> zfs_arc_no_grow_shift) {
4972 arc_no_grow = B_TRUE;
4973 } else if (gethrtime() >= arc_growtime) {
4974 arc_no_grow = B_FALSE;
4975 }
4976
4977 /*
4978 * Called unconditionally every 60 seconds to reclaim unused
4979 * zstd compression and decompression context. This is done
4980 * here to avoid the need for an independent thread.
4981 */
4982 if (!((reap_cb_check_counter++) % 60))
4983 zfs_zstd_cache_reap_now();
4984
4985 return (B_FALSE);
4986 }
4987
4988 /*
4989 * Keep enough free memory in the system by reaping the ARC's kmem
4990 * caches. To cause more slabs to be reapable, we may reduce the
4991 * target size of the cache (arc_c), causing the arc_evict_cb()
4992 * to free more buffers.
4993 */
4994 static void
arc_reap_cb(void * arg,zthr_t * zthr)4995 arc_reap_cb(void *arg, zthr_t *zthr)
4996 {
4997 int64_t can_free, free_memory, to_free;
4998
4999 (void) arg, (void) zthr;
5000 fstrans_cookie_t cookie = spl_fstrans_mark();
5001
5002 /*
5003 * Kick off asynchronous kmem_reap()'s of all our caches.
5004 */
5005 arc_kmem_reap_soon();
5006
5007 /*
5008 * Wait at least arc_kmem_cache_reap_retry_ms between
5009 * arc_kmem_reap_soon() calls. Without this check it is possible to
5010 * end up in a situation where we spend lots of time reaping
5011 * caches, while we're near arc_c_min. Waiting here also gives the
5012 * subsequent free memory check a chance of finding that the
5013 * asynchronous reap has already freed enough memory, and we don't
5014 * need to call arc_reduce_target_size().
5015 */
5016 delay((hz * arc_kmem_cache_reap_retry_ms + 999) / 1000);
5017
5018 /*
5019 * Reduce the target size as needed to maintain the amount of free
5020 * memory in the system at a fraction of the arc_size (1/128th by
5021 * default). If oversubscribed (free_memory < 0) then reduce the
5022 * target arc_size by the deficit amount plus the fractional
5023 * amount. If free memory is positive but less than the fractional
5024 * amount, reduce by what is needed to hit the fractional amount.
5025 */
5026 free_memory = arc_available_memory();
5027 can_free = arc_c - arc_c_min;
5028 to_free = (MAX(can_free, 0) >> arc_shrink_shift) - free_memory;
5029 if (to_free > 0)
5030 arc_reduce_target_size(to_free);
5031 spl_fstrans_unmark(cookie);
5032 }
5033
5034 #ifdef _KERNEL
5035 /*
5036 * Determine the amount of memory eligible for eviction contained in the
5037 * ARC. All clean data reported by the ghost lists can always be safely
5038 * evicted. Due to arc_c_min, the same does not hold for all clean data
5039 * contained by the regular mru and mfu lists.
5040 *
5041 * In the case of the regular mru and mfu lists, we need to report as
5042 * much clean data as possible, such that evicting that same reported
5043 * data will not bring arc_size below arc_c_min. Thus, in certain
5044 * circumstances, the total amount of clean data in the mru and mfu
5045 * lists might not actually be evictable.
5046 *
5047 * The following two distinct cases are accounted for:
5048 *
5049 * 1. The sum of the amount of dirty data contained by both the mru and
5050 * mfu lists, plus the ARC's other accounting (e.g. the anon list),
5051 * is greater than or equal to arc_c_min.
5052 * (i.e. amount of dirty data >= arc_c_min)
5053 *
5054 * This is the easy case; all clean data contained by the mru and mfu
5055 * lists is evictable. Evicting all clean data can only drop arc_size
5056 * to the amount of dirty data, which is greater than arc_c_min.
5057 *
5058 * 2. The sum of the amount of dirty data contained by both the mru and
5059 * mfu lists, plus the ARC's other accounting (e.g. the anon list),
5060 * is less than arc_c_min.
5061 * (i.e. arc_c_min > amount of dirty data)
5062 *
5063 * 2.1. arc_size is greater than or equal arc_c_min.
5064 * (i.e. arc_size >= arc_c_min > amount of dirty data)
5065 *
5066 * In this case, not all clean data from the regular mru and mfu
5067 * lists is actually evictable; we must leave enough clean data
5068 * to keep arc_size above arc_c_min. Thus, the maximum amount of
5069 * evictable data from the two lists combined, is exactly the
5070 * difference between arc_size and arc_c_min.
5071 *
5072 * 2.2. arc_size is less than arc_c_min
5073 * (i.e. arc_c_min > arc_size > amount of dirty data)
5074 *
5075 * In this case, none of the data contained in the mru and mfu
5076 * lists is evictable, even if it's clean. Since arc_size is
5077 * already below arc_c_min, evicting any more would only
5078 * increase this negative difference.
5079 */
5080
5081 #endif /* _KERNEL */
5082
5083 /*
5084 * Adapt arc info given the number of bytes we are trying to add and
5085 * the state that we are coming from. This function is only called
5086 * when we are adding new content to the cache.
5087 */
5088 static void
arc_adapt(uint64_t bytes)5089 arc_adapt(uint64_t bytes)
5090 {
5091 /*
5092 * Wake reap thread if we do not have any available memory
5093 */
5094 if (arc_reclaim_needed()) {
5095 zthr_wakeup(arc_reap_zthr);
5096 return;
5097 }
5098
5099 if (arc_no_grow)
5100 return;
5101
5102 if (arc_c >= arc_c_max)
5103 return;
5104
5105 /*
5106 * If we're within (2 * maxblocksize) bytes of the target
5107 * cache size, increment the target cache size
5108 */
5109 if (aggsum_upper_bound(&arc_sums.arcstat_size) +
5110 2 * SPA_MAXBLOCKSIZE >= arc_c) {
5111 uint64_t dc = MAX(bytes, SPA_OLD_MAXBLOCKSIZE);
5112 if (atomic_add_64_nv(&arc_c, dc) > arc_c_max)
5113 arc_c = arc_c_max;
5114 }
5115 }
5116
5117 /*
5118 * Check if ARC current size has grown past our upper thresholds.
5119 */
5120 static arc_ovf_level_t
arc_is_overflowing(boolean_t lax,boolean_t use_reserve)5121 arc_is_overflowing(boolean_t lax, boolean_t use_reserve)
5122 {
5123 /*
5124 * We just compare the lower bound here for performance reasons. Our
5125 * primary goals are to make sure that the arc never grows without
5126 * bound, and that it can reach its maximum size. This check
5127 * accomplishes both goals. The maximum amount we could run over by is
5128 * 2 * aggsum_borrow_multiplier * NUM_CPUS * the average size of a block
5129 * in the ARC. In practice, that's in the tens of MB, which is low
5130 * enough to be safe.
5131 */
5132 int64_t arc_over = aggsum_lower_bound(&arc_sums.arcstat_size) - arc_c -
5133 zfs_max_recordsize;
5134 int64_t dn_over = aggsum_lower_bound(&arc_sums.arcstat_dnode_size) -
5135 arc_dnode_limit;
5136
5137 /* Always allow at least one block of overflow. */
5138 if (arc_over < 0 && dn_over <= 0)
5139 return (ARC_OVF_NONE);
5140
5141 /* If we are under memory pressure, report severe overflow. */
5142 if (!lax)
5143 return (ARC_OVF_SEVERE);
5144
5145 /* We are not under pressure, so be more or less relaxed. */
5146 int64_t overflow = (arc_c >> zfs_arc_overflow_shift) / 2;
5147 if (use_reserve)
5148 overflow *= 3;
5149 return (arc_over < overflow ? ARC_OVF_SOME : ARC_OVF_SEVERE);
5150 }
5151
5152 static abd_t *
arc_get_data_abd(arc_buf_hdr_t * hdr,uint64_t size,const void * tag,int alloc_flags)5153 arc_get_data_abd(arc_buf_hdr_t *hdr, uint64_t size, const void *tag,
5154 int alloc_flags)
5155 {
5156 arc_buf_contents_t type = arc_buf_type(hdr);
5157
5158 arc_get_data_impl(hdr, size, tag, alloc_flags);
5159 if (alloc_flags & ARC_HDR_ALLOC_LINEAR)
5160 return (abd_alloc_linear(size, type == ARC_BUFC_METADATA));
5161 else
5162 return (abd_alloc(size, type == ARC_BUFC_METADATA));
5163 }
5164
5165 static void *
arc_get_data_buf(arc_buf_hdr_t * hdr,uint64_t size,const void * tag)5166 arc_get_data_buf(arc_buf_hdr_t *hdr, uint64_t size, const void *tag)
5167 {
5168 arc_buf_contents_t type = arc_buf_type(hdr);
5169
5170 arc_get_data_impl(hdr, size, tag, 0);
5171 if (type == ARC_BUFC_METADATA) {
5172 return (zio_buf_alloc(size));
5173 } else {
5174 ASSERT(type == ARC_BUFC_DATA);
5175 return (zio_data_buf_alloc(size));
5176 }
5177 }
5178
5179 /*
5180 * Wait for the specified amount of data (in bytes) to be evicted from the
5181 * ARC, and for there to be sufficient free memory in the system.
5182 * The lax argument specifies that caller does not have a specific reason
5183 * to wait, not aware of any memory pressure. Low memory handlers though
5184 * should set it to B_FALSE to wait for all required evictions to complete.
5185 * The use_reserve argument allows some callers to wait less than others
5186 * to not block critical code paths, possibly blocking other resources.
5187 */
5188 void
arc_wait_for_eviction(uint64_t amount,boolean_t lax,boolean_t use_reserve)5189 arc_wait_for_eviction(uint64_t amount, boolean_t lax, boolean_t use_reserve)
5190 {
5191 switch (arc_is_overflowing(lax, use_reserve)) {
5192 case ARC_OVF_NONE:
5193 return;
5194 case ARC_OVF_SOME:
5195 /*
5196 * This is a bit racy without taking arc_evict_lock, but the
5197 * worst that can happen is we either call zthr_wakeup() extra
5198 * time due to race with other thread here, or the set flag
5199 * get cleared by arc_evict_cb(), which is unlikely due to
5200 * big hysteresis, but also not important since at this level
5201 * of overflow the eviction is purely advisory. Same time
5202 * taking the global lock here every time without waiting for
5203 * the actual eviction creates a significant lock contention.
5204 */
5205 if (!arc_evict_needed) {
5206 arc_evict_needed = B_TRUE;
5207 zthr_wakeup(arc_evict_zthr);
5208 }
5209 return;
5210 case ARC_OVF_SEVERE:
5211 default:
5212 {
5213 arc_evict_waiter_t aw;
5214 list_link_init(&aw.aew_node);
5215 cv_init(&aw.aew_cv, NULL, CV_DEFAULT, NULL);
5216
5217 uint64_t last_count = 0;
5218 mutex_enter(&arc_evict_lock);
5219 arc_evict_waiter_t *last;
5220 if ((last = list_tail(&arc_evict_waiters)) != NULL) {
5221 last_count = last->aew_count;
5222 } else if (!arc_evict_needed) {
5223 arc_evict_needed = B_TRUE;
5224 zthr_wakeup(arc_evict_zthr);
5225 }
5226 /*
5227 * Note, the last waiter's count may be less than
5228 * arc_evict_count if we are low on memory in which
5229 * case arc_evict_state_impl() may have deferred
5230 * wakeups (but still incremented arc_evict_count).
5231 */
5232 aw.aew_count = MAX(last_count, arc_evict_count) + amount;
5233
5234 list_insert_tail(&arc_evict_waiters, &aw);
5235
5236 arc_set_need_free();
5237
5238 DTRACE_PROBE3(arc__wait__for__eviction,
5239 uint64_t, amount,
5240 uint64_t, arc_evict_count,
5241 uint64_t, aw.aew_count);
5242
5243 /*
5244 * We will be woken up either when arc_evict_count reaches
5245 * aew_count, or when the ARC is no longer overflowing and
5246 * eviction completes.
5247 * In case of "false" wakeup, we will still be on the list.
5248 */
5249 do {
5250 cv_wait(&aw.aew_cv, &arc_evict_lock);
5251 } while (list_link_active(&aw.aew_node));
5252 mutex_exit(&arc_evict_lock);
5253
5254 cv_destroy(&aw.aew_cv);
5255 }
5256 }
5257 }
5258
5259 /*
5260 * Allocate a block and return it to the caller. If we are hitting the
5261 * hard limit for the cache size, we must sleep, waiting for the eviction
5262 * thread to catch up. If we're past the target size but below the hard
5263 * limit, we'll only signal the reclaim thread and continue on.
5264 */
5265 static void
arc_get_data_impl(arc_buf_hdr_t * hdr,uint64_t size,const void * tag,int alloc_flags)5266 arc_get_data_impl(arc_buf_hdr_t *hdr, uint64_t size, const void *tag,
5267 int alloc_flags)
5268 {
5269 arc_adapt(size);
5270
5271 /*
5272 * If arc_size is currently overflowing, we must be adding data
5273 * faster than we are evicting. To ensure we don't compound the
5274 * problem by adding more data and forcing arc_size to grow even
5275 * further past it's target size, we wait for the eviction thread to
5276 * make some progress. We also wait for there to be sufficient free
5277 * memory in the system, as measured by arc_free_memory().
5278 *
5279 * Specifically, we wait for zfs_arc_eviction_pct percent of the
5280 * requested size to be evicted. This should be more than 100%, to
5281 * ensure that that progress is also made towards getting arc_size
5282 * under arc_c. See the comment above zfs_arc_eviction_pct.
5283 */
5284 arc_wait_for_eviction(size * zfs_arc_eviction_pct / 100,
5285 B_TRUE, alloc_flags & ARC_HDR_USE_RESERVE);
5286
5287 arc_buf_contents_t type = arc_buf_type(hdr);
5288 if (type == ARC_BUFC_METADATA) {
5289 arc_space_consume(size, ARC_SPACE_META);
5290 } else {
5291 arc_space_consume(size, ARC_SPACE_DATA);
5292 }
5293
5294 /*
5295 * Update the state size. Note that ghost states have a
5296 * "ghost size" and so don't need to be updated.
5297 */
5298 arc_state_t *state = hdr->b_l1hdr.b_state;
5299 if (!GHOST_STATE(state)) {
5300
5301 (void) zfs_refcount_add_many(&state->arcs_size[type], size,
5302 tag);
5303
5304 /*
5305 * If this is reached via arc_read, the link is
5306 * protected by the hash lock. If reached via
5307 * arc_buf_alloc, the header should not be accessed by
5308 * any other thread. And, if reached via arc_read_done,
5309 * the hash lock will protect it if it's found in the
5310 * hash table; otherwise no other thread should be
5311 * trying to [add|remove]_reference it.
5312 */
5313 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
5314 ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5315 (void) zfs_refcount_add_many(&state->arcs_esize[type],
5316 size, tag);
5317 }
5318 }
5319 }
5320
5321 static void
arc_free_data_abd(arc_buf_hdr_t * hdr,abd_t * abd,uint64_t size,const void * tag)5322 arc_free_data_abd(arc_buf_hdr_t *hdr, abd_t *abd, uint64_t size,
5323 const void *tag)
5324 {
5325 arc_free_data_impl(hdr, size, tag);
5326 abd_free(abd);
5327 }
5328
5329 static void
arc_free_data_buf(arc_buf_hdr_t * hdr,void * buf,uint64_t size,const void * tag)5330 arc_free_data_buf(arc_buf_hdr_t *hdr, void *buf, uint64_t size, const void *tag)
5331 {
5332 arc_buf_contents_t type = arc_buf_type(hdr);
5333
5334 arc_free_data_impl(hdr, size, tag);
5335 if (type == ARC_BUFC_METADATA) {
5336 zio_buf_free(buf, size);
5337 } else {
5338 ASSERT(type == ARC_BUFC_DATA);
5339 zio_data_buf_free(buf, size);
5340 }
5341 }
5342
5343 /*
5344 * Free the arc data buffer.
5345 */
5346 static void
arc_free_data_impl(arc_buf_hdr_t * hdr,uint64_t size,const void * tag)5347 arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, const void *tag)
5348 {
5349 arc_state_t *state = hdr->b_l1hdr.b_state;
5350 arc_buf_contents_t type = arc_buf_type(hdr);
5351
5352 /* protected by hash lock, if in the hash table */
5353 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
5354 ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5355 ASSERT(state != arc_anon && state != arc_l2c_only);
5356
5357 (void) zfs_refcount_remove_many(&state->arcs_esize[type],
5358 size, tag);
5359 }
5360 (void) zfs_refcount_remove_many(&state->arcs_size[type], size, tag);
5361
5362 VERIFY3U(hdr->b_type, ==, type);
5363 if (type == ARC_BUFC_METADATA) {
5364 arc_space_return(size, ARC_SPACE_META);
5365 } else {
5366 ASSERT(type == ARC_BUFC_DATA);
5367 arc_space_return(size, ARC_SPACE_DATA);
5368 }
5369 }
5370
5371 /*
5372 * This routine is called whenever a buffer is accessed.
5373 */
5374 static void
arc_access(arc_buf_hdr_t * hdr,arc_flags_t arc_flags,boolean_t hit)5375 arc_access(arc_buf_hdr_t *hdr, arc_flags_t arc_flags, boolean_t hit)
5376 {
5377 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
5378 ASSERT(HDR_HAS_L1HDR(hdr));
5379
5380 /*
5381 * Update buffer prefetch status.
5382 */
5383 boolean_t was_prefetch = HDR_PREFETCH(hdr);
5384 boolean_t now_prefetch = arc_flags & ARC_FLAG_PREFETCH;
5385 if (was_prefetch != now_prefetch) {
5386 if (was_prefetch) {
5387 ARCSTAT_CONDSTAT(hit, demand_hit, demand_iohit,
5388 HDR_PRESCIENT_PREFETCH(hdr), prescient, predictive,
5389 prefetch);
5390 }
5391 if (HDR_HAS_L2HDR(hdr))
5392 l2arc_hdr_arcstats_decrement_state(hdr);
5393 if (was_prefetch) {
5394 arc_hdr_clear_flags(hdr,
5395 ARC_FLAG_PREFETCH | ARC_FLAG_PRESCIENT_PREFETCH);
5396 } else {
5397 arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5398 }
5399 if (HDR_HAS_L2HDR(hdr))
5400 l2arc_hdr_arcstats_increment_state(hdr);
5401 }
5402 if (now_prefetch) {
5403 if (arc_flags & ARC_FLAG_PRESCIENT_PREFETCH) {
5404 arc_hdr_set_flags(hdr, ARC_FLAG_PRESCIENT_PREFETCH);
5405 ARCSTAT_BUMP(arcstat_prescient_prefetch);
5406 } else {
5407 ARCSTAT_BUMP(arcstat_predictive_prefetch);
5408 }
5409 }
5410 if (arc_flags & ARC_FLAG_L2CACHE)
5411 arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5412
5413 clock_t now = ddi_get_lbolt();
5414 if (hdr->b_l1hdr.b_state == arc_anon) {
5415 arc_state_t *new_state;
5416 /*
5417 * This buffer is not in the cache, and does not appear in
5418 * our "ghost" lists. Add it to the MRU or uncached state.
5419 */
5420 ASSERT0(hdr->b_l1hdr.b_arc_access);
5421 hdr->b_l1hdr.b_arc_access = now;
5422 if (HDR_UNCACHED(hdr)) {
5423 new_state = arc_uncached;
5424 DTRACE_PROBE1(new_state__uncached, arc_buf_hdr_t *,
5425 hdr);
5426 } else {
5427 new_state = arc_mru;
5428 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
5429 }
5430 arc_change_state(new_state, hdr);
5431 } else if (hdr->b_l1hdr.b_state == arc_mru) {
5432 /*
5433 * This buffer has been accessed once recently and either
5434 * its read is still in progress or it is in the cache.
5435 */
5436 if (HDR_IO_IN_PROGRESS(hdr)) {
5437 hdr->b_l1hdr.b_arc_access = now;
5438 return;
5439 }
5440 hdr->b_l1hdr.b_mru_hits++;
5441 ARCSTAT_BUMP(arcstat_mru_hits);
5442
5443 /*
5444 * If the previous access was a prefetch, then it already
5445 * handled possible promotion, so nothing more to do for now.
5446 */
5447 if (was_prefetch) {
5448 hdr->b_l1hdr.b_arc_access = now;
5449 return;
5450 }
5451
5452 /*
5453 * If more than ARC_MINTIME have passed from the previous
5454 * hit, promote the buffer to the MFU state.
5455 */
5456 if (ddi_time_after(now, hdr->b_l1hdr.b_arc_access +
5457 ARC_MINTIME)) {
5458 hdr->b_l1hdr.b_arc_access = now;
5459 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5460 arc_change_state(arc_mfu, hdr);
5461 }
5462 } else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
5463 arc_state_t *new_state;
5464 /*
5465 * This buffer has been accessed once recently, but was
5466 * evicted from the cache. Would we have bigger MRU, it
5467 * would be an MRU hit, so handle it the same way, except
5468 * we don't need to check the previous access time.
5469 */
5470 hdr->b_l1hdr.b_mru_ghost_hits++;
5471 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
5472 hdr->b_l1hdr.b_arc_access = now;
5473 wmsum_add(&arc_mru_ghost->arcs_hits[arc_buf_type(hdr)],
5474 arc_hdr_size(hdr));
5475 if (was_prefetch) {
5476 new_state = arc_mru;
5477 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
5478 } else {
5479 new_state = arc_mfu;
5480 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5481 }
5482 arc_change_state(new_state, hdr);
5483 } else if (hdr->b_l1hdr.b_state == arc_mfu) {
5484 /*
5485 * This buffer has been accessed more than once and either
5486 * still in the cache or being restored from one of ghosts.
5487 */
5488 if (!HDR_IO_IN_PROGRESS(hdr)) {
5489 hdr->b_l1hdr.b_mfu_hits++;
5490 ARCSTAT_BUMP(arcstat_mfu_hits);
5491 }
5492 hdr->b_l1hdr.b_arc_access = now;
5493 } else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
5494 /*
5495 * This buffer has been accessed more than once recently, but
5496 * has been evicted from the cache. Would we have bigger MFU
5497 * it would stay in cache, so move it back to MFU state.
5498 */
5499 hdr->b_l1hdr.b_mfu_ghost_hits++;
5500 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
5501 hdr->b_l1hdr.b_arc_access = now;
5502 wmsum_add(&arc_mfu_ghost->arcs_hits[arc_buf_type(hdr)],
5503 arc_hdr_size(hdr));
5504 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5505 arc_change_state(arc_mfu, hdr);
5506 } else if (hdr->b_l1hdr.b_state == arc_uncached) {
5507 /*
5508 * This buffer is uncacheable, but we got a hit. Probably
5509 * a demand read after prefetch. Nothing more to do here.
5510 */
5511 if (!HDR_IO_IN_PROGRESS(hdr))
5512 ARCSTAT_BUMP(arcstat_uncached_hits);
5513 hdr->b_l1hdr.b_arc_access = now;
5514 } else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
5515 /*
5516 * This buffer is on the 2nd Level ARC and was not accessed
5517 * for a long time, so treat it as new and put into MRU.
5518 */
5519 hdr->b_l1hdr.b_arc_access = now;
5520 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
5521 arc_change_state(arc_mru, hdr);
5522 } else {
5523 cmn_err(CE_PANIC, "invalid arc state 0x%p",
5524 hdr->b_l1hdr.b_state);
5525 }
5526 }
5527
5528 /*
5529 * This routine is called by dbuf_hold() to update the arc_access() state
5530 * which otherwise would be skipped for entries in the dbuf cache.
5531 */
5532 void
arc_buf_access(arc_buf_t * buf)5533 arc_buf_access(arc_buf_t *buf)
5534 {
5535 arc_buf_hdr_t *hdr = buf->b_hdr;
5536
5537 /*
5538 * Avoid taking the hash_lock when possible as an optimization.
5539 * The header must be checked again under the hash_lock in order
5540 * to handle the case where it is concurrently being released.
5541 */
5542 if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr))
5543 return;
5544
5545 kmutex_t *hash_lock = HDR_LOCK(hdr);
5546 mutex_enter(hash_lock);
5547
5548 if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr)) {
5549 mutex_exit(hash_lock);
5550 ARCSTAT_BUMP(arcstat_access_skip);
5551 return;
5552 }
5553
5554 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
5555 hdr->b_l1hdr.b_state == arc_mfu ||
5556 hdr->b_l1hdr.b_state == arc_uncached);
5557
5558 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
5559 arc_access(hdr, 0, B_TRUE);
5560 mutex_exit(hash_lock);
5561
5562 ARCSTAT_BUMP(arcstat_hits);
5563 ARCSTAT_CONDSTAT(B_TRUE /* demand */, demand, prefetch,
5564 !HDR_ISTYPE_METADATA(hdr), data, metadata, hits);
5565 }
5566
5567 /* a generic arc_read_done_func_t */
5568 void
arc_getbuf_func(zio_t * zio,const zbookmark_phys_t * zb,const blkptr_t * bp,arc_buf_t * buf,void * arg)5569 arc_getbuf_func(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
5570 arc_buf_t *buf, void *arg)
5571 {
5572 (void) zb, (void) bp;
5573 arc_buf_t **bufp = arg;
5574
5575 if (buf == NULL) {
5576 ASSERT(zio == NULL || zio->io_error != 0);
5577 *bufp = NULL;
5578 } else {
5579 ASSERT(zio == NULL || zio->io_error == 0);
5580 *bufp = buf;
5581 ASSERT(buf->b_data != NULL);
5582 }
5583 }
5584
5585 static void
arc_hdr_verify(arc_buf_hdr_t * hdr,blkptr_t * bp)5586 arc_hdr_verify(arc_buf_hdr_t *hdr, blkptr_t *bp)
5587 {
5588 if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
5589 ASSERT0(HDR_GET_PSIZE(hdr));
5590 ASSERT3U(arc_hdr_get_compress(hdr), ==, ZIO_COMPRESS_OFF);
5591 } else {
5592 if (HDR_COMPRESSION_ENABLED(hdr)) {
5593 ASSERT3U(arc_hdr_get_compress(hdr), ==,
5594 BP_GET_COMPRESS(bp));
5595 }
5596 ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
5597 ASSERT3U(HDR_GET_PSIZE(hdr), ==, BP_GET_PSIZE(bp));
5598 ASSERT3U(!!HDR_PROTECTED(hdr), ==, BP_IS_PROTECTED(bp));
5599 }
5600 }
5601
5602 static void
arc_read_done(zio_t * zio)5603 arc_read_done(zio_t *zio)
5604 {
5605 blkptr_t *bp = zio->io_bp;
5606 arc_buf_hdr_t *hdr = zio->io_private;
5607 kmutex_t *hash_lock = NULL;
5608 arc_callback_t *callback_list;
5609 arc_callback_t *acb;
5610 boolean_t read_error = (zio->io_error != 0);
5611
5612 /*
5613 * The hdr was inserted into hash-table and removed from lists
5614 * prior to starting I/O. The reference taken for the I/O
5615 * keeps it from being evicted, freed or re-keyed, so its identity
5616 * is stable here and the hash lock can be derived from it directly.
5617 * Embedded bps have no DVA, are never hashed and need no lock.
5618 */
5619 if (!BP_IS_EMBEDDED(bp)) {
5620 hash_lock = HDR_LOCK(hdr);
5621 mutex_enter(hash_lock);
5622
5623 ASSERT(HDR_IN_HASH_TABLE(hdr));
5624 ASSERT(hdr->b_l1hdr.b_state != arc_anon);
5625
5626 ASSERT3U(hdr->b_birth, ==, BP_GET_PHYSICAL_BIRTH(zio->io_bp));
5627 ASSERT3U(hdr->b_dva.dva_word[0], ==,
5628 BP_IDENTITY(zio->io_bp)->dva_word[0]);
5629 ASSERT3U(hdr->b_dva.dva_word[1], ==,
5630 BP_IDENTITY(zio->io_bp)->dva_word[1]);
5631 }
5632
5633 if (BP_IS_PROTECTED(bp)) {
5634 hdr->b_crypt_hdr.b_ot = BP_GET_TYPE(bp);
5635 hdr->b_crypt_hdr.b_dsobj = zio->io_bookmark.zb_objset;
5636 zio_crypt_decode_params_bp(bp, hdr->b_crypt_hdr.b_salt,
5637 hdr->b_crypt_hdr.b_iv);
5638
5639 if (zio->io_error == 0) {
5640 if (BP_GET_TYPE(bp) == DMU_OT_INTENT_LOG) {
5641 void *tmpbuf;
5642
5643 tmpbuf = abd_borrow_buf_copy(zio->io_abd,
5644 sizeof (zil_chain_t));
5645 zio_crypt_decode_mac_zil(tmpbuf,
5646 hdr->b_crypt_hdr.b_mac);
5647 abd_return_buf(zio->io_abd, tmpbuf,
5648 sizeof (zil_chain_t));
5649 } else {
5650 zio_crypt_decode_mac_bp(bp,
5651 hdr->b_crypt_hdr.b_mac);
5652 }
5653 }
5654 }
5655
5656 if (zio->io_error == 0) {
5657 /* byteswap if necessary */
5658 if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
5659 if (BP_GET_LEVEL(zio->io_bp) > 0) {
5660 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
5661 } else {
5662 hdr->b_l1hdr.b_byteswap =
5663 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
5664 }
5665 } else {
5666 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
5667 }
5668 if (!HDR_L2_READING(hdr)) {
5669 hdr->b_complevel = zio->io_prop.zp_complevel;
5670 }
5671 }
5672
5673 arc_hdr_clear_flags(hdr, ARC_FLAG_L2_EVICTED);
5674 if (l2arc_noprefetch && HDR_PREFETCH(hdr))
5675 arc_hdr_clear_flags(hdr, ARC_FLAG_L2CACHE);
5676
5677 callback_list = hdr->b_l1hdr.b_acb;
5678 ASSERT3P(callback_list, !=, NULL);
5679 hdr->b_l1hdr.b_acb = NULL;
5680
5681 /*
5682 * If a read request has a callback (i.e. acb_done is not NULL), then we
5683 * make a buf containing the data according to the parameters which were
5684 * passed in. The implementation of arc_buf_alloc_impl() ensures that we
5685 * aren't needlessly decompressing the data multiple times.
5686 */
5687 int callback_cnt = 0;
5688 for (acb = callback_list; acb != NULL; acb = acb->acb_next) {
5689
5690 /* We need the last one to call below in original order. */
5691 callback_list = acb;
5692
5693 if (!acb->acb_done || acb->acb_nobuf)
5694 continue;
5695
5696 callback_cnt++;
5697
5698 if (zio->io_error != 0)
5699 continue;
5700
5701 int error = arc_buf_alloc_impl(hdr, zio->io_spa,
5702 &acb->acb_zb, acb->acb_private, acb->acb_encrypted,
5703 acb->acb_compressed, acb->acb_noauth, B_TRUE,
5704 &acb->acb_buf);
5705
5706 /*
5707 * Assert non-speculative zios didn't fail because an
5708 * encryption key wasn't loaded
5709 */
5710 ASSERT((zio->io_flags & ZIO_FLAG_SPECULATIVE) ||
5711 error != EACCES);
5712
5713 /*
5714 * If we failed to decrypt, report an error now (as the zio
5715 * layer would have done if it had done the transforms).
5716 */
5717 if (error == ECKSUM) {
5718 ASSERT(BP_IS_PROTECTED(bp));
5719 error = SET_ERROR(EIO);
5720 if ((zio->io_flags & ZIO_FLAG_SPECULATIVE) == 0) {
5721 spa_log_error(zio->io_spa, &acb->acb_zb,
5722 BP_GET_PHYSICAL_BIRTH(zio->io_bp));
5723 (void) zfs_ereport_post(
5724 FM_EREPORT_ZFS_AUTHENTICATION,
5725 zio->io_spa, NULL, &acb->acb_zb, zio, 0);
5726 }
5727 }
5728
5729 if (error != 0) {
5730 /*
5731 * Decompression or decryption failed. Set
5732 * io_error so that when we call acb_done
5733 * (below), we will indicate that the read
5734 * failed. Note that in the unusual case
5735 * where one callback is compressed and another
5736 * uncompressed, we will mark all of them
5737 * as failed, even though the uncompressed
5738 * one can't actually fail. In this case,
5739 * the hdr will not be anonymous, because
5740 * if there are multiple callbacks, it's
5741 * because multiple threads found the same
5742 * arc buf in the hash table.
5743 */
5744 zio->io_error = error;
5745 }
5746 }
5747
5748 /*
5749 * If there are multiple callbacks, we must have the hash lock,
5750 * because the only way for multiple threads to find this hdr is
5751 * in the hash table. This ensures that if there are multiple
5752 * callbacks, the hdr is not anonymous. If it were anonymous,
5753 * we couldn't use arc_buf_destroy() in the error case below.
5754 */
5755 ASSERT(callback_cnt < 2 || hash_lock != NULL);
5756
5757 if (zio->io_error == 0) {
5758 arc_hdr_verify(hdr, zio->io_bp);
5759 } else {
5760 /*
5761 * A failed *physical* read leaves the raw/encrypted buffer it
5762 * was filling full of garbage. If a valid decrypted b_pabd
5763 * survives (the raw re-read case) the header stays cached, and
5764 * a later raw read would be served this garbage as a hit —
5765 * arc_read()'s hit test honors HDR_HAS_RABD, not IO_ERROR, and
5766 * arc_cksum_verify() skips IO_ERROR headers. We should free it
5767 * so that representation misses and re-fetches from disk.
5768 *
5769 * Gate on read_error: a *valid* b_rabd whose consumer merely
5770 * failed to decrypt it (keys not loaded) also reaches here,
5771 * but the read succeeded and the data should be kept.
5772 */
5773 if (read_error) {
5774 if (HDR_HAS_RABD(hdr))
5775 arc_hdr_free_abd(hdr, B_TRUE);
5776 else if (hdr->b_l1hdr.b_pabd != NULL)
5777 arc_hdr_free_abd(hdr, B_FALSE);
5778 }
5779 /* Flag for teardown only if nothing valid remains. */
5780 if (hdr->b_l1hdr.b_pabd == NULL && !HDR_HAS_RABD(hdr) &&
5781 hdr->b_l1hdr.b_buf == NULL)
5782 arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
5783 }
5784
5785 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5786 (void) remove_reference(hdr, hdr);
5787
5788 if (hash_lock != NULL)
5789 mutex_exit(hash_lock);
5790
5791 /* execute each callback and free its structure */
5792 while ((acb = callback_list) != NULL) {
5793 if (acb->acb_done != NULL) {
5794 if (zio->io_error != 0 && acb->acb_buf != NULL) {
5795 /*
5796 * If arc_buf_alloc_impl() fails during
5797 * decompression, the buf will still be
5798 * allocated, and needs to be freed here.
5799 */
5800 arc_buf_destroy(acb->acb_buf,
5801 acb->acb_private);
5802 acb->acb_buf = NULL;
5803 }
5804 acb->acb_done(zio, &zio->io_bookmark, zio->io_bp,
5805 acb->acb_buf, acb->acb_private);
5806 }
5807
5808 if (acb->acb_zio_dummy != NULL) {
5809 acb->acb_zio_dummy->io_error = zio->io_error;
5810 zio_nowait(acb->acb_zio_dummy);
5811 }
5812
5813 callback_list = acb->acb_prev;
5814 if (acb->acb_wait) {
5815 mutex_enter(&acb->acb_wait_lock);
5816 acb->acb_wait_error = zio->io_error;
5817 acb->acb_wait = B_FALSE;
5818 cv_signal(&acb->acb_wait_cv);
5819 mutex_exit(&acb->acb_wait_lock);
5820 /* acb will be freed by the waiting thread. */
5821 } else {
5822 kmem_free(acb, sizeof (arc_callback_t));
5823 }
5824 }
5825 }
5826
5827 /*
5828 * Lookup the block at the specified DVA (in bp), and return the manner in
5829 * which the block is cached. A zero return indicates not cached.
5830 */
5831 int
arc_cached(spa_t * spa,const blkptr_t * bp)5832 arc_cached(spa_t *spa, const blkptr_t *bp)
5833 {
5834 arc_buf_hdr_t *hdr = NULL;
5835 kmutex_t *hash_lock = NULL;
5836 uint64_t guid = spa_load_guid(spa);
5837 int flags = 0;
5838
5839 if (BP_IS_EMBEDDED(bp))
5840 return (ARC_CACHED_EMBEDDED);
5841
5842 hdr = buf_hash_find(guid, bp, &hash_lock);
5843 if (hdr == NULL)
5844 return (0);
5845
5846 if (HDR_HAS_L1HDR(hdr)) {
5847 arc_state_t *state = hdr->b_l1hdr.b_state;
5848 /*
5849 * We switch to ensure that any future arc_state_type_t
5850 * changes are handled. This is just a shift to promote
5851 * more compile-time checking.
5852 */
5853 switch (state->arcs_state) {
5854 case ARC_STATE_ANON:
5855 break;
5856 case ARC_STATE_MRU:
5857 flags |= ARC_CACHED_IN_MRU | ARC_CACHED_IN_L1;
5858 break;
5859 case ARC_STATE_MFU:
5860 flags |= ARC_CACHED_IN_MFU | ARC_CACHED_IN_L1;
5861 break;
5862 case ARC_STATE_UNCACHED:
5863 /* The header is still in L1, probably not for long */
5864 flags |= ARC_CACHED_IN_L1;
5865 break;
5866 default:
5867 break;
5868 }
5869 }
5870 if (HDR_HAS_L2HDR(hdr))
5871 flags |= ARC_CACHED_IN_L2;
5872
5873 mutex_exit(hash_lock);
5874
5875 return (flags);
5876 }
5877
5878 /*
5879 * "Read" the block at the specified DVA (in bp) via the
5880 * cache. If the block is found in the cache, invoke the provided
5881 * callback immediately and return. Note that the `zio' parameter
5882 * in the callback will be NULL in this case, since no IO was
5883 * required. If the block is not in the cache pass the read request
5884 * on to the spa with a substitute callback function, so that the
5885 * requested block will be added to the cache.
5886 *
5887 * If a read request arrives for a block that has a read in-progress,
5888 * either wait for the in-progress read to complete (and return the
5889 * results); or, if this is a read with a "done" func, add a record
5890 * to the read to invoke the "done" func when the read completes,
5891 * and return; or just return.
5892 *
5893 * arc_read_done() will invoke all the requested "done" functions
5894 * for readers of this block.
5895 */
5896 int
arc_read(zio_t * pio,spa_t * spa,const blkptr_t * bp,arc_read_done_func_t * done,void * private,zio_priority_t priority,int zio_flags,arc_flags_t * arc_flags,const zbookmark_phys_t * zb)5897 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp,
5898 arc_read_done_func_t *done, void *private, zio_priority_t priority,
5899 int zio_flags, arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
5900 {
5901 arc_buf_hdr_t *hdr = NULL;
5902 kmutex_t *hash_lock = NULL;
5903 zio_t *rzio;
5904 uint64_t guid = spa_load_guid(spa);
5905 boolean_t compressed_read = (zio_flags & ZIO_FLAG_RAW_COMPRESS) != 0;
5906 boolean_t encrypted_read = BP_IS_ENCRYPTED(bp) &&
5907 (zio_flags & ZIO_FLAG_RAW_ENCRYPT) != 0;
5908 boolean_t noauth_read = BP_IS_AUTHENTICATED(bp) &&
5909 (zio_flags & ZIO_FLAG_RAW_ENCRYPT) != 0;
5910 boolean_t embedded_bp = !!BP_IS_EMBEDDED(bp);
5911 boolean_t no_buf = *arc_flags & ARC_FLAG_NO_BUF;
5912 arc_buf_t *buf = NULL;
5913 int rc = 0;
5914 boolean_t bp_validation = B_FALSE;
5915
5916 ASSERT(!embedded_bp ||
5917 BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
5918 ASSERT(!BP_IS_HOLE(bp));
5919 ASSERT(!BP_IS_REDACTED(bp));
5920
5921 /*
5922 * Normally SPL_FSTRANS will already be set since kernel threads which
5923 * expect to call the DMU interfaces will set it when created. System
5924 * calls are similarly handled by setting/cleaning the bit in the
5925 * registered callback (module/os/.../zfs/zpl_*).
5926 *
5927 * External consumers such as Lustre which call the exported DMU
5928 * interfaces may not have set SPL_FSTRANS. To avoid a deadlock
5929 * on the hash_lock always set and clear the bit.
5930 */
5931 fstrans_cookie_t cookie = spl_fstrans_mark();
5932 top:
5933 if (!embedded_bp) {
5934 /*
5935 * Embedded BP's have no DVA and require no I/O to "read".
5936 * Create an anonymous arc buf to back it.
5937 */
5938 hdr = buf_hash_find(guid, bp, &hash_lock);
5939 }
5940
5941 /*
5942 * Determine if we have an L1 cache hit or a cache miss. For simplicity
5943 * we maintain encrypted data separately from compressed / uncompressed
5944 * data. If the user is requesting raw encrypted data and we don't have
5945 * that in the header we will read from disk to guarantee that we can
5946 * get it even if the encryption keys aren't loaded.
5947 */
5948 if (hdr != NULL && HDR_HAS_L1HDR(hdr) && (HDR_HAS_RABD(hdr) ||
5949 (hdr->b_l1hdr.b_pabd != NULL && !encrypted_read))) {
5950 boolean_t is_data = !HDR_ISTYPE_METADATA(hdr);
5951
5952 /*
5953 * Verify the block pointer contents are reasonable. This
5954 * should always be the case since the blkptr is protected by
5955 * a checksum.
5956 */
5957 if (zfs_blkptr_verify(spa, bp, BLK_CONFIG_SKIP,
5958 BLK_VERIFY_LOG)) {
5959 mutex_exit(hash_lock);
5960 rc = SET_ERROR(ECKSUM);
5961 goto done;
5962 }
5963
5964 if (HDR_IO_IN_PROGRESS(hdr)) {
5965 if (*arc_flags & ARC_FLAG_CACHED_ONLY) {
5966 mutex_exit(hash_lock);
5967 ARCSTAT_BUMP(arcstat_cached_only_in_progress);
5968 rc = SET_ERROR(ENOENT);
5969 goto done;
5970 }
5971
5972 zio_t *head_zio = hdr->b_l1hdr.b_acb->acb_zio_head;
5973 ASSERT3P(head_zio, !=, NULL);
5974 if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
5975 priority == ZIO_PRIORITY_SYNC_READ) {
5976 /*
5977 * This is a sync read that needs to wait for
5978 * an in-flight async read. Request that the
5979 * zio have its priority upgraded.
5980 */
5981 zio_change_priority(head_zio, priority);
5982 DTRACE_PROBE1(arc__async__upgrade__sync,
5983 arc_buf_hdr_t *, hdr);
5984 ARCSTAT_BUMP(arcstat_async_upgrade_sync);
5985 }
5986
5987 DTRACE_PROBE1(arc__iohit, arc_buf_hdr_t *, hdr);
5988 arc_access(hdr, *arc_flags, B_FALSE);
5989
5990 /*
5991 * If there are multiple threads reading the same block
5992 * and that block is not yet in the ARC, then only one
5993 * thread will do the physical I/O and all other
5994 * threads will wait until that I/O completes.
5995 * Synchronous reads use the acb_wait_cv whereas nowait
5996 * reads register a callback. Both are signalled/called
5997 * in arc_read_done.
5998 *
5999 * Errors of the physical I/O may need to be propagated.
6000 * Synchronous read errors are returned here from
6001 * arc_read_done via acb_wait_error. Nowait reads
6002 * attach the acb_zio_dummy zio to pio and
6003 * arc_read_done propagates the physical I/O's io_error
6004 * to acb_zio_dummy, and thereby to pio.
6005 */
6006 arc_callback_t *acb = NULL;
6007 if (done || pio || *arc_flags & ARC_FLAG_WAIT) {
6008 acb = kmem_zalloc(sizeof (arc_callback_t),
6009 KM_SLEEP);
6010 acb->acb_done = done;
6011 acb->acb_private = private;
6012 acb->acb_compressed = compressed_read;
6013 acb->acb_encrypted = encrypted_read;
6014 acb->acb_noauth = noauth_read;
6015 acb->acb_nobuf = no_buf;
6016 if (*arc_flags & ARC_FLAG_WAIT) {
6017 acb->acb_wait = B_TRUE;
6018 mutex_init(&acb->acb_wait_lock, NULL,
6019 MUTEX_DEFAULT, NULL);
6020 cv_init(&acb->acb_wait_cv, NULL,
6021 CV_DEFAULT, NULL);
6022 }
6023 acb->acb_zb = *zb;
6024 if (pio != NULL) {
6025 acb->acb_zio_dummy = zio_null(pio,
6026 spa, NULL, NULL, NULL, zio_flags);
6027 }
6028 acb->acb_zio_head = head_zio;
6029 acb->acb_next = hdr->b_l1hdr.b_acb;
6030 hdr->b_l1hdr.b_acb->acb_prev = acb;
6031 hdr->b_l1hdr.b_acb = acb;
6032 }
6033 mutex_exit(hash_lock);
6034
6035 ARCSTAT_BUMP(arcstat_iohits);
6036 ARCSTAT_CONDSTAT(!(*arc_flags & ARC_FLAG_PREFETCH),
6037 demand, prefetch, is_data, data, metadata, iohits);
6038
6039 if (*arc_flags & ARC_FLAG_WAIT) {
6040 mutex_enter(&acb->acb_wait_lock);
6041 while (acb->acb_wait) {
6042 cv_wait(&acb->acb_wait_cv,
6043 &acb->acb_wait_lock);
6044 }
6045 rc = acb->acb_wait_error;
6046 mutex_exit(&acb->acb_wait_lock);
6047 mutex_destroy(&acb->acb_wait_lock);
6048 cv_destroy(&acb->acb_wait_cv);
6049 kmem_free(acb, sizeof (arc_callback_t));
6050 }
6051 goto out;
6052 }
6053
6054 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
6055 hdr->b_l1hdr.b_state == arc_mfu ||
6056 hdr->b_l1hdr.b_state == arc_uncached);
6057
6058 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
6059 arc_access(hdr, *arc_flags, B_TRUE);
6060
6061 if (done && !no_buf) {
6062 ASSERT(!embedded_bp || !BP_IS_HOLE(bp));
6063
6064 /* Get a buf with the desired data in it. */
6065 rc = arc_buf_alloc_impl(hdr, spa, zb, private,
6066 encrypted_read, compressed_read, noauth_read,
6067 B_TRUE, &buf);
6068 if (rc == ECKSUM) {
6069 /*
6070 * Convert authentication and decryption errors
6071 * to EIO (and generate an ereport if needed)
6072 * before leaving the ARC.
6073 */
6074 rc = SET_ERROR(EIO);
6075 if ((zio_flags & ZIO_FLAG_SPECULATIVE) == 0) {
6076 spa_log_error(spa, zb, hdr->b_birth);
6077 (void) zfs_ereport_post(
6078 FM_EREPORT_ZFS_AUTHENTICATION,
6079 spa, NULL, zb, NULL, 0);
6080 }
6081 }
6082 if (rc != 0) {
6083 arc_buf_destroy_impl(buf);
6084 buf = NULL;
6085 (void) remove_reference(hdr, private);
6086 }
6087
6088 /* assert any errors weren't due to unloaded keys */
6089 ASSERT((zio_flags & ZIO_FLAG_SPECULATIVE) ||
6090 rc != EACCES);
6091 }
6092 mutex_exit(hash_lock);
6093 ARCSTAT_BUMP(arcstat_hits);
6094 ARCSTAT_CONDSTAT(!(*arc_flags & ARC_FLAG_PREFETCH),
6095 demand, prefetch, is_data, data, metadata, hits);
6096 *arc_flags |= ARC_FLAG_CACHED;
6097 goto done;
6098 } else {
6099 uint64_t lsize = BP_GET_LSIZE(bp);
6100 uint64_t psize = BP_GET_PSIZE(bp);
6101 arc_callback_t *acb;
6102 vdev_t *vd = NULL;
6103 uint64_t addr = 0;
6104 boolean_t devw = B_FALSE;
6105 uint64_t size;
6106 abd_t *hdr_abd;
6107 int alloc_flags = encrypted_read ? ARC_HDR_ALLOC_RDATA : 0;
6108 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
6109 int config_lock;
6110 int error;
6111
6112 if (*arc_flags & ARC_FLAG_CACHED_ONLY) {
6113 if (hash_lock != NULL)
6114 mutex_exit(hash_lock);
6115 rc = SET_ERROR(ENOENT);
6116 goto done;
6117 }
6118
6119 if (zio_flags & ZIO_FLAG_CONFIG_WRITER) {
6120 config_lock = BLK_CONFIG_HELD;
6121 } else if (hash_lock != NULL) {
6122 /*
6123 * Prevent lock order reversal
6124 */
6125 config_lock = BLK_CONFIG_NEEDED_TRY;
6126 } else {
6127 config_lock = BLK_CONFIG_NEEDED;
6128 }
6129
6130 /*
6131 * Verify the block pointer contents are reasonable. This
6132 * should always be the case since the blkptr is protected by
6133 * a checksum.
6134 */
6135 if (!bp_validation && (error = zfs_blkptr_verify(spa, bp,
6136 config_lock, BLK_VERIFY_LOG))) {
6137 if (hash_lock != NULL)
6138 mutex_exit(hash_lock);
6139 if (error == EBUSY && !zfs_blkptr_verify(spa, bp,
6140 BLK_CONFIG_NEEDED, BLK_VERIFY_LOG)) {
6141 bp_validation = B_TRUE;
6142 goto top;
6143 }
6144 rc = SET_ERROR(ECKSUM);
6145 goto done;
6146 }
6147
6148 if (hdr == NULL) {
6149 /*
6150 * This block is not in the cache or it has
6151 * embedded data.
6152 */
6153 arc_buf_hdr_t *exists = NULL;
6154 hdr = arc_hdr_alloc(guid, psize, lsize,
6155 BP_IS_PROTECTED(bp), BP_GET_COMPRESS(bp), 0, type);
6156
6157 if (!embedded_bp) {
6158 hdr->b_dva = *BP_IDENTITY(bp);
6159 hdr->b_birth = BP_GET_PHYSICAL_BIRTH(bp);
6160 exists = buf_hash_insert(hdr, &hash_lock);
6161 }
6162 if (exists != NULL) {
6163 /* somebody beat us to the hash insert */
6164 mutex_exit(hash_lock);
6165 buf_discard_identity(hdr);
6166 arc_hdr_destroy(hdr);
6167 goto top; /* restart the IO request */
6168 }
6169 } else {
6170 /*
6171 * This block is in the ghost cache or encrypted data
6172 * was requested and we didn't have it. If it was
6173 * L2-only (and thus didn't have an L1 hdr),
6174 * we realloc the header to add an L1 hdr.
6175 */
6176 if (!HDR_HAS_L1HDR(hdr)) {
6177 hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
6178 hdr_full_cache);
6179 }
6180
6181 if (GHOST_STATE(hdr->b_l1hdr.b_state)) {
6182 ASSERT0P(hdr->b_l1hdr.b_pabd);
6183 ASSERT(!HDR_HAS_RABD(hdr));
6184 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6185 ASSERT0(zfs_refcount_count(
6186 &hdr->b_l1hdr.b_refcnt));
6187 ASSERT0P(hdr->b_l1hdr.b_buf);
6188 #ifdef ZFS_DEBUG
6189 ASSERT0P(hdr->b_l1hdr.b_freeze_cksum);
6190 #endif
6191 } else if (HDR_IO_IN_PROGRESS(hdr)) {
6192 /*
6193 * If this header already had an IO in progress
6194 * and we are performing another IO to fetch
6195 * encrypted data we must wait until the first
6196 * IO completes so as not to confuse
6197 * arc_read_done(). This should be very rare
6198 * and so the performance impact shouldn't
6199 * matter.
6200 */
6201 arc_callback_t *acb = kmem_zalloc(
6202 sizeof (arc_callback_t), KM_SLEEP);
6203 acb->acb_wait = B_TRUE;
6204 mutex_init(&acb->acb_wait_lock, NULL,
6205 MUTEX_DEFAULT, NULL);
6206 cv_init(&acb->acb_wait_cv, NULL, CV_DEFAULT,
6207 NULL);
6208 acb->acb_zio_head =
6209 hdr->b_l1hdr.b_acb->acb_zio_head;
6210 acb->acb_next = hdr->b_l1hdr.b_acb;
6211 hdr->b_l1hdr.b_acb->acb_prev = acb;
6212 hdr->b_l1hdr.b_acb = acb;
6213 mutex_exit(hash_lock);
6214 mutex_enter(&acb->acb_wait_lock);
6215 while (acb->acb_wait) {
6216 cv_wait(&acb->acb_wait_cv,
6217 &acb->acb_wait_lock);
6218 }
6219 mutex_exit(&acb->acb_wait_lock);
6220 mutex_destroy(&acb->acb_wait_lock);
6221 cv_destroy(&acb->acb_wait_cv);
6222 kmem_free(acb, sizeof (arc_callback_t));
6223 goto top;
6224 }
6225 }
6226 if (*arc_flags & ARC_FLAG_UNCACHED) {
6227 arc_hdr_set_flags(hdr, ARC_FLAG_UNCACHED);
6228 if (!encrypted_read)
6229 alloc_flags |= ARC_HDR_ALLOC_LINEAR;
6230 }
6231
6232 /*
6233 * Take additional reference for IO_IN_PROGRESS. It stops
6234 * arc_access() from putting this header without any buffers
6235 * and so other references but obviously nonevictable onto
6236 * the evictable list of MRU or MFU state.
6237 */
6238 add_reference(hdr, hdr);
6239 if (!embedded_bp)
6240 arc_access(hdr, *arc_flags, B_FALSE);
6241 arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6242 arc_hdr_alloc_abd(hdr, alloc_flags);
6243 if (encrypted_read) {
6244 ASSERT(HDR_HAS_RABD(hdr));
6245 size = HDR_GET_PSIZE(hdr);
6246 hdr_abd = hdr->b_crypt_hdr.b_rabd;
6247 zio_flags |= ZIO_FLAG_RAW;
6248 } else {
6249 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
6250 size = arc_hdr_size(hdr);
6251 hdr_abd = hdr->b_l1hdr.b_pabd;
6252
6253 if (arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF) {
6254 zio_flags |= ZIO_FLAG_RAW_COMPRESS;
6255 }
6256
6257 /*
6258 * For authenticated bp's, we do not ask the ZIO layer
6259 * to authenticate them since this will cause the entire
6260 * IO to fail if the key isn't loaded. Instead, we
6261 * defer authentication until arc_buf_fill(), which will
6262 * verify the data when the key is available.
6263 */
6264 if (BP_IS_AUTHENTICATED(bp))
6265 zio_flags |= ZIO_FLAG_RAW_ENCRYPT;
6266 }
6267
6268 if (BP_IS_AUTHENTICATED(bp))
6269 arc_hdr_set_flags(hdr, ARC_FLAG_NOAUTH);
6270 if (BP_GET_LEVEL(bp) > 0)
6271 arc_hdr_set_flags(hdr, ARC_FLAG_INDIRECT);
6272 ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
6273
6274 acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
6275 acb->acb_done = done;
6276 acb->acb_private = private;
6277 acb->acb_compressed = compressed_read;
6278 acb->acb_encrypted = encrypted_read;
6279 acb->acb_noauth = noauth_read;
6280 acb->acb_nobuf = no_buf;
6281 acb->acb_zb = *zb;
6282
6283 ASSERT0P(hdr->b_l1hdr.b_acb);
6284 hdr->b_l1hdr.b_acb = acb;
6285
6286 if (HDR_HAS_L2HDR(hdr) &&
6287 (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
6288 devw = hdr->b_l2hdr.b_dev->l2ad_writing;
6289 addr = hdr->b_l2hdr.b_daddr;
6290 /*
6291 * Lock out L2ARC device removal.
6292 */
6293 if (vdev_is_dead(vd) ||
6294 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
6295 vd = NULL;
6296 }
6297
6298 /*
6299 * We count both async reads and scrub IOs as asynchronous so
6300 * that both can be upgraded in the event of a cache hit while
6301 * the read IO is still in-flight.
6302 */
6303 if (priority == ZIO_PRIORITY_ASYNC_READ ||
6304 priority == ZIO_PRIORITY_SCRUB)
6305 arc_hdr_set_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
6306 else
6307 arc_hdr_clear_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
6308
6309 /*
6310 * At this point, we have a level 1 cache miss or a blkptr
6311 * with embedded data. Try again in L2ARC if possible.
6312 */
6313 ASSERT3U(HDR_GET_LSIZE(hdr), ==, lsize);
6314
6315 /*
6316 * Skip ARC stat bump for block pointers with embedded
6317 * data. The data are read from the blkptr itself via
6318 * decode_embedded_bp_compressed().
6319 */
6320 if (!embedded_bp) {
6321 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr,
6322 blkptr_t *, bp, uint64_t, lsize,
6323 zbookmark_phys_t *, zb);
6324 ARCSTAT_BUMP(arcstat_misses);
6325 ARCSTAT_CONDSTAT(!(*arc_flags & ARC_FLAG_PREFETCH),
6326 demand, prefetch, !HDR_ISTYPE_METADATA(hdr), data,
6327 metadata, misses);
6328 zfs_racct_read(spa, size, 1,
6329 (*arc_flags & ARC_FLAG_UNCACHED) ?
6330 DMU_UNCACHEDIO : 0);
6331 }
6332
6333 /* Check if the spa even has l2 configured */
6334 const boolean_t spa_has_l2 = l2arc_ndev != 0 &&
6335 spa->spa_l2cache.sav_count > 0;
6336
6337 if (vd != NULL && spa_has_l2 && !(l2arc_norw && devw)) {
6338 /*
6339 * Read from the L2ARC if the following are true:
6340 * 1. The L2ARC vdev was previously cached.
6341 * 2. This buffer still has L2ARC metadata.
6342 * 3. This buffer isn't currently writing to the L2ARC.
6343 * 4. The L2ARC entry wasn't evicted, which may
6344 * also have invalidated the vdev.
6345 */
6346 if (HDR_HAS_L2HDR(hdr) &&
6347 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr)) {
6348 l2arc_read_callback_t *cb;
6349 abd_t *abd;
6350 uint64_t asize;
6351
6352 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
6353 ARCSTAT_BUMP(arcstat_l2_hits);
6354 hdr->b_l2hdr.b_hits++;
6355
6356 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
6357 KM_SLEEP);
6358 cb->l2rcb_hdr = hdr;
6359 cb->l2rcb_bp = *bp;
6360 cb->l2rcb_zb = *zb;
6361 cb->l2rcb_flags = zio_flags;
6362
6363 /*
6364 * When Compressed ARC is disabled, but the
6365 * L2ARC block is compressed, arc_hdr_size()
6366 * will have returned LSIZE rather than PSIZE.
6367 */
6368 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
6369 !HDR_COMPRESSION_ENABLED(hdr) &&
6370 HDR_GET_PSIZE(hdr) != 0) {
6371 size = HDR_GET_PSIZE(hdr);
6372 }
6373
6374 asize = vdev_psize_to_asize(vd, size);
6375 if (asize != size) {
6376 abd = abd_alloc_for_io(asize,
6377 HDR_ISTYPE_METADATA(hdr));
6378 cb->l2rcb_abd = abd;
6379 } else {
6380 abd = hdr_abd;
6381 }
6382
6383 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
6384 addr + asize <= vd->vdev_psize -
6385 VDEV_LABEL_END_SIZE);
6386
6387 /*
6388 * l2arc read. The SCL_L2ARC lock will be
6389 * released by l2arc_read_done().
6390 * Issue a null zio if the underlying buffer
6391 * was squashed to zero size by compression.
6392 */
6393 ASSERT3U(arc_hdr_get_compress(hdr), !=,
6394 ZIO_COMPRESS_EMPTY);
6395 rzio = zio_read_phys(pio, vd, addr,
6396 asize, abd,
6397 ZIO_CHECKSUM_OFF,
6398 l2arc_read_done, cb, priority,
6399 zio_flags | ZIO_FLAG_CANFAIL |
6400 ZIO_FLAG_DONT_PROPAGATE |
6401 ZIO_FLAG_DONT_RETRY, B_FALSE);
6402 acb->acb_zio_head = rzio;
6403
6404 if (hash_lock != NULL)
6405 mutex_exit(hash_lock);
6406
6407 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
6408 zio_t *, rzio);
6409 ARCSTAT_INCR(arcstat_l2_read_bytes,
6410 HDR_GET_PSIZE(hdr));
6411
6412 if (*arc_flags & ARC_FLAG_NOWAIT) {
6413 zio_nowait(rzio);
6414 goto out;
6415 }
6416
6417 ASSERT(*arc_flags & ARC_FLAG_WAIT);
6418 if (zio_wait(rzio) == 0)
6419 goto out;
6420
6421 /* l2arc read error; goto zio_read() */
6422 if (hash_lock != NULL)
6423 mutex_enter(hash_lock);
6424 } else {
6425 DTRACE_PROBE1(l2arc__miss,
6426 arc_buf_hdr_t *, hdr);
6427 ARCSTAT_BUMP(arcstat_l2_misses);
6428 if (HDR_L2_WRITING(hdr))
6429 ARCSTAT_BUMP(arcstat_l2_rw_clash);
6430 spa_config_exit(spa, SCL_L2ARC, vd);
6431 }
6432 } else {
6433 if (vd != NULL)
6434 spa_config_exit(spa, SCL_L2ARC, vd);
6435
6436 /*
6437 * Only a spa with l2 should contribute to l2
6438 * miss stats. (Including the case of having a
6439 * faulted cache device - that's also a miss.)
6440 */
6441 if (spa_has_l2) {
6442 /*
6443 * Skip ARC stat bump for block pointers with
6444 * embedded data. The data are read from the
6445 * blkptr itself via
6446 * decode_embedded_bp_compressed().
6447 */
6448 if (!embedded_bp) {
6449 DTRACE_PROBE1(l2arc__miss,
6450 arc_buf_hdr_t *, hdr);
6451 ARCSTAT_BUMP(arcstat_l2_misses);
6452 }
6453 }
6454 }
6455
6456 rzio = zio_read(pio, spa, bp, hdr_abd, size,
6457 arc_read_done, hdr, priority, zio_flags, zb);
6458 acb->acb_zio_head = rzio;
6459
6460 if (hash_lock != NULL)
6461 mutex_exit(hash_lock);
6462
6463 if (*arc_flags & ARC_FLAG_WAIT) {
6464 rc = zio_wait(rzio);
6465 goto out;
6466 }
6467
6468 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
6469 zio_nowait(rzio);
6470 }
6471
6472 out:
6473 /* embedded bps don't actually go to disk */
6474 if (!embedded_bp)
6475 spa_read_history_add(spa, zb, *arc_flags);
6476 spl_fstrans_unmark(cookie);
6477 return (rc);
6478
6479 done:
6480 if (done)
6481 done(NULL, zb, bp, buf, private);
6482 if (pio && rc != 0) {
6483 zio_t *zio = zio_null(pio, spa, NULL, NULL, NULL, zio_flags);
6484 zio->io_error = rc;
6485 zio_nowait(zio);
6486 }
6487 goto out;
6488 }
6489
6490 arc_prune_t *
arc_add_prune_callback(arc_prune_func_t * func,void * private)6491 arc_add_prune_callback(arc_prune_func_t *func, void *private)
6492 {
6493 arc_prune_t *p;
6494
6495 p = kmem_alloc(sizeof (*p), KM_SLEEP);
6496 p->p_pfunc = func;
6497 p->p_private = private;
6498 list_link_init(&p->p_node);
6499 zfs_refcount_create(&p->p_refcnt);
6500
6501 mutex_enter(&arc_prune_mtx);
6502 zfs_refcount_add(&p->p_refcnt, &arc_prune_list);
6503 list_insert_head(&arc_prune_list, p);
6504 mutex_exit(&arc_prune_mtx);
6505
6506 return (p);
6507 }
6508
6509 void
arc_remove_prune_callback(arc_prune_t * p)6510 arc_remove_prune_callback(arc_prune_t *p)
6511 {
6512 boolean_t wait = B_FALSE;
6513 mutex_enter(&arc_prune_mtx);
6514 list_remove(&arc_prune_list, p);
6515 if (zfs_refcount_remove(&p->p_refcnt, &arc_prune_list) > 0)
6516 wait = B_TRUE;
6517 mutex_exit(&arc_prune_mtx);
6518
6519 /* wait for arc_prune_task to finish */
6520 if (wait)
6521 taskq_wait_outstanding(arc_prune_taskq, 0);
6522 ASSERT0(zfs_refcount_count(&p->p_refcnt));
6523 zfs_refcount_destroy(&p->p_refcnt);
6524 kmem_free(p, sizeof (*p));
6525 }
6526
6527 /*
6528 * Helper function for arc_prune_async() it is responsible for safely
6529 * handling the execution of a registered arc_prune_func_t.
6530 */
6531 static void
arc_prune_task(void * ptr)6532 arc_prune_task(void *ptr)
6533 {
6534 arc_prune_t *ap = (arc_prune_t *)ptr;
6535 arc_prune_func_t *func = ap->p_pfunc;
6536
6537 if (func != NULL)
6538 func(ap->p_adjust, ap->p_private);
6539
6540 (void) zfs_refcount_remove(&ap->p_refcnt, func);
6541 }
6542
6543 /*
6544 * Notify registered consumers they must drop holds on a portion of the ARC
6545 * buffers they reference. This provides a mechanism to ensure the ARC can
6546 * honor the metadata limit and reclaim otherwise pinned ARC buffers.
6547 *
6548 * This operation is performed asynchronously so it may be safely called
6549 * in the context of the arc_reclaim_thread(). A reference is taken here
6550 * for each registered arc_prune_t and the arc_prune_task() is responsible
6551 * for releasing it once the registered arc_prune_func_t has completed.
6552 */
6553 static void
arc_prune_async(uint64_t adjust)6554 arc_prune_async(uint64_t adjust)
6555 {
6556 arc_prune_t *ap;
6557
6558 mutex_enter(&arc_prune_mtx);
6559 for (ap = list_head(&arc_prune_list); ap != NULL;
6560 ap = list_next(&arc_prune_list, ap)) {
6561
6562 if (zfs_refcount_count(&ap->p_refcnt) >= 2)
6563 continue;
6564
6565 zfs_refcount_add(&ap->p_refcnt, ap->p_pfunc);
6566 ap->p_adjust = adjust;
6567 if (taskq_dispatch(arc_prune_taskq, arc_prune_task,
6568 ap, TQ_SLEEP) == TASKQID_INVALID) {
6569 (void) zfs_refcount_remove(&ap->p_refcnt, ap->p_pfunc);
6570 continue;
6571 }
6572 ARCSTAT_BUMP(arcstat_prune);
6573 }
6574 mutex_exit(&arc_prune_mtx);
6575 }
6576
6577 /*
6578 * Notify the arc that a block was freed, and thus will never be used again.
6579 */
6580 void
arc_freed(spa_t * spa,const blkptr_t * bp)6581 arc_freed(spa_t *spa, const blkptr_t *bp)
6582 {
6583 arc_buf_hdr_t *hdr;
6584 kmutex_t *hash_lock;
6585 uint64_t guid = spa_load_guid(spa);
6586
6587 ASSERT(!BP_IS_EMBEDDED(bp));
6588
6589 hdr = buf_hash_find(guid, bp, &hash_lock);
6590 if (hdr == NULL)
6591 return;
6592
6593 /*
6594 * We might be trying to free a block that is still doing I/O
6595 * (i.e. prefetch) or has some other reference (i.e. a dedup-ed,
6596 * dmu_sync-ed block). A block may also have a reference if it is
6597 * part of a dedup-ed, dmu_synced write. The dmu_sync() function would
6598 * have written the new block to its final resting place on disk but
6599 * without the dedup flag set. This would have left the hdr in the MRU
6600 * state and discoverable. When the txg finally syncs it detects that
6601 * the block was overridden in open context and issues an override I/O.
6602 * Since this is a dedup block, the override I/O will determine if the
6603 * block is already in the DDT. If so, then it will replace the io_bp
6604 * with the bp from the DDT and allow the I/O to finish. When the I/O
6605 * reaches the done callback, dbuf_write_override_done, it will
6606 * check to see if the io_bp and io_bp_override are identical.
6607 * If they are not, then it indicates that the bp was replaced with
6608 * the bp in the DDT and the override bp is freed. This allows
6609 * us to arrive here with a reference on a block that is being
6610 * freed. So if we have an I/O in progress, or a reference to
6611 * this hdr, then we don't destroy the hdr.
6612 */
6613 if (!HDR_HAS_L1HDR(hdr) ||
6614 zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
6615 arc_change_state(arc_anon, hdr);
6616 arc_hdr_destroy(hdr);
6617 mutex_exit(hash_lock);
6618 } else {
6619 mutex_exit(hash_lock);
6620 }
6621 }
6622
6623 /*
6624 * Release this buffer from the cache, making it an anonymous buffer. This
6625 * must be done after a read and prior to modifying the buffer contents.
6626 * If the buffer has more than one reference, we must make
6627 * a new hdr for the buffer.
6628 */
6629 void
arc_release(arc_buf_t * buf,const void * tag)6630 arc_release(arc_buf_t *buf, const void *tag)
6631 {
6632 arc_buf_hdr_t *hdr = buf->b_hdr;
6633
6634 /*
6635 * It would be nice to assert that if its DMU metadata (level >
6636 * 0 || it's the dnode file), then it must be syncing context.
6637 * But we don't know that information at this level.
6638 */
6639
6640 ASSERT(HDR_HAS_L1HDR(hdr));
6641
6642 /*
6643 * We don't grab the hash lock prior to this check, because if
6644 * the buffer's header is in the arc_anon state, it won't be
6645 * linked into the hash table.
6646 */
6647 if (hdr->b_l1hdr.b_state == arc_anon) {
6648 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6649 ASSERT(!HDR_IN_HASH_TABLE(hdr));
6650 ASSERT(!HDR_HAS_L2HDR(hdr));
6651
6652 ASSERT3P(hdr->b_l1hdr.b_buf, ==, buf);
6653 ASSERT(ARC_BUF_LAST(buf));
6654 ASSERT3S(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
6655 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
6656
6657 hdr->b_l1hdr.b_arc_access = 0;
6658
6659 /*
6660 * If the buf is being overridden then it may already
6661 * have a hdr that is not empty.
6662 */
6663 buf_discard_identity(hdr);
6664 arc_buf_thaw(buf);
6665
6666 return;
6667 }
6668
6669 kmutex_t *hash_lock = HDR_LOCK(hdr);
6670 mutex_enter(hash_lock);
6671
6672 /*
6673 * This assignment is only valid as long as the hash_lock is
6674 * held, we must be careful not to reference state or the
6675 * b_state field after dropping the lock.
6676 */
6677 arc_state_t *state = hdr->b_l1hdr.b_state;
6678 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
6679 ASSERT3P(state, !=, arc_anon);
6680 ASSERT3P(state, !=, arc_l2c_only);
6681
6682 /* this buffer is not on any list */
6683 ASSERT3S(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt), >, 0);
6684
6685 /*
6686 * Do we have more than one buf? Or L2_WRITING with unshared data?
6687 * Single-buf L2_WRITING with shared data can reuse the header since
6688 * L2ARC uses its own transformed copy.
6689 * Or I/O is in progress (a raw/encrypted read filling b_rabd while
6690 * our decrypted buf backs b_pabd) and arc_read_done() is yet to add
6691 * more bufs?
6692 */
6693 if (hdr->b_l1hdr.b_buf != buf || !ARC_BUF_LAST(buf) ||
6694 (HDR_L2_WRITING(hdr) && !ARC_BUF_SHARED(buf)) ||
6695 HDR_IO_IN_PROGRESS(hdr)) {
6696 arc_buf_hdr_t *nhdr;
6697 uint64_t spa = hdr->b_spa;
6698 uint64_t psize = HDR_GET_PSIZE(hdr);
6699 uint64_t lsize = HDR_GET_LSIZE(hdr);
6700 boolean_t protected = HDR_PROTECTED(hdr);
6701 enum zio_compress compress = arc_hdr_get_compress(hdr);
6702 uint8_t complevel = hdr->b_complevel;
6703 arc_buf_contents_t type = arc_buf_type(hdr);
6704 boolean_t single_buf = (hdr->b_l1hdr.b_buf == buf &&
6705 ARC_BUF_LAST(buf));
6706 boolean_t single_buf_l2writing = (single_buf &&
6707 HDR_L2_WRITING(hdr) && !HDR_IO_IN_PROGRESS(hdr));
6708
6709 if (ARC_BUF_SHARED(buf) && !ARC_BUF_COMPRESSED(buf)) {
6710 ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
6711 ASSERT(ARC_BUF_LAST(buf));
6712 }
6713
6714 /*
6715 * Pull the buffer off of this hdr and find the last buffer
6716 * in the hdr's buffer list.
6717 */
6718 arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
6719 EQUIV(single_buf, lastbuf == NULL);
6720
6721 /*
6722 * If the current arc_buf_t and the hdr are sharing their data
6723 * buffer, then we must stop sharing that block.
6724 */
6725 if (!single_buf_l2writing) {
6726 if (ARC_BUF_SHARED(buf)) {
6727 ASSERT(single_buf ||
6728 !arc_buf_is_shared(lastbuf));
6729
6730 /*
6731 * First, sever the block sharing relationship
6732 * between buf and the arc_buf_hdr_t.
6733 */
6734 arc_unshare_buf(hdr, buf);
6735
6736 /*
6737 * Now we need to recreate the hdr's b_pabd.
6738 * Since we have lastbuf handy, we try to share
6739 * with it, but if we can't then we allocate a
6740 * new b_pabd and copy the data from buf into it
6741 */
6742 if (!single_buf &&
6743 arc_can_share(hdr, lastbuf)) {
6744 arc_share_buf(hdr, lastbuf);
6745 } else {
6746 arc_hdr_alloc_abd(hdr, 0);
6747 abd_copy_from_buf(hdr->b_l1hdr.b_pabd,
6748 buf->b_data, psize);
6749 }
6750 } else if (HDR_SHARED_DATA(hdr)) {
6751 /*
6752 * Uncompressed shared buffers are always at the
6753 * end of the list. Compressed buffers don't
6754 * have the same requirements. This makes it
6755 * hard to simply assert that the lastbuf is
6756 * shared so we rely on the hdr's compression
6757 * flags to determine if we have a compressed,
6758 * shared buffer.
6759 */
6760 ASSERT(arc_buf_is_shared(lastbuf) ||
6761 arc_hdr_get_compress(hdr) !=
6762 ZIO_COMPRESS_OFF);
6763 ASSERT(!arc_buf_is_shared(buf));
6764 }
6765 }
6766
6767 ASSERT(hdr->b_l1hdr.b_pabd != NULL || HDR_HAS_RABD(hdr));
6768
6769 (void) zfs_refcount_remove_many(&state->arcs_size[type],
6770 arc_buf_size(buf), buf);
6771
6772 arc_cksum_verify(buf);
6773 arc_buf_unwatch(buf);
6774
6775 /* If this is the last uncompressed buf, free the checksum. */
6776 if (!arc_hdr_has_uncompressed_buf(hdr))
6777 arc_cksum_free(hdr);
6778
6779 if (single_buf_l2writing)
6780 VERIFY3S(remove_reference(hdr, tag), ==, 0);
6781 else
6782 VERIFY3S(remove_reference(hdr, tag), >, 0);
6783
6784 mutex_exit(hash_lock);
6785
6786 nhdr = arc_hdr_alloc(spa, psize, lsize, protected, compress,
6787 complevel, type);
6788 ASSERT0P(nhdr->b_l1hdr.b_buf);
6789 ASSERT0(zfs_refcount_count(&nhdr->b_l1hdr.b_refcnt));
6790 VERIFY3U(nhdr->b_type, ==, type);
6791 ASSERT(!HDR_SHARED_DATA(nhdr));
6792
6793 nhdr->b_l1hdr.b_buf = buf;
6794 (void) zfs_refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
6795 buf->b_hdr = nhdr;
6796
6797 (void) zfs_refcount_add_many(&arc_anon->arcs_size[type],
6798 arc_buf_size(buf), buf);
6799 } else {
6800 ASSERT(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
6801 /* protected by hash lock, or hdr is on arc_anon */
6802 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
6803 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6804
6805 if (HDR_HAS_L2HDR(hdr)) {
6806 mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
6807 /* Recheck to prevent race with l2arc_evict(). */
6808 if (HDR_HAS_L2HDR(hdr))
6809 arc_hdr_l2hdr_destroy(hdr);
6810 mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
6811 }
6812
6813 hdr->b_l1hdr.b_mru_hits = 0;
6814 hdr->b_l1hdr.b_mru_ghost_hits = 0;
6815 hdr->b_l1hdr.b_mfu_hits = 0;
6816 hdr->b_l1hdr.b_mfu_ghost_hits = 0;
6817 arc_change_state(arc_anon, hdr);
6818 hdr->b_l1hdr.b_arc_access = 0;
6819
6820 mutex_exit(hash_lock);
6821 buf_discard_identity(hdr);
6822 arc_buf_thaw(buf);
6823 }
6824 }
6825
6826 int
arc_released(arc_buf_t * buf)6827 arc_released(arc_buf_t *buf)
6828 {
6829 return (buf->b_data != NULL &&
6830 buf->b_hdr->b_l1hdr.b_state == arc_anon);
6831 }
6832
6833 #ifdef ZFS_DEBUG
6834 int
arc_referenced(arc_buf_t * buf)6835 arc_referenced(arc_buf_t *buf)
6836 {
6837 return (zfs_refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
6838 }
6839 #endif
6840
6841 static void
arc_write_ready(zio_t * zio)6842 arc_write_ready(zio_t *zio)
6843 {
6844 arc_write_callback_t *callback = zio->io_private;
6845 arc_buf_t *buf = callback->awcb_buf;
6846 arc_buf_hdr_t *hdr = buf->b_hdr;
6847 blkptr_t *bp = zio->io_bp;
6848 uint64_t psize = BP_IS_HOLE(bp) ? 0 : BP_GET_PSIZE(bp);
6849 fstrans_cookie_t cookie = spl_fstrans_mark();
6850
6851 ASSERT(HDR_HAS_L1HDR(hdr));
6852 ASSERT(!zfs_refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
6853 ASSERT3P(hdr->b_l1hdr.b_buf, !=, NULL);
6854
6855 /*
6856 * If we're reexecuting this zio because the pool suspended, then
6857 * cleanup any state that was previously set the first time the
6858 * callback was invoked.
6859 */
6860 if (zio->io_flags & ZIO_FLAG_REEXECUTED) {
6861 arc_cksum_free(hdr);
6862 arc_buf_unwatch(buf);
6863 if (hdr->b_l1hdr.b_pabd != NULL) {
6864 if (ARC_BUF_SHARED(buf)) {
6865 arc_unshare_buf(hdr, buf);
6866 } else {
6867 ASSERT(!arc_buf_is_shared(buf));
6868 arc_hdr_free_abd(hdr, B_FALSE);
6869 }
6870 }
6871
6872 if (HDR_HAS_RABD(hdr))
6873 arc_hdr_free_abd(hdr, B_TRUE);
6874 }
6875 ASSERT0P(hdr->b_l1hdr.b_pabd);
6876 ASSERT(!HDR_HAS_RABD(hdr));
6877 ASSERT(!HDR_SHARED_DATA(hdr));
6878 ASSERT(!arc_buf_is_shared(buf));
6879
6880 callback->awcb_ready(zio, buf, callback->awcb_private);
6881
6882 if (HDR_IO_IN_PROGRESS(hdr)) {
6883 ASSERT(zio->io_flags & ZIO_FLAG_REEXECUTED);
6884 } else {
6885 arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6886 add_reference(hdr, hdr); /* For IO_IN_PROGRESS. */
6887 }
6888
6889 if (BP_IS_PROTECTED(bp)) {
6890 /* ZIL blocks are written through zio_rewrite */
6891 ASSERT3U(BP_GET_TYPE(bp), !=, DMU_OT_INTENT_LOG);
6892
6893 if (BP_SHOULD_BYTESWAP(bp)) {
6894 if (BP_GET_LEVEL(bp) > 0) {
6895 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
6896 } else {
6897 hdr->b_l1hdr.b_byteswap =
6898 DMU_OT_BYTESWAP(BP_GET_TYPE(bp));
6899 }
6900 } else {
6901 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
6902 }
6903
6904 arc_hdr_set_flags(hdr, ARC_FLAG_PROTECTED);
6905 hdr->b_crypt_hdr.b_ot = BP_GET_TYPE(bp);
6906 hdr->b_crypt_hdr.b_dsobj = zio->io_bookmark.zb_objset;
6907 zio_crypt_decode_params_bp(bp, hdr->b_crypt_hdr.b_salt,
6908 hdr->b_crypt_hdr.b_iv);
6909 zio_crypt_decode_mac_bp(bp, hdr->b_crypt_hdr.b_mac);
6910 } else {
6911 arc_hdr_clear_flags(hdr, ARC_FLAG_PROTECTED);
6912 }
6913
6914 /*
6915 * If this block was written for raw encryption but the zio layer
6916 * ended up only authenticating it, adjust the buffer flags now.
6917 */
6918 if (BP_IS_AUTHENTICATED(bp) && ARC_BUF_ENCRYPTED(buf)) {
6919 arc_hdr_set_flags(hdr, ARC_FLAG_NOAUTH);
6920 buf->b_flags &= ~ARC_BUF_FLAG_ENCRYPTED;
6921 if (BP_GET_COMPRESS(bp) == ZIO_COMPRESS_OFF)
6922 buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
6923 } else if (BP_IS_HOLE(bp) && ARC_BUF_ENCRYPTED(buf)) {
6924 buf->b_flags &= ~ARC_BUF_FLAG_ENCRYPTED;
6925 buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
6926 }
6927
6928 /* this must be done after the buffer flags are adjusted */
6929 arc_cksum_compute(buf);
6930
6931 enum zio_compress compress;
6932 if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
6933 compress = ZIO_COMPRESS_OFF;
6934 } else {
6935 ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
6936 compress = BP_GET_COMPRESS(bp);
6937 }
6938 HDR_SET_PSIZE(hdr, psize);
6939 arc_hdr_set_compress(hdr, compress);
6940 hdr->b_complevel = zio->io_prop.zp_complevel;
6941
6942 if (zio->io_error != 0 || psize == 0)
6943 goto out;
6944
6945 /*
6946 * Fill the hdr with data. If the buffer is encrypted we have no choice
6947 * but to copy the data into b_radb. If the hdr is compressed, the data
6948 * we want is available from the zio, otherwise we can take it from
6949 * the buf.
6950 *
6951 * We might be able to share the buf's data with the hdr here. However,
6952 * doing so would cause the ARC to be full of linear ABDs if we write a
6953 * lot of shareable data. As a compromise, we check whether scattered
6954 * ABDs are allowed, and assume that if they are then the user wants
6955 * the ARC to be primarily filled with them regardless of the data being
6956 * written. Therefore, if they're allowed then we allocate one and copy
6957 * the data into it; otherwise, we share the data directly if we can.
6958 */
6959 if (ARC_BUF_ENCRYPTED(buf)) {
6960 ASSERT3U(psize, >, 0);
6961 ASSERT(ARC_BUF_COMPRESSED(buf));
6962 arc_hdr_alloc_abd(hdr, ARC_HDR_ALLOC_RDATA |
6963 ARC_HDR_USE_RESERVE);
6964 abd_copy(hdr->b_crypt_hdr.b_rabd, zio->io_abd, psize);
6965 } else if (!(HDR_UNCACHED(hdr) ||
6966 abd_size_alloc_linear(arc_buf_size(buf))) ||
6967 !arc_can_share(hdr, buf)) {
6968 /*
6969 * Ideally, we would always copy the io_abd into b_pabd, but the
6970 * user may have disabled compressed ARC, thus we must check the
6971 * hdr's compression setting rather than the io_bp's.
6972 */
6973 if (BP_IS_ENCRYPTED(bp)) {
6974 ASSERT3U(psize, >, 0);
6975 arc_hdr_alloc_abd(hdr, ARC_HDR_ALLOC_RDATA |
6976 ARC_HDR_USE_RESERVE);
6977 abd_copy(hdr->b_crypt_hdr.b_rabd, zio->io_abd, psize);
6978 } else if (arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF &&
6979 !ARC_BUF_COMPRESSED(buf)) {
6980 ASSERT3U(psize, >, 0);
6981 arc_hdr_alloc_abd(hdr, ARC_HDR_USE_RESERVE);
6982 abd_copy(hdr->b_l1hdr.b_pabd, zio->io_abd, psize);
6983 } else {
6984 ASSERT3U(zio->io_orig_size, ==, arc_hdr_size(hdr));
6985 arc_hdr_alloc_abd(hdr, ARC_HDR_USE_RESERVE);
6986 abd_copy_from_buf(hdr->b_l1hdr.b_pabd, buf->b_data,
6987 arc_buf_size(buf));
6988 }
6989 } else {
6990 ASSERT3P(buf->b_data, ==, abd_to_buf(zio->io_orig_abd));
6991 ASSERT3U(zio->io_orig_size, ==, arc_buf_size(buf));
6992 ASSERT3P(hdr->b_l1hdr.b_buf, ==, buf);
6993 ASSERT(ARC_BUF_LAST(buf));
6994
6995 arc_share_buf(hdr, buf);
6996 }
6997
6998 out:
6999 arc_hdr_verify(hdr, bp);
7000 spl_fstrans_unmark(cookie);
7001 }
7002
7003 static void
arc_write_children_ready(zio_t * zio)7004 arc_write_children_ready(zio_t *zio)
7005 {
7006 arc_write_callback_t *callback = zio->io_private;
7007 arc_buf_t *buf = callback->awcb_buf;
7008
7009 callback->awcb_children_ready(zio, buf, callback->awcb_private);
7010 }
7011
7012 static void
arc_write_done(zio_t * zio)7013 arc_write_done(zio_t *zio)
7014 {
7015 arc_write_callback_t *callback = zio->io_private;
7016 arc_buf_t *buf = callback->awcb_buf;
7017 arc_buf_hdr_t *hdr = buf->b_hdr;
7018
7019 ASSERT0P(hdr->b_l1hdr.b_acb);
7020
7021 if (zio->io_error == 0) {
7022 arc_hdr_verify(hdr, zio->io_bp);
7023
7024 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
7025 buf_discard_identity(hdr);
7026 } else {
7027 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
7028 hdr->b_birth = BP_GET_PHYSICAL_BIRTH(zio->io_bp);
7029 }
7030 } else {
7031 ASSERT(HDR_EMPTY(hdr));
7032 }
7033
7034 /*
7035 * If the block to be written was all-zero or compressed enough to be
7036 * embedded in the BP, no write was performed so there will be no
7037 * dva/birth/checksum. The buffer must therefore remain anonymous
7038 * (and uncached).
7039 */
7040 if (!HDR_EMPTY(hdr)) {
7041 arc_buf_hdr_t *exists;
7042 kmutex_t *hash_lock;
7043
7044 ASSERT0(zio->io_error);
7045
7046 arc_cksum_verify(buf);
7047
7048 exists = buf_hash_insert(hdr, &hash_lock);
7049 if (exists != NULL) {
7050 /*
7051 * This can only happen if we overwrite for
7052 * sync-to-convergence, because we remove
7053 * buffers from the hash table at arc_release().
7054 */
7055 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
7056 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
7057 panic("bad overwrite, hdr=%p exists=%p",
7058 (void *)hdr, (void *)exists);
7059 VERIFY(zfs_refcount_is_zero(
7060 &exists->b_l1hdr.b_refcnt));
7061 arc_change_state(arc_anon, exists);
7062 arc_hdr_destroy(exists);
7063 mutex_exit(hash_lock);
7064 exists = buf_hash_insert(hdr, &hash_lock);
7065 VERIFY0P(exists);
7066 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
7067 /* nopwrite */
7068 ASSERT(zio->io_prop.zp_nopwrite);
7069 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
7070 panic("bad nopwrite, hdr=%p exists=%p",
7071 (void *)hdr, (void *)exists);
7072 } else {
7073 /* Dedup */
7074 ASSERT3P(hdr->b_l1hdr.b_buf, !=, NULL);
7075 ASSERT(ARC_BUF_LAST(hdr->b_l1hdr.b_buf));
7076 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
7077 ASSERT(BP_GET_DEDUP(zio->io_bp));
7078 ASSERT0(BP_GET_LEVEL(zio->io_bp));
7079 }
7080 }
7081 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
7082 VERIFY3S(remove_reference(hdr, hdr), >, 0);
7083 /* if it's not anon, we are doing a scrub */
7084 if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
7085 arc_access(hdr, 0, B_FALSE);
7086 mutex_exit(hash_lock);
7087 } else {
7088 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
7089 VERIFY3S(remove_reference(hdr, hdr), >, 0);
7090 }
7091
7092 callback->awcb_done(zio, buf, callback->awcb_private);
7093
7094 abd_free(zio->io_abd);
7095 kmem_free(callback, sizeof (arc_write_callback_t));
7096 }
7097
7098 zio_t *
arc_write(zio_t * pio,spa_t * spa,uint64_t txg,blkptr_t * bp,arc_buf_t * buf,boolean_t uncached,boolean_t l2arc,const zio_prop_t * zp,arc_write_done_func_t * ready,arc_write_done_func_t * children_ready,arc_write_done_func_t * done,void * private,zio_priority_t priority,int zio_flags,const zbookmark_phys_t * zb)7099 arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
7100 blkptr_t *bp, arc_buf_t *buf, boolean_t uncached, boolean_t l2arc,
7101 const zio_prop_t *zp, arc_write_done_func_t *ready,
7102 arc_write_done_func_t *children_ready, arc_write_done_func_t *done,
7103 void *private, zio_priority_t priority, int zio_flags,
7104 const zbookmark_phys_t *zb)
7105 {
7106 arc_buf_hdr_t *hdr = buf->b_hdr;
7107 arc_write_callback_t *callback;
7108 zio_t *zio;
7109 zio_prop_t localprop = *zp;
7110
7111 ASSERT3P(ready, !=, NULL);
7112 ASSERT3P(done, !=, NULL);
7113 ASSERT(!HDR_IO_ERROR(hdr));
7114 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
7115 ASSERT0P(hdr->b_l1hdr.b_acb);
7116 ASSERT3P(hdr->b_l1hdr.b_buf, !=, NULL);
7117 if (uncached)
7118 arc_hdr_set_flags(hdr, ARC_FLAG_UNCACHED);
7119 else if (l2arc)
7120 arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
7121
7122 if (ARC_BUF_ENCRYPTED(buf)) {
7123 ASSERT(ARC_BUF_COMPRESSED(buf));
7124 localprop.zp_encrypt = B_TRUE;
7125 localprop.zp_compress = HDR_GET_COMPRESS(hdr);
7126 localprop.zp_complevel = hdr->b_complevel;
7127 localprop.zp_byteorder =
7128 (hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS) ?
7129 ZFS_HOST_BYTEORDER : !ZFS_HOST_BYTEORDER;
7130 memcpy(localprop.zp_salt, hdr->b_crypt_hdr.b_salt,
7131 ZIO_DATA_SALT_LEN);
7132 memcpy(localprop.zp_iv, hdr->b_crypt_hdr.b_iv,
7133 ZIO_DATA_IV_LEN);
7134 memcpy(localprop.zp_mac, hdr->b_crypt_hdr.b_mac,
7135 ZIO_DATA_MAC_LEN);
7136 if (DMU_OT_IS_ENCRYPTED(localprop.zp_type)) {
7137 localprop.zp_nopwrite = B_FALSE;
7138 localprop.zp_copies =
7139 MIN(localprop.zp_copies, SPA_DVAS_PER_BP - 1);
7140 localprop.zp_gang_copies =
7141 MIN(localprop.zp_gang_copies, SPA_DVAS_PER_BP - 1);
7142 }
7143 zio_flags |= ZIO_FLAG_RAW;
7144 } else if (ARC_BUF_COMPRESSED(buf)) {
7145 ASSERT3U(HDR_GET_LSIZE(hdr), !=, arc_buf_size(buf));
7146 localprop.zp_compress = HDR_GET_COMPRESS(hdr);
7147 localprop.zp_complevel = hdr->b_complevel;
7148 zio_flags |= ZIO_FLAG_RAW_COMPRESS;
7149 }
7150 callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
7151 callback->awcb_ready = ready;
7152 callback->awcb_children_ready = children_ready;
7153 callback->awcb_done = done;
7154 callback->awcb_private = private;
7155 callback->awcb_buf = buf;
7156
7157 /*
7158 * The hdr's b_pabd is now stale, free it now. A new data block
7159 * will be allocated when the zio pipeline calls arc_write_ready().
7160 */
7161 if (hdr->b_l1hdr.b_pabd != NULL) {
7162 /*
7163 * If the buf is currently sharing the data block with
7164 * the hdr then we need to break that relationship here.
7165 * The hdr will remain with a NULL data pointer and the
7166 * buf will take sole ownership of the block.
7167 */
7168 if (ARC_BUF_SHARED(buf)) {
7169 arc_unshare_buf(hdr, buf);
7170 } else {
7171 ASSERT(!arc_buf_is_shared(buf));
7172 arc_hdr_free_abd(hdr, B_FALSE);
7173 }
7174 VERIFY3P(buf->b_data, !=, NULL);
7175 }
7176
7177 if (HDR_HAS_RABD(hdr))
7178 arc_hdr_free_abd(hdr, B_TRUE);
7179
7180 if (!(zio_flags & ZIO_FLAG_RAW))
7181 arc_hdr_set_compress(hdr, ZIO_COMPRESS_OFF);
7182
7183 ASSERT(!arc_buf_is_shared(buf));
7184 ASSERT0P(hdr->b_l1hdr.b_pabd);
7185
7186 zio = zio_write(pio, spa, txg, bp,
7187 abd_get_from_buf(buf->b_data, HDR_GET_LSIZE(hdr)),
7188 HDR_GET_LSIZE(hdr), arc_buf_size(buf), &localprop, arc_write_ready,
7189 (children_ready != NULL) ? arc_write_children_ready : NULL,
7190 arc_write_done, callback, priority, zio_flags, zb);
7191
7192 return (zio);
7193 }
7194
7195 void
arc_tempreserve_clear(uint64_t reserve)7196 arc_tempreserve_clear(uint64_t reserve)
7197 {
7198 atomic_add_64(&arc_tempreserve, -reserve);
7199 ASSERT((int64_t)arc_tempreserve >= 0);
7200 }
7201
7202 int
arc_tempreserve_space(spa_t * spa,uint64_t reserve,uint64_t txg)7203 arc_tempreserve_space(spa_t *spa, uint64_t reserve, uint64_t txg)
7204 {
7205 int error;
7206 uint64_t anon_size;
7207
7208 if (!arc_no_grow &&
7209 reserve > arc_c/4 &&
7210 reserve * 4 > (2ULL << SPA_MAXBLOCKSHIFT))
7211 arc_c = MIN(arc_c_max, reserve * 4);
7212
7213 /*
7214 * Throttle when the calculated memory footprint for the TXG
7215 * exceeds the target ARC size.
7216 */
7217 if (reserve > arc_c) {
7218 DMU_TX_STAT_BUMP(dmu_tx_memory_reserve);
7219 return (SET_ERROR(ERESTART));
7220 }
7221
7222 /*
7223 * Don't count loaned bufs as in flight dirty data to prevent long
7224 * network delays from blocking transactions that are ready to be
7225 * assigned to a txg.
7226 */
7227
7228 /* assert that it has not wrapped around */
7229 ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
7230
7231 anon_size = MAX((int64_t)
7232 (zfs_refcount_count(&arc_anon->arcs_size[ARC_BUFC_DATA]) +
7233 zfs_refcount_count(&arc_anon->arcs_size[ARC_BUFC_METADATA]) -
7234 arc_loaned_bytes), 0);
7235
7236 /*
7237 * Writes will, almost always, require additional memory allocations
7238 * in order to compress/encrypt/etc the data. We therefore need to
7239 * make sure that there is sufficient available memory for this.
7240 */
7241 error = arc_memory_throttle(spa, reserve, txg);
7242 if (error != 0)
7243 return (error);
7244
7245 /*
7246 * Throttle writes when the amount of dirty data in the cache
7247 * gets too large. We try to keep the cache less than half full
7248 * of dirty blocks so that our sync times don't grow too large.
7249 *
7250 * In the case of one pool being built on another pool, we want
7251 * to make sure we don't end up throttling the lower (backing)
7252 * pool when the upper pool is the majority contributor to dirty
7253 * data. To insure we make forward progress during throttling, we
7254 * also check the current pool's net dirty data and only throttle
7255 * if it exceeds zfs_arc_pool_dirty_percent of the anonymous dirty
7256 * data in the cache.
7257 *
7258 * Note: if two requests come in concurrently, we might let them
7259 * both succeed, when one of them should fail. Not a huge deal.
7260 */
7261 uint64_t total_dirty = reserve + arc_tempreserve + anon_size;
7262 uint64_t spa_dirty_anon = spa_dirty_data(spa);
7263 uint64_t rarc_c = arc_warm ? arc_c : arc_c_max;
7264 if (total_dirty > rarc_c * zfs_arc_dirty_limit_percent / 100 &&
7265 anon_size > rarc_c * zfs_arc_anon_limit_percent / 100 &&
7266 spa_dirty_anon > anon_size * zfs_arc_pool_dirty_percent / 100) {
7267 #ifdef ZFS_DEBUG
7268 uint64_t meta_esize = zfs_refcount_count(
7269 &arc_anon->arcs_esize[ARC_BUFC_METADATA]);
7270 uint64_t data_esize =
7271 zfs_refcount_count(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
7272 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
7273 "anon_data=%lluK tempreserve=%lluK rarc_c=%lluK\n",
7274 (u_longlong_t)arc_tempreserve >> 10,
7275 (u_longlong_t)meta_esize >> 10,
7276 (u_longlong_t)data_esize >> 10,
7277 (u_longlong_t)reserve >> 10,
7278 (u_longlong_t)rarc_c >> 10);
7279 #endif
7280 DMU_TX_STAT_BUMP(dmu_tx_dirty_throttle);
7281 return (SET_ERROR(ERESTART));
7282 }
7283 atomic_add_64(&arc_tempreserve, reserve);
7284 return (0);
7285 }
7286
7287 static void
arc_kstat_update_state(arc_state_t * state,kstat_named_t * size,kstat_named_t * data,kstat_named_t * metadata,kstat_named_t * evict_data,kstat_named_t * evict_metadata)7288 arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
7289 kstat_named_t *data, kstat_named_t *metadata,
7290 kstat_named_t *evict_data, kstat_named_t *evict_metadata)
7291 {
7292 data->value.ui64 =
7293 zfs_refcount_count(&state->arcs_size[ARC_BUFC_DATA]);
7294 metadata->value.ui64 =
7295 zfs_refcount_count(&state->arcs_size[ARC_BUFC_METADATA]);
7296 size->value.ui64 = data->value.ui64 + metadata->value.ui64;
7297 evict_data->value.ui64 =
7298 zfs_refcount_count(&state->arcs_esize[ARC_BUFC_DATA]);
7299 evict_metadata->value.ui64 =
7300 zfs_refcount_count(&state->arcs_esize[ARC_BUFC_METADATA]);
7301 }
7302
7303 static int
arc_kstat_update(kstat_t * ksp,int rw)7304 arc_kstat_update(kstat_t *ksp, int rw)
7305 {
7306 arc_stats_t *as = ksp->ks_data;
7307
7308 if (rw == KSTAT_WRITE)
7309 return (SET_ERROR(EACCES));
7310
7311 as->arcstat_hits.value.ui64 =
7312 wmsum_value(&arc_sums.arcstat_hits);
7313 as->arcstat_iohits.value.ui64 =
7314 wmsum_value(&arc_sums.arcstat_iohits);
7315 as->arcstat_misses.value.ui64 =
7316 wmsum_value(&arc_sums.arcstat_misses);
7317 as->arcstat_demand_data_hits.value.ui64 =
7318 wmsum_value(&arc_sums.arcstat_demand_data_hits);
7319 as->arcstat_demand_data_iohits.value.ui64 =
7320 wmsum_value(&arc_sums.arcstat_demand_data_iohits);
7321 as->arcstat_demand_data_misses.value.ui64 =
7322 wmsum_value(&arc_sums.arcstat_demand_data_misses);
7323 as->arcstat_demand_metadata_hits.value.ui64 =
7324 wmsum_value(&arc_sums.arcstat_demand_metadata_hits);
7325 as->arcstat_demand_metadata_iohits.value.ui64 =
7326 wmsum_value(&arc_sums.arcstat_demand_metadata_iohits);
7327 as->arcstat_demand_metadata_misses.value.ui64 =
7328 wmsum_value(&arc_sums.arcstat_demand_metadata_misses);
7329 as->arcstat_prefetch_data_hits.value.ui64 =
7330 wmsum_value(&arc_sums.arcstat_prefetch_data_hits);
7331 as->arcstat_prefetch_data_iohits.value.ui64 =
7332 wmsum_value(&arc_sums.arcstat_prefetch_data_iohits);
7333 as->arcstat_prefetch_data_misses.value.ui64 =
7334 wmsum_value(&arc_sums.arcstat_prefetch_data_misses);
7335 as->arcstat_prefetch_metadata_hits.value.ui64 =
7336 wmsum_value(&arc_sums.arcstat_prefetch_metadata_hits);
7337 as->arcstat_prefetch_metadata_iohits.value.ui64 =
7338 wmsum_value(&arc_sums.arcstat_prefetch_metadata_iohits);
7339 as->arcstat_prefetch_metadata_misses.value.ui64 =
7340 wmsum_value(&arc_sums.arcstat_prefetch_metadata_misses);
7341 as->arcstat_mru_hits.value.ui64 =
7342 wmsum_value(&arc_sums.arcstat_mru_hits);
7343 as->arcstat_mru_ghost_hits.value.ui64 =
7344 wmsum_value(&arc_sums.arcstat_mru_ghost_hits);
7345 as->arcstat_mfu_hits.value.ui64 =
7346 wmsum_value(&arc_sums.arcstat_mfu_hits);
7347 as->arcstat_mfu_ghost_hits.value.ui64 =
7348 wmsum_value(&arc_sums.arcstat_mfu_ghost_hits);
7349 as->arcstat_uncached_hits.value.ui64 =
7350 wmsum_value(&arc_sums.arcstat_uncached_hits);
7351 as->arcstat_deleted.value.ui64 =
7352 wmsum_value(&arc_sums.arcstat_deleted);
7353 as->arcstat_mutex_miss.value.ui64 =
7354 wmsum_value(&arc_sums.arcstat_mutex_miss);
7355 as->arcstat_access_skip.value.ui64 =
7356 wmsum_value(&arc_sums.arcstat_access_skip);
7357 as->arcstat_evict_skip.value.ui64 =
7358 wmsum_value(&arc_sums.arcstat_evict_skip);
7359 as->arcstat_evict_not_enough.value.ui64 =
7360 wmsum_value(&arc_sums.arcstat_evict_not_enough);
7361 as->arcstat_evict_l2_cached.value.ui64 =
7362 wmsum_value(&arc_sums.arcstat_evict_l2_cached);
7363 as->arcstat_evict_l2_eligible.value.ui64 =
7364 wmsum_value(&arc_sums.arcstat_evict_l2_eligible);
7365 as->arcstat_evict_l2_eligible_mfu.value.ui64 =
7366 wmsum_value(&arc_sums.arcstat_evict_l2_eligible_mfu);
7367 as->arcstat_evict_l2_eligible_mru.value.ui64 =
7368 wmsum_value(&arc_sums.arcstat_evict_l2_eligible_mru);
7369 as->arcstat_evict_l2_ineligible.value.ui64 =
7370 wmsum_value(&arc_sums.arcstat_evict_l2_ineligible);
7371 as->arcstat_evict_l2_skip.value.ui64 =
7372 wmsum_value(&arc_sums.arcstat_evict_l2_skip);
7373 as->arcstat_hash_elements.value.ui64 =
7374 as->arcstat_hash_elements_max.value.ui64 =
7375 wmsum_value(&arc_sums.arcstat_hash_elements);
7376 as->arcstat_hash_collisions.value.ui64 =
7377 wmsum_value(&arc_sums.arcstat_hash_collisions);
7378 as->arcstat_hash_chains.value.ui64 =
7379 wmsum_value(&arc_sums.arcstat_hash_chains);
7380 as->arcstat_size.value.ui64 =
7381 aggsum_value(&arc_sums.arcstat_size);
7382 as->arcstat_compressed_size.value.ui64 =
7383 wmsum_value(&arc_sums.arcstat_compressed_size);
7384 as->arcstat_uncompressed_size.value.ui64 =
7385 wmsum_value(&arc_sums.arcstat_uncompressed_size);
7386 as->arcstat_overhead_size.value.ui64 =
7387 wmsum_value(&arc_sums.arcstat_overhead_size);
7388 as->arcstat_hdr_size.value.ui64 =
7389 wmsum_value(&arc_sums.arcstat_hdr_size);
7390 as->arcstat_data_size.value.ui64 =
7391 wmsum_value(&arc_sums.arcstat_data_size);
7392 as->arcstat_metadata_size.value.ui64 =
7393 wmsum_value(&arc_sums.arcstat_metadata_size);
7394 as->arcstat_dbuf_size.value.ui64 =
7395 wmsum_value(&arc_sums.arcstat_dbuf_size);
7396 #if defined(COMPAT_FREEBSD11)
7397 as->arcstat_other_size.value.ui64 =
7398 wmsum_value(&arc_sums.arcstat_bonus_size) +
7399 aggsum_value(&arc_sums.arcstat_dnode_size) +
7400 wmsum_value(&arc_sums.arcstat_dbuf_size);
7401 #endif
7402
7403 arc_kstat_update_state(arc_anon,
7404 &as->arcstat_anon_size,
7405 &as->arcstat_anon_data,
7406 &as->arcstat_anon_metadata,
7407 &as->arcstat_anon_evictable_data,
7408 &as->arcstat_anon_evictable_metadata);
7409 arc_kstat_update_state(arc_mru,
7410 &as->arcstat_mru_size,
7411 &as->arcstat_mru_data,
7412 &as->arcstat_mru_metadata,
7413 &as->arcstat_mru_evictable_data,
7414 &as->arcstat_mru_evictable_metadata);
7415 arc_kstat_update_state(arc_mru_ghost,
7416 &as->arcstat_mru_ghost_size,
7417 &as->arcstat_mru_ghost_data,
7418 &as->arcstat_mru_ghost_metadata,
7419 &as->arcstat_mru_ghost_evictable_data,
7420 &as->arcstat_mru_ghost_evictable_metadata);
7421 arc_kstat_update_state(arc_mfu,
7422 &as->arcstat_mfu_size,
7423 &as->arcstat_mfu_data,
7424 &as->arcstat_mfu_metadata,
7425 &as->arcstat_mfu_evictable_data,
7426 &as->arcstat_mfu_evictable_metadata);
7427 arc_kstat_update_state(arc_mfu_ghost,
7428 &as->arcstat_mfu_ghost_size,
7429 &as->arcstat_mfu_ghost_data,
7430 &as->arcstat_mfu_ghost_metadata,
7431 &as->arcstat_mfu_ghost_evictable_data,
7432 &as->arcstat_mfu_ghost_evictable_metadata);
7433 arc_kstat_update_state(arc_uncached,
7434 &as->arcstat_uncached_size,
7435 &as->arcstat_uncached_data,
7436 &as->arcstat_uncached_metadata,
7437 &as->arcstat_uncached_evictable_data,
7438 &as->arcstat_uncached_evictable_metadata);
7439
7440 as->arcstat_dnode_size.value.ui64 =
7441 aggsum_value(&arc_sums.arcstat_dnode_size);
7442 as->arcstat_bonus_size.value.ui64 =
7443 wmsum_value(&arc_sums.arcstat_bonus_size);
7444 as->arcstat_l2_ndev.value.ui64 = l2arc_ndev;
7445 as->arcstat_l2_hits.value.ui64 =
7446 wmsum_value(&arc_sums.arcstat_l2_hits);
7447 as->arcstat_l2_misses.value.ui64 =
7448 wmsum_value(&arc_sums.arcstat_l2_misses);
7449 as->arcstat_l2_prefetch_asize.value.ui64 =
7450 wmsum_value(&arc_sums.arcstat_l2_prefetch_asize);
7451 as->arcstat_l2_mru_asize.value.ui64 =
7452 wmsum_value(&arc_sums.arcstat_l2_mru_asize);
7453 as->arcstat_l2_mfu_asize.value.ui64 =
7454 wmsum_value(&arc_sums.arcstat_l2_mfu_asize);
7455 as->arcstat_l2_bufc_data_asize.value.ui64 =
7456 wmsum_value(&arc_sums.arcstat_l2_bufc_data_asize);
7457 as->arcstat_l2_bufc_metadata_asize.value.ui64 =
7458 wmsum_value(&arc_sums.arcstat_l2_bufc_metadata_asize);
7459 as->arcstat_l2_feeds.value.ui64 =
7460 wmsum_value(&arc_sums.arcstat_l2_feeds);
7461 as->arcstat_l2_rw_clash.value.ui64 =
7462 wmsum_value(&arc_sums.arcstat_l2_rw_clash);
7463 as->arcstat_l2_read_bytes.value.ui64 =
7464 wmsum_value(&arc_sums.arcstat_l2_read_bytes);
7465 as->arcstat_l2_write_bytes.value.ui64 =
7466 wmsum_value(&arc_sums.arcstat_l2_write_bytes);
7467 as->arcstat_l2_writes_sent.value.ui64 =
7468 wmsum_value(&arc_sums.arcstat_l2_writes_sent);
7469 as->arcstat_l2_writes_done.value.ui64 =
7470 wmsum_value(&arc_sums.arcstat_l2_writes_done);
7471 as->arcstat_l2_writes_error.value.ui64 =
7472 wmsum_value(&arc_sums.arcstat_l2_writes_error);
7473 as->arcstat_l2_writes_lock_retry.value.ui64 =
7474 wmsum_value(&arc_sums.arcstat_l2_writes_lock_retry);
7475 as->arcstat_l2_evict_lock_retry.value.ui64 =
7476 wmsum_value(&arc_sums.arcstat_l2_evict_lock_retry);
7477 as->arcstat_l2_evict_reading.value.ui64 =
7478 wmsum_value(&arc_sums.arcstat_l2_evict_reading);
7479 as->arcstat_l2_evict_l1cached.value.ui64 =
7480 wmsum_value(&arc_sums.arcstat_l2_evict_l1cached);
7481 as->arcstat_l2_free_on_write.value.ui64 =
7482 wmsum_value(&arc_sums.arcstat_l2_free_on_write);
7483 as->arcstat_l2_abort_lowmem.value.ui64 =
7484 wmsum_value(&arc_sums.arcstat_l2_abort_lowmem);
7485 as->arcstat_l2_cksum_bad.value.ui64 =
7486 wmsum_value(&arc_sums.arcstat_l2_cksum_bad);
7487 as->arcstat_l2_io_error.value.ui64 =
7488 wmsum_value(&arc_sums.arcstat_l2_io_error);
7489 as->arcstat_l2_lsize.value.ui64 =
7490 wmsum_value(&arc_sums.arcstat_l2_lsize);
7491 as->arcstat_l2_psize.value.ui64 =
7492 wmsum_value(&arc_sums.arcstat_l2_psize);
7493 as->arcstat_l2_hdr_size.value.ui64 =
7494 aggsum_value(&arc_sums.arcstat_l2_hdr_size);
7495 as->arcstat_l2_log_blk_writes.value.ui64 =
7496 wmsum_value(&arc_sums.arcstat_l2_log_blk_writes);
7497 as->arcstat_l2_log_blk_asize.value.ui64 =
7498 wmsum_value(&arc_sums.arcstat_l2_log_blk_asize);
7499 as->arcstat_l2_log_blk_count.value.ui64 =
7500 wmsum_value(&arc_sums.arcstat_l2_log_blk_count);
7501 as->arcstat_l2_rebuild_success.value.ui64 =
7502 wmsum_value(&arc_sums.arcstat_l2_rebuild_success);
7503 as->arcstat_l2_rebuild_abort_unsupported.value.ui64 =
7504 wmsum_value(&arc_sums.arcstat_l2_rebuild_abort_unsupported);
7505 as->arcstat_l2_rebuild_abort_io_errors.value.ui64 =
7506 wmsum_value(&arc_sums.arcstat_l2_rebuild_abort_io_errors);
7507 as->arcstat_l2_rebuild_abort_dh_errors.value.ui64 =
7508 wmsum_value(&arc_sums.arcstat_l2_rebuild_abort_dh_errors);
7509 as->arcstat_l2_rebuild_abort_cksum_lb_errors.value.ui64 =
7510 wmsum_value(&arc_sums.arcstat_l2_rebuild_abort_cksum_lb_errors);
7511 as->arcstat_l2_rebuild_abort_lowmem.value.ui64 =
7512 wmsum_value(&arc_sums.arcstat_l2_rebuild_abort_lowmem);
7513 as->arcstat_l2_rebuild_size.value.ui64 =
7514 wmsum_value(&arc_sums.arcstat_l2_rebuild_size);
7515 as->arcstat_l2_rebuild_asize.value.ui64 =
7516 wmsum_value(&arc_sums.arcstat_l2_rebuild_asize);
7517 as->arcstat_l2_rebuild_bufs.value.ui64 =
7518 wmsum_value(&arc_sums.arcstat_l2_rebuild_bufs);
7519 as->arcstat_l2_rebuild_bufs_precached.value.ui64 =
7520 wmsum_value(&arc_sums.arcstat_l2_rebuild_bufs_precached);
7521 as->arcstat_l2_rebuild_log_blks.value.ui64 =
7522 wmsum_value(&arc_sums.arcstat_l2_rebuild_log_blks);
7523 as->arcstat_memory_throttle_count.value.ui64 =
7524 wmsum_value(&arc_sums.arcstat_memory_throttle_count);
7525 as->arcstat_memory_direct_count.value.ui64 =
7526 wmsum_value(&arc_sums.arcstat_memory_direct_count);
7527 as->arcstat_memory_indirect_count.value.ui64 =
7528 wmsum_value(&arc_sums.arcstat_memory_indirect_count);
7529
7530 as->arcstat_memory_all_bytes.value.ui64 =
7531 arc_all_memory();
7532 as->arcstat_memory_free_bytes.value.ui64 =
7533 arc_free_memory();
7534 as->arcstat_memory_available_bytes.value.i64 =
7535 arc_available_memory();
7536
7537 as->arcstat_prune.value.ui64 =
7538 wmsum_value(&arc_sums.arcstat_prune);
7539 as->arcstat_meta_used.value.ui64 =
7540 wmsum_value(&arc_sums.arcstat_meta_used);
7541 as->arcstat_async_upgrade_sync.value.ui64 =
7542 wmsum_value(&arc_sums.arcstat_async_upgrade_sync);
7543 as->arcstat_predictive_prefetch.value.ui64 =
7544 wmsum_value(&arc_sums.arcstat_predictive_prefetch);
7545 as->arcstat_demand_hit_predictive_prefetch.value.ui64 =
7546 wmsum_value(&arc_sums.arcstat_demand_hit_predictive_prefetch);
7547 as->arcstat_demand_iohit_predictive_prefetch.value.ui64 =
7548 wmsum_value(&arc_sums.arcstat_demand_iohit_predictive_prefetch);
7549 as->arcstat_prescient_prefetch.value.ui64 =
7550 wmsum_value(&arc_sums.arcstat_prescient_prefetch);
7551 as->arcstat_demand_hit_prescient_prefetch.value.ui64 =
7552 wmsum_value(&arc_sums.arcstat_demand_hit_prescient_prefetch);
7553 as->arcstat_demand_iohit_prescient_prefetch.value.ui64 =
7554 wmsum_value(&arc_sums.arcstat_demand_iohit_prescient_prefetch);
7555 as->arcstat_raw_size.value.ui64 =
7556 wmsum_value(&arc_sums.arcstat_raw_size);
7557 as->arcstat_cached_only_in_progress.value.ui64 =
7558 wmsum_value(&arc_sums.arcstat_cached_only_in_progress);
7559 as->arcstat_abd_chunk_waste_size.value.ui64 =
7560 wmsum_value(&arc_sums.arcstat_abd_chunk_waste_size);
7561
7562 return (0);
7563 }
7564
7565 /*
7566 * This function *must* return indices evenly distributed between all
7567 * sublists of the multilist. This is needed due to how the ARC eviction
7568 * code is laid out; arc_evict_state() assumes ARC buffers are evenly
7569 * distributed between all sublists and uses this assumption when
7570 * deciding which sublist to evict from and how much to evict from it.
7571 */
7572 static unsigned int
arc_state_multilist_index_func(multilist_t * ml,void * obj)7573 arc_state_multilist_index_func(multilist_t *ml, void *obj)
7574 {
7575 arc_buf_hdr_t *hdr = obj;
7576
7577 /*
7578 * We rely on b_dva to generate evenly distributed index
7579 * numbers using buf_hash below. So, as an added precaution,
7580 * let's make sure we never add empty buffers to the arc lists.
7581 */
7582 ASSERT(!HDR_EMPTY(hdr));
7583
7584 /*
7585 * The assumption here, is the hash value for a given
7586 * arc_buf_hdr_t will remain constant throughout its lifetime
7587 * (i.e. its b_spa, b_dva, and b_birth fields don't change).
7588 * Thus, we don't need to store the header's sublist index
7589 * on insertion, as this index can be recalculated on removal.
7590 *
7591 * Also, the low order bits of the hash value are thought to be
7592 * distributed evenly. Otherwise, in the case that the multilist
7593 * has a power of two number of sublists, each sublists' usage
7594 * would not be evenly distributed. In this context full 64bit
7595 * division would be a waste of time, so limit it to 32 bits.
7596 */
7597 return ((unsigned int)buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
7598 multilist_get_num_sublists(ml));
7599 }
7600
7601 static unsigned int
arc_state_l2c_multilist_index_func(multilist_t * ml,void * obj)7602 arc_state_l2c_multilist_index_func(multilist_t *ml, void *obj)
7603 {
7604 panic("Header %p insert into arc_l2c_only %p", obj, ml);
7605 }
7606
7607 #define WARN_IF_TUNING_IGNORED(tuning, value, do_warn) do { \
7608 if ((do_warn) && (tuning) && ((tuning) != (value))) { \
7609 cmn_err(CE_WARN, \
7610 "ignoring tunable %s (using %llu instead)", \
7611 (#tuning), (u_longlong_t)(value)); \
7612 } \
7613 } while (0)
7614
7615 /*
7616 * Called during module initialization and periodically thereafter to
7617 * apply reasonable changes to the exposed performance tunings. Can also be
7618 * called explicitly by param_set_arc_*() functions when ARC tunables are
7619 * updated manually. Non-zero zfs_* values which differ from the currently set
7620 * values will be applied.
7621 */
7622 void
arc_tuning_update(boolean_t verbose)7623 arc_tuning_update(boolean_t verbose)
7624 {
7625 uint64_t allmem = arc_all_memory();
7626
7627 /* Valid range: 32M - <arc_c_max> */
7628 if ((zfs_arc_min) && (zfs_arc_min != arc_c_min) &&
7629 (zfs_arc_min >= 2ULL << SPA_MAXBLOCKSHIFT) &&
7630 (zfs_arc_min <= arc_c_max)) {
7631 arc_c_min = zfs_arc_min;
7632 arc_c = MAX(arc_c, arc_c_min);
7633 }
7634 WARN_IF_TUNING_IGNORED(zfs_arc_min, arc_c_min, verbose);
7635
7636 /* Valid range: 64M - <all physical memory> */
7637 if ((zfs_arc_max) && (zfs_arc_max != arc_c_max) &&
7638 (zfs_arc_max >= MIN_ARC_MAX) && (zfs_arc_max < allmem) &&
7639 (zfs_arc_max > arc_c_min)) {
7640 arc_c_max = zfs_arc_max;
7641 arc_c = MIN(arc_c, arc_c_max);
7642 if (arc_dnode_limit > arc_c_max)
7643 arc_dnode_limit = arc_c_max;
7644 }
7645 WARN_IF_TUNING_IGNORED(zfs_arc_max, arc_c_max, verbose);
7646
7647 /* Valid range: 0 - <all physical memory> */
7648 arc_dnode_limit = zfs_arc_dnode_limit ? zfs_arc_dnode_limit :
7649 MIN(zfs_arc_dnode_limit_percent, 100) * arc_c_max / 100;
7650 WARN_IF_TUNING_IGNORED(zfs_arc_dnode_limit, arc_dnode_limit, verbose);
7651
7652 /* Valid range: 1 - N */
7653 if (zfs_arc_grow_retry)
7654 arc_grow_retry = zfs_arc_grow_retry;
7655
7656 /* Valid range: 1 - N */
7657 if (zfs_arc_shrink_shift) {
7658 arc_shrink_shift = zfs_arc_shrink_shift;
7659 zfs_arc_no_grow_shift = MIN(zfs_arc_no_grow_shift,
7660 arc_shrink_shift - 1);
7661 }
7662
7663 /* Valid range: 1 - N ms */
7664 if (zfs_arc_min_prefetch_ms)
7665 arc_min_prefetch = MSEC_TO_TICK(zfs_arc_min_prefetch_ms);
7666
7667 /* Valid range: 1 - N ms */
7668 if (zfs_arc_min_prescient_prefetch_ms) {
7669 arc_min_prescient_prefetch =
7670 MSEC_TO_TICK(zfs_arc_min_prescient_prefetch_ms);
7671 }
7672
7673 /* Valid range: 0 - 100 */
7674 if (zfs_arc_lotsfree_percent <= 100)
7675 arc_lotsfree_percent = zfs_arc_lotsfree_percent;
7676 WARN_IF_TUNING_IGNORED(zfs_arc_lotsfree_percent, arc_lotsfree_percent,
7677 verbose);
7678
7679 /* Valid range: 0 - <all physical memory> */
7680 if ((zfs_arc_sys_free) && (zfs_arc_sys_free != arc_sys_free))
7681 arc_sys_free = MIN(zfs_arc_sys_free, allmem);
7682 WARN_IF_TUNING_IGNORED(zfs_arc_sys_free, arc_sys_free, verbose);
7683 }
7684
7685 static void
arc_state_multilist_init(multilist_t * ml,multilist_sublist_index_func_t * index_func,int * maxcountp)7686 arc_state_multilist_init(multilist_t *ml,
7687 multilist_sublist_index_func_t *index_func, int *maxcountp)
7688 {
7689 multilist_create(ml, sizeof (arc_buf_hdr_t),
7690 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node), index_func);
7691 *maxcountp = MAX(*maxcountp, multilist_get_num_sublists(ml));
7692 }
7693
7694 static void
arc_state_init(void)7695 arc_state_init(void)
7696 {
7697 int num_sublists = 0;
7698
7699 arc_state_multilist_init(&arc_mru->arcs_list[ARC_BUFC_METADATA],
7700 arc_state_multilist_index_func, &num_sublists);
7701 arc_state_multilist_init(&arc_mru->arcs_list[ARC_BUFC_DATA],
7702 arc_state_multilist_index_func, &num_sublists);
7703 arc_state_multilist_init(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
7704 arc_state_multilist_index_func, &num_sublists);
7705 arc_state_multilist_init(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
7706 arc_state_multilist_index_func, &num_sublists);
7707 arc_state_multilist_init(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
7708 arc_state_multilist_index_func, &num_sublists);
7709 arc_state_multilist_init(&arc_mfu->arcs_list[ARC_BUFC_DATA],
7710 arc_state_multilist_index_func, &num_sublists);
7711 arc_state_multilist_init(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
7712 arc_state_multilist_index_func, &num_sublists);
7713 arc_state_multilist_init(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
7714 arc_state_multilist_index_func, &num_sublists);
7715 arc_state_multilist_init(&arc_uncached->arcs_list[ARC_BUFC_METADATA],
7716 arc_state_multilist_index_func, &num_sublists);
7717 arc_state_multilist_init(&arc_uncached->arcs_list[ARC_BUFC_DATA],
7718 arc_state_multilist_index_func, &num_sublists);
7719
7720 /*
7721 * L2 headers should never be on the L2 state list since they don't
7722 * have L1 headers allocated. Special index function asserts that.
7723 */
7724 arc_state_multilist_init(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
7725 arc_state_l2c_multilist_index_func, &num_sublists);
7726 arc_state_multilist_init(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
7727 arc_state_l2c_multilist_index_func, &num_sublists);
7728
7729 /*
7730 * Keep track of the number of markers needed to reclaim buffers from
7731 * any ARC state. The markers will be pre-allocated so as to minimize
7732 * the number of memory allocations performed by the eviction thread.
7733 */
7734 arc_state_evict_marker_count = num_sublists;
7735
7736 zfs_refcount_create(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
7737 zfs_refcount_create(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
7738 zfs_refcount_create(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
7739 zfs_refcount_create(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
7740 zfs_refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
7741 zfs_refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
7742 zfs_refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
7743 zfs_refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
7744 zfs_refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
7745 zfs_refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
7746 zfs_refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
7747 zfs_refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
7748 zfs_refcount_create(&arc_uncached->arcs_esize[ARC_BUFC_METADATA]);
7749 zfs_refcount_create(&arc_uncached->arcs_esize[ARC_BUFC_DATA]);
7750
7751 zfs_refcount_create(&arc_anon->arcs_size[ARC_BUFC_DATA]);
7752 zfs_refcount_create(&arc_anon->arcs_size[ARC_BUFC_METADATA]);
7753 zfs_refcount_create(&arc_mru->arcs_size[ARC_BUFC_DATA]);
7754 zfs_refcount_create(&arc_mru->arcs_size[ARC_BUFC_METADATA]);
7755 zfs_refcount_create(&arc_mru_ghost->arcs_size[ARC_BUFC_DATA]);
7756 zfs_refcount_create(&arc_mru_ghost->arcs_size[ARC_BUFC_METADATA]);
7757 zfs_refcount_create(&arc_mfu->arcs_size[ARC_BUFC_DATA]);
7758 zfs_refcount_create(&arc_mfu->arcs_size[ARC_BUFC_METADATA]);
7759 zfs_refcount_create(&arc_mfu_ghost->arcs_size[ARC_BUFC_DATA]);
7760 zfs_refcount_create(&arc_mfu_ghost->arcs_size[ARC_BUFC_METADATA]);
7761 zfs_refcount_create(&arc_l2c_only->arcs_size[ARC_BUFC_DATA]);
7762 zfs_refcount_create(&arc_l2c_only->arcs_size[ARC_BUFC_METADATA]);
7763 zfs_refcount_create(&arc_uncached->arcs_size[ARC_BUFC_DATA]);
7764 zfs_refcount_create(&arc_uncached->arcs_size[ARC_BUFC_METADATA]);
7765
7766 wmsum_init(&arc_mru_ghost->arcs_hits[ARC_BUFC_DATA], 0);
7767 wmsum_init(&arc_mru_ghost->arcs_hits[ARC_BUFC_METADATA], 0);
7768 wmsum_init(&arc_mfu_ghost->arcs_hits[ARC_BUFC_DATA], 0);
7769 wmsum_init(&arc_mfu_ghost->arcs_hits[ARC_BUFC_METADATA], 0);
7770
7771 wmsum_init(&arc_sums.arcstat_hits, 0);
7772 wmsum_init(&arc_sums.arcstat_iohits, 0);
7773 wmsum_init(&arc_sums.arcstat_misses, 0);
7774 wmsum_init(&arc_sums.arcstat_demand_data_hits, 0);
7775 wmsum_init(&arc_sums.arcstat_demand_data_iohits, 0);
7776 wmsum_init(&arc_sums.arcstat_demand_data_misses, 0);
7777 wmsum_init(&arc_sums.arcstat_demand_metadata_hits, 0);
7778 wmsum_init(&arc_sums.arcstat_demand_metadata_iohits, 0);
7779 wmsum_init(&arc_sums.arcstat_demand_metadata_misses, 0);
7780 wmsum_init(&arc_sums.arcstat_prefetch_data_hits, 0);
7781 wmsum_init(&arc_sums.arcstat_prefetch_data_iohits, 0);
7782 wmsum_init(&arc_sums.arcstat_prefetch_data_misses, 0);
7783 wmsum_init(&arc_sums.arcstat_prefetch_metadata_hits, 0);
7784 wmsum_init(&arc_sums.arcstat_prefetch_metadata_iohits, 0);
7785 wmsum_init(&arc_sums.arcstat_prefetch_metadata_misses, 0);
7786 wmsum_init(&arc_sums.arcstat_mru_hits, 0);
7787 wmsum_init(&arc_sums.arcstat_mru_ghost_hits, 0);
7788 wmsum_init(&arc_sums.arcstat_mfu_hits, 0);
7789 wmsum_init(&arc_sums.arcstat_mfu_ghost_hits, 0);
7790 wmsum_init(&arc_sums.arcstat_uncached_hits, 0);
7791 wmsum_init(&arc_sums.arcstat_deleted, 0);
7792 wmsum_init(&arc_sums.arcstat_mutex_miss, 0);
7793 wmsum_init(&arc_sums.arcstat_access_skip, 0);
7794 wmsum_init(&arc_sums.arcstat_evict_skip, 0);
7795 wmsum_init(&arc_sums.arcstat_evict_not_enough, 0);
7796 wmsum_init(&arc_sums.arcstat_evict_l2_cached, 0);
7797 wmsum_init(&arc_sums.arcstat_evict_l2_eligible, 0);
7798 wmsum_init(&arc_sums.arcstat_evict_l2_eligible_mfu, 0);
7799 wmsum_init(&arc_sums.arcstat_evict_l2_eligible_mru, 0);
7800 wmsum_init(&arc_sums.arcstat_evict_l2_ineligible, 0);
7801 wmsum_init(&arc_sums.arcstat_evict_l2_skip, 0);
7802 wmsum_init(&arc_sums.arcstat_hash_elements, 0);
7803 wmsum_init(&arc_sums.arcstat_hash_collisions, 0);
7804 wmsum_init(&arc_sums.arcstat_hash_chains, 0);
7805 aggsum_init(&arc_sums.arcstat_size, 0);
7806 wmsum_init(&arc_sums.arcstat_compressed_size, 0);
7807 wmsum_init(&arc_sums.arcstat_uncompressed_size, 0);
7808 wmsum_init(&arc_sums.arcstat_overhead_size, 0);
7809 wmsum_init(&arc_sums.arcstat_hdr_size, 0);
7810 wmsum_init(&arc_sums.arcstat_data_size, 0);
7811 wmsum_init(&arc_sums.arcstat_metadata_size, 0);
7812 wmsum_init(&arc_sums.arcstat_dbuf_size, 0);
7813 aggsum_init(&arc_sums.arcstat_dnode_size, 0);
7814 wmsum_init(&arc_sums.arcstat_bonus_size, 0);
7815 wmsum_init(&arc_sums.arcstat_l2_hits, 0);
7816 wmsum_init(&arc_sums.arcstat_l2_misses, 0);
7817 wmsum_init(&arc_sums.arcstat_l2_prefetch_asize, 0);
7818 wmsum_init(&arc_sums.arcstat_l2_mru_asize, 0);
7819 wmsum_init(&arc_sums.arcstat_l2_mfu_asize, 0);
7820 wmsum_init(&arc_sums.arcstat_l2_bufc_data_asize, 0);
7821 wmsum_init(&arc_sums.arcstat_l2_bufc_metadata_asize, 0);
7822 wmsum_init(&arc_sums.arcstat_l2_feeds, 0);
7823 wmsum_init(&arc_sums.arcstat_l2_rw_clash, 0);
7824 wmsum_init(&arc_sums.arcstat_l2_read_bytes, 0);
7825 wmsum_init(&arc_sums.arcstat_l2_write_bytes, 0);
7826 wmsum_init(&arc_sums.arcstat_l2_writes_sent, 0);
7827 wmsum_init(&arc_sums.arcstat_l2_writes_done, 0);
7828 wmsum_init(&arc_sums.arcstat_l2_writes_error, 0);
7829 wmsum_init(&arc_sums.arcstat_l2_writes_lock_retry, 0);
7830 wmsum_init(&arc_sums.arcstat_l2_evict_lock_retry, 0);
7831 wmsum_init(&arc_sums.arcstat_l2_evict_reading, 0);
7832 wmsum_init(&arc_sums.arcstat_l2_evict_l1cached, 0);
7833 wmsum_init(&arc_sums.arcstat_l2_free_on_write, 0);
7834 wmsum_init(&arc_sums.arcstat_l2_abort_lowmem, 0);
7835 wmsum_init(&arc_sums.arcstat_l2_cksum_bad, 0);
7836 wmsum_init(&arc_sums.arcstat_l2_io_error, 0);
7837 wmsum_init(&arc_sums.arcstat_l2_lsize, 0);
7838 wmsum_init(&arc_sums.arcstat_l2_psize, 0);
7839 aggsum_init(&arc_sums.arcstat_l2_hdr_size, 0);
7840 wmsum_init(&arc_sums.arcstat_l2_log_blk_writes, 0);
7841 wmsum_init(&arc_sums.arcstat_l2_log_blk_asize, 0);
7842 wmsum_init(&arc_sums.arcstat_l2_log_blk_count, 0);
7843 wmsum_init(&arc_sums.arcstat_l2_rebuild_success, 0);
7844 wmsum_init(&arc_sums.arcstat_l2_rebuild_abort_unsupported, 0);
7845 wmsum_init(&arc_sums.arcstat_l2_rebuild_abort_io_errors, 0);
7846 wmsum_init(&arc_sums.arcstat_l2_rebuild_abort_dh_errors, 0);
7847 wmsum_init(&arc_sums.arcstat_l2_rebuild_abort_cksum_lb_errors, 0);
7848 wmsum_init(&arc_sums.arcstat_l2_rebuild_abort_lowmem, 0);
7849 wmsum_init(&arc_sums.arcstat_l2_rebuild_size, 0);
7850 wmsum_init(&arc_sums.arcstat_l2_rebuild_asize, 0);
7851 wmsum_init(&arc_sums.arcstat_l2_rebuild_bufs, 0);
7852 wmsum_init(&arc_sums.arcstat_l2_rebuild_bufs_precached, 0);
7853 wmsum_init(&arc_sums.arcstat_l2_rebuild_log_blks, 0);
7854 wmsum_init(&arc_sums.arcstat_memory_throttle_count, 0);
7855 wmsum_init(&arc_sums.arcstat_memory_direct_count, 0);
7856 wmsum_init(&arc_sums.arcstat_memory_indirect_count, 0);
7857 wmsum_init(&arc_sums.arcstat_prune, 0);
7858 wmsum_init(&arc_sums.arcstat_meta_used, 0);
7859 wmsum_init(&arc_sums.arcstat_async_upgrade_sync, 0);
7860 wmsum_init(&arc_sums.arcstat_predictive_prefetch, 0);
7861 wmsum_init(&arc_sums.arcstat_demand_hit_predictive_prefetch, 0);
7862 wmsum_init(&arc_sums.arcstat_demand_iohit_predictive_prefetch, 0);
7863 wmsum_init(&arc_sums.arcstat_prescient_prefetch, 0);
7864 wmsum_init(&arc_sums.arcstat_demand_hit_prescient_prefetch, 0);
7865 wmsum_init(&arc_sums.arcstat_demand_iohit_prescient_prefetch, 0);
7866 wmsum_init(&arc_sums.arcstat_raw_size, 0);
7867 wmsum_init(&arc_sums.arcstat_cached_only_in_progress, 0);
7868 wmsum_init(&arc_sums.arcstat_abd_chunk_waste_size, 0);
7869
7870 arc_anon->arcs_state = ARC_STATE_ANON;
7871 arc_mru->arcs_state = ARC_STATE_MRU;
7872 arc_mru_ghost->arcs_state = ARC_STATE_MRU_GHOST;
7873 arc_mfu->arcs_state = ARC_STATE_MFU;
7874 arc_mfu_ghost->arcs_state = ARC_STATE_MFU_GHOST;
7875 arc_l2c_only->arcs_state = ARC_STATE_L2C_ONLY;
7876 arc_uncached->arcs_state = ARC_STATE_UNCACHED;
7877 }
7878
7879 static void
arc_state_fini(void)7880 arc_state_fini(void)
7881 {
7882 zfs_refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
7883 zfs_refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
7884 zfs_refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
7885 zfs_refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
7886 zfs_refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
7887 zfs_refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
7888 zfs_refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
7889 zfs_refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
7890 zfs_refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
7891 zfs_refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
7892 zfs_refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
7893 zfs_refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
7894 zfs_refcount_destroy(&arc_uncached->arcs_esize[ARC_BUFC_METADATA]);
7895 zfs_refcount_destroy(&arc_uncached->arcs_esize[ARC_BUFC_DATA]);
7896
7897 zfs_refcount_destroy(&arc_anon->arcs_size[ARC_BUFC_DATA]);
7898 zfs_refcount_destroy(&arc_anon->arcs_size[ARC_BUFC_METADATA]);
7899 zfs_refcount_destroy(&arc_mru->arcs_size[ARC_BUFC_DATA]);
7900 zfs_refcount_destroy(&arc_mru->arcs_size[ARC_BUFC_METADATA]);
7901 zfs_refcount_destroy(&arc_mru_ghost->arcs_size[ARC_BUFC_DATA]);
7902 zfs_refcount_destroy(&arc_mru_ghost->arcs_size[ARC_BUFC_METADATA]);
7903 zfs_refcount_destroy(&arc_mfu->arcs_size[ARC_BUFC_DATA]);
7904 zfs_refcount_destroy(&arc_mfu->arcs_size[ARC_BUFC_METADATA]);
7905 zfs_refcount_destroy(&arc_mfu_ghost->arcs_size[ARC_BUFC_DATA]);
7906 zfs_refcount_destroy(&arc_mfu_ghost->arcs_size[ARC_BUFC_METADATA]);
7907 zfs_refcount_destroy(&arc_l2c_only->arcs_size[ARC_BUFC_DATA]);
7908 zfs_refcount_destroy(&arc_l2c_only->arcs_size[ARC_BUFC_METADATA]);
7909 zfs_refcount_destroy(&arc_uncached->arcs_size[ARC_BUFC_DATA]);
7910 zfs_refcount_destroy(&arc_uncached->arcs_size[ARC_BUFC_METADATA]);
7911
7912 multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
7913 multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
7914 multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
7915 multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
7916 multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
7917 multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
7918 multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
7919 multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
7920 multilist_destroy(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA]);
7921 multilist_destroy(&arc_l2c_only->arcs_list[ARC_BUFC_DATA]);
7922 multilist_destroy(&arc_uncached->arcs_list[ARC_BUFC_METADATA]);
7923 multilist_destroy(&arc_uncached->arcs_list[ARC_BUFC_DATA]);
7924
7925 wmsum_fini(&arc_mru_ghost->arcs_hits[ARC_BUFC_DATA]);
7926 wmsum_fini(&arc_mru_ghost->arcs_hits[ARC_BUFC_METADATA]);
7927 wmsum_fini(&arc_mfu_ghost->arcs_hits[ARC_BUFC_DATA]);
7928 wmsum_fini(&arc_mfu_ghost->arcs_hits[ARC_BUFC_METADATA]);
7929
7930 wmsum_fini(&arc_sums.arcstat_hits);
7931 wmsum_fini(&arc_sums.arcstat_iohits);
7932 wmsum_fini(&arc_sums.arcstat_misses);
7933 wmsum_fini(&arc_sums.arcstat_demand_data_hits);
7934 wmsum_fini(&arc_sums.arcstat_demand_data_iohits);
7935 wmsum_fini(&arc_sums.arcstat_demand_data_misses);
7936 wmsum_fini(&arc_sums.arcstat_demand_metadata_hits);
7937 wmsum_fini(&arc_sums.arcstat_demand_metadata_iohits);
7938 wmsum_fini(&arc_sums.arcstat_demand_metadata_misses);
7939 wmsum_fini(&arc_sums.arcstat_prefetch_data_hits);
7940 wmsum_fini(&arc_sums.arcstat_prefetch_data_iohits);
7941 wmsum_fini(&arc_sums.arcstat_prefetch_data_misses);
7942 wmsum_fini(&arc_sums.arcstat_prefetch_metadata_hits);
7943 wmsum_fini(&arc_sums.arcstat_prefetch_metadata_iohits);
7944 wmsum_fini(&arc_sums.arcstat_prefetch_metadata_misses);
7945 wmsum_fini(&arc_sums.arcstat_mru_hits);
7946 wmsum_fini(&arc_sums.arcstat_mru_ghost_hits);
7947 wmsum_fini(&arc_sums.arcstat_mfu_hits);
7948 wmsum_fini(&arc_sums.arcstat_mfu_ghost_hits);
7949 wmsum_fini(&arc_sums.arcstat_uncached_hits);
7950 wmsum_fini(&arc_sums.arcstat_deleted);
7951 wmsum_fini(&arc_sums.arcstat_mutex_miss);
7952 wmsum_fini(&arc_sums.arcstat_access_skip);
7953 wmsum_fini(&arc_sums.arcstat_evict_skip);
7954 wmsum_fini(&arc_sums.arcstat_evict_not_enough);
7955 wmsum_fini(&arc_sums.arcstat_evict_l2_cached);
7956 wmsum_fini(&arc_sums.arcstat_evict_l2_eligible);
7957 wmsum_fini(&arc_sums.arcstat_evict_l2_eligible_mfu);
7958 wmsum_fini(&arc_sums.arcstat_evict_l2_eligible_mru);
7959 wmsum_fini(&arc_sums.arcstat_evict_l2_ineligible);
7960 wmsum_fini(&arc_sums.arcstat_evict_l2_skip);
7961 wmsum_fini(&arc_sums.arcstat_hash_elements);
7962 wmsum_fini(&arc_sums.arcstat_hash_collisions);
7963 wmsum_fini(&arc_sums.arcstat_hash_chains);
7964 aggsum_fini(&arc_sums.arcstat_size);
7965 wmsum_fini(&arc_sums.arcstat_compressed_size);
7966 wmsum_fini(&arc_sums.arcstat_uncompressed_size);
7967 wmsum_fini(&arc_sums.arcstat_overhead_size);
7968 wmsum_fini(&arc_sums.arcstat_hdr_size);
7969 wmsum_fini(&arc_sums.arcstat_data_size);
7970 wmsum_fini(&arc_sums.arcstat_metadata_size);
7971 wmsum_fini(&arc_sums.arcstat_dbuf_size);
7972 aggsum_fini(&arc_sums.arcstat_dnode_size);
7973 wmsum_fini(&arc_sums.arcstat_bonus_size);
7974 wmsum_fini(&arc_sums.arcstat_l2_hits);
7975 wmsum_fini(&arc_sums.arcstat_l2_misses);
7976 wmsum_fini(&arc_sums.arcstat_l2_prefetch_asize);
7977 wmsum_fini(&arc_sums.arcstat_l2_mru_asize);
7978 wmsum_fini(&arc_sums.arcstat_l2_mfu_asize);
7979 wmsum_fini(&arc_sums.arcstat_l2_bufc_data_asize);
7980 wmsum_fini(&arc_sums.arcstat_l2_bufc_metadata_asize);
7981 wmsum_fini(&arc_sums.arcstat_l2_feeds);
7982 wmsum_fini(&arc_sums.arcstat_l2_rw_clash);
7983 wmsum_fini(&arc_sums.arcstat_l2_read_bytes);
7984 wmsum_fini(&arc_sums.arcstat_l2_write_bytes);
7985 wmsum_fini(&arc_sums.arcstat_l2_writes_sent);
7986 wmsum_fini(&arc_sums.arcstat_l2_writes_done);
7987 wmsum_fini(&arc_sums.arcstat_l2_writes_error);
7988 wmsum_fini(&arc_sums.arcstat_l2_writes_lock_retry);
7989 wmsum_fini(&arc_sums.arcstat_l2_evict_lock_retry);
7990 wmsum_fini(&arc_sums.arcstat_l2_evict_reading);
7991 wmsum_fini(&arc_sums.arcstat_l2_evict_l1cached);
7992 wmsum_fini(&arc_sums.arcstat_l2_free_on_write);
7993 wmsum_fini(&arc_sums.arcstat_l2_abort_lowmem);
7994 wmsum_fini(&arc_sums.arcstat_l2_cksum_bad);
7995 wmsum_fini(&arc_sums.arcstat_l2_io_error);
7996 wmsum_fini(&arc_sums.arcstat_l2_lsize);
7997 wmsum_fini(&arc_sums.arcstat_l2_psize);
7998 aggsum_fini(&arc_sums.arcstat_l2_hdr_size);
7999 wmsum_fini(&arc_sums.arcstat_l2_log_blk_writes);
8000 wmsum_fini(&arc_sums.arcstat_l2_log_blk_asize);
8001 wmsum_fini(&arc_sums.arcstat_l2_log_blk_count);
8002 wmsum_fini(&arc_sums.arcstat_l2_rebuild_success);
8003 wmsum_fini(&arc_sums.arcstat_l2_rebuild_abort_unsupported);
8004 wmsum_fini(&arc_sums.arcstat_l2_rebuild_abort_io_errors);
8005 wmsum_fini(&arc_sums.arcstat_l2_rebuild_abort_dh_errors);
8006 wmsum_fini(&arc_sums.arcstat_l2_rebuild_abort_cksum_lb_errors);
8007 wmsum_fini(&arc_sums.arcstat_l2_rebuild_abort_lowmem);
8008 wmsum_fini(&arc_sums.arcstat_l2_rebuild_size);
8009 wmsum_fini(&arc_sums.arcstat_l2_rebuild_asize);
8010 wmsum_fini(&arc_sums.arcstat_l2_rebuild_bufs);
8011 wmsum_fini(&arc_sums.arcstat_l2_rebuild_bufs_precached);
8012 wmsum_fini(&arc_sums.arcstat_l2_rebuild_log_blks);
8013 wmsum_fini(&arc_sums.arcstat_memory_throttle_count);
8014 wmsum_fini(&arc_sums.arcstat_memory_direct_count);
8015 wmsum_fini(&arc_sums.arcstat_memory_indirect_count);
8016 wmsum_fini(&arc_sums.arcstat_prune);
8017 wmsum_fini(&arc_sums.arcstat_meta_used);
8018 wmsum_fini(&arc_sums.arcstat_async_upgrade_sync);
8019 wmsum_fini(&arc_sums.arcstat_predictive_prefetch);
8020 wmsum_fini(&arc_sums.arcstat_demand_hit_predictive_prefetch);
8021 wmsum_fini(&arc_sums.arcstat_demand_iohit_predictive_prefetch);
8022 wmsum_fini(&arc_sums.arcstat_prescient_prefetch);
8023 wmsum_fini(&arc_sums.arcstat_demand_hit_prescient_prefetch);
8024 wmsum_fini(&arc_sums.arcstat_demand_iohit_prescient_prefetch);
8025 wmsum_fini(&arc_sums.arcstat_raw_size);
8026 wmsum_fini(&arc_sums.arcstat_cached_only_in_progress);
8027 wmsum_fini(&arc_sums.arcstat_abd_chunk_waste_size);
8028 }
8029
8030 uint64_t
arc_target_bytes(void)8031 arc_target_bytes(void)
8032 {
8033 return (arc_c);
8034 }
8035
8036 /*
8037 * Byte budget for a single explicit (user) prefetch request, e.g.
8038 * POSIX_FADV_WILLNEED. Follows the adaptive ARC target (arc_c) once the cache
8039 * is warm, but while cold -- when arc_c still sits near arc_c_min -- uses the
8040 * midpoint toward arc_c_max so a hint issued right after boot is not starved.
8041 * The caller applies the fraction that may be outstanding at once.
8042 */
8043 uint64_t
arc_boot_target_bytes(void)8044 arc_boot_target_bytes(void)
8045 {
8046 return (arc_warm ? arc_c : (arc_c + arc_c_max) / 2);
8047 }
8048
8049 void
arc_set_limits(uint64_t allmem)8050 arc_set_limits(uint64_t allmem)
8051 {
8052 /* Set min cache to 1/32 of all memory, or 32MB, whichever is more. */
8053 arc_c_min = MAX(allmem / 32, 2ULL << SPA_MAXBLOCKSHIFT);
8054
8055 /* How to set default max varies by platform. */
8056 arc_c_max = arc_default_max(arc_c_min, allmem);
8057 }
8058
8059 void
arc_init(void)8060 arc_init(void)
8061 {
8062 uint64_t percent, allmem = arc_all_memory();
8063 mutex_init(&arc_evict_lock, NULL, MUTEX_DEFAULT, NULL);
8064 list_create(&arc_evict_waiters, sizeof (arc_evict_waiter_t),
8065 offsetof(arc_evict_waiter_t, aew_node));
8066
8067 arc_min_prefetch = MSEC_TO_TICK(1000);
8068 arc_min_prescient_prefetch = MSEC_TO_TICK(6000);
8069
8070 #if defined(_KERNEL)
8071 arc_lowmem_init();
8072 #endif
8073
8074 arc_set_limits(allmem);
8075
8076 #ifdef _KERNEL
8077 /*
8078 * If zfs_arc_max is non-zero at init, meaning it was set in the kernel
8079 * environment before the module was loaded, don't block setting the
8080 * maximum because it is less than arc_c_min, instead, reset arc_c_min
8081 * to a lower value.
8082 * zfs_arc_min will be handled by arc_tuning_update().
8083 */
8084 if (zfs_arc_max != 0 && zfs_arc_max >= MIN_ARC_MAX &&
8085 zfs_arc_max < allmem) {
8086 arc_c_max = zfs_arc_max;
8087 if (arc_c_min >= arc_c_max) {
8088 arc_c_min = MAX(zfs_arc_max / 2,
8089 2ULL << SPA_MAXBLOCKSHIFT);
8090 }
8091 }
8092 #else
8093 /*
8094 * In userland, there's only the memory pressure that we artificially
8095 * create (see arc_available_memory()). Don't let arc_c get too
8096 * small, because it can cause transactions to be larger than
8097 * arc_c, causing arc_tempreserve_space() to fail.
8098 */
8099 arc_c_min = MAX(arc_c_max / 2, 2ULL << SPA_MAXBLOCKSHIFT);
8100 #endif
8101
8102 arc_c = arc_c_min;
8103 /*
8104 * 32-bit fixed point fractions of metadata from total ARC size,
8105 * MRU data from all data and MRU metadata from all metadata.
8106 */
8107 arc_meta = (1ULL << 32) / 4; /* Metadata is 25% of arc_c. */
8108 arc_pd = (1ULL << 32) / 2; /* Data MRU is 50% of data. */
8109 arc_pm = (1ULL << 32) / 2; /* Metadata MRU is 50% of metadata. */
8110
8111 percent = MIN(zfs_arc_dnode_limit_percent, 100);
8112 arc_dnode_limit = arc_c_max * percent / 100;
8113
8114 /* Apply user specified tunings */
8115 arc_tuning_update(B_TRUE);
8116
8117 /* if kmem_flags are set, lets try to use less memory */
8118 if (kmem_debugging())
8119 arc_c = arc_c / 2;
8120 if (arc_c < arc_c_min)
8121 arc_c = arc_c_min;
8122
8123 arc_register_hotplug();
8124
8125 arc_state_init();
8126
8127 buf_init();
8128
8129 list_create(&arc_prune_list, sizeof (arc_prune_t),
8130 offsetof(arc_prune_t, p_node));
8131 mutex_init(&arc_prune_mtx, NULL, MUTEX_DEFAULT, NULL);
8132
8133 arc_prune_taskq = taskq_create("arc_prune", zfs_arc_prune_task_threads,
8134 defclsyspri, 100, INT_MAX, TASKQ_PREPOPULATE | TASKQ_DYNAMIC);
8135
8136 arc_evict_thread_init();
8137
8138 list_create(&arc_async_flush_list, sizeof (arc_async_flush_t),
8139 offsetof(arc_async_flush_t, af_node));
8140 mutex_init(&arc_async_flush_lock, NULL, MUTEX_DEFAULT, NULL);
8141 arc_flush_taskq = taskq_create("arc_flush", MIN(boot_ncpus, 4),
8142 defclsyspri, 1, INT_MAX, TASKQ_DYNAMIC);
8143
8144 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
8145 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
8146
8147 if (arc_ksp != NULL) {
8148 arc_ksp->ks_data = &arc_stats;
8149 arc_ksp->ks_update = arc_kstat_update;
8150 kstat_install(arc_ksp);
8151 }
8152
8153 arc_state_evict_markers =
8154 arc_state_alloc_markers(arc_state_evict_marker_count);
8155 arc_evict_zthr = zthr_create_timer("arc_evict",
8156 arc_evict_cb_check, arc_evict_cb, NULL, SEC2NSEC(1), defclsyspri);
8157 arc_reap_zthr = zthr_create_timer("arc_reap",
8158 arc_reap_cb_check, arc_reap_cb, NULL, SEC2NSEC(1), minclsyspri);
8159
8160 arc_warm = B_FALSE;
8161
8162 /*
8163 * Calculate maximum amount of dirty data per pool.
8164 *
8165 * If it has been set by a module parameter, take that.
8166 * Otherwise, use a percentage of physical memory defined by
8167 * zfs_dirty_data_max_percent (default 10%) with a cap at
8168 * zfs_dirty_data_max_max (default 4G or 25% of physical memory).
8169 */
8170 #ifdef __LP64__
8171 if (zfs_dirty_data_max_max == 0)
8172 zfs_dirty_data_max_max = MIN(4ULL * 1024 * 1024 * 1024,
8173 allmem * zfs_dirty_data_max_max_percent / 100);
8174 #else
8175 if (zfs_dirty_data_max_max == 0)
8176 zfs_dirty_data_max_max = MIN(1ULL * 1024 * 1024 * 1024,
8177 allmem * zfs_dirty_data_max_max_percent / 100);
8178 #endif
8179
8180 if (zfs_dirty_data_max == 0) {
8181 zfs_dirty_data_max = allmem *
8182 zfs_dirty_data_max_percent / 100;
8183 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
8184 zfs_dirty_data_max_max);
8185 }
8186
8187 if (zfs_wrlog_data_max == 0) {
8188
8189 /*
8190 * dp_wrlog_total is reduced for each txg at the end of
8191 * spa_sync(). However, dp_dirty_total is reduced every time
8192 * a block is written out. Thus under normal operation,
8193 * dp_wrlog_total could grow 2 times as big as
8194 * zfs_dirty_data_max.
8195 */
8196 zfs_wrlog_data_max = zfs_dirty_data_max * 2;
8197 }
8198 }
8199
8200 void
arc_fini(void)8201 arc_fini(void)
8202 {
8203 arc_prune_t *p;
8204
8205 #ifdef _KERNEL
8206 arc_lowmem_fini();
8207 #endif /* _KERNEL */
8208
8209 /* Wait for any background flushes */
8210 taskq_wait(arc_flush_taskq);
8211 taskq_destroy(arc_flush_taskq);
8212
8213 /* Use B_TRUE to ensure *all* buffers are evicted */
8214 arc_flush(NULL, B_TRUE);
8215
8216 if (arc_ksp != NULL) {
8217 kstat_delete(arc_ksp);
8218 arc_ksp = NULL;
8219 }
8220
8221 taskq_wait(arc_prune_taskq);
8222 taskq_destroy(arc_prune_taskq);
8223
8224 list_destroy(&arc_async_flush_list);
8225 mutex_destroy(&arc_async_flush_lock);
8226
8227 mutex_enter(&arc_prune_mtx);
8228 while ((p = list_remove_head(&arc_prune_list)) != NULL) {
8229 (void) zfs_refcount_remove(&p->p_refcnt, &arc_prune_list);
8230 zfs_refcount_destroy(&p->p_refcnt);
8231 kmem_free(p, sizeof (*p));
8232 }
8233 mutex_exit(&arc_prune_mtx);
8234
8235 list_destroy(&arc_prune_list);
8236 mutex_destroy(&arc_prune_mtx);
8237
8238 if (arc_evict_taskq != NULL)
8239 taskq_wait(arc_evict_taskq);
8240
8241 (void) zthr_cancel(arc_evict_zthr);
8242 (void) zthr_cancel(arc_reap_zthr);
8243 arc_state_free_markers(arc_state_evict_markers,
8244 arc_state_evict_marker_count);
8245
8246 if (arc_evict_taskq != NULL) {
8247 taskq_destroy(arc_evict_taskq);
8248 kmem_free(arc_evict_arg,
8249 sizeof (evict_arg_t) * zfs_arc_evict_threads);
8250 }
8251
8252 mutex_destroy(&arc_evict_lock);
8253 list_destroy(&arc_evict_waiters);
8254
8255 /*
8256 * Free any buffers that were tagged for destruction. This needs
8257 * to occur before arc_state_fini() runs and destroys the aggsum
8258 * values which are updated when freeing scatter ABDs.
8259 * Pass NULL to free all ABDs regardless of device.
8260 */
8261 l2arc_do_free_on_write(NULL);
8262
8263 /*
8264 * buf_fini() must proceed arc_state_fini() because buf_fin() may
8265 * trigger the release of kmem magazines, which can callback to
8266 * arc_space_return() which accesses aggsums freed in act_state_fini().
8267 */
8268 buf_fini();
8269 arc_state_fini();
8270
8271 arc_unregister_hotplug();
8272
8273 /*
8274 * We destroy the zthrs after all the ARC state has been
8275 * torn down to avoid the case of them receiving any
8276 * wakeup() signals after they are destroyed.
8277 */
8278 zthr_destroy(arc_evict_zthr);
8279 zthr_destroy(arc_reap_zthr);
8280
8281 ASSERT0(arc_loaned_bytes);
8282 }
8283
8284 /*
8285 * Level 2 ARC
8286 *
8287 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
8288 * It uses dedicated storage devices to hold cached data, which are populated
8289 * using large infrequent writes. The main role of this cache is to boost
8290 * the performance of random read workloads. The intended L2ARC devices
8291 * include short-stroked disks, solid state disks, and other media with
8292 * substantially faster read latency than disk.
8293 *
8294 * +-----------------------+
8295 * | ARC |
8296 * +-----------------------+
8297 * | ^ ^
8298 * | | |
8299 * l2arc_feed_thread() arc_read()
8300 * | | |
8301 * | l2arc read |
8302 * V | |
8303 * +---------------+ |
8304 * | L2ARC | |
8305 * +---------------+ |
8306 * | ^ |
8307 * l2arc_write() | |
8308 * | | |
8309 * V | |
8310 * +-------+ +-------+
8311 * | vdev | | vdev |
8312 * | cache | | cache |
8313 * +-------+ +-------+
8314 * +=========+ .-----.
8315 * : L2ARC : |-_____-|
8316 * : devices : | Disks |
8317 * +=========+ `-_____-'
8318 *
8319 * Read requests are satisfied from the following sources, in order:
8320 *
8321 * 1) ARC
8322 * 2) vdev cache of L2ARC devices
8323 * 3) L2ARC devices
8324 * 4) vdev cache of disks
8325 * 5) disks
8326 *
8327 * Some L2ARC device types exhibit extremely slow write performance.
8328 * To accommodate for this there are some significant differences between
8329 * the L2ARC and traditional cache design:
8330 *
8331 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
8332 * the ARC behave as usual, freeing buffers and placing headers on ghost
8333 * lists. The ARC does not send buffers to the L2ARC during eviction as
8334 * this would add inflated write latencies for all ARC memory pressure.
8335 *
8336 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
8337 * It does this by periodically scanning buffers from the eviction-end of
8338 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
8339 * not already there. It scans until a headroom of buffers is satisfied,
8340 * which itself is a buffer for ARC eviction. If a compressible buffer is
8341 * found during scanning and selected for writing to an L2ARC device, we
8342 * temporarily boost scanning headroom during the next scan cycle to make
8343 * sure we adapt to compression effects (which might significantly reduce
8344 * the data volume we write to L2ARC). The thread that does this is
8345 * l2arc_feed_thread(), illustrated below; example sizes are included to
8346 * provide a better sense of ratio than this diagram:
8347 *
8348 * head --> tail
8349 * +---------------------+----------+
8350 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
8351 * +---------------------+----------+ | o L2ARC eligible
8352 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
8353 * +---------------------+----------+ |
8354 * 15.9 Gbytes ^ 32 Mbytes |
8355 * headroom |
8356 * l2arc_feed_thread()
8357 * |
8358 * l2arc write hand <--[oooo]--'
8359 * | 8 Mbyte
8360 * | write max
8361 * V
8362 * +==============================+
8363 * L2ARC dev |####|#|###|###| |####| ... |
8364 * +==============================+
8365 * 32 Gbytes
8366 *
8367 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
8368 * evicted, then the L2ARC has cached a buffer much sooner than it probably
8369 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
8370 * safe to say that this is an uncommon case, since buffers at the end of
8371 * the ARC lists have moved there due to inactivity.
8372 *
8373 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
8374 * then the L2ARC simply misses copying some buffers. This serves as a
8375 * pressure valve to prevent heavy read workloads from both stalling the ARC
8376 * with waits and clogging the L2ARC with writes. This also helps prevent
8377 * the potential for the L2ARC to churn if it attempts to cache content too
8378 * quickly, such as during backups of the entire pool.
8379 *
8380 * 5. After system boot and before the ARC has filled main memory, there are
8381 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
8382 * lists can remain mostly static. Instead of searching from tail of these
8383 * lists as pictured, the l2arc_feed_thread() will search from the list heads
8384 * for eligible buffers, greatly increasing its chance of finding them.
8385 *
8386 * The L2ARC device write speed is also boosted during this time so that
8387 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
8388 * there are no L2ARC reads, and no fear of degrading read performance
8389 * through increased writes.
8390 *
8391 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
8392 * the vdev queue can aggregate them into larger and fewer writes. Each
8393 * device is written to in a rotor fashion, sweeping writes through
8394 * available space then repeating.
8395 *
8396 * 7. The L2ARC does not store dirty content. It never needs to flush
8397 * write buffers back to disk based storage.
8398 *
8399 * 8. If an ARC buffer is written (and dirtied) which also exists in the
8400 * L2ARC, the now stale L2ARC buffer is immediately dropped.
8401 *
8402 * The performance of the L2ARC can be tweaked by a number of tunables, which
8403 * may be necessary for different workloads:
8404 *
8405 * l2arc_write_max max write bytes per interval
8406 * l2arc_dwpd_limit device write endurance limit (100 = 1.0 DWPD)
8407 * l2arc_noprefetch skip caching prefetched buffers
8408 * l2arc_headroom number of max device writes to precache
8409 * l2arc_headroom_boost when we find compressed buffers during ARC
8410 * scanning, we multiply headroom by this
8411 * percentage factor for the next scan cycle,
8412 * since more compressed buffers are likely to
8413 * be present
8414 * l2arc_feed_secs seconds between L2ARC writing
8415 *
8416 * Tunables may be removed or added as future performance improvements are
8417 * integrated, and also may become zpool properties.
8418 *
8419 * There are three key functions that control how the L2ARC warms up:
8420 *
8421 * l2arc_write_eligible() check if a buffer is eligible to cache
8422 * l2arc_write_size() calculate how much to write
8423 *
8424 * These three functions determine what to write, how much, and how quickly
8425 * to send writes.
8426 *
8427 * L2ARC persistence:
8428 *
8429 * When writing buffers to L2ARC, we periodically add some metadata to
8430 * make sure we can pick them up after reboot, thus dramatically reducing
8431 * the impact that any downtime has on the performance of storage systems
8432 * with large caches.
8433 *
8434 * The implementation works fairly simply by integrating the following two
8435 * modifications:
8436 *
8437 * *) When writing to the L2ARC, we occasionally write a "l2arc log block",
8438 * which is an additional piece of metadata which describes what's been
8439 * written. This allows us to rebuild the arc_buf_hdr_t structures of the
8440 * main ARC buffers. There are 2 linked-lists of log blocks headed by
8441 * dh_start_lbps[2]. We alternate which chain we append to, so they are
8442 * time-wise and offset-wise interleaved, but that is an optimization rather
8443 * than for correctness. The log block also includes a pointer to the
8444 * previous block in its chain.
8445 *
8446 * *) We reserve SPA_MINBLOCKSIZE of space at the start of each L2ARC device
8447 * for our header bookkeeping purposes. This contains a device header,
8448 * which contains our top-level reference structures. We update it each
8449 * time we write a new log block, so that we're able to locate it in the
8450 * L2ARC device. If this write results in an inconsistent device header
8451 * (e.g. due to power failure), we detect this by verifying the header's
8452 * checksum and simply fail to reconstruct the L2ARC after reboot.
8453 *
8454 * Implementation diagram:
8455 *
8456 * +=== L2ARC device (not to scale) ======================================+
8457 * | ___two newest log block pointers__.__________ |
8458 * | / \dh_start_lbps[1] |
8459 * | / \ \dh_start_lbps[0]|
8460 * |.___/__. V V |
8461 * ||L2 dev|....|lb |bufs |lb |bufs |lb |bufs |lb |bufs |lb |---(empty)---|
8462 * || hdr| ^ /^ /^ / / |
8463 * |+------+ ...--\-------/ \-----/--\------/ / |
8464 * | \--------------/ \--------------/ |
8465 * +======================================================================+
8466 *
8467 * As can be seen on the diagram, rather than using a simple linked list,
8468 * we use a pair of linked lists with alternating elements. This is a
8469 * performance enhancement due to the fact that we only find out the
8470 * address of the next log block access once the current block has been
8471 * completely read in. Obviously, this hurts performance, because we'd be
8472 * keeping the device's I/O queue at only a 1 operation deep, thus
8473 * incurring a large amount of I/O round-trip latency. Having two lists
8474 * allows us to fetch two log blocks ahead of where we are currently
8475 * rebuilding L2ARC buffers.
8476 *
8477 * On-device data structures:
8478 *
8479 * L2ARC device header: l2arc_dev_hdr_phys_t
8480 * L2ARC log block: l2arc_log_blk_phys_t
8481 *
8482 * L2ARC reconstruction:
8483 *
8484 * When writing data, we simply write in the standard rotary fashion,
8485 * evicting buffers as we go and simply writing new data over them (writing
8486 * a new log block every now and then). This obviously means that once we
8487 * loop around the end of the device, we will start cutting into an already
8488 * committed log block (and its referenced data buffers), like so:
8489 *
8490 * current write head__ __old tail
8491 * \ /
8492 * V V
8493 * <--|bufs |lb |bufs |lb | |bufs |lb |bufs |lb |-->
8494 * ^ ^^^^^^^^^___________________________________
8495 * | \
8496 * <<nextwrite>> may overwrite this blk and/or its bufs --'
8497 *
8498 * When importing the pool, we detect this situation and use it to stop
8499 * our scanning process (see l2arc_rebuild).
8500 *
8501 * There is one significant caveat to consider when rebuilding ARC contents
8502 * from an L2ARC device: what about invalidated buffers? Given the above
8503 * construction, we cannot update blocks which we've already written to amend
8504 * them to remove buffers which were invalidated. Thus, during reconstruction,
8505 * we might be populating the cache with buffers for data that's not on the
8506 * main pool anymore, or may have been overwritten!
8507 *
8508 * As it turns out, this isn't a problem. Every arc_read request includes
8509 * both the DVA and, crucially, the birth TXG of the BP the caller is
8510 * looking for. So even if the cache were populated by completely rotten
8511 * blocks for data that had been long deleted and/or overwritten, we'll
8512 * never actually return bad data from the cache, since the DVA with the
8513 * birth TXG uniquely identify a block in space and time - once created,
8514 * a block is immutable on disk. The worst thing we have done is wasted
8515 * some time and memory at l2arc rebuild to reconstruct outdated ARC
8516 * entries that will get dropped from the l2arc as it is being updated
8517 * with new blocks.
8518 *
8519 * L2ARC buffers that have been evicted by l2arc_evict() ahead of the write
8520 * hand are not restored. This is done by saving the offset (in bytes)
8521 * l2arc_evict() has evicted to in the L2ARC device header and taking it
8522 * into account when restoring buffers.
8523 */
8524
8525 static boolean_t
l2arc_write_eligible(uint64_t spa_guid,arc_buf_hdr_t * hdr)8526 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
8527 {
8528 /*
8529 * A buffer is *not* eligible for the L2ARC if it:
8530 * 1. belongs to a different spa.
8531 * 2. is already cached on the L2ARC.
8532 * 3. has an I/O in progress (it may be an incomplete read).
8533 * 4. is flagged not eligible (zfs property).
8534 */
8535 if (hdr->b_spa != spa_guid || HDR_HAS_L2HDR(hdr) ||
8536 HDR_IO_IN_PROGRESS(hdr) || !HDR_L2CACHE(hdr))
8537 return (B_FALSE);
8538
8539 return (B_TRUE);
8540 }
8541
8542 static uint64_t
l2arc_write_size(l2arc_dev_t * dev,clock_t * interval)8543 l2arc_write_size(l2arc_dev_t *dev, clock_t *interval)
8544 {
8545 uint64_t size;
8546 uint64_t write_rate = l2arc_get_write_rate(dev);
8547
8548 if (write_rate > L2ARC_BURST_SIZE_MAX) {
8549 /* Calculate interval to achieve desired rate with burst cap */
8550 uint64_t feeds_per_sec =
8551 MAX(DIV_ROUND_UP(write_rate, L2ARC_BURST_SIZE_MAX), 1);
8552 *interval = hz / feeds_per_sec;
8553 size = write_rate / feeds_per_sec;
8554 } else {
8555 *interval = hz; /* 1 second default */
8556 size = write_rate;
8557 }
8558
8559 /* We need to add in the worst case scenario of log block overhead. */
8560 size += l2arc_log_blk_overhead(size, dev);
8561 if (dev->l2ad_vdev->vdev_has_trim && l2arc_trim_ahead > 0) {
8562 /*
8563 * Trim ahead of the write size 64MB or (l2arc_trim_ahead/100)
8564 * times the writesize, whichever is greater.
8565 */
8566 size += MAX(64 * 1024 * 1024,
8567 (size * l2arc_trim_ahead) / 100);
8568 }
8569
8570 /*
8571 * Make sure the write size does not exceed the size of the cache
8572 * device. This is important in l2arc_evict(), otherwise infinite
8573 * iteration can occur.
8574 */
8575 size = MIN(size, (dev->l2ad_end - dev->l2ad_start) / 4);
8576
8577 size = P2ROUNDUP(size, 1ULL << dev->l2ad_vdev->vdev_ashift);
8578
8579 return (size);
8580
8581 }
8582
8583 /*
8584 * Free buffers that were tagged for destruction.
8585 */
8586 static void
l2arc_do_free_on_write(l2arc_dev_t * dev)8587 l2arc_do_free_on_write(l2arc_dev_t *dev)
8588 {
8589 l2arc_data_free_t *df, *df_next;
8590 boolean_t all = (dev == NULL);
8591
8592 mutex_enter(&l2arc_free_on_write_mtx);
8593 df = list_head(l2arc_free_on_write);
8594 while (df != NULL) {
8595 df_next = list_next(l2arc_free_on_write, df);
8596 if (all || df->l2df_dev == dev) {
8597 list_remove(l2arc_free_on_write, df);
8598 ASSERT3P(df->l2df_abd, !=, NULL);
8599 abd_free(df->l2df_abd);
8600 kmem_free(df, sizeof (l2arc_data_free_t));
8601 }
8602 df = df_next;
8603 }
8604 mutex_exit(&l2arc_free_on_write_mtx);
8605 }
8606
8607 /*
8608 * A write to a cache device has completed. Update all headers to allow
8609 * reads from these buffers to begin.
8610 */
8611 static void
l2arc_write_done(zio_t * zio)8612 l2arc_write_done(zio_t *zio)
8613 {
8614 l2arc_write_callback_t *cb;
8615 l2arc_lb_abd_buf_t *abd_buf;
8616 l2arc_lb_ptr_buf_t *lb_ptr_buf;
8617 l2arc_dev_t *dev;
8618 l2arc_dev_hdr_phys_t *l2dhdr;
8619 list_t *buflist;
8620 arc_buf_hdr_t *head, *hdr, *hdr_prev;
8621 kmutex_t *hash_lock;
8622 int64_t bytes_dropped = 0;
8623
8624 cb = zio->io_private;
8625 ASSERT3P(cb, !=, NULL);
8626 dev = cb->l2wcb_dev;
8627 l2dhdr = dev->l2ad_dev_hdr;
8628 ASSERT3P(dev, !=, NULL);
8629 head = cb->l2wcb_head;
8630 ASSERT3P(head, !=, NULL);
8631 buflist = &dev->l2ad_buflist;
8632 ASSERT3P(buflist, !=, NULL);
8633 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
8634 l2arc_write_callback_t *, cb);
8635
8636 /*
8637 * All writes completed, or an error was hit.
8638 */
8639 top:
8640 mutex_enter(&dev->l2ad_mtx);
8641 for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
8642 hdr_prev = list_prev(buflist, hdr);
8643
8644 hash_lock = HDR_LOCK(hdr);
8645
8646 /*
8647 * We cannot use mutex_enter or else we can deadlock
8648 * with l2arc_write_buffers (due to swapping the order
8649 * the hash lock and l2ad_mtx are taken).
8650 */
8651 if (!mutex_tryenter(hash_lock)) {
8652 /*
8653 * Missed the hash lock. We must retry so we
8654 * don't leave the ARC_FLAG_L2_WRITING bit set.
8655 */
8656 ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
8657
8658 /*
8659 * We don't want to rescan the headers we've
8660 * already marked as having been written out, so
8661 * we reinsert the head node so we can pick up
8662 * where we left off.
8663 */
8664 list_remove(buflist, head);
8665 list_insert_after(buflist, hdr, head);
8666
8667 mutex_exit(&dev->l2ad_mtx);
8668
8669 /*
8670 * We wait for the hash lock to become available
8671 * to try and prevent busy waiting, and increase
8672 * the chance we'll be able to acquire the lock
8673 * the next time around.
8674 */
8675 mutex_enter(hash_lock);
8676 mutex_exit(hash_lock);
8677 goto top;
8678 }
8679
8680 /*
8681 * We could not have been moved into the arc_l2c_only
8682 * state while in-flight due to our ARC_FLAG_L2_WRITING
8683 * bit being set. Let's just ensure that's being enforced.
8684 */
8685 ASSERT(HDR_HAS_L1HDR(hdr));
8686
8687 /*
8688 * Skipped - drop L2ARC entry and mark the header as no
8689 * longer L2 eligibile.
8690 */
8691 if (zio->io_error != 0) {
8692 /*
8693 * Error - drop L2ARC entry.
8694 */
8695 list_remove(buflist, hdr);
8696 arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
8697
8698 uint64_t psize = HDR_GET_PSIZE(hdr);
8699 l2arc_hdr_arcstats_decrement(hdr);
8700
8701 ASSERT(dev->l2ad_vdev != NULL);
8702
8703 bytes_dropped +=
8704 vdev_psize_to_asize(dev->l2ad_vdev, psize);
8705 (void) zfs_refcount_remove_many(&dev->l2ad_alloc,
8706 arc_hdr_size(hdr), hdr);
8707 }
8708
8709 /*
8710 * Allow ARC to begin reads and ghost list evictions to
8711 * this L2ARC entry.
8712 */
8713 arc_hdr_clear_flags(hdr, ARC_FLAG_L2_WRITING);
8714
8715 mutex_exit(hash_lock);
8716 }
8717
8718 /*
8719 * Free the allocated abd buffers for writing the log blocks.
8720 * If the zio failed reclaim the allocated space and remove the
8721 * pointers to these log blocks from the log block pointer list
8722 * of the L2ARC device.
8723 */
8724 while ((abd_buf = list_remove_tail(&cb->l2wcb_abd_list)) != NULL) {
8725 abd_free(abd_buf->abd);
8726 zio_buf_free(abd_buf, sizeof (*abd_buf));
8727 if (zio->io_error != 0) {
8728 lb_ptr_buf = list_remove_head(&dev->l2ad_lbptr_list);
8729 /*
8730 * L2BLK_GET_PSIZE returns aligned size for log
8731 * blocks.
8732 */
8733 uint64_t asize =
8734 L2BLK_GET_PSIZE((lb_ptr_buf->lb_ptr)->lbp_prop);
8735 bytes_dropped += asize;
8736 ARCSTAT_INCR(arcstat_l2_log_blk_asize, -asize);
8737 ARCSTAT_BUMPDOWN(arcstat_l2_log_blk_count);
8738 zfs_refcount_remove_many(&dev->l2ad_lb_asize, asize,
8739 lb_ptr_buf);
8740 (void) zfs_refcount_remove(&dev->l2ad_lb_count,
8741 lb_ptr_buf);
8742 kmem_free(lb_ptr_buf->lb_ptr,
8743 sizeof (l2arc_log_blkptr_t));
8744 kmem_free(lb_ptr_buf, sizeof (l2arc_lb_ptr_buf_t));
8745 }
8746 }
8747 list_destroy(&cb->l2wcb_abd_list);
8748
8749 if (zio->io_error != 0) {
8750 ARCSTAT_BUMP(arcstat_l2_writes_error);
8751
8752 /*
8753 * Restore the lbps array in the header to its previous state.
8754 * If the list of log block pointers is empty, zero out the
8755 * log block pointers in the device header.
8756 */
8757 lb_ptr_buf = list_head(&dev->l2ad_lbptr_list);
8758 for (int i = 0; i < 2; i++) {
8759 if (lb_ptr_buf == NULL) {
8760 /*
8761 * If the list is empty zero out the device
8762 * header. Otherwise zero out the second log
8763 * block pointer in the header.
8764 */
8765 if (i == 0) {
8766 memset(l2dhdr, 0,
8767 dev->l2ad_dev_hdr_asize);
8768 } else {
8769 memset(&l2dhdr->dh_start_lbps[i], 0,
8770 sizeof (l2arc_log_blkptr_t));
8771 }
8772 break;
8773 }
8774 memcpy(&l2dhdr->dh_start_lbps[i], lb_ptr_buf->lb_ptr,
8775 sizeof (l2arc_log_blkptr_t));
8776 lb_ptr_buf = list_next(&dev->l2ad_lbptr_list,
8777 lb_ptr_buf);
8778 }
8779 }
8780
8781 ARCSTAT_BUMP(arcstat_l2_writes_done);
8782 list_remove(buflist, head);
8783 ASSERT(!HDR_HAS_L1HDR(head));
8784 kmem_cache_free(hdr_l2only_cache, head);
8785 mutex_exit(&dev->l2ad_mtx);
8786
8787 ASSERT(dev->l2ad_vdev != NULL);
8788 vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
8789
8790 l2arc_do_free_on_write(dev);
8791
8792 kmem_free(cb, sizeof (l2arc_write_callback_t));
8793 }
8794
8795 static int
l2arc_untransform(zio_t * zio,l2arc_read_callback_t * cb)8796 l2arc_untransform(zio_t *zio, l2arc_read_callback_t *cb)
8797 {
8798 int ret;
8799 spa_t *spa = zio->io_spa;
8800 arc_buf_hdr_t *hdr = cb->l2rcb_hdr;
8801 blkptr_t *bp = zio->io_bp;
8802 uint8_t salt[ZIO_DATA_SALT_LEN];
8803 uint8_t iv[ZIO_DATA_IV_LEN];
8804 uint8_t mac[ZIO_DATA_MAC_LEN];
8805 boolean_t no_crypt = B_FALSE;
8806
8807 /*
8808 * ZIL data is never be written to the L2ARC, so we don't need
8809 * special handling for its unique MAC storage.
8810 */
8811 ASSERT3U(BP_GET_TYPE(bp), !=, DMU_OT_INTENT_LOG);
8812 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
8813 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
8814
8815 /*
8816 * If the data was encrypted, decrypt it now. Note that
8817 * we must check the bp here and not the hdr, since the
8818 * hdr does not have its encryption parameters updated
8819 * until arc_read_done().
8820 */
8821 if (BP_IS_ENCRYPTED(bp)) {
8822 abd_t *eabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr,
8823 ARC_HDR_USE_RESERVE);
8824
8825 zio_crypt_decode_params_bp(bp, salt, iv);
8826 zio_crypt_decode_mac_bp(bp, mac);
8827
8828 ret = spa_do_crypt_abd(B_FALSE, spa, &cb->l2rcb_zb,
8829 BP_GET_TYPE(bp), BP_GET_DEDUP(bp), BP_SHOULD_BYTESWAP(bp),
8830 salt, iv, mac, HDR_GET_PSIZE(hdr), eabd,
8831 hdr->b_l1hdr.b_pabd, &no_crypt);
8832 if (ret != 0) {
8833 arc_free_data_abd(hdr, eabd, arc_hdr_size(hdr), hdr);
8834 goto error;
8835 }
8836
8837 /*
8838 * If we actually performed decryption, replace b_pabd
8839 * with the decrypted data. Otherwise we can just throw
8840 * our decryption buffer away.
8841 */
8842 if (!no_crypt) {
8843 arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
8844 arc_hdr_size(hdr), hdr);
8845 hdr->b_l1hdr.b_pabd = eabd;
8846 zio->io_abd = eabd;
8847 } else {
8848 arc_free_data_abd(hdr, eabd, arc_hdr_size(hdr), hdr);
8849 }
8850 }
8851
8852 /*
8853 * If the L2ARC block was compressed, but ARC compression
8854 * is disabled we decompress the data into a new buffer and
8855 * replace the existing data.
8856 */
8857 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
8858 !HDR_COMPRESSION_ENABLED(hdr)) {
8859 abd_t *cabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr,
8860 ARC_HDR_USE_RESERVE);
8861
8862 ret = zio_decompress_data(HDR_GET_COMPRESS(hdr),
8863 hdr->b_l1hdr.b_pabd, cabd, HDR_GET_PSIZE(hdr),
8864 HDR_GET_LSIZE(hdr), &hdr->b_complevel);
8865 if (ret != 0) {
8866 arc_free_data_abd(hdr, cabd, arc_hdr_size(hdr), hdr);
8867 goto error;
8868 }
8869
8870 arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
8871 arc_hdr_size(hdr), hdr);
8872 hdr->b_l1hdr.b_pabd = cabd;
8873 zio->io_abd = cabd;
8874 zio->io_size = HDR_GET_LSIZE(hdr);
8875 }
8876
8877 return (0);
8878
8879 error:
8880 return (ret);
8881 }
8882
8883
8884 /*
8885 * A read to a cache device completed. Validate buffer contents before
8886 * handing over to the regular ARC routines.
8887 */
8888 static void
l2arc_read_done(zio_t * zio)8889 l2arc_read_done(zio_t *zio)
8890 {
8891 int tfm_error = 0;
8892 l2arc_read_callback_t *cb = zio->io_private;
8893 arc_buf_hdr_t *hdr;
8894 kmutex_t *hash_lock;
8895 boolean_t valid_cksum;
8896 boolean_t using_rdata = (BP_IS_ENCRYPTED(&cb->l2rcb_bp) &&
8897 (cb->l2rcb_flags & ZIO_FLAG_RAW_ENCRYPT));
8898
8899 ASSERT3P(zio->io_vd, !=, NULL);
8900 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
8901
8902 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
8903
8904 ASSERT3P(cb, !=, NULL);
8905 hdr = cb->l2rcb_hdr;
8906 ASSERT3P(hdr, !=, NULL);
8907
8908 hash_lock = HDR_LOCK(hdr);
8909 mutex_enter(hash_lock);
8910 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
8911
8912 /*
8913 * If the data was read into a temporary buffer,
8914 * move it and free the buffer.
8915 */
8916 if (cb->l2rcb_abd != NULL) {
8917 ASSERT3U(arc_hdr_size(hdr), <, zio->io_size);
8918 if (zio->io_error == 0) {
8919 if (using_rdata) {
8920 abd_copy(hdr->b_crypt_hdr.b_rabd,
8921 cb->l2rcb_abd, arc_hdr_size(hdr));
8922 } else {
8923 abd_copy(hdr->b_l1hdr.b_pabd,
8924 cb->l2rcb_abd, arc_hdr_size(hdr));
8925 }
8926 }
8927
8928 /*
8929 * The following must be done regardless of whether
8930 * there was an error:
8931 * - free the temporary buffer
8932 * - point zio to the real ARC buffer
8933 * - set zio size accordingly
8934 * These are required because zio is either re-used for
8935 * an I/O of the block in the case of the error
8936 * or the zio is passed to arc_read_done() and it
8937 * needs real data.
8938 */
8939 abd_free(cb->l2rcb_abd);
8940 zio->io_size = zio->io_orig_size = arc_hdr_size(hdr);
8941
8942 if (using_rdata) {
8943 ASSERT(HDR_HAS_RABD(hdr));
8944 zio->io_abd = zio->io_orig_abd =
8945 hdr->b_crypt_hdr.b_rabd;
8946 } else {
8947 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
8948 zio->io_abd = zio->io_orig_abd = hdr->b_l1hdr.b_pabd;
8949 }
8950 }
8951
8952 ASSERT3P(zio->io_abd, !=, NULL);
8953
8954 /*
8955 * Check this survived the L2ARC journey.
8956 */
8957 ASSERT(zio->io_abd == hdr->b_l1hdr.b_pabd ||
8958 (HDR_HAS_RABD(hdr) && zio->io_abd == hdr->b_crypt_hdr.b_rabd));
8959 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
8960 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
8961 zio->io_prop.zp_complevel = hdr->b_complevel;
8962
8963 valid_cksum = arc_cksum_is_equal(hdr, zio);
8964
8965 /*
8966 * b_rabd will always match the data as it exists on disk if it is
8967 * being used. Therefore if we are reading into b_rabd we do not
8968 * attempt to untransform the data.
8969 */
8970 if (valid_cksum && !using_rdata)
8971 tfm_error = l2arc_untransform(zio, cb);
8972
8973 if (valid_cksum && tfm_error == 0 && zio->io_error == 0 &&
8974 !HDR_L2_EVICTED(hdr)) {
8975 mutex_exit(hash_lock);
8976 zio->io_private = hdr;
8977 arc_read_done(zio);
8978 } else {
8979 /*
8980 * Buffer didn't survive caching. Increment stats and
8981 * reissue to the original storage device.
8982 */
8983 if (zio->io_error != 0) {
8984 ARCSTAT_BUMP(arcstat_l2_io_error);
8985 } else {
8986 zio->io_error = SET_ERROR(EIO);
8987 }
8988 if (!valid_cksum || tfm_error != 0)
8989 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
8990
8991 /*
8992 * If there's no waiter, issue an async i/o to the primary
8993 * storage now. If there *is* a waiter, the caller must
8994 * issue the i/o in a context where it's OK to block.
8995 */
8996 if (zio->io_waiter == NULL) {
8997 zio_t *pio = zio_unique_parent(zio);
8998 void *abd = (using_rdata) ?
8999 hdr->b_crypt_hdr.b_rabd : hdr->b_l1hdr.b_pabd;
9000
9001 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
9002
9003 zio = zio_read(pio, zio->io_spa, zio->io_bp,
9004 abd, zio->io_size, arc_read_done,
9005 hdr, zio->io_priority, cb->l2rcb_flags,
9006 &cb->l2rcb_zb);
9007
9008 /*
9009 * Original ZIO will be freed, so we need to update
9010 * ARC header with the new ZIO pointer to be used
9011 * by zio_change_priority() in arc_read().
9012 */
9013 for (struct arc_callback *acb = hdr->b_l1hdr.b_acb;
9014 acb != NULL; acb = acb->acb_next)
9015 acb->acb_zio_head = zio;
9016
9017 mutex_exit(hash_lock);
9018 zio_nowait(zio);
9019 } else {
9020 mutex_exit(hash_lock);
9021 }
9022 }
9023
9024 kmem_free(cb, sizeof (l2arc_read_callback_t));
9025 }
9026
9027 /*
9028 * Get the multilist for the given list number (0..3) to cycle through
9029 * lists in the desired order. This order can have a significant effect
9030 * on cache performance.
9031 *
9032 * Currently the metadata lists are hit first, MFU then MRU, followed by
9033 * the data lists.
9034 */
9035 static multilist_t *
l2arc_get_list(int list_num)9036 l2arc_get_list(int list_num)
9037 {
9038 ASSERT(list_num >= 0 && list_num < L2ARC_FEED_TYPES);
9039
9040 switch (list_num) {
9041 case 0:
9042 return (&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
9043 case 1:
9044 return (&arc_mru->arcs_list[ARC_BUFC_METADATA]);
9045 case 2:
9046 return (&arc_mfu->arcs_list[ARC_BUFC_DATA]);
9047 case 3:
9048 return (&arc_mru->arcs_list[ARC_BUFC_DATA]);
9049 default:
9050 return (NULL);
9051 }
9052 }
9053
9054
9055 /*
9056 * Lock a specific sublist within the given list number.
9057 */
9058 static multilist_sublist_t *
l2arc_sublist_lock(int list_num,int sublist_idx)9059 l2arc_sublist_lock(int list_num, int sublist_idx)
9060 {
9061 multilist_t *ml = l2arc_get_list(list_num);
9062 if (ml == NULL)
9063 return (NULL);
9064
9065 return (multilist_sublist_lock_idx(ml, sublist_idx));
9066 }
9067
9068 /*
9069 * Check if a pool has any L2ARC devices.
9070 */
9071 static boolean_t
l2arc_pool_has_devices(spa_t * target_spa)9072 l2arc_pool_has_devices(spa_t *target_spa)
9073 {
9074 l2arc_dev_t *dev;
9075
9076 ASSERT(MUTEX_HELD(&l2arc_dev_mtx));
9077
9078 for (dev = list_head(l2arc_dev_list); dev != NULL;
9079 dev = list_next(l2arc_dev_list, dev)) {
9080 if (dev->l2ad_spa == target_spa) {
9081 return (B_TRUE);
9082 }
9083 }
9084
9085 return (B_FALSE);
9086 }
9087
9088 /*
9089 * Initialize pool-based markers for l2arc position saving.
9090 */
9091 static void
l2arc_pool_markers_init(spa_t * spa)9092 l2arc_pool_markers_init(spa_t *spa)
9093 {
9094 mutex_init(&spa->spa_l2arc_info.l2arc_sublist_lock, NULL,
9095 MUTEX_DEFAULT, NULL);
9096
9097 for (int pass = 0; pass < L2ARC_FEED_TYPES; pass++) {
9098 multilist_t *ml = l2arc_get_list(pass);
9099 if (ml == NULL)
9100 continue;
9101
9102 int num_sublists = multilist_get_num_sublists(ml);
9103
9104 spa->spa_l2arc_info.l2arc_markers[pass] =
9105 arc_state_alloc_markers(num_sublists);
9106 spa->spa_l2arc_info.l2arc_sublist_busy[pass] =
9107 kmem_zalloc(num_sublists * sizeof (boolean_t), KM_SLEEP);
9108 spa->spa_l2arc_info.l2arc_sublist_reset[pass] =
9109 kmem_zalloc(num_sublists * sizeof (boolean_t), KM_SLEEP);
9110
9111 for (int i = 0; i < num_sublists; i++) {
9112 multilist_sublist_t *mls =
9113 multilist_sublist_lock_idx(ml, i);
9114 multilist_sublist_insert_tail(mls,
9115 spa->spa_l2arc_info.l2arc_markers[pass][i]);
9116 multilist_sublist_unlock(mls);
9117 }
9118
9119 spa->spa_l2arc_info.l2arc_ext_scanned[pass] = 0;
9120 }
9121 }
9122
9123 /*
9124 * Free all allocated pool-based markers.
9125 */
9126 static void
l2arc_pool_markers_fini(spa_t * spa)9127 l2arc_pool_markers_fini(spa_t *spa)
9128 {
9129 for (int pass = 0; pass < L2ARC_FEED_TYPES; pass++) {
9130 if (spa->spa_l2arc_info.l2arc_markers[pass] == NULL)
9131 continue;
9132
9133 multilist_t *ml = l2arc_get_list(pass);
9134 if (ml == NULL)
9135 continue;
9136
9137 int num_sublists = multilist_get_num_sublists(ml);
9138
9139 for (int i = 0; i < num_sublists; i++) {
9140 ASSERT3P(spa->spa_l2arc_info.l2arc_markers[pass][i],
9141 !=, NULL);
9142 multilist_sublist_t *mls =
9143 multilist_sublist_lock_idx(ml, i);
9144 ASSERT(multilist_link_active(
9145 &spa->spa_l2arc_info.l2arc_markers[pass][i]->
9146 b_l1hdr.b_arc_node));
9147 multilist_sublist_remove(mls,
9148 spa->spa_l2arc_info.l2arc_markers[pass][i]);
9149 multilist_sublist_unlock(mls);
9150 }
9151
9152 arc_state_free_markers(spa->spa_l2arc_info.l2arc_markers[pass],
9153 num_sublists);
9154 spa->spa_l2arc_info.l2arc_markers[pass] = NULL;
9155
9156 /* Free sublist busy and reset flags for this pass */
9157 ASSERT3P(spa->spa_l2arc_info.l2arc_sublist_busy[pass], !=,
9158 NULL);
9159 kmem_free(spa->spa_l2arc_info.l2arc_sublist_busy[pass],
9160 num_sublists * sizeof (boolean_t));
9161 spa->spa_l2arc_info.l2arc_sublist_busy[pass] = NULL;
9162
9163 ASSERT3P(spa->spa_l2arc_info.l2arc_sublist_reset[pass], !=,
9164 NULL);
9165 kmem_free(spa->spa_l2arc_info.l2arc_sublist_reset[pass],
9166 num_sublists * sizeof (boolean_t));
9167 spa->spa_l2arc_info.l2arc_sublist_reset[pass] = NULL;
9168 }
9169
9170 mutex_destroy(&spa->spa_l2arc_info.l2arc_sublist_lock);
9171 }
9172
9173 /*
9174 * Calculates the maximum overhead of L2ARC metadata log blocks for a given
9175 * L2ARC write size. l2arc_evict and l2arc_write_size need to include this
9176 * overhead in processing to make sure there is enough headroom available
9177 * when writing buffers.
9178 */
9179 static inline uint64_t
l2arc_log_blk_overhead(uint64_t write_sz,l2arc_dev_t * dev)9180 l2arc_log_blk_overhead(uint64_t write_sz, l2arc_dev_t *dev)
9181 {
9182 if (dev->l2ad_log_entries == 0) {
9183 return (0);
9184 } else {
9185 ASSERT(dev->l2ad_vdev != NULL);
9186
9187 uint64_t log_entries = write_sz >> SPA_MINBLOCKSHIFT;
9188
9189 uint64_t log_blocks = (log_entries +
9190 dev->l2ad_log_entries - 1) /
9191 dev->l2ad_log_entries;
9192
9193 return (vdev_psize_to_asize(dev->l2ad_vdev,
9194 sizeof (l2arc_log_blk_phys_t)) * log_blocks);
9195 }
9196 }
9197
9198 /*
9199 * Bump the DWPD generation to trigger stats reset on all devices.
9200 */
9201 void
l2arc_dwpd_bump_reset(void)9202 l2arc_dwpd_bump_reset(void)
9203 {
9204 l2arc_dwpd_bump++;
9205 }
9206
9207 /*
9208 * Calculate DWPD rate limit for L2ARC device.
9209 */
9210 static uint64_t
l2arc_dwpd_rate_limit(l2arc_dev_t * dev)9211 l2arc_dwpd_rate_limit(l2arc_dev_t *dev)
9212 {
9213 uint64_t device_size = dev->l2ad_end - dev->l2ad_start;
9214 uint64_t daily_budget = (device_size * l2arc_dwpd_limit) / 100;
9215 uint64_t now = gethrestime_sec();
9216
9217 /* Reset stats on param change or daily period expiry */
9218 if (dev->l2ad_dwpd_bump != l2arc_dwpd_bump ||
9219 (now - dev->l2ad_dwpd_start) >= 24 * 3600) {
9220 if (dev->l2ad_dwpd_bump != l2arc_dwpd_bump) {
9221 /* Full reset on param change, no carryover */
9222 dev->l2ad_dwpd_accumulated = 0;
9223 dev->l2ad_dwpd_bump = l2arc_dwpd_bump;
9224 } else {
9225 /* Save unused budget from last period (max 1 day) */
9226 if (dev->l2ad_dwpd_writes >= daily_budget)
9227 dev->l2ad_dwpd_accumulated = 0;
9228 else
9229 dev->l2ad_dwpd_accumulated =
9230 daily_budget - dev->l2ad_dwpd_writes;
9231 }
9232 dev->l2ad_dwpd_writes = 0;
9233 dev->l2ad_dwpd_start = now;
9234 }
9235
9236 uint64_t elapsed = now - dev->l2ad_dwpd_start;
9237 uint64_t remaining_secs = MAX((24 * 3600) - elapsed, 1);
9238 /* Add burst allowance for the first write after device wrap */
9239 uint64_t total_budget = daily_budget + dev->l2ad_dwpd_accumulated +
9240 L2ARC_BURST_SIZE_MAX;
9241
9242 if (dev->l2ad_dwpd_writes >= total_budget)
9243 return (0);
9244
9245 return ((total_budget - dev->l2ad_dwpd_writes) / remaining_secs);
9246 }
9247
9248 /*
9249 * Get write rate based on device state and DWPD configuration.
9250 */
9251 static uint64_t
l2arc_get_write_rate(l2arc_dev_t * dev)9252 l2arc_get_write_rate(l2arc_dev_t *dev)
9253 {
9254 uint64_t write_max = l2arc_write_max;
9255 spa_t *spa = dev->l2ad_spa;
9256
9257 /*
9258 * Make sure l2arc_write_max is valid in case user altered it.
9259 */
9260 if (write_max == 0) {
9261 cmn_err(CE_NOTE, "l2arc_write_max must be greater than zero, "
9262 "resetting it to the default (%d)", L2ARC_WRITE_SIZE);
9263 write_max = l2arc_write_max = L2ARC_WRITE_SIZE;
9264 }
9265
9266 /* Apply DWPD rate limit for persistent marker configurations */
9267 if (!dev->l2ad_first && l2arc_dwpd_limit > 0 &&
9268 spa->spa_l2arc_info.l2arc_total_capacity >=
9269 L2ARC_PERSIST_THRESHOLD) {
9270 uint64_t dwpd_rate = l2arc_dwpd_rate_limit(dev);
9271 return (MIN(dwpd_rate, write_max));
9272 }
9273
9274 return (write_max);
9275 }
9276
9277 /*
9278 * Evict buffers from the device write hand to the distance specified in
9279 * bytes. This distance may span populated buffers, it may span nothing.
9280 * This is clearing a region on the L2ARC device ready for writing.
9281 * If the 'all' boolean is set, every buffer is evicted.
9282 */
9283 static void
l2arc_evict(l2arc_dev_t * dev,uint64_t distance,boolean_t all)9284 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
9285 {
9286 list_t *buflist;
9287 arc_buf_hdr_t *hdr, *hdr_prev;
9288 kmutex_t *hash_lock;
9289 uint64_t taddr;
9290 l2arc_lb_ptr_buf_t *lb_ptr_buf, *lb_ptr_buf_prev;
9291 vdev_t *vd = dev->l2ad_vdev;
9292 boolean_t rerun;
9293
9294 ASSERT(vd != NULL || all);
9295 ASSERT(dev->l2ad_spa != NULL || all);
9296
9297 buflist = &dev->l2ad_buflist;
9298
9299 top:
9300 rerun = B_FALSE;
9301 if (dev->l2ad_hand + distance > dev->l2ad_end) {
9302 /*
9303 * When there is no space to accommodate upcoming writes,
9304 * evict to the end. Then bump the write and evict hands
9305 * to the start and iterate. This iteration does not
9306 * happen indefinitely as we make sure in
9307 * l2arc_write_size() that when the write hand is reset,
9308 * the write size does not exceed the end of the device.
9309 */
9310 rerun = B_TRUE;
9311 taddr = dev->l2ad_end;
9312 } else {
9313 taddr = dev->l2ad_hand + distance;
9314 }
9315 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
9316 uint64_t, taddr, boolean_t, all);
9317
9318 if (!all) {
9319 /*
9320 * This check has to be placed after deciding whether to
9321 * iterate (rerun).
9322 */
9323 if (dev->l2ad_first) {
9324 /*
9325 * This is the first sweep through the device. There is
9326 * nothing to evict. We have already trimmed the
9327 * whole device.
9328 */
9329 goto out;
9330 } else {
9331 /*
9332 * Trim the space to be evicted.
9333 */
9334 if (vd->vdev_has_trim && dev->l2ad_evict < taddr &&
9335 l2arc_trim_ahead > 0) {
9336 /*
9337 * We have to drop the spa_config lock because
9338 * vdev_trim_range() will acquire it.
9339 * l2ad_evict already accounts for the label
9340 * size. To prevent vdev_trim_ranges() from
9341 * adding it again, we subtract it from
9342 * l2ad_evict.
9343 */
9344 spa_config_exit(dev->l2ad_spa, SCL_L2ARC, dev);
9345 vdev_trim_simple(vd,
9346 dev->l2ad_evict - VDEV_LABEL_START_SIZE,
9347 taddr - dev->l2ad_evict);
9348 spa_config_enter(dev->l2ad_spa, SCL_L2ARC, dev,
9349 RW_READER);
9350 }
9351
9352 /*
9353 * When rebuilding L2ARC we retrieve the evict hand
9354 * from the header of the device. Of note, l2arc_evict()
9355 * does not actually delete buffers from the cache
9356 * device, but trimming may do so depending on the
9357 * hardware implementation. Thus keeping track of the
9358 * evict hand is useful.
9359 */
9360 dev->l2ad_evict = MAX(dev->l2ad_evict, taddr);
9361 }
9362 }
9363
9364 retry:
9365 mutex_enter(&dev->l2ad_mtx);
9366 /*
9367 * We have to account for evicted log blocks. Run vdev_space_update()
9368 * on log blocks whose offset (in bytes) is before the evicted offset
9369 * (in bytes) by searching in the list of pointers to log blocks
9370 * present in the L2ARC device.
9371 */
9372 for (lb_ptr_buf = list_tail(&dev->l2ad_lbptr_list); lb_ptr_buf;
9373 lb_ptr_buf = lb_ptr_buf_prev) {
9374
9375 lb_ptr_buf_prev = list_prev(&dev->l2ad_lbptr_list, lb_ptr_buf);
9376
9377 /* L2BLK_GET_PSIZE returns aligned size for log blocks */
9378 uint64_t asize = L2BLK_GET_PSIZE(
9379 (lb_ptr_buf->lb_ptr)->lbp_prop);
9380
9381 /*
9382 * We don't worry about log blocks left behind (ie
9383 * lbp_payload_start < l2ad_hand) because l2arc_write_buffers()
9384 * will never write more than l2arc_evict() evicts.
9385 */
9386 if (!all && l2arc_log_blkptr_valid(dev, lb_ptr_buf->lb_ptr)) {
9387 break;
9388 } else {
9389 if (vd != NULL)
9390 vdev_space_update(vd, -asize, 0, 0);
9391 ARCSTAT_INCR(arcstat_l2_log_blk_asize, -asize);
9392 ARCSTAT_BUMPDOWN(arcstat_l2_log_blk_count);
9393 zfs_refcount_remove_many(&dev->l2ad_lb_asize, asize,
9394 lb_ptr_buf);
9395 (void) zfs_refcount_remove(&dev->l2ad_lb_count,
9396 lb_ptr_buf);
9397 list_remove(&dev->l2ad_lbptr_list, lb_ptr_buf);
9398 kmem_free(lb_ptr_buf->lb_ptr,
9399 sizeof (l2arc_log_blkptr_t));
9400 kmem_free(lb_ptr_buf, sizeof (l2arc_lb_ptr_buf_t));
9401 }
9402 }
9403
9404 for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
9405 hdr_prev = list_prev(buflist, hdr);
9406
9407 ASSERT(!HDR_EMPTY(hdr));
9408 hash_lock = HDR_LOCK(hdr);
9409
9410 /*
9411 * We cannot use mutex_enter or else we can deadlock
9412 * with l2arc_write_buffers (due to swapping the order
9413 * the hash lock and l2ad_mtx are taken).
9414 */
9415 if (!mutex_tryenter(hash_lock)) {
9416 /*
9417 * Missed the hash lock. Retry.
9418 */
9419 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
9420 mutex_exit(&dev->l2ad_mtx);
9421 mutex_enter(hash_lock);
9422 mutex_exit(hash_lock);
9423 goto retry;
9424 }
9425
9426 /*
9427 * A header can't be on this list if it doesn't have L2 header.
9428 */
9429 ASSERT(HDR_HAS_L2HDR(hdr));
9430
9431 /* Ensure this header has finished being written. */
9432 ASSERT(!HDR_L2_WRITING(hdr));
9433 ASSERT(!HDR_L2_WRITE_HEAD(hdr));
9434
9435 if (!all && (hdr->b_l2hdr.b_daddr >= dev->l2ad_evict ||
9436 hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
9437 /*
9438 * We've evicted to the target address,
9439 * or the end of the device.
9440 */
9441 mutex_exit(hash_lock);
9442 break;
9443 }
9444
9445 if (!HDR_HAS_L1HDR(hdr)) {
9446 ASSERT(!HDR_L2_READING(hdr));
9447 /*
9448 * This doesn't exist in the ARC. Destroy.
9449 * arc_hdr_destroy() will call list_remove()
9450 * and decrement arcstat_l2_lsize.
9451 */
9452 arc_change_state(arc_anon, hdr);
9453 arc_hdr_destroy(hdr);
9454 } else {
9455 ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
9456 ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
9457 /*
9458 * Invalidate issued or about to be issued
9459 * reads, since we may be about to write
9460 * over this location.
9461 */
9462 if (HDR_L2_READING(hdr)) {
9463 ARCSTAT_BUMP(arcstat_l2_evict_reading);
9464 arc_hdr_set_flags(hdr, ARC_FLAG_L2_EVICTED);
9465 }
9466
9467 arc_hdr_l2hdr_destroy(hdr);
9468 }
9469 mutex_exit(hash_lock);
9470 }
9471 mutex_exit(&dev->l2ad_mtx);
9472
9473 out:
9474 /*
9475 * We need to check if we evict all buffers, otherwise we may iterate
9476 * unnecessarily.
9477 */
9478 if (!all && rerun) {
9479 /*
9480 * Bump device hand to the device start if it is approaching the
9481 * end. l2arc_evict() has already evicted ahead for this case.
9482 */
9483 dev->l2ad_hand = dev->l2ad_start;
9484 dev->l2ad_evict = dev->l2ad_start;
9485 dev->l2ad_first = B_FALSE;
9486 /*
9487 * Reset DWPD counters - first pass writes are free, start
9488 * fresh 24h budget period now that device is full.
9489 */
9490 dev->l2ad_dwpd_writes = 0;
9491 dev->l2ad_dwpd_start = gethrestime_sec();
9492 dev->l2ad_dwpd_accumulated = 0;
9493 dev->l2ad_dwpd_bump = l2arc_dwpd_bump;
9494 goto top;
9495 }
9496
9497 if (!all) {
9498 /*
9499 * In case of cache device removal (all) the following
9500 * assertions may be violated without functional consequences
9501 * as the device is about to be removed.
9502 */
9503 ASSERT3U(dev->l2ad_hand + distance, <=, dev->l2ad_end);
9504 if (!dev->l2ad_first)
9505 ASSERT3U(dev->l2ad_hand, <=, dev->l2ad_evict);
9506 }
9507 }
9508
9509 /*
9510 * Handle any abd transforms that might be required for writing to the L2ARC.
9511 * If successful, this function will always return an abd with the data
9512 * transformed as it is on disk in a new abd of asize bytes.
9513 */
9514 static int
l2arc_apply_transforms(spa_t * spa,arc_buf_hdr_t * hdr,uint64_t asize,abd_t ** abd_out)9515 l2arc_apply_transforms(spa_t *spa, arc_buf_hdr_t *hdr, uint64_t asize,
9516 abd_t **abd_out)
9517 {
9518 int ret;
9519 abd_t *cabd = NULL, *eabd = NULL, *to_write = hdr->b_l1hdr.b_pabd;
9520 enum zio_compress compress = HDR_GET_COMPRESS(hdr);
9521 uint64_t psize = HDR_GET_PSIZE(hdr);
9522 uint64_t size = arc_hdr_size(hdr);
9523 boolean_t ismd = HDR_ISTYPE_METADATA(hdr);
9524 boolean_t bswap = (hdr->b_l1hdr.b_byteswap != DMU_BSWAP_NUMFUNCS);
9525 dsl_crypto_key_t *dck = NULL;
9526 uint8_t mac[ZIO_DATA_MAC_LEN] = { 0 };
9527 boolean_t no_crypt = B_FALSE;
9528
9529 ASSERT((HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
9530 !HDR_COMPRESSION_ENABLED(hdr)) ||
9531 HDR_ENCRYPTED(hdr) || HDR_SHARED_DATA(hdr) || psize != asize);
9532 ASSERT3U(psize, <=, asize);
9533
9534 /*
9535 * If this data simply needs its own buffer, we simply allocate it
9536 * and copy the data. This may be done to eliminate a dependency on a
9537 * shared buffer or to reallocate the buffer to match asize.
9538 */
9539 if (HDR_HAS_RABD(hdr)) {
9540 ASSERT3U(asize, >, psize);
9541 to_write = abd_alloc_for_io(asize, ismd);
9542 abd_copy(to_write, hdr->b_crypt_hdr.b_rabd, psize);
9543 abd_zero_off(to_write, psize, asize - psize);
9544 goto out;
9545 }
9546
9547 if ((compress == ZIO_COMPRESS_OFF || HDR_COMPRESSION_ENABLED(hdr)) &&
9548 !HDR_ENCRYPTED(hdr)) {
9549 ASSERT3U(size, ==, psize);
9550 to_write = abd_alloc_for_io(asize, ismd);
9551 abd_copy(to_write, hdr->b_l1hdr.b_pabd, size);
9552 if (asize > size)
9553 abd_zero_off(to_write, size, asize - size);
9554 goto out;
9555 }
9556
9557 if (compress != ZIO_COMPRESS_OFF && !HDR_COMPRESSION_ENABLED(hdr)) {
9558 cabd = abd_alloc_for_io(MAX(size, asize), ismd);
9559 uint64_t csize = zio_compress_data(compress, to_write, &cabd,
9560 size, MIN(size, psize), hdr->b_complevel);
9561 if (csize >= size || csize > psize) {
9562 /*
9563 * We can't re-compress the block into the original
9564 * psize. Even if it fits into asize, it does not
9565 * matter, since checksum will never match on read.
9566 */
9567 abd_free(cabd);
9568 return (SET_ERROR(EIO));
9569 }
9570 if (asize > csize)
9571 abd_zero_off(cabd, csize, asize - csize);
9572 to_write = cabd;
9573 }
9574
9575 if (HDR_ENCRYPTED(hdr)) {
9576 eabd = abd_alloc_for_io(asize, ismd);
9577
9578 /*
9579 * If the dataset was disowned before the buffer
9580 * made it to this point, the key to re-encrypt
9581 * it won't be available. In this case we simply
9582 * won't write the buffer to the L2ARC.
9583 */
9584 ret = spa_keystore_lookup_key(spa, hdr->b_crypt_hdr.b_dsobj,
9585 FTAG, &dck);
9586 if (ret != 0)
9587 goto error;
9588
9589 ret = zio_do_crypt_abd(B_TRUE, &dck->dck_key,
9590 hdr->b_crypt_hdr.b_ot, bswap, hdr->b_crypt_hdr.b_salt,
9591 hdr->b_crypt_hdr.b_iv, mac, psize, to_write, eabd,
9592 &no_crypt);
9593 if (ret != 0)
9594 goto error;
9595
9596 if (no_crypt)
9597 abd_copy(eabd, to_write, psize);
9598
9599 if (psize != asize)
9600 abd_zero_off(eabd, psize, asize - psize);
9601
9602 /* assert that the MAC we got here matches the one we saved */
9603 ASSERT0(memcmp(mac, hdr->b_crypt_hdr.b_mac, ZIO_DATA_MAC_LEN));
9604 spa_keystore_dsl_key_rele(spa, dck, FTAG);
9605
9606 if (to_write == cabd)
9607 abd_free(cabd);
9608
9609 to_write = eabd;
9610 }
9611
9612 out:
9613 ASSERT3P(to_write, !=, hdr->b_l1hdr.b_pabd);
9614 *abd_out = to_write;
9615 return (0);
9616
9617 error:
9618 if (dck != NULL)
9619 spa_keystore_dsl_key_rele(spa, dck, FTAG);
9620 if (cabd != NULL)
9621 abd_free(cabd);
9622 if (eabd != NULL)
9623 abd_free(eabd);
9624
9625 *abd_out = NULL;
9626 return (ret);
9627 }
9628
9629 /*
9630 * Write buffers from a single sublist to L2ARC.
9631 * Handles locking, marker determination, and buffer processing.
9632 * Returns B_TRUE if target size reached, B_FALSE otherwise.
9633 */
9634 static boolean_t
l2arc_write_sublist(spa_t * spa,l2arc_dev_t * dev,int pass,int sublist_idx,uint64_t target_sz,uint64_t * write_asize,uint64_t * write_psize,zio_t ** pio,l2arc_write_callback_t ** cb,arc_buf_hdr_t * head,uint64_t * consumed,uint64_t sublist_headroom,boolean_t save_position)9635 l2arc_write_sublist(spa_t *spa, l2arc_dev_t *dev, int pass, int sublist_idx,
9636 uint64_t target_sz, uint64_t *write_asize, uint64_t *write_psize,
9637 zio_t **pio, l2arc_write_callback_t **cb, arc_buf_hdr_t *head,
9638 uint64_t *consumed, uint64_t sublist_headroom, boolean_t save_position)
9639 {
9640 multilist_sublist_t *mls;
9641 arc_buf_hdr_t *hdr;
9642 arc_buf_hdr_t *persistent_marker, *local_marker;
9643 boolean_t full = B_FALSE;
9644 boolean_t scan_from_head = B_FALSE;
9645 uint64_t guid = spa_load_guid(spa);
9646
9647 mls = l2arc_sublist_lock(pass, sublist_idx);
9648 ASSERT3P(mls, !=, NULL);
9649
9650 persistent_marker = spa->spa_l2arc_info.
9651 l2arc_markers[pass][sublist_idx];
9652
9653 /*
9654 * Check if this sublist's marker was flagged for reset to tail.
9655 * This handles depth cap resets and global resets without needing
9656 * to coordinate with actively-scanning threads.
9657 */
9658 if (save_position &&
9659 spa->spa_l2arc_info.l2arc_sublist_reset[pass][sublist_idx]) {
9660 multilist_sublist_remove(mls, persistent_marker);
9661 multilist_sublist_insert_tail(mls, persistent_marker);
9662 spa->spa_l2arc_info.l2arc_sublist_reset[pass][sublist_idx] =
9663 B_FALSE;
9664 }
9665
9666 if (save_position && persistent_marker == multilist_sublist_head(mls)) {
9667 multilist_sublist_unlock(mls);
9668 return (B_FALSE);
9669 }
9670
9671 local_marker = arc_state_alloc_marker();
9672
9673 if (save_position) {
9674 hdr = multilist_sublist_prev(mls, persistent_marker);
9675 ASSERT3P(hdr, !=, NULL);
9676 scan_from_head = B_FALSE;
9677 } else {
9678 if (arc_warm) {
9679 hdr = multilist_sublist_tail(mls);
9680 scan_from_head = B_FALSE;
9681 } else {
9682 hdr = multilist_sublist_head(mls);
9683 scan_from_head = B_TRUE;
9684 }
9685 ASSERT3P(hdr, !=, NULL);
9686 }
9687
9688 while (hdr != NULL) {
9689 kmutex_t *hash_lock;
9690 abd_t *to_write = NULL;
9691
9692 hash_lock = HDR_LOCK(hdr);
9693 if (!mutex_tryenter(hash_lock)) {
9694 skip:
9695 /* Skip this buffer rather than waiting. */
9696 if (scan_from_head)
9697 hdr = multilist_sublist_next(mls, hdr);
9698 else
9699 hdr = multilist_sublist_prev(mls, hdr);
9700 continue;
9701 }
9702
9703 if (l2arc_headroom != 0 &&
9704 *consumed + HDR_GET_LSIZE(hdr) >
9705 MAX(sublist_headroom, HDR_GET_LSIZE(hdr))) {
9706 /*
9707 * Searched too far in this sublist.
9708 */
9709 mutex_exit(hash_lock);
9710 break;
9711 }
9712
9713 *consumed += HDR_GET_LSIZE(hdr);
9714
9715 if (!l2arc_write_eligible(guid, hdr)) {
9716 mutex_exit(hash_lock);
9717 goto skip;
9718 }
9719
9720 ASSERT(HDR_HAS_L1HDR(hdr));
9721 ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
9722 ASSERT3U(arc_hdr_size(hdr), >, 0);
9723 ASSERT(hdr->b_l1hdr.b_pabd != NULL || HDR_HAS_RABD(hdr));
9724 uint64_t psize = HDR_GET_PSIZE(hdr);
9725 uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev, psize);
9726
9727 /*
9728 * If the allocated size of this buffer plus the max
9729 * size for the pending log block exceeds the evicted
9730 * target size, terminate writing buffers for this run.
9731 */
9732 if (*write_asize + asize +
9733 sizeof (l2arc_log_blk_phys_t) > target_sz) {
9734 full = B_TRUE;
9735 mutex_exit(hash_lock);
9736 break;
9737 }
9738
9739 /*
9740 * We should not sleep with sublist lock held or it
9741 * may block ARC eviction. Insert a marker to save
9742 * the position and drop the lock.
9743 */
9744 if (scan_from_head)
9745 multilist_sublist_insert_after(mls, hdr, local_marker);
9746 else
9747 multilist_sublist_insert_before(mls, hdr, local_marker);
9748 multilist_sublist_unlock(mls);
9749
9750 /*
9751 * If this header has b_rabd, we can use this since it
9752 * must always match the data exactly as it exists on
9753 * disk. Otherwise, the L2ARC can normally use the
9754 * hdr's data, but if we're sharing data between the
9755 * hdr and one of its bufs, L2ARC needs its own copy of
9756 * the data so that the ZIO below can't race with the
9757 * buf consumer. To ensure that this copy will be
9758 * available for the lifetime of the ZIO and be cleaned
9759 * up afterwards, we add it to the l2arc_free_on_write
9760 * queue. If we need to apply any transforms to the
9761 * data (compression, encryption) we will also need the
9762 * extra buffer.
9763 */
9764 if (HDR_HAS_RABD(hdr) && psize == asize) {
9765 to_write = hdr->b_crypt_hdr.b_rabd;
9766 } else if ((HDR_COMPRESSION_ENABLED(hdr) ||
9767 HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_OFF) &&
9768 !HDR_ENCRYPTED(hdr) && !HDR_SHARED_DATA(hdr) &&
9769 psize == asize) {
9770 to_write = hdr->b_l1hdr.b_pabd;
9771 } else {
9772 int ret = l2arc_apply_transforms(spa, hdr, asize,
9773 &to_write);
9774 if (ret != 0) {
9775 arc_hdr_clear_flags(hdr, ARC_FLAG_L2CACHE);
9776 mutex_exit(hash_lock);
9777 goto next;
9778 }
9779
9780 l2arc_free_abd_on_write(to_write, dev);
9781 }
9782
9783 hdr->b_l2hdr.b_dev = dev;
9784 hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
9785 hdr->b_l2hdr.b_hits = 0;
9786 hdr->b_l2hdr.b_arcs_state =
9787 hdr->b_l1hdr.b_state->arcs_state;
9788 /* l2arc_hdr_arcstats_update() expects a valid asize */
9789 HDR_SET_L2SIZE(hdr, asize);
9790 arc_hdr_set_flags(hdr, ARC_FLAG_HAS_L2HDR |
9791 ARC_FLAG_L2_WRITING);
9792
9793 (void) zfs_refcount_add_many(&dev->l2ad_alloc,
9794 arc_hdr_size(hdr), hdr);
9795 l2arc_hdr_arcstats_increment(hdr);
9796 vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
9797
9798 mutex_enter(&dev->l2ad_mtx);
9799 if (*pio == NULL) {
9800 /*
9801 * Insert a dummy header on the buflist so
9802 * l2arc_write_done() can find where the
9803 * write buffers begin without searching.
9804 */
9805 list_insert_head(&dev->l2ad_buflist, head);
9806 }
9807 list_insert_head(&dev->l2ad_buflist, hdr);
9808 mutex_exit(&dev->l2ad_mtx);
9809
9810 boolean_t commit = l2arc_log_blk_insert(dev, hdr);
9811 mutex_exit(hash_lock);
9812
9813 if (*pio == NULL) {
9814 *cb = kmem_alloc(sizeof (l2arc_write_callback_t),
9815 KM_SLEEP);
9816 (*cb)->l2wcb_dev = dev;
9817 (*cb)->l2wcb_head = head;
9818 list_create(&(*cb)->l2wcb_abd_list,
9819 sizeof (l2arc_lb_abd_buf_t),
9820 offsetof(l2arc_lb_abd_buf_t, node));
9821 *pio = zio_root(spa, l2arc_write_done, *cb,
9822 ZIO_FLAG_CANFAIL);
9823 }
9824
9825 zio_t *wzio = zio_write_phys(*pio, dev->l2ad_vdev,
9826 dev->l2ad_hand, asize, to_write, ZIO_CHECKSUM_OFF,
9827 NULL, hdr, ZIO_PRIORITY_ASYNC_WRITE,
9828 ZIO_FLAG_CANFAIL, B_FALSE);
9829
9830 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
9831 zio_t *, wzio);
9832 zio_nowait(wzio);
9833
9834 *write_psize += psize;
9835 *write_asize += asize;
9836 dev->l2ad_hand += asize;
9837
9838 if (commit) {
9839 /* l2ad_hand will be adjusted inside. */
9840 *write_asize += l2arc_log_blk_commit(dev, *pio, *cb);
9841 }
9842
9843 next:
9844 multilist_sublist_lock(mls);
9845 if (scan_from_head)
9846 hdr = multilist_sublist_next(mls, local_marker);
9847 else
9848 hdr = multilist_sublist_prev(mls, local_marker);
9849 multilist_sublist_remove(mls, local_marker);
9850 }
9851
9852 /* Reposition persistent marker for next iteration. */
9853 multilist_sublist_remove(mls, persistent_marker);
9854 if (save_position &&
9855 spa->spa_l2arc_info.l2arc_sublist_reset[pass][sublist_idx]) {
9856 /* Reset flagged during scan, restart from tail. */
9857 multilist_sublist_insert_tail(mls, persistent_marker);
9858 spa->spa_l2arc_info.l2arc_sublist_reset[pass][sublist_idx] =
9859 B_FALSE;
9860 } else if (save_position && hdr != NULL) {
9861 /*
9862 * Write budget or sublist headroom exhausted, position
9863 * marker after hdr to retry it next time.
9864 */
9865 multilist_sublist_insert_after(mls, hdr, persistent_marker);
9866 } else if (save_position) {
9867 /* End of sublist, position marker at head. */
9868 multilist_sublist_insert_head(mls, persistent_marker);
9869 } else {
9870 /* Non-persistent, reset marker to tail. */
9871 multilist_sublist_insert_tail(mls, persistent_marker);
9872 }
9873
9874 multilist_sublist_unlock(mls);
9875
9876 arc_state_free_marker(local_marker);
9877
9878 return (full);
9879 }
9880
9881 static void
l2arc_blk_fetch_done(zio_t * zio)9882 l2arc_blk_fetch_done(zio_t *zio)
9883 {
9884 l2arc_read_callback_t *cb;
9885
9886 cb = zio->io_private;
9887 if (cb->l2rcb_abd != NULL)
9888 abd_free(cb->l2rcb_abd);
9889 kmem_free(cb, sizeof (l2arc_read_callback_t));
9890 }
9891
9892 /*
9893 * Return the total size of the ARC state corresponding to the given
9894 * L2ARC pass number (0..3).
9895 */
9896 static uint64_t
l2arc_get_state_size(int pass)9897 l2arc_get_state_size(int pass)
9898 {
9899 switch (pass) {
9900 case L2ARC_MFU_META:
9901 return (zfs_refcount_count(
9902 &arc_mfu->arcs_size[ARC_BUFC_METADATA]));
9903 case L2ARC_MRU_META:
9904 return (zfs_refcount_count(
9905 &arc_mru->arcs_size[ARC_BUFC_METADATA]));
9906 case L2ARC_MFU_DATA:
9907 return (zfs_refcount_count(
9908 &arc_mfu->arcs_size[ARC_BUFC_DATA]));
9909 case L2ARC_MRU_DATA:
9910 return (zfs_refcount_count(
9911 &arc_mru->arcs_size[ARC_BUFC_DATA]));
9912 default:
9913 return (0);
9914 }
9915 }
9916
9917 /*
9918 * Flag all sublists for a single pass for lazy marker reset to tail.
9919 * Each sublist's marker will be reset when next visited by a feed thread.
9920 */
9921 static void
l2arc_flag_pass_reset(spa_t * spa,int pass)9922 l2arc_flag_pass_reset(spa_t *spa, int pass)
9923 {
9924 ASSERT(MUTEX_HELD(&spa->spa_l2arc_info.l2arc_sublist_lock));
9925
9926 multilist_t *ml = l2arc_get_list(pass);
9927 int num_sublists = multilist_get_num_sublists(ml);
9928
9929 for (int i = 0; i < num_sublists; i++) {
9930 multilist_sublist_t *mls = multilist_sublist_lock_idx(ml, i);
9931 spa->spa_l2arc_info.l2arc_sublist_reset[pass][i] = B_TRUE;
9932 multilist_sublist_unlock(mls);
9933 }
9934
9935 spa->spa_l2arc_info.l2arc_ext_scanned[pass] = 0;
9936 }
9937
9938 /*
9939 * Flag all L2ARC markers for lazy reset to tail for the given spa.
9940 * Each sublist's marker will be reset when next visited by a feed thread.
9941 */
9942 static void
l2arc_reset_all_markers(spa_t * spa)9943 l2arc_reset_all_markers(spa_t *spa)
9944 {
9945 for (int pass = 0; pass < L2ARC_FEED_TYPES; pass++)
9946 l2arc_flag_pass_reset(spa, pass);
9947
9948 /* Reset write counter */
9949 spa->spa_l2arc_info.l2arc_total_writes = 0;
9950 }
9951
9952 /*
9953 * Find and write ARC buffers to the L2ARC device.
9954 *
9955 * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
9956 * for reading until they have completed writing.
9957 * The headroom_boost is an in-out parameter used to maintain headroom boost
9958 * state between calls to this function.
9959 *
9960 * Returns the number of bytes actually written (which may be smaller than
9961 * the delta by which the device hand has changed due to alignment and the
9962 * writing of log blocks).
9963 */
9964 static uint64_t
l2arc_write_buffers(spa_t * spa,l2arc_dev_t * dev,uint64_t target_sz)9965 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
9966 {
9967 arc_buf_hdr_t *head;
9968 uint64_t write_asize, write_psize, headroom;
9969 boolean_t full;
9970 l2arc_write_callback_t *cb = NULL;
9971 zio_t *pio;
9972 l2arc_dev_hdr_phys_t *l2dhdr = dev->l2ad_dev_hdr;
9973
9974 ASSERT3P(dev->l2ad_vdev, !=, NULL);
9975
9976 pio = NULL;
9977 write_asize = write_psize = 0;
9978 full = B_FALSE;
9979 head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
9980 arc_hdr_set_flags(head, ARC_FLAG_L2_WRITE_HEAD | ARC_FLAG_HAS_L2HDR);
9981
9982 /*
9983 * Determine L2ARC implementation based on total pool L2ARC capacity
9984 * vs ARC size. Use persistent markers for pools with significant
9985 * L2ARC investment, otherwise use simple HEAD/TAIL scanning.
9986 */
9987 boolean_t save_position =
9988 (spa->spa_l2arc_info.l2arc_total_capacity >=
9989 L2ARC_PERSIST_THRESHOLD);
9990
9991 /*
9992 * Check if markers need reset based on smallest device threshold.
9993 * Reset when cumulative writes exceed 1/8th of smallest device.
9994 * Must be protected since multiple device threads may check/update.
9995 */
9996 mutex_enter(&spa->spa_l2arc_info.l2arc_sublist_lock);
9997 if (save_position && spa->spa_l2arc_info.l2arc_total_writes >=
9998 spa->spa_l2arc_info.l2arc_smallest_capacity / 8) {
9999 l2arc_reset_all_markers(spa);
10000 }
10001 mutex_exit(&spa->spa_l2arc_info.l2arc_sublist_lock);
10002
10003 /*
10004 * Copy buffers for L2ARC writing.
10005 */
10006 boolean_t skip_meta = (save_position &&
10007 l2arc_meta_cycles > 0 &&
10008 dev->l2ad_meta_cycles >= l2arc_meta_cycles);
10009 if (skip_meta)
10010 dev->l2ad_meta_cycles = 0;
10011
10012 for (int pass = 0; pass < L2ARC_FEED_TYPES; pass++) {
10013 /*
10014 * pass == 0: MFU meta
10015 * pass == 1: MRU meta
10016 * pass == 2: MFU data
10017 * pass == 3: MRU data
10018 */
10019 if (l2arc_mfuonly == 1) {
10020 if (pass == 1 || pass == 3)
10021 continue;
10022 } else if (l2arc_mfuonly > 1) {
10023 if (pass == 3)
10024 continue;
10025 }
10026
10027 if (skip_meta && pass <= L2ARC_MRU_META)
10028 continue;
10029
10030 headroom = target_sz * l2arc_headroom;
10031 if (zfs_compressed_arc_enabled)
10032 headroom = (headroom * l2arc_headroom_boost) / 100;
10033
10034 multilist_t *ml = l2arc_get_list(pass);
10035 ASSERT3P(ml, !=, NULL);
10036 int num_sublists = multilist_get_num_sublists(ml);
10037 uint64_t consumed_headroom = 0;
10038
10039 /*
10040 * Equal per-sublist headroom prevents later
10041 * sublists from getting disproportionate shares
10042 * that would defeat the depth cap.
10043 */
10044 uint64_t sublist_headroom = headroom / num_sublists;
10045
10046 int current_sublist = spa->spa_l2arc_info.
10047 l2arc_next_sublist[pass];
10048 int processed_sublists = 0;
10049 while (processed_sublists < num_sublists && !full) {
10050 if (consumed_headroom >= headroom)
10051 break;
10052
10053 /*
10054 * Check if sublist is busy (being processed by another
10055 * L2ARC device thread). If so, skip to next sublist.
10056 */
10057 mutex_enter(&spa->spa_l2arc_info.l2arc_sublist_lock);
10058 if (spa->spa_l2arc_info.l2arc_sublist_busy[pass]
10059 [current_sublist]) {
10060 mutex_exit(&spa->spa_l2arc_info.
10061 l2arc_sublist_lock);
10062 current_sublist = (current_sublist + 1) %
10063 num_sublists;
10064 processed_sublists++;
10065 continue;
10066 }
10067 /* Mark sublist as busy */
10068 spa->spa_l2arc_info.l2arc_sublist_busy[pass]
10069 [current_sublist] = B_TRUE;
10070 mutex_exit(&spa->spa_l2arc_info.l2arc_sublist_lock);
10071
10072 /*
10073 * Write buffers from this sublist to L2ARC.
10074 * Function handles locking, marker management, and
10075 * buffer processing internally.
10076 */
10077 full = l2arc_write_sublist(spa, dev, pass,
10078 current_sublist, target_sz, &write_asize,
10079 &write_psize, &pio, &cb, head,
10080 &consumed_headroom, sublist_headroom,
10081 save_position);
10082
10083 /* Clear busy flag for this sublist */
10084 mutex_enter(&spa->spa_l2arc_info.l2arc_sublist_lock);
10085 spa->spa_l2arc_info.l2arc_sublist_busy[pass]
10086 [current_sublist] = B_FALSE;
10087 mutex_exit(&spa->spa_l2arc_info.l2arc_sublist_lock);
10088
10089 current_sublist = (current_sublist + 1) % num_sublists;
10090 processed_sublists++;
10091 }
10092
10093 spa->spa_l2arc_info.l2arc_next_sublist[pass] =
10094 (spa->spa_l2arc_info.l2arc_next_sublist[pass] + 1) %
10095 num_sublists;
10096
10097 /*
10098 * Count consecutive metadata monopolization toward
10099 * l2arc_meta_cycles. Only count when metadata actually
10100 * filled the write budget, starving data passes.
10101 */
10102 if (save_position && pass <= L2ARC_MRU_META && full)
10103 dev->l2ad_meta_cycles++;
10104
10105 /*
10106 * Depth cap: track cumulative bytes scanned per pass
10107 * and reset markers when the scan cap is reached.
10108 * Keeps the marker near the tail where L2ARC adds
10109 * the most value.
10110 */
10111 if (save_position) {
10112 mutex_enter(&spa->spa_l2arc_info.l2arc_sublist_lock);
10113
10114 spa->spa_l2arc_info.l2arc_ext_scanned[pass] +=
10115 consumed_headroom;
10116
10117 uint64_t state_sz = l2arc_get_state_size(pass);
10118 uint64_t scan_cap =
10119 state_sz * l2arc_ext_headroom_pct / 100;
10120
10121 if (scan_cap > 0 &&
10122 spa->spa_l2arc_info.l2arc_ext_scanned[pass] >=
10123 scan_cap) {
10124 l2arc_flag_pass_reset(spa, pass);
10125 }
10126
10127 mutex_exit(&spa->spa_l2arc_info.l2arc_sublist_lock);
10128 }
10129
10130 if (full == B_TRUE)
10131 break;
10132 }
10133
10134 /*
10135 * If nothing was written at all, reset monopolization counter.
10136 * No point skipping metadata if data has nothing either.
10137 */
10138 if (write_asize == 0)
10139 dev->l2ad_meta_cycles = 0;
10140
10141 /* No buffers selected for writing? */
10142 if (pio == NULL) {
10143 ASSERT0(write_psize);
10144 ASSERT(!HDR_HAS_L1HDR(head));
10145 kmem_cache_free(hdr_l2only_cache, head);
10146
10147 /*
10148 * Although we did not write any buffers l2ad_evict may
10149 * have advanced.
10150 */
10151 if (dev->l2ad_evict != l2dhdr->dh_evict)
10152 l2arc_dev_hdr_update(dev);
10153
10154 return (0);
10155 }
10156
10157 if (!dev->l2ad_first)
10158 ASSERT3U(dev->l2ad_hand, <=, dev->l2ad_evict);
10159
10160 ASSERT3U(write_asize, <=, target_sz);
10161 ARCSTAT_BUMP(arcstat_l2_writes_sent);
10162 ARCSTAT_INCR(arcstat_l2_write_bytes, write_psize);
10163
10164 dev->l2ad_writing = B_TRUE;
10165 (void) zio_wait(pio);
10166 dev->l2ad_writing = B_FALSE;
10167
10168 /*
10169 * Update cumulative write tracking for marker reset logic.
10170 * Protected for multi-device thread access.
10171 */
10172 mutex_enter(&spa->spa_l2arc_info.l2arc_sublist_lock);
10173 spa->spa_l2arc_info.l2arc_total_writes += write_asize;
10174 mutex_exit(&spa->spa_l2arc_info.l2arc_sublist_lock);
10175
10176 /* Track writes for DWPD rate limiting */
10177 dev->l2ad_dwpd_writes += write_asize;
10178
10179 /*
10180 * Update the device header after the zio completes as
10181 * l2arc_write_done() may have updated the memory holding the log block
10182 * pointers in the device header.
10183 */
10184 l2arc_dev_hdr_update(dev);
10185
10186 return (write_asize);
10187 }
10188
10189 static boolean_t
l2arc_hdr_limit_reached(void)10190 l2arc_hdr_limit_reached(void)
10191 {
10192 int64_t s = aggsum_upper_bound(&arc_sums.arcstat_l2_hdr_size);
10193
10194 return (arc_reclaim_needed() ||
10195 (s > (arc_warm ? arc_c : arc_c_max) * l2arc_meta_percent / 100));
10196 }
10197
10198 /*
10199 * Per-device L2ARC feed thread. Each L2ARC device has its own thread
10200 * to allow parallel writes to multiple devices.
10201 */
10202 static __attribute__((noreturn)) void
l2arc_feed_thread(void * arg)10203 l2arc_feed_thread(void *arg)
10204 {
10205 l2arc_dev_t *dev = arg;
10206 callb_cpr_t cpr;
10207 spa_t *spa;
10208 uint64_t size, wrote;
10209 clock_t begin, next = ddi_get_lbolt();
10210 fstrans_cookie_t cookie;
10211
10212 ASSERT3P(dev, !=, NULL);
10213
10214 CALLB_CPR_INIT(&cpr, &dev->l2ad_feed_thr_lock, callb_generic_cpr, FTAG);
10215
10216 mutex_enter(&dev->l2ad_feed_thr_lock);
10217
10218 cookie = spl_fstrans_mark();
10219 while (dev->l2ad_thread_exit == B_FALSE) {
10220 CALLB_CPR_SAFE_BEGIN(&cpr);
10221 (void) cv_timedwait_idle(&dev->l2ad_feed_cv,
10222 &dev->l2ad_feed_thr_lock, next);
10223 CALLB_CPR_SAFE_END(&cpr, &dev->l2ad_feed_thr_lock);
10224 next = ddi_get_lbolt() + hz;
10225
10226 /*
10227 * Check if thread should exit.
10228 */
10229 if (dev->l2ad_thread_exit)
10230 break;
10231
10232 /*
10233 * Check if device is still valid. If not, thread should exit.
10234 */
10235 if (dev->l2ad_vdev == NULL || vdev_is_dead(dev->l2ad_vdev))
10236 break;
10237 begin = ddi_get_lbolt();
10238
10239 /*
10240 * Try to acquire the spa config lock. If we can't get it,
10241 * skip this iteration as removal might be in progress.
10242 * The feed thread will exit naturally when it wakes up and
10243 * sees l2ad_thread_exit is set.
10244 */
10245 spa = dev->l2ad_spa;
10246 ASSERT3P(spa, !=, NULL);
10247 if (!spa_config_tryenter(spa, SCL_L2ARC, dev, RW_READER))
10248 continue;
10249
10250 /*
10251 * Avoid contributing to memory pressure.
10252 */
10253 if (l2arc_hdr_limit_reached()) {
10254 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
10255 spa_config_exit(spa, SCL_L2ARC, dev);
10256 continue;
10257 }
10258
10259 ARCSTAT_BUMP(arcstat_l2_feeds);
10260
10261 clock_t interval;
10262 size = l2arc_write_size(dev, &interval);
10263
10264 /*
10265 * Evict L2ARC buffers that will be overwritten.
10266 */
10267 l2arc_evict(dev, size, B_FALSE);
10268
10269 /*
10270 * Write ARC buffers.
10271 */
10272 wrote = l2arc_write_buffers(spa, dev, size);
10273
10274 /*
10275 * Adjust interval based on actual write.
10276 */
10277 if (wrote == 0)
10278 interval = hz * l2arc_feed_secs;
10279 else if (wrote < size)
10280 interval = (interval * wrote) / size;
10281
10282 /*
10283 * Calculate next feed time.
10284 */
10285 clock_t now = ddi_get_lbolt();
10286 next = MAX(now, MIN(now + interval, begin + interval));
10287 spa_config_exit(spa, SCL_L2ARC, dev);
10288 }
10289 spl_fstrans_unmark(cookie);
10290
10291 dev->l2ad_feed_thread = NULL;
10292 cv_broadcast(&dev->l2ad_feed_cv);
10293 CALLB_CPR_EXIT(&cpr); /* drops dev->l2ad_feed_thr_lock */
10294 thread_exit();
10295 }
10296
10297 boolean_t
l2arc_vdev_present(vdev_t * vd)10298 l2arc_vdev_present(vdev_t *vd)
10299 {
10300 return (l2arc_vdev_get(vd) != NULL);
10301 }
10302
10303 /*
10304 * Returns the l2arc_dev_t associated with a particular vdev_t or NULL if
10305 * the vdev_t isn't an L2ARC device.
10306 */
10307 l2arc_dev_t *
l2arc_vdev_get(vdev_t * vd)10308 l2arc_vdev_get(vdev_t *vd)
10309 {
10310 l2arc_dev_t *dev;
10311
10312 mutex_enter(&l2arc_dev_mtx);
10313 for (dev = list_head(l2arc_dev_list); dev != NULL;
10314 dev = list_next(l2arc_dev_list, dev)) {
10315 if (dev->l2ad_vdev == vd)
10316 break;
10317 }
10318 mutex_exit(&l2arc_dev_mtx);
10319
10320 return (dev);
10321 }
10322
10323 static void
l2arc_rebuild_dev(l2arc_dev_t * dev,boolean_t reopen)10324 l2arc_rebuild_dev(l2arc_dev_t *dev, boolean_t reopen)
10325 {
10326 l2arc_dev_hdr_phys_t *l2dhdr = dev->l2ad_dev_hdr;
10327 uint64_t l2dhdr_asize = dev->l2ad_dev_hdr_asize;
10328 spa_t *spa = dev->l2ad_spa;
10329
10330 /*
10331 * After a l2arc_remove_vdev(), the spa_t will no longer be valid
10332 */
10333 if (spa == NULL)
10334 return;
10335
10336 /*
10337 * The L2ARC has to hold at least the payload of one log block for
10338 * them to be restored (persistent L2ARC). The payload of a log block
10339 * depends on the amount of its log entries. We always write log blocks
10340 * with 1022 entries. How many of them are committed or restored depends
10341 * on the size of the L2ARC device. Thus the maximum payload of
10342 * one log block is 1022 * SPA_MAXBLOCKSIZE = 16GB. If the L2ARC device
10343 * is less than that, we reduce the amount of committed and restored
10344 * log entries per block so as to enable persistence.
10345 */
10346 if (dev->l2ad_end < l2arc_rebuild_blocks_min_l2size) {
10347 dev->l2ad_log_entries = 0;
10348 } else {
10349 dev->l2ad_log_entries = MIN((dev->l2ad_end -
10350 dev->l2ad_start) >> SPA_MAXBLOCKSHIFT,
10351 L2ARC_LOG_BLK_MAX_ENTRIES);
10352 }
10353
10354 /*
10355 * Read the device header, if an error is returned do not rebuild L2ARC.
10356 */
10357 if (l2arc_dev_hdr_read(dev) == 0 && dev->l2ad_log_entries > 0) {
10358 /*
10359 * If we are onlining a cache device (vdev_reopen) that was
10360 * still present (l2arc_vdev_present()) and rebuild is enabled,
10361 * we should evict all ARC buffers and pointers to log blocks
10362 * and reclaim their space before restoring its contents to
10363 * L2ARC.
10364 */
10365 if (reopen) {
10366 if (!l2arc_rebuild_enabled) {
10367 return;
10368 } else {
10369 l2arc_evict(dev, 0, B_TRUE);
10370 /* start a new log block */
10371 dev->l2ad_log_ent_idx = 0;
10372 dev->l2ad_log_blk_payload_asize = 0;
10373 dev->l2ad_log_blk_payload_start = 0;
10374 }
10375 }
10376 /*
10377 * Just mark the device as pending for a rebuild. We won't
10378 * be starting a rebuild in line here as it would block pool
10379 * import. Instead spa_load_impl will hand that off to an
10380 * async task which will call l2arc_spa_rebuild_start.
10381 */
10382 dev->l2ad_rebuild = B_TRUE;
10383 } else if (spa_writeable(spa)) {
10384 /*
10385 * In this case TRIM the whole device if l2arc_trim_ahead > 0,
10386 * otherwise create a new header. We zero out the memory holding
10387 * the header to reset dh_start_lbps. If we TRIM the whole
10388 * device the new header will be written by
10389 * vdev_trim_l2arc_thread() at the end of the TRIM to update the
10390 * trim_state in the header too. When reading the header, if
10391 * trim_state is not VDEV_TRIM_COMPLETE and l2arc_trim_ahead > 0
10392 * we opt to TRIM the whole device again.
10393 */
10394 if (l2arc_trim_ahead > 0) {
10395 dev->l2ad_trim_all = B_TRUE;
10396 } else {
10397 memset(l2dhdr, 0, l2dhdr_asize);
10398 l2arc_dev_hdr_update(dev);
10399 }
10400 }
10401 }
10402
10403
10404 /*
10405 * Recalculate smallest L2ARC device capacity for the given spa.
10406 * Must be called under l2arc_dev_mtx.
10407 */
10408 static void
l2arc_update_smallest_capacity(spa_t * spa)10409 l2arc_update_smallest_capacity(spa_t *spa)
10410 {
10411 ASSERT(MUTEX_HELD(&l2arc_dev_mtx));
10412 l2arc_dev_t *dev;
10413 uint64_t smallest = UINT64_MAX;
10414
10415 for (dev = list_head(l2arc_dev_list); dev != NULL;
10416 dev = list_next(l2arc_dev_list, dev)) {
10417 if (dev->l2ad_spa == spa) {
10418 uint64_t cap = dev->l2ad_end - dev->l2ad_start;
10419 if (cap < smallest)
10420 smallest = cap;
10421 }
10422 }
10423
10424 spa->spa_l2arc_info.l2arc_smallest_capacity = smallest;
10425 }
10426
10427 /*
10428 * Add a vdev for use by the L2ARC. By this point the spa has already
10429 * validated the vdev and opened it.
10430 */
10431 void
l2arc_add_vdev(spa_t * spa,vdev_t * vd)10432 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
10433 {
10434 l2arc_dev_t *adddev;
10435 uint64_t l2dhdr_asize;
10436
10437 ASSERT(!l2arc_vdev_present(vd));
10438
10439 /*
10440 * Create a new l2arc device entry.
10441 */
10442 adddev = vmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
10443 adddev->l2ad_spa = spa;
10444 adddev->l2ad_vdev = vd;
10445 /* leave extra size for an l2arc device header */
10446 l2dhdr_asize = adddev->l2ad_dev_hdr_asize =
10447 MAX(sizeof (*adddev->l2ad_dev_hdr), 1 << vd->vdev_ashift);
10448 adddev->l2ad_start = VDEV_LABEL_START_SIZE + l2dhdr_asize;
10449 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
10450 ASSERT3U(adddev->l2ad_start, <, adddev->l2ad_end);
10451 adddev->l2ad_hand = adddev->l2ad_start;
10452 adddev->l2ad_evict = adddev->l2ad_start;
10453 adddev->l2ad_first = B_TRUE;
10454 adddev->l2ad_writing = B_FALSE;
10455 adddev->l2ad_trim_all = B_FALSE;
10456 adddev->l2ad_dwpd_writes = 0;
10457 adddev->l2ad_dwpd_start = gethrestime_sec();
10458 adddev->l2ad_dwpd_accumulated = 0;
10459 adddev->l2ad_dwpd_bump = l2arc_dwpd_bump;
10460 list_link_init(&adddev->l2ad_node);
10461 adddev->l2ad_dev_hdr = kmem_zalloc(l2dhdr_asize, KM_SLEEP);
10462
10463 mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
10464 /*
10465 * This is a list of all ARC buffers that are still valid on the
10466 * device.
10467 */
10468 list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
10469 offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
10470
10471 /*
10472 * This is a list of pointers to log blocks that are still present
10473 * on the device.
10474 */
10475 list_create(&adddev->l2ad_lbptr_list, sizeof (l2arc_lb_ptr_buf_t),
10476 offsetof(l2arc_lb_ptr_buf_t, node));
10477
10478 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
10479 zfs_refcount_create(&adddev->l2ad_alloc);
10480
10481 /*
10482 * Initialize per-device thread fields
10483 */
10484 adddev->l2ad_thread_exit = B_FALSE;
10485 mutex_init(&adddev->l2ad_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
10486 cv_init(&adddev->l2ad_feed_cv, NULL, CV_DEFAULT, NULL);
10487
10488 zfs_refcount_create(&adddev->l2ad_lb_asize);
10489 zfs_refcount_create(&adddev->l2ad_lb_count);
10490
10491 /*
10492 * Decide if dev is eligible for L2ARC rebuild or whole device
10493 * trimming. This has to happen before the device is added in the
10494 * cache device list and l2arc_dev_mtx is released. Otherwise
10495 * l2arc_feed_thread() might already start writing on the
10496 * device.
10497 */
10498 l2arc_rebuild_dev(adddev, B_FALSE);
10499
10500 /*
10501 * Add device to global list
10502 */
10503 mutex_enter(&l2arc_dev_mtx);
10504
10505 /*
10506 * Initialize pool-based position saving markers if this is the first
10507 * L2ARC device for this pool
10508 */
10509 if (!l2arc_pool_has_devices(spa)) {
10510 l2arc_pool_markers_init(spa);
10511 }
10512
10513 list_insert_head(l2arc_dev_list, adddev);
10514 atomic_inc_64(&l2arc_ndev);
10515 spa->spa_l2arc_info.l2arc_total_capacity += (adddev->l2ad_end -
10516 adddev->l2ad_start);
10517 l2arc_update_smallest_capacity(spa);
10518
10519 /*
10520 * Create per-device feed thread only if spa is writable.
10521 * The thread name includes the spa name and device number
10522 * for easy identification.
10523 */
10524 if (spa_writeable(spa)) {
10525 char thread_name[MAXNAMELEN];
10526 snprintf(thread_name, sizeof (thread_name), "l2arc_%s_%llu",
10527 spa_name(spa), (u_longlong_t)vd->vdev_id);
10528 adddev->l2ad_feed_thread = thread_create_named(thread_name,
10529 NULL, 0, l2arc_feed_thread, adddev, 0, &p0, TS_RUN,
10530 minclsyspri);
10531 if (adddev->l2ad_feed_thread == NULL) {
10532 cmn_err(CE_WARN, "l2arc: failed to create feed thread "
10533 "for vdev %llu in pool '%s'",
10534 (u_longlong_t)vd->vdev_id, spa_name(spa));
10535 }
10536 } else {
10537 adddev->l2ad_feed_thread = NULL;
10538 }
10539
10540 mutex_exit(&l2arc_dev_mtx);
10541 }
10542
10543 /*
10544 * Decide if a vdev is eligible for L2ARC rebuild, called from vdev_reopen()
10545 * in case of onlining a cache device.
10546 */
10547 void
l2arc_rebuild_vdev(vdev_t * vd,boolean_t reopen)10548 l2arc_rebuild_vdev(vdev_t *vd, boolean_t reopen)
10549 {
10550 l2arc_dev_t *dev = NULL;
10551
10552 dev = l2arc_vdev_get(vd);
10553 ASSERT3P(dev, !=, NULL);
10554
10555 /*
10556 * In contrast to l2arc_add_vdev() we do not have to worry about
10557 * l2arc_feed_thread() invalidating previous content when onlining a
10558 * cache device. The device parameters (l2ad*) are not cleared when
10559 * offlining the device and writing new buffers will not invalidate
10560 * all previous content. In worst case only buffers that have not had
10561 * their log block written to the device will be lost.
10562 * When onlining the cache device (ie offline->online without exporting
10563 * the pool in between) this happens:
10564 * vdev_reopen() -> vdev_open() -> l2arc_rebuild_vdev()
10565 * | |
10566 * vdev_is_dead() = B_FALSE l2ad_rebuild = B_TRUE
10567 * During the time where vdev_is_dead = B_FALSE and until l2ad_rebuild
10568 * is set to B_TRUE we might write additional buffers to the device.
10569 */
10570 l2arc_rebuild_dev(dev, reopen);
10571 }
10572
10573 typedef struct {
10574 l2arc_dev_t *rva_l2arc_dev;
10575 uint64_t rva_spa_gid;
10576 uint64_t rva_vdev_gid;
10577 boolean_t rva_async;
10578
10579 } remove_vdev_args_t;
10580
10581 static void
l2arc_device_teardown(void * arg)10582 l2arc_device_teardown(void *arg)
10583 {
10584 remove_vdev_args_t *rva = arg;
10585 l2arc_dev_t *remdev = rva->rva_l2arc_dev;
10586 hrtime_t start_time = gethrtime();
10587
10588 /*
10589 * Clear all buflists and ARC references. L2ARC device flush.
10590 */
10591 l2arc_evict(remdev, 0, B_TRUE);
10592 list_destroy(&remdev->l2ad_buflist);
10593 ASSERT(list_is_empty(&remdev->l2ad_lbptr_list));
10594 list_destroy(&remdev->l2ad_lbptr_list);
10595 mutex_destroy(&remdev->l2ad_mtx);
10596 mutex_destroy(&remdev->l2ad_feed_thr_lock);
10597 cv_destroy(&remdev->l2ad_feed_cv);
10598 zfs_refcount_destroy(&remdev->l2ad_alloc);
10599 zfs_refcount_destroy(&remdev->l2ad_lb_asize);
10600 zfs_refcount_destroy(&remdev->l2ad_lb_count);
10601 kmem_free(remdev->l2ad_dev_hdr, remdev->l2ad_dev_hdr_asize);
10602 vmem_free(remdev, sizeof (l2arc_dev_t));
10603
10604 uint64_t elapsed = NSEC2MSEC(gethrtime() - start_time);
10605 if (elapsed > 0) {
10606 zfs_dbgmsg("spa %llu, vdev %llu removed in %llu ms",
10607 (u_longlong_t)rva->rva_spa_gid,
10608 (u_longlong_t)rva->rva_vdev_gid,
10609 (u_longlong_t)elapsed);
10610 }
10611
10612 if (rva->rva_async)
10613 arc_async_flush_remove(rva->rva_spa_gid, 2);
10614 kmem_free(rva, sizeof (remove_vdev_args_t));
10615 }
10616
10617 /*
10618 * Remove a vdev from the L2ARC.
10619 */
10620 void
l2arc_remove_vdev(vdev_t * vd)10621 l2arc_remove_vdev(vdev_t *vd)
10622 {
10623 spa_t *spa = vd->vdev_spa;
10624 boolean_t asynchronous = spa->spa_state == POOL_STATE_EXPORTED ||
10625 spa->spa_state == POOL_STATE_DESTROYED;
10626
10627 /*
10628 * Find the device by vdev
10629 */
10630 l2arc_dev_t *remdev = l2arc_vdev_get(vd);
10631 ASSERT3P(remdev, !=, NULL);
10632
10633 /*
10634 * Save info for final teardown
10635 */
10636 remove_vdev_args_t *rva = kmem_alloc(sizeof (remove_vdev_args_t),
10637 KM_SLEEP);
10638 rva->rva_l2arc_dev = remdev;
10639 rva->rva_spa_gid = spa_load_guid(spa);
10640 rva->rva_vdev_gid = remdev->l2ad_vdev->vdev_guid;
10641
10642 /*
10643 * Cancel any ongoing or scheduled rebuild.
10644 */
10645 mutex_enter(&l2arc_rebuild_thr_lock);
10646 remdev->l2ad_rebuild_cancel = B_TRUE;
10647 if (remdev->l2ad_rebuild_began == B_TRUE) {
10648 while (remdev->l2ad_rebuild == B_TRUE)
10649 cv_wait(&l2arc_rebuild_thr_cv, &l2arc_rebuild_thr_lock);
10650 }
10651 mutex_exit(&l2arc_rebuild_thr_lock);
10652
10653 /*
10654 * Signal per-device feed thread to exit and wait for it.
10655 * Thread only exists if pool was imported read-write.
10656 */
10657 if (remdev->l2ad_feed_thread != NULL) {
10658 mutex_enter(&remdev->l2ad_feed_thr_lock);
10659 remdev->l2ad_thread_exit = B_TRUE;
10660 cv_signal(&remdev->l2ad_feed_cv);
10661 while (remdev->l2ad_feed_thread != NULL)
10662 cv_wait(&remdev->l2ad_feed_cv,
10663 &remdev->l2ad_feed_thr_lock);
10664 mutex_exit(&remdev->l2ad_feed_thr_lock);
10665 }
10666
10667 rva->rva_async = asynchronous;
10668
10669 /*
10670 * Remove device from global list
10671 */
10672 ASSERT(spa_config_held(spa, SCL_L2ARC, RW_WRITER) & SCL_L2ARC);
10673 mutex_enter(&l2arc_dev_mtx);
10674 list_remove(l2arc_dev_list, remdev);
10675 atomic_dec_64(&l2arc_ndev);
10676 spa->spa_l2arc_info.l2arc_total_capacity -=
10677 (remdev->l2ad_end - remdev->l2ad_start);
10678 l2arc_update_smallest_capacity(spa);
10679
10680 /*
10681 * Clean up pool-based markers if this was the last L2ARC device
10682 * for this pool
10683 */
10684 if (!l2arc_pool_has_devices(spa)) {
10685 l2arc_pool_markers_fini(spa);
10686 }
10687
10688 /* During a pool export spa & vdev will no longer be valid */
10689 if (asynchronous) {
10690 remdev->l2ad_spa = NULL;
10691 remdev->l2ad_vdev = NULL;
10692 }
10693 mutex_exit(&l2arc_dev_mtx);
10694
10695 if (!asynchronous) {
10696 l2arc_device_teardown(rva);
10697 return;
10698 }
10699
10700 arc_async_flush_t *af = arc_async_flush_add(rva->rva_spa_gid, 2);
10701
10702 taskq_dispatch_ent(arc_flush_taskq, l2arc_device_teardown, rva,
10703 TQ_SLEEP, &af->af_tqent);
10704 }
10705
10706 void
l2arc_init(void)10707 l2arc_init(void)
10708 {
10709 l2arc_ndev = 0;
10710
10711 mutex_init(&l2arc_rebuild_thr_lock, NULL, MUTEX_DEFAULT, NULL);
10712 cv_init(&l2arc_rebuild_thr_cv, NULL, CV_DEFAULT, NULL);
10713 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
10714 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
10715
10716 l2arc_dev_list = &L2ARC_dev_list;
10717 l2arc_free_on_write = &L2ARC_free_on_write;
10718 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
10719 offsetof(l2arc_dev_t, l2ad_node));
10720 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
10721 offsetof(l2arc_data_free_t, l2df_list_node));
10722 }
10723
10724 void
l2arc_fini(void)10725 l2arc_fini(void)
10726 {
10727 mutex_destroy(&l2arc_rebuild_thr_lock);
10728 cv_destroy(&l2arc_rebuild_thr_cv);
10729 mutex_destroy(&l2arc_dev_mtx);
10730 mutex_destroy(&l2arc_free_on_write_mtx);
10731
10732 list_destroy(l2arc_dev_list);
10733 list_destroy(l2arc_free_on_write);
10734 }
10735
10736
10737 /*
10738 * Punches out rebuild threads for the L2ARC devices in a spa. This should
10739 * be called after pool import from the spa async thread, since starting
10740 * these threads directly from spa_import() will make them part of the
10741 * "zpool import" context and delay process exit (and thus pool import).
10742 */
10743 void
l2arc_spa_rebuild_start(spa_t * spa)10744 l2arc_spa_rebuild_start(spa_t *spa)
10745 {
10746 ASSERT(spa_namespace_held());
10747
10748 /*
10749 * Locate the spa's l2arc devices and kick off rebuild threads.
10750 */
10751 for (int i = 0; i < spa->spa_l2cache.sav_count; i++) {
10752 l2arc_dev_t *dev =
10753 l2arc_vdev_get(spa->spa_l2cache.sav_vdevs[i]);
10754 if (dev == NULL) {
10755 /* Don't attempt a rebuild if the vdev is UNAVAIL */
10756 continue;
10757 }
10758 mutex_enter(&l2arc_rebuild_thr_lock);
10759 if (dev->l2ad_rebuild && !dev->l2ad_rebuild_cancel) {
10760 dev->l2ad_rebuild_began = B_TRUE;
10761 (void) thread_create(NULL, 0, l2arc_dev_rebuild_thread,
10762 dev, 0, &p0, TS_RUN, minclsyspri);
10763 }
10764 mutex_exit(&l2arc_rebuild_thr_lock);
10765 }
10766 }
10767
10768 void
l2arc_spa_rebuild_stop(spa_t * spa)10769 l2arc_spa_rebuild_stop(spa_t *spa)
10770 {
10771 ASSERT(spa_namespace_held() ||
10772 spa->spa_export_thread == curthread);
10773
10774 for (int i = 0; i < spa->spa_l2cache.sav_count; i++) {
10775 l2arc_dev_t *dev =
10776 l2arc_vdev_get(spa->spa_l2cache.sav_vdevs[i]);
10777 if (dev == NULL)
10778 continue;
10779 mutex_enter(&l2arc_rebuild_thr_lock);
10780 dev->l2ad_rebuild_cancel = B_TRUE;
10781 mutex_exit(&l2arc_rebuild_thr_lock);
10782 }
10783 for (int i = 0; i < spa->spa_l2cache.sav_count; i++) {
10784 l2arc_dev_t *dev =
10785 l2arc_vdev_get(spa->spa_l2cache.sav_vdevs[i]);
10786 if (dev == NULL)
10787 continue;
10788 mutex_enter(&l2arc_rebuild_thr_lock);
10789 if (dev->l2ad_rebuild_began == B_TRUE) {
10790 while (dev->l2ad_rebuild == B_TRUE) {
10791 cv_wait(&l2arc_rebuild_thr_cv,
10792 &l2arc_rebuild_thr_lock);
10793 }
10794 }
10795 mutex_exit(&l2arc_rebuild_thr_lock);
10796 }
10797 }
10798
10799 /*
10800 * Main entry point for L2ARC rebuilding.
10801 */
10802 static __attribute__((noreturn)) void
l2arc_dev_rebuild_thread(void * arg)10803 l2arc_dev_rebuild_thread(void *arg)
10804 {
10805 l2arc_dev_t *dev = arg;
10806
10807 VERIFY(dev->l2ad_rebuild);
10808 (void) l2arc_rebuild(dev);
10809 mutex_enter(&l2arc_rebuild_thr_lock);
10810 dev->l2ad_rebuild_began = B_FALSE;
10811 dev->l2ad_rebuild = B_FALSE;
10812 cv_signal(&l2arc_rebuild_thr_cv);
10813 mutex_exit(&l2arc_rebuild_thr_lock);
10814
10815 thread_exit();
10816 }
10817
10818 /*
10819 * This function implements the actual L2ARC metadata rebuild. It:
10820 * starts reading the log block chain and restores each block's contents
10821 * to memory (reconstructing arc_buf_hdr_t's).
10822 *
10823 * Operation stops under any of the following conditions:
10824 *
10825 * 1) We reach the end of the log block chain.
10826 * 2) We encounter *any* error condition (cksum errors, io errors)
10827 */
10828 static int
l2arc_rebuild(l2arc_dev_t * dev)10829 l2arc_rebuild(l2arc_dev_t *dev)
10830 {
10831 vdev_t *vd = dev->l2ad_vdev;
10832 spa_t *spa = vd->vdev_spa;
10833 int err = 0;
10834 l2arc_dev_hdr_phys_t *l2dhdr = dev->l2ad_dev_hdr;
10835 l2arc_log_blk_phys_t *this_lb, *next_lb;
10836 zio_t *this_io = NULL, *next_io = NULL;
10837 l2arc_log_blkptr_t lbps[2];
10838 l2arc_lb_ptr_buf_t *lb_ptr_buf;
10839 boolean_t lock_held;
10840
10841 this_lb = vmem_zalloc(sizeof (*this_lb), KM_SLEEP);
10842 next_lb = vmem_zalloc(sizeof (*next_lb), KM_SLEEP);
10843
10844 /*
10845 * We prevent device removal while issuing reads to the device,
10846 * then during the rebuilding phases we drop this lock again so
10847 * that a spa_unload or device remove can be initiated - this is
10848 * safe, because the spa will signal us to stop before removing
10849 * our device and wait for us to stop.
10850 */
10851 spa_config_enter(spa, SCL_L2ARC, vd, RW_READER);
10852 lock_held = B_TRUE;
10853
10854 /*
10855 * Retrieve the persistent L2ARC device state.
10856 * L2BLK_GET_PSIZE returns aligned size for log blocks.
10857 */
10858 dev->l2ad_evict = MAX(l2dhdr->dh_evict, dev->l2ad_start);
10859 dev->l2ad_hand = MAX(l2dhdr->dh_start_lbps[0].lbp_daddr +
10860 L2BLK_GET_PSIZE((&l2dhdr->dh_start_lbps[0])->lbp_prop),
10861 dev->l2ad_start);
10862 dev->l2ad_first = !!(l2dhdr->dh_flags & L2ARC_DEV_HDR_EVICT_FIRST);
10863
10864 vd->vdev_trim_action_time = l2dhdr->dh_trim_action_time;
10865 vd->vdev_trim_state = l2dhdr->dh_trim_state;
10866
10867 /*
10868 * In case the zfs module parameter l2arc_rebuild_enabled is false
10869 * we do not start the rebuild process.
10870 */
10871 if (!l2arc_rebuild_enabled)
10872 goto out;
10873
10874 /* Prepare the rebuild process */
10875 memcpy(lbps, l2dhdr->dh_start_lbps, sizeof (lbps));
10876
10877 /* Start the rebuild process */
10878 for (;;) {
10879 if (!l2arc_log_blkptr_valid(dev, &lbps[0]))
10880 break;
10881
10882 if ((err = l2arc_log_blk_read(dev, &lbps[0], &lbps[1],
10883 this_lb, next_lb, this_io, &next_io)) != 0)
10884 goto out;
10885
10886 /*
10887 * Our memory pressure valve. If the system is running low
10888 * on memory, rather than swamping memory with new ARC buf
10889 * hdrs, we opt not to rebuild the L2ARC. At this point,
10890 * however, we have already set up our L2ARC dev to chain in
10891 * new metadata log blocks, so the user may choose to offline/
10892 * online the L2ARC dev at a later time (or re-import the pool)
10893 * to reconstruct it (when there's less memory pressure).
10894 */
10895 if (l2arc_hdr_limit_reached()) {
10896 ARCSTAT_BUMP(arcstat_l2_rebuild_abort_lowmem);
10897 cmn_err(CE_NOTE, "System running low on memory, "
10898 "aborting L2ARC rebuild.");
10899 err = SET_ERROR(ENOMEM);
10900 goto out;
10901 }
10902
10903 spa_config_exit(spa, SCL_L2ARC, vd);
10904 lock_held = B_FALSE;
10905
10906 /*
10907 * Now that we know that the next_lb checks out alright, we
10908 * can start reconstruction from this log block.
10909 * L2BLK_GET_PSIZE returns aligned size for log blocks.
10910 */
10911 uint64_t asize = L2BLK_GET_PSIZE((&lbps[0])->lbp_prop);
10912 l2arc_log_blk_restore(dev, this_lb, asize);
10913
10914 /*
10915 * log block restored, include its pointer in the list of
10916 * pointers to log blocks present in the L2ARC device.
10917 */
10918 lb_ptr_buf = kmem_zalloc(sizeof (l2arc_lb_ptr_buf_t), KM_SLEEP);
10919 lb_ptr_buf->lb_ptr = kmem_zalloc(sizeof (l2arc_log_blkptr_t),
10920 KM_SLEEP);
10921 memcpy(lb_ptr_buf->lb_ptr, &lbps[0],
10922 sizeof (l2arc_log_blkptr_t));
10923 mutex_enter(&dev->l2ad_mtx);
10924 list_insert_tail(&dev->l2ad_lbptr_list, lb_ptr_buf);
10925 ARCSTAT_INCR(arcstat_l2_log_blk_asize, asize);
10926 ARCSTAT_BUMP(arcstat_l2_log_blk_count);
10927 zfs_refcount_add_many(&dev->l2ad_lb_asize, asize, lb_ptr_buf);
10928 zfs_refcount_add(&dev->l2ad_lb_count, lb_ptr_buf);
10929 mutex_exit(&dev->l2ad_mtx);
10930 vdev_space_update(vd, asize, 0, 0);
10931
10932 /*
10933 * Protection against loops of log blocks:
10934 *
10935 * l2ad_hand l2ad_evict
10936 * V V
10937 * l2ad_start |=======================================| l2ad_end
10938 * -----|||----|||---|||----|||
10939 * (3) (2) (1) (0)
10940 * ---|||---|||----|||---|||
10941 * (7) (6) (5) (4)
10942 *
10943 * In this situation the pointer of log block (4) passes
10944 * l2arc_log_blkptr_valid() but the log block should not be
10945 * restored as it is overwritten by the payload of log block
10946 * (0). Only log blocks (0)-(3) should be restored. We check
10947 * whether l2ad_evict lies in between the payload starting
10948 * offset of the next log block (lbps[1].lbp_payload_start)
10949 * and the payload starting offset of the present log block
10950 * (lbps[0].lbp_payload_start). If true and this isn't the
10951 * first pass, we are looping from the beginning and we should
10952 * stop.
10953 */
10954 if (l2arc_range_check_overlap(lbps[1].lbp_payload_start,
10955 lbps[0].lbp_payload_start, dev->l2ad_evict) &&
10956 !dev->l2ad_first)
10957 goto out;
10958
10959 kpreempt(KPREEMPT_SYNC);
10960 for (;;) {
10961 mutex_enter(&l2arc_rebuild_thr_lock);
10962 if (dev->l2ad_rebuild_cancel) {
10963 mutex_exit(&l2arc_rebuild_thr_lock);
10964 err = SET_ERROR(ECANCELED);
10965 goto out;
10966 }
10967 mutex_exit(&l2arc_rebuild_thr_lock);
10968 if (spa_config_tryenter(spa, SCL_L2ARC, vd,
10969 RW_READER)) {
10970 lock_held = B_TRUE;
10971 break;
10972 }
10973 /*
10974 * L2ARC config lock held by somebody in writer,
10975 * possibly due to them trying to remove us. They'll
10976 * likely to want us to shut down, so after a little
10977 * delay, we check l2ad_rebuild_cancel and retry
10978 * the lock again.
10979 */
10980 delay(1);
10981 }
10982
10983 /*
10984 * Continue with the next log block.
10985 */
10986 lbps[0] = lbps[1];
10987 lbps[1] = this_lb->lb_prev_lbp;
10988 PTR_SWAP(this_lb, next_lb);
10989 this_io = next_io;
10990 next_io = NULL;
10991 }
10992
10993 if (this_io != NULL)
10994 l2arc_log_blk_fetch_abort(this_io);
10995 out:
10996 if (next_io != NULL)
10997 l2arc_log_blk_fetch_abort(next_io);
10998 vmem_free(this_lb, sizeof (*this_lb));
10999 vmem_free(next_lb, sizeof (*next_lb));
11000
11001 if (err == ECANCELED) {
11002 /*
11003 * In case the rebuild was canceled do not log to spa history
11004 * log as the pool may be in the process of being removed.
11005 */
11006 zfs_dbgmsg("L2ARC rebuild aborted, restored %llu blocks",
11007 (u_longlong_t)zfs_refcount_count(&dev->l2ad_lb_count));
11008 return (err);
11009 } else if (!l2arc_rebuild_enabled) {
11010 spa_history_log_internal(spa, "L2ARC rebuild", NULL,
11011 "disabled");
11012 } else if (err == 0 && zfs_refcount_count(&dev->l2ad_lb_count) > 0) {
11013 ARCSTAT_BUMP(arcstat_l2_rebuild_success);
11014 spa_history_log_internal(spa, "L2ARC rebuild", NULL,
11015 "successful, restored %llu blocks",
11016 (u_longlong_t)zfs_refcount_count(&dev->l2ad_lb_count));
11017 } else if (err == 0 && zfs_refcount_count(&dev->l2ad_lb_count) == 0) {
11018 /*
11019 * No error but also nothing restored, meaning the lbps array
11020 * in the device header points to invalid/non-present log
11021 * blocks. Reset the header.
11022 */
11023 spa_history_log_internal(spa, "L2ARC rebuild", NULL,
11024 "no valid log blocks");
11025 memset(l2dhdr, 0, dev->l2ad_dev_hdr_asize);
11026 l2arc_dev_hdr_update(dev);
11027 } else if (err != 0) {
11028 spa_history_log_internal(spa, "L2ARC rebuild", NULL,
11029 "aborted, restored %llu blocks",
11030 (u_longlong_t)zfs_refcount_count(&dev->l2ad_lb_count));
11031 }
11032
11033 if (lock_held)
11034 spa_config_exit(spa, SCL_L2ARC, vd);
11035
11036 return (err);
11037 }
11038
11039 /*
11040 * Attempts to read the device header on the provided L2ARC device and writes
11041 * it to `hdr'. On success, this function returns 0, otherwise the appropriate
11042 * error code is returned.
11043 */
11044 static int
l2arc_dev_hdr_read(l2arc_dev_t * dev)11045 l2arc_dev_hdr_read(l2arc_dev_t *dev)
11046 {
11047 int err;
11048 uint64_t guid;
11049 l2arc_dev_hdr_phys_t *l2dhdr = dev->l2ad_dev_hdr;
11050 const uint64_t l2dhdr_asize = dev->l2ad_dev_hdr_asize;
11051 abd_t *abd;
11052
11053 guid = spa_guid(dev->l2ad_vdev->vdev_spa);
11054
11055 abd = abd_get_from_buf(l2dhdr, l2dhdr_asize);
11056
11057 err = zio_wait(zio_read_phys(NULL, dev->l2ad_vdev,
11058 VDEV_LABEL_START_SIZE, l2dhdr_asize, abd,
11059 ZIO_CHECKSUM_LABEL, NULL, NULL, ZIO_PRIORITY_SYNC_READ,
11060 ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY |
11061 ZIO_FLAG_SPECULATIVE, B_FALSE));
11062
11063 abd_free(abd);
11064
11065 if (err != 0) {
11066 ARCSTAT_BUMP(arcstat_l2_rebuild_abort_dh_errors);
11067 zfs_dbgmsg("L2ARC IO error (%d) while reading device header, "
11068 "vdev guid: %llu", err,
11069 (u_longlong_t)dev->l2ad_vdev->vdev_guid);
11070 return (err);
11071 }
11072
11073 if (l2dhdr->dh_magic == BSWAP_64(L2ARC_DEV_HDR_MAGIC))
11074 byteswap_uint64_array(l2dhdr, sizeof (*l2dhdr));
11075
11076 if (l2dhdr->dh_magic != L2ARC_DEV_HDR_MAGIC ||
11077 l2dhdr->dh_spa_guid != guid ||
11078 l2dhdr->dh_vdev_guid != dev->l2ad_vdev->vdev_guid ||
11079 l2dhdr->dh_version != L2ARC_PERSISTENT_VERSION ||
11080 l2dhdr->dh_log_entries != dev->l2ad_log_entries ||
11081 l2dhdr->dh_end != dev->l2ad_end ||
11082 !l2arc_range_check_overlap(dev->l2ad_start, dev->l2ad_end,
11083 l2dhdr->dh_evict) ||
11084 (l2dhdr->dh_trim_state != VDEV_TRIM_COMPLETE &&
11085 l2arc_trim_ahead > 0)) {
11086 /*
11087 * Attempt to rebuild a device containing no actual dev hdr
11088 * or containing a header from some other pool or from another
11089 * version of persistent L2ARC.
11090 */
11091 ARCSTAT_BUMP(arcstat_l2_rebuild_abort_unsupported);
11092 return (SET_ERROR(ENOTSUP));
11093 }
11094
11095 return (0);
11096 }
11097
11098 /*
11099 * Reads L2ARC log blocks from storage and validates their contents.
11100 *
11101 * This function implements a simple fetcher to make sure that while
11102 * we're processing one buffer the L2ARC is already fetching the next
11103 * one in the chain.
11104 *
11105 * The arguments this_lp and next_lp point to the current and next log block
11106 * address in the block chain. Similarly, this_lb and next_lb hold the
11107 * l2arc_log_blk_phys_t's of the current and next L2ARC blk.
11108 *
11109 * The `this_io' and `next_io' arguments are used for block fetching.
11110 * When issuing the first blk IO during rebuild, you should pass NULL for
11111 * `this_io'. This function will then issue a sync IO to read the block and
11112 * also issue an async IO to fetch the next block in the block chain. The
11113 * fetched IO is returned in `next_io'. On subsequent calls to this
11114 * function, pass the value returned in `next_io' from the previous call
11115 * as `this_io' and a fresh `next_io' pointer to hold the next fetch IO.
11116 * Prior to the call, you should initialize your `next_io' pointer to be
11117 * NULL. If no fetch IO was issued, the pointer is left set at NULL.
11118 *
11119 * On success, this function returns 0, otherwise it returns an appropriate
11120 * error code. On error the fetching IO is aborted and cleared before
11121 * returning from this function. Therefore, if we return `success', the
11122 * caller can assume that we have taken care of cleanup of fetch IOs.
11123 */
11124 static int
l2arc_log_blk_read(l2arc_dev_t * dev,const l2arc_log_blkptr_t * this_lbp,const l2arc_log_blkptr_t * next_lbp,l2arc_log_blk_phys_t * this_lb,l2arc_log_blk_phys_t * next_lb,zio_t * this_io,zio_t ** next_io)11125 l2arc_log_blk_read(l2arc_dev_t *dev,
11126 const l2arc_log_blkptr_t *this_lbp, const l2arc_log_blkptr_t *next_lbp,
11127 l2arc_log_blk_phys_t *this_lb, l2arc_log_blk_phys_t *next_lb,
11128 zio_t *this_io, zio_t **next_io)
11129 {
11130 int err = 0;
11131 zio_cksum_t cksum;
11132 uint64_t asize;
11133
11134 ASSERT(this_lbp != NULL && next_lbp != NULL);
11135 ASSERT(this_lb != NULL && next_lb != NULL);
11136 ASSERT(next_io != NULL && *next_io == NULL);
11137 ASSERT(l2arc_log_blkptr_valid(dev, this_lbp));
11138
11139 /*
11140 * Check to see if we have issued the IO for this log block in a
11141 * previous run. If not, this is the first call, so issue it now.
11142 */
11143 if (this_io == NULL) {
11144 this_io = l2arc_log_blk_fetch(dev->l2ad_vdev, this_lbp,
11145 this_lb);
11146 }
11147
11148 /*
11149 * Peek to see if we can start issuing the next IO immediately.
11150 */
11151 if (l2arc_log_blkptr_valid(dev, next_lbp)) {
11152 /*
11153 * Start issuing IO for the next log block early - this
11154 * should help keep the L2ARC device busy while we
11155 * decompress and restore this log block.
11156 */
11157 *next_io = l2arc_log_blk_fetch(dev->l2ad_vdev, next_lbp,
11158 next_lb);
11159 }
11160
11161 /* Wait for the IO to read this log block to complete */
11162 if ((err = zio_wait(this_io)) != 0) {
11163 ARCSTAT_BUMP(arcstat_l2_rebuild_abort_io_errors);
11164 zfs_dbgmsg("L2ARC IO error (%d) while reading log block, "
11165 "offset: %llu, vdev guid: %llu", err,
11166 (u_longlong_t)this_lbp->lbp_daddr,
11167 (u_longlong_t)dev->l2ad_vdev->vdev_guid);
11168 goto cleanup;
11169 }
11170
11171 /*
11172 * Make sure the buffer checks out.
11173 * L2BLK_GET_PSIZE returns aligned size for log blocks.
11174 */
11175 asize = L2BLK_GET_PSIZE((this_lbp)->lbp_prop);
11176 fletcher_4_native(this_lb, asize, NULL, &cksum);
11177 if (!ZIO_CHECKSUM_EQUAL(cksum, this_lbp->lbp_cksum)) {
11178 ARCSTAT_BUMP(arcstat_l2_rebuild_abort_cksum_lb_errors);
11179 zfs_dbgmsg("L2ARC log block cksum failed, offset: %llu, "
11180 "vdev guid: %llu, l2ad_hand: %llu, l2ad_evict: %llu",
11181 (u_longlong_t)this_lbp->lbp_daddr,
11182 (u_longlong_t)dev->l2ad_vdev->vdev_guid,
11183 (u_longlong_t)dev->l2ad_hand,
11184 (u_longlong_t)dev->l2ad_evict);
11185 err = SET_ERROR(ECKSUM);
11186 goto cleanup;
11187 }
11188
11189 /* Now we can take our time decoding this buffer */
11190 switch (L2BLK_GET_COMPRESS((this_lbp)->lbp_prop)) {
11191 case ZIO_COMPRESS_OFF:
11192 break;
11193 case ZIO_COMPRESS_LZ4: {
11194 abd_t *abd = abd_alloc_linear(asize, B_TRUE);
11195 abd_copy_from_buf_off(abd, this_lb, 0, asize);
11196 abd_t dabd;
11197 abd_get_from_buf_struct(&dabd, this_lb, sizeof (*this_lb));
11198 err = zio_decompress_data(
11199 L2BLK_GET_COMPRESS((this_lbp)->lbp_prop),
11200 abd, &dabd, asize, sizeof (*this_lb), NULL);
11201 abd_free(&dabd);
11202 abd_free(abd);
11203 if (err != 0) {
11204 err = SET_ERROR(EINVAL);
11205 goto cleanup;
11206 }
11207 break;
11208 }
11209 default:
11210 err = SET_ERROR(EINVAL);
11211 goto cleanup;
11212 }
11213 if (this_lb->lb_magic == BSWAP_64(L2ARC_LOG_BLK_MAGIC))
11214 byteswap_uint64_array(this_lb, sizeof (*this_lb));
11215 if (this_lb->lb_magic != L2ARC_LOG_BLK_MAGIC) {
11216 err = SET_ERROR(EINVAL);
11217 goto cleanup;
11218 }
11219 cleanup:
11220 /* Abort an in-flight fetch I/O in case of error */
11221 if (err != 0 && *next_io != NULL) {
11222 l2arc_log_blk_fetch_abort(*next_io);
11223 *next_io = NULL;
11224 }
11225 return (err);
11226 }
11227
11228 /*
11229 * Restores the payload of a log block to ARC. This creates empty ARC hdr
11230 * entries which only contain an l2arc hdr, essentially restoring the
11231 * buffers to their L2ARC evicted state. This function also updates space
11232 * usage on the L2ARC vdev to make sure it tracks restored buffers.
11233 */
11234 static void
l2arc_log_blk_restore(l2arc_dev_t * dev,const l2arc_log_blk_phys_t * lb,uint64_t lb_asize)11235 l2arc_log_blk_restore(l2arc_dev_t *dev, const l2arc_log_blk_phys_t *lb,
11236 uint64_t lb_asize)
11237 {
11238 uint64_t size = 0, asize = 0;
11239 uint64_t log_entries = dev->l2ad_log_entries;
11240
11241 /*
11242 * Usually arc_adapt() is called only for data, not headers, but
11243 * since we may allocate significant amount of memory here, let ARC
11244 * grow its arc_c.
11245 */
11246 arc_adapt(log_entries * HDR_L2ONLY_SIZE);
11247
11248 for (int i = log_entries - 1; i >= 0; i--) {
11249 /*
11250 * Restore goes in the reverse temporal direction to preserve
11251 * correct temporal ordering of buffers in the l2ad_buflist.
11252 * l2arc_hdr_restore also does a list_insert_tail instead of
11253 * list_insert_head on the l2ad_buflist:
11254 *
11255 * LIST l2ad_buflist LIST
11256 * HEAD <------ (time) ------ TAIL
11257 * direction +-----+-----+-----+-----+-----+ direction
11258 * of l2arc <== | buf | buf | buf | buf | buf | ===> of rebuild
11259 * fill +-----+-----+-----+-----+-----+
11260 * ^ ^
11261 * | |
11262 * | |
11263 * l2arc_feed_thread l2arc_rebuild
11264 * will place new bufs here restores bufs here
11265 *
11266 * During l2arc_rebuild() the device is not used by
11267 * l2arc_feed_thread() as dev->l2ad_rebuild is set to true.
11268 */
11269 size += L2BLK_GET_LSIZE((&lb->lb_entries[i])->le_prop);
11270 asize += vdev_psize_to_asize(dev->l2ad_vdev,
11271 L2BLK_GET_PSIZE((&lb->lb_entries[i])->le_prop));
11272 l2arc_hdr_restore(&lb->lb_entries[i], dev);
11273 }
11274
11275 /*
11276 * Record rebuild stats:
11277 * size Logical size of restored buffers in the L2ARC
11278 * asize Aligned size of restored buffers in the L2ARC
11279 */
11280 ARCSTAT_INCR(arcstat_l2_rebuild_size, size);
11281 ARCSTAT_INCR(arcstat_l2_rebuild_asize, asize);
11282 ARCSTAT_INCR(arcstat_l2_rebuild_bufs, log_entries);
11283 ARCSTAT_F_AVG(arcstat_l2_log_blk_avg_asize, lb_asize);
11284 ARCSTAT_F_AVG(arcstat_l2_data_to_meta_ratio, asize / lb_asize);
11285 ARCSTAT_BUMP(arcstat_l2_rebuild_log_blks);
11286 }
11287
11288 /*
11289 * Restores a single ARC buf hdr from a log entry. The ARC buffer is put
11290 * into a state indicating that it has been evicted to L2ARC.
11291 */
11292 static void
l2arc_hdr_restore(const l2arc_log_ent_phys_t * le,l2arc_dev_t * dev)11293 l2arc_hdr_restore(const l2arc_log_ent_phys_t *le, l2arc_dev_t *dev)
11294 {
11295 arc_buf_hdr_t *hdr, *exists;
11296 kmutex_t *hash_lock;
11297 arc_buf_contents_t type = L2BLK_GET_TYPE((le)->le_prop);
11298 uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev,
11299 L2BLK_GET_PSIZE((le)->le_prop));
11300
11301 /*
11302 * Do all the allocation before grabbing any locks, this lets us
11303 * sleep if memory is full and we don't have to deal with failed
11304 * allocations.
11305 */
11306 hdr = arc_buf_alloc_l2only(L2BLK_GET_LSIZE((le)->le_prop), type,
11307 dev, le->le_dva, le->le_daddr,
11308 L2BLK_GET_PSIZE((le)->le_prop), asize, le->le_birth,
11309 L2BLK_GET_COMPRESS((le)->le_prop), le->le_complevel,
11310 L2BLK_GET_PROTECTED((le)->le_prop),
11311 L2BLK_GET_PREFETCH((le)->le_prop),
11312 L2BLK_GET_STATE((le)->le_prop));
11313
11314 /*
11315 * vdev_space_update() has to be called before arc_hdr_destroy() to
11316 * avoid underflow since the latter also calls vdev_space_update().
11317 */
11318 l2arc_hdr_arcstats_increment(hdr);
11319 vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
11320
11321 mutex_enter(&dev->l2ad_mtx);
11322 list_insert_tail(&dev->l2ad_buflist, hdr);
11323 (void) zfs_refcount_add_many(&dev->l2ad_alloc, arc_hdr_size(hdr), hdr);
11324 mutex_exit(&dev->l2ad_mtx);
11325
11326 exists = buf_hash_insert(hdr, &hash_lock);
11327 if (exists) {
11328 /* Buffer was already cached, no need to restore it. */
11329 arc_hdr_destroy(hdr);
11330 /*
11331 * If the buffer is already cached, check whether it has
11332 * L2ARC metadata. If not, enter them and update the flag.
11333 * This is important is case of onlining a cache device, since
11334 * we previously evicted all L2ARC metadata from ARC.
11335 */
11336 if (!HDR_HAS_L2HDR(exists)) {
11337 arc_hdr_set_flags(exists, ARC_FLAG_HAS_L2HDR);
11338 exists->b_l2hdr.b_dev = dev;
11339 exists->b_l2hdr.b_daddr = le->le_daddr;
11340 exists->b_l2hdr.b_arcs_state =
11341 L2BLK_GET_STATE((le)->le_prop);
11342 /* l2arc_hdr_arcstats_update() expects a valid asize */
11343 HDR_SET_L2SIZE(exists, asize);
11344 mutex_enter(&dev->l2ad_mtx);
11345 list_insert_tail(&dev->l2ad_buflist, exists);
11346 (void) zfs_refcount_add_many(&dev->l2ad_alloc,
11347 arc_hdr_size(exists), exists);
11348 mutex_exit(&dev->l2ad_mtx);
11349 l2arc_hdr_arcstats_increment(exists);
11350 vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
11351 }
11352 ARCSTAT_BUMP(arcstat_l2_rebuild_bufs_precached);
11353 }
11354
11355 mutex_exit(hash_lock);
11356 }
11357
11358 /*
11359 * Starts an asynchronous read IO to read a log block. This is used in log
11360 * block reconstruction to start reading the next block before we are done
11361 * decoding and reconstructing the current block, to keep the l2arc device
11362 * nice and hot with read IO to process.
11363 * The returned zio will contain a newly allocated memory buffers for the IO
11364 * data which should then be freed by the caller once the zio is no longer
11365 * needed (i.e. due to it having completed). If you wish to abort this
11366 * zio, you should do so using l2arc_log_blk_fetch_abort, which takes
11367 * care of disposing of the allocated buffers correctly.
11368 */
11369 static zio_t *
l2arc_log_blk_fetch(vdev_t * vd,const l2arc_log_blkptr_t * lbp,l2arc_log_blk_phys_t * lb)11370 l2arc_log_blk_fetch(vdev_t *vd, const l2arc_log_blkptr_t *lbp,
11371 l2arc_log_blk_phys_t *lb)
11372 {
11373 uint32_t asize;
11374 zio_t *pio;
11375 l2arc_read_callback_t *cb;
11376
11377 /* L2BLK_GET_PSIZE returns aligned size for log blocks */
11378 asize = L2BLK_GET_PSIZE((lbp)->lbp_prop);
11379 ASSERT(asize <= sizeof (l2arc_log_blk_phys_t));
11380
11381 cb = kmem_zalloc(sizeof (l2arc_read_callback_t), KM_SLEEP);
11382 cb->l2rcb_abd = abd_get_from_buf(lb, asize);
11383 pio = zio_root(vd->vdev_spa, l2arc_blk_fetch_done, cb,
11384 ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY);
11385 (void) zio_nowait(zio_read_phys(pio, vd, lbp->lbp_daddr, asize,
11386 cb->l2rcb_abd, ZIO_CHECKSUM_OFF, NULL, NULL,
11387 ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL |
11388 ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY, B_FALSE));
11389
11390 return (pio);
11391 }
11392
11393 /*
11394 * Aborts a zio returned from l2arc_log_blk_fetch and frees the data
11395 * buffers allocated for it.
11396 */
11397 static void
l2arc_log_blk_fetch_abort(zio_t * zio)11398 l2arc_log_blk_fetch_abort(zio_t *zio)
11399 {
11400 (void) zio_wait(zio);
11401 }
11402
11403 /*
11404 * Creates a zio to update the device header on an l2arc device.
11405 */
11406 void
l2arc_dev_hdr_update(l2arc_dev_t * dev)11407 l2arc_dev_hdr_update(l2arc_dev_t *dev)
11408 {
11409 l2arc_dev_hdr_phys_t *l2dhdr = dev->l2ad_dev_hdr;
11410 const uint64_t l2dhdr_asize = dev->l2ad_dev_hdr_asize;
11411 abd_t *abd;
11412 int err;
11413
11414 VERIFY(spa_config_held(dev->l2ad_spa, SCL_STATE_ALL, RW_READER));
11415
11416 l2dhdr->dh_magic = L2ARC_DEV_HDR_MAGIC;
11417 l2dhdr->dh_version = L2ARC_PERSISTENT_VERSION;
11418 l2dhdr->dh_spa_guid = spa_guid(dev->l2ad_vdev->vdev_spa);
11419 l2dhdr->dh_vdev_guid = dev->l2ad_vdev->vdev_guid;
11420 l2dhdr->dh_log_entries = dev->l2ad_log_entries;
11421 l2dhdr->dh_evict = dev->l2ad_evict;
11422 l2dhdr->dh_start = dev->l2ad_start;
11423 l2dhdr->dh_end = dev->l2ad_end;
11424 l2dhdr->dh_lb_asize = zfs_refcount_count(&dev->l2ad_lb_asize);
11425 l2dhdr->dh_lb_count = zfs_refcount_count(&dev->l2ad_lb_count);
11426 l2dhdr->dh_flags = 0;
11427 l2dhdr->dh_trim_action_time = dev->l2ad_vdev->vdev_trim_action_time;
11428 l2dhdr->dh_trim_state = dev->l2ad_vdev->vdev_trim_state;
11429 if (dev->l2ad_first)
11430 l2dhdr->dh_flags |= L2ARC_DEV_HDR_EVICT_FIRST;
11431
11432 abd = abd_get_from_buf(l2dhdr, l2dhdr_asize);
11433
11434 err = zio_wait(zio_write_phys(NULL, dev->l2ad_vdev,
11435 VDEV_LABEL_START_SIZE, l2dhdr_asize, abd, ZIO_CHECKSUM_LABEL, NULL,
11436 NULL, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_CANFAIL, B_FALSE));
11437
11438 abd_free(abd);
11439
11440 if (err != 0) {
11441 zfs_dbgmsg("L2ARC IO error (%d) while writing device header, "
11442 "vdev guid: %llu", err,
11443 (u_longlong_t)dev->l2ad_vdev->vdev_guid);
11444 }
11445 }
11446
11447 /*
11448 * Commits a log block to the L2ARC device. This routine is invoked from
11449 * l2arc_write_buffers when the log block fills up.
11450 * This function allocates some memory to temporarily hold the serialized
11451 * buffer to be written. This is then released in l2arc_write_done.
11452 */
11453 static uint64_t
l2arc_log_blk_commit(l2arc_dev_t * dev,zio_t * pio,l2arc_write_callback_t * cb)11454 l2arc_log_blk_commit(l2arc_dev_t *dev, zio_t *pio, l2arc_write_callback_t *cb)
11455 {
11456 l2arc_log_blk_phys_t *lb = &dev->l2ad_log_blk;
11457 l2arc_dev_hdr_phys_t *l2dhdr = dev->l2ad_dev_hdr;
11458 uint64_t psize, asize;
11459 zio_t *wzio;
11460 l2arc_lb_abd_buf_t *abd_buf;
11461 abd_t *abd = NULL;
11462 l2arc_lb_ptr_buf_t *lb_ptr_buf;
11463
11464 VERIFY3S(dev->l2ad_log_ent_idx, ==, dev->l2ad_log_entries);
11465
11466 abd_buf = zio_buf_alloc(sizeof (*abd_buf));
11467 abd_buf->abd = abd_get_from_buf(lb, sizeof (*lb));
11468 lb_ptr_buf = kmem_zalloc(sizeof (l2arc_lb_ptr_buf_t), KM_SLEEP);
11469 lb_ptr_buf->lb_ptr = kmem_zalloc(sizeof (l2arc_log_blkptr_t), KM_SLEEP);
11470
11471 /* link the buffer into the block chain */
11472 lb->lb_prev_lbp = l2dhdr->dh_start_lbps[1];
11473 lb->lb_magic = L2ARC_LOG_BLK_MAGIC;
11474
11475 /*
11476 * l2arc_log_blk_commit() may be called multiple times during a single
11477 * l2arc_write_buffers() call. Save the allocated abd buffers in a list
11478 * so we can free them in l2arc_write_done() later on.
11479 */
11480 list_insert_tail(&cb->l2wcb_abd_list, abd_buf);
11481
11482 /* try to compress the buffer, at least one sector to save */
11483 psize = zio_compress_data(ZIO_COMPRESS_LZ4,
11484 abd_buf->abd, &abd, sizeof (*lb),
11485 zio_get_compression_max_size(ZIO_COMPRESS_LZ4,
11486 dev->l2ad_vdev->vdev_ashift,
11487 dev->l2ad_vdev->vdev_ashift, sizeof (*lb)), 0);
11488
11489 /* a log block is never entirely zero */
11490 ASSERT(psize != 0);
11491 asize = vdev_psize_to_asize(dev->l2ad_vdev, psize);
11492 ASSERT(asize <= sizeof (*lb));
11493
11494 /*
11495 * Update the start log block pointer in the device header to point
11496 * to the log block we're about to write.
11497 */
11498 l2dhdr->dh_start_lbps[1] = l2dhdr->dh_start_lbps[0];
11499 l2dhdr->dh_start_lbps[0].lbp_daddr = dev->l2ad_hand;
11500 l2dhdr->dh_start_lbps[0].lbp_payload_asize =
11501 dev->l2ad_log_blk_payload_asize;
11502 l2dhdr->dh_start_lbps[0].lbp_payload_start =
11503 dev->l2ad_log_blk_payload_start;
11504 L2BLK_SET_LSIZE(
11505 (&l2dhdr->dh_start_lbps[0])->lbp_prop, sizeof (*lb));
11506 L2BLK_SET_PSIZE(
11507 (&l2dhdr->dh_start_lbps[0])->lbp_prop, asize);
11508 L2BLK_SET_CHECKSUM(
11509 (&l2dhdr->dh_start_lbps[0])->lbp_prop,
11510 ZIO_CHECKSUM_FLETCHER_4);
11511 if (asize < sizeof (*lb)) {
11512 /* compression succeeded */
11513 abd_zero_off(abd, psize, asize - psize);
11514 L2BLK_SET_COMPRESS(
11515 (&l2dhdr->dh_start_lbps[0])->lbp_prop,
11516 ZIO_COMPRESS_LZ4);
11517 } else {
11518 /* compression failed */
11519 abd_copy_from_buf_off(abd, lb, 0, sizeof (*lb));
11520 L2BLK_SET_COMPRESS(
11521 (&l2dhdr->dh_start_lbps[0])->lbp_prop,
11522 ZIO_COMPRESS_OFF);
11523 }
11524
11525 /* checksum what we're about to write */
11526 abd_fletcher_4_native(abd, asize, NULL,
11527 &l2dhdr->dh_start_lbps[0].lbp_cksum);
11528
11529 abd_free(abd_buf->abd);
11530
11531 /* perform the write itself */
11532 abd_buf->abd = abd;
11533 wzio = zio_write_phys(pio, dev->l2ad_vdev, dev->l2ad_hand,
11534 asize, abd_buf->abd, ZIO_CHECKSUM_OFF, NULL, NULL,
11535 ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_CANFAIL, B_FALSE);
11536 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev, zio_t *, wzio);
11537 (void) zio_nowait(wzio);
11538
11539 dev->l2ad_hand += asize;
11540 vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
11541
11542 /*
11543 * Include the committed log block's pointer in the list of pointers
11544 * to log blocks present in the L2ARC device.
11545 */
11546 memcpy(lb_ptr_buf->lb_ptr, &l2dhdr->dh_start_lbps[0],
11547 sizeof (l2arc_log_blkptr_t));
11548 mutex_enter(&dev->l2ad_mtx);
11549 list_insert_head(&dev->l2ad_lbptr_list, lb_ptr_buf);
11550 ARCSTAT_INCR(arcstat_l2_log_blk_asize, asize);
11551 ARCSTAT_BUMP(arcstat_l2_log_blk_count);
11552 zfs_refcount_add_many(&dev->l2ad_lb_asize, asize, lb_ptr_buf);
11553 zfs_refcount_add(&dev->l2ad_lb_count, lb_ptr_buf);
11554 mutex_exit(&dev->l2ad_mtx);
11555
11556 /* bump the kstats */
11557 ARCSTAT_INCR(arcstat_l2_write_bytes, asize);
11558 ARCSTAT_BUMP(arcstat_l2_log_blk_writes);
11559 ARCSTAT_F_AVG(arcstat_l2_log_blk_avg_asize, asize);
11560 ARCSTAT_F_AVG(arcstat_l2_data_to_meta_ratio,
11561 dev->l2ad_log_blk_payload_asize / asize);
11562
11563 /* start a new log block */
11564 dev->l2ad_log_ent_idx = 0;
11565 dev->l2ad_log_blk_payload_asize = 0;
11566 dev->l2ad_log_blk_payload_start = 0;
11567
11568 return (asize);
11569 }
11570
11571 /*
11572 * Validates an L2ARC log block address to make sure that it can be read
11573 * from the provided L2ARC device.
11574 */
11575 boolean_t
l2arc_log_blkptr_valid(l2arc_dev_t * dev,const l2arc_log_blkptr_t * lbp)11576 l2arc_log_blkptr_valid(l2arc_dev_t *dev, const l2arc_log_blkptr_t *lbp)
11577 {
11578 /* L2BLK_GET_PSIZE returns aligned size for log blocks */
11579 uint64_t asize = L2BLK_GET_PSIZE((lbp)->lbp_prop);
11580 uint64_t end = lbp->lbp_daddr + asize - 1;
11581 uint64_t start = lbp->lbp_payload_start;
11582 boolean_t evicted = B_FALSE;
11583
11584 /*
11585 * A log block is valid if all of the following conditions are true:
11586 * - it fits entirely (including its payload) between l2ad_start and
11587 * l2ad_end
11588 * - it has a valid size
11589 * - neither the log block itself nor part of its payload was evicted
11590 * by l2arc_evict():
11591 *
11592 * l2ad_hand l2ad_evict
11593 * | | lbp_daddr
11594 * | start | | end
11595 * | | | | |
11596 * V V V V V
11597 * l2ad_start ============================================ l2ad_end
11598 * --------------------------||||
11599 * ^ ^
11600 * | log block
11601 * payload
11602 */
11603
11604 evicted =
11605 l2arc_range_check_overlap(start, end, dev->l2ad_hand) ||
11606 l2arc_range_check_overlap(start, end, dev->l2ad_evict) ||
11607 l2arc_range_check_overlap(dev->l2ad_hand, dev->l2ad_evict, start) ||
11608 l2arc_range_check_overlap(dev->l2ad_hand, dev->l2ad_evict, end);
11609
11610 if (asize == 0 || asize > sizeof (l2arc_log_blk_phys_t) ||
11611 start < dev->l2ad_start || end > dev->l2ad_end)
11612 return (B_FALSE);
11613
11614 /* On a first sweep only the region below the write hand was written. */
11615 if (dev->l2ad_first)
11616 return (end < dev->l2ad_hand);
11617
11618 return (!evicted);
11619 }
11620
11621 /*
11622 * Inserts ARC buffer header `hdr' into the current L2ARC log block on
11623 * the device. The buffer being inserted must be present in L2ARC.
11624 * Returns B_TRUE if the L2ARC log block is full and needs to be committed
11625 * to L2ARC, or B_FALSE if it still has room for more ARC buffers.
11626 */
11627 static boolean_t
l2arc_log_blk_insert(l2arc_dev_t * dev,const arc_buf_hdr_t * hdr)11628 l2arc_log_blk_insert(l2arc_dev_t *dev, const arc_buf_hdr_t *hdr)
11629 {
11630 l2arc_log_blk_phys_t *lb = &dev->l2ad_log_blk;
11631 l2arc_log_ent_phys_t *le;
11632
11633 if (dev->l2ad_log_entries == 0)
11634 return (B_FALSE);
11635
11636 int index = dev->l2ad_log_ent_idx++;
11637
11638 ASSERT3S(index, <, dev->l2ad_log_entries);
11639 ASSERT(HDR_HAS_L2HDR(hdr));
11640
11641 le = &lb->lb_entries[index];
11642 memset(le, 0, sizeof (*le));
11643 le->le_dva = hdr->b_dva;
11644 le->le_birth = hdr->b_birth;
11645 le->le_daddr = hdr->b_l2hdr.b_daddr;
11646 if (index == 0)
11647 dev->l2ad_log_blk_payload_start = le->le_daddr;
11648 L2BLK_SET_LSIZE((le)->le_prop, HDR_GET_LSIZE(hdr));
11649 L2BLK_SET_PSIZE((le)->le_prop, HDR_GET_PSIZE(hdr));
11650 L2BLK_SET_COMPRESS((le)->le_prop, HDR_GET_COMPRESS(hdr));
11651 le->le_complevel = hdr->b_complevel;
11652 L2BLK_SET_TYPE((le)->le_prop, hdr->b_type);
11653 L2BLK_SET_PROTECTED((le)->le_prop, !!(HDR_PROTECTED(hdr)));
11654 L2BLK_SET_PREFETCH((le)->le_prop, !!(HDR_PREFETCH(hdr)));
11655 L2BLK_SET_STATE((le)->le_prop, hdr->b_l2hdr.b_arcs_state);
11656
11657 dev->l2ad_log_blk_payload_asize += vdev_psize_to_asize(dev->l2ad_vdev,
11658 HDR_GET_PSIZE(hdr));
11659
11660 return (dev->l2ad_log_ent_idx == dev->l2ad_log_entries);
11661 }
11662
11663 /*
11664 * Checks whether a given L2ARC device address sits in a time-sequential
11665 * range. The trick here is that the L2ARC is a rotary buffer, so we can't
11666 * just do a range comparison, we need to handle the situation in which the
11667 * range wraps around the end of the L2ARC device. Arguments:
11668 * bottom -- Lower end of the range to check (written to earlier).
11669 * top -- Upper end of the range to check (written to later).
11670 * check -- The address for which we want to determine if it sits in
11671 * between the top and bottom.
11672 *
11673 * The 3-way conditional below represents the following cases:
11674 *
11675 * bottom < top : Sequentially ordered case:
11676 * <check>--------+-------------------+
11677 * | (overlap here?) |
11678 * L2ARC dev V V
11679 * |---------------<bottom>============<top>--------------|
11680 *
11681 * bottom > top: Looped-around case:
11682 * <check>--------+------------------+
11683 * | (overlap here?) |
11684 * L2ARC dev V V
11685 * |===============<top>---------------<bottom>===========|
11686 * ^ ^
11687 * | (or here?) |
11688 * +---------------+---------<check>
11689 *
11690 * top == bottom : Just a single address comparison.
11691 */
11692 boolean_t
l2arc_range_check_overlap(uint64_t bottom,uint64_t top,uint64_t check)11693 l2arc_range_check_overlap(uint64_t bottom, uint64_t top, uint64_t check)
11694 {
11695 if (bottom < top)
11696 return (bottom <= check && check <= top);
11697 else if (bottom > top)
11698 return (check <= top || bottom <= check);
11699 else
11700 return (check == top);
11701 }
11702
11703 EXPORT_SYMBOL(arc_buf_size);
11704 EXPORT_SYMBOL(arc_write);
11705 EXPORT_SYMBOL(arc_read);
11706 EXPORT_SYMBOL(arc_buf_info);
11707 EXPORT_SYMBOL(arc_getbuf_func);
11708 EXPORT_SYMBOL(arc_buf_destroy);
11709 EXPORT_SYMBOL(arc_add_prune_callback);
11710 EXPORT_SYMBOL(arc_remove_prune_callback);
11711
11712 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, min, param_set_arc_min,
11713 spl_param_get_u64, ZMOD_RW, "Minimum ARC size in bytes");
11714
11715 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, max, param_set_arc_max,
11716 spl_param_get_u64, ZMOD_RW, "Maximum ARC size in bytes");
11717
11718 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, meta_balance, UINT, ZMOD_RW,
11719 "Balance between metadata and data on ghost hits.");
11720
11721 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, grow_retry, param_set_arc_int,
11722 param_get_uint, ZMOD_RW, "Seconds before growing ARC size");
11723
11724 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, shrink_shift, param_set_arc_int,
11725 param_get_uint, ZMOD_RW, "log2(fraction of ARC to reclaim)");
11726
11727 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, no_grow_shift,
11728 param_set_arc_no_grow_shift, param_get_uint, ZMOD_RW,
11729 "log2(fraction of ARC which must be free to allow growing)");
11730
11731 #ifdef _KERNEL
11732 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, pc_percent, UINT, ZMOD_RW,
11733 "Percent of pagecache to reclaim ARC to");
11734 #endif
11735
11736 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, average_blocksize, UINT, ZMOD_RD,
11737 "Target average block size");
11738
11739 ZFS_MODULE_PARAM(zfs, zfs_, compressed_arc_enabled, INT, ZMOD_RW,
11740 "Disable compressed ARC buffers");
11741
11742 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, min_prefetch_ms, param_set_arc_int,
11743 param_get_uint, ZMOD_RW, "Min life of prefetch block in ms");
11744
11745 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, min_prescient_prefetch_ms,
11746 param_set_arc_int, param_get_uint, ZMOD_RW,
11747 "Min life of prescient prefetched block in ms");
11748
11749 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, write_max, U64, ZMOD_RW,
11750 "Max write bytes per interval");
11751
11752 ZFS_MODULE_PARAM_CALL(zfs_l2arc, l2arc_, dwpd_limit, param_set_l2arc_dwpd_limit,
11753 spl_param_get_u64, ZMOD_RW,
11754 "L2ARC device endurance limit as percentage (100 = 1.0 DWPD)");
11755
11756 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, headroom, U64, ZMOD_RW,
11757 "Number of max device writes to precache");
11758
11759 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, headroom_boost, U64, ZMOD_RW,
11760 "Compressed l2arc_headroom multiplier");
11761
11762 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, trim_ahead, U64, ZMOD_RW,
11763 "TRIM ahead L2ARC write size multiplier");
11764
11765 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, feed_secs, U64, ZMOD_RW,
11766 "Seconds between L2ARC writing");
11767
11768 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, feed_min_ms, U64, ZMOD_RW,
11769 "Min feed interval in milliseconds");
11770
11771 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, noprefetch, INT, ZMOD_RW,
11772 "Skip caching prefetched buffers");
11773
11774 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, feed_again, INT, ZMOD_RW,
11775 "Turbo L2ARC warmup");
11776
11777 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, norw, INT, ZMOD_RW,
11778 "No reads during writes");
11779
11780 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, meta_percent, UINT, ZMOD_RW,
11781 "Percent of ARC size allowed for L2ARC-only headers");
11782
11783 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, rebuild_enabled, INT, ZMOD_RW,
11784 "Rebuild the L2ARC when importing a pool");
11785
11786 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, rebuild_blocks_min_l2size, U64, ZMOD_RW,
11787 "Min size in bytes to write rebuild log blocks in L2ARC");
11788
11789 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, mfuonly, INT, ZMOD_RW,
11790 "Cache only MFU data from ARC into L2ARC");
11791
11792 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, exclude_special, INT, ZMOD_RW,
11793 "Exclude dbufs on special vdevs from being cached to L2ARC if set.");
11794
11795 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, meta_cycles, U64, ZMOD_RW,
11796 "Consecutive metadata cycles before skipping to let data run");
11797
11798 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, ext_headroom_pct, U64, ZMOD_RW,
11799 "Depth cap as percentage of state size for marker reset");
11800
11801 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, lotsfree_percent, param_set_arc_int,
11802 param_get_uint, ZMOD_RW, "System free memory I/O throttle in bytes");
11803
11804 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, sys_free, param_set_arc_u64,
11805 spl_param_get_u64, ZMOD_RW, "System free memory target size in bytes");
11806
11807 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, dnode_limit, param_set_arc_u64,
11808 spl_param_get_u64, ZMOD_RW, "Minimum bytes of dnodes in ARC");
11809
11810 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, dnode_limit_percent,
11811 param_set_arc_int, param_get_uint, ZMOD_RW,
11812 "Percent of ARC meta buffers for dnodes");
11813
11814 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, dnode_reduce_percent, UINT, ZMOD_RW,
11815 "Percentage of excess dnodes to try to unpin");
11816
11817 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, eviction_pct, UINT, ZMOD_RW,
11818 "When full, ARC allocation waits for eviction of this % of alloc size");
11819
11820 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, evict_batch_limit, UINT, ZMOD_RW,
11821 "The number of headers to evict per sublist before moving to the next");
11822
11823 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, evict_batches_limit, UINT, ZMOD_RW,
11824 "The number of batches to run per parallel eviction task");
11825
11826 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, prune_task_threads, INT, ZMOD_RW,
11827 "Number of arc_prune threads");
11828
11829 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, evict_threads, UINT, ZMOD_RD,
11830 "Number of threads to use for ARC eviction.");
11831