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