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