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