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