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