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