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