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