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