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