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