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