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