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