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