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