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