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