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