arc.c revision 275811
1/*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21/*
22 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23 * Copyright (c) 2011, 2014 by Delphix. All rights reserved.
24 * Copyright (c) 2014 by Saso Kiselkov. All rights reserved.
25 * Copyright 2014 Nexenta Systems, Inc.  All rights reserved.
26 */
27
28/*
29 * DVA-based Adjustable Replacement Cache
30 *
31 * While much of the theory of operation used here is
32 * based on the self-tuning, low overhead replacement cache
33 * presented by Megiddo and Modha at FAST 2003, there are some
34 * significant differences:
35 *
36 * 1. The Megiddo and Modha model assumes any page is evictable.
37 * Pages in its cache cannot be "locked" into memory.  This makes
38 * the eviction algorithm simple: evict the last page in the list.
39 * This also make the performance characteristics easy to reason
40 * about.  Our cache is not so simple.  At any given moment, some
41 * subset of the blocks in the cache are un-evictable because we
42 * have handed out a reference to them.  Blocks are only evictable
43 * when there are no external references active.  This makes
44 * eviction far more problematic:  we choose to evict the evictable
45 * blocks that are the "lowest" in the list.
46 *
47 * There are times when it is not possible to evict the requested
48 * space.  In these circumstances we are unable to adjust the cache
49 * size.  To prevent the cache growing unbounded at these times we
50 * implement a "cache throttle" that slows the flow of new data
51 * into the cache until we can make space available.
52 *
53 * 2. The Megiddo and Modha model assumes a fixed cache size.
54 * Pages are evicted when the cache is full and there is a cache
55 * miss.  Our model has a variable sized cache.  It grows with
56 * high use, but also tries to react to memory pressure from the
57 * operating system: decreasing its size when system memory is
58 * tight.
59 *
60 * 3. The Megiddo and Modha model assumes a fixed page size. All
61 * elements of the cache are therefore exactly the same size.  So
62 * when adjusting the cache size following a cache miss, its simply
63 * a matter of choosing a single page to evict.  In our model, we
64 * have variable sized cache blocks (rangeing from 512 bytes to
65 * 128K bytes).  We therefore choose a set of blocks to evict to make
66 * space for a cache miss that approximates as closely as possible
67 * the space used by the new block.
68 *
69 * See also:  "ARC: A Self-Tuning, Low Overhead Replacement Cache"
70 * by N. Megiddo & D. Modha, FAST 2003
71 */
72
73/*
74 * The locking model:
75 *
76 * A new reference to a cache buffer can be obtained in two
77 * ways: 1) via a hash table lookup using the DVA as a key,
78 * or 2) via one of the ARC lists.  The arc_read() interface
79 * uses method 1, while the internal arc algorithms for
80 * adjusting the cache use method 2.  We therefore provide two
81 * types of locks: 1) the hash table lock array, and 2) the
82 * arc list locks.
83 *
84 * Buffers do not have their own mutexs, rather they rely on the
85 * hash table mutexs for the bulk of their protection (i.e. most
86 * fields in the arc_buf_hdr_t are protected by these mutexs).
87 *
88 * buf_hash_find() returns the appropriate mutex (held) when it
89 * locates the requested buffer in the hash table.  It returns
90 * NULL for the mutex if the buffer was not in the table.
91 *
92 * buf_hash_remove() expects the appropriate hash mutex to be
93 * already held before it is invoked.
94 *
95 * Each arc state also has a mutex which is used to protect the
96 * buffer list associated with the state.  When attempting to
97 * obtain a hash table lock while holding an arc list lock you
98 * must use: mutex_tryenter() to avoid deadlock.  Also note that
99 * the active state mutex must be held before the ghost state mutex.
100 *
101 * Arc buffers may have an associated eviction callback function.
102 * This function will be invoked prior to removing the buffer (e.g.
103 * in arc_do_user_evicts()).  Note however that the data associated
104 * with the buffer may be evicted prior to the callback.  The callback
105 * must be made with *no locks held* (to prevent deadlock).  Additionally,
106 * the users of callbacks must ensure that their private data is
107 * protected from simultaneous callbacks from arc_clear_callback()
108 * and arc_do_user_evicts().
109 *
110 * Note that the majority of the performance stats are manipulated
111 * with atomic operations.
112 *
113 * The L2ARC uses the l2arc_buflist_mtx global mutex for the following:
114 *
115 *	- L2ARC buflist creation
116 *	- L2ARC buflist eviction
117 *	- L2ARC write completion, which walks L2ARC buflists
118 *	- ARC header destruction, as it removes from L2ARC buflists
119 *	- ARC header release, as it removes from L2ARC buflists
120 */
121
122#include <sys/spa.h>
123#include <sys/zio.h>
124#include <sys/zio_compress.h>
125#include <sys/zfs_context.h>
126#include <sys/arc.h>
127#include <sys/refcount.h>
128#include <sys/vdev.h>
129#include <sys/vdev_impl.h>
130#include <sys/dsl_pool.h>
131#ifdef _KERNEL
132#include <sys/dnlc.h>
133#endif
134#include <sys/callb.h>
135#include <sys/kstat.h>
136#include <sys/trim_map.h>
137#include <zfs_fletcher.h>
138#include <sys/sdt.h>
139
140#include <vm/vm_pageout.h>
141#include <machine/vmparam.h>
142
143#ifdef illumos
144#ifndef _KERNEL
145/* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
146boolean_t arc_watch = B_FALSE;
147int arc_procfd;
148#endif
149#endif /* illumos */
150
151static kmutex_t		arc_reclaim_thr_lock;
152static kcondvar_t	arc_reclaim_thr_cv;	/* used to signal reclaim thr */
153static uint8_t		arc_thread_exit;
154
155#define	ARC_REDUCE_DNLC_PERCENT	3
156uint_t arc_reduce_dnlc_percent = ARC_REDUCE_DNLC_PERCENT;
157
158typedef enum arc_reclaim_strategy {
159	ARC_RECLAIM_AGGR,		/* Aggressive reclaim strategy */
160	ARC_RECLAIM_CONS		/* Conservative reclaim strategy */
161} arc_reclaim_strategy_t;
162
163/*
164 * The number of iterations through arc_evict_*() before we
165 * drop & reacquire the lock.
166 */
167int arc_evict_iterations = 100;
168
169/* number of seconds before growing cache again */
170static int		arc_grow_retry = 60;
171
172/* shift of arc_c for calculating both min and max arc_p */
173static int		arc_p_min_shift = 4;
174
175/* log2(fraction of arc to reclaim) */
176static int		arc_shrink_shift = 5;
177
178/*
179 * minimum lifespan of a prefetch block in clock ticks
180 * (initialized in arc_init())
181 */
182static int		arc_min_prefetch_lifespan;
183
184/*
185 * If this percent of memory is free, don't throttle.
186 */
187int arc_lotsfree_percent = 10;
188
189static int arc_dead;
190extern int zfs_prefetch_disable;
191
192/*
193 * The arc has filled available memory and has now warmed up.
194 */
195static boolean_t arc_warm;
196
197uint64_t zfs_arc_max;
198uint64_t zfs_arc_min;
199uint64_t zfs_arc_meta_limit = 0;
200uint64_t zfs_arc_meta_min = 0;
201int zfs_arc_grow_retry = 0;
202int zfs_arc_shrink_shift = 0;
203int zfs_arc_p_min_shift = 0;
204int zfs_disable_dup_eviction = 0;
205uint64_t zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
206u_int zfs_arc_free_target = 0;
207
208static int sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS);
209static int sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS);
210
211#ifdef _KERNEL
212static void
213arc_free_target_init(void *unused __unused)
214{
215
216	zfs_arc_free_target = vm_pageout_wakeup_thresh;
217}
218SYSINIT(arc_free_target_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_ANY,
219    arc_free_target_init, NULL);
220
221TUNABLE_QUAD("vfs.zfs.arc_meta_limit", &zfs_arc_meta_limit);
222TUNABLE_QUAD("vfs.zfs.arc_meta_min", &zfs_arc_meta_min);
223TUNABLE_INT("vfs.zfs.arc_shrink_shift", &zfs_arc_shrink_shift);
224SYSCTL_DECL(_vfs_zfs);
225SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_max, CTLFLAG_RDTUN, &zfs_arc_max, 0,
226    "Maximum ARC size");
227SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_min, CTLFLAG_RDTUN, &zfs_arc_min, 0,
228    "Minimum ARC size");
229SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_average_blocksize, CTLFLAG_RDTUN,
230    &zfs_arc_average_blocksize, 0,
231    "ARC average blocksize");
232SYSCTL_INT(_vfs_zfs, OID_AUTO, arc_shrink_shift, CTLFLAG_RW,
233    &arc_shrink_shift, 0,
234    "log2(fraction of arc to reclaim)");
235
236/*
237 * We don't have a tunable for arc_free_target due to the dependency on
238 * pagedaemon initialisation.
239 */
240SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_free_target,
241    CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(u_int),
242    sysctl_vfs_zfs_arc_free_target, "IU",
243    "Desired number of free pages below which ARC triggers reclaim");
244
245static int
246sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS)
247{
248	u_int val;
249	int err;
250
251	val = zfs_arc_free_target;
252	err = sysctl_handle_int(oidp, &val, 0, req);
253	if (err != 0 || req->newptr == NULL)
254		return (err);
255
256	if (val < minfree)
257		return (EINVAL);
258	if (val > vm_cnt.v_page_count)
259		return (EINVAL);
260
261	zfs_arc_free_target = val;
262
263	return (0);
264}
265
266/*
267 * Must be declared here, before the definition of corresponding kstat
268 * macro which uses the same names will confuse the compiler.
269 */
270SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_meta_limit,
271    CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
272    sysctl_vfs_zfs_arc_meta_limit, "QU",
273    "ARC metadata limit");
274#endif
275
276/*
277 * Note that buffers can be in one of 6 states:
278 *	ARC_anon	- anonymous (discussed below)
279 *	ARC_mru		- recently used, currently cached
280 *	ARC_mru_ghost	- recentely used, no longer in cache
281 *	ARC_mfu		- frequently used, currently cached
282 *	ARC_mfu_ghost	- frequently used, no longer in cache
283 *	ARC_l2c_only	- exists in L2ARC but not other states
284 * When there are no active references to the buffer, they are
285 * are linked onto a list in one of these arc states.  These are
286 * the only buffers that can be evicted or deleted.  Within each
287 * state there are multiple lists, one for meta-data and one for
288 * non-meta-data.  Meta-data (indirect blocks, blocks of dnodes,
289 * etc.) is tracked separately so that it can be managed more
290 * explicitly: favored over data, limited explicitly.
291 *
292 * Anonymous buffers are buffers that are not associated with
293 * a DVA.  These are buffers that hold dirty block copies
294 * before they are written to stable storage.  By definition,
295 * they are "ref'd" and are considered part of arc_mru
296 * that cannot be freed.  Generally, they will aquire a DVA
297 * as they are written and migrate onto the arc_mru list.
298 *
299 * The ARC_l2c_only state is for buffers that are in the second
300 * level ARC but no longer in any of the ARC_m* lists.  The second
301 * level ARC itself may also contain buffers that are in any of
302 * the ARC_m* states - meaning that a buffer can exist in two
303 * places.  The reason for the ARC_l2c_only state is to keep the
304 * buffer header in the hash table, so that reads that hit the
305 * second level ARC benefit from these fast lookups.
306 */
307
308#define	ARCS_LOCK_PAD		CACHE_LINE_SIZE
309struct arcs_lock {
310	kmutex_t	arcs_lock;
311#ifdef _KERNEL
312	unsigned char	pad[(ARCS_LOCK_PAD - sizeof (kmutex_t))];
313#endif
314};
315
316/*
317 * must be power of two for mask use to work
318 *
319 */
320#define ARC_BUFC_NUMDATALISTS		16
321#define ARC_BUFC_NUMMETADATALISTS	16
322#define ARC_BUFC_NUMLISTS	(ARC_BUFC_NUMMETADATALISTS + ARC_BUFC_NUMDATALISTS)
323
324typedef struct arc_state {
325	uint64_t arcs_lsize[ARC_BUFC_NUMTYPES];	/* amount of evictable data */
326	uint64_t arcs_size;	/* total amount of data in this state */
327	list_t	arcs_lists[ARC_BUFC_NUMLISTS]; /* list of evictable buffers */
328	struct arcs_lock arcs_locks[ARC_BUFC_NUMLISTS] __aligned(CACHE_LINE_SIZE);
329} arc_state_t;
330
331#define ARCS_LOCK(s, i)	(&((s)->arcs_locks[(i)].arcs_lock))
332
333/* The 6 states: */
334static arc_state_t ARC_anon;
335static arc_state_t ARC_mru;
336static arc_state_t ARC_mru_ghost;
337static arc_state_t ARC_mfu;
338static arc_state_t ARC_mfu_ghost;
339static arc_state_t ARC_l2c_only;
340
341typedef struct arc_stats {
342	kstat_named_t arcstat_hits;
343	kstat_named_t arcstat_misses;
344	kstat_named_t arcstat_demand_data_hits;
345	kstat_named_t arcstat_demand_data_misses;
346	kstat_named_t arcstat_demand_metadata_hits;
347	kstat_named_t arcstat_demand_metadata_misses;
348	kstat_named_t arcstat_prefetch_data_hits;
349	kstat_named_t arcstat_prefetch_data_misses;
350	kstat_named_t arcstat_prefetch_metadata_hits;
351	kstat_named_t arcstat_prefetch_metadata_misses;
352	kstat_named_t arcstat_mru_hits;
353	kstat_named_t arcstat_mru_ghost_hits;
354	kstat_named_t arcstat_mfu_hits;
355	kstat_named_t arcstat_mfu_ghost_hits;
356	kstat_named_t arcstat_allocated;
357	kstat_named_t arcstat_deleted;
358	kstat_named_t arcstat_stolen;
359	kstat_named_t arcstat_recycle_miss;
360	/*
361	 * Number of buffers that could not be evicted because the hash lock
362	 * was held by another thread.  The lock may not necessarily be held
363	 * by something using the same buffer, since hash locks are shared
364	 * by multiple buffers.
365	 */
366	kstat_named_t arcstat_mutex_miss;
367	/*
368	 * Number of buffers skipped because they have I/O in progress, are
369	 * indrect prefetch buffers that have not lived long enough, or are
370	 * not from the spa we're trying to evict from.
371	 */
372	kstat_named_t arcstat_evict_skip;
373	kstat_named_t arcstat_evict_l2_cached;
374	kstat_named_t arcstat_evict_l2_eligible;
375	kstat_named_t arcstat_evict_l2_ineligible;
376	kstat_named_t arcstat_hash_elements;
377	kstat_named_t arcstat_hash_elements_max;
378	kstat_named_t arcstat_hash_collisions;
379	kstat_named_t arcstat_hash_chains;
380	kstat_named_t arcstat_hash_chain_max;
381	kstat_named_t arcstat_p;
382	kstat_named_t arcstat_c;
383	kstat_named_t arcstat_c_min;
384	kstat_named_t arcstat_c_max;
385	kstat_named_t arcstat_size;
386	kstat_named_t arcstat_hdr_size;
387	kstat_named_t arcstat_data_size;
388	kstat_named_t arcstat_other_size;
389	kstat_named_t arcstat_l2_hits;
390	kstat_named_t arcstat_l2_misses;
391	kstat_named_t arcstat_l2_feeds;
392	kstat_named_t arcstat_l2_rw_clash;
393	kstat_named_t arcstat_l2_read_bytes;
394	kstat_named_t arcstat_l2_write_bytes;
395	kstat_named_t arcstat_l2_writes_sent;
396	kstat_named_t arcstat_l2_writes_done;
397	kstat_named_t arcstat_l2_writes_error;
398	kstat_named_t arcstat_l2_writes_hdr_miss;
399	kstat_named_t arcstat_l2_evict_lock_retry;
400	kstat_named_t arcstat_l2_evict_reading;
401	kstat_named_t arcstat_l2_free_on_write;
402	kstat_named_t arcstat_l2_cdata_free_on_write;
403	kstat_named_t arcstat_l2_abort_lowmem;
404	kstat_named_t arcstat_l2_cksum_bad;
405	kstat_named_t arcstat_l2_io_error;
406	kstat_named_t arcstat_l2_size;
407	kstat_named_t arcstat_l2_asize;
408	kstat_named_t arcstat_l2_hdr_size;
409	kstat_named_t arcstat_l2_compress_successes;
410	kstat_named_t arcstat_l2_compress_zeros;
411	kstat_named_t arcstat_l2_compress_failures;
412	kstat_named_t arcstat_l2_write_trylock_fail;
413	kstat_named_t arcstat_l2_write_passed_headroom;
414	kstat_named_t arcstat_l2_write_spa_mismatch;
415	kstat_named_t arcstat_l2_write_in_l2;
416	kstat_named_t arcstat_l2_write_hdr_io_in_progress;
417	kstat_named_t arcstat_l2_write_not_cacheable;
418	kstat_named_t arcstat_l2_write_full;
419	kstat_named_t arcstat_l2_write_buffer_iter;
420	kstat_named_t arcstat_l2_write_pios;
421	kstat_named_t arcstat_l2_write_buffer_bytes_scanned;
422	kstat_named_t arcstat_l2_write_buffer_list_iter;
423	kstat_named_t arcstat_l2_write_buffer_list_null_iter;
424	kstat_named_t arcstat_memory_throttle_count;
425	kstat_named_t arcstat_duplicate_buffers;
426	kstat_named_t arcstat_duplicate_buffers_size;
427	kstat_named_t arcstat_duplicate_reads;
428	kstat_named_t arcstat_meta_used;
429	kstat_named_t arcstat_meta_limit;
430	kstat_named_t arcstat_meta_max;
431	kstat_named_t arcstat_meta_min;
432} arc_stats_t;
433
434static arc_stats_t arc_stats = {
435	{ "hits",			KSTAT_DATA_UINT64 },
436	{ "misses",			KSTAT_DATA_UINT64 },
437	{ "demand_data_hits",		KSTAT_DATA_UINT64 },
438	{ "demand_data_misses",		KSTAT_DATA_UINT64 },
439	{ "demand_metadata_hits",	KSTAT_DATA_UINT64 },
440	{ "demand_metadata_misses",	KSTAT_DATA_UINT64 },
441	{ "prefetch_data_hits",		KSTAT_DATA_UINT64 },
442	{ "prefetch_data_misses",	KSTAT_DATA_UINT64 },
443	{ "prefetch_metadata_hits",	KSTAT_DATA_UINT64 },
444	{ "prefetch_metadata_misses",	KSTAT_DATA_UINT64 },
445	{ "mru_hits",			KSTAT_DATA_UINT64 },
446	{ "mru_ghost_hits",		KSTAT_DATA_UINT64 },
447	{ "mfu_hits",			KSTAT_DATA_UINT64 },
448	{ "mfu_ghost_hits",		KSTAT_DATA_UINT64 },
449	{ "allocated",			KSTAT_DATA_UINT64 },
450	{ "deleted",			KSTAT_DATA_UINT64 },
451	{ "stolen",			KSTAT_DATA_UINT64 },
452	{ "recycle_miss",		KSTAT_DATA_UINT64 },
453	{ "mutex_miss",			KSTAT_DATA_UINT64 },
454	{ "evict_skip",			KSTAT_DATA_UINT64 },
455	{ "evict_l2_cached",		KSTAT_DATA_UINT64 },
456	{ "evict_l2_eligible",		KSTAT_DATA_UINT64 },
457	{ "evict_l2_ineligible",	KSTAT_DATA_UINT64 },
458	{ "hash_elements",		KSTAT_DATA_UINT64 },
459	{ "hash_elements_max",		KSTAT_DATA_UINT64 },
460	{ "hash_collisions",		KSTAT_DATA_UINT64 },
461	{ "hash_chains",		KSTAT_DATA_UINT64 },
462	{ "hash_chain_max",		KSTAT_DATA_UINT64 },
463	{ "p",				KSTAT_DATA_UINT64 },
464	{ "c",				KSTAT_DATA_UINT64 },
465	{ "c_min",			KSTAT_DATA_UINT64 },
466	{ "c_max",			KSTAT_DATA_UINT64 },
467	{ "size",			KSTAT_DATA_UINT64 },
468	{ "hdr_size",			KSTAT_DATA_UINT64 },
469	{ "data_size",			KSTAT_DATA_UINT64 },
470	{ "other_size",			KSTAT_DATA_UINT64 },
471	{ "l2_hits",			KSTAT_DATA_UINT64 },
472	{ "l2_misses",			KSTAT_DATA_UINT64 },
473	{ "l2_feeds",			KSTAT_DATA_UINT64 },
474	{ "l2_rw_clash",		KSTAT_DATA_UINT64 },
475	{ "l2_read_bytes",		KSTAT_DATA_UINT64 },
476	{ "l2_write_bytes",		KSTAT_DATA_UINT64 },
477	{ "l2_writes_sent",		KSTAT_DATA_UINT64 },
478	{ "l2_writes_done",		KSTAT_DATA_UINT64 },
479	{ "l2_writes_error",		KSTAT_DATA_UINT64 },
480	{ "l2_writes_hdr_miss",		KSTAT_DATA_UINT64 },
481	{ "l2_evict_lock_retry",	KSTAT_DATA_UINT64 },
482	{ "l2_evict_reading",		KSTAT_DATA_UINT64 },
483	{ "l2_free_on_write",		KSTAT_DATA_UINT64 },
484	{ "l2_cdata_free_on_write",	KSTAT_DATA_UINT64 },
485	{ "l2_abort_lowmem",		KSTAT_DATA_UINT64 },
486	{ "l2_cksum_bad",		KSTAT_DATA_UINT64 },
487	{ "l2_io_error",		KSTAT_DATA_UINT64 },
488	{ "l2_size",			KSTAT_DATA_UINT64 },
489	{ "l2_asize",			KSTAT_DATA_UINT64 },
490	{ "l2_hdr_size",		KSTAT_DATA_UINT64 },
491	{ "l2_compress_successes",	KSTAT_DATA_UINT64 },
492	{ "l2_compress_zeros",		KSTAT_DATA_UINT64 },
493	{ "l2_compress_failures",	KSTAT_DATA_UINT64 },
494	{ "l2_write_trylock_fail",	KSTAT_DATA_UINT64 },
495	{ "l2_write_passed_headroom",	KSTAT_DATA_UINT64 },
496	{ "l2_write_spa_mismatch",	KSTAT_DATA_UINT64 },
497	{ "l2_write_in_l2",		KSTAT_DATA_UINT64 },
498	{ "l2_write_io_in_progress",	KSTAT_DATA_UINT64 },
499	{ "l2_write_not_cacheable",	KSTAT_DATA_UINT64 },
500	{ "l2_write_full",		KSTAT_DATA_UINT64 },
501	{ "l2_write_buffer_iter",	KSTAT_DATA_UINT64 },
502	{ "l2_write_pios",		KSTAT_DATA_UINT64 },
503	{ "l2_write_buffer_bytes_scanned", KSTAT_DATA_UINT64 },
504	{ "l2_write_buffer_list_iter",	KSTAT_DATA_UINT64 },
505	{ "l2_write_buffer_list_null_iter", KSTAT_DATA_UINT64 },
506	{ "memory_throttle_count",	KSTAT_DATA_UINT64 },
507	{ "duplicate_buffers",		KSTAT_DATA_UINT64 },
508	{ "duplicate_buffers_size",	KSTAT_DATA_UINT64 },
509	{ "duplicate_reads",		KSTAT_DATA_UINT64 },
510	{ "arc_meta_used",		KSTAT_DATA_UINT64 },
511	{ "arc_meta_limit",		KSTAT_DATA_UINT64 },
512	{ "arc_meta_max",		KSTAT_DATA_UINT64 },
513	{ "arc_meta_min",		KSTAT_DATA_UINT64 }
514};
515
516#define	ARCSTAT(stat)	(arc_stats.stat.value.ui64)
517
518#define	ARCSTAT_INCR(stat, val) \
519	atomic_add_64(&arc_stats.stat.value.ui64, (val))
520
521#define	ARCSTAT_BUMP(stat)	ARCSTAT_INCR(stat, 1)
522#define	ARCSTAT_BUMPDOWN(stat)	ARCSTAT_INCR(stat, -1)
523
524#define	ARCSTAT_MAX(stat, val) {					\
525	uint64_t m;							\
526	while ((val) > (m = arc_stats.stat.value.ui64) &&		\
527	    (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val))))	\
528		continue;						\
529}
530
531#define	ARCSTAT_MAXSTAT(stat) \
532	ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
533
534/*
535 * We define a macro to allow ARC hits/misses to be easily broken down by
536 * two separate conditions, giving a total of four different subtypes for
537 * each of hits and misses (so eight statistics total).
538 */
539#define	ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
540	if (cond1) {							\
541		if (cond2) {						\
542			ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
543		} else {						\
544			ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
545		}							\
546	} else {							\
547		if (cond2) {						\
548			ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
549		} else {						\
550			ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
551		}							\
552	}
553
554kstat_t			*arc_ksp;
555static arc_state_t	*arc_anon;
556static arc_state_t	*arc_mru;
557static arc_state_t	*arc_mru_ghost;
558static arc_state_t	*arc_mfu;
559static arc_state_t	*arc_mfu_ghost;
560static arc_state_t	*arc_l2c_only;
561
562/*
563 * There are several ARC variables that are critical to export as kstats --
564 * but we don't want to have to grovel around in the kstat whenever we wish to
565 * manipulate them.  For these variables, we therefore define them to be in
566 * terms of the statistic variable.  This assures that we are not introducing
567 * the possibility of inconsistency by having shadow copies of the variables,
568 * while still allowing the code to be readable.
569 */
570#define	arc_size	ARCSTAT(arcstat_size)	/* actual total arc size */
571#define	arc_p		ARCSTAT(arcstat_p)	/* target size of MRU */
572#define	arc_c		ARCSTAT(arcstat_c)	/* target size of cache */
573#define	arc_c_min	ARCSTAT(arcstat_c_min)	/* min target cache size */
574#define	arc_c_max	ARCSTAT(arcstat_c_max)	/* max target cache size */
575#define	arc_meta_limit	ARCSTAT(arcstat_meta_limit) /* max size for metadata */
576#define	arc_meta_min	ARCSTAT(arcstat_meta_min) /* min size for metadata */
577#define	arc_meta_used	ARCSTAT(arcstat_meta_used) /* size of metadata */
578#define	arc_meta_max	ARCSTAT(arcstat_meta_max) /* max size of metadata */
579
580#define	L2ARC_IS_VALID_COMPRESS(_c_) \
581	((_c_) == ZIO_COMPRESS_LZ4 || (_c_) == ZIO_COMPRESS_EMPTY)
582
583static int		arc_no_grow;	/* Don't try to grow cache size */
584static uint64_t		arc_tempreserve;
585static uint64_t		arc_loaned_bytes;
586
587typedef struct l2arc_buf_hdr l2arc_buf_hdr_t;
588
589typedef struct arc_callback arc_callback_t;
590
591struct arc_callback {
592	void			*acb_private;
593	arc_done_func_t		*acb_done;
594	arc_buf_t		*acb_buf;
595	zio_t			*acb_zio_dummy;
596	arc_callback_t		*acb_next;
597};
598
599typedef struct arc_write_callback arc_write_callback_t;
600
601struct arc_write_callback {
602	void		*awcb_private;
603	arc_done_func_t	*awcb_ready;
604	arc_done_func_t	*awcb_physdone;
605	arc_done_func_t	*awcb_done;
606	arc_buf_t	*awcb_buf;
607};
608
609struct arc_buf_hdr {
610	/* protected by hash lock */
611	dva_t			b_dva;
612	uint64_t		b_birth;
613	uint64_t		b_cksum0;
614
615	kmutex_t		b_freeze_lock;
616	zio_cksum_t		*b_freeze_cksum;
617	void			*b_thawed;
618
619	arc_buf_hdr_t		*b_hash_next;
620	arc_buf_t		*b_buf;
621	arc_flags_t		b_flags;
622	uint32_t		b_datacnt;
623
624	arc_callback_t		*b_acb;
625	kcondvar_t		b_cv;
626
627	/* immutable */
628	arc_buf_contents_t	b_type;
629	uint64_t		b_size;
630	uint64_t		b_spa;
631
632	/* protected by arc state mutex */
633	arc_state_t		*b_state;
634	list_node_t		b_arc_node;
635
636	/* updated atomically */
637	clock_t			b_arc_access;
638
639	/* self protecting */
640	refcount_t		b_refcnt;
641
642	l2arc_buf_hdr_t		*b_l2hdr;
643	list_node_t		b_l2node;
644};
645
646#ifdef _KERNEL
647static int
648sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS)
649{
650	uint64_t val;
651	int err;
652
653	val = arc_meta_limit;
654	err = sysctl_handle_64(oidp, &val, 0, req);
655	if (err != 0 || req->newptr == NULL)
656		return (err);
657
658        if (val <= 0 || val > arc_c_max)
659		return (EINVAL);
660
661	arc_meta_limit = val;
662	return (0);
663}
664#endif
665
666static arc_buf_t *arc_eviction_list;
667static kmutex_t arc_eviction_mtx;
668static arc_buf_hdr_t arc_eviction_hdr;
669
670#define	GHOST_STATE(state)	\
671	((state) == arc_mru_ghost || (state) == arc_mfu_ghost ||	\
672	(state) == arc_l2c_only)
673
674#define	HDR_IN_HASH_TABLE(hdr)	((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
675#define	HDR_IO_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
676#define	HDR_IO_ERROR(hdr)	((hdr)->b_flags & ARC_FLAG_IO_ERROR)
677#define	HDR_PREFETCH(hdr)	((hdr)->b_flags & ARC_FLAG_PREFETCH)
678#define	HDR_FREED_IN_READ(hdr)	((hdr)->b_flags & ARC_FLAG_FREED_IN_READ)
679#define	HDR_BUF_AVAILABLE(hdr)	((hdr)->b_flags & ARC_FLAG_BUF_AVAILABLE)
680#define	HDR_FREE_IN_PROGRESS(hdr)	\
681	((hdr)->b_flags & ARC_FLAG_FREE_IN_PROGRESS)
682#define	HDR_L2CACHE(hdr)	((hdr)->b_flags & ARC_FLAG_L2CACHE)
683#define	HDR_L2_READING(hdr)	\
684	((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS &&	\
685	    (hdr)->b_l2hdr != NULL)
686#define	HDR_L2_WRITING(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITING)
687#define	HDR_L2_EVICTED(hdr)	((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
688#define	HDR_L2_WRITE_HEAD(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
689
690/*
691 * Other sizes
692 */
693
694#define	HDR_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
695#define	L2HDR_SIZE ((int64_t)sizeof (l2arc_buf_hdr_t))
696
697/*
698 * Hash table routines
699 */
700
701#define	HT_LOCK_PAD	CACHE_LINE_SIZE
702
703struct ht_lock {
704	kmutex_t	ht_lock;
705#ifdef _KERNEL
706	unsigned char	pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
707#endif
708};
709
710#define	BUF_LOCKS 256
711typedef struct buf_hash_table {
712	uint64_t ht_mask;
713	arc_buf_hdr_t **ht_table;
714	struct ht_lock ht_locks[BUF_LOCKS] __aligned(CACHE_LINE_SIZE);
715} buf_hash_table_t;
716
717static buf_hash_table_t buf_hash_table;
718
719#define	BUF_HASH_INDEX(spa, dva, birth) \
720	(buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
721#define	BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
722#define	BUF_HASH_LOCK(idx)	(&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
723#define	HDR_LOCK(hdr) \
724	(BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
725
726uint64_t zfs_crc64_table[256];
727
728/*
729 * Level 2 ARC
730 */
731
732#define	L2ARC_WRITE_SIZE	(8 * 1024 * 1024)	/* initial write max */
733#define	L2ARC_HEADROOM		2			/* num of writes */
734/*
735 * If we discover during ARC scan any buffers to be compressed, we boost
736 * our headroom for the next scanning cycle by this percentage multiple.
737 */
738#define	L2ARC_HEADROOM_BOOST	200
739#define	L2ARC_FEED_SECS		1		/* caching interval secs */
740#define	L2ARC_FEED_MIN_MS	200		/* min caching interval ms */
741
742#define	l2arc_writes_sent	ARCSTAT(arcstat_l2_writes_sent)
743#define	l2arc_writes_done	ARCSTAT(arcstat_l2_writes_done)
744
745/* L2ARC Performance Tunables */
746uint64_t l2arc_write_max = L2ARC_WRITE_SIZE;	/* default max write size */
747uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE;	/* extra write during warmup */
748uint64_t l2arc_headroom = L2ARC_HEADROOM;	/* number of dev writes */
749uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
750uint64_t l2arc_feed_secs = L2ARC_FEED_SECS;	/* interval seconds */
751uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS;	/* min interval milliseconds */
752boolean_t l2arc_noprefetch = B_TRUE;		/* don't cache prefetch bufs */
753boolean_t l2arc_feed_again = B_TRUE;		/* turbo warmup */
754boolean_t l2arc_norw = B_TRUE;			/* no reads during writes */
755
756SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RW,
757    &l2arc_write_max, 0, "max write size");
758SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RW,
759    &l2arc_write_boost, 0, "extra write during warmup");
760SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RW,
761    &l2arc_headroom, 0, "number of dev writes");
762SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RW,
763    &l2arc_feed_secs, 0, "interval seconds");
764SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RW,
765    &l2arc_feed_min_ms, 0, "min interval milliseconds");
766
767SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RW,
768    &l2arc_noprefetch, 0, "don't cache prefetch bufs");
769SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RW,
770    &l2arc_feed_again, 0, "turbo warmup");
771SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RW,
772    &l2arc_norw, 0, "no reads during writes");
773
774SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
775    &ARC_anon.arcs_size, 0, "size of anonymous state");
776SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_metadata_lsize, CTLFLAG_RD,
777    &ARC_anon.arcs_lsize[ARC_BUFC_METADATA], 0, "size of anonymous state");
778SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_data_lsize, CTLFLAG_RD,
779    &ARC_anon.arcs_lsize[ARC_BUFC_DATA], 0, "size of anonymous state");
780
781SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
782    &ARC_mru.arcs_size, 0, "size of mru state");
783SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_metadata_lsize, CTLFLAG_RD,
784    &ARC_mru.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mru state");
785SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_data_lsize, CTLFLAG_RD,
786    &ARC_mru.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mru state");
787
788SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
789    &ARC_mru_ghost.arcs_size, 0, "size of mru ghost state");
790SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_lsize, CTLFLAG_RD,
791    &ARC_mru_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
792    "size of metadata in mru ghost state");
793SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_lsize, CTLFLAG_RD,
794    &ARC_mru_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
795    "size of data in mru ghost state");
796
797SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
798    &ARC_mfu.arcs_size, 0, "size of mfu state");
799SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_metadata_lsize, CTLFLAG_RD,
800    &ARC_mfu.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mfu state");
801SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_data_lsize, CTLFLAG_RD,
802    &ARC_mfu.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mfu state");
803
804SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
805    &ARC_mfu_ghost.arcs_size, 0, "size of mfu ghost state");
806SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_lsize, CTLFLAG_RD,
807    &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
808    "size of metadata in mfu ghost state");
809SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_lsize, CTLFLAG_RD,
810    &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
811    "size of data in mfu ghost state");
812
813SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
814    &ARC_l2c_only.arcs_size, 0, "size of mru state");
815
816/*
817 * L2ARC Internals
818 */
819typedef struct l2arc_dev {
820	vdev_t			*l2ad_vdev;	/* vdev */
821	spa_t			*l2ad_spa;	/* spa */
822	uint64_t		l2ad_hand;	/* next write location */
823	uint64_t		l2ad_start;	/* first addr on device */
824	uint64_t		l2ad_end;	/* last addr on device */
825	uint64_t		l2ad_evict;	/* last addr eviction reached */
826	boolean_t		l2ad_first;	/* first sweep through */
827	boolean_t		l2ad_writing;	/* currently writing */
828	list_t			*l2ad_buflist;	/* buffer list */
829	list_node_t		l2ad_node;	/* device list node */
830} l2arc_dev_t;
831
832static list_t L2ARC_dev_list;			/* device list */
833static list_t *l2arc_dev_list;			/* device list pointer */
834static kmutex_t l2arc_dev_mtx;			/* device list mutex */
835static l2arc_dev_t *l2arc_dev_last;		/* last device used */
836static kmutex_t l2arc_buflist_mtx;		/* mutex for all buflists */
837static list_t L2ARC_free_on_write;		/* free after write buf list */
838static list_t *l2arc_free_on_write;		/* free after write list ptr */
839static kmutex_t l2arc_free_on_write_mtx;	/* mutex for list */
840static uint64_t l2arc_ndev;			/* number of devices */
841
842typedef struct l2arc_read_callback {
843	arc_buf_t		*l2rcb_buf;		/* read buffer */
844	spa_t			*l2rcb_spa;		/* spa */
845	blkptr_t		l2rcb_bp;		/* original blkptr */
846	zbookmark_phys_t	l2rcb_zb;		/* original bookmark */
847	int			l2rcb_flags;		/* original flags */
848	enum zio_compress	l2rcb_compress;		/* applied compress */
849} l2arc_read_callback_t;
850
851typedef struct l2arc_write_callback {
852	l2arc_dev_t	*l2wcb_dev;		/* device info */
853	arc_buf_hdr_t	*l2wcb_head;		/* head of write buflist */
854} l2arc_write_callback_t;
855
856struct l2arc_buf_hdr {
857	/* protected by arc_buf_hdr  mutex */
858	l2arc_dev_t		*b_dev;		/* L2ARC device */
859	uint64_t		b_daddr;	/* disk address, offset byte */
860	/* compression applied to buffer data */
861	enum zio_compress	b_compress;
862	/* real alloc'd buffer size depending on b_compress applied */
863	int			b_asize;
864	/* temporary buffer holder for in-flight compressed data */
865	void			*b_tmp_cdata;
866};
867
868typedef struct l2arc_data_free {
869	/* protected by l2arc_free_on_write_mtx */
870	void		*l2df_data;
871	size_t		l2df_size;
872	void		(*l2df_func)(void *, size_t);
873	list_node_t	l2df_list_node;
874} l2arc_data_free_t;
875
876static kmutex_t l2arc_feed_thr_lock;
877static kcondvar_t l2arc_feed_thr_cv;
878static uint8_t l2arc_thread_exit;
879
880static void arc_get_data_buf(arc_buf_t *);
881static void arc_access(arc_buf_hdr_t *, kmutex_t *);
882static int arc_evict_needed(arc_buf_contents_t);
883static void arc_evict_ghost(arc_state_t *, uint64_t, int64_t);
884static void arc_buf_watch(arc_buf_t *);
885
886static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
887static void l2arc_read_done(zio_t *);
888static void l2arc_hdr_stat_add(void);
889static void l2arc_hdr_stat_remove(void);
890
891static boolean_t l2arc_compress_buf(l2arc_buf_hdr_t *);
892static void l2arc_decompress_zio(zio_t *, arc_buf_hdr_t *, enum zio_compress);
893static void l2arc_release_cdata_buf(arc_buf_hdr_t *);
894
895static uint64_t
896buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
897{
898	uint8_t *vdva = (uint8_t *)dva;
899	uint64_t crc = -1ULL;
900	int i;
901
902	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
903
904	for (i = 0; i < sizeof (dva_t); i++)
905		crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
906
907	crc ^= (spa>>8) ^ birth;
908
909	return (crc);
910}
911
912#define	BUF_EMPTY(buf)						\
913	((buf)->b_dva.dva_word[0] == 0 &&			\
914	(buf)->b_dva.dva_word[1] == 0 &&			\
915	(buf)->b_cksum0 == 0)
916
917#define	BUF_EQUAL(spa, dva, birth, buf)				\
918	((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) &&	\
919	((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) &&	\
920	((buf)->b_birth == birth) && ((buf)->b_spa == spa)
921
922static void
923buf_discard_identity(arc_buf_hdr_t *hdr)
924{
925	hdr->b_dva.dva_word[0] = 0;
926	hdr->b_dva.dva_word[1] = 0;
927	hdr->b_birth = 0;
928	hdr->b_cksum0 = 0;
929}
930
931static arc_buf_hdr_t *
932buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
933{
934	const dva_t *dva = BP_IDENTITY(bp);
935	uint64_t birth = BP_PHYSICAL_BIRTH(bp);
936	uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
937	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
938	arc_buf_hdr_t *hdr;
939
940	mutex_enter(hash_lock);
941	for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
942	    hdr = hdr->b_hash_next) {
943		if (BUF_EQUAL(spa, dva, birth, hdr)) {
944			*lockp = hash_lock;
945			return (hdr);
946		}
947	}
948	mutex_exit(hash_lock);
949	*lockp = NULL;
950	return (NULL);
951}
952
953/*
954 * Insert an entry into the hash table.  If there is already an element
955 * equal to elem in the hash table, then the already existing element
956 * will be returned and the new element will not be inserted.
957 * Otherwise returns NULL.
958 */
959static arc_buf_hdr_t *
960buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
961{
962	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
963	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
964	arc_buf_hdr_t *fhdr;
965	uint32_t i;
966
967	ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
968	ASSERT(hdr->b_birth != 0);
969	ASSERT(!HDR_IN_HASH_TABLE(hdr));
970	*lockp = hash_lock;
971	mutex_enter(hash_lock);
972	for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
973	    fhdr = fhdr->b_hash_next, i++) {
974		if (BUF_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
975			return (fhdr);
976	}
977
978	hdr->b_hash_next = buf_hash_table.ht_table[idx];
979	buf_hash_table.ht_table[idx] = hdr;
980	hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
981
982	/* collect some hash table performance data */
983	if (i > 0) {
984		ARCSTAT_BUMP(arcstat_hash_collisions);
985		if (i == 1)
986			ARCSTAT_BUMP(arcstat_hash_chains);
987
988		ARCSTAT_MAX(arcstat_hash_chain_max, i);
989	}
990
991	ARCSTAT_BUMP(arcstat_hash_elements);
992	ARCSTAT_MAXSTAT(arcstat_hash_elements);
993
994	return (NULL);
995}
996
997static void
998buf_hash_remove(arc_buf_hdr_t *hdr)
999{
1000	arc_buf_hdr_t *fhdr, **hdrp;
1001	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1002
1003	ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
1004	ASSERT(HDR_IN_HASH_TABLE(hdr));
1005
1006	hdrp = &buf_hash_table.ht_table[idx];
1007	while ((fhdr = *hdrp) != hdr) {
1008		ASSERT(fhdr != NULL);
1009		hdrp = &fhdr->b_hash_next;
1010	}
1011	*hdrp = hdr->b_hash_next;
1012	hdr->b_hash_next = NULL;
1013	hdr->b_flags &= ~ARC_FLAG_IN_HASH_TABLE;
1014
1015	/* collect some hash table performance data */
1016	ARCSTAT_BUMPDOWN(arcstat_hash_elements);
1017
1018	if (buf_hash_table.ht_table[idx] &&
1019	    buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1020		ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1021}
1022
1023/*
1024 * Global data structures and functions for the buf kmem cache.
1025 */
1026static kmem_cache_t *hdr_cache;
1027static kmem_cache_t *buf_cache;
1028
1029static void
1030buf_fini(void)
1031{
1032	int i;
1033
1034	kmem_free(buf_hash_table.ht_table,
1035	    (buf_hash_table.ht_mask + 1) * sizeof (void *));
1036	for (i = 0; i < BUF_LOCKS; i++)
1037		mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
1038	kmem_cache_destroy(hdr_cache);
1039	kmem_cache_destroy(buf_cache);
1040}
1041
1042/*
1043 * Constructor callback - called when the cache is empty
1044 * and a new buf is requested.
1045 */
1046/* ARGSUSED */
1047static int
1048hdr_cons(void *vbuf, void *unused, int kmflag)
1049{
1050	arc_buf_hdr_t *hdr = vbuf;
1051
1052	bzero(hdr, sizeof (arc_buf_hdr_t));
1053	refcount_create(&hdr->b_refcnt);
1054	cv_init(&hdr->b_cv, NULL, CV_DEFAULT, NULL);
1055	mutex_init(&hdr->b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1056	arc_space_consume(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
1057
1058	return (0);
1059}
1060
1061/* ARGSUSED */
1062static int
1063buf_cons(void *vbuf, void *unused, int kmflag)
1064{
1065	arc_buf_t *buf = vbuf;
1066
1067	bzero(buf, sizeof (arc_buf_t));
1068	mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1069	arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1070
1071	return (0);
1072}
1073
1074/*
1075 * Destructor callback - called when a cached buf is
1076 * no longer required.
1077 */
1078/* ARGSUSED */
1079static void
1080hdr_dest(void *vbuf, void *unused)
1081{
1082	arc_buf_hdr_t *hdr = vbuf;
1083
1084	ASSERT(BUF_EMPTY(hdr));
1085	refcount_destroy(&hdr->b_refcnt);
1086	cv_destroy(&hdr->b_cv);
1087	mutex_destroy(&hdr->b_freeze_lock);
1088	arc_space_return(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
1089}
1090
1091/* ARGSUSED */
1092static void
1093buf_dest(void *vbuf, void *unused)
1094{
1095	arc_buf_t *buf = vbuf;
1096
1097	mutex_destroy(&buf->b_evict_lock);
1098	arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1099}
1100
1101/*
1102 * Reclaim callback -- invoked when memory is low.
1103 */
1104/* ARGSUSED */
1105static void
1106hdr_recl(void *unused)
1107{
1108	dprintf("hdr_recl called\n");
1109	/*
1110	 * umem calls the reclaim func when we destroy the buf cache,
1111	 * which is after we do arc_fini().
1112	 */
1113	if (!arc_dead)
1114		cv_signal(&arc_reclaim_thr_cv);
1115}
1116
1117static void
1118buf_init(void)
1119{
1120	uint64_t *ct;
1121	uint64_t hsize = 1ULL << 12;
1122	int i, j;
1123
1124	/*
1125	 * The hash table is big enough to fill all of physical memory
1126	 * with an average block size of zfs_arc_average_blocksize (default 8K).
1127	 * By default, the table will take up
1128	 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1129	 */
1130	while (hsize * zfs_arc_average_blocksize < (uint64_t)physmem * PAGESIZE)
1131		hsize <<= 1;
1132retry:
1133	buf_hash_table.ht_mask = hsize - 1;
1134	buf_hash_table.ht_table =
1135	    kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1136	if (buf_hash_table.ht_table == NULL) {
1137		ASSERT(hsize > (1ULL << 8));
1138		hsize >>= 1;
1139		goto retry;
1140	}
1141
1142	hdr_cache = kmem_cache_create("arc_buf_hdr_t", sizeof (arc_buf_hdr_t),
1143	    0, hdr_cons, hdr_dest, hdr_recl, NULL, NULL, 0);
1144	buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1145	    0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1146
1147	for (i = 0; i < 256; i++)
1148		for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1149			*ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1150
1151	for (i = 0; i < BUF_LOCKS; i++) {
1152		mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1153		    NULL, MUTEX_DEFAULT, NULL);
1154	}
1155}
1156
1157#define	ARC_MINTIME	(hz>>4) /* 62 ms */
1158
1159static void
1160arc_cksum_verify(arc_buf_t *buf)
1161{
1162	zio_cksum_t zc;
1163
1164	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1165		return;
1166
1167	mutex_enter(&buf->b_hdr->b_freeze_lock);
1168	if (buf->b_hdr->b_freeze_cksum == NULL ||
1169	    (buf->b_hdr->b_flags & ARC_FLAG_IO_ERROR)) {
1170		mutex_exit(&buf->b_hdr->b_freeze_lock);
1171		return;
1172	}
1173	fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1174	if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
1175		panic("buffer modified while frozen!");
1176	mutex_exit(&buf->b_hdr->b_freeze_lock);
1177}
1178
1179static int
1180arc_cksum_equal(arc_buf_t *buf)
1181{
1182	zio_cksum_t zc;
1183	int equal;
1184
1185	mutex_enter(&buf->b_hdr->b_freeze_lock);
1186	fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1187	equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
1188	mutex_exit(&buf->b_hdr->b_freeze_lock);
1189
1190	return (equal);
1191}
1192
1193static void
1194arc_cksum_compute(arc_buf_t *buf, boolean_t force)
1195{
1196	if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
1197		return;
1198
1199	mutex_enter(&buf->b_hdr->b_freeze_lock);
1200	if (buf->b_hdr->b_freeze_cksum != NULL) {
1201		mutex_exit(&buf->b_hdr->b_freeze_lock);
1202		return;
1203	}
1204	buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
1205	fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
1206	    buf->b_hdr->b_freeze_cksum);
1207	mutex_exit(&buf->b_hdr->b_freeze_lock);
1208#ifdef illumos
1209	arc_buf_watch(buf);
1210#endif /* illumos */
1211}
1212
1213#ifdef illumos
1214#ifndef _KERNEL
1215typedef struct procctl {
1216	long cmd;
1217	prwatch_t prwatch;
1218} procctl_t;
1219#endif
1220
1221/* ARGSUSED */
1222static void
1223arc_buf_unwatch(arc_buf_t *buf)
1224{
1225#ifndef _KERNEL
1226	if (arc_watch) {
1227		int result;
1228		procctl_t ctl;
1229		ctl.cmd = PCWATCH;
1230		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1231		ctl.prwatch.pr_size = 0;
1232		ctl.prwatch.pr_wflags = 0;
1233		result = write(arc_procfd, &ctl, sizeof (ctl));
1234		ASSERT3U(result, ==, sizeof (ctl));
1235	}
1236#endif
1237}
1238
1239/* ARGSUSED */
1240static void
1241arc_buf_watch(arc_buf_t *buf)
1242{
1243#ifndef _KERNEL
1244	if (arc_watch) {
1245		int result;
1246		procctl_t ctl;
1247		ctl.cmd = PCWATCH;
1248		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1249		ctl.prwatch.pr_size = buf->b_hdr->b_size;
1250		ctl.prwatch.pr_wflags = WA_WRITE;
1251		result = write(arc_procfd, &ctl, sizeof (ctl));
1252		ASSERT3U(result, ==, sizeof (ctl));
1253	}
1254#endif
1255}
1256#endif /* illumos */
1257
1258void
1259arc_buf_thaw(arc_buf_t *buf)
1260{
1261	if (zfs_flags & ZFS_DEBUG_MODIFY) {
1262		if (buf->b_hdr->b_state != arc_anon)
1263			panic("modifying non-anon buffer!");
1264		if (buf->b_hdr->b_flags & ARC_FLAG_IO_IN_PROGRESS)
1265			panic("modifying buffer while i/o in progress!");
1266		arc_cksum_verify(buf);
1267	}
1268
1269	mutex_enter(&buf->b_hdr->b_freeze_lock);
1270	if (buf->b_hdr->b_freeze_cksum != NULL) {
1271		kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1272		buf->b_hdr->b_freeze_cksum = NULL;
1273	}
1274
1275	if (zfs_flags & ZFS_DEBUG_MODIFY) {
1276		if (buf->b_hdr->b_thawed)
1277			kmem_free(buf->b_hdr->b_thawed, 1);
1278		buf->b_hdr->b_thawed = kmem_alloc(1, KM_SLEEP);
1279	}
1280
1281	mutex_exit(&buf->b_hdr->b_freeze_lock);
1282
1283#ifdef illumos
1284	arc_buf_unwatch(buf);
1285#endif /* illumos */
1286}
1287
1288void
1289arc_buf_freeze(arc_buf_t *buf)
1290{
1291	kmutex_t *hash_lock;
1292
1293	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1294		return;
1295
1296	hash_lock = HDR_LOCK(buf->b_hdr);
1297	mutex_enter(hash_lock);
1298
1299	ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
1300	    buf->b_hdr->b_state == arc_anon);
1301	arc_cksum_compute(buf, B_FALSE);
1302	mutex_exit(hash_lock);
1303
1304}
1305
1306static void
1307get_buf_info(arc_buf_hdr_t *hdr, arc_state_t *state, list_t **list, kmutex_t **lock)
1308{
1309	uint64_t buf_hashid = buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1310
1311	if (hdr->b_type == ARC_BUFC_METADATA)
1312		buf_hashid &= (ARC_BUFC_NUMMETADATALISTS - 1);
1313	else {
1314		buf_hashid &= (ARC_BUFC_NUMDATALISTS - 1);
1315		buf_hashid += ARC_BUFC_NUMMETADATALISTS;
1316	}
1317
1318	*list = &state->arcs_lists[buf_hashid];
1319	*lock = ARCS_LOCK(state, buf_hashid);
1320}
1321
1322
1323static void
1324add_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1325{
1326	ASSERT(MUTEX_HELD(hash_lock));
1327
1328	if ((refcount_add(&hdr->b_refcnt, tag) == 1) &&
1329	    (hdr->b_state != arc_anon)) {
1330		uint64_t delta = hdr->b_size * hdr->b_datacnt;
1331		uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
1332		list_t *list;
1333		kmutex_t *lock;
1334
1335		get_buf_info(hdr, hdr->b_state, &list, &lock);
1336		ASSERT(!MUTEX_HELD(lock));
1337		mutex_enter(lock);
1338		ASSERT(list_link_active(&hdr->b_arc_node));
1339		list_remove(list, hdr);
1340		if (GHOST_STATE(hdr->b_state)) {
1341			ASSERT0(hdr->b_datacnt);
1342			ASSERT3P(hdr->b_buf, ==, NULL);
1343			delta = hdr->b_size;
1344		}
1345		ASSERT(delta > 0);
1346		ASSERT3U(*size, >=, delta);
1347		atomic_add_64(size, -delta);
1348		mutex_exit(lock);
1349		/* remove the prefetch flag if we get a reference */
1350		if (hdr->b_flags & ARC_FLAG_PREFETCH)
1351			hdr->b_flags &= ~ARC_FLAG_PREFETCH;
1352	}
1353}
1354
1355static int
1356remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1357{
1358	int cnt;
1359	arc_state_t *state = hdr->b_state;
1360
1361	ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
1362	ASSERT(!GHOST_STATE(state));
1363
1364	if (((cnt = refcount_remove(&hdr->b_refcnt, tag)) == 0) &&
1365	    (state != arc_anon)) {
1366		uint64_t *size = &state->arcs_lsize[hdr->b_type];
1367		list_t *list;
1368		kmutex_t *lock;
1369
1370		get_buf_info(hdr, state, &list, &lock);
1371		ASSERT(!MUTEX_HELD(lock));
1372		mutex_enter(lock);
1373		ASSERT(!list_link_active(&hdr->b_arc_node));
1374		list_insert_head(list, hdr);
1375		ASSERT(hdr->b_datacnt > 0);
1376		atomic_add_64(size, hdr->b_size * hdr->b_datacnt);
1377		mutex_exit(lock);
1378	}
1379	return (cnt);
1380}
1381
1382/*
1383 * Move the supplied buffer to the indicated state.  The mutex
1384 * for the buffer must be held by the caller.
1385 */
1386static void
1387arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
1388    kmutex_t *hash_lock)
1389{
1390	arc_state_t *old_state = hdr->b_state;
1391	int64_t refcnt = refcount_count(&hdr->b_refcnt);
1392	uint64_t from_delta, to_delta;
1393	list_t *list;
1394	kmutex_t *lock;
1395
1396	ASSERT(MUTEX_HELD(hash_lock));
1397	ASSERT3P(new_state, !=, old_state);
1398	ASSERT(refcnt == 0 || hdr->b_datacnt > 0);
1399	ASSERT(hdr->b_datacnt == 0 || !GHOST_STATE(new_state));
1400	ASSERT(hdr->b_datacnt <= 1 || old_state != arc_anon);
1401
1402	from_delta = to_delta = hdr->b_datacnt * hdr->b_size;
1403
1404	/*
1405	 * If this buffer is evictable, transfer it from the
1406	 * old state list to the new state list.
1407	 */
1408	if (refcnt == 0) {
1409		if (old_state != arc_anon) {
1410			int use_mutex;
1411			uint64_t *size = &old_state->arcs_lsize[hdr->b_type];
1412
1413			get_buf_info(hdr, old_state, &list, &lock);
1414			use_mutex = !MUTEX_HELD(lock);
1415			if (use_mutex)
1416				mutex_enter(lock);
1417
1418			ASSERT(list_link_active(&hdr->b_arc_node));
1419			list_remove(list, hdr);
1420
1421			/*
1422			 * If prefetching out of the ghost cache,
1423			 * we will have a non-zero datacnt.
1424			 */
1425			if (GHOST_STATE(old_state) && hdr->b_datacnt == 0) {
1426				/* ghost elements have a ghost size */
1427				ASSERT(hdr->b_buf == NULL);
1428				from_delta = hdr->b_size;
1429			}
1430			ASSERT3U(*size, >=, from_delta);
1431			atomic_add_64(size, -from_delta);
1432
1433			if (use_mutex)
1434				mutex_exit(lock);
1435		}
1436		if (new_state != arc_anon) {
1437			int use_mutex;
1438			uint64_t *size = &new_state->arcs_lsize[hdr->b_type];
1439
1440			get_buf_info(hdr, new_state, &list, &lock);
1441			use_mutex = !MUTEX_HELD(lock);
1442			if (use_mutex)
1443				mutex_enter(lock);
1444
1445			list_insert_head(list, hdr);
1446
1447			/* ghost elements have a ghost size */
1448			if (GHOST_STATE(new_state)) {
1449				ASSERT(hdr->b_datacnt == 0);
1450				ASSERT(hdr->b_buf == NULL);
1451				to_delta = hdr->b_size;
1452			}
1453			atomic_add_64(size, to_delta);
1454
1455			if (use_mutex)
1456				mutex_exit(lock);
1457		}
1458	}
1459
1460	ASSERT(!BUF_EMPTY(hdr));
1461	if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
1462		buf_hash_remove(hdr);
1463
1464	/* adjust state sizes */
1465	if (to_delta)
1466		atomic_add_64(&new_state->arcs_size, to_delta);
1467	if (from_delta) {
1468		ASSERT3U(old_state->arcs_size, >=, from_delta);
1469		atomic_add_64(&old_state->arcs_size, -from_delta);
1470	}
1471	hdr->b_state = new_state;
1472
1473	/* adjust l2arc hdr stats */
1474	if (new_state == arc_l2c_only)
1475		l2arc_hdr_stat_add();
1476	else if (old_state == arc_l2c_only)
1477		l2arc_hdr_stat_remove();
1478}
1479
1480void
1481arc_space_consume(uint64_t space, arc_space_type_t type)
1482{
1483	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1484
1485	switch (type) {
1486	case ARC_SPACE_DATA:
1487		ARCSTAT_INCR(arcstat_data_size, space);
1488		break;
1489	case ARC_SPACE_OTHER:
1490		ARCSTAT_INCR(arcstat_other_size, space);
1491		break;
1492	case ARC_SPACE_HDRS:
1493		ARCSTAT_INCR(arcstat_hdr_size, space);
1494		break;
1495	case ARC_SPACE_L2HDRS:
1496		ARCSTAT_INCR(arcstat_l2_hdr_size, space);
1497		break;
1498	}
1499
1500	ARCSTAT_INCR(arcstat_meta_used, space);
1501	atomic_add_64(&arc_size, space);
1502}
1503
1504void
1505arc_space_return(uint64_t space, arc_space_type_t type)
1506{
1507	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1508
1509	switch (type) {
1510	case ARC_SPACE_DATA:
1511		ARCSTAT_INCR(arcstat_data_size, -space);
1512		break;
1513	case ARC_SPACE_OTHER:
1514		ARCSTAT_INCR(arcstat_other_size, -space);
1515		break;
1516	case ARC_SPACE_HDRS:
1517		ARCSTAT_INCR(arcstat_hdr_size, -space);
1518		break;
1519	case ARC_SPACE_L2HDRS:
1520		ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
1521		break;
1522	}
1523
1524	ASSERT(arc_meta_used >= space);
1525	if (arc_meta_max < arc_meta_used)
1526		arc_meta_max = arc_meta_used;
1527	ARCSTAT_INCR(arcstat_meta_used, -space);
1528	ASSERT(arc_size >= space);
1529	atomic_add_64(&arc_size, -space);
1530}
1531
1532arc_buf_t *
1533arc_buf_alloc(spa_t *spa, int size, void *tag, arc_buf_contents_t type)
1534{
1535	arc_buf_hdr_t *hdr;
1536	arc_buf_t *buf;
1537
1538	ASSERT3U(size, >, 0);
1539	hdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
1540	ASSERT(BUF_EMPTY(hdr));
1541	hdr->b_size = size;
1542	hdr->b_type = type;
1543	hdr->b_spa = spa_load_guid(spa);
1544	hdr->b_state = arc_anon;
1545	hdr->b_arc_access = 0;
1546	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1547	buf->b_hdr = hdr;
1548	buf->b_data = NULL;
1549	buf->b_efunc = NULL;
1550	buf->b_private = NULL;
1551	buf->b_next = NULL;
1552	hdr->b_buf = buf;
1553	arc_get_data_buf(buf);
1554	hdr->b_datacnt = 1;
1555	hdr->b_flags = 0;
1556	ASSERT(refcount_is_zero(&hdr->b_refcnt));
1557	(void) refcount_add(&hdr->b_refcnt, tag);
1558
1559	return (buf);
1560}
1561
1562static char *arc_onloan_tag = "onloan";
1563
1564/*
1565 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
1566 * flight data by arc_tempreserve_space() until they are "returned". Loaned
1567 * buffers must be returned to the arc before they can be used by the DMU or
1568 * freed.
1569 */
1570arc_buf_t *
1571arc_loan_buf(spa_t *spa, int size)
1572{
1573	arc_buf_t *buf;
1574
1575	buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
1576
1577	atomic_add_64(&arc_loaned_bytes, size);
1578	return (buf);
1579}
1580
1581/*
1582 * Return a loaned arc buffer to the arc.
1583 */
1584void
1585arc_return_buf(arc_buf_t *buf, void *tag)
1586{
1587	arc_buf_hdr_t *hdr = buf->b_hdr;
1588
1589	ASSERT(buf->b_data != NULL);
1590	(void) refcount_add(&hdr->b_refcnt, tag);
1591	(void) refcount_remove(&hdr->b_refcnt, arc_onloan_tag);
1592
1593	atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
1594}
1595
1596/* Detach an arc_buf from a dbuf (tag) */
1597void
1598arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
1599{
1600	arc_buf_hdr_t *hdr;
1601
1602	ASSERT(buf->b_data != NULL);
1603	hdr = buf->b_hdr;
1604	(void) refcount_add(&hdr->b_refcnt, arc_onloan_tag);
1605	(void) refcount_remove(&hdr->b_refcnt, tag);
1606	buf->b_efunc = NULL;
1607	buf->b_private = NULL;
1608
1609	atomic_add_64(&arc_loaned_bytes, hdr->b_size);
1610}
1611
1612static arc_buf_t *
1613arc_buf_clone(arc_buf_t *from)
1614{
1615	arc_buf_t *buf;
1616	arc_buf_hdr_t *hdr = from->b_hdr;
1617	uint64_t size = hdr->b_size;
1618
1619	ASSERT(hdr->b_state != arc_anon);
1620
1621	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1622	buf->b_hdr = hdr;
1623	buf->b_data = NULL;
1624	buf->b_efunc = NULL;
1625	buf->b_private = NULL;
1626	buf->b_next = hdr->b_buf;
1627	hdr->b_buf = buf;
1628	arc_get_data_buf(buf);
1629	bcopy(from->b_data, buf->b_data, size);
1630
1631	/*
1632	 * This buffer already exists in the arc so create a duplicate
1633	 * copy for the caller.  If the buffer is associated with user data
1634	 * then track the size and number of duplicates.  These stats will be
1635	 * updated as duplicate buffers are created and destroyed.
1636	 */
1637	if (hdr->b_type == ARC_BUFC_DATA) {
1638		ARCSTAT_BUMP(arcstat_duplicate_buffers);
1639		ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
1640	}
1641	hdr->b_datacnt += 1;
1642	return (buf);
1643}
1644
1645void
1646arc_buf_add_ref(arc_buf_t *buf, void* tag)
1647{
1648	arc_buf_hdr_t *hdr;
1649	kmutex_t *hash_lock;
1650
1651	/*
1652	 * Check to see if this buffer is evicted.  Callers
1653	 * must verify b_data != NULL to know if the add_ref
1654	 * was successful.
1655	 */
1656	mutex_enter(&buf->b_evict_lock);
1657	if (buf->b_data == NULL) {
1658		mutex_exit(&buf->b_evict_lock);
1659		return;
1660	}
1661	hash_lock = HDR_LOCK(buf->b_hdr);
1662	mutex_enter(hash_lock);
1663	hdr = buf->b_hdr;
1664	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1665	mutex_exit(&buf->b_evict_lock);
1666
1667	ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
1668	add_reference(hdr, hash_lock, tag);
1669	DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
1670	arc_access(hdr, hash_lock);
1671	mutex_exit(hash_lock);
1672	ARCSTAT_BUMP(arcstat_hits);
1673	ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_FLAG_PREFETCH),
1674	    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
1675	    data, metadata, hits);
1676}
1677
1678static void
1679arc_buf_free_on_write(void *data, size_t size,
1680    void (*free_func)(void *, size_t))
1681{
1682	l2arc_data_free_t *df;
1683
1684	df = kmem_alloc(sizeof (l2arc_data_free_t), KM_SLEEP);
1685	df->l2df_data = data;
1686	df->l2df_size = size;
1687	df->l2df_func = free_func;
1688	mutex_enter(&l2arc_free_on_write_mtx);
1689	list_insert_head(l2arc_free_on_write, df);
1690	mutex_exit(&l2arc_free_on_write_mtx);
1691}
1692
1693/*
1694 * Free the arc data buffer.  If it is an l2arc write in progress,
1695 * the buffer is placed on l2arc_free_on_write to be freed later.
1696 */
1697static void
1698arc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
1699{
1700	arc_buf_hdr_t *hdr = buf->b_hdr;
1701
1702	if (HDR_L2_WRITING(hdr)) {
1703		arc_buf_free_on_write(buf->b_data, hdr->b_size, free_func);
1704		ARCSTAT_BUMP(arcstat_l2_free_on_write);
1705	} else {
1706		free_func(buf->b_data, hdr->b_size);
1707	}
1708}
1709
1710/*
1711 * Free up buf->b_data and if 'remove' is set, then pull the
1712 * arc_buf_t off of the the arc_buf_hdr_t's list and free it.
1713 */
1714static void
1715arc_buf_l2_cdata_free(arc_buf_hdr_t *hdr)
1716{
1717	l2arc_buf_hdr_t *l2hdr = hdr->b_l2hdr;
1718
1719	ASSERT(MUTEX_HELD(&l2arc_buflist_mtx));
1720
1721	if (l2hdr->b_tmp_cdata == NULL)
1722		return;
1723
1724	ASSERT(HDR_L2_WRITING(hdr));
1725	arc_buf_free_on_write(l2hdr->b_tmp_cdata, hdr->b_size,
1726	    zio_data_buf_free);
1727	ARCSTAT_BUMP(arcstat_l2_cdata_free_on_write);
1728	l2hdr->b_tmp_cdata = NULL;
1729}
1730
1731static void
1732arc_buf_destroy(arc_buf_t *buf, boolean_t recycle, boolean_t remove)
1733{
1734	arc_buf_t **bufp;
1735
1736	/* free up data associated with the buf */
1737	if (buf->b_data) {
1738		arc_state_t *state = buf->b_hdr->b_state;
1739		uint64_t size = buf->b_hdr->b_size;
1740		arc_buf_contents_t type = buf->b_hdr->b_type;
1741
1742		arc_cksum_verify(buf);
1743#ifdef illumos
1744		arc_buf_unwatch(buf);
1745#endif /* illumos */
1746
1747		if (!recycle) {
1748			if (type == ARC_BUFC_METADATA) {
1749				arc_buf_data_free(buf, zio_buf_free);
1750				arc_space_return(size, ARC_SPACE_DATA);
1751			} else {
1752				ASSERT(type == ARC_BUFC_DATA);
1753				arc_buf_data_free(buf, zio_data_buf_free);
1754				ARCSTAT_INCR(arcstat_data_size, -size);
1755				atomic_add_64(&arc_size, -size);
1756			}
1757		}
1758		if (list_link_active(&buf->b_hdr->b_arc_node)) {
1759			uint64_t *cnt = &state->arcs_lsize[type];
1760
1761			ASSERT(refcount_is_zero(&buf->b_hdr->b_refcnt));
1762			ASSERT(state != arc_anon);
1763
1764			ASSERT3U(*cnt, >=, size);
1765			atomic_add_64(cnt, -size);
1766		}
1767		ASSERT3U(state->arcs_size, >=, size);
1768		atomic_add_64(&state->arcs_size, -size);
1769		buf->b_data = NULL;
1770
1771		/*
1772		 * If we're destroying a duplicate buffer make sure
1773		 * that the appropriate statistics are updated.
1774		 */
1775		if (buf->b_hdr->b_datacnt > 1 &&
1776		    buf->b_hdr->b_type == ARC_BUFC_DATA) {
1777			ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
1778			ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
1779		}
1780		ASSERT(buf->b_hdr->b_datacnt > 0);
1781		buf->b_hdr->b_datacnt -= 1;
1782	}
1783
1784	/* only remove the buf if requested */
1785	if (!remove)
1786		return;
1787
1788	/* remove the buf from the hdr list */
1789	for (bufp = &buf->b_hdr->b_buf; *bufp != buf; bufp = &(*bufp)->b_next)
1790		continue;
1791	*bufp = buf->b_next;
1792	buf->b_next = NULL;
1793
1794	ASSERT(buf->b_efunc == NULL);
1795
1796	/* clean up the buf */
1797	buf->b_hdr = NULL;
1798	kmem_cache_free(buf_cache, buf);
1799}
1800
1801static void
1802arc_hdr_destroy(arc_buf_hdr_t *hdr)
1803{
1804	ASSERT(refcount_is_zero(&hdr->b_refcnt));
1805	ASSERT3P(hdr->b_state, ==, arc_anon);
1806	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1807	l2arc_buf_hdr_t *l2hdr = hdr->b_l2hdr;
1808
1809	if (l2hdr != NULL) {
1810		boolean_t buflist_held = MUTEX_HELD(&l2arc_buflist_mtx);
1811		/*
1812		 * To prevent arc_free() and l2arc_evict() from
1813		 * attempting to free the same buffer at the same time,
1814		 * a FREE_IN_PROGRESS flag is given to arc_free() to
1815		 * give it priority.  l2arc_evict() can't destroy this
1816		 * header while we are waiting on l2arc_buflist_mtx.
1817		 *
1818		 * The hdr may be removed from l2ad_buflist before we
1819		 * grab l2arc_buflist_mtx, so b_l2hdr is rechecked.
1820		 */
1821		if (!buflist_held) {
1822			mutex_enter(&l2arc_buflist_mtx);
1823			l2hdr = hdr->b_l2hdr;
1824		}
1825
1826		if (l2hdr != NULL) {
1827			trim_map_free(l2hdr->b_dev->l2ad_vdev, l2hdr->b_daddr,
1828			    hdr->b_size, 0);
1829			list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
1830			arc_buf_l2_cdata_free(hdr);
1831			ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
1832			ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
1833			vdev_space_update(l2hdr->b_dev->l2ad_vdev,
1834			    -l2hdr->b_asize, 0, 0);
1835			kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
1836			if (hdr->b_state == arc_l2c_only)
1837				l2arc_hdr_stat_remove();
1838			hdr->b_l2hdr = NULL;
1839		}
1840
1841		if (!buflist_held)
1842			mutex_exit(&l2arc_buflist_mtx);
1843	}
1844
1845	if (!BUF_EMPTY(hdr)) {
1846		ASSERT(!HDR_IN_HASH_TABLE(hdr));
1847		buf_discard_identity(hdr);
1848	}
1849	while (hdr->b_buf) {
1850		arc_buf_t *buf = hdr->b_buf;
1851
1852		if (buf->b_efunc) {
1853			mutex_enter(&arc_eviction_mtx);
1854			mutex_enter(&buf->b_evict_lock);
1855			ASSERT(buf->b_hdr != NULL);
1856			arc_buf_destroy(hdr->b_buf, FALSE, FALSE);
1857			hdr->b_buf = buf->b_next;
1858			buf->b_hdr = &arc_eviction_hdr;
1859			buf->b_next = arc_eviction_list;
1860			arc_eviction_list = buf;
1861			mutex_exit(&buf->b_evict_lock);
1862			mutex_exit(&arc_eviction_mtx);
1863		} else {
1864			arc_buf_destroy(hdr->b_buf, FALSE, TRUE);
1865		}
1866	}
1867	if (hdr->b_freeze_cksum != NULL) {
1868		kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1869		hdr->b_freeze_cksum = NULL;
1870	}
1871	if (hdr->b_thawed) {
1872		kmem_free(hdr->b_thawed, 1);
1873		hdr->b_thawed = NULL;
1874	}
1875
1876	ASSERT(!list_link_active(&hdr->b_arc_node));
1877	ASSERT3P(hdr->b_hash_next, ==, NULL);
1878	ASSERT3P(hdr->b_acb, ==, NULL);
1879	kmem_cache_free(hdr_cache, hdr);
1880}
1881
1882void
1883arc_buf_free(arc_buf_t *buf, void *tag)
1884{
1885	arc_buf_hdr_t *hdr = buf->b_hdr;
1886	int hashed = hdr->b_state != arc_anon;
1887
1888	ASSERT(buf->b_efunc == NULL);
1889	ASSERT(buf->b_data != NULL);
1890
1891	if (hashed) {
1892		kmutex_t *hash_lock = HDR_LOCK(hdr);
1893
1894		mutex_enter(hash_lock);
1895		hdr = buf->b_hdr;
1896		ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1897
1898		(void) remove_reference(hdr, hash_lock, tag);
1899		if (hdr->b_datacnt > 1) {
1900			arc_buf_destroy(buf, FALSE, TRUE);
1901		} else {
1902			ASSERT(buf == hdr->b_buf);
1903			ASSERT(buf->b_efunc == NULL);
1904			hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
1905		}
1906		mutex_exit(hash_lock);
1907	} else if (HDR_IO_IN_PROGRESS(hdr)) {
1908		int destroy_hdr;
1909		/*
1910		 * We are in the middle of an async write.  Don't destroy
1911		 * this buffer unless the write completes before we finish
1912		 * decrementing the reference count.
1913		 */
1914		mutex_enter(&arc_eviction_mtx);
1915		(void) remove_reference(hdr, NULL, tag);
1916		ASSERT(refcount_is_zero(&hdr->b_refcnt));
1917		destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
1918		mutex_exit(&arc_eviction_mtx);
1919		if (destroy_hdr)
1920			arc_hdr_destroy(hdr);
1921	} else {
1922		if (remove_reference(hdr, NULL, tag) > 0)
1923			arc_buf_destroy(buf, FALSE, TRUE);
1924		else
1925			arc_hdr_destroy(hdr);
1926	}
1927}
1928
1929boolean_t
1930arc_buf_remove_ref(arc_buf_t *buf, void* tag)
1931{
1932	arc_buf_hdr_t *hdr = buf->b_hdr;
1933	kmutex_t *hash_lock = HDR_LOCK(hdr);
1934	boolean_t no_callback = (buf->b_efunc == NULL);
1935
1936	if (hdr->b_state == arc_anon) {
1937		ASSERT(hdr->b_datacnt == 1);
1938		arc_buf_free(buf, tag);
1939		return (no_callback);
1940	}
1941
1942	mutex_enter(hash_lock);
1943	hdr = buf->b_hdr;
1944	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1945	ASSERT(hdr->b_state != arc_anon);
1946	ASSERT(buf->b_data != NULL);
1947
1948	(void) remove_reference(hdr, hash_lock, tag);
1949	if (hdr->b_datacnt > 1) {
1950		if (no_callback)
1951			arc_buf_destroy(buf, FALSE, TRUE);
1952	} else if (no_callback) {
1953		ASSERT(hdr->b_buf == buf && buf->b_next == NULL);
1954		ASSERT(buf->b_efunc == NULL);
1955		hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
1956	}
1957	ASSERT(no_callback || hdr->b_datacnt > 1 ||
1958	    refcount_is_zero(&hdr->b_refcnt));
1959	mutex_exit(hash_lock);
1960	return (no_callback);
1961}
1962
1963int
1964arc_buf_size(arc_buf_t *buf)
1965{
1966	return (buf->b_hdr->b_size);
1967}
1968
1969/*
1970 * Called from the DMU to determine if the current buffer should be
1971 * evicted. In order to ensure proper locking, the eviction must be initiated
1972 * from the DMU. Return true if the buffer is associated with user data and
1973 * duplicate buffers still exist.
1974 */
1975boolean_t
1976arc_buf_eviction_needed(arc_buf_t *buf)
1977{
1978	arc_buf_hdr_t *hdr;
1979	boolean_t evict_needed = B_FALSE;
1980
1981	if (zfs_disable_dup_eviction)
1982		return (B_FALSE);
1983
1984	mutex_enter(&buf->b_evict_lock);
1985	hdr = buf->b_hdr;
1986	if (hdr == NULL) {
1987		/*
1988		 * We are in arc_do_user_evicts(); let that function
1989		 * perform the eviction.
1990		 */
1991		ASSERT(buf->b_data == NULL);
1992		mutex_exit(&buf->b_evict_lock);
1993		return (B_FALSE);
1994	} else if (buf->b_data == NULL) {
1995		/*
1996		 * We have already been added to the arc eviction list;
1997		 * recommend eviction.
1998		 */
1999		ASSERT3P(hdr, ==, &arc_eviction_hdr);
2000		mutex_exit(&buf->b_evict_lock);
2001		return (B_TRUE);
2002	}
2003
2004	if (hdr->b_datacnt > 1 && hdr->b_type == ARC_BUFC_DATA)
2005		evict_needed = B_TRUE;
2006
2007	mutex_exit(&buf->b_evict_lock);
2008	return (evict_needed);
2009}
2010
2011/*
2012 * Evict buffers from list until we've removed the specified number of
2013 * bytes.  Move the removed buffers to the appropriate evict state.
2014 * If the recycle flag is set, then attempt to "recycle" a buffer:
2015 * - look for a buffer to evict that is `bytes' long.
2016 * - return the data block from this buffer rather than freeing it.
2017 * This flag is used by callers that are trying to make space for a
2018 * new buffer in a full arc cache.
2019 *
2020 * This function makes a "best effort".  It skips over any buffers
2021 * it can't get a hash_lock on, and so may not catch all candidates.
2022 * It may also return without evicting as much space as requested.
2023 */
2024static void *
2025arc_evict(arc_state_t *state, uint64_t spa, int64_t bytes, boolean_t recycle,
2026    arc_buf_contents_t type)
2027{
2028	arc_state_t *evicted_state;
2029	uint64_t bytes_evicted = 0, skipped = 0, missed = 0;
2030	int64_t bytes_remaining;
2031	arc_buf_hdr_t *hdr, *hdr_prev = NULL;
2032	list_t *evicted_list, *list, *evicted_list_start, *list_start;
2033	kmutex_t *lock, *evicted_lock;
2034	kmutex_t *hash_lock;
2035	boolean_t have_lock;
2036	void *stolen = NULL;
2037	arc_buf_hdr_t marker = { 0 };
2038	int count = 0;
2039	static int evict_metadata_offset, evict_data_offset;
2040	int i, idx, offset, list_count, lists;
2041
2042	ASSERT(state == arc_mru || state == arc_mfu);
2043
2044	evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
2045
2046	/*
2047	 * Decide which "type" (data vs metadata) to recycle from.
2048	 *
2049	 * If we are over the metadata limit, recycle from metadata.
2050	 * If we are under the metadata minimum, recycle from data.
2051	 * Otherwise, recycle from whichever type has the oldest (least
2052	 * recently accessed) header.  This is not yet implemented.
2053	 */
2054	if (recycle) {
2055		arc_buf_contents_t realtype;
2056		if (state->arcs_lsize[ARC_BUFC_DATA] == 0) {
2057			realtype = ARC_BUFC_METADATA;
2058		} else if (state->arcs_lsize[ARC_BUFC_METADATA] == 0) {
2059			realtype = ARC_BUFC_DATA;
2060		} else if (arc_meta_used >= arc_meta_limit) {
2061			realtype = ARC_BUFC_METADATA;
2062		} else if (arc_meta_used <= arc_meta_min) {
2063			realtype = ARC_BUFC_DATA;
2064		} else {
2065#ifdef illumos
2066			if (data_hdr->b_arc_access <
2067			    metadata_hdr->b_arc_access) {
2068				realtype = ARC_BUFC_DATA;
2069			} else {
2070				realtype = ARC_BUFC_METADATA;
2071			}
2072#else
2073			/* TODO */
2074			realtype = type;
2075#endif
2076		}
2077		if (realtype != type) {
2078			/*
2079			 * If we want to evict from a different list,
2080			 * we can not recycle, because DATA vs METADATA
2081			 * buffers are segregated into different kmem
2082			 * caches (and vmem arenas).
2083			 */
2084			type = realtype;
2085			recycle = B_FALSE;
2086		}
2087	}
2088
2089	if (type == ARC_BUFC_METADATA) {
2090		offset = 0;
2091		list_count = ARC_BUFC_NUMMETADATALISTS;
2092		list_start = &state->arcs_lists[0];
2093		evicted_list_start = &evicted_state->arcs_lists[0];
2094		idx = evict_metadata_offset;
2095	} else {
2096		offset = ARC_BUFC_NUMMETADATALISTS;
2097		list_start = &state->arcs_lists[offset];
2098		evicted_list_start = &evicted_state->arcs_lists[offset];
2099		list_count = ARC_BUFC_NUMDATALISTS;
2100		idx = evict_data_offset;
2101	}
2102	bytes_remaining = evicted_state->arcs_lsize[type];
2103	lists = 0;
2104
2105evict_start:
2106	list = &list_start[idx];
2107	evicted_list = &evicted_list_start[idx];
2108	lock = ARCS_LOCK(state, (offset + idx));
2109	evicted_lock = ARCS_LOCK(evicted_state, (offset + idx));
2110
2111	mutex_enter(lock);
2112	mutex_enter(evicted_lock);
2113
2114	for (hdr = list_tail(list); hdr; hdr = hdr_prev) {
2115		hdr_prev = list_prev(list, hdr);
2116		bytes_remaining -= (hdr->b_size * hdr->b_datacnt);
2117		/* prefetch buffers have a minimum lifespan */
2118		if (HDR_IO_IN_PROGRESS(hdr) ||
2119		    (spa && hdr->b_spa != spa) ||
2120		    (hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT) &&
2121		    ddi_get_lbolt() - hdr->b_arc_access <
2122		    arc_min_prefetch_lifespan)) {
2123			skipped++;
2124			continue;
2125		}
2126		/* "lookahead" for better eviction candidate */
2127		if (recycle && hdr->b_size != bytes &&
2128		    hdr_prev && hdr_prev->b_size == bytes)
2129			continue;
2130
2131		/* ignore markers */
2132		if (hdr->b_spa == 0)
2133			continue;
2134
2135		/*
2136		 * It may take a long time to evict all the bufs requested.
2137		 * To avoid blocking all arc activity, periodically drop
2138		 * the arcs_mtx and give other threads a chance to run
2139		 * before reacquiring the lock.
2140		 *
2141		 * If we are looking for a buffer to recycle, we are in
2142		 * the hot code path, so don't sleep.
2143		 */
2144		if (!recycle && count++ > arc_evict_iterations) {
2145			list_insert_after(list, hdr, &marker);
2146			mutex_exit(evicted_lock);
2147			mutex_exit(lock);
2148			kpreempt(KPREEMPT_SYNC);
2149			mutex_enter(lock);
2150			mutex_enter(evicted_lock);
2151			hdr_prev = list_prev(list, &marker);
2152			list_remove(list, &marker);
2153			count = 0;
2154			continue;
2155		}
2156
2157		hash_lock = HDR_LOCK(hdr);
2158		have_lock = MUTEX_HELD(hash_lock);
2159		if (have_lock || mutex_tryenter(hash_lock)) {
2160			ASSERT0(refcount_count(&hdr->b_refcnt));
2161			ASSERT(hdr->b_datacnt > 0);
2162			while (hdr->b_buf) {
2163				arc_buf_t *buf = hdr->b_buf;
2164				if (!mutex_tryenter(&buf->b_evict_lock)) {
2165					missed += 1;
2166					break;
2167				}
2168				if (buf->b_data) {
2169					bytes_evicted += hdr->b_size;
2170					if (recycle && hdr->b_type == type &&
2171					    hdr->b_size == bytes &&
2172					    !HDR_L2_WRITING(hdr)) {
2173						stolen = buf->b_data;
2174						recycle = FALSE;
2175					}
2176				}
2177				if (buf->b_efunc) {
2178					mutex_enter(&arc_eviction_mtx);
2179					arc_buf_destroy(buf,
2180					    buf->b_data == stolen, FALSE);
2181					hdr->b_buf = buf->b_next;
2182					buf->b_hdr = &arc_eviction_hdr;
2183					buf->b_next = arc_eviction_list;
2184					arc_eviction_list = buf;
2185					mutex_exit(&arc_eviction_mtx);
2186					mutex_exit(&buf->b_evict_lock);
2187				} else {
2188					mutex_exit(&buf->b_evict_lock);
2189					arc_buf_destroy(buf,
2190					    buf->b_data == stolen, TRUE);
2191				}
2192			}
2193
2194			if (hdr->b_l2hdr) {
2195				ARCSTAT_INCR(arcstat_evict_l2_cached,
2196				    hdr->b_size);
2197			} else {
2198				if (l2arc_write_eligible(hdr->b_spa, hdr)) {
2199					ARCSTAT_INCR(arcstat_evict_l2_eligible,
2200					    hdr->b_size);
2201				} else {
2202					ARCSTAT_INCR(
2203					    arcstat_evict_l2_ineligible,
2204					    hdr->b_size);
2205				}
2206			}
2207
2208			if (hdr->b_datacnt == 0) {
2209				arc_change_state(evicted_state, hdr, hash_lock);
2210				ASSERT(HDR_IN_HASH_TABLE(hdr));
2211				hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
2212				hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
2213				DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
2214			}
2215			if (!have_lock)
2216				mutex_exit(hash_lock);
2217			if (bytes >= 0 && bytes_evicted >= bytes)
2218				break;
2219			if (bytes_remaining > 0) {
2220				mutex_exit(evicted_lock);
2221				mutex_exit(lock);
2222				idx  = ((idx + 1) & (list_count - 1));
2223				lists++;
2224				goto evict_start;
2225			}
2226		} else {
2227			missed += 1;
2228		}
2229	}
2230
2231	mutex_exit(evicted_lock);
2232	mutex_exit(lock);
2233
2234	idx  = ((idx + 1) & (list_count - 1));
2235	lists++;
2236
2237	if (bytes_evicted < bytes) {
2238		if (lists < list_count)
2239			goto evict_start;
2240		else
2241			dprintf("only evicted %lld bytes from %x",
2242			    (longlong_t)bytes_evicted, state);
2243	}
2244	if (type == ARC_BUFC_METADATA)
2245		evict_metadata_offset = idx;
2246	else
2247		evict_data_offset = idx;
2248
2249	if (skipped)
2250		ARCSTAT_INCR(arcstat_evict_skip, skipped);
2251
2252	if (missed)
2253		ARCSTAT_INCR(arcstat_mutex_miss, missed);
2254
2255	/*
2256	 * Note: we have just evicted some data into the ghost state,
2257	 * potentially putting the ghost size over the desired size.  Rather
2258	 * that evicting from the ghost list in this hot code path, leave
2259	 * this chore to the arc_reclaim_thread().
2260	 */
2261
2262	if (stolen)
2263		ARCSTAT_BUMP(arcstat_stolen);
2264	return (stolen);
2265}
2266
2267/*
2268 * Remove buffers from list until we've removed the specified number of
2269 * bytes.  Destroy the buffers that are removed.
2270 */
2271static void
2272arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes)
2273{
2274	arc_buf_hdr_t *hdr, *hdr_prev;
2275	arc_buf_hdr_t marker = { 0 };
2276	list_t *list, *list_start;
2277	kmutex_t *hash_lock, *lock;
2278	uint64_t bytes_deleted = 0;
2279	uint64_t bufs_skipped = 0;
2280	int count = 0;
2281	static int evict_offset;
2282	int list_count, idx = evict_offset;
2283	int offset, lists = 0;
2284
2285	ASSERT(GHOST_STATE(state));
2286
2287	/*
2288	 * data lists come after metadata lists
2289	 */
2290	list_start = &state->arcs_lists[ARC_BUFC_NUMMETADATALISTS];
2291	list_count = ARC_BUFC_NUMDATALISTS;
2292	offset = ARC_BUFC_NUMMETADATALISTS;
2293
2294evict_start:
2295	list = &list_start[idx];
2296	lock = ARCS_LOCK(state, idx + offset);
2297
2298	mutex_enter(lock);
2299	for (hdr = list_tail(list); hdr; hdr = hdr_prev) {
2300		hdr_prev = list_prev(list, hdr);
2301		if (hdr->b_type > ARC_BUFC_NUMTYPES)
2302			panic("invalid hdr=%p", (void *)hdr);
2303		if (spa && hdr->b_spa != spa)
2304			continue;
2305
2306		/* ignore markers */
2307		if (hdr->b_spa == 0)
2308			continue;
2309
2310		hash_lock = HDR_LOCK(hdr);
2311		/* caller may be trying to modify this buffer, skip it */
2312		if (MUTEX_HELD(hash_lock))
2313			continue;
2314
2315		/*
2316		 * It may take a long time to evict all the bufs requested.
2317		 * To avoid blocking all arc activity, periodically drop
2318		 * the arcs_mtx and give other threads a chance to run
2319		 * before reacquiring the lock.
2320		 */
2321		if (count++ > arc_evict_iterations) {
2322			list_insert_after(list, hdr, &marker);
2323			mutex_exit(lock);
2324			kpreempt(KPREEMPT_SYNC);
2325			mutex_enter(lock);
2326			hdr_prev = list_prev(list, &marker);
2327			list_remove(list, &marker);
2328			count = 0;
2329			continue;
2330		}
2331		if (mutex_tryenter(hash_lock)) {
2332			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2333			ASSERT(hdr->b_buf == NULL);
2334			ARCSTAT_BUMP(arcstat_deleted);
2335			bytes_deleted += hdr->b_size;
2336
2337			if (hdr->b_l2hdr != NULL) {
2338				/*
2339				 * This buffer is cached on the 2nd Level ARC;
2340				 * don't destroy the header.
2341				 */
2342				arc_change_state(arc_l2c_only, hdr, hash_lock);
2343				mutex_exit(hash_lock);
2344			} else {
2345				arc_change_state(arc_anon, hdr, hash_lock);
2346				mutex_exit(hash_lock);
2347				arc_hdr_destroy(hdr);
2348			}
2349
2350			DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
2351			if (bytes >= 0 && bytes_deleted >= bytes)
2352				break;
2353		} else if (bytes < 0) {
2354			/*
2355			 * Insert a list marker and then wait for the
2356			 * hash lock to become available. Once its
2357			 * available, restart from where we left off.
2358			 */
2359			list_insert_after(list, hdr, &marker);
2360			mutex_exit(lock);
2361			mutex_enter(hash_lock);
2362			mutex_exit(hash_lock);
2363			mutex_enter(lock);
2364			hdr_prev = list_prev(list, &marker);
2365			list_remove(list, &marker);
2366		} else {
2367			bufs_skipped += 1;
2368		}
2369
2370	}
2371	mutex_exit(lock);
2372	idx  = ((idx + 1) & (ARC_BUFC_NUMDATALISTS - 1));
2373	lists++;
2374
2375	if (lists < list_count)
2376		goto evict_start;
2377
2378	evict_offset = idx;
2379	if ((uintptr_t)list > (uintptr_t)&state->arcs_lists[ARC_BUFC_NUMMETADATALISTS] &&
2380	    (bytes < 0 || bytes_deleted < bytes)) {
2381		list_start = &state->arcs_lists[0];
2382		list_count = ARC_BUFC_NUMMETADATALISTS;
2383		offset = lists = 0;
2384		goto evict_start;
2385	}
2386
2387	if (bufs_skipped) {
2388		ARCSTAT_INCR(arcstat_mutex_miss, bufs_skipped);
2389		ASSERT(bytes >= 0);
2390	}
2391
2392	if (bytes_deleted < bytes)
2393		dprintf("only deleted %lld bytes from %p",
2394		    (longlong_t)bytes_deleted, state);
2395}
2396
2397static void
2398arc_adjust(void)
2399{
2400	int64_t adjustment, delta;
2401
2402	/*
2403	 * Adjust MRU size
2404	 */
2405
2406	adjustment = MIN((int64_t)(arc_size - arc_c),
2407	    (int64_t)(arc_anon->arcs_size + arc_mru->arcs_size + arc_meta_used -
2408	    arc_p));
2409
2410	if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_DATA] > 0) {
2411		delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_DATA], adjustment);
2412		(void) arc_evict(arc_mru, 0, delta, FALSE, ARC_BUFC_DATA);
2413		adjustment -= delta;
2414	}
2415
2416	if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2417		delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_METADATA], adjustment);
2418		(void) arc_evict(arc_mru, 0, delta, FALSE,
2419		    ARC_BUFC_METADATA);
2420	}
2421
2422	/*
2423	 * Adjust MFU size
2424	 */
2425
2426	adjustment = arc_size - arc_c;
2427
2428	if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_DATA] > 0) {
2429		delta = MIN(adjustment, arc_mfu->arcs_lsize[ARC_BUFC_DATA]);
2430		(void) arc_evict(arc_mfu, 0, delta, FALSE, ARC_BUFC_DATA);
2431		adjustment -= delta;
2432	}
2433
2434	if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2435		int64_t delta = MIN(adjustment,
2436		    arc_mfu->arcs_lsize[ARC_BUFC_METADATA]);
2437		(void) arc_evict(arc_mfu, 0, delta, FALSE,
2438		    ARC_BUFC_METADATA);
2439	}
2440
2441	/*
2442	 * Adjust ghost lists
2443	 */
2444
2445	adjustment = arc_mru->arcs_size + arc_mru_ghost->arcs_size - arc_c;
2446
2447	if (adjustment > 0 && arc_mru_ghost->arcs_size > 0) {
2448		delta = MIN(arc_mru_ghost->arcs_size, adjustment);
2449		arc_evict_ghost(arc_mru_ghost, 0, delta);
2450	}
2451
2452	adjustment =
2453	    arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size - arc_c;
2454
2455	if (adjustment > 0 && arc_mfu_ghost->arcs_size > 0) {
2456		delta = MIN(arc_mfu_ghost->arcs_size, adjustment);
2457		arc_evict_ghost(arc_mfu_ghost, 0, delta);
2458	}
2459}
2460
2461static void
2462arc_do_user_evicts(void)
2463{
2464	static arc_buf_t *tmp_arc_eviction_list;
2465
2466	/*
2467	 * Move list over to avoid LOR
2468	 */
2469restart:
2470	mutex_enter(&arc_eviction_mtx);
2471	tmp_arc_eviction_list = arc_eviction_list;
2472	arc_eviction_list = NULL;
2473	mutex_exit(&arc_eviction_mtx);
2474
2475	while (tmp_arc_eviction_list != NULL) {
2476		arc_buf_t *buf = tmp_arc_eviction_list;
2477		tmp_arc_eviction_list = buf->b_next;
2478		mutex_enter(&buf->b_evict_lock);
2479		buf->b_hdr = NULL;
2480		mutex_exit(&buf->b_evict_lock);
2481
2482		if (buf->b_efunc != NULL)
2483			VERIFY0(buf->b_efunc(buf->b_private));
2484
2485		buf->b_efunc = NULL;
2486		buf->b_private = NULL;
2487		kmem_cache_free(buf_cache, buf);
2488	}
2489
2490	if (arc_eviction_list != NULL)
2491		goto restart;
2492}
2493
2494/*
2495 * Flush all *evictable* data from the cache for the given spa.
2496 * NOTE: this will not touch "active" (i.e. referenced) data.
2497 */
2498void
2499arc_flush(spa_t *spa)
2500{
2501	uint64_t guid = 0;
2502
2503	if (spa)
2504		guid = spa_load_guid(spa);
2505
2506	while (arc_mru->arcs_lsize[ARC_BUFC_DATA]) {
2507		(void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_DATA);
2508		if (spa)
2509			break;
2510	}
2511	while (arc_mru->arcs_lsize[ARC_BUFC_METADATA]) {
2512		(void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_METADATA);
2513		if (spa)
2514			break;
2515	}
2516	while (arc_mfu->arcs_lsize[ARC_BUFC_DATA]) {
2517		(void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_DATA);
2518		if (spa)
2519			break;
2520	}
2521	while (arc_mfu->arcs_lsize[ARC_BUFC_METADATA]) {
2522		(void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_METADATA);
2523		if (spa)
2524			break;
2525	}
2526
2527	arc_evict_ghost(arc_mru_ghost, guid, -1);
2528	arc_evict_ghost(arc_mfu_ghost, guid, -1);
2529
2530	mutex_enter(&arc_reclaim_thr_lock);
2531	arc_do_user_evicts();
2532	mutex_exit(&arc_reclaim_thr_lock);
2533	ASSERT(spa || arc_eviction_list == NULL);
2534}
2535
2536void
2537arc_shrink(void)
2538{
2539
2540	if (arc_c > arc_c_min) {
2541		uint64_t to_free;
2542
2543		DTRACE_PROBE4(arc__shrink, uint64_t, arc_c, uint64_t,
2544			arc_c_min, uint64_t, arc_p, uint64_t, to_free);
2545#ifdef _KERNEL
2546		to_free = arc_c >> arc_shrink_shift;
2547#else
2548		to_free = arc_c >> arc_shrink_shift;
2549#endif
2550		if (arc_c > arc_c_min + to_free)
2551			atomic_add_64(&arc_c, -to_free);
2552		else
2553			arc_c = arc_c_min;
2554
2555		atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
2556		if (arc_c > arc_size)
2557			arc_c = MAX(arc_size, arc_c_min);
2558		if (arc_p > arc_c)
2559			arc_p = (arc_c >> 1);
2560
2561		DTRACE_PROBE2(arc__shrunk, uint64_t, arc_c, uint64_t,
2562			arc_p);
2563
2564		ASSERT(arc_c >= arc_c_min);
2565		ASSERT((int64_t)arc_p >= 0);
2566	}
2567
2568	if (arc_size > arc_c) {
2569		DTRACE_PROBE2(arc__shrink_adjust, uint64_t, arc_size,
2570			uint64_t, arc_c);
2571		arc_adjust();
2572	}
2573}
2574
2575static int needfree = 0;
2576
2577static int
2578arc_reclaim_needed(void)
2579{
2580
2581#ifdef _KERNEL
2582
2583	if (needfree) {
2584		DTRACE_PROBE(arc__reclaim_needfree);
2585		return (1);
2586	}
2587
2588	/*
2589	 * Cooperate with pagedaemon when it's time for it to scan
2590	 * and reclaim some pages.
2591	 */
2592	if (freemem < zfs_arc_free_target) {
2593		DTRACE_PROBE2(arc__reclaim_freemem, uint64_t,
2594		    freemem, uint64_t, zfs_arc_free_target);
2595		return (1);
2596	}
2597
2598#ifdef sun
2599	/*
2600	 * take 'desfree' extra pages, so we reclaim sooner, rather than later
2601	 */
2602	extra = desfree;
2603
2604	/*
2605	 * check that we're out of range of the pageout scanner.  It starts to
2606	 * schedule paging if freemem is less than lotsfree and needfree.
2607	 * lotsfree is the high-water mark for pageout, and needfree is the
2608	 * number of needed free pages.  We add extra pages here to make sure
2609	 * the scanner doesn't start up while we're freeing memory.
2610	 */
2611	if (freemem < lotsfree + needfree + extra)
2612		return (1);
2613
2614	/*
2615	 * check to make sure that swapfs has enough space so that anon
2616	 * reservations can still succeed. anon_resvmem() checks that the
2617	 * availrmem is greater than swapfs_minfree, and the number of reserved
2618	 * swap pages.  We also add a bit of extra here just to prevent
2619	 * circumstances from getting really dire.
2620	 */
2621	if (availrmem < swapfs_minfree + swapfs_reserve + extra)
2622		return (1);
2623
2624	/*
2625	 * Check that we have enough availrmem that memory locking (e.g., via
2626	 * mlock(3C) or memcntl(2)) can still succeed.  (pages_pp_maximum
2627	 * stores the number of pages that cannot be locked; when availrmem
2628	 * drops below pages_pp_maximum, page locking mechanisms such as
2629	 * page_pp_lock() will fail.)
2630	 */
2631	if (availrmem <= pages_pp_maximum)
2632		return (1);
2633
2634#endif	/* sun */
2635#if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
2636	/*
2637	 * If we're on an i386 platform, it's possible that we'll exhaust the
2638	 * kernel heap space before we ever run out of available physical
2639	 * memory.  Most checks of the size of the heap_area compare against
2640	 * tune.t_minarmem, which is the minimum available real memory that we
2641	 * can have in the system.  However, this is generally fixed at 25 pages
2642	 * which is so low that it's useless.  In this comparison, we seek to
2643	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
2644	 * heap is allocated.  (Or, in the calculation, if less than 1/4th is
2645	 * free)
2646	 */
2647	if (vmem_size(heap_arena, VMEM_FREE) <
2648	    (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2)) {
2649		DTRACE_PROBE2(arc__reclaim_used, uint64_t,
2650		    vmem_size(heap_arena, VMEM_FREE), uint64_t,
2651		    (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC)) >> 2);
2652		return (1);
2653	}
2654#endif
2655#ifdef sun
2656	/*
2657	 * If zio data pages are being allocated out of a separate heap segment,
2658	 * then enforce that the size of available vmem for this arena remains
2659	 * above about 1/16th free.
2660	 *
2661	 * Note: The 1/16th arena free requirement was put in place
2662	 * to aggressively evict memory from the arc in order to avoid
2663	 * memory fragmentation issues.
2664	 */
2665	if (zio_arena != NULL &&
2666	    vmem_size(zio_arena, VMEM_FREE) <
2667	    (vmem_size(zio_arena, VMEM_ALLOC) >> 4))
2668		return (1);
2669#endif	/* sun */
2670#else	/* _KERNEL */
2671	if (spa_get_random(100) == 0)
2672		return (1);
2673#endif	/* _KERNEL */
2674	DTRACE_PROBE(arc__reclaim_no);
2675
2676	return (0);
2677}
2678
2679extern kmem_cache_t	*zio_buf_cache[];
2680extern kmem_cache_t	*zio_data_buf_cache[];
2681extern kmem_cache_t	*range_seg_cache;
2682
2683static void __noinline
2684arc_kmem_reap_now(arc_reclaim_strategy_t strat)
2685{
2686	size_t			i;
2687	kmem_cache_t		*prev_cache = NULL;
2688	kmem_cache_t		*prev_data_cache = NULL;
2689
2690	DTRACE_PROBE(arc__kmem_reap_start);
2691#ifdef _KERNEL
2692	if (arc_meta_used >= arc_meta_limit) {
2693		/*
2694		 * We are exceeding our meta-data cache limit.
2695		 * Purge some DNLC entries to release holds on meta-data.
2696		 */
2697		dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
2698	}
2699#if defined(__i386)
2700	/*
2701	 * Reclaim unused memory from all kmem caches.
2702	 */
2703	kmem_reap();
2704#endif
2705#endif
2706
2707	/*
2708	 * An aggressive reclamation will shrink the cache size as well as
2709	 * reap free buffers from the arc kmem caches.
2710	 */
2711	if (strat == ARC_RECLAIM_AGGR)
2712		arc_shrink();
2713
2714	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
2715		if (zio_buf_cache[i] != prev_cache) {
2716			prev_cache = zio_buf_cache[i];
2717			kmem_cache_reap_now(zio_buf_cache[i]);
2718		}
2719		if (zio_data_buf_cache[i] != prev_data_cache) {
2720			prev_data_cache = zio_data_buf_cache[i];
2721			kmem_cache_reap_now(zio_data_buf_cache[i]);
2722		}
2723	}
2724	kmem_cache_reap_now(buf_cache);
2725	kmem_cache_reap_now(hdr_cache);
2726	kmem_cache_reap_now(range_seg_cache);
2727
2728#ifdef sun
2729	/*
2730	 * Ask the vmem arena to reclaim unused memory from its
2731	 * quantum caches.
2732	 */
2733	if (zio_arena != NULL && strat == ARC_RECLAIM_AGGR)
2734		vmem_qcache_reap(zio_arena);
2735#endif
2736	DTRACE_PROBE(arc__kmem_reap_end);
2737}
2738
2739static void
2740arc_reclaim_thread(void *dummy __unused)
2741{
2742	clock_t			growtime = 0;
2743	arc_reclaim_strategy_t	last_reclaim = ARC_RECLAIM_CONS;
2744	callb_cpr_t		cpr;
2745
2746	CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
2747
2748	mutex_enter(&arc_reclaim_thr_lock);
2749	while (arc_thread_exit == 0) {
2750		if (arc_reclaim_needed()) {
2751
2752			if (arc_no_grow) {
2753				if (last_reclaim == ARC_RECLAIM_CONS) {
2754					DTRACE_PROBE(arc__reclaim_aggr_no_grow);
2755					last_reclaim = ARC_RECLAIM_AGGR;
2756				} else {
2757					last_reclaim = ARC_RECLAIM_CONS;
2758				}
2759			} else {
2760				arc_no_grow = TRUE;
2761				last_reclaim = ARC_RECLAIM_AGGR;
2762				DTRACE_PROBE(arc__reclaim_aggr);
2763				membar_producer();
2764			}
2765
2766			/* reset the growth delay for every reclaim */
2767			growtime = ddi_get_lbolt() + (arc_grow_retry * hz);
2768
2769			if (needfree && last_reclaim == ARC_RECLAIM_CONS) {
2770				/*
2771				 * If needfree is TRUE our vm_lowmem hook
2772				 * was called and in that case we must free some
2773				 * memory, so switch to aggressive mode.
2774				 */
2775				arc_no_grow = TRUE;
2776				last_reclaim = ARC_RECLAIM_AGGR;
2777			}
2778			arc_kmem_reap_now(last_reclaim);
2779			arc_warm = B_TRUE;
2780
2781		} else if (arc_no_grow && ddi_get_lbolt() >= growtime) {
2782			arc_no_grow = FALSE;
2783		}
2784
2785		arc_adjust();
2786
2787		if (arc_eviction_list != NULL)
2788			arc_do_user_evicts();
2789
2790#ifdef _KERNEL
2791		if (needfree) {
2792			needfree = 0;
2793			wakeup(&needfree);
2794		}
2795#endif
2796
2797		/* block until needed, or one second, whichever is shorter */
2798		CALLB_CPR_SAFE_BEGIN(&cpr);
2799		(void) cv_timedwait(&arc_reclaim_thr_cv,
2800		    &arc_reclaim_thr_lock, hz);
2801		CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
2802	}
2803
2804	arc_thread_exit = 0;
2805	cv_broadcast(&arc_reclaim_thr_cv);
2806	CALLB_CPR_EXIT(&cpr);		/* drops arc_reclaim_thr_lock */
2807	thread_exit();
2808}
2809
2810/*
2811 * Adapt arc info given the number of bytes we are trying to add and
2812 * the state that we are comming from.  This function is only called
2813 * when we are adding new content to the cache.
2814 */
2815static void
2816arc_adapt(int bytes, arc_state_t *state)
2817{
2818	int mult;
2819	uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
2820
2821	if (state == arc_l2c_only)
2822		return;
2823
2824	ASSERT(bytes > 0);
2825	/*
2826	 * Adapt the target size of the MRU list:
2827	 *	- if we just hit in the MRU ghost list, then increase
2828	 *	  the target size of the MRU list.
2829	 *	- if we just hit in the MFU ghost list, then increase
2830	 *	  the target size of the MFU list by decreasing the
2831	 *	  target size of the MRU list.
2832	 */
2833	if (state == arc_mru_ghost) {
2834		mult = ((arc_mru_ghost->arcs_size >= arc_mfu_ghost->arcs_size) ?
2835		    1 : (arc_mfu_ghost->arcs_size/arc_mru_ghost->arcs_size));
2836		mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
2837
2838		arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
2839	} else if (state == arc_mfu_ghost) {
2840		uint64_t delta;
2841
2842		mult = ((arc_mfu_ghost->arcs_size >= arc_mru_ghost->arcs_size) ?
2843		    1 : (arc_mru_ghost->arcs_size/arc_mfu_ghost->arcs_size));
2844		mult = MIN(mult, 10);
2845
2846		delta = MIN(bytes * mult, arc_p);
2847		arc_p = MAX(arc_p_min, arc_p - delta);
2848	}
2849	ASSERT((int64_t)arc_p >= 0);
2850
2851	if (arc_reclaim_needed()) {
2852		cv_signal(&arc_reclaim_thr_cv);
2853		return;
2854	}
2855
2856	if (arc_no_grow)
2857		return;
2858
2859	if (arc_c >= arc_c_max)
2860		return;
2861
2862	/*
2863	 * If we're within (2 * maxblocksize) bytes of the target
2864	 * cache size, increment the target cache size
2865	 */
2866	if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
2867		DTRACE_PROBE1(arc__inc_adapt, int, bytes);
2868		atomic_add_64(&arc_c, (int64_t)bytes);
2869		if (arc_c > arc_c_max)
2870			arc_c = arc_c_max;
2871		else if (state == arc_anon)
2872			atomic_add_64(&arc_p, (int64_t)bytes);
2873		if (arc_p > arc_c)
2874			arc_p = arc_c;
2875	}
2876	ASSERT((int64_t)arc_p >= 0);
2877}
2878
2879/*
2880 * Check if the cache has reached its limits and eviction is required
2881 * prior to insert.
2882 */
2883static int
2884arc_evict_needed(arc_buf_contents_t type)
2885{
2886	if (type == ARC_BUFC_METADATA && arc_meta_used >= arc_meta_limit)
2887		return (1);
2888
2889	if (arc_reclaim_needed())
2890		return (1);
2891
2892	return (arc_size > arc_c);
2893}
2894
2895/*
2896 * The buffer, supplied as the first argument, needs a data block.
2897 * So, if we are at cache max, determine which cache should be victimized.
2898 * We have the following cases:
2899 *
2900 * 1. Insert for MRU, p > sizeof(arc_anon + arc_mru) ->
2901 * In this situation if we're out of space, but the resident size of the MFU is
2902 * under the limit, victimize the MFU cache to satisfy this insertion request.
2903 *
2904 * 2. Insert for MRU, p <= sizeof(arc_anon + arc_mru) ->
2905 * Here, we've used up all of the available space for the MRU, so we need to
2906 * evict from our own cache instead.  Evict from the set of resident MRU
2907 * entries.
2908 *
2909 * 3. Insert for MFU (c - p) > sizeof(arc_mfu) ->
2910 * c minus p represents the MFU space in the cache, since p is the size of the
2911 * cache that is dedicated to the MRU.  In this situation there's still space on
2912 * the MFU side, so the MRU side needs to be victimized.
2913 *
2914 * 4. Insert for MFU (c - p) < sizeof(arc_mfu) ->
2915 * MFU's resident set is consuming more space than it has been allotted.  In
2916 * this situation, we must victimize our own cache, the MFU, for this insertion.
2917 */
2918static void
2919arc_get_data_buf(arc_buf_t *buf)
2920{
2921	arc_state_t		*state = buf->b_hdr->b_state;
2922	uint64_t		size = buf->b_hdr->b_size;
2923	arc_buf_contents_t	type = buf->b_hdr->b_type;
2924
2925	arc_adapt(size, state);
2926
2927	/*
2928	 * We have not yet reached cache maximum size,
2929	 * just allocate a new buffer.
2930	 */
2931	if (!arc_evict_needed(type)) {
2932		if (type == ARC_BUFC_METADATA) {
2933			buf->b_data = zio_buf_alloc(size);
2934			arc_space_consume(size, ARC_SPACE_DATA);
2935		} else {
2936			ASSERT(type == ARC_BUFC_DATA);
2937			buf->b_data = zio_data_buf_alloc(size);
2938			ARCSTAT_INCR(arcstat_data_size, size);
2939			atomic_add_64(&arc_size, size);
2940		}
2941		goto out;
2942	}
2943
2944	/*
2945	 * If we are prefetching from the mfu ghost list, this buffer
2946	 * will end up on the mru list; so steal space from there.
2947	 */
2948	if (state == arc_mfu_ghost)
2949		state = buf->b_hdr->b_flags & ARC_FLAG_PREFETCH ?
2950		    arc_mru : arc_mfu;
2951	else if (state == arc_mru_ghost)
2952		state = arc_mru;
2953
2954	if (state == arc_mru || state == arc_anon) {
2955		uint64_t mru_used = arc_anon->arcs_size + arc_mru->arcs_size;
2956		state = (arc_mfu->arcs_lsize[type] >= size &&
2957		    arc_p > mru_used) ? arc_mfu : arc_mru;
2958	} else {
2959		/* MFU cases */
2960		uint64_t mfu_space = arc_c - arc_p;
2961		state =  (arc_mru->arcs_lsize[type] >= size &&
2962		    mfu_space > arc_mfu->arcs_size) ? arc_mru : arc_mfu;
2963	}
2964	if ((buf->b_data = arc_evict(state, 0, size, TRUE, type)) == NULL) {
2965		if (type == ARC_BUFC_METADATA) {
2966			buf->b_data = zio_buf_alloc(size);
2967			arc_space_consume(size, ARC_SPACE_DATA);
2968		} else {
2969			ASSERT(type == ARC_BUFC_DATA);
2970			buf->b_data = zio_data_buf_alloc(size);
2971			ARCSTAT_INCR(arcstat_data_size, size);
2972			atomic_add_64(&arc_size, size);
2973		}
2974		ARCSTAT_BUMP(arcstat_recycle_miss);
2975	}
2976	ASSERT(buf->b_data != NULL);
2977out:
2978	/*
2979	 * Update the state size.  Note that ghost states have a
2980	 * "ghost size" and so don't need to be updated.
2981	 */
2982	if (!GHOST_STATE(buf->b_hdr->b_state)) {
2983		arc_buf_hdr_t *hdr = buf->b_hdr;
2984
2985		atomic_add_64(&hdr->b_state->arcs_size, size);
2986		if (list_link_active(&hdr->b_arc_node)) {
2987			ASSERT(refcount_is_zero(&hdr->b_refcnt));
2988			atomic_add_64(&hdr->b_state->arcs_lsize[type], size);
2989		}
2990		/*
2991		 * If we are growing the cache, and we are adding anonymous
2992		 * data, and we have outgrown arc_p, update arc_p
2993		 */
2994		if (arc_size < arc_c && hdr->b_state == arc_anon &&
2995		    arc_anon->arcs_size + arc_mru->arcs_size > arc_p)
2996			arc_p = MIN(arc_c, arc_p + size);
2997	}
2998	ARCSTAT_BUMP(arcstat_allocated);
2999}
3000
3001/*
3002 * This routine is called whenever a buffer is accessed.
3003 * NOTE: the hash lock is dropped in this function.
3004 */
3005static void
3006arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3007{
3008	clock_t now;
3009
3010	ASSERT(MUTEX_HELD(hash_lock));
3011
3012	if (hdr->b_state == arc_anon) {
3013		/*
3014		 * This buffer is not in the cache, and does not
3015		 * appear in our "ghost" list.  Add the new buffer
3016		 * to the MRU state.
3017		 */
3018
3019		ASSERT(hdr->b_arc_access == 0);
3020		hdr->b_arc_access = ddi_get_lbolt();
3021		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3022		arc_change_state(arc_mru, hdr, hash_lock);
3023
3024	} else if (hdr->b_state == arc_mru) {
3025		now = ddi_get_lbolt();
3026
3027		/*
3028		 * If this buffer is here because of a prefetch, then either:
3029		 * - clear the flag if this is a "referencing" read
3030		 *   (any subsequent access will bump this into the MFU state).
3031		 * or
3032		 * - move the buffer to the head of the list if this is
3033		 *   another prefetch (to make it less likely to be evicted).
3034		 */
3035		if ((hdr->b_flags & ARC_FLAG_PREFETCH) != 0) {
3036			if (refcount_count(&hdr->b_refcnt) == 0) {
3037				ASSERT(list_link_active(&hdr->b_arc_node));
3038			} else {
3039				hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3040				ARCSTAT_BUMP(arcstat_mru_hits);
3041			}
3042			hdr->b_arc_access = now;
3043			return;
3044		}
3045
3046		/*
3047		 * This buffer has been "accessed" only once so far,
3048		 * but it is still in the cache. Move it to the MFU
3049		 * state.
3050		 */
3051		if (now > hdr->b_arc_access + ARC_MINTIME) {
3052			/*
3053			 * More than 125ms have passed since we
3054			 * instantiated this buffer.  Move it to the
3055			 * most frequently used state.
3056			 */
3057			hdr->b_arc_access = now;
3058			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3059			arc_change_state(arc_mfu, hdr, hash_lock);
3060		}
3061		ARCSTAT_BUMP(arcstat_mru_hits);
3062	} else if (hdr->b_state == arc_mru_ghost) {
3063		arc_state_t	*new_state;
3064		/*
3065		 * This buffer has been "accessed" recently, but
3066		 * was evicted from the cache.  Move it to the
3067		 * MFU state.
3068		 */
3069
3070		if (hdr->b_flags & ARC_FLAG_PREFETCH) {
3071			new_state = arc_mru;
3072			if (refcount_count(&hdr->b_refcnt) > 0)
3073				hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3074			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3075		} else {
3076			new_state = arc_mfu;
3077			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3078		}
3079
3080		hdr->b_arc_access = ddi_get_lbolt();
3081		arc_change_state(new_state, hdr, hash_lock);
3082
3083		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
3084	} else if (hdr->b_state == arc_mfu) {
3085		/*
3086		 * This buffer has been accessed more than once and is
3087		 * still in the cache.  Keep it in the MFU state.
3088		 *
3089		 * NOTE: an add_reference() that occurred when we did
3090		 * the arc_read() will have kicked this off the list.
3091		 * If it was a prefetch, we will explicitly move it to
3092		 * the head of the list now.
3093		 */
3094		if ((hdr->b_flags & ARC_FLAG_PREFETCH) != 0) {
3095			ASSERT(refcount_count(&hdr->b_refcnt) == 0);
3096			ASSERT(list_link_active(&hdr->b_arc_node));
3097		}
3098		ARCSTAT_BUMP(arcstat_mfu_hits);
3099		hdr->b_arc_access = ddi_get_lbolt();
3100	} else if (hdr->b_state == arc_mfu_ghost) {
3101		arc_state_t	*new_state = arc_mfu;
3102		/*
3103		 * This buffer has been accessed more than once but has
3104		 * been evicted from the cache.  Move it back to the
3105		 * MFU state.
3106		 */
3107
3108		if (hdr->b_flags & ARC_FLAG_PREFETCH) {
3109			/*
3110			 * This is a prefetch access...
3111			 * move this block back to the MRU state.
3112			 */
3113			ASSERT0(refcount_count(&hdr->b_refcnt));
3114			new_state = arc_mru;
3115		}
3116
3117		hdr->b_arc_access = ddi_get_lbolt();
3118		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3119		arc_change_state(new_state, hdr, hash_lock);
3120
3121		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
3122	} else if (hdr->b_state == arc_l2c_only) {
3123		/*
3124		 * This buffer is on the 2nd Level ARC.
3125		 */
3126
3127		hdr->b_arc_access = ddi_get_lbolt();
3128		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3129		arc_change_state(arc_mfu, hdr, hash_lock);
3130	} else {
3131		ASSERT(!"invalid arc state");
3132	}
3133}
3134
3135/* a generic arc_done_func_t which you can use */
3136/* ARGSUSED */
3137void
3138arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
3139{
3140	if (zio == NULL || zio->io_error == 0)
3141		bcopy(buf->b_data, arg, buf->b_hdr->b_size);
3142	VERIFY(arc_buf_remove_ref(buf, arg));
3143}
3144
3145/* a generic arc_done_func_t */
3146void
3147arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
3148{
3149	arc_buf_t **bufp = arg;
3150	if (zio && zio->io_error) {
3151		VERIFY(arc_buf_remove_ref(buf, arg));
3152		*bufp = NULL;
3153	} else {
3154		*bufp = buf;
3155		ASSERT(buf->b_data);
3156	}
3157}
3158
3159static void
3160arc_read_done(zio_t *zio)
3161{
3162	arc_buf_hdr_t	*hdr;
3163	arc_buf_t	*buf;
3164	arc_buf_t	*abuf;	/* buffer we're assigning to callback */
3165	kmutex_t	*hash_lock = NULL;
3166	arc_callback_t	*callback_list, *acb;
3167	int		freeable = FALSE;
3168
3169	buf = zio->io_private;
3170	hdr = buf->b_hdr;
3171
3172	/*
3173	 * The hdr was inserted into hash-table and removed from lists
3174	 * prior to starting I/O.  We should find this header, since
3175	 * it's in the hash table, and it should be legit since it's
3176	 * not possible to evict it during the I/O.  The only possible
3177	 * reason for it not to be found is if we were freed during the
3178	 * read.
3179	 */
3180	if (HDR_IN_HASH_TABLE(hdr)) {
3181		ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
3182		ASSERT3U(hdr->b_dva.dva_word[0], ==,
3183		    BP_IDENTITY(zio->io_bp)->dva_word[0]);
3184		ASSERT3U(hdr->b_dva.dva_word[1], ==,
3185		    BP_IDENTITY(zio->io_bp)->dva_word[1]);
3186
3187		arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
3188		    &hash_lock);
3189
3190		ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) &&
3191		    hash_lock == NULL) ||
3192		    (found == hdr &&
3193		    DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
3194		    (found == hdr && HDR_L2_READING(hdr)));
3195	}
3196
3197	hdr->b_flags &= ~ARC_FLAG_L2_EVICTED;
3198	if (l2arc_noprefetch && (hdr->b_flags & ARC_FLAG_PREFETCH))
3199		hdr->b_flags &= ~ARC_FLAG_L2CACHE;
3200
3201	/* byteswap if necessary */
3202	callback_list = hdr->b_acb;
3203	ASSERT(callback_list != NULL);
3204	if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
3205		dmu_object_byteswap_t bswap =
3206		    DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
3207		arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
3208		    byteswap_uint64_array :
3209		    dmu_ot_byteswap[bswap].ob_func;
3210		func(buf->b_data, hdr->b_size);
3211	}
3212
3213	arc_cksum_compute(buf, B_FALSE);
3214#ifdef illumos
3215	arc_buf_watch(buf);
3216#endif /* illumos */
3217
3218	if (hash_lock && zio->io_error == 0 && hdr->b_state == arc_anon) {
3219		/*
3220		 * Only call arc_access on anonymous buffers.  This is because
3221		 * if we've issued an I/O for an evicted buffer, we've already
3222		 * called arc_access (to prevent any simultaneous readers from
3223		 * getting confused).
3224		 */
3225		arc_access(hdr, hash_lock);
3226	}
3227
3228	/* create copies of the data buffer for the callers */
3229	abuf = buf;
3230	for (acb = callback_list; acb; acb = acb->acb_next) {
3231		if (acb->acb_done) {
3232			if (abuf == NULL) {
3233				ARCSTAT_BUMP(arcstat_duplicate_reads);
3234				abuf = arc_buf_clone(buf);
3235			}
3236			acb->acb_buf = abuf;
3237			abuf = NULL;
3238		}
3239	}
3240	hdr->b_acb = NULL;
3241	hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
3242	ASSERT(!HDR_BUF_AVAILABLE(hdr));
3243	if (abuf == buf) {
3244		ASSERT(buf->b_efunc == NULL);
3245		ASSERT(hdr->b_datacnt == 1);
3246		hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
3247	}
3248
3249	ASSERT(refcount_is_zero(&hdr->b_refcnt) || callback_list != NULL);
3250
3251	if (zio->io_error != 0) {
3252		hdr->b_flags |= ARC_FLAG_IO_ERROR;
3253		if (hdr->b_state != arc_anon)
3254			arc_change_state(arc_anon, hdr, hash_lock);
3255		if (HDR_IN_HASH_TABLE(hdr))
3256			buf_hash_remove(hdr);
3257		freeable = refcount_is_zero(&hdr->b_refcnt);
3258	}
3259
3260	/*
3261	 * Broadcast before we drop the hash_lock to avoid the possibility
3262	 * that the hdr (and hence the cv) might be freed before we get to
3263	 * the cv_broadcast().
3264	 */
3265	cv_broadcast(&hdr->b_cv);
3266
3267	if (hash_lock) {
3268		mutex_exit(hash_lock);
3269	} else {
3270		/*
3271		 * This block was freed while we waited for the read to
3272		 * complete.  It has been removed from the hash table and
3273		 * moved to the anonymous state (so that it won't show up
3274		 * in the cache).
3275		 */
3276		ASSERT3P(hdr->b_state, ==, arc_anon);
3277		freeable = refcount_is_zero(&hdr->b_refcnt);
3278	}
3279
3280	/* execute each callback and free its structure */
3281	while ((acb = callback_list) != NULL) {
3282		if (acb->acb_done)
3283			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
3284
3285		if (acb->acb_zio_dummy != NULL) {
3286			acb->acb_zio_dummy->io_error = zio->io_error;
3287			zio_nowait(acb->acb_zio_dummy);
3288		}
3289
3290		callback_list = acb->acb_next;
3291		kmem_free(acb, sizeof (arc_callback_t));
3292	}
3293
3294	if (freeable)
3295		arc_hdr_destroy(hdr);
3296}
3297
3298/*
3299 * "Read" the block block at the specified DVA (in bp) via the
3300 * cache.  If the block is found in the cache, invoke the provided
3301 * callback immediately and return.  Note that the `zio' parameter
3302 * in the callback will be NULL in this case, since no IO was
3303 * required.  If the block is not in the cache pass the read request
3304 * on to the spa with a substitute callback function, so that the
3305 * requested block will be added to the cache.
3306 *
3307 * If a read request arrives for a block that has a read in-progress,
3308 * either wait for the in-progress read to complete (and return the
3309 * results); or, if this is a read with a "done" func, add a record
3310 * to the read to invoke the "done" func when the read completes,
3311 * and return; or just return.
3312 *
3313 * arc_read_done() will invoke all the requested "done" functions
3314 * for readers of this block.
3315 */
3316int
3317arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
3318    void *private, zio_priority_t priority, int zio_flags,
3319    arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
3320{
3321	arc_buf_hdr_t *hdr = NULL;
3322	arc_buf_t *buf = NULL;
3323	kmutex_t *hash_lock = NULL;
3324	zio_t *rzio;
3325	uint64_t guid = spa_load_guid(spa);
3326
3327	ASSERT(!BP_IS_EMBEDDED(bp) ||
3328	    BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
3329
3330top:
3331	if (!BP_IS_EMBEDDED(bp)) {
3332		/*
3333		 * Embedded BP's have no DVA and require no I/O to "read".
3334		 * Create an anonymous arc buf to back it.
3335		 */
3336		hdr = buf_hash_find(guid, bp, &hash_lock);
3337	}
3338
3339	if (hdr != NULL && hdr->b_datacnt > 0) {
3340
3341		*arc_flags |= ARC_FLAG_CACHED;
3342
3343		if (HDR_IO_IN_PROGRESS(hdr)) {
3344
3345			if (*arc_flags & ARC_FLAG_WAIT) {
3346				cv_wait(&hdr->b_cv, hash_lock);
3347				mutex_exit(hash_lock);
3348				goto top;
3349			}
3350			ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
3351
3352			if (done) {
3353				arc_callback_t	*acb = NULL;
3354
3355				acb = kmem_zalloc(sizeof (arc_callback_t),
3356				    KM_SLEEP);
3357				acb->acb_done = done;
3358				acb->acb_private = private;
3359				if (pio != NULL)
3360					acb->acb_zio_dummy = zio_null(pio,
3361					    spa, NULL, NULL, NULL, zio_flags);
3362
3363				ASSERT(acb->acb_done != NULL);
3364				acb->acb_next = hdr->b_acb;
3365				hdr->b_acb = acb;
3366				add_reference(hdr, hash_lock, private);
3367				mutex_exit(hash_lock);
3368				return (0);
3369			}
3370			mutex_exit(hash_lock);
3371			return (0);
3372		}
3373
3374		ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3375
3376		if (done) {
3377			add_reference(hdr, hash_lock, private);
3378			/*
3379			 * If this block is already in use, create a new
3380			 * copy of the data so that we will be guaranteed
3381			 * that arc_release() will always succeed.
3382			 */
3383			buf = hdr->b_buf;
3384			ASSERT(buf);
3385			ASSERT(buf->b_data);
3386			if (HDR_BUF_AVAILABLE(hdr)) {
3387				ASSERT(buf->b_efunc == NULL);
3388				hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
3389			} else {
3390				buf = arc_buf_clone(buf);
3391			}
3392
3393		} else if (*arc_flags & ARC_FLAG_PREFETCH &&
3394		    refcount_count(&hdr->b_refcnt) == 0) {
3395			hdr->b_flags |= ARC_FLAG_PREFETCH;
3396		}
3397		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
3398		arc_access(hdr, hash_lock);
3399		if (*arc_flags & ARC_FLAG_L2CACHE)
3400			hdr->b_flags |= ARC_FLAG_L2CACHE;
3401		if (*arc_flags & ARC_FLAG_L2COMPRESS)
3402			hdr->b_flags |= ARC_FLAG_L2COMPRESS;
3403		mutex_exit(hash_lock);
3404		ARCSTAT_BUMP(arcstat_hits);
3405		ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_FLAG_PREFETCH),
3406		    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3407		    data, metadata, hits);
3408
3409		if (done)
3410			done(NULL, buf, private);
3411	} else {
3412		uint64_t size = BP_GET_LSIZE(bp);
3413		arc_callback_t *acb;
3414		vdev_t *vd = NULL;
3415		uint64_t addr = 0;
3416		boolean_t devw = B_FALSE;
3417		enum zio_compress b_compress = ZIO_COMPRESS_OFF;
3418		uint64_t b_asize = 0;
3419
3420		if (hdr == NULL) {
3421			/* this block is not in the cache */
3422			arc_buf_hdr_t *exists = NULL;
3423			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
3424			buf = arc_buf_alloc(spa, size, private, type);
3425			hdr = buf->b_hdr;
3426			if (!BP_IS_EMBEDDED(bp)) {
3427				hdr->b_dva = *BP_IDENTITY(bp);
3428				hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
3429				hdr->b_cksum0 = bp->blk_cksum.zc_word[0];
3430				exists = buf_hash_insert(hdr, &hash_lock);
3431			}
3432			if (exists != NULL) {
3433				/* somebody beat us to the hash insert */
3434				mutex_exit(hash_lock);
3435				buf_discard_identity(hdr);
3436				(void) arc_buf_remove_ref(buf, private);
3437				goto top; /* restart the IO request */
3438			}
3439
3440			/* if this is a prefetch, we don't have a reference */
3441			if (*arc_flags & ARC_FLAG_PREFETCH) {
3442				(void) remove_reference(hdr, hash_lock,
3443				    private);
3444				hdr->b_flags |= ARC_FLAG_PREFETCH;
3445			}
3446			if (*arc_flags & ARC_FLAG_L2CACHE)
3447				hdr->b_flags |= ARC_FLAG_L2CACHE;
3448			if (*arc_flags & ARC_FLAG_L2COMPRESS)
3449				hdr->b_flags |= ARC_FLAG_L2COMPRESS;
3450			if (BP_GET_LEVEL(bp) > 0)
3451				hdr->b_flags |= ARC_FLAG_INDIRECT;
3452		} else {
3453			/* this block is in the ghost cache */
3454			ASSERT(GHOST_STATE(hdr->b_state));
3455			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3456			ASSERT0(refcount_count(&hdr->b_refcnt));
3457			ASSERT(hdr->b_buf == NULL);
3458
3459			/* if this is a prefetch, we don't have a reference */
3460			if (*arc_flags & ARC_FLAG_PREFETCH)
3461				hdr->b_flags |= ARC_FLAG_PREFETCH;
3462			else
3463				add_reference(hdr, hash_lock, private);
3464			if (*arc_flags & ARC_FLAG_L2CACHE)
3465				hdr->b_flags |= ARC_FLAG_L2CACHE;
3466			if (*arc_flags & ARC_FLAG_L2COMPRESS)
3467				hdr->b_flags |= ARC_FLAG_L2COMPRESS;
3468			buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
3469			buf->b_hdr = hdr;
3470			buf->b_data = NULL;
3471			buf->b_efunc = NULL;
3472			buf->b_private = NULL;
3473			buf->b_next = NULL;
3474			hdr->b_buf = buf;
3475			ASSERT(hdr->b_datacnt == 0);
3476			hdr->b_datacnt = 1;
3477			arc_get_data_buf(buf);
3478			arc_access(hdr, hash_lock);
3479		}
3480
3481		ASSERT(!GHOST_STATE(hdr->b_state));
3482
3483		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
3484		acb->acb_done = done;
3485		acb->acb_private = private;
3486
3487		ASSERT(hdr->b_acb == NULL);
3488		hdr->b_acb = acb;
3489		hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
3490
3491		if (hdr->b_l2hdr != NULL &&
3492		    (vd = hdr->b_l2hdr->b_dev->l2ad_vdev) != NULL) {
3493			devw = hdr->b_l2hdr->b_dev->l2ad_writing;
3494			addr = hdr->b_l2hdr->b_daddr;
3495			b_compress = hdr->b_l2hdr->b_compress;
3496			b_asize = hdr->b_l2hdr->b_asize;
3497			/*
3498			 * Lock out device removal.
3499			 */
3500			if (vdev_is_dead(vd) ||
3501			    !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
3502				vd = NULL;
3503		}
3504
3505		if (hash_lock != NULL)
3506			mutex_exit(hash_lock);
3507
3508		/*
3509		 * At this point, we have a level 1 cache miss.  Try again in
3510		 * L2ARC if possible.
3511		 */
3512		ASSERT3U(hdr->b_size, ==, size);
3513		DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
3514		    uint64_t, size, zbookmark_phys_t *, zb);
3515		ARCSTAT_BUMP(arcstat_misses);
3516		ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_FLAG_PREFETCH),
3517		    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3518		    data, metadata, misses);
3519#ifdef _KERNEL
3520		curthread->td_ru.ru_inblock++;
3521#endif
3522
3523		if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
3524			/*
3525			 * Read from the L2ARC if the following are true:
3526			 * 1. The L2ARC vdev was previously cached.
3527			 * 2. This buffer still has L2ARC metadata.
3528			 * 3. This buffer isn't currently writing to the L2ARC.
3529			 * 4. The L2ARC entry wasn't evicted, which may
3530			 *    also have invalidated the vdev.
3531			 * 5. This isn't prefetch and l2arc_noprefetch is set.
3532			 */
3533			if (hdr->b_l2hdr != NULL &&
3534			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
3535			    !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
3536				l2arc_read_callback_t *cb;
3537
3538				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
3539				ARCSTAT_BUMP(arcstat_l2_hits);
3540
3541				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
3542				    KM_SLEEP);
3543				cb->l2rcb_buf = buf;
3544				cb->l2rcb_spa = spa;
3545				cb->l2rcb_bp = *bp;
3546				cb->l2rcb_zb = *zb;
3547				cb->l2rcb_flags = zio_flags;
3548				cb->l2rcb_compress = b_compress;
3549
3550				ASSERT(addr >= VDEV_LABEL_START_SIZE &&
3551				    addr + size < vd->vdev_psize -
3552				    VDEV_LABEL_END_SIZE);
3553
3554				/*
3555				 * l2arc read.  The SCL_L2ARC lock will be
3556				 * released by l2arc_read_done().
3557				 * Issue a null zio if the underlying buffer
3558				 * was squashed to zero size by compression.
3559				 */
3560				if (b_compress == ZIO_COMPRESS_EMPTY) {
3561					rzio = zio_null(pio, spa, vd,
3562					    l2arc_read_done, cb,
3563					    zio_flags | ZIO_FLAG_DONT_CACHE |
3564					    ZIO_FLAG_CANFAIL |
3565					    ZIO_FLAG_DONT_PROPAGATE |
3566					    ZIO_FLAG_DONT_RETRY);
3567				} else {
3568					rzio = zio_read_phys(pio, vd, addr,
3569					    b_asize, buf->b_data,
3570					    ZIO_CHECKSUM_OFF,
3571					    l2arc_read_done, cb, priority,
3572					    zio_flags | ZIO_FLAG_DONT_CACHE |
3573					    ZIO_FLAG_CANFAIL |
3574					    ZIO_FLAG_DONT_PROPAGATE |
3575					    ZIO_FLAG_DONT_RETRY, B_FALSE);
3576				}
3577				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
3578				    zio_t *, rzio);
3579				ARCSTAT_INCR(arcstat_l2_read_bytes, b_asize);
3580
3581				if (*arc_flags & ARC_FLAG_NOWAIT) {
3582					zio_nowait(rzio);
3583					return (0);
3584				}
3585
3586				ASSERT(*arc_flags & ARC_FLAG_WAIT);
3587				if (zio_wait(rzio) == 0)
3588					return (0);
3589
3590				/* l2arc read error; goto zio_read() */
3591			} else {
3592				DTRACE_PROBE1(l2arc__miss,
3593				    arc_buf_hdr_t *, hdr);
3594				ARCSTAT_BUMP(arcstat_l2_misses);
3595				if (HDR_L2_WRITING(hdr))
3596					ARCSTAT_BUMP(arcstat_l2_rw_clash);
3597				spa_config_exit(spa, SCL_L2ARC, vd);
3598			}
3599		} else {
3600			if (vd != NULL)
3601				spa_config_exit(spa, SCL_L2ARC, vd);
3602			if (l2arc_ndev != 0) {
3603				DTRACE_PROBE1(l2arc__miss,
3604				    arc_buf_hdr_t *, hdr);
3605				ARCSTAT_BUMP(arcstat_l2_misses);
3606			}
3607		}
3608
3609		rzio = zio_read(pio, spa, bp, buf->b_data, size,
3610		    arc_read_done, buf, priority, zio_flags, zb);
3611
3612		if (*arc_flags & ARC_FLAG_WAIT)
3613			return (zio_wait(rzio));
3614
3615		ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
3616		zio_nowait(rzio);
3617	}
3618	return (0);
3619}
3620
3621void
3622arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
3623{
3624	ASSERT(buf->b_hdr != NULL);
3625	ASSERT(buf->b_hdr->b_state != arc_anon);
3626	ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt) || func == NULL);
3627	ASSERT(buf->b_efunc == NULL);
3628	ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
3629
3630	buf->b_efunc = func;
3631	buf->b_private = private;
3632}
3633
3634/*
3635 * Notify the arc that a block was freed, and thus will never be used again.
3636 */
3637void
3638arc_freed(spa_t *spa, const blkptr_t *bp)
3639{
3640	arc_buf_hdr_t *hdr;
3641	kmutex_t *hash_lock;
3642	uint64_t guid = spa_load_guid(spa);
3643
3644	ASSERT(!BP_IS_EMBEDDED(bp));
3645
3646	hdr = buf_hash_find(guid, bp, &hash_lock);
3647	if (hdr == NULL)
3648		return;
3649	if (HDR_BUF_AVAILABLE(hdr)) {
3650		arc_buf_t *buf = hdr->b_buf;
3651		add_reference(hdr, hash_lock, FTAG);
3652		hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
3653		mutex_exit(hash_lock);
3654
3655		arc_release(buf, FTAG);
3656		(void) arc_buf_remove_ref(buf, FTAG);
3657	} else {
3658		mutex_exit(hash_lock);
3659	}
3660
3661}
3662
3663/*
3664 * Clear the user eviction callback set by arc_set_callback(), first calling
3665 * it if it exists.  Because the presence of a callback keeps an arc_buf cached
3666 * clearing the callback may result in the arc_buf being destroyed.  However,
3667 * it will not result in the *last* arc_buf being destroyed, hence the data
3668 * will remain cached in the ARC. We make a copy of the arc buffer here so
3669 * that we can process the callback without holding any locks.
3670 *
3671 * It's possible that the callback is already in the process of being cleared
3672 * by another thread.  In this case we can not clear the callback.
3673 *
3674 * Returns B_TRUE if the callback was successfully called and cleared.
3675 */
3676boolean_t
3677arc_clear_callback(arc_buf_t *buf)
3678{
3679	arc_buf_hdr_t *hdr;
3680	kmutex_t *hash_lock;
3681	arc_evict_func_t *efunc = buf->b_efunc;
3682	void *private = buf->b_private;
3683	list_t *list, *evicted_list;
3684	kmutex_t *lock, *evicted_lock;
3685
3686	mutex_enter(&buf->b_evict_lock);
3687	hdr = buf->b_hdr;
3688	if (hdr == NULL) {
3689		/*
3690		 * We are in arc_do_user_evicts().
3691		 */
3692		ASSERT(buf->b_data == NULL);
3693		mutex_exit(&buf->b_evict_lock);
3694		return (B_FALSE);
3695	} else if (buf->b_data == NULL) {
3696		/*
3697		 * We are on the eviction list; process this buffer now
3698		 * but let arc_do_user_evicts() do the reaping.
3699		 */
3700		buf->b_efunc = NULL;
3701		mutex_exit(&buf->b_evict_lock);
3702		VERIFY0(efunc(private));
3703		return (B_TRUE);
3704	}
3705	hash_lock = HDR_LOCK(hdr);
3706	mutex_enter(hash_lock);
3707	hdr = buf->b_hdr;
3708	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3709
3710	ASSERT3U(refcount_count(&hdr->b_refcnt), <, hdr->b_datacnt);
3711	ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3712
3713	buf->b_efunc = NULL;
3714	buf->b_private = NULL;
3715
3716	if (hdr->b_datacnt > 1) {
3717		mutex_exit(&buf->b_evict_lock);
3718		arc_buf_destroy(buf, FALSE, TRUE);
3719	} else {
3720		ASSERT(buf == hdr->b_buf);
3721		hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
3722		mutex_exit(&buf->b_evict_lock);
3723	}
3724
3725	mutex_exit(hash_lock);
3726	VERIFY0(efunc(private));
3727	return (B_TRUE);
3728}
3729
3730/*
3731 * Release this buffer from the cache, making it an anonymous buffer.  This
3732 * must be done after a read and prior to modifying the buffer contents.
3733 * If the buffer has more than one reference, we must make
3734 * a new hdr for the buffer.
3735 */
3736void
3737arc_release(arc_buf_t *buf, void *tag)
3738{
3739	arc_buf_hdr_t *hdr;
3740	kmutex_t *hash_lock = NULL;
3741	l2arc_buf_hdr_t *l2hdr;
3742	uint64_t buf_size;
3743
3744	/*
3745	 * It would be nice to assert that if it's DMU metadata (level >
3746	 * 0 || it's the dnode file), then it must be syncing context.
3747	 * But we don't know that information at this level.
3748	 */
3749
3750	mutex_enter(&buf->b_evict_lock);
3751	hdr = buf->b_hdr;
3752
3753	/* this buffer is not on any list */
3754	ASSERT(refcount_count(&hdr->b_refcnt) > 0);
3755
3756	if (hdr->b_state == arc_anon) {
3757		/* this buffer is already released */
3758		ASSERT(buf->b_efunc == NULL);
3759	} else {
3760		hash_lock = HDR_LOCK(hdr);
3761		mutex_enter(hash_lock);
3762		hdr = buf->b_hdr;
3763		ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3764	}
3765
3766	l2hdr = hdr->b_l2hdr;
3767	if (l2hdr) {
3768		mutex_enter(&l2arc_buflist_mtx);
3769		arc_buf_l2_cdata_free(hdr);
3770		hdr->b_l2hdr = NULL;
3771		list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
3772	}
3773	buf_size = hdr->b_size;
3774
3775	/*
3776	 * Do we have more than one buf?
3777	 */
3778	if (hdr->b_datacnt > 1) {
3779		arc_buf_hdr_t *nhdr;
3780		arc_buf_t **bufp;
3781		uint64_t blksz = hdr->b_size;
3782		uint64_t spa = hdr->b_spa;
3783		arc_buf_contents_t type = hdr->b_type;
3784		uint32_t flags = hdr->b_flags;
3785
3786		ASSERT(hdr->b_buf != buf || buf->b_next != NULL);
3787		/*
3788		 * Pull the data off of this hdr and attach it to
3789		 * a new anonymous hdr.
3790		 */
3791		(void) remove_reference(hdr, hash_lock, tag);
3792		bufp = &hdr->b_buf;
3793		while (*bufp != buf)
3794			bufp = &(*bufp)->b_next;
3795		*bufp = buf->b_next;
3796		buf->b_next = NULL;
3797
3798		ASSERT3U(hdr->b_state->arcs_size, >=, hdr->b_size);
3799		atomic_add_64(&hdr->b_state->arcs_size, -hdr->b_size);
3800		if (refcount_is_zero(&hdr->b_refcnt)) {
3801			uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
3802			ASSERT3U(*size, >=, hdr->b_size);
3803			atomic_add_64(size, -hdr->b_size);
3804		}
3805
3806		/*
3807		 * We're releasing a duplicate user data buffer, update
3808		 * our statistics accordingly.
3809		 */
3810		if (hdr->b_type == ARC_BUFC_DATA) {
3811			ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
3812			ARCSTAT_INCR(arcstat_duplicate_buffers_size,
3813			    -hdr->b_size);
3814		}
3815		hdr->b_datacnt -= 1;
3816		arc_cksum_verify(buf);
3817#ifdef illumos
3818		arc_buf_unwatch(buf);
3819#endif /* illumos */
3820
3821		mutex_exit(hash_lock);
3822
3823		nhdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
3824		nhdr->b_size = blksz;
3825		nhdr->b_spa = spa;
3826		nhdr->b_type = type;
3827		nhdr->b_buf = buf;
3828		nhdr->b_state = arc_anon;
3829		nhdr->b_arc_access = 0;
3830		nhdr->b_flags = flags & ARC_FLAG_L2_WRITING;
3831		nhdr->b_l2hdr = NULL;
3832		nhdr->b_datacnt = 1;
3833		nhdr->b_freeze_cksum = NULL;
3834		(void) refcount_add(&nhdr->b_refcnt, tag);
3835		buf->b_hdr = nhdr;
3836		mutex_exit(&buf->b_evict_lock);
3837		atomic_add_64(&arc_anon->arcs_size, blksz);
3838	} else {
3839		mutex_exit(&buf->b_evict_lock);
3840		ASSERT(refcount_count(&hdr->b_refcnt) == 1);
3841		ASSERT(!list_link_active(&hdr->b_arc_node));
3842		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3843		if (hdr->b_state != arc_anon)
3844			arc_change_state(arc_anon, hdr, hash_lock);
3845		hdr->b_arc_access = 0;
3846		if (hash_lock)
3847			mutex_exit(hash_lock);
3848
3849		buf_discard_identity(hdr);
3850		arc_buf_thaw(buf);
3851	}
3852	buf->b_efunc = NULL;
3853	buf->b_private = NULL;
3854
3855	if (l2hdr) {
3856		ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
3857		vdev_space_update(l2hdr->b_dev->l2ad_vdev,
3858		    -l2hdr->b_asize, 0, 0);
3859		trim_map_free(l2hdr->b_dev->l2ad_vdev, l2hdr->b_daddr,
3860		    hdr->b_size, 0);
3861		kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
3862		ARCSTAT_INCR(arcstat_l2_size, -buf_size);
3863		mutex_exit(&l2arc_buflist_mtx);
3864	}
3865}
3866
3867int
3868arc_released(arc_buf_t *buf)
3869{
3870	int released;
3871
3872	mutex_enter(&buf->b_evict_lock);
3873	released = (buf->b_data != NULL && buf->b_hdr->b_state == arc_anon);
3874	mutex_exit(&buf->b_evict_lock);
3875	return (released);
3876}
3877
3878#ifdef ZFS_DEBUG
3879int
3880arc_referenced(arc_buf_t *buf)
3881{
3882	int referenced;
3883
3884	mutex_enter(&buf->b_evict_lock);
3885	referenced = (refcount_count(&buf->b_hdr->b_refcnt));
3886	mutex_exit(&buf->b_evict_lock);
3887	return (referenced);
3888}
3889#endif
3890
3891static void
3892arc_write_ready(zio_t *zio)
3893{
3894	arc_write_callback_t *callback = zio->io_private;
3895	arc_buf_t *buf = callback->awcb_buf;
3896	arc_buf_hdr_t *hdr = buf->b_hdr;
3897
3898	ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt));
3899	callback->awcb_ready(zio, buf, callback->awcb_private);
3900
3901	/*
3902	 * If the IO is already in progress, then this is a re-write
3903	 * attempt, so we need to thaw and re-compute the cksum.
3904	 * It is the responsibility of the callback to handle the
3905	 * accounting for any re-write attempt.
3906	 */
3907	if (HDR_IO_IN_PROGRESS(hdr)) {
3908		mutex_enter(&hdr->b_freeze_lock);
3909		if (hdr->b_freeze_cksum != NULL) {
3910			kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
3911			hdr->b_freeze_cksum = NULL;
3912		}
3913		mutex_exit(&hdr->b_freeze_lock);
3914	}
3915	arc_cksum_compute(buf, B_FALSE);
3916	hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
3917}
3918
3919/*
3920 * The SPA calls this callback for each physical write that happens on behalf
3921 * of a logical write.  See the comment in dbuf_write_physdone() for details.
3922 */
3923static void
3924arc_write_physdone(zio_t *zio)
3925{
3926	arc_write_callback_t *cb = zio->io_private;
3927	if (cb->awcb_physdone != NULL)
3928		cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
3929}
3930
3931static void
3932arc_write_done(zio_t *zio)
3933{
3934	arc_write_callback_t *callback = zio->io_private;
3935	arc_buf_t *buf = callback->awcb_buf;
3936	arc_buf_hdr_t *hdr = buf->b_hdr;
3937
3938	ASSERT(hdr->b_acb == NULL);
3939
3940	if (zio->io_error == 0) {
3941		if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
3942			buf_discard_identity(hdr);
3943		} else {
3944			hdr->b_dva = *BP_IDENTITY(zio->io_bp);
3945			hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
3946			hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
3947		}
3948	} else {
3949		ASSERT(BUF_EMPTY(hdr));
3950	}
3951
3952	/*
3953	 * If the block to be written was all-zero or compressed enough to be
3954	 * embedded in the BP, no write was performed so there will be no
3955	 * dva/birth/checksum.  The buffer must therefore remain anonymous
3956	 * (and uncached).
3957	 */
3958	if (!BUF_EMPTY(hdr)) {
3959		arc_buf_hdr_t *exists;
3960		kmutex_t *hash_lock;
3961
3962		ASSERT(zio->io_error == 0);
3963
3964		arc_cksum_verify(buf);
3965
3966		exists = buf_hash_insert(hdr, &hash_lock);
3967		if (exists) {
3968			/*
3969			 * This can only happen if we overwrite for
3970			 * sync-to-convergence, because we remove
3971			 * buffers from the hash table when we arc_free().
3972			 */
3973			if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
3974				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3975					panic("bad overwrite, hdr=%p exists=%p",
3976					    (void *)hdr, (void *)exists);
3977				ASSERT(refcount_is_zero(&exists->b_refcnt));
3978				arc_change_state(arc_anon, exists, hash_lock);
3979				mutex_exit(hash_lock);
3980				arc_hdr_destroy(exists);
3981				exists = buf_hash_insert(hdr, &hash_lock);
3982				ASSERT3P(exists, ==, NULL);
3983			} else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
3984				/* nopwrite */
3985				ASSERT(zio->io_prop.zp_nopwrite);
3986				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3987					panic("bad nopwrite, hdr=%p exists=%p",
3988					    (void *)hdr, (void *)exists);
3989			} else {
3990				/* Dedup */
3991				ASSERT(hdr->b_datacnt == 1);
3992				ASSERT(hdr->b_state == arc_anon);
3993				ASSERT(BP_GET_DEDUP(zio->io_bp));
3994				ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
3995			}
3996		}
3997		hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
3998		/* if it's not anon, we are doing a scrub */
3999		if (!exists && hdr->b_state == arc_anon)
4000			arc_access(hdr, hash_lock);
4001		mutex_exit(hash_lock);
4002	} else {
4003		hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
4004	}
4005
4006	ASSERT(!refcount_is_zero(&hdr->b_refcnt));
4007	callback->awcb_done(zio, buf, callback->awcb_private);
4008
4009	kmem_free(callback, sizeof (arc_write_callback_t));
4010}
4011
4012zio_t *
4013arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
4014    blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
4015    const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *physdone,
4016    arc_done_func_t *done, void *private, zio_priority_t priority,
4017    int zio_flags, const zbookmark_phys_t *zb)
4018{
4019	arc_buf_hdr_t *hdr = buf->b_hdr;
4020	arc_write_callback_t *callback;
4021	zio_t *zio;
4022
4023	ASSERT(ready != NULL);
4024	ASSERT(done != NULL);
4025	ASSERT(!HDR_IO_ERROR(hdr));
4026	ASSERT((hdr->b_flags & ARC_FLAG_IO_IN_PROGRESS) == 0);
4027	ASSERT(hdr->b_acb == NULL);
4028	if (l2arc)
4029		hdr->b_flags |= ARC_FLAG_L2CACHE;
4030	if (l2arc_compress)
4031		hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4032	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
4033	callback->awcb_ready = ready;
4034	callback->awcb_physdone = physdone;
4035	callback->awcb_done = done;
4036	callback->awcb_private = private;
4037	callback->awcb_buf = buf;
4038
4039	zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
4040	    arc_write_ready, arc_write_physdone, arc_write_done, callback,
4041	    priority, zio_flags, zb);
4042
4043	return (zio);
4044}
4045
4046static int
4047arc_memory_throttle(uint64_t reserve, uint64_t txg)
4048{
4049#ifdef _KERNEL
4050	uint64_t available_memory = ptob(freemem);
4051	static uint64_t page_load = 0;
4052	static uint64_t last_txg = 0;
4053
4054#if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
4055	available_memory =
4056	    MIN(available_memory, ptob(vmem_size(heap_arena, VMEM_FREE)));
4057#endif
4058
4059	if (freemem > (uint64_t)physmem * arc_lotsfree_percent / 100)
4060		return (0);
4061
4062	if (txg > last_txg) {
4063		last_txg = txg;
4064		page_load = 0;
4065	}
4066	/*
4067	 * If we are in pageout, we know that memory is already tight,
4068	 * the arc is already going to be evicting, so we just want to
4069	 * continue to let page writes occur as quickly as possible.
4070	 */
4071	if (curproc == pageproc) {
4072		if (page_load > MAX(ptob(minfree), available_memory) / 4)
4073			return (SET_ERROR(ERESTART));
4074		/* Note: reserve is inflated, so we deflate */
4075		page_load += reserve / 8;
4076		return (0);
4077	} else if (page_load > 0 && arc_reclaim_needed()) {
4078		/* memory is low, delay before restarting */
4079		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
4080		return (SET_ERROR(EAGAIN));
4081	}
4082	page_load = 0;
4083#endif
4084	return (0);
4085}
4086
4087void
4088arc_tempreserve_clear(uint64_t reserve)
4089{
4090	atomic_add_64(&arc_tempreserve, -reserve);
4091	ASSERT((int64_t)arc_tempreserve >= 0);
4092}
4093
4094int
4095arc_tempreserve_space(uint64_t reserve, uint64_t txg)
4096{
4097	int error;
4098	uint64_t anon_size;
4099
4100	if (reserve > arc_c/4 && !arc_no_grow) {
4101		arc_c = MIN(arc_c_max, reserve * 4);
4102		DTRACE_PROBE1(arc__set_reserve, uint64_t, arc_c);
4103	}
4104	if (reserve > arc_c)
4105		return (SET_ERROR(ENOMEM));
4106
4107	/*
4108	 * Don't count loaned bufs as in flight dirty data to prevent long
4109	 * network delays from blocking transactions that are ready to be
4110	 * assigned to a txg.
4111	 */
4112	anon_size = MAX((int64_t)(arc_anon->arcs_size - arc_loaned_bytes), 0);
4113
4114	/*
4115	 * Writes will, almost always, require additional memory allocations
4116	 * in order to compress/encrypt/etc the data.  We therefore need to
4117	 * make sure that there is sufficient available memory for this.
4118	 */
4119	error = arc_memory_throttle(reserve, txg);
4120	if (error != 0)
4121		return (error);
4122
4123	/*
4124	 * Throttle writes when the amount of dirty data in the cache
4125	 * gets too large.  We try to keep the cache less than half full
4126	 * of dirty blocks so that our sync times don't grow too large.
4127	 * Note: if two requests come in concurrently, we might let them
4128	 * both succeed, when one of them should fail.  Not a huge deal.
4129	 */
4130
4131	if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
4132	    anon_size > arc_c / 4) {
4133		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
4134		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
4135		    arc_tempreserve>>10,
4136		    arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
4137		    arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
4138		    reserve>>10, arc_c>>10);
4139		return (SET_ERROR(ERESTART));
4140	}
4141	atomic_add_64(&arc_tempreserve, reserve);
4142	return (0);
4143}
4144
4145static kmutex_t arc_lowmem_lock;
4146#ifdef _KERNEL
4147static eventhandler_tag arc_event_lowmem = NULL;
4148
4149static void
4150arc_lowmem(void *arg __unused, int howto __unused)
4151{
4152
4153	/* Serialize access via arc_lowmem_lock. */
4154	mutex_enter(&arc_lowmem_lock);
4155	mutex_enter(&arc_reclaim_thr_lock);
4156	needfree = 1;
4157	DTRACE_PROBE(arc__needfree);
4158	cv_signal(&arc_reclaim_thr_cv);
4159
4160	/*
4161	 * It is unsafe to block here in arbitrary threads, because we can come
4162	 * here from ARC itself and may hold ARC locks and thus risk a deadlock
4163	 * with ARC reclaim thread.
4164	 */
4165	if (curproc == pageproc) {
4166		while (needfree)
4167			msleep(&needfree, &arc_reclaim_thr_lock, 0, "zfs:lowmem", 0);
4168	}
4169	mutex_exit(&arc_reclaim_thr_lock);
4170	mutex_exit(&arc_lowmem_lock);
4171}
4172#endif
4173
4174void
4175arc_init(void)
4176{
4177	int i, prefetch_tunable_set = 0;
4178
4179	mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
4180	cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
4181	mutex_init(&arc_lowmem_lock, NULL, MUTEX_DEFAULT, NULL);
4182
4183	/* Convert seconds to clock ticks */
4184	arc_min_prefetch_lifespan = 1 * hz;
4185
4186	/* Start out with 1/8 of all memory */
4187	arc_c = kmem_size() / 8;
4188
4189#ifdef sun
4190#ifdef _KERNEL
4191	/*
4192	 * On architectures where the physical memory can be larger
4193	 * than the addressable space (intel in 32-bit mode), we may
4194	 * need to limit the cache to 1/8 of VM size.
4195	 */
4196	arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
4197#endif
4198#endif	/* sun */
4199	/* set min cache to 1/32 of all memory, or 16MB, whichever is more */
4200	arc_c_min = MAX(arc_c / 4, 64<<18);
4201	/* set max to 1/2 of all memory, or all but 1GB, whichever is more */
4202	if (arc_c * 8 >= 1<<30)
4203		arc_c_max = (arc_c * 8) - (1<<30);
4204	else
4205		arc_c_max = arc_c_min;
4206	arc_c_max = MAX(arc_c * 5, arc_c_max);
4207
4208#ifdef _KERNEL
4209	/*
4210	 * Allow the tunables to override our calculations if they are
4211	 * reasonable (ie. over 16MB)
4212	 */
4213	if (zfs_arc_max > 64<<18 && zfs_arc_max < kmem_size())
4214		arc_c_max = zfs_arc_max;
4215	if (zfs_arc_min > 64<<18 && zfs_arc_min <= arc_c_max)
4216		arc_c_min = zfs_arc_min;
4217#endif
4218
4219	arc_c = arc_c_max;
4220	arc_p = (arc_c >> 1);
4221
4222	/* limit meta-data to 1/4 of the arc capacity */
4223	arc_meta_limit = arc_c_max / 4;
4224
4225	/* Allow the tunable to override if it is reasonable */
4226	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
4227		arc_meta_limit = zfs_arc_meta_limit;
4228
4229	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
4230		arc_c_min = arc_meta_limit / 2;
4231
4232	if (zfs_arc_meta_min > 0) {
4233		arc_meta_min = zfs_arc_meta_min;
4234	} else {
4235		arc_meta_min = arc_c_min / 2;
4236	}
4237
4238	if (zfs_arc_grow_retry > 0)
4239		arc_grow_retry = zfs_arc_grow_retry;
4240
4241	if (zfs_arc_shrink_shift > 0)
4242		arc_shrink_shift = zfs_arc_shrink_shift;
4243
4244	if (zfs_arc_p_min_shift > 0)
4245		arc_p_min_shift = zfs_arc_p_min_shift;
4246
4247	/* if kmem_flags are set, lets try to use less memory */
4248	if (kmem_debugging())
4249		arc_c = arc_c / 2;
4250	if (arc_c < arc_c_min)
4251		arc_c = arc_c_min;
4252
4253	zfs_arc_min = arc_c_min;
4254	zfs_arc_max = arc_c_max;
4255
4256	arc_anon = &ARC_anon;
4257	arc_mru = &ARC_mru;
4258	arc_mru_ghost = &ARC_mru_ghost;
4259	arc_mfu = &ARC_mfu;
4260	arc_mfu_ghost = &ARC_mfu_ghost;
4261	arc_l2c_only = &ARC_l2c_only;
4262	arc_size = 0;
4263
4264	for (i = 0; i < ARC_BUFC_NUMLISTS; i++) {
4265		mutex_init(&arc_anon->arcs_locks[i].arcs_lock,
4266		    NULL, MUTEX_DEFAULT, NULL);
4267		mutex_init(&arc_mru->arcs_locks[i].arcs_lock,
4268		    NULL, MUTEX_DEFAULT, NULL);
4269		mutex_init(&arc_mru_ghost->arcs_locks[i].arcs_lock,
4270		    NULL, MUTEX_DEFAULT, NULL);
4271		mutex_init(&arc_mfu->arcs_locks[i].arcs_lock,
4272		    NULL, MUTEX_DEFAULT, NULL);
4273		mutex_init(&arc_mfu_ghost->arcs_locks[i].arcs_lock,
4274		    NULL, MUTEX_DEFAULT, NULL);
4275		mutex_init(&arc_l2c_only->arcs_locks[i].arcs_lock,
4276		    NULL, MUTEX_DEFAULT, NULL);
4277
4278		list_create(&arc_mru->arcs_lists[i],
4279		    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4280		list_create(&arc_mru_ghost->arcs_lists[i],
4281		    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4282		list_create(&arc_mfu->arcs_lists[i],
4283		    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4284		list_create(&arc_mfu_ghost->arcs_lists[i],
4285		    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4286		list_create(&arc_mfu_ghost->arcs_lists[i],
4287		    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4288		list_create(&arc_l2c_only->arcs_lists[i],
4289		    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4290	}
4291
4292	buf_init();
4293
4294	arc_thread_exit = 0;
4295	arc_eviction_list = NULL;
4296	mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
4297	bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
4298
4299	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
4300	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
4301
4302	if (arc_ksp != NULL) {
4303		arc_ksp->ks_data = &arc_stats;
4304		kstat_install(arc_ksp);
4305	}
4306
4307	(void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
4308	    TS_RUN, minclsyspri);
4309
4310#ifdef _KERNEL
4311	arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
4312	    EVENTHANDLER_PRI_FIRST);
4313#endif
4314
4315	arc_dead = FALSE;
4316	arc_warm = B_FALSE;
4317
4318	/*
4319	 * Calculate maximum amount of dirty data per pool.
4320	 *
4321	 * If it has been set by /etc/system, take that.
4322	 * Otherwise, use a percentage of physical memory defined by
4323	 * zfs_dirty_data_max_percent (default 10%) with a cap at
4324	 * zfs_dirty_data_max_max (default 4GB).
4325	 */
4326	if (zfs_dirty_data_max == 0) {
4327		zfs_dirty_data_max = ptob(physmem) *
4328		    zfs_dirty_data_max_percent / 100;
4329		zfs_dirty_data_max = MIN(zfs_dirty_data_max,
4330		    zfs_dirty_data_max_max);
4331	}
4332
4333#ifdef _KERNEL
4334	if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
4335		prefetch_tunable_set = 1;
4336
4337#ifdef __i386__
4338	if (prefetch_tunable_set == 0) {
4339		printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
4340		    "-- to enable,\n");
4341		printf("            add \"vfs.zfs.prefetch_disable=0\" "
4342		    "to /boot/loader.conf.\n");
4343		zfs_prefetch_disable = 1;
4344	}
4345#else
4346	if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
4347	    prefetch_tunable_set == 0) {
4348		printf("ZFS NOTICE: Prefetch is disabled by default if less "
4349		    "than 4GB of RAM is present;\n"
4350		    "            to enable, add \"vfs.zfs.prefetch_disable=0\" "
4351		    "to /boot/loader.conf.\n");
4352		zfs_prefetch_disable = 1;
4353	}
4354#endif
4355	/* Warn about ZFS memory and address space requirements. */
4356	if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
4357		printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
4358		    "expect unstable behavior.\n");
4359	}
4360	if (kmem_size() < 512 * (1 << 20)) {
4361		printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
4362		    "expect unstable behavior.\n");
4363		printf("             Consider tuning vm.kmem_size and "
4364		    "vm.kmem_size_max\n");
4365		printf("             in /boot/loader.conf.\n");
4366	}
4367#endif
4368}
4369
4370void
4371arc_fini(void)
4372{
4373	int i;
4374
4375	mutex_enter(&arc_reclaim_thr_lock);
4376	arc_thread_exit = 1;
4377	cv_signal(&arc_reclaim_thr_cv);
4378	while (arc_thread_exit != 0)
4379		cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
4380	mutex_exit(&arc_reclaim_thr_lock);
4381
4382	arc_flush(NULL);
4383
4384	arc_dead = TRUE;
4385
4386	if (arc_ksp != NULL) {
4387		kstat_delete(arc_ksp);
4388		arc_ksp = NULL;
4389	}
4390
4391	mutex_destroy(&arc_eviction_mtx);
4392	mutex_destroy(&arc_reclaim_thr_lock);
4393	cv_destroy(&arc_reclaim_thr_cv);
4394
4395	for (i = 0; i < ARC_BUFC_NUMLISTS; i++) {
4396		list_destroy(&arc_mru->arcs_lists[i]);
4397		list_destroy(&arc_mru_ghost->arcs_lists[i]);
4398		list_destroy(&arc_mfu->arcs_lists[i]);
4399		list_destroy(&arc_mfu_ghost->arcs_lists[i]);
4400		list_destroy(&arc_l2c_only->arcs_lists[i]);
4401
4402		mutex_destroy(&arc_anon->arcs_locks[i].arcs_lock);
4403		mutex_destroy(&arc_mru->arcs_locks[i].arcs_lock);
4404		mutex_destroy(&arc_mru_ghost->arcs_locks[i].arcs_lock);
4405		mutex_destroy(&arc_mfu->arcs_locks[i].arcs_lock);
4406		mutex_destroy(&arc_mfu_ghost->arcs_locks[i].arcs_lock);
4407		mutex_destroy(&arc_l2c_only->arcs_locks[i].arcs_lock);
4408	}
4409
4410	buf_fini();
4411
4412	ASSERT(arc_loaned_bytes == 0);
4413
4414	mutex_destroy(&arc_lowmem_lock);
4415#ifdef _KERNEL
4416	if (arc_event_lowmem != NULL)
4417		EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
4418#endif
4419}
4420
4421/*
4422 * Level 2 ARC
4423 *
4424 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
4425 * It uses dedicated storage devices to hold cached data, which are populated
4426 * using large infrequent writes.  The main role of this cache is to boost
4427 * the performance of random read workloads.  The intended L2ARC devices
4428 * include short-stroked disks, solid state disks, and other media with
4429 * substantially faster read latency than disk.
4430 *
4431 *                 +-----------------------+
4432 *                 |         ARC           |
4433 *                 +-----------------------+
4434 *                    |         ^     ^
4435 *                    |         |     |
4436 *      l2arc_feed_thread()    arc_read()
4437 *                    |         |     |
4438 *                    |  l2arc read   |
4439 *                    V         |     |
4440 *               +---------------+    |
4441 *               |     L2ARC     |    |
4442 *               +---------------+    |
4443 *                   |    ^           |
4444 *          l2arc_write() |           |
4445 *                   |    |           |
4446 *                   V    |           |
4447 *                 +-------+      +-------+
4448 *                 | vdev  |      | vdev  |
4449 *                 | cache |      | cache |
4450 *                 +-------+      +-------+
4451 *                 +=========+     .-----.
4452 *                 :  L2ARC  :    |-_____-|
4453 *                 : devices :    | Disks |
4454 *                 +=========+    `-_____-'
4455 *
4456 * Read requests are satisfied from the following sources, in order:
4457 *
4458 *	1) ARC
4459 *	2) vdev cache of L2ARC devices
4460 *	3) L2ARC devices
4461 *	4) vdev cache of disks
4462 *	5) disks
4463 *
4464 * Some L2ARC device types exhibit extremely slow write performance.
4465 * To accommodate for this there are some significant differences between
4466 * the L2ARC and traditional cache design:
4467 *
4468 * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
4469 * the ARC behave as usual, freeing buffers and placing headers on ghost
4470 * lists.  The ARC does not send buffers to the L2ARC during eviction as
4471 * this would add inflated write latencies for all ARC memory pressure.
4472 *
4473 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
4474 * It does this by periodically scanning buffers from the eviction-end of
4475 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
4476 * not already there. It scans until a headroom of buffers is satisfied,
4477 * which itself is a buffer for ARC eviction. If a compressible buffer is
4478 * found during scanning and selected for writing to an L2ARC device, we
4479 * temporarily boost scanning headroom during the next scan cycle to make
4480 * sure we adapt to compression effects (which might significantly reduce
4481 * the data volume we write to L2ARC). The thread that does this is
4482 * l2arc_feed_thread(), illustrated below; example sizes are included to
4483 * provide a better sense of ratio than this diagram:
4484 *
4485 *	       head -->                        tail
4486 *	        +---------------------+----------+
4487 *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
4488 *	        +---------------------+----------+   |   o L2ARC eligible
4489 *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
4490 *	        +---------------------+----------+   |
4491 *	             15.9 Gbytes      ^ 32 Mbytes    |
4492 *	                           headroom          |
4493 *	                                      l2arc_feed_thread()
4494 *	                                             |
4495 *	                 l2arc write hand <--[oooo]--'
4496 *	                         |           8 Mbyte
4497 *	                         |          write max
4498 *	                         V
4499 *		  +==============================+
4500 *	L2ARC dev |####|#|###|###|    |####| ... |
4501 *	          +==============================+
4502 *	                     32 Gbytes
4503 *
4504 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
4505 * evicted, then the L2ARC has cached a buffer much sooner than it probably
4506 * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
4507 * safe to say that this is an uncommon case, since buffers at the end of
4508 * the ARC lists have moved there due to inactivity.
4509 *
4510 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
4511 * then the L2ARC simply misses copying some buffers.  This serves as a
4512 * pressure valve to prevent heavy read workloads from both stalling the ARC
4513 * with waits and clogging the L2ARC with writes.  This also helps prevent
4514 * the potential for the L2ARC to churn if it attempts to cache content too
4515 * quickly, such as during backups of the entire pool.
4516 *
4517 * 5. After system boot and before the ARC has filled main memory, there are
4518 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
4519 * lists can remain mostly static.  Instead of searching from tail of these
4520 * lists as pictured, the l2arc_feed_thread() will search from the list heads
4521 * for eligible buffers, greatly increasing its chance of finding them.
4522 *
4523 * The L2ARC device write speed is also boosted during this time so that
4524 * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
4525 * there are no L2ARC reads, and no fear of degrading read performance
4526 * through increased writes.
4527 *
4528 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
4529 * the vdev queue can aggregate them into larger and fewer writes.  Each
4530 * device is written to in a rotor fashion, sweeping writes through
4531 * available space then repeating.
4532 *
4533 * 7. The L2ARC does not store dirty content.  It never needs to flush
4534 * write buffers back to disk based storage.
4535 *
4536 * 8. If an ARC buffer is written (and dirtied) which also exists in the
4537 * L2ARC, the now stale L2ARC buffer is immediately dropped.
4538 *
4539 * The performance of the L2ARC can be tweaked by a number of tunables, which
4540 * may be necessary for different workloads:
4541 *
4542 *	l2arc_write_max		max write bytes per interval
4543 *	l2arc_write_boost	extra write bytes during device warmup
4544 *	l2arc_noprefetch	skip caching prefetched buffers
4545 *	l2arc_headroom		number of max device writes to precache
4546 *	l2arc_headroom_boost	when we find compressed buffers during ARC
4547 *				scanning, we multiply headroom by this
4548 *				percentage factor for the next scan cycle,
4549 *				since more compressed buffers are likely to
4550 *				be present
4551 *	l2arc_feed_secs		seconds between L2ARC writing
4552 *
4553 * Tunables may be removed or added as future performance improvements are
4554 * integrated, and also may become zpool properties.
4555 *
4556 * There are three key functions that control how the L2ARC warms up:
4557 *
4558 *	l2arc_write_eligible()	check if a buffer is eligible to cache
4559 *	l2arc_write_size()	calculate how much to write
4560 *	l2arc_write_interval()	calculate sleep delay between writes
4561 *
4562 * These three functions determine what to write, how much, and how quickly
4563 * to send writes.
4564 */
4565
4566static boolean_t
4567l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
4568{
4569	/*
4570	 * A buffer is *not* eligible for the L2ARC if it:
4571	 * 1. belongs to a different spa.
4572	 * 2. is already cached on the L2ARC.
4573	 * 3. has an I/O in progress (it may be an incomplete read).
4574	 * 4. is flagged not eligible (zfs property).
4575	 */
4576	if (hdr->b_spa != spa_guid) {
4577		ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
4578		return (B_FALSE);
4579	}
4580	if (hdr->b_l2hdr != NULL) {
4581		ARCSTAT_BUMP(arcstat_l2_write_in_l2);
4582		return (B_FALSE);
4583	}
4584	if (HDR_IO_IN_PROGRESS(hdr)) {
4585		ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
4586		return (B_FALSE);
4587	}
4588	if (!HDR_L2CACHE(hdr)) {
4589		ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
4590		return (B_FALSE);
4591	}
4592
4593	return (B_TRUE);
4594}
4595
4596static uint64_t
4597l2arc_write_size(void)
4598{
4599	uint64_t size;
4600
4601	/*
4602	 * Make sure our globals have meaningful values in case the user
4603	 * altered them.
4604	 */
4605	size = l2arc_write_max;
4606	if (size == 0) {
4607		cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
4608		    "be greater than zero, resetting it to the default (%d)",
4609		    L2ARC_WRITE_SIZE);
4610		size = l2arc_write_max = L2ARC_WRITE_SIZE;
4611	}
4612
4613	if (arc_warm == B_FALSE)
4614		size += l2arc_write_boost;
4615
4616	return (size);
4617
4618}
4619
4620static clock_t
4621l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
4622{
4623	clock_t interval, next, now;
4624
4625	/*
4626	 * If the ARC lists are busy, increase our write rate; if the
4627	 * lists are stale, idle back.  This is achieved by checking
4628	 * how much we previously wrote - if it was more than half of
4629	 * what we wanted, schedule the next write much sooner.
4630	 */
4631	if (l2arc_feed_again && wrote > (wanted / 2))
4632		interval = (hz * l2arc_feed_min_ms) / 1000;
4633	else
4634		interval = hz * l2arc_feed_secs;
4635
4636	now = ddi_get_lbolt();
4637	next = MAX(now, MIN(now + interval, began + interval));
4638
4639	return (next);
4640}
4641
4642static void
4643l2arc_hdr_stat_add(void)
4644{
4645	ARCSTAT_INCR(arcstat_l2_hdr_size, HDR_SIZE + L2HDR_SIZE);
4646	ARCSTAT_INCR(arcstat_hdr_size, -HDR_SIZE);
4647}
4648
4649static void
4650l2arc_hdr_stat_remove(void)
4651{
4652	ARCSTAT_INCR(arcstat_l2_hdr_size, -(HDR_SIZE + L2HDR_SIZE));
4653	ARCSTAT_INCR(arcstat_hdr_size, HDR_SIZE);
4654}
4655
4656/*
4657 * Cycle through L2ARC devices.  This is how L2ARC load balances.
4658 * If a device is returned, this also returns holding the spa config lock.
4659 */
4660static l2arc_dev_t *
4661l2arc_dev_get_next(void)
4662{
4663	l2arc_dev_t *first, *next = NULL;
4664
4665	/*
4666	 * Lock out the removal of spas (spa_namespace_lock), then removal
4667	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
4668	 * both locks will be dropped and a spa config lock held instead.
4669	 */
4670	mutex_enter(&spa_namespace_lock);
4671	mutex_enter(&l2arc_dev_mtx);
4672
4673	/* if there are no vdevs, there is nothing to do */
4674	if (l2arc_ndev == 0)
4675		goto out;
4676
4677	first = NULL;
4678	next = l2arc_dev_last;
4679	do {
4680		/* loop around the list looking for a non-faulted vdev */
4681		if (next == NULL) {
4682			next = list_head(l2arc_dev_list);
4683		} else {
4684			next = list_next(l2arc_dev_list, next);
4685			if (next == NULL)
4686				next = list_head(l2arc_dev_list);
4687		}
4688
4689		/* if we have come back to the start, bail out */
4690		if (first == NULL)
4691			first = next;
4692		else if (next == first)
4693			break;
4694
4695	} while (vdev_is_dead(next->l2ad_vdev));
4696
4697	/* if we were unable to find any usable vdevs, return NULL */
4698	if (vdev_is_dead(next->l2ad_vdev))
4699		next = NULL;
4700
4701	l2arc_dev_last = next;
4702
4703out:
4704	mutex_exit(&l2arc_dev_mtx);
4705
4706	/*
4707	 * Grab the config lock to prevent the 'next' device from being
4708	 * removed while we are writing to it.
4709	 */
4710	if (next != NULL)
4711		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
4712	mutex_exit(&spa_namespace_lock);
4713
4714	return (next);
4715}
4716
4717/*
4718 * Free buffers that were tagged for destruction.
4719 */
4720static void
4721l2arc_do_free_on_write()
4722{
4723	list_t *buflist;
4724	l2arc_data_free_t *df, *df_prev;
4725
4726	mutex_enter(&l2arc_free_on_write_mtx);
4727	buflist = l2arc_free_on_write;
4728
4729	for (df = list_tail(buflist); df; df = df_prev) {
4730		df_prev = list_prev(buflist, df);
4731		ASSERT(df->l2df_data != NULL);
4732		ASSERT(df->l2df_func != NULL);
4733		df->l2df_func(df->l2df_data, df->l2df_size);
4734		list_remove(buflist, df);
4735		kmem_free(df, sizeof (l2arc_data_free_t));
4736	}
4737
4738	mutex_exit(&l2arc_free_on_write_mtx);
4739}
4740
4741/*
4742 * A write to a cache device has completed.  Update all headers to allow
4743 * reads from these buffers to begin.
4744 */
4745static void
4746l2arc_write_done(zio_t *zio)
4747{
4748	l2arc_write_callback_t *cb;
4749	l2arc_dev_t *dev;
4750	list_t *buflist;
4751	arc_buf_hdr_t *head, *hdr, *hdr_prev;
4752	l2arc_buf_hdr_t *abl2;
4753	kmutex_t *hash_lock;
4754	int64_t bytes_dropped = 0;
4755
4756	cb = zio->io_private;
4757	ASSERT(cb != NULL);
4758	dev = cb->l2wcb_dev;
4759	ASSERT(dev != NULL);
4760	head = cb->l2wcb_head;
4761	ASSERT(head != NULL);
4762	buflist = dev->l2ad_buflist;
4763	ASSERT(buflist != NULL);
4764	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
4765	    l2arc_write_callback_t *, cb);
4766
4767	if (zio->io_error != 0)
4768		ARCSTAT_BUMP(arcstat_l2_writes_error);
4769
4770	mutex_enter(&l2arc_buflist_mtx);
4771
4772	/*
4773	 * All writes completed, or an error was hit.
4774	 */
4775	for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
4776		hdr_prev = list_prev(buflist, hdr);
4777		abl2 = hdr->b_l2hdr;
4778
4779		/*
4780		 * Release the temporary compressed buffer as soon as possible.
4781		 */
4782		if (abl2->b_compress != ZIO_COMPRESS_OFF)
4783			l2arc_release_cdata_buf(hdr);
4784
4785		hash_lock = HDR_LOCK(hdr);
4786		if (!mutex_tryenter(hash_lock)) {
4787			/*
4788			 * This buffer misses out.  It may be in a stage
4789			 * of eviction.  Its ARC_L2_WRITING flag will be
4790			 * left set, denying reads to this buffer.
4791			 */
4792			ARCSTAT_BUMP(arcstat_l2_writes_hdr_miss);
4793			continue;
4794		}
4795
4796		if (zio->io_error != 0) {
4797			/*
4798			 * Error - drop L2ARC entry.
4799			 */
4800			list_remove(buflist, hdr);
4801			ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
4802			bytes_dropped += abl2->b_asize;
4803			hdr->b_l2hdr = NULL;
4804			trim_map_free(abl2->b_dev->l2ad_vdev, abl2->b_daddr,
4805			    hdr->b_size, 0);
4806			kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
4807			ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
4808		}
4809
4810		/*
4811		 * Allow ARC to begin reads to this L2ARC entry.
4812		 */
4813		hdr->b_flags &= ~ARC_FLAG_L2_WRITING;
4814
4815		mutex_exit(hash_lock);
4816	}
4817
4818	atomic_inc_64(&l2arc_writes_done);
4819	list_remove(buflist, head);
4820	kmem_cache_free(hdr_cache, head);
4821	mutex_exit(&l2arc_buflist_mtx);
4822
4823	vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
4824
4825	l2arc_do_free_on_write();
4826
4827	kmem_free(cb, sizeof (l2arc_write_callback_t));
4828}
4829
4830/*
4831 * A read to a cache device completed.  Validate buffer contents before
4832 * handing over to the regular ARC routines.
4833 */
4834static void
4835l2arc_read_done(zio_t *zio)
4836{
4837	l2arc_read_callback_t *cb;
4838	arc_buf_hdr_t *hdr;
4839	arc_buf_t *buf;
4840	kmutex_t *hash_lock;
4841	int equal;
4842
4843	ASSERT(zio->io_vd != NULL);
4844	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
4845
4846	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
4847
4848	cb = zio->io_private;
4849	ASSERT(cb != NULL);
4850	buf = cb->l2rcb_buf;
4851	ASSERT(buf != NULL);
4852
4853	hash_lock = HDR_LOCK(buf->b_hdr);
4854	mutex_enter(hash_lock);
4855	hdr = buf->b_hdr;
4856	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4857
4858	/*
4859	 * If the buffer was compressed, decompress it first.
4860	 */
4861	if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
4862		l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
4863	ASSERT(zio->io_data != NULL);
4864
4865	/*
4866	 * Check this survived the L2ARC journey.
4867	 */
4868	equal = arc_cksum_equal(buf);
4869	if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
4870		mutex_exit(hash_lock);
4871		zio->io_private = buf;
4872		zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
4873		zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
4874		arc_read_done(zio);
4875	} else {
4876		mutex_exit(hash_lock);
4877		/*
4878		 * Buffer didn't survive caching.  Increment stats and
4879		 * reissue to the original storage device.
4880		 */
4881		if (zio->io_error != 0) {
4882			ARCSTAT_BUMP(arcstat_l2_io_error);
4883		} else {
4884			zio->io_error = SET_ERROR(EIO);
4885		}
4886		if (!equal)
4887			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
4888
4889		/*
4890		 * If there's no waiter, issue an async i/o to the primary
4891		 * storage now.  If there *is* a waiter, the caller must
4892		 * issue the i/o in a context where it's OK to block.
4893		 */
4894		if (zio->io_waiter == NULL) {
4895			zio_t *pio = zio_unique_parent(zio);
4896
4897			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
4898
4899			zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
4900			    buf->b_data, zio->io_size, arc_read_done, buf,
4901			    zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
4902		}
4903	}
4904
4905	kmem_free(cb, sizeof (l2arc_read_callback_t));
4906}
4907
4908/*
4909 * This is the list priority from which the L2ARC will search for pages to
4910 * cache.  This is used within loops (0..3) to cycle through lists in the
4911 * desired order.  This order can have a significant effect on cache
4912 * performance.
4913 *
4914 * Currently the metadata lists are hit first, MFU then MRU, followed by
4915 * the data lists.  This function returns a locked list, and also returns
4916 * the lock pointer.
4917 */
4918static list_t *
4919l2arc_list_locked(int list_num, kmutex_t **lock)
4920{
4921	list_t *list = NULL;
4922	int idx;
4923
4924	ASSERT(list_num >= 0 && list_num < 2 * ARC_BUFC_NUMLISTS);
4925
4926	if (list_num < ARC_BUFC_NUMMETADATALISTS) {
4927		idx = list_num;
4928		list = &arc_mfu->arcs_lists[idx];
4929		*lock = ARCS_LOCK(arc_mfu, idx);
4930	} else if (list_num < ARC_BUFC_NUMMETADATALISTS * 2) {
4931		idx = list_num - ARC_BUFC_NUMMETADATALISTS;
4932		list = &arc_mru->arcs_lists[idx];
4933		*lock = ARCS_LOCK(arc_mru, idx);
4934	} else if (list_num < (ARC_BUFC_NUMMETADATALISTS * 2 +
4935		ARC_BUFC_NUMDATALISTS)) {
4936		idx = list_num - ARC_BUFC_NUMMETADATALISTS;
4937		list = &arc_mfu->arcs_lists[idx];
4938		*lock = ARCS_LOCK(arc_mfu, idx);
4939	} else {
4940		idx = list_num - ARC_BUFC_NUMLISTS;
4941		list = &arc_mru->arcs_lists[idx];
4942		*lock = ARCS_LOCK(arc_mru, idx);
4943	}
4944
4945	ASSERT(!(MUTEX_HELD(*lock)));
4946	mutex_enter(*lock);
4947	return (list);
4948}
4949
4950/*
4951 * Evict buffers from the device write hand to the distance specified in
4952 * bytes.  This distance may span populated buffers, it may span nothing.
4953 * This is clearing a region on the L2ARC device ready for writing.
4954 * If the 'all' boolean is set, every buffer is evicted.
4955 */
4956static void
4957l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
4958{
4959	list_t *buflist;
4960	l2arc_buf_hdr_t *abl2;
4961	arc_buf_hdr_t *hdr, *hdr_prev;
4962	kmutex_t *hash_lock;
4963	uint64_t taddr;
4964	int64_t bytes_evicted = 0;
4965
4966	buflist = dev->l2ad_buflist;
4967
4968	if (buflist == NULL)
4969		return;
4970
4971	if (!all && dev->l2ad_first) {
4972		/*
4973		 * This is the first sweep through the device.  There is
4974		 * nothing to evict.
4975		 */
4976		return;
4977	}
4978
4979	if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
4980		/*
4981		 * When nearing the end of the device, evict to the end
4982		 * before the device write hand jumps to the start.
4983		 */
4984		taddr = dev->l2ad_end;
4985	} else {
4986		taddr = dev->l2ad_hand + distance;
4987	}
4988	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
4989	    uint64_t, taddr, boolean_t, all);
4990
4991top:
4992	mutex_enter(&l2arc_buflist_mtx);
4993	for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
4994		hdr_prev = list_prev(buflist, hdr);
4995
4996		hash_lock = HDR_LOCK(hdr);
4997		if (!mutex_tryenter(hash_lock)) {
4998			/*
4999			 * Missed the hash lock.  Retry.
5000			 */
5001			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
5002			mutex_exit(&l2arc_buflist_mtx);
5003			mutex_enter(hash_lock);
5004			mutex_exit(hash_lock);
5005			goto top;
5006		}
5007
5008		if (HDR_L2_WRITE_HEAD(hdr)) {
5009			/*
5010			 * We hit a write head node.  Leave it for
5011			 * l2arc_write_done().
5012			 */
5013			list_remove(buflist, hdr);
5014			mutex_exit(hash_lock);
5015			continue;
5016		}
5017
5018		if (!all && hdr->b_l2hdr != NULL &&
5019		    (hdr->b_l2hdr->b_daddr > taddr ||
5020		    hdr->b_l2hdr->b_daddr < dev->l2ad_hand)) {
5021			/*
5022			 * We've evicted to the target address,
5023			 * or the end of the device.
5024			 */
5025			mutex_exit(hash_lock);
5026			break;
5027		}
5028
5029		if (HDR_FREE_IN_PROGRESS(hdr)) {
5030			/*
5031			 * Already on the path to destruction.
5032			 */
5033			mutex_exit(hash_lock);
5034			continue;
5035		}
5036
5037		if (hdr->b_state == arc_l2c_only) {
5038			ASSERT(!HDR_L2_READING(hdr));
5039			/*
5040			 * This doesn't exist in the ARC.  Destroy.
5041			 * arc_hdr_destroy() will call list_remove()
5042			 * and decrement arcstat_l2_size.
5043			 */
5044			arc_change_state(arc_anon, hdr, hash_lock);
5045			arc_hdr_destroy(hdr);
5046		} else {
5047			/*
5048			 * Invalidate issued or about to be issued
5049			 * reads, since we may be about to write
5050			 * over this location.
5051			 */
5052			if (HDR_L2_READING(hdr)) {
5053				ARCSTAT_BUMP(arcstat_l2_evict_reading);
5054				hdr->b_flags |= ARC_FLAG_L2_EVICTED;
5055			}
5056
5057			/*
5058			 * Tell ARC this no longer exists in L2ARC.
5059			 */
5060			if (hdr->b_l2hdr != NULL) {
5061				abl2 = hdr->b_l2hdr;
5062				ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
5063				bytes_evicted += abl2->b_asize;
5064				hdr->b_l2hdr = NULL;
5065				/*
5066				 * We are destroying l2hdr, so ensure that
5067				 * its compressed buffer, if any, is not leaked.
5068				 */
5069				ASSERT(abl2->b_tmp_cdata == NULL);
5070				kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
5071				ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
5072			}
5073			list_remove(buflist, hdr);
5074
5075			/*
5076			 * This may have been leftover after a
5077			 * failed write.
5078			 */
5079			hdr->b_flags &= ~ARC_FLAG_L2_WRITING;
5080		}
5081		mutex_exit(hash_lock);
5082	}
5083	mutex_exit(&l2arc_buflist_mtx);
5084
5085	vdev_space_update(dev->l2ad_vdev, -bytes_evicted, 0, 0);
5086	dev->l2ad_evict = taddr;
5087}
5088
5089/*
5090 * Find and write ARC buffers to the L2ARC device.
5091 *
5092 * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
5093 * for reading until they have completed writing.
5094 * The headroom_boost is an in-out parameter used to maintain headroom boost
5095 * state between calls to this function.
5096 *
5097 * Returns the number of bytes actually written (which may be smaller than
5098 * the delta by which the device hand has changed due to alignment).
5099 */
5100static uint64_t
5101l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
5102    boolean_t *headroom_boost)
5103{
5104	arc_buf_hdr_t *hdr, *hdr_prev, *head;
5105	list_t *list;
5106	uint64_t write_asize, write_psize, write_sz, headroom,
5107	    buf_compress_minsz;
5108	void *buf_data;
5109	kmutex_t *list_lock;
5110	boolean_t full;
5111	l2arc_write_callback_t *cb;
5112	zio_t *pio, *wzio;
5113	uint64_t guid = spa_load_guid(spa);
5114	const boolean_t do_headroom_boost = *headroom_boost;
5115	int try;
5116
5117	ASSERT(dev->l2ad_vdev != NULL);
5118
5119	/* Lower the flag now, we might want to raise it again later. */
5120	*headroom_boost = B_FALSE;
5121
5122	pio = NULL;
5123	write_sz = write_asize = write_psize = 0;
5124	full = B_FALSE;
5125	head = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
5126	head->b_flags |= ARC_FLAG_L2_WRITE_HEAD;
5127
5128	ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
5129	/*
5130	 * We will want to try to compress buffers that are at least 2x the
5131	 * device sector size.
5132	 */
5133	buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
5134
5135	/*
5136	 * Copy buffers for L2ARC writing.
5137	 */
5138	mutex_enter(&l2arc_buflist_mtx);
5139	for (try = 0; try < 2 * ARC_BUFC_NUMLISTS; try++) {
5140		uint64_t passed_sz = 0;
5141
5142		list = l2arc_list_locked(try, &list_lock);
5143		ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
5144
5145		/*
5146		 * L2ARC fast warmup.
5147		 *
5148		 * Until the ARC is warm and starts to evict, read from the
5149		 * head of the ARC lists rather than the tail.
5150		 */
5151		if (arc_warm == B_FALSE)
5152			hdr = list_head(list);
5153		else
5154			hdr = list_tail(list);
5155		if (hdr == NULL)
5156			ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
5157
5158		headroom = target_sz * l2arc_headroom * 2 / ARC_BUFC_NUMLISTS;
5159		if (do_headroom_boost)
5160			headroom = (headroom * l2arc_headroom_boost) / 100;
5161
5162		for (; hdr; hdr = hdr_prev) {
5163			l2arc_buf_hdr_t *l2hdr;
5164			kmutex_t *hash_lock;
5165			uint64_t buf_sz;
5166
5167			if (arc_warm == B_FALSE)
5168				hdr_prev = list_next(list, hdr);
5169			else
5170				hdr_prev = list_prev(list, hdr);
5171			ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned, hdr->b_size);
5172
5173			hash_lock = HDR_LOCK(hdr);
5174			if (!mutex_tryenter(hash_lock)) {
5175				ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
5176				/*
5177				 * Skip this buffer rather than waiting.
5178				 */
5179				continue;
5180			}
5181
5182			passed_sz += hdr->b_size;
5183			if (passed_sz > headroom) {
5184				/*
5185				 * Searched too far.
5186				 */
5187				mutex_exit(hash_lock);
5188				ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
5189				break;
5190			}
5191
5192			if (!l2arc_write_eligible(guid, hdr)) {
5193				mutex_exit(hash_lock);
5194				continue;
5195			}
5196
5197			if ((write_sz + hdr->b_size) > target_sz) {
5198				full = B_TRUE;
5199				mutex_exit(hash_lock);
5200				ARCSTAT_BUMP(arcstat_l2_write_full);
5201				break;
5202			}
5203
5204			if (pio == NULL) {
5205				/*
5206				 * Insert a dummy header on the buflist so
5207				 * l2arc_write_done() can find where the
5208				 * write buffers begin without searching.
5209				 */
5210				list_insert_head(dev->l2ad_buflist, head);
5211
5212				cb = kmem_alloc(
5213				    sizeof (l2arc_write_callback_t), KM_SLEEP);
5214				cb->l2wcb_dev = dev;
5215				cb->l2wcb_head = head;
5216				pio = zio_root(spa, l2arc_write_done, cb,
5217				    ZIO_FLAG_CANFAIL);
5218				ARCSTAT_BUMP(arcstat_l2_write_pios);
5219			}
5220
5221			/*
5222			 * Create and add a new L2ARC header.
5223			 */
5224			l2hdr = kmem_zalloc(sizeof (l2arc_buf_hdr_t), KM_SLEEP);
5225			l2hdr->b_dev = dev;
5226			hdr->b_flags |= ARC_FLAG_L2_WRITING;
5227
5228			/*
5229			 * Temporarily stash the data buffer in b_tmp_cdata.
5230			 * The subsequent write step will pick it up from
5231			 * there. This is because can't access hdr->b_buf
5232			 * without holding the hash_lock, which we in turn
5233			 * can't access without holding the ARC list locks
5234			 * (which we want to avoid during compression/writing).
5235			 */
5236			l2hdr->b_compress = ZIO_COMPRESS_OFF;
5237			l2hdr->b_asize = hdr->b_size;
5238			l2hdr->b_tmp_cdata = hdr->b_buf->b_data;
5239
5240			buf_sz = hdr->b_size;
5241			hdr->b_l2hdr = l2hdr;
5242
5243			list_insert_head(dev->l2ad_buflist, hdr);
5244
5245			/*
5246			 * Compute and store the buffer cksum before
5247			 * writing.  On debug the cksum is verified first.
5248			 */
5249			arc_cksum_verify(hdr->b_buf);
5250			arc_cksum_compute(hdr->b_buf, B_TRUE);
5251
5252			mutex_exit(hash_lock);
5253
5254			write_sz += buf_sz;
5255		}
5256
5257		mutex_exit(list_lock);
5258
5259		if (full == B_TRUE)
5260			break;
5261	}
5262
5263	/* No buffers selected for writing? */
5264	if (pio == NULL) {
5265		ASSERT0(write_sz);
5266		mutex_exit(&l2arc_buflist_mtx);
5267		kmem_cache_free(hdr_cache, head);
5268		return (0);
5269	}
5270
5271	/*
5272	 * Now start writing the buffers. We're starting at the write head
5273	 * and work backwards, retracing the course of the buffer selector
5274	 * loop above.
5275	 */
5276	for (hdr = list_prev(dev->l2ad_buflist, head); hdr;
5277	    hdr = list_prev(dev->l2ad_buflist, hdr)) {
5278		l2arc_buf_hdr_t *l2hdr;
5279		uint64_t buf_sz;
5280
5281		/*
5282		 * We shouldn't need to lock the buffer here, since we flagged
5283		 * it as ARC_FLAG_L2_WRITING in the previous step, but we must
5284		 * take care to only access its L2 cache parameters. In
5285		 * particular, hdr->b_buf may be invalid by now due to
5286		 * ARC eviction.
5287		 */
5288		l2hdr = hdr->b_l2hdr;
5289		l2hdr->b_daddr = dev->l2ad_hand;
5290
5291		if ((hdr->b_flags & ARC_FLAG_L2COMPRESS) &&
5292		    l2hdr->b_asize >= buf_compress_minsz) {
5293			if (l2arc_compress_buf(l2hdr)) {
5294				/*
5295				 * If compression succeeded, enable headroom
5296				 * boost on the next scan cycle.
5297				 */
5298				*headroom_boost = B_TRUE;
5299			}
5300		}
5301
5302		/*
5303		 * Pick up the buffer data we had previously stashed away
5304		 * (and now potentially also compressed).
5305		 */
5306		buf_data = l2hdr->b_tmp_cdata;
5307		buf_sz = l2hdr->b_asize;
5308
5309		/*
5310		 * If the data has not been compressed, then clear b_tmp_cdata
5311		 * to make sure that it points only to a temporary compression
5312		 * buffer.
5313		 */
5314		if (!L2ARC_IS_VALID_COMPRESS(l2hdr->b_compress))
5315			l2hdr->b_tmp_cdata = NULL;
5316
5317		/* Compression may have squashed the buffer to zero length. */
5318		if (buf_sz != 0) {
5319			uint64_t buf_p_sz;
5320
5321			wzio = zio_write_phys(pio, dev->l2ad_vdev,
5322			    dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
5323			    NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
5324			    ZIO_FLAG_CANFAIL, B_FALSE);
5325
5326			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
5327			    zio_t *, wzio);
5328			(void) zio_nowait(wzio);
5329
5330			write_asize += buf_sz;
5331			/*
5332			 * Keep the clock hand suitably device-aligned.
5333			 */
5334			buf_p_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
5335			write_psize += buf_p_sz;
5336			dev->l2ad_hand += buf_p_sz;
5337		}
5338	}
5339
5340	mutex_exit(&l2arc_buflist_mtx);
5341
5342	ASSERT3U(write_asize, <=, target_sz);
5343	ARCSTAT_BUMP(arcstat_l2_writes_sent);
5344	ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
5345	ARCSTAT_INCR(arcstat_l2_size, write_sz);
5346	ARCSTAT_INCR(arcstat_l2_asize, write_asize);
5347	vdev_space_update(dev->l2ad_vdev, write_asize, 0, 0);
5348
5349	/*
5350	 * Bump device hand to the device start if it is approaching the end.
5351	 * l2arc_evict() will already have evicted ahead for this case.
5352	 */
5353	if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
5354		dev->l2ad_hand = dev->l2ad_start;
5355		dev->l2ad_evict = dev->l2ad_start;
5356		dev->l2ad_first = B_FALSE;
5357	}
5358
5359	dev->l2ad_writing = B_TRUE;
5360	(void) zio_wait(pio);
5361	dev->l2ad_writing = B_FALSE;
5362
5363	return (write_asize);
5364}
5365
5366/*
5367 * Compresses an L2ARC buffer.
5368 * The data to be compressed must be prefilled in l2hdr->b_tmp_cdata and its
5369 * size in l2hdr->b_asize. This routine tries to compress the data and
5370 * depending on the compression result there are three possible outcomes:
5371 * *) The buffer was incompressible. The original l2hdr contents were left
5372 *    untouched and are ready for writing to an L2 device.
5373 * *) The buffer was all-zeros, so there is no need to write it to an L2
5374 *    device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
5375 *    set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
5376 * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
5377 *    data buffer which holds the compressed data to be written, and b_asize
5378 *    tells us how much data there is. b_compress is set to the appropriate
5379 *    compression algorithm. Once writing is done, invoke
5380 *    l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
5381 *
5382 * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
5383 * buffer was incompressible).
5384 */
5385static boolean_t
5386l2arc_compress_buf(l2arc_buf_hdr_t *l2hdr)
5387{
5388	void *cdata;
5389	size_t csize, len, rounded;
5390
5391	ASSERT(l2hdr->b_compress == ZIO_COMPRESS_OFF);
5392	ASSERT(l2hdr->b_tmp_cdata != NULL);
5393
5394	len = l2hdr->b_asize;
5395	cdata = zio_data_buf_alloc(len);
5396	csize = zio_compress_data(ZIO_COMPRESS_LZ4, l2hdr->b_tmp_cdata,
5397	    cdata, l2hdr->b_asize);
5398
5399	if (csize == 0) {
5400		/* zero block, indicate that there's nothing to write */
5401		zio_data_buf_free(cdata, len);
5402		l2hdr->b_compress = ZIO_COMPRESS_EMPTY;
5403		l2hdr->b_asize = 0;
5404		l2hdr->b_tmp_cdata = NULL;
5405		ARCSTAT_BUMP(arcstat_l2_compress_zeros);
5406		return (B_TRUE);
5407	}
5408
5409	rounded = P2ROUNDUP(csize,
5410	    (size_t)1 << l2hdr->b_dev->l2ad_vdev->vdev_ashift);
5411	if (rounded < len) {
5412		/*
5413		 * Compression succeeded, we'll keep the cdata around for
5414		 * writing and release it afterwards.
5415		 */
5416		if (rounded > csize) {
5417			bzero((char *)cdata + csize, rounded - csize);
5418			csize = rounded;
5419		}
5420		l2hdr->b_compress = ZIO_COMPRESS_LZ4;
5421		l2hdr->b_asize = csize;
5422		l2hdr->b_tmp_cdata = cdata;
5423		ARCSTAT_BUMP(arcstat_l2_compress_successes);
5424		return (B_TRUE);
5425	} else {
5426		/*
5427		 * Compression failed, release the compressed buffer.
5428		 * l2hdr will be left unmodified.
5429		 */
5430		zio_data_buf_free(cdata, len);
5431		ARCSTAT_BUMP(arcstat_l2_compress_failures);
5432		return (B_FALSE);
5433	}
5434}
5435
5436/*
5437 * Decompresses a zio read back from an l2arc device. On success, the
5438 * underlying zio's io_data buffer is overwritten by the uncompressed
5439 * version. On decompression error (corrupt compressed stream), the
5440 * zio->io_error value is set to signal an I/O error.
5441 *
5442 * Please note that the compressed data stream is not checksummed, so
5443 * if the underlying device is experiencing data corruption, we may feed
5444 * corrupt data to the decompressor, so the decompressor needs to be
5445 * able to handle this situation (LZ4 does).
5446 */
5447static void
5448l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
5449{
5450	ASSERT(L2ARC_IS_VALID_COMPRESS(c));
5451
5452	if (zio->io_error != 0) {
5453		/*
5454		 * An io error has occured, just restore the original io
5455		 * size in preparation for a main pool read.
5456		 */
5457		zio->io_orig_size = zio->io_size = hdr->b_size;
5458		return;
5459	}
5460
5461	if (c == ZIO_COMPRESS_EMPTY) {
5462		/*
5463		 * An empty buffer results in a null zio, which means we
5464		 * need to fill its io_data after we're done restoring the
5465		 * buffer's contents.
5466		 */
5467		ASSERT(hdr->b_buf != NULL);
5468		bzero(hdr->b_buf->b_data, hdr->b_size);
5469		zio->io_data = zio->io_orig_data = hdr->b_buf->b_data;
5470	} else {
5471		ASSERT(zio->io_data != NULL);
5472		/*
5473		 * We copy the compressed data from the start of the arc buffer
5474		 * (the zio_read will have pulled in only what we need, the
5475		 * rest is garbage which we will overwrite at decompression)
5476		 * and then decompress back to the ARC data buffer. This way we
5477		 * can minimize copying by simply decompressing back over the
5478		 * original compressed data (rather than decompressing to an
5479		 * aux buffer and then copying back the uncompressed buffer,
5480		 * which is likely to be much larger).
5481		 */
5482		uint64_t csize;
5483		void *cdata;
5484
5485		csize = zio->io_size;
5486		cdata = zio_data_buf_alloc(csize);
5487		bcopy(zio->io_data, cdata, csize);
5488		if (zio_decompress_data(c, cdata, zio->io_data, csize,
5489		    hdr->b_size) != 0)
5490			zio->io_error = EIO;
5491		zio_data_buf_free(cdata, csize);
5492	}
5493
5494	/* Restore the expected uncompressed IO size. */
5495	zio->io_orig_size = zio->io_size = hdr->b_size;
5496}
5497
5498/*
5499 * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
5500 * This buffer serves as a temporary holder of compressed data while
5501 * the buffer entry is being written to an l2arc device. Once that is
5502 * done, we can dispose of it.
5503 */
5504static void
5505l2arc_release_cdata_buf(arc_buf_hdr_t *hdr)
5506{
5507	l2arc_buf_hdr_t *l2hdr = hdr->b_l2hdr;
5508
5509	ASSERT(L2ARC_IS_VALID_COMPRESS(l2hdr->b_compress));
5510	if (l2hdr->b_compress != ZIO_COMPRESS_EMPTY) {
5511		/*
5512		 * If the data was compressed, then we've allocated a
5513		 * temporary buffer for it, so now we need to release it.
5514		 */
5515		ASSERT(l2hdr->b_tmp_cdata != NULL);
5516		zio_data_buf_free(l2hdr->b_tmp_cdata, hdr->b_size);
5517		l2hdr->b_tmp_cdata = NULL;
5518	} else {
5519		ASSERT(l2hdr->b_tmp_cdata == NULL);
5520	}
5521}
5522
5523/*
5524 * This thread feeds the L2ARC at regular intervals.  This is the beating
5525 * heart of the L2ARC.
5526 */
5527static void
5528l2arc_feed_thread(void *dummy __unused)
5529{
5530	callb_cpr_t cpr;
5531	l2arc_dev_t *dev;
5532	spa_t *spa;
5533	uint64_t size, wrote;
5534	clock_t begin, next = ddi_get_lbolt();
5535	boolean_t headroom_boost = B_FALSE;
5536
5537	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
5538
5539	mutex_enter(&l2arc_feed_thr_lock);
5540
5541	while (l2arc_thread_exit == 0) {
5542		CALLB_CPR_SAFE_BEGIN(&cpr);
5543		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
5544		    next - ddi_get_lbolt());
5545		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
5546		next = ddi_get_lbolt() + hz;
5547
5548		/*
5549		 * Quick check for L2ARC devices.
5550		 */
5551		mutex_enter(&l2arc_dev_mtx);
5552		if (l2arc_ndev == 0) {
5553			mutex_exit(&l2arc_dev_mtx);
5554			continue;
5555		}
5556		mutex_exit(&l2arc_dev_mtx);
5557		begin = ddi_get_lbolt();
5558
5559		/*
5560		 * This selects the next l2arc device to write to, and in
5561		 * doing so the next spa to feed from: dev->l2ad_spa.   This
5562		 * will return NULL if there are now no l2arc devices or if
5563		 * they are all faulted.
5564		 *
5565		 * If a device is returned, its spa's config lock is also
5566		 * held to prevent device removal.  l2arc_dev_get_next()
5567		 * will grab and release l2arc_dev_mtx.
5568		 */
5569		if ((dev = l2arc_dev_get_next()) == NULL)
5570			continue;
5571
5572		spa = dev->l2ad_spa;
5573		ASSERT(spa != NULL);
5574
5575		/*
5576		 * If the pool is read-only then force the feed thread to
5577		 * sleep a little longer.
5578		 */
5579		if (!spa_writeable(spa)) {
5580			next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
5581			spa_config_exit(spa, SCL_L2ARC, dev);
5582			continue;
5583		}
5584
5585		/*
5586		 * Avoid contributing to memory pressure.
5587		 */
5588		if (arc_reclaim_needed()) {
5589			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
5590			spa_config_exit(spa, SCL_L2ARC, dev);
5591			continue;
5592		}
5593
5594		ARCSTAT_BUMP(arcstat_l2_feeds);
5595
5596		size = l2arc_write_size();
5597
5598		/*
5599		 * Evict L2ARC buffers that will be overwritten.
5600		 */
5601		l2arc_evict(dev, size, B_FALSE);
5602
5603		/*
5604		 * Write ARC buffers.
5605		 */
5606		wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
5607
5608		/*
5609		 * Calculate interval between writes.
5610		 */
5611		next = l2arc_write_interval(begin, size, wrote);
5612		spa_config_exit(spa, SCL_L2ARC, dev);
5613	}
5614
5615	l2arc_thread_exit = 0;
5616	cv_broadcast(&l2arc_feed_thr_cv);
5617	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
5618	thread_exit();
5619}
5620
5621boolean_t
5622l2arc_vdev_present(vdev_t *vd)
5623{
5624	l2arc_dev_t *dev;
5625
5626	mutex_enter(&l2arc_dev_mtx);
5627	for (dev = list_head(l2arc_dev_list); dev != NULL;
5628	    dev = list_next(l2arc_dev_list, dev)) {
5629		if (dev->l2ad_vdev == vd)
5630			break;
5631	}
5632	mutex_exit(&l2arc_dev_mtx);
5633
5634	return (dev != NULL);
5635}
5636
5637/*
5638 * Add a vdev for use by the L2ARC.  By this point the spa has already
5639 * validated the vdev and opened it.
5640 */
5641void
5642l2arc_add_vdev(spa_t *spa, vdev_t *vd)
5643{
5644	l2arc_dev_t *adddev;
5645
5646	ASSERT(!l2arc_vdev_present(vd));
5647
5648	vdev_ashift_optimize(vd);
5649
5650	/*
5651	 * Create a new l2arc device entry.
5652	 */
5653	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
5654	adddev->l2ad_spa = spa;
5655	adddev->l2ad_vdev = vd;
5656	adddev->l2ad_start = VDEV_LABEL_START_SIZE;
5657	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
5658	adddev->l2ad_hand = adddev->l2ad_start;
5659	adddev->l2ad_evict = adddev->l2ad_start;
5660	adddev->l2ad_first = B_TRUE;
5661	adddev->l2ad_writing = B_FALSE;
5662
5663	/*
5664	 * This is a list of all ARC buffers that are still valid on the
5665	 * device.
5666	 */
5667	adddev->l2ad_buflist = kmem_zalloc(sizeof (list_t), KM_SLEEP);
5668	list_create(adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
5669	    offsetof(arc_buf_hdr_t, b_l2node));
5670
5671	vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
5672
5673	/*
5674	 * Add device to global list
5675	 */
5676	mutex_enter(&l2arc_dev_mtx);
5677	list_insert_head(l2arc_dev_list, adddev);
5678	atomic_inc_64(&l2arc_ndev);
5679	mutex_exit(&l2arc_dev_mtx);
5680}
5681
5682/*
5683 * Remove a vdev from the L2ARC.
5684 */
5685void
5686l2arc_remove_vdev(vdev_t *vd)
5687{
5688	l2arc_dev_t *dev, *nextdev, *remdev = NULL;
5689
5690	/*
5691	 * Find the device by vdev
5692	 */
5693	mutex_enter(&l2arc_dev_mtx);
5694	for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
5695		nextdev = list_next(l2arc_dev_list, dev);
5696		if (vd == dev->l2ad_vdev) {
5697			remdev = dev;
5698			break;
5699		}
5700	}
5701	ASSERT(remdev != NULL);
5702
5703	/*
5704	 * Remove device from global list
5705	 */
5706	list_remove(l2arc_dev_list, remdev);
5707	l2arc_dev_last = NULL;		/* may have been invalidated */
5708	atomic_dec_64(&l2arc_ndev);
5709	mutex_exit(&l2arc_dev_mtx);
5710
5711	/*
5712	 * Clear all buflists and ARC references.  L2ARC device flush.
5713	 */
5714	l2arc_evict(remdev, 0, B_TRUE);
5715	list_destroy(remdev->l2ad_buflist);
5716	kmem_free(remdev->l2ad_buflist, sizeof (list_t));
5717	kmem_free(remdev, sizeof (l2arc_dev_t));
5718}
5719
5720void
5721l2arc_init(void)
5722{
5723	l2arc_thread_exit = 0;
5724	l2arc_ndev = 0;
5725	l2arc_writes_sent = 0;
5726	l2arc_writes_done = 0;
5727
5728	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
5729	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
5730	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
5731	mutex_init(&l2arc_buflist_mtx, NULL, MUTEX_DEFAULT, NULL);
5732	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
5733
5734	l2arc_dev_list = &L2ARC_dev_list;
5735	l2arc_free_on_write = &L2ARC_free_on_write;
5736	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
5737	    offsetof(l2arc_dev_t, l2ad_node));
5738	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
5739	    offsetof(l2arc_data_free_t, l2df_list_node));
5740}
5741
5742void
5743l2arc_fini(void)
5744{
5745	/*
5746	 * This is called from dmu_fini(), which is called from spa_fini();
5747	 * Because of this, we can assume that all l2arc devices have
5748	 * already been removed when the pools themselves were removed.
5749	 */
5750
5751	l2arc_do_free_on_write();
5752
5753	mutex_destroy(&l2arc_feed_thr_lock);
5754	cv_destroy(&l2arc_feed_thr_cv);
5755	mutex_destroy(&l2arc_dev_mtx);
5756	mutex_destroy(&l2arc_buflist_mtx);
5757	mutex_destroy(&l2arc_free_on_write_mtx);
5758
5759	list_destroy(l2arc_dev_list);
5760	list_destroy(l2arc_free_on_write);
5761}
5762
5763void
5764l2arc_start(void)
5765{
5766	if (!(spa_mode_global & FWRITE))
5767		return;
5768
5769	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
5770	    TS_RUN, minclsyspri);
5771}
5772
5773void
5774l2arc_stop(void)
5775{
5776	if (!(spa_mode_global & FWRITE))
5777		return;
5778
5779	mutex_enter(&l2arc_feed_thr_lock);
5780	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
5781	l2arc_thread_exit = 1;
5782	while (l2arc_thread_exit != 0)
5783		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
5784	mutex_exit(&l2arc_feed_thr_lock);
5785}
5786