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