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