arc.c revision 286774
1168404Spjd/*
2168404Spjd * CDDL HEADER START
3168404Spjd *
4168404Spjd * The contents of this file are subject to the terms of the
5168404Spjd * Common Development and Distribution License (the "License").
6168404Spjd * You may not use this file except in compliance with the License.
7168404Spjd *
8168404Spjd * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9168404Spjd * or http://www.opensolaris.org/os/licensing.
10168404Spjd * See the License for the specific language governing permissions
11168404Spjd * and limitations under the License.
12168404Spjd *
13168404Spjd * When distributing Covered Code, include this CDDL HEADER in each
14168404Spjd * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15168404Spjd * If applicable, add the following below this CDDL HEADER, with the
16168404Spjd * fields enclosed by brackets "[]" replaced with your own identifying
17168404Spjd * information: Portions Copyright [yyyy] [name of copyright owner]
18168404Spjd *
19168404Spjd * CDDL HEADER END
20168404Spjd */
21168404Spjd/*
22219089Spjd * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23277826Sdelphij * Copyright (c) 2012, Joyent, Inc. All rights reserved.
24286766Smav * Copyright (c) 2011, 2015 by Delphix. All rights reserved.
25260835Sdelphij * Copyright (c) 2014 by Saso Kiselkov. All rights reserved.
26286764Smav * Copyright 2015 Nexenta Systems, Inc.  All rights reserved.
27168404Spjd */
28168404Spjd
29168404Spjd/*
30168404Spjd * DVA-based Adjustable Replacement Cache
31168404Spjd *
32168404Spjd * While much of the theory of operation used here is
33168404Spjd * based on the self-tuning, low overhead replacement cache
34168404Spjd * presented by Megiddo and Modha at FAST 2003, there are some
35168404Spjd * significant differences:
36168404Spjd *
37168404Spjd * 1. The Megiddo and Modha model assumes any page is evictable.
38168404Spjd * Pages in its cache cannot be "locked" into memory.  This makes
39168404Spjd * the eviction algorithm simple: evict the last page in the list.
40168404Spjd * This also make the performance characteristics easy to reason
41168404Spjd * about.  Our cache is not so simple.  At any given moment, some
42168404Spjd * subset of the blocks in the cache are un-evictable because we
43168404Spjd * have handed out a reference to them.  Blocks are only evictable
44168404Spjd * when there are no external references active.  This makes
45168404Spjd * eviction far more problematic:  we choose to evict the evictable
46168404Spjd * blocks that are the "lowest" in the list.
47168404Spjd *
48168404Spjd * There are times when it is not possible to evict the requested
49168404Spjd * space.  In these circumstances we are unable to adjust the cache
50168404Spjd * size.  To prevent the cache growing unbounded at these times we
51185029Spjd * implement a "cache throttle" that slows the flow of new data
52185029Spjd * into the cache until we can make space available.
53168404Spjd *
54168404Spjd * 2. The Megiddo and Modha model assumes a fixed cache size.
55168404Spjd * Pages are evicted when the cache is full and there is a cache
56168404Spjd * miss.  Our model has a variable sized cache.  It grows with
57185029Spjd * high use, but also tries to react to memory pressure from the
58168404Spjd * operating system: decreasing its size when system memory is
59168404Spjd * tight.
60168404Spjd *
61168404Spjd * 3. The Megiddo and Modha model assumes a fixed page size. All
62251631Sdelphij * elements of the cache are therefore exactly the same size.  So
63168404Spjd * when adjusting the cache size following a cache miss, its simply
64168404Spjd * a matter of choosing a single page to evict.  In our model, we
65168404Spjd * have variable sized cache blocks (rangeing from 512 bytes to
66251631Sdelphij * 128K bytes).  We therefore choose a set of blocks to evict to make
67168404Spjd * space for a cache miss that approximates as closely as possible
68168404Spjd * the space used by the new block.
69168404Spjd *
70168404Spjd * See also:  "ARC: A Self-Tuning, Low Overhead Replacement Cache"
71168404Spjd * by N. Megiddo & D. Modha, FAST 2003
72168404Spjd */
73168404Spjd
74168404Spjd/*
75168404Spjd * The locking model:
76168404Spjd *
77168404Spjd * A new reference to a cache buffer can be obtained in two
78168404Spjd * ways: 1) via a hash table lookup using the DVA as a key,
79185029Spjd * or 2) via one of the ARC lists.  The arc_read() interface
80168404Spjd * uses method 1, while the internal arc algorithms for
81251631Sdelphij * adjusting the cache use method 2.  We therefore provide two
82168404Spjd * types of locks: 1) the hash table lock array, and 2) the
83168404Spjd * arc list locks.
84168404Spjd *
85286774Smav * Buffers do not have their own mutexes, rather they rely on the
86286774Smav * hash table mutexes for the bulk of their protection (i.e. most
87286774Smav * fields in the arc_buf_hdr_t are protected by these mutexes).
88168404Spjd *
89168404Spjd * buf_hash_find() returns the appropriate mutex (held) when it
90168404Spjd * locates the requested buffer in the hash table.  It returns
91168404Spjd * NULL for the mutex if the buffer was not in the table.
92168404Spjd *
93168404Spjd * buf_hash_remove() expects the appropriate hash mutex to be
94168404Spjd * already held before it is invoked.
95168404Spjd *
96168404Spjd * Each arc state also has a mutex which is used to protect the
97168404Spjd * buffer list associated with the state.  When attempting to
98168404Spjd * obtain a hash table lock while holding an arc list lock you
99168404Spjd * must use: mutex_tryenter() to avoid deadlock.  Also note that
100168404Spjd * the active state mutex must be held before the ghost state mutex.
101168404Spjd *
102168404Spjd * Arc buffers may have an associated eviction callback function.
103168404Spjd * This function will be invoked prior to removing the buffer (e.g.
104168404Spjd * in arc_do_user_evicts()).  Note however that the data associated
105168404Spjd * with the buffer may be evicted prior to the callback.  The callback
106168404Spjd * must be made with *no locks held* (to prevent deadlock).  Additionally,
107168404Spjd * the users of callbacks must ensure that their private data is
108268858Sdelphij * protected from simultaneous callbacks from arc_clear_callback()
109168404Spjd * and arc_do_user_evicts().
110168404Spjd *
111168404Spjd * Note that the majority of the performance stats are manipulated
112168404Spjd * with atomic operations.
113185029Spjd *
114286570Smav * The L2ARC uses the l2ad_mtx on each vdev for the following:
115185029Spjd *
116185029Spjd *	- L2ARC buflist creation
117185029Spjd *	- L2ARC buflist eviction
118185029Spjd *	- L2ARC write completion, which walks L2ARC buflists
119185029Spjd *	- ARC header destruction, as it removes from L2ARC buflists
120185029Spjd *	- ARC header release, as it removes from L2ARC buflists
121168404Spjd */
122168404Spjd
123168404Spjd#include <sys/spa.h>
124168404Spjd#include <sys/zio.h>
125251478Sdelphij#include <sys/zio_compress.h>
126168404Spjd#include <sys/zfs_context.h>
127168404Spjd#include <sys/arc.h>
128168404Spjd#include <sys/refcount.h>
129185029Spjd#include <sys/vdev.h>
130219089Spjd#include <sys/vdev_impl.h>
131258632Savg#include <sys/dsl_pool.h>
132286763Smav#include <sys/multilist.h>
133168404Spjd#ifdef _KERNEL
134168404Spjd#include <sys/dnlc.h>
135168404Spjd#endif
136168404Spjd#include <sys/callb.h>
137168404Spjd#include <sys/kstat.h>
138248572Ssmh#include <sys/trim_map.h>
139219089Spjd#include <zfs_fletcher.h>
140168404Spjd#include <sys/sdt.h>
141168404Spjd
142191902Skmacy#include <vm/vm_pageout.h>
143272483Ssmh#include <machine/vmparam.h>
144191902Skmacy
145240133Smm#ifdef illumos
146240133Smm#ifndef _KERNEL
147240133Smm/* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
148240133Smmboolean_t arc_watch = B_FALSE;
149240133Smmint arc_procfd;
150240133Smm#endif
151240133Smm#endif /* illumos */
152240133Smm
153286763Smavstatic kmutex_t		arc_reclaim_lock;
154286763Smavstatic kcondvar_t	arc_reclaim_thread_cv;
155286763Smavstatic boolean_t	arc_reclaim_thread_exit;
156286763Smavstatic kcondvar_t	arc_reclaim_waiters_cv;
157168404Spjd
158286763Smavstatic kmutex_t		arc_user_evicts_lock;
159286763Smavstatic kcondvar_t	arc_user_evicts_cv;
160286763Smavstatic boolean_t	arc_user_evicts_thread_exit;
161286763Smav
162286625Smavuint_t arc_reduce_dnlc_percent = 3;
163168404Spjd
164258632Savg/*
165286763Smav * The number of headers to evict in arc_evict_state_impl() before
166286763Smav * dropping the sublist lock and evicting from another sublist. A lower
167286763Smav * value means we're more likely to evict the "correct" header (i.e. the
168286763Smav * oldest header in the arc state), but comes with higher overhead
169286763Smav * (i.e. more invocations of arc_evict_state_impl()).
170258632Savg */
171286763Smavint zfs_arc_evict_batch_limit = 10;
172258632Savg
173286763Smav/*
174286763Smav * The number of sublists used for each of the arc state lists. If this
175286763Smav * is not set to a suitable value by the user, it will be configured to
176286763Smav * the number of CPUs on the system in arc_init().
177286763Smav */
178286763Smavint zfs_arc_num_sublists_per_state = 0;
179286763Smav
180168404Spjd/* number of seconds before growing cache again */
181168404Spjdstatic int		arc_grow_retry = 60;
182168404Spjd
183286763Smav/* shift of arc_c for calculating overflow limit in arc_get_data_buf */
184286763Smavint		zfs_arc_overflow_shift = 8;
185286763Smav
186208373Smm/* shift of arc_c for calculating both min and max arc_p */
187208373Smmstatic int		arc_p_min_shift = 4;
188208373Smm
189208373Smm/* log2(fraction of arc to reclaim) */
190286625Smavstatic int		arc_shrink_shift = 7;
191208373Smm
192168404Spjd/*
193286625Smav * log2(fraction of ARC which must be free to allow growing).
194286625Smav * I.e. If there is less than arc_c >> arc_no_grow_shift free memory,
195286625Smav * when reading a new block into the ARC, we will evict an equal-sized block
196286625Smav * from the ARC.
197286625Smav *
198286625Smav * This must be less than arc_shrink_shift, so that when we shrink the ARC,
199286625Smav * we will still not allow it to grow.
200286625Smav */
201286625Smavint			arc_no_grow_shift = 5;
202286625Smav
203286625Smav
204286625Smav/*
205168404Spjd * minimum lifespan of a prefetch block in clock ticks
206168404Spjd * (initialized in arc_init())
207168404Spjd */
208168404Spjdstatic int		arc_min_prefetch_lifespan;
209168404Spjd
210258632Savg/*
211258632Savg * If this percent of memory is free, don't throttle.
212258632Savg */
213258632Savgint arc_lotsfree_percent = 10;
214258632Savg
215208373Smmstatic int arc_dead;
216194043Skmacyextern int zfs_prefetch_disable;
217168404Spjd
218168404Spjd/*
219185029Spjd * The arc has filled available memory and has now warmed up.
220185029Spjd */
221185029Spjdstatic boolean_t arc_warm;
222185029Spjd
223286762Smav/*
224286762Smav * These tunables are for performance analysis.
225286762Smav */
226185029Spjduint64_t zfs_arc_max;
227185029Spjduint64_t zfs_arc_min;
228185029Spjduint64_t zfs_arc_meta_limit = 0;
229275780Sdelphijuint64_t zfs_arc_meta_min = 0;
230208373Smmint zfs_arc_grow_retry = 0;
231208373Smmint zfs_arc_shrink_shift = 0;
232208373Smmint zfs_arc_p_min_shift = 0;
233242845Sdelphijint zfs_disable_dup_eviction = 0;
234269230Sdelphijuint64_t zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
235272483Ssmhu_int zfs_arc_free_target = 0;
236185029Spjd
237270759Ssmhstatic int sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS);
238275748Sdelphijstatic int sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS);
239270759Ssmh
240270759Ssmh#ifdef _KERNEL
241270759Ssmhstatic void
242270759Ssmharc_free_target_init(void *unused __unused)
243270759Ssmh{
244270759Ssmh
245272483Ssmh	zfs_arc_free_target = vm_pageout_wakeup_thresh;
246270759Ssmh}
247270759SsmhSYSINIT(arc_free_target_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_ANY,
248270759Ssmh    arc_free_target_init, NULL);
249270759Ssmh
250185029SpjdTUNABLE_QUAD("vfs.zfs.arc_meta_limit", &zfs_arc_meta_limit);
251275780SdelphijTUNABLE_QUAD("vfs.zfs.arc_meta_min", &zfs_arc_meta_min);
252273026SdelphijTUNABLE_INT("vfs.zfs.arc_shrink_shift", &zfs_arc_shrink_shift);
253168473SpjdSYSCTL_DECL(_vfs_zfs);
254217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_max, CTLFLAG_RDTUN, &zfs_arc_max, 0,
255168473Spjd    "Maximum ARC size");
256217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_min, CTLFLAG_RDTUN, &zfs_arc_min, 0,
257168473Spjd    "Minimum ARC size");
258269230SdelphijSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_average_blocksize, CTLFLAG_RDTUN,
259269230Sdelphij    &zfs_arc_average_blocksize, 0,
260269230Sdelphij    "ARC average blocksize");
261273026SdelphijSYSCTL_INT(_vfs_zfs, OID_AUTO, arc_shrink_shift, CTLFLAG_RW,
262273026Sdelphij    &arc_shrink_shift, 0,
263273026Sdelphij    "log2(fraction of arc to reclaim)");
264273026Sdelphij
265270759Ssmh/*
266270759Ssmh * We don't have a tunable for arc_free_target due to the dependency on
267270759Ssmh * pagedaemon initialisation.
268270759Ssmh */
269270759SsmhSYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_free_target,
270270759Ssmh    CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(u_int),
271270759Ssmh    sysctl_vfs_zfs_arc_free_target, "IU",
272270759Ssmh    "Desired number of free pages below which ARC triggers reclaim");
273168404Spjd
274270759Ssmhstatic int
275270759Ssmhsysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS)
276270759Ssmh{
277270759Ssmh	u_int val;
278270759Ssmh	int err;
279270759Ssmh
280270759Ssmh	val = zfs_arc_free_target;
281270759Ssmh	err = sysctl_handle_int(oidp, &val, 0, req);
282270759Ssmh	if (err != 0 || req->newptr == NULL)
283270759Ssmh		return (err);
284270759Ssmh
285272483Ssmh	if (val < minfree)
286270759Ssmh		return (EINVAL);
287272483Ssmh	if (val > vm_cnt.v_page_count)
288270759Ssmh		return (EINVAL);
289270759Ssmh
290270759Ssmh	zfs_arc_free_target = val;
291270759Ssmh
292270759Ssmh	return (0);
293270759Ssmh}
294275748Sdelphij
295275748Sdelphij/*
296275748Sdelphij * Must be declared here, before the definition of corresponding kstat
297275748Sdelphij * macro which uses the same names will confuse the compiler.
298275748Sdelphij */
299275748SdelphijSYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_meta_limit,
300275748Sdelphij    CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
301275748Sdelphij    sysctl_vfs_zfs_arc_meta_limit, "QU",
302275748Sdelphij    "ARC metadata limit");
303272483Ssmh#endif
304270759Ssmh
305168404Spjd/*
306185029Spjd * Note that buffers can be in one of 6 states:
307168404Spjd *	ARC_anon	- anonymous (discussed below)
308168404Spjd *	ARC_mru		- recently used, currently cached
309168404Spjd *	ARC_mru_ghost	- recentely used, no longer in cache
310168404Spjd *	ARC_mfu		- frequently used, currently cached
311168404Spjd *	ARC_mfu_ghost	- frequently used, no longer in cache
312185029Spjd *	ARC_l2c_only	- exists in L2ARC but not other states
313185029Spjd * When there are no active references to the buffer, they are
314185029Spjd * are linked onto a list in one of these arc states.  These are
315185029Spjd * the only buffers that can be evicted or deleted.  Within each
316185029Spjd * state there are multiple lists, one for meta-data and one for
317185029Spjd * non-meta-data.  Meta-data (indirect blocks, blocks of dnodes,
318185029Spjd * etc.) is tracked separately so that it can be managed more
319185029Spjd * explicitly: favored over data, limited explicitly.
320168404Spjd *
321168404Spjd * Anonymous buffers are buffers that are not associated with
322168404Spjd * a DVA.  These are buffers that hold dirty block copies
323168404Spjd * before they are written to stable storage.  By definition,
324168404Spjd * they are "ref'd" and are considered part of arc_mru
325168404Spjd * that cannot be freed.  Generally, they will aquire a DVA
326168404Spjd * as they are written and migrate onto the arc_mru list.
327185029Spjd *
328185029Spjd * The ARC_l2c_only state is for buffers that are in the second
329185029Spjd * level ARC but no longer in any of the ARC_m* lists.  The second
330185029Spjd * level ARC itself may also contain buffers that are in any of
331185029Spjd * the ARC_m* states - meaning that a buffer can exist in two
332185029Spjd * places.  The reason for the ARC_l2c_only state is to keep the
333185029Spjd * buffer header in the hash table, so that reads that hit the
334185029Spjd * second level ARC benefit from these fast lookups.
335168404Spjd */
336168404Spjd
337168404Spjdtypedef struct arc_state {
338286763Smav	/*
339286763Smav	 * list of evictable buffers
340286763Smav	 */
341286763Smav	multilist_t arcs_list[ARC_BUFC_NUMTYPES];
342286763Smav	/*
343286763Smav	 * total amount of evictable data in this state
344286763Smav	 */
345286763Smav	uint64_t arcs_lsize[ARC_BUFC_NUMTYPES];
346286763Smav	/*
347286763Smav	 * total amount of data in this state; this includes: evictable,
348286763Smav	 * non-evictable, ARC_BUFC_DATA, and ARC_BUFC_METADATA.
349286763Smav	 */
350286766Smav	refcount_t arcs_size;
351168404Spjd} arc_state_t;
352168404Spjd
353185029Spjd/* The 6 states: */
354168404Spjdstatic arc_state_t ARC_anon;
355168404Spjdstatic arc_state_t ARC_mru;
356168404Spjdstatic arc_state_t ARC_mru_ghost;
357168404Spjdstatic arc_state_t ARC_mfu;
358168404Spjdstatic arc_state_t ARC_mfu_ghost;
359185029Spjdstatic arc_state_t ARC_l2c_only;
360168404Spjd
361168404Spjdtypedef struct arc_stats {
362168404Spjd	kstat_named_t arcstat_hits;
363168404Spjd	kstat_named_t arcstat_misses;
364168404Spjd	kstat_named_t arcstat_demand_data_hits;
365168404Spjd	kstat_named_t arcstat_demand_data_misses;
366168404Spjd	kstat_named_t arcstat_demand_metadata_hits;
367168404Spjd	kstat_named_t arcstat_demand_metadata_misses;
368168404Spjd	kstat_named_t arcstat_prefetch_data_hits;
369168404Spjd	kstat_named_t arcstat_prefetch_data_misses;
370168404Spjd	kstat_named_t arcstat_prefetch_metadata_hits;
371168404Spjd	kstat_named_t arcstat_prefetch_metadata_misses;
372168404Spjd	kstat_named_t arcstat_mru_hits;
373168404Spjd	kstat_named_t arcstat_mru_ghost_hits;
374168404Spjd	kstat_named_t arcstat_mfu_hits;
375168404Spjd	kstat_named_t arcstat_mfu_ghost_hits;
376205231Skmacy	kstat_named_t arcstat_allocated;
377168404Spjd	kstat_named_t arcstat_deleted;
378251629Sdelphij	/*
379251629Sdelphij	 * Number of buffers that could not be evicted because the hash lock
380251629Sdelphij	 * was held by another thread.  The lock may not necessarily be held
381251629Sdelphij	 * by something using the same buffer, since hash locks are shared
382251629Sdelphij	 * by multiple buffers.
383251629Sdelphij	 */
384168404Spjd	kstat_named_t arcstat_mutex_miss;
385251629Sdelphij	/*
386251629Sdelphij	 * Number of buffers skipped because they have I/O in progress, are
387251629Sdelphij	 * indrect prefetch buffers that have not lived long enough, or are
388251629Sdelphij	 * not from the spa we're trying to evict from.
389251629Sdelphij	 */
390168404Spjd	kstat_named_t arcstat_evict_skip;
391286763Smav	/*
392286763Smav	 * Number of times arc_evict_state() was unable to evict enough
393286763Smav	 * buffers to reach it's target amount.
394286763Smav	 */
395286763Smav	kstat_named_t arcstat_evict_not_enough;
396208373Smm	kstat_named_t arcstat_evict_l2_cached;
397208373Smm	kstat_named_t arcstat_evict_l2_eligible;
398208373Smm	kstat_named_t arcstat_evict_l2_ineligible;
399286763Smav	kstat_named_t arcstat_evict_l2_skip;
400168404Spjd	kstat_named_t arcstat_hash_elements;
401168404Spjd	kstat_named_t arcstat_hash_elements_max;
402168404Spjd	kstat_named_t arcstat_hash_collisions;
403168404Spjd	kstat_named_t arcstat_hash_chains;
404168404Spjd	kstat_named_t arcstat_hash_chain_max;
405168404Spjd	kstat_named_t arcstat_p;
406168404Spjd	kstat_named_t arcstat_c;
407168404Spjd	kstat_named_t arcstat_c_min;
408168404Spjd	kstat_named_t arcstat_c_max;
409168404Spjd	kstat_named_t arcstat_size;
410286574Smav	/*
411286574Smav	 * Number of bytes consumed by internal ARC structures necessary
412286574Smav	 * for tracking purposes; these structures are not actually
413286574Smav	 * backed by ARC buffers. This includes arc_buf_hdr_t structures
414286574Smav	 * (allocated via arc_buf_hdr_t_full and arc_buf_hdr_t_l2only
415286574Smav	 * caches), and arc_buf_t structures (allocated via arc_buf_t
416286574Smav	 * cache).
417286574Smav	 */
418185029Spjd	kstat_named_t arcstat_hdr_size;
419286574Smav	/*
420286574Smav	 * Number of bytes consumed by ARC buffers of type equal to
421286574Smav	 * ARC_BUFC_DATA. This is generally consumed by buffers backing
422286574Smav	 * on disk user data (e.g. plain file contents).
423286574Smav	 */
424208373Smm	kstat_named_t arcstat_data_size;
425286574Smav	/*
426286574Smav	 * Number of bytes consumed by ARC buffers of type equal to
427286574Smav	 * ARC_BUFC_METADATA. This is generally consumed by buffers
428286574Smav	 * backing on disk data that is used for internal ZFS
429286574Smav	 * structures (e.g. ZAP, dnode, indirect blocks, etc).
430286574Smav	 */
431286574Smav	kstat_named_t arcstat_metadata_size;
432286574Smav	/*
433286574Smav	 * Number of bytes consumed by various buffers and structures
434286574Smav	 * not actually backed with ARC buffers. This includes bonus
435286574Smav	 * buffers (allocated directly via zio_buf_* functions),
436286574Smav	 * dmu_buf_impl_t structures (allocated via dmu_buf_impl_t
437286574Smav	 * cache), and dnode_t structures (allocated via dnode_t cache).
438286574Smav	 */
439208373Smm	kstat_named_t arcstat_other_size;
440286574Smav	/*
441286574Smav	 * Total number of bytes consumed by ARC buffers residing in the
442286574Smav	 * arc_anon state. This includes *all* buffers in the arc_anon
443286574Smav	 * state; e.g. data, metadata, evictable, and unevictable buffers
444286574Smav	 * are all included in this value.
445286574Smav	 */
446286574Smav	kstat_named_t arcstat_anon_size;
447286574Smav	/*
448286574Smav	 * Number of bytes consumed by ARC buffers that meet the
449286574Smav	 * following criteria: backing buffers of type ARC_BUFC_DATA,
450286574Smav	 * residing in the arc_anon state, and are eligible for eviction
451286574Smav	 * (e.g. have no outstanding holds on the buffer).
452286574Smav	 */
453286574Smav	kstat_named_t arcstat_anon_evictable_data;
454286574Smav	/*
455286574Smav	 * Number of bytes consumed by ARC buffers that meet the
456286574Smav	 * following criteria: backing buffers of type ARC_BUFC_METADATA,
457286574Smav	 * residing in the arc_anon state, and are eligible for eviction
458286574Smav	 * (e.g. have no outstanding holds on the buffer).
459286574Smav	 */
460286574Smav	kstat_named_t arcstat_anon_evictable_metadata;
461286574Smav	/*
462286574Smav	 * Total number of bytes consumed by ARC buffers residing in the
463286574Smav	 * arc_mru state. This includes *all* buffers in the arc_mru
464286574Smav	 * state; e.g. data, metadata, evictable, and unevictable buffers
465286574Smav	 * are all included in this value.
466286574Smav	 */
467286574Smav	kstat_named_t arcstat_mru_size;
468286574Smav	/*
469286574Smav	 * Number of bytes consumed by ARC buffers that meet the
470286574Smav	 * following criteria: backing buffers of type ARC_BUFC_DATA,
471286574Smav	 * residing in the arc_mru state, and are eligible for eviction
472286574Smav	 * (e.g. have no outstanding holds on the buffer).
473286574Smav	 */
474286574Smav	kstat_named_t arcstat_mru_evictable_data;
475286574Smav	/*
476286574Smav	 * Number of bytes consumed by ARC buffers that meet the
477286574Smav	 * following criteria: backing buffers of type ARC_BUFC_METADATA,
478286574Smav	 * residing in the arc_mru state, and are eligible for eviction
479286574Smav	 * (e.g. have no outstanding holds on the buffer).
480286574Smav	 */
481286574Smav	kstat_named_t arcstat_mru_evictable_metadata;
482286574Smav	/*
483286574Smav	 * Total number of bytes that *would have been* consumed by ARC
484286574Smav	 * buffers in the arc_mru_ghost state. The key thing to note
485286574Smav	 * here, is the fact that this size doesn't actually indicate
486286574Smav	 * RAM consumption. The ghost lists only consist of headers and
487286574Smav	 * don't actually have ARC buffers linked off of these headers.
488286574Smav	 * Thus, *if* the headers had associated ARC buffers, these
489286574Smav	 * buffers *would have* consumed this number of bytes.
490286574Smav	 */
491286574Smav	kstat_named_t arcstat_mru_ghost_size;
492286574Smav	/*
493286574Smav	 * Number of bytes that *would have been* consumed by ARC
494286574Smav	 * buffers that are eligible for eviction, of type
495286574Smav	 * ARC_BUFC_DATA, and linked off the arc_mru_ghost state.
496286574Smav	 */
497286574Smav	kstat_named_t arcstat_mru_ghost_evictable_data;
498286574Smav	/*
499286574Smav	 * Number of bytes that *would have been* consumed by ARC
500286574Smav	 * buffers that are eligible for eviction, of type
501286574Smav	 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
502286574Smav	 */
503286574Smav	kstat_named_t arcstat_mru_ghost_evictable_metadata;
504286574Smav	/*
505286574Smav	 * Total number of bytes consumed by ARC buffers residing in the
506286574Smav	 * arc_mfu state. This includes *all* buffers in the arc_mfu
507286574Smav	 * state; e.g. data, metadata, evictable, and unevictable buffers
508286574Smav	 * are all included in this value.
509286574Smav	 */
510286574Smav	kstat_named_t arcstat_mfu_size;
511286574Smav	/*
512286574Smav	 * Number of bytes consumed by ARC buffers that are eligible for
513286574Smav	 * eviction, of type ARC_BUFC_DATA, and reside in the arc_mfu
514286574Smav	 * state.
515286574Smav	 */
516286574Smav	kstat_named_t arcstat_mfu_evictable_data;
517286574Smav	/*
518286574Smav	 * Number of bytes consumed by ARC buffers that are eligible for
519286574Smav	 * eviction, of type ARC_BUFC_METADATA, and reside in the
520286574Smav	 * arc_mfu state.
521286574Smav	 */
522286574Smav	kstat_named_t arcstat_mfu_evictable_metadata;
523286574Smav	/*
524286574Smav	 * Total number of bytes that *would have been* consumed by ARC
525286574Smav	 * buffers in the arc_mfu_ghost state. See the comment above
526286574Smav	 * arcstat_mru_ghost_size for more details.
527286574Smav	 */
528286574Smav	kstat_named_t arcstat_mfu_ghost_size;
529286574Smav	/*
530286574Smav	 * Number of bytes that *would have been* consumed by ARC
531286574Smav	 * buffers that are eligible for eviction, of type
532286574Smav	 * ARC_BUFC_DATA, and linked off the arc_mfu_ghost state.
533286574Smav	 */
534286574Smav	kstat_named_t arcstat_mfu_ghost_evictable_data;
535286574Smav	/*
536286574Smav	 * Number of bytes that *would have been* consumed by ARC
537286574Smav	 * buffers that are eligible for eviction, of type
538286574Smav	 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
539286574Smav	 */
540286574Smav	kstat_named_t arcstat_mfu_ghost_evictable_metadata;
541185029Spjd	kstat_named_t arcstat_l2_hits;
542185029Spjd	kstat_named_t arcstat_l2_misses;
543185029Spjd	kstat_named_t arcstat_l2_feeds;
544185029Spjd	kstat_named_t arcstat_l2_rw_clash;
545208373Smm	kstat_named_t arcstat_l2_read_bytes;
546208373Smm	kstat_named_t arcstat_l2_write_bytes;
547185029Spjd	kstat_named_t arcstat_l2_writes_sent;
548185029Spjd	kstat_named_t arcstat_l2_writes_done;
549185029Spjd	kstat_named_t arcstat_l2_writes_error;
550286763Smav	kstat_named_t arcstat_l2_writes_lock_retry;
551185029Spjd	kstat_named_t arcstat_l2_evict_lock_retry;
552185029Spjd	kstat_named_t arcstat_l2_evict_reading;
553286570Smav	kstat_named_t arcstat_l2_evict_l1cached;
554185029Spjd	kstat_named_t arcstat_l2_free_on_write;
555274172Savg	kstat_named_t arcstat_l2_cdata_free_on_write;
556185029Spjd	kstat_named_t arcstat_l2_abort_lowmem;
557185029Spjd	kstat_named_t arcstat_l2_cksum_bad;
558185029Spjd	kstat_named_t arcstat_l2_io_error;
559185029Spjd	kstat_named_t arcstat_l2_size;
560251478Sdelphij	kstat_named_t arcstat_l2_asize;
561185029Spjd	kstat_named_t arcstat_l2_hdr_size;
562251478Sdelphij	kstat_named_t arcstat_l2_compress_successes;
563251478Sdelphij	kstat_named_t arcstat_l2_compress_zeros;
564251478Sdelphij	kstat_named_t arcstat_l2_compress_failures;
565205231Skmacy	kstat_named_t arcstat_l2_write_trylock_fail;
566205231Skmacy	kstat_named_t arcstat_l2_write_passed_headroom;
567205231Skmacy	kstat_named_t arcstat_l2_write_spa_mismatch;
568206796Spjd	kstat_named_t arcstat_l2_write_in_l2;
569205231Skmacy	kstat_named_t arcstat_l2_write_hdr_io_in_progress;
570205231Skmacy	kstat_named_t arcstat_l2_write_not_cacheable;
571205231Skmacy	kstat_named_t arcstat_l2_write_full;
572205231Skmacy	kstat_named_t arcstat_l2_write_buffer_iter;
573205231Skmacy	kstat_named_t arcstat_l2_write_pios;
574205231Skmacy	kstat_named_t arcstat_l2_write_buffer_bytes_scanned;
575205231Skmacy	kstat_named_t arcstat_l2_write_buffer_list_iter;
576205231Skmacy	kstat_named_t arcstat_l2_write_buffer_list_null_iter;
577242845Sdelphij	kstat_named_t arcstat_memory_throttle_count;
578242845Sdelphij	kstat_named_t arcstat_duplicate_buffers;
579242845Sdelphij	kstat_named_t arcstat_duplicate_buffers_size;
580242845Sdelphij	kstat_named_t arcstat_duplicate_reads;
581275748Sdelphij	kstat_named_t arcstat_meta_used;
582275748Sdelphij	kstat_named_t arcstat_meta_limit;
583275748Sdelphij	kstat_named_t arcstat_meta_max;
584275780Sdelphij	kstat_named_t arcstat_meta_min;
585168404Spjd} arc_stats_t;
586168404Spjd
587168404Spjdstatic arc_stats_t arc_stats = {
588168404Spjd	{ "hits",			KSTAT_DATA_UINT64 },
589168404Spjd	{ "misses",			KSTAT_DATA_UINT64 },
590168404Spjd	{ "demand_data_hits",		KSTAT_DATA_UINT64 },
591168404Spjd	{ "demand_data_misses",		KSTAT_DATA_UINT64 },
592168404Spjd	{ "demand_metadata_hits",	KSTAT_DATA_UINT64 },
593168404Spjd	{ "demand_metadata_misses",	KSTAT_DATA_UINT64 },
594168404Spjd	{ "prefetch_data_hits",		KSTAT_DATA_UINT64 },
595168404Spjd	{ "prefetch_data_misses",	KSTAT_DATA_UINT64 },
596168404Spjd	{ "prefetch_metadata_hits",	KSTAT_DATA_UINT64 },
597168404Spjd	{ "prefetch_metadata_misses",	KSTAT_DATA_UINT64 },
598168404Spjd	{ "mru_hits",			KSTAT_DATA_UINT64 },
599168404Spjd	{ "mru_ghost_hits",		KSTAT_DATA_UINT64 },
600168404Spjd	{ "mfu_hits",			KSTAT_DATA_UINT64 },
601168404Spjd	{ "mfu_ghost_hits",		KSTAT_DATA_UINT64 },
602205231Skmacy	{ "allocated",			KSTAT_DATA_UINT64 },
603168404Spjd	{ "deleted",			KSTAT_DATA_UINT64 },
604168404Spjd	{ "mutex_miss",			KSTAT_DATA_UINT64 },
605168404Spjd	{ "evict_skip",			KSTAT_DATA_UINT64 },
606286763Smav	{ "evict_not_enough",		KSTAT_DATA_UINT64 },
607208373Smm	{ "evict_l2_cached",		KSTAT_DATA_UINT64 },
608208373Smm	{ "evict_l2_eligible",		KSTAT_DATA_UINT64 },
609208373Smm	{ "evict_l2_ineligible",	KSTAT_DATA_UINT64 },
610286763Smav	{ "evict_l2_skip",		KSTAT_DATA_UINT64 },
611168404Spjd	{ "hash_elements",		KSTAT_DATA_UINT64 },
612168404Spjd	{ "hash_elements_max",		KSTAT_DATA_UINT64 },
613168404Spjd	{ "hash_collisions",		KSTAT_DATA_UINT64 },
614168404Spjd	{ "hash_chains",		KSTAT_DATA_UINT64 },
615168404Spjd	{ "hash_chain_max",		KSTAT_DATA_UINT64 },
616168404Spjd	{ "p",				KSTAT_DATA_UINT64 },
617168404Spjd	{ "c",				KSTAT_DATA_UINT64 },
618168404Spjd	{ "c_min",			KSTAT_DATA_UINT64 },
619168404Spjd	{ "c_max",			KSTAT_DATA_UINT64 },
620185029Spjd	{ "size",			KSTAT_DATA_UINT64 },
621185029Spjd	{ "hdr_size",			KSTAT_DATA_UINT64 },
622208373Smm	{ "data_size",			KSTAT_DATA_UINT64 },
623286574Smav	{ "metadata_size",		KSTAT_DATA_UINT64 },
624208373Smm	{ "other_size",			KSTAT_DATA_UINT64 },
625286574Smav	{ "anon_size",			KSTAT_DATA_UINT64 },
626286574Smav	{ "anon_evictable_data",	KSTAT_DATA_UINT64 },
627286574Smav	{ "anon_evictable_metadata",	KSTAT_DATA_UINT64 },
628286574Smav	{ "mru_size",			KSTAT_DATA_UINT64 },
629286574Smav	{ "mru_evictable_data",		KSTAT_DATA_UINT64 },
630286574Smav	{ "mru_evictable_metadata",	KSTAT_DATA_UINT64 },
631286574Smav	{ "mru_ghost_size",		KSTAT_DATA_UINT64 },
632286574Smav	{ "mru_ghost_evictable_data",	KSTAT_DATA_UINT64 },
633286574Smav	{ "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
634286574Smav	{ "mfu_size",			KSTAT_DATA_UINT64 },
635286574Smav	{ "mfu_evictable_data",		KSTAT_DATA_UINT64 },
636286574Smav	{ "mfu_evictable_metadata",	KSTAT_DATA_UINT64 },
637286574Smav	{ "mfu_ghost_size",		KSTAT_DATA_UINT64 },
638286574Smav	{ "mfu_ghost_evictable_data",	KSTAT_DATA_UINT64 },
639286574Smav	{ "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
640185029Spjd	{ "l2_hits",			KSTAT_DATA_UINT64 },
641185029Spjd	{ "l2_misses",			KSTAT_DATA_UINT64 },
642185029Spjd	{ "l2_feeds",			KSTAT_DATA_UINT64 },
643185029Spjd	{ "l2_rw_clash",		KSTAT_DATA_UINT64 },
644208373Smm	{ "l2_read_bytes",		KSTAT_DATA_UINT64 },
645208373Smm	{ "l2_write_bytes",		KSTAT_DATA_UINT64 },
646185029Spjd	{ "l2_writes_sent",		KSTAT_DATA_UINT64 },
647185029Spjd	{ "l2_writes_done",		KSTAT_DATA_UINT64 },
648185029Spjd	{ "l2_writes_error",		KSTAT_DATA_UINT64 },
649286763Smav	{ "l2_writes_lock_retry",	KSTAT_DATA_UINT64 },
650185029Spjd	{ "l2_evict_lock_retry",	KSTAT_DATA_UINT64 },
651185029Spjd	{ "l2_evict_reading",		KSTAT_DATA_UINT64 },
652286570Smav	{ "l2_evict_l1cached",		KSTAT_DATA_UINT64 },
653185029Spjd	{ "l2_free_on_write",		KSTAT_DATA_UINT64 },
654274172Savg	{ "l2_cdata_free_on_write",	KSTAT_DATA_UINT64 },
655185029Spjd	{ "l2_abort_lowmem",		KSTAT_DATA_UINT64 },
656185029Spjd	{ "l2_cksum_bad",		KSTAT_DATA_UINT64 },
657185029Spjd	{ "l2_io_error",		KSTAT_DATA_UINT64 },
658185029Spjd	{ "l2_size",			KSTAT_DATA_UINT64 },
659251478Sdelphij	{ "l2_asize",			KSTAT_DATA_UINT64 },
660185029Spjd	{ "l2_hdr_size",		KSTAT_DATA_UINT64 },
661251478Sdelphij	{ "l2_compress_successes",	KSTAT_DATA_UINT64 },
662251478Sdelphij	{ "l2_compress_zeros",		KSTAT_DATA_UINT64 },
663251478Sdelphij	{ "l2_compress_failures",	KSTAT_DATA_UINT64 },
664206796Spjd	{ "l2_write_trylock_fail",	KSTAT_DATA_UINT64 },
665206796Spjd	{ "l2_write_passed_headroom",	KSTAT_DATA_UINT64 },
666206796Spjd	{ "l2_write_spa_mismatch",	KSTAT_DATA_UINT64 },
667206796Spjd	{ "l2_write_in_l2",		KSTAT_DATA_UINT64 },
668206796Spjd	{ "l2_write_io_in_progress",	KSTAT_DATA_UINT64 },
669206796Spjd	{ "l2_write_not_cacheable",	KSTAT_DATA_UINT64 },
670206796Spjd	{ "l2_write_full",		KSTAT_DATA_UINT64 },
671206796Spjd	{ "l2_write_buffer_iter",	KSTAT_DATA_UINT64 },
672206796Spjd	{ "l2_write_pios",		KSTAT_DATA_UINT64 },
673206796Spjd	{ "l2_write_buffer_bytes_scanned", KSTAT_DATA_UINT64 },
674206796Spjd	{ "l2_write_buffer_list_iter",	KSTAT_DATA_UINT64 },
675242845Sdelphij	{ "l2_write_buffer_list_null_iter", KSTAT_DATA_UINT64 },
676242845Sdelphij	{ "memory_throttle_count",	KSTAT_DATA_UINT64 },
677242845Sdelphij	{ "duplicate_buffers",		KSTAT_DATA_UINT64 },
678242845Sdelphij	{ "duplicate_buffers_size",	KSTAT_DATA_UINT64 },
679275748Sdelphij	{ "duplicate_reads",		KSTAT_DATA_UINT64 },
680275748Sdelphij	{ "arc_meta_used",		KSTAT_DATA_UINT64 },
681275748Sdelphij	{ "arc_meta_limit",		KSTAT_DATA_UINT64 },
682275780Sdelphij	{ "arc_meta_max",		KSTAT_DATA_UINT64 },
683275780Sdelphij	{ "arc_meta_min",		KSTAT_DATA_UINT64 }
684168404Spjd};
685168404Spjd
686168404Spjd#define	ARCSTAT(stat)	(arc_stats.stat.value.ui64)
687168404Spjd
688168404Spjd#define	ARCSTAT_INCR(stat, val) \
689251631Sdelphij	atomic_add_64(&arc_stats.stat.value.ui64, (val))
690168404Spjd
691206796Spjd#define	ARCSTAT_BUMP(stat)	ARCSTAT_INCR(stat, 1)
692168404Spjd#define	ARCSTAT_BUMPDOWN(stat)	ARCSTAT_INCR(stat, -1)
693168404Spjd
694168404Spjd#define	ARCSTAT_MAX(stat, val) {					\
695168404Spjd	uint64_t m;							\
696168404Spjd	while ((val) > (m = arc_stats.stat.value.ui64) &&		\
697168404Spjd	    (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val))))	\
698168404Spjd		continue;						\
699168404Spjd}
700168404Spjd
701168404Spjd#define	ARCSTAT_MAXSTAT(stat) \
702168404Spjd	ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
703168404Spjd
704168404Spjd/*
705168404Spjd * We define a macro to allow ARC hits/misses to be easily broken down by
706168404Spjd * two separate conditions, giving a total of four different subtypes for
707168404Spjd * each of hits and misses (so eight statistics total).
708168404Spjd */
709168404Spjd#define	ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
710168404Spjd	if (cond1) {							\
711168404Spjd		if (cond2) {						\
712168404Spjd			ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
713168404Spjd		} else {						\
714168404Spjd			ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
715168404Spjd		}							\
716168404Spjd	} else {							\
717168404Spjd		if (cond2) {						\
718168404Spjd			ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
719168404Spjd		} else {						\
720168404Spjd			ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
721168404Spjd		}							\
722168404Spjd	}
723168404Spjd
724168404Spjdkstat_t			*arc_ksp;
725206796Spjdstatic arc_state_t	*arc_anon;
726168404Spjdstatic arc_state_t	*arc_mru;
727168404Spjdstatic arc_state_t	*arc_mru_ghost;
728168404Spjdstatic arc_state_t	*arc_mfu;
729168404Spjdstatic arc_state_t	*arc_mfu_ghost;
730185029Spjdstatic arc_state_t	*arc_l2c_only;
731168404Spjd
732168404Spjd/*
733168404Spjd * There are several ARC variables that are critical to export as kstats --
734168404Spjd * but we don't want to have to grovel around in the kstat whenever we wish to
735168404Spjd * manipulate them.  For these variables, we therefore define them to be in
736168404Spjd * terms of the statistic variable.  This assures that we are not introducing
737168404Spjd * the possibility of inconsistency by having shadow copies of the variables,
738168404Spjd * while still allowing the code to be readable.
739168404Spjd */
740168404Spjd#define	arc_size	ARCSTAT(arcstat_size)	/* actual total arc size */
741168404Spjd#define	arc_p		ARCSTAT(arcstat_p)	/* target size of MRU */
742168404Spjd#define	arc_c		ARCSTAT(arcstat_c)	/* target size of cache */
743168404Spjd#define	arc_c_min	ARCSTAT(arcstat_c_min)	/* min target cache size */
744168404Spjd#define	arc_c_max	ARCSTAT(arcstat_c_max)	/* max target cache size */
745275748Sdelphij#define	arc_meta_limit	ARCSTAT(arcstat_meta_limit) /* max size for metadata */
746275780Sdelphij#define	arc_meta_min	ARCSTAT(arcstat_meta_min) /* min size for metadata */
747275748Sdelphij#define	arc_meta_used	ARCSTAT(arcstat_meta_used) /* size of metadata */
748275748Sdelphij#define	arc_meta_max	ARCSTAT(arcstat_meta_max) /* max size of metadata */
749168404Spjd
750251478Sdelphij#define	L2ARC_IS_VALID_COMPRESS(_c_) \
751251478Sdelphij	((_c_) == ZIO_COMPRESS_LZ4 || (_c_) == ZIO_COMPRESS_EMPTY)
752251478Sdelphij
753168404Spjdstatic int		arc_no_grow;	/* Don't try to grow cache size */
754168404Spjdstatic uint64_t		arc_tempreserve;
755209962Smmstatic uint64_t		arc_loaned_bytes;
756168404Spjd
757168404Spjdtypedef struct arc_callback arc_callback_t;
758168404Spjd
759168404Spjdstruct arc_callback {
760168404Spjd	void			*acb_private;
761168404Spjd	arc_done_func_t		*acb_done;
762168404Spjd	arc_buf_t		*acb_buf;
763168404Spjd	zio_t			*acb_zio_dummy;
764168404Spjd	arc_callback_t		*acb_next;
765168404Spjd};
766168404Spjd
767168404Spjdtypedef struct arc_write_callback arc_write_callback_t;
768168404Spjd
769168404Spjdstruct arc_write_callback {
770168404Spjd	void		*awcb_private;
771168404Spjd	arc_done_func_t	*awcb_ready;
772258632Savg	arc_done_func_t	*awcb_physdone;
773168404Spjd	arc_done_func_t	*awcb_done;
774168404Spjd	arc_buf_t	*awcb_buf;
775168404Spjd};
776168404Spjd
777286570Smav/*
778286570Smav * ARC buffers are separated into multiple structs as a memory saving measure:
779286570Smav *   - Common fields struct, always defined, and embedded within it:
780286570Smav *       - L2-only fields, always allocated but undefined when not in L2ARC
781286570Smav *       - L1-only fields, only allocated when in L1ARC
782286570Smav *
783286570Smav *           Buffer in L1                     Buffer only in L2
784286570Smav *    +------------------------+          +------------------------+
785286570Smav *    | arc_buf_hdr_t          |          | arc_buf_hdr_t          |
786286570Smav *    |                        |          |                        |
787286570Smav *    |                        |          |                        |
788286570Smav *    |                        |          |                        |
789286570Smav *    +------------------------+          +------------------------+
790286570Smav *    | l2arc_buf_hdr_t        |          | l2arc_buf_hdr_t        |
791286570Smav *    | (undefined if L1-only) |          |                        |
792286570Smav *    +------------------------+          +------------------------+
793286570Smav *    | l1arc_buf_hdr_t        |
794286570Smav *    |                        |
795286570Smav *    |                        |
796286570Smav *    |                        |
797286570Smav *    |                        |
798286570Smav *    +------------------------+
799286570Smav *
800286570Smav * Because it's possible for the L2ARC to become extremely large, we can wind
801286570Smav * up eating a lot of memory in L2ARC buffer headers, so the size of a header
802286570Smav * is minimized by only allocating the fields necessary for an L1-cached buffer
803286570Smav * when a header is actually in the L1 cache. The sub-headers (l1arc_buf_hdr and
804286570Smav * l2arc_buf_hdr) are embedded rather than allocated separately to save a couple
805286570Smav * words in pointers. arc_hdr_realloc() is used to switch a header between
806286570Smav * these two allocation states.
807286570Smav */
808286570Smavtypedef struct l1arc_buf_hdr {
809168404Spjd	kmutex_t		b_freeze_lock;
810286570Smav#ifdef ZFS_DEBUG
811286570Smav	/*
812286570Smav	 * used for debugging wtih kmem_flags - by allocating and freeing
813286570Smav	 * b_thawed when the buffer is thawed, we get a record of the stack
814286570Smav	 * trace that thawed it.
815286570Smav	 */
816219089Spjd	void			*b_thawed;
817286570Smav#endif
818168404Spjd
819168404Spjd	arc_buf_t		*b_buf;
820168404Spjd	uint32_t		b_datacnt;
821286570Smav	/* for waiting on writes to complete */
822168404Spjd	kcondvar_t		b_cv;
823168404Spjd
824168404Spjd	/* protected by arc state mutex */
825168404Spjd	arc_state_t		*b_state;
826286763Smav	multilist_node_t	b_arc_node;
827168404Spjd
828168404Spjd	/* updated atomically */
829168404Spjd	clock_t			b_arc_access;
830168404Spjd
831168404Spjd	/* self protecting */
832168404Spjd	refcount_t		b_refcnt;
833185029Spjd
834286570Smav	arc_callback_t		*b_acb;
835286570Smav	/* temporary buffer holder for in-flight compressed data */
836286570Smav	void			*b_tmp_cdata;
837286570Smav} l1arc_buf_hdr_t;
838286570Smav
839286570Smavtypedef struct l2arc_dev l2arc_dev_t;
840286570Smav
841286570Smavtypedef struct l2arc_buf_hdr {
842286570Smav	/* protected by arc_buf_hdr mutex */
843286570Smav	l2arc_dev_t		*b_dev;		/* L2ARC device */
844286570Smav	uint64_t		b_daddr;	/* disk address, offset byte */
845286570Smav	/* real alloc'd buffer size depending on b_compress applied */
846286570Smav	int32_t			b_asize;
847286570Smav
848185029Spjd	list_node_t		b_l2node;
849286570Smav} l2arc_buf_hdr_t;
850286570Smav
851286570Smavstruct arc_buf_hdr {
852286570Smav	/* protected by hash lock */
853286570Smav	dva_t			b_dva;
854286570Smav	uint64_t		b_birth;
855286570Smav	/*
856286570Smav	 * Even though this checksum is only set/verified when a buffer is in
857286570Smav	 * the L1 cache, it needs to be in the set of common fields because it
858286570Smav	 * must be preserved from the time before a buffer is written out to
859286570Smav	 * L2ARC until after it is read back in.
860286570Smav	 */
861286570Smav	zio_cksum_t		*b_freeze_cksum;
862286570Smav
863286570Smav	arc_buf_hdr_t		*b_hash_next;
864286570Smav	arc_flags_t		b_flags;
865286570Smav
866286570Smav	/* immutable */
867286570Smav	int32_t			b_size;
868286570Smav	uint64_t		b_spa;
869286570Smav
870286570Smav	/* L2ARC fields. Undefined when not in L2ARC. */
871286570Smav	l2arc_buf_hdr_t		b_l2hdr;
872286570Smav	/* L1ARC fields. Undefined when in l2arc_only state */
873286570Smav	l1arc_buf_hdr_t		b_l1hdr;
874168404Spjd};
875168404Spjd
876275748Sdelphij#ifdef _KERNEL
877275748Sdelphijstatic int
878275748Sdelphijsysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS)
879275748Sdelphij{
880275748Sdelphij	uint64_t val;
881275748Sdelphij	int err;
882275748Sdelphij
883275748Sdelphij	val = arc_meta_limit;
884275748Sdelphij	err = sysctl_handle_64(oidp, &val, 0, req);
885275748Sdelphij	if (err != 0 || req->newptr == NULL)
886275748Sdelphij		return (err);
887275748Sdelphij
888275748Sdelphij        if (val <= 0 || val > arc_c_max)
889275748Sdelphij		return (EINVAL);
890275748Sdelphij
891275748Sdelphij	arc_meta_limit = val;
892275748Sdelphij	return (0);
893275748Sdelphij}
894275748Sdelphij#endif
895275748Sdelphij
896168404Spjdstatic arc_buf_t *arc_eviction_list;
897168404Spjdstatic arc_buf_hdr_t arc_eviction_hdr;
898168404Spjd
899168404Spjd#define	GHOST_STATE(state)	\
900185029Spjd	((state) == arc_mru_ghost || (state) == arc_mfu_ghost ||	\
901185029Spjd	(state) == arc_l2c_only)
902168404Spjd
903275811Sdelphij#define	HDR_IN_HASH_TABLE(hdr)	((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
904275811Sdelphij#define	HDR_IO_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
905275811Sdelphij#define	HDR_IO_ERROR(hdr)	((hdr)->b_flags & ARC_FLAG_IO_ERROR)
906275811Sdelphij#define	HDR_PREFETCH(hdr)	((hdr)->b_flags & ARC_FLAG_PREFETCH)
907275811Sdelphij#define	HDR_FREED_IN_READ(hdr)	((hdr)->b_flags & ARC_FLAG_FREED_IN_READ)
908275811Sdelphij#define	HDR_BUF_AVAILABLE(hdr)	((hdr)->b_flags & ARC_FLAG_BUF_AVAILABLE)
909286570Smav
910275811Sdelphij#define	HDR_L2CACHE(hdr)	((hdr)->b_flags & ARC_FLAG_L2CACHE)
911286570Smav#define	HDR_L2COMPRESS(hdr)	((hdr)->b_flags & ARC_FLAG_L2COMPRESS)
912275811Sdelphij#define	HDR_L2_READING(hdr)	\
913286570Smav	    (((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) &&	\
914286570Smav	    ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
915275811Sdelphij#define	HDR_L2_WRITING(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITING)
916275811Sdelphij#define	HDR_L2_EVICTED(hdr)	((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
917275811Sdelphij#define	HDR_L2_WRITE_HEAD(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
918168404Spjd
919286570Smav#define	HDR_ISTYPE_METADATA(hdr)	\
920286570Smav	    ((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
921286570Smav#define	HDR_ISTYPE_DATA(hdr)	(!HDR_ISTYPE_METADATA(hdr))
922286570Smav
923286570Smav#define	HDR_HAS_L1HDR(hdr)	((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
924286570Smav#define	HDR_HAS_L2HDR(hdr)	((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
925286570Smav
926286570Smav/* For storing compression mode in b_flags */
927286570Smav#define	HDR_COMPRESS_OFFSET	24
928286570Smav#define	HDR_COMPRESS_NBITS	7
929286570Smav
930286570Smav#define	HDR_GET_COMPRESS(hdr)	((enum zio_compress)BF32_GET(hdr->b_flags, \
931286570Smav	    HDR_COMPRESS_OFFSET, HDR_COMPRESS_NBITS))
932286570Smav#define	HDR_SET_COMPRESS(hdr, cmp) BF32_SET(hdr->b_flags, \
933286570Smav	    HDR_COMPRESS_OFFSET, HDR_COMPRESS_NBITS, (cmp))
934286570Smav
935168404Spjd/*
936185029Spjd * Other sizes
937185029Spjd */
938185029Spjd
939286570Smav#define	HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
940286570Smav#define	HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
941185029Spjd
942185029Spjd/*
943168404Spjd * Hash table routines
944168404Spjd */
945168404Spjd
946205253Skmacy#define	HT_LOCK_PAD	CACHE_LINE_SIZE
947168404Spjd
948168404Spjdstruct ht_lock {
949168404Spjd	kmutex_t	ht_lock;
950168404Spjd#ifdef _KERNEL
951168404Spjd	unsigned char	pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
952168404Spjd#endif
953168404Spjd};
954168404Spjd
955168404Spjd#define	BUF_LOCKS 256
956168404Spjdtypedef struct buf_hash_table {
957168404Spjd	uint64_t ht_mask;
958168404Spjd	arc_buf_hdr_t **ht_table;
959205264Skmacy	struct ht_lock ht_locks[BUF_LOCKS] __aligned(CACHE_LINE_SIZE);
960168404Spjd} buf_hash_table_t;
961168404Spjd
962168404Spjdstatic buf_hash_table_t buf_hash_table;
963168404Spjd
964168404Spjd#define	BUF_HASH_INDEX(spa, dva, birth) \
965168404Spjd	(buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
966168404Spjd#define	BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
967168404Spjd#define	BUF_HASH_LOCK(idx)	(&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
968219089Spjd#define	HDR_LOCK(hdr) \
969219089Spjd	(BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
970168404Spjd
971168404Spjduint64_t zfs_crc64_table[256];
972168404Spjd
973185029Spjd/*
974185029Spjd * Level 2 ARC
975185029Spjd */
976185029Spjd
977272707Savg#define	L2ARC_WRITE_SIZE	(8 * 1024 * 1024)	/* initial write max */
978251478Sdelphij#define	L2ARC_HEADROOM		2			/* num of writes */
979251478Sdelphij/*
980251478Sdelphij * If we discover during ARC scan any buffers to be compressed, we boost
981251478Sdelphij * our headroom for the next scanning cycle by this percentage multiple.
982251478Sdelphij */
983251478Sdelphij#define	L2ARC_HEADROOM_BOOST	200
984208373Smm#define	L2ARC_FEED_SECS		1		/* caching interval secs */
985208373Smm#define	L2ARC_FEED_MIN_MS	200		/* min caching interval ms */
986185029Spjd
987286598Smav/*
988286598Smav * Used to distinguish headers that are being process by
989286598Smav * l2arc_write_buffers(), but have yet to be assigned to a l2arc disk
990286598Smav * address. This can happen when the header is added to the l2arc's list
991286598Smav * of buffers to write in the first stage of l2arc_write_buffers(), but
992286598Smav * has not yet been written out which happens in the second stage of
993286598Smav * l2arc_write_buffers().
994286598Smav */
995286598Smav#define	L2ARC_ADDR_UNSET	((uint64_t)(-1))
996286598Smav
997185029Spjd#define	l2arc_writes_sent	ARCSTAT(arcstat_l2_writes_sent)
998185029Spjd#define	l2arc_writes_done	ARCSTAT(arcstat_l2_writes_done)
999185029Spjd
1000251631Sdelphij/* L2ARC Performance Tunables */
1001185029Spjduint64_t l2arc_write_max = L2ARC_WRITE_SIZE;	/* default max write size */
1002185029Spjduint64_t l2arc_write_boost = L2ARC_WRITE_SIZE;	/* extra write during warmup */
1003185029Spjduint64_t l2arc_headroom = L2ARC_HEADROOM;	/* number of dev writes */
1004251478Sdelphijuint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
1005185029Spjduint64_t l2arc_feed_secs = L2ARC_FEED_SECS;	/* interval seconds */
1006208373Smmuint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS;	/* min interval milliseconds */
1007219089Spjdboolean_t l2arc_noprefetch = B_TRUE;		/* don't cache prefetch bufs */
1008208373Smmboolean_t l2arc_feed_again = B_TRUE;		/* turbo warmup */
1009208373Smmboolean_t l2arc_norw = B_TRUE;			/* no reads during writes */
1010185029Spjd
1011217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RW,
1012205231Skmacy    &l2arc_write_max, 0, "max write size");
1013217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RW,
1014205231Skmacy    &l2arc_write_boost, 0, "extra write during warmup");
1015217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RW,
1016205231Skmacy    &l2arc_headroom, 0, "number of dev writes");
1017217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RW,
1018205231Skmacy    &l2arc_feed_secs, 0, "interval seconds");
1019217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RW,
1020208373Smm    &l2arc_feed_min_ms, 0, "min interval milliseconds");
1021205231Skmacy
1022205231SkmacySYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RW,
1023205231Skmacy    &l2arc_noprefetch, 0, "don't cache prefetch bufs");
1024208373SmmSYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RW,
1025208373Smm    &l2arc_feed_again, 0, "turbo warmup");
1026208373SmmSYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RW,
1027208373Smm    &l2arc_norw, 0, "no reads during writes");
1028205231Skmacy
1029217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
1030286770Smav    &ARC_anon.arcs_size.rc_count, 0, "size of anonymous state");
1031217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_metadata_lsize, CTLFLAG_RD,
1032205231Skmacy    &ARC_anon.arcs_lsize[ARC_BUFC_METADATA], 0, "size of anonymous state");
1033217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_data_lsize, CTLFLAG_RD,
1034205231Skmacy    &ARC_anon.arcs_lsize[ARC_BUFC_DATA], 0, "size of anonymous state");
1035205231Skmacy
1036217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
1037286770Smav    &ARC_mru.arcs_size.rc_count, 0, "size of mru state");
1038217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_metadata_lsize, CTLFLAG_RD,
1039205231Skmacy    &ARC_mru.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mru state");
1040217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_data_lsize, CTLFLAG_RD,
1041205231Skmacy    &ARC_mru.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mru state");
1042205231Skmacy
1043217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
1044286770Smav    &ARC_mru_ghost.arcs_size.rc_count, 0, "size of mru ghost state");
1045217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_lsize, CTLFLAG_RD,
1046205231Skmacy    &ARC_mru_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
1047205231Skmacy    "size of metadata in mru ghost state");
1048217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_lsize, CTLFLAG_RD,
1049205231Skmacy    &ARC_mru_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
1050205231Skmacy    "size of data in mru ghost state");
1051205231Skmacy
1052217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
1053286770Smav    &ARC_mfu.arcs_size.rc_count, 0, "size of mfu state");
1054217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_metadata_lsize, CTLFLAG_RD,
1055205231Skmacy    &ARC_mfu.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mfu state");
1056217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_data_lsize, CTLFLAG_RD,
1057205231Skmacy    &ARC_mfu.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mfu state");
1058205231Skmacy
1059217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
1060286770Smav    &ARC_mfu_ghost.arcs_size.rc_count, 0, "size of mfu ghost state");
1061217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_lsize, CTLFLAG_RD,
1062205231Skmacy    &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
1063205231Skmacy    "size of metadata in mfu ghost state");
1064217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_lsize, CTLFLAG_RD,
1065205231Skmacy    &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
1066205231Skmacy    "size of data in mfu ghost state");
1067205231Skmacy
1068217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
1069286770Smav    &ARC_l2c_only.arcs_size.rc_count, 0, "size of mru state");
1070205231Skmacy
1071185029Spjd/*
1072185029Spjd * L2ARC Internals
1073185029Spjd */
1074286570Smavstruct l2arc_dev {
1075185029Spjd	vdev_t			*l2ad_vdev;	/* vdev */
1076185029Spjd	spa_t			*l2ad_spa;	/* spa */
1077185029Spjd	uint64_t		l2ad_hand;	/* next write location */
1078185029Spjd	uint64_t		l2ad_start;	/* first addr on device */
1079185029Spjd	uint64_t		l2ad_end;	/* last addr on device */
1080185029Spjd	boolean_t		l2ad_first;	/* first sweep through */
1081208373Smm	boolean_t		l2ad_writing;	/* currently writing */
1082286570Smav	kmutex_t		l2ad_mtx;	/* lock for buffer list */
1083286570Smav	list_t			l2ad_buflist;	/* buffer list */
1084185029Spjd	list_node_t		l2ad_node;	/* device list node */
1085286598Smav	refcount_t		l2ad_alloc;	/* allocated bytes */
1086286570Smav};
1087185029Spjd
1088185029Spjdstatic list_t L2ARC_dev_list;			/* device list */
1089185029Spjdstatic list_t *l2arc_dev_list;			/* device list pointer */
1090185029Spjdstatic kmutex_t l2arc_dev_mtx;			/* device list mutex */
1091185029Spjdstatic l2arc_dev_t *l2arc_dev_last;		/* last device used */
1092185029Spjdstatic list_t L2ARC_free_on_write;		/* free after write buf list */
1093185029Spjdstatic list_t *l2arc_free_on_write;		/* free after write list ptr */
1094185029Spjdstatic kmutex_t l2arc_free_on_write_mtx;	/* mutex for list */
1095185029Spjdstatic uint64_t l2arc_ndev;			/* number of devices */
1096185029Spjd
1097185029Spjdtypedef struct l2arc_read_callback {
1098251478Sdelphij	arc_buf_t		*l2rcb_buf;		/* read buffer */
1099251478Sdelphij	spa_t			*l2rcb_spa;		/* spa */
1100251478Sdelphij	blkptr_t		l2rcb_bp;		/* original blkptr */
1101268123Sdelphij	zbookmark_phys_t	l2rcb_zb;		/* original bookmark */
1102251478Sdelphij	int			l2rcb_flags;		/* original flags */
1103251478Sdelphij	enum zio_compress	l2rcb_compress;		/* applied compress */
1104185029Spjd} l2arc_read_callback_t;
1105185029Spjd
1106185029Spjdtypedef struct l2arc_write_callback {
1107185029Spjd	l2arc_dev_t	*l2wcb_dev;		/* device info */
1108185029Spjd	arc_buf_hdr_t	*l2wcb_head;		/* head of write buflist */
1109185029Spjd} l2arc_write_callback_t;
1110185029Spjd
1111185029Spjdtypedef struct l2arc_data_free {
1112185029Spjd	/* protected by l2arc_free_on_write_mtx */
1113185029Spjd	void		*l2df_data;
1114185029Spjd	size_t		l2df_size;
1115185029Spjd	void		(*l2df_func)(void *, size_t);
1116185029Spjd	list_node_t	l2df_list_node;
1117185029Spjd} l2arc_data_free_t;
1118185029Spjd
1119185029Spjdstatic kmutex_t l2arc_feed_thr_lock;
1120185029Spjdstatic kcondvar_t l2arc_feed_thr_cv;
1121185029Spjdstatic uint8_t l2arc_thread_exit;
1122185029Spjd
1123275811Sdelphijstatic void arc_get_data_buf(arc_buf_t *);
1124275811Sdelphijstatic void arc_access(arc_buf_hdr_t *, kmutex_t *);
1125286763Smavstatic boolean_t arc_is_overflowing();
1126275811Sdelphijstatic void arc_buf_watch(arc_buf_t *);
1127275811Sdelphij
1128286570Smavstatic arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
1129286570Smavstatic uint32_t arc_bufc_to_flags(arc_buf_contents_t);
1130286570Smav
1131275811Sdelphijstatic boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
1132275811Sdelphijstatic void l2arc_read_done(zio_t *);
1133185029Spjd
1134286570Smavstatic boolean_t l2arc_compress_buf(arc_buf_hdr_t *);
1135275811Sdelphijstatic void l2arc_decompress_zio(zio_t *, arc_buf_hdr_t *, enum zio_compress);
1136275811Sdelphijstatic void l2arc_release_cdata_buf(arc_buf_hdr_t *);
1137251478Sdelphij
1138168404Spjdstatic uint64_t
1139209962Smmbuf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
1140168404Spjd{
1141168404Spjd	uint8_t *vdva = (uint8_t *)dva;
1142168404Spjd	uint64_t crc = -1ULL;
1143168404Spjd	int i;
1144168404Spjd
1145168404Spjd	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
1146168404Spjd
1147168404Spjd	for (i = 0; i < sizeof (dva_t); i++)
1148168404Spjd		crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
1149168404Spjd
1150209962Smm	crc ^= (spa>>8) ^ birth;
1151168404Spjd
1152168404Spjd	return (crc);
1153168404Spjd}
1154168404Spjd
1155168404Spjd#define	BUF_EMPTY(buf)						\
1156168404Spjd	((buf)->b_dva.dva_word[0] == 0 &&			\
1157286570Smav	(buf)->b_dva.dva_word[1] == 0)
1158168404Spjd
1159168404Spjd#define	BUF_EQUAL(spa, dva, birth, buf)				\
1160168404Spjd	((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) &&	\
1161168404Spjd	((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) &&	\
1162168404Spjd	((buf)->b_birth == birth) && ((buf)->b_spa == spa)
1163168404Spjd
1164219089Spjdstatic void
1165219089Spjdbuf_discard_identity(arc_buf_hdr_t *hdr)
1166219089Spjd{
1167219089Spjd	hdr->b_dva.dva_word[0] = 0;
1168219089Spjd	hdr->b_dva.dva_word[1] = 0;
1169219089Spjd	hdr->b_birth = 0;
1170219089Spjd}
1171219089Spjd
1172168404Spjdstatic arc_buf_hdr_t *
1173268075Sdelphijbuf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
1174168404Spjd{
1175268075Sdelphij	const dva_t *dva = BP_IDENTITY(bp);
1176268075Sdelphij	uint64_t birth = BP_PHYSICAL_BIRTH(bp);
1177168404Spjd	uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1178168404Spjd	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1179275811Sdelphij	arc_buf_hdr_t *hdr;
1180168404Spjd
1181168404Spjd	mutex_enter(hash_lock);
1182275811Sdelphij	for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
1183275811Sdelphij	    hdr = hdr->b_hash_next) {
1184275811Sdelphij		if (BUF_EQUAL(spa, dva, birth, hdr)) {
1185168404Spjd			*lockp = hash_lock;
1186275811Sdelphij			return (hdr);
1187168404Spjd		}
1188168404Spjd	}
1189168404Spjd	mutex_exit(hash_lock);
1190168404Spjd	*lockp = NULL;
1191168404Spjd	return (NULL);
1192168404Spjd}
1193168404Spjd
1194168404Spjd/*
1195168404Spjd * Insert an entry into the hash table.  If there is already an element
1196168404Spjd * equal to elem in the hash table, then the already existing element
1197168404Spjd * will be returned and the new element will not be inserted.
1198168404Spjd * Otherwise returns NULL.
1199286570Smav * If lockp == NULL, the caller is assumed to already hold the hash lock.
1200168404Spjd */
1201168404Spjdstatic arc_buf_hdr_t *
1202275811Sdelphijbuf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1203168404Spjd{
1204275811Sdelphij	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1205168404Spjd	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1206275811Sdelphij	arc_buf_hdr_t *fhdr;
1207168404Spjd	uint32_t i;
1208168404Spjd
1209275811Sdelphij	ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
1210275811Sdelphij	ASSERT(hdr->b_birth != 0);
1211275811Sdelphij	ASSERT(!HDR_IN_HASH_TABLE(hdr));
1212286570Smav
1213286570Smav	if (lockp != NULL) {
1214286570Smav		*lockp = hash_lock;
1215286570Smav		mutex_enter(hash_lock);
1216286570Smav	} else {
1217286570Smav		ASSERT(MUTEX_HELD(hash_lock));
1218286570Smav	}
1219286570Smav
1220275811Sdelphij	for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
1221275811Sdelphij	    fhdr = fhdr->b_hash_next, i++) {
1222275811Sdelphij		if (BUF_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
1223275811Sdelphij			return (fhdr);
1224168404Spjd	}
1225168404Spjd
1226275811Sdelphij	hdr->b_hash_next = buf_hash_table.ht_table[idx];
1227275811Sdelphij	buf_hash_table.ht_table[idx] = hdr;
1228275811Sdelphij	hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
1229168404Spjd
1230168404Spjd	/* collect some hash table performance data */
1231168404Spjd	if (i > 0) {
1232168404Spjd		ARCSTAT_BUMP(arcstat_hash_collisions);
1233168404Spjd		if (i == 1)
1234168404Spjd			ARCSTAT_BUMP(arcstat_hash_chains);
1235168404Spjd
1236168404Spjd		ARCSTAT_MAX(arcstat_hash_chain_max, i);
1237168404Spjd	}
1238168404Spjd
1239168404Spjd	ARCSTAT_BUMP(arcstat_hash_elements);
1240168404Spjd	ARCSTAT_MAXSTAT(arcstat_hash_elements);
1241168404Spjd
1242168404Spjd	return (NULL);
1243168404Spjd}
1244168404Spjd
1245168404Spjdstatic void
1246275811Sdelphijbuf_hash_remove(arc_buf_hdr_t *hdr)
1247168404Spjd{
1248275811Sdelphij	arc_buf_hdr_t *fhdr, **hdrp;
1249275811Sdelphij	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1250168404Spjd
1251168404Spjd	ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
1252275811Sdelphij	ASSERT(HDR_IN_HASH_TABLE(hdr));
1253168404Spjd
1254275811Sdelphij	hdrp = &buf_hash_table.ht_table[idx];
1255275811Sdelphij	while ((fhdr = *hdrp) != hdr) {
1256275811Sdelphij		ASSERT(fhdr != NULL);
1257275811Sdelphij		hdrp = &fhdr->b_hash_next;
1258168404Spjd	}
1259275811Sdelphij	*hdrp = hdr->b_hash_next;
1260275811Sdelphij	hdr->b_hash_next = NULL;
1261275811Sdelphij	hdr->b_flags &= ~ARC_FLAG_IN_HASH_TABLE;
1262168404Spjd
1263168404Spjd	/* collect some hash table performance data */
1264168404Spjd	ARCSTAT_BUMPDOWN(arcstat_hash_elements);
1265168404Spjd
1266168404Spjd	if (buf_hash_table.ht_table[idx] &&
1267168404Spjd	    buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1268168404Spjd		ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1269168404Spjd}
1270168404Spjd
1271168404Spjd/*
1272168404Spjd * Global data structures and functions for the buf kmem cache.
1273168404Spjd */
1274286570Smavstatic kmem_cache_t *hdr_full_cache;
1275286570Smavstatic kmem_cache_t *hdr_l2only_cache;
1276168404Spjdstatic kmem_cache_t *buf_cache;
1277168404Spjd
1278168404Spjdstatic void
1279168404Spjdbuf_fini(void)
1280168404Spjd{
1281168404Spjd	int i;
1282168404Spjd
1283168404Spjd	kmem_free(buf_hash_table.ht_table,
1284168404Spjd	    (buf_hash_table.ht_mask + 1) * sizeof (void *));
1285168404Spjd	for (i = 0; i < BUF_LOCKS; i++)
1286168404Spjd		mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
1287286570Smav	kmem_cache_destroy(hdr_full_cache);
1288286570Smav	kmem_cache_destroy(hdr_l2only_cache);
1289168404Spjd	kmem_cache_destroy(buf_cache);
1290168404Spjd}
1291168404Spjd
1292168404Spjd/*
1293168404Spjd * Constructor callback - called when the cache is empty
1294168404Spjd * and a new buf is requested.
1295168404Spjd */
1296168404Spjd/* ARGSUSED */
1297168404Spjdstatic int
1298286570Smavhdr_full_cons(void *vbuf, void *unused, int kmflag)
1299168404Spjd{
1300275811Sdelphij	arc_buf_hdr_t *hdr = vbuf;
1301168404Spjd
1302286570Smav	bzero(hdr, HDR_FULL_SIZE);
1303286570Smav	cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
1304286570Smav	refcount_create(&hdr->b_l1hdr.b_refcnt);
1305286570Smav	mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1306286763Smav	multilist_link_init(&hdr->b_l1hdr.b_arc_node);
1307286570Smav	arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1308185029Spjd
1309168404Spjd	return (0);
1310168404Spjd}
1311168404Spjd
1312185029Spjd/* ARGSUSED */
1313185029Spjdstatic int
1314286570Smavhdr_l2only_cons(void *vbuf, void *unused, int kmflag)
1315286570Smav{
1316286570Smav	arc_buf_hdr_t *hdr = vbuf;
1317286570Smav
1318286570Smav	bzero(hdr, HDR_L2ONLY_SIZE);
1319286570Smav	arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1320286570Smav
1321286570Smav	return (0);
1322286570Smav}
1323286570Smav
1324286570Smav/* ARGSUSED */
1325286570Smavstatic int
1326185029Spjdbuf_cons(void *vbuf, void *unused, int kmflag)
1327185029Spjd{
1328185029Spjd	arc_buf_t *buf = vbuf;
1329185029Spjd
1330185029Spjd	bzero(buf, sizeof (arc_buf_t));
1331219089Spjd	mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1332208373Smm	arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1333208373Smm
1334185029Spjd	return (0);
1335185029Spjd}
1336185029Spjd
1337168404Spjd/*
1338168404Spjd * Destructor callback - called when a cached buf is
1339168404Spjd * no longer required.
1340168404Spjd */
1341168404Spjd/* ARGSUSED */
1342168404Spjdstatic void
1343286570Smavhdr_full_dest(void *vbuf, void *unused)
1344168404Spjd{
1345275811Sdelphij	arc_buf_hdr_t *hdr = vbuf;
1346168404Spjd
1347275811Sdelphij	ASSERT(BUF_EMPTY(hdr));
1348286570Smav	cv_destroy(&hdr->b_l1hdr.b_cv);
1349286570Smav	refcount_destroy(&hdr->b_l1hdr.b_refcnt);
1350286570Smav	mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1351286763Smav	ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1352286570Smav	arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1353168404Spjd}
1354168404Spjd
1355185029Spjd/* ARGSUSED */
1356185029Spjdstatic void
1357286570Smavhdr_l2only_dest(void *vbuf, void *unused)
1358286570Smav{
1359286570Smav	arc_buf_hdr_t *hdr = vbuf;
1360286570Smav
1361286570Smav	ASSERT(BUF_EMPTY(hdr));
1362286570Smav	arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1363286570Smav}
1364286570Smav
1365286570Smav/* ARGSUSED */
1366286570Smavstatic void
1367185029Spjdbuf_dest(void *vbuf, void *unused)
1368185029Spjd{
1369185029Spjd	arc_buf_t *buf = vbuf;
1370185029Spjd
1371219089Spjd	mutex_destroy(&buf->b_evict_lock);
1372208373Smm	arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1373185029Spjd}
1374185029Spjd
1375168404Spjd/*
1376168404Spjd * Reclaim callback -- invoked when memory is low.
1377168404Spjd */
1378168404Spjd/* ARGSUSED */
1379168404Spjdstatic void
1380168404Spjdhdr_recl(void *unused)
1381168404Spjd{
1382168404Spjd	dprintf("hdr_recl called\n");
1383168404Spjd	/*
1384168404Spjd	 * umem calls the reclaim func when we destroy the buf cache,
1385168404Spjd	 * which is after we do arc_fini().
1386168404Spjd	 */
1387168404Spjd	if (!arc_dead)
1388286763Smav		cv_signal(&arc_reclaim_thread_cv);
1389168404Spjd}
1390168404Spjd
1391168404Spjdstatic void
1392168404Spjdbuf_init(void)
1393168404Spjd{
1394168404Spjd	uint64_t *ct;
1395168404Spjd	uint64_t hsize = 1ULL << 12;
1396168404Spjd	int i, j;
1397168404Spjd
1398168404Spjd	/*
1399168404Spjd	 * The hash table is big enough to fill all of physical memory
1400269230Sdelphij	 * with an average block size of zfs_arc_average_blocksize (default 8K).
1401269230Sdelphij	 * By default, the table will take up
1402269230Sdelphij	 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1403168404Spjd	 */
1404269230Sdelphij	while (hsize * zfs_arc_average_blocksize < (uint64_t)physmem * PAGESIZE)
1405168404Spjd		hsize <<= 1;
1406168404Spjdretry:
1407168404Spjd	buf_hash_table.ht_mask = hsize - 1;
1408168404Spjd	buf_hash_table.ht_table =
1409168404Spjd	    kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1410168404Spjd	if (buf_hash_table.ht_table == NULL) {
1411168404Spjd		ASSERT(hsize > (1ULL << 8));
1412168404Spjd		hsize >>= 1;
1413168404Spjd		goto retry;
1414168404Spjd	}
1415168404Spjd
1416286570Smav	hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
1417286570Smav	    0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
1418286570Smav	hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
1419286570Smav	    HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
1420286570Smav	    NULL, NULL, 0);
1421168404Spjd	buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1422185029Spjd	    0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1423168404Spjd
1424168404Spjd	for (i = 0; i < 256; i++)
1425168404Spjd		for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1426168404Spjd			*ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1427168404Spjd
1428168404Spjd	for (i = 0; i < BUF_LOCKS; i++) {
1429168404Spjd		mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1430168404Spjd		    NULL, MUTEX_DEFAULT, NULL);
1431168404Spjd	}
1432168404Spjd}
1433168404Spjd
1434286570Smav/*
1435286570Smav * Transition between the two allocation states for the arc_buf_hdr struct.
1436286570Smav * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
1437286570Smav * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
1438286570Smav * version is used when a cache buffer is only in the L2ARC in order to reduce
1439286570Smav * memory usage.
1440286570Smav */
1441286570Smavstatic arc_buf_hdr_t *
1442286570Smavarc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
1443286570Smav{
1444286570Smav	ASSERT(HDR_HAS_L2HDR(hdr));
1445286570Smav
1446286570Smav	arc_buf_hdr_t *nhdr;
1447286570Smav	l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
1448286570Smav
1449286570Smav	ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
1450286570Smav	    (old == hdr_l2only_cache && new == hdr_full_cache));
1451286570Smav
1452286570Smav	nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
1453286570Smav
1454286570Smav	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
1455286570Smav	buf_hash_remove(hdr);
1456286570Smav
1457286570Smav	bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
1458286598Smav
1459286570Smav	if (new == hdr_full_cache) {
1460286570Smav		nhdr->b_flags |= ARC_FLAG_HAS_L1HDR;
1461286570Smav		/*
1462286570Smav		 * arc_access and arc_change_state need to be aware that a
1463286570Smav		 * header has just come out of L2ARC, so we set its state to
1464286570Smav		 * l2c_only even though it's about to change.
1465286570Smav		 */
1466286570Smav		nhdr->b_l1hdr.b_state = arc_l2c_only;
1467286763Smav
1468286763Smav		/* Verify previous threads set to NULL before freeing */
1469286763Smav		ASSERT3P(nhdr->b_l1hdr.b_tmp_cdata, ==, NULL);
1470286570Smav	} else {
1471286570Smav		ASSERT(hdr->b_l1hdr.b_buf == NULL);
1472286570Smav		ASSERT0(hdr->b_l1hdr.b_datacnt);
1473286763Smav
1474286570Smav		/*
1475286763Smav		 * If we've reached here, We must have been called from
1476286763Smav		 * arc_evict_hdr(), as such we should have already been
1477286763Smav		 * removed from any ghost list we were previously on
1478286763Smav		 * (which protects us from racing with arc_evict_state),
1479286763Smav		 * thus no locking is needed during this check.
1480286570Smav		 */
1481286763Smav		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1482286763Smav
1483286763Smav		/*
1484286763Smav		 * A buffer must not be moved into the arc_l2c_only
1485286763Smav		 * state if it's not finished being written out to the
1486286763Smav		 * l2arc device. Otherwise, the b_l1hdr.b_tmp_cdata field
1487286763Smav		 * might try to be accessed, even though it was removed.
1488286763Smav		 */
1489286763Smav		VERIFY(!HDR_L2_WRITING(hdr));
1490286763Smav		VERIFY3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
1491286763Smav
1492286570Smav		nhdr->b_flags &= ~ARC_FLAG_HAS_L1HDR;
1493286570Smav	}
1494286570Smav	/*
1495286570Smav	 * The header has been reallocated so we need to re-insert it into any
1496286570Smav	 * lists it was on.
1497286570Smav	 */
1498286570Smav	(void) buf_hash_insert(nhdr, NULL);
1499286570Smav
1500286570Smav	ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
1501286570Smav
1502286570Smav	mutex_enter(&dev->l2ad_mtx);
1503286570Smav
1504286570Smav	/*
1505286570Smav	 * We must place the realloc'ed header back into the list at
1506286570Smav	 * the same spot. Otherwise, if it's placed earlier in the list,
1507286570Smav	 * l2arc_write_buffers() could find it during the function's
1508286570Smav	 * write phase, and try to write it out to the l2arc.
1509286570Smav	 */
1510286570Smav	list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
1511286570Smav	list_remove(&dev->l2ad_buflist, hdr);
1512286570Smav
1513286570Smav	mutex_exit(&dev->l2ad_mtx);
1514286570Smav
1515286598Smav	/*
1516286598Smav	 * Since we're using the pointer address as the tag when
1517286598Smav	 * incrementing and decrementing the l2ad_alloc refcount, we
1518286598Smav	 * must remove the old pointer (that we're about to destroy) and
1519286598Smav	 * add the new pointer to the refcount. Otherwise we'd remove
1520286598Smav	 * the wrong pointer address when calling arc_hdr_destroy() later.
1521286598Smav	 */
1522286598Smav
1523286598Smav	(void) refcount_remove_many(&dev->l2ad_alloc,
1524286598Smav	    hdr->b_l2hdr.b_asize, hdr);
1525286598Smav
1526286598Smav	(void) refcount_add_many(&dev->l2ad_alloc,
1527286598Smav	    nhdr->b_l2hdr.b_asize, nhdr);
1528286598Smav
1529286570Smav	buf_discard_identity(hdr);
1530286570Smav	hdr->b_freeze_cksum = NULL;
1531286570Smav	kmem_cache_free(old, hdr);
1532286570Smav
1533286570Smav	return (nhdr);
1534286570Smav}
1535286570Smav
1536286570Smav
1537168404Spjd#define	ARC_MINTIME	(hz>>4) /* 62 ms */
1538168404Spjd
1539168404Spjdstatic void
1540168404Spjdarc_cksum_verify(arc_buf_t *buf)
1541168404Spjd{
1542168404Spjd	zio_cksum_t zc;
1543168404Spjd
1544168404Spjd	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1545168404Spjd		return;
1546168404Spjd
1547286570Smav	mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1548286570Smav	if (buf->b_hdr->b_freeze_cksum == NULL || HDR_IO_ERROR(buf->b_hdr)) {
1549286570Smav		mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1550168404Spjd		return;
1551168404Spjd	}
1552168404Spjd	fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1553168404Spjd	if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
1554168404Spjd		panic("buffer modified while frozen!");
1555286570Smav	mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1556168404Spjd}
1557168404Spjd
1558185029Spjdstatic int
1559185029Spjdarc_cksum_equal(arc_buf_t *buf)
1560185029Spjd{
1561185029Spjd	zio_cksum_t zc;
1562185029Spjd	int equal;
1563185029Spjd
1564286570Smav	mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1565185029Spjd	fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1566185029Spjd	equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
1567286570Smav	mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1568185029Spjd
1569185029Spjd	return (equal);
1570185029Spjd}
1571185029Spjd
1572168404Spjdstatic void
1573185029Spjdarc_cksum_compute(arc_buf_t *buf, boolean_t force)
1574168404Spjd{
1575185029Spjd	if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
1576168404Spjd		return;
1577168404Spjd
1578286570Smav	mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1579168404Spjd	if (buf->b_hdr->b_freeze_cksum != NULL) {
1580286570Smav		mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1581168404Spjd		return;
1582168404Spjd	}
1583168404Spjd	buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
1584168404Spjd	fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
1585168404Spjd	    buf->b_hdr->b_freeze_cksum);
1586286570Smav	mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1587240133Smm#ifdef illumos
1588240133Smm	arc_buf_watch(buf);
1589277300Ssmh#endif
1590168404Spjd}
1591168404Spjd
1592240133Smm#ifdef illumos
1593240133Smm#ifndef _KERNEL
1594240133Smmtypedef struct procctl {
1595240133Smm	long cmd;
1596240133Smm	prwatch_t prwatch;
1597240133Smm} procctl_t;
1598240133Smm#endif
1599240133Smm
1600240133Smm/* ARGSUSED */
1601240133Smmstatic void
1602240133Smmarc_buf_unwatch(arc_buf_t *buf)
1603240133Smm{
1604240133Smm#ifndef _KERNEL
1605240133Smm	if (arc_watch) {
1606240133Smm		int result;
1607240133Smm		procctl_t ctl;
1608240133Smm		ctl.cmd = PCWATCH;
1609240133Smm		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1610240133Smm		ctl.prwatch.pr_size = 0;
1611240133Smm		ctl.prwatch.pr_wflags = 0;
1612240133Smm		result = write(arc_procfd, &ctl, sizeof (ctl));
1613240133Smm		ASSERT3U(result, ==, sizeof (ctl));
1614240133Smm	}
1615240133Smm#endif
1616240133Smm}
1617240133Smm
1618240133Smm/* ARGSUSED */
1619240133Smmstatic void
1620240133Smmarc_buf_watch(arc_buf_t *buf)
1621240133Smm{
1622240133Smm#ifndef _KERNEL
1623240133Smm	if (arc_watch) {
1624240133Smm		int result;
1625240133Smm		procctl_t ctl;
1626240133Smm		ctl.cmd = PCWATCH;
1627240133Smm		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1628240133Smm		ctl.prwatch.pr_size = buf->b_hdr->b_size;
1629240133Smm		ctl.prwatch.pr_wflags = WA_WRITE;
1630240133Smm		result = write(arc_procfd, &ctl, sizeof (ctl));
1631240133Smm		ASSERT3U(result, ==, sizeof (ctl));
1632240133Smm	}
1633240133Smm#endif
1634240133Smm}
1635240133Smm#endif /* illumos */
1636240133Smm
1637286570Smavstatic arc_buf_contents_t
1638286570Smavarc_buf_type(arc_buf_hdr_t *hdr)
1639286570Smav{
1640286570Smav	if (HDR_ISTYPE_METADATA(hdr)) {
1641286570Smav		return (ARC_BUFC_METADATA);
1642286570Smav	} else {
1643286570Smav		return (ARC_BUFC_DATA);
1644286570Smav	}
1645286570Smav}
1646286570Smav
1647286570Smavstatic uint32_t
1648286570Smavarc_bufc_to_flags(arc_buf_contents_t type)
1649286570Smav{
1650286570Smav	switch (type) {
1651286570Smav	case ARC_BUFC_DATA:
1652286570Smav		/* metadata field is 0 if buffer contains normal data */
1653286570Smav		return (0);
1654286570Smav	case ARC_BUFC_METADATA:
1655286570Smav		return (ARC_FLAG_BUFC_METADATA);
1656286570Smav	default:
1657286570Smav		break;
1658286570Smav	}
1659286570Smav	panic("undefined ARC buffer type!");
1660286570Smav	return ((uint32_t)-1);
1661286570Smav}
1662286570Smav
1663168404Spjdvoid
1664168404Spjdarc_buf_thaw(arc_buf_t *buf)
1665168404Spjd{
1666185029Spjd	if (zfs_flags & ZFS_DEBUG_MODIFY) {
1667286570Smav		if (buf->b_hdr->b_l1hdr.b_state != arc_anon)
1668185029Spjd			panic("modifying non-anon buffer!");
1669286570Smav		if (HDR_IO_IN_PROGRESS(buf->b_hdr))
1670185029Spjd			panic("modifying buffer while i/o in progress!");
1671185029Spjd		arc_cksum_verify(buf);
1672185029Spjd	}
1673168404Spjd
1674286570Smav	mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1675168404Spjd	if (buf->b_hdr->b_freeze_cksum != NULL) {
1676168404Spjd		kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1677168404Spjd		buf->b_hdr->b_freeze_cksum = NULL;
1678168404Spjd	}
1679219089Spjd
1680286570Smav#ifdef ZFS_DEBUG
1681219089Spjd	if (zfs_flags & ZFS_DEBUG_MODIFY) {
1682286570Smav		if (buf->b_hdr->b_l1hdr.b_thawed != NULL)
1683286570Smav			kmem_free(buf->b_hdr->b_l1hdr.b_thawed, 1);
1684286570Smav		buf->b_hdr->b_l1hdr.b_thawed = kmem_alloc(1, KM_SLEEP);
1685219089Spjd	}
1686286570Smav#endif
1687219089Spjd
1688286570Smav	mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1689240133Smm
1690240133Smm#ifdef illumos
1691240133Smm	arc_buf_unwatch(buf);
1692277300Ssmh#endif
1693168404Spjd}
1694168404Spjd
1695168404Spjdvoid
1696168404Spjdarc_buf_freeze(arc_buf_t *buf)
1697168404Spjd{
1698219089Spjd	kmutex_t *hash_lock;
1699219089Spjd
1700168404Spjd	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1701168404Spjd		return;
1702168404Spjd
1703219089Spjd	hash_lock = HDR_LOCK(buf->b_hdr);
1704219089Spjd	mutex_enter(hash_lock);
1705219089Spjd
1706168404Spjd	ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
1707286570Smav	    buf->b_hdr->b_l1hdr.b_state == arc_anon);
1708185029Spjd	arc_cksum_compute(buf, B_FALSE);
1709219089Spjd	mutex_exit(hash_lock);
1710240133Smm
1711168404Spjd}
1712168404Spjd
1713168404Spjdstatic void
1714275811Sdelphijadd_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1715168404Spjd{
1716286570Smav	ASSERT(HDR_HAS_L1HDR(hdr));
1717168404Spjd	ASSERT(MUTEX_HELD(hash_lock));
1718286570Smav	arc_state_t *state = hdr->b_l1hdr.b_state;
1719168404Spjd
1720286570Smav	if ((refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
1721286570Smav	    (state != arc_anon)) {
1722286570Smav		/* We don't use the L2-only state list. */
1723286570Smav		if (state != arc_l2c_only) {
1724286763Smav			arc_buf_contents_t type = arc_buf_type(hdr);
1725286570Smav			uint64_t delta = hdr->b_size * hdr->b_l1hdr.b_datacnt;
1726286763Smav			multilist_t *list = &state->arcs_list[type];
1727286763Smav			uint64_t *size = &state->arcs_lsize[type];
1728168404Spjd
1729286763Smav			multilist_remove(list, hdr);
1730286763Smav
1731286570Smav			if (GHOST_STATE(state)) {
1732286570Smav				ASSERT0(hdr->b_l1hdr.b_datacnt);
1733286570Smav				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
1734286570Smav				delta = hdr->b_size;
1735286570Smav			}
1736286570Smav			ASSERT(delta > 0);
1737286570Smav			ASSERT3U(*size, >=, delta);
1738286570Smav			atomic_add_64(size, -delta);
1739168404Spjd		}
1740185029Spjd		/* remove the prefetch flag if we get a reference */
1741286570Smav		hdr->b_flags &= ~ARC_FLAG_PREFETCH;
1742168404Spjd	}
1743168404Spjd}
1744168404Spjd
1745168404Spjdstatic int
1746275811Sdelphijremove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1747168404Spjd{
1748168404Spjd	int cnt;
1749286570Smav	arc_state_t *state = hdr->b_l1hdr.b_state;
1750168404Spjd
1751286570Smav	ASSERT(HDR_HAS_L1HDR(hdr));
1752168404Spjd	ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
1753168404Spjd	ASSERT(!GHOST_STATE(state));
1754168404Spjd
1755286570Smav	/*
1756286570Smav	 * arc_l2c_only counts as a ghost state so we don't need to explicitly
1757286570Smav	 * check to prevent usage of the arc_l2c_only list.
1758286570Smav	 */
1759286570Smav	if (((cnt = refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
1760168404Spjd	    (state != arc_anon)) {
1761286763Smav		arc_buf_contents_t type = arc_buf_type(hdr);
1762286763Smav		multilist_t *list = &state->arcs_list[type];
1763286763Smav		uint64_t *size = &state->arcs_lsize[type];
1764185029Spjd
1765286763Smav		multilist_insert(list, hdr);
1766286763Smav
1767286570Smav		ASSERT(hdr->b_l1hdr.b_datacnt > 0);
1768286570Smav		atomic_add_64(size, hdr->b_size *
1769286570Smav		    hdr->b_l1hdr.b_datacnt);
1770168404Spjd	}
1771168404Spjd	return (cnt);
1772168404Spjd}
1773168404Spjd
1774168404Spjd/*
1775286763Smav * Move the supplied buffer to the indicated state. The hash lock
1776168404Spjd * for the buffer must be held by the caller.
1777168404Spjd */
1778168404Spjdstatic void
1779275811Sdelphijarc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
1780275811Sdelphij    kmutex_t *hash_lock)
1781168404Spjd{
1782286570Smav	arc_state_t *old_state;
1783286570Smav	int64_t refcnt;
1784286570Smav	uint32_t datacnt;
1785168404Spjd	uint64_t from_delta, to_delta;
1786286570Smav	arc_buf_contents_t buftype = arc_buf_type(hdr);
1787168404Spjd
1788286570Smav	/*
1789286570Smav	 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
1790286570Smav	 * in arc_read() when bringing a buffer out of the L2ARC.  However, the
1791286570Smav	 * L1 hdr doesn't always exist when we change state to arc_anon before
1792286570Smav	 * destroying a header, in which case reallocating to add the L1 hdr is
1793286570Smav	 * pointless.
1794286570Smav	 */
1795286570Smav	if (HDR_HAS_L1HDR(hdr)) {
1796286570Smav		old_state = hdr->b_l1hdr.b_state;
1797286570Smav		refcnt = refcount_count(&hdr->b_l1hdr.b_refcnt);
1798286570Smav		datacnt = hdr->b_l1hdr.b_datacnt;
1799286570Smav	} else {
1800286570Smav		old_state = arc_l2c_only;
1801286570Smav		refcnt = 0;
1802286570Smav		datacnt = 0;
1803286570Smav	}
1804286570Smav
1805168404Spjd	ASSERT(MUTEX_HELD(hash_lock));
1806258632Savg	ASSERT3P(new_state, !=, old_state);
1807286570Smav	ASSERT(refcnt == 0 || datacnt > 0);
1808286570Smav	ASSERT(!GHOST_STATE(new_state) || datacnt == 0);
1809286570Smav	ASSERT(old_state != arc_anon || datacnt <= 1);
1810168404Spjd
1811286570Smav	from_delta = to_delta = datacnt * hdr->b_size;
1812168404Spjd
1813168404Spjd	/*
1814168404Spjd	 * If this buffer is evictable, transfer it from the
1815168404Spjd	 * old state list to the new state list.
1816168404Spjd	 */
1817168404Spjd	if (refcnt == 0) {
1818286570Smav		if (old_state != arc_anon && old_state != arc_l2c_only) {
1819286570Smav			uint64_t *size = &old_state->arcs_lsize[buftype];
1820168404Spjd
1821286570Smav			ASSERT(HDR_HAS_L1HDR(hdr));
1822286763Smav			multilist_remove(&old_state->arcs_list[buftype], hdr);
1823168404Spjd
1824168404Spjd			/*
1825168404Spjd			 * If prefetching out of the ghost cache,
1826219089Spjd			 * we will have a non-zero datacnt.
1827168404Spjd			 */
1828286570Smav			if (GHOST_STATE(old_state) && datacnt == 0) {
1829168404Spjd				/* ghost elements have a ghost size */
1830286570Smav				ASSERT(hdr->b_l1hdr.b_buf == NULL);
1831275811Sdelphij				from_delta = hdr->b_size;
1832168404Spjd			}
1833185029Spjd			ASSERT3U(*size, >=, from_delta);
1834185029Spjd			atomic_add_64(size, -from_delta);
1835168404Spjd		}
1836286570Smav		if (new_state != arc_anon && new_state != arc_l2c_only) {
1837286570Smav			uint64_t *size = &new_state->arcs_lsize[buftype];
1838168404Spjd
1839286570Smav			/*
1840286570Smav			 * An L1 header always exists here, since if we're
1841286570Smav			 * moving to some L1-cached state (i.e. not l2c_only or
1842286570Smav			 * anonymous), we realloc the header to add an L1hdr
1843286570Smav			 * beforehand.
1844286570Smav			 */
1845286570Smav			ASSERT(HDR_HAS_L1HDR(hdr));
1846286763Smav			multilist_insert(&new_state->arcs_list[buftype], hdr);
1847168404Spjd
1848168404Spjd			/* ghost elements have a ghost size */
1849168404Spjd			if (GHOST_STATE(new_state)) {
1850286762Smav				ASSERT0(datacnt);
1851286570Smav				ASSERT(hdr->b_l1hdr.b_buf == NULL);
1852275811Sdelphij				to_delta = hdr->b_size;
1853168404Spjd			}
1854185029Spjd			atomic_add_64(size, to_delta);
1855168404Spjd		}
1856168404Spjd	}
1857168404Spjd
1858275811Sdelphij	ASSERT(!BUF_EMPTY(hdr));
1859275811Sdelphij	if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
1860275811Sdelphij		buf_hash_remove(hdr);
1861168404Spjd
1862286570Smav	/* adjust state sizes (ignore arc_l2c_only) */
1863286766Smav
1864286766Smav	if (to_delta && new_state != arc_l2c_only) {
1865286766Smav		ASSERT(HDR_HAS_L1HDR(hdr));
1866286766Smav		if (GHOST_STATE(new_state)) {
1867286766Smav			ASSERT0(datacnt);
1868286766Smav
1869286766Smav			/*
1870286766Smav			 * We moving a header to a ghost state, we first
1871286766Smav			 * remove all arc buffers. Thus, we'll have a
1872286766Smav			 * datacnt of zero, and no arc buffer to use for
1873286766Smav			 * the reference. As a result, we use the arc
1874286766Smav			 * header pointer for the reference.
1875286766Smav			 */
1876286766Smav			(void) refcount_add_many(&new_state->arcs_size,
1877286766Smav			    hdr->b_size, hdr);
1878286766Smav		} else {
1879286766Smav			ASSERT3U(datacnt, !=, 0);
1880286766Smav
1881286766Smav			/*
1882286766Smav			 * Each individual buffer holds a unique reference,
1883286766Smav			 * thus we must remove each of these references one
1884286766Smav			 * at a time.
1885286766Smav			 */
1886286766Smav			for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
1887286766Smav			    buf = buf->b_next) {
1888286766Smav				(void) refcount_add_many(&new_state->arcs_size,
1889286766Smav				    hdr->b_size, buf);
1890286766Smav			}
1891286766Smav		}
1892286766Smav	}
1893286766Smav
1894286570Smav	if (from_delta && old_state != arc_l2c_only) {
1895286766Smav		ASSERT(HDR_HAS_L1HDR(hdr));
1896286766Smav		if (GHOST_STATE(old_state)) {
1897286766Smav			/*
1898286766Smav			 * When moving a header off of a ghost state,
1899286766Smav			 * there's the possibility for datacnt to be
1900286766Smav			 * non-zero. This is because we first add the
1901286766Smav			 * arc buffer to the header prior to changing
1902286766Smav			 * the header's state. Since we used the header
1903286766Smav			 * for the reference when putting the header on
1904286766Smav			 * the ghost state, we must balance that and use
1905286766Smav			 * the header when removing off the ghost state
1906286766Smav			 * (even though datacnt is non zero).
1907286766Smav			 */
1908286766Smav
1909286766Smav			IMPLY(datacnt == 0, new_state == arc_anon ||
1910286766Smav			    new_state == arc_l2c_only);
1911286766Smav
1912286766Smav			(void) refcount_remove_many(&old_state->arcs_size,
1913286766Smav			    hdr->b_size, hdr);
1914286766Smav		} else {
1915286766Smav			ASSERT3P(datacnt, !=, 0);
1916286766Smav
1917286766Smav			/*
1918286766Smav			 * Each individual buffer holds a unique reference,
1919286766Smav			 * thus we must remove each of these references one
1920286766Smav			 * at a time.
1921286766Smav			 */
1922286766Smav			for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
1923286766Smav			    buf = buf->b_next) {
1924286766Smav				(void) refcount_remove_many(
1925286766Smav				    &old_state->arcs_size, hdr->b_size, buf);
1926286766Smav			}
1927286766Smav		}
1928168404Spjd	}
1929286766Smav
1930286570Smav	if (HDR_HAS_L1HDR(hdr))
1931286570Smav		hdr->b_l1hdr.b_state = new_state;
1932185029Spjd
1933286570Smav	/*
1934286570Smav	 * L2 headers should never be on the L2 state list since they don't
1935286570Smav	 * have L1 headers allocated.
1936286570Smav	 */
1937286763Smav	ASSERT(multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
1938286763Smav	    multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
1939168404Spjd}
1940168404Spjd
1941185029Spjdvoid
1942208373Smmarc_space_consume(uint64_t space, arc_space_type_t type)
1943185029Spjd{
1944208373Smm	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1945208373Smm
1946208373Smm	switch (type) {
1947208373Smm	case ARC_SPACE_DATA:
1948208373Smm		ARCSTAT_INCR(arcstat_data_size, space);
1949208373Smm		break;
1950286574Smav	case ARC_SPACE_META:
1951286574Smav		ARCSTAT_INCR(arcstat_metadata_size, space);
1952286574Smav		break;
1953208373Smm	case ARC_SPACE_OTHER:
1954208373Smm		ARCSTAT_INCR(arcstat_other_size, space);
1955208373Smm		break;
1956208373Smm	case ARC_SPACE_HDRS:
1957208373Smm		ARCSTAT_INCR(arcstat_hdr_size, space);
1958208373Smm		break;
1959208373Smm	case ARC_SPACE_L2HDRS:
1960208373Smm		ARCSTAT_INCR(arcstat_l2_hdr_size, space);
1961208373Smm		break;
1962208373Smm	}
1963208373Smm
1964286574Smav	if (type != ARC_SPACE_DATA)
1965286574Smav		ARCSTAT_INCR(arcstat_meta_used, space);
1966286574Smav
1967185029Spjd	atomic_add_64(&arc_size, space);
1968185029Spjd}
1969185029Spjd
1970185029Spjdvoid
1971208373Smmarc_space_return(uint64_t space, arc_space_type_t type)
1972185029Spjd{
1973208373Smm	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1974208373Smm
1975208373Smm	switch (type) {
1976208373Smm	case ARC_SPACE_DATA:
1977208373Smm		ARCSTAT_INCR(arcstat_data_size, -space);
1978208373Smm		break;
1979286574Smav	case ARC_SPACE_META:
1980286574Smav		ARCSTAT_INCR(arcstat_metadata_size, -space);
1981286574Smav		break;
1982208373Smm	case ARC_SPACE_OTHER:
1983208373Smm		ARCSTAT_INCR(arcstat_other_size, -space);
1984208373Smm		break;
1985208373Smm	case ARC_SPACE_HDRS:
1986208373Smm		ARCSTAT_INCR(arcstat_hdr_size, -space);
1987208373Smm		break;
1988208373Smm	case ARC_SPACE_L2HDRS:
1989208373Smm		ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
1990208373Smm		break;
1991208373Smm	}
1992208373Smm
1993286574Smav	if (type != ARC_SPACE_DATA) {
1994286574Smav		ASSERT(arc_meta_used >= space);
1995286574Smav		if (arc_meta_max < arc_meta_used)
1996286574Smav			arc_meta_max = arc_meta_used;
1997286574Smav		ARCSTAT_INCR(arcstat_meta_used, -space);
1998286574Smav	}
1999286574Smav
2000185029Spjd	ASSERT(arc_size >= space);
2001185029Spjd	atomic_add_64(&arc_size, -space);
2002185029Spjd}
2003185029Spjd
2004168404Spjdarc_buf_t *
2005286570Smavarc_buf_alloc(spa_t *spa, int32_t size, void *tag, arc_buf_contents_t type)
2006168404Spjd{
2007168404Spjd	arc_buf_hdr_t *hdr;
2008168404Spjd	arc_buf_t *buf;
2009168404Spjd
2010168404Spjd	ASSERT3U(size, >, 0);
2011286570Smav	hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
2012168404Spjd	ASSERT(BUF_EMPTY(hdr));
2013286570Smav	ASSERT3P(hdr->b_freeze_cksum, ==, NULL);
2014168404Spjd	hdr->b_size = size;
2015228103Smm	hdr->b_spa = spa_load_guid(spa);
2016286570Smav
2017185029Spjd	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2018168404Spjd	buf->b_hdr = hdr;
2019168404Spjd	buf->b_data = NULL;
2020168404Spjd	buf->b_efunc = NULL;
2021168404Spjd	buf->b_private = NULL;
2022168404Spjd	buf->b_next = NULL;
2023286570Smav
2024286570Smav	hdr->b_flags = arc_bufc_to_flags(type);
2025286570Smav	hdr->b_flags |= ARC_FLAG_HAS_L1HDR;
2026286570Smav
2027286570Smav	hdr->b_l1hdr.b_buf = buf;
2028286570Smav	hdr->b_l1hdr.b_state = arc_anon;
2029286570Smav	hdr->b_l1hdr.b_arc_access = 0;
2030286570Smav	hdr->b_l1hdr.b_datacnt = 1;
2031286763Smav	hdr->b_l1hdr.b_tmp_cdata = NULL;
2032286570Smav
2033168404Spjd	arc_get_data_buf(buf);
2034286570Smav	ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2035286570Smav	(void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2036168404Spjd
2037168404Spjd	return (buf);
2038168404Spjd}
2039168404Spjd
2040209962Smmstatic char *arc_onloan_tag = "onloan";
2041209962Smm
2042209962Smm/*
2043209962Smm * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
2044209962Smm * flight data by arc_tempreserve_space() until they are "returned". Loaned
2045209962Smm * buffers must be returned to the arc before they can be used by the DMU or
2046209962Smm * freed.
2047209962Smm */
2048209962Smmarc_buf_t *
2049209962Smmarc_loan_buf(spa_t *spa, int size)
2050209962Smm{
2051209962Smm	arc_buf_t *buf;
2052209962Smm
2053209962Smm	buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
2054209962Smm
2055209962Smm	atomic_add_64(&arc_loaned_bytes, size);
2056209962Smm	return (buf);
2057209962Smm}
2058209962Smm
2059209962Smm/*
2060209962Smm * Return a loaned arc buffer to the arc.
2061209962Smm */
2062209962Smmvoid
2063209962Smmarc_return_buf(arc_buf_t *buf, void *tag)
2064209962Smm{
2065209962Smm	arc_buf_hdr_t *hdr = buf->b_hdr;
2066209962Smm
2067209962Smm	ASSERT(buf->b_data != NULL);
2068286570Smav	ASSERT(HDR_HAS_L1HDR(hdr));
2069286570Smav	(void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2070286570Smav	(void) refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2071209962Smm
2072209962Smm	atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
2073209962Smm}
2074209962Smm
2075219089Spjd/* Detach an arc_buf from a dbuf (tag) */
2076219089Spjdvoid
2077219089Spjdarc_loan_inuse_buf(arc_buf_t *buf, void *tag)
2078219089Spjd{
2079286570Smav	arc_buf_hdr_t *hdr = buf->b_hdr;
2080219089Spjd
2081219089Spjd	ASSERT(buf->b_data != NULL);
2082286570Smav	ASSERT(HDR_HAS_L1HDR(hdr));
2083286570Smav	(void) refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2084286570Smav	(void) refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
2085219089Spjd	buf->b_efunc = NULL;
2086219089Spjd	buf->b_private = NULL;
2087219089Spjd
2088219089Spjd	atomic_add_64(&arc_loaned_bytes, hdr->b_size);
2089219089Spjd}
2090219089Spjd
2091168404Spjdstatic arc_buf_t *
2092168404Spjdarc_buf_clone(arc_buf_t *from)
2093168404Spjd{
2094168404Spjd	arc_buf_t *buf;
2095168404Spjd	arc_buf_hdr_t *hdr = from->b_hdr;
2096168404Spjd	uint64_t size = hdr->b_size;
2097168404Spjd
2098286570Smav	ASSERT(HDR_HAS_L1HDR(hdr));
2099286570Smav	ASSERT(hdr->b_l1hdr.b_state != arc_anon);
2100219089Spjd
2101185029Spjd	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2102168404Spjd	buf->b_hdr = hdr;
2103168404Spjd	buf->b_data = NULL;
2104168404Spjd	buf->b_efunc = NULL;
2105168404Spjd	buf->b_private = NULL;
2106286570Smav	buf->b_next = hdr->b_l1hdr.b_buf;
2107286570Smav	hdr->b_l1hdr.b_buf = buf;
2108168404Spjd	arc_get_data_buf(buf);
2109168404Spjd	bcopy(from->b_data, buf->b_data, size);
2110242845Sdelphij
2111242845Sdelphij	/*
2112242845Sdelphij	 * This buffer already exists in the arc so create a duplicate
2113242845Sdelphij	 * copy for the caller.  If the buffer is associated with user data
2114242845Sdelphij	 * then track the size and number of duplicates.  These stats will be
2115242845Sdelphij	 * updated as duplicate buffers are created and destroyed.
2116242845Sdelphij	 */
2117286570Smav	if (HDR_ISTYPE_DATA(hdr)) {
2118242845Sdelphij		ARCSTAT_BUMP(arcstat_duplicate_buffers);
2119242845Sdelphij		ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
2120242845Sdelphij	}
2121286570Smav	hdr->b_l1hdr.b_datacnt += 1;
2122168404Spjd	return (buf);
2123168404Spjd}
2124168404Spjd
2125168404Spjdvoid
2126168404Spjdarc_buf_add_ref(arc_buf_t *buf, void* tag)
2127168404Spjd{
2128168404Spjd	arc_buf_hdr_t *hdr;
2129168404Spjd	kmutex_t *hash_lock;
2130168404Spjd
2131168404Spjd	/*
2132185029Spjd	 * Check to see if this buffer is evicted.  Callers
2133185029Spjd	 * must verify b_data != NULL to know if the add_ref
2134185029Spjd	 * was successful.
2135168404Spjd	 */
2136219089Spjd	mutex_enter(&buf->b_evict_lock);
2137185029Spjd	if (buf->b_data == NULL) {
2138219089Spjd		mutex_exit(&buf->b_evict_lock);
2139168404Spjd		return;
2140168404Spjd	}
2141219089Spjd	hash_lock = HDR_LOCK(buf->b_hdr);
2142219089Spjd	mutex_enter(hash_lock);
2143185029Spjd	hdr = buf->b_hdr;
2144286570Smav	ASSERT(HDR_HAS_L1HDR(hdr));
2145219089Spjd	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2146219089Spjd	mutex_exit(&buf->b_evict_lock);
2147168404Spjd
2148286570Smav	ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
2149286570Smav	    hdr->b_l1hdr.b_state == arc_mfu);
2150286570Smav
2151168404Spjd	add_reference(hdr, hash_lock, tag);
2152208373Smm	DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
2153168404Spjd	arc_access(hdr, hash_lock);
2154168404Spjd	mutex_exit(hash_lock);
2155168404Spjd	ARCSTAT_BUMP(arcstat_hits);
2156286570Smav	ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
2157286570Smav	    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
2158168404Spjd	    data, metadata, hits);
2159168404Spjd}
2160168404Spjd
2161274172Savgstatic void
2162274172Savgarc_buf_free_on_write(void *data, size_t size,
2163274172Savg    void (*free_func)(void *, size_t))
2164274172Savg{
2165274172Savg	l2arc_data_free_t *df;
2166274172Savg
2167286763Smav	df = kmem_alloc(sizeof (*df), KM_SLEEP);
2168274172Savg	df->l2df_data = data;
2169274172Savg	df->l2df_size = size;
2170274172Savg	df->l2df_func = free_func;
2171274172Savg	mutex_enter(&l2arc_free_on_write_mtx);
2172274172Savg	list_insert_head(l2arc_free_on_write, df);
2173274172Savg	mutex_exit(&l2arc_free_on_write_mtx);
2174274172Savg}
2175274172Savg
2176185029Spjd/*
2177185029Spjd * Free the arc data buffer.  If it is an l2arc write in progress,
2178185029Spjd * the buffer is placed on l2arc_free_on_write to be freed later.
2179185029Spjd */
2180168404Spjdstatic void
2181240133Smmarc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
2182185029Spjd{
2183240133Smm	arc_buf_hdr_t *hdr = buf->b_hdr;
2184240133Smm
2185185029Spjd	if (HDR_L2_WRITING(hdr)) {
2186274172Savg		arc_buf_free_on_write(buf->b_data, hdr->b_size, free_func);
2187185029Spjd		ARCSTAT_BUMP(arcstat_l2_free_on_write);
2188185029Spjd	} else {
2189240133Smm		free_func(buf->b_data, hdr->b_size);
2190185029Spjd	}
2191185029Spjd}
2192185029Spjd
2193185029Spjdstatic void
2194274172Savgarc_buf_l2_cdata_free(arc_buf_hdr_t *hdr)
2195274172Savg{
2196286570Smav	ASSERT(HDR_HAS_L2HDR(hdr));
2197286570Smav	ASSERT(MUTEX_HELD(&hdr->b_l2hdr.b_dev->l2ad_mtx));
2198274172Savg
2199286570Smav	/*
2200286570Smav	 * The b_tmp_cdata field is linked off of the b_l1hdr, so if
2201286570Smav	 * that doesn't exist, the header is in the arc_l2c_only state,
2202286570Smav	 * and there isn't anything to free (it's already been freed).
2203286570Smav	 */
2204286570Smav	if (!HDR_HAS_L1HDR(hdr))
2205286570Smav		return;
2206274172Savg
2207286763Smav	/*
2208286763Smav	 * The header isn't being written to the l2arc device, thus it
2209286763Smav	 * shouldn't have a b_tmp_cdata to free.
2210286763Smav	 */
2211286763Smav	if (!HDR_L2_WRITING(hdr)) {
2212286763Smav		ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
2213274172Savg		return;
2214286763Smav	}
2215274172Savg
2216286763Smav	/*
2217286763Smav	 * The header does not have compression enabled. This can be due
2218286763Smav	 * to the buffer not being compressible, or because we're
2219286763Smav	 * freeing the buffer before the second phase of
2220286763Smav	 * l2arc_write_buffer() has started (which does the compression
2221286763Smav	 * step). In either case, b_tmp_cdata does not point to a
2222286763Smav	 * separately compressed buffer, so there's nothing to free (it
2223286763Smav	 * points to the same buffer as the arc_buf_t's b_data field).
2224286763Smav	 */
2225286763Smav	if (HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_OFF) {
2226286763Smav		hdr->b_l1hdr.b_tmp_cdata = NULL;
2227286763Smav		return;
2228286763Smav	}
2229286570Smav
2230286763Smav	/*
2231286763Smav	 * There's nothing to free since the buffer was all zero's and
2232286763Smav	 * compressed to a zero length buffer.
2233286763Smav	 */
2234286763Smav	if (HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_EMPTY) {
2235286763Smav		ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
2236286763Smav		return;
2237286763Smav	}
2238286763Smav
2239286763Smav	ASSERT(L2ARC_IS_VALID_COMPRESS(HDR_GET_COMPRESS(hdr)));
2240286763Smav
2241286763Smav	arc_buf_free_on_write(hdr->b_l1hdr.b_tmp_cdata,
2242286763Smav	    hdr->b_size, zio_data_buf_free);
2243286763Smav
2244274172Savg	ARCSTAT_BUMP(arcstat_l2_cdata_free_on_write);
2245286570Smav	hdr->b_l1hdr.b_tmp_cdata = NULL;
2246274172Savg}
2247274172Savg
2248286767Smav/*
2249286767Smav * Free up buf->b_data and if 'remove' is set, then pull the
2250286767Smav * arc_buf_t off of the the arc_buf_hdr_t's list and free it.
2251286767Smav */
2252274172Savgstatic void
2253286763Smavarc_buf_destroy(arc_buf_t *buf, boolean_t remove)
2254168404Spjd{
2255168404Spjd	arc_buf_t **bufp;
2256168404Spjd
2257168404Spjd	/* free up data associated with the buf */
2258286570Smav	if (buf->b_data != NULL) {
2259286570Smav		arc_state_t *state = buf->b_hdr->b_l1hdr.b_state;
2260168404Spjd		uint64_t size = buf->b_hdr->b_size;
2261286570Smav		arc_buf_contents_t type = arc_buf_type(buf->b_hdr);
2262168404Spjd
2263168404Spjd		arc_cksum_verify(buf);
2264240133Smm#ifdef illumos
2265240133Smm		arc_buf_unwatch(buf);
2266277300Ssmh#endif
2267219089Spjd
2268286763Smav		if (type == ARC_BUFC_METADATA) {
2269286763Smav			arc_buf_data_free(buf, zio_buf_free);
2270286763Smav			arc_space_return(size, ARC_SPACE_META);
2271286763Smav		} else {
2272286763Smav			ASSERT(type == ARC_BUFC_DATA);
2273286763Smav			arc_buf_data_free(buf, zio_data_buf_free);
2274286763Smav			arc_space_return(size, ARC_SPACE_DATA);
2275168404Spjd		}
2276286763Smav
2277286763Smav		/* protected by hash lock, if in the hash table */
2278286763Smav		if (multilist_link_active(&buf->b_hdr->b_l1hdr.b_arc_node)) {
2279185029Spjd			uint64_t *cnt = &state->arcs_lsize[type];
2280185029Spjd
2281286570Smav			ASSERT(refcount_is_zero(
2282286570Smav			    &buf->b_hdr->b_l1hdr.b_refcnt));
2283286570Smav			ASSERT(state != arc_anon && state != arc_l2c_only);
2284185029Spjd
2285185029Spjd			ASSERT3U(*cnt, >=, size);
2286185029Spjd			atomic_add_64(cnt, -size);
2287168404Spjd		}
2288286766Smav
2289286766Smav		(void) refcount_remove_many(&state->arcs_size, size, buf);
2290168404Spjd		buf->b_data = NULL;
2291242845Sdelphij
2292242845Sdelphij		/*
2293242845Sdelphij		 * If we're destroying a duplicate buffer make sure
2294242845Sdelphij		 * that the appropriate statistics are updated.
2295242845Sdelphij		 */
2296286570Smav		if (buf->b_hdr->b_l1hdr.b_datacnt > 1 &&
2297286570Smav		    HDR_ISTYPE_DATA(buf->b_hdr)) {
2298242845Sdelphij			ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
2299242845Sdelphij			ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
2300242845Sdelphij		}
2301286570Smav		ASSERT(buf->b_hdr->b_l1hdr.b_datacnt > 0);
2302286570Smav		buf->b_hdr->b_l1hdr.b_datacnt -= 1;
2303168404Spjd	}
2304168404Spjd
2305168404Spjd	/* only remove the buf if requested */
2306268858Sdelphij	if (!remove)
2307168404Spjd		return;
2308168404Spjd
2309168404Spjd	/* remove the buf from the hdr list */
2310286570Smav	for (bufp = &buf->b_hdr->b_l1hdr.b_buf; *bufp != buf;
2311286570Smav	    bufp = &(*bufp)->b_next)
2312168404Spjd		continue;
2313168404Spjd	*bufp = buf->b_next;
2314219089Spjd	buf->b_next = NULL;
2315168404Spjd
2316168404Spjd	ASSERT(buf->b_efunc == NULL);
2317168404Spjd
2318168404Spjd	/* clean up the buf */
2319168404Spjd	buf->b_hdr = NULL;
2320168404Spjd	kmem_cache_free(buf_cache, buf);
2321168404Spjd}
2322168404Spjd
2323168404Spjdstatic void
2324286598Smavarc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
2325286598Smav{
2326286598Smav	l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
2327286598Smav	l2arc_dev_t *dev = l2hdr->b_dev;
2328286598Smav
2329286598Smav	ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
2330286598Smav	ASSERT(HDR_HAS_L2HDR(hdr));
2331286598Smav
2332286598Smav	list_remove(&dev->l2ad_buflist, hdr);
2333286598Smav
2334286598Smav	/*
2335286598Smav	 * We don't want to leak the b_tmp_cdata buffer that was
2336286598Smav	 * allocated in l2arc_write_buffers()
2337286598Smav	 */
2338286598Smav	arc_buf_l2_cdata_free(hdr);
2339286598Smav
2340286598Smav	/*
2341286598Smav	 * If the l2hdr's b_daddr is equal to L2ARC_ADDR_UNSET, then
2342286598Smav	 * this header is being processed by l2arc_write_buffers() (i.e.
2343286598Smav	 * it's in the first stage of l2arc_write_buffers()).
2344286598Smav	 * Re-affirming that truth here, just to serve as a reminder. If
2345286598Smav	 * b_daddr does not equal L2ARC_ADDR_UNSET, then the header may or
2346286598Smav	 * may not have its HDR_L2_WRITING flag set. (the write may have
2347286598Smav	 * completed, in which case HDR_L2_WRITING will be false and the
2348286598Smav	 * b_daddr field will point to the address of the buffer on disk).
2349286598Smav	 */
2350286598Smav	IMPLY(l2hdr->b_daddr == L2ARC_ADDR_UNSET, HDR_L2_WRITING(hdr));
2351286598Smav
2352286598Smav	/*
2353286598Smav	 * If b_daddr is equal to L2ARC_ADDR_UNSET, we're racing with
2354286598Smav	 * l2arc_write_buffers(). Since we've just removed this header
2355286598Smav	 * from the l2arc buffer list, this header will never reach the
2356286598Smav	 * second stage of l2arc_write_buffers(), which increments the
2357286598Smav	 * accounting stats for this header. Thus, we must be careful
2358286598Smav	 * not to decrement them for this header either.
2359286598Smav	 */
2360286598Smav	if (l2hdr->b_daddr != L2ARC_ADDR_UNSET) {
2361286598Smav		ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
2362286598Smav		ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
2363286598Smav
2364286598Smav		vdev_space_update(dev->l2ad_vdev,
2365286598Smav		    -l2hdr->b_asize, 0, 0);
2366286598Smav
2367286598Smav		(void) refcount_remove_many(&dev->l2ad_alloc,
2368286598Smav		    l2hdr->b_asize, hdr);
2369286598Smav	}
2370286598Smav
2371286598Smav	hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
2372286598Smav}
2373286598Smav
2374286598Smavstatic void
2375168404Spjdarc_hdr_destroy(arc_buf_hdr_t *hdr)
2376168404Spjd{
2377286570Smav	if (HDR_HAS_L1HDR(hdr)) {
2378286570Smav		ASSERT(hdr->b_l1hdr.b_buf == NULL ||
2379286570Smav		    hdr->b_l1hdr.b_datacnt > 0);
2380286570Smav		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2381286570Smav		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
2382286570Smav	}
2383168404Spjd	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2384286570Smav	ASSERT(!HDR_IN_HASH_TABLE(hdr));
2385168404Spjd
2386286570Smav	if (HDR_HAS_L2HDR(hdr)) {
2387286598Smav		l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
2388286598Smav		boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
2389286570Smav
2390286598Smav		if (!buflist_held)
2391286598Smav			mutex_enter(&dev->l2ad_mtx);
2392219089Spjd
2393286570Smav		/*
2394286598Smav		 * Even though we checked this conditional above, we
2395286598Smav		 * need to check this again now that we have the
2396286598Smav		 * l2ad_mtx. This is because we could be racing with
2397286598Smav		 * another thread calling l2arc_evict() which might have
2398286598Smav		 * destroyed this header's L2 portion as we were waiting
2399286598Smav		 * to acquire the l2ad_mtx. If that happens, we don't
2400286598Smav		 * want to re-destroy the header's L2 portion.
2401286570Smav		 */
2402286598Smav		if (HDR_HAS_L2HDR(hdr)) {
2403286647Smav			if (hdr->b_l2hdr.b_daddr != L2ARC_ADDR_UNSET)
2404286647Smav				trim_map_free(dev->l2ad_vdev,
2405286647Smav				    hdr->b_l2hdr.b_daddr,
2406286647Smav				    hdr->b_l2hdr.b_asize, 0);
2407286598Smav			arc_hdr_l2hdr_destroy(hdr);
2408286598Smav		}
2409286570Smav
2410219089Spjd		if (!buflist_held)
2411286598Smav			mutex_exit(&dev->l2ad_mtx);
2412185029Spjd	}
2413185029Spjd
2414286570Smav	if (!BUF_EMPTY(hdr))
2415219089Spjd		buf_discard_identity(hdr);
2416168404Spjd	if (hdr->b_freeze_cksum != NULL) {
2417168404Spjd		kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
2418168404Spjd		hdr->b_freeze_cksum = NULL;
2419168404Spjd	}
2420286570Smav
2421286570Smav	if (HDR_HAS_L1HDR(hdr)) {
2422286570Smav		while (hdr->b_l1hdr.b_buf) {
2423286570Smav			arc_buf_t *buf = hdr->b_l1hdr.b_buf;
2424286570Smav
2425286570Smav			if (buf->b_efunc != NULL) {
2426286763Smav				mutex_enter(&arc_user_evicts_lock);
2427286570Smav				mutex_enter(&buf->b_evict_lock);
2428286570Smav				ASSERT(buf->b_hdr != NULL);
2429286763Smav				arc_buf_destroy(hdr->b_l1hdr.b_buf, FALSE);
2430286570Smav				hdr->b_l1hdr.b_buf = buf->b_next;
2431286570Smav				buf->b_hdr = &arc_eviction_hdr;
2432286570Smav				buf->b_next = arc_eviction_list;
2433286570Smav				arc_eviction_list = buf;
2434286570Smav				mutex_exit(&buf->b_evict_lock);
2435286763Smav				cv_signal(&arc_user_evicts_cv);
2436286763Smav				mutex_exit(&arc_user_evicts_lock);
2437286570Smav			} else {
2438286763Smav				arc_buf_destroy(hdr->b_l1hdr.b_buf, TRUE);
2439286570Smav			}
2440286570Smav		}
2441286570Smav#ifdef ZFS_DEBUG
2442286570Smav		if (hdr->b_l1hdr.b_thawed != NULL) {
2443286570Smav			kmem_free(hdr->b_l1hdr.b_thawed, 1);
2444286570Smav			hdr->b_l1hdr.b_thawed = NULL;
2445286570Smav		}
2446286570Smav#endif
2447219089Spjd	}
2448168404Spjd
2449168404Spjd	ASSERT3P(hdr->b_hash_next, ==, NULL);
2450286570Smav	if (HDR_HAS_L1HDR(hdr)) {
2451286763Smav		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
2452286570Smav		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
2453286570Smav		kmem_cache_free(hdr_full_cache, hdr);
2454286570Smav	} else {
2455286570Smav		kmem_cache_free(hdr_l2only_cache, hdr);
2456286570Smav	}
2457168404Spjd}
2458168404Spjd
2459168404Spjdvoid
2460168404Spjdarc_buf_free(arc_buf_t *buf, void *tag)
2461168404Spjd{
2462168404Spjd	arc_buf_hdr_t *hdr = buf->b_hdr;
2463286570Smav	int hashed = hdr->b_l1hdr.b_state != arc_anon;
2464168404Spjd
2465168404Spjd	ASSERT(buf->b_efunc == NULL);
2466168404Spjd	ASSERT(buf->b_data != NULL);
2467168404Spjd
2468168404Spjd	if (hashed) {
2469168404Spjd		kmutex_t *hash_lock = HDR_LOCK(hdr);
2470168404Spjd
2471168404Spjd		mutex_enter(hash_lock);
2472219089Spjd		hdr = buf->b_hdr;
2473219089Spjd		ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2474219089Spjd
2475168404Spjd		(void) remove_reference(hdr, hash_lock, tag);
2476286570Smav		if (hdr->b_l1hdr.b_datacnt > 1) {
2477286763Smav			arc_buf_destroy(buf, TRUE);
2478219089Spjd		} else {
2479286570Smav			ASSERT(buf == hdr->b_l1hdr.b_buf);
2480219089Spjd			ASSERT(buf->b_efunc == NULL);
2481275811Sdelphij			hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
2482219089Spjd		}
2483168404Spjd		mutex_exit(hash_lock);
2484168404Spjd	} else if (HDR_IO_IN_PROGRESS(hdr)) {
2485168404Spjd		int destroy_hdr;
2486168404Spjd		/*
2487168404Spjd		 * We are in the middle of an async write.  Don't destroy
2488168404Spjd		 * this buffer unless the write completes before we finish
2489168404Spjd		 * decrementing the reference count.
2490168404Spjd		 */
2491286763Smav		mutex_enter(&arc_user_evicts_lock);
2492168404Spjd		(void) remove_reference(hdr, NULL, tag);
2493286570Smav		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2494168404Spjd		destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
2495286763Smav		mutex_exit(&arc_user_evicts_lock);
2496168404Spjd		if (destroy_hdr)
2497168404Spjd			arc_hdr_destroy(hdr);
2498168404Spjd	} else {
2499219089Spjd		if (remove_reference(hdr, NULL, tag) > 0)
2500286763Smav			arc_buf_destroy(buf, TRUE);
2501219089Spjd		else
2502168404Spjd			arc_hdr_destroy(hdr);
2503168404Spjd	}
2504168404Spjd}
2505168404Spjd
2506248571Smmboolean_t
2507168404Spjdarc_buf_remove_ref(arc_buf_t *buf, void* tag)
2508168404Spjd{
2509168404Spjd	arc_buf_hdr_t *hdr = buf->b_hdr;
2510168404Spjd	kmutex_t *hash_lock = HDR_LOCK(hdr);
2511248571Smm	boolean_t no_callback = (buf->b_efunc == NULL);
2512168404Spjd
2513286570Smav	if (hdr->b_l1hdr.b_state == arc_anon) {
2514286570Smav		ASSERT(hdr->b_l1hdr.b_datacnt == 1);
2515168404Spjd		arc_buf_free(buf, tag);
2516168404Spjd		return (no_callback);
2517168404Spjd	}
2518168404Spjd
2519168404Spjd	mutex_enter(hash_lock);
2520219089Spjd	hdr = buf->b_hdr;
2521286570Smav	ASSERT(hdr->b_l1hdr.b_datacnt > 0);
2522219089Spjd	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2523286570Smav	ASSERT(hdr->b_l1hdr.b_state != arc_anon);
2524168404Spjd	ASSERT(buf->b_data != NULL);
2525168404Spjd
2526168404Spjd	(void) remove_reference(hdr, hash_lock, tag);
2527286570Smav	if (hdr->b_l1hdr.b_datacnt > 1) {
2528168404Spjd		if (no_callback)
2529286763Smav			arc_buf_destroy(buf, TRUE);
2530168404Spjd	} else if (no_callback) {
2531286570Smav		ASSERT(hdr->b_l1hdr.b_buf == buf && buf->b_next == NULL);
2532219089Spjd		ASSERT(buf->b_efunc == NULL);
2533275811Sdelphij		hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
2534168404Spjd	}
2535286570Smav	ASSERT(no_callback || hdr->b_l1hdr.b_datacnt > 1 ||
2536286570Smav	    refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2537168404Spjd	mutex_exit(hash_lock);
2538168404Spjd	return (no_callback);
2539168404Spjd}
2540168404Spjd
2541286570Smavint32_t
2542168404Spjdarc_buf_size(arc_buf_t *buf)
2543168404Spjd{
2544168404Spjd	return (buf->b_hdr->b_size);
2545168404Spjd}
2546168404Spjd
2547168404Spjd/*
2548242845Sdelphij * Called from the DMU to determine if the current buffer should be
2549242845Sdelphij * evicted. In order to ensure proper locking, the eviction must be initiated
2550242845Sdelphij * from the DMU. Return true if the buffer is associated with user data and
2551242845Sdelphij * duplicate buffers still exist.
2552242845Sdelphij */
2553242845Sdelphijboolean_t
2554242845Sdelphijarc_buf_eviction_needed(arc_buf_t *buf)
2555242845Sdelphij{
2556242845Sdelphij	arc_buf_hdr_t *hdr;
2557242845Sdelphij	boolean_t evict_needed = B_FALSE;
2558242845Sdelphij
2559242845Sdelphij	if (zfs_disable_dup_eviction)
2560242845Sdelphij		return (B_FALSE);
2561242845Sdelphij
2562242845Sdelphij	mutex_enter(&buf->b_evict_lock);
2563242845Sdelphij	hdr = buf->b_hdr;
2564242845Sdelphij	if (hdr == NULL) {
2565242845Sdelphij		/*
2566242845Sdelphij		 * We are in arc_do_user_evicts(); let that function
2567242845Sdelphij		 * perform the eviction.
2568242845Sdelphij		 */
2569242845Sdelphij		ASSERT(buf->b_data == NULL);
2570242845Sdelphij		mutex_exit(&buf->b_evict_lock);
2571242845Sdelphij		return (B_FALSE);
2572242845Sdelphij	} else if (buf->b_data == NULL) {
2573242845Sdelphij		/*
2574242845Sdelphij		 * We have already been added to the arc eviction list;
2575242845Sdelphij		 * recommend eviction.
2576242845Sdelphij		 */
2577242845Sdelphij		ASSERT3P(hdr, ==, &arc_eviction_hdr);
2578242845Sdelphij		mutex_exit(&buf->b_evict_lock);
2579242845Sdelphij		return (B_TRUE);
2580242845Sdelphij	}
2581242845Sdelphij
2582286570Smav	if (hdr->b_l1hdr.b_datacnt > 1 && HDR_ISTYPE_DATA(hdr))
2583242845Sdelphij		evict_needed = B_TRUE;
2584242845Sdelphij
2585242845Sdelphij	mutex_exit(&buf->b_evict_lock);
2586242845Sdelphij	return (evict_needed);
2587242845Sdelphij}
2588242845Sdelphij
2589242845Sdelphij/*
2590286763Smav * Evict the arc_buf_hdr that is provided as a parameter. The resultant
2591286763Smav * state of the header is dependent on it's state prior to entering this
2592286763Smav * function. The following transitions are possible:
2593185029Spjd *
2594286763Smav *    - arc_mru -> arc_mru_ghost
2595286763Smav *    - arc_mfu -> arc_mfu_ghost
2596286763Smav *    - arc_mru_ghost -> arc_l2c_only
2597286763Smav *    - arc_mru_ghost -> deleted
2598286763Smav *    - arc_mfu_ghost -> arc_l2c_only
2599286763Smav *    - arc_mfu_ghost -> deleted
2600168404Spjd */
2601286763Smavstatic int64_t
2602286763Smavarc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
2603168404Spjd{
2604286763Smav	arc_state_t *evicted_state, *state;
2605286763Smav	int64_t bytes_evicted = 0;
2606168404Spjd
2607286763Smav	ASSERT(MUTEX_HELD(hash_lock));
2608286763Smav	ASSERT(HDR_HAS_L1HDR(hdr));
2609168404Spjd
2610286763Smav	state = hdr->b_l1hdr.b_state;
2611286763Smav	if (GHOST_STATE(state)) {
2612286763Smav		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2613286763Smav		ASSERT(hdr->b_l1hdr.b_buf == NULL);
2614206796Spjd
2615286763Smav		/*
2616286763Smav		 * l2arc_write_buffers() relies on a header's L1 portion
2617286763Smav		 * (i.e. it's b_tmp_cdata field) during it's write phase.
2618286763Smav		 * Thus, we cannot push a header onto the arc_l2c_only
2619286763Smav		 * state (removing it's L1 piece) until the header is
2620286763Smav		 * done being written to the l2arc.
2621286763Smav		 */
2622286763Smav		if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
2623286763Smav			ARCSTAT_BUMP(arcstat_evict_l2_skip);
2624286763Smav			return (bytes_evicted);
2625286763Smav		}
2626286762Smav
2627286763Smav		ARCSTAT_BUMP(arcstat_deleted);
2628286763Smav		bytes_evicted += hdr->b_size;
2629286762Smav
2630286763Smav		DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
2631286763Smav
2632286763Smav		if (HDR_HAS_L2HDR(hdr)) {
2633275780Sdelphij			/*
2634286763Smav			 * This buffer is cached on the 2nd Level ARC;
2635286763Smav			 * don't destroy the header.
2636275780Sdelphij			 */
2637286763Smav			arc_change_state(arc_l2c_only, hdr, hash_lock);
2638286763Smav			/*
2639286763Smav			 * dropping from L1+L2 cached to L2-only,
2640286763Smav			 * realloc to remove the L1 header.
2641286763Smav			 */
2642286763Smav			hdr = arc_hdr_realloc(hdr, hdr_full_cache,
2643286763Smav			    hdr_l2only_cache);
2644286763Smav		} else {
2645286763Smav			arc_change_state(arc_anon, hdr, hash_lock);
2646286763Smav			arc_hdr_destroy(hdr);
2647275780Sdelphij		}
2648286763Smav		return (bytes_evicted);
2649275780Sdelphij	}
2650275780Sdelphij
2651286763Smav	ASSERT(state == arc_mru || state == arc_mfu);
2652286763Smav	evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
2653206796Spjd
2654286763Smav	/* prefetch buffers have a minimum lifespan */
2655286763Smav	if (HDR_IO_IN_PROGRESS(hdr) ||
2656286763Smav	    ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
2657286763Smav	    ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
2658286763Smav	    arc_min_prefetch_lifespan)) {
2659286763Smav		ARCSTAT_BUMP(arcstat_evict_skip);
2660286763Smav		return (bytes_evicted);
2661286763Smav	}
2662286763Smav
2663286763Smav	ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
2664286763Smav	ASSERT3U(hdr->b_l1hdr.b_datacnt, >, 0);
2665286763Smav	while (hdr->b_l1hdr.b_buf) {
2666286763Smav		arc_buf_t *buf = hdr->b_l1hdr.b_buf;
2667286763Smav		if (!mutex_tryenter(&buf->b_evict_lock)) {
2668286763Smav			ARCSTAT_BUMP(arcstat_mutex_miss);
2669286763Smav			break;
2670168404Spjd		}
2671286763Smav		if (buf->b_data != NULL)
2672286763Smav			bytes_evicted += hdr->b_size;
2673286763Smav		if (buf->b_efunc != NULL) {
2674286763Smav			mutex_enter(&arc_user_evicts_lock);
2675286763Smav			arc_buf_destroy(buf, FALSE);
2676286763Smav			hdr->b_l1hdr.b_buf = buf->b_next;
2677286763Smav			buf->b_hdr = &arc_eviction_hdr;
2678286763Smav			buf->b_next = arc_eviction_list;
2679286763Smav			arc_eviction_list = buf;
2680286763Smav			cv_signal(&arc_user_evicts_cv);
2681286763Smav			mutex_exit(&arc_user_evicts_lock);
2682286763Smav			mutex_exit(&buf->b_evict_lock);
2683286763Smav		} else {
2684286763Smav			mutex_exit(&buf->b_evict_lock);
2685286763Smav			arc_buf_destroy(buf, TRUE);
2686286763Smav		}
2687286763Smav	}
2688258632Savg
2689286763Smav	if (HDR_HAS_L2HDR(hdr)) {
2690286763Smav		ARCSTAT_INCR(arcstat_evict_l2_cached, hdr->b_size);
2691286763Smav	} else {
2692286763Smav		if (l2arc_write_eligible(hdr->b_spa, hdr))
2693286763Smav			ARCSTAT_INCR(arcstat_evict_l2_eligible, hdr->b_size);
2694286763Smav		else
2695286763Smav			ARCSTAT_INCR(arcstat_evict_l2_ineligible, hdr->b_size);
2696286763Smav	}
2697258632Savg
2698286763Smav	if (hdr->b_l1hdr.b_datacnt == 0) {
2699286763Smav		arc_change_state(evicted_state, hdr, hash_lock);
2700286763Smav		ASSERT(HDR_IN_HASH_TABLE(hdr));
2701286763Smav		hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
2702286763Smav		hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
2703286763Smav		DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
2704286763Smav	}
2705286763Smav
2706286763Smav	return (bytes_evicted);
2707286763Smav}
2708286763Smav
2709286763Smavstatic uint64_t
2710286763Smavarc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
2711286763Smav    uint64_t spa, int64_t bytes)
2712286763Smav{
2713286763Smav	multilist_sublist_t *mls;
2714286763Smav	uint64_t bytes_evicted = 0;
2715286763Smav	arc_buf_hdr_t *hdr;
2716286763Smav	kmutex_t *hash_lock;
2717286763Smav	int evict_count = 0;
2718286763Smav
2719286763Smav	ASSERT3P(marker, !=, NULL);
2720286763Smav	IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
2721286763Smav
2722286763Smav	mls = multilist_sublist_lock(ml, idx);
2723286763Smav
2724286763Smav	for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
2725286763Smav	    hdr = multilist_sublist_prev(mls, marker)) {
2726286763Smav		if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
2727286763Smav		    (evict_count >= zfs_arc_evict_batch_limit))
2728286763Smav			break;
2729286763Smav
2730258632Savg		/*
2731286763Smav		 * To keep our iteration location, move the marker
2732286763Smav		 * forward. Since we're not holding hdr's hash lock, we
2733286763Smav		 * must be very careful and not remove 'hdr' from the
2734286763Smav		 * sublist. Otherwise, other consumers might mistake the
2735286763Smav		 * 'hdr' as not being on a sublist when they call the
2736286763Smav		 * multilist_link_active() function (they all rely on
2737286763Smav		 * the hash lock protecting concurrent insertions and
2738286763Smav		 * removals). multilist_sublist_move_forward() was
2739286763Smav		 * specifically implemented to ensure this is the case
2740286763Smav		 * (only 'marker' will be removed and re-inserted).
2741258632Savg		 */
2742286763Smav		multilist_sublist_move_forward(mls, marker);
2743286763Smav
2744286763Smav		/*
2745286763Smav		 * The only case where the b_spa field should ever be
2746286763Smav		 * zero, is the marker headers inserted by
2747286763Smav		 * arc_evict_state(). It's possible for multiple threads
2748286763Smav		 * to be calling arc_evict_state() concurrently (e.g.
2749286763Smav		 * dsl_pool_close() and zio_inject_fault()), so we must
2750286763Smav		 * skip any markers we see from these other threads.
2751286763Smav		 */
2752286763Smav		if (hdr->b_spa == 0)
2753258632Savg			continue;
2754286763Smav
2755286763Smav		/* we're only interested in evicting buffers of a certain spa */
2756286763Smav		if (spa != 0 && hdr->b_spa != spa) {
2757286763Smav			ARCSTAT_BUMP(arcstat_evict_skip);
2758286763Smav			continue;
2759258632Savg		}
2760258632Savg
2761275811Sdelphij		hash_lock = HDR_LOCK(hdr);
2762208373Smm
2763286763Smav		/*
2764286763Smav		 * We aren't calling this function from any code path
2765286763Smav		 * that would already be holding a hash lock, so we're
2766286763Smav		 * asserting on this assumption to be defensive in case
2767286763Smav		 * this ever changes. Without this check, it would be
2768286763Smav		 * possible to incorrectly increment arcstat_mutex_miss
2769286763Smav		 * below (e.g. if the code changed such that we called
2770286763Smav		 * this function with a hash lock held).
2771286763Smav		 */
2772286763Smav		ASSERT(!MUTEX_HELD(hash_lock));
2773208373Smm
2774286763Smav		if (mutex_tryenter(hash_lock)) {
2775286763Smav			uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
2776286763Smav			mutex_exit(hash_lock);
2777286763Smav
2778286763Smav			bytes_evicted += evicted;
2779286763Smav
2780286763Smav			/*
2781286763Smav			 * If evicted is zero, arc_evict_hdr() must have
2782286763Smav			 * decided to skip this header, don't increment
2783286763Smav			 * evict_count in this case.
2784286763Smav			 */
2785286763Smav			if (evicted != 0)
2786286763Smav				evict_count++;
2787286763Smav
2788286763Smav			/*
2789286763Smav			 * If arc_size isn't overflowing, signal any
2790286763Smav			 * threads that might happen to be waiting.
2791286763Smav			 *
2792286763Smav			 * For each header evicted, we wake up a single
2793286763Smav			 * thread. If we used cv_broadcast, we could
2794286763Smav			 * wake up "too many" threads causing arc_size
2795286763Smav			 * to significantly overflow arc_c; since
2796286763Smav			 * arc_get_data_buf() doesn't check for overflow
2797286763Smav			 * when it's woken up (it doesn't because it's
2798286763Smav			 * possible for the ARC to be overflowing while
2799286763Smav			 * full of un-evictable buffers, and the
2800286763Smav			 * function should proceed in this case).
2801286763Smav			 *
2802286763Smav			 * If threads are left sleeping, due to not
2803286763Smav			 * using cv_broadcast, they will be woken up
2804286763Smav			 * just before arc_reclaim_thread() sleeps.
2805286763Smav			 */
2806286763Smav			mutex_enter(&arc_reclaim_lock);
2807286763Smav			if (!arc_is_overflowing())
2808286763Smav				cv_signal(&arc_reclaim_waiters_cv);
2809286763Smav			mutex_exit(&arc_reclaim_lock);
2810168404Spjd		} else {
2811286763Smav			ARCSTAT_BUMP(arcstat_mutex_miss);
2812168404Spjd		}
2813168404Spjd	}
2814168404Spjd
2815286763Smav	multilist_sublist_unlock(mls);
2816206796Spjd
2817286763Smav	return (bytes_evicted);
2818286763Smav}
2819168404Spjd
2820286763Smav/*
2821286763Smav * Evict buffers from the given arc state, until we've removed the
2822286763Smav * specified number of bytes. Move the removed buffers to the
2823286763Smav * appropriate evict state.
2824286763Smav *
2825286763Smav * This function makes a "best effort". It skips over any buffers
2826286763Smav * it can't get a hash_lock on, and so, may not catch all candidates.
2827286763Smav * It may also return without evicting as much space as requested.
2828286763Smav *
2829286763Smav * If bytes is specified using the special value ARC_EVICT_ALL, this
2830286763Smav * will evict all available (i.e. unlocked and evictable) buffers from
2831286763Smav * the given arc state; which is used by arc_flush().
2832286763Smav */
2833286763Smavstatic uint64_t
2834286763Smavarc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
2835286763Smav    arc_buf_contents_t type)
2836286763Smav{
2837286763Smav	uint64_t total_evicted = 0;
2838286763Smav	multilist_t *ml = &state->arcs_list[type];
2839286763Smav	int num_sublists;
2840286763Smav	arc_buf_hdr_t **markers;
2841168404Spjd
2842286763Smav	IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
2843168404Spjd
2844286763Smav	num_sublists = multilist_get_num_sublists(ml);
2845286763Smav
2846185029Spjd	/*
2847286763Smav	 * If we've tried to evict from each sublist, made some
2848286763Smav	 * progress, but still have not hit the target number of bytes
2849286763Smav	 * to evict, we want to keep trying. The markers allow us to
2850286763Smav	 * pick up where we left off for each individual sublist, rather
2851286763Smav	 * than starting from the tail each time.
2852185029Spjd	 */
2853286763Smav	markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
2854286763Smav	for (int i = 0; i < num_sublists; i++) {
2855286763Smav		markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
2856185029Spjd
2857286763Smav		/*
2858286763Smav		 * A b_spa of 0 is used to indicate that this header is
2859286763Smav		 * a marker. This fact is used in arc_adjust_type() and
2860286763Smav		 * arc_evict_state_impl().
2861286763Smav		 */
2862286763Smav		markers[i]->b_spa = 0;
2863168404Spjd
2864286763Smav		multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
2865286763Smav		multilist_sublist_insert_tail(mls, markers[i]);
2866286763Smav		multilist_sublist_unlock(mls);
2867286763Smav	}
2868168404Spjd
2869286763Smav	/*
2870286763Smav	 * While we haven't hit our target number of bytes to evict, or
2871286763Smav	 * we're evicting all available buffers.
2872286763Smav	 */
2873286763Smav	while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
2874286763Smav		/*
2875286763Smav		 * Start eviction using a randomly selected sublist,
2876286763Smav		 * this is to try and evenly balance eviction across all
2877286763Smav		 * sublists. Always starting at the same sublist
2878286763Smav		 * (e.g. index 0) would cause evictions to favor certain
2879286763Smav		 * sublists over others.
2880286763Smav		 */
2881286763Smav		int sublist_idx = multilist_get_random_index(ml);
2882286763Smav		uint64_t scan_evicted = 0;
2883219089Spjd
2884286763Smav		for (int i = 0; i < num_sublists; i++) {
2885286763Smav			uint64_t bytes_remaining;
2886286763Smav			uint64_t bytes_evicted;
2887219089Spjd
2888286763Smav			if (bytes == ARC_EVICT_ALL)
2889286763Smav				bytes_remaining = ARC_EVICT_ALL;
2890286763Smav			else if (total_evicted < bytes)
2891286763Smav				bytes_remaining = bytes - total_evicted;
2892286763Smav			else
2893286763Smav				break;
2894258632Savg
2895286763Smav			bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
2896286763Smav			    markers[sublist_idx], spa, bytes_remaining);
2897286763Smav
2898286763Smav			scan_evicted += bytes_evicted;
2899286763Smav			total_evicted += bytes_evicted;
2900286763Smav
2901286763Smav			/* we've reached the end, wrap to the beginning */
2902286763Smav			if (++sublist_idx >= num_sublists)
2903286763Smav				sublist_idx = 0;
2904286763Smav		}
2905286763Smav
2906258632Savg		/*
2907286763Smav		 * If we didn't evict anything during this scan, we have
2908286763Smav		 * no reason to believe we'll evict more during another
2909286763Smav		 * scan, so break the loop.
2910258632Savg		 */
2911286763Smav		if (scan_evicted == 0) {
2912286763Smav			/* This isn't possible, let's make that obvious */
2913286763Smav			ASSERT3S(bytes, !=, 0);
2914185029Spjd
2915286763Smav			/*
2916286763Smav			 * When bytes is ARC_EVICT_ALL, the only way to
2917286763Smav			 * break the loop is when scan_evicted is zero.
2918286763Smav			 * In that case, we actually have evicted enough,
2919286763Smav			 * so we don't want to increment the kstat.
2920286763Smav			 */
2921286763Smav			if (bytes != ARC_EVICT_ALL) {
2922286763Smav				ASSERT3S(total_evicted, <, bytes);
2923286763Smav				ARCSTAT_BUMP(arcstat_evict_not_enough);
2924185029Spjd			}
2925185029Spjd
2926286763Smav			break;
2927258632Savg		}
2928286763Smav	}
2929258632Savg
2930286763Smav	for (int i = 0; i < num_sublists; i++) {
2931286763Smav		multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
2932286763Smav		multilist_sublist_remove(mls, markers[i]);
2933286763Smav		multilist_sublist_unlock(mls);
2934286763Smav
2935286763Smav		kmem_cache_free(hdr_full_cache, markers[i]);
2936168404Spjd	}
2937286763Smav	kmem_free(markers, sizeof (*markers) * num_sublists);
2938206796Spjd
2939286763Smav	return (total_evicted);
2940286763Smav}
2941286763Smav
2942286763Smav/*
2943286763Smav * Flush all "evictable" data of the given type from the arc state
2944286763Smav * specified. This will not evict any "active" buffers (i.e. referenced).
2945286763Smav *
2946286763Smav * When 'retry' is set to FALSE, the function will make a single pass
2947286763Smav * over the state and evict any buffers that it can. Since it doesn't
2948286763Smav * continually retry the eviction, it might end up leaving some buffers
2949286763Smav * in the ARC due to lock misses.
2950286763Smav *
2951286763Smav * When 'retry' is set to TRUE, the function will continually retry the
2952286763Smav * eviction until *all* evictable buffers have been removed from the
2953286763Smav * state. As a result, if concurrent insertions into the state are
2954286763Smav * allowed (e.g. if the ARC isn't shutting down), this function might
2955286763Smav * wind up in an infinite loop, continually trying to evict buffers.
2956286763Smav */
2957286763Smavstatic uint64_t
2958286763Smavarc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
2959286763Smav    boolean_t retry)
2960286763Smav{
2961286763Smav	uint64_t evicted = 0;
2962286763Smav
2963286763Smav	while (state->arcs_lsize[type] != 0) {
2964286763Smav		evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
2965286763Smav
2966286763Smav		if (!retry)
2967286763Smav			break;
2968185029Spjd	}
2969185029Spjd
2970286763Smav	return (evicted);
2971286763Smav}
2972286763Smav
2973286763Smav/*
2974286763Smav * Evict the specified number of bytes from the state specified,
2975286763Smav * restricting eviction to the spa and type given. This function
2976286763Smav * prevents us from trying to evict more from a state's list than
2977286763Smav * is "evictable", and to skip evicting altogether when passed a
2978286763Smav * negative value for "bytes". In contrast, arc_evict_state() will
2979286763Smav * evict everything it can, when passed a negative value for "bytes".
2980286763Smav */
2981286763Smavstatic uint64_t
2982286763Smavarc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
2983286763Smav    arc_buf_contents_t type)
2984286763Smav{
2985286763Smav	int64_t delta;
2986286763Smav
2987286763Smav	if (bytes > 0 && state->arcs_lsize[type] > 0) {
2988286763Smav		delta = MIN(state->arcs_lsize[type], bytes);
2989286763Smav		return (arc_evict_state(state, spa, delta, type));
2990168404Spjd	}
2991168404Spjd
2992286763Smav	return (0);
2993168404Spjd}
2994168404Spjd
2995286763Smav/*
2996286763Smav * Evict metadata buffers from the cache, such that arc_meta_used is
2997286763Smav * capped by the arc_meta_limit tunable.
2998286763Smav */
2999286763Smavstatic uint64_t
3000286763Smavarc_adjust_meta(void)
3001286763Smav{
3002286763Smav	uint64_t total_evicted = 0;
3003286763Smav	int64_t target;
3004286763Smav
3005286763Smav	/*
3006286763Smav	 * If we're over the meta limit, we want to evict enough
3007286763Smav	 * metadata to get back under the meta limit. We don't want to
3008286763Smav	 * evict so much that we drop the MRU below arc_p, though. If
3009286763Smav	 * we're over the meta limit more than we're over arc_p, we
3010286763Smav	 * evict some from the MRU here, and some from the MFU below.
3011286763Smav	 */
3012286763Smav	target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
3013286766Smav	    (int64_t)(refcount_count(&arc_anon->arcs_size) +
3014286766Smav	    refcount_count(&arc_mru->arcs_size) - arc_p));
3015286763Smav
3016286763Smav	total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3017286763Smav
3018286763Smav	/*
3019286763Smav	 * Similar to the above, we want to evict enough bytes to get us
3020286763Smav	 * below the meta limit, but not so much as to drop us below the
3021286763Smav	 * space alloted to the MFU (which is defined as arc_c - arc_p).
3022286763Smav	 */
3023286763Smav	target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
3024286766Smav	    (int64_t)(refcount_count(&arc_mfu->arcs_size) - (arc_c - arc_p)));
3025286763Smav
3026286763Smav	total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3027286763Smav
3028286763Smav	return (total_evicted);
3029286763Smav}
3030286763Smav
3031286763Smav/*
3032286763Smav * Return the type of the oldest buffer in the given arc state
3033286763Smav *
3034286763Smav * This function will select a random sublist of type ARC_BUFC_DATA and
3035286763Smav * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
3036286763Smav * is compared, and the type which contains the "older" buffer will be
3037286763Smav * returned.
3038286763Smav */
3039286763Smavstatic arc_buf_contents_t
3040286763Smavarc_adjust_type(arc_state_t *state)
3041286763Smav{
3042286763Smav	multilist_t *data_ml = &state->arcs_list[ARC_BUFC_DATA];
3043286763Smav	multilist_t *meta_ml = &state->arcs_list[ARC_BUFC_METADATA];
3044286763Smav	int data_idx = multilist_get_random_index(data_ml);
3045286763Smav	int meta_idx = multilist_get_random_index(meta_ml);
3046286763Smav	multilist_sublist_t *data_mls;
3047286763Smav	multilist_sublist_t *meta_mls;
3048286763Smav	arc_buf_contents_t type;
3049286763Smav	arc_buf_hdr_t *data_hdr;
3050286763Smav	arc_buf_hdr_t *meta_hdr;
3051286763Smav
3052286763Smav	/*
3053286763Smav	 * We keep the sublist lock until we're finished, to prevent
3054286763Smav	 * the headers from being destroyed via arc_evict_state().
3055286763Smav	 */
3056286763Smav	data_mls = multilist_sublist_lock(data_ml, data_idx);
3057286763Smav	meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
3058286763Smav
3059286763Smav	/*
3060286763Smav	 * These two loops are to ensure we skip any markers that
3061286763Smav	 * might be at the tail of the lists due to arc_evict_state().
3062286763Smav	 */
3063286763Smav
3064286763Smav	for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
3065286763Smav	    data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
3066286763Smav		if (data_hdr->b_spa != 0)
3067286763Smav			break;
3068286763Smav	}
3069286763Smav
3070286763Smav	for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
3071286763Smav	    meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
3072286763Smav		if (meta_hdr->b_spa != 0)
3073286763Smav			break;
3074286763Smav	}
3075286763Smav
3076286763Smav	if (data_hdr == NULL && meta_hdr == NULL) {
3077286763Smav		type = ARC_BUFC_DATA;
3078286763Smav	} else if (data_hdr == NULL) {
3079286763Smav		ASSERT3P(meta_hdr, !=, NULL);
3080286763Smav		type = ARC_BUFC_METADATA;
3081286763Smav	} else if (meta_hdr == NULL) {
3082286763Smav		ASSERT3P(data_hdr, !=, NULL);
3083286763Smav		type = ARC_BUFC_DATA;
3084286763Smav	} else {
3085286763Smav		ASSERT3P(data_hdr, !=, NULL);
3086286763Smav		ASSERT3P(meta_hdr, !=, NULL);
3087286763Smav
3088286763Smav		/* The headers can't be on the sublist without an L1 header */
3089286763Smav		ASSERT(HDR_HAS_L1HDR(data_hdr));
3090286763Smav		ASSERT(HDR_HAS_L1HDR(meta_hdr));
3091286763Smav
3092286763Smav		if (data_hdr->b_l1hdr.b_arc_access <
3093286763Smav		    meta_hdr->b_l1hdr.b_arc_access) {
3094286763Smav			type = ARC_BUFC_DATA;
3095286763Smav		} else {
3096286763Smav			type = ARC_BUFC_METADATA;
3097286763Smav		}
3098286763Smav	}
3099286763Smav
3100286763Smav	multilist_sublist_unlock(meta_mls);
3101286763Smav	multilist_sublist_unlock(data_mls);
3102286763Smav
3103286763Smav	return (type);
3104286763Smav}
3105286763Smav
3106286763Smav/*
3107286763Smav * Evict buffers from the cache, such that arc_size is capped by arc_c.
3108286763Smav */
3109286763Smavstatic uint64_t
3110168404Spjdarc_adjust(void)
3111168404Spjd{
3112286763Smav	uint64_t total_evicted = 0;
3113286763Smav	uint64_t bytes;
3114286763Smav	int64_t target;
3115168404Spjd
3116208373Smm	/*
3117286763Smav	 * If we're over arc_meta_limit, we want to correct that before
3118286763Smav	 * potentially evicting data buffers below.
3119286763Smav	 */
3120286763Smav	total_evicted += arc_adjust_meta();
3121286763Smav
3122286763Smav	/*
3123208373Smm	 * Adjust MRU size
3124286763Smav	 *
3125286763Smav	 * If we're over the target cache size, we want to evict enough
3126286763Smav	 * from the list to get back to our target size. We don't want
3127286763Smav	 * to evict too much from the MRU, such that it drops below
3128286763Smav	 * arc_p. So, if we're over our target cache size more than
3129286763Smav	 * the MRU is over arc_p, we'll evict enough to get back to
3130286763Smav	 * arc_p here, and then evict more from the MFU below.
3131208373Smm	 */
3132286763Smav	target = MIN((int64_t)(arc_size - arc_c),
3133286766Smav	    (int64_t)(refcount_count(&arc_anon->arcs_size) +
3134286766Smav	    refcount_count(&arc_mru->arcs_size) + arc_meta_used - arc_p));
3135208373Smm
3136286763Smav	/*
3137286763Smav	 * If we're below arc_meta_min, always prefer to evict data.
3138286763Smav	 * Otherwise, try to satisfy the requested number of bytes to
3139286763Smav	 * evict from the type which contains older buffers; in an
3140286763Smav	 * effort to keep newer buffers in the cache regardless of their
3141286763Smav	 * type. If we cannot satisfy the number of bytes from this
3142286763Smav	 * type, spill over into the next type.
3143286763Smav	 */
3144286763Smav	if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
3145286763Smav	    arc_meta_used > arc_meta_min) {
3146286763Smav		bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3147286763Smav		total_evicted += bytes;
3148168404Spjd
3149286763Smav		/*
3150286763Smav		 * If we couldn't evict our target number of bytes from
3151286763Smav		 * metadata, we try to get the rest from data.
3152286763Smav		 */
3153286763Smav		target -= bytes;
3154286763Smav
3155286763Smav		total_evicted +=
3156286763Smav		    arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3157286763Smav	} else {
3158286763Smav		bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3159286763Smav		total_evicted += bytes;
3160286763Smav
3161286763Smav		/*
3162286763Smav		 * If we couldn't evict our target number of bytes from
3163286763Smav		 * data, we try to get the rest from metadata.
3164286763Smav		 */
3165286763Smav		target -= bytes;
3166286763Smav
3167286763Smav		total_evicted +=
3168286763Smav		    arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3169185029Spjd	}
3170185029Spjd
3171208373Smm	/*
3172208373Smm	 * Adjust MFU size
3173286763Smav	 *
3174286763Smav	 * Now that we've tried to evict enough from the MRU to get its
3175286763Smav	 * size back to arc_p, if we're still above the target cache
3176286763Smav	 * size, we evict the rest from the MFU.
3177208373Smm	 */
3178286763Smav	target = arc_size - arc_c;
3179168404Spjd
3180286764Smav	if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
3181286763Smav	    arc_meta_used > arc_meta_min) {
3182286763Smav		bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3183286763Smav		total_evicted += bytes;
3184208373Smm
3185286763Smav		/*
3186286763Smav		 * If we couldn't evict our target number of bytes from
3187286763Smav		 * metadata, we try to get the rest from data.
3188286763Smav		 */
3189286763Smav		target -= bytes;
3190168404Spjd
3191286763Smav		total_evicted +=
3192286763Smav		    arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3193286763Smav	} else {
3194286763Smav		bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3195286763Smav		total_evicted += bytes;
3196286763Smav
3197286763Smav		/*
3198286763Smav		 * If we couldn't evict our target number of bytes from
3199286763Smav		 * data, we try to get the rest from data.
3200286763Smav		 */
3201286763Smav		target -= bytes;
3202286763Smav
3203286763Smav		total_evicted +=
3204286763Smav		    arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3205208373Smm	}
3206168404Spjd
3207208373Smm	/*
3208208373Smm	 * Adjust ghost lists
3209286763Smav	 *
3210286763Smav	 * In addition to the above, the ARC also defines target values
3211286763Smav	 * for the ghost lists. The sum of the mru list and mru ghost
3212286763Smav	 * list should never exceed the target size of the cache, and
3213286763Smav	 * the sum of the mru list, mfu list, mru ghost list, and mfu
3214286763Smav	 * ghost list should never exceed twice the target size of the
3215286763Smav	 * cache. The following logic enforces these limits on the ghost
3216286763Smav	 * caches, and evicts from them as needed.
3217208373Smm	 */
3218286766Smav	target = refcount_count(&arc_mru->arcs_size) +
3219286766Smav	    refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
3220168404Spjd
3221286763Smav	bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
3222286763Smav	total_evicted += bytes;
3223168404Spjd
3224286763Smav	target -= bytes;
3225185029Spjd
3226286763Smav	total_evicted +=
3227286763Smav	    arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
3228208373Smm
3229286763Smav	/*
3230286763Smav	 * We assume the sum of the mru list and mfu list is less than
3231286763Smav	 * or equal to arc_c (we enforced this above), which means we
3232286763Smav	 * can use the simpler of the two equations below:
3233286763Smav	 *
3234286763Smav	 *	mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
3235286763Smav	 *		    mru ghost + mfu ghost <= arc_c
3236286763Smav	 */
3237286766Smav	target = refcount_count(&arc_mru_ghost->arcs_size) +
3238286766Smav	    refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
3239286763Smav
3240286763Smav	bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
3241286763Smav	total_evicted += bytes;
3242286763Smav
3243286763Smav	target -= bytes;
3244286763Smav
3245286763Smav	total_evicted +=
3246286763Smav	    arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
3247286763Smav
3248286763Smav	return (total_evicted);
3249168404Spjd}
3250168404Spjd
3251168404Spjdstatic void
3252168404Spjdarc_do_user_evicts(void)
3253168404Spjd{
3254286763Smav	mutex_enter(&arc_user_evicts_lock);
3255286762Smav	while (arc_eviction_list != NULL) {
3256286762Smav		arc_buf_t *buf = arc_eviction_list;
3257286762Smav		arc_eviction_list = buf->b_next;
3258219089Spjd		mutex_enter(&buf->b_evict_lock);
3259168404Spjd		buf->b_hdr = NULL;
3260219089Spjd		mutex_exit(&buf->b_evict_lock);
3261286763Smav		mutex_exit(&arc_user_evicts_lock);
3262168404Spjd
3263168404Spjd		if (buf->b_efunc != NULL)
3264268858Sdelphij			VERIFY0(buf->b_efunc(buf->b_private));
3265168404Spjd
3266168404Spjd		buf->b_efunc = NULL;
3267168404Spjd		buf->b_private = NULL;
3268168404Spjd		kmem_cache_free(buf_cache, buf);
3269286763Smav		mutex_enter(&arc_user_evicts_lock);
3270168404Spjd	}
3271286763Smav	mutex_exit(&arc_user_evicts_lock);
3272168404Spjd}
3273168404Spjd
3274168404Spjdvoid
3275286763Smavarc_flush(spa_t *spa, boolean_t retry)
3276168404Spjd{
3277209962Smm	uint64_t guid = 0;
3278209962Smm
3279286763Smav	/*
3280286763Smav	 * If retry is TRUE, a spa must not be specified since we have
3281286763Smav	 * no good way to determine if all of a spa's buffers have been
3282286763Smav	 * evicted from an arc state.
3283286763Smav	 */
3284286763Smav	ASSERT(!retry || spa == 0);
3285286763Smav
3286286570Smav	if (spa != NULL)
3287228103Smm		guid = spa_load_guid(spa);
3288209962Smm
3289286763Smav	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
3290286763Smav	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
3291168404Spjd
3292286763Smav	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
3293286763Smav	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
3294168404Spjd
3295286763Smav	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
3296286763Smav	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
3297286763Smav
3298286763Smav	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
3299286763Smav	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
3300286763Smav
3301168404Spjd	arc_do_user_evicts();
3302185029Spjd	ASSERT(spa || arc_eviction_list == NULL);
3303168404Spjd}
3304168404Spjd
3305168404Spjdvoid
3306286625Smavarc_shrink(int64_t to_free)
3307168404Spjd{
3308168404Spjd	if (arc_c > arc_c_min) {
3309272483Ssmh		DTRACE_PROBE4(arc__shrink, uint64_t, arc_c, uint64_t,
3310272483Ssmh			arc_c_min, uint64_t, arc_p, uint64_t, to_free);
3311168404Spjd		if (arc_c > arc_c_min + to_free)
3312168404Spjd			atomic_add_64(&arc_c, -to_free);
3313168404Spjd		else
3314168404Spjd			arc_c = arc_c_min;
3315168404Spjd
3316168404Spjd		atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
3317168404Spjd		if (arc_c > arc_size)
3318168404Spjd			arc_c = MAX(arc_size, arc_c_min);
3319168404Spjd		if (arc_p > arc_c)
3320168404Spjd			arc_p = (arc_c >> 1);
3321272483Ssmh
3322272483Ssmh		DTRACE_PROBE2(arc__shrunk, uint64_t, arc_c, uint64_t,
3323272483Ssmh			arc_p);
3324272483Ssmh
3325168404Spjd		ASSERT(arc_c >= arc_c_min);
3326168404Spjd		ASSERT((int64_t)arc_p >= 0);
3327168404Spjd	}
3328168404Spjd
3329270759Ssmh	if (arc_size > arc_c) {
3330270759Ssmh		DTRACE_PROBE2(arc__shrink_adjust, uint64_t, arc_size,
3331270759Ssmh			uint64_t, arc_c);
3332286763Smav		(void) arc_adjust();
3333270759Ssmh	}
3334168404Spjd}
3335168404Spjd
3336286625Smavstatic long needfree = 0;
3337168404Spjd
3338286625Smavtypedef enum free_memory_reason_t {
3339286625Smav	FMR_UNKNOWN,
3340286625Smav	FMR_NEEDFREE,
3341286625Smav	FMR_LOTSFREE,
3342286625Smav	FMR_SWAPFS_MINFREE,
3343286625Smav	FMR_PAGES_PP_MAXIMUM,
3344286625Smav	FMR_HEAP_ARENA,
3345286625Smav	FMR_ZIO_ARENA,
3346286625Smav	FMR_ZIO_FRAG,
3347286625Smav} free_memory_reason_t;
3348286625Smav
3349286625Smavint64_t last_free_memory;
3350286625Smavfree_memory_reason_t last_free_reason;
3351286625Smav
3352286625Smav/*
3353286625Smav * Additional reserve of pages for pp_reserve.
3354286625Smav */
3355286625Smavint64_t arc_pages_pp_reserve = 64;
3356286625Smav
3357286625Smav/*
3358286625Smav * Additional reserve of pages for swapfs.
3359286625Smav */
3360286625Smavint64_t arc_swapfs_reserve = 64;
3361286625Smav
3362286625Smav/*
3363286625Smav * Return the amount of memory that can be consumed before reclaim will be
3364286625Smav * needed.  Positive if there is sufficient free memory, negative indicates
3365286625Smav * the amount of memory that needs to be freed up.
3366286625Smav */
3367286625Smavstatic int64_t
3368286625Smavarc_available_memory(void)
3369168404Spjd{
3370286625Smav	int64_t lowest = INT64_MAX;
3371286625Smav	int64_t n;
3372286625Smav	free_memory_reason_t r = FMR_UNKNOWN;
3373168404Spjd
3374168404Spjd#ifdef _KERNEL
3375286625Smav	if (needfree > 0) {
3376286625Smav		n = PAGESIZE * (-needfree);
3377286625Smav		if (n < lowest) {
3378286625Smav			lowest = n;
3379286625Smav			r = FMR_NEEDFREE;
3380286625Smav		}
3381270759Ssmh	}
3382168404Spjd
3383191902Skmacy	/*
3384212780Savg	 * Cooperate with pagedaemon when it's time for it to scan
3385212780Savg	 * and reclaim some pages.
3386191902Skmacy	 */
3387286655Smav	n = PAGESIZE * ((int64_t)freemem - zfs_arc_free_target);
3388286625Smav	if (n < lowest) {
3389286625Smav		lowest = n;
3390286625Smav		r = FMR_LOTSFREE;
3391270759Ssmh	}
3392191902Skmacy
3393277300Ssmh#ifdef illumos
3394168404Spjd	/*
3395185029Spjd	 * check that we're out of range of the pageout scanner.  It starts to
3396185029Spjd	 * schedule paging if freemem is less than lotsfree and needfree.
3397185029Spjd	 * lotsfree is the high-water mark for pageout, and needfree is the
3398185029Spjd	 * number of needed free pages.  We add extra pages here to make sure
3399185029Spjd	 * the scanner doesn't start up while we're freeing memory.
3400185029Spjd	 */
3401286625Smav	n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
3402286625Smav	if (n < lowest) {
3403286625Smav		lowest = n;
3404286625Smav		r = FMR_LOTSFREE;
3405286625Smav	}
3406185029Spjd
3407185029Spjd	/*
3408168404Spjd	 * check to make sure that swapfs has enough space so that anon
3409185029Spjd	 * reservations can still succeed. anon_resvmem() checks that the
3410168404Spjd	 * availrmem is greater than swapfs_minfree, and the number of reserved
3411168404Spjd	 * swap pages.  We also add a bit of extra here just to prevent
3412168404Spjd	 * circumstances from getting really dire.
3413168404Spjd	 */
3414286625Smav	n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
3415286625Smav	    desfree - arc_swapfs_reserve);
3416286625Smav	if (n < lowest) {
3417286625Smav		lowest = n;
3418286625Smav		r = FMR_SWAPFS_MINFREE;
3419286625Smav	}
3420168404Spjd
3421286625Smav
3422168404Spjd	/*
3423272483Ssmh	 * Check that we have enough availrmem that memory locking (e.g., via
3424272483Ssmh	 * mlock(3C) or memcntl(2)) can still succeed.  (pages_pp_maximum
3425272483Ssmh	 * stores the number of pages that cannot be locked; when availrmem
3426272483Ssmh	 * drops below pages_pp_maximum, page locking mechanisms such as
3427272483Ssmh	 * page_pp_lock() will fail.)
3428272483Ssmh	 */
3429286625Smav	n = PAGESIZE * (availrmem - pages_pp_maximum -
3430286625Smav	    arc_pages_pp_reserve);
3431286625Smav	if (n < lowest) {
3432286625Smav		lowest = n;
3433286625Smav		r = FMR_PAGES_PP_MAXIMUM;
3434286625Smav	}
3435272483Ssmh
3436277300Ssmh#endif	/* illumos */
3437272483Ssmh#if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
3438272483Ssmh	/*
3439168404Spjd	 * If we're on an i386 platform, it's possible that we'll exhaust the
3440168404Spjd	 * kernel heap space before we ever run out of available physical
3441168404Spjd	 * memory.  Most checks of the size of the heap_area compare against
3442168404Spjd	 * tune.t_minarmem, which is the minimum available real memory that we
3443168404Spjd	 * can have in the system.  However, this is generally fixed at 25 pages
3444168404Spjd	 * which is so low that it's useless.  In this comparison, we seek to
3445168404Spjd	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
3446185029Spjd	 * heap is allocated.  (Or, in the calculation, if less than 1/4th is
3447168404Spjd	 * free)
3448168404Spjd	 */
3449286655Smav	n = (int64_t)vmem_size(heap_arena, VMEM_FREE) -
3450286628Smav	    (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2);
3451286625Smav	if (n < lowest) {
3452286625Smav		lowest = n;
3453286625Smav		r = FMR_HEAP_ARENA;
3454270861Ssmh	}
3455281026Smav#define	zio_arena	NULL
3456281026Smav#else
3457281026Smav#define	zio_arena	heap_arena
3458270861Ssmh#endif
3459281026Smav
3460272483Ssmh	/*
3461272483Ssmh	 * If zio data pages are being allocated out of a separate heap segment,
3462272483Ssmh	 * then enforce that the size of available vmem for this arena remains
3463272483Ssmh	 * above about 1/16th free.
3464272483Ssmh	 *
3465272483Ssmh	 * Note: The 1/16th arena free requirement was put in place
3466272483Ssmh	 * to aggressively evict memory from the arc in order to avoid
3467272483Ssmh	 * memory fragmentation issues.
3468272483Ssmh	 */
3469286625Smav	if (zio_arena != NULL) {
3470286655Smav		n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
3471286625Smav		    (vmem_size(zio_arena, VMEM_ALLOC) >> 4);
3472286625Smav		if (n < lowest) {
3473286625Smav			lowest = n;
3474286625Smav			r = FMR_ZIO_ARENA;
3475286625Smav		}
3476286625Smav	}
3477281026Smav
3478281026Smav	/*
3479281026Smav	 * Above limits know nothing about real level of KVA fragmentation.
3480281026Smav	 * Start aggressive reclamation if too little sequential KVA left.
3481281026Smav	 */
3482286625Smav	if (lowest > 0) {
3483286625Smav		n = (vmem_size(heap_arena, VMEM_MAXFREE) < zfs_max_recordsize) ?
3484286655Smav		    -((int64_t)vmem_size(heap_arena, VMEM_ALLOC) >> 4) :
3485286655Smav		    INT64_MAX;
3486286625Smav		if (n < lowest) {
3487286625Smav			lowest = n;
3488286625Smav			r = FMR_ZIO_FRAG;
3489286625Smav		}
3490281109Smav	}
3491281026Smav
3492272483Ssmh#else	/* _KERNEL */
3493286625Smav	/* Every 100 calls, free a small amount */
3494168404Spjd	if (spa_get_random(100) == 0)
3495286625Smav		lowest = -1024;
3496272483Ssmh#endif	/* _KERNEL */
3497270759Ssmh
3498286625Smav	last_free_memory = lowest;
3499286625Smav	last_free_reason = r;
3500286625Smav	DTRACE_PROBE2(arc__available_memory, int64_t, lowest, int, r);
3501286625Smav	return (lowest);
3502168404Spjd}
3503168404Spjd
3504286625Smav
3505286625Smav/*
3506286625Smav * Determine if the system is under memory pressure and is asking
3507286625Smav * to reclaim memory. A return value of TRUE indicates that the system
3508286625Smav * is under memory pressure and that the arc should adjust accordingly.
3509286625Smav */
3510286625Smavstatic boolean_t
3511286625Smavarc_reclaim_needed(void)
3512286625Smav{
3513286625Smav	return (arc_available_memory() < 0);
3514286625Smav}
3515286625Smav
3516208454Spjdextern kmem_cache_t	*zio_buf_cache[];
3517208454Spjdextern kmem_cache_t	*zio_data_buf_cache[];
3518272527Sdelphijextern kmem_cache_t	*range_seg_cache;
3519208454Spjd
3520278040Ssmhstatic __noinline void
3521286625Smavarc_kmem_reap_now(void)
3522168404Spjd{
3523168404Spjd	size_t			i;
3524168404Spjd	kmem_cache_t		*prev_cache = NULL;
3525168404Spjd	kmem_cache_t		*prev_data_cache = NULL;
3526168404Spjd
3527272483Ssmh	DTRACE_PROBE(arc__kmem_reap_start);
3528168404Spjd#ifdef _KERNEL
3529185029Spjd	if (arc_meta_used >= arc_meta_limit) {
3530185029Spjd		/*
3531185029Spjd		 * We are exceeding our meta-data cache limit.
3532185029Spjd		 * Purge some DNLC entries to release holds on meta-data.
3533185029Spjd		 */
3534185029Spjd		dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
3535185029Spjd	}
3536168404Spjd#if defined(__i386)
3537168404Spjd	/*
3538168404Spjd	 * Reclaim unused memory from all kmem caches.
3539168404Spjd	 */
3540168404Spjd	kmem_reap();
3541168404Spjd#endif
3542168404Spjd#endif
3543168404Spjd
3544168404Spjd	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
3545168404Spjd		if (zio_buf_cache[i] != prev_cache) {
3546168404Spjd			prev_cache = zio_buf_cache[i];
3547168404Spjd			kmem_cache_reap_now(zio_buf_cache[i]);
3548168404Spjd		}
3549168404Spjd		if (zio_data_buf_cache[i] != prev_data_cache) {
3550168404Spjd			prev_data_cache = zio_data_buf_cache[i];
3551168404Spjd			kmem_cache_reap_now(zio_data_buf_cache[i]);
3552168404Spjd		}
3553168404Spjd	}
3554168404Spjd	kmem_cache_reap_now(buf_cache);
3555286570Smav	kmem_cache_reap_now(hdr_full_cache);
3556286570Smav	kmem_cache_reap_now(hdr_l2only_cache);
3557272506Sdelphij	kmem_cache_reap_now(range_seg_cache);
3558272483Ssmh
3559277300Ssmh#ifdef illumos
3560286625Smav	if (zio_arena != NULL) {
3561286625Smav		/*
3562286625Smav		 * Ask the vmem arena to reclaim unused memory from its
3563286625Smav		 * quantum caches.
3564286625Smav		 */
3565272483Ssmh		vmem_qcache_reap(zio_arena);
3566286625Smav	}
3567272483Ssmh#endif
3568272483Ssmh	DTRACE_PROBE(arc__kmem_reap_end);
3569168404Spjd}
3570168404Spjd
3571286763Smav/*
3572286763Smav * Threads can block in arc_get_data_buf() waiting for this thread to evict
3573286763Smav * enough data and signal them to proceed. When this happens, the threads in
3574286763Smav * arc_get_data_buf() are sleeping while holding the hash lock for their
3575286763Smav * particular arc header. Thus, we must be careful to never sleep on a
3576286763Smav * hash lock in this thread. This is to prevent the following deadlock:
3577286763Smav *
3578286763Smav *  - Thread A sleeps on CV in arc_get_data_buf() holding hash lock "L",
3579286763Smav *    waiting for the reclaim thread to signal it.
3580286763Smav *
3581286763Smav *  - arc_reclaim_thread() tries to acquire hash lock "L" using mutex_enter,
3582286763Smav *    fails, and goes to sleep forever.
3583286763Smav *
3584286763Smav * This possible deadlock is avoided by always acquiring a hash lock
3585286763Smav * using mutex_tryenter() from arc_reclaim_thread().
3586286763Smav */
3587168404Spjdstatic void
3588168404Spjdarc_reclaim_thread(void *dummy __unused)
3589168404Spjd{
3590168404Spjd	clock_t			growtime = 0;
3591168404Spjd	callb_cpr_t		cpr;
3592168404Spjd
3593286763Smav	CALLB_CPR_INIT(&cpr, &arc_reclaim_lock, callb_generic_cpr, FTAG);
3594168404Spjd
3595286763Smav	mutex_enter(&arc_reclaim_lock);
3596286763Smav	while (!arc_reclaim_thread_exit) {
3597286625Smav		int64_t free_memory = arc_available_memory();
3598286763Smav		uint64_t evicted = 0;
3599286763Smav
3600286763Smav		mutex_exit(&arc_reclaim_lock);
3601286763Smav
3602286625Smav		if (free_memory < 0) {
3603168404Spjd
3604286625Smav			arc_no_grow = B_TRUE;
3605286625Smav			arc_warm = B_TRUE;
3606168404Spjd
3607286625Smav			/*
3608286625Smav			 * Wait at least zfs_grow_retry (default 60) seconds
3609286625Smav			 * before considering growing.
3610286625Smav			 */
3611219089Spjd			growtime = ddi_get_lbolt() + (arc_grow_retry * hz);
3612168404Spjd
3613286625Smav			arc_kmem_reap_now();
3614286625Smav
3615286625Smav			/*
3616286625Smav			 * If we are still low on memory, shrink the ARC
3617286625Smav			 * so that we have arc_shrink_min free space.
3618286625Smav			 */
3619286625Smav			free_memory = arc_available_memory();
3620286625Smav
3621286625Smav			int64_t to_free =
3622286625Smav			    (arc_c >> arc_shrink_shift) - free_memory;
3623286625Smav			if (to_free > 0) {
3624286625Smav#ifdef _KERNEL
3625286625Smav				to_free = MAX(to_free, ptob(needfree));
3626286625Smav#endif
3627286625Smav				arc_shrink(to_free);
3628168404Spjd			}
3629286625Smav		} else if (free_memory < arc_c >> arc_no_grow_shift) {
3630286625Smav			arc_no_grow = B_TRUE;
3631286625Smav		} else if (ddi_get_lbolt() >= growtime) {
3632286625Smav			arc_no_grow = B_FALSE;
3633168404Spjd		}
3634168404Spjd
3635286763Smav		evicted = arc_adjust();
3636168404Spjd
3637286763Smav		mutex_enter(&arc_reclaim_lock);
3638168404Spjd
3639286763Smav		/*
3640286763Smav		 * If evicted is zero, we couldn't evict anything via
3641286763Smav		 * arc_adjust(). This could be due to hash lock
3642286763Smav		 * collisions, but more likely due to the majority of
3643286763Smav		 * arc buffers being unevictable. Therefore, even if
3644286763Smav		 * arc_size is above arc_c, another pass is unlikely to
3645286763Smav		 * be helpful and could potentially cause us to enter an
3646286763Smav		 * infinite loop.
3647286763Smav		 */
3648286763Smav		if (arc_size <= arc_c || evicted == 0) {
3649211762Savg#ifdef _KERNEL
3650185029Spjd			needfree = 0;
3651168404Spjd#endif
3652286763Smav			/*
3653286763Smav			 * We're either no longer overflowing, or we
3654286763Smav			 * can't evict anything more, so we should wake
3655286763Smav			 * up any threads before we go to sleep.
3656286763Smav			 */
3657286763Smav			cv_broadcast(&arc_reclaim_waiters_cv);
3658168404Spjd
3659286763Smav			/*
3660286763Smav			 * Block until signaled, or after one second (we
3661286763Smav			 * might need to perform arc_kmem_reap_now()
3662286763Smav			 * even if we aren't being signalled)
3663286763Smav			 */
3664286763Smav			CALLB_CPR_SAFE_BEGIN(&cpr);
3665286763Smav			(void) cv_timedwait(&arc_reclaim_thread_cv,
3666286763Smav			    &arc_reclaim_lock, hz);
3667286763Smav			CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_lock);
3668286763Smav		}
3669286763Smav	}
3670286763Smav
3671286763Smav	arc_reclaim_thread_exit = FALSE;
3672286763Smav	cv_broadcast(&arc_reclaim_thread_cv);
3673286763Smav	CALLB_CPR_EXIT(&cpr);		/* drops arc_reclaim_lock */
3674286763Smav	thread_exit();
3675286763Smav}
3676286763Smav
3677286763Smavstatic void
3678286763Smavarc_user_evicts_thread(void *dummy __unused)
3679286763Smav{
3680286763Smav	callb_cpr_t cpr;
3681286763Smav
3682286763Smav	CALLB_CPR_INIT(&cpr, &arc_user_evicts_lock, callb_generic_cpr, FTAG);
3683286763Smav
3684286763Smav	mutex_enter(&arc_user_evicts_lock);
3685286763Smav	while (!arc_user_evicts_thread_exit) {
3686286763Smav		mutex_exit(&arc_user_evicts_lock);
3687286763Smav
3688286763Smav		arc_do_user_evicts();
3689286763Smav
3690286574Smav		/*
3691286574Smav		 * This is necessary in order for the mdb ::arc dcmd to
3692286574Smav		 * show up to date information. Since the ::arc command
3693286574Smav		 * does not call the kstat's update function, without
3694286574Smav		 * this call, the command may show stale stats for the
3695286574Smav		 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
3696286574Smav		 * with this change, the data might be up to 1 second
3697286574Smav		 * out of date; but that should suffice. The arc_state_t
3698286574Smav		 * structures can be queried directly if more accurate
3699286574Smav		 * information is needed.
3700286574Smav		 */
3701286574Smav		if (arc_ksp != NULL)
3702286574Smav			arc_ksp->ks_update(arc_ksp, KSTAT_READ);
3703286574Smav
3704286763Smav		mutex_enter(&arc_user_evicts_lock);
3705286763Smav
3706286763Smav		/*
3707286763Smav		 * Block until signaled, or after one second (we need to
3708286763Smav		 * call the arc's kstat update function regularly).
3709286763Smav		 */
3710168404Spjd		CALLB_CPR_SAFE_BEGIN(&cpr);
3711286763Smav		(void) cv_timedwait(&arc_user_evicts_cv,
3712286763Smav		    &arc_user_evicts_lock, hz);
3713286763Smav		CALLB_CPR_SAFE_END(&cpr, &arc_user_evicts_lock);
3714168404Spjd	}
3715168404Spjd
3716286763Smav	arc_user_evicts_thread_exit = FALSE;
3717286763Smav	cv_broadcast(&arc_user_evicts_cv);
3718286763Smav	CALLB_CPR_EXIT(&cpr);		/* drops arc_user_evicts_lock */
3719168404Spjd	thread_exit();
3720168404Spjd}
3721168404Spjd
3722168404Spjd/*
3723168404Spjd * Adapt arc info given the number of bytes we are trying to add and
3724168404Spjd * the state that we are comming from.  This function is only called
3725168404Spjd * when we are adding new content to the cache.
3726168404Spjd */
3727168404Spjdstatic void
3728168404Spjdarc_adapt(int bytes, arc_state_t *state)
3729168404Spjd{
3730168404Spjd	int mult;
3731208373Smm	uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
3732286766Smav	int64_t mrug_size = refcount_count(&arc_mru_ghost->arcs_size);
3733286766Smav	int64_t mfug_size = refcount_count(&arc_mfu_ghost->arcs_size);
3734168404Spjd
3735185029Spjd	if (state == arc_l2c_only)
3736185029Spjd		return;
3737185029Spjd
3738168404Spjd	ASSERT(bytes > 0);
3739168404Spjd	/*
3740168404Spjd	 * Adapt the target size of the MRU list:
3741168404Spjd	 *	- if we just hit in the MRU ghost list, then increase
3742168404Spjd	 *	  the target size of the MRU list.
3743168404Spjd	 *	- if we just hit in the MFU ghost list, then increase
3744168404Spjd	 *	  the target size of the MFU list by decreasing the
3745168404Spjd	 *	  target size of the MRU list.
3746168404Spjd	 */
3747168404Spjd	if (state == arc_mru_ghost) {
3748286766Smav		mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
3749209275Smm		mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
3750168404Spjd
3751208373Smm		arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
3752168404Spjd	} else if (state == arc_mfu_ghost) {
3753208373Smm		uint64_t delta;
3754208373Smm
3755286766Smav		mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
3756209275Smm		mult = MIN(mult, 10);
3757168404Spjd
3758208373Smm		delta = MIN(bytes * mult, arc_p);
3759208373Smm		arc_p = MAX(arc_p_min, arc_p - delta);
3760168404Spjd	}
3761168404Spjd	ASSERT((int64_t)arc_p >= 0);
3762168404Spjd
3763168404Spjd	if (arc_reclaim_needed()) {
3764286763Smav		cv_signal(&arc_reclaim_thread_cv);
3765168404Spjd		return;
3766168404Spjd	}
3767168404Spjd
3768168404Spjd	if (arc_no_grow)
3769168404Spjd		return;
3770168404Spjd
3771168404Spjd	if (arc_c >= arc_c_max)
3772168404Spjd		return;
3773168404Spjd
3774168404Spjd	/*
3775168404Spjd	 * If we're within (2 * maxblocksize) bytes of the target
3776168404Spjd	 * cache size, increment the target cache size
3777168404Spjd	 */
3778168404Spjd	if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
3779272483Ssmh		DTRACE_PROBE1(arc__inc_adapt, int, bytes);
3780168404Spjd		atomic_add_64(&arc_c, (int64_t)bytes);
3781168404Spjd		if (arc_c > arc_c_max)
3782168404Spjd			arc_c = arc_c_max;
3783168404Spjd		else if (state == arc_anon)
3784168404Spjd			atomic_add_64(&arc_p, (int64_t)bytes);
3785168404Spjd		if (arc_p > arc_c)
3786168404Spjd			arc_p = arc_c;
3787168404Spjd	}
3788168404Spjd	ASSERT((int64_t)arc_p >= 0);
3789168404Spjd}
3790168404Spjd
3791168404Spjd/*
3792286763Smav * Check if arc_size has grown past our upper threshold, determined by
3793286763Smav * zfs_arc_overflow_shift.
3794168404Spjd */
3795286763Smavstatic boolean_t
3796286763Smavarc_is_overflowing(void)
3797168404Spjd{
3798286763Smav	/* Always allow at least one block of overflow */
3799286763Smav	uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
3800286763Smav	    arc_c >> zfs_arc_overflow_shift);
3801185029Spjd
3802286763Smav	return (arc_size >= arc_c + overflow);
3803168404Spjd}
3804168404Spjd
3805168404Spjd/*
3806286763Smav * The buffer, supplied as the first argument, needs a data block. If we
3807286763Smav * are hitting the hard limit for the cache size, we must sleep, waiting
3808286763Smav * for the eviction thread to catch up. If we're past the target size
3809286763Smav * but below the hard limit, we'll only signal the reclaim thread and
3810286763Smav * continue on.
3811168404Spjd */
3812168404Spjdstatic void
3813168404Spjdarc_get_data_buf(arc_buf_t *buf)
3814168404Spjd{
3815286570Smav	arc_state_t		*state = buf->b_hdr->b_l1hdr.b_state;
3816168404Spjd	uint64_t		size = buf->b_hdr->b_size;
3817286570Smav	arc_buf_contents_t	type = arc_buf_type(buf->b_hdr);
3818168404Spjd
3819168404Spjd	arc_adapt(size, state);
3820168404Spjd
3821168404Spjd	/*
3822286763Smav	 * If arc_size is currently overflowing, and has grown past our
3823286763Smav	 * upper limit, we must be adding data faster than the evict
3824286763Smav	 * thread can evict. Thus, to ensure we don't compound the
3825286763Smav	 * problem by adding more data and forcing arc_size to grow even
3826286763Smav	 * further past it's target size, we halt and wait for the
3827286763Smav	 * eviction thread to catch up.
3828286763Smav	 *
3829286763Smav	 * It's also possible that the reclaim thread is unable to evict
3830286763Smav	 * enough buffers to get arc_size below the overflow limit (e.g.
3831286763Smav	 * due to buffers being un-evictable, or hash lock collisions).
3832286763Smav	 * In this case, we want to proceed regardless if we're
3833286763Smav	 * overflowing; thus we don't use a while loop here.
3834168404Spjd	 */
3835286763Smav	if (arc_is_overflowing()) {
3836286763Smav		mutex_enter(&arc_reclaim_lock);
3837286763Smav
3838286763Smav		/*
3839286763Smav		 * Now that we've acquired the lock, we may no longer be
3840286763Smav		 * over the overflow limit, lets check.
3841286763Smav		 *
3842286763Smav		 * We're ignoring the case of spurious wake ups. If that
3843286763Smav		 * were to happen, it'd let this thread consume an ARC
3844286763Smav		 * buffer before it should have (i.e. before we're under
3845286763Smav		 * the overflow limit and were signalled by the reclaim
3846286763Smav		 * thread). As long as that is a rare occurrence, it
3847286763Smav		 * shouldn't cause any harm.
3848286763Smav		 */
3849286763Smav		if (arc_is_overflowing()) {
3850286763Smav			cv_signal(&arc_reclaim_thread_cv);
3851286763Smav			cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
3852168404Spjd		}
3853286763Smav
3854286763Smav		mutex_exit(&arc_reclaim_lock);
3855168404Spjd	}
3856168404Spjd
3857286763Smav	if (type == ARC_BUFC_METADATA) {
3858286763Smav		buf->b_data = zio_buf_alloc(size);
3859286763Smav		arc_space_consume(size, ARC_SPACE_META);
3860168404Spjd	} else {
3861286763Smav		ASSERT(type == ARC_BUFC_DATA);
3862286763Smav		buf->b_data = zio_data_buf_alloc(size);
3863286763Smav		arc_space_consume(size, ARC_SPACE_DATA);
3864168404Spjd	}
3865286763Smav
3866168404Spjd	/*
3867168404Spjd	 * Update the state size.  Note that ghost states have a
3868168404Spjd	 * "ghost size" and so don't need to be updated.
3869168404Spjd	 */
3870286570Smav	if (!GHOST_STATE(buf->b_hdr->b_l1hdr.b_state)) {
3871168404Spjd		arc_buf_hdr_t *hdr = buf->b_hdr;
3872286766Smav		arc_state_t *state = hdr->b_l1hdr.b_state;
3873168404Spjd
3874286766Smav		(void) refcount_add_many(&state->arcs_size, size, buf);
3875286763Smav
3876286763Smav		/*
3877286763Smav		 * If this is reached via arc_read, the link is
3878286763Smav		 * protected by the hash lock. If reached via
3879286763Smav		 * arc_buf_alloc, the header should not be accessed by
3880286763Smav		 * any other thread. And, if reached via arc_read_done,
3881286763Smav		 * the hash lock will protect it if it's found in the
3882286763Smav		 * hash table; otherwise no other thread should be
3883286763Smav		 * trying to [add|remove]_reference it.
3884286763Smav		 */
3885286763Smav		if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
3886286570Smav			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3887286570Smav			atomic_add_64(&hdr->b_l1hdr.b_state->arcs_lsize[type],
3888286570Smav			    size);
3889168404Spjd		}
3890168404Spjd		/*
3891168404Spjd		 * If we are growing the cache, and we are adding anonymous
3892168404Spjd		 * data, and we have outgrown arc_p, update arc_p
3893168404Spjd		 */
3894286570Smav		if (arc_size < arc_c && hdr->b_l1hdr.b_state == arc_anon &&
3895286766Smav		    (refcount_count(&arc_anon->arcs_size) +
3896286766Smav		    refcount_count(&arc_mru->arcs_size) > arc_p))
3897168404Spjd			arc_p = MIN(arc_c, arc_p + size);
3898168404Spjd	}
3899205231Skmacy	ARCSTAT_BUMP(arcstat_allocated);
3900168404Spjd}
3901168404Spjd
3902168404Spjd/*
3903168404Spjd * This routine is called whenever a buffer is accessed.
3904168404Spjd * NOTE: the hash lock is dropped in this function.
3905168404Spjd */
3906168404Spjdstatic void
3907275811Sdelphijarc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3908168404Spjd{
3909219089Spjd	clock_t now;
3910219089Spjd
3911168404Spjd	ASSERT(MUTEX_HELD(hash_lock));
3912286570Smav	ASSERT(HDR_HAS_L1HDR(hdr));
3913168404Spjd
3914286570Smav	if (hdr->b_l1hdr.b_state == arc_anon) {
3915168404Spjd		/*
3916168404Spjd		 * This buffer is not in the cache, and does not
3917168404Spjd		 * appear in our "ghost" list.  Add the new buffer
3918168404Spjd		 * to the MRU state.
3919168404Spjd		 */
3920168404Spjd
3921286570Smav		ASSERT0(hdr->b_l1hdr.b_arc_access);
3922286570Smav		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3923275811Sdelphij		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3924275811Sdelphij		arc_change_state(arc_mru, hdr, hash_lock);
3925168404Spjd
3926286570Smav	} else if (hdr->b_l1hdr.b_state == arc_mru) {
3927219089Spjd		now = ddi_get_lbolt();
3928219089Spjd
3929168404Spjd		/*
3930168404Spjd		 * If this buffer is here because of a prefetch, then either:
3931168404Spjd		 * - clear the flag if this is a "referencing" read
3932168404Spjd		 *   (any subsequent access will bump this into the MFU state).
3933168404Spjd		 * or
3934168404Spjd		 * - move the buffer to the head of the list if this is
3935168404Spjd		 *   another prefetch (to make it less likely to be evicted).
3936168404Spjd		 */
3937286570Smav		if (HDR_PREFETCH(hdr)) {
3938286570Smav			if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
3939286763Smav				/* link protected by hash lock */
3940286763Smav				ASSERT(multilist_link_active(
3941286570Smav				    &hdr->b_l1hdr.b_arc_node));
3942168404Spjd			} else {
3943275811Sdelphij				hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3944168404Spjd				ARCSTAT_BUMP(arcstat_mru_hits);
3945168404Spjd			}
3946286570Smav			hdr->b_l1hdr.b_arc_access = now;
3947168404Spjd			return;
3948168404Spjd		}
3949168404Spjd
3950168404Spjd		/*
3951168404Spjd		 * This buffer has been "accessed" only once so far,
3952168404Spjd		 * but it is still in the cache. Move it to the MFU
3953168404Spjd		 * state.
3954168404Spjd		 */
3955286570Smav		if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
3956168404Spjd			/*
3957168404Spjd			 * More than 125ms have passed since we
3958168404Spjd			 * instantiated this buffer.  Move it to the
3959168404Spjd			 * most frequently used state.
3960168404Spjd			 */
3961286570Smav			hdr->b_l1hdr.b_arc_access = now;
3962275811Sdelphij			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3963275811Sdelphij			arc_change_state(arc_mfu, hdr, hash_lock);
3964168404Spjd		}
3965168404Spjd		ARCSTAT_BUMP(arcstat_mru_hits);
3966286570Smav	} else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
3967168404Spjd		arc_state_t	*new_state;
3968168404Spjd		/*
3969168404Spjd		 * This buffer has been "accessed" recently, but
3970168404Spjd		 * was evicted from the cache.  Move it to the
3971168404Spjd		 * MFU state.
3972168404Spjd		 */
3973168404Spjd
3974286570Smav		if (HDR_PREFETCH(hdr)) {
3975168404Spjd			new_state = arc_mru;
3976286570Smav			if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0)
3977275811Sdelphij				hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3978275811Sdelphij			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3979168404Spjd		} else {
3980168404Spjd			new_state = arc_mfu;
3981275811Sdelphij			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3982168404Spjd		}
3983168404Spjd
3984286570Smav		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3985275811Sdelphij		arc_change_state(new_state, hdr, hash_lock);
3986168404Spjd
3987168404Spjd		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
3988286570Smav	} else if (hdr->b_l1hdr.b_state == arc_mfu) {
3989168404Spjd		/*
3990168404Spjd		 * This buffer has been accessed more than once and is
3991168404Spjd		 * still in the cache.  Keep it in the MFU state.
3992168404Spjd		 *
3993168404Spjd		 * NOTE: an add_reference() that occurred when we did
3994168404Spjd		 * the arc_read() will have kicked this off the list.
3995168404Spjd		 * If it was a prefetch, we will explicitly move it to
3996168404Spjd		 * the head of the list now.
3997168404Spjd		 */
3998286570Smav		if ((HDR_PREFETCH(hdr)) != 0) {
3999286570Smav			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4000286763Smav			/* link protected by hash_lock */
4001286763Smav			ASSERT(multilist_link_active(&hdr->b_l1hdr.b_arc_node));
4002168404Spjd		}
4003168404Spjd		ARCSTAT_BUMP(arcstat_mfu_hits);
4004286570Smav		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4005286570Smav	} else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
4006168404Spjd		arc_state_t	*new_state = arc_mfu;
4007168404Spjd		/*
4008168404Spjd		 * This buffer has been accessed more than once but has
4009168404Spjd		 * been evicted from the cache.  Move it back to the
4010168404Spjd		 * MFU state.
4011168404Spjd		 */
4012168404Spjd
4013286570Smav		if (HDR_PREFETCH(hdr)) {
4014168404Spjd			/*
4015168404Spjd			 * This is a prefetch access...
4016168404Spjd			 * move this block back to the MRU state.
4017168404Spjd			 */
4018286570Smav			ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
4019168404Spjd			new_state = arc_mru;
4020168404Spjd		}
4021168404Spjd
4022286570Smav		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4023275811Sdelphij		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4024275811Sdelphij		arc_change_state(new_state, hdr, hash_lock);
4025168404Spjd
4026168404Spjd		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
4027286570Smav	} else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
4028185029Spjd		/*
4029185029Spjd		 * This buffer is on the 2nd Level ARC.
4030185029Spjd		 */
4031185029Spjd
4032286570Smav		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4033275811Sdelphij		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4034275811Sdelphij		arc_change_state(arc_mfu, hdr, hash_lock);
4035168404Spjd	} else {
4036168404Spjd		ASSERT(!"invalid arc state");
4037168404Spjd	}
4038168404Spjd}
4039168404Spjd
4040168404Spjd/* a generic arc_done_func_t which you can use */
4041168404Spjd/* ARGSUSED */
4042168404Spjdvoid
4043168404Spjdarc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
4044168404Spjd{
4045219089Spjd	if (zio == NULL || zio->io_error == 0)
4046219089Spjd		bcopy(buf->b_data, arg, buf->b_hdr->b_size);
4047248571Smm	VERIFY(arc_buf_remove_ref(buf, arg));
4048168404Spjd}
4049168404Spjd
4050185029Spjd/* a generic arc_done_func_t */
4051168404Spjdvoid
4052168404Spjdarc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
4053168404Spjd{
4054168404Spjd	arc_buf_t **bufp = arg;
4055168404Spjd	if (zio && zio->io_error) {
4056248571Smm		VERIFY(arc_buf_remove_ref(buf, arg));
4057168404Spjd		*bufp = NULL;
4058168404Spjd	} else {
4059168404Spjd		*bufp = buf;
4060219089Spjd		ASSERT(buf->b_data);
4061168404Spjd	}
4062168404Spjd}
4063168404Spjd
4064168404Spjdstatic void
4065168404Spjdarc_read_done(zio_t *zio)
4066168404Spjd{
4067268075Sdelphij	arc_buf_hdr_t	*hdr;
4068168404Spjd	arc_buf_t	*buf;
4069168404Spjd	arc_buf_t	*abuf;	/* buffer we're assigning to callback */
4070268075Sdelphij	kmutex_t	*hash_lock = NULL;
4071168404Spjd	arc_callback_t	*callback_list, *acb;
4072168404Spjd	int		freeable = FALSE;
4073168404Spjd
4074168404Spjd	buf = zio->io_private;
4075168404Spjd	hdr = buf->b_hdr;
4076168404Spjd
4077168404Spjd	/*
4078168404Spjd	 * The hdr was inserted into hash-table and removed from lists
4079168404Spjd	 * prior to starting I/O.  We should find this header, since
4080168404Spjd	 * it's in the hash table, and it should be legit since it's
4081168404Spjd	 * not possible to evict it during the I/O.  The only possible
4082168404Spjd	 * reason for it not to be found is if we were freed during the
4083168404Spjd	 * read.
4084168404Spjd	 */
4085268075Sdelphij	if (HDR_IN_HASH_TABLE(hdr)) {
4086268075Sdelphij		ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
4087268075Sdelphij		ASSERT3U(hdr->b_dva.dva_word[0], ==,
4088268075Sdelphij		    BP_IDENTITY(zio->io_bp)->dva_word[0]);
4089268075Sdelphij		ASSERT3U(hdr->b_dva.dva_word[1], ==,
4090268075Sdelphij		    BP_IDENTITY(zio->io_bp)->dva_word[1]);
4091168404Spjd
4092268075Sdelphij		arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
4093268075Sdelphij		    &hash_lock);
4094168404Spjd
4095268075Sdelphij		ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) &&
4096268075Sdelphij		    hash_lock == NULL) ||
4097268075Sdelphij		    (found == hdr &&
4098268075Sdelphij		    DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
4099268075Sdelphij		    (found == hdr && HDR_L2_READING(hdr)));
4100268075Sdelphij	}
4101268075Sdelphij
4102275811Sdelphij	hdr->b_flags &= ~ARC_FLAG_L2_EVICTED;
4103286570Smav	if (l2arc_noprefetch && HDR_PREFETCH(hdr))
4104275811Sdelphij		hdr->b_flags &= ~ARC_FLAG_L2CACHE;
4105206796Spjd
4106168404Spjd	/* byteswap if necessary */
4107286570Smav	callback_list = hdr->b_l1hdr.b_acb;
4108168404Spjd	ASSERT(callback_list != NULL);
4109209101Smm	if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
4110236884Smm		dmu_object_byteswap_t bswap =
4111236884Smm		    DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
4112185029Spjd		arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
4113185029Spjd		    byteswap_uint64_array :
4114236884Smm		    dmu_ot_byteswap[bswap].ob_func;
4115185029Spjd		func(buf->b_data, hdr->b_size);
4116185029Spjd	}
4117168404Spjd
4118185029Spjd	arc_cksum_compute(buf, B_FALSE);
4119240133Smm#ifdef illumos
4120240133Smm	arc_buf_watch(buf);
4121277300Ssmh#endif
4122168404Spjd
4123286570Smav	if (hash_lock && zio->io_error == 0 &&
4124286570Smav	    hdr->b_l1hdr.b_state == arc_anon) {
4125219089Spjd		/*
4126219089Spjd		 * Only call arc_access on anonymous buffers.  This is because
4127219089Spjd		 * if we've issued an I/O for an evicted buffer, we've already
4128219089Spjd		 * called arc_access (to prevent any simultaneous readers from
4129219089Spjd		 * getting confused).
4130219089Spjd		 */
4131219089Spjd		arc_access(hdr, hash_lock);
4132219089Spjd	}
4133219089Spjd
4134168404Spjd	/* create copies of the data buffer for the callers */
4135168404Spjd	abuf = buf;
4136168404Spjd	for (acb = callback_list; acb; acb = acb->acb_next) {
4137168404Spjd		if (acb->acb_done) {
4138242845Sdelphij			if (abuf == NULL) {
4139242845Sdelphij				ARCSTAT_BUMP(arcstat_duplicate_reads);
4140168404Spjd				abuf = arc_buf_clone(buf);
4141242845Sdelphij			}
4142168404Spjd			acb->acb_buf = abuf;
4143168404Spjd			abuf = NULL;
4144168404Spjd		}
4145168404Spjd	}
4146286570Smav	hdr->b_l1hdr.b_acb = NULL;
4147275811Sdelphij	hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
4148168404Spjd	ASSERT(!HDR_BUF_AVAILABLE(hdr));
4149219089Spjd	if (abuf == buf) {
4150219089Spjd		ASSERT(buf->b_efunc == NULL);
4151286570Smav		ASSERT(hdr->b_l1hdr.b_datacnt == 1);
4152275811Sdelphij		hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
4153219089Spjd	}
4154168404Spjd
4155286570Smav	ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
4156286570Smav	    callback_list != NULL);
4157168404Spjd
4158168404Spjd	if (zio->io_error != 0) {
4159275811Sdelphij		hdr->b_flags |= ARC_FLAG_IO_ERROR;
4160286570Smav		if (hdr->b_l1hdr.b_state != arc_anon)
4161168404Spjd			arc_change_state(arc_anon, hdr, hash_lock);
4162168404Spjd		if (HDR_IN_HASH_TABLE(hdr))
4163168404Spjd			buf_hash_remove(hdr);
4164286570Smav		freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4165168404Spjd	}
4166168404Spjd
4167168404Spjd	/*
4168168404Spjd	 * Broadcast before we drop the hash_lock to avoid the possibility
4169168404Spjd	 * that the hdr (and hence the cv) might be freed before we get to
4170168404Spjd	 * the cv_broadcast().
4171168404Spjd	 */
4172286570Smav	cv_broadcast(&hdr->b_l1hdr.b_cv);
4173168404Spjd
4174286570Smav	if (hash_lock != NULL) {
4175168404Spjd		mutex_exit(hash_lock);
4176168404Spjd	} else {
4177168404Spjd		/*
4178168404Spjd		 * This block was freed while we waited for the read to
4179168404Spjd		 * complete.  It has been removed from the hash table and
4180168404Spjd		 * moved to the anonymous state (so that it won't show up
4181168404Spjd		 * in the cache).
4182168404Spjd		 */
4183286570Smav		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
4184286570Smav		freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4185168404Spjd	}
4186168404Spjd
4187168404Spjd	/* execute each callback and free its structure */
4188168404Spjd	while ((acb = callback_list) != NULL) {
4189168404Spjd		if (acb->acb_done)
4190168404Spjd			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
4191168404Spjd
4192168404Spjd		if (acb->acb_zio_dummy != NULL) {
4193168404Spjd			acb->acb_zio_dummy->io_error = zio->io_error;
4194168404Spjd			zio_nowait(acb->acb_zio_dummy);
4195168404Spjd		}
4196168404Spjd
4197168404Spjd		callback_list = acb->acb_next;
4198168404Spjd		kmem_free(acb, sizeof (arc_callback_t));
4199168404Spjd	}
4200168404Spjd
4201168404Spjd	if (freeable)
4202168404Spjd		arc_hdr_destroy(hdr);
4203168404Spjd}
4204168404Spjd
4205168404Spjd/*
4206286762Smav * "Read" the block at the specified DVA (in bp) via the
4207168404Spjd * cache.  If the block is found in the cache, invoke the provided
4208168404Spjd * callback immediately and return.  Note that the `zio' parameter
4209168404Spjd * in the callback will be NULL in this case, since no IO was
4210168404Spjd * required.  If the block is not in the cache pass the read request
4211168404Spjd * on to the spa with a substitute callback function, so that the
4212168404Spjd * requested block will be added to the cache.
4213168404Spjd *
4214168404Spjd * If a read request arrives for a block that has a read in-progress,
4215168404Spjd * either wait for the in-progress read to complete (and return the
4216168404Spjd * results); or, if this is a read with a "done" func, add a record
4217168404Spjd * to the read to invoke the "done" func when the read completes,
4218168404Spjd * and return; or just return.
4219168404Spjd *
4220168404Spjd * arc_read_done() will invoke all the requested "done" functions
4221168404Spjd * for readers of this block.
4222168404Spjd */
4223168404Spjdint
4224246666Smmarc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
4225275811Sdelphij    void *private, zio_priority_t priority, int zio_flags,
4226275811Sdelphij    arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
4227168404Spjd{
4228268075Sdelphij	arc_buf_hdr_t *hdr = NULL;
4229247187Smm	arc_buf_t *buf = NULL;
4230268075Sdelphij	kmutex_t *hash_lock = NULL;
4231185029Spjd	zio_t *rzio;
4232228103Smm	uint64_t guid = spa_load_guid(spa);
4233168404Spjd
4234268075Sdelphij	ASSERT(!BP_IS_EMBEDDED(bp) ||
4235268075Sdelphij	    BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
4236268075Sdelphij
4237168404Spjdtop:
4238268075Sdelphij	if (!BP_IS_EMBEDDED(bp)) {
4239268075Sdelphij		/*
4240268075Sdelphij		 * Embedded BP's have no DVA and require no I/O to "read".
4241268075Sdelphij		 * Create an anonymous arc buf to back it.
4242268075Sdelphij		 */
4243268075Sdelphij		hdr = buf_hash_find(guid, bp, &hash_lock);
4244268075Sdelphij	}
4245168404Spjd
4246286570Smav	if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_datacnt > 0) {
4247268075Sdelphij
4248275811Sdelphij		*arc_flags |= ARC_FLAG_CACHED;
4249168404Spjd
4250168404Spjd		if (HDR_IO_IN_PROGRESS(hdr)) {
4251168404Spjd
4252275811Sdelphij			if (*arc_flags & ARC_FLAG_WAIT) {
4253286570Smav				cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
4254168404Spjd				mutex_exit(hash_lock);
4255168404Spjd				goto top;
4256168404Spjd			}
4257275811Sdelphij			ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
4258168404Spjd
4259168404Spjd			if (done) {
4260168404Spjd				arc_callback_t	*acb = NULL;
4261168404Spjd
4262168404Spjd				acb = kmem_zalloc(sizeof (arc_callback_t),
4263168404Spjd				    KM_SLEEP);
4264168404Spjd				acb->acb_done = done;
4265168404Spjd				acb->acb_private = private;
4266168404Spjd				if (pio != NULL)
4267168404Spjd					acb->acb_zio_dummy = zio_null(pio,
4268209962Smm					    spa, NULL, NULL, NULL, zio_flags);
4269168404Spjd
4270168404Spjd				ASSERT(acb->acb_done != NULL);
4271286570Smav				acb->acb_next = hdr->b_l1hdr.b_acb;
4272286570Smav				hdr->b_l1hdr.b_acb = acb;
4273168404Spjd				add_reference(hdr, hash_lock, private);
4274168404Spjd				mutex_exit(hash_lock);
4275168404Spjd				return (0);
4276168404Spjd			}
4277168404Spjd			mutex_exit(hash_lock);
4278168404Spjd			return (0);
4279168404Spjd		}
4280168404Spjd
4281286570Smav		ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
4282286570Smav		    hdr->b_l1hdr.b_state == arc_mfu);
4283168404Spjd
4284168404Spjd		if (done) {
4285168404Spjd			add_reference(hdr, hash_lock, private);
4286168404Spjd			/*
4287168404Spjd			 * If this block is already in use, create a new
4288168404Spjd			 * copy of the data so that we will be guaranteed
4289168404Spjd			 * that arc_release() will always succeed.
4290168404Spjd			 */
4291286570Smav			buf = hdr->b_l1hdr.b_buf;
4292168404Spjd			ASSERT(buf);
4293168404Spjd			ASSERT(buf->b_data);
4294168404Spjd			if (HDR_BUF_AVAILABLE(hdr)) {
4295168404Spjd				ASSERT(buf->b_efunc == NULL);
4296275811Sdelphij				hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
4297168404Spjd			} else {
4298168404Spjd				buf = arc_buf_clone(buf);
4299168404Spjd			}
4300219089Spjd
4301275811Sdelphij		} else if (*arc_flags & ARC_FLAG_PREFETCH &&
4302286570Smav		    refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4303275811Sdelphij			hdr->b_flags |= ARC_FLAG_PREFETCH;
4304168404Spjd		}
4305168404Spjd		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
4306168404Spjd		arc_access(hdr, hash_lock);
4307275811Sdelphij		if (*arc_flags & ARC_FLAG_L2CACHE)
4308275811Sdelphij			hdr->b_flags |= ARC_FLAG_L2CACHE;
4309275811Sdelphij		if (*arc_flags & ARC_FLAG_L2COMPRESS)
4310275811Sdelphij			hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4311168404Spjd		mutex_exit(hash_lock);
4312168404Spjd		ARCSTAT_BUMP(arcstat_hits);
4313286570Smav		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4314286570Smav		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
4315168404Spjd		    data, metadata, hits);
4316168404Spjd
4317168404Spjd		if (done)
4318168404Spjd			done(NULL, buf, private);
4319168404Spjd	} else {
4320168404Spjd		uint64_t size = BP_GET_LSIZE(bp);
4321268075Sdelphij		arc_callback_t *acb;
4322185029Spjd		vdev_t *vd = NULL;
4323247187Smm		uint64_t addr = 0;
4324208373Smm		boolean_t devw = B_FALSE;
4325258389Savg		enum zio_compress b_compress = ZIO_COMPRESS_OFF;
4326286570Smav		int32_t b_asize = 0;
4327168404Spjd
4328168404Spjd		if (hdr == NULL) {
4329168404Spjd			/* this block is not in the cache */
4330268075Sdelphij			arc_buf_hdr_t *exists = NULL;
4331168404Spjd			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
4332168404Spjd			buf = arc_buf_alloc(spa, size, private, type);
4333168404Spjd			hdr = buf->b_hdr;
4334268075Sdelphij			if (!BP_IS_EMBEDDED(bp)) {
4335268075Sdelphij				hdr->b_dva = *BP_IDENTITY(bp);
4336268075Sdelphij				hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
4337268075Sdelphij				exists = buf_hash_insert(hdr, &hash_lock);
4338268075Sdelphij			}
4339268075Sdelphij			if (exists != NULL) {
4340168404Spjd				/* somebody beat us to the hash insert */
4341168404Spjd				mutex_exit(hash_lock);
4342219089Spjd				buf_discard_identity(hdr);
4343168404Spjd				(void) arc_buf_remove_ref(buf, private);
4344168404Spjd				goto top; /* restart the IO request */
4345168404Spjd			}
4346275811Sdelphij
4347168404Spjd			/* if this is a prefetch, we don't have a reference */
4348275811Sdelphij			if (*arc_flags & ARC_FLAG_PREFETCH) {
4349168404Spjd				(void) remove_reference(hdr, hash_lock,
4350168404Spjd				    private);
4351275811Sdelphij				hdr->b_flags |= ARC_FLAG_PREFETCH;
4352168404Spjd			}
4353275811Sdelphij			if (*arc_flags & ARC_FLAG_L2CACHE)
4354275811Sdelphij				hdr->b_flags |= ARC_FLAG_L2CACHE;
4355275811Sdelphij			if (*arc_flags & ARC_FLAG_L2COMPRESS)
4356275811Sdelphij				hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4357168404Spjd			if (BP_GET_LEVEL(bp) > 0)
4358275811Sdelphij				hdr->b_flags |= ARC_FLAG_INDIRECT;
4359168404Spjd		} else {
4360286570Smav			/*
4361286570Smav			 * This block is in the ghost cache. If it was L2-only
4362286570Smav			 * (and thus didn't have an L1 hdr), we realloc the
4363286570Smav			 * header to add an L1 hdr.
4364286570Smav			 */
4365286570Smav			if (!HDR_HAS_L1HDR(hdr)) {
4366286570Smav				hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
4367286570Smav				    hdr_full_cache);
4368286570Smav			}
4369286570Smav
4370286570Smav			ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
4371168404Spjd			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4372286570Smav			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4373286763Smav			ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
4374168404Spjd
4375168404Spjd			/* if this is a prefetch, we don't have a reference */
4376275811Sdelphij			if (*arc_flags & ARC_FLAG_PREFETCH)
4377275811Sdelphij				hdr->b_flags |= ARC_FLAG_PREFETCH;
4378168404Spjd			else
4379168404Spjd				add_reference(hdr, hash_lock, private);
4380275811Sdelphij			if (*arc_flags & ARC_FLAG_L2CACHE)
4381275811Sdelphij				hdr->b_flags |= ARC_FLAG_L2CACHE;
4382275811Sdelphij			if (*arc_flags & ARC_FLAG_L2COMPRESS)
4383275811Sdelphij				hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4384185029Spjd			buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
4385168404Spjd			buf->b_hdr = hdr;
4386168404Spjd			buf->b_data = NULL;
4387168404Spjd			buf->b_efunc = NULL;
4388168404Spjd			buf->b_private = NULL;
4389168404Spjd			buf->b_next = NULL;
4390286570Smav			hdr->b_l1hdr.b_buf = buf;
4391286570Smav			ASSERT0(hdr->b_l1hdr.b_datacnt);
4392286570Smav			hdr->b_l1hdr.b_datacnt = 1;
4393219089Spjd			arc_get_data_buf(buf);
4394219089Spjd			arc_access(hdr, hash_lock);
4395168404Spjd		}
4396168404Spjd
4397286570Smav		ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
4398219089Spjd
4399168404Spjd		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
4400168404Spjd		acb->acb_done = done;
4401168404Spjd		acb->acb_private = private;
4402168404Spjd
4403286570Smav		ASSERT(hdr->b_l1hdr.b_acb == NULL);
4404286570Smav		hdr->b_l1hdr.b_acb = acb;
4405275811Sdelphij		hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
4406168404Spjd
4407286570Smav		if (HDR_HAS_L2HDR(hdr) &&
4408286570Smav		    (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
4409286570Smav			devw = hdr->b_l2hdr.b_dev->l2ad_writing;
4410286570Smav			addr = hdr->b_l2hdr.b_daddr;
4411286570Smav			b_compress = HDR_GET_COMPRESS(hdr);
4412286570Smav			b_asize = hdr->b_l2hdr.b_asize;
4413185029Spjd			/*
4414185029Spjd			 * Lock out device removal.
4415185029Spjd			 */
4416185029Spjd			if (vdev_is_dead(vd) ||
4417185029Spjd			    !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
4418185029Spjd				vd = NULL;
4419185029Spjd		}
4420185029Spjd
4421268075Sdelphij		if (hash_lock != NULL)
4422268075Sdelphij			mutex_exit(hash_lock);
4423168404Spjd
4424251629Sdelphij		/*
4425251629Sdelphij		 * At this point, we have a level 1 cache miss.  Try again in
4426251629Sdelphij		 * L2ARC if possible.
4427251629Sdelphij		 */
4428168404Spjd		ASSERT3U(hdr->b_size, ==, size);
4429219089Spjd		DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
4430268123Sdelphij		    uint64_t, size, zbookmark_phys_t *, zb);
4431168404Spjd		ARCSTAT_BUMP(arcstat_misses);
4432286570Smav		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4433286570Smav		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
4434168404Spjd		    data, metadata, misses);
4435228392Spjd#ifdef _KERNEL
4436228392Spjd		curthread->td_ru.ru_inblock++;
4437228392Spjd#endif
4438168404Spjd
4439208373Smm		if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
4440185029Spjd			/*
4441185029Spjd			 * Read from the L2ARC if the following are true:
4442185029Spjd			 * 1. The L2ARC vdev was previously cached.
4443185029Spjd			 * 2. This buffer still has L2ARC metadata.
4444185029Spjd			 * 3. This buffer isn't currently writing to the L2ARC.
4445185029Spjd			 * 4. The L2ARC entry wasn't evicted, which may
4446185029Spjd			 *    also have invalidated the vdev.
4447208373Smm			 * 5. This isn't prefetch and l2arc_noprefetch is set.
4448185029Spjd			 */
4449286570Smav			if (HDR_HAS_L2HDR(hdr) &&
4450208373Smm			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
4451208373Smm			    !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
4452185029Spjd				l2arc_read_callback_t *cb;
4453185029Spjd
4454185029Spjd				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
4455185029Spjd				ARCSTAT_BUMP(arcstat_l2_hits);
4456185029Spjd
4457185029Spjd				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
4458185029Spjd				    KM_SLEEP);
4459185029Spjd				cb->l2rcb_buf = buf;
4460185029Spjd				cb->l2rcb_spa = spa;
4461185029Spjd				cb->l2rcb_bp = *bp;
4462185029Spjd				cb->l2rcb_zb = *zb;
4463185029Spjd				cb->l2rcb_flags = zio_flags;
4464258389Savg				cb->l2rcb_compress = b_compress;
4465185029Spjd
4466247187Smm				ASSERT(addr >= VDEV_LABEL_START_SIZE &&
4467247187Smm				    addr + size < vd->vdev_psize -
4468247187Smm				    VDEV_LABEL_END_SIZE);
4469247187Smm
4470185029Spjd				/*
4471185029Spjd				 * l2arc read.  The SCL_L2ARC lock will be
4472185029Spjd				 * released by l2arc_read_done().
4473251478Sdelphij				 * Issue a null zio if the underlying buffer
4474251478Sdelphij				 * was squashed to zero size by compression.
4475185029Spjd				 */
4476258389Savg				if (b_compress == ZIO_COMPRESS_EMPTY) {
4477251478Sdelphij					rzio = zio_null(pio, spa, vd,
4478251478Sdelphij					    l2arc_read_done, cb,
4479251478Sdelphij					    zio_flags | ZIO_FLAG_DONT_CACHE |
4480251478Sdelphij					    ZIO_FLAG_CANFAIL |
4481251478Sdelphij					    ZIO_FLAG_DONT_PROPAGATE |
4482251478Sdelphij					    ZIO_FLAG_DONT_RETRY);
4483251478Sdelphij				} else {
4484251478Sdelphij					rzio = zio_read_phys(pio, vd, addr,
4485258389Savg					    b_asize, buf->b_data,
4486258389Savg					    ZIO_CHECKSUM_OFF,
4487251478Sdelphij					    l2arc_read_done, cb, priority,
4488251478Sdelphij					    zio_flags | ZIO_FLAG_DONT_CACHE |
4489251478Sdelphij					    ZIO_FLAG_CANFAIL |
4490251478Sdelphij					    ZIO_FLAG_DONT_PROPAGATE |
4491251478Sdelphij					    ZIO_FLAG_DONT_RETRY, B_FALSE);
4492251478Sdelphij				}
4493185029Spjd				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
4494185029Spjd				    zio_t *, rzio);
4495258389Savg				ARCSTAT_INCR(arcstat_l2_read_bytes, b_asize);
4496185029Spjd
4497275811Sdelphij				if (*arc_flags & ARC_FLAG_NOWAIT) {
4498185029Spjd					zio_nowait(rzio);
4499185029Spjd					return (0);
4500185029Spjd				}
4501185029Spjd
4502275811Sdelphij				ASSERT(*arc_flags & ARC_FLAG_WAIT);
4503185029Spjd				if (zio_wait(rzio) == 0)
4504185029Spjd					return (0);
4505185029Spjd
4506185029Spjd				/* l2arc read error; goto zio_read() */
4507185029Spjd			} else {
4508185029Spjd				DTRACE_PROBE1(l2arc__miss,
4509185029Spjd				    arc_buf_hdr_t *, hdr);
4510185029Spjd				ARCSTAT_BUMP(arcstat_l2_misses);
4511185029Spjd				if (HDR_L2_WRITING(hdr))
4512185029Spjd					ARCSTAT_BUMP(arcstat_l2_rw_clash);
4513185029Spjd				spa_config_exit(spa, SCL_L2ARC, vd);
4514185029Spjd			}
4515208373Smm		} else {
4516208373Smm			if (vd != NULL)
4517208373Smm				spa_config_exit(spa, SCL_L2ARC, vd);
4518208373Smm			if (l2arc_ndev != 0) {
4519208373Smm				DTRACE_PROBE1(l2arc__miss,
4520208373Smm				    arc_buf_hdr_t *, hdr);
4521208373Smm				ARCSTAT_BUMP(arcstat_l2_misses);
4522208373Smm			}
4523185029Spjd		}
4524185029Spjd
4525168404Spjd		rzio = zio_read(pio, spa, bp, buf->b_data, size,
4526185029Spjd		    arc_read_done, buf, priority, zio_flags, zb);
4527168404Spjd
4528275811Sdelphij		if (*arc_flags & ARC_FLAG_WAIT)
4529168404Spjd			return (zio_wait(rzio));
4530168404Spjd
4531275811Sdelphij		ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
4532168404Spjd		zio_nowait(rzio);
4533168404Spjd	}
4534168404Spjd	return (0);
4535168404Spjd}
4536168404Spjd
4537168404Spjdvoid
4538168404Spjdarc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
4539168404Spjd{
4540168404Spjd	ASSERT(buf->b_hdr != NULL);
4541286570Smav	ASSERT(buf->b_hdr->b_l1hdr.b_state != arc_anon);
4542286570Smav	ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt) ||
4543286570Smav	    func == NULL);
4544219089Spjd	ASSERT(buf->b_efunc == NULL);
4545219089Spjd	ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
4546219089Spjd
4547168404Spjd	buf->b_efunc = func;
4548168404Spjd	buf->b_private = private;
4549168404Spjd}
4550168404Spjd
4551168404Spjd/*
4552251520Sdelphij * Notify the arc that a block was freed, and thus will never be used again.
4553251520Sdelphij */
4554251520Sdelphijvoid
4555251520Sdelphijarc_freed(spa_t *spa, const blkptr_t *bp)
4556251520Sdelphij{
4557251520Sdelphij	arc_buf_hdr_t *hdr;
4558251520Sdelphij	kmutex_t *hash_lock;
4559251520Sdelphij	uint64_t guid = spa_load_guid(spa);
4560251520Sdelphij
4561268075Sdelphij	ASSERT(!BP_IS_EMBEDDED(bp));
4562268075Sdelphij
4563268075Sdelphij	hdr = buf_hash_find(guid, bp, &hash_lock);
4564251520Sdelphij	if (hdr == NULL)
4565251520Sdelphij		return;
4566251520Sdelphij	if (HDR_BUF_AVAILABLE(hdr)) {
4567286570Smav		arc_buf_t *buf = hdr->b_l1hdr.b_buf;
4568251520Sdelphij		add_reference(hdr, hash_lock, FTAG);
4569275811Sdelphij		hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
4570251520Sdelphij		mutex_exit(hash_lock);
4571251520Sdelphij
4572251520Sdelphij		arc_release(buf, FTAG);
4573251520Sdelphij		(void) arc_buf_remove_ref(buf, FTAG);
4574251520Sdelphij	} else {
4575251520Sdelphij		mutex_exit(hash_lock);
4576251520Sdelphij	}
4577251520Sdelphij
4578251520Sdelphij}
4579251520Sdelphij
4580251520Sdelphij/*
4581268858Sdelphij * Clear the user eviction callback set by arc_set_callback(), first calling
4582268858Sdelphij * it if it exists.  Because the presence of a callback keeps an arc_buf cached
4583268858Sdelphij * clearing the callback may result in the arc_buf being destroyed.  However,
4584268858Sdelphij * it will not result in the *last* arc_buf being destroyed, hence the data
4585268858Sdelphij * will remain cached in the ARC. We make a copy of the arc buffer here so
4586268858Sdelphij * that we can process the callback without holding any locks.
4587268858Sdelphij *
4588268858Sdelphij * It's possible that the callback is already in the process of being cleared
4589268858Sdelphij * by another thread.  In this case we can not clear the callback.
4590268858Sdelphij *
4591268858Sdelphij * Returns B_TRUE if the callback was successfully called and cleared.
4592168404Spjd */
4593268858Sdelphijboolean_t
4594268858Sdelphijarc_clear_callback(arc_buf_t *buf)
4595168404Spjd{
4596168404Spjd	arc_buf_hdr_t *hdr;
4597168404Spjd	kmutex_t *hash_lock;
4598268858Sdelphij	arc_evict_func_t *efunc = buf->b_efunc;
4599268858Sdelphij	void *private = buf->b_private;
4600206796Spjd
4601219089Spjd	mutex_enter(&buf->b_evict_lock);
4602168404Spjd	hdr = buf->b_hdr;
4603168404Spjd	if (hdr == NULL) {
4604168404Spjd		/*
4605168404Spjd		 * We are in arc_do_user_evicts().
4606168404Spjd		 */
4607168404Spjd		ASSERT(buf->b_data == NULL);
4608219089Spjd		mutex_exit(&buf->b_evict_lock);
4609268858Sdelphij		return (B_FALSE);
4610185029Spjd	} else if (buf->b_data == NULL) {
4611185029Spjd		/*
4612185029Spjd		 * We are on the eviction list; process this buffer now
4613185029Spjd		 * but let arc_do_user_evicts() do the reaping.
4614185029Spjd		 */
4615185029Spjd		buf->b_efunc = NULL;
4616219089Spjd		mutex_exit(&buf->b_evict_lock);
4617268858Sdelphij		VERIFY0(efunc(private));
4618268858Sdelphij		return (B_TRUE);
4619168404Spjd	}
4620168404Spjd	hash_lock = HDR_LOCK(hdr);
4621168404Spjd	mutex_enter(hash_lock);
4622219089Spjd	hdr = buf->b_hdr;
4623219089Spjd	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4624168404Spjd
4625286570Smav	ASSERT3U(refcount_count(&hdr->b_l1hdr.b_refcnt), <,
4626286570Smav	    hdr->b_l1hdr.b_datacnt);
4627286570Smav	ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
4628286570Smav	    hdr->b_l1hdr.b_state == arc_mfu);
4629168404Spjd
4630268858Sdelphij	buf->b_efunc = NULL;
4631268858Sdelphij	buf->b_private = NULL;
4632168404Spjd
4633286570Smav	if (hdr->b_l1hdr.b_datacnt > 1) {
4634268858Sdelphij		mutex_exit(&buf->b_evict_lock);
4635286763Smav		arc_buf_destroy(buf, TRUE);
4636268858Sdelphij	} else {
4637286570Smav		ASSERT(buf == hdr->b_l1hdr.b_buf);
4638275811Sdelphij		hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
4639268858Sdelphij		mutex_exit(&buf->b_evict_lock);
4640268858Sdelphij	}
4641168404Spjd
4642168404Spjd	mutex_exit(hash_lock);
4643268858Sdelphij	VERIFY0(efunc(private));
4644268858Sdelphij	return (B_TRUE);
4645168404Spjd}
4646168404Spjd
4647168404Spjd/*
4648251629Sdelphij * Release this buffer from the cache, making it an anonymous buffer.  This
4649251629Sdelphij * must be done after a read and prior to modifying the buffer contents.
4650168404Spjd * If the buffer has more than one reference, we must make
4651185029Spjd * a new hdr for the buffer.
4652168404Spjd */
4653168404Spjdvoid
4654168404Spjdarc_release(arc_buf_t *buf, void *tag)
4655168404Spjd{
4656286570Smav	arc_buf_hdr_t *hdr = buf->b_hdr;
4657168404Spjd
4658286763Smav	ASSERT(HDR_HAS_L1HDR(hdr));
4659286763Smav
4660219089Spjd	/*
4661219089Spjd	 * It would be nice to assert that if it's DMU metadata (level >
4662219089Spjd	 * 0 || it's the dnode file), then it must be syncing context.
4663219089Spjd	 * But we don't know that information at this level.
4664219089Spjd	 */
4665219089Spjd
4666219089Spjd	mutex_enter(&buf->b_evict_lock);
4667286570Smav	/*
4668286570Smav	 * We don't grab the hash lock prior to this check, because if
4669286570Smav	 * the buffer's header is in the arc_anon state, it won't be
4670286570Smav	 * linked into the hash table.
4671286570Smav	 */
4672286570Smav	if (hdr->b_l1hdr.b_state == arc_anon) {
4673286570Smav		mutex_exit(&buf->b_evict_lock);
4674286570Smav		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4675286570Smav		ASSERT(!HDR_IN_HASH_TABLE(hdr));
4676286570Smav		ASSERT(!HDR_HAS_L2HDR(hdr));
4677286570Smav		ASSERT(BUF_EMPTY(hdr));
4678286570Smav		ASSERT3U(hdr->b_l1hdr.b_datacnt, ==, 1);
4679286570Smav		ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
4680286570Smav		ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
4681185029Spjd
4682286570Smav		ASSERT3P(buf->b_efunc, ==, NULL);
4683286570Smav		ASSERT3P(buf->b_private, ==, NULL);
4684168404Spjd
4685286570Smav		hdr->b_l1hdr.b_arc_access = 0;
4686286570Smav		arc_buf_thaw(buf);
4687286570Smav
4688286570Smav		return;
4689168404Spjd	}
4690168404Spjd
4691286570Smav	kmutex_t *hash_lock = HDR_LOCK(hdr);
4692286570Smav	mutex_enter(hash_lock);
4693286570Smav
4694286570Smav	/*
4695286570Smav	 * This assignment is only valid as long as the hash_lock is
4696286570Smav	 * held, we must be careful not to reference state or the
4697286570Smav	 * b_state field after dropping the lock.
4698286570Smav	 */
4699286570Smav	arc_state_t *state = hdr->b_l1hdr.b_state;
4700286570Smav	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4701286570Smav	ASSERT3P(state, !=, arc_anon);
4702286570Smav
4703286570Smav	/* this buffer is not on any list */
4704286570Smav	ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) > 0);
4705286570Smav
4706286570Smav	if (HDR_HAS_L2HDR(hdr)) {
4707286570Smav		mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
4708286570Smav
4709286570Smav		/*
4710286598Smav		 * We have to recheck this conditional again now that
4711286598Smav		 * we're holding the l2ad_mtx to prevent a race with
4712286598Smav		 * another thread which might be concurrently calling
4713286598Smav		 * l2arc_evict(). In that case, l2arc_evict() might have
4714286598Smav		 * destroyed the header's L2 portion as we were waiting
4715286598Smav		 * to acquire the l2ad_mtx.
4716286570Smav		 */
4717286598Smav		if (HDR_HAS_L2HDR(hdr)) {
4718286647Smav			if (hdr->b_l2hdr.b_daddr != L2ARC_ADDR_UNSET)
4719286647Smav				trim_map_free(hdr->b_l2hdr.b_dev->l2ad_vdev,
4720286647Smav				    hdr->b_l2hdr.b_daddr,
4721286647Smav				    hdr->b_l2hdr.b_asize, 0);
4722286598Smav			arc_hdr_l2hdr_destroy(hdr);
4723286598Smav		}
4724286570Smav
4725286570Smav		mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
4726185029Spjd	}
4727185029Spjd
4728168404Spjd	/*
4729168404Spjd	 * Do we have more than one buf?
4730168404Spjd	 */
4731286570Smav	if (hdr->b_l1hdr.b_datacnt > 1) {
4732168404Spjd		arc_buf_hdr_t *nhdr;
4733168404Spjd		arc_buf_t **bufp;
4734168404Spjd		uint64_t blksz = hdr->b_size;
4735209962Smm		uint64_t spa = hdr->b_spa;
4736286570Smav		arc_buf_contents_t type = arc_buf_type(hdr);
4737185029Spjd		uint32_t flags = hdr->b_flags;
4738168404Spjd
4739286570Smav		ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
4740168404Spjd		/*
4741219089Spjd		 * Pull the data off of this hdr and attach it to
4742219089Spjd		 * a new anonymous hdr.
4743168404Spjd		 */
4744168404Spjd		(void) remove_reference(hdr, hash_lock, tag);
4745286570Smav		bufp = &hdr->b_l1hdr.b_buf;
4746168404Spjd		while (*bufp != buf)
4747168404Spjd			bufp = &(*bufp)->b_next;
4748219089Spjd		*bufp = buf->b_next;
4749168404Spjd		buf->b_next = NULL;
4750168404Spjd
4751286570Smav		ASSERT3P(state, !=, arc_l2c_only);
4752286766Smav
4753286766Smav		(void) refcount_remove_many(
4754286766Smav		    &state->arcs_size, hdr->b_size, buf);
4755286766Smav
4756286570Smav		if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
4757286570Smav			ASSERT3P(state, !=, arc_l2c_only);
4758286570Smav			uint64_t *size = &state->arcs_lsize[type];
4759185029Spjd			ASSERT3U(*size, >=, hdr->b_size);
4760185029Spjd			atomic_add_64(size, -hdr->b_size);
4761168404Spjd		}
4762242845Sdelphij
4763242845Sdelphij		/*
4764242845Sdelphij		 * We're releasing a duplicate user data buffer, update
4765242845Sdelphij		 * our statistics accordingly.
4766242845Sdelphij		 */
4767286570Smav		if (HDR_ISTYPE_DATA(hdr)) {
4768242845Sdelphij			ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
4769242845Sdelphij			ARCSTAT_INCR(arcstat_duplicate_buffers_size,
4770242845Sdelphij			    -hdr->b_size);
4771242845Sdelphij		}
4772286570Smav		hdr->b_l1hdr.b_datacnt -= 1;
4773168404Spjd		arc_cksum_verify(buf);
4774240133Smm#ifdef illumos
4775240133Smm		arc_buf_unwatch(buf);
4776277300Ssmh#endif
4777168404Spjd
4778168404Spjd		mutex_exit(hash_lock);
4779168404Spjd
4780286570Smav		nhdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
4781168404Spjd		nhdr->b_size = blksz;
4782168404Spjd		nhdr->b_spa = spa;
4783286570Smav
4784275811Sdelphij		nhdr->b_flags = flags & ARC_FLAG_L2_WRITING;
4785286570Smav		nhdr->b_flags |= arc_bufc_to_flags(type);
4786286570Smav		nhdr->b_flags |= ARC_FLAG_HAS_L1HDR;
4787286570Smav
4788286570Smav		nhdr->b_l1hdr.b_buf = buf;
4789286570Smav		nhdr->b_l1hdr.b_datacnt = 1;
4790286570Smav		nhdr->b_l1hdr.b_state = arc_anon;
4791286570Smav		nhdr->b_l1hdr.b_arc_access = 0;
4792286763Smav		nhdr->b_l1hdr.b_tmp_cdata = NULL;
4793168404Spjd		nhdr->b_freeze_cksum = NULL;
4794286570Smav
4795286570Smav		(void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
4796168404Spjd		buf->b_hdr = nhdr;
4797219089Spjd		mutex_exit(&buf->b_evict_lock);
4798286766Smav		(void) refcount_add_many(&arc_anon->arcs_size, blksz, buf);
4799168404Spjd	} else {
4800219089Spjd		mutex_exit(&buf->b_evict_lock);
4801286570Smav		ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
4802286763Smav		/* protected by hash lock, or hdr is on arc_anon */
4803286763Smav		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
4804168404Spjd		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4805286570Smav		arc_change_state(arc_anon, hdr, hash_lock);
4806286570Smav		hdr->b_l1hdr.b_arc_access = 0;
4807286570Smav		mutex_exit(hash_lock);
4808185029Spjd
4809219089Spjd		buf_discard_identity(hdr);
4810168404Spjd		arc_buf_thaw(buf);
4811168404Spjd	}
4812168404Spjd	buf->b_efunc = NULL;
4813168404Spjd	buf->b_private = NULL;
4814168404Spjd}
4815168404Spjd
4816168404Spjdint
4817168404Spjdarc_released(arc_buf_t *buf)
4818168404Spjd{
4819185029Spjd	int released;
4820185029Spjd
4821219089Spjd	mutex_enter(&buf->b_evict_lock);
4822286570Smav	released = (buf->b_data != NULL &&
4823286570Smav	    buf->b_hdr->b_l1hdr.b_state == arc_anon);
4824219089Spjd	mutex_exit(&buf->b_evict_lock);
4825185029Spjd	return (released);
4826168404Spjd}
4827168404Spjd
4828168404Spjd#ifdef ZFS_DEBUG
4829168404Spjdint
4830168404Spjdarc_referenced(arc_buf_t *buf)
4831168404Spjd{
4832185029Spjd	int referenced;
4833185029Spjd
4834219089Spjd	mutex_enter(&buf->b_evict_lock);
4835286570Smav	referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
4836219089Spjd	mutex_exit(&buf->b_evict_lock);
4837185029Spjd	return (referenced);
4838168404Spjd}
4839168404Spjd#endif
4840168404Spjd
4841168404Spjdstatic void
4842168404Spjdarc_write_ready(zio_t *zio)
4843168404Spjd{
4844168404Spjd	arc_write_callback_t *callback = zio->io_private;
4845168404Spjd	arc_buf_t *buf = callback->awcb_buf;
4846185029Spjd	arc_buf_hdr_t *hdr = buf->b_hdr;
4847168404Spjd
4848286570Smav	ASSERT(HDR_HAS_L1HDR(hdr));
4849286570Smav	ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
4850286570Smav	ASSERT(hdr->b_l1hdr.b_datacnt > 0);
4851185029Spjd	callback->awcb_ready(zio, buf, callback->awcb_private);
4852185029Spjd
4853185029Spjd	/*
4854185029Spjd	 * If the IO is already in progress, then this is a re-write
4855185029Spjd	 * attempt, so we need to thaw and re-compute the cksum.
4856185029Spjd	 * It is the responsibility of the callback to handle the
4857185029Spjd	 * accounting for any re-write attempt.
4858185029Spjd	 */
4859185029Spjd	if (HDR_IO_IN_PROGRESS(hdr)) {
4860286570Smav		mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
4861185029Spjd		if (hdr->b_freeze_cksum != NULL) {
4862185029Spjd			kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
4863185029Spjd			hdr->b_freeze_cksum = NULL;
4864185029Spjd		}
4865286570Smav		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
4866168404Spjd	}
4867185029Spjd	arc_cksum_compute(buf, B_FALSE);
4868275811Sdelphij	hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
4869168404Spjd}
4870168404Spjd
4871258632Savg/*
4872258632Savg * The SPA calls this callback for each physical write that happens on behalf
4873258632Savg * of a logical write.  See the comment in dbuf_write_physdone() for details.
4874258632Savg */
4875168404Spjdstatic void
4876258632Savgarc_write_physdone(zio_t *zio)
4877258632Savg{
4878258632Savg	arc_write_callback_t *cb = zio->io_private;
4879258632Savg	if (cb->awcb_physdone != NULL)
4880258632Savg		cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
4881258632Savg}
4882258632Savg
4883258632Savgstatic void
4884168404Spjdarc_write_done(zio_t *zio)
4885168404Spjd{
4886168404Spjd	arc_write_callback_t *callback = zio->io_private;
4887168404Spjd	arc_buf_t *buf = callback->awcb_buf;
4888168404Spjd	arc_buf_hdr_t *hdr = buf->b_hdr;
4889168404Spjd
4890286570Smav	ASSERT(hdr->b_l1hdr.b_acb == NULL);
4891168404Spjd
4892219089Spjd	if (zio->io_error == 0) {
4893268075Sdelphij		if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
4894260150Sdelphij			buf_discard_identity(hdr);
4895260150Sdelphij		} else {
4896260150Sdelphij			hdr->b_dva = *BP_IDENTITY(zio->io_bp);
4897260150Sdelphij			hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
4898260150Sdelphij		}
4899219089Spjd	} else {
4900219089Spjd		ASSERT(BUF_EMPTY(hdr));
4901219089Spjd	}
4902219089Spjd
4903168404Spjd	/*
4904268075Sdelphij	 * If the block to be written was all-zero or compressed enough to be
4905268075Sdelphij	 * embedded in the BP, no write was performed so there will be no
4906268075Sdelphij	 * dva/birth/checksum.  The buffer must therefore remain anonymous
4907268075Sdelphij	 * (and uncached).
4908168404Spjd	 */
4909168404Spjd	if (!BUF_EMPTY(hdr)) {
4910168404Spjd		arc_buf_hdr_t *exists;
4911168404Spjd		kmutex_t *hash_lock;
4912168404Spjd
4913219089Spjd		ASSERT(zio->io_error == 0);
4914219089Spjd
4915168404Spjd		arc_cksum_verify(buf);
4916168404Spjd
4917168404Spjd		exists = buf_hash_insert(hdr, &hash_lock);
4918286570Smav		if (exists != NULL) {
4919168404Spjd			/*
4920168404Spjd			 * This can only happen if we overwrite for
4921168404Spjd			 * sync-to-convergence, because we remove
4922168404Spjd			 * buffers from the hash table when we arc_free().
4923168404Spjd			 */
4924219089Spjd			if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
4925219089Spjd				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
4926219089Spjd					panic("bad overwrite, hdr=%p exists=%p",
4927219089Spjd					    (void *)hdr, (void *)exists);
4928286570Smav				ASSERT(refcount_is_zero(
4929286570Smav				    &exists->b_l1hdr.b_refcnt));
4930219089Spjd				arc_change_state(arc_anon, exists, hash_lock);
4931219089Spjd				mutex_exit(hash_lock);
4932219089Spjd				arc_hdr_destroy(exists);
4933219089Spjd				exists = buf_hash_insert(hdr, &hash_lock);
4934219089Spjd				ASSERT3P(exists, ==, NULL);
4935243524Smm			} else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
4936243524Smm				/* nopwrite */
4937243524Smm				ASSERT(zio->io_prop.zp_nopwrite);
4938243524Smm				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
4939243524Smm					panic("bad nopwrite, hdr=%p exists=%p",
4940243524Smm					    (void *)hdr, (void *)exists);
4941219089Spjd			} else {
4942219089Spjd				/* Dedup */
4943286570Smav				ASSERT(hdr->b_l1hdr.b_datacnt == 1);
4944286570Smav				ASSERT(hdr->b_l1hdr.b_state == arc_anon);
4945219089Spjd				ASSERT(BP_GET_DEDUP(zio->io_bp));
4946219089Spjd				ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
4947219089Spjd			}
4948168404Spjd		}
4949275811Sdelphij		hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
4950185029Spjd		/* if it's not anon, we are doing a scrub */
4951286570Smav		if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
4952185029Spjd			arc_access(hdr, hash_lock);
4953168404Spjd		mutex_exit(hash_lock);
4954168404Spjd	} else {
4955275811Sdelphij		hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
4956168404Spjd	}
4957168404Spjd
4958286570Smav	ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4959219089Spjd	callback->awcb_done(zio, buf, callback->awcb_private);
4960168404Spjd
4961168404Spjd	kmem_free(callback, sizeof (arc_write_callback_t));
4962168404Spjd}
4963168404Spjd
4964168404Spjdzio_t *
4965219089Spjdarc_write(zio_t *pio, spa_t *spa, uint64_t txg,
4966251478Sdelphij    blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
4967258632Savg    const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *physdone,
4968258632Savg    arc_done_func_t *done, void *private, zio_priority_t priority,
4969268123Sdelphij    int zio_flags, const zbookmark_phys_t *zb)
4970168404Spjd{
4971168404Spjd	arc_buf_hdr_t *hdr = buf->b_hdr;
4972168404Spjd	arc_write_callback_t *callback;
4973185029Spjd	zio_t *zio;
4974168404Spjd
4975185029Spjd	ASSERT(ready != NULL);
4976219089Spjd	ASSERT(done != NULL);
4977168404Spjd	ASSERT(!HDR_IO_ERROR(hdr));
4978286570Smav	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4979286570Smav	ASSERT(hdr->b_l1hdr.b_acb == NULL);
4980286570Smav	ASSERT(hdr->b_l1hdr.b_datacnt > 0);
4981185029Spjd	if (l2arc)
4982275811Sdelphij		hdr->b_flags |= ARC_FLAG_L2CACHE;
4983251478Sdelphij	if (l2arc_compress)
4984275811Sdelphij		hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4985168404Spjd	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
4986168404Spjd	callback->awcb_ready = ready;
4987258632Savg	callback->awcb_physdone = physdone;
4988168404Spjd	callback->awcb_done = done;
4989168404Spjd	callback->awcb_private = private;
4990168404Spjd	callback->awcb_buf = buf;
4991168404Spjd
4992219089Spjd	zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
4993258632Savg	    arc_write_ready, arc_write_physdone, arc_write_done, callback,
4994258632Savg	    priority, zio_flags, zb);
4995185029Spjd
4996168404Spjd	return (zio);
4997168404Spjd}
4998168404Spjd
4999185029Spjdstatic int
5000258632Savgarc_memory_throttle(uint64_t reserve, uint64_t txg)
5001185029Spjd{
5002185029Spjd#ifdef _KERNEL
5003272483Ssmh	uint64_t available_memory = ptob(freemem);
5004185029Spjd	static uint64_t page_load = 0;
5005185029Spjd	static uint64_t last_txg = 0;
5006185029Spjd
5007272483Ssmh#if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
5008185029Spjd	available_memory =
5009272483Ssmh	    MIN(available_memory, ptob(vmem_size(heap_arena, VMEM_FREE)));
5010185029Spjd#endif
5011258632Savg
5012272483Ssmh	if (freemem > (uint64_t)physmem * arc_lotsfree_percent / 100)
5013185029Spjd		return (0);
5014185029Spjd
5015185029Spjd	if (txg > last_txg) {
5016185029Spjd		last_txg = txg;
5017185029Spjd		page_load = 0;
5018185029Spjd	}
5019185029Spjd	/*
5020185029Spjd	 * If we are in pageout, we know that memory is already tight,
5021185029Spjd	 * the arc is already going to be evicting, so we just want to
5022185029Spjd	 * continue to let page writes occur as quickly as possible.
5023185029Spjd	 */
5024185029Spjd	if (curproc == pageproc) {
5025272483Ssmh		if (page_load > MAX(ptob(minfree), available_memory) / 4)
5026249195Smm			return (SET_ERROR(ERESTART));
5027185029Spjd		/* Note: reserve is inflated, so we deflate */
5028185029Spjd		page_load += reserve / 8;
5029185029Spjd		return (0);
5030185029Spjd	} else if (page_load > 0 && arc_reclaim_needed()) {
5031185029Spjd		/* memory is low, delay before restarting */
5032185029Spjd		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
5033249195Smm		return (SET_ERROR(EAGAIN));
5034185029Spjd	}
5035185029Spjd	page_load = 0;
5036185029Spjd#endif
5037185029Spjd	return (0);
5038185029Spjd}
5039185029Spjd
5040168404Spjdvoid
5041185029Spjdarc_tempreserve_clear(uint64_t reserve)
5042168404Spjd{
5043185029Spjd	atomic_add_64(&arc_tempreserve, -reserve);
5044168404Spjd	ASSERT((int64_t)arc_tempreserve >= 0);
5045168404Spjd}
5046168404Spjd
5047168404Spjdint
5048185029Spjdarc_tempreserve_space(uint64_t reserve, uint64_t txg)
5049168404Spjd{
5050185029Spjd	int error;
5051209962Smm	uint64_t anon_size;
5052185029Spjd
5053272483Ssmh	if (reserve > arc_c/4 && !arc_no_grow) {
5054185029Spjd		arc_c = MIN(arc_c_max, reserve * 4);
5055272483Ssmh		DTRACE_PROBE1(arc__set_reserve, uint64_t, arc_c);
5056272483Ssmh	}
5057185029Spjd	if (reserve > arc_c)
5058249195Smm		return (SET_ERROR(ENOMEM));
5059168404Spjd
5060168404Spjd	/*
5061209962Smm	 * Don't count loaned bufs as in flight dirty data to prevent long
5062209962Smm	 * network delays from blocking transactions that are ready to be
5063209962Smm	 * assigned to a txg.
5064209962Smm	 */
5065286766Smav	anon_size = MAX((int64_t)(refcount_count(&arc_anon->arcs_size) -
5066286766Smav	    arc_loaned_bytes), 0);
5067209962Smm
5068209962Smm	/*
5069185029Spjd	 * Writes will, almost always, require additional memory allocations
5070251631Sdelphij	 * in order to compress/encrypt/etc the data.  We therefore need to
5071185029Spjd	 * make sure that there is sufficient available memory for this.
5072185029Spjd	 */
5073258632Savg	error = arc_memory_throttle(reserve, txg);
5074258632Savg	if (error != 0)
5075185029Spjd		return (error);
5076185029Spjd
5077185029Spjd	/*
5078168404Spjd	 * Throttle writes when the amount of dirty data in the cache
5079168404Spjd	 * gets too large.  We try to keep the cache less than half full
5080168404Spjd	 * of dirty blocks so that our sync times don't grow too large.
5081168404Spjd	 * Note: if two requests come in concurrently, we might let them
5082168404Spjd	 * both succeed, when one of them should fail.  Not a huge deal.
5083168404Spjd	 */
5084209962Smm
5085209962Smm	if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
5086209962Smm	    anon_size > arc_c / 4) {
5087185029Spjd		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
5088185029Spjd		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
5089185029Spjd		    arc_tempreserve>>10,
5090185029Spjd		    arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
5091185029Spjd		    arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
5092185029Spjd		    reserve>>10, arc_c>>10);
5093249195Smm		return (SET_ERROR(ERESTART));
5094168404Spjd	}
5095185029Spjd	atomic_add_64(&arc_tempreserve, reserve);
5096168404Spjd	return (0);
5097168404Spjd}
5098168404Spjd
5099286626Smavstatic void
5100286626Smavarc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
5101286626Smav    kstat_named_t *evict_data, kstat_named_t *evict_metadata)
5102286626Smav{
5103286766Smav	size->value.ui64 = refcount_count(&state->arcs_size);
5104286626Smav	evict_data->value.ui64 = state->arcs_lsize[ARC_BUFC_DATA];
5105286626Smav	evict_metadata->value.ui64 = state->arcs_lsize[ARC_BUFC_METADATA];
5106286626Smav}
5107286626Smav
5108286626Smavstatic int
5109286626Smavarc_kstat_update(kstat_t *ksp, int rw)
5110286626Smav{
5111286626Smav	arc_stats_t *as = ksp->ks_data;
5112286626Smav
5113286626Smav	if (rw == KSTAT_WRITE) {
5114286626Smav		return (EACCES);
5115286626Smav	} else {
5116286626Smav		arc_kstat_update_state(arc_anon,
5117286626Smav		    &as->arcstat_anon_size,
5118286626Smav		    &as->arcstat_anon_evictable_data,
5119286626Smav		    &as->arcstat_anon_evictable_metadata);
5120286626Smav		arc_kstat_update_state(arc_mru,
5121286626Smav		    &as->arcstat_mru_size,
5122286626Smav		    &as->arcstat_mru_evictable_data,
5123286626Smav		    &as->arcstat_mru_evictable_metadata);
5124286626Smav		arc_kstat_update_state(arc_mru_ghost,
5125286626Smav		    &as->arcstat_mru_ghost_size,
5126286626Smav		    &as->arcstat_mru_ghost_evictable_data,
5127286626Smav		    &as->arcstat_mru_ghost_evictable_metadata);
5128286626Smav		arc_kstat_update_state(arc_mfu,
5129286626Smav		    &as->arcstat_mfu_size,
5130286626Smav		    &as->arcstat_mfu_evictable_data,
5131286626Smav		    &as->arcstat_mfu_evictable_metadata);
5132286626Smav		arc_kstat_update_state(arc_mfu_ghost,
5133286626Smav		    &as->arcstat_mfu_ghost_size,
5134286626Smav		    &as->arcstat_mfu_ghost_evictable_data,
5135286626Smav		    &as->arcstat_mfu_ghost_evictable_metadata);
5136286626Smav	}
5137286626Smav
5138286626Smav	return (0);
5139286626Smav}
5140286626Smav
5141286763Smav/*
5142286763Smav * This function *must* return indices evenly distributed between all
5143286763Smav * sublists of the multilist. This is needed due to how the ARC eviction
5144286763Smav * code is laid out; arc_evict_state() assumes ARC buffers are evenly
5145286763Smav * distributed between all sublists and uses this assumption when
5146286763Smav * deciding which sublist to evict from and how much to evict from it.
5147286763Smav */
5148286763Smavunsigned int
5149286763Smavarc_state_multilist_index_func(multilist_t *ml, void *obj)
5150286763Smav{
5151286763Smav	arc_buf_hdr_t *hdr = obj;
5152286763Smav
5153286763Smav	/*
5154286763Smav	 * We rely on b_dva to generate evenly distributed index
5155286763Smav	 * numbers using buf_hash below. So, as an added precaution,
5156286763Smav	 * let's make sure we never add empty buffers to the arc lists.
5157286763Smav	 */
5158286763Smav	ASSERT(!BUF_EMPTY(hdr));
5159286763Smav
5160286763Smav	/*
5161286763Smav	 * The assumption here, is the hash value for a given
5162286763Smav	 * arc_buf_hdr_t will remain constant throughout it's lifetime
5163286763Smav	 * (i.e. it's b_spa, b_dva, and b_birth fields don't change).
5164286763Smav	 * Thus, we don't need to store the header's sublist index
5165286763Smav	 * on insertion, as this index can be recalculated on removal.
5166286763Smav	 *
5167286763Smav	 * Also, the low order bits of the hash value are thought to be
5168286763Smav	 * distributed evenly. Otherwise, in the case that the multilist
5169286763Smav	 * has a power of two number of sublists, each sublists' usage
5170286763Smav	 * would not be evenly distributed.
5171286763Smav	 */
5172286763Smav	return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
5173286763Smav	    multilist_get_num_sublists(ml));
5174286763Smav}
5175286763Smav
5176168404Spjd#ifdef _KERNEL
5177168566Spjdstatic eventhandler_tag arc_event_lowmem = NULL;
5178168404Spjd
5179168404Spjdstatic void
5180168566Spjdarc_lowmem(void *arg __unused, int howto __unused)
5181168404Spjd{
5182168404Spjd
5183286763Smav	mutex_enter(&arc_reclaim_lock);
5184286625Smav	/* XXX: Memory deficit should be passed as argument. */
5185286625Smav	needfree = btoc(arc_c >> arc_shrink_shift);
5186272483Ssmh	DTRACE_PROBE(arc__needfree);
5187286763Smav	cv_signal(&arc_reclaim_thread_cv);
5188241773Savg
5189241773Savg	/*
5190241773Savg	 * It is unsafe to block here in arbitrary threads, because we can come
5191241773Savg	 * here from ARC itself and may hold ARC locks and thus risk a deadlock
5192241773Savg	 * with ARC reclaim thread.
5193241773Savg	 */
5194286623Smav	if (curproc == pageproc)
5195286763Smav		(void) cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
5196286763Smav	mutex_exit(&arc_reclaim_lock);
5197168404Spjd}
5198168404Spjd#endif
5199168404Spjd
5200168404Spjdvoid
5201168404Spjdarc_init(void)
5202168404Spjd{
5203219089Spjd	int i, prefetch_tunable_set = 0;
5204205231Skmacy
5205286763Smav	mutex_init(&arc_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
5206286763Smav	cv_init(&arc_reclaim_thread_cv, NULL, CV_DEFAULT, NULL);
5207286763Smav	cv_init(&arc_reclaim_waiters_cv, NULL, CV_DEFAULT, NULL);
5208168404Spjd
5209286763Smav	mutex_init(&arc_user_evicts_lock, NULL, MUTEX_DEFAULT, NULL);
5210286763Smav	cv_init(&arc_user_evicts_cv, NULL, CV_DEFAULT, NULL);
5211286763Smav
5212168404Spjd	/* Convert seconds to clock ticks */
5213168404Spjd	arc_min_prefetch_lifespan = 1 * hz;
5214168404Spjd
5215168404Spjd	/* Start out with 1/8 of all memory */
5216168566Spjd	arc_c = kmem_size() / 8;
5217219089Spjd
5218277300Ssmh#ifdef illumos
5219192360Skmacy#ifdef _KERNEL
5220192360Skmacy	/*
5221192360Skmacy	 * On architectures where the physical memory can be larger
5222192360Skmacy	 * than the addressable space (intel in 32-bit mode), we may
5223192360Skmacy	 * need to limit the cache to 1/8 of VM size.
5224192360Skmacy	 */
5225192360Skmacy	arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
5226192360Skmacy#endif
5227277300Ssmh#endif	/* illumos */
5228168566Spjd	/* set min cache to 1/32 of all memory, or 16MB, whichever is more */
5229280822Smav	arc_c_min = MAX(arc_c / 4, 16 << 20);
5230168566Spjd	/* set max to 1/2 of all memory, or all but 1GB, whichever is more */
5231280822Smav	if (arc_c * 8 >= 1 << 30)
5232280822Smav		arc_c_max = (arc_c * 8) - (1 << 30);
5233168404Spjd	else
5234168404Spjd		arc_c_max = arc_c_min;
5235175633Spjd	arc_c_max = MAX(arc_c * 5, arc_c_max);
5236219089Spjd
5237168481Spjd#ifdef _KERNEL
5238168404Spjd	/*
5239168404Spjd	 * Allow the tunables to override our calculations if they are
5240168566Spjd	 * reasonable (ie. over 16MB)
5241168404Spjd	 */
5242280822Smav	if (zfs_arc_max > 16 << 20 && zfs_arc_max < kmem_size())
5243168404Spjd		arc_c_max = zfs_arc_max;
5244280822Smav	if (zfs_arc_min > 16 << 20 && zfs_arc_min <= arc_c_max)
5245168404Spjd		arc_c_min = zfs_arc_min;
5246168481Spjd#endif
5247219089Spjd
5248168404Spjd	arc_c = arc_c_max;
5249168404Spjd	arc_p = (arc_c >> 1);
5250168404Spjd
5251185029Spjd	/* limit meta-data to 1/4 of the arc capacity */
5252185029Spjd	arc_meta_limit = arc_c_max / 4;
5253185029Spjd
5254185029Spjd	/* Allow the tunable to override if it is reasonable */
5255185029Spjd	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
5256185029Spjd		arc_meta_limit = zfs_arc_meta_limit;
5257185029Spjd
5258185029Spjd	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
5259185029Spjd		arc_c_min = arc_meta_limit / 2;
5260185029Spjd
5261275780Sdelphij	if (zfs_arc_meta_min > 0) {
5262275780Sdelphij		arc_meta_min = zfs_arc_meta_min;
5263275780Sdelphij	} else {
5264275780Sdelphij		arc_meta_min = arc_c_min / 2;
5265275780Sdelphij	}
5266275780Sdelphij
5267208373Smm	if (zfs_arc_grow_retry > 0)
5268208373Smm		arc_grow_retry = zfs_arc_grow_retry;
5269208373Smm
5270208373Smm	if (zfs_arc_shrink_shift > 0)
5271208373Smm		arc_shrink_shift = zfs_arc_shrink_shift;
5272208373Smm
5273286625Smav	/*
5274286625Smav	 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
5275286625Smav	 */
5276286625Smav	if (arc_no_grow_shift >= arc_shrink_shift)
5277286625Smav		arc_no_grow_shift = arc_shrink_shift - 1;
5278286625Smav
5279208373Smm	if (zfs_arc_p_min_shift > 0)
5280208373Smm		arc_p_min_shift = zfs_arc_p_min_shift;
5281208373Smm
5282286763Smav	if (zfs_arc_num_sublists_per_state < 1)
5283286763Smav		zfs_arc_num_sublists_per_state = MAX(max_ncpus, 1);
5284286763Smav
5285168404Spjd	/* if kmem_flags are set, lets try to use less memory */
5286168404Spjd	if (kmem_debugging())
5287168404Spjd		arc_c = arc_c / 2;
5288168404Spjd	if (arc_c < arc_c_min)
5289168404Spjd		arc_c = arc_c_min;
5290168404Spjd
5291168473Spjd	zfs_arc_min = arc_c_min;
5292168473Spjd	zfs_arc_max = arc_c_max;
5293168473Spjd
5294168404Spjd	arc_anon = &ARC_anon;
5295168404Spjd	arc_mru = &ARC_mru;
5296168404Spjd	arc_mru_ghost = &ARC_mru_ghost;
5297168404Spjd	arc_mfu = &ARC_mfu;
5298168404Spjd	arc_mfu_ghost = &ARC_mfu_ghost;
5299185029Spjd	arc_l2c_only = &ARC_l2c_only;
5300168404Spjd	arc_size = 0;
5301168404Spjd
5302286763Smav	multilist_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
5303286762Smav	    sizeof (arc_buf_hdr_t),
5304286763Smav	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5305286763Smav	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5306286763Smav	multilist_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
5307286762Smav	    sizeof (arc_buf_hdr_t),
5308286763Smav	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5309286763Smav	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5310286763Smav	multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
5311286762Smav	    sizeof (arc_buf_hdr_t),
5312286763Smav	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5313286763Smav	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5314286763Smav	multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
5315286762Smav	    sizeof (arc_buf_hdr_t),
5316286763Smav	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5317286763Smav	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5318286763Smav	multilist_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
5319286762Smav	    sizeof (arc_buf_hdr_t),
5320286763Smav	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5321286763Smav	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5322286763Smav	multilist_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
5323286762Smav	    sizeof (arc_buf_hdr_t),
5324286763Smav	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5325286763Smav	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5326286763Smav	multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
5327286762Smav	    sizeof (arc_buf_hdr_t),
5328286763Smav	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5329286763Smav	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5330286763Smav	multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
5331286762Smav	    sizeof (arc_buf_hdr_t),
5332286763Smav	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5333286763Smav	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5334286763Smav	multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
5335286762Smav	    sizeof (arc_buf_hdr_t),
5336286763Smav	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5337286763Smav	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5338286763Smav	multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
5339286762Smav	    sizeof (arc_buf_hdr_t),
5340286763Smav	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5341286763Smav	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5342168404Spjd
5343286766Smav	refcount_create(&arc_anon->arcs_size);
5344286766Smav	refcount_create(&arc_mru->arcs_size);
5345286766Smav	refcount_create(&arc_mru_ghost->arcs_size);
5346286766Smav	refcount_create(&arc_mfu->arcs_size);
5347286766Smav	refcount_create(&arc_mfu_ghost->arcs_size);
5348286766Smav	refcount_create(&arc_l2c_only->arcs_size);
5349286766Smav
5350168404Spjd	buf_init();
5351168404Spjd
5352286763Smav	arc_reclaim_thread_exit = FALSE;
5353286763Smav	arc_user_evicts_thread_exit = FALSE;
5354168404Spjd	arc_eviction_list = NULL;
5355168404Spjd	bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
5356168404Spjd
5357168404Spjd	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
5358168404Spjd	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
5359168404Spjd
5360168404Spjd	if (arc_ksp != NULL) {
5361168404Spjd		arc_ksp->ks_data = &arc_stats;
5362286574Smav		arc_ksp->ks_update = arc_kstat_update;
5363168404Spjd		kstat_install(arc_ksp);
5364168404Spjd	}
5365168404Spjd
5366168404Spjd	(void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
5367168404Spjd	    TS_RUN, minclsyspri);
5368168404Spjd
5369168404Spjd#ifdef _KERNEL
5370168566Spjd	arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
5371168404Spjd	    EVENTHANDLER_PRI_FIRST);
5372168404Spjd#endif
5373168404Spjd
5374286763Smav	(void) thread_create(NULL, 0, arc_user_evicts_thread, NULL, 0, &p0,
5375286763Smav	    TS_RUN, minclsyspri);
5376286763Smav
5377168404Spjd	arc_dead = FALSE;
5378185029Spjd	arc_warm = B_FALSE;
5379168566Spjd
5380258632Savg	/*
5381258632Savg	 * Calculate maximum amount of dirty data per pool.
5382258632Savg	 *
5383258632Savg	 * If it has been set by /etc/system, take that.
5384258632Savg	 * Otherwise, use a percentage of physical memory defined by
5385258632Savg	 * zfs_dirty_data_max_percent (default 10%) with a cap at
5386258632Savg	 * zfs_dirty_data_max_max (default 4GB).
5387258632Savg	 */
5388258632Savg	if (zfs_dirty_data_max == 0) {
5389258632Savg		zfs_dirty_data_max = ptob(physmem) *
5390258632Savg		    zfs_dirty_data_max_percent / 100;
5391258632Savg		zfs_dirty_data_max = MIN(zfs_dirty_data_max,
5392258632Savg		    zfs_dirty_data_max_max);
5393258632Savg	}
5394185029Spjd
5395168566Spjd#ifdef _KERNEL
5396194043Skmacy	if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
5397193953Skmacy		prefetch_tunable_set = 1;
5398206796Spjd
5399193878Skmacy#ifdef __i386__
5400193953Skmacy	if (prefetch_tunable_set == 0) {
5401196863Strasz		printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
5402196863Strasz		    "-- to enable,\n");
5403196863Strasz		printf("            add \"vfs.zfs.prefetch_disable=0\" "
5404196863Strasz		    "to /boot/loader.conf.\n");
5405219089Spjd		zfs_prefetch_disable = 1;
5406193878Skmacy	}
5407206796Spjd#else
5408193878Skmacy	if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
5409193953Skmacy	    prefetch_tunable_set == 0) {
5410196863Strasz		printf("ZFS NOTICE: Prefetch is disabled by default if less "
5411196941Strasz		    "than 4GB of RAM is present;\n"
5412196863Strasz		    "            to enable, add \"vfs.zfs.prefetch_disable=0\" "
5413196863Strasz		    "to /boot/loader.conf.\n");
5414219089Spjd		zfs_prefetch_disable = 1;
5415193878Skmacy	}
5416206796Spjd#endif
5417175633Spjd	/* Warn about ZFS memory and address space requirements. */
5418168696Spjd	if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
5419168987Sbmah		printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
5420168987Sbmah		    "expect unstable behavior.\n");
5421175633Spjd	}
5422175633Spjd	if (kmem_size() < 512 * (1 << 20)) {
5423173419Spjd		printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
5424168987Sbmah		    "expect unstable behavior.\n");
5425185029Spjd		printf("             Consider tuning vm.kmem_size and "
5426173419Spjd		    "vm.kmem_size_max\n");
5427185029Spjd		printf("             in /boot/loader.conf.\n");
5428168566Spjd	}
5429168566Spjd#endif
5430168404Spjd}
5431168404Spjd
5432168404Spjdvoid
5433168404Spjdarc_fini(void)
5434168404Spjd{
5435286763Smav	mutex_enter(&arc_reclaim_lock);
5436286763Smav	arc_reclaim_thread_exit = TRUE;
5437286763Smav	/*
5438286763Smav	 * The reclaim thread will set arc_reclaim_thread_exit back to
5439286763Smav	 * FALSE when it is finished exiting; we're waiting for that.
5440286763Smav	 */
5441286763Smav	while (arc_reclaim_thread_exit) {
5442286763Smav		cv_signal(&arc_reclaim_thread_cv);
5443286763Smav		cv_wait(&arc_reclaim_thread_cv, &arc_reclaim_lock);
5444286763Smav	}
5445286763Smav	mutex_exit(&arc_reclaim_lock);
5446168404Spjd
5447286763Smav	mutex_enter(&arc_user_evicts_lock);
5448286763Smav	arc_user_evicts_thread_exit = TRUE;
5449286763Smav	/*
5450286763Smav	 * The user evicts thread will set arc_user_evicts_thread_exit
5451286763Smav	 * to FALSE when it is finished exiting; we're waiting for that.
5452286763Smav	 */
5453286763Smav	while (arc_user_evicts_thread_exit) {
5454286763Smav		cv_signal(&arc_user_evicts_cv);
5455286763Smav		cv_wait(&arc_user_evicts_cv, &arc_user_evicts_lock);
5456286763Smav	}
5457286763Smav	mutex_exit(&arc_user_evicts_lock);
5458168404Spjd
5459286763Smav	/* Use TRUE to ensure *all* buffers are evicted */
5460286763Smav	arc_flush(NULL, TRUE);
5461286763Smav
5462168404Spjd	arc_dead = TRUE;
5463168404Spjd
5464168404Spjd	if (arc_ksp != NULL) {
5465168404Spjd		kstat_delete(arc_ksp);
5466168404Spjd		arc_ksp = NULL;
5467168404Spjd	}
5468168404Spjd
5469286763Smav	mutex_destroy(&arc_reclaim_lock);
5470286763Smav	cv_destroy(&arc_reclaim_thread_cv);
5471286763Smav	cv_destroy(&arc_reclaim_waiters_cv);
5472168404Spjd
5473286763Smav	mutex_destroy(&arc_user_evicts_lock);
5474286763Smav	cv_destroy(&arc_user_evicts_cv);
5475168404Spjd
5476286766Smav	refcount_destroy(&arc_anon->arcs_size);
5477286766Smav	refcount_destroy(&arc_mru->arcs_size);
5478286766Smav	refcount_destroy(&arc_mru_ghost->arcs_size);
5479286766Smav	refcount_destroy(&arc_mfu->arcs_size);
5480286766Smav	refcount_destroy(&arc_mfu_ghost->arcs_size);
5481286766Smav	refcount_destroy(&arc_l2c_only->arcs_size);
5482286766Smav
5483286763Smav	multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
5484286763Smav	multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
5485286763Smav	multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
5486286763Smav	multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
5487286763Smav	multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
5488286763Smav	multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
5489286763Smav	multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
5490286763Smav	multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
5491206796Spjd
5492168404Spjd	buf_fini();
5493168404Spjd
5494286570Smav	ASSERT0(arc_loaned_bytes);
5495209962Smm
5496168404Spjd#ifdef _KERNEL
5497168566Spjd	if (arc_event_lowmem != NULL)
5498168566Spjd		EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
5499168404Spjd#endif
5500168404Spjd}
5501185029Spjd
5502185029Spjd/*
5503185029Spjd * Level 2 ARC
5504185029Spjd *
5505185029Spjd * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
5506185029Spjd * It uses dedicated storage devices to hold cached data, which are populated
5507185029Spjd * using large infrequent writes.  The main role of this cache is to boost
5508185029Spjd * the performance of random read workloads.  The intended L2ARC devices
5509185029Spjd * include short-stroked disks, solid state disks, and other media with
5510185029Spjd * substantially faster read latency than disk.
5511185029Spjd *
5512185029Spjd *                 +-----------------------+
5513185029Spjd *                 |         ARC           |
5514185029Spjd *                 +-----------------------+
5515185029Spjd *                    |         ^     ^
5516185029Spjd *                    |         |     |
5517185029Spjd *      l2arc_feed_thread()    arc_read()
5518185029Spjd *                    |         |     |
5519185029Spjd *                    |  l2arc read   |
5520185029Spjd *                    V         |     |
5521185029Spjd *               +---------------+    |
5522185029Spjd *               |     L2ARC     |    |
5523185029Spjd *               +---------------+    |
5524185029Spjd *                   |    ^           |
5525185029Spjd *          l2arc_write() |           |
5526185029Spjd *                   |    |           |
5527185029Spjd *                   V    |           |
5528185029Spjd *                 +-------+      +-------+
5529185029Spjd *                 | vdev  |      | vdev  |
5530185029Spjd *                 | cache |      | cache |
5531185029Spjd *                 +-------+      +-------+
5532185029Spjd *                 +=========+     .-----.
5533185029Spjd *                 :  L2ARC  :    |-_____-|
5534185029Spjd *                 : devices :    | Disks |
5535185029Spjd *                 +=========+    `-_____-'
5536185029Spjd *
5537185029Spjd * Read requests are satisfied from the following sources, in order:
5538185029Spjd *
5539185029Spjd *	1) ARC
5540185029Spjd *	2) vdev cache of L2ARC devices
5541185029Spjd *	3) L2ARC devices
5542185029Spjd *	4) vdev cache of disks
5543185029Spjd *	5) disks
5544185029Spjd *
5545185029Spjd * Some L2ARC device types exhibit extremely slow write performance.
5546185029Spjd * To accommodate for this there are some significant differences between
5547185029Spjd * the L2ARC and traditional cache design:
5548185029Spjd *
5549185029Spjd * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
5550185029Spjd * the ARC behave as usual, freeing buffers and placing headers on ghost
5551185029Spjd * lists.  The ARC does not send buffers to the L2ARC during eviction as
5552185029Spjd * this would add inflated write latencies for all ARC memory pressure.
5553185029Spjd *
5554185029Spjd * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
5555185029Spjd * It does this by periodically scanning buffers from the eviction-end of
5556185029Spjd * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
5557251478Sdelphij * not already there. It scans until a headroom of buffers is satisfied,
5558251478Sdelphij * which itself is a buffer for ARC eviction. If a compressible buffer is
5559251478Sdelphij * found during scanning and selected for writing to an L2ARC device, we
5560251478Sdelphij * temporarily boost scanning headroom during the next scan cycle to make
5561251478Sdelphij * sure we adapt to compression effects (which might significantly reduce
5562251478Sdelphij * the data volume we write to L2ARC). The thread that does this is
5563185029Spjd * l2arc_feed_thread(), illustrated below; example sizes are included to
5564185029Spjd * provide a better sense of ratio than this diagram:
5565185029Spjd *
5566185029Spjd *	       head -->                        tail
5567185029Spjd *	        +---------------------+----------+
5568185029Spjd *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
5569185029Spjd *	        +---------------------+----------+   |   o L2ARC eligible
5570185029Spjd *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
5571185029Spjd *	        +---------------------+----------+   |
5572185029Spjd *	             15.9 Gbytes      ^ 32 Mbytes    |
5573185029Spjd *	                           headroom          |
5574185029Spjd *	                                      l2arc_feed_thread()
5575185029Spjd *	                                             |
5576185029Spjd *	                 l2arc write hand <--[oooo]--'
5577185029Spjd *	                         |           8 Mbyte
5578185029Spjd *	                         |          write max
5579185029Spjd *	                         V
5580185029Spjd *		  +==============================+
5581185029Spjd *	L2ARC dev |####|#|###|###|    |####| ... |
5582185029Spjd *	          +==============================+
5583185029Spjd *	                     32 Gbytes
5584185029Spjd *
5585185029Spjd * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
5586185029Spjd * evicted, then the L2ARC has cached a buffer much sooner than it probably
5587185029Spjd * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
5588185029Spjd * safe to say that this is an uncommon case, since buffers at the end of
5589185029Spjd * the ARC lists have moved there due to inactivity.
5590185029Spjd *
5591185029Spjd * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
5592185029Spjd * then the L2ARC simply misses copying some buffers.  This serves as a
5593185029Spjd * pressure valve to prevent heavy read workloads from both stalling the ARC
5594185029Spjd * with waits and clogging the L2ARC with writes.  This also helps prevent
5595185029Spjd * the potential for the L2ARC to churn if it attempts to cache content too
5596185029Spjd * quickly, such as during backups of the entire pool.
5597185029Spjd *
5598185029Spjd * 5. After system boot and before the ARC has filled main memory, there are
5599185029Spjd * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
5600185029Spjd * lists can remain mostly static.  Instead of searching from tail of these
5601185029Spjd * lists as pictured, the l2arc_feed_thread() will search from the list heads
5602185029Spjd * for eligible buffers, greatly increasing its chance of finding them.
5603185029Spjd *
5604185029Spjd * The L2ARC device write speed is also boosted during this time so that
5605185029Spjd * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
5606185029Spjd * there are no L2ARC reads, and no fear of degrading read performance
5607185029Spjd * through increased writes.
5608185029Spjd *
5609185029Spjd * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
5610185029Spjd * the vdev queue can aggregate them into larger and fewer writes.  Each
5611185029Spjd * device is written to in a rotor fashion, sweeping writes through
5612185029Spjd * available space then repeating.
5613185029Spjd *
5614185029Spjd * 7. The L2ARC does not store dirty content.  It never needs to flush
5615185029Spjd * write buffers back to disk based storage.
5616185029Spjd *
5617185029Spjd * 8. If an ARC buffer is written (and dirtied) which also exists in the
5618185029Spjd * L2ARC, the now stale L2ARC buffer is immediately dropped.
5619185029Spjd *
5620185029Spjd * The performance of the L2ARC can be tweaked by a number of tunables, which
5621185029Spjd * may be necessary for different workloads:
5622185029Spjd *
5623185029Spjd *	l2arc_write_max		max write bytes per interval
5624185029Spjd *	l2arc_write_boost	extra write bytes during device warmup
5625185029Spjd *	l2arc_noprefetch	skip caching prefetched buffers
5626185029Spjd *	l2arc_headroom		number of max device writes to precache
5627251478Sdelphij *	l2arc_headroom_boost	when we find compressed buffers during ARC
5628251478Sdelphij *				scanning, we multiply headroom by this
5629251478Sdelphij *				percentage factor for the next scan cycle,
5630251478Sdelphij *				since more compressed buffers are likely to
5631251478Sdelphij *				be present
5632185029Spjd *	l2arc_feed_secs		seconds between L2ARC writing
5633185029Spjd *
5634185029Spjd * Tunables may be removed or added as future performance improvements are
5635185029Spjd * integrated, and also may become zpool properties.
5636208373Smm *
5637208373Smm * There are three key functions that control how the L2ARC warms up:
5638208373Smm *
5639208373Smm *	l2arc_write_eligible()	check if a buffer is eligible to cache
5640208373Smm *	l2arc_write_size()	calculate how much to write
5641208373Smm *	l2arc_write_interval()	calculate sleep delay between writes
5642208373Smm *
5643208373Smm * These three functions determine what to write, how much, and how quickly
5644208373Smm * to send writes.
5645185029Spjd */
5646185029Spjd
5647208373Smmstatic boolean_t
5648275811Sdelphijl2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
5649208373Smm{
5650208373Smm	/*
5651208373Smm	 * A buffer is *not* eligible for the L2ARC if it:
5652208373Smm	 * 1. belongs to a different spa.
5653208373Smm	 * 2. is already cached on the L2ARC.
5654208373Smm	 * 3. has an I/O in progress (it may be an incomplete read).
5655208373Smm	 * 4. is flagged not eligible (zfs property).
5656208373Smm	 */
5657275811Sdelphij	if (hdr->b_spa != spa_guid) {
5658208373Smm		ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
5659208373Smm		return (B_FALSE);
5660208373Smm	}
5661286570Smav	if (HDR_HAS_L2HDR(hdr)) {
5662208373Smm		ARCSTAT_BUMP(arcstat_l2_write_in_l2);
5663208373Smm		return (B_FALSE);
5664208373Smm	}
5665275811Sdelphij	if (HDR_IO_IN_PROGRESS(hdr)) {
5666208373Smm		ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
5667208373Smm		return (B_FALSE);
5668208373Smm	}
5669275811Sdelphij	if (!HDR_L2CACHE(hdr)) {
5670208373Smm		ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
5671208373Smm		return (B_FALSE);
5672208373Smm	}
5673208373Smm
5674208373Smm	return (B_TRUE);
5675208373Smm}
5676208373Smm
5677208373Smmstatic uint64_t
5678251478Sdelphijl2arc_write_size(void)
5679208373Smm{
5680208373Smm	uint64_t size;
5681208373Smm
5682251478Sdelphij	/*
5683251478Sdelphij	 * Make sure our globals have meaningful values in case the user
5684251478Sdelphij	 * altered them.
5685251478Sdelphij	 */
5686251478Sdelphij	size = l2arc_write_max;
5687251478Sdelphij	if (size == 0) {
5688251478Sdelphij		cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
5689251478Sdelphij		    "be greater than zero, resetting it to the default (%d)",
5690251478Sdelphij		    L2ARC_WRITE_SIZE);
5691251478Sdelphij		size = l2arc_write_max = L2ARC_WRITE_SIZE;
5692251478Sdelphij	}
5693208373Smm
5694208373Smm	if (arc_warm == B_FALSE)
5695251478Sdelphij		size += l2arc_write_boost;
5696208373Smm
5697208373Smm	return (size);
5698208373Smm
5699208373Smm}
5700208373Smm
5701208373Smmstatic clock_t
5702208373Smml2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
5703208373Smm{
5704219089Spjd	clock_t interval, next, now;
5705208373Smm
5706208373Smm	/*
5707208373Smm	 * If the ARC lists are busy, increase our write rate; if the
5708208373Smm	 * lists are stale, idle back.  This is achieved by checking
5709208373Smm	 * how much we previously wrote - if it was more than half of
5710208373Smm	 * what we wanted, schedule the next write much sooner.
5711208373Smm	 */
5712208373Smm	if (l2arc_feed_again && wrote > (wanted / 2))
5713208373Smm		interval = (hz * l2arc_feed_min_ms) / 1000;
5714208373Smm	else
5715208373Smm		interval = hz * l2arc_feed_secs;
5716208373Smm
5717219089Spjd	now = ddi_get_lbolt();
5718219089Spjd	next = MAX(now, MIN(now + interval, began + interval));
5719208373Smm
5720208373Smm	return (next);
5721208373Smm}
5722208373Smm
5723185029Spjd/*
5724185029Spjd * Cycle through L2ARC devices.  This is how L2ARC load balances.
5725185029Spjd * If a device is returned, this also returns holding the spa config lock.
5726185029Spjd */
5727185029Spjdstatic l2arc_dev_t *
5728185029Spjdl2arc_dev_get_next(void)
5729185029Spjd{
5730185029Spjd	l2arc_dev_t *first, *next = NULL;
5731185029Spjd
5732185029Spjd	/*
5733185029Spjd	 * Lock out the removal of spas (spa_namespace_lock), then removal
5734185029Spjd	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
5735185029Spjd	 * both locks will be dropped and a spa config lock held instead.
5736185029Spjd	 */
5737185029Spjd	mutex_enter(&spa_namespace_lock);
5738185029Spjd	mutex_enter(&l2arc_dev_mtx);
5739185029Spjd
5740185029Spjd	/* if there are no vdevs, there is nothing to do */
5741185029Spjd	if (l2arc_ndev == 0)
5742185029Spjd		goto out;
5743185029Spjd
5744185029Spjd	first = NULL;
5745185029Spjd	next = l2arc_dev_last;
5746185029Spjd	do {
5747185029Spjd		/* loop around the list looking for a non-faulted vdev */
5748185029Spjd		if (next == NULL) {
5749185029Spjd			next = list_head(l2arc_dev_list);
5750185029Spjd		} else {
5751185029Spjd			next = list_next(l2arc_dev_list, next);
5752185029Spjd			if (next == NULL)
5753185029Spjd				next = list_head(l2arc_dev_list);
5754185029Spjd		}
5755185029Spjd
5756185029Spjd		/* if we have come back to the start, bail out */
5757185029Spjd		if (first == NULL)
5758185029Spjd			first = next;
5759185029Spjd		else if (next == first)
5760185029Spjd			break;
5761185029Spjd
5762185029Spjd	} while (vdev_is_dead(next->l2ad_vdev));
5763185029Spjd
5764185029Spjd	/* if we were unable to find any usable vdevs, return NULL */
5765185029Spjd	if (vdev_is_dead(next->l2ad_vdev))
5766185029Spjd		next = NULL;
5767185029Spjd
5768185029Spjd	l2arc_dev_last = next;
5769185029Spjd
5770185029Spjdout:
5771185029Spjd	mutex_exit(&l2arc_dev_mtx);
5772185029Spjd
5773185029Spjd	/*
5774185029Spjd	 * Grab the config lock to prevent the 'next' device from being
5775185029Spjd	 * removed while we are writing to it.
5776185029Spjd	 */
5777185029Spjd	if (next != NULL)
5778185029Spjd		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
5779185029Spjd	mutex_exit(&spa_namespace_lock);
5780185029Spjd
5781185029Spjd	return (next);
5782185029Spjd}
5783185029Spjd
5784185029Spjd/*
5785185029Spjd * Free buffers that were tagged for destruction.
5786185029Spjd */
5787185029Spjdstatic void
5788185029Spjdl2arc_do_free_on_write()
5789185029Spjd{
5790185029Spjd	list_t *buflist;
5791185029Spjd	l2arc_data_free_t *df, *df_prev;
5792185029Spjd
5793185029Spjd	mutex_enter(&l2arc_free_on_write_mtx);
5794185029Spjd	buflist = l2arc_free_on_write;
5795185029Spjd
5796185029Spjd	for (df = list_tail(buflist); df; df = df_prev) {
5797185029Spjd		df_prev = list_prev(buflist, df);
5798185029Spjd		ASSERT(df->l2df_data != NULL);
5799185029Spjd		ASSERT(df->l2df_func != NULL);
5800185029Spjd		df->l2df_func(df->l2df_data, df->l2df_size);
5801185029Spjd		list_remove(buflist, df);
5802185029Spjd		kmem_free(df, sizeof (l2arc_data_free_t));
5803185029Spjd	}
5804185029Spjd
5805185029Spjd	mutex_exit(&l2arc_free_on_write_mtx);
5806185029Spjd}
5807185029Spjd
5808185029Spjd/*
5809185029Spjd * A write to a cache device has completed.  Update all headers to allow
5810185029Spjd * reads from these buffers to begin.
5811185029Spjd */
5812185029Spjdstatic void
5813185029Spjdl2arc_write_done(zio_t *zio)
5814185029Spjd{
5815185029Spjd	l2arc_write_callback_t *cb;
5816185029Spjd	l2arc_dev_t *dev;
5817185029Spjd	list_t *buflist;
5818275811Sdelphij	arc_buf_hdr_t *head, *hdr, *hdr_prev;
5819185029Spjd	kmutex_t *hash_lock;
5820268085Sdelphij	int64_t bytes_dropped = 0;
5821185029Spjd
5822185029Spjd	cb = zio->io_private;
5823185029Spjd	ASSERT(cb != NULL);
5824185029Spjd	dev = cb->l2wcb_dev;
5825185029Spjd	ASSERT(dev != NULL);
5826185029Spjd	head = cb->l2wcb_head;
5827185029Spjd	ASSERT(head != NULL);
5828286570Smav	buflist = &dev->l2ad_buflist;
5829185029Spjd	ASSERT(buflist != NULL);
5830185029Spjd	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
5831185029Spjd	    l2arc_write_callback_t *, cb);
5832185029Spjd
5833185029Spjd	if (zio->io_error != 0)
5834185029Spjd		ARCSTAT_BUMP(arcstat_l2_writes_error);
5835185029Spjd
5836185029Spjd	/*
5837185029Spjd	 * All writes completed, or an error was hit.
5838185029Spjd	 */
5839286763Smavtop:
5840286763Smav	mutex_enter(&dev->l2ad_mtx);
5841275811Sdelphij	for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
5842275811Sdelphij		hdr_prev = list_prev(buflist, hdr);
5843185029Spjd
5844275811Sdelphij		hash_lock = HDR_LOCK(hdr);
5845286763Smav
5846286763Smav		/*
5847286763Smav		 * We cannot use mutex_enter or else we can deadlock
5848286763Smav		 * with l2arc_write_buffers (due to swapping the order
5849286763Smav		 * the hash lock and l2ad_mtx are taken).
5850286763Smav		 */
5851185029Spjd		if (!mutex_tryenter(hash_lock)) {
5852185029Spjd			/*
5853286763Smav			 * Missed the hash lock. We must retry so we
5854286763Smav			 * don't leave the ARC_FLAG_L2_WRITING bit set.
5855185029Spjd			 */
5856286763Smav			ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
5857286763Smav
5858286763Smav			/*
5859286763Smav			 * We don't want to rescan the headers we've
5860286763Smav			 * already marked as having been written out, so
5861286763Smav			 * we reinsert the head node so we can pick up
5862286763Smav			 * where we left off.
5863286763Smav			 */
5864286763Smav			list_remove(buflist, head);
5865286763Smav			list_insert_after(buflist, hdr, head);
5866286763Smav
5867286763Smav			mutex_exit(&dev->l2ad_mtx);
5868286763Smav
5869286763Smav			/*
5870286763Smav			 * We wait for the hash lock to become available
5871286763Smav			 * to try and prevent busy waiting, and increase
5872286763Smav			 * the chance we'll be able to acquire the lock
5873286763Smav			 * the next time around.
5874286763Smav			 */
5875286763Smav			mutex_enter(hash_lock);
5876286763Smav			mutex_exit(hash_lock);
5877286763Smav			goto top;
5878185029Spjd		}
5879185029Spjd
5880286570Smav		/*
5881286763Smav		 * We could not have been moved into the arc_l2c_only
5882286763Smav		 * state while in-flight due to our ARC_FLAG_L2_WRITING
5883286763Smav		 * bit being set. Let's just ensure that's being enforced.
5884286570Smav		 */
5885286763Smav		ASSERT(HDR_HAS_L1HDR(hdr));
5886286570Smav
5887286763Smav		/*
5888286763Smav		 * We may have allocated a buffer for L2ARC compression,
5889286763Smav		 * we must release it to avoid leaking this data.
5890286763Smav		 */
5891286763Smav		l2arc_release_cdata_buf(hdr);
5892286763Smav
5893185029Spjd		if (zio->io_error != 0) {
5894185029Spjd			/*
5895185029Spjd			 * Error - drop L2ARC entry.
5896185029Spjd			 */
5897286570Smav			trim_map_free(hdr->b_l2hdr.b_dev->l2ad_vdev,
5898286570Smav			    hdr->b_l2hdr.b_daddr, hdr->b_l2hdr.b_asize, 0);
5899286570Smav			hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
5900286570Smav
5901286570Smav			ARCSTAT_INCR(arcstat_l2_asize, -hdr->b_l2hdr.b_asize);
5902275811Sdelphij			ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
5903286598Smav
5904286598Smav			bytes_dropped += hdr->b_l2hdr.b_asize;
5905286598Smav			(void) refcount_remove_many(&dev->l2ad_alloc,
5906286598Smav			    hdr->b_l2hdr.b_asize, hdr);
5907185029Spjd		}
5908185029Spjd
5909185029Spjd		/*
5910286763Smav		 * Allow ARC to begin reads and ghost list evictions to
5911286763Smav		 * this L2ARC entry.
5912185029Spjd		 */
5913275811Sdelphij		hdr->b_flags &= ~ARC_FLAG_L2_WRITING;
5914185029Spjd
5915185029Spjd		mutex_exit(hash_lock);
5916185029Spjd	}
5917185029Spjd
5918185029Spjd	atomic_inc_64(&l2arc_writes_done);
5919185029Spjd	list_remove(buflist, head);
5920286570Smav	ASSERT(!HDR_HAS_L1HDR(head));
5921286570Smav	kmem_cache_free(hdr_l2only_cache, head);
5922286570Smav	mutex_exit(&dev->l2ad_mtx);
5923185029Spjd
5924268085Sdelphij	vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
5925268085Sdelphij
5926185029Spjd	l2arc_do_free_on_write();
5927185029Spjd
5928185029Spjd	kmem_free(cb, sizeof (l2arc_write_callback_t));
5929185029Spjd}
5930185029Spjd
5931185029Spjd/*
5932185029Spjd * A read to a cache device completed.  Validate buffer contents before
5933185029Spjd * handing over to the regular ARC routines.
5934185029Spjd */
5935185029Spjdstatic void
5936185029Spjdl2arc_read_done(zio_t *zio)
5937185029Spjd{
5938185029Spjd	l2arc_read_callback_t *cb;
5939185029Spjd	arc_buf_hdr_t *hdr;
5940185029Spjd	arc_buf_t *buf;
5941185029Spjd	kmutex_t *hash_lock;
5942185029Spjd	int equal;
5943185029Spjd
5944185029Spjd	ASSERT(zio->io_vd != NULL);
5945185029Spjd	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
5946185029Spjd
5947185029Spjd	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
5948185029Spjd
5949185029Spjd	cb = zio->io_private;
5950185029Spjd	ASSERT(cb != NULL);
5951185029Spjd	buf = cb->l2rcb_buf;
5952185029Spjd	ASSERT(buf != NULL);
5953185029Spjd
5954219089Spjd	hash_lock = HDR_LOCK(buf->b_hdr);
5955185029Spjd	mutex_enter(hash_lock);
5956219089Spjd	hdr = buf->b_hdr;
5957219089Spjd	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
5958185029Spjd
5959185029Spjd	/*
5960251478Sdelphij	 * If the buffer was compressed, decompress it first.
5961251478Sdelphij	 */
5962251478Sdelphij	if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
5963251478Sdelphij		l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
5964251478Sdelphij	ASSERT(zio->io_data != NULL);
5965251478Sdelphij
5966251478Sdelphij	/*
5967185029Spjd	 * Check this survived the L2ARC journey.
5968185029Spjd	 */
5969185029Spjd	equal = arc_cksum_equal(buf);
5970185029Spjd	if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
5971185029Spjd		mutex_exit(hash_lock);
5972185029Spjd		zio->io_private = buf;
5973185029Spjd		zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
5974185029Spjd		zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
5975185029Spjd		arc_read_done(zio);
5976185029Spjd	} else {
5977185029Spjd		mutex_exit(hash_lock);
5978185029Spjd		/*
5979185029Spjd		 * Buffer didn't survive caching.  Increment stats and
5980185029Spjd		 * reissue to the original storage device.
5981185029Spjd		 */
5982185029Spjd		if (zio->io_error != 0) {
5983185029Spjd			ARCSTAT_BUMP(arcstat_l2_io_error);
5984185029Spjd		} else {
5985249195Smm			zio->io_error = SET_ERROR(EIO);
5986185029Spjd		}
5987185029Spjd		if (!equal)
5988185029Spjd			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
5989185029Spjd
5990185029Spjd		/*
5991185029Spjd		 * If there's no waiter, issue an async i/o to the primary
5992185029Spjd		 * storage now.  If there *is* a waiter, the caller must
5993185029Spjd		 * issue the i/o in a context where it's OK to block.
5994185029Spjd		 */
5995209962Smm		if (zio->io_waiter == NULL) {
5996209962Smm			zio_t *pio = zio_unique_parent(zio);
5997209962Smm
5998209962Smm			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
5999209962Smm
6000209962Smm			zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
6001185029Spjd			    buf->b_data, zio->io_size, arc_read_done, buf,
6002185029Spjd			    zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
6003209962Smm		}
6004185029Spjd	}
6005185029Spjd
6006185029Spjd	kmem_free(cb, sizeof (l2arc_read_callback_t));
6007185029Spjd}
6008185029Spjd
6009185029Spjd/*
6010185029Spjd * This is the list priority from which the L2ARC will search for pages to
6011185029Spjd * cache.  This is used within loops (0..3) to cycle through lists in the
6012185029Spjd * desired order.  This order can have a significant effect on cache
6013185029Spjd * performance.
6014185029Spjd *
6015185029Spjd * Currently the metadata lists are hit first, MFU then MRU, followed by
6016185029Spjd * the data lists.  This function returns a locked list, and also returns
6017185029Spjd * the lock pointer.
6018185029Spjd */
6019286763Smavstatic multilist_sublist_t *
6020286763Smavl2arc_sublist_lock(int list_num)
6021185029Spjd{
6022286763Smav	multilist_t *ml = NULL;
6023286763Smav	unsigned int idx;
6024185029Spjd
6025286762Smav	ASSERT(list_num >= 0 && list_num <= 3);
6026206796Spjd
6027286762Smav	switch (list_num) {
6028286762Smav	case 0:
6029286763Smav		ml = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
6030286762Smav		break;
6031286762Smav	case 1:
6032286763Smav		ml = &arc_mru->arcs_list[ARC_BUFC_METADATA];
6033286762Smav		break;
6034286762Smav	case 2:
6035286763Smav		ml = &arc_mfu->arcs_list[ARC_BUFC_DATA];
6036286762Smav		break;
6037286762Smav	case 3:
6038286763Smav		ml = &arc_mru->arcs_list[ARC_BUFC_DATA];
6039286762Smav		break;
6040185029Spjd	}
6041185029Spjd
6042286763Smav	/*
6043286763Smav	 * Return a randomly-selected sublist. This is acceptable
6044286763Smav	 * because the caller feeds only a little bit of data for each
6045286763Smav	 * call (8MB). Subsequent calls will result in different
6046286763Smav	 * sublists being selected.
6047286763Smav	 */
6048286763Smav	idx = multilist_get_random_index(ml);
6049286763Smav	return (multilist_sublist_lock(ml, idx));
6050185029Spjd}
6051185029Spjd
6052185029Spjd/*
6053185029Spjd * Evict buffers from the device write hand to the distance specified in
6054185029Spjd * bytes.  This distance may span populated buffers, it may span nothing.
6055185029Spjd * This is clearing a region on the L2ARC device ready for writing.
6056185029Spjd * If the 'all' boolean is set, every buffer is evicted.
6057185029Spjd */
6058185029Spjdstatic void
6059185029Spjdl2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
6060185029Spjd{
6061185029Spjd	list_t *buflist;
6062275811Sdelphij	arc_buf_hdr_t *hdr, *hdr_prev;
6063185029Spjd	kmutex_t *hash_lock;
6064185029Spjd	uint64_t taddr;
6065185029Spjd
6066286570Smav	buflist = &dev->l2ad_buflist;
6067185029Spjd
6068185029Spjd	if (!all && dev->l2ad_first) {
6069185029Spjd		/*
6070185029Spjd		 * This is the first sweep through the device.  There is
6071185029Spjd		 * nothing to evict.
6072185029Spjd		 */
6073185029Spjd		return;
6074185029Spjd	}
6075185029Spjd
6076185029Spjd	if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
6077185029Spjd		/*
6078185029Spjd		 * When nearing the end of the device, evict to the end
6079185029Spjd		 * before the device write hand jumps to the start.
6080185029Spjd		 */
6081185029Spjd		taddr = dev->l2ad_end;
6082185029Spjd	} else {
6083185029Spjd		taddr = dev->l2ad_hand + distance;
6084185029Spjd	}
6085185029Spjd	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
6086185029Spjd	    uint64_t, taddr, boolean_t, all);
6087185029Spjd
6088185029Spjdtop:
6089286570Smav	mutex_enter(&dev->l2ad_mtx);
6090275811Sdelphij	for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
6091275811Sdelphij		hdr_prev = list_prev(buflist, hdr);
6092185029Spjd
6093275811Sdelphij		hash_lock = HDR_LOCK(hdr);
6094286763Smav
6095286763Smav		/*
6096286763Smav		 * We cannot use mutex_enter or else we can deadlock
6097286763Smav		 * with l2arc_write_buffers (due to swapping the order
6098286763Smav		 * the hash lock and l2ad_mtx are taken).
6099286763Smav		 */
6100185029Spjd		if (!mutex_tryenter(hash_lock)) {
6101185029Spjd			/*
6102185029Spjd			 * Missed the hash lock.  Retry.
6103185029Spjd			 */
6104185029Spjd			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
6105286570Smav			mutex_exit(&dev->l2ad_mtx);
6106185029Spjd			mutex_enter(hash_lock);
6107185029Spjd			mutex_exit(hash_lock);
6108185029Spjd			goto top;
6109185029Spjd		}
6110185029Spjd
6111275811Sdelphij		if (HDR_L2_WRITE_HEAD(hdr)) {
6112185029Spjd			/*
6113185029Spjd			 * We hit a write head node.  Leave it for
6114185029Spjd			 * l2arc_write_done().
6115185029Spjd			 */
6116275811Sdelphij			list_remove(buflist, hdr);
6117185029Spjd			mutex_exit(hash_lock);
6118185029Spjd			continue;
6119185029Spjd		}
6120185029Spjd
6121286570Smav		if (!all && HDR_HAS_L2HDR(hdr) &&
6122286570Smav		    (hdr->b_l2hdr.b_daddr > taddr ||
6123286570Smav		    hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
6124185029Spjd			/*
6125185029Spjd			 * We've evicted to the target address,
6126185029Spjd			 * or the end of the device.
6127185029Spjd			 */
6128185029Spjd			mutex_exit(hash_lock);
6129185029Spjd			break;
6130185029Spjd		}
6131185029Spjd
6132286570Smav		ASSERT(HDR_HAS_L2HDR(hdr));
6133286570Smav		if (!HDR_HAS_L1HDR(hdr)) {
6134275811Sdelphij			ASSERT(!HDR_L2_READING(hdr));
6135185029Spjd			/*
6136185029Spjd			 * This doesn't exist in the ARC.  Destroy.
6137185029Spjd			 * arc_hdr_destroy() will call list_remove()
6138185029Spjd			 * and decrement arcstat_l2_size.
6139185029Spjd			 */
6140275811Sdelphij			arc_change_state(arc_anon, hdr, hash_lock);
6141275811Sdelphij			arc_hdr_destroy(hdr);
6142185029Spjd		} else {
6143286570Smav			ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
6144286570Smav			ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
6145185029Spjd			/*
6146185029Spjd			 * Invalidate issued or about to be issued
6147185029Spjd			 * reads, since we may be about to write
6148185029Spjd			 * over this location.
6149185029Spjd			 */
6150275811Sdelphij			if (HDR_L2_READING(hdr)) {
6151185029Spjd				ARCSTAT_BUMP(arcstat_l2_evict_reading);
6152275811Sdelphij				hdr->b_flags |= ARC_FLAG_L2_EVICTED;
6153185029Spjd			}
6154185029Spjd
6155286763Smav			/* Ensure this header has finished being written */
6156286763Smav			ASSERT(!HDR_L2_WRITING(hdr));
6157286763Smav			ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
6158286763Smav
6159286598Smav			arc_hdr_l2hdr_destroy(hdr);
6160185029Spjd		}
6161185029Spjd		mutex_exit(hash_lock);
6162185029Spjd	}
6163286570Smav	mutex_exit(&dev->l2ad_mtx);
6164185029Spjd}
6165185029Spjd
6166185029Spjd/*
6167185029Spjd * Find and write ARC buffers to the L2ARC device.
6168185029Spjd *
6169275811Sdelphij * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
6170185029Spjd * for reading until they have completed writing.
6171251478Sdelphij * The headroom_boost is an in-out parameter used to maintain headroom boost
6172251478Sdelphij * state between calls to this function.
6173251478Sdelphij *
6174251478Sdelphij * Returns the number of bytes actually written (which may be smaller than
6175251478Sdelphij * the delta by which the device hand has changed due to alignment).
6176185029Spjd */
6177208373Smmstatic uint64_t
6178251478Sdelphijl2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
6179251478Sdelphij    boolean_t *headroom_boost)
6180185029Spjd{
6181275811Sdelphij	arc_buf_hdr_t *hdr, *hdr_prev, *head;
6182251478Sdelphij	uint64_t write_asize, write_psize, write_sz, headroom,
6183251478Sdelphij	    buf_compress_minsz;
6184185029Spjd	void *buf_data;
6185251478Sdelphij	boolean_t full;
6186185029Spjd	l2arc_write_callback_t *cb;
6187185029Spjd	zio_t *pio, *wzio;
6188228103Smm	uint64_t guid = spa_load_guid(spa);
6189251478Sdelphij	const boolean_t do_headroom_boost = *headroom_boost;
6190185029Spjd	int try;
6191185029Spjd
6192185029Spjd	ASSERT(dev->l2ad_vdev != NULL);
6193185029Spjd
6194251478Sdelphij	/* Lower the flag now, we might want to raise it again later. */
6195251478Sdelphij	*headroom_boost = B_FALSE;
6196251478Sdelphij
6197185029Spjd	pio = NULL;
6198251478Sdelphij	write_sz = write_asize = write_psize = 0;
6199185029Spjd	full = B_FALSE;
6200286570Smav	head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
6201275811Sdelphij	head->b_flags |= ARC_FLAG_L2_WRITE_HEAD;
6202286570Smav	head->b_flags |= ARC_FLAG_HAS_L2HDR;
6203185029Spjd
6204205231Skmacy	ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
6205185029Spjd	/*
6206251478Sdelphij	 * We will want to try to compress buffers that are at least 2x the
6207251478Sdelphij	 * device sector size.
6208251478Sdelphij	 */
6209251478Sdelphij	buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
6210251478Sdelphij
6211251478Sdelphij	/*
6212185029Spjd	 * Copy buffers for L2ARC writing.
6213185029Spjd	 */
6214286762Smav	for (try = 0; try <= 3; try++) {
6215286763Smav		multilist_sublist_t *mls = l2arc_sublist_lock(try);
6216251478Sdelphij		uint64_t passed_sz = 0;
6217251478Sdelphij
6218205231Skmacy		ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
6219185029Spjd
6220185029Spjd		/*
6221185029Spjd		 * L2ARC fast warmup.
6222185029Spjd		 *
6223185029Spjd		 * Until the ARC is warm and starts to evict, read from the
6224185029Spjd		 * head of the ARC lists rather than the tail.
6225185029Spjd		 */
6226185029Spjd		if (arc_warm == B_FALSE)
6227286763Smav			hdr = multilist_sublist_head(mls);
6228185029Spjd		else
6229286763Smav			hdr = multilist_sublist_tail(mls);
6230275811Sdelphij		if (hdr == NULL)
6231205231Skmacy			ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
6232185029Spjd
6233286762Smav		headroom = target_sz * l2arc_headroom;
6234251478Sdelphij		if (do_headroom_boost)
6235251478Sdelphij			headroom = (headroom * l2arc_headroom_boost) / 100;
6236251478Sdelphij
6237275811Sdelphij		for (; hdr; hdr = hdr_prev) {
6238251478Sdelphij			kmutex_t *hash_lock;
6239251478Sdelphij			uint64_t buf_sz;
6240251478Sdelphij
6241185029Spjd			if (arc_warm == B_FALSE)
6242286763Smav				hdr_prev = multilist_sublist_next(mls, hdr);
6243185029Spjd			else
6244286763Smav				hdr_prev = multilist_sublist_prev(mls, hdr);
6245275811Sdelphij			ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned, hdr->b_size);
6246206796Spjd
6247275811Sdelphij			hash_lock = HDR_LOCK(hdr);
6248251478Sdelphij			if (!mutex_tryenter(hash_lock)) {
6249205231Skmacy				ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
6250185029Spjd				/*
6251185029Spjd				 * Skip this buffer rather than waiting.
6252185029Spjd				 */
6253185029Spjd				continue;
6254185029Spjd			}
6255185029Spjd
6256275811Sdelphij			passed_sz += hdr->b_size;
6257185029Spjd			if (passed_sz > headroom) {
6258185029Spjd				/*
6259185029Spjd				 * Searched too far.
6260185029Spjd				 */
6261185029Spjd				mutex_exit(hash_lock);
6262205231Skmacy				ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
6263185029Spjd				break;
6264185029Spjd			}
6265185029Spjd
6266275811Sdelphij			if (!l2arc_write_eligible(guid, hdr)) {
6267185029Spjd				mutex_exit(hash_lock);
6268185029Spjd				continue;
6269185029Spjd			}
6270185029Spjd
6271275811Sdelphij			if ((write_sz + hdr->b_size) > target_sz) {
6272185029Spjd				full = B_TRUE;
6273185029Spjd				mutex_exit(hash_lock);
6274205231Skmacy				ARCSTAT_BUMP(arcstat_l2_write_full);
6275185029Spjd				break;
6276185029Spjd			}
6277185029Spjd
6278185029Spjd			if (pio == NULL) {
6279185029Spjd				/*
6280185029Spjd				 * Insert a dummy header on the buflist so
6281185029Spjd				 * l2arc_write_done() can find where the
6282185029Spjd				 * write buffers begin without searching.
6283185029Spjd				 */
6284286763Smav				mutex_enter(&dev->l2ad_mtx);
6285286570Smav				list_insert_head(&dev->l2ad_buflist, head);
6286286763Smav				mutex_exit(&dev->l2ad_mtx);
6287185029Spjd
6288185029Spjd				cb = kmem_alloc(
6289185029Spjd				    sizeof (l2arc_write_callback_t), KM_SLEEP);
6290185029Spjd				cb->l2wcb_dev = dev;
6291185029Spjd				cb->l2wcb_head = head;
6292185029Spjd				pio = zio_root(spa, l2arc_write_done, cb,
6293185029Spjd				    ZIO_FLAG_CANFAIL);
6294205231Skmacy				ARCSTAT_BUMP(arcstat_l2_write_pios);
6295185029Spjd			}
6296185029Spjd
6297185029Spjd			/*
6298185029Spjd			 * Create and add a new L2ARC header.
6299185029Spjd			 */
6300286570Smav			hdr->b_l2hdr.b_dev = dev;
6301275811Sdelphij			hdr->b_flags |= ARC_FLAG_L2_WRITING;
6302251478Sdelphij			/*
6303251478Sdelphij			 * Temporarily stash the data buffer in b_tmp_cdata.
6304251478Sdelphij			 * The subsequent write step will pick it up from
6305286570Smav			 * there. This is because can't access b_l1hdr.b_buf
6306251478Sdelphij			 * without holding the hash_lock, which we in turn
6307251478Sdelphij			 * can't access without holding the ARC list locks
6308251478Sdelphij			 * (which we want to avoid during compression/writing).
6309251478Sdelphij			 */
6310286570Smav			HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_OFF);
6311286570Smav			hdr->b_l2hdr.b_asize = hdr->b_size;
6312286570Smav			hdr->b_l1hdr.b_tmp_cdata = hdr->b_l1hdr.b_buf->b_data;
6313251478Sdelphij
6314286598Smav			/*
6315286598Smav			 * Explicitly set the b_daddr field to a known
6316286598Smav			 * value which means "invalid address". This
6317286598Smav			 * enables us to differentiate which stage of
6318286598Smav			 * l2arc_write_buffers() the particular header
6319286598Smav			 * is in (e.g. this loop, or the one below).
6320286598Smav			 * ARC_FLAG_L2_WRITING is not enough to make
6321286598Smav			 * this distinction, and we need to know in
6322286598Smav			 * order to do proper l2arc vdev accounting in
6323286598Smav			 * arc_release() and arc_hdr_destroy().
6324286598Smav			 *
6325286598Smav			 * Note, we can't use a new flag to distinguish
6326286598Smav			 * the two stages because we don't hold the
6327286598Smav			 * header's hash_lock below, in the second stage
6328286598Smav			 * of this function. Thus, we can't simply
6329286598Smav			 * change the b_flags field to denote that the
6330286598Smav			 * IO has been sent. We can change the b_daddr
6331286598Smav			 * field of the L2 portion, though, since we'll
6332286598Smav			 * be holding the l2ad_mtx; which is why we're
6333286598Smav			 * using it to denote the header's state change.
6334286598Smav			 */
6335286598Smav			hdr->b_l2hdr.b_daddr = L2ARC_ADDR_UNSET;
6336286598Smav
6337275811Sdelphij			buf_sz = hdr->b_size;
6338286570Smav			hdr->b_flags |= ARC_FLAG_HAS_L2HDR;
6339185029Spjd
6340286763Smav			mutex_enter(&dev->l2ad_mtx);
6341286570Smav			list_insert_head(&dev->l2ad_buflist, hdr);
6342286763Smav			mutex_exit(&dev->l2ad_mtx);
6343251478Sdelphij
6344185029Spjd			/*
6345185029Spjd			 * Compute and store the buffer cksum before
6346185029Spjd			 * writing.  On debug the cksum is verified first.
6347185029Spjd			 */
6348286570Smav			arc_cksum_verify(hdr->b_l1hdr.b_buf);
6349286570Smav			arc_cksum_compute(hdr->b_l1hdr.b_buf, B_TRUE);
6350185029Spjd
6351185029Spjd			mutex_exit(hash_lock);
6352185029Spjd
6353251478Sdelphij			write_sz += buf_sz;
6354251478Sdelphij		}
6355251478Sdelphij
6356286763Smav		multilist_sublist_unlock(mls);
6357251478Sdelphij
6358251478Sdelphij		if (full == B_TRUE)
6359251478Sdelphij			break;
6360251478Sdelphij	}
6361251478Sdelphij
6362251478Sdelphij	/* No buffers selected for writing? */
6363251478Sdelphij	if (pio == NULL) {
6364251478Sdelphij		ASSERT0(write_sz);
6365286570Smav		ASSERT(!HDR_HAS_L1HDR(head));
6366286570Smav		kmem_cache_free(hdr_l2only_cache, head);
6367251478Sdelphij		return (0);
6368251478Sdelphij	}
6369251478Sdelphij
6370286763Smav	mutex_enter(&dev->l2ad_mtx);
6371286763Smav
6372251478Sdelphij	/*
6373251478Sdelphij	 * Now start writing the buffers. We're starting at the write head
6374251478Sdelphij	 * and work backwards, retracing the course of the buffer selector
6375251478Sdelphij	 * loop above.
6376251478Sdelphij	 */
6377286570Smav	for (hdr = list_prev(&dev->l2ad_buflist, head); hdr;
6378286570Smav	    hdr = list_prev(&dev->l2ad_buflist, hdr)) {
6379251478Sdelphij		uint64_t buf_sz;
6380251478Sdelphij
6381251478Sdelphij		/*
6382286763Smav		 * We rely on the L1 portion of the header below, so
6383286763Smav		 * it's invalid for this header to have been evicted out
6384286763Smav		 * of the ghost cache, prior to being written out. The
6385286763Smav		 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
6386286763Smav		 */
6387286763Smav		ASSERT(HDR_HAS_L1HDR(hdr));
6388286763Smav
6389286763Smav		/*
6390251478Sdelphij		 * We shouldn't need to lock the buffer here, since we flagged
6391275811Sdelphij		 * it as ARC_FLAG_L2_WRITING in the previous step, but we must
6392275811Sdelphij		 * take care to only access its L2 cache parameters. In
6393286570Smav		 * particular, hdr->l1hdr.b_buf may be invalid by now due to
6394275811Sdelphij		 * ARC eviction.
6395251478Sdelphij		 */
6396286570Smav		hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
6397251478Sdelphij
6398286570Smav		if ((HDR_L2COMPRESS(hdr)) &&
6399286570Smav		    hdr->b_l2hdr.b_asize >= buf_compress_minsz) {
6400286570Smav			if (l2arc_compress_buf(hdr)) {
6401251478Sdelphij				/*
6402251478Sdelphij				 * If compression succeeded, enable headroom
6403251478Sdelphij				 * boost on the next scan cycle.
6404251478Sdelphij				 */
6405251478Sdelphij				*headroom_boost = B_TRUE;
6406251478Sdelphij			}
6407251478Sdelphij		}
6408251478Sdelphij
6409251478Sdelphij		/*
6410251478Sdelphij		 * Pick up the buffer data we had previously stashed away
6411251478Sdelphij		 * (and now potentially also compressed).
6412251478Sdelphij		 */
6413286570Smav		buf_data = hdr->b_l1hdr.b_tmp_cdata;
6414286570Smav		buf_sz = hdr->b_l2hdr.b_asize;
6415251478Sdelphij
6416274172Savg		/*
6417274172Savg		 * If the data has not been compressed, then clear b_tmp_cdata
6418274172Savg		 * to make sure that it points only to a temporary compression
6419274172Savg		 * buffer.
6420274172Savg		 */
6421286570Smav		if (!L2ARC_IS_VALID_COMPRESS(HDR_GET_COMPRESS(hdr)))
6422286570Smav			hdr->b_l1hdr.b_tmp_cdata = NULL;
6423274172Savg
6424286598Smav		/*
6425286598Smav		 * We need to do this regardless if buf_sz is zero or
6426286598Smav		 * not, otherwise, when this l2hdr is evicted we'll
6427286598Smav		 * remove a reference that was never added.
6428286598Smav		 */
6429286598Smav		(void) refcount_add_many(&dev->l2ad_alloc, buf_sz, hdr);
6430286598Smav
6431251478Sdelphij		/* Compression may have squashed the buffer to zero length. */
6432251478Sdelphij		if (buf_sz != 0) {
6433251478Sdelphij			uint64_t buf_p_sz;
6434251478Sdelphij
6435185029Spjd			wzio = zio_write_phys(pio, dev->l2ad_vdev,
6436185029Spjd			    dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
6437185029Spjd			    NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
6438185029Spjd			    ZIO_FLAG_CANFAIL, B_FALSE);
6439185029Spjd
6440185029Spjd			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
6441185029Spjd			    zio_t *, wzio);
6442185029Spjd			(void) zio_nowait(wzio);
6443185029Spjd
6444251478Sdelphij			write_asize += buf_sz;
6445286598Smav
6446185029Spjd			/*
6447185029Spjd			 * Keep the clock hand suitably device-aligned.
6448185029Spjd			 */
6449251478Sdelphij			buf_p_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
6450251478Sdelphij			write_psize += buf_p_sz;
6451251478Sdelphij			dev->l2ad_hand += buf_p_sz;
6452185029Spjd		}
6453251478Sdelphij	}
6454185029Spjd
6455286570Smav	mutex_exit(&dev->l2ad_mtx);
6456185029Spjd
6457251478Sdelphij	ASSERT3U(write_asize, <=, target_sz);
6458185029Spjd	ARCSTAT_BUMP(arcstat_l2_writes_sent);
6459251478Sdelphij	ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
6460185029Spjd	ARCSTAT_INCR(arcstat_l2_size, write_sz);
6461251478Sdelphij	ARCSTAT_INCR(arcstat_l2_asize, write_asize);
6462275096Sdelphij	vdev_space_update(dev->l2ad_vdev, write_asize, 0, 0);
6463185029Spjd
6464185029Spjd	/*
6465185029Spjd	 * Bump device hand to the device start if it is approaching the end.
6466185029Spjd	 * l2arc_evict() will already have evicted ahead for this case.
6467185029Spjd	 */
6468185029Spjd	if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
6469185029Spjd		dev->l2ad_hand = dev->l2ad_start;
6470185029Spjd		dev->l2ad_first = B_FALSE;
6471185029Spjd	}
6472185029Spjd
6473208373Smm	dev->l2ad_writing = B_TRUE;
6474185029Spjd	(void) zio_wait(pio);
6475208373Smm	dev->l2ad_writing = B_FALSE;
6476208373Smm
6477251478Sdelphij	return (write_asize);
6478185029Spjd}
6479185029Spjd
6480185029Spjd/*
6481251478Sdelphij * Compresses an L2ARC buffer.
6482286570Smav * The data to be compressed must be prefilled in l1hdr.b_tmp_cdata and its
6483251478Sdelphij * size in l2hdr->b_asize. This routine tries to compress the data and
6484251478Sdelphij * depending on the compression result there are three possible outcomes:
6485251478Sdelphij * *) The buffer was incompressible. The original l2hdr contents were left
6486251478Sdelphij *    untouched and are ready for writing to an L2 device.
6487251478Sdelphij * *) The buffer was all-zeros, so there is no need to write it to an L2
6488251478Sdelphij *    device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
6489251478Sdelphij *    set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
6490251478Sdelphij * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
6491251478Sdelphij *    data buffer which holds the compressed data to be written, and b_asize
6492251478Sdelphij *    tells us how much data there is. b_compress is set to the appropriate
6493251478Sdelphij *    compression algorithm. Once writing is done, invoke
6494251478Sdelphij *    l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
6495251478Sdelphij *
6496251478Sdelphij * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
6497251478Sdelphij * buffer was incompressible).
6498251478Sdelphij */
6499251478Sdelphijstatic boolean_t
6500286570Smavl2arc_compress_buf(arc_buf_hdr_t *hdr)
6501251478Sdelphij{
6502251478Sdelphij	void *cdata;
6503268075Sdelphij	size_t csize, len, rounded;
6504286570Smav	ASSERT(HDR_HAS_L2HDR(hdr));
6505286570Smav	l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
6506251478Sdelphij
6507286570Smav	ASSERT(HDR_HAS_L1HDR(hdr));
6508286570Smav	ASSERT(HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_OFF);
6509286570Smav	ASSERT(hdr->b_l1hdr.b_tmp_cdata != NULL);
6510251478Sdelphij
6511251478Sdelphij	len = l2hdr->b_asize;
6512251478Sdelphij	cdata = zio_data_buf_alloc(len);
6513286570Smav	ASSERT3P(cdata, !=, NULL);
6514286570Smav	csize = zio_compress_data(ZIO_COMPRESS_LZ4, hdr->b_l1hdr.b_tmp_cdata,
6515269086Sdelphij	    cdata, l2hdr->b_asize);
6516251478Sdelphij
6517251478Sdelphij	if (csize == 0) {
6518251478Sdelphij		/* zero block, indicate that there's nothing to write */
6519251478Sdelphij		zio_data_buf_free(cdata, len);
6520286570Smav		HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_EMPTY);
6521251478Sdelphij		l2hdr->b_asize = 0;
6522286570Smav		hdr->b_l1hdr.b_tmp_cdata = NULL;
6523251478Sdelphij		ARCSTAT_BUMP(arcstat_l2_compress_zeros);
6524251478Sdelphij		return (B_TRUE);
6525274628Savg	}
6526274628Savg
6527274628Savg	rounded = P2ROUNDUP(csize,
6528274628Savg	    (size_t)1 << l2hdr->b_dev->l2ad_vdev->vdev_ashift);
6529274628Savg	if (rounded < len) {
6530251478Sdelphij		/*
6531251478Sdelphij		 * Compression succeeded, we'll keep the cdata around for
6532251478Sdelphij		 * writing and release it afterwards.
6533251478Sdelphij		 */
6534274628Savg		if (rounded > csize) {
6535274628Savg			bzero((char *)cdata + csize, rounded - csize);
6536274628Savg			csize = rounded;
6537274628Savg		}
6538286570Smav		HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_LZ4);
6539251478Sdelphij		l2hdr->b_asize = csize;
6540286570Smav		hdr->b_l1hdr.b_tmp_cdata = cdata;
6541251478Sdelphij		ARCSTAT_BUMP(arcstat_l2_compress_successes);
6542251478Sdelphij		return (B_TRUE);
6543251478Sdelphij	} else {
6544251478Sdelphij		/*
6545251478Sdelphij		 * Compression failed, release the compressed buffer.
6546251478Sdelphij		 * l2hdr will be left unmodified.
6547251478Sdelphij		 */
6548251478Sdelphij		zio_data_buf_free(cdata, len);
6549251478Sdelphij		ARCSTAT_BUMP(arcstat_l2_compress_failures);
6550251478Sdelphij		return (B_FALSE);
6551251478Sdelphij	}
6552251478Sdelphij}
6553251478Sdelphij
6554251478Sdelphij/*
6555251478Sdelphij * Decompresses a zio read back from an l2arc device. On success, the
6556251478Sdelphij * underlying zio's io_data buffer is overwritten by the uncompressed
6557251478Sdelphij * version. On decompression error (corrupt compressed stream), the
6558251478Sdelphij * zio->io_error value is set to signal an I/O error.
6559251478Sdelphij *
6560251478Sdelphij * Please note that the compressed data stream is not checksummed, so
6561251478Sdelphij * if the underlying device is experiencing data corruption, we may feed
6562251478Sdelphij * corrupt data to the decompressor, so the decompressor needs to be
6563251478Sdelphij * able to handle this situation (LZ4 does).
6564251478Sdelphij */
6565251478Sdelphijstatic void
6566251478Sdelphijl2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
6567251478Sdelphij{
6568251478Sdelphij	ASSERT(L2ARC_IS_VALID_COMPRESS(c));
6569251478Sdelphij
6570251478Sdelphij	if (zio->io_error != 0) {
6571251478Sdelphij		/*
6572251478Sdelphij		 * An io error has occured, just restore the original io
6573251478Sdelphij		 * size in preparation for a main pool read.
6574251478Sdelphij		 */
6575251478Sdelphij		zio->io_orig_size = zio->io_size = hdr->b_size;
6576251478Sdelphij		return;
6577251478Sdelphij	}
6578251478Sdelphij
6579251478Sdelphij	if (c == ZIO_COMPRESS_EMPTY) {
6580251478Sdelphij		/*
6581251478Sdelphij		 * An empty buffer results in a null zio, which means we
6582251478Sdelphij		 * need to fill its io_data after we're done restoring the
6583251478Sdelphij		 * buffer's contents.
6584251478Sdelphij		 */
6585286570Smav		ASSERT(hdr->b_l1hdr.b_buf != NULL);
6586286570Smav		bzero(hdr->b_l1hdr.b_buf->b_data, hdr->b_size);
6587286570Smav		zio->io_data = zio->io_orig_data = hdr->b_l1hdr.b_buf->b_data;
6588251478Sdelphij	} else {
6589251478Sdelphij		ASSERT(zio->io_data != NULL);
6590251478Sdelphij		/*
6591251478Sdelphij		 * We copy the compressed data from the start of the arc buffer
6592251478Sdelphij		 * (the zio_read will have pulled in only what we need, the
6593251478Sdelphij		 * rest is garbage which we will overwrite at decompression)
6594251478Sdelphij		 * and then decompress back to the ARC data buffer. This way we
6595251478Sdelphij		 * can minimize copying by simply decompressing back over the
6596251478Sdelphij		 * original compressed data (rather than decompressing to an
6597251478Sdelphij		 * aux buffer and then copying back the uncompressed buffer,
6598251478Sdelphij		 * which is likely to be much larger).
6599251478Sdelphij		 */
6600251478Sdelphij		uint64_t csize;
6601251478Sdelphij		void *cdata;
6602251478Sdelphij
6603251478Sdelphij		csize = zio->io_size;
6604251478Sdelphij		cdata = zio_data_buf_alloc(csize);
6605251478Sdelphij		bcopy(zio->io_data, cdata, csize);
6606251478Sdelphij		if (zio_decompress_data(c, cdata, zio->io_data, csize,
6607251478Sdelphij		    hdr->b_size) != 0)
6608251478Sdelphij			zio->io_error = EIO;
6609251478Sdelphij		zio_data_buf_free(cdata, csize);
6610251478Sdelphij	}
6611251478Sdelphij
6612251478Sdelphij	/* Restore the expected uncompressed IO size. */
6613251478Sdelphij	zio->io_orig_size = zio->io_size = hdr->b_size;
6614251478Sdelphij}
6615251478Sdelphij
6616251478Sdelphij/*
6617251478Sdelphij * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
6618251478Sdelphij * This buffer serves as a temporary holder of compressed data while
6619251478Sdelphij * the buffer entry is being written to an l2arc device. Once that is
6620251478Sdelphij * done, we can dispose of it.
6621251478Sdelphij */
6622251478Sdelphijstatic void
6623275811Sdelphijl2arc_release_cdata_buf(arc_buf_hdr_t *hdr)
6624251478Sdelphij{
6625286763Smav	enum zio_compress comp = HDR_GET_COMPRESS(hdr);
6626286763Smav
6627286570Smav	ASSERT(HDR_HAS_L1HDR(hdr));
6628286763Smav	ASSERT(comp == ZIO_COMPRESS_OFF || L2ARC_IS_VALID_COMPRESS(comp));
6629286763Smav
6630286763Smav	if (comp == ZIO_COMPRESS_OFF) {
6631251478Sdelphij		/*
6632286763Smav		 * In this case, b_tmp_cdata points to the same buffer
6633286763Smav		 * as the arc_buf_t's b_data field. We don't want to
6634286763Smav		 * free it, since the arc_buf_t will handle that.
6635286763Smav		 */
6636286763Smav		hdr->b_l1hdr.b_tmp_cdata = NULL;
6637286763Smav	} else if (comp == ZIO_COMPRESS_EMPTY) {
6638286763Smav		/*
6639286763Smav		 * In this case, b_tmp_cdata was compressed to an empty
6640286763Smav		 * buffer, thus there's nothing to free and b_tmp_cdata
6641286763Smav		 * should have been set to NULL in l2arc_write_buffers().
6642286763Smav		 */
6643286763Smav		ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
6644286763Smav	} else {
6645286763Smav		/*
6646251478Sdelphij		 * If the data was compressed, then we've allocated a
6647251478Sdelphij		 * temporary buffer for it, so now we need to release it.
6648251478Sdelphij		 */
6649286570Smav		ASSERT(hdr->b_l1hdr.b_tmp_cdata != NULL);
6650286570Smav		zio_data_buf_free(hdr->b_l1hdr.b_tmp_cdata,
6651286570Smav		    hdr->b_size);
6652286570Smav		hdr->b_l1hdr.b_tmp_cdata = NULL;
6653251478Sdelphij	}
6654251478Sdelphij}
6655251478Sdelphij
6656251478Sdelphij/*
6657185029Spjd * This thread feeds the L2ARC at regular intervals.  This is the beating
6658185029Spjd * heart of the L2ARC.
6659185029Spjd */
6660185029Spjdstatic void
6661185029Spjdl2arc_feed_thread(void *dummy __unused)
6662185029Spjd{
6663185029Spjd	callb_cpr_t cpr;
6664185029Spjd	l2arc_dev_t *dev;
6665185029Spjd	spa_t *spa;
6666208373Smm	uint64_t size, wrote;
6667219089Spjd	clock_t begin, next = ddi_get_lbolt();
6668251478Sdelphij	boolean_t headroom_boost = B_FALSE;
6669185029Spjd
6670185029Spjd	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
6671185029Spjd
6672185029Spjd	mutex_enter(&l2arc_feed_thr_lock);
6673185029Spjd
6674185029Spjd	while (l2arc_thread_exit == 0) {
6675185029Spjd		CALLB_CPR_SAFE_BEGIN(&cpr);
6676185029Spjd		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
6677219089Spjd		    next - ddi_get_lbolt());
6678185029Spjd		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
6679219089Spjd		next = ddi_get_lbolt() + hz;
6680185029Spjd
6681185029Spjd		/*
6682185029Spjd		 * Quick check for L2ARC devices.
6683185029Spjd		 */
6684185029Spjd		mutex_enter(&l2arc_dev_mtx);
6685185029Spjd		if (l2arc_ndev == 0) {
6686185029Spjd			mutex_exit(&l2arc_dev_mtx);
6687185029Spjd			continue;
6688185029Spjd		}
6689185029Spjd		mutex_exit(&l2arc_dev_mtx);
6690219089Spjd		begin = ddi_get_lbolt();
6691185029Spjd
6692185029Spjd		/*
6693185029Spjd		 * This selects the next l2arc device to write to, and in
6694185029Spjd		 * doing so the next spa to feed from: dev->l2ad_spa.   This
6695185029Spjd		 * will return NULL if there are now no l2arc devices or if
6696185029Spjd		 * they are all faulted.
6697185029Spjd		 *
6698185029Spjd		 * If a device is returned, its spa's config lock is also
6699185029Spjd		 * held to prevent device removal.  l2arc_dev_get_next()
6700185029Spjd		 * will grab and release l2arc_dev_mtx.
6701185029Spjd		 */
6702185029Spjd		if ((dev = l2arc_dev_get_next()) == NULL)
6703185029Spjd			continue;
6704185029Spjd
6705185029Spjd		spa = dev->l2ad_spa;
6706185029Spjd		ASSERT(spa != NULL);
6707185029Spjd
6708185029Spjd		/*
6709219089Spjd		 * If the pool is read-only then force the feed thread to
6710219089Spjd		 * sleep a little longer.
6711219089Spjd		 */
6712219089Spjd		if (!spa_writeable(spa)) {
6713219089Spjd			next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
6714219089Spjd			spa_config_exit(spa, SCL_L2ARC, dev);
6715219089Spjd			continue;
6716219089Spjd		}
6717219089Spjd
6718219089Spjd		/*
6719185029Spjd		 * Avoid contributing to memory pressure.
6720185029Spjd		 */
6721185029Spjd		if (arc_reclaim_needed()) {
6722185029Spjd			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
6723185029Spjd			spa_config_exit(spa, SCL_L2ARC, dev);
6724185029Spjd			continue;
6725185029Spjd		}
6726185029Spjd
6727185029Spjd		ARCSTAT_BUMP(arcstat_l2_feeds);
6728185029Spjd
6729251478Sdelphij		size = l2arc_write_size();
6730185029Spjd
6731185029Spjd		/*
6732185029Spjd		 * Evict L2ARC buffers that will be overwritten.
6733185029Spjd		 */
6734185029Spjd		l2arc_evict(dev, size, B_FALSE);
6735185029Spjd
6736185029Spjd		/*
6737185029Spjd		 * Write ARC buffers.
6738185029Spjd		 */
6739251478Sdelphij		wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
6740208373Smm
6741208373Smm		/*
6742208373Smm		 * Calculate interval between writes.
6743208373Smm		 */
6744208373Smm		next = l2arc_write_interval(begin, size, wrote);
6745185029Spjd		spa_config_exit(spa, SCL_L2ARC, dev);
6746185029Spjd	}
6747185029Spjd
6748185029Spjd	l2arc_thread_exit = 0;
6749185029Spjd	cv_broadcast(&l2arc_feed_thr_cv);
6750185029Spjd	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
6751185029Spjd	thread_exit();
6752185029Spjd}
6753185029Spjd
6754185029Spjdboolean_t
6755185029Spjdl2arc_vdev_present(vdev_t *vd)
6756185029Spjd{
6757185029Spjd	l2arc_dev_t *dev;
6758185029Spjd
6759185029Spjd	mutex_enter(&l2arc_dev_mtx);
6760185029Spjd	for (dev = list_head(l2arc_dev_list); dev != NULL;
6761185029Spjd	    dev = list_next(l2arc_dev_list, dev)) {
6762185029Spjd		if (dev->l2ad_vdev == vd)
6763185029Spjd			break;
6764185029Spjd	}
6765185029Spjd	mutex_exit(&l2arc_dev_mtx);
6766185029Spjd
6767185029Spjd	return (dev != NULL);
6768185029Spjd}
6769185029Spjd
6770185029Spjd/*
6771185029Spjd * Add a vdev for use by the L2ARC.  By this point the spa has already
6772185029Spjd * validated the vdev and opened it.
6773185029Spjd */
6774185029Spjdvoid
6775219089Spjdl2arc_add_vdev(spa_t *spa, vdev_t *vd)
6776185029Spjd{
6777185029Spjd	l2arc_dev_t *adddev;
6778185029Spjd
6779185029Spjd	ASSERT(!l2arc_vdev_present(vd));
6780185029Spjd
6781255753Sgibbs	vdev_ashift_optimize(vd);
6782255753Sgibbs
6783185029Spjd	/*
6784185029Spjd	 * Create a new l2arc device entry.
6785185029Spjd	 */
6786185029Spjd	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
6787185029Spjd	adddev->l2ad_spa = spa;
6788185029Spjd	adddev->l2ad_vdev = vd;
6789219089Spjd	adddev->l2ad_start = VDEV_LABEL_START_SIZE;
6790219089Spjd	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
6791185029Spjd	adddev->l2ad_hand = adddev->l2ad_start;
6792185029Spjd	adddev->l2ad_first = B_TRUE;
6793208373Smm	adddev->l2ad_writing = B_FALSE;
6794185029Spjd
6795286570Smav	mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
6796185029Spjd	/*
6797185029Spjd	 * This is a list of all ARC buffers that are still valid on the
6798185029Spjd	 * device.
6799185029Spjd	 */
6800286570Smav	list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
6801286570Smav	    offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
6802185029Spjd
6803219089Spjd	vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
6804286598Smav	refcount_create(&adddev->l2ad_alloc);
6805185029Spjd
6806185029Spjd	/*
6807185029Spjd	 * Add device to global list
6808185029Spjd	 */
6809185029Spjd	mutex_enter(&l2arc_dev_mtx);
6810185029Spjd	list_insert_head(l2arc_dev_list, adddev);
6811185029Spjd	atomic_inc_64(&l2arc_ndev);
6812185029Spjd	mutex_exit(&l2arc_dev_mtx);
6813185029Spjd}
6814185029Spjd
6815185029Spjd/*
6816185029Spjd * Remove a vdev from the L2ARC.
6817185029Spjd */
6818185029Spjdvoid
6819185029Spjdl2arc_remove_vdev(vdev_t *vd)
6820185029Spjd{
6821185029Spjd	l2arc_dev_t *dev, *nextdev, *remdev = NULL;
6822185029Spjd
6823185029Spjd	/*
6824185029Spjd	 * Find the device by vdev
6825185029Spjd	 */
6826185029Spjd	mutex_enter(&l2arc_dev_mtx);
6827185029Spjd	for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
6828185029Spjd		nextdev = list_next(l2arc_dev_list, dev);
6829185029Spjd		if (vd == dev->l2ad_vdev) {
6830185029Spjd			remdev = dev;
6831185029Spjd			break;
6832185029Spjd		}
6833185029Spjd	}
6834185029Spjd	ASSERT(remdev != NULL);
6835185029Spjd
6836185029Spjd	/*
6837185029Spjd	 * Remove device from global list
6838185029Spjd	 */
6839185029Spjd	list_remove(l2arc_dev_list, remdev);
6840185029Spjd	l2arc_dev_last = NULL;		/* may have been invalidated */
6841185029Spjd	atomic_dec_64(&l2arc_ndev);
6842185029Spjd	mutex_exit(&l2arc_dev_mtx);
6843185029Spjd
6844185029Spjd	/*
6845185029Spjd	 * Clear all buflists and ARC references.  L2ARC device flush.
6846185029Spjd	 */
6847185029Spjd	l2arc_evict(remdev, 0, B_TRUE);
6848286570Smav	list_destroy(&remdev->l2ad_buflist);
6849286570Smav	mutex_destroy(&remdev->l2ad_mtx);
6850286598Smav	refcount_destroy(&remdev->l2ad_alloc);
6851185029Spjd	kmem_free(remdev, sizeof (l2arc_dev_t));
6852185029Spjd}
6853185029Spjd
6854185029Spjdvoid
6855185029Spjdl2arc_init(void)
6856185029Spjd{
6857185029Spjd	l2arc_thread_exit = 0;
6858185029Spjd	l2arc_ndev = 0;
6859185029Spjd	l2arc_writes_sent = 0;
6860185029Spjd	l2arc_writes_done = 0;
6861185029Spjd
6862185029Spjd	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
6863185029Spjd	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
6864185029Spjd	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
6865185029Spjd	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
6866185029Spjd
6867185029Spjd	l2arc_dev_list = &L2ARC_dev_list;
6868185029Spjd	l2arc_free_on_write = &L2ARC_free_on_write;
6869185029Spjd	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
6870185029Spjd	    offsetof(l2arc_dev_t, l2ad_node));
6871185029Spjd	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
6872185029Spjd	    offsetof(l2arc_data_free_t, l2df_list_node));
6873185029Spjd}
6874185029Spjd
6875185029Spjdvoid
6876185029Spjdl2arc_fini(void)
6877185029Spjd{
6878185029Spjd	/*
6879185029Spjd	 * This is called from dmu_fini(), which is called from spa_fini();
6880185029Spjd	 * Because of this, we can assume that all l2arc devices have
6881185029Spjd	 * already been removed when the pools themselves were removed.
6882185029Spjd	 */
6883185029Spjd
6884185029Spjd	l2arc_do_free_on_write();
6885185029Spjd
6886185029Spjd	mutex_destroy(&l2arc_feed_thr_lock);
6887185029Spjd	cv_destroy(&l2arc_feed_thr_cv);
6888185029Spjd	mutex_destroy(&l2arc_dev_mtx);
6889185029Spjd	mutex_destroy(&l2arc_free_on_write_mtx);
6890185029Spjd
6891185029Spjd	list_destroy(l2arc_dev_list);
6892185029Spjd	list_destroy(l2arc_free_on_write);
6893185029Spjd}
6894185029Spjd
6895185029Spjdvoid
6896185029Spjdl2arc_start(void)
6897185029Spjd{
6898209962Smm	if (!(spa_mode_global & FWRITE))
6899185029Spjd		return;
6900185029Spjd
6901185029Spjd	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
6902185029Spjd	    TS_RUN, minclsyspri);
6903185029Spjd}
6904185029Spjd
6905185029Spjdvoid
6906185029Spjdl2arc_stop(void)
6907185029Spjd{
6908209962Smm	if (!(spa_mode_global & FWRITE))
6909185029Spjd		return;
6910185029Spjd
6911185029Spjd	mutex_enter(&l2arc_feed_thr_lock);
6912185029Spjd	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
6913185029Spjd	l2arc_thread_exit = 1;
6914185029Spjd	while (l2arc_thread_exit != 0)
6915185029Spjd		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
6916185029Spjd	mutex_exit(&l2arc_feed_thr_lock);
6917185029Spjd}
6918