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