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