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