xref: /illumos-gate/usr/src/uts/common/fs/zfs/arc.c (revision 4c28a617e3922d92a58e813a5b955eb526b9c386)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 2018, Joyent, Inc.
24  * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
25  * Copyright (c) 2014 by Saso Kiselkov. All rights reserved.
26  * Copyright 2017 Nexenta Systems, Inc.  All rights reserved.
27  */
28 
29 /*
30  * DVA-based Adjustable Replacement Cache
31  *
32  * While much of the theory of operation used here is
33  * based on the self-tuning, low overhead replacement cache
34  * presented by Megiddo and Modha at FAST 2003, there are some
35  * significant differences:
36  *
37  * 1. The Megiddo and Modha model assumes any page is evictable.
38  * Pages in its cache cannot be "locked" into memory.  This makes
39  * the eviction algorithm simple: evict the last page in the list.
40  * This also make the performance characteristics easy to reason
41  * about.  Our cache is not so simple.  At any given moment, some
42  * subset of the blocks in the cache are un-evictable because we
43  * have handed out a reference to them.  Blocks are only evictable
44  * when there are no external references active.  This makes
45  * eviction far more problematic:  we choose to evict the evictable
46  * blocks that are the "lowest" in the list.
47  *
48  * There are times when it is not possible to evict the requested
49  * space.  In these circumstances we are unable to adjust the cache
50  * size.  To prevent the cache growing unbounded at these times we
51  * implement a "cache throttle" that slows the flow of new data
52  * into the cache until we can make space available.
53  *
54  * 2. The Megiddo and Modha model assumes a fixed cache size.
55  * Pages are evicted when the cache is full and there is a cache
56  * miss.  Our model has a variable sized cache.  It grows with
57  * high use, but also tries to react to memory pressure from the
58  * operating system: decreasing its size when system memory is
59  * tight.
60  *
61  * 3. The Megiddo and Modha model assumes a fixed page size. All
62  * elements of the cache are therefore exactly the same size.  So
63  * when adjusting the cache size following a cache miss, its simply
64  * a matter of choosing a single page to evict.  In our model, we
65  * have variable sized cache blocks (rangeing from 512 bytes to
66  * 128K bytes).  We therefore choose a set of blocks to evict to make
67  * space for a cache miss that approximates as closely as possible
68  * the space used by the new block.
69  *
70  * See also:  "ARC: A Self-Tuning, Low Overhead Replacement Cache"
71  * by N. Megiddo & D. Modha, FAST 2003
72  */
73 
74 /*
75  * The locking model:
76  *
77  * A new reference to a cache buffer can be obtained in two
78  * ways: 1) via a hash table lookup using the DVA as a key,
79  * or 2) via one of the ARC lists.  The arc_read() interface
80  * uses method 1, while the internal ARC algorithms for
81  * adjusting the cache use method 2.  We therefore provide two
82  * types of locks: 1) the hash table lock array, and 2) the
83  * ARC list locks.
84  *
85  * Buffers do not have their own mutexes, rather they rely on the
86  * hash table mutexes for the bulk of their protection (i.e. most
87  * fields in the arc_buf_hdr_t are protected by these mutexes).
88  *
89  * buf_hash_find() returns the appropriate mutex (held) when it
90  * locates the requested buffer in the hash table.  It returns
91  * NULL for the mutex if the buffer was not in the table.
92  *
93  * buf_hash_remove() expects the appropriate hash mutex to be
94  * already held before it is invoked.
95  *
96  * Each ARC state also has a mutex which is used to protect the
97  * buffer list associated with the state.  When attempting to
98  * obtain a hash table lock while holding an ARC list lock you
99  * must use: mutex_tryenter() to avoid deadlock.  Also note that
100  * the active state mutex must be held before the ghost state mutex.
101  *
102  * Note that the majority of the performance stats are manipulated
103  * with atomic operations.
104  *
105  * The L2ARC uses the l2ad_mtx on each vdev for the following:
106  *
107  *	- L2ARC buflist creation
108  *	- L2ARC buflist eviction
109  *	- L2ARC write completion, which walks L2ARC buflists
110  *	- ARC header destruction, as it removes from L2ARC buflists
111  *	- ARC header release, as it removes from L2ARC buflists
112  */
113 
114 /*
115  * ARC operation:
116  *
117  * Every block that is in the ARC is tracked by an arc_buf_hdr_t structure.
118  * This structure can point either to a block that is still in the cache or to
119  * one that is only accessible in an L2 ARC device, or it can provide
120  * information about a block that was recently evicted. If a block is
121  * only accessible in the L2ARC, then the arc_buf_hdr_t only has enough
122  * information to retrieve it from the L2ARC device. This information is
123  * stored in the l2arc_buf_hdr_t sub-structure of the arc_buf_hdr_t. A block
124  * that is in this state cannot access the data directly.
125  *
126  * Blocks that are actively being referenced or have not been evicted
127  * are cached in the L1ARC. The L1ARC (l1arc_buf_hdr_t) is a structure within
128  * the arc_buf_hdr_t that will point to the data block in memory. A block can
129  * only be read by a consumer if it has an l1arc_buf_hdr_t. The L1ARC
130  * caches data in two ways -- in a list of ARC buffers (arc_buf_t) and
131  * also in the arc_buf_hdr_t's private physical data block pointer (b_pabd).
132  *
133  * The L1ARC's data pointer may or may not be uncompressed. The ARC has the
134  * ability to store the physical data (b_pabd) associated with the DVA of the
135  * arc_buf_hdr_t. Since the b_pabd is a copy of the on-disk physical block,
136  * it will match its on-disk compression characteristics. This behavior can be
137  * disabled by setting 'zfs_compressed_arc_enabled' to B_FALSE. When the
138  * compressed ARC functionality is disabled, the b_pabd will point to an
139  * uncompressed version of the on-disk data.
140  *
141  * Data in the L1ARC is not accessed by consumers of the ARC directly. Each
142  * arc_buf_hdr_t can have multiple ARC buffers (arc_buf_t) which reference it.
143  * Each ARC buffer (arc_buf_t) is being actively accessed by a specific ARC
144  * consumer. The ARC will provide references to this data and will keep it
145  * cached until it is no longer in use. The ARC caches only the L1ARC's physical
146  * data block and will evict any arc_buf_t that is no longer referenced. The
147  * amount of memory consumed by the arc_buf_ts' data buffers can be seen via the
148  * "overhead_size" kstat.
149  *
150  * Depending on the consumer, an arc_buf_t can be requested in uncompressed or
151  * compressed form. The typical case is that consumers will want uncompressed
152  * data, and when that happens a new data buffer is allocated where the data is
153  * decompressed for them to use. Currently the only consumer who wants
154  * compressed arc_buf_t's is "zfs send", when it streams data exactly as it
155  * exists on disk. When this happens, the arc_buf_t's data buffer is shared
156  * with the arc_buf_hdr_t.
157  *
158  * Here is a diagram showing an arc_buf_hdr_t referenced by two arc_buf_t's. The
159  * first one is owned by a compressed send consumer (and therefore references
160  * the same compressed data buffer as the arc_buf_hdr_t) and the second could be
161  * used by any other consumer (and has its own uncompressed copy of the data
162  * buffer).
163  *
164  *   arc_buf_hdr_t
165  *   +-----------+
166  *   | fields    |
167  *   | common to |
168  *   | L1- and   |
169  *   | L2ARC     |
170  *   +-----------+
171  *   | l2arc_buf_hdr_t
172  *   |           |
173  *   +-----------+
174  *   | l1arc_buf_hdr_t
175  *   |           |              arc_buf_t
176  *   | b_buf     +------------>+-----------+      arc_buf_t
177  *   | b_pabd    +-+           |b_next     +---->+-----------+
178  *   +-----------+ |           |-----------|     |b_next     +-->NULL
179  *                 |           |b_comp = T |     +-----------+
180  *                 |           |b_data     +-+   |b_comp = F |
181  *                 |           +-----------+ |   |b_data     +-+
182  *                 +->+------+               |   +-----------+ |
183  *        compressed  |      |               |                 |
184  *           data     |      |<--------------+                 | uncompressed
185  *                    +------+          compressed,            |     data
186  *                                        shared               +-->+------+
187  *                                         data                    |      |
188  *                                                                 |      |
189  *                                                                 +------+
190  *
191  * When a consumer reads a block, the ARC must first look to see if the
192  * arc_buf_hdr_t is cached. If the hdr is cached then the ARC allocates a new
193  * arc_buf_t and either copies uncompressed data into a new data buffer from an
194  * existing uncompressed arc_buf_t, decompresses the hdr's b_pabd buffer into a
195  * new data buffer, or shares the hdr's b_pabd buffer, depending on whether the
196  * hdr is compressed and the desired compression characteristics of the
197  * arc_buf_t consumer. If the arc_buf_t ends up sharing data with the
198  * arc_buf_hdr_t and both of them are uncompressed then the arc_buf_t must be
199  * the last buffer in the hdr's b_buf list, however a shared compressed buf can
200  * be anywhere in the hdr's list.
201  *
202  * The diagram below shows an example of an uncompressed ARC hdr that is
203  * sharing its data with an arc_buf_t (note that the shared uncompressed buf is
204  * the last element in the buf list):
205  *
206  *                arc_buf_hdr_t
207  *                +-----------+
208  *                |           |
209  *                |           |
210  *                |           |
211  *                +-----------+
212  * l2arc_buf_hdr_t|           |
213  *                |           |
214  *                +-----------+
215  * l1arc_buf_hdr_t|           |
216  *                |           |                 arc_buf_t    (shared)
217  *                |    b_buf  +------------>+---------+      arc_buf_t
218  *                |           |             |b_next   +---->+---------+
219  *                |  b_pabd   +-+           |---------|     |b_next   +-->NULL
220  *                +-----------+ |           |         |     +---------+
221  *                              |           |b_data   +-+   |         |
222  *                              |           +---------+ |   |b_data   +-+
223  *                              +->+------+             |   +---------+ |
224  *                                 |      |             |               |
225  *                   uncompressed  |      |             |               |
226  *                        data     +------+             |               |
227  *                                    ^                 +->+------+     |
228  *                                    |       uncompressed |      |     |
229  *                                    |           data     |      |     |
230  *                                    |                    +------+     |
231  *                                    +---------------------------------+
232  *
233  * Writing to the ARC requires that the ARC first discard the hdr's b_pabd
234  * since the physical block is about to be rewritten. The new data contents
235  * will be contained in the arc_buf_t. As the I/O pipeline performs the write,
236  * it may compress the data before writing it to disk. The ARC will be called
237  * with the transformed data and will bcopy the transformed on-disk block into
238  * a newly allocated b_pabd. Writes are always done into buffers which have
239  * either been loaned (and hence are new and don't have other readers) or
240  * buffers which have been released (and hence have their own hdr, if there
241  * were originally other readers of the buf's original hdr). This ensures that
242  * the ARC only needs to update a single buf and its hdr after a write occurs.
243  *
244  * When the L2ARC is in use, it will also take advantage of the b_pabd. The
245  * L2ARC will always write the contents of b_pabd to the L2ARC. This means
246  * that when compressed ARC is enabled that the L2ARC blocks are identical
247  * to the on-disk block in the main data pool. This provides a significant
248  * advantage since the ARC can leverage the bp's checksum when reading from the
249  * L2ARC to determine if the contents are valid. However, if the compressed
250  * ARC is disabled, then the L2ARC's block must be transformed to look
251  * like the physical block in the main data pool before comparing the
252  * checksum and determining its validity.
253  */
254 
255 #include <sys/spa.h>
256 #include <sys/zio.h>
257 #include <sys/spa_impl.h>
258 #include <sys/zio_compress.h>
259 #include <sys/zio_checksum.h>
260 #include <sys/zfs_context.h>
261 #include <sys/arc.h>
262 #include <sys/refcount.h>
263 #include <sys/vdev.h>
264 #include <sys/vdev_impl.h>
265 #include <sys/dsl_pool.h>
266 #include <sys/zio_checksum.h>
267 #include <sys/multilist.h>
268 #include <sys/abd.h>
269 #ifdef _KERNEL
270 #include <sys/vmsystm.h>
271 #include <vm/anon.h>
272 #include <sys/fs/swapnode.h>
273 #include <sys/dnlc.h>
274 #endif
275 #include <sys/callb.h>
276 #include <sys/kstat.h>
277 #include <sys/zthr.h>
278 #include <zfs_fletcher.h>
279 #include <sys/aggsum.h>
280 #include <sys/cityhash.h>
281 
282 #ifndef _KERNEL
283 /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
284 boolean_t arc_watch = B_FALSE;
285 int arc_procfd;
286 #endif
287 
288 /*
289  * This thread's job is to keep enough free memory in the system, by
290  * calling arc_kmem_reap_now() plus arc_shrink(), which improves
291  * arc_available_memory().
292  */
293 static zthr_t		*arc_reap_zthr;
294 
295 /*
296  * This thread's job is to keep arc_size under arc_c, by calling
297  * arc_adjust(), which improves arc_is_overflowing().
298  */
299 static zthr_t		*arc_adjust_zthr;
300 
301 static kmutex_t		arc_adjust_lock;
302 static kcondvar_t	arc_adjust_waiters_cv;
303 static boolean_t	arc_adjust_needed = B_FALSE;
304 
305 uint_t arc_reduce_dnlc_percent = 3;
306 
307 /*
308  * The number of headers to evict in arc_evict_state_impl() before
309  * dropping the sublist lock and evicting from another sublist. A lower
310  * value means we're more likely to evict the "correct" header (i.e. the
311  * oldest header in the arc state), but comes with higher overhead
312  * (i.e. more invocations of arc_evict_state_impl()).
313  */
314 int zfs_arc_evict_batch_limit = 10;
315 
316 /* number of seconds before growing cache again */
317 int arc_grow_retry = 60;
318 
319 /*
320  * Minimum time between calls to arc_kmem_reap_soon().  Note that this will
321  * be converted to ticks, so with the default hz=100, a setting of 15 ms
322  * will actually wait 2 ticks, or 20ms.
323  */
324 int arc_kmem_cache_reap_retry_ms = 1000;
325 
326 /* shift of arc_c for calculating overflow limit in arc_get_data_impl */
327 int zfs_arc_overflow_shift = 8;
328 
329 /* shift of arc_c for calculating both min and max arc_p */
330 int arc_p_min_shift = 4;
331 
332 /* log2(fraction of arc to reclaim) */
333 int arc_shrink_shift = 7;
334 
335 /*
336  * log2(fraction of ARC which must be free to allow growing).
337  * I.e. If there is less than arc_c >> arc_no_grow_shift free memory,
338  * when reading a new block into the ARC, we will evict an equal-sized block
339  * from the ARC.
340  *
341  * This must be less than arc_shrink_shift, so that when we shrink the ARC,
342  * we will still not allow it to grow.
343  */
344 int			arc_no_grow_shift = 5;
345 
346 
347 /*
348  * minimum lifespan of a prefetch block in clock ticks
349  * (initialized in arc_init())
350  */
351 static int		arc_min_prefetch_lifespan;
352 
353 /*
354  * If this percent of memory is free, don't throttle.
355  */
356 int arc_lotsfree_percent = 10;
357 
358 static boolean_t arc_initialized;
359 
360 /*
361  * The arc has filled available memory and has now warmed up.
362  */
363 static boolean_t arc_warm;
364 
365 /*
366  * log2 fraction of the zio arena to keep free.
367  */
368 int arc_zio_arena_free_shift = 2;
369 
370 /*
371  * These tunables are for performance analysis.
372  */
373 uint64_t zfs_arc_max;
374 uint64_t zfs_arc_min;
375 uint64_t zfs_arc_meta_limit = 0;
376 uint64_t zfs_arc_meta_min = 0;
377 int zfs_arc_grow_retry = 0;
378 int zfs_arc_shrink_shift = 0;
379 int zfs_arc_p_min_shift = 0;
380 int zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
381 
382 boolean_t zfs_compressed_arc_enabled = B_TRUE;
383 
384 /*
385  * Note that buffers can be in one of 6 states:
386  *	ARC_anon	- anonymous (discussed below)
387  *	ARC_mru		- recently used, currently cached
388  *	ARC_mru_ghost	- recentely used, no longer in cache
389  *	ARC_mfu		- frequently used, currently cached
390  *	ARC_mfu_ghost	- frequently used, no longer in cache
391  *	ARC_l2c_only	- exists in L2ARC but not other states
392  * When there are no active references to the buffer, they are
393  * are linked onto a list in one of these arc states.  These are
394  * the only buffers that can be evicted or deleted.  Within each
395  * state there are multiple lists, one for meta-data and one for
396  * non-meta-data.  Meta-data (indirect blocks, blocks of dnodes,
397  * etc.) is tracked separately so that it can be managed more
398  * explicitly: favored over data, limited explicitly.
399  *
400  * Anonymous buffers are buffers that are not associated with
401  * a DVA.  These are buffers that hold dirty block copies
402  * before they are written to stable storage.  By definition,
403  * they are "ref'd" and are considered part of arc_mru
404  * that cannot be freed.  Generally, they will aquire a DVA
405  * as they are written and migrate onto the arc_mru list.
406  *
407  * The ARC_l2c_only state is for buffers that are in the second
408  * level ARC but no longer in any of the ARC_m* lists.  The second
409  * level ARC itself may also contain buffers that are in any of
410  * the ARC_m* states - meaning that a buffer can exist in two
411  * places.  The reason for the ARC_l2c_only state is to keep the
412  * buffer header in the hash table, so that reads that hit the
413  * second level ARC benefit from these fast lookups.
414  */
415 
416 typedef struct arc_state {
417 	/*
418 	 * list of evictable buffers
419 	 */
420 	multilist_t *arcs_list[ARC_BUFC_NUMTYPES];
421 	/*
422 	 * total amount of evictable data in this state
423 	 */
424 	refcount_t arcs_esize[ARC_BUFC_NUMTYPES];
425 	/*
426 	 * total amount of data in this state; this includes: evictable,
427 	 * non-evictable, ARC_BUFC_DATA, and ARC_BUFC_METADATA.
428 	 */
429 	refcount_t arcs_size;
430 } arc_state_t;
431 
432 /* The 6 states: */
433 static arc_state_t ARC_anon;
434 static arc_state_t ARC_mru;
435 static arc_state_t ARC_mru_ghost;
436 static arc_state_t ARC_mfu;
437 static arc_state_t ARC_mfu_ghost;
438 static arc_state_t ARC_l2c_only;
439 
440 typedef struct arc_stats {
441 	kstat_named_t arcstat_hits;
442 	kstat_named_t arcstat_misses;
443 	kstat_named_t arcstat_demand_data_hits;
444 	kstat_named_t arcstat_demand_data_misses;
445 	kstat_named_t arcstat_demand_metadata_hits;
446 	kstat_named_t arcstat_demand_metadata_misses;
447 	kstat_named_t arcstat_prefetch_data_hits;
448 	kstat_named_t arcstat_prefetch_data_misses;
449 	kstat_named_t arcstat_prefetch_metadata_hits;
450 	kstat_named_t arcstat_prefetch_metadata_misses;
451 	kstat_named_t arcstat_mru_hits;
452 	kstat_named_t arcstat_mru_ghost_hits;
453 	kstat_named_t arcstat_mfu_hits;
454 	kstat_named_t arcstat_mfu_ghost_hits;
455 	kstat_named_t arcstat_deleted;
456 	/*
457 	 * Number of buffers that could not be evicted because the hash lock
458 	 * was held by another thread.  The lock may not necessarily be held
459 	 * by something using the same buffer, since hash locks are shared
460 	 * by multiple buffers.
461 	 */
462 	kstat_named_t arcstat_mutex_miss;
463 	/*
464 	 * Number of buffers skipped because they have I/O in progress, are
465 	 * indrect prefetch buffers that have not lived long enough, or are
466 	 * not from the spa we're trying to evict from.
467 	 */
468 	kstat_named_t arcstat_evict_skip;
469 	/*
470 	 * Number of times arc_evict_state() was unable to evict enough
471 	 * buffers to reach it's target amount.
472 	 */
473 	kstat_named_t arcstat_evict_not_enough;
474 	kstat_named_t arcstat_evict_l2_cached;
475 	kstat_named_t arcstat_evict_l2_eligible;
476 	kstat_named_t arcstat_evict_l2_ineligible;
477 	kstat_named_t arcstat_evict_l2_skip;
478 	kstat_named_t arcstat_hash_elements;
479 	kstat_named_t arcstat_hash_elements_max;
480 	kstat_named_t arcstat_hash_collisions;
481 	kstat_named_t arcstat_hash_chains;
482 	kstat_named_t arcstat_hash_chain_max;
483 	kstat_named_t arcstat_p;
484 	kstat_named_t arcstat_c;
485 	kstat_named_t arcstat_c_min;
486 	kstat_named_t arcstat_c_max;
487 	/* Not updated directly; only synced in arc_kstat_update. */
488 	kstat_named_t arcstat_size;
489 	/*
490 	 * Number of compressed bytes stored in the arc_buf_hdr_t's b_pabd.
491 	 * Note that the compressed bytes may match the uncompressed bytes
492 	 * if the block is either not compressed or compressed arc is disabled.
493 	 */
494 	kstat_named_t arcstat_compressed_size;
495 	/*
496 	 * Uncompressed size of the data stored in b_pabd. If compressed
497 	 * arc is disabled then this value will be identical to the stat
498 	 * above.
499 	 */
500 	kstat_named_t arcstat_uncompressed_size;
501 	/*
502 	 * Number of bytes stored in all the arc_buf_t's. This is classified
503 	 * as "overhead" since this data is typically short-lived and will
504 	 * be evicted from the arc when it becomes unreferenced unless the
505 	 * zfs_keep_uncompressed_metadata or zfs_keep_uncompressed_level
506 	 * values have been set (see comment in dbuf.c for more information).
507 	 */
508 	kstat_named_t arcstat_overhead_size;
509 	/*
510 	 * Number of bytes consumed by internal ARC structures necessary
511 	 * for tracking purposes; these structures are not actually
512 	 * backed by ARC buffers. This includes arc_buf_hdr_t structures
513 	 * (allocated via arc_buf_hdr_t_full and arc_buf_hdr_t_l2only
514 	 * caches), and arc_buf_t structures (allocated via arc_buf_t
515 	 * cache).
516 	 * Not updated directly; only synced in arc_kstat_update.
517 	 */
518 	kstat_named_t arcstat_hdr_size;
519 	/*
520 	 * Number of bytes consumed by ARC buffers of type equal to
521 	 * ARC_BUFC_DATA. This is generally consumed by buffers backing
522 	 * on disk user data (e.g. plain file contents).
523 	 * Not updated directly; only synced in arc_kstat_update.
524 	 */
525 	kstat_named_t arcstat_data_size;
526 	/*
527 	 * Number of bytes consumed by ARC buffers of type equal to
528 	 * ARC_BUFC_METADATA. This is generally consumed by buffers
529 	 * backing on disk data that is used for internal ZFS
530 	 * structures (e.g. ZAP, dnode, indirect blocks, etc).
531 	 * Not updated directly; only synced in arc_kstat_update.
532 	 */
533 	kstat_named_t arcstat_metadata_size;
534 	/*
535 	 * Number of bytes consumed by various buffers and structures
536 	 * not actually backed with ARC buffers. This includes bonus
537 	 * buffers (allocated directly via zio_buf_* functions),
538 	 * dmu_buf_impl_t structures (allocated via dmu_buf_impl_t
539 	 * cache), and dnode_t structures (allocated via dnode_t cache).
540 	 * Not updated directly; only synced in arc_kstat_update.
541 	 */
542 	kstat_named_t arcstat_other_size;
543 	/*
544 	 * Total number of bytes consumed by ARC buffers residing in the
545 	 * arc_anon state. This includes *all* buffers in the arc_anon
546 	 * state; e.g. data, metadata, evictable, and unevictable buffers
547 	 * are all included in this value.
548 	 * Not updated directly; only synced in arc_kstat_update.
549 	 */
550 	kstat_named_t arcstat_anon_size;
551 	/*
552 	 * Number of bytes consumed by ARC buffers that meet the
553 	 * following criteria: backing buffers of type ARC_BUFC_DATA,
554 	 * residing in the arc_anon state, and are eligible for eviction
555 	 * (e.g. have no outstanding holds on the buffer).
556 	 * Not updated directly; only synced in arc_kstat_update.
557 	 */
558 	kstat_named_t arcstat_anon_evictable_data;
559 	/*
560 	 * Number of bytes consumed by ARC buffers that meet the
561 	 * following criteria: backing buffers of type ARC_BUFC_METADATA,
562 	 * residing in the arc_anon state, and are eligible for eviction
563 	 * (e.g. have no outstanding holds on the buffer).
564 	 * Not updated directly; only synced in arc_kstat_update.
565 	 */
566 	kstat_named_t arcstat_anon_evictable_metadata;
567 	/*
568 	 * Total number of bytes consumed by ARC buffers residing in the
569 	 * arc_mru state. This includes *all* buffers in the arc_mru
570 	 * state; e.g. data, metadata, evictable, and unevictable buffers
571 	 * are all included in this value.
572 	 * Not updated directly; only synced in arc_kstat_update.
573 	 */
574 	kstat_named_t arcstat_mru_size;
575 	/*
576 	 * Number of bytes consumed by ARC buffers that meet the
577 	 * following criteria: backing buffers of type ARC_BUFC_DATA,
578 	 * residing in the arc_mru state, and are eligible for eviction
579 	 * (e.g. have no outstanding holds on the buffer).
580 	 * Not updated directly; only synced in arc_kstat_update.
581 	 */
582 	kstat_named_t arcstat_mru_evictable_data;
583 	/*
584 	 * Number of bytes consumed by ARC buffers that meet the
585 	 * following criteria: backing buffers of type ARC_BUFC_METADATA,
586 	 * residing in the arc_mru state, and are eligible for eviction
587 	 * (e.g. have no outstanding holds on the buffer).
588 	 * Not updated directly; only synced in arc_kstat_update.
589 	 */
590 	kstat_named_t arcstat_mru_evictable_metadata;
591 	/*
592 	 * Total number of bytes that *would have been* consumed by ARC
593 	 * buffers in the arc_mru_ghost state. The key thing to note
594 	 * here, is the fact that this size doesn't actually indicate
595 	 * RAM consumption. The ghost lists only consist of headers and
596 	 * don't actually have ARC buffers linked off of these headers.
597 	 * Thus, *if* the headers had associated ARC buffers, these
598 	 * buffers *would have* consumed this number of bytes.
599 	 * Not updated directly; only synced in arc_kstat_update.
600 	 */
601 	kstat_named_t arcstat_mru_ghost_size;
602 	/*
603 	 * Number of bytes that *would have been* consumed by ARC
604 	 * buffers that are eligible for eviction, of type
605 	 * ARC_BUFC_DATA, and linked off the arc_mru_ghost state.
606 	 * Not updated directly; only synced in arc_kstat_update.
607 	 */
608 	kstat_named_t arcstat_mru_ghost_evictable_data;
609 	/*
610 	 * Number of bytes that *would have been* consumed by ARC
611 	 * buffers that are eligible for eviction, of type
612 	 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
613 	 * Not updated directly; only synced in arc_kstat_update.
614 	 */
615 	kstat_named_t arcstat_mru_ghost_evictable_metadata;
616 	/*
617 	 * Total number of bytes consumed by ARC buffers residing in the
618 	 * arc_mfu state. This includes *all* buffers in the arc_mfu
619 	 * state; e.g. data, metadata, evictable, and unevictable buffers
620 	 * are all included in this value.
621 	 * Not updated directly; only synced in arc_kstat_update.
622 	 */
623 	kstat_named_t arcstat_mfu_size;
624 	/*
625 	 * Number of bytes consumed by ARC buffers that are eligible for
626 	 * eviction, of type ARC_BUFC_DATA, and reside in the arc_mfu
627 	 * state.
628 	 * Not updated directly; only synced in arc_kstat_update.
629 	 */
630 	kstat_named_t arcstat_mfu_evictable_data;
631 	/*
632 	 * Number of bytes consumed by ARC buffers that are eligible for
633 	 * eviction, of type ARC_BUFC_METADATA, and reside in the
634 	 * arc_mfu state.
635 	 * Not updated directly; only synced in arc_kstat_update.
636 	 */
637 	kstat_named_t arcstat_mfu_evictable_metadata;
638 	/*
639 	 * Total number of bytes that *would have been* consumed by ARC
640 	 * buffers in the arc_mfu_ghost state. See the comment above
641 	 * arcstat_mru_ghost_size for more details.
642 	 * Not updated directly; only synced in arc_kstat_update.
643 	 */
644 	kstat_named_t arcstat_mfu_ghost_size;
645 	/*
646 	 * Number of bytes that *would have been* consumed by ARC
647 	 * buffers that are eligible for eviction, of type
648 	 * ARC_BUFC_DATA, and linked off the arc_mfu_ghost state.
649 	 * Not updated directly; only synced in arc_kstat_update.
650 	 */
651 	kstat_named_t arcstat_mfu_ghost_evictable_data;
652 	/*
653 	 * Number of bytes that *would have been* consumed by ARC
654 	 * buffers that are eligible for eviction, of type
655 	 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
656 	 * Not updated directly; only synced in arc_kstat_update.
657 	 */
658 	kstat_named_t arcstat_mfu_ghost_evictable_metadata;
659 	kstat_named_t arcstat_l2_hits;
660 	kstat_named_t arcstat_l2_misses;
661 	kstat_named_t arcstat_l2_feeds;
662 	kstat_named_t arcstat_l2_rw_clash;
663 	kstat_named_t arcstat_l2_read_bytes;
664 	kstat_named_t arcstat_l2_write_bytes;
665 	kstat_named_t arcstat_l2_writes_sent;
666 	kstat_named_t arcstat_l2_writes_done;
667 	kstat_named_t arcstat_l2_writes_error;
668 	kstat_named_t arcstat_l2_writes_lock_retry;
669 	kstat_named_t arcstat_l2_evict_lock_retry;
670 	kstat_named_t arcstat_l2_evict_reading;
671 	kstat_named_t arcstat_l2_evict_l1cached;
672 	kstat_named_t arcstat_l2_free_on_write;
673 	kstat_named_t arcstat_l2_abort_lowmem;
674 	kstat_named_t arcstat_l2_cksum_bad;
675 	kstat_named_t arcstat_l2_io_error;
676 	kstat_named_t arcstat_l2_lsize;
677 	kstat_named_t arcstat_l2_psize;
678 	/* Not updated directly; only synced in arc_kstat_update. */
679 	kstat_named_t arcstat_l2_hdr_size;
680 	kstat_named_t arcstat_memory_throttle_count;
681 	/* Not updated directly; only synced in arc_kstat_update. */
682 	kstat_named_t arcstat_meta_used;
683 	kstat_named_t arcstat_meta_limit;
684 	kstat_named_t arcstat_meta_max;
685 	kstat_named_t arcstat_meta_min;
686 	kstat_named_t arcstat_sync_wait_for_async;
687 	kstat_named_t arcstat_demand_hit_predictive_prefetch;
688 } arc_stats_t;
689 
690 static arc_stats_t arc_stats = {
691 	{ "hits",			KSTAT_DATA_UINT64 },
692 	{ "misses",			KSTAT_DATA_UINT64 },
693 	{ "demand_data_hits",		KSTAT_DATA_UINT64 },
694 	{ "demand_data_misses",		KSTAT_DATA_UINT64 },
695 	{ "demand_metadata_hits",	KSTAT_DATA_UINT64 },
696 	{ "demand_metadata_misses",	KSTAT_DATA_UINT64 },
697 	{ "prefetch_data_hits",		KSTAT_DATA_UINT64 },
698 	{ "prefetch_data_misses",	KSTAT_DATA_UINT64 },
699 	{ "prefetch_metadata_hits",	KSTAT_DATA_UINT64 },
700 	{ "prefetch_metadata_misses",	KSTAT_DATA_UINT64 },
701 	{ "mru_hits",			KSTAT_DATA_UINT64 },
702 	{ "mru_ghost_hits",		KSTAT_DATA_UINT64 },
703 	{ "mfu_hits",			KSTAT_DATA_UINT64 },
704 	{ "mfu_ghost_hits",		KSTAT_DATA_UINT64 },
705 	{ "deleted",			KSTAT_DATA_UINT64 },
706 	{ "mutex_miss",			KSTAT_DATA_UINT64 },
707 	{ "evict_skip",			KSTAT_DATA_UINT64 },
708 	{ "evict_not_enough",		KSTAT_DATA_UINT64 },
709 	{ "evict_l2_cached",		KSTAT_DATA_UINT64 },
710 	{ "evict_l2_eligible",		KSTAT_DATA_UINT64 },
711 	{ "evict_l2_ineligible",	KSTAT_DATA_UINT64 },
712 	{ "evict_l2_skip",		KSTAT_DATA_UINT64 },
713 	{ "hash_elements",		KSTAT_DATA_UINT64 },
714 	{ "hash_elements_max",		KSTAT_DATA_UINT64 },
715 	{ "hash_collisions",		KSTAT_DATA_UINT64 },
716 	{ "hash_chains",		KSTAT_DATA_UINT64 },
717 	{ "hash_chain_max",		KSTAT_DATA_UINT64 },
718 	{ "p",				KSTAT_DATA_UINT64 },
719 	{ "c",				KSTAT_DATA_UINT64 },
720 	{ "c_min",			KSTAT_DATA_UINT64 },
721 	{ "c_max",			KSTAT_DATA_UINT64 },
722 	{ "size",			KSTAT_DATA_UINT64 },
723 	{ "compressed_size",		KSTAT_DATA_UINT64 },
724 	{ "uncompressed_size",		KSTAT_DATA_UINT64 },
725 	{ "overhead_size",		KSTAT_DATA_UINT64 },
726 	{ "hdr_size",			KSTAT_DATA_UINT64 },
727 	{ "data_size",			KSTAT_DATA_UINT64 },
728 	{ "metadata_size",		KSTAT_DATA_UINT64 },
729 	{ "other_size",			KSTAT_DATA_UINT64 },
730 	{ "anon_size",			KSTAT_DATA_UINT64 },
731 	{ "anon_evictable_data",	KSTAT_DATA_UINT64 },
732 	{ "anon_evictable_metadata",	KSTAT_DATA_UINT64 },
733 	{ "mru_size",			KSTAT_DATA_UINT64 },
734 	{ "mru_evictable_data",		KSTAT_DATA_UINT64 },
735 	{ "mru_evictable_metadata",	KSTAT_DATA_UINT64 },
736 	{ "mru_ghost_size",		KSTAT_DATA_UINT64 },
737 	{ "mru_ghost_evictable_data",	KSTAT_DATA_UINT64 },
738 	{ "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
739 	{ "mfu_size",			KSTAT_DATA_UINT64 },
740 	{ "mfu_evictable_data",		KSTAT_DATA_UINT64 },
741 	{ "mfu_evictable_metadata",	KSTAT_DATA_UINT64 },
742 	{ "mfu_ghost_size",		KSTAT_DATA_UINT64 },
743 	{ "mfu_ghost_evictable_data",	KSTAT_DATA_UINT64 },
744 	{ "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
745 	{ "l2_hits",			KSTAT_DATA_UINT64 },
746 	{ "l2_misses",			KSTAT_DATA_UINT64 },
747 	{ "l2_feeds",			KSTAT_DATA_UINT64 },
748 	{ "l2_rw_clash",		KSTAT_DATA_UINT64 },
749 	{ "l2_read_bytes",		KSTAT_DATA_UINT64 },
750 	{ "l2_write_bytes",		KSTAT_DATA_UINT64 },
751 	{ "l2_writes_sent",		KSTAT_DATA_UINT64 },
752 	{ "l2_writes_done",		KSTAT_DATA_UINT64 },
753 	{ "l2_writes_error",		KSTAT_DATA_UINT64 },
754 	{ "l2_writes_lock_retry",	KSTAT_DATA_UINT64 },
755 	{ "l2_evict_lock_retry",	KSTAT_DATA_UINT64 },
756 	{ "l2_evict_reading",		KSTAT_DATA_UINT64 },
757 	{ "l2_evict_l1cached",		KSTAT_DATA_UINT64 },
758 	{ "l2_free_on_write",		KSTAT_DATA_UINT64 },
759 	{ "l2_abort_lowmem",		KSTAT_DATA_UINT64 },
760 	{ "l2_cksum_bad",		KSTAT_DATA_UINT64 },
761 	{ "l2_io_error",		KSTAT_DATA_UINT64 },
762 	{ "l2_size",			KSTAT_DATA_UINT64 },
763 	{ "l2_asize",			KSTAT_DATA_UINT64 },
764 	{ "l2_hdr_size",		KSTAT_DATA_UINT64 },
765 	{ "memory_throttle_count",	KSTAT_DATA_UINT64 },
766 	{ "arc_meta_used",		KSTAT_DATA_UINT64 },
767 	{ "arc_meta_limit",		KSTAT_DATA_UINT64 },
768 	{ "arc_meta_max",		KSTAT_DATA_UINT64 },
769 	{ "arc_meta_min",		KSTAT_DATA_UINT64 },
770 	{ "sync_wait_for_async",	KSTAT_DATA_UINT64 },
771 	{ "demand_hit_predictive_prefetch", KSTAT_DATA_UINT64 },
772 };
773 
774 #define	ARCSTAT(stat)	(arc_stats.stat.value.ui64)
775 
776 #define	ARCSTAT_INCR(stat, val) \
777 	atomic_add_64(&arc_stats.stat.value.ui64, (val))
778 
779 #define	ARCSTAT_BUMP(stat)	ARCSTAT_INCR(stat, 1)
780 #define	ARCSTAT_BUMPDOWN(stat)	ARCSTAT_INCR(stat, -1)
781 
782 #define	ARCSTAT_MAX(stat, val) {					\
783 	uint64_t m;							\
784 	while ((val) > (m = arc_stats.stat.value.ui64) &&		\
785 	    (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val))))	\
786 		continue;						\
787 }
788 
789 #define	ARCSTAT_MAXSTAT(stat) \
790 	ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
791 
792 /*
793  * We define a macro to allow ARC hits/misses to be easily broken down by
794  * two separate conditions, giving a total of four different subtypes for
795  * each of hits and misses (so eight statistics total).
796  */
797 #define	ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
798 	if (cond1) {							\
799 		if (cond2) {						\
800 			ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
801 		} else {						\
802 			ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
803 		}							\
804 	} else {							\
805 		if (cond2) {						\
806 			ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
807 		} else {						\
808 			ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
809 		}							\
810 	}
811 
812 kstat_t			*arc_ksp;
813 static arc_state_t	*arc_anon;
814 static arc_state_t	*arc_mru;
815 static arc_state_t	*arc_mru_ghost;
816 static arc_state_t	*arc_mfu;
817 static arc_state_t	*arc_mfu_ghost;
818 static arc_state_t	*arc_l2c_only;
819 
820 /*
821  * There are several ARC variables that are critical to export as kstats --
822  * but we don't want to have to grovel around in the kstat whenever we wish to
823  * manipulate them.  For these variables, we therefore define them to be in
824  * terms of the statistic variable.  This assures that we are not introducing
825  * the possibility of inconsistency by having shadow copies of the variables,
826  * while still allowing the code to be readable.
827  */
828 #define	arc_p		ARCSTAT(arcstat_p)	/* target size of MRU */
829 #define	arc_c		ARCSTAT(arcstat_c)	/* target size of cache */
830 #define	arc_c_min	ARCSTAT(arcstat_c_min)	/* min target cache size */
831 #define	arc_c_max	ARCSTAT(arcstat_c_max)	/* max target cache size */
832 #define	arc_meta_limit	ARCSTAT(arcstat_meta_limit) /* max size for metadata */
833 #define	arc_meta_min	ARCSTAT(arcstat_meta_min) /* min size for metadata */
834 #define	arc_meta_max	ARCSTAT(arcstat_meta_max) /* max size of metadata */
835 
836 /* compressed size of entire arc */
837 #define	arc_compressed_size	ARCSTAT(arcstat_compressed_size)
838 /* uncompressed size of entire arc */
839 #define	arc_uncompressed_size	ARCSTAT(arcstat_uncompressed_size)
840 /* number of bytes in the arc from arc_buf_t's */
841 #define	arc_overhead_size	ARCSTAT(arcstat_overhead_size)
842 
843 /*
844  * There are also some ARC variables that we want to export, but that are
845  * updated so often that having the canonical representation be the statistic
846  * variable causes a performance bottleneck. We want to use aggsum_t's for these
847  * instead, but still be able to export the kstat in the same way as before.
848  * The solution is to always use the aggsum version, except in the kstat update
849  * callback.
850  */
851 aggsum_t arc_size;
852 aggsum_t arc_meta_used;
853 aggsum_t astat_data_size;
854 aggsum_t astat_metadata_size;
855 aggsum_t astat_hdr_size;
856 aggsum_t astat_other_size;
857 aggsum_t astat_l2_hdr_size;
858 
859 static int		arc_no_grow;	/* Don't try to grow cache size */
860 static hrtime_t		arc_growtime;
861 static uint64_t		arc_tempreserve;
862 static uint64_t		arc_loaned_bytes;
863 
864 typedef struct arc_callback arc_callback_t;
865 
866 struct arc_callback {
867 	void			*acb_private;
868 	arc_done_func_t		*acb_done;
869 	arc_buf_t		*acb_buf;
870 	boolean_t		acb_compressed;
871 	zio_t			*acb_zio_dummy;
872 	arc_callback_t		*acb_next;
873 };
874 
875 typedef struct arc_write_callback arc_write_callback_t;
876 
877 struct arc_write_callback {
878 	void		*awcb_private;
879 	arc_done_func_t	*awcb_ready;
880 	arc_done_func_t	*awcb_children_ready;
881 	arc_done_func_t	*awcb_physdone;
882 	arc_done_func_t	*awcb_done;
883 	arc_buf_t	*awcb_buf;
884 };
885 
886 /*
887  * ARC buffers are separated into multiple structs as a memory saving measure:
888  *   - Common fields struct, always defined, and embedded within it:
889  *       - L2-only fields, always allocated but undefined when not in L2ARC
890  *       - L1-only fields, only allocated when in L1ARC
891  *
892  *           Buffer in L1                     Buffer only in L2
893  *    +------------------------+          +------------------------+
894  *    | arc_buf_hdr_t          |          | arc_buf_hdr_t          |
895  *    |                        |          |                        |
896  *    |                        |          |                        |
897  *    |                        |          |                        |
898  *    +------------------------+          +------------------------+
899  *    | l2arc_buf_hdr_t        |          | l2arc_buf_hdr_t        |
900  *    | (undefined if L1-only) |          |                        |
901  *    +------------------------+          +------------------------+
902  *    | l1arc_buf_hdr_t        |
903  *    |                        |
904  *    |                        |
905  *    |                        |
906  *    |                        |
907  *    +------------------------+
908  *
909  * Because it's possible for the L2ARC to become extremely large, we can wind
910  * up eating a lot of memory in L2ARC buffer headers, so the size of a header
911  * is minimized by only allocating the fields necessary for an L1-cached buffer
912  * when a header is actually in the L1 cache. The sub-headers (l1arc_buf_hdr and
913  * l2arc_buf_hdr) are embedded rather than allocated separately to save a couple
914  * words in pointers. arc_hdr_realloc() is used to switch a header between
915  * these two allocation states.
916  */
917 typedef struct l1arc_buf_hdr {
918 	kmutex_t		b_freeze_lock;
919 	zio_cksum_t		*b_freeze_cksum;
920 #ifdef ZFS_DEBUG
921 	/*
922 	 * Used for debugging with kmem_flags - by allocating and freeing
923 	 * b_thawed when the buffer is thawed, we get a record of the stack
924 	 * trace that thawed it.
925 	 */
926 	void			*b_thawed;
927 #endif
928 
929 	arc_buf_t		*b_buf;
930 	uint32_t		b_bufcnt;
931 	/* for waiting on writes to complete */
932 	kcondvar_t		b_cv;
933 	uint8_t			b_byteswap;
934 
935 	/* protected by arc state mutex */
936 	arc_state_t		*b_state;
937 	multilist_node_t	b_arc_node;
938 
939 	/* updated atomically */
940 	clock_t			b_arc_access;
941 
942 	/* self protecting */
943 	refcount_t		b_refcnt;
944 
945 	arc_callback_t		*b_acb;
946 	abd_t			*b_pabd;
947 } l1arc_buf_hdr_t;
948 
949 typedef struct l2arc_dev l2arc_dev_t;
950 
951 typedef struct l2arc_buf_hdr {
952 	/* protected by arc_buf_hdr mutex */
953 	l2arc_dev_t		*b_dev;		/* L2ARC device */
954 	uint64_t		b_daddr;	/* disk address, offset byte */
955 
956 	list_node_t		b_l2node;
957 } l2arc_buf_hdr_t;
958 
959 struct arc_buf_hdr {
960 	/* protected by hash lock */
961 	dva_t			b_dva;
962 	uint64_t		b_birth;
963 
964 	arc_buf_contents_t	b_type;
965 	arc_buf_hdr_t		*b_hash_next;
966 	arc_flags_t		b_flags;
967 
968 	/*
969 	 * This field stores the size of the data buffer after
970 	 * compression, and is set in the arc's zio completion handlers.
971 	 * It is in units of SPA_MINBLOCKSIZE (e.g. 1 == 512 bytes).
972 	 *
973 	 * While the block pointers can store up to 32MB in their psize
974 	 * field, we can only store up to 32MB minus 512B. This is due
975 	 * to the bp using a bias of 1, whereas we use a bias of 0 (i.e.
976 	 * a field of zeros represents 512B in the bp). We can't use a
977 	 * bias of 1 since we need to reserve a psize of zero, here, to
978 	 * represent holes and embedded blocks.
979 	 *
980 	 * This isn't a problem in practice, since the maximum size of a
981 	 * buffer is limited to 16MB, so we never need to store 32MB in
982 	 * this field. Even in the upstream illumos code base, the
983 	 * maximum size of a buffer is limited to 16MB.
984 	 */
985 	uint16_t		b_psize;
986 
987 	/*
988 	 * This field stores the size of the data buffer before
989 	 * compression, and cannot change once set. It is in units
990 	 * of SPA_MINBLOCKSIZE (e.g. 2 == 1024 bytes)
991 	 */
992 	uint16_t		b_lsize;	/* immutable */
993 	uint64_t		b_spa;		/* immutable */
994 
995 	/* L2ARC fields. Undefined when not in L2ARC. */
996 	l2arc_buf_hdr_t		b_l2hdr;
997 	/* L1ARC fields. Undefined when in l2arc_only state */
998 	l1arc_buf_hdr_t		b_l1hdr;
999 };
1000 
1001 #define	GHOST_STATE(state)	\
1002 	((state) == arc_mru_ghost || (state) == arc_mfu_ghost ||	\
1003 	(state) == arc_l2c_only)
1004 
1005 #define	HDR_IN_HASH_TABLE(hdr)	((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
1006 #define	HDR_IO_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
1007 #define	HDR_IO_ERROR(hdr)	((hdr)->b_flags & ARC_FLAG_IO_ERROR)
1008 #define	HDR_PREFETCH(hdr)	((hdr)->b_flags & ARC_FLAG_PREFETCH)
1009 #define	HDR_COMPRESSION_ENABLED(hdr)	\
1010 	((hdr)->b_flags & ARC_FLAG_COMPRESSED_ARC)
1011 
1012 #define	HDR_L2CACHE(hdr)	((hdr)->b_flags & ARC_FLAG_L2CACHE)
1013 #define	HDR_L2_READING(hdr)	\
1014 	(((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) &&	\
1015 	((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
1016 #define	HDR_L2_WRITING(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITING)
1017 #define	HDR_L2_EVICTED(hdr)	((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
1018 #define	HDR_L2_WRITE_HEAD(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
1019 #define	HDR_SHARED_DATA(hdr)	((hdr)->b_flags & ARC_FLAG_SHARED_DATA)
1020 
1021 #define	HDR_ISTYPE_METADATA(hdr)	\
1022 	((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
1023 #define	HDR_ISTYPE_DATA(hdr)	(!HDR_ISTYPE_METADATA(hdr))
1024 
1025 #define	HDR_HAS_L1HDR(hdr)	((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
1026 #define	HDR_HAS_L2HDR(hdr)	((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
1027 
1028 /* For storing compression mode in b_flags */
1029 #define	HDR_COMPRESS_OFFSET	(highbit64(ARC_FLAG_COMPRESS_0) - 1)
1030 
1031 #define	HDR_GET_COMPRESS(hdr)	((enum zio_compress)BF32_GET((hdr)->b_flags, \
1032 	HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS))
1033 #define	HDR_SET_COMPRESS(hdr, cmp) BF32_SET((hdr)->b_flags, \
1034 	HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS, (cmp));
1035 
1036 #define	ARC_BUF_LAST(buf)	((buf)->b_next == NULL)
1037 #define	ARC_BUF_SHARED(buf)	((buf)->b_flags & ARC_BUF_FLAG_SHARED)
1038 #define	ARC_BUF_COMPRESSED(buf)	((buf)->b_flags & ARC_BUF_FLAG_COMPRESSED)
1039 
1040 /*
1041  * Other sizes
1042  */
1043 
1044 #define	HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
1045 #define	HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
1046 
1047 /*
1048  * Hash table routines
1049  */
1050 
1051 #define	HT_LOCK_PAD	64
1052 
1053 struct ht_lock {
1054 	kmutex_t	ht_lock;
1055 #ifdef _KERNEL
1056 	unsigned char	pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
1057 #endif
1058 };
1059 
1060 #define	BUF_LOCKS 256
1061 typedef struct buf_hash_table {
1062 	uint64_t ht_mask;
1063 	arc_buf_hdr_t **ht_table;
1064 	struct ht_lock ht_locks[BUF_LOCKS];
1065 } buf_hash_table_t;
1066 
1067 static buf_hash_table_t buf_hash_table;
1068 
1069 #define	BUF_HASH_INDEX(spa, dva, birth) \
1070 	(buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
1071 #define	BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
1072 #define	BUF_HASH_LOCK(idx)	(&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
1073 #define	HDR_LOCK(hdr) \
1074 	(BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
1075 
1076 uint64_t zfs_crc64_table[256];
1077 
1078 /*
1079  * Level 2 ARC
1080  */
1081 
1082 #define	L2ARC_WRITE_SIZE	(8 * 1024 * 1024)	/* initial write max */
1083 #define	L2ARC_HEADROOM		2			/* num of writes */
1084 /*
1085  * If we discover during ARC scan any buffers to be compressed, we boost
1086  * our headroom for the next scanning cycle by this percentage multiple.
1087  */
1088 #define	L2ARC_HEADROOM_BOOST	200
1089 #define	L2ARC_FEED_SECS		1		/* caching interval secs */
1090 #define	L2ARC_FEED_MIN_MS	200		/* min caching interval ms */
1091 
1092 #define	l2arc_writes_sent	ARCSTAT(arcstat_l2_writes_sent)
1093 #define	l2arc_writes_done	ARCSTAT(arcstat_l2_writes_done)
1094 
1095 /* L2ARC Performance Tunables */
1096 uint64_t l2arc_write_max = L2ARC_WRITE_SIZE;	/* default max write size */
1097 uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE;	/* extra write during warmup */
1098 uint64_t l2arc_headroom = L2ARC_HEADROOM;	/* number of dev writes */
1099 uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
1100 uint64_t l2arc_feed_secs = L2ARC_FEED_SECS;	/* interval seconds */
1101 uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS;	/* min interval milliseconds */
1102 boolean_t l2arc_noprefetch = B_TRUE;		/* don't cache prefetch bufs */
1103 boolean_t l2arc_feed_again = B_TRUE;		/* turbo warmup */
1104 boolean_t l2arc_norw = B_TRUE;			/* no reads during writes */
1105 
1106 /*
1107  * L2ARC Internals
1108  */
1109 struct l2arc_dev {
1110 	vdev_t			*l2ad_vdev;	/* vdev */
1111 	spa_t			*l2ad_spa;	/* spa */
1112 	uint64_t		l2ad_hand;	/* next write location */
1113 	uint64_t		l2ad_start;	/* first addr on device */
1114 	uint64_t		l2ad_end;	/* last addr on device */
1115 	boolean_t		l2ad_first;	/* first sweep through */
1116 	boolean_t		l2ad_writing;	/* currently writing */
1117 	kmutex_t		l2ad_mtx;	/* lock for buffer list */
1118 	list_t			l2ad_buflist;	/* buffer list */
1119 	list_node_t		l2ad_node;	/* device list node */
1120 	refcount_t		l2ad_alloc;	/* allocated bytes */
1121 };
1122 
1123 static list_t L2ARC_dev_list;			/* device list */
1124 static list_t *l2arc_dev_list;			/* device list pointer */
1125 static kmutex_t l2arc_dev_mtx;			/* device list mutex */
1126 static l2arc_dev_t *l2arc_dev_last;		/* last device used */
1127 static list_t L2ARC_free_on_write;		/* free after write buf list */
1128 static list_t *l2arc_free_on_write;		/* free after write list ptr */
1129 static kmutex_t l2arc_free_on_write_mtx;	/* mutex for list */
1130 static uint64_t l2arc_ndev;			/* number of devices */
1131 
1132 typedef struct l2arc_read_callback {
1133 	arc_buf_hdr_t		*l2rcb_hdr;		/* read header */
1134 	blkptr_t		l2rcb_bp;		/* original blkptr */
1135 	zbookmark_phys_t	l2rcb_zb;		/* original bookmark */
1136 	int			l2rcb_flags;		/* original flags */
1137 	abd_t			*l2rcb_abd;		/* temporary buffer */
1138 } l2arc_read_callback_t;
1139 
1140 typedef struct l2arc_write_callback {
1141 	l2arc_dev_t	*l2wcb_dev;		/* device info */
1142 	arc_buf_hdr_t	*l2wcb_head;		/* head of write buflist */
1143 } l2arc_write_callback_t;
1144 
1145 typedef struct l2arc_data_free {
1146 	/* protected by l2arc_free_on_write_mtx */
1147 	abd_t		*l2df_abd;
1148 	size_t		l2df_size;
1149 	arc_buf_contents_t l2df_type;
1150 	list_node_t	l2df_list_node;
1151 } l2arc_data_free_t;
1152 
1153 static kmutex_t l2arc_feed_thr_lock;
1154 static kcondvar_t l2arc_feed_thr_cv;
1155 static uint8_t l2arc_thread_exit;
1156 
1157 static abd_t *arc_get_data_abd(arc_buf_hdr_t *, uint64_t, void *);
1158 static void *arc_get_data_buf(arc_buf_hdr_t *, uint64_t, void *);
1159 static void arc_get_data_impl(arc_buf_hdr_t *, uint64_t, void *);
1160 static void arc_free_data_abd(arc_buf_hdr_t *, abd_t *, uint64_t, void *);
1161 static void arc_free_data_buf(arc_buf_hdr_t *, void *, uint64_t, void *);
1162 static void arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag);
1163 static void arc_hdr_free_pabd(arc_buf_hdr_t *);
1164 static void arc_hdr_alloc_pabd(arc_buf_hdr_t *);
1165 static void arc_access(arc_buf_hdr_t *, kmutex_t *);
1166 static boolean_t arc_is_overflowing();
1167 static void arc_buf_watch(arc_buf_t *);
1168 
1169 static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
1170 static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
1171 static inline void arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
1172 static inline void arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
1173 
1174 static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
1175 static void l2arc_read_done(zio_t *);
1176 
1177 
1178 /*
1179  * We use Cityhash for this. It's fast, and has good hash properties without
1180  * requiring any large static buffers.
1181  */
1182 static uint64_t
1183 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
1184 {
1185 	return (cityhash4(spa, dva->dva_word[0], dva->dva_word[1], birth));
1186 }
1187 
1188 #define	HDR_EMPTY(hdr)						\
1189 	((hdr)->b_dva.dva_word[0] == 0 &&			\
1190 	(hdr)->b_dva.dva_word[1] == 0)
1191 
1192 #define	HDR_EQUAL(spa, dva, birth, hdr)				\
1193 	((hdr)->b_dva.dva_word[0] == (dva)->dva_word[0]) &&	\
1194 	((hdr)->b_dva.dva_word[1] == (dva)->dva_word[1]) &&	\
1195 	((hdr)->b_birth == birth) && ((hdr)->b_spa == spa)
1196 
1197 static void
1198 buf_discard_identity(arc_buf_hdr_t *hdr)
1199 {
1200 	hdr->b_dva.dva_word[0] = 0;
1201 	hdr->b_dva.dva_word[1] = 0;
1202 	hdr->b_birth = 0;
1203 }
1204 
1205 static arc_buf_hdr_t *
1206 buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
1207 {
1208 	const dva_t *dva = BP_IDENTITY(bp);
1209 	uint64_t birth = BP_PHYSICAL_BIRTH(bp);
1210 	uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1211 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1212 	arc_buf_hdr_t *hdr;
1213 
1214 	mutex_enter(hash_lock);
1215 	for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
1216 	    hdr = hdr->b_hash_next) {
1217 		if (HDR_EQUAL(spa, dva, birth, hdr)) {
1218 			*lockp = hash_lock;
1219 			return (hdr);
1220 		}
1221 	}
1222 	mutex_exit(hash_lock);
1223 	*lockp = NULL;
1224 	return (NULL);
1225 }
1226 
1227 /*
1228  * Insert an entry into the hash table.  If there is already an element
1229  * equal to elem in the hash table, then the already existing element
1230  * will be returned and the new element will not be inserted.
1231  * Otherwise returns NULL.
1232  * If lockp == NULL, the caller is assumed to already hold the hash lock.
1233  */
1234 static arc_buf_hdr_t *
1235 buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1236 {
1237 	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1238 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1239 	arc_buf_hdr_t *fhdr;
1240 	uint32_t i;
1241 
1242 	ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
1243 	ASSERT(hdr->b_birth != 0);
1244 	ASSERT(!HDR_IN_HASH_TABLE(hdr));
1245 
1246 	if (lockp != NULL) {
1247 		*lockp = hash_lock;
1248 		mutex_enter(hash_lock);
1249 	} else {
1250 		ASSERT(MUTEX_HELD(hash_lock));
1251 	}
1252 
1253 	for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
1254 	    fhdr = fhdr->b_hash_next, i++) {
1255 		if (HDR_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
1256 			return (fhdr);
1257 	}
1258 
1259 	hdr->b_hash_next = buf_hash_table.ht_table[idx];
1260 	buf_hash_table.ht_table[idx] = hdr;
1261 	arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1262 
1263 	/* collect some hash table performance data */
1264 	if (i > 0) {
1265 		ARCSTAT_BUMP(arcstat_hash_collisions);
1266 		if (i == 1)
1267 			ARCSTAT_BUMP(arcstat_hash_chains);
1268 
1269 		ARCSTAT_MAX(arcstat_hash_chain_max, i);
1270 	}
1271 
1272 	ARCSTAT_BUMP(arcstat_hash_elements);
1273 	ARCSTAT_MAXSTAT(arcstat_hash_elements);
1274 
1275 	return (NULL);
1276 }
1277 
1278 static void
1279 buf_hash_remove(arc_buf_hdr_t *hdr)
1280 {
1281 	arc_buf_hdr_t *fhdr, **hdrp;
1282 	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1283 
1284 	ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
1285 	ASSERT(HDR_IN_HASH_TABLE(hdr));
1286 
1287 	hdrp = &buf_hash_table.ht_table[idx];
1288 	while ((fhdr = *hdrp) != hdr) {
1289 		ASSERT3P(fhdr, !=, NULL);
1290 		hdrp = &fhdr->b_hash_next;
1291 	}
1292 	*hdrp = hdr->b_hash_next;
1293 	hdr->b_hash_next = NULL;
1294 	arc_hdr_clear_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1295 
1296 	/* collect some hash table performance data */
1297 	ARCSTAT_BUMPDOWN(arcstat_hash_elements);
1298 
1299 	if (buf_hash_table.ht_table[idx] &&
1300 	    buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1301 		ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1302 }
1303 
1304 /*
1305  * Global data structures and functions for the buf kmem cache.
1306  */
1307 static kmem_cache_t *hdr_full_cache;
1308 static kmem_cache_t *hdr_l2only_cache;
1309 static kmem_cache_t *buf_cache;
1310 
1311 static void
1312 buf_fini(void)
1313 {
1314 	int i;
1315 
1316 	kmem_free(buf_hash_table.ht_table,
1317 	    (buf_hash_table.ht_mask + 1) * sizeof (void *));
1318 	for (i = 0; i < BUF_LOCKS; i++)
1319 		mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
1320 	kmem_cache_destroy(hdr_full_cache);
1321 	kmem_cache_destroy(hdr_l2only_cache);
1322 	kmem_cache_destroy(buf_cache);
1323 }
1324 
1325 /*
1326  * Constructor callback - called when the cache is empty
1327  * and a new buf is requested.
1328  */
1329 /* ARGSUSED */
1330 static int
1331 hdr_full_cons(void *vbuf, void *unused, int kmflag)
1332 {
1333 	arc_buf_hdr_t *hdr = vbuf;
1334 
1335 	bzero(hdr, HDR_FULL_SIZE);
1336 	cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
1337 	refcount_create(&hdr->b_l1hdr.b_refcnt);
1338 	mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1339 	multilist_link_init(&hdr->b_l1hdr.b_arc_node);
1340 	arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1341 
1342 	return (0);
1343 }
1344 
1345 /* ARGSUSED */
1346 static int
1347 hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
1348 {
1349 	arc_buf_hdr_t *hdr = vbuf;
1350 
1351 	bzero(hdr, HDR_L2ONLY_SIZE);
1352 	arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1353 
1354 	return (0);
1355 }
1356 
1357 /* ARGSUSED */
1358 static int
1359 buf_cons(void *vbuf, void *unused, int kmflag)
1360 {
1361 	arc_buf_t *buf = vbuf;
1362 
1363 	bzero(buf, sizeof (arc_buf_t));
1364 	mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1365 	arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1366 
1367 	return (0);
1368 }
1369 
1370 /*
1371  * Destructor callback - called when a cached buf is
1372  * no longer required.
1373  */
1374 /* ARGSUSED */
1375 static void
1376 hdr_full_dest(void *vbuf, void *unused)
1377 {
1378 	arc_buf_hdr_t *hdr = vbuf;
1379 
1380 	ASSERT(HDR_EMPTY(hdr));
1381 	cv_destroy(&hdr->b_l1hdr.b_cv);
1382 	refcount_destroy(&hdr->b_l1hdr.b_refcnt);
1383 	mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1384 	ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1385 	arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1386 }
1387 
1388 /* ARGSUSED */
1389 static void
1390 hdr_l2only_dest(void *vbuf, void *unused)
1391 {
1392 	arc_buf_hdr_t *hdr = vbuf;
1393 
1394 	ASSERT(HDR_EMPTY(hdr));
1395 	arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1396 }
1397 
1398 /* ARGSUSED */
1399 static void
1400 buf_dest(void *vbuf, void *unused)
1401 {
1402 	arc_buf_t *buf = vbuf;
1403 
1404 	mutex_destroy(&buf->b_evict_lock);
1405 	arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1406 }
1407 
1408 /*
1409  * Reclaim callback -- invoked when memory is low.
1410  */
1411 /* ARGSUSED */
1412 static void
1413 hdr_recl(void *unused)
1414 {
1415 	dprintf("hdr_recl called\n");
1416 	/*
1417 	 * umem calls the reclaim func when we destroy the buf cache,
1418 	 * which is after we do arc_fini().
1419 	 */
1420 	if (arc_initialized)
1421 		zthr_wakeup(arc_reap_zthr);
1422 }
1423 
1424 static void
1425 buf_init(void)
1426 {
1427 	uint64_t *ct;
1428 	uint64_t hsize = 1ULL << 12;
1429 	int i, j;
1430 
1431 	/*
1432 	 * The hash table is big enough to fill all of physical memory
1433 	 * with an average block size of zfs_arc_average_blocksize (default 8K).
1434 	 * By default, the table will take up
1435 	 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1436 	 */
1437 	while (hsize * zfs_arc_average_blocksize < physmem * PAGESIZE)
1438 		hsize <<= 1;
1439 retry:
1440 	buf_hash_table.ht_mask = hsize - 1;
1441 	buf_hash_table.ht_table =
1442 	    kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1443 	if (buf_hash_table.ht_table == NULL) {
1444 		ASSERT(hsize > (1ULL << 8));
1445 		hsize >>= 1;
1446 		goto retry;
1447 	}
1448 
1449 	hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
1450 	    0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
1451 	hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
1452 	    HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
1453 	    NULL, NULL, 0);
1454 	buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1455 	    0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1456 
1457 	for (i = 0; i < 256; i++)
1458 		for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1459 			*ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1460 
1461 	for (i = 0; i < BUF_LOCKS; i++) {
1462 		mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1463 		    NULL, MUTEX_DEFAULT, NULL);
1464 	}
1465 }
1466 
1467 /*
1468  * This is the size that the buf occupies in memory. If the buf is compressed,
1469  * it will correspond to the compressed size. You should use this method of
1470  * getting the buf size unless you explicitly need the logical size.
1471  */
1472 int32_t
1473 arc_buf_size(arc_buf_t *buf)
1474 {
1475 	return (ARC_BUF_COMPRESSED(buf) ?
1476 	    HDR_GET_PSIZE(buf->b_hdr) : HDR_GET_LSIZE(buf->b_hdr));
1477 }
1478 
1479 int32_t
1480 arc_buf_lsize(arc_buf_t *buf)
1481 {
1482 	return (HDR_GET_LSIZE(buf->b_hdr));
1483 }
1484 
1485 enum zio_compress
1486 arc_get_compression(arc_buf_t *buf)
1487 {
1488 	return (ARC_BUF_COMPRESSED(buf) ?
1489 	    HDR_GET_COMPRESS(buf->b_hdr) : ZIO_COMPRESS_OFF);
1490 }
1491 
1492 #define	ARC_MINTIME	(hz>>4) /* 62 ms */
1493 
1494 static inline boolean_t
1495 arc_buf_is_shared(arc_buf_t *buf)
1496 {
1497 	boolean_t shared = (buf->b_data != NULL &&
1498 	    buf->b_hdr->b_l1hdr.b_pabd != NULL &&
1499 	    abd_is_linear(buf->b_hdr->b_l1hdr.b_pabd) &&
1500 	    buf->b_data == abd_to_buf(buf->b_hdr->b_l1hdr.b_pabd));
1501 	IMPLY(shared, HDR_SHARED_DATA(buf->b_hdr));
1502 	IMPLY(shared, ARC_BUF_SHARED(buf));
1503 	IMPLY(shared, ARC_BUF_COMPRESSED(buf) || ARC_BUF_LAST(buf));
1504 
1505 	/*
1506 	 * It would be nice to assert arc_can_share() too, but the "hdr isn't
1507 	 * already being shared" requirement prevents us from doing that.
1508 	 */
1509 
1510 	return (shared);
1511 }
1512 
1513 /*
1514  * Free the checksum associated with this header. If there is no checksum, this
1515  * is a no-op.
1516  */
1517 static inline void
1518 arc_cksum_free(arc_buf_hdr_t *hdr)
1519 {
1520 	ASSERT(HDR_HAS_L1HDR(hdr));
1521 	mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1522 	if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
1523 		kmem_free(hdr->b_l1hdr.b_freeze_cksum, sizeof (zio_cksum_t));
1524 		hdr->b_l1hdr.b_freeze_cksum = NULL;
1525 	}
1526 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1527 }
1528 
1529 /*
1530  * Return true iff at least one of the bufs on hdr is not compressed.
1531  */
1532 static boolean_t
1533 arc_hdr_has_uncompressed_buf(arc_buf_hdr_t *hdr)
1534 {
1535 	for (arc_buf_t *b = hdr->b_l1hdr.b_buf; b != NULL; b = b->b_next) {
1536 		if (!ARC_BUF_COMPRESSED(b)) {
1537 			return (B_TRUE);
1538 		}
1539 	}
1540 	return (B_FALSE);
1541 }
1542 
1543 /*
1544  * If we've turned on the ZFS_DEBUG_MODIFY flag, verify that the buf's data
1545  * matches the checksum that is stored in the hdr. If there is no checksum,
1546  * or if the buf is compressed, this is a no-op.
1547  */
1548 static void
1549 arc_cksum_verify(arc_buf_t *buf)
1550 {
1551 	arc_buf_hdr_t *hdr = buf->b_hdr;
1552 	zio_cksum_t zc;
1553 
1554 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1555 		return;
1556 
1557 	if (ARC_BUF_COMPRESSED(buf)) {
1558 		ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
1559 		    arc_hdr_has_uncompressed_buf(hdr));
1560 		return;
1561 	}
1562 
1563 	ASSERT(HDR_HAS_L1HDR(hdr));
1564 
1565 	mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1566 	if (hdr->b_l1hdr.b_freeze_cksum == NULL || HDR_IO_ERROR(hdr)) {
1567 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1568 		return;
1569 	}
1570 
1571 	fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL, &zc);
1572 	if (!ZIO_CHECKSUM_EQUAL(*hdr->b_l1hdr.b_freeze_cksum, zc))
1573 		panic("buffer modified while frozen!");
1574 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1575 }
1576 
1577 static boolean_t
1578 arc_cksum_is_equal(arc_buf_hdr_t *hdr, zio_t *zio)
1579 {
1580 	enum zio_compress compress = BP_GET_COMPRESS(zio->io_bp);
1581 	boolean_t valid_cksum;
1582 
1583 	ASSERT(!BP_IS_EMBEDDED(zio->io_bp));
1584 	VERIFY3U(BP_GET_PSIZE(zio->io_bp), ==, HDR_GET_PSIZE(hdr));
1585 
1586 	/*
1587 	 * We rely on the blkptr's checksum to determine if the block
1588 	 * is valid or not. When compressed arc is enabled, the l2arc
1589 	 * writes the block to the l2arc just as it appears in the pool.
1590 	 * This allows us to use the blkptr's checksum to validate the
1591 	 * data that we just read off of the l2arc without having to store
1592 	 * a separate checksum in the arc_buf_hdr_t. However, if compressed
1593 	 * arc is disabled, then the data written to the l2arc is always
1594 	 * uncompressed and won't match the block as it exists in the main
1595 	 * pool. When this is the case, we must first compress it if it is
1596 	 * compressed on the main pool before we can validate the checksum.
1597 	 */
1598 	if (!HDR_COMPRESSION_ENABLED(hdr) && compress != ZIO_COMPRESS_OFF) {
1599 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
1600 		uint64_t lsize = HDR_GET_LSIZE(hdr);
1601 		uint64_t csize;
1602 
1603 		abd_t *cdata = abd_alloc_linear(HDR_GET_PSIZE(hdr), B_TRUE);
1604 		csize = zio_compress_data(compress, zio->io_abd,
1605 		    abd_to_buf(cdata), lsize);
1606 
1607 		ASSERT3U(csize, <=, HDR_GET_PSIZE(hdr));
1608 		if (csize < HDR_GET_PSIZE(hdr)) {
1609 			/*
1610 			 * Compressed blocks are always a multiple of the
1611 			 * smallest ashift in the pool. Ideally, we would
1612 			 * like to round up the csize to the next
1613 			 * spa_min_ashift but that value may have changed
1614 			 * since the block was last written. Instead,
1615 			 * we rely on the fact that the hdr's psize
1616 			 * was set to the psize of the block when it was
1617 			 * last written. We set the csize to that value
1618 			 * and zero out any part that should not contain
1619 			 * data.
1620 			 */
1621 			abd_zero_off(cdata, csize, HDR_GET_PSIZE(hdr) - csize);
1622 			csize = HDR_GET_PSIZE(hdr);
1623 		}
1624 		zio_push_transform(zio, cdata, csize, HDR_GET_PSIZE(hdr), NULL);
1625 	}
1626 
1627 	/*
1628 	 * Block pointers always store the checksum for the logical data.
1629 	 * If the block pointer has the gang bit set, then the checksum
1630 	 * it represents is for the reconstituted data and not for an
1631 	 * individual gang member. The zio pipeline, however, must be able to
1632 	 * determine the checksum of each of the gang constituents so it
1633 	 * treats the checksum comparison differently than what we need
1634 	 * for l2arc blocks. This prevents us from using the
1635 	 * zio_checksum_error() interface directly. Instead we must call the
1636 	 * zio_checksum_error_impl() so that we can ensure the checksum is
1637 	 * generated using the correct checksum algorithm and accounts for the
1638 	 * logical I/O size and not just a gang fragment.
1639 	 */
1640 	valid_cksum = (zio_checksum_error_impl(zio->io_spa, zio->io_bp,
1641 	    BP_GET_CHECKSUM(zio->io_bp), zio->io_abd, zio->io_size,
1642 	    zio->io_offset, NULL) == 0);
1643 	zio_pop_transforms(zio);
1644 	return (valid_cksum);
1645 }
1646 
1647 /*
1648  * Given a buf full of data, if ZFS_DEBUG_MODIFY is enabled this computes a
1649  * checksum and attaches it to the buf's hdr so that we can ensure that the buf
1650  * isn't modified later on. If buf is compressed or there is already a checksum
1651  * on the hdr, this is a no-op (we only checksum uncompressed bufs).
1652  */
1653 static void
1654 arc_cksum_compute(arc_buf_t *buf)
1655 {
1656 	arc_buf_hdr_t *hdr = buf->b_hdr;
1657 
1658 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1659 		return;
1660 
1661 	ASSERT(HDR_HAS_L1HDR(hdr));
1662 
1663 	mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1664 	if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
1665 		ASSERT(arc_hdr_has_uncompressed_buf(hdr));
1666 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1667 		return;
1668 	} else if (ARC_BUF_COMPRESSED(buf)) {
1669 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1670 		return;
1671 	}
1672 
1673 	ASSERT(!ARC_BUF_COMPRESSED(buf));
1674 	hdr->b_l1hdr.b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t),
1675 	    KM_SLEEP);
1676 	fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL,
1677 	    hdr->b_l1hdr.b_freeze_cksum);
1678 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1679 	arc_buf_watch(buf);
1680 }
1681 
1682 #ifndef _KERNEL
1683 typedef struct procctl {
1684 	long cmd;
1685 	prwatch_t prwatch;
1686 } procctl_t;
1687 #endif
1688 
1689 /* ARGSUSED */
1690 static void
1691 arc_buf_unwatch(arc_buf_t *buf)
1692 {
1693 #ifndef _KERNEL
1694 	if (arc_watch) {
1695 		int result;
1696 		procctl_t ctl;
1697 		ctl.cmd = PCWATCH;
1698 		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1699 		ctl.prwatch.pr_size = 0;
1700 		ctl.prwatch.pr_wflags = 0;
1701 		result = write(arc_procfd, &ctl, sizeof (ctl));
1702 		ASSERT3U(result, ==, sizeof (ctl));
1703 	}
1704 #endif
1705 }
1706 
1707 /* ARGSUSED */
1708 static void
1709 arc_buf_watch(arc_buf_t *buf)
1710 {
1711 #ifndef _KERNEL
1712 	if (arc_watch) {
1713 		int result;
1714 		procctl_t ctl;
1715 		ctl.cmd = PCWATCH;
1716 		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1717 		ctl.prwatch.pr_size = arc_buf_size(buf);
1718 		ctl.prwatch.pr_wflags = WA_WRITE;
1719 		result = write(arc_procfd, &ctl, sizeof (ctl));
1720 		ASSERT3U(result, ==, sizeof (ctl));
1721 	}
1722 #endif
1723 }
1724 
1725 static arc_buf_contents_t
1726 arc_buf_type(arc_buf_hdr_t *hdr)
1727 {
1728 	arc_buf_contents_t type;
1729 	if (HDR_ISTYPE_METADATA(hdr)) {
1730 		type = ARC_BUFC_METADATA;
1731 	} else {
1732 		type = ARC_BUFC_DATA;
1733 	}
1734 	VERIFY3U(hdr->b_type, ==, type);
1735 	return (type);
1736 }
1737 
1738 boolean_t
1739 arc_is_metadata(arc_buf_t *buf)
1740 {
1741 	return (HDR_ISTYPE_METADATA(buf->b_hdr) != 0);
1742 }
1743 
1744 static uint32_t
1745 arc_bufc_to_flags(arc_buf_contents_t type)
1746 {
1747 	switch (type) {
1748 	case ARC_BUFC_DATA:
1749 		/* metadata field is 0 if buffer contains normal data */
1750 		return (0);
1751 	case ARC_BUFC_METADATA:
1752 		return (ARC_FLAG_BUFC_METADATA);
1753 	default:
1754 		break;
1755 	}
1756 	panic("undefined ARC buffer type!");
1757 	return ((uint32_t)-1);
1758 }
1759 
1760 void
1761 arc_buf_thaw(arc_buf_t *buf)
1762 {
1763 	arc_buf_hdr_t *hdr = buf->b_hdr;
1764 
1765 	ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
1766 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1767 
1768 	arc_cksum_verify(buf);
1769 
1770 	/*
1771 	 * Compressed buffers do not manipulate the b_freeze_cksum or
1772 	 * allocate b_thawed.
1773 	 */
1774 	if (ARC_BUF_COMPRESSED(buf)) {
1775 		ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
1776 		    arc_hdr_has_uncompressed_buf(hdr));
1777 		return;
1778 	}
1779 
1780 	ASSERT(HDR_HAS_L1HDR(hdr));
1781 	arc_cksum_free(hdr);
1782 
1783 	mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1784 #ifdef ZFS_DEBUG
1785 	if (zfs_flags & ZFS_DEBUG_MODIFY) {
1786 		if (hdr->b_l1hdr.b_thawed != NULL)
1787 			kmem_free(hdr->b_l1hdr.b_thawed, 1);
1788 		hdr->b_l1hdr.b_thawed = kmem_alloc(1, KM_SLEEP);
1789 	}
1790 #endif
1791 
1792 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1793 
1794 	arc_buf_unwatch(buf);
1795 }
1796 
1797 void
1798 arc_buf_freeze(arc_buf_t *buf)
1799 {
1800 	arc_buf_hdr_t *hdr = buf->b_hdr;
1801 	kmutex_t *hash_lock;
1802 
1803 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1804 		return;
1805 
1806 	if (ARC_BUF_COMPRESSED(buf)) {
1807 		ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
1808 		    arc_hdr_has_uncompressed_buf(hdr));
1809 		return;
1810 	}
1811 
1812 	hash_lock = HDR_LOCK(hdr);
1813 	mutex_enter(hash_lock);
1814 
1815 	ASSERT(HDR_HAS_L1HDR(hdr));
1816 	ASSERT(hdr->b_l1hdr.b_freeze_cksum != NULL ||
1817 	    hdr->b_l1hdr.b_state == arc_anon);
1818 	arc_cksum_compute(buf);
1819 	mutex_exit(hash_lock);
1820 }
1821 
1822 /*
1823  * The arc_buf_hdr_t's b_flags should never be modified directly. Instead,
1824  * the following functions should be used to ensure that the flags are
1825  * updated in a thread-safe way. When manipulating the flags either
1826  * the hash_lock must be held or the hdr must be undiscoverable. This
1827  * ensures that we're not racing with any other threads when updating
1828  * the flags.
1829  */
1830 static inline void
1831 arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
1832 {
1833 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
1834 	hdr->b_flags |= flags;
1835 }
1836 
1837 static inline void
1838 arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
1839 {
1840 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
1841 	hdr->b_flags &= ~flags;
1842 }
1843 
1844 /*
1845  * Setting the compression bits in the arc_buf_hdr_t's b_flags is
1846  * done in a special way since we have to clear and set bits
1847  * at the same time. Consumers that wish to set the compression bits
1848  * must use this function to ensure that the flags are updated in
1849  * thread-safe manner.
1850  */
1851 static void
1852 arc_hdr_set_compress(arc_buf_hdr_t *hdr, enum zio_compress cmp)
1853 {
1854 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
1855 
1856 	/*
1857 	 * Holes and embedded blocks will always have a psize = 0 so
1858 	 * we ignore the compression of the blkptr and set the
1859 	 * arc_buf_hdr_t's compression to ZIO_COMPRESS_OFF.
1860 	 * Holes and embedded blocks remain anonymous so we don't
1861 	 * want to uncompress them. Mark them as uncompressed.
1862 	 */
1863 	if (!zfs_compressed_arc_enabled || HDR_GET_PSIZE(hdr) == 0) {
1864 		arc_hdr_clear_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
1865 		HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_OFF);
1866 		ASSERT(!HDR_COMPRESSION_ENABLED(hdr));
1867 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
1868 	} else {
1869 		arc_hdr_set_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
1870 		HDR_SET_COMPRESS(hdr, cmp);
1871 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, cmp);
1872 		ASSERT(HDR_COMPRESSION_ENABLED(hdr));
1873 	}
1874 }
1875 
1876 /*
1877  * Looks for another buf on the same hdr which has the data decompressed, copies
1878  * from it, and returns true. If no such buf exists, returns false.
1879  */
1880 static boolean_t
1881 arc_buf_try_copy_decompressed_data(arc_buf_t *buf)
1882 {
1883 	arc_buf_hdr_t *hdr = buf->b_hdr;
1884 	boolean_t copied = B_FALSE;
1885 
1886 	ASSERT(HDR_HAS_L1HDR(hdr));
1887 	ASSERT3P(buf->b_data, !=, NULL);
1888 	ASSERT(!ARC_BUF_COMPRESSED(buf));
1889 
1890 	for (arc_buf_t *from = hdr->b_l1hdr.b_buf; from != NULL;
1891 	    from = from->b_next) {
1892 		/* can't use our own data buffer */
1893 		if (from == buf) {
1894 			continue;
1895 		}
1896 
1897 		if (!ARC_BUF_COMPRESSED(from)) {
1898 			bcopy(from->b_data, buf->b_data, arc_buf_size(buf));
1899 			copied = B_TRUE;
1900 			break;
1901 		}
1902 	}
1903 
1904 	/*
1905 	 * There were no decompressed bufs, so there should not be a
1906 	 * checksum on the hdr either.
1907 	 */
1908 	EQUIV(!copied, hdr->b_l1hdr.b_freeze_cksum == NULL);
1909 
1910 	return (copied);
1911 }
1912 
1913 /*
1914  * Given a buf that has a data buffer attached to it, this function will
1915  * efficiently fill the buf with data of the specified compression setting from
1916  * the hdr and update the hdr's b_freeze_cksum if necessary. If the buf and hdr
1917  * are already sharing a data buf, no copy is performed.
1918  *
1919  * If the buf is marked as compressed but uncompressed data was requested, this
1920  * will allocate a new data buffer for the buf, remove that flag, and fill the
1921  * buf with uncompressed data. You can't request a compressed buf on a hdr with
1922  * uncompressed data, and (since we haven't added support for it yet) if you
1923  * want compressed data your buf must already be marked as compressed and have
1924  * the correct-sized data buffer.
1925  */
1926 static int
1927 arc_buf_fill(arc_buf_t *buf, boolean_t compressed)
1928 {
1929 	arc_buf_hdr_t *hdr = buf->b_hdr;
1930 	boolean_t hdr_compressed = (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
1931 	dmu_object_byteswap_t bswap = hdr->b_l1hdr.b_byteswap;
1932 
1933 	ASSERT3P(buf->b_data, !=, NULL);
1934 	IMPLY(compressed, hdr_compressed);
1935 	IMPLY(compressed, ARC_BUF_COMPRESSED(buf));
1936 
1937 	if (hdr_compressed == compressed) {
1938 		if (!arc_buf_is_shared(buf)) {
1939 			abd_copy_to_buf(buf->b_data, hdr->b_l1hdr.b_pabd,
1940 			    arc_buf_size(buf));
1941 		}
1942 	} else {
1943 		ASSERT(hdr_compressed);
1944 		ASSERT(!compressed);
1945 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, HDR_GET_PSIZE(hdr));
1946 
1947 		/*
1948 		 * If the buf is sharing its data with the hdr, unlink it and
1949 		 * allocate a new data buffer for the buf.
1950 		 */
1951 		if (arc_buf_is_shared(buf)) {
1952 			ASSERT(ARC_BUF_COMPRESSED(buf));
1953 
1954 			/* We need to give the buf it's own b_data */
1955 			buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
1956 			buf->b_data =
1957 			    arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
1958 			arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
1959 
1960 			/* Previously overhead was 0; just add new overhead */
1961 			ARCSTAT_INCR(arcstat_overhead_size, HDR_GET_LSIZE(hdr));
1962 		} else if (ARC_BUF_COMPRESSED(buf)) {
1963 			/* We need to reallocate the buf's b_data */
1964 			arc_free_data_buf(hdr, buf->b_data, HDR_GET_PSIZE(hdr),
1965 			    buf);
1966 			buf->b_data =
1967 			    arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
1968 
1969 			/* We increased the size of b_data; update overhead */
1970 			ARCSTAT_INCR(arcstat_overhead_size,
1971 			    HDR_GET_LSIZE(hdr) - HDR_GET_PSIZE(hdr));
1972 		}
1973 
1974 		/*
1975 		 * Regardless of the buf's previous compression settings, it
1976 		 * should not be compressed at the end of this function.
1977 		 */
1978 		buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
1979 
1980 		/*
1981 		 * Try copying the data from another buf which already has a
1982 		 * decompressed version. If that's not possible, it's time to
1983 		 * bite the bullet and decompress the data from the hdr.
1984 		 */
1985 		if (arc_buf_try_copy_decompressed_data(buf)) {
1986 			/* Skip byteswapping and checksumming (already done) */
1987 			ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, !=, NULL);
1988 			return (0);
1989 		} else {
1990 			int error = zio_decompress_data(HDR_GET_COMPRESS(hdr),
1991 			    hdr->b_l1hdr.b_pabd, buf->b_data,
1992 			    HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
1993 
1994 			/*
1995 			 * Absent hardware errors or software bugs, this should
1996 			 * be impossible, but log it anyway so we can debug it.
1997 			 */
1998 			if (error != 0) {
1999 				zfs_dbgmsg(
2000 				    "hdr %p, compress %d, psize %d, lsize %d",
2001 				    hdr, HDR_GET_COMPRESS(hdr),
2002 				    HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
2003 				return (SET_ERROR(EIO));
2004 			}
2005 		}
2006 	}
2007 
2008 	/* Byteswap the buf's data if necessary */
2009 	if (bswap != DMU_BSWAP_NUMFUNCS) {
2010 		ASSERT(!HDR_SHARED_DATA(hdr));
2011 		ASSERT3U(bswap, <, DMU_BSWAP_NUMFUNCS);
2012 		dmu_ot_byteswap[bswap].ob_func(buf->b_data, HDR_GET_LSIZE(hdr));
2013 	}
2014 
2015 	/* Compute the hdr's checksum if necessary */
2016 	arc_cksum_compute(buf);
2017 
2018 	return (0);
2019 }
2020 
2021 int
2022 arc_decompress(arc_buf_t *buf)
2023 {
2024 	return (arc_buf_fill(buf, B_FALSE));
2025 }
2026 
2027 /*
2028  * Return the size of the block, b_pabd, that is stored in the arc_buf_hdr_t.
2029  */
2030 static uint64_t
2031 arc_hdr_size(arc_buf_hdr_t *hdr)
2032 {
2033 	uint64_t size;
2034 
2035 	if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
2036 	    HDR_GET_PSIZE(hdr) > 0) {
2037 		size = HDR_GET_PSIZE(hdr);
2038 	} else {
2039 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, 0);
2040 		size = HDR_GET_LSIZE(hdr);
2041 	}
2042 	return (size);
2043 }
2044 
2045 /*
2046  * Increment the amount of evictable space in the arc_state_t's refcount.
2047  * We account for the space used by the hdr and the arc buf individually
2048  * so that we can add and remove them from the refcount individually.
2049  */
2050 static void
2051 arc_evictable_space_increment(arc_buf_hdr_t *hdr, arc_state_t *state)
2052 {
2053 	arc_buf_contents_t type = arc_buf_type(hdr);
2054 
2055 	ASSERT(HDR_HAS_L1HDR(hdr));
2056 
2057 	if (GHOST_STATE(state)) {
2058 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
2059 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2060 		ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2061 		(void) refcount_add_many(&state->arcs_esize[type],
2062 		    HDR_GET_LSIZE(hdr), hdr);
2063 		return;
2064 	}
2065 
2066 	ASSERT(!GHOST_STATE(state));
2067 	if (hdr->b_l1hdr.b_pabd != NULL) {
2068 		(void) refcount_add_many(&state->arcs_esize[type],
2069 		    arc_hdr_size(hdr), hdr);
2070 	}
2071 	for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2072 	    buf = buf->b_next) {
2073 		if (arc_buf_is_shared(buf))
2074 			continue;
2075 		(void) refcount_add_many(&state->arcs_esize[type],
2076 		    arc_buf_size(buf), buf);
2077 	}
2078 }
2079 
2080 /*
2081  * Decrement the amount of evictable space in the arc_state_t's refcount.
2082  * We account for the space used by the hdr and the arc buf individually
2083  * so that we can add and remove them from the refcount individually.
2084  */
2085 static void
2086 arc_evictable_space_decrement(arc_buf_hdr_t *hdr, arc_state_t *state)
2087 {
2088 	arc_buf_contents_t type = arc_buf_type(hdr);
2089 
2090 	ASSERT(HDR_HAS_L1HDR(hdr));
2091 
2092 	if (GHOST_STATE(state)) {
2093 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
2094 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2095 		ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2096 		(void) refcount_remove_many(&state->arcs_esize[type],
2097 		    HDR_GET_LSIZE(hdr), hdr);
2098 		return;
2099 	}
2100 
2101 	ASSERT(!GHOST_STATE(state));
2102 	if (hdr->b_l1hdr.b_pabd != NULL) {
2103 		(void) refcount_remove_many(&state->arcs_esize[type],
2104 		    arc_hdr_size(hdr), hdr);
2105 	}
2106 	for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2107 	    buf = buf->b_next) {
2108 		if (arc_buf_is_shared(buf))
2109 			continue;
2110 		(void) refcount_remove_many(&state->arcs_esize[type],
2111 		    arc_buf_size(buf), buf);
2112 	}
2113 }
2114 
2115 /*
2116  * Add a reference to this hdr indicating that someone is actively
2117  * referencing that memory. When the refcount transitions from 0 to 1,
2118  * we remove it from the respective arc_state_t list to indicate that
2119  * it is not evictable.
2120  */
2121 static void
2122 add_reference(arc_buf_hdr_t *hdr, void *tag)
2123 {
2124 	ASSERT(HDR_HAS_L1HDR(hdr));
2125 	if (!MUTEX_HELD(HDR_LOCK(hdr))) {
2126 		ASSERT(hdr->b_l1hdr.b_state == arc_anon);
2127 		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2128 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2129 	}
2130 
2131 	arc_state_t *state = hdr->b_l1hdr.b_state;
2132 
2133 	if ((refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
2134 	    (state != arc_anon)) {
2135 		/* We don't use the L2-only state list. */
2136 		if (state != arc_l2c_only) {
2137 			multilist_remove(state->arcs_list[arc_buf_type(hdr)],
2138 			    hdr);
2139 			arc_evictable_space_decrement(hdr, state);
2140 		}
2141 		/* remove the prefetch flag if we get a reference */
2142 		arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
2143 	}
2144 }
2145 
2146 /*
2147  * Remove a reference from this hdr. When the reference transitions from
2148  * 1 to 0 and we're not anonymous, then we add this hdr to the arc_state_t's
2149  * list making it eligible for eviction.
2150  */
2151 static int
2152 remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
2153 {
2154 	int cnt;
2155 	arc_state_t *state = hdr->b_l1hdr.b_state;
2156 
2157 	ASSERT(HDR_HAS_L1HDR(hdr));
2158 	ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
2159 	ASSERT(!GHOST_STATE(state));
2160 
2161 	/*
2162 	 * arc_l2c_only counts as a ghost state so we don't need to explicitly
2163 	 * check to prevent usage of the arc_l2c_only list.
2164 	 */
2165 	if (((cnt = refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
2166 	    (state != arc_anon)) {
2167 		multilist_insert(state->arcs_list[arc_buf_type(hdr)], hdr);
2168 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
2169 		arc_evictable_space_increment(hdr, state);
2170 	}
2171 	return (cnt);
2172 }
2173 
2174 /*
2175  * Move the supplied buffer to the indicated state. The hash lock
2176  * for the buffer must be held by the caller.
2177  */
2178 static void
2179 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
2180     kmutex_t *hash_lock)
2181 {
2182 	arc_state_t *old_state;
2183 	int64_t refcnt;
2184 	uint32_t bufcnt;
2185 	boolean_t update_old, update_new;
2186 	arc_buf_contents_t buftype = arc_buf_type(hdr);
2187 
2188 	/*
2189 	 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
2190 	 * in arc_read() when bringing a buffer out of the L2ARC.  However, the
2191 	 * L1 hdr doesn't always exist when we change state to arc_anon before
2192 	 * destroying a header, in which case reallocating to add the L1 hdr is
2193 	 * pointless.
2194 	 */
2195 	if (HDR_HAS_L1HDR(hdr)) {
2196 		old_state = hdr->b_l1hdr.b_state;
2197 		refcnt = refcount_count(&hdr->b_l1hdr.b_refcnt);
2198 		bufcnt = hdr->b_l1hdr.b_bufcnt;
2199 		update_old = (bufcnt > 0 || hdr->b_l1hdr.b_pabd != NULL);
2200 	} else {
2201 		old_state = arc_l2c_only;
2202 		refcnt = 0;
2203 		bufcnt = 0;
2204 		update_old = B_FALSE;
2205 	}
2206 	update_new = update_old;
2207 
2208 	ASSERT(MUTEX_HELD(hash_lock));
2209 	ASSERT3P(new_state, !=, old_state);
2210 	ASSERT(!GHOST_STATE(new_state) || bufcnt == 0);
2211 	ASSERT(old_state != arc_anon || bufcnt <= 1);
2212 
2213 	/*
2214 	 * If this buffer is evictable, transfer it from the
2215 	 * old state list to the new state list.
2216 	 */
2217 	if (refcnt == 0) {
2218 		if (old_state != arc_anon && old_state != arc_l2c_only) {
2219 			ASSERT(HDR_HAS_L1HDR(hdr));
2220 			multilist_remove(old_state->arcs_list[buftype], hdr);
2221 
2222 			if (GHOST_STATE(old_state)) {
2223 				ASSERT0(bufcnt);
2224 				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2225 				update_old = B_TRUE;
2226 			}
2227 			arc_evictable_space_decrement(hdr, old_state);
2228 		}
2229 		if (new_state != arc_anon && new_state != arc_l2c_only) {
2230 
2231 			/*
2232 			 * An L1 header always exists here, since if we're
2233 			 * moving to some L1-cached state (i.e. not l2c_only or
2234 			 * anonymous), we realloc the header to add an L1hdr
2235 			 * beforehand.
2236 			 */
2237 			ASSERT(HDR_HAS_L1HDR(hdr));
2238 			multilist_insert(new_state->arcs_list[buftype], hdr);
2239 
2240 			if (GHOST_STATE(new_state)) {
2241 				ASSERT0(bufcnt);
2242 				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2243 				update_new = B_TRUE;
2244 			}
2245 			arc_evictable_space_increment(hdr, new_state);
2246 		}
2247 	}
2248 
2249 	ASSERT(!HDR_EMPTY(hdr));
2250 	if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
2251 		buf_hash_remove(hdr);
2252 
2253 	/* adjust state sizes (ignore arc_l2c_only) */
2254 
2255 	if (update_new && new_state != arc_l2c_only) {
2256 		ASSERT(HDR_HAS_L1HDR(hdr));
2257 		if (GHOST_STATE(new_state)) {
2258 			ASSERT0(bufcnt);
2259 
2260 			/*
2261 			 * When moving a header to a ghost state, we first
2262 			 * remove all arc buffers. Thus, we'll have a
2263 			 * bufcnt of zero, and no arc buffer to use for
2264 			 * the reference. As a result, we use the arc
2265 			 * header pointer for the reference.
2266 			 */
2267 			(void) refcount_add_many(&new_state->arcs_size,
2268 			    HDR_GET_LSIZE(hdr), hdr);
2269 			ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2270 		} else {
2271 			uint32_t buffers = 0;
2272 
2273 			/*
2274 			 * Each individual buffer holds a unique reference,
2275 			 * thus we must remove each of these references one
2276 			 * at a time.
2277 			 */
2278 			for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2279 			    buf = buf->b_next) {
2280 				ASSERT3U(bufcnt, !=, 0);
2281 				buffers++;
2282 
2283 				/*
2284 				 * When the arc_buf_t is sharing the data
2285 				 * block with the hdr, the owner of the
2286 				 * reference belongs to the hdr. Only
2287 				 * add to the refcount if the arc_buf_t is
2288 				 * not shared.
2289 				 */
2290 				if (arc_buf_is_shared(buf))
2291 					continue;
2292 
2293 				(void) refcount_add_many(&new_state->arcs_size,
2294 				    arc_buf_size(buf), buf);
2295 			}
2296 			ASSERT3U(bufcnt, ==, buffers);
2297 
2298 			if (hdr->b_l1hdr.b_pabd != NULL) {
2299 				(void) refcount_add_many(&new_state->arcs_size,
2300 				    arc_hdr_size(hdr), hdr);
2301 			} else {
2302 				ASSERT(GHOST_STATE(old_state));
2303 			}
2304 		}
2305 	}
2306 
2307 	if (update_old && old_state != arc_l2c_only) {
2308 		ASSERT(HDR_HAS_L1HDR(hdr));
2309 		if (GHOST_STATE(old_state)) {
2310 			ASSERT0(bufcnt);
2311 			ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2312 
2313 			/*
2314 			 * When moving a header off of a ghost state,
2315 			 * the header will not contain any arc buffers.
2316 			 * We use the arc header pointer for the reference
2317 			 * which is exactly what we did when we put the
2318 			 * header on the ghost state.
2319 			 */
2320 
2321 			(void) refcount_remove_many(&old_state->arcs_size,
2322 			    HDR_GET_LSIZE(hdr), hdr);
2323 		} else {
2324 			uint32_t buffers = 0;
2325 
2326 			/*
2327 			 * Each individual buffer holds a unique reference,
2328 			 * thus we must remove each of these references one
2329 			 * at a time.
2330 			 */
2331 			for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2332 			    buf = buf->b_next) {
2333 				ASSERT3U(bufcnt, !=, 0);
2334 				buffers++;
2335 
2336 				/*
2337 				 * When the arc_buf_t is sharing the data
2338 				 * block with the hdr, the owner of the
2339 				 * reference belongs to the hdr. Only
2340 				 * add to the refcount if the arc_buf_t is
2341 				 * not shared.
2342 				 */
2343 				if (arc_buf_is_shared(buf))
2344 					continue;
2345 
2346 				(void) refcount_remove_many(
2347 				    &old_state->arcs_size, arc_buf_size(buf),
2348 				    buf);
2349 			}
2350 			ASSERT3U(bufcnt, ==, buffers);
2351 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2352 			(void) refcount_remove_many(
2353 			    &old_state->arcs_size, arc_hdr_size(hdr), hdr);
2354 		}
2355 	}
2356 
2357 	if (HDR_HAS_L1HDR(hdr))
2358 		hdr->b_l1hdr.b_state = new_state;
2359 
2360 	/*
2361 	 * L2 headers should never be on the L2 state list since they don't
2362 	 * have L1 headers allocated.
2363 	 */
2364 	ASSERT(multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
2365 	    multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
2366 }
2367 
2368 void
2369 arc_space_consume(uint64_t space, arc_space_type_t type)
2370 {
2371 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2372 
2373 	switch (type) {
2374 	case ARC_SPACE_DATA:
2375 		aggsum_add(&astat_data_size, space);
2376 		break;
2377 	case ARC_SPACE_META:
2378 		aggsum_add(&astat_metadata_size, space);
2379 		break;
2380 	case ARC_SPACE_OTHER:
2381 		aggsum_add(&astat_other_size, space);
2382 		break;
2383 	case ARC_SPACE_HDRS:
2384 		aggsum_add(&astat_hdr_size, space);
2385 		break;
2386 	case ARC_SPACE_L2HDRS:
2387 		aggsum_add(&astat_l2_hdr_size, space);
2388 		break;
2389 	}
2390 
2391 	if (type != ARC_SPACE_DATA)
2392 		aggsum_add(&arc_meta_used, space);
2393 
2394 	aggsum_add(&arc_size, space);
2395 }
2396 
2397 void
2398 arc_space_return(uint64_t space, arc_space_type_t type)
2399 {
2400 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2401 
2402 	switch (type) {
2403 	case ARC_SPACE_DATA:
2404 		aggsum_add(&astat_data_size, -space);
2405 		break;
2406 	case ARC_SPACE_META:
2407 		aggsum_add(&astat_metadata_size, -space);
2408 		break;
2409 	case ARC_SPACE_OTHER:
2410 		aggsum_add(&astat_other_size, -space);
2411 		break;
2412 	case ARC_SPACE_HDRS:
2413 		aggsum_add(&astat_hdr_size, -space);
2414 		break;
2415 	case ARC_SPACE_L2HDRS:
2416 		aggsum_add(&astat_l2_hdr_size, -space);
2417 		break;
2418 	}
2419 
2420 	if (type != ARC_SPACE_DATA) {
2421 		ASSERT(aggsum_compare(&arc_meta_used, space) >= 0);
2422 		/*
2423 		 * We use the upper bound here rather than the precise value
2424 		 * because the arc_meta_max value doesn't need to be
2425 		 * precise. It's only consumed by humans via arcstats.
2426 		 */
2427 		if (arc_meta_max < aggsum_upper_bound(&arc_meta_used))
2428 			arc_meta_max = aggsum_upper_bound(&arc_meta_used);
2429 		aggsum_add(&arc_meta_used, -space);
2430 	}
2431 
2432 	ASSERT(aggsum_compare(&arc_size, space) >= 0);
2433 	aggsum_add(&arc_size, -space);
2434 }
2435 
2436 /*
2437  * Given a hdr and a buf, returns whether that buf can share its b_data buffer
2438  * with the hdr's b_pabd.
2439  */
2440 static boolean_t
2441 arc_can_share(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2442 {
2443 	/*
2444 	 * The criteria for sharing a hdr's data are:
2445 	 * 1. the hdr's compression matches the buf's compression
2446 	 * 2. the hdr doesn't need to be byteswapped
2447 	 * 3. the hdr isn't already being shared
2448 	 * 4. the buf is either compressed or it is the last buf in the hdr list
2449 	 *
2450 	 * Criterion #4 maintains the invariant that shared uncompressed
2451 	 * bufs must be the final buf in the hdr's b_buf list. Reading this, you
2452 	 * might ask, "if a compressed buf is allocated first, won't that be the
2453 	 * last thing in the list?", but in that case it's impossible to create
2454 	 * a shared uncompressed buf anyway (because the hdr must be compressed
2455 	 * to have the compressed buf). You might also think that #3 is
2456 	 * sufficient to make this guarantee, however it's possible
2457 	 * (specifically in the rare L2ARC write race mentioned in
2458 	 * arc_buf_alloc_impl()) there will be an existing uncompressed buf that
2459 	 * is sharable, but wasn't at the time of its allocation. Rather than
2460 	 * allow a new shared uncompressed buf to be created and then shuffle
2461 	 * the list around to make it the last element, this simply disallows
2462 	 * sharing if the new buf isn't the first to be added.
2463 	 */
2464 	ASSERT3P(buf->b_hdr, ==, hdr);
2465 	boolean_t hdr_compressed = HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF;
2466 	boolean_t buf_compressed = ARC_BUF_COMPRESSED(buf) != 0;
2467 	return (buf_compressed == hdr_compressed &&
2468 	    hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS &&
2469 	    !HDR_SHARED_DATA(hdr) &&
2470 	    (ARC_BUF_LAST(buf) || ARC_BUF_COMPRESSED(buf)));
2471 }
2472 
2473 /*
2474  * Allocate a buf for this hdr. If you care about the data that's in the hdr,
2475  * or if you want a compressed buffer, pass those flags in. Returns 0 if the
2476  * copy was made successfully, or an error code otherwise.
2477  */
2478 static int
2479 arc_buf_alloc_impl(arc_buf_hdr_t *hdr, void *tag, boolean_t compressed,
2480     boolean_t fill, arc_buf_t **ret)
2481 {
2482 	arc_buf_t *buf;
2483 
2484 	ASSERT(HDR_HAS_L1HDR(hdr));
2485 	ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
2486 	VERIFY(hdr->b_type == ARC_BUFC_DATA ||
2487 	    hdr->b_type == ARC_BUFC_METADATA);
2488 	ASSERT3P(ret, !=, NULL);
2489 	ASSERT3P(*ret, ==, NULL);
2490 
2491 	buf = *ret = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2492 	buf->b_hdr = hdr;
2493 	buf->b_data = NULL;
2494 	buf->b_next = hdr->b_l1hdr.b_buf;
2495 	buf->b_flags = 0;
2496 
2497 	add_reference(hdr, tag);
2498 
2499 	/*
2500 	 * We're about to change the hdr's b_flags. We must either
2501 	 * hold the hash_lock or be undiscoverable.
2502 	 */
2503 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2504 
2505 	/*
2506 	 * Only honor requests for compressed bufs if the hdr is actually
2507 	 * compressed.
2508 	 */
2509 	if (compressed && HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF)
2510 		buf->b_flags |= ARC_BUF_FLAG_COMPRESSED;
2511 
2512 	/*
2513 	 * If the hdr's data can be shared then we share the data buffer and
2514 	 * set the appropriate bit in the hdr's b_flags to indicate the hdr is
2515 	 * sharing it's b_pabd with the arc_buf_t. Otherwise, we allocate a new
2516 	 * buffer to store the buf's data.
2517 	 *
2518 	 * There are two additional restrictions here because we're sharing
2519 	 * hdr -> buf instead of the usual buf -> hdr. First, the hdr can't be
2520 	 * actively involved in an L2ARC write, because if this buf is used by
2521 	 * an arc_write() then the hdr's data buffer will be released when the
2522 	 * write completes, even though the L2ARC write might still be using it.
2523 	 * Second, the hdr's ABD must be linear so that the buf's user doesn't
2524 	 * need to be ABD-aware.
2525 	 */
2526 	boolean_t can_share = arc_can_share(hdr, buf) && !HDR_L2_WRITING(hdr) &&
2527 	    abd_is_linear(hdr->b_l1hdr.b_pabd);
2528 
2529 	/* Set up b_data and sharing */
2530 	if (can_share) {
2531 		buf->b_data = abd_to_buf(hdr->b_l1hdr.b_pabd);
2532 		buf->b_flags |= ARC_BUF_FLAG_SHARED;
2533 		arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
2534 	} else {
2535 		buf->b_data =
2536 		    arc_get_data_buf(hdr, arc_buf_size(buf), buf);
2537 		ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
2538 	}
2539 	VERIFY3P(buf->b_data, !=, NULL);
2540 
2541 	hdr->b_l1hdr.b_buf = buf;
2542 	hdr->b_l1hdr.b_bufcnt += 1;
2543 
2544 	/*
2545 	 * If the user wants the data from the hdr, we need to either copy or
2546 	 * decompress the data.
2547 	 */
2548 	if (fill) {
2549 		return (arc_buf_fill(buf, ARC_BUF_COMPRESSED(buf) != 0));
2550 	}
2551 
2552 	return (0);
2553 }
2554 
2555 static char *arc_onloan_tag = "onloan";
2556 
2557 static inline void
2558 arc_loaned_bytes_update(int64_t delta)
2559 {
2560 	atomic_add_64(&arc_loaned_bytes, delta);
2561 
2562 	/* assert that it did not wrap around */
2563 	ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
2564 }
2565 
2566 /*
2567  * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
2568  * flight data by arc_tempreserve_space() until they are "returned". Loaned
2569  * buffers must be returned to the arc before they can be used by the DMU or
2570  * freed.
2571  */
2572 arc_buf_t *
2573 arc_loan_buf(spa_t *spa, boolean_t is_metadata, int size)
2574 {
2575 	arc_buf_t *buf = arc_alloc_buf(spa, arc_onloan_tag,
2576 	    is_metadata ? ARC_BUFC_METADATA : ARC_BUFC_DATA, size);
2577 
2578 	arc_loaned_bytes_update(arc_buf_size(buf));
2579 
2580 	return (buf);
2581 }
2582 
2583 arc_buf_t *
2584 arc_loan_compressed_buf(spa_t *spa, uint64_t psize, uint64_t lsize,
2585     enum zio_compress compression_type)
2586 {
2587 	arc_buf_t *buf = arc_alloc_compressed_buf(spa, arc_onloan_tag,
2588 	    psize, lsize, compression_type);
2589 
2590 	arc_loaned_bytes_update(arc_buf_size(buf));
2591 
2592 	return (buf);
2593 }
2594 
2595 
2596 /*
2597  * Return a loaned arc buffer to the arc.
2598  */
2599 void
2600 arc_return_buf(arc_buf_t *buf, void *tag)
2601 {
2602 	arc_buf_hdr_t *hdr = buf->b_hdr;
2603 
2604 	ASSERT3P(buf->b_data, !=, NULL);
2605 	ASSERT(HDR_HAS_L1HDR(hdr));
2606 	(void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2607 	(void) refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2608 
2609 	arc_loaned_bytes_update(-arc_buf_size(buf));
2610 }
2611 
2612 /* Detach an arc_buf from a dbuf (tag) */
2613 void
2614 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
2615 {
2616 	arc_buf_hdr_t *hdr = buf->b_hdr;
2617 
2618 	ASSERT3P(buf->b_data, !=, NULL);
2619 	ASSERT(HDR_HAS_L1HDR(hdr));
2620 	(void) refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2621 	(void) refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
2622 
2623 	arc_loaned_bytes_update(arc_buf_size(buf));
2624 }
2625 
2626 static void
2627 l2arc_free_abd_on_write(abd_t *abd, size_t size, arc_buf_contents_t type)
2628 {
2629 	l2arc_data_free_t *df = kmem_alloc(sizeof (*df), KM_SLEEP);
2630 
2631 	df->l2df_abd = abd;
2632 	df->l2df_size = size;
2633 	df->l2df_type = type;
2634 	mutex_enter(&l2arc_free_on_write_mtx);
2635 	list_insert_head(l2arc_free_on_write, df);
2636 	mutex_exit(&l2arc_free_on_write_mtx);
2637 }
2638 
2639 static void
2640 arc_hdr_free_on_write(arc_buf_hdr_t *hdr)
2641 {
2642 	arc_state_t *state = hdr->b_l1hdr.b_state;
2643 	arc_buf_contents_t type = arc_buf_type(hdr);
2644 	uint64_t size = arc_hdr_size(hdr);
2645 
2646 	/* protected by hash lock, if in the hash table */
2647 	if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
2648 		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2649 		ASSERT(state != arc_anon && state != arc_l2c_only);
2650 
2651 		(void) refcount_remove_many(&state->arcs_esize[type],
2652 		    size, hdr);
2653 	}
2654 	(void) refcount_remove_many(&state->arcs_size, size, hdr);
2655 	if (type == ARC_BUFC_METADATA) {
2656 		arc_space_return(size, ARC_SPACE_META);
2657 	} else {
2658 		ASSERT(type == ARC_BUFC_DATA);
2659 		arc_space_return(size, ARC_SPACE_DATA);
2660 	}
2661 
2662 	l2arc_free_abd_on_write(hdr->b_l1hdr.b_pabd, size, type);
2663 }
2664 
2665 /*
2666  * Share the arc_buf_t's data with the hdr. Whenever we are sharing the
2667  * data buffer, we transfer the refcount ownership to the hdr and update
2668  * the appropriate kstats.
2669  */
2670 static void
2671 arc_share_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2672 {
2673 	arc_state_t *state = hdr->b_l1hdr.b_state;
2674 
2675 	ASSERT(arc_can_share(hdr, buf));
2676 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2677 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2678 
2679 	/*
2680 	 * Start sharing the data buffer. We transfer the
2681 	 * refcount ownership to the hdr since it always owns
2682 	 * the refcount whenever an arc_buf_t is shared.
2683 	 */
2684 	refcount_transfer_ownership(&state->arcs_size, buf, hdr);
2685 	hdr->b_l1hdr.b_pabd = abd_get_from_buf(buf->b_data, arc_buf_size(buf));
2686 	abd_take_ownership_of_buf(hdr->b_l1hdr.b_pabd,
2687 	    HDR_ISTYPE_METADATA(hdr));
2688 	arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
2689 	buf->b_flags |= ARC_BUF_FLAG_SHARED;
2690 
2691 	/*
2692 	 * Since we've transferred ownership to the hdr we need
2693 	 * to increment its compressed and uncompressed kstats and
2694 	 * decrement the overhead size.
2695 	 */
2696 	ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
2697 	ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
2698 	ARCSTAT_INCR(arcstat_overhead_size, -arc_buf_size(buf));
2699 }
2700 
2701 static void
2702 arc_unshare_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2703 {
2704 	arc_state_t *state = hdr->b_l1hdr.b_state;
2705 
2706 	ASSERT(arc_buf_is_shared(buf));
2707 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2708 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2709 
2710 	/*
2711 	 * We are no longer sharing this buffer so we need
2712 	 * to transfer its ownership to the rightful owner.
2713 	 */
2714 	refcount_transfer_ownership(&state->arcs_size, hdr, buf);
2715 	arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2716 	abd_release_ownership_of_buf(hdr->b_l1hdr.b_pabd);
2717 	abd_put(hdr->b_l1hdr.b_pabd);
2718 	hdr->b_l1hdr.b_pabd = NULL;
2719 	buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
2720 
2721 	/*
2722 	 * Since the buffer is no longer shared between
2723 	 * the arc buf and the hdr, count it as overhead.
2724 	 */
2725 	ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
2726 	ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
2727 	ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
2728 }
2729 
2730 /*
2731  * Remove an arc_buf_t from the hdr's buf list and return the last
2732  * arc_buf_t on the list. If no buffers remain on the list then return
2733  * NULL.
2734  */
2735 static arc_buf_t *
2736 arc_buf_remove(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2737 {
2738 	ASSERT(HDR_HAS_L1HDR(hdr));
2739 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2740 
2741 	arc_buf_t **bufp = &hdr->b_l1hdr.b_buf;
2742 	arc_buf_t *lastbuf = NULL;
2743 
2744 	/*
2745 	 * Remove the buf from the hdr list and locate the last
2746 	 * remaining buffer on the list.
2747 	 */
2748 	while (*bufp != NULL) {
2749 		if (*bufp == buf)
2750 			*bufp = buf->b_next;
2751 
2752 		/*
2753 		 * If we've removed a buffer in the middle of
2754 		 * the list then update the lastbuf and update
2755 		 * bufp.
2756 		 */
2757 		if (*bufp != NULL) {
2758 			lastbuf = *bufp;
2759 			bufp = &(*bufp)->b_next;
2760 		}
2761 	}
2762 	buf->b_next = NULL;
2763 	ASSERT3P(lastbuf, !=, buf);
2764 	IMPLY(hdr->b_l1hdr.b_bufcnt > 0, lastbuf != NULL);
2765 	IMPLY(hdr->b_l1hdr.b_bufcnt > 0, hdr->b_l1hdr.b_buf != NULL);
2766 	IMPLY(lastbuf != NULL, ARC_BUF_LAST(lastbuf));
2767 
2768 	return (lastbuf);
2769 }
2770 
2771 /*
2772  * Free up buf->b_data and pull the arc_buf_t off of the the arc_buf_hdr_t's
2773  * list and free it.
2774  */
2775 static void
2776 arc_buf_destroy_impl(arc_buf_t *buf)
2777 {
2778 	arc_buf_hdr_t *hdr = buf->b_hdr;
2779 
2780 	/*
2781 	 * Free up the data associated with the buf but only if we're not
2782 	 * sharing this with the hdr. If we are sharing it with the hdr, the
2783 	 * hdr is responsible for doing the free.
2784 	 */
2785 	if (buf->b_data != NULL) {
2786 		/*
2787 		 * We're about to change the hdr's b_flags. We must either
2788 		 * hold the hash_lock or be undiscoverable.
2789 		 */
2790 		ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2791 
2792 		arc_cksum_verify(buf);
2793 		arc_buf_unwatch(buf);
2794 
2795 		if (arc_buf_is_shared(buf)) {
2796 			arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2797 		} else {
2798 			uint64_t size = arc_buf_size(buf);
2799 			arc_free_data_buf(hdr, buf->b_data, size, buf);
2800 			ARCSTAT_INCR(arcstat_overhead_size, -size);
2801 		}
2802 		buf->b_data = NULL;
2803 
2804 		ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
2805 		hdr->b_l1hdr.b_bufcnt -= 1;
2806 	}
2807 
2808 	arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
2809 
2810 	if (ARC_BUF_SHARED(buf) && !ARC_BUF_COMPRESSED(buf)) {
2811 		/*
2812 		 * If the current arc_buf_t is sharing its data buffer with the
2813 		 * hdr, then reassign the hdr's b_pabd to share it with the new
2814 		 * buffer at the end of the list. The shared buffer is always
2815 		 * the last one on the hdr's buffer list.
2816 		 *
2817 		 * There is an equivalent case for compressed bufs, but since
2818 		 * they aren't guaranteed to be the last buf in the list and
2819 		 * that is an exceedingly rare case, we just allow that space be
2820 		 * wasted temporarily.
2821 		 */
2822 		if (lastbuf != NULL) {
2823 			/* Only one buf can be shared at once */
2824 			VERIFY(!arc_buf_is_shared(lastbuf));
2825 			/* hdr is uncompressed so can't have compressed buf */
2826 			VERIFY(!ARC_BUF_COMPRESSED(lastbuf));
2827 
2828 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2829 			arc_hdr_free_pabd(hdr);
2830 
2831 			/*
2832 			 * We must setup a new shared block between the
2833 			 * last buffer and the hdr. The data would have
2834 			 * been allocated by the arc buf so we need to transfer
2835 			 * ownership to the hdr since it's now being shared.
2836 			 */
2837 			arc_share_buf(hdr, lastbuf);
2838 		}
2839 	} else if (HDR_SHARED_DATA(hdr)) {
2840 		/*
2841 		 * Uncompressed shared buffers are always at the end
2842 		 * of the list. Compressed buffers don't have the
2843 		 * same requirements. This makes it hard to
2844 		 * simply assert that the lastbuf is shared so
2845 		 * we rely on the hdr's compression flags to determine
2846 		 * if we have a compressed, shared buffer.
2847 		 */
2848 		ASSERT3P(lastbuf, !=, NULL);
2849 		ASSERT(arc_buf_is_shared(lastbuf) ||
2850 		    HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
2851 	}
2852 
2853 	/*
2854 	 * Free the checksum if we're removing the last uncompressed buf from
2855 	 * this hdr.
2856 	 */
2857 	if (!arc_hdr_has_uncompressed_buf(hdr)) {
2858 		arc_cksum_free(hdr);
2859 	}
2860 
2861 	/* clean up the buf */
2862 	buf->b_hdr = NULL;
2863 	kmem_cache_free(buf_cache, buf);
2864 }
2865 
2866 static void
2867 arc_hdr_alloc_pabd(arc_buf_hdr_t *hdr)
2868 {
2869 	ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
2870 	ASSERT(HDR_HAS_L1HDR(hdr));
2871 	ASSERT(!HDR_SHARED_DATA(hdr));
2872 
2873 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2874 	hdr->b_l1hdr.b_pabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr);
2875 	hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
2876 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2877 
2878 	ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
2879 	ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
2880 }
2881 
2882 static void
2883 arc_hdr_free_pabd(arc_buf_hdr_t *hdr)
2884 {
2885 	ASSERT(HDR_HAS_L1HDR(hdr));
2886 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2887 
2888 	/*
2889 	 * If the hdr is currently being written to the l2arc then
2890 	 * we defer freeing the data by adding it to the l2arc_free_on_write
2891 	 * list. The l2arc will free the data once it's finished
2892 	 * writing it to the l2arc device.
2893 	 */
2894 	if (HDR_L2_WRITING(hdr)) {
2895 		arc_hdr_free_on_write(hdr);
2896 		ARCSTAT_BUMP(arcstat_l2_free_on_write);
2897 	} else {
2898 		arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
2899 		    arc_hdr_size(hdr), hdr);
2900 	}
2901 	hdr->b_l1hdr.b_pabd = NULL;
2902 	hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
2903 
2904 	ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
2905 	ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
2906 }
2907 
2908 static arc_buf_hdr_t *
2909 arc_hdr_alloc(uint64_t spa, int32_t psize, int32_t lsize,
2910     enum zio_compress compression_type, arc_buf_contents_t type)
2911 {
2912 	arc_buf_hdr_t *hdr;
2913 
2914 	VERIFY(type == ARC_BUFC_DATA || type == ARC_BUFC_METADATA);
2915 
2916 	hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
2917 	ASSERT(HDR_EMPTY(hdr));
2918 	ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
2919 	ASSERT3P(hdr->b_l1hdr.b_thawed, ==, NULL);
2920 	HDR_SET_PSIZE(hdr, psize);
2921 	HDR_SET_LSIZE(hdr, lsize);
2922 	hdr->b_spa = spa;
2923 	hdr->b_type = type;
2924 	hdr->b_flags = 0;
2925 	arc_hdr_set_flags(hdr, arc_bufc_to_flags(type) | ARC_FLAG_HAS_L1HDR);
2926 	arc_hdr_set_compress(hdr, compression_type);
2927 
2928 	hdr->b_l1hdr.b_state = arc_anon;
2929 	hdr->b_l1hdr.b_arc_access = 0;
2930 	hdr->b_l1hdr.b_bufcnt = 0;
2931 	hdr->b_l1hdr.b_buf = NULL;
2932 
2933 	/*
2934 	 * Allocate the hdr's buffer. This will contain either
2935 	 * the compressed or uncompressed data depending on the block
2936 	 * it references and compressed arc enablement.
2937 	 */
2938 	arc_hdr_alloc_pabd(hdr);
2939 	ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2940 
2941 	return (hdr);
2942 }
2943 
2944 /*
2945  * Transition between the two allocation states for the arc_buf_hdr struct.
2946  * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
2947  * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
2948  * version is used when a cache buffer is only in the L2ARC in order to reduce
2949  * memory usage.
2950  */
2951 static arc_buf_hdr_t *
2952 arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
2953 {
2954 	ASSERT(HDR_HAS_L2HDR(hdr));
2955 
2956 	arc_buf_hdr_t *nhdr;
2957 	l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
2958 
2959 	ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
2960 	    (old == hdr_l2only_cache && new == hdr_full_cache));
2961 
2962 	nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
2963 
2964 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
2965 	buf_hash_remove(hdr);
2966 
2967 	bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
2968 
2969 	if (new == hdr_full_cache) {
2970 		arc_hdr_set_flags(nhdr, ARC_FLAG_HAS_L1HDR);
2971 		/*
2972 		 * arc_access and arc_change_state need to be aware that a
2973 		 * header has just come out of L2ARC, so we set its state to
2974 		 * l2c_only even though it's about to change.
2975 		 */
2976 		nhdr->b_l1hdr.b_state = arc_l2c_only;
2977 
2978 		/* Verify previous threads set to NULL before freeing */
2979 		ASSERT3P(nhdr->b_l1hdr.b_pabd, ==, NULL);
2980 	} else {
2981 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2982 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
2983 		ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
2984 
2985 		/*
2986 		 * If we've reached here, We must have been called from
2987 		 * arc_evict_hdr(), as such we should have already been
2988 		 * removed from any ghost list we were previously on
2989 		 * (which protects us from racing with arc_evict_state),
2990 		 * thus no locking is needed during this check.
2991 		 */
2992 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
2993 
2994 		/*
2995 		 * A buffer must not be moved into the arc_l2c_only
2996 		 * state if it's not finished being written out to the
2997 		 * l2arc device. Otherwise, the b_l1hdr.b_pabd field
2998 		 * might try to be accessed, even though it was removed.
2999 		 */
3000 		VERIFY(!HDR_L2_WRITING(hdr));
3001 		VERIFY3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3002 
3003 #ifdef ZFS_DEBUG
3004 		if (hdr->b_l1hdr.b_thawed != NULL) {
3005 			kmem_free(hdr->b_l1hdr.b_thawed, 1);
3006 			hdr->b_l1hdr.b_thawed = NULL;
3007 		}
3008 #endif
3009 
3010 		arc_hdr_clear_flags(nhdr, ARC_FLAG_HAS_L1HDR);
3011 	}
3012 	/*
3013 	 * The header has been reallocated so we need to re-insert it into any
3014 	 * lists it was on.
3015 	 */
3016 	(void) buf_hash_insert(nhdr, NULL);
3017 
3018 	ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
3019 
3020 	mutex_enter(&dev->l2ad_mtx);
3021 
3022 	/*
3023 	 * We must place the realloc'ed header back into the list at
3024 	 * the same spot. Otherwise, if it's placed earlier in the list,
3025 	 * l2arc_write_buffers() could find it during the function's
3026 	 * write phase, and try to write it out to the l2arc.
3027 	 */
3028 	list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
3029 	list_remove(&dev->l2ad_buflist, hdr);
3030 
3031 	mutex_exit(&dev->l2ad_mtx);
3032 
3033 	/*
3034 	 * Since we're using the pointer address as the tag when
3035 	 * incrementing and decrementing the l2ad_alloc refcount, we
3036 	 * must remove the old pointer (that we're about to destroy) and
3037 	 * add the new pointer to the refcount. Otherwise we'd remove
3038 	 * the wrong pointer address when calling arc_hdr_destroy() later.
3039 	 */
3040 
3041 	(void) refcount_remove_many(&dev->l2ad_alloc, arc_hdr_size(hdr), hdr);
3042 	(void) refcount_add_many(&dev->l2ad_alloc, arc_hdr_size(nhdr), nhdr);
3043 
3044 	buf_discard_identity(hdr);
3045 	kmem_cache_free(old, hdr);
3046 
3047 	return (nhdr);
3048 }
3049 
3050 /*
3051  * Allocate a new arc_buf_hdr_t and arc_buf_t and return the buf to the caller.
3052  * The buf is returned thawed since we expect the consumer to modify it.
3053  */
3054 arc_buf_t *
3055 arc_alloc_buf(spa_t *spa, void *tag, arc_buf_contents_t type, int32_t size)
3056 {
3057 	arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), size, size,
3058 	    ZIO_COMPRESS_OFF, type);
3059 	ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
3060 
3061 	arc_buf_t *buf = NULL;
3062 	VERIFY0(arc_buf_alloc_impl(hdr, tag, B_FALSE, B_FALSE, &buf));
3063 	arc_buf_thaw(buf);
3064 
3065 	return (buf);
3066 }
3067 
3068 /*
3069  * Allocate a compressed buf in the same manner as arc_alloc_buf. Don't use this
3070  * for bufs containing metadata.
3071  */
3072 arc_buf_t *
3073 arc_alloc_compressed_buf(spa_t *spa, void *tag, uint64_t psize, uint64_t lsize,
3074     enum zio_compress compression_type)
3075 {
3076 	ASSERT3U(lsize, >, 0);
3077 	ASSERT3U(lsize, >=, psize);
3078 	ASSERT(compression_type > ZIO_COMPRESS_OFF);
3079 	ASSERT(compression_type < ZIO_COMPRESS_FUNCTIONS);
3080 
3081 	arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
3082 	    compression_type, ARC_BUFC_DATA);
3083 	ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
3084 
3085 	arc_buf_t *buf = NULL;
3086 	VERIFY0(arc_buf_alloc_impl(hdr, tag, B_TRUE, B_FALSE, &buf));
3087 	arc_buf_thaw(buf);
3088 	ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3089 
3090 	if (!arc_buf_is_shared(buf)) {
3091 		/*
3092 		 * To ensure that the hdr has the correct data in it if we call
3093 		 * arc_decompress() on this buf before it's been written to
3094 		 * disk, it's easiest if we just set up sharing between the
3095 		 * buf and the hdr.
3096 		 */
3097 		ASSERT(!abd_is_linear(hdr->b_l1hdr.b_pabd));
3098 		arc_hdr_free_pabd(hdr);
3099 		arc_share_buf(hdr, buf);
3100 	}
3101 
3102 	return (buf);
3103 }
3104 
3105 static void
3106 arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
3107 {
3108 	l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
3109 	l2arc_dev_t *dev = l2hdr->b_dev;
3110 	uint64_t psize = arc_hdr_size(hdr);
3111 
3112 	ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
3113 	ASSERT(HDR_HAS_L2HDR(hdr));
3114 
3115 	list_remove(&dev->l2ad_buflist, hdr);
3116 
3117 	ARCSTAT_INCR(arcstat_l2_psize, -psize);
3118 	ARCSTAT_INCR(arcstat_l2_lsize, -HDR_GET_LSIZE(hdr));
3119 
3120 	vdev_space_update(dev->l2ad_vdev, -psize, 0, 0);
3121 
3122 	(void) refcount_remove_many(&dev->l2ad_alloc, psize, hdr);
3123 	arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
3124 }
3125 
3126 static void
3127 arc_hdr_destroy(arc_buf_hdr_t *hdr)
3128 {
3129 	if (HDR_HAS_L1HDR(hdr)) {
3130 		ASSERT(hdr->b_l1hdr.b_buf == NULL ||
3131 		    hdr->b_l1hdr.b_bufcnt > 0);
3132 		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3133 		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
3134 	}
3135 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3136 	ASSERT(!HDR_IN_HASH_TABLE(hdr));
3137 
3138 	if (!HDR_EMPTY(hdr))
3139 		buf_discard_identity(hdr);
3140 
3141 	if (HDR_HAS_L2HDR(hdr)) {
3142 		l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3143 		boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
3144 
3145 		if (!buflist_held)
3146 			mutex_enter(&dev->l2ad_mtx);
3147 
3148 		/*
3149 		 * Even though we checked this conditional above, we
3150 		 * need to check this again now that we have the
3151 		 * l2ad_mtx. This is because we could be racing with
3152 		 * another thread calling l2arc_evict() which might have
3153 		 * destroyed this header's L2 portion as we were waiting
3154 		 * to acquire the l2ad_mtx. If that happens, we don't
3155 		 * want to re-destroy the header's L2 portion.
3156 		 */
3157 		if (HDR_HAS_L2HDR(hdr))
3158 			arc_hdr_l2hdr_destroy(hdr);
3159 
3160 		if (!buflist_held)
3161 			mutex_exit(&dev->l2ad_mtx);
3162 	}
3163 
3164 	if (HDR_HAS_L1HDR(hdr)) {
3165 		arc_cksum_free(hdr);
3166 
3167 		while (hdr->b_l1hdr.b_buf != NULL)
3168 			arc_buf_destroy_impl(hdr->b_l1hdr.b_buf);
3169 
3170 #ifdef ZFS_DEBUG
3171 		if (hdr->b_l1hdr.b_thawed != NULL) {
3172 			kmem_free(hdr->b_l1hdr.b_thawed, 1);
3173 			hdr->b_l1hdr.b_thawed = NULL;
3174 		}
3175 #endif
3176 
3177 		if (hdr->b_l1hdr.b_pabd != NULL) {
3178 			arc_hdr_free_pabd(hdr);
3179 		}
3180 	}
3181 
3182 	ASSERT3P(hdr->b_hash_next, ==, NULL);
3183 	if (HDR_HAS_L1HDR(hdr)) {
3184 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3185 		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
3186 		kmem_cache_free(hdr_full_cache, hdr);
3187 	} else {
3188 		kmem_cache_free(hdr_l2only_cache, hdr);
3189 	}
3190 }
3191 
3192 void
3193 arc_buf_destroy(arc_buf_t *buf, void* tag)
3194 {
3195 	arc_buf_hdr_t *hdr = buf->b_hdr;
3196 	kmutex_t *hash_lock = HDR_LOCK(hdr);
3197 
3198 	if (hdr->b_l1hdr.b_state == arc_anon) {
3199 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
3200 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3201 		VERIFY0(remove_reference(hdr, NULL, tag));
3202 		arc_hdr_destroy(hdr);
3203 		return;
3204 	}
3205 
3206 	mutex_enter(hash_lock);
3207 	ASSERT3P(hdr, ==, buf->b_hdr);
3208 	ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
3209 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3210 	ASSERT3P(hdr->b_l1hdr.b_state, !=, arc_anon);
3211 	ASSERT3P(buf->b_data, !=, NULL);
3212 
3213 	(void) remove_reference(hdr, hash_lock, tag);
3214 	arc_buf_destroy_impl(buf);
3215 	mutex_exit(hash_lock);
3216 }
3217 
3218 /*
3219  * Evict the arc_buf_hdr that is provided as a parameter. The resultant
3220  * state of the header is dependent on it's state prior to entering this
3221  * function. The following transitions are possible:
3222  *
3223  *    - arc_mru -> arc_mru_ghost
3224  *    - arc_mfu -> arc_mfu_ghost
3225  *    - arc_mru_ghost -> arc_l2c_only
3226  *    - arc_mru_ghost -> deleted
3227  *    - arc_mfu_ghost -> arc_l2c_only
3228  *    - arc_mfu_ghost -> deleted
3229  */
3230 static int64_t
3231 arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3232 {
3233 	arc_state_t *evicted_state, *state;
3234 	int64_t bytes_evicted = 0;
3235 
3236 	ASSERT(MUTEX_HELD(hash_lock));
3237 	ASSERT(HDR_HAS_L1HDR(hdr));
3238 
3239 	state = hdr->b_l1hdr.b_state;
3240 	if (GHOST_STATE(state)) {
3241 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3242 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3243 
3244 		/*
3245 		 * l2arc_write_buffers() relies on a header's L1 portion
3246 		 * (i.e. its b_pabd field) during it's write phase.
3247 		 * Thus, we cannot push a header onto the arc_l2c_only
3248 		 * state (removing it's L1 piece) until the header is
3249 		 * done being written to the l2arc.
3250 		 */
3251 		if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
3252 			ARCSTAT_BUMP(arcstat_evict_l2_skip);
3253 			return (bytes_evicted);
3254 		}
3255 
3256 		ARCSTAT_BUMP(arcstat_deleted);
3257 		bytes_evicted += HDR_GET_LSIZE(hdr);
3258 
3259 		DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
3260 
3261 		ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3262 		if (HDR_HAS_L2HDR(hdr)) {
3263 			/*
3264 			 * This buffer is cached on the 2nd Level ARC;
3265 			 * don't destroy the header.
3266 			 */
3267 			arc_change_state(arc_l2c_only, hdr, hash_lock);
3268 			/*
3269 			 * dropping from L1+L2 cached to L2-only,
3270 			 * realloc to remove the L1 header.
3271 			 */
3272 			hdr = arc_hdr_realloc(hdr, hdr_full_cache,
3273 			    hdr_l2only_cache);
3274 		} else {
3275 			arc_change_state(arc_anon, hdr, hash_lock);
3276 			arc_hdr_destroy(hdr);
3277 		}
3278 		return (bytes_evicted);
3279 	}
3280 
3281 	ASSERT(state == arc_mru || state == arc_mfu);
3282 	evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
3283 
3284 	/* prefetch buffers have a minimum lifespan */
3285 	if (HDR_IO_IN_PROGRESS(hdr) ||
3286 	    ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
3287 	    ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
3288 	    arc_min_prefetch_lifespan)) {
3289 		ARCSTAT_BUMP(arcstat_evict_skip);
3290 		return (bytes_evicted);
3291 	}
3292 
3293 	ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
3294 	while (hdr->b_l1hdr.b_buf) {
3295 		arc_buf_t *buf = hdr->b_l1hdr.b_buf;
3296 		if (!mutex_tryenter(&buf->b_evict_lock)) {
3297 			ARCSTAT_BUMP(arcstat_mutex_miss);
3298 			break;
3299 		}
3300 		if (buf->b_data != NULL)
3301 			bytes_evicted += HDR_GET_LSIZE(hdr);
3302 		mutex_exit(&buf->b_evict_lock);
3303 		arc_buf_destroy_impl(buf);
3304 	}
3305 
3306 	if (HDR_HAS_L2HDR(hdr)) {
3307 		ARCSTAT_INCR(arcstat_evict_l2_cached, HDR_GET_LSIZE(hdr));
3308 	} else {
3309 		if (l2arc_write_eligible(hdr->b_spa, hdr)) {
3310 			ARCSTAT_INCR(arcstat_evict_l2_eligible,
3311 			    HDR_GET_LSIZE(hdr));
3312 		} else {
3313 			ARCSTAT_INCR(arcstat_evict_l2_ineligible,
3314 			    HDR_GET_LSIZE(hdr));
3315 		}
3316 	}
3317 
3318 	if (hdr->b_l1hdr.b_bufcnt == 0) {
3319 		arc_cksum_free(hdr);
3320 
3321 		bytes_evicted += arc_hdr_size(hdr);
3322 
3323 		/*
3324 		 * If this hdr is being evicted and has a compressed
3325 		 * buffer then we discard it here before we change states.
3326 		 * This ensures that the accounting is updated correctly
3327 		 * in arc_free_data_impl().
3328 		 */
3329 		arc_hdr_free_pabd(hdr);
3330 
3331 		arc_change_state(evicted_state, hdr, hash_lock);
3332 		ASSERT(HDR_IN_HASH_TABLE(hdr));
3333 		arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
3334 		DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
3335 	}
3336 
3337 	return (bytes_evicted);
3338 }
3339 
3340 static uint64_t
3341 arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
3342     uint64_t spa, int64_t bytes)
3343 {
3344 	multilist_sublist_t *mls;
3345 	uint64_t bytes_evicted = 0;
3346 	arc_buf_hdr_t *hdr;
3347 	kmutex_t *hash_lock;
3348 	int evict_count = 0;
3349 
3350 	ASSERT3P(marker, !=, NULL);
3351 	IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3352 
3353 	mls = multilist_sublist_lock(ml, idx);
3354 
3355 	for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
3356 	    hdr = multilist_sublist_prev(mls, marker)) {
3357 		if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
3358 		    (evict_count >= zfs_arc_evict_batch_limit))
3359 			break;
3360 
3361 		/*
3362 		 * To keep our iteration location, move the marker
3363 		 * forward. Since we're not holding hdr's hash lock, we
3364 		 * must be very careful and not remove 'hdr' from the
3365 		 * sublist. Otherwise, other consumers might mistake the
3366 		 * 'hdr' as not being on a sublist when they call the
3367 		 * multilist_link_active() function (they all rely on
3368 		 * the hash lock protecting concurrent insertions and
3369 		 * removals). multilist_sublist_move_forward() was
3370 		 * specifically implemented to ensure this is the case
3371 		 * (only 'marker' will be removed and re-inserted).
3372 		 */
3373 		multilist_sublist_move_forward(mls, marker);
3374 
3375 		/*
3376 		 * The only case where the b_spa field should ever be
3377 		 * zero, is the marker headers inserted by
3378 		 * arc_evict_state(). It's possible for multiple threads
3379 		 * to be calling arc_evict_state() concurrently (e.g.
3380 		 * dsl_pool_close() and zio_inject_fault()), so we must
3381 		 * skip any markers we see from these other threads.
3382 		 */
3383 		if (hdr->b_spa == 0)
3384 			continue;
3385 
3386 		/* we're only interested in evicting buffers of a certain spa */
3387 		if (spa != 0 && hdr->b_spa != spa) {
3388 			ARCSTAT_BUMP(arcstat_evict_skip);
3389 			continue;
3390 		}
3391 
3392 		hash_lock = HDR_LOCK(hdr);
3393 
3394 		/*
3395 		 * We aren't calling this function from any code path
3396 		 * that would already be holding a hash lock, so we're
3397 		 * asserting on this assumption to be defensive in case
3398 		 * this ever changes. Without this check, it would be
3399 		 * possible to incorrectly increment arcstat_mutex_miss
3400 		 * below (e.g. if the code changed such that we called
3401 		 * this function with a hash lock held).
3402 		 */
3403 		ASSERT(!MUTEX_HELD(hash_lock));
3404 
3405 		if (mutex_tryenter(hash_lock)) {
3406 			uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
3407 			mutex_exit(hash_lock);
3408 
3409 			bytes_evicted += evicted;
3410 
3411 			/*
3412 			 * If evicted is zero, arc_evict_hdr() must have
3413 			 * decided to skip this header, don't increment
3414 			 * evict_count in this case.
3415 			 */
3416 			if (evicted != 0)
3417 				evict_count++;
3418 
3419 			/*
3420 			 * If arc_size isn't overflowing, signal any
3421 			 * threads that might happen to be waiting.
3422 			 *
3423 			 * For each header evicted, we wake up a single
3424 			 * thread. If we used cv_broadcast, we could
3425 			 * wake up "too many" threads causing arc_size
3426 			 * to significantly overflow arc_c; since
3427 			 * arc_get_data_impl() doesn't check for overflow
3428 			 * when it's woken up (it doesn't because it's
3429 			 * possible for the ARC to be overflowing while
3430 			 * full of un-evictable buffers, and the
3431 			 * function should proceed in this case).
3432 			 *
3433 			 * If threads are left sleeping, due to not
3434 			 * using cv_broadcast here, they will be woken
3435 			 * up via cv_broadcast in arc_adjust_cb() just
3436 			 * before arc_adjust_zthr sleeps.
3437 			 */
3438 			mutex_enter(&arc_adjust_lock);
3439 			if (!arc_is_overflowing())
3440 				cv_signal(&arc_adjust_waiters_cv);
3441 			mutex_exit(&arc_adjust_lock);
3442 		} else {
3443 			ARCSTAT_BUMP(arcstat_mutex_miss);
3444 		}
3445 	}
3446 
3447 	multilist_sublist_unlock(mls);
3448 
3449 	return (bytes_evicted);
3450 }
3451 
3452 /*
3453  * Evict buffers from the given arc state, until we've removed the
3454  * specified number of bytes. Move the removed buffers to the
3455  * appropriate evict state.
3456  *
3457  * This function makes a "best effort". It skips over any buffers
3458  * it can't get a hash_lock on, and so, may not catch all candidates.
3459  * It may also return without evicting as much space as requested.
3460  *
3461  * If bytes is specified using the special value ARC_EVICT_ALL, this
3462  * will evict all available (i.e. unlocked and evictable) buffers from
3463  * the given arc state; which is used by arc_flush().
3464  */
3465 static uint64_t
3466 arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
3467     arc_buf_contents_t type)
3468 {
3469 	uint64_t total_evicted = 0;
3470 	multilist_t *ml = state->arcs_list[type];
3471 	int num_sublists;
3472 	arc_buf_hdr_t **markers;
3473 
3474 	IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3475 
3476 	num_sublists = multilist_get_num_sublists(ml);
3477 
3478 	/*
3479 	 * If we've tried to evict from each sublist, made some
3480 	 * progress, but still have not hit the target number of bytes
3481 	 * to evict, we want to keep trying. The markers allow us to
3482 	 * pick up where we left off for each individual sublist, rather
3483 	 * than starting from the tail each time.
3484 	 */
3485 	markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
3486 	for (int i = 0; i < num_sublists; i++) {
3487 		markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
3488 
3489 		/*
3490 		 * A b_spa of 0 is used to indicate that this header is
3491 		 * a marker. This fact is used in arc_adjust_type() and
3492 		 * arc_evict_state_impl().
3493 		 */
3494 		markers[i]->b_spa = 0;
3495 
3496 		multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3497 		multilist_sublist_insert_tail(mls, markers[i]);
3498 		multilist_sublist_unlock(mls);
3499 	}
3500 
3501 	/*
3502 	 * While we haven't hit our target number of bytes to evict, or
3503 	 * we're evicting all available buffers.
3504 	 */
3505 	while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
3506 		/*
3507 		 * Start eviction using a randomly selected sublist,
3508 		 * this is to try and evenly balance eviction across all
3509 		 * sublists. Always starting at the same sublist
3510 		 * (e.g. index 0) would cause evictions to favor certain
3511 		 * sublists over others.
3512 		 */
3513 		int sublist_idx = multilist_get_random_index(ml);
3514 		uint64_t scan_evicted = 0;
3515 
3516 		for (int i = 0; i < num_sublists; i++) {
3517 			uint64_t bytes_remaining;
3518 			uint64_t bytes_evicted;
3519 
3520 			if (bytes == ARC_EVICT_ALL)
3521 				bytes_remaining = ARC_EVICT_ALL;
3522 			else if (total_evicted < bytes)
3523 				bytes_remaining = bytes - total_evicted;
3524 			else
3525 				break;
3526 
3527 			bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
3528 			    markers[sublist_idx], spa, bytes_remaining);
3529 
3530 			scan_evicted += bytes_evicted;
3531 			total_evicted += bytes_evicted;
3532 
3533 			/* we've reached the end, wrap to the beginning */
3534 			if (++sublist_idx >= num_sublists)
3535 				sublist_idx = 0;
3536 		}
3537 
3538 		/*
3539 		 * If we didn't evict anything during this scan, we have
3540 		 * no reason to believe we'll evict more during another
3541 		 * scan, so break the loop.
3542 		 */
3543 		if (scan_evicted == 0) {
3544 			/* This isn't possible, let's make that obvious */
3545 			ASSERT3S(bytes, !=, 0);
3546 
3547 			/*
3548 			 * When bytes is ARC_EVICT_ALL, the only way to
3549 			 * break the loop is when scan_evicted is zero.
3550 			 * In that case, we actually have evicted enough,
3551 			 * so we don't want to increment the kstat.
3552 			 */
3553 			if (bytes != ARC_EVICT_ALL) {
3554 				ASSERT3S(total_evicted, <, bytes);
3555 				ARCSTAT_BUMP(arcstat_evict_not_enough);
3556 			}
3557 
3558 			break;
3559 		}
3560 	}
3561 
3562 	for (int i = 0; i < num_sublists; i++) {
3563 		multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3564 		multilist_sublist_remove(mls, markers[i]);
3565 		multilist_sublist_unlock(mls);
3566 
3567 		kmem_cache_free(hdr_full_cache, markers[i]);
3568 	}
3569 	kmem_free(markers, sizeof (*markers) * num_sublists);
3570 
3571 	return (total_evicted);
3572 }
3573 
3574 /*
3575  * Flush all "evictable" data of the given type from the arc state
3576  * specified. This will not evict any "active" buffers (i.e. referenced).
3577  *
3578  * When 'retry' is set to B_FALSE, the function will make a single pass
3579  * over the state and evict any buffers that it can. Since it doesn't
3580  * continually retry the eviction, it might end up leaving some buffers
3581  * in the ARC due to lock misses.
3582  *
3583  * When 'retry' is set to B_TRUE, the function will continually retry the
3584  * eviction until *all* evictable buffers have been removed from the
3585  * state. As a result, if concurrent insertions into the state are
3586  * allowed (e.g. if the ARC isn't shutting down), this function might
3587  * wind up in an infinite loop, continually trying to evict buffers.
3588  */
3589 static uint64_t
3590 arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
3591     boolean_t retry)
3592 {
3593 	uint64_t evicted = 0;
3594 
3595 	while (refcount_count(&state->arcs_esize[type]) != 0) {
3596 		evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
3597 
3598 		if (!retry)
3599 			break;
3600 	}
3601 
3602 	return (evicted);
3603 }
3604 
3605 /*
3606  * Evict the specified number of bytes from the state specified,
3607  * restricting eviction to the spa and type given. This function
3608  * prevents us from trying to evict more from a state's list than
3609  * is "evictable", and to skip evicting altogether when passed a
3610  * negative value for "bytes". In contrast, arc_evict_state() will
3611  * evict everything it can, when passed a negative value for "bytes".
3612  */
3613 static uint64_t
3614 arc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
3615     arc_buf_contents_t type)
3616 {
3617 	int64_t delta;
3618 
3619 	if (bytes > 0 && refcount_count(&state->arcs_esize[type]) > 0) {
3620 		delta = MIN(refcount_count(&state->arcs_esize[type]), bytes);
3621 		return (arc_evict_state(state, spa, delta, type));
3622 	}
3623 
3624 	return (0);
3625 }
3626 
3627 /*
3628  * Evict metadata buffers from the cache, such that arc_meta_used is
3629  * capped by the arc_meta_limit tunable.
3630  */
3631 static uint64_t
3632 arc_adjust_meta(uint64_t meta_used)
3633 {
3634 	uint64_t total_evicted = 0;
3635 	int64_t target;
3636 
3637 	/*
3638 	 * If we're over the meta limit, we want to evict enough
3639 	 * metadata to get back under the meta limit. We don't want to
3640 	 * evict so much that we drop the MRU below arc_p, though. If
3641 	 * we're over the meta limit more than we're over arc_p, we
3642 	 * evict some from the MRU here, and some from the MFU below.
3643 	 */
3644 	target = MIN((int64_t)(meta_used - arc_meta_limit),
3645 	    (int64_t)(refcount_count(&arc_anon->arcs_size) +
3646 	    refcount_count(&arc_mru->arcs_size) - arc_p));
3647 
3648 	total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3649 
3650 	/*
3651 	 * Similar to the above, we want to evict enough bytes to get us
3652 	 * below the meta limit, but not so much as to drop us below the
3653 	 * space allotted to the MFU (which is defined as arc_c - arc_p).
3654 	 */
3655 	target = MIN((int64_t)(meta_used - arc_meta_limit),
3656 	    (int64_t)(refcount_count(&arc_mfu->arcs_size) -
3657 	    (arc_c - arc_p)));
3658 
3659 	total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3660 
3661 	return (total_evicted);
3662 }
3663 
3664 /*
3665  * Return the type of the oldest buffer in the given arc state
3666  *
3667  * This function will select a random sublist of type ARC_BUFC_DATA and
3668  * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
3669  * is compared, and the type which contains the "older" buffer will be
3670  * returned.
3671  */
3672 static arc_buf_contents_t
3673 arc_adjust_type(arc_state_t *state)
3674 {
3675 	multilist_t *data_ml = state->arcs_list[ARC_BUFC_DATA];
3676 	multilist_t *meta_ml = state->arcs_list[ARC_BUFC_METADATA];
3677 	int data_idx = multilist_get_random_index(data_ml);
3678 	int meta_idx = multilist_get_random_index(meta_ml);
3679 	multilist_sublist_t *data_mls;
3680 	multilist_sublist_t *meta_mls;
3681 	arc_buf_contents_t type;
3682 	arc_buf_hdr_t *data_hdr;
3683 	arc_buf_hdr_t *meta_hdr;
3684 
3685 	/*
3686 	 * We keep the sublist lock until we're finished, to prevent
3687 	 * the headers from being destroyed via arc_evict_state().
3688 	 */
3689 	data_mls = multilist_sublist_lock(data_ml, data_idx);
3690 	meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
3691 
3692 	/*
3693 	 * These two loops are to ensure we skip any markers that
3694 	 * might be at the tail of the lists due to arc_evict_state().
3695 	 */
3696 
3697 	for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
3698 	    data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
3699 		if (data_hdr->b_spa != 0)
3700 			break;
3701 	}
3702 
3703 	for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
3704 	    meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
3705 		if (meta_hdr->b_spa != 0)
3706 			break;
3707 	}
3708 
3709 	if (data_hdr == NULL && meta_hdr == NULL) {
3710 		type = ARC_BUFC_DATA;
3711 	} else if (data_hdr == NULL) {
3712 		ASSERT3P(meta_hdr, !=, NULL);
3713 		type = ARC_BUFC_METADATA;
3714 	} else if (meta_hdr == NULL) {
3715 		ASSERT3P(data_hdr, !=, NULL);
3716 		type = ARC_BUFC_DATA;
3717 	} else {
3718 		ASSERT3P(data_hdr, !=, NULL);
3719 		ASSERT3P(meta_hdr, !=, NULL);
3720 
3721 		/* The headers can't be on the sublist without an L1 header */
3722 		ASSERT(HDR_HAS_L1HDR(data_hdr));
3723 		ASSERT(HDR_HAS_L1HDR(meta_hdr));
3724 
3725 		if (data_hdr->b_l1hdr.b_arc_access <
3726 		    meta_hdr->b_l1hdr.b_arc_access) {
3727 			type = ARC_BUFC_DATA;
3728 		} else {
3729 			type = ARC_BUFC_METADATA;
3730 		}
3731 	}
3732 
3733 	multilist_sublist_unlock(meta_mls);
3734 	multilist_sublist_unlock(data_mls);
3735 
3736 	return (type);
3737 }
3738 
3739 /*
3740  * Evict buffers from the cache, such that arc_size is capped by arc_c.
3741  */
3742 static uint64_t
3743 arc_adjust(void)
3744 {
3745 	uint64_t total_evicted = 0;
3746 	uint64_t bytes;
3747 	int64_t target;
3748 	uint64_t asize = aggsum_value(&arc_size);
3749 	uint64_t ameta = aggsum_value(&arc_meta_used);
3750 
3751 	/*
3752 	 * If we're over arc_meta_limit, we want to correct that before
3753 	 * potentially evicting data buffers below.
3754 	 */
3755 	total_evicted += arc_adjust_meta(ameta);
3756 
3757 	/*
3758 	 * Adjust MRU size
3759 	 *
3760 	 * If we're over the target cache size, we want to evict enough
3761 	 * from the list to get back to our target size. We don't want
3762 	 * to evict too much from the MRU, such that it drops below
3763 	 * arc_p. So, if we're over our target cache size more than
3764 	 * the MRU is over arc_p, we'll evict enough to get back to
3765 	 * arc_p here, and then evict more from the MFU below.
3766 	 */
3767 	target = MIN((int64_t)(asize - arc_c),
3768 	    (int64_t)(refcount_count(&arc_anon->arcs_size) +
3769 	    refcount_count(&arc_mru->arcs_size) + ameta - arc_p));
3770 
3771 	/*
3772 	 * If we're below arc_meta_min, always prefer to evict data.
3773 	 * Otherwise, try to satisfy the requested number of bytes to
3774 	 * evict from the type which contains older buffers; in an
3775 	 * effort to keep newer buffers in the cache regardless of their
3776 	 * type. If we cannot satisfy the number of bytes from this
3777 	 * type, spill over into the next type.
3778 	 */
3779 	if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
3780 	    ameta > arc_meta_min) {
3781 		bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3782 		total_evicted += bytes;
3783 
3784 		/*
3785 		 * If we couldn't evict our target number of bytes from
3786 		 * metadata, we try to get the rest from data.
3787 		 */
3788 		target -= bytes;
3789 
3790 		total_evicted +=
3791 		    arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3792 	} else {
3793 		bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3794 		total_evicted += bytes;
3795 
3796 		/*
3797 		 * If we couldn't evict our target number of bytes from
3798 		 * data, we try to get the rest from metadata.
3799 		 */
3800 		target -= bytes;
3801 
3802 		total_evicted +=
3803 		    arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3804 	}
3805 
3806 	/*
3807 	 * Adjust MFU size
3808 	 *
3809 	 * Now that we've tried to evict enough from the MRU to get its
3810 	 * size back to arc_p, if we're still above the target cache
3811 	 * size, we evict the rest from the MFU.
3812 	 */
3813 	target = asize - arc_c;
3814 
3815 	if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
3816 	    ameta > arc_meta_min) {
3817 		bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3818 		total_evicted += bytes;
3819 
3820 		/*
3821 		 * If we couldn't evict our target number of bytes from
3822 		 * metadata, we try to get the rest from data.
3823 		 */
3824 		target -= bytes;
3825 
3826 		total_evicted +=
3827 		    arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3828 	} else {
3829 		bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3830 		total_evicted += bytes;
3831 
3832 		/*
3833 		 * If we couldn't evict our target number of bytes from
3834 		 * data, we try to get the rest from data.
3835 		 */
3836 		target -= bytes;
3837 
3838 		total_evicted +=
3839 		    arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3840 	}
3841 
3842 	/*
3843 	 * Adjust ghost lists
3844 	 *
3845 	 * In addition to the above, the ARC also defines target values
3846 	 * for the ghost lists. The sum of the mru list and mru ghost
3847 	 * list should never exceed the target size of the cache, and
3848 	 * the sum of the mru list, mfu list, mru ghost list, and mfu
3849 	 * ghost list should never exceed twice the target size of the
3850 	 * cache. The following logic enforces these limits on the ghost
3851 	 * caches, and evicts from them as needed.
3852 	 */
3853 	target = refcount_count(&arc_mru->arcs_size) +
3854 	    refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
3855 
3856 	bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
3857 	total_evicted += bytes;
3858 
3859 	target -= bytes;
3860 
3861 	total_evicted +=
3862 	    arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
3863 
3864 	/*
3865 	 * We assume the sum of the mru list and mfu list is less than
3866 	 * or equal to arc_c (we enforced this above), which means we
3867 	 * can use the simpler of the two equations below:
3868 	 *
3869 	 *	mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
3870 	 *		    mru ghost + mfu ghost <= arc_c
3871 	 */
3872 	target = refcount_count(&arc_mru_ghost->arcs_size) +
3873 	    refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
3874 
3875 	bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
3876 	total_evicted += bytes;
3877 
3878 	target -= bytes;
3879 
3880 	total_evicted +=
3881 	    arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
3882 
3883 	return (total_evicted);
3884 }
3885 
3886 void
3887 arc_flush(spa_t *spa, boolean_t retry)
3888 {
3889 	uint64_t guid = 0;
3890 
3891 	/*
3892 	 * If retry is B_TRUE, a spa must not be specified since we have
3893 	 * no good way to determine if all of a spa's buffers have been
3894 	 * evicted from an arc state.
3895 	 */
3896 	ASSERT(!retry || spa == 0);
3897 
3898 	if (spa != NULL)
3899 		guid = spa_load_guid(spa);
3900 
3901 	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
3902 	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
3903 
3904 	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
3905 	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
3906 
3907 	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
3908 	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
3909 
3910 	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
3911 	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
3912 }
3913 
3914 static void
3915 arc_reduce_target_size(int64_t to_free)
3916 {
3917 	uint64_t asize = aggsum_value(&arc_size);
3918 	if (arc_c > arc_c_min) {
3919 
3920 		if (arc_c > arc_c_min + to_free)
3921 			atomic_add_64(&arc_c, -to_free);
3922 		else
3923 			arc_c = arc_c_min;
3924 
3925 		atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
3926 		if (asize < arc_c)
3927 			arc_c = MAX(asize, arc_c_min);
3928 		if (arc_p > arc_c)
3929 			arc_p = (arc_c >> 1);
3930 		ASSERT(arc_c >= arc_c_min);
3931 		ASSERT((int64_t)arc_p >= 0);
3932 	}
3933 
3934 	if (asize > arc_c) {
3935 		/* See comment in arc_adjust_cb_check() on why lock+flag */
3936 		mutex_enter(&arc_adjust_lock);
3937 		arc_adjust_needed = B_TRUE;
3938 		mutex_exit(&arc_adjust_lock);
3939 		zthr_wakeup(arc_adjust_zthr);
3940 	}
3941 }
3942 
3943 typedef enum free_memory_reason_t {
3944 	FMR_UNKNOWN,
3945 	FMR_NEEDFREE,
3946 	FMR_LOTSFREE,
3947 	FMR_SWAPFS_MINFREE,
3948 	FMR_PAGES_PP_MAXIMUM,
3949 	FMR_HEAP_ARENA,
3950 	FMR_ZIO_ARENA,
3951 } free_memory_reason_t;
3952 
3953 int64_t last_free_memory;
3954 free_memory_reason_t last_free_reason;
3955 
3956 /*
3957  * Additional reserve of pages for pp_reserve.
3958  */
3959 int64_t arc_pages_pp_reserve = 64;
3960 
3961 /*
3962  * Additional reserve of pages for swapfs.
3963  */
3964 int64_t arc_swapfs_reserve = 64;
3965 
3966 /*
3967  * Return the amount of memory that can be consumed before reclaim will be
3968  * needed.  Positive if there is sufficient free memory, negative indicates
3969  * the amount of memory that needs to be freed up.
3970  */
3971 static int64_t
3972 arc_available_memory(void)
3973 {
3974 	int64_t lowest = INT64_MAX;
3975 	int64_t n;
3976 	free_memory_reason_t r = FMR_UNKNOWN;
3977 
3978 #ifdef _KERNEL
3979 	if (needfree > 0) {
3980 		n = PAGESIZE * (-needfree);
3981 		if (n < lowest) {
3982 			lowest = n;
3983 			r = FMR_NEEDFREE;
3984 		}
3985 	}
3986 
3987 	/*
3988 	 * check that we're out of range of the pageout scanner.  It starts to
3989 	 * schedule paging if freemem is less than lotsfree and needfree.
3990 	 * lotsfree is the high-water mark for pageout, and needfree is the
3991 	 * number of needed free pages.  We add extra pages here to make sure
3992 	 * the scanner doesn't start up while we're freeing memory.
3993 	 */
3994 	n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
3995 	if (n < lowest) {
3996 		lowest = n;
3997 		r = FMR_LOTSFREE;
3998 	}
3999 
4000 	/*
4001 	 * check to make sure that swapfs has enough space so that anon
4002 	 * reservations can still succeed. anon_resvmem() checks that the
4003 	 * availrmem is greater than swapfs_minfree, and the number of reserved
4004 	 * swap pages.  We also add a bit of extra here just to prevent
4005 	 * circumstances from getting really dire.
4006 	 */
4007 	n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
4008 	    desfree - arc_swapfs_reserve);
4009 	if (n < lowest) {
4010 		lowest = n;
4011 		r = FMR_SWAPFS_MINFREE;
4012 	}
4013 
4014 
4015 	/*
4016 	 * Check that we have enough availrmem that memory locking (e.g., via
4017 	 * mlock(3C) or memcntl(2)) can still succeed.  (pages_pp_maximum
4018 	 * stores the number of pages that cannot be locked; when availrmem
4019 	 * drops below pages_pp_maximum, page locking mechanisms such as
4020 	 * page_pp_lock() will fail.)
4021 	 */
4022 	n = PAGESIZE * (availrmem - pages_pp_maximum -
4023 	    arc_pages_pp_reserve);
4024 	if (n < lowest) {
4025 		lowest = n;
4026 		r = FMR_PAGES_PP_MAXIMUM;
4027 	}
4028 
4029 #if defined(__i386)
4030 	/*
4031 	 * If we're on an i386 platform, it's possible that we'll exhaust the
4032 	 * kernel heap space before we ever run out of available physical
4033 	 * memory.  Most checks of the size of the heap_area compare against
4034 	 * tune.t_minarmem, which is the minimum available real memory that we
4035 	 * can have in the system.  However, this is generally fixed at 25 pages
4036 	 * which is so low that it's useless.  In this comparison, we seek to
4037 	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
4038 	 * heap is allocated.  (Or, in the calculation, if less than 1/4th is
4039 	 * free)
4040 	 */
4041 	n = (int64_t)vmem_size(heap_arena, VMEM_FREE) -
4042 	    (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2);
4043 	if (n < lowest) {
4044 		lowest = n;
4045 		r = FMR_HEAP_ARENA;
4046 	}
4047 #endif
4048 
4049 	/*
4050 	 * If zio data pages are being allocated out of a separate heap segment,
4051 	 * then enforce that the size of available vmem for this arena remains
4052 	 * above about 1/4th (1/(2^arc_zio_arena_free_shift)) free.
4053 	 *
4054 	 * Note that reducing the arc_zio_arena_free_shift keeps more virtual
4055 	 * memory (in the zio_arena) free, which can avoid memory
4056 	 * fragmentation issues.
4057 	 */
4058 	if (zio_arena != NULL) {
4059 		n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
4060 		    (vmem_size(zio_arena, VMEM_ALLOC) >>
4061 		    arc_zio_arena_free_shift);
4062 		if (n < lowest) {
4063 			lowest = n;
4064 			r = FMR_ZIO_ARENA;
4065 		}
4066 	}
4067 #else
4068 	/* Every 100 calls, free a small amount */
4069 	if (spa_get_random(100) == 0)
4070 		lowest = -1024;
4071 #endif
4072 
4073 	last_free_memory = lowest;
4074 	last_free_reason = r;
4075 
4076 	return (lowest);
4077 }
4078 
4079 
4080 /*
4081  * Determine if the system is under memory pressure and is asking
4082  * to reclaim memory. A return value of B_TRUE indicates that the system
4083  * is under memory pressure and that the arc should adjust accordingly.
4084  */
4085 static boolean_t
4086 arc_reclaim_needed(void)
4087 {
4088 	return (arc_available_memory() < 0);
4089 }
4090 
4091 static void
4092 arc_kmem_reap_soon(void)
4093 {
4094 	size_t			i;
4095 	kmem_cache_t		*prev_cache = NULL;
4096 	kmem_cache_t		*prev_data_cache = NULL;
4097 	extern kmem_cache_t	*zio_buf_cache[];
4098 	extern kmem_cache_t	*zio_data_buf_cache[];
4099 	extern kmem_cache_t	*range_seg_cache;
4100 	extern kmem_cache_t	*abd_chunk_cache;
4101 
4102 #ifdef _KERNEL
4103 	if (aggsum_compare(&arc_meta_used, arc_meta_limit) >= 0) {
4104 		/*
4105 		 * We are exceeding our meta-data cache limit.
4106 		 * Purge some DNLC entries to release holds on meta-data.
4107 		 */
4108 		dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
4109 	}
4110 #if defined(__i386)
4111 	/*
4112 	 * Reclaim unused memory from all kmem caches.
4113 	 */
4114 	kmem_reap();
4115 #endif
4116 #endif
4117 
4118 	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
4119 		if (zio_buf_cache[i] != prev_cache) {
4120 			prev_cache = zio_buf_cache[i];
4121 			kmem_cache_reap_soon(zio_buf_cache[i]);
4122 		}
4123 		if (zio_data_buf_cache[i] != prev_data_cache) {
4124 			prev_data_cache = zio_data_buf_cache[i];
4125 			kmem_cache_reap_soon(zio_data_buf_cache[i]);
4126 		}
4127 	}
4128 	kmem_cache_reap_soon(abd_chunk_cache);
4129 	kmem_cache_reap_soon(buf_cache);
4130 	kmem_cache_reap_soon(hdr_full_cache);
4131 	kmem_cache_reap_soon(hdr_l2only_cache);
4132 	kmem_cache_reap_soon(range_seg_cache);
4133 
4134 	if (zio_arena != NULL) {
4135 		/*
4136 		 * Ask the vmem arena to reclaim unused memory from its
4137 		 * quantum caches.
4138 		 */
4139 		vmem_qcache_reap(zio_arena);
4140 	}
4141 }
4142 
4143 /* ARGSUSED */
4144 static boolean_t
4145 arc_adjust_cb_check(void *arg, zthr_t *zthr)
4146 {
4147 	/*
4148 	 * This is necessary in order for the mdb ::arc dcmd to
4149 	 * show up to date information. Since the ::arc command
4150 	 * does not call the kstat's update function, without
4151 	 * this call, the command may show stale stats for the
4152 	 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
4153 	 * with this change, the data might be up to 1 second
4154 	 * out of date(the arc_adjust_zthr has a maximum sleep
4155 	 * time of 1 second); but that should suffice.  The
4156 	 * arc_state_t structures can be queried directly if more
4157 	 * accurate information is needed.
4158 	 */
4159 	if (arc_ksp != NULL)
4160 		arc_ksp->ks_update(arc_ksp, KSTAT_READ);
4161 
4162 	/*
4163 	 * We have to rely on arc_get_data_impl() to tell us when to adjust,
4164 	 * rather than checking if we are overflowing here, so that we are
4165 	 * sure to not leave arc_get_data_impl() waiting on
4166 	 * arc_adjust_waiters_cv.  If we have become "not overflowing" since
4167 	 * arc_get_data_impl() checked, we need to wake it up.  We could
4168 	 * broadcast the CV here, but arc_get_data_impl() may have not yet
4169 	 * gone to sleep.  We would need to use a mutex to ensure that this
4170 	 * function doesn't broadcast until arc_get_data_impl() has gone to
4171 	 * sleep (e.g. the arc_adjust_lock).  However, the lock ordering of
4172 	 * such a lock would necessarily be incorrect with respect to the
4173 	 * zthr_lock, which is held before this function is called, and is
4174 	 * held by arc_get_data_impl() when it calls zthr_wakeup().
4175 	 */
4176 	return (arc_adjust_needed);
4177 }
4178 
4179 /*
4180  * Keep arc_size under arc_c by running arc_adjust which evicts data
4181  * from the ARC.
4182  */
4183 /* ARGSUSED */
4184 static int
4185 arc_adjust_cb(void *arg, zthr_t *zthr)
4186 {
4187 	uint64_t evicted = 0;
4188 
4189 	/* Evict from cache */
4190 	evicted = arc_adjust();
4191 
4192 	/*
4193 	 * If evicted is zero, we couldn't evict anything
4194 	 * via arc_adjust(). This could be due to hash lock
4195 	 * collisions, but more likely due to the majority of
4196 	 * arc buffers being unevictable. Therefore, even if
4197 	 * arc_size is above arc_c, another pass is unlikely to
4198 	 * be helpful and could potentially cause us to enter an
4199 	 * infinite loop.  Additionally, zthr_iscancelled() is
4200 	 * checked here so that if the arc is shutting down, the
4201 	 * broadcast will wake any remaining arc adjust waiters.
4202 	 */
4203 	mutex_enter(&arc_adjust_lock);
4204 	arc_adjust_needed = !zthr_iscancelled(arc_adjust_zthr) &&
4205 	    evicted > 0 && aggsum_compare(&arc_size, arc_c) > 0;
4206 	if (!arc_adjust_needed) {
4207 		/*
4208 		 * We're either no longer overflowing, or we
4209 		 * can't evict anything more, so we should wake
4210 		 * up any waiters.
4211 		 */
4212 		cv_broadcast(&arc_adjust_waiters_cv);
4213 	}
4214 	mutex_exit(&arc_adjust_lock);
4215 
4216 	return (0);
4217 }
4218 
4219 /* ARGSUSED */
4220 static boolean_t
4221 arc_reap_cb_check(void *arg, zthr_t *zthr)
4222 {
4223 	int64_t free_memory = arc_available_memory();
4224 
4225 	/*
4226 	 * If a kmem reap is already active, don't schedule more.  We must
4227 	 * check for this because kmem_cache_reap_soon() won't actually
4228 	 * block on the cache being reaped (this is to prevent callers from
4229 	 * becoming implicitly blocked by a system-wide kmem reap -- which,
4230 	 * on a system with many, many full magazines, can take minutes).
4231 	 */
4232 	if (!kmem_cache_reap_active() &&
4233 	    free_memory < 0) {
4234 		arc_no_grow = B_TRUE;
4235 		arc_warm = B_TRUE;
4236 		/*
4237 		 * Wait at least zfs_grow_retry (default 60) seconds
4238 		 * before considering growing.
4239 		 */
4240 		arc_growtime = gethrtime() + SEC2NSEC(arc_grow_retry);
4241 		return (B_TRUE);
4242 	} else if (free_memory < arc_c >> arc_no_grow_shift) {
4243 		arc_no_grow = B_TRUE;
4244 	} else if (gethrtime() >= arc_growtime) {
4245 		arc_no_grow = B_FALSE;
4246 	}
4247 
4248 	return (B_FALSE);
4249 }
4250 
4251 /*
4252  * Keep enough free memory in the system by reaping the ARC's kmem
4253  * caches.  To cause more slabs to be reapable, we may reduce the
4254  * target size of the cache (arc_c), causing the arc_adjust_cb()
4255  * to free more buffers.
4256  */
4257 /* ARGSUSED */
4258 static int
4259 arc_reap_cb(void *arg, zthr_t *zthr)
4260 {
4261 	int64_t free_memory;
4262 
4263 	/*
4264 	 * Kick off asynchronous kmem_reap()'s of all our caches.
4265 	 */
4266 	arc_kmem_reap_soon();
4267 
4268 	/*
4269 	 * Wait at least arc_kmem_cache_reap_retry_ms between
4270 	 * arc_kmem_reap_soon() calls. Without this check it is possible to
4271 	 * end up in a situation where we spend lots of time reaping
4272 	 * caches, while we're near arc_c_min.  Waiting here also gives the
4273 	 * subsequent free memory check a chance of finding that the
4274 	 * asynchronous reap has already freed enough memory, and we don't
4275 	 * need to call arc_reduce_target_size().
4276 	 */
4277 	delay((hz * arc_kmem_cache_reap_retry_ms + 999) / 1000);
4278 
4279 	/*
4280 	 * Reduce the target size as needed to maintain the amount of free
4281 	 * memory in the system at a fraction of the arc_size (1/128th by
4282 	 * default).  If oversubscribed (free_memory < 0) then reduce the
4283 	 * target arc_size by the deficit amount plus the fractional
4284 	 * amount.  If free memory is positive but less then the fractional
4285 	 * amount, reduce by what is needed to hit the fractional amount.
4286 	 */
4287 	free_memory = arc_available_memory();
4288 
4289 	int64_t to_free =
4290 	    (arc_c >> arc_shrink_shift) - free_memory;
4291 	if (to_free > 0) {
4292 #ifdef _KERNEL
4293 		to_free = MAX(to_free, ptob(needfree));
4294 #endif
4295 		arc_reduce_target_size(to_free);
4296 	}
4297 
4298 	return (0);
4299 }
4300 
4301 /*
4302  * Adapt arc info given the number of bytes we are trying to add and
4303  * the state that we are comming from.  This function is only called
4304  * when we are adding new content to the cache.
4305  */
4306 static void
4307 arc_adapt(int bytes, arc_state_t *state)
4308 {
4309 	int mult;
4310 	uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
4311 	int64_t mrug_size = refcount_count(&arc_mru_ghost->arcs_size);
4312 	int64_t mfug_size = refcount_count(&arc_mfu_ghost->arcs_size);
4313 
4314 	if (state == arc_l2c_only)
4315 		return;
4316 
4317 	ASSERT(bytes > 0);
4318 	/*
4319 	 * Adapt the target size of the MRU list:
4320 	 *	- if we just hit in the MRU ghost list, then increase
4321 	 *	  the target size of the MRU list.
4322 	 *	- if we just hit in the MFU ghost list, then increase
4323 	 *	  the target size of the MFU list by decreasing the
4324 	 *	  target size of the MRU list.
4325 	 */
4326 	if (state == arc_mru_ghost) {
4327 		mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
4328 		mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
4329 
4330 		arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
4331 	} else if (state == arc_mfu_ghost) {
4332 		uint64_t delta;
4333 
4334 		mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
4335 		mult = MIN(mult, 10);
4336 
4337 		delta = MIN(bytes * mult, arc_p);
4338 		arc_p = MAX(arc_p_min, arc_p - delta);
4339 	}
4340 	ASSERT((int64_t)arc_p >= 0);
4341 
4342 	/*
4343 	 * Wake reap thread if we do not have any available memory
4344 	 */
4345 	if (arc_reclaim_needed()) {
4346 		zthr_wakeup(arc_reap_zthr);
4347 		return;
4348 	}
4349 
4350 
4351 	if (arc_no_grow)
4352 		return;
4353 
4354 	if (arc_c >= arc_c_max)
4355 		return;
4356 
4357 	/*
4358 	 * If we're within (2 * maxblocksize) bytes of the target
4359 	 * cache size, increment the target cache size
4360 	 */
4361 	if (aggsum_compare(&arc_size, arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) >
4362 	    0) {
4363 		atomic_add_64(&arc_c, (int64_t)bytes);
4364 		if (arc_c > arc_c_max)
4365 			arc_c = arc_c_max;
4366 		else if (state == arc_anon)
4367 			atomic_add_64(&arc_p, (int64_t)bytes);
4368 		if (arc_p > arc_c)
4369 			arc_p = arc_c;
4370 	}
4371 	ASSERT((int64_t)arc_p >= 0);
4372 }
4373 
4374 /*
4375  * Check if arc_size has grown past our upper threshold, determined by
4376  * zfs_arc_overflow_shift.
4377  */
4378 static boolean_t
4379 arc_is_overflowing(void)
4380 {
4381 	/* Always allow at least one block of overflow */
4382 	uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
4383 	    arc_c >> zfs_arc_overflow_shift);
4384 
4385 	/*
4386 	 * We just compare the lower bound here for performance reasons. Our
4387 	 * primary goals are to make sure that the arc never grows without
4388 	 * bound, and that it can reach its maximum size. This check
4389 	 * accomplishes both goals. The maximum amount we could run over by is
4390 	 * 2 * aggsum_borrow_multiplier * NUM_CPUS * the average size of a block
4391 	 * in the ARC. In practice, that's in the tens of MB, which is low
4392 	 * enough to be safe.
4393 	 */
4394 	return (aggsum_lower_bound(&arc_size) >= arc_c + overflow);
4395 }
4396 
4397 static abd_t *
4398 arc_get_data_abd(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4399 {
4400 	arc_buf_contents_t type = arc_buf_type(hdr);
4401 
4402 	arc_get_data_impl(hdr, size, tag);
4403 	if (type == ARC_BUFC_METADATA) {
4404 		return (abd_alloc(size, B_TRUE));
4405 	} else {
4406 		ASSERT(type == ARC_BUFC_DATA);
4407 		return (abd_alloc(size, B_FALSE));
4408 	}
4409 }
4410 
4411 static void *
4412 arc_get_data_buf(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4413 {
4414 	arc_buf_contents_t type = arc_buf_type(hdr);
4415 
4416 	arc_get_data_impl(hdr, size, tag);
4417 	if (type == ARC_BUFC_METADATA) {
4418 		return (zio_buf_alloc(size));
4419 	} else {
4420 		ASSERT(type == ARC_BUFC_DATA);
4421 		return (zio_data_buf_alloc(size));
4422 	}
4423 }
4424 
4425 /*
4426  * Allocate a block and return it to the caller. If we are hitting the
4427  * hard limit for the cache size, we must sleep, waiting for the eviction
4428  * thread to catch up. If we're past the target size but below the hard
4429  * limit, we'll only signal the reclaim thread and continue on.
4430  */
4431 static void
4432 arc_get_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4433 {
4434 	arc_state_t *state = hdr->b_l1hdr.b_state;
4435 	arc_buf_contents_t type = arc_buf_type(hdr);
4436 
4437 	arc_adapt(size, state);
4438 
4439 	/*
4440 	 * If arc_size is currently overflowing, and has grown past our
4441 	 * upper limit, we must be adding data faster than the evict
4442 	 * thread can evict. Thus, to ensure we don't compound the
4443 	 * problem by adding more data and forcing arc_size to grow even
4444 	 * further past it's target size, we halt and wait for the
4445 	 * eviction thread to catch up.
4446 	 *
4447 	 * It's also possible that the reclaim thread is unable to evict
4448 	 * enough buffers to get arc_size below the overflow limit (e.g.
4449 	 * due to buffers being un-evictable, or hash lock collisions).
4450 	 * In this case, we want to proceed regardless if we're
4451 	 * overflowing; thus we don't use a while loop here.
4452 	 */
4453 	if (arc_is_overflowing()) {
4454 		mutex_enter(&arc_adjust_lock);
4455 
4456 		/*
4457 		 * Now that we've acquired the lock, we may no longer be
4458 		 * over the overflow limit, lets check.
4459 		 *
4460 		 * We're ignoring the case of spurious wake ups. If that
4461 		 * were to happen, it'd let this thread consume an ARC
4462 		 * buffer before it should have (i.e. before we're under
4463 		 * the overflow limit and were signalled by the reclaim
4464 		 * thread). As long as that is a rare occurrence, it
4465 		 * shouldn't cause any harm.
4466 		 */
4467 		if (arc_is_overflowing()) {
4468 			arc_adjust_needed = B_TRUE;
4469 			zthr_wakeup(arc_adjust_zthr);
4470 			(void) cv_wait(&arc_adjust_waiters_cv,
4471 			    &arc_adjust_lock);
4472 		}
4473 		mutex_exit(&arc_adjust_lock);
4474 	}
4475 
4476 	VERIFY3U(hdr->b_type, ==, type);
4477 	if (type == ARC_BUFC_METADATA) {
4478 		arc_space_consume(size, ARC_SPACE_META);
4479 	} else {
4480 		arc_space_consume(size, ARC_SPACE_DATA);
4481 	}
4482 
4483 	/*
4484 	 * Update the state size.  Note that ghost states have a
4485 	 * "ghost size" and so don't need to be updated.
4486 	 */
4487 	if (!GHOST_STATE(state)) {
4488 
4489 		(void) refcount_add_many(&state->arcs_size, size, tag);
4490 
4491 		/*
4492 		 * If this is reached via arc_read, the link is
4493 		 * protected by the hash lock. If reached via
4494 		 * arc_buf_alloc, the header should not be accessed by
4495 		 * any other thread. And, if reached via arc_read_done,
4496 		 * the hash lock will protect it if it's found in the
4497 		 * hash table; otherwise no other thread should be
4498 		 * trying to [add|remove]_reference it.
4499 		 */
4500 		if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
4501 			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4502 			(void) refcount_add_many(&state->arcs_esize[type],
4503 			    size, tag);
4504 		}
4505 
4506 		/*
4507 		 * If we are growing the cache, and we are adding anonymous
4508 		 * data, and we have outgrown arc_p, update arc_p
4509 		 */
4510 		if (aggsum_compare(&arc_size, arc_c) < 0 &&
4511 		    hdr->b_l1hdr.b_state == arc_anon &&
4512 		    (refcount_count(&arc_anon->arcs_size) +
4513 		    refcount_count(&arc_mru->arcs_size) > arc_p))
4514 			arc_p = MIN(arc_c, arc_p + size);
4515 	}
4516 }
4517 
4518 static void
4519 arc_free_data_abd(arc_buf_hdr_t *hdr, abd_t *abd, uint64_t size, void *tag)
4520 {
4521 	arc_free_data_impl(hdr, size, tag);
4522 	abd_free(abd);
4523 }
4524 
4525 static void
4526 arc_free_data_buf(arc_buf_hdr_t *hdr, void *buf, uint64_t size, void *tag)
4527 {
4528 	arc_buf_contents_t type = arc_buf_type(hdr);
4529 
4530 	arc_free_data_impl(hdr, size, tag);
4531 	if (type == ARC_BUFC_METADATA) {
4532 		zio_buf_free(buf, size);
4533 	} else {
4534 		ASSERT(type == ARC_BUFC_DATA);
4535 		zio_data_buf_free(buf, size);
4536 	}
4537 }
4538 
4539 /*
4540  * Free the arc data buffer.
4541  */
4542 static void
4543 arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4544 {
4545 	arc_state_t *state = hdr->b_l1hdr.b_state;
4546 	arc_buf_contents_t type = arc_buf_type(hdr);
4547 
4548 	/* protected by hash lock, if in the hash table */
4549 	if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
4550 		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4551 		ASSERT(state != arc_anon && state != arc_l2c_only);
4552 
4553 		(void) refcount_remove_many(&state->arcs_esize[type],
4554 		    size, tag);
4555 	}
4556 	(void) refcount_remove_many(&state->arcs_size, size, tag);
4557 
4558 	VERIFY3U(hdr->b_type, ==, type);
4559 	if (type == ARC_BUFC_METADATA) {
4560 		arc_space_return(size, ARC_SPACE_META);
4561 	} else {
4562 		ASSERT(type == ARC_BUFC_DATA);
4563 		arc_space_return(size, ARC_SPACE_DATA);
4564 	}
4565 }
4566 
4567 /*
4568  * This routine is called whenever a buffer is accessed.
4569  * NOTE: the hash lock is dropped in this function.
4570  */
4571 static void
4572 arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
4573 {
4574 	clock_t now;
4575 
4576 	ASSERT(MUTEX_HELD(hash_lock));
4577 	ASSERT(HDR_HAS_L1HDR(hdr));
4578 
4579 	if (hdr->b_l1hdr.b_state == arc_anon) {
4580 		/*
4581 		 * This buffer is not in the cache, and does not
4582 		 * appear in our "ghost" list.  Add the new buffer
4583 		 * to the MRU state.
4584 		 */
4585 
4586 		ASSERT0(hdr->b_l1hdr.b_arc_access);
4587 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4588 		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
4589 		arc_change_state(arc_mru, hdr, hash_lock);
4590 
4591 	} else if (hdr->b_l1hdr.b_state == arc_mru) {
4592 		now = ddi_get_lbolt();
4593 
4594 		/*
4595 		 * If this buffer is here because of a prefetch, then either:
4596 		 * - clear the flag if this is a "referencing" read
4597 		 *   (any subsequent access will bump this into the MFU state).
4598 		 * or
4599 		 * - move the buffer to the head of the list if this is
4600 		 *   another prefetch (to make it less likely to be evicted).
4601 		 */
4602 		if (HDR_PREFETCH(hdr)) {
4603 			if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4604 				/* link protected by hash lock */
4605 				ASSERT(multilist_link_active(
4606 				    &hdr->b_l1hdr.b_arc_node));
4607 			} else {
4608 				arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
4609 				ARCSTAT_BUMP(arcstat_mru_hits);
4610 			}
4611 			hdr->b_l1hdr.b_arc_access = now;
4612 			return;
4613 		}
4614 
4615 		/*
4616 		 * This buffer has been "accessed" only once so far,
4617 		 * but it is still in the cache. Move it to the MFU
4618 		 * state.
4619 		 */
4620 		if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
4621 			/*
4622 			 * More than 125ms have passed since we
4623 			 * instantiated this buffer.  Move it to the
4624 			 * most frequently used state.
4625 			 */
4626 			hdr->b_l1hdr.b_arc_access = now;
4627 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4628 			arc_change_state(arc_mfu, hdr, hash_lock);
4629 		}
4630 		ARCSTAT_BUMP(arcstat_mru_hits);
4631 	} else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
4632 		arc_state_t	*new_state;
4633 		/*
4634 		 * This buffer has been "accessed" recently, but
4635 		 * was evicted from the cache.  Move it to the
4636 		 * MFU state.
4637 		 */
4638 
4639 		if (HDR_PREFETCH(hdr)) {
4640 			new_state = arc_mru;
4641 			if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0)
4642 				arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
4643 			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
4644 		} else {
4645 			new_state = arc_mfu;
4646 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4647 		}
4648 
4649 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4650 		arc_change_state(new_state, hdr, hash_lock);
4651 
4652 		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
4653 	} else if (hdr->b_l1hdr.b_state == arc_mfu) {
4654 		/*
4655 		 * This buffer has been accessed more than once and is
4656 		 * still in the cache.  Keep it in the MFU state.
4657 		 *
4658 		 * NOTE: an add_reference() that occurred when we did
4659 		 * the arc_read() will have kicked this off the list.
4660 		 * If it was a prefetch, we will explicitly move it to
4661 		 * the head of the list now.
4662 		 */
4663 		if ((HDR_PREFETCH(hdr)) != 0) {
4664 			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4665 			/* link protected by hash_lock */
4666 			ASSERT(multilist_link_active(&hdr->b_l1hdr.b_arc_node));
4667 		}
4668 		ARCSTAT_BUMP(arcstat_mfu_hits);
4669 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4670 	} else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
4671 		arc_state_t	*new_state = arc_mfu;
4672 		/*
4673 		 * This buffer has been accessed more than once but has
4674 		 * been evicted from the cache.  Move it back to the
4675 		 * MFU state.
4676 		 */
4677 
4678 		if (HDR_PREFETCH(hdr)) {
4679 			/*
4680 			 * This is a prefetch access...
4681 			 * move this block back to the MRU state.
4682 			 */
4683 			ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
4684 			new_state = arc_mru;
4685 		}
4686 
4687 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4688 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4689 		arc_change_state(new_state, hdr, hash_lock);
4690 
4691 		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
4692 	} else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
4693 		/*
4694 		 * This buffer is on the 2nd Level ARC.
4695 		 */
4696 
4697 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4698 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4699 		arc_change_state(arc_mfu, hdr, hash_lock);
4700 	} else {
4701 		ASSERT(!"invalid arc state");
4702 	}
4703 }
4704 
4705 /* a generic arc_done_func_t which you can use */
4706 /* ARGSUSED */
4707 void
4708 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
4709 {
4710 	if (zio == NULL || zio->io_error == 0)
4711 		bcopy(buf->b_data, arg, arc_buf_size(buf));
4712 	arc_buf_destroy(buf, arg);
4713 }
4714 
4715 /* a generic arc_done_func_t */
4716 void
4717 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
4718 {
4719 	arc_buf_t **bufp = arg;
4720 	if (buf == NULL) {
4721 		ASSERT(zio == NULL || zio->io_error != 0);
4722 		*bufp = NULL;
4723 	} else {
4724 		ASSERT(zio == NULL || zio->io_error == 0);
4725 		*bufp = buf;
4726 		ASSERT(buf->b_data != NULL);
4727 	}
4728 }
4729 
4730 static void
4731 arc_hdr_verify(arc_buf_hdr_t *hdr, blkptr_t *bp)
4732 {
4733 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
4734 		ASSERT3U(HDR_GET_PSIZE(hdr), ==, 0);
4735 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
4736 	} else {
4737 		if (HDR_COMPRESSION_ENABLED(hdr)) {
4738 			ASSERT3U(HDR_GET_COMPRESS(hdr), ==,
4739 			    BP_GET_COMPRESS(bp));
4740 		}
4741 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
4742 		ASSERT3U(HDR_GET_PSIZE(hdr), ==, BP_GET_PSIZE(bp));
4743 	}
4744 }
4745 
4746 static void
4747 arc_read_done(zio_t *zio)
4748 {
4749 	arc_buf_hdr_t	*hdr = zio->io_private;
4750 	kmutex_t	*hash_lock = NULL;
4751 	arc_callback_t	*callback_list;
4752 	arc_callback_t	*acb;
4753 	boolean_t	freeable = B_FALSE;
4754 	boolean_t	no_zio_error = (zio->io_error == 0);
4755 
4756 	/*
4757 	 * The hdr was inserted into hash-table and removed from lists
4758 	 * prior to starting I/O.  We should find this header, since
4759 	 * it's in the hash table, and it should be legit since it's
4760 	 * not possible to evict it during the I/O.  The only possible
4761 	 * reason for it not to be found is if we were freed during the
4762 	 * read.
4763 	 */
4764 	if (HDR_IN_HASH_TABLE(hdr)) {
4765 		ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
4766 		ASSERT3U(hdr->b_dva.dva_word[0], ==,
4767 		    BP_IDENTITY(zio->io_bp)->dva_word[0]);
4768 		ASSERT3U(hdr->b_dva.dva_word[1], ==,
4769 		    BP_IDENTITY(zio->io_bp)->dva_word[1]);
4770 
4771 		arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
4772 		    &hash_lock);
4773 
4774 		ASSERT((found == hdr &&
4775 		    DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
4776 		    (found == hdr && HDR_L2_READING(hdr)));
4777 		ASSERT3P(hash_lock, !=, NULL);
4778 	}
4779 
4780 	if (no_zio_error) {
4781 		/* byteswap if necessary */
4782 		if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
4783 			if (BP_GET_LEVEL(zio->io_bp) > 0) {
4784 				hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
4785 			} else {
4786 				hdr->b_l1hdr.b_byteswap =
4787 				    DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
4788 			}
4789 		} else {
4790 			hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
4791 		}
4792 	}
4793 
4794 	arc_hdr_clear_flags(hdr, ARC_FLAG_L2_EVICTED);
4795 	if (l2arc_noprefetch && HDR_PREFETCH(hdr))
4796 		arc_hdr_clear_flags(hdr, ARC_FLAG_L2CACHE);
4797 
4798 	callback_list = hdr->b_l1hdr.b_acb;
4799 	ASSERT3P(callback_list, !=, NULL);
4800 
4801 	if (hash_lock && no_zio_error && hdr->b_l1hdr.b_state == arc_anon) {
4802 		/*
4803 		 * Only call arc_access on anonymous buffers.  This is because
4804 		 * if we've issued an I/O for an evicted buffer, we've already
4805 		 * called arc_access (to prevent any simultaneous readers from
4806 		 * getting confused).
4807 		 */
4808 		arc_access(hdr, hash_lock);
4809 	}
4810 
4811 	/*
4812 	 * If a read request has a callback (i.e. acb_done is not NULL), then we
4813 	 * make a buf containing the data according to the parameters which were
4814 	 * passed in. The implementation of arc_buf_alloc_impl() ensures that we
4815 	 * aren't needlessly decompressing the data multiple times.
4816 	 */
4817 	int callback_cnt = 0;
4818 	for (acb = callback_list; acb != NULL; acb = acb->acb_next) {
4819 		if (!acb->acb_done)
4820 			continue;
4821 
4822 		/* This is a demand read since prefetches don't use callbacks */
4823 		callback_cnt++;
4824 
4825 		if (no_zio_error) {
4826 			int error = arc_buf_alloc_impl(hdr, acb->acb_private,
4827 			    acb->acb_compressed, zio->io_error == 0,
4828 			    &acb->acb_buf);
4829 			if (error != 0) {
4830 				/*
4831 				 * Decompression failed.  Set io_error
4832 				 * so that when we call acb_done (below),
4833 				 * we will indicate that the read failed.
4834 				 * Note that in the unusual case where one
4835 				 * callback is compressed and another
4836 				 * uncompressed, we will mark all of them
4837 				 * as failed, even though the uncompressed
4838 				 * one can't actually fail.  In this case,
4839 				 * the hdr will not be anonymous, because
4840 				 * if there are multiple callbacks, it's
4841 				 * because multiple threads found the same
4842 				 * arc buf in the hash table.
4843 				 */
4844 				zio->io_error = error;
4845 			}
4846 		}
4847 	}
4848 	/*
4849 	 * If there are multiple callbacks, we must have the hash lock,
4850 	 * because the only way for multiple threads to find this hdr is
4851 	 * in the hash table.  This ensures that if there are multiple
4852 	 * callbacks, the hdr is not anonymous.  If it were anonymous,
4853 	 * we couldn't use arc_buf_destroy() in the error case below.
4854 	 */
4855 	ASSERT(callback_cnt < 2 || hash_lock != NULL);
4856 
4857 	hdr->b_l1hdr.b_acb = NULL;
4858 	arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
4859 	if (callback_cnt == 0) {
4860 		ASSERT(HDR_PREFETCH(hdr));
4861 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
4862 		ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
4863 	}
4864 
4865 	ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
4866 	    callback_list != NULL);
4867 
4868 	if (no_zio_error) {
4869 		arc_hdr_verify(hdr, zio->io_bp);
4870 	} else {
4871 		arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
4872 		if (hdr->b_l1hdr.b_state != arc_anon)
4873 			arc_change_state(arc_anon, hdr, hash_lock);
4874 		if (HDR_IN_HASH_TABLE(hdr))
4875 			buf_hash_remove(hdr);
4876 		freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4877 	}
4878 
4879 	/*
4880 	 * Broadcast before we drop the hash_lock to avoid the possibility
4881 	 * that the hdr (and hence the cv) might be freed before we get to
4882 	 * the cv_broadcast().
4883 	 */
4884 	cv_broadcast(&hdr->b_l1hdr.b_cv);
4885 
4886 	if (hash_lock != NULL) {
4887 		mutex_exit(hash_lock);
4888 	} else {
4889 		/*
4890 		 * This block was freed while we waited for the read to
4891 		 * complete.  It has been removed from the hash table and
4892 		 * moved to the anonymous state (so that it won't show up
4893 		 * in the cache).
4894 		 */
4895 		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
4896 		freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4897 	}
4898 
4899 	/* execute each callback and free its structure */
4900 	while ((acb = callback_list) != NULL) {
4901 		if (acb->acb_done != NULL) {
4902 			if (zio->io_error != 0 && acb->acb_buf != NULL) {
4903 				/*
4904 				 * If arc_buf_alloc_impl() fails during
4905 				 * decompression, the buf will still be
4906 				 * allocated, and needs to be freed here.
4907 				 */
4908 				arc_buf_destroy(acb->acb_buf, acb->acb_private);
4909 				acb->acb_buf = NULL;
4910 			}
4911 			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
4912 		}
4913 
4914 		if (acb->acb_zio_dummy != NULL) {
4915 			acb->acb_zio_dummy->io_error = zio->io_error;
4916 			zio_nowait(acb->acb_zio_dummy);
4917 		}
4918 
4919 		callback_list = acb->acb_next;
4920 		kmem_free(acb, sizeof (arc_callback_t));
4921 	}
4922 
4923 	if (freeable)
4924 		arc_hdr_destroy(hdr);
4925 }
4926 
4927 /*
4928  * "Read" the block at the specified DVA (in bp) via the
4929  * cache.  If the block is found in the cache, invoke the provided
4930  * callback immediately and return.  Note that the `zio' parameter
4931  * in the callback will be NULL in this case, since no IO was
4932  * required.  If the block is not in the cache pass the read request
4933  * on to the spa with a substitute callback function, so that the
4934  * requested block will be added to the cache.
4935  *
4936  * If a read request arrives for a block that has a read in-progress,
4937  * either wait for the in-progress read to complete (and return the
4938  * results); or, if this is a read with a "done" func, add a record
4939  * to the read to invoke the "done" func when the read completes,
4940  * and return; or just return.
4941  *
4942  * arc_read_done() will invoke all the requested "done" functions
4943  * for readers of this block.
4944  */
4945 int
4946 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
4947     void *private, zio_priority_t priority, int zio_flags,
4948     arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
4949 {
4950 	arc_buf_hdr_t *hdr = NULL;
4951 	kmutex_t *hash_lock = NULL;
4952 	zio_t *rzio;
4953 	uint64_t guid = spa_load_guid(spa);
4954 	boolean_t compressed_read = (zio_flags & ZIO_FLAG_RAW) != 0;
4955 
4956 	ASSERT(!BP_IS_EMBEDDED(bp) ||
4957 	    BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
4958 
4959 top:
4960 	if (!BP_IS_EMBEDDED(bp)) {
4961 		/*
4962 		 * Embedded BP's have no DVA and require no I/O to "read".
4963 		 * Create an anonymous arc buf to back it.
4964 		 */
4965 		hdr = buf_hash_find(guid, bp, &hash_lock);
4966 	}
4967 
4968 	if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_pabd != NULL) {
4969 		arc_buf_t *buf = NULL;
4970 		*arc_flags |= ARC_FLAG_CACHED;
4971 
4972 		if (HDR_IO_IN_PROGRESS(hdr)) {
4973 
4974 			if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
4975 			    priority == ZIO_PRIORITY_SYNC_READ) {
4976 				/*
4977 				 * This sync read must wait for an
4978 				 * in-progress async read (e.g. a predictive
4979 				 * prefetch).  Async reads are queued
4980 				 * separately at the vdev_queue layer, so
4981 				 * this is a form of priority inversion.
4982 				 * Ideally, we would "inherit" the demand
4983 				 * i/o's priority by moving the i/o from
4984 				 * the async queue to the synchronous queue,
4985 				 * but there is currently no mechanism to do
4986 				 * so.  Track this so that we can evaluate
4987 				 * the magnitude of this potential performance
4988 				 * problem.
4989 				 *
4990 				 * Note that if the prefetch i/o is already
4991 				 * active (has been issued to the device),
4992 				 * the prefetch improved performance, because
4993 				 * we issued it sooner than we would have
4994 				 * without the prefetch.
4995 				 */
4996 				DTRACE_PROBE1(arc__sync__wait__for__async,
4997 				    arc_buf_hdr_t *, hdr);
4998 				ARCSTAT_BUMP(arcstat_sync_wait_for_async);
4999 			}
5000 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5001 				arc_hdr_clear_flags(hdr,
5002 				    ARC_FLAG_PREDICTIVE_PREFETCH);
5003 			}
5004 
5005 			if (*arc_flags & ARC_FLAG_WAIT) {
5006 				cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
5007 				mutex_exit(hash_lock);
5008 				goto top;
5009 			}
5010 			ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
5011 
5012 			if (done) {
5013 				arc_callback_t *acb = NULL;
5014 
5015 				acb = kmem_zalloc(sizeof (arc_callback_t),
5016 				    KM_SLEEP);
5017 				acb->acb_done = done;
5018 				acb->acb_private = private;
5019 				acb->acb_compressed = compressed_read;
5020 				if (pio != NULL)
5021 					acb->acb_zio_dummy = zio_null(pio,
5022 					    spa, NULL, NULL, NULL, zio_flags);
5023 
5024 				ASSERT3P(acb->acb_done, !=, NULL);
5025 				acb->acb_next = hdr->b_l1hdr.b_acb;
5026 				hdr->b_l1hdr.b_acb = acb;
5027 				mutex_exit(hash_lock);
5028 				return (0);
5029 			}
5030 			mutex_exit(hash_lock);
5031 			return (0);
5032 		}
5033 
5034 		ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
5035 		    hdr->b_l1hdr.b_state == arc_mfu);
5036 
5037 		if (done) {
5038 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5039 				/*
5040 				 * This is a demand read which does not have to
5041 				 * wait for i/o because we did a predictive
5042 				 * prefetch i/o for it, which has completed.
5043 				 */
5044 				DTRACE_PROBE1(
5045 				    arc__demand__hit__predictive__prefetch,
5046 				    arc_buf_hdr_t *, hdr);
5047 				ARCSTAT_BUMP(
5048 				    arcstat_demand_hit_predictive_prefetch);
5049 				arc_hdr_clear_flags(hdr,
5050 				    ARC_FLAG_PREDICTIVE_PREFETCH);
5051 			}
5052 			ASSERT(!BP_IS_EMBEDDED(bp) || !BP_IS_HOLE(bp));
5053 
5054 			/* Get a buf with the desired data in it. */
5055 			VERIFY0(arc_buf_alloc_impl(hdr, private,
5056 			    compressed_read, B_TRUE, &buf));
5057 		} else if (*arc_flags & ARC_FLAG_PREFETCH &&
5058 		    refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
5059 			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5060 		}
5061 		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
5062 		arc_access(hdr, hash_lock);
5063 		if (*arc_flags & ARC_FLAG_L2CACHE)
5064 			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5065 		mutex_exit(hash_lock);
5066 		ARCSTAT_BUMP(arcstat_hits);
5067 		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5068 		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
5069 		    data, metadata, hits);
5070 
5071 		if (done)
5072 			done(NULL, buf, private);
5073 	} else {
5074 		uint64_t lsize = BP_GET_LSIZE(bp);
5075 		uint64_t psize = BP_GET_PSIZE(bp);
5076 		arc_callback_t *acb;
5077 		vdev_t *vd = NULL;
5078 		uint64_t addr = 0;
5079 		boolean_t devw = B_FALSE;
5080 		uint64_t size;
5081 
5082 		if (hdr == NULL) {
5083 			/* this block is not in the cache */
5084 			arc_buf_hdr_t *exists = NULL;
5085 			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
5086 			hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
5087 			    BP_GET_COMPRESS(bp), type);
5088 
5089 			if (!BP_IS_EMBEDDED(bp)) {
5090 				hdr->b_dva = *BP_IDENTITY(bp);
5091 				hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
5092 				exists = buf_hash_insert(hdr, &hash_lock);
5093 			}
5094 			if (exists != NULL) {
5095 				/* somebody beat us to the hash insert */
5096 				mutex_exit(hash_lock);
5097 				buf_discard_identity(hdr);
5098 				arc_hdr_destroy(hdr);
5099 				goto top; /* restart the IO request */
5100 			}
5101 		} else {
5102 			/*
5103 			 * This block is in the ghost cache. If it was L2-only
5104 			 * (and thus didn't have an L1 hdr), we realloc the
5105 			 * header to add an L1 hdr.
5106 			 */
5107 			if (!HDR_HAS_L1HDR(hdr)) {
5108 				hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
5109 				    hdr_full_cache);
5110 			}
5111 			ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
5112 			ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
5113 			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5114 			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5115 			ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
5116 			ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
5117 
5118 			/*
5119 			 * This is a delicate dance that we play here.
5120 			 * This hdr is in the ghost list so we access it
5121 			 * to move it out of the ghost list before we
5122 			 * initiate the read. If it's a prefetch then
5123 			 * it won't have a callback so we'll remove the
5124 			 * reference that arc_buf_alloc_impl() created. We
5125 			 * do this after we've called arc_access() to
5126 			 * avoid hitting an assert in remove_reference().
5127 			 */
5128 			arc_access(hdr, hash_lock);
5129 			arc_hdr_alloc_pabd(hdr);
5130 		}
5131 		ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
5132 		size = arc_hdr_size(hdr);
5133 
5134 		/*
5135 		 * If compression is enabled on the hdr, then will do
5136 		 * RAW I/O and will store the compressed data in the hdr's
5137 		 * data block. Otherwise, the hdr's data block will contain
5138 		 * the uncompressed data.
5139 		 */
5140 		if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
5141 			zio_flags |= ZIO_FLAG_RAW;
5142 		}
5143 
5144 		if (*arc_flags & ARC_FLAG_PREFETCH)
5145 			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5146 		if (*arc_flags & ARC_FLAG_L2CACHE)
5147 			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5148 		if (BP_GET_LEVEL(bp) > 0)
5149 			arc_hdr_set_flags(hdr, ARC_FLAG_INDIRECT);
5150 		if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
5151 			arc_hdr_set_flags(hdr, ARC_FLAG_PREDICTIVE_PREFETCH);
5152 		ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
5153 
5154 		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
5155 		acb->acb_done = done;
5156 		acb->acb_private = private;
5157 		acb->acb_compressed = compressed_read;
5158 
5159 		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5160 		hdr->b_l1hdr.b_acb = acb;
5161 		arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5162 
5163 		if (HDR_HAS_L2HDR(hdr) &&
5164 		    (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
5165 			devw = hdr->b_l2hdr.b_dev->l2ad_writing;
5166 			addr = hdr->b_l2hdr.b_daddr;
5167 			/*
5168 			 * Lock out L2ARC device removal.
5169 			 */
5170 			if (vdev_is_dead(vd) ||
5171 			    !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
5172 				vd = NULL;
5173 		}
5174 
5175 		if (priority == ZIO_PRIORITY_ASYNC_READ)
5176 			arc_hdr_set_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5177 		else
5178 			arc_hdr_clear_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5179 
5180 		if (hash_lock != NULL)
5181 			mutex_exit(hash_lock);
5182 
5183 		/*
5184 		 * At this point, we have a level 1 cache miss.  Try again in
5185 		 * L2ARC if possible.
5186 		 */
5187 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, lsize);
5188 
5189 		DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
5190 		    uint64_t, lsize, zbookmark_phys_t *, zb);
5191 		ARCSTAT_BUMP(arcstat_misses);
5192 		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5193 		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
5194 		    data, metadata, misses);
5195 
5196 		if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
5197 			/*
5198 			 * Read from the L2ARC if the following are true:
5199 			 * 1. The L2ARC vdev was previously cached.
5200 			 * 2. This buffer still has L2ARC metadata.
5201 			 * 3. This buffer isn't currently writing to the L2ARC.
5202 			 * 4. The L2ARC entry wasn't evicted, which may
5203 			 *    also have invalidated the vdev.
5204 			 * 5. This isn't prefetch and l2arc_noprefetch is set.
5205 			 */
5206 			if (HDR_HAS_L2HDR(hdr) &&
5207 			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
5208 			    !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
5209 				l2arc_read_callback_t *cb;
5210 				abd_t *abd;
5211 				uint64_t asize;
5212 
5213 				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
5214 				ARCSTAT_BUMP(arcstat_l2_hits);
5215 
5216 				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
5217 				    KM_SLEEP);
5218 				cb->l2rcb_hdr = hdr;
5219 				cb->l2rcb_bp = *bp;
5220 				cb->l2rcb_zb = *zb;
5221 				cb->l2rcb_flags = zio_flags;
5222 
5223 				asize = vdev_psize_to_asize(vd, size);
5224 				if (asize != size) {
5225 					abd = abd_alloc_for_io(asize,
5226 					    HDR_ISTYPE_METADATA(hdr));
5227 					cb->l2rcb_abd = abd;
5228 				} else {
5229 					abd = hdr->b_l1hdr.b_pabd;
5230 				}
5231 
5232 				ASSERT(addr >= VDEV_LABEL_START_SIZE &&
5233 				    addr + asize <= vd->vdev_psize -
5234 				    VDEV_LABEL_END_SIZE);
5235 
5236 				/*
5237 				 * l2arc read.  The SCL_L2ARC lock will be
5238 				 * released by l2arc_read_done().
5239 				 * Issue a null zio if the underlying buffer
5240 				 * was squashed to zero size by compression.
5241 				 */
5242 				ASSERT3U(HDR_GET_COMPRESS(hdr), !=,
5243 				    ZIO_COMPRESS_EMPTY);
5244 				rzio = zio_read_phys(pio, vd, addr,
5245 				    asize, abd,
5246 				    ZIO_CHECKSUM_OFF,
5247 				    l2arc_read_done, cb, priority,
5248 				    zio_flags | ZIO_FLAG_DONT_CACHE |
5249 				    ZIO_FLAG_CANFAIL |
5250 				    ZIO_FLAG_DONT_PROPAGATE |
5251 				    ZIO_FLAG_DONT_RETRY, B_FALSE);
5252 				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
5253 				    zio_t *, rzio);
5254 				ARCSTAT_INCR(arcstat_l2_read_bytes, size);
5255 
5256 				if (*arc_flags & ARC_FLAG_NOWAIT) {
5257 					zio_nowait(rzio);
5258 					return (0);
5259 				}
5260 
5261 				ASSERT(*arc_flags & ARC_FLAG_WAIT);
5262 				if (zio_wait(rzio) == 0)
5263 					return (0);
5264 
5265 				/* l2arc read error; goto zio_read() */
5266 			} else {
5267 				DTRACE_PROBE1(l2arc__miss,
5268 				    arc_buf_hdr_t *, hdr);
5269 				ARCSTAT_BUMP(arcstat_l2_misses);
5270 				if (HDR_L2_WRITING(hdr))
5271 					ARCSTAT_BUMP(arcstat_l2_rw_clash);
5272 				spa_config_exit(spa, SCL_L2ARC, vd);
5273 			}
5274 		} else {
5275 			if (vd != NULL)
5276 				spa_config_exit(spa, SCL_L2ARC, vd);
5277 			if (l2arc_ndev != 0) {
5278 				DTRACE_PROBE1(l2arc__miss,
5279 				    arc_buf_hdr_t *, hdr);
5280 				ARCSTAT_BUMP(arcstat_l2_misses);
5281 			}
5282 		}
5283 
5284 		rzio = zio_read(pio, spa, bp, hdr->b_l1hdr.b_pabd, size,
5285 		    arc_read_done, hdr, priority, zio_flags, zb);
5286 
5287 		if (*arc_flags & ARC_FLAG_WAIT)
5288 			return (zio_wait(rzio));
5289 
5290 		ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
5291 		zio_nowait(rzio);
5292 	}
5293 	return (0);
5294 }
5295 
5296 /*
5297  * Notify the arc that a block was freed, and thus will never be used again.
5298  */
5299 void
5300 arc_freed(spa_t *spa, const blkptr_t *bp)
5301 {
5302 	arc_buf_hdr_t *hdr;
5303 	kmutex_t *hash_lock;
5304 	uint64_t guid = spa_load_guid(spa);
5305 
5306 	ASSERT(!BP_IS_EMBEDDED(bp));
5307 
5308 	hdr = buf_hash_find(guid, bp, &hash_lock);
5309 	if (hdr == NULL)
5310 		return;
5311 
5312 	/*
5313 	 * We might be trying to free a block that is still doing I/O
5314 	 * (i.e. prefetch) or has a reference (i.e. a dedup-ed,
5315 	 * dmu_sync-ed block). If this block is being prefetched, then it
5316 	 * would still have the ARC_FLAG_IO_IN_PROGRESS flag set on the hdr
5317 	 * until the I/O completes. A block may also have a reference if it is
5318 	 * part of a dedup-ed, dmu_synced write. The dmu_sync() function would
5319 	 * have written the new block to its final resting place on disk but
5320 	 * without the dedup flag set. This would have left the hdr in the MRU
5321 	 * state and discoverable. When the txg finally syncs it detects that
5322 	 * the block was overridden in open context and issues an override I/O.
5323 	 * Since this is a dedup block, the override I/O will determine if the
5324 	 * block is already in the DDT. If so, then it will replace the io_bp
5325 	 * with the bp from the DDT and allow the I/O to finish. When the I/O
5326 	 * reaches the done callback, dbuf_write_override_done, it will
5327 	 * check to see if the io_bp and io_bp_override are identical.
5328 	 * If they are not, then it indicates that the bp was replaced with
5329 	 * the bp in the DDT and the override bp is freed. This allows
5330 	 * us to arrive here with a reference on a block that is being
5331 	 * freed. So if we have an I/O in progress, or a reference to
5332 	 * this hdr, then we don't destroy the hdr.
5333 	 */
5334 	if (!HDR_HAS_L1HDR(hdr) || (!HDR_IO_IN_PROGRESS(hdr) &&
5335 	    refcount_is_zero(&hdr->b_l1hdr.b_refcnt))) {
5336 		arc_change_state(arc_anon, hdr, hash_lock);
5337 		arc_hdr_destroy(hdr);
5338 		mutex_exit(hash_lock);
5339 	} else {
5340 		mutex_exit(hash_lock);
5341 	}
5342 
5343 }
5344 
5345 /*
5346  * Release this buffer from the cache, making it an anonymous buffer.  This
5347  * must be done after a read and prior to modifying the buffer contents.
5348  * If the buffer has more than one reference, we must make
5349  * a new hdr for the buffer.
5350  */
5351 void
5352 arc_release(arc_buf_t *buf, void *tag)
5353 {
5354 	arc_buf_hdr_t *hdr = buf->b_hdr;
5355 
5356 	/*
5357 	 * It would be nice to assert that if it's DMU metadata (level >
5358 	 * 0 || it's the dnode file), then it must be syncing context.
5359 	 * But we don't know that information at this level.
5360 	 */
5361 
5362 	mutex_enter(&buf->b_evict_lock);
5363 
5364 	ASSERT(HDR_HAS_L1HDR(hdr));
5365 
5366 	/*
5367 	 * We don't grab the hash lock prior to this check, because if
5368 	 * the buffer's header is in the arc_anon state, it won't be
5369 	 * linked into the hash table.
5370 	 */
5371 	if (hdr->b_l1hdr.b_state == arc_anon) {
5372 		mutex_exit(&buf->b_evict_lock);
5373 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5374 		ASSERT(!HDR_IN_HASH_TABLE(hdr));
5375 		ASSERT(!HDR_HAS_L2HDR(hdr));
5376 		ASSERT(HDR_EMPTY(hdr));
5377 
5378 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
5379 		ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
5380 		ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
5381 
5382 		hdr->b_l1hdr.b_arc_access = 0;
5383 
5384 		/*
5385 		 * If the buf is being overridden then it may already
5386 		 * have a hdr that is not empty.
5387 		 */
5388 		buf_discard_identity(hdr);
5389 		arc_buf_thaw(buf);
5390 
5391 		return;
5392 	}
5393 
5394 	kmutex_t *hash_lock = HDR_LOCK(hdr);
5395 	mutex_enter(hash_lock);
5396 
5397 	/*
5398 	 * This assignment is only valid as long as the hash_lock is
5399 	 * held, we must be careful not to reference state or the
5400 	 * b_state field after dropping the lock.
5401 	 */
5402 	arc_state_t *state = hdr->b_l1hdr.b_state;
5403 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
5404 	ASSERT3P(state, !=, arc_anon);
5405 
5406 	/* this buffer is not on any list */
5407 	ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), >, 0);
5408 
5409 	if (HDR_HAS_L2HDR(hdr)) {
5410 		mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
5411 
5412 		/*
5413 		 * We have to recheck this conditional again now that
5414 		 * we're holding the l2ad_mtx to prevent a race with
5415 		 * another thread which might be concurrently calling
5416 		 * l2arc_evict(). In that case, l2arc_evict() might have
5417 		 * destroyed the header's L2 portion as we were waiting
5418 		 * to acquire the l2ad_mtx.
5419 		 */
5420 		if (HDR_HAS_L2HDR(hdr))
5421 			arc_hdr_l2hdr_destroy(hdr);
5422 
5423 		mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
5424 	}
5425 
5426 	/*
5427 	 * Do we have more than one buf?
5428 	 */
5429 	if (hdr->b_l1hdr.b_bufcnt > 1) {
5430 		arc_buf_hdr_t *nhdr;
5431 		uint64_t spa = hdr->b_spa;
5432 		uint64_t psize = HDR_GET_PSIZE(hdr);
5433 		uint64_t lsize = HDR_GET_LSIZE(hdr);
5434 		enum zio_compress compress = HDR_GET_COMPRESS(hdr);
5435 		arc_buf_contents_t type = arc_buf_type(hdr);
5436 		VERIFY3U(hdr->b_type, ==, type);
5437 
5438 		ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
5439 		(void) remove_reference(hdr, hash_lock, tag);
5440 
5441 		if (arc_buf_is_shared(buf) && !ARC_BUF_COMPRESSED(buf)) {
5442 			ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
5443 			ASSERT(ARC_BUF_LAST(buf));
5444 		}
5445 
5446 		/*
5447 		 * Pull the data off of this hdr and attach it to
5448 		 * a new anonymous hdr. Also find the last buffer
5449 		 * in the hdr's buffer list.
5450 		 */
5451 		arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
5452 		ASSERT3P(lastbuf, !=, NULL);
5453 
5454 		/*
5455 		 * If the current arc_buf_t and the hdr are sharing their data
5456 		 * buffer, then we must stop sharing that block.
5457 		 */
5458 		if (arc_buf_is_shared(buf)) {
5459 			VERIFY(!arc_buf_is_shared(lastbuf));
5460 
5461 			/*
5462 			 * First, sever the block sharing relationship between
5463 			 * buf and the arc_buf_hdr_t.
5464 			 */
5465 			arc_unshare_buf(hdr, buf);
5466 
5467 			/*
5468 			 * Now we need to recreate the hdr's b_pabd. Since we
5469 			 * have lastbuf handy, we try to share with it, but if
5470 			 * we can't then we allocate a new b_pabd and copy the
5471 			 * data from buf into it.
5472 			 */
5473 			if (arc_can_share(hdr, lastbuf)) {
5474 				arc_share_buf(hdr, lastbuf);
5475 			} else {
5476 				arc_hdr_alloc_pabd(hdr);
5477 				abd_copy_from_buf(hdr->b_l1hdr.b_pabd,
5478 				    buf->b_data, psize);
5479 			}
5480 			VERIFY3P(lastbuf->b_data, !=, NULL);
5481 		} else if (HDR_SHARED_DATA(hdr)) {
5482 			/*
5483 			 * Uncompressed shared buffers are always at the end
5484 			 * of the list. Compressed buffers don't have the
5485 			 * same requirements. This makes it hard to
5486 			 * simply assert that the lastbuf is shared so
5487 			 * we rely on the hdr's compression flags to determine
5488 			 * if we have a compressed, shared buffer.
5489 			 */
5490 			ASSERT(arc_buf_is_shared(lastbuf) ||
5491 			    HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
5492 			ASSERT(!ARC_BUF_SHARED(buf));
5493 		}
5494 		ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
5495 		ASSERT3P(state, !=, arc_l2c_only);
5496 
5497 		(void) refcount_remove_many(&state->arcs_size,
5498 		    arc_buf_size(buf), buf);
5499 
5500 		if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
5501 			ASSERT3P(state, !=, arc_l2c_only);
5502 			(void) refcount_remove_many(&state->arcs_esize[type],
5503 			    arc_buf_size(buf), buf);
5504 		}
5505 
5506 		hdr->b_l1hdr.b_bufcnt -= 1;
5507 		arc_cksum_verify(buf);
5508 		arc_buf_unwatch(buf);
5509 
5510 		mutex_exit(hash_lock);
5511 
5512 		/*
5513 		 * Allocate a new hdr. The new hdr will contain a b_pabd
5514 		 * buffer which will be freed in arc_write().
5515 		 */
5516 		nhdr = arc_hdr_alloc(spa, psize, lsize, compress, type);
5517 		ASSERT3P(nhdr->b_l1hdr.b_buf, ==, NULL);
5518 		ASSERT0(nhdr->b_l1hdr.b_bufcnt);
5519 		ASSERT0(refcount_count(&nhdr->b_l1hdr.b_refcnt));
5520 		VERIFY3U(nhdr->b_type, ==, type);
5521 		ASSERT(!HDR_SHARED_DATA(nhdr));
5522 
5523 		nhdr->b_l1hdr.b_buf = buf;
5524 		nhdr->b_l1hdr.b_bufcnt = 1;
5525 		(void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
5526 		buf->b_hdr = nhdr;
5527 
5528 		mutex_exit(&buf->b_evict_lock);
5529 		(void) refcount_add_many(&arc_anon->arcs_size,
5530 		    arc_buf_size(buf), buf);
5531 	} else {
5532 		mutex_exit(&buf->b_evict_lock);
5533 		ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
5534 		/* protected by hash lock, or hdr is on arc_anon */
5535 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
5536 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5537 		arc_change_state(arc_anon, hdr, hash_lock);
5538 		hdr->b_l1hdr.b_arc_access = 0;
5539 		mutex_exit(hash_lock);
5540 
5541 		buf_discard_identity(hdr);
5542 		arc_buf_thaw(buf);
5543 	}
5544 }
5545 
5546 int
5547 arc_released(arc_buf_t *buf)
5548 {
5549 	int released;
5550 
5551 	mutex_enter(&buf->b_evict_lock);
5552 	released = (buf->b_data != NULL &&
5553 	    buf->b_hdr->b_l1hdr.b_state == arc_anon);
5554 	mutex_exit(&buf->b_evict_lock);
5555 	return (released);
5556 }
5557 
5558 #ifdef ZFS_DEBUG
5559 int
5560 arc_referenced(arc_buf_t *buf)
5561 {
5562 	int referenced;
5563 
5564 	mutex_enter(&buf->b_evict_lock);
5565 	referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
5566 	mutex_exit(&buf->b_evict_lock);
5567 	return (referenced);
5568 }
5569 #endif
5570 
5571 static void
5572 arc_write_ready(zio_t *zio)
5573 {
5574 	arc_write_callback_t *callback = zio->io_private;
5575 	arc_buf_t *buf = callback->awcb_buf;
5576 	arc_buf_hdr_t *hdr = buf->b_hdr;
5577 	uint64_t psize = BP_IS_HOLE(zio->io_bp) ? 0 : BP_GET_PSIZE(zio->io_bp);
5578 
5579 	ASSERT(HDR_HAS_L1HDR(hdr));
5580 	ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
5581 	ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
5582 
5583 	/*
5584 	 * If we're reexecuting this zio because the pool suspended, then
5585 	 * cleanup any state that was previously set the first time the
5586 	 * callback was invoked.
5587 	 */
5588 	if (zio->io_flags & ZIO_FLAG_REEXECUTED) {
5589 		arc_cksum_free(hdr);
5590 		arc_buf_unwatch(buf);
5591 		if (hdr->b_l1hdr.b_pabd != NULL) {
5592 			if (arc_buf_is_shared(buf)) {
5593 				arc_unshare_buf(hdr, buf);
5594 			} else {
5595 				arc_hdr_free_pabd(hdr);
5596 			}
5597 		}
5598 	}
5599 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
5600 	ASSERT(!HDR_SHARED_DATA(hdr));
5601 	ASSERT(!arc_buf_is_shared(buf));
5602 
5603 	callback->awcb_ready(zio, buf, callback->awcb_private);
5604 
5605 	if (HDR_IO_IN_PROGRESS(hdr))
5606 		ASSERT(zio->io_flags & ZIO_FLAG_REEXECUTED);
5607 
5608 	arc_cksum_compute(buf);
5609 	arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5610 
5611 	enum zio_compress compress;
5612 	if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
5613 		compress = ZIO_COMPRESS_OFF;
5614 	} else {
5615 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(zio->io_bp));
5616 		compress = BP_GET_COMPRESS(zio->io_bp);
5617 	}
5618 	HDR_SET_PSIZE(hdr, psize);
5619 	arc_hdr_set_compress(hdr, compress);
5620 
5621 
5622 	/*
5623 	 * Fill the hdr with data. If the hdr is compressed, the data we want
5624 	 * is available from the zio, otherwise we can take it from the buf.
5625 	 *
5626 	 * We might be able to share the buf's data with the hdr here. However,
5627 	 * doing so would cause the ARC to be full of linear ABDs if we write a
5628 	 * lot of shareable data. As a compromise, we check whether scattered
5629 	 * ABDs are allowed, and assume that if they are then the user wants
5630 	 * the ARC to be primarily filled with them regardless of the data being
5631 	 * written. Therefore, if they're allowed then we allocate one and copy
5632 	 * the data into it; otherwise, we share the data directly if we can.
5633 	 */
5634 	if (zfs_abd_scatter_enabled || !arc_can_share(hdr, buf)) {
5635 		arc_hdr_alloc_pabd(hdr);
5636 
5637 		/*
5638 		 * Ideally, we would always copy the io_abd into b_pabd, but the
5639 		 * user may have disabled compressed ARC, thus we must check the
5640 		 * hdr's compression setting rather than the io_bp's.
5641 		 */
5642 		if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
5643 			ASSERT3U(BP_GET_COMPRESS(zio->io_bp), !=,
5644 			    ZIO_COMPRESS_OFF);
5645 			ASSERT3U(psize, >, 0);
5646 
5647 			abd_copy(hdr->b_l1hdr.b_pabd, zio->io_abd, psize);
5648 		} else {
5649 			ASSERT3U(zio->io_orig_size, ==, arc_hdr_size(hdr));
5650 
5651 			abd_copy_from_buf(hdr->b_l1hdr.b_pabd, buf->b_data,
5652 			    arc_buf_size(buf));
5653 		}
5654 	} else {
5655 		ASSERT3P(buf->b_data, ==, abd_to_buf(zio->io_orig_abd));
5656 		ASSERT3U(zio->io_orig_size, ==, arc_buf_size(buf));
5657 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
5658 
5659 		arc_share_buf(hdr, buf);
5660 	}
5661 
5662 	arc_hdr_verify(hdr, zio->io_bp);
5663 }
5664 
5665 static void
5666 arc_write_children_ready(zio_t *zio)
5667 {
5668 	arc_write_callback_t *callback = zio->io_private;
5669 	arc_buf_t *buf = callback->awcb_buf;
5670 
5671 	callback->awcb_children_ready(zio, buf, callback->awcb_private);
5672 }
5673 
5674 /*
5675  * The SPA calls this callback for each physical write that happens on behalf
5676  * of a logical write.  See the comment in dbuf_write_physdone() for details.
5677  */
5678 static void
5679 arc_write_physdone(zio_t *zio)
5680 {
5681 	arc_write_callback_t *cb = zio->io_private;
5682 	if (cb->awcb_physdone != NULL)
5683 		cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
5684 }
5685 
5686 static void
5687 arc_write_done(zio_t *zio)
5688 {
5689 	arc_write_callback_t *callback = zio->io_private;
5690 	arc_buf_t *buf = callback->awcb_buf;
5691 	arc_buf_hdr_t *hdr = buf->b_hdr;
5692 
5693 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5694 
5695 	if (zio->io_error == 0) {
5696 		arc_hdr_verify(hdr, zio->io_bp);
5697 
5698 		if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
5699 			buf_discard_identity(hdr);
5700 		} else {
5701 			hdr->b_dva = *BP_IDENTITY(zio->io_bp);
5702 			hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
5703 		}
5704 	} else {
5705 		ASSERT(HDR_EMPTY(hdr));
5706 	}
5707 
5708 	/*
5709 	 * If the block to be written was all-zero or compressed enough to be
5710 	 * embedded in the BP, no write was performed so there will be no
5711 	 * dva/birth/checksum.  The buffer must therefore remain anonymous
5712 	 * (and uncached).
5713 	 */
5714 	if (!HDR_EMPTY(hdr)) {
5715 		arc_buf_hdr_t *exists;
5716 		kmutex_t *hash_lock;
5717 
5718 		ASSERT3U(zio->io_error, ==, 0);
5719 
5720 		arc_cksum_verify(buf);
5721 
5722 		exists = buf_hash_insert(hdr, &hash_lock);
5723 		if (exists != NULL) {
5724 			/*
5725 			 * This can only happen if we overwrite for
5726 			 * sync-to-convergence, because we remove
5727 			 * buffers from the hash table when we arc_free().
5728 			 */
5729 			if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
5730 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5731 					panic("bad overwrite, hdr=%p exists=%p",
5732 					    (void *)hdr, (void *)exists);
5733 				ASSERT(refcount_is_zero(
5734 				    &exists->b_l1hdr.b_refcnt));
5735 				arc_change_state(arc_anon, exists, hash_lock);
5736 				mutex_exit(hash_lock);
5737 				arc_hdr_destroy(exists);
5738 				exists = buf_hash_insert(hdr, &hash_lock);
5739 				ASSERT3P(exists, ==, NULL);
5740 			} else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
5741 				/* nopwrite */
5742 				ASSERT(zio->io_prop.zp_nopwrite);
5743 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5744 					panic("bad nopwrite, hdr=%p exists=%p",
5745 					    (void *)hdr, (void *)exists);
5746 			} else {
5747 				/* Dedup */
5748 				ASSERT(hdr->b_l1hdr.b_bufcnt == 1);
5749 				ASSERT(hdr->b_l1hdr.b_state == arc_anon);
5750 				ASSERT(BP_GET_DEDUP(zio->io_bp));
5751 				ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
5752 			}
5753 		}
5754 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5755 		/* if it's not anon, we are doing a scrub */
5756 		if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
5757 			arc_access(hdr, hash_lock);
5758 		mutex_exit(hash_lock);
5759 	} else {
5760 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5761 	}
5762 
5763 	ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5764 	callback->awcb_done(zio, buf, callback->awcb_private);
5765 
5766 	abd_put(zio->io_abd);
5767 	kmem_free(callback, sizeof (arc_write_callback_t));
5768 }
5769 
5770 zio_t *
5771 arc_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
5772     boolean_t l2arc, const zio_prop_t *zp, arc_done_func_t *ready,
5773     arc_done_func_t *children_ready, arc_done_func_t *physdone,
5774     arc_done_func_t *done, void *private, zio_priority_t priority,
5775     int zio_flags, const zbookmark_phys_t *zb)
5776 {
5777 	arc_buf_hdr_t *hdr = buf->b_hdr;
5778 	arc_write_callback_t *callback;
5779 	zio_t *zio;
5780 	zio_prop_t localprop = *zp;
5781 
5782 	ASSERT3P(ready, !=, NULL);
5783 	ASSERT3P(done, !=, NULL);
5784 	ASSERT(!HDR_IO_ERROR(hdr));
5785 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5786 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5787 	ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
5788 	if (l2arc)
5789 		arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5790 	if (ARC_BUF_COMPRESSED(buf)) {
5791 		/*
5792 		 * We're writing a pre-compressed buffer.  Make the
5793 		 * compression algorithm requested by the zio_prop_t match
5794 		 * the pre-compressed buffer's compression algorithm.
5795 		 */
5796 		localprop.zp_compress = HDR_GET_COMPRESS(hdr);
5797 
5798 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, arc_buf_size(buf));
5799 		zio_flags |= ZIO_FLAG_RAW;
5800 	}
5801 	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
5802 	callback->awcb_ready = ready;
5803 	callback->awcb_children_ready = children_ready;
5804 	callback->awcb_physdone = physdone;
5805 	callback->awcb_done = done;
5806 	callback->awcb_private = private;
5807 	callback->awcb_buf = buf;
5808 
5809 	/*
5810 	 * The hdr's b_pabd is now stale, free it now. A new data block
5811 	 * will be allocated when the zio pipeline calls arc_write_ready().
5812 	 */
5813 	if (hdr->b_l1hdr.b_pabd != NULL) {
5814 		/*
5815 		 * If the buf is currently sharing the data block with
5816 		 * the hdr then we need to break that relationship here.
5817 		 * The hdr will remain with a NULL data pointer and the
5818 		 * buf will take sole ownership of the block.
5819 		 */
5820 		if (arc_buf_is_shared(buf)) {
5821 			arc_unshare_buf(hdr, buf);
5822 		} else {
5823 			arc_hdr_free_pabd(hdr);
5824 		}
5825 		VERIFY3P(buf->b_data, !=, NULL);
5826 		arc_hdr_set_compress(hdr, ZIO_COMPRESS_OFF);
5827 	}
5828 	ASSERT(!arc_buf_is_shared(buf));
5829 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
5830 
5831 	zio = zio_write(pio, spa, txg, bp,
5832 	    abd_get_from_buf(buf->b_data, HDR_GET_LSIZE(hdr)),
5833 	    HDR_GET_LSIZE(hdr), arc_buf_size(buf), &localprop, arc_write_ready,
5834 	    (children_ready != NULL) ? arc_write_children_ready : NULL,
5835 	    arc_write_physdone, arc_write_done, callback,
5836 	    priority, zio_flags, zb);
5837 
5838 	return (zio);
5839 }
5840 
5841 static int
5842 arc_memory_throttle(uint64_t reserve, uint64_t txg)
5843 {
5844 #ifdef _KERNEL
5845 	uint64_t available_memory = ptob(freemem);
5846 	static uint64_t page_load = 0;
5847 	static uint64_t last_txg = 0;
5848 
5849 #if defined(__i386)
5850 	available_memory =
5851 	    MIN(available_memory, vmem_size(heap_arena, VMEM_FREE));
5852 #endif
5853 
5854 	if (freemem > physmem * arc_lotsfree_percent / 100)
5855 		return (0);
5856 
5857 	if (txg > last_txg) {
5858 		last_txg = txg;
5859 		page_load = 0;
5860 	}
5861 	/*
5862 	 * If we are in pageout, we know that memory is already tight,
5863 	 * the arc is already going to be evicting, so we just want to
5864 	 * continue to let page writes occur as quickly as possible.
5865 	 */
5866 	if (curproc == proc_pageout) {
5867 		if (page_load > MAX(ptob(minfree), available_memory) / 4)
5868 			return (SET_ERROR(ERESTART));
5869 		/* Note: reserve is inflated, so we deflate */
5870 		page_load += reserve / 8;
5871 		return (0);
5872 	} else if (page_load > 0 && arc_reclaim_needed()) {
5873 		/* memory is low, delay before restarting */
5874 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
5875 		return (SET_ERROR(EAGAIN));
5876 	}
5877 	page_load = 0;
5878 #endif
5879 	return (0);
5880 }
5881 
5882 void
5883 arc_tempreserve_clear(uint64_t reserve)
5884 {
5885 	atomic_add_64(&arc_tempreserve, -reserve);
5886 	ASSERT((int64_t)arc_tempreserve >= 0);
5887 }
5888 
5889 int
5890 arc_tempreserve_space(uint64_t reserve, uint64_t txg)
5891 {
5892 	int error;
5893 	uint64_t anon_size;
5894 
5895 	if (reserve > arc_c/4 && !arc_no_grow)
5896 		arc_c = MIN(arc_c_max, reserve * 4);
5897 	if (reserve > arc_c)
5898 		return (SET_ERROR(ENOMEM));
5899 
5900 	/*
5901 	 * Don't count loaned bufs as in flight dirty data to prevent long
5902 	 * network delays from blocking transactions that are ready to be
5903 	 * assigned to a txg.
5904 	 */
5905 
5906 	/* assert that it has not wrapped around */
5907 	ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
5908 
5909 	anon_size = MAX((int64_t)(refcount_count(&arc_anon->arcs_size) -
5910 	    arc_loaned_bytes), 0);
5911 
5912 	/*
5913 	 * Writes will, almost always, require additional memory allocations
5914 	 * in order to compress/encrypt/etc the data.  We therefore need to
5915 	 * make sure that there is sufficient available memory for this.
5916 	 */
5917 	error = arc_memory_throttle(reserve, txg);
5918 	if (error != 0)
5919 		return (error);
5920 
5921 	/*
5922 	 * Throttle writes when the amount of dirty data in the cache
5923 	 * gets too large.  We try to keep the cache less than half full
5924 	 * of dirty blocks so that our sync times don't grow too large.
5925 	 * Note: if two requests come in concurrently, we might let them
5926 	 * both succeed, when one of them should fail.  Not a huge deal.
5927 	 */
5928 
5929 	if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
5930 	    anon_size > arc_c / 4) {
5931 		uint64_t meta_esize =
5932 		    refcount_count(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
5933 		uint64_t data_esize =
5934 		    refcount_count(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
5935 		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
5936 		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
5937 		    arc_tempreserve >> 10, meta_esize >> 10,
5938 		    data_esize >> 10, reserve >> 10, arc_c >> 10);
5939 		return (SET_ERROR(ERESTART));
5940 	}
5941 	atomic_add_64(&arc_tempreserve, reserve);
5942 	return (0);
5943 }
5944 
5945 static void
5946 arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
5947     kstat_named_t *evict_data, kstat_named_t *evict_metadata)
5948 {
5949 	size->value.ui64 = refcount_count(&state->arcs_size);
5950 	evict_data->value.ui64 =
5951 	    refcount_count(&state->arcs_esize[ARC_BUFC_DATA]);
5952 	evict_metadata->value.ui64 =
5953 	    refcount_count(&state->arcs_esize[ARC_BUFC_METADATA]);
5954 }
5955 
5956 static int
5957 arc_kstat_update(kstat_t *ksp, int rw)
5958 {
5959 	arc_stats_t *as = ksp->ks_data;
5960 
5961 	if (rw == KSTAT_WRITE) {
5962 		return (EACCES);
5963 	} else {
5964 		arc_kstat_update_state(arc_anon,
5965 		    &as->arcstat_anon_size,
5966 		    &as->arcstat_anon_evictable_data,
5967 		    &as->arcstat_anon_evictable_metadata);
5968 		arc_kstat_update_state(arc_mru,
5969 		    &as->arcstat_mru_size,
5970 		    &as->arcstat_mru_evictable_data,
5971 		    &as->arcstat_mru_evictable_metadata);
5972 		arc_kstat_update_state(arc_mru_ghost,
5973 		    &as->arcstat_mru_ghost_size,
5974 		    &as->arcstat_mru_ghost_evictable_data,
5975 		    &as->arcstat_mru_ghost_evictable_metadata);
5976 		arc_kstat_update_state(arc_mfu,
5977 		    &as->arcstat_mfu_size,
5978 		    &as->arcstat_mfu_evictable_data,
5979 		    &as->arcstat_mfu_evictable_metadata);
5980 		arc_kstat_update_state(arc_mfu_ghost,
5981 		    &as->arcstat_mfu_ghost_size,
5982 		    &as->arcstat_mfu_ghost_evictable_data,
5983 		    &as->arcstat_mfu_ghost_evictable_metadata);
5984 
5985 		ARCSTAT(arcstat_size) = aggsum_value(&arc_size);
5986 		ARCSTAT(arcstat_meta_used) = aggsum_value(&arc_meta_used);
5987 		ARCSTAT(arcstat_data_size) = aggsum_value(&astat_data_size);
5988 		ARCSTAT(arcstat_metadata_size) =
5989 		    aggsum_value(&astat_metadata_size);
5990 		ARCSTAT(arcstat_hdr_size) = aggsum_value(&astat_hdr_size);
5991 		ARCSTAT(arcstat_other_size) = aggsum_value(&astat_other_size);
5992 		ARCSTAT(arcstat_l2_hdr_size) = aggsum_value(&astat_l2_hdr_size);
5993 	}
5994 
5995 	return (0);
5996 }
5997 
5998 /*
5999  * This function *must* return indices evenly distributed between all
6000  * sublists of the multilist. This is needed due to how the ARC eviction
6001  * code is laid out; arc_evict_state() assumes ARC buffers are evenly
6002  * distributed between all sublists and uses this assumption when
6003  * deciding which sublist to evict from and how much to evict from it.
6004  */
6005 unsigned int
6006 arc_state_multilist_index_func(multilist_t *ml, void *obj)
6007 {
6008 	arc_buf_hdr_t *hdr = obj;
6009 
6010 	/*
6011 	 * We rely on b_dva to generate evenly distributed index
6012 	 * numbers using buf_hash below. So, as an added precaution,
6013 	 * let's make sure we never add empty buffers to the arc lists.
6014 	 */
6015 	ASSERT(!HDR_EMPTY(hdr));
6016 
6017 	/*
6018 	 * The assumption here, is the hash value for a given
6019 	 * arc_buf_hdr_t will remain constant throughout it's lifetime
6020 	 * (i.e. it's b_spa, b_dva, and b_birth fields don't change).
6021 	 * Thus, we don't need to store the header's sublist index
6022 	 * on insertion, as this index can be recalculated on removal.
6023 	 *
6024 	 * Also, the low order bits of the hash value are thought to be
6025 	 * distributed evenly. Otherwise, in the case that the multilist
6026 	 * has a power of two number of sublists, each sublists' usage
6027 	 * would not be evenly distributed.
6028 	 */
6029 	return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
6030 	    multilist_get_num_sublists(ml));
6031 }
6032 
6033 static void
6034 arc_state_init(void)
6035 {
6036 	arc_anon = &ARC_anon;
6037 	arc_mru = &ARC_mru;
6038 	arc_mru_ghost = &ARC_mru_ghost;
6039 	arc_mfu = &ARC_mfu;
6040 	arc_mfu_ghost = &ARC_mfu_ghost;
6041 	arc_l2c_only = &ARC_l2c_only;
6042 
6043 	arc_mru->arcs_list[ARC_BUFC_METADATA] =
6044 	    multilist_create(sizeof (arc_buf_hdr_t),
6045 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6046 	    arc_state_multilist_index_func);
6047 	arc_mru->arcs_list[ARC_BUFC_DATA] =
6048 	    multilist_create(sizeof (arc_buf_hdr_t),
6049 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6050 	    arc_state_multilist_index_func);
6051 	arc_mru_ghost->arcs_list[ARC_BUFC_METADATA] =
6052 	    multilist_create(sizeof (arc_buf_hdr_t),
6053 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6054 	    arc_state_multilist_index_func);
6055 	arc_mru_ghost->arcs_list[ARC_BUFC_DATA] =
6056 	    multilist_create(sizeof (arc_buf_hdr_t),
6057 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6058 	    arc_state_multilist_index_func);
6059 	arc_mfu->arcs_list[ARC_BUFC_METADATA] =
6060 	    multilist_create(sizeof (arc_buf_hdr_t),
6061 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6062 	    arc_state_multilist_index_func);
6063 	arc_mfu->arcs_list[ARC_BUFC_DATA] =
6064 	    multilist_create(sizeof (arc_buf_hdr_t),
6065 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6066 	    arc_state_multilist_index_func);
6067 	arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA] =
6068 	    multilist_create(sizeof (arc_buf_hdr_t),
6069 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6070 	    arc_state_multilist_index_func);
6071 	arc_mfu_ghost->arcs_list[ARC_BUFC_DATA] =
6072 	    multilist_create(sizeof (arc_buf_hdr_t),
6073 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6074 	    arc_state_multilist_index_func);
6075 	arc_l2c_only->arcs_list[ARC_BUFC_METADATA] =
6076 	    multilist_create(sizeof (arc_buf_hdr_t),
6077 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6078 	    arc_state_multilist_index_func);
6079 	arc_l2c_only->arcs_list[ARC_BUFC_DATA] =
6080 	    multilist_create(sizeof (arc_buf_hdr_t),
6081 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6082 	    arc_state_multilist_index_func);
6083 
6084 	refcount_create(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6085 	refcount_create(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6086 	refcount_create(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
6087 	refcount_create(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
6088 	refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
6089 	refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
6090 	refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
6091 	refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
6092 	refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
6093 	refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
6094 	refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
6095 	refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
6096 
6097 	refcount_create(&arc_anon->arcs_size);
6098 	refcount_create(&arc_mru->arcs_size);
6099 	refcount_create(&arc_mru_ghost->arcs_size);
6100 	refcount_create(&arc_mfu->arcs_size);
6101 	refcount_create(&arc_mfu_ghost->arcs_size);
6102 	refcount_create(&arc_l2c_only->arcs_size);
6103 
6104 	aggsum_init(&arc_meta_used, 0);
6105 	aggsum_init(&arc_size, 0);
6106 	aggsum_init(&astat_data_size, 0);
6107 	aggsum_init(&astat_metadata_size, 0);
6108 	aggsum_init(&astat_hdr_size, 0);
6109 	aggsum_init(&astat_other_size, 0);
6110 	aggsum_init(&astat_l2_hdr_size, 0);
6111 }
6112 
6113 static void
6114 arc_state_fini(void)
6115 {
6116 	refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6117 	refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6118 	refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
6119 	refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
6120 	refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
6121 	refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
6122 	refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
6123 	refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
6124 	refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
6125 	refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
6126 	refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
6127 	refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
6128 
6129 	refcount_destroy(&arc_anon->arcs_size);
6130 	refcount_destroy(&arc_mru->arcs_size);
6131 	refcount_destroy(&arc_mru_ghost->arcs_size);
6132 	refcount_destroy(&arc_mfu->arcs_size);
6133 	refcount_destroy(&arc_mfu_ghost->arcs_size);
6134 	refcount_destroy(&arc_l2c_only->arcs_size);
6135 
6136 	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_METADATA]);
6137 	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
6138 	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_METADATA]);
6139 	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
6140 	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_DATA]);
6141 	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
6142 	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_DATA]);
6143 	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
6144 }
6145 
6146 uint64_t
6147 arc_max_bytes(void)
6148 {
6149 	return (arc_c_max);
6150 }
6151 
6152 void
6153 arc_init(void)
6154 {
6155 	/*
6156 	 * allmem is "all memory that we could possibly use".
6157 	 */
6158 #ifdef _KERNEL
6159 	uint64_t allmem = ptob(physmem - swapfs_minfree);
6160 #else
6161 	uint64_t allmem = (physmem * PAGESIZE) / 2;
6162 #endif
6163 	mutex_init(&arc_adjust_lock, NULL, MUTEX_DEFAULT, NULL);
6164 	cv_init(&arc_adjust_waiters_cv, NULL, CV_DEFAULT, NULL);
6165 
6166 	/* Convert seconds to clock ticks */
6167 	arc_min_prefetch_lifespan = 1 * hz;
6168 
6169 	/* set min cache to 1/32 of all memory, or 64MB, whichever is more */
6170 	arc_c_min = MAX(allmem / 32, 64 << 20);
6171 	/* set max to 3/4 of all memory, or all but 1GB, whichever is more */
6172 	if (allmem >= 1 << 30)
6173 		arc_c_max = allmem - (1 << 30);
6174 	else
6175 		arc_c_max = arc_c_min;
6176 	arc_c_max = MAX(allmem * 3 / 4, arc_c_max);
6177 
6178 	/*
6179 	 * In userland, there's only the memory pressure that we artificially
6180 	 * create (see arc_available_memory()).  Don't let arc_c get too
6181 	 * small, because it can cause transactions to be larger than
6182 	 * arc_c, causing arc_tempreserve_space() to fail.
6183 	 */
6184 #ifndef _KERNEL
6185 	arc_c_min = arc_c_max / 2;
6186 #endif
6187 
6188 	/*
6189 	 * Allow the tunables to override our calculations if they are
6190 	 * reasonable (ie. over 64MB)
6191 	 */
6192 	if (zfs_arc_max > 64 << 20 && zfs_arc_max < allmem) {
6193 		arc_c_max = zfs_arc_max;
6194 		arc_c_min = MIN(arc_c_min, arc_c_max);
6195 	}
6196 	if (zfs_arc_min > 64 << 20 && zfs_arc_min <= arc_c_max)
6197 		arc_c_min = zfs_arc_min;
6198 
6199 	arc_c = arc_c_max;
6200 	arc_p = (arc_c >> 1);
6201 
6202 	/* limit meta-data to 1/4 of the arc capacity */
6203 	arc_meta_limit = arc_c_max / 4;
6204 
6205 #ifdef _KERNEL
6206 	/*
6207 	 * Metadata is stored in the kernel's heap.  Don't let us
6208 	 * use more than half the heap for the ARC.
6209 	 */
6210 	arc_meta_limit = MIN(arc_meta_limit,
6211 	    vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 2);
6212 #endif
6213 
6214 	/* Allow the tunable to override if it is reasonable */
6215 	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
6216 		arc_meta_limit = zfs_arc_meta_limit;
6217 
6218 	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
6219 		arc_c_min = arc_meta_limit / 2;
6220 
6221 	if (zfs_arc_meta_min > 0) {
6222 		arc_meta_min = zfs_arc_meta_min;
6223 	} else {
6224 		arc_meta_min = arc_c_min / 2;
6225 	}
6226 
6227 	if (zfs_arc_grow_retry > 0)
6228 		arc_grow_retry = zfs_arc_grow_retry;
6229 
6230 	if (zfs_arc_shrink_shift > 0)
6231 		arc_shrink_shift = zfs_arc_shrink_shift;
6232 
6233 	/*
6234 	 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
6235 	 */
6236 	if (arc_no_grow_shift >= arc_shrink_shift)
6237 		arc_no_grow_shift = arc_shrink_shift - 1;
6238 
6239 	if (zfs_arc_p_min_shift > 0)
6240 		arc_p_min_shift = zfs_arc_p_min_shift;
6241 
6242 	/* if kmem_flags are set, lets try to use less memory */
6243 	if (kmem_debugging())
6244 		arc_c = arc_c / 2;
6245 	if (arc_c < arc_c_min)
6246 		arc_c = arc_c_min;
6247 
6248 	arc_state_init();
6249 
6250 	/*
6251 	 * The arc must be "uninitialized", so that hdr_recl() (which is
6252 	 * registered by buf_init()) will not access arc_reap_zthr before
6253 	 * it is created.
6254 	 */
6255 	ASSERT(!arc_initialized);
6256 	buf_init();
6257 
6258 	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
6259 	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
6260 
6261 	if (arc_ksp != NULL) {
6262 		arc_ksp->ks_data = &arc_stats;
6263 		arc_ksp->ks_update = arc_kstat_update;
6264 		kstat_install(arc_ksp);
6265 	}
6266 
6267 	arc_adjust_zthr = zthr_create(arc_adjust_cb_check,
6268 	    arc_adjust_cb, NULL);
6269 	arc_reap_zthr = zthr_create_timer(arc_reap_cb_check,
6270 	    arc_reap_cb, NULL, SEC2NSEC(1));
6271 
6272 	arc_initialized = B_TRUE;
6273 	arc_warm = B_FALSE;
6274 
6275 	/*
6276 	 * Calculate maximum amount of dirty data per pool.
6277 	 *
6278 	 * If it has been set by /etc/system, take that.
6279 	 * Otherwise, use a percentage of physical memory defined by
6280 	 * zfs_dirty_data_max_percent (default 10%) with a cap at
6281 	 * zfs_dirty_data_max_max (default 4GB).
6282 	 */
6283 	if (zfs_dirty_data_max == 0) {
6284 		zfs_dirty_data_max = physmem * PAGESIZE *
6285 		    zfs_dirty_data_max_percent / 100;
6286 		zfs_dirty_data_max = MIN(zfs_dirty_data_max,
6287 		    zfs_dirty_data_max_max);
6288 	}
6289 }
6290 
6291 void
6292 arc_fini(void)
6293 {
6294 	/* Use B_TRUE to ensure *all* buffers are evicted */
6295 	arc_flush(NULL, B_TRUE);
6296 
6297 	arc_initialized = B_FALSE;
6298 
6299 	if (arc_ksp != NULL) {
6300 		kstat_delete(arc_ksp);
6301 		arc_ksp = NULL;
6302 	}
6303 
6304 	(void) zthr_cancel(arc_adjust_zthr);
6305 	zthr_destroy(arc_adjust_zthr);
6306 
6307 	(void) zthr_cancel(arc_reap_zthr);
6308 	zthr_destroy(arc_reap_zthr);
6309 
6310 	mutex_destroy(&arc_adjust_lock);
6311 	cv_destroy(&arc_adjust_waiters_cv);
6312 
6313 	arc_state_fini();
6314 	buf_fini();
6315 
6316 	ASSERT0(arc_loaned_bytes);
6317 }
6318 
6319 /*
6320  * Level 2 ARC
6321  *
6322  * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
6323  * It uses dedicated storage devices to hold cached data, which are populated
6324  * using large infrequent writes.  The main role of this cache is to boost
6325  * the performance of random read workloads.  The intended L2ARC devices
6326  * include short-stroked disks, solid state disks, and other media with
6327  * substantially faster read latency than disk.
6328  *
6329  *                 +-----------------------+
6330  *                 |         ARC           |
6331  *                 +-----------------------+
6332  *                    |         ^     ^
6333  *                    |         |     |
6334  *      l2arc_feed_thread()    arc_read()
6335  *                    |         |     |
6336  *                    |  l2arc read   |
6337  *                    V         |     |
6338  *               +---------------+    |
6339  *               |     L2ARC     |    |
6340  *               +---------------+    |
6341  *                   |    ^           |
6342  *          l2arc_write() |           |
6343  *                   |    |           |
6344  *                   V    |           |
6345  *                 +-------+      +-------+
6346  *                 | vdev  |      | vdev  |
6347  *                 | cache |      | cache |
6348  *                 +-------+      +-------+
6349  *                 +=========+     .-----.
6350  *                 :  L2ARC  :    |-_____-|
6351  *                 : devices :    | Disks |
6352  *                 +=========+    `-_____-'
6353  *
6354  * Read requests are satisfied from the following sources, in order:
6355  *
6356  *	1) ARC
6357  *	2) vdev cache of L2ARC devices
6358  *	3) L2ARC devices
6359  *	4) vdev cache of disks
6360  *	5) disks
6361  *
6362  * Some L2ARC device types exhibit extremely slow write performance.
6363  * To accommodate for this there are some significant differences between
6364  * the L2ARC and traditional cache design:
6365  *
6366  * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
6367  * the ARC behave as usual, freeing buffers and placing headers on ghost
6368  * lists.  The ARC does not send buffers to the L2ARC during eviction as
6369  * this would add inflated write latencies for all ARC memory pressure.
6370  *
6371  * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
6372  * It does this by periodically scanning buffers from the eviction-end of
6373  * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
6374  * not already there. It scans until a headroom of buffers is satisfied,
6375  * which itself is a buffer for ARC eviction. If a compressible buffer is
6376  * found during scanning and selected for writing to an L2ARC device, we
6377  * temporarily boost scanning headroom during the next scan cycle to make
6378  * sure we adapt to compression effects (which might significantly reduce
6379  * the data volume we write to L2ARC). The thread that does this is
6380  * l2arc_feed_thread(), illustrated below; example sizes are included to
6381  * provide a better sense of ratio than this diagram:
6382  *
6383  *	       head -->                        tail
6384  *	        +---------------------+----------+
6385  *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
6386  *	        +---------------------+----------+   |   o L2ARC eligible
6387  *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
6388  *	        +---------------------+----------+   |
6389  *	             15.9 Gbytes      ^ 32 Mbytes    |
6390  *	                           headroom          |
6391  *	                                      l2arc_feed_thread()
6392  *	                                             |
6393  *	                 l2arc write hand <--[oooo]--'
6394  *	                         |           8 Mbyte
6395  *	                         |          write max
6396  *	                         V
6397  *		  +==============================+
6398  *	L2ARC dev |####|#|###|###|    |####| ... |
6399  *	          +==============================+
6400  *	                     32 Gbytes
6401  *
6402  * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
6403  * evicted, then the L2ARC has cached a buffer much sooner than it probably
6404  * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
6405  * safe to say that this is an uncommon case, since buffers at the end of
6406  * the ARC lists have moved there due to inactivity.
6407  *
6408  * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
6409  * then the L2ARC simply misses copying some buffers.  This serves as a
6410  * pressure valve to prevent heavy read workloads from both stalling the ARC
6411  * with waits and clogging the L2ARC with writes.  This also helps prevent
6412  * the potential for the L2ARC to churn if it attempts to cache content too
6413  * quickly, such as during backups of the entire pool.
6414  *
6415  * 5. After system boot and before the ARC has filled main memory, there are
6416  * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
6417  * lists can remain mostly static.  Instead of searching from tail of these
6418  * lists as pictured, the l2arc_feed_thread() will search from the list heads
6419  * for eligible buffers, greatly increasing its chance of finding them.
6420  *
6421  * The L2ARC device write speed is also boosted during this time so that
6422  * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
6423  * there are no L2ARC reads, and no fear of degrading read performance
6424  * through increased writes.
6425  *
6426  * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
6427  * the vdev queue can aggregate them into larger and fewer writes.  Each
6428  * device is written to in a rotor fashion, sweeping writes through
6429  * available space then repeating.
6430  *
6431  * 7. The L2ARC does not store dirty content.  It never needs to flush
6432  * write buffers back to disk based storage.
6433  *
6434  * 8. If an ARC buffer is written (and dirtied) which also exists in the
6435  * L2ARC, the now stale L2ARC buffer is immediately dropped.
6436  *
6437  * The performance of the L2ARC can be tweaked by a number of tunables, which
6438  * may be necessary for different workloads:
6439  *
6440  *	l2arc_write_max		max write bytes per interval
6441  *	l2arc_write_boost	extra write bytes during device warmup
6442  *	l2arc_noprefetch	skip caching prefetched buffers
6443  *	l2arc_headroom		number of max device writes to precache
6444  *	l2arc_headroom_boost	when we find compressed buffers during ARC
6445  *				scanning, we multiply headroom by this
6446  *				percentage factor for the next scan cycle,
6447  *				since more compressed buffers are likely to
6448  *				be present
6449  *	l2arc_feed_secs		seconds between L2ARC writing
6450  *
6451  * Tunables may be removed or added as future performance improvements are
6452  * integrated, and also may become zpool properties.
6453  *
6454  * There are three key functions that control how the L2ARC warms up:
6455  *
6456  *	l2arc_write_eligible()	check if a buffer is eligible to cache
6457  *	l2arc_write_size()	calculate how much to write
6458  *	l2arc_write_interval()	calculate sleep delay between writes
6459  *
6460  * These three functions determine what to write, how much, and how quickly
6461  * to send writes.
6462  */
6463 
6464 static boolean_t
6465 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
6466 {
6467 	/*
6468 	 * A buffer is *not* eligible for the L2ARC if it:
6469 	 * 1. belongs to a different spa.
6470 	 * 2. is already cached on the L2ARC.
6471 	 * 3. has an I/O in progress (it may be an incomplete read).
6472 	 * 4. is flagged not eligible (zfs property).
6473 	 */
6474 	if (hdr->b_spa != spa_guid || HDR_HAS_L2HDR(hdr) ||
6475 	    HDR_IO_IN_PROGRESS(hdr) || !HDR_L2CACHE(hdr))
6476 		return (B_FALSE);
6477 
6478 	return (B_TRUE);
6479 }
6480 
6481 static uint64_t
6482 l2arc_write_size(void)
6483 {
6484 	uint64_t size;
6485 
6486 	/*
6487 	 * Make sure our globals have meaningful values in case the user
6488 	 * altered them.
6489 	 */
6490 	size = l2arc_write_max;
6491 	if (size == 0) {
6492 		cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
6493 		    "be greater than zero, resetting it to the default (%d)",
6494 		    L2ARC_WRITE_SIZE);
6495 		size = l2arc_write_max = L2ARC_WRITE_SIZE;
6496 	}
6497 
6498 	if (arc_warm == B_FALSE)
6499 		size += l2arc_write_boost;
6500 
6501 	return (size);
6502 
6503 }
6504 
6505 static clock_t
6506 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
6507 {
6508 	clock_t interval, next, now;
6509 
6510 	/*
6511 	 * If the ARC lists are busy, increase our write rate; if the
6512 	 * lists are stale, idle back.  This is achieved by checking
6513 	 * how much we previously wrote - if it was more than half of
6514 	 * what we wanted, schedule the next write much sooner.
6515 	 */
6516 	if (l2arc_feed_again && wrote > (wanted / 2))
6517 		interval = (hz * l2arc_feed_min_ms) / 1000;
6518 	else
6519 		interval = hz * l2arc_feed_secs;
6520 
6521 	now = ddi_get_lbolt();
6522 	next = MAX(now, MIN(now + interval, began + interval));
6523 
6524 	return (next);
6525 }
6526 
6527 /*
6528  * Cycle through L2ARC devices.  This is how L2ARC load balances.
6529  * If a device is returned, this also returns holding the spa config lock.
6530  */
6531 static l2arc_dev_t *
6532 l2arc_dev_get_next(void)
6533 {
6534 	l2arc_dev_t *first, *next = NULL;
6535 
6536 	/*
6537 	 * Lock out the removal of spas (spa_namespace_lock), then removal
6538 	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
6539 	 * both locks will be dropped and a spa config lock held instead.
6540 	 */
6541 	mutex_enter(&spa_namespace_lock);
6542 	mutex_enter(&l2arc_dev_mtx);
6543 
6544 	/* if there are no vdevs, there is nothing to do */
6545 	if (l2arc_ndev == 0)
6546 		goto out;
6547 
6548 	first = NULL;
6549 	next = l2arc_dev_last;
6550 	do {
6551 		/* loop around the list looking for a non-faulted vdev */
6552 		if (next == NULL) {
6553 			next = list_head(l2arc_dev_list);
6554 		} else {
6555 			next = list_next(l2arc_dev_list, next);
6556 			if (next == NULL)
6557 				next = list_head(l2arc_dev_list);
6558 		}
6559 
6560 		/* if we have come back to the start, bail out */
6561 		if (first == NULL)
6562 			first = next;
6563 		else if (next == first)
6564 			break;
6565 
6566 	} while (vdev_is_dead(next->l2ad_vdev));
6567 
6568 	/* if we were unable to find any usable vdevs, return NULL */
6569 	if (vdev_is_dead(next->l2ad_vdev))
6570 		next = NULL;
6571 
6572 	l2arc_dev_last = next;
6573 
6574 out:
6575 	mutex_exit(&l2arc_dev_mtx);
6576 
6577 	/*
6578 	 * Grab the config lock to prevent the 'next' device from being
6579 	 * removed while we are writing to it.
6580 	 */
6581 	if (next != NULL)
6582 		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
6583 	mutex_exit(&spa_namespace_lock);
6584 
6585 	return (next);
6586 }
6587 
6588 /*
6589  * Free buffers that were tagged for destruction.
6590  */
6591 static void
6592 l2arc_do_free_on_write()
6593 {
6594 	list_t *buflist;
6595 	l2arc_data_free_t *df, *df_prev;
6596 
6597 	mutex_enter(&l2arc_free_on_write_mtx);
6598 	buflist = l2arc_free_on_write;
6599 
6600 	for (df = list_tail(buflist); df; df = df_prev) {
6601 		df_prev = list_prev(buflist, df);
6602 		ASSERT3P(df->l2df_abd, !=, NULL);
6603 		abd_free(df->l2df_abd);
6604 		list_remove(buflist, df);
6605 		kmem_free(df, sizeof (l2arc_data_free_t));
6606 	}
6607 
6608 	mutex_exit(&l2arc_free_on_write_mtx);
6609 }
6610 
6611 /*
6612  * A write to a cache device has completed.  Update all headers to allow
6613  * reads from these buffers to begin.
6614  */
6615 static void
6616 l2arc_write_done(zio_t *zio)
6617 {
6618 	l2arc_write_callback_t *cb;
6619 	l2arc_dev_t *dev;
6620 	list_t *buflist;
6621 	arc_buf_hdr_t *head, *hdr, *hdr_prev;
6622 	kmutex_t *hash_lock;
6623 	int64_t bytes_dropped = 0;
6624 
6625 	cb = zio->io_private;
6626 	ASSERT3P(cb, !=, NULL);
6627 	dev = cb->l2wcb_dev;
6628 	ASSERT3P(dev, !=, NULL);
6629 	head = cb->l2wcb_head;
6630 	ASSERT3P(head, !=, NULL);
6631 	buflist = &dev->l2ad_buflist;
6632 	ASSERT3P(buflist, !=, NULL);
6633 	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
6634 	    l2arc_write_callback_t *, cb);
6635 
6636 	if (zio->io_error != 0)
6637 		ARCSTAT_BUMP(arcstat_l2_writes_error);
6638 
6639 	/*
6640 	 * All writes completed, or an error was hit.
6641 	 */
6642 top:
6643 	mutex_enter(&dev->l2ad_mtx);
6644 	for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
6645 		hdr_prev = list_prev(buflist, hdr);
6646 
6647 		hash_lock = HDR_LOCK(hdr);
6648 
6649 		/*
6650 		 * We cannot use mutex_enter or else we can deadlock
6651 		 * with l2arc_write_buffers (due to swapping the order
6652 		 * the hash lock and l2ad_mtx are taken).
6653 		 */
6654 		if (!mutex_tryenter(hash_lock)) {
6655 			/*
6656 			 * Missed the hash lock. We must retry so we
6657 			 * don't leave the ARC_FLAG_L2_WRITING bit set.
6658 			 */
6659 			ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
6660 
6661 			/*
6662 			 * We don't want to rescan the headers we've
6663 			 * already marked as having been written out, so
6664 			 * we reinsert the head node so we can pick up
6665 			 * where we left off.
6666 			 */
6667 			list_remove(buflist, head);
6668 			list_insert_after(buflist, hdr, head);
6669 
6670 			mutex_exit(&dev->l2ad_mtx);
6671 
6672 			/*
6673 			 * We wait for the hash lock to become available
6674 			 * to try and prevent busy waiting, and increase
6675 			 * the chance we'll be able to acquire the lock
6676 			 * the next time around.
6677 			 */
6678 			mutex_enter(hash_lock);
6679 			mutex_exit(hash_lock);
6680 			goto top;
6681 		}
6682 
6683 		/*
6684 		 * We could not have been moved into the arc_l2c_only
6685 		 * state while in-flight due to our ARC_FLAG_L2_WRITING
6686 		 * bit being set. Let's just ensure that's being enforced.
6687 		 */
6688 		ASSERT(HDR_HAS_L1HDR(hdr));
6689 
6690 		if (zio->io_error != 0) {
6691 			/*
6692 			 * Error - drop L2ARC entry.
6693 			 */
6694 			list_remove(buflist, hdr);
6695 			arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
6696 
6697 			ARCSTAT_INCR(arcstat_l2_psize, -arc_hdr_size(hdr));
6698 			ARCSTAT_INCR(arcstat_l2_lsize, -HDR_GET_LSIZE(hdr));
6699 
6700 			bytes_dropped += arc_hdr_size(hdr);
6701 			(void) refcount_remove_many(&dev->l2ad_alloc,
6702 			    arc_hdr_size(hdr), hdr);
6703 		}
6704 
6705 		/*
6706 		 * Allow ARC to begin reads and ghost list evictions to
6707 		 * this L2ARC entry.
6708 		 */
6709 		arc_hdr_clear_flags(hdr, ARC_FLAG_L2_WRITING);
6710 
6711 		mutex_exit(hash_lock);
6712 	}
6713 
6714 	atomic_inc_64(&l2arc_writes_done);
6715 	list_remove(buflist, head);
6716 	ASSERT(!HDR_HAS_L1HDR(head));
6717 	kmem_cache_free(hdr_l2only_cache, head);
6718 	mutex_exit(&dev->l2ad_mtx);
6719 
6720 	vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
6721 
6722 	l2arc_do_free_on_write();
6723 
6724 	kmem_free(cb, sizeof (l2arc_write_callback_t));
6725 }
6726 
6727 /*
6728  * A read to a cache device completed.  Validate buffer contents before
6729  * handing over to the regular ARC routines.
6730  */
6731 static void
6732 l2arc_read_done(zio_t *zio)
6733 {
6734 	l2arc_read_callback_t *cb;
6735 	arc_buf_hdr_t *hdr;
6736 	kmutex_t *hash_lock;
6737 	boolean_t valid_cksum;
6738 
6739 	ASSERT3P(zio->io_vd, !=, NULL);
6740 	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
6741 
6742 	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
6743 
6744 	cb = zio->io_private;
6745 	ASSERT3P(cb, !=, NULL);
6746 	hdr = cb->l2rcb_hdr;
6747 	ASSERT3P(hdr, !=, NULL);
6748 
6749 	hash_lock = HDR_LOCK(hdr);
6750 	mutex_enter(hash_lock);
6751 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
6752 
6753 	/*
6754 	 * If the data was read into a temporary buffer,
6755 	 * move it and free the buffer.
6756 	 */
6757 	if (cb->l2rcb_abd != NULL) {
6758 		ASSERT3U(arc_hdr_size(hdr), <, zio->io_size);
6759 		if (zio->io_error == 0) {
6760 			abd_copy(hdr->b_l1hdr.b_pabd, cb->l2rcb_abd,
6761 			    arc_hdr_size(hdr));
6762 		}
6763 
6764 		/*
6765 		 * The following must be done regardless of whether
6766 		 * there was an error:
6767 		 * - free the temporary buffer
6768 		 * - point zio to the real ARC buffer
6769 		 * - set zio size accordingly
6770 		 * These are required because zio is either re-used for
6771 		 * an I/O of the block in the case of the error
6772 		 * or the zio is passed to arc_read_done() and it
6773 		 * needs real data.
6774 		 */
6775 		abd_free(cb->l2rcb_abd);
6776 		zio->io_size = zio->io_orig_size = arc_hdr_size(hdr);
6777 		zio->io_abd = zio->io_orig_abd = hdr->b_l1hdr.b_pabd;
6778 	}
6779 
6780 	ASSERT3P(zio->io_abd, !=, NULL);
6781 
6782 	/*
6783 	 * Check this survived the L2ARC journey.
6784 	 */
6785 	ASSERT3P(zio->io_abd, ==, hdr->b_l1hdr.b_pabd);
6786 	zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
6787 	zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
6788 
6789 	valid_cksum = arc_cksum_is_equal(hdr, zio);
6790 	if (valid_cksum && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
6791 		mutex_exit(hash_lock);
6792 		zio->io_private = hdr;
6793 		arc_read_done(zio);
6794 	} else {
6795 		mutex_exit(hash_lock);
6796 		/*
6797 		 * Buffer didn't survive caching.  Increment stats and
6798 		 * reissue to the original storage device.
6799 		 */
6800 		if (zio->io_error != 0) {
6801 			ARCSTAT_BUMP(arcstat_l2_io_error);
6802 		} else {
6803 			zio->io_error = SET_ERROR(EIO);
6804 		}
6805 		if (!valid_cksum)
6806 			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
6807 
6808 		/*
6809 		 * If there's no waiter, issue an async i/o to the primary
6810 		 * storage now.  If there *is* a waiter, the caller must
6811 		 * issue the i/o in a context where it's OK to block.
6812 		 */
6813 		if (zio->io_waiter == NULL) {
6814 			zio_t *pio = zio_unique_parent(zio);
6815 
6816 			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
6817 
6818 			zio_nowait(zio_read(pio, zio->io_spa, zio->io_bp,
6819 			    hdr->b_l1hdr.b_pabd, zio->io_size, arc_read_done,
6820 			    hdr, zio->io_priority, cb->l2rcb_flags,
6821 			    &cb->l2rcb_zb));
6822 		}
6823 	}
6824 
6825 	kmem_free(cb, sizeof (l2arc_read_callback_t));
6826 }
6827 
6828 /*
6829  * This is the list priority from which the L2ARC will search for pages to
6830  * cache.  This is used within loops (0..3) to cycle through lists in the
6831  * desired order.  This order can have a significant effect on cache
6832  * performance.
6833  *
6834  * Currently the metadata lists are hit first, MFU then MRU, followed by
6835  * the data lists.  This function returns a locked list, and also returns
6836  * the lock pointer.
6837  */
6838 static multilist_sublist_t *
6839 l2arc_sublist_lock(int list_num)
6840 {
6841 	multilist_t *ml = NULL;
6842 	unsigned int idx;
6843 
6844 	ASSERT(list_num >= 0 && list_num <= 3);
6845 
6846 	switch (list_num) {
6847 	case 0:
6848 		ml = arc_mfu->arcs_list[ARC_BUFC_METADATA];
6849 		break;
6850 	case 1:
6851 		ml = arc_mru->arcs_list[ARC_BUFC_METADATA];
6852 		break;
6853 	case 2:
6854 		ml = arc_mfu->arcs_list[ARC_BUFC_DATA];
6855 		break;
6856 	case 3:
6857 		ml = arc_mru->arcs_list[ARC_BUFC_DATA];
6858 		break;
6859 	}
6860 
6861 	/*
6862 	 * Return a randomly-selected sublist. This is acceptable
6863 	 * because the caller feeds only a little bit of data for each
6864 	 * call (8MB). Subsequent calls will result in different
6865 	 * sublists being selected.
6866 	 */
6867 	idx = multilist_get_random_index(ml);
6868 	return (multilist_sublist_lock(ml, idx));
6869 }
6870 
6871 /*
6872  * Evict buffers from the device write hand to the distance specified in
6873  * bytes.  This distance may span populated buffers, it may span nothing.
6874  * This is clearing a region on the L2ARC device ready for writing.
6875  * If the 'all' boolean is set, every buffer is evicted.
6876  */
6877 static void
6878 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
6879 {
6880 	list_t *buflist;
6881 	arc_buf_hdr_t *hdr, *hdr_prev;
6882 	kmutex_t *hash_lock;
6883 	uint64_t taddr;
6884 
6885 	buflist = &dev->l2ad_buflist;
6886 
6887 	if (!all && dev->l2ad_first) {
6888 		/*
6889 		 * This is the first sweep through the device.  There is
6890 		 * nothing to evict.
6891 		 */
6892 		return;
6893 	}
6894 
6895 	if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
6896 		/*
6897 		 * When nearing the end of the device, evict to the end
6898 		 * before the device write hand jumps to the start.
6899 		 */
6900 		taddr = dev->l2ad_end;
6901 	} else {
6902 		taddr = dev->l2ad_hand + distance;
6903 	}
6904 	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
6905 	    uint64_t, taddr, boolean_t, all);
6906 
6907 top:
6908 	mutex_enter(&dev->l2ad_mtx);
6909 	for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
6910 		hdr_prev = list_prev(buflist, hdr);
6911 
6912 		hash_lock = HDR_LOCK(hdr);
6913 
6914 		/*
6915 		 * We cannot use mutex_enter or else we can deadlock
6916 		 * with l2arc_write_buffers (due to swapping the order
6917 		 * the hash lock and l2ad_mtx are taken).
6918 		 */
6919 		if (!mutex_tryenter(hash_lock)) {
6920 			/*
6921 			 * Missed the hash lock.  Retry.
6922 			 */
6923 			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
6924 			mutex_exit(&dev->l2ad_mtx);
6925 			mutex_enter(hash_lock);
6926 			mutex_exit(hash_lock);
6927 			goto top;
6928 		}
6929 
6930 		/*
6931 		 * A header can't be on this list if it doesn't have L2 header.
6932 		 */
6933 		ASSERT(HDR_HAS_L2HDR(hdr));
6934 
6935 		/* Ensure this header has finished being written. */
6936 		ASSERT(!HDR_L2_WRITING(hdr));
6937 		ASSERT(!HDR_L2_WRITE_HEAD(hdr));
6938 
6939 		if (!all && (hdr->b_l2hdr.b_daddr >= taddr ||
6940 		    hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
6941 			/*
6942 			 * We've evicted to the target address,
6943 			 * or the end of the device.
6944 			 */
6945 			mutex_exit(hash_lock);
6946 			break;
6947 		}
6948 
6949 		if (!HDR_HAS_L1HDR(hdr)) {
6950 			ASSERT(!HDR_L2_READING(hdr));
6951 			/*
6952 			 * This doesn't exist in the ARC.  Destroy.
6953 			 * arc_hdr_destroy() will call list_remove()
6954 			 * and decrement arcstat_l2_lsize.
6955 			 */
6956 			arc_change_state(arc_anon, hdr, hash_lock);
6957 			arc_hdr_destroy(hdr);
6958 		} else {
6959 			ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
6960 			ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
6961 			/*
6962 			 * Invalidate issued or about to be issued
6963 			 * reads, since we may be about to write
6964 			 * over this location.
6965 			 */
6966 			if (HDR_L2_READING(hdr)) {
6967 				ARCSTAT_BUMP(arcstat_l2_evict_reading);
6968 				arc_hdr_set_flags(hdr, ARC_FLAG_L2_EVICTED);
6969 			}
6970 
6971 			arc_hdr_l2hdr_destroy(hdr);
6972 		}
6973 		mutex_exit(hash_lock);
6974 	}
6975 	mutex_exit(&dev->l2ad_mtx);
6976 }
6977 
6978 /*
6979  * Find and write ARC buffers to the L2ARC device.
6980  *
6981  * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
6982  * for reading until they have completed writing.
6983  * The headroom_boost is an in-out parameter used to maintain headroom boost
6984  * state between calls to this function.
6985  *
6986  * Returns the number of bytes actually written (which may be smaller than
6987  * the delta by which the device hand has changed due to alignment).
6988  */
6989 static uint64_t
6990 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
6991 {
6992 	arc_buf_hdr_t *hdr, *hdr_prev, *head;
6993 	uint64_t write_asize, write_psize, write_lsize, headroom;
6994 	boolean_t full;
6995 	l2arc_write_callback_t *cb;
6996 	zio_t *pio, *wzio;
6997 	uint64_t guid = spa_load_guid(spa);
6998 
6999 	ASSERT3P(dev->l2ad_vdev, !=, NULL);
7000 
7001 	pio = NULL;
7002 	write_lsize = write_asize = write_psize = 0;
7003 	full = B_FALSE;
7004 	head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
7005 	arc_hdr_set_flags(head, ARC_FLAG_L2_WRITE_HEAD | ARC_FLAG_HAS_L2HDR);
7006 
7007 	/*
7008 	 * Copy buffers for L2ARC writing.
7009 	 */
7010 	for (int try = 0; try <= 3; try++) {
7011 		multilist_sublist_t *mls = l2arc_sublist_lock(try);
7012 		uint64_t passed_sz = 0;
7013 
7014 		/*
7015 		 * L2ARC fast warmup.
7016 		 *
7017 		 * Until the ARC is warm and starts to evict, read from the
7018 		 * head of the ARC lists rather than the tail.
7019 		 */
7020 		if (arc_warm == B_FALSE)
7021 			hdr = multilist_sublist_head(mls);
7022 		else
7023 			hdr = multilist_sublist_tail(mls);
7024 
7025 		headroom = target_sz * l2arc_headroom;
7026 		if (zfs_compressed_arc_enabled)
7027 			headroom = (headroom * l2arc_headroom_boost) / 100;
7028 
7029 		for (; hdr; hdr = hdr_prev) {
7030 			kmutex_t *hash_lock;
7031 
7032 			if (arc_warm == B_FALSE)
7033 				hdr_prev = multilist_sublist_next(mls, hdr);
7034 			else
7035 				hdr_prev = multilist_sublist_prev(mls, hdr);
7036 
7037 			hash_lock = HDR_LOCK(hdr);
7038 			if (!mutex_tryenter(hash_lock)) {
7039 				/*
7040 				 * Skip this buffer rather than waiting.
7041 				 */
7042 				continue;
7043 			}
7044 
7045 			passed_sz += HDR_GET_LSIZE(hdr);
7046 			if (passed_sz > headroom) {
7047 				/*
7048 				 * Searched too far.
7049 				 */
7050 				mutex_exit(hash_lock);
7051 				break;
7052 			}
7053 
7054 			if (!l2arc_write_eligible(guid, hdr)) {
7055 				mutex_exit(hash_lock);
7056 				continue;
7057 			}
7058 
7059 			/*
7060 			 * We rely on the L1 portion of the header below, so
7061 			 * it's invalid for this header to have been evicted out
7062 			 * of the ghost cache, prior to being written out. The
7063 			 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
7064 			 */
7065 			ASSERT(HDR_HAS_L1HDR(hdr));
7066 
7067 			ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
7068 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
7069 			ASSERT3U(arc_hdr_size(hdr), >, 0);
7070 			uint64_t psize = arc_hdr_size(hdr);
7071 			uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev,
7072 			    psize);
7073 
7074 			if ((write_asize + asize) > target_sz) {
7075 				full = B_TRUE;
7076 				mutex_exit(hash_lock);
7077 				break;
7078 			}
7079 
7080 			if (pio == NULL) {
7081 				/*
7082 				 * Insert a dummy header on the buflist so
7083 				 * l2arc_write_done() can find where the
7084 				 * write buffers begin without searching.
7085 				 */
7086 				mutex_enter(&dev->l2ad_mtx);
7087 				list_insert_head(&dev->l2ad_buflist, head);
7088 				mutex_exit(&dev->l2ad_mtx);
7089 
7090 				cb = kmem_alloc(
7091 				    sizeof (l2arc_write_callback_t), KM_SLEEP);
7092 				cb->l2wcb_dev = dev;
7093 				cb->l2wcb_head = head;
7094 				pio = zio_root(spa, l2arc_write_done, cb,
7095 				    ZIO_FLAG_CANFAIL);
7096 			}
7097 
7098 			hdr->b_l2hdr.b_dev = dev;
7099 			hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
7100 			arc_hdr_set_flags(hdr,
7101 			    ARC_FLAG_L2_WRITING | ARC_FLAG_HAS_L2HDR);
7102 
7103 			mutex_enter(&dev->l2ad_mtx);
7104 			list_insert_head(&dev->l2ad_buflist, hdr);
7105 			mutex_exit(&dev->l2ad_mtx);
7106 
7107 			(void) refcount_add_many(&dev->l2ad_alloc, psize, hdr);
7108 
7109 			/*
7110 			 * Normally the L2ARC can use the hdr's data, but if
7111 			 * we're sharing data between the hdr and one of its
7112 			 * bufs, L2ARC needs its own copy of the data so that
7113 			 * the ZIO below can't race with the buf consumer.
7114 			 * Another case where we need to create a copy of the
7115 			 * data is when the buffer size is not device-aligned
7116 			 * and we need to pad the block to make it such.
7117 			 * That also keeps the clock hand suitably aligned.
7118 			 *
7119 			 * To ensure that the copy will be available for the
7120 			 * lifetime of the ZIO and be cleaned up afterwards, we
7121 			 * add it to the l2arc_free_on_write queue.
7122 			 */
7123 			abd_t *to_write;
7124 			if (!HDR_SHARED_DATA(hdr) && psize == asize) {
7125 				to_write = hdr->b_l1hdr.b_pabd;
7126 			} else {
7127 				to_write = abd_alloc_for_io(asize,
7128 				    HDR_ISTYPE_METADATA(hdr));
7129 				abd_copy(to_write, hdr->b_l1hdr.b_pabd, psize);
7130 				if (asize != psize) {
7131 					abd_zero_off(to_write, psize,
7132 					    asize - psize);
7133 				}
7134 				l2arc_free_abd_on_write(to_write, asize,
7135 				    arc_buf_type(hdr));
7136 			}
7137 			wzio = zio_write_phys(pio, dev->l2ad_vdev,
7138 			    hdr->b_l2hdr.b_daddr, asize, to_write,
7139 			    ZIO_CHECKSUM_OFF, NULL, hdr,
7140 			    ZIO_PRIORITY_ASYNC_WRITE,
7141 			    ZIO_FLAG_CANFAIL, B_FALSE);
7142 
7143 			write_lsize += HDR_GET_LSIZE(hdr);
7144 			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
7145 			    zio_t *, wzio);
7146 
7147 			write_psize += psize;
7148 			write_asize += asize;
7149 			dev->l2ad_hand += asize;
7150 
7151 			mutex_exit(hash_lock);
7152 
7153 			(void) zio_nowait(wzio);
7154 		}
7155 
7156 		multilist_sublist_unlock(mls);
7157 
7158 		if (full == B_TRUE)
7159 			break;
7160 	}
7161 
7162 	/* No buffers selected for writing? */
7163 	if (pio == NULL) {
7164 		ASSERT0(write_lsize);
7165 		ASSERT(!HDR_HAS_L1HDR(head));
7166 		kmem_cache_free(hdr_l2only_cache, head);
7167 		return (0);
7168 	}
7169 
7170 	ASSERT3U(write_asize, <=, target_sz);
7171 	ARCSTAT_BUMP(arcstat_l2_writes_sent);
7172 	ARCSTAT_INCR(arcstat_l2_write_bytes, write_psize);
7173 	ARCSTAT_INCR(arcstat_l2_lsize, write_lsize);
7174 	ARCSTAT_INCR(arcstat_l2_psize, write_psize);
7175 	vdev_space_update(dev->l2ad_vdev, write_psize, 0, 0);
7176 
7177 	/*
7178 	 * Bump device hand to the device start if it is approaching the end.
7179 	 * l2arc_evict() will already have evicted ahead for this case.
7180 	 */
7181 	if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
7182 		dev->l2ad_hand = dev->l2ad_start;
7183 		dev->l2ad_first = B_FALSE;
7184 	}
7185 
7186 	dev->l2ad_writing = B_TRUE;
7187 	(void) zio_wait(pio);
7188 	dev->l2ad_writing = B_FALSE;
7189 
7190 	return (write_asize);
7191 }
7192 
7193 /*
7194  * This thread feeds the L2ARC at regular intervals.  This is the beating
7195  * heart of the L2ARC.
7196  */
7197 /* ARGSUSED */
7198 static void
7199 l2arc_feed_thread(void *unused)
7200 {
7201 	callb_cpr_t cpr;
7202 	l2arc_dev_t *dev;
7203 	spa_t *spa;
7204 	uint64_t size, wrote;
7205 	clock_t begin, next = ddi_get_lbolt();
7206 
7207 	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
7208 
7209 	mutex_enter(&l2arc_feed_thr_lock);
7210 
7211 	while (l2arc_thread_exit == 0) {
7212 		CALLB_CPR_SAFE_BEGIN(&cpr);
7213 		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
7214 		    next);
7215 		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
7216 		next = ddi_get_lbolt() + hz;
7217 
7218 		/*
7219 		 * Quick check for L2ARC devices.
7220 		 */
7221 		mutex_enter(&l2arc_dev_mtx);
7222 		if (l2arc_ndev == 0) {
7223 			mutex_exit(&l2arc_dev_mtx);
7224 			continue;
7225 		}
7226 		mutex_exit(&l2arc_dev_mtx);
7227 		begin = ddi_get_lbolt();
7228 
7229 		/*
7230 		 * This selects the next l2arc device to write to, and in
7231 		 * doing so the next spa to feed from: dev->l2ad_spa.   This
7232 		 * will return NULL if there are now no l2arc devices or if
7233 		 * they are all faulted.
7234 		 *
7235 		 * If a device is returned, its spa's config lock is also
7236 		 * held to prevent device removal.  l2arc_dev_get_next()
7237 		 * will grab and release l2arc_dev_mtx.
7238 		 */
7239 		if ((dev = l2arc_dev_get_next()) == NULL)
7240 			continue;
7241 
7242 		spa = dev->l2ad_spa;
7243 		ASSERT3P(spa, !=, NULL);
7244 
7245 		/*
7246 		 * If the pool is read-only then force the feed thread to
7247 		 * sleep a little longer.
7248 		 */
7249 		if (!spa_writeable(spa)) {
7250 			next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
7251 			spa_config_exit(spa, SCL_L2ARC, dev);
7252 			continue;
7253 		}
7254 
7255 		/*
7256 		 * Avoid contributing to memory pressure.
7257 		 */
7258 		if (arc_reclaim_needed()) {
7259 			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
7260 			spa_config_exit(spa, SCL_L2ARC, dev);
7261 			continue;
7262 		}
7263 
7264 		ARCSTAT_BUMP(arcstat_l2_feeds);
7265 
7266 		size = l2arc_write_size();
7267 
7268 		/*
7269 		 * Evict L2ARC buffers that will be overwritten.
7270 		 */
7271 		l2arc_evict(dev, size, B_FALSE);
7272 
7273 		/*
7274 		 * Write ARC buffers.
7275 		 */
7276 		wrote = l2arc_write_buffers(spa, dev, size);
7277 
7278 		/*
7279 		 * Calculate interval between writes.
7280 		 */
7281 		next = l2arc_write_interval(begin, size, wrote);
7282 		spa_config_exit(spa, SCL_L2ARC, dev);
7283 	}
7284 
7285 	l2arc_thread_exit = 0;
7286 	cv_broadcast(&l2arc_feed_thr_cv);
7287 	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
7288 	thread_exit();
7289 }
7290 
7291 boolean_t
7292 l2arc_vdev_present(vdev_t *vd)
7293 {
7294 	l2arc_dev_t *dev;
7295 
7296 	mutex_enter(&l2arc_dev_mtx);
7297 	for (dev = list_head(l2arc_dev_list); dev != NULL;
7298 	    dev = list_next(l2arc_dev_list, dev)) {
7299 		if (dev->l2ad_vdev == vd)
7300 			break;
7301 	}
7302 	mutex_exit(&l2arc_dev_mtx);
7303 
7304 	return (dev != NULL);
7305 }
7306 
7307 /*
7308  * Add a vdev for use by the L2ARC.  By this point the spa has already
7309  * validated the vdev and opened it.
7310  */
7311 void
7312 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
7313 {
7314 	l2arc_dev_t *adddev;
7315 
7316 	ASSERT(!l2arc_vdev_present(vd));
7317 
7318 	/*
7319 	 * Create a new l2arc device entry.
7320 	 */
7321 	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
7322 	adddev->l2ad_spa = spa;
7323 	adddev->l2ad_vdev = vd;
7324 	adddev->l2ad_start = VDEV_LABEL_START_SIZE;
7325 	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
7326 	adddev->l2ad_hand = adddev->l2ad_start;
7327 	adddev->l2ad_first = B_TRUE;
7328 	adddev->l2ad_writing = B_FALSE;
7329 
7330 	mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
7331 	/*
7332 	 * This is a list of all ARC buffers that are still valid on the
7333 	 * device.
7334 	 */
7335 	list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
7336 	    offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
7337 
7338 	vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
7339 	refcount_create(&adddev->l2ad_alloc);
7340 
7341 	/*
7342 	 * Add device to global list
7343 	 */
7344 	mutex_enter(&l2arc_dev_mtx);
7345 	list_insert_head(l2arc_dev_list, adddev);
7346 	atomic_inc_64(&l2arc_ndev);
7347 	mutex_exit(&l2arc_dev_mtx);
7348 }
7349 
7350 /*
7351  * Remove a vdev from the L2ARC.
7352  */
7353 void
7354 l2arc_remove_vdev(vdev_t *vd)
7355 {
7356 	l2arc_dev_t *dev, *nextdev, *remdev = NULL;
7357 
7358 	/*
7359 	 * Find the device by vdev
7360 	 */
7361 	mutex_enter(&l2arc_dev_mtx);
7362 	for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
7363 		nextdev = list_next(l2arc_dev_list, dev);
7364 		if (vd == dev->l2ad_vdev) {
7365 			remdev = dev;
7366 			break;
7367 		}
7368 	}
7369 	ASSERT3P(remdev, !=, NULL);
7370 
7371 	/*
7372 	 * Remove device from global list
7373 	 */
7374 	list_remove(l2arc_dev_list, remdev);
7375 	l2arc_dev_last = NULL;		/* may have been invalidated */
7376 	atomic_dec_64(&l2arc_ndev);
7377 	mutex_exit(&l2arc_dev_mtx);
7378 
7379 	/*
7380 	 * Clear all buflists and ARC references.  L2ARC device flush.
7381 	 */
7382 	l2arc_evict(remdev, 0, B_TRUE);
7383 	list_destroy(&remdev->l2ad_buflist);
7384 	mutex_destroy(&remdev->l2ad_mtx);
7385 	refcount_destroy(&remdev->l2ad_alloc);
7386 	kmem_free(remdev, sizeof (l2arc_dev_t));
7387 }
7388 
7389 void
7390 l2arc_init(void)
7391 {
7392 	l2arc_thread_exit = 0;
7393 	l2arc_ndev = 0;
7394 	l2arc_writes_sent = 0;
7395 	l2arc_writes_done = 0;
7396 
7397 	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
7398 	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
7399 	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
7400 	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
7401 
7402 	l2arc_dev_list = &L2ARC_dev_list;
7403 	l2arc_free_on_write = &L2ARC_free_on_write;
7404 	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
7405 	    offsetof(l2arc_dev_t, l2ad_node));
7406 	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
7407 	    offsetof(l2arc_data_free_t, l2df_list_node));
7408 }
7409 
7410 void
7411 l2arc_fini(void)
7412 {
7413 	/*
7414 	 * This is called from dmu_fini(), which is called from spa_fini();
7415 	 * Because of this, we can assume that all l2arc devices have
7416 	 * already been removed when the pools themselves were removed.
7417 	 */
7418 
7419 	l2arc_do_free_on_write();
7420 
7421 	mutex_destroy(&l2arc_feed_thr_lock);
7422 	cv_destroy(&l2arc_feed_thr_cv);
7423 	mutex_destroy(&l2arc_dev_mtx);
7424 	mutex_destroy(&l2arc_free_on_write_mtx);
7425 
7426 	list_destroy(l2arc_dev_list);
7427 	list_destroy(l2arc_free_on_write);
7428 }
7429 
7430 void
7431 l2arc_start(void)
7432 {
7433 	if (!(spa_mode_global & FWRITE))
7434 		return;
7435 
7436 	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
7437 	    TS_RUN, minclsyspri);
7438 }
7439 
7440 void
7441 l2arc_stop(void)
7442 {
7443 	if (!(spa_mode_global & FWRITE))
7444 		return;
7445 
7446 	mutex_enter(&l2arc_feed_thr_lock);
7447 	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
7448 	l2arc_thread_exit = 1;
7449 	while (l2arc_thread_exit != 0)
7450 		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
7451 	mutex_exit(&l2arc_feed_thr_lock);
7452 }
7453