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