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