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