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