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