arc.c revision 286764
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.
24268123Sdelphij * Copyright (c) 2011, 2014 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 *
85168404Spjd * Buffers do not have their own mutexs, rather they rely on the
86168404Spjd * hash table mutexs for the bulk of their protection (i.e. most
87168404Spjd * fields in the arc_buf_hdr_t are protected by these mutexs).
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	 */
350286763Smav	uint64_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,
1030205231Skmacy    &ARC_anon.arcs_size, 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,
1037205231Skmacy    &ARC_mru.arcs_size, 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,
1044205231Skmacy    &ARC_mru_ghost.arcs_size, 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,
1053205231Skmacy    &ARC_mfu.arcs_size, 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,
1060205231Skmacy    &ARC_mfu_ghost.arcs_size, 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,
1069205231Skmacy    &ARC_l2c_only.arcs_size, 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) */
1863286570Smav	if (to_delta && new_state != arc_l2c_only)
1864168404Spjd		atomic_add_64(&new_state->arcs_size, to_delta);
1865286570Smav	if (from_delta && old_state != arc_l2c_only) {
1866168404Spjd		ASSERT3U(old_state->arcs_size, >=, from_delta);
1867168404Spjd		atomic_add_64(&old_state->arcs_size, -from_delta);
1868168404Spjd	}
1869286570Smav	if (HDR_HAS_L1HDR(hdr))
1870286570Smav		hdr->b_l1hdr.b_state = new_state;
1871185029Spjd
1872286570Smav	/*
1873286570Smav	 * L2 headers should never be on the L2 state list since they don't
1874286570Smav	 * have L1 headers allocated.
1875286570Smav	 */
1876286763Smav	ASSERT(multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
1877286763Smav	    multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
1878168404Spjd}
1879168404Spjd
1880185029Spjdvoid
1881208373Smmarc_space_consume(uint64_t space, arc_space_type_t type)
1882185029Spjd{
1883208373Smm	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1884208373Smm
1885208373Smm	switch (type) {
1886208373Smm	case ARC_SPACE_DATA:
1887208373Smm		ARCSTAT_INCR(arcstat_data_size, space);
1888208373Smm		break;
1889286574Smav	case ARC_SPACE_META:
1890286574Smav		ARCSTAT_INCR(arcstat_metadata_size, space);
1891286574Smav		break;
1892208373Smm	case ARC_SPACE_OTHER:
1893208373Smm		ARCSTAT_INCR(arcstat_other_size, space);
1894208373Smm		break;
1895208373Smm	case ARC_SPACE_HDRS:
1896208373Smm		ARCSTAT_INCR(arcstat_hdr_size, space);
1897208373Smm		break;
1898208373Smm	case ARC_SPACE_L2HDRS:
1899208373Smm		ARCSTAT_INCR(arcstat_l2_hdr_size, space);
1900208373Smm		break;
1901208373Smm	}
1902208373Smm
1903286574Smav	if (type != ARC_SPACE_DATA)
1904286574Smav		ARCSTAT_INCR(arcstat_meta_used, space);
1905286574Smav
1906185029Spjd	atomic_add_64(&arc_size, space);
1907185029Spjd}
1908185029Spjd
1909185029Spjdvoid
1910208373Smmarc_space_return(uint64_t space, arc_space_type_t type)
1911185029Spjd{
1912208373Smm	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1913208373Smm
1914208373Smm	switch (type) {
1915208373Smm	case ARC_SPACE_DATA:
1916208373Smm		ARCSTAT_INCR(arcstat_data_size, -space);
1917208373Smm		break;
1918286574Smav	case ARC_SPACE_META:
1919286574Smav		ARCSTAT_INCR(arcstat_metadata_size, -space);
1920286574Smav		break;
1921208373Smm	case ARC_SPACE_OTHER:
1922208373Smm		ARCSTAT_INCR(arcstat_other_size, -space);
1923208373Smm		break;
1924208373Smm	case ARC_SPACE_HDRS:
1925208373Smm		ARCSTAT_INCR(arcstat_hdr_size, -space);
1926208373Smm		break;
1927208373Smm	case ARC_SPACE_L2HDRS:
1928208373Smm		ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
1929208373Smm		break;
1930208373Smm	}
1931208373Smm
1932286574Smav	if (type != ARC_SPACE_DATA) {
1933286574Smav		ASSERT(arc_meta_used >= space);
1934286574Smav		if (arc_meta_max < arc_meta_used)
1935286574Smav			arc_meta_max = arc_meta_used;
1936286574Smav		ARCSTAT_INCR(arcstat_meta_used, -space);
1937286574Smav	}
1938286574Smav
1939185029Spjd	ASSERT(arc_size >= space);
1940185029Spjd	atomic_add_64(&arc_size, -space);
1941185029Spjd}
1942185029Spjd
1943168404Spjdarc_buf_t *
1944286570Smavarc_buf_alloc(spa_t *spa, int32_t size, void *tag, arc_buf_contents_t type)
1945168404Spjd{
1946168404Spjd	arc_buf_hdr_t *hdr;
1947168404Spjd	arc_buf_t *buf;
1948168404Spjd
1949168404Spjd	ASSERT3U(size, >, 0);
1950286570Smav	hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
1951168404Spjd	ASSERT(BUF_EMPTY(hdr));
1952286570Smav	ASSERT3P(hdr->b_freeze_cksum, ==, NULL);
1953168404Spjd	hdr->b_size = size;
1954228103Smm	hdr->b_spa = spa_load_guid(spa);
1955286570Smav
1956185029Spjd	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1957168404Spjd	buf->b_hdr = hdr;
1958168404Spjd	buf->b_data = NULL;
1959168404Spjd	buf->b_efunc = NULL;
1960168404Spjd	buf->b_private = NULL;
1961168404Spjd	buf->b_next = NULL;
1962286570Smav
1963286570Smav	hdr->b_flags = arc_bufc_to_flags(type);
1964286570Smav	hdr->b_flags |= ARC_FLAG_HAS_L1HDR;
1965286570Smav
1966286570Smav	hdr->b_l1hdr.b_buf = buf;
1967286570Smav	hdr->b_l1hdr.b_state = arc_anon;
1968286570Smav	hdr->b_l1hdr.b_arc_access = 0;
1969286570Smav	hdr->b_l1hdr.b_datacnt = 1;
1970286763Smav	hdr->b_l1hdr.b_tmp_cdata = NULL;
1971286570Smav
1972168404Spjd	arc_get_data_buf(buf);
1973286570Smav	ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
1974286570Smav	(void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
1975168404Spjd
1976168404Spjd	return (buf);
1977168404Spjd}
1978168404Spjd
1979209962Smmstatic char *arc_onloan_tag = "onloan";
1980209962Smm
1981209962Smm/*
1982209962Smm * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
1983209962Smm * flight data by arc_tempreserve_space() until they are "returned". Loaned
1984209962Smm * buffers must be returned to the arc before they can be used by the DMU or
1985209962Smm * freed.
1986209962Smm */
1987209962Smmarc_buf_t *
1988209962Smmarc_loan_buf(spa_t *spa, int size)
1989209962Smm{
1990209962Smm	arc_buf_t *buf;
1991209962Smm
1992209962Smm	buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
1993209962Smm
1994209962Smm	atomic_add_64(&arc_loaned_bytes, size);
1995209962Smm	return (buf);
1996209962Smm}
1997209962Smm
1998209962Smm/*
1999209962Smm * Return a loaned arc buffer to the arc.
2000209962Smm */
2001209962Smmvoid
2002209962Smmarc_return_buf(arc_buf_t *buf, void *tag)
2003209962Smm{
2004209962Smm	arc_buf_hdr_t *hdr = buf->b_hdr;
2005209962Smm
2006209962Smm	ASSERT(buf->b_data != NULL);
2007286570Smav	ASSERT(HDR_HAS_L1HDR(hdr));
2008286570Smav	(void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2009286570Smav	(void) refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2010209962Smm
2011209962Smm	atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
2012209962Smm}
2013209962Smm
2014219089Spjd/* Detach an arc_buf from a dbuf (tag) */
2015219089Spjdvoid
2016219089Spjdarc_loan_inuse_buf(arc_buf_t *buf, void *tag)
2017219089Spjd{
2018286570Smav	arc_buf_hdr_t *hdr = buf->b_hdr;
2019219089Spjd
2020219089Spjd	ASSERT(buf->b_data != NULL);
2021286570Smav	ASSERT(HDR_HAS_L1HDR(hdr));
2022286570Smav	(void) refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2023286570Smav	(void) refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
2024219089Spjd	buf->b_efunc = NULL;
2025219089Spjd	buf->b_private = NULL;
2026219089Spjd
2027219089Spjd	atomic_add_64(&arc_loaned_bytes, hdr->b_size);
2028219089Spjd}
2029219089Spjd
2030168404Spjdstatic arc_buf_t *
2031168404Spjdarc_buf_clone(arc_buf_t *from)
2032168404Spjd{
2033168404Spjd	arc_buf_t *buf;
2034168404Spjd	arc_buf_hdr_t *hdr = from->b_hdr;
2035168404Spjd	uint64_t size = hdr->b_size;
2036168404Spjd
2037286570Smav	ASSERT(HDR_HAS_L1HDR(hdr));
2038286570Smav	ASSERT(hdr->b_l1hdr.b_state != arc_anon);
2039219089Spjd
2040185029Spjd	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2041168404Spjd	buf->b_hdr = hdr;
2042168404Spjd	buf->b_data = NULL;
2043168404Spjd	buf->b_efunc = NULL;
2044168404Spjd	buf->b_private = NULL;
2045286570Smav	buf->b_next = hdr->b_l1hdr.b_buf;
2046286570Smav	hdr->b_l1hdr.b_buf = buf;
2047168404Spjd	arc_get_data_buf(buf);
2048168404Spjd	bcopy(from->b_data, buf->b_data, size);
2049242845Sdelphij
2050242845Sdelphij	/*
2051242845Sdelphij	 * This buffer already exists in the arc so create a duplicate
2052242845Sdelphij	 * copy for the caller.  If the buffer is associated with user data
2053242845Sdelphij	 * then track the size and number of duplicates.  These stats will be
2054242845Sdelphij	 * updated as duplicate buffers are created and destroyed.
2055242845Sdelphij	 */
2056286570Smav	if (HDR_ISTYPE_DATA(hdr)) {
2057242845Sdelphij		ARCSTAT_BUMP(arcstat_duplicate_buffers);
2058242845Sdelphij		ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
2059242845Sdelphij	}
2060286570Smav	hdr->b_l1hdr.b_datacnt += 1;
2061168404Spjd	return (buf);
2062168404Spjd}
2063168404Spjd
2064168404Spjdvoid
2065168404Spjdarc_buf_add_ref(arc_buf_t *buf, void* tag)
2066168404Spjd{
2067168404Spjd	arc_buf_hdr_t *hdr;
2068168404Spjd	kmutex_t *hash_lock;
2069168404Spjd
2070168404Spjd	/*
2071185029Spjd	 * Check to see if this buffer is evicted.  Callers
2072185029Spjd	 * must verify b_data != NULL to know if the add_ref
2073185029Spjd	 * was successful.
2074168404Spjd	 */
2075219089Spjd	mutex_enter(&buf->b_evict_lock);
2076185029Spjd	if (buf->b_data == NULL) {
2077219089Spjd		mutex_exit(&buf->b_evict_lock);
2078168404Spjd		return;
2079168404Spjd	}
2080219089Spjd	hash_lock = HDR_LOCK(buf->b_hdr);
2081219089Spjd	mutex_enter(hash_lock);
2082185029Spjd	hdr = buf->b_hdr;
2083286570Smav	ASSERT(HDR_HAS_L1HDR(hdr));
2084219089Spjd	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2085219089Spjd	mutex_exit(&buf->b_evict_lock);
2086168404Spjd
2087286570Smav	ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
2088286570Smav	    hdr->b_l1hdr.b_state == arc_mfu);
2089286570Smav
2090168404Spjd	add_reference(hdr, hash_lock, tag);
2091208373Smm	DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
2092168404Spjd	arc_access(hdr, hash_lock);
2093168404Spjd	mutex_exit(hash_lock);
2094168404Spjd	ARCSTAT_BUMP(arcstat_hits);
2095286570Smav	ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
2096286570Smav	    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
2097168404Spjd	    data, metadata, hits);
2098168404Spjd}
2099168404Spjd
2100274172Savgstatic void
2101274172Savgarc_buf_free_on_write(void *data, size_t size,
2102274172Savg    void (*free_func)(void *, size_t))
2103274172Savg{
2104274172Savg	l2arc_data_free_t *df;
2105274172Savg
2106286763Smav	df = kmem_alloc(sizeof (*df), KM_SLEEP);
2107274172Savg	df->l2df_data = data;
2108274172Savg	df->l2df_size = size;
2109274172Savg	df->l2df_func = free_func;
2110274172Savg	mutex_enter(&l2arc_free_on_write_mtx);
2111274172Savg	list_insert_head(l2arc_free_on_write, df);
2112274172Savg	mutex_exit(&l2arc_free_on_write_mtx);
2113274172Savg}
2114274172Savg
2115185029Spjd/*
2116185029Spjd * Free the arc data buffer.  If it is an l2arc write in progress,
2117185029Spjd * the buffer is placed on l2arc_free_on_write to be freed later.
2118185029Spjd */
2119168404Spjdstatic void
2120240133Smmarc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
2121185029Spjd{
2122240133Smm	arc_buf_hdr_t *hdr = buf->b_hdr;
2123240133Smm
2124185029Spjd	if (HDR_L2_WRITING(hdr)) {
2125274172Savg		arc_buf_free_on_write(buf->b_data, hdr->b_size, free_func);
2126185029Spjd		ARCSTAT_BUMP(arcstat_l2_free_on_write);
2127185029Spjd	} else {
2128240133Smm		free_func(buf->b_data, hdr->b_size);
2129185029Spjd	}
2130185029Spjd}
2131185029Spjd
2132268858Sdelphij/*
2133268858Sdelphij * Free up buf->b_data and if 'remove' is set, then pull the
2134268858Sdelphij * arc_buf_t off of the the arc_buf_hdr_t's list and free it.
2135268858Sdelphij */
2136185029Spjdstatic void
2137274172Savgarc_buf_l2_cdata_free(arc_buf_hdr_t *hdr)
2138274172Savg{
2139286570Smav	ASSERT(HDR_HAS_L2HDR(hdr));
2140286570Smav	ASSERT(MUTEX_HELD(&hdr->b_l2hdr.b_dev->l2ad_mtx));
2141274172Savg
2142286570Smav	/*
2143286570Smav	 * The b_tmp_cdata field is linked off of the b_l1hdr, so if
2144286570Smav	 * that doesn't exist, the header is in the arc_l2c_only state,
2145286570Smav	 * and there isn't anything to free (it's already been freed).
2146286570Smav	 */
2147286570Smav	if (!HDR_HAS_L1HDR(hdr))
2148286570Smav		return;
2149274172Savg
2150286763Smav	/*
2151286763Smav	 * The header isn't being written to the l2arc device, thus it
2152286763Smav	 * shouldn't have a b_tmp_cdata to free.
2153286763Smav	 */
2154286763Smav	if (!HDR_L2_WRITING(hdr)) {
2155286763Smav		ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
2156274172Savg		return;
2157286763Smav	}
2158274172Savg
2159286763Smav	/*
2160286763Smav	 * The header does not have compression enabled. This can be due
2161286763Smav	 * to the buffer not being compressible, or because we're
2162286763Smav	 * freeing the buffer before the second phase of
2163286763Smav	 * l2arc_write_buffer() has started (which does the compression
2164286763Smav	 * step). In either case, b_tmp_cdata does not point to a
2165286763Smav	 * separately compressed buffer, so there's nothing to free (it
2166286763Smav	 * points to the same buffer as the arc_buf_t's b_data field).
2167286763Smav	 */
2168286763Smav	if (HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_OFF) {
2169286763Smav		hdr->b_l1hdr.b_tmp_cdata = NULL;
2170286763Smav		return;
2171286763Smav	}
2172286570Smav
2173286763Smav	/*
2174286763Smav	 * There's nothing to free since the buffer was all zero's and
2175286763Smav	 * compressed to a zero length buffer.
2176286763Smav	 */
2177286763Smav	if (HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_EMPTY) {
2178286763Smav		ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
2179286763Smav		return;
2180286763Smav	}
2181286763Smav
2182286763Smav	ASSERT(L2ARC_IS_VALID_COMPRESS(HDR_GET_COMPRESS(hdr)));
2183286763Smav
2184286763Smav	arc_buf_free_on_write(hdr->b_l1hdr.b_tmp_cdata,
2185286763Smav	    hdr->b_size, zio_data_buf_free);
2186286763Smav
2187274172Savg	ARCSTAT_BUMP(arcstat_l2_cdata_free_on_write);
2188286570Smav	hdr->b_l1hdr.b_tmp_cdata = NULL;
2189274172Savg}
2190274172Savg
2191274172Savgstatic void
2192286763Smavarc_buf_destroy(arc_buf_t *buf, boolean_t remove)
2193168404Spjd{
2194168404Spjd	arc_buf_t **bufp;
2195168404Spjd
2196168404Spjd	/* free up data associated with the buf */
2197286570Smav	if (buf->b_data != NULL) {
2198286570Smav		arc_state_t *state = buf->b_hdr->b_l1hdr.b_state;
2199168404Spjd		uint64_t size = buf->b_hdr->b_size;
2200286570Smav		arc_buf_contents_t type = arc_buf_type(buf->b_hdr);
2201168404Spjd
2202168404Spjd		arc_cksum_verify(buf);
2203240133Smm#ifdef illumos
2204240133Smm		arc_buf_unwatch(buf);
2205277300Ssmh#endif
2206219089Spjd
2207286763Smav		if (type == ARC_BUFC_METADATA) {
2208286763Smav			arc_buf_data_free(buf, zio_buf_free);
2209286763Smav			arc_space_return(size, ARC_SPACE_META);
2210286763Smav		} else {
2211286763Smav			ASSERT(type == ARC_BUFC_DATA);
2212286763Smav			arc_buf_data_free(buf, zio_data_buf_free);
2213286763Smav			arc_space_return(size, ARC_SPACE_DATA);
2214168404Spjd		}
2215286763Smav
2216286763Smav		/* protected by hash lock, if in the hash table */
2217286763Smav		if (multilist_link_active(&buf->b_hdr->b_l1hdr.b_arc_node)) {
2218185029Spjd			uint64_t *cnt = &state->arcs_lsize[type];
2219185029Spjd
2220286570Smav			ASSERT(refcount_is_zero(
2221286570Smav			    &buf->b_hdr->b_l1hdr.b_refcnt));
2222286570Smav			ASSERT(state != arc_anon && state != arc_l2c_only);
2223185029Spjd
2224185029Spjd			ASSERT3U(*cnt, >=, size);
2225185029Spjd			atomic_add_64(cnt, -size);
2226168404Spjd		}
2227168404Spjd		ASSERT3U(state->arcs_size, >=, size);
2228168404Spjd		atomic_add_64(&state->arcs_size, -size);
2229168404Spjd		buf->b_data = NULL;
2230242845Sdelphij
2231242845Sdelphij		/*
2232242845Sdelphij		 * If we're destroying a duplicate buffer make sure
2233242845Sdelphij		 * that the appropriate statistics are updated.
2234242845Sdelphij		 */
2235286570Smav		if (buf->b_hdr->b_l1hdr.b_datacnt > 1 &&
2236286570Smav		    HDR_ISTYPE_DATA(buf->b_hdr)) {
2237242845Sdelphij			ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
2238242845Sdelphij			ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
2239242845Sdelphij		}
2240286570Smav		ASSERT(buf->b_hdr->b_l1hdr.b_datacnt > 0);
2241286570Smav		buf->b_hdr->b_l1hdr.b_datacnt -= 1;
2242168404Spjd	}
2243168404Spjd
2244168404Spjd	/* only remove the buf if requested */
2245268858Sdelphij	if (!remove)
2246168404Spjd		return;
2247168404Spjd
2248168404Spjd	/* remove the buf from the hdr list */
2249286570Smav	for (bufp = &buf->b_hdr->b_l1hdr.b_buf; *bufp != buf;
2250286570Smav	    bufp = &(*bufp)->b_next)
2251168404Spjd		continue;
2252168404Spjd	*bufp = buf->b_next;
2253219089Spjd	buf->b_next = NULL;
2254168404Spjd
2255168404Spjd	ASSERT(buf->b_efunc == NULL);
2256168404Spjd
2257168404Spjd	/* clean up the buf */
2258168404Spjd	buf->b_hdr = NULL;
2259168404Spjd	kmem_cache_free(buf_cache, buf);
2260168404Spjd}
2261168404Spjd
2262168404Spjdstatic void
2263286598Smavarc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
2264286598Smav{
2265286598Smav	l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
2266286598Smav	l2arc_dev_t *dev = l2hdr->b_dev;
2267286598Smav
2268286598Smav	ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
2269286598Smav	ASSERT(HDR_HAS_L2HDR(hdr));
2270286598Smav
2271286598Smav	list_remove(&dev->l2ad_buflist, hdr);
2272286598Smav
2273286598Smav	/*
2274286598Smav	 * We don't want to leak the b_tmp_cdata buffer that was
2275286598Smav	 * allocated in l2arc_write_buffers()
2276286598Smav	 */
2277286598Smav	arc_buf_l2_cdata_free(hdr);
2278286598Smav
2279286598Smav	/*
2280286598Smav	 * If the l2hdr's b_daddr is equal to L2ARC_ADDR_UNSET, then
2281286598Smav	 * this header is being processed by l2arc_write_buffers() (i.e.
2282286598Smav	 * it's in the first stage of l2arc_write_buffers()).
2283286598Smav	 * Re-affirming that truth here, just to serve as a reminder. If
2284286598Smav	 * b_daddr does not equal L2ARC_ADDR_UNSET, then the header may or
2285286598Smav	 * may not have its HDR_L2_WRITING flag set. (the write may have
2286286598Smav	 * completed, in which case HDR_L2_WRITING will be false and the
2287286598Smav	 * b_daddr field will point to the address of the buffer on disk).
2288286598Smav	 */
2289286598Smav	IMPLY(l2hdr->b_daddr == L2ARC_ADDR_UNSET, HDR_L2_WRITING(hdr));
2290286598Smav
2291286598Smav	/*
2292286598Smav	 * If b_daddr is equal to L2ARC_ADDR_UNSET, we're racing with
2293286598Smav	 * l2arc_write_buffers(). Since we've just removed this header
2294286598Smav	 * from the l2arc buffer list, this header will never reach the
2295286598Smav	 * second stage of l2arc_write_buffers(), which increments the
2296286598Smav	 * accounting stats for this header. Thus, we must be careful
2297286598Smav	 * not to decrement them for this header either.
2298286598Smav	 */
2299286598Smav	if (l2hdr->b_daddr != L2ARC_ADDR_UNSET) {
2300286598Smav		ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
2301286598Smav		ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
2302286598Smav
2303286598Smav		vdev_space_update(dev->l2ad_vdev,
2304286598Smav		    -l2hdr->b_asize, 0, 0);
2305286598Smav
2306286598Smav		(void) refcount_remove_many(&dev->l2ad_alloc,
2307286598Smav		    l2hdr->b_asize, hdr);
2308286598Smav	}
2309286598Smav
2310286598Smav	hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
2311286598Smav}
2312286598Smav
2313286598Smavstatic void
2314168404Spjdarc_hdr_destroy(arc_buf_hdr_t *hdr)
2315168404Spjd{
2316286570Smav	if (HDR_HAS_L1HDR(hdr)) {
2317286570Smav		ASSERT(hdr->b_l1hdr.b_buf == NULL ||
2318286570Smav		    hdr->b_l1hdr.b_datacnt > 0);
2319286570Smav		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2320286570Smav		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
2321286570Smav	}
2322168404Spjd	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2323286570Smav	ASSERT(!HDR_IN_HASH_TABLE(hdr));
2324168404Spjd
2325286570Smav	if (HDR_HAS_L2HDR(hdr)) {
2326286598Smav		l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
2327286598Smav		boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
2328286570Smav
2329286598Smav		if (!buflist_held)
2330286598Smav			mutex_enter(&dev->l2ad_mtx);
2331219089Spjd
2332286570Smav		/*
2333286598Smav		 * Even though we checked this conditional above, we
2334286598Smav		 * need to check this again now that we have the
2335286598Smav		 * l2ad_mtx. This is because we could be racing with
2336286598Smav		 * another thread calling l2arc_evict() which might have
2337286598Smav		 * destroyed this header's L2 portion as we were waiting
2338286598Smav		 * to acquire the l2ad_mtx. If that happens, we don't
2339286598Smav		 * want to re-destroy the header's L2 portion.
2340286570Smav		 */
2341286598Smav		if (HDR_HAS_L2HDR(hdr)) {
2342286647Smav			if (hdr->b_l2hdr.b_daddr != L2ARC_ADDR_UNSET)
2343286647Smav				trim_map_free(dev->l2ad_vdev,
2344286647Smav				    hdr->b_l2hdr.b_daddr,
2345286647Smav				    hdr->b_l2hdr.b_asize, 0);
2346286598Smav			arc_hdr_l2hdr_destroy(hdr);
2347286598Smav		}
2348286570Smav
2349219089Spjd		if (!buflist_held)
2350286598Smav			mutex_exit(&dev->l2ad_mtx);
2351185029Spjd	}
2352185029Spjd
2353286570Smav	if (!BUF_EMPTY(hdr))
2354219089Spjd		buf_discard_identity(hdr);
2355168404Spjd	if (hdr->b_freeze_cksum != NULL) {
2356168404Spjd		kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
2357168404Spjd		hdr->b_freeze_cksum = NULL;
2358168404Spjd	}
2359286570Smav
2360286570Smav	if (HDR_HAS_L1HDR(hdr)) {
2361286570Smav		while (hdr->b_l1hdr.b_buf) {
2362286570Smav			arc_buf_t *buf = hdr->b_l1hdr.b_buf;
2363286570Smav
2364286570Smav			if (buf->b_efunc != NULL) {
2365286763Smav				mutex_enter(&arc_user_evicts_lock);
2366286570Smav				mutex_enter(&buf->b_evict_lock);
2367286570Smav				ASSERT(buf->b_hdr != NULL);
2368286763Smav				arc_buf_destroy(hdr->b_l1hdr.b_buf, FALSE);
2369286570Smav				hdr->b_l1hdr.b_buf = buf->b_next;
2370286570Smav				buf->b_hdr = &arc_eviction_hdr;
2371286570Smav				buf->b_next = arc_eviction_list;
2372286570Smav				arc_eviction_list = buf;
2373286570Smav				mutex_exit(&buf->b_evict_lock);
2374286763Smav				cv_signal(&arc_user_evicts_cv);
2375286763Smav				mutex_exit(&arc_user_evicts_lock);
2376286570Smav			} else {
2377286763Smav				arc_buf_destroy(hdr->b_l1hdr.b_buf, TRUE);
2378286570Smav			}
2379286570Smav		}
2380286570Smav#ifdef ZFS_DEBUG
2381286570Smav		if (hdr->b_l1hdr.b_thawed != NULL) {
2382286570Smav			kmem_free(hdr->b_l1hdr.b_thawed, 1);
2383286570Smav			hdr->b_l1hdr.b_thawed = NULL;
2384286570Smav		}
2385286570Smav#endif
2386219089Spjd	}
2387168404Spjd
2388168404Spjd	ASSERT3P(hdr->b_hash_next, ==, NULL);
2389286570Smav	if (HDR_HAS_L1HDR(hdr)) {
2390286763Smav		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
2391286570Smav		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
2392286570Smav		kmem_cache_free(hdr_full_cache, hdr);
2393286570Smav	} else {
2394286570Smav		kmem_cache_free(hdr_l2only_cache, hdr);
2395286570Smav	}
2396168404Spjd}
2397168404Spjd
2398168404Spjdvoid
2399168404Spjdarc_buf_free(arc_buf_t *buf, void *tag)
2400168404Spjd{
2401168404Spjd	arc_buf_hdr_t *hdr = buf->b_hdr;
2402286570Smav	int hashed = hdr->b_l1hdr.b_state != arc_anon;
2403168404Spjd
2404168404Spjd	ASSERT(buf->b_efunc == NULL);
2405168404Spjd	ASSERT(buf->b_data != NULL);
2406168404Spjd
2407168404Spjd	if (hashed) {
2408168404Spjd		kmutex_t *hash_lock = HDR_LOCK(hdr);
2409168404Spjd
2410168404Spjd		mutex_enter(hash_lock);
2411219089Spjd		hdr = buf->b_hdr;
2412219089Spjd		ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2413219089Spjd
2414168404Spjd		(void) remove_reference(hdr, hash_lock, tag);
2415286570Smav		if (hdr->b_l1hdr.b_datacnt > 1) {
2416286763Smav			arc_buf_destroy(buf, TRUE);
2417219089Spjd		} else {
2418286570Smav			ASSERT(buf == hdr->b_l1hdr.b_buf);
2419219089Spjd			ASSERT(buf->b_efunc == NULL);
2420275811Sdelphij			hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
2421219089Spjd		}
2422168404Spjd		mutex_exit(hash_lock);
2423168404Spjd	} else if (HDR_IO_IN_PROGRESS(hdr)) {
2424168404Spjd		int destroy_hdr;
2425168404Spjd		/*
2426168404Spjd		 * We are in the middle of an async write.  Don't destroy
2427168404Spjd		 * this buffer unless the write completes before we finish
2428168404Spjd		 * decrementing the reference count.
2429168404Spjd		 */
2430286763Smav		mutex_enter(&arc_user_evicts_lock);
2431168404Spjd		(void) remove_reference(hdr, NULL, tag);
2432286570Smav		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2433168404Spjd		destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
2434286763Smav		mutex_exit(&arc_user_evicts_lock);
2435168404Spjd		if (destroy_hdr)
2436168404Spjd			arc_hdr_destroy(hdr);
2437168404Spjd	} else {
2438219089Spjd		if (remove_reference(hdr, NULL, tag) > 0)
2439286763Smav			arc_buf_destroy(buf, TRUE);
2440219089Spjd		else
2441168404Spjd			arc_hdr_destroy(hdr);
2442168404Spjd	}
2443168404Spjd}
2444168404Spjd
2445248571Smmboolean_t
2446168404Spjdarc_buf_remove_ref(arc_buf_t *buf, void* tag)
2447168404Spjd{
2448168404Spjd	arc_buf_hdr_t *hdr = buf->b_hdr;
2449168404Spjd	kmutex_t *hash_lock = HDR_LOCK(hdr);
2450248571Smm	boolean_t no_callback = (buf->b_efunc == NULL);
2451168404Spjd
2452286570Smav	if (hdr->b_l1hdr.b_state == arc_anon) {
2453286570Smav		ASSERT(hdr->b_l1hdr.b_datacnt == 1);
2454168404Spjd		arc_buf_free(buf, tag);
2455168404Spjd		return (no_callback);
2456168404Spjd	}
2457168404Spjd
2458168404Spjd	mutex_enter(hash_lock);
2459219089Spjd	hdr = buf->b_hdr;
2460286570Smav	ASSERT(hdr->b_l1hdr.b_datacnt > 0);
2461219089Spjd	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2462286570Smav	ASSERT(hdr->b_l1hdr.b_state != arc_anon);
2463168404Spjd	ASSERT(buf->b_data != NULL);
2464168404Spjd
2465168404Spjd	(void) remove_reference(hdr, hash_lock, tag);
2466286570Smav	if (hdr->b_l1hdr.b_datacnt > 1) {
2467168404Spjd		if (no_callback)
2468286763Smav			arc_buf_destroy(buf, TRUE);
2469168404Spjd	} else if (no_callback) {
2470286570Smav		ASSERT(hdr->b_l1hdr.b_buf == buf && buf->b_next == NULL);
2471219089Spjd		ASSERT(buf->b_efunc == NULL);
2472275811Sdelphij		hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
2473168404Spjd	}
2474286570Smav	ASSERT(no_callback || hdr->b_l1hdr.b_datacnt > 1 ||
2475286570Smav	    refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2476168404Spjd	mutex_exit(hash_lock);
2477168404Spjd	return (no_callback);
2478168404Spjd}
2479168404Spjd
2480286570Smavint32_t
2481168404Spjdarc_buf_size(arc_buf_t *buf)
2482168404Spjd{
2483168404Spjd	return (buf->b_hdr->b_size);
2484168404Spjd}
2485168404Spjd
2486168404Spjd/*
2487242845Sdelphij * Called from the DMU to determine if the current buffer should be
2488242845Sdelphij * evicted. In order to ensure proper locking, the eviction must be initiated
2489242845Sdelphij * from the DMU. Return true if the buffer is associated with user data and
2490242845Sdelphij * duplicate buffers still exist.
2491242845Sdelphij */
2492242845Sdelphijboolean_t
2493242845Sdelphijarc_buf_eviction_needed(arc_buf_t *buf)
2494242845Sdelphij{
2495242845Sdelphij	arc_buf_hdr_t *hdr;
2496242845Sdelphij	boolean_t evict_needed = B_FALSE;
2497242845Sdelphij
2498242845Sdelphij	if (zfs_disable_dup_eviction)
2499242845Sdelphij		return (B_FALSE);
2500242845Sdelphij
2501242845Sdelphij	mutex_enter(&buf->b_evict_lock);
2502242845Sdelphij	hdr = buf->b_hdr;
2503242845Sdelphij	if (hdr == NULL) {
2504242845Sdelphij		/*
2505242845Sdelphij		 * We are in arc_do_user_evicts(); let that function
2506242845Sdelphij		 * perform the eviction.
2507242845Sdelphij		 */
2508242845Sdelphij		ASSERT(buf->b_data == NULL);
2509242845Sdelphij		mutex_exit(&buf->b_evict_lock);
2510242845Sdelphij		return (B_FALSE);
2511242845Sdelphij	} else if (buf->b_data == NULL) {
2512242845Sdelphij		/*
2513242845Sdelphij		 * We have already been added to the arc eviction list;
2514242845Sdelphij		 * recommend eviction.
2515242845Sdelphij		 */
2516242845Sdelphij		ASSERT3P(hdr, ==, &arc_eviction_hdr);
2517242845Sdelphij		mutex_exit(&buf->b_evict_lock);
2518242845Sdelphij		return (B_TRUE);
2519242845Sdelphij	}
2520242845Sdelphij
2521286570Smav	if (hdr->b_l1hdr.b_datacnt > 1 && HDR_ISTYPE_DATA(hdr))
2522242845Sdelphij		evict_needed = B_TRUE;
2523242845Sdelphij
2524242845Sdelphij	mutex_exit(&buf->b_evict_lock);
2525242845Sdelphij	return (evict_needed);
2526242845Sdelphij}
2527242845Sdelphij
2528242845Sdelphij/*
2529286763Smav * Evict the arc_buf_hdr that is provided as a parameter. The resultant
2530286763Smav * state of the header is dependent on it's state prior to entering this
2531286763Smav * function. The following transitions are possible:
2532185029Spjd *
2533286763Smav *    - arc_mru -> arc_mru_ghost
2534286763Smav *    - arc_mfu -> arc_mfu_ghost
2535286763Smav *    - arc_mru_ghost -> arc_l2c_only
2536286763Smav *    - arc_mru_ghost -> deleted
2537286763Smav *    - arc_mfu_ghost -> arc_l2c_only
2538286763Smav *    - arc_mfu_ghost -> deleted
2539168404Spjd */
2540286763Smavstatic int64_t
2541286763Smavarc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
2542168404Spjd{
2543286763Smav	arc_state_t *evicted_state, *state;
2544286763Smav	int64_t bytes_evicted = 0;
2545168404Spjd
2546286763Smav	ASSERT(MUTEX_HELD(hash_lock));
2547286763Smav	ASSERT(HDR_HAS_L1HDR(hdr));
2548168404Spjd
2549286763Smav	state = hdr->b_l1hdr.b_state;
2550286763Smav	if (GHOST_STATE(state)) {
2551286763Smav		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2552286763Smav		ASSERT(hdr->b_l1hdr.b_buf == NULL);
2553206796Spjd
2554286763Smav		/*
2555286763Smav		 * l2arc_write_buffers() relies on a header's L1 portion
2556286763Smav		 * (i.e. it's b_tmp_cdata field) during it's write phase.
2557286763Smav		 * Thus, we cannot push a header onto the arc_l2c_only
2558286763Smav		 * state (removing it's L1 piece) until the header is
2559286763Smav		 * done being written to the l2arc.
2560286763Smav		 */
2561286763Smav		if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
2562286763Smav			ARCSTAT_BUMP(arcstat_evict_l2_skip);
2563286763Smav			return (bytes_evicted);
2564286763Smav		}
2565286762Smav
2566286763Smav		ARCSTAT_BUMP(arcstat_deleted);
2567286763Smav		bytes_evicted += hdr->b_size;
2568286762Smav
2569286763Smav		DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
2570286763Smav
2571286763Smav		if (HDR_HAS_L2HDR(hdr)) {
2572275780Sdelphij			/*
2573286763Smav			 * This buffer is cached on the 2nd Level ARC;
2574286763Smav			 * don't destroy the header.
2575275780Sdelphij			 */
2576286763Smav			arc_change_state(arc_l2c_only, hdr, hash_lock);
2577286763Smav			/*
2578286763Smav			 * dropping from L1+L2 cached to L2-only,
2579286763Smav			 * realloc to remove the L1 header.
2580286763Smav			 */
2581286763Smav			hdr = arc_hdr_realloc(hdr, hdr_full_cache,
2582286763Smav			    hdr_l2only_cache);
2583286763Smav		} else {
2584286763Smav			arc_change_state(arc_anon, hdr, hash_lock);
2585286763Smav			arc_hdr_destroy(hdr);
2586275780Sdelphij		}
2587286763Smav		return (bytes_evicted);
2588275780Sdelphij	}
2589275780Sdelphij
2590286763Smav	ASSERT(state == arc_mru || state == arc_mfu);
2591286763Smav	evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
2592206796Spjd
2593286763Smav	/* prefetch buffers have a minimum lifespan */
2594286763Smav	if (HDR_IO_IN_PROGRESS(hdr) ||
2595286763Smav	    ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
2596286763Smav	    ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
2597286763Smav	    arc_min_prefetch_lifespan)) {
2598286763Smav		ARCSTAT_BUMP(arcstat_evict_skip);
2599286763Smav		return (bytes_evicted);
2600286763Smav	}
2601286763Smav
2602286763Smav	ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
2603286763Smav	ASSERT3U(hdr->b_l1hdr.b_datacnt, >, 0);
2604286763Smav	while (hdr->b_l1hdr.b_buf) {
2605286763Smav		arc_buf_t *buf = hdr->b_l1hdr.b_buf;
2606286763Smav		if (!mutex_tryenter(&buf->b_evict_lock)) {
2607286763Smav			ARCSTAT_BUMP(arcstat_mutex_miss);
2608286763Smav			break;
2609168404Spjd		}
2610286763Smav		if (buf->b_data != NULL)
2611286763Smav			bytes_evicted += hdr->b_size;
2612286763Smav		if (buf->b_efunc != NULL) {
2613286763Smav			mutex_enter(&arc_user_evicts_lock);
2614286763Smav			arc_buf_destroy(buf, FALSE);
2615286763Smav			hdr->b_l1hdr.b_buf = buf->b_next;
2616286763Smav			buf->b_hdr = &arc_eviction_hdr;
2617286763Smav			buf->b_next = arc_eviction_list;
2618286763Smav			arc_eviction_list = buf;
2619286763Smav			cv_signal(&arc_user_evicts_cv);
2620286763Smav			mutex_exit(&arc_user_evicts_lock);
2621286763Smav			mutex_exit(&buf->b_evict_lock);
2622286763Smav		} else {
2623286763Smav			mutex_exit(&buf->b_evict_lock);
2624286763Smav			arc_buf_destroy(buf, TRUE);
2625286763Smav		}
2626286763Smav	}
2627258632Savg
2628286763Smav	if (HDR_HAS_L2HDR(hdr)) {
2629286763Smav		ARCSTAT_INCR(arcstat_evict_l2_cached, hdr->b_size);
2630286763Smav	} else {
2631286763Smav		if (l2arc_write_eligible(hdr->b_spa, hdr))
2632286763Smav			ARCSTAT_INCR(arcstat_evict_l2_eligible, hdr->b_size);
2633286763Smav		else
2634286763Smav			ARCSTAT_INCR(arcstat_evict_l2_ineligible, hdr->b_size);
2635286763Smav	}
2636258632Savg
2637286763Smav	if (hdr->b_l1hdr.b_datacnt == 0) {
2638286763Smav		arc_change_state(evicted_state, hdr, hash_lock);
2639286763Smav		ASSERT(HDR_IN_HASH_TABLE(hdr));
2640286763Smav		hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
2641286763Smav		hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
2642286763Smav		DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
2643286763Smav	}
2644286763Smav
2645286763Smav	return (bytes_evicted);
2646286763Smav}
2647286763Smav
2648286763Smavstatic uint64_t
2649286763Smavarc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
2650286763Smav    uint64_t spa, int64_t bytes)
2651286763Smav{
2652286763Smav	multilist_sublist_t *mls;
2653286763Smav	uint64_t bytes_evicted = 0;
2654286763Smav	arc_buf_hdr_t *hdr;
2655286763Smav	kmutex_t *hash_lock;
2656286763Smav	int evict_count = 0;
2657286763Smav
2658286763Smav	ASSERT3P(marker, !=, NULL);
2659286763Smav	IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
2660286763Smav
2661286763Smav	mls = multilist_sublist_lock(ml, idx);
2662286763Smav
2663286763Smav	for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
2664286763Smav	    hdr = multilist_sublist_prev(mls, marker)) {
2665286763Smav		if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
2666286763Smav		    (evict_count >= zfs_arc_evict_batch_limit))
2667286763Smav			break;
2668286763Smav
2669258632Savg		/*
2670286763Smav		 * To keep our iteration location, move the marker
2671286763Smav		 * forward. Since we're not holding hdr's hash lock, we
2672286763Smav		 * must be very careful and not remove 'hdr' from the
2673286763Smav		 * sublist. Otherwise, other consumers might mistake the
2674286763Smav		 * 'hdr' as not being on a sublist when they call the
2675286763Smav		 * multilist_link_active() function (they all rely on
2676286763Smav		 * the hash lock protecting concurrent insertions and
2677286763Smav		 * removals). multilist_sublist_move_forward() was
2678286763Smav		 * specifically implemented to ensure this is the case
2679286763Smav		 * (only 'marker' will be removed and re-inserted).
2680258632Savg		 */
2681286763Smav		multilist_sublist_move_forward(mls, marker);
2682286763Smav
2683286763Smav		/*
2684286763Smav		 * The only case where the b_spa field should ever be
2685286763Smav		 * zero, is the marker headers inserted by
2686286763Smav		 * arc_evict_state(). It's possible for multiple threads
2687286763Smav		 * to be calling arc_evict_state() concurrently (e.g.
2688286763Smav		 * dsl_pool_close() and zio_inject_fault()), so we must
2689286763Smav		 * skip any markers we see from these other threads.
2690286763Smav		 */
2691286763Smav		if (hdr->b_spa == 0)
2692258632Savg			continue;
2693286763Smav
2694286763Smav		/* we're only interested in evicting buffers of a certain spa */
2695286763Smav		if (spa != 0 && hdr->b_spa != spa) {
2696286763Smav			ARCSTAT_BUMP(arcstat_evict_skip);
2697286763Smav			continue;
2698258632Savg		}
2699258632Savg
2700275811Sdelphij		hash_lock = HDR_LOCK(hdr);
2701208373Smm
2702286763Smav		/*
2703286763Smav		 * We aren't calling this function from any code path
2704286763Smav		 * that would already be holding a hash lock, so we're
2705286763Smav		 * asserting on this assumption to be defensive in case
2706286763Smav		 * this ever changes. Without this check, it would be
2707286763Smav		 * possible to incorrectly increment arcstat_mutex_miss
2708286763Smav		 * below (e.g. if the code changed such that we called
2709286763Smav		 * this function with a hash lock held).
2710286763Smav		 */
2711286763Smav		ASSERT(!MUTEX_HELD(hash_lock));
2712208373Smm
2713286763Smav		if (mutex_tryenter(hash_lock)) {
2714286763Smav			uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
2715286763Smav			mutex_exit(hash_lock);
2716286763Smav
2717286763Smav			bytes_evicted += evicted;
2718286763Smav
2719286763Smav			/*
2720286763Smav			 * If evicted is zero, arc_evict_hdr() must have
2721286763Smav			 * decided to skip this header, don't increment
2722286763Smav			 * evict_count in this case.
2723286763Smav			 */
2724286763Smav			if (evicted != 0)
2725286763Smav				evict_count++;
2726286763Smav
2727286763Smav			/*
2728286763Smav			 * If arc_size isn't overflowing, signal any
2729286763Smav			 * threads that might happen to be waiting.
2730286763Smav			 *
2731286763Smav			 * For each header evicted, we wake up a single
2732286763Smav			 * thread. If we used cv_broadcast, we could
2733286763Smav			 * wake up "too many" threads causing arc_size
2734286763Smav			 * to significantly overflow arc_c; since
2735286763Smav			 * arc_get_data_buf() doesn't check for overflow
2736286763Smav			 * when it's woken up (it doesn't because it's
2737286763Smav			 * possible for the ARC to be overflowing while
2738286763Smav			 * full of un-evictable buffers, and the
2739286763Smav			 * function should proceed in this case).
2740286763Smav			 *
2741286763Smav			 * If threads are left sleeping, due to not
2742286763Smav			 * using cv_broadcast, they will be woken up
2743286763Smav			 * just before arc_reclaim_thread() sleeps.
2744286763Smav			 */
2745286763Smav			mutex_enter(&arc_reclaim_lock);
2746286763Smav			if (!arc_is_overflowing())
2747286763Smav				cv_signal(&arc_reclaim_waiters_cv);
2748286763Smav			mutex_exit(&arc_reclaim_lock);
2749168404Spjd		} else {
2750286763Smav			ARCSTAT_BUMP(arcstat_mutex_miss);
2751168404Spjd		}
2752168404Spjd	}
2753168404Spjd
2754286763Smav	multilist_sublist_unlock(mls);
2755206796Spjd
2756286763Smav	return (bytes_evicted);
2757286763Smav}
2758168404Spjd
2759286763Smav/*
2760286763Smav * Evict buffers from the given arc state, until we've removed the
2761286763Smav * specified number of bytes. Move the removed buffers to the
2762286763Smav * appropriate evict state.
2763286763Smav *
2764286763Smav * This function makes a "best effort". It skips over any buffers
2765286763Smav * it can't get a hash_lock on, and so, may not catch all candidates.
2766286763Smav * It may also return without evicting as much space as requested.
2767286763Smav *
2768286763Smav * If bytes is specified using the special value ARC_EVICT_ALL, this
2769286763Smav * will evict all available (i.e. unlocked and evictable) buffers from
2770286763Smav * the given arc state; which is used by arc_flush().
2771286763Smav */
2772286763Smavstatic uint64_t
2773286763Smavarc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
2774286763Smav    arc_buf_contents_t type)
2775286763Smav{
2776286763Smav	uint64_t total_evicted = 0;
2777286763Smav	multilist_t *ml = &state->arcs_list[type];
2778286763Smav	int num_sublists;
2779286763Smav	arc_buf_hdr_t **markers;
2780168404Spjd
2781286763Smav	IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
2782168404Spjd
2783286763Smav	num_sublists = multilist_get_num_sublists(ml);
2784286763Smav
2785185029Spjd	/*
2786286763Smav	 * If we've tried to evict from each sublist, made some
2787286763Smav	 * progress, but still have not hit the target number of bytes
2788286763Smav	 * to evict, we want to keep trying. The markers allow us to
2789286763Smav	 * pick up where we left off for each individual sublist, rather
2790286763Smav	 * than starting from the tail each time.
2791185029Spjd	 */
2792286763Smav	markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
2793286763Smav	for (int i = 0; i < num_sublists; i++) {
2794286763Smav		markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
2795185029Spjd
2796286763Smav		/*
2797286763Smav		 * A b_spa of 0 is used to indicate that this header is
2798286763Smav		 * a marker. This fact is used in arc_adjust_type() and
2799286763Smav		 * arc_evict_state_impl().
2800286763Smav		 */
2801286763Smav		markers[i]->b_spa = 0;
2802168404Spjd
2803286763Smav		multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
2804286763Smav		multilist_sublist_insert_tail(mls, markers[i]);
2805286763Smav		multilist_sublist_unlock(mls);
2806286763Smav	}
2807168404Spjd
2808286763Smav	/*
2809286763Smav	 * While we haven't hit our target number of bytes to evict, or
2810286763Smav	 * we're evicting all available buffers.
2811286763Smav	 */
2812286763Smav	while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
2813286763Smav		/*
2814286763Smav		 * Start eviction using a randomly selected sublist,
2815286763Smav		 * this is to try and evenly balance eviction across all
2816286763Smav		 * sublists. Always starting at the same sublist
2817286763Smav		 * (e.g. index 0) would cause evictions to favor certain
2818286763Smav		 * sublists over others.
2819286763Smav		 */
2820286763Smav		int sublist_idx = multilist_get_random_index(ml);
2821286763Smav		uint64_t scan_evicted = 0;
2822219089Spjd
2823286763Smav		for (int i = 0; i < num_sublists; i++) {
2824286763Smav			uint64_t bytes_remaining;
2825286763Smav			uint64_t bytes_evicted;
2826219089Spjd
2827286763Smav			if (bytes == ARC_EVICT_ALL)
2828286763Smav				bytes_remaining = ARC_EVICT_ALL;
2829286763Smav			else if (total_evicted < bytes)
2830286763Smav				bytes_remaining = bytes - total_evicted;
2831286763Smav			else
2832286763Smav				break;
2833258632Savg
2834286763Smav			bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
2835286763Smav			    markers[sublist_idx], spa, bytes_remaining);
2836286763Smav
2837286763Smav			scan_evicted += bytes_evicted;
2838286763Smav			total_evicted += bytes_evicted;
2839286763Smav
2840286763Smav			/* we've reached the end, wrap to the beginning */
2841286763Smav			if (++sublist_idx >= num_sublists)
2842286763Smav				sublist_idx = 0;
2843286763Smav		}
2844286763Smav
2845258632Savg		/*
2846286763Smav		 * If we didn't evict anything during this scan, we have
2847286763Smav		 * no reason to believe we'll evict more during another
2848286763Smav		 * scan, so break the loop.
2849258632Savg		 */
2850286763Smav		if (scan_evicted == 0) {
2851286763Smav			/* This isn't possible, let's make that obvious */
2852286763Smav			ASSERT3S(bytes, !=, 0);
2853185029Spjd
2854286763Smav			/*
2855286763Smav			 * When bytes is ARC_EVICT_ALL, the only way to
2856286763Smav			 * break the loop is when scan_evicted is zero.
2857286763Smav			 * In that case, we actually have evicted enough,
2858286763Smav			 * so we don't want to increment the kstat.
2859286763Smav			 */
2860286763Smav			if (bytes != ARC_EVICT_ALL) {
2861286763Smav				ASSERT3S(total_evicted, <, bytes);
2862286763Smav				ARCSTAT_BUMP(arcstat_evict_not_enough);
2863185029Spjd			}
2864185029Spjd
2865286763Smav			break;
2866258632Savg		}
2867286763Smav	}
2868258632Savg
2869286763Smav	for (int i = 0; i < num_sublists; i++) {
2870286763Smav		multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
2871286763Smav		multilist_sublist_remove(mls, markers[i]);
2872286763Smav		multilist_sublist_unlock(mls);
2873286763Smav
2874286763Smav		kmem_cache_free(hdr_full_cache, markers[i]);
2875168404Spjd	}
2876286763Smav	kmem_free(markers, sizeof (*markers) * num_sublists);
2877206796Spjd
2878286763Smav	return (total_evicted);
2879286763Smav}
2880286763Smav
2881286763Smav/*
2882286763Smav * Flush all "evictable" data of the given type from the arc state
2883286763Smav * specified. This will not evict any "active" buffers (i.e. referenced).
2884286763Smav *
2885286763Smav * When 'retry' is set to FALSE, the function will make a single pass
2886286763Smav * over the state and evict any buffers that it can. Since it doesn't
2887286763Smav * continually retry the eviction, it might end up leaving some buffers
2888286763Smav * in the ARC due to lock misses.
2889286763Smav *
2890286763Smav * When 'retry' is set to TRUE, the function will continually retry the
2891286763Smav * eviction until *all* evictable buffers have been removed from the
2892286763Smav * state. As a result, if concurrent insertions into the state are
2893286763Smav * allowed (e.g. if the ARC isn't shutting down), this function might
2894286763Smav * wind up in an infinite loop, continually trying to evict buffers.
2895286763Smav */
2896286763Smavstatic uint64_t
2897286763Smavarc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
2898286763Smav    boolean_t retry)
2899286763Smav{
2900286763Smav	uint64_t evicted = 0;
2901286763Smav
2902286763Smav	while (state->arcs_lsize[type] != 0) {
2903286763Smav		evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
2904286763Smav
2905286763Smav		if (!retry)
2906286763Smav			break;
2907185029Spjd	}
2908185029Spjd
2909286763Smav	return (evicted);
2910286763Smav}
2911286763Smav
2912286763Smav/*
2913286763Smav * Evict the specified number of bytes from the state specified,
2914286763Smav * restricting eviction to the spa and type given. This function
2915286763Smav * prevents us from trying to evict more from a state's list than
2916286763Smav * is "evictable", and to skip evicting altogether when passed a
2917286763Smav * negative value for "bytes". In contrast, arc_evict_state() will
2918286763Smav * evict everything it can, when passed a negative value for "bytes".
2919286763Smav */
2920286763Smavstatic uint64_t
2921286763Smavarc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
2922286763Smav    arc_buf_contents_t type)
2923286763Smav{
2924286763Smav	int64_t delta;
2925286763Smav
2926286763Smav	if (bytes > 0 && state->arcs_lsize[type] > 0) {
2927286763Smav		delta = MIN(state->arcs_lsize[type], bytes);
2928286763Smav		return (arc_evict_state(state, spa, delta, type));
2929168404Spjd	}
2930168404Spjd
2931286763Smav	return (0);
2932168404Spjd}
2933168404Spjd
2934286763Smav/*
2935286763Smav * Evict metadata buffers from the cache, such that arc_meta_used is
2936286763Smav * capped by the arc_meta_limit tunable.
2937286763Smav */
2938286763Smavstatic uint64_t
2939286763Smavarc_adjust_meta(void)
2940286763Smav{
2941286763Smav	uint64_t total_evicted = 0;
2942286763Smav	int64_t target;
2943286763Smav
2944286763Smav	/*
2945286763Smav	 * If we're over the meta limit, we want to evict enough
2946286763Smav	 * metadata to get back under the meta limit. We don't want to
2947286763Smav	 * evict so much that we drop the MRU below arc_p, though. If
2948286763Smav	 * we're over the meta limit more than we're over arc_p, we
2949286763Smav	 * evict some from the MRU here, and some from the MFU below.
2950286763Smav	 */
2951286763Smav	target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
2952286763Smav	    (int64_t)(arc_anon->arcs_size + arc_mru->arcs_size - arc_p));
2953286763Smav
2954286763Smav	total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
2955286763Smav
2956286763Smav	/*
2957286763Smav	 * Similar to the above, we want to evict enough bytes to get us
2958286763Smav	 * below the meta limit, but not so much as to drop us below the
2959286763Smav	 * space alloted to the MFU (which is defined as arc_c - arc_p).
2960286763Smav	 */
2961286763Smav	target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
2962286763Smav	    (int64_t)(arc_mfu->arcs_size - (arc_c - arc_p)));
2963286763Smav
2964286763Smav	total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
2965286763Smav
2966286763Smav	return (total_evicted);
2967286763Smav}
2968286763Smav
2969286763Smav/*
2970286763Smav * Return the type of the oldest buffer in the given arc state
2971286763Smav *
2972286763Smav * This function will select a random sublist of type ARC_BUFC_DATA and
2973286763Smav * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
2974286763Smav * is compared, and the type which contains the "older" buffer will be
2975286763Smav * returned.
2976286763Smav */
2977286763Smavstatic arc_buf_contents_t
2978286763Smavarc_adjust_type(arc_state_t *state)
2979286763Smav{
2980286763Smav	multilist_t *data_ml = &state->arcs_list[ARC_BUFC_DATA];
2981286763Smav	multilist_t *meta_ml = &state->arcs_list[ARC_BUFC_METADATA];
2982286763Smav	int data_idx = multilist_get_random_index(data_ml);
2983286763Smav	int meta_idx = multilist_get_random_index(meta_ml);
2984286763Smav	multilist_sublist_t *data_mls;
2985286763Smav	multilist_sublist_t *meta_mls;
2986286763Smav	arc_buf_contents_t type;
2987286763Smav	arc_buf_hdr_t *data_hdr;
2988286763Smav	arc_buf_hdr_t *meta_hdr;
2989286763Smav
2990286763Smav	/*
2991286763Smav	 * We keep the sublist lock until we're finished, to prevent
2992286763Smav	 * the headers from being destroyed via arc_evict_state().
2993286763Smav	 */
2994286763Smav	data_mls = multilist_sublist_lock(data_ml, data_idx);
2995286763Smav	meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
2996286763Smav
2997286763Smav	/*
2998286763Smav	 * These two loops are to ensure we skip any markers that
2999286763Smav	 * might be at the tail of the lists due to arc_evict_state().
3000286763Smav	 */
3001286763Smav
3002286763Smav	for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
3003286763Smav	    data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
3004286763Smav		if (data_hdr->b_spa != 0)
3005286763Smav			break;
3006286763Smav	}
3007286763Smav
3008286763Smav	for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
3009286763Smav	    meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
3010286763Smav		if (meta_hdr->b_spa != 0)
3011286763Smav			break;
3012286763Smav	}
3013286763Smav
3014286763Smav	if (data_hdr == NULL && meta_hdr == NULL) {
3015286763Smav		type = ARC_BUFC_DATA;
3016286763Smav	} else if (data_hdr == NULL) {
3017286763Smav		ASSERT3P(meta_hdr, !=, NULL);
3018286763Smav		type = ARC_BUFC_METADATA;
3019286763Smav	} else if (meta_hdr == NULL) {
3020286763Smav		ASSERT3P(data_hdr, !=, NULL);
3021286763Smav		type = ARC_BUFC_DATA;
3022286763Smav	} else {
3023286763Smav		ASSERT3P(data_hdr, !=, NULL);
3024286763Smav		ASSERT3P(meta_hdr, !=, NULL);
3025286763Smav
3026286763Smav		/* The headers can't be on the sublist without an L1 header */
3027286763Smav		ASSERT(HDR_HAS_L1HDR(data_hdr));
3028286763Smav		ASSERT(HDR_HAS_L1HDR(meta_hdr));
3029286763Smav
3030286763Smav		if (data_hdr->b_l1hdr.b_arc_access <
3031286763Smav		    meta_hdr->b_l1hdr.b_arc_access) {
3032286763Smav			type = ARC_BUFC_DATA;
3033286763Smav		} else {
3034286763Smav			type = ARC_BUFC_METADATA;
3035286763Smav		}
3036286763Smav	}
3037286763Smav
3038286763Smav	multilist_sublist_unlock(meta_mls);
3039286763Smav	multilist_sublist_unlock(data_mls);
3040286763Smav
3041286763Smav	return (type);
3042286763Smav}
3043286763Smav
3044286763Smav/*
3045286763Smav * Evict buffers from the cache, such that arc_size is capped by arc_c.
3046286763Smav */
3047286763Smavstatic uint64_t
3048168404Spjdarc_adjust(void)
3049168404Spjd{
3050286763Smav	uint64_t total_evicted = 0;
3051286763Smav	uint64_t bytes;
3052286763Smav	int64_t target;
3053168404Spjd
3054208373Smm	/*
3055286763Smav	 * If we're over arc_meta_limit, we want to correct that before
3056286763Smav	 * potentially evicting data buffers below.
3057286763Smav	 */
3058286763Smav	total_evicted += arc_adjust_meta();
3059286763Smav
3060286763Smav	/*
3061208373Smm	 * Adjust MRU size
3062286763Smav	 *
3063286763Smav	 * If we're over the target cache size, we want to evict enough
3064286763Smav	 * from the list to get back to our target size. We don't want
3065286763Smav	 * to evict too much from the MRU, such that it drops below
3066286763Smav	 * arc_p. So, if we're over our target cache size more than
3067286763Smav	 * the MRU is over arc_p, we'll evict enough to get back to
3068286763Smav	 * arc_p here, and then evict more from the MFU below.
3069208373Smm	 */
3070286763Smav	target = MIN((int64_t)(arc_size - arc_c),
3071209275Smm	    (int64_t)(arc_anon->arcs_size + arc_mru->arcs_size + arc_meta_used -
3072209275Smm	    arc_p));
3073208373Smm
3074286763Smav	/*
3075286763Smav	 * If we're below arc_meta_min, always prefer to evict data.
3076286763Smav	 * Otherwise, try to satisfy the requested number of bytes to
3077286763Smav	 * evict from the type which contains older buffers; in an
3078286763Smav	 * effort to keep newer buffers in the cache regardless of their
3079286763Smav	 * type. If we cannot satisfy the number of bytes from this
3080286763Smav	 * type, spill over into the next type.
3081286763Smav	 */
3082286763Smav	if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
3083286763Smav	    arc_meta_used > arc_meta_min) {
3084286763Smav		bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3085286763Smav		total_evicted += bytes;
3086168404Spjd
3087286763Smav		/*
3088286763Smav		 * If we couldn't evict our target number of bytes from
3089286763Smav		 * metadata, we try to get the rest from data.
3090286763Smav		 */
3091286763Smav		target -= bytes;
3092286763Smav
3093286763Smav		total_evicted +=
3094286763Smav		    arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3095286763Smav	} else {
3096286763Smav		bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3097286763Smav		total_evicted += bytes;
3098286763Smav
3099286763Smav		/*
3100286763Smav		 * If we couldn't evict our target number of bytes from
3101286763Smav		 * data, we try to get the rest from metadata.
3102286763Smav		 */
3103286763Smav		target -= bytes;
3104286763Smav
3105286763Smav		total_evicted +=
3106286763Smav		    arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3107185029Spjd	}
3108185029Spjd
3109208373Smm	/*
3110208373Smm	 * Adjust MFU size
3111286763Smav	 *
3112286763Smav	 * Now that we've tried to evict enough from the MRU to get its
3113286763Smav	 * size back to arc_p, if we're still above the target cache
3114286763Smav	 * size, we evict the rest from the MFU.
3115208373Smm	 */
3116286763Smav	target = arc_size - arc_c;
3117168404Spjd
3118286764Smav	if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
3119286763Smav	    arc_meta_used > arc_meta_min) {
3120286763Smav		bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3121286763Smav		total_evicted += bytes;
3122208373Smm
3123286763Smav		/*
3124286763Smav		 * If we couldn't evict our target number of bytes from
3125286763Smav		 * metadata, we try to get the rest from data.
3126286763Smav		 */
3127286763Smav		target -= bytes;
3128168404Spjd
3129286763Smav		total_evicted +=
3130286763Smav		    arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3131286763Smav	} else {
3132286763Smav		bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3133286763Smav		total_evicted += bytes;
3134286763Smav
3135286763Smav		/*
3136286763Smav		 * If we couldn't evict our target number of bytes from
3137286763Smav		 * data, we try to get the rest from data.
3138286763Smav		 */
3139286763Smav		target -= bytes;
3140286763Smav
3141286763Smav		total_evicted +=
3142286763Smav		    arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3143208373Smm	}
3144168404Spjd
3145208373Smm	/*
3146208373Smm	 * Adjust ghost lists
3147286763Smav	 *
3148286763Smav	 * In addition to the above, the ARC also defines target values
3149286763Smav	 * for the ghost lists. The sum of the mru list and mru ghost
3150286763Smav	 * list should never exceed the target size of the cache, and
3151286763Smav	 * the sum of the mru list, mfu list, mru ghost list, and mfu
3152286763Smav	 * ghost list should never exceed twice the target size of the
3153286763Smav	 * cache. The following logic enforces these limits on the ghost
3154286763Smav	 * caches, and evicts from them as needed.
3155208373Smm	 */
3156286763Smav	target = arc_mru->arcs_size + arc_mru_ghost->arcs_size - arc_c;
3157168404Spjd
3158286763Smav	bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
3159286763Smav	total_evicted += bytes;
3160168404Spjd
3161286763Smav	target -= bytes;
3162185029Spjd
3163286763Smav	total_evicted +=
3164286763Smav	    arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
3165208373Smm
3166286763Smav	/*
3167286763Smav	 * We assume the sum of the mru list and mfu list is less than
3168286763Smav	 * or equal to arc_c (we enforced this above), which means we
3169286763Smav	 * can use the simpler of the two equations below:
3170286763Smav	 *
3171286763Smav	 *	mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
3172286763Smav	 *		    mru ghost + mfu ghost <= arc_c
3173286763Smav	 */
3174286763Smav	target = arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size - arc_c;
3175286763Smav
3176286763Smav	bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
3177286763Smav	total_evicted += bytes;
3178286763Smav
3179286763Smav	target -= bytes;
3180286763Smav
3181286763Smav	total_evicted +=
3182286763Smav	    arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
3183286763Smav
3184286763Smav	return (total_evicted);
3185168404Spjd}
3186168404Spjd
3187168404Spjdstatic void
3188168404Spjdarc_do_user_evicts(void)
3189168404Spjd{
3190286763Smav	mutex_enter(&arc_user_evicts_lock);
3191286762Smav	while (arc_eviction_list != NULL) {
3192286762Smav		arc_buf_t *buf = arc_eviction_list;
3193286762Smav		arc_eviction_list = buf->b_next;
3194219089Spjd		mutex_enter(&buf->b_evict_lock);
3195168404Spjd		buf->b_hdr = NULL;
3196219089Spjd		mutex_exit(&buf->b_evict_lock);
3197286763Smav		mutex_exit(&arc_user_evicts_lock);
3198168404Spjd
3199168404Spjd		if (buf->b_efunc != NULL)
3200268858Sdelphij			VERIFY0(buf->b_efunc(buf->b_private));
3201168404Spjd
3202168404Spjd		buf->b_efunc = NULL;
3203168404Spjd		buf->b_private = NULL;
3204168404Spjd		kmem_cache_free(buf_cache, buf);
3205286763Smav		mutex_enter(&arc_user_evicts_lock);
3206168404Spjd	}
3207286763Smav	mutex_exit(&arc_user_evicts_lock);
3208168404Spjd}
3209168404Spjd
3210168404Spjdvoid
3211286763Smavarc_flush(spa_t *spa, boolean_t retry)
3212168404Spjd{
3213209962Smm	uint64_t guid = 0;
3214209962Smm
3215286763Smav	/*
3216286763Smav	 * If retry is TRUE, a spa must not be specified since we have
3217286763Smav	 * no good way to determine if all of a spa's buffers have been
3218286763Smav	 * evicted from an arc state.
3219286763Smav	 */
3220286763Smav	ASSERT(!retry || spa == 0);
3221286763Smav
3222286570Smav	if (spa != NULL)
3223228103Smm		guid = spa_load_guid(spa);
3224209962Smm
3225286763Smav	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
3226286763Smav	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
3227168404Spjd
3228286763Smav	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
3229286763Smav	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
3230168404Spjd
3231286763Smav	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
3232286763Smav	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
3233286763Smav
3234286763Smav	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
3235286763Smav	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
3236286763Smav
3237168404Spjd	arc_do_user_evicts();
3238185029Spjd	ASSERT(spa || arc_eviction_list == NULL);
3239168404Spjd}
3240168404Spjd
3241168404Spjdvoid
3242286625Smavarc_shrink(int64_t to_free)
3243168404Spjd{
3244168404Spjd	if (arc_c > arc_c_min) {
3245272483Ssmh		DTRACE_PROBE4(arc__shrink, uint64_t, arc_c, uint64_t,
3246272483Ssmh			arc_c_min, uint64_t, arc_p, uint64_t, to_free);
3247168404Spjd		if (arc_c > arc_c_min + to_free)
3248168404Spjd			atomic_add_64(&arc_c, -to_free);
3249168404Spjd		else
3250168404Spjd			arc_c = arc_c_min;
3251168404Spjd
3252168404Spjd		atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
3253168404Spjd		if (arc_c > arc_size)
3254168404Spjd			arc_c = MAX(arc_size, arc_c_min);
3255168404Spjd		if (arc_p > arc_c)
3256168404Spjd			arc_p = (arc_c >> 1);
3257272483Ssmh
3258272483Ssmh		DTRACE_PROBE2(arc__shrunk, uint64_t, arc_c, uint64_t,
3259272483Ssmh			arc_p);
3260272483Ssmh
3261168404Spjd		ASSERT(arc_c >= arc_c_min);
3262168404Spjd		ASSERT((int64_t)arc_p >= 0);
3263168404Spjd	}
3264168404Spjd
3265270759Ssmh	if (arc_size > arc_c) {
3266270759Ssmh		DTRACE_PROBE2(arc__shrink_adjust, uint64_t, arc_size,
3267270759Ssmh			uint64_t, arc_c);
3268286763Smav		(void) arc_adjust();
3269270759Ssmh	}
3270168404Spjd}
3271168404Spjd
3272286625Smavstatic long needfree = 0;
3273168404Spjd
3274286625Smavtypedef enum free_memory_reason_t {
3275286625Smav	FMR_UNKNOWN,
3276286625Smav	FMR_NEEDFREE,
3277286625Smav	FMR_LOTSFREE,
3278286625Smav	FMR_SWAPFS_MINFREE,
3279286625Smav	FMR_PAGES_PP_MAXIMUM,
3280286625Smav	FMR_HEAP_ARENA,
3281286625Smav	FMR_ZIO_ARENA,
3282286625Smav	FMR_ZIO_FRAG,
3283286625Smav} free_memory_reason_t;
3284286625Smav
3285286625Smavint64_t last_free_memory;
3286286625Smavfree_memory_reason_t last_free_reason;
3287286625Smav
3288286625Smav/*
3289286625Smav * Additional reserve of pages for pp_reserve.
3290286625Smav */
3291286625Smavint64_t arc_pages_pp_reserve = 64;
3292286625Smav
3293286625Smav/*
3294286625Smav * Additional reserve of pages for swapfs.
3295286625Smav */
3296286625Smavint64_t arc_swapfs_reserve = 64;
3297286625Smav
3298286625Smav/*
3299286625Smav * Return the amount of memory that can be consumed before reclaim will be
3300286625Smav * needed.  Positive if there is sufficient free memory, negative indicates
3301286625Smav * the amount of memory that needs to be freed up.
3302286625Smav */
3303286625Smavstatic int64_t
3304286625Smavarc_available_memory(void)
3305168404Spjd{
3306286625Smav	int64_t lowest = INT64_MAX;
3307286625Smav	int64_t n;
3308286625Smav	free_memory_reason_t r = FMR_UNKNOWN;
3309168404Spjd
3310168404Spjd#ifdef _KERNEL
3311286625Smav	if (needfree > 0) {
3312286625Smav		n = PAGESIZE * (-needfree);
3313286625Smav		if (n < lowest) {
3314286625Smav			lowest = n;
3315286625Smav			r = FMR_NEEDFREE;
3316286625Smav		}
3317270759Ssmh	}
3318168404Spjd
3319191902Skmacy	/*
3320212780Savg	 * Cooperate with pagedaemon when it's time for it to scan
3321212780Savg	 * and reclaim some pages.
3322191902Skmacy	 */
3323286655Smav	n = PAGESIZE * ((int64_t)freemem - zfs_arc_free_target);
3324286625Smav	if (n < lowest) {
3325286625Smav		lowest = n;
3326286625Smav		r = FMR_LOTSFREE;
3327270759Ssmh	}
3328191902Skmacy
3329277300Ssmh#ifdef illumos
3330168404Spjd	/*
3331185029Spjd	 * check that we're out of range of the pageout scanner.  It starts to
3332185029Spjd	 * schedule paging if freemem is less than lotsfree and needfree.
3333185029Spjd	 * lotsfree is the high-water mark for pageout, and needfree is the
3334185029Spjd	 * number of needed free pages.  We add extra pages here to make sure
3335185029Spjd	 * the scanner doesn't start up while we're freeing memory.
3336185029Spjd	 */
3337286625Smav	n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
3338286625Smav	if (n < lowest) {
3339286625Smav		lowest = n;
3340286625Smav		r = FMR_LOTSFREE;
3341286625Smav	}
3342185029Spjd
3343185029Spjd	/*
3344168404Spjd	 * check to make sure that swapfs has enough space so that anon
3345185029Spjd	 * reservations can still succeed. anon_resvmem() checks that the
3346168404Spjd	 * availrmem is greater than swapfs_minfree, and the number of reserved
3347168404Spjd	 * swap pages.  We also add a bit of extra here just to prevent
3348168404Spjd	 * circumstances from getting really dire.
3349168404Spjd	 */
3350286625Smav	n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
3351286625Smav	    desfree - arc_swapfs_reserve);
3352286625Smav	if (n < lowest) {
3353286625Smav		lowest = n;
3354286625Smav		r = FMR_SWAPFS_MINFREE;
3355286625Smav	}
3356168404Spjd
3357286625Smav
3358168404Spjd	/*
3359272483Ssmh	 * Check that we have enough availrmem that memory locking (e.g., via
3360272483Ssmh	 * mlock(3C) or memcntl(2)) can still succeed.  (pages_pp_maximum
3361272483Ssmh	 * stores the number of pages that cannot be locked; when availrmem
3362272483Ssmh	 * drops below pages_pp_maximum, page locking mechanisms such as
3363272483Ssmh	 * page_pp_lock() will fail.)
3364272483Ssmh	 */
3365286625Smav	n = PAGESIZE * (availrmem - pages_pp_maximum -
3366286625Smav	    arc_pages_pp_reserve);
3367286625Smav	if (n < lowest) {
3368286625Smav		lowest = n;
3369286625Smav		r = FMR_PAGES_PP_MAXIMUM;
3370286625Smav	}
3371272483Ssmh
3372277300Ssmh#endif	/* illumos */
3373272483Ssmh#if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
3374272483Ssmh	/*
3375168404Spjd	 * If we're on an i386 platform, it's possible that we'll exhaust the
3376168404Spjd	 * kernel heap space before we ever run out of available physical
3377168404Spjd	 * memory.  Most checks of the size of the heap_area compare against
3378168404Spjd	 * tune.t_minarmem, which is the minimum available real memory that we
3379168404Spjd	 * can have in the system.  However, this is generally fixed at 25 pages
3380168404Spjd	 * which is so low that it's useless.  In this comparison, we seek to
3381168404Spjd	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
3382185029Spjd	 * heap is allocated.  (Or, in the calculation, if less than 1/4th is
3383168404Spjd	 * free)
3384168404Spjd	 */
3385286655Smav	n = (int64_t)vmem_size(heap_arena, VMEM_FREE) -
3386286628Smav	    (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2);
3387286625Smav	if (n < lowest) {
3388286625Smav		lowest = n;
3389286625Smav		r = FMR_HEAP_ARENA;
3390270861Ssmh	}
3391281026Smav#define	zio_arena	NULL
3392281026Smav#else
3393281026Smav#define	zio_arena	heap_arena
3394270861Ssmh#endif
3395281026Smav
3396272483Ssmh	/*
3397272483Ssmh	 * If zio data pages are being allocated out of a separate heap segment,
3398272483Ssmh	 * then enforce that the size of available vmem for this arena remains
3399272483Ssmh	 * above about 1/16th free.
3400272483Ssmh	 *
3401272483Ssmh	 * Note: The 1/16th arena free requirement was put in place
3402272483Ssmh	 * to aggressively evict memory from the arc in order to avoid
3403272483Ssmh	 * memory fragmentation issues.
3404272483Ssmh	 */
3405286625Smav	if (zio_arena != NULL) {
3406286655Smav		n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
3407286625Smav		    (vmem_size(zio_arena, VMEM_ALLOC) >> 4);
3408286625Smav		if (n < lowest) {
3409286625Smav			lowest = n;
3410286625Smav			r = FMR_ZIO_ARENA;
3411286625Smav		}
3412286625Smav	}
3413281026Smav
3414281026Smav	/*
3415281026Smav	 * Above limits know nothing about real level of KVA fragmentation.
3416281026Smav	 * Start aggressive reclamation if too little sequential KVA left.
3417281026Smav	 */
3418286625Smav	if (lowest > 0) {
3419286625Smav		n = (vmem_size(heap_arena, VMEM_MAXFREE) < zfs_max_recordsize) ?
3420286655Smav		    -((int64_t)vmem_size(heap_arena, VMEM_ALLOC) >> 4) :
3421286655Smav		    INT64_MAX;
3422286625Smav		if (n < lowest) {
3423286625Smav			lowest = n;
3424286625Smav			r = FMR_ZIO_FRAG;
3425286625Smav		}
3426281109Smav	}
3427281026Smav
3428272483Ssmh#else	/* _KERNEL */
3429286625Smav	/* Every 100 calls, free a small amount */
3430168404Spjd	if (spa_get_random(100) == 0)
3431286625Smav		lowest = -1024;
3432272483Ssmh#endif	/* _KERNEL */
3433270759Ssmh
3434286625Smav	last_free_memory = lowest;
3435286625Smav	last_free_reason = r;
3436286625Smav	DTRACE_PROBE2(arc__available_memory, int64_t, lowest, int, r);
3437286625Smav	return (lowest);
3438168404Spjd}
3439168404Spjd
3440286625Smav
3441286625Smav/*
3442286625Smav * Determine if the system is under memory pressure and is asking
3443286625Smav * to reclaim memory. A return value of TRUE indicates that the system
3444286625Smav * is under memory pressure and that the arc should adjust accordingly.
3445286625Smav */
3446286625Smavstatic boolean_t
3447286625Smavarc_reclaim_needed(void)
3448286625Smav{
3449286625Smav	return (arc_available_memory() < 0);
3450286625Smav}
3451286625Smav
3452208454Spjdextern kmem_cache_t	*zio_buf_cache[];
3453208454Spjdextern kmem_cache_t	*zio_data_buf_cache[];
3454272527Sdelphijextern kmem_cache_t	*range_seg_cache;
3455208454Spjd
3456278040Ssmhstatic __noinline void
3457286625Smavarc_kmem_reap_now(void)
3458168404Spjd{
3459168404Spjd	size_t			i;
3460168404Spjd	kmem_cache_t		*prev_cache = NULL;
3461168404Spjd	kmem_cache_t		*prev_data_cache = NULL;
3462168404Spjd
3463272483Ssmh	DTRACE_PROBE(arc__kmem_reap_start);
3464168404Spjd#ifdef _KERNEL
3465185029Spjd	if (arc_meta_used >= arc_meta_limit) {
3466185029Spjd		/*
3467185029Spjd		 * We are exceeding our meta-data cache limit.
3468185029Spjd		 * Purge some DNLC entries to release holds on meta-data.
3469185029Spjd		 */
3470185029Spjd		dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
3471185029Spjd	}
3472168404Spjd#if defined(__i386)
3473168404Spjd	/*
3474168404Spjd	 * Reclaim unused memory from all kmem caches.
3475168404Spjd	 */
3476168404Spjd	kmem_reap();
3477168404Spjd#endif
3478168404Spjd#endif
3479168404Spjd
3480168404Spjd	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
3481168404Spjd		if (zio_buf_cache[i] != prev_cache) {
3482168404Spjd			prev_cache = zio_buf_cache[i];
3483168404Spjd			kmem_cache_reap_now(zio_buf_cache[i]);
3484168404Spjd		}
3485168404Spjd		if (zio_data_buf_cache[i] != prev_data_cache) {
3486168404Spjd			prev_data_cache = zio_data_buf_cache[i];
3487168404Spjd			kmem_cache_reap_now(zio_data_buf_cache[i]);
3488168404Spjd		}
3489168404Spjd	}
3490168404Spjd	kmem_cache_reap_now(buf_cache);
3491286570Smav	kmem_cache_reap_now(hdr_full_cache);
3492286570Smav	kmem_cache_reap_now(hdr_l2only_cache);
3493272506Sdelphij	kmem_cache_reap_now(range_seg_cache);
3494272483Ssmh
3495277300Ssmh#ifdef illumos
3496286625Smav	if (zio_arena != NULL) {
3497286625Smav		/*
3498286625Smav		 * Ask the vmem arena to reclaim unused memory from its
3499286625Smav		 * quantum caches.
3500286625Smav		 */
3501272483Ssmh		vmem_qcache_reap(zio_arena);
3502286625Smav	}
3503272483Ssmh#endif
3504272483Ssmh	DTRACE_PROBE(arc__kmem_reap_end);
3505168404Spjd}
3506168404Spjd
3507286763Smav/*
3508286763Smav * Threads can block in arc_get_data_buf() waiting for this thread to evict
3509286763Smav * enough data and signal them to proceed. When this happens, the threads in
3510286763Smav * arc_get_data_buf() are sleeping while holding the hash lock for their
3511286763Smav * particular arc header. Thus, we must be careful to never sleep on a
3512286763Smav * hash lock in this thread. This is to prevent the following deadlock:
3513286763Smav *
3514286763Smav *  - Thread A sleeps on CV in arc_get_data_buf() holding hash lock "L",
3515286763Smav *    waiting for the reclaim thread to signal it.
3516286763Smav *
3517286763Smav *  - arc_reclaim_thread() tries to acquire hash lock "L" using mutex_enter,
3518286763Smav *    fails, and goes to sleep forever.
3519286763Smav *
3520286763Smav * This possible deadlock is avoided by always acquiring a hash lock
3521286763Smav * using mutex_tryenter() from arc_reclaim_thread().
3522286763Smav */
3523168404Spjdstatic void
3524168404Spjdarc_reclaim_thread(void *dummy __unused)
3525168404Spjd{
3526168404Spjd	clock_t			growtime = 0;
3527168404Spjd	callb_cpr_t		cpr;
3528168404Spjd
3529286763Smav	CALLB_CPR_INIT(&cpr, &arc_reclaim_lock, callb_generic_cpr, FTAG);
3530168404Spjd
3531286763Smav	mutex_enter(&arc_reclaim_lock);
3532286763Smav	while (!arc_reclaim_thread_exit) {
3533286625Smav		int64_t free_memory = arc_available_memory();
3534286763Smav		uint64_t evicted = 0;
3535286763Smav
3536286763Smav		mutex_exit(&arc_reclaim_lock);
3537286763Smav
3538286625Smav		if (free_memory < 0) {
3539168404Spjd
3540286625Smav			arc_no_grow = B_TRUE;
3541286625Smav			arc_warm = B_TRUE;
3542168404Spjd
3543286625Smav			/*
3544286625Smav			 * Wait at least zfs_grow_retry (default 60) seconds
3545286625Smav			 * before considering growing.
3546286625Smav			 */
3547219089Spjd			growtime = ddi_get_lbolt() + (arc_grow_retry * hz);
3548168404Spjd
3549286625Smav			arc_kmem_reap_now();
3550286625Smav
3551286625Smav			/*
3552286625Smav			 * If we are still low on memory, shrink the ARC
3553286625Smav			 * so that we have arc_shrink_min free space.
3554286625Smav			 */
3555286625Smav			free_memory = arc_available_memory();
3556286625Smav
3557286625Smav			int64_t to_free =
3558286625Smav			    (arc_c >> arc_shrink_shift) - free_memory;
3559286625Smav			if (to_free > 0) {
3560286625Smav#ifdef _KERNEL
3561286625Smav				to_free = MAX(to_free, ptob(needfree));
3562286625Smav#endif
3563286625Smav				arc_shrink(to_free);
3564168404Spjd			}
3565286625Smav		} else if (free_memory < arc_c >> arc_no_grow_shift) {
3566286625Smav			arc_no_grow = B_TRUE;
3567286625Smav		} else if (ddi_get_lbolt() >= growtime) {
3568286625Smav			arc_no_grow = B_FALSE;
3569168404Spjd		}
3570168404Spjd
3571286763Smav		evicted = arc_adjust();
3572168404Spjd
3573286763Smav		mutex_enter(&arc_reclaim_lock);
3574168404Spjd
3575286763Smav		/*
3576286763Smav		 * If evicted is zero, we couldn't evict anything via
3577286763Smav		 * arc_adjust(). This could be due to hash lock
3578286763Smav		 * collisions, but more likely due to the majority of
3579286763Smav		 * arc buffers being unevictable. Therefore, even if
3580286763Smav		 * arc_size is above arc_c, another pass is unlikely to
3581286763Smav		 * be helpful and could potentially cause us to enter an
3582286763Smav		 * infinite loop.
3583286763Smav		 */
3584286763Smav		if (arc_size <= arc_c || evicted == 0) {
3585211762Savg#ifdef _KERNEL
3586185029Spjd			needfree = 0;
3587168404Spjd#endif
3588286763Smav			/*
3589286763Smav			 * We're either no longer overflowing, or we
3590286763Smav			 * can't evict anything more, so we should wake
3591286763Smav			 * up any threads before we go to sleep.
3592286763Smav			 */
3593286763Smav			cv_broadcast(&arc_reclaim_waiters_cv);
3594168404Spjd
3595286763Smav			/*
3596286763Smav			 * Block until signaled, or after one second (we
3597286763Smav			 * might need to perform arc_kmem_reap_now()
3598286763Smav			 * even if we aren't being signalled)
3599286763Smav			 */
3600286763Smav			CALLB_CPR_SAFE_BEGIN(&cpr);
3601286763Smav			(void) cv_timedwait(&arc_reclaim_thread_cv,
3602286763Smav			    &arc_reclaim_lock, hz);
3603286763Smav			CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_lock);
3604286763Smav		}
3605286763Smav	}
3606286763Smav
3607286763Smav	arc_reclaim_thread_exit = FALSE;
3608286763Smav	cv_broadcast(&arc_reclaim_thread_cv);
3609286763Smav	CALLB_CPR_EXIT(&cpr);		/* drops arc_reclaim_lock */
3610286763Smav	thread_exit();
3611286763Smav}
3612286763Smav
3613286763Smavstatic void
3614286763Smavarc_user_evicts_thread(void *dummy __unused)
3615286763Smav{
3616286763Smav	callb_cpr_t cpr;
3617286763Smav
3618286763Smav	CALLB_CPR_INIT(&cpr, &arc_user_evicts_lock, callb_generic_cpr, FTAG);
3619286763Smav
3620286763Smav	mutex_enter(&arc_user_evicts_lock);
3621286763Smav	while (!arc_user_evicts_thread_exit) {
3622286763Smav		mutex_exit(&arc_user_evicts_lock);
3623286763Smav
3624286763Smav		arc_do_user_evicts();
3625286763Smav
3626286574Smav		/*
3627286574Smav		 * This is necessary in order for the mdb ::arc dcmd to
3628286574Smav		 * show up to date information. Since the ::arc command
3629286574Smav		 * does not call the kstat's update function, without
3630286574Smav		 * this call, the command may show stale stats for the
3631286574Smav		 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
3632286574Smav		 * with this change, the data might be up to 1 second
3633286574Smav		 * out of date; but that should suffice. The arc_state_t
3634286574Smav		 * structures can be queried directly if more accurate
3635286574Smav		 * information is needed.
3636286574Smav		 */
3637286574Smav		if (arc_ksp != NULL)
3638286574Smav			arc_ksp->ks_update(arc_ksp, KSTAT_READ);
3639286574Smav
3640286763Smav		mutex_enter(&arc_user_evicts_lock);
3641286763Smav
3642286763Smav		/*
3643286763Smav		 * Block until signaled, or after one second (we need to
3644286763Smav		 * call the arc's kstat update function regularly).
3645286763Smav		 */
3646168404Spjd		CALLB_CPR_SAFE_BEGIN(&cpr);
3647286763Smav		(void) cv_timedwait(&arc_user_evicts_cv,
3648286763Smav		    &arc_user_evicts_lock, hz);
3649286763Smav		CALLB_CPR_SAFE_END(&cpr, &arc_user_evicts_lock);
3650168404Spjd	}
3651168404Spjd
3652286763Smav	arc_user_evicts_thread_exit = FALSE;
3653286763Smav	cv_broadcast(&arc_user_evicts_cv);
3654286763Smav	CALLB_CPR_EXIT(&cpr);		/* drops arc_user_evicts_lock */
3655168404Spjd	thread_exit();
3656168404Spjd}
3657168404Spjd
3658168404Spjd/*
3659168404Spjd * Adapt arc info given the number of bytes we are trying to add and
3660168404Spjd * the state that we are comming from.  This function is only called
3661168404Spjd * when we are adding new content to the cache.
3662168404Spjd */
3663168404Spjdstatic void
3664168404Spjdarc_adapt(int bytes, arc_state_t *state)
3665168404Spjd{
3666168404Spjd	int mult;
3667208373Smm	uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
3668168404Spjd
3669185029Spjd	if (state == arc_l2c_only)
3670185029Spjd		return;
3671185029Spjd
3672168404Spjd	ASSERT(bytes > 0);
3673168404Spjd	/*
3674168404Spjd	 * Adapt the target size of the MRU list:
3675168404Spjd	 *	- if we just hit in the MRU ghost list, then increase
3676168404Spjd	 *	  the target size of the MRU list.
3677168404Spjd	 *	- if we just hit in the MFU ghost list, then increase
3678168404Spjd	 *	  the target size of the MFU list by decreasing the
3679168404Spjd	 *	  target size of the MRU list.
3680168404Spjd	 */
3681168404Spjd	if (state == arc_mru_ghost) {
3682168404Spjd		mult = ((arc_mru_ghost->arcs_size >= arc_mfu_ghost->arcs_size) ?
3683168404Spjd		    1 : (arc_mfu_ghost->arcs_size/arc_mru_ghost->arcs_size));
3684209275Smm		mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
3685168404Spjd
3686208373Smm		arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
3687168404Spjd	} else if (state == arc_mfu_ghost) {
3688208373Smm		uint64_t delta;
3689208373Smm
3690168404Spjd		mult = ((arc_mfu_ghost->arcs_size >= arc_mru_ghost->arcs_size) ?
3691168404Spjd		    1 : (arc_mru_ghost->arcs_size/arc_mfu_ghost->arcs_size));
3692209275Smm		mult = MIN(mult, 10);
3693168404Spjd
3694208373Smm		delta = MIN(bytes * mult, arc_p);
3695208373Smm		arc_p = MAX(arc_p_min, arc_p - delta);
3696168404Spjd	}
3697168404Spjd	ASSERT((int64_t)arc_p >= 0);
3698168404Spjd
3699168404Spjd	if (arc_reclaim_needed()) {
3700286763Smav		cv_signal(&arc_reclaim_thread_cv);
3701168404Spjd		return;
3702168404Spjd	}
3703168404Spjd
3704168404Spjd	if (arc_no_grow)
3705168404Spjd		return;
3706168404Spjd
3707168404Spjd	if (arc_c >= arc_c_max)
3708168404Spjd		return;
3709168404Spjd
3710168404Spjd	/*
3711168404Spjd	 * If we're within (2 * maxblocksize) bytes of the target
3712168404Spjd	 * cache size, increment the target cache size
3713168404Spjd	 */
3714168404Spjd	if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
3715272483Ssmh		DTRACE_PROBE1(arc__inc_adapt, int, bytes);
3716168404Spjd		atomic_add_64(&arc_c, (int64_t)bytes);
3717168404Spjd		if (arc_c > arc_c_max)
3718168404Spjd			arc_c = arc_c_max;
3719168404Spjd		else if (state == arc_anon)
3720168404Spjd			atomic_add_64(&arc_p, (int64_t)bytes);
3721168404Spjd		if (arc_p > arc_c)
3722168404Spjd			arc_p = arc_c;
3723168404Spjd	}
3724168404Spjd	ASSERT((int64_t)arc_p >= 0);
3725168404Spjd}
3726168404Spjd
3727168404Spjd/*
3728286763Smav * Check if arc_size has grown past our upper threshold, determined by
3729286763Smav * zfs_arc_overflow_shift.
3730168404Spjd */
3731286763Smavstatic boolean_t
3732286763Smavarc_is_overflowing(void)
3733168404Spjd{
3734286763Smav	/* Always allow at least one block of overflow */
3735286763Smav	uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
3736286763Smav	    arc_c >> zfs_arc_overflow_shift);
3737185029Spjd
3738286763Smav	return (arc_size >= arc_c + overflow);
3739168404Spjd}
3740168404Spjd
3741168404Spjd/*
3742286763Smav * The buffer, supplied as the first argument, needs a data block. If we
3743286763Smav * are hitting the hard limit for the cache size, we must sleep, waiting
3744286763Smav * for the eviction thread to catch up. If we're past the target size
3745286763Smav * but below the hard limit, we'll only signal the reclaim thread and
3746286763Smav * continue on.
3747168404Spjd */
3748168404Spjdstatic void
3749168404Spjdarc_get_data_buf(arc_buf_t *buf)
3750168404Spjd{
3751286570Smav	arc_state_t		*state = buf->b_hdr->b_l1hdr.b_state;
3752168404Spjd	uint64_t		size = buf->b_hdr->b_size;
3753286570Smav	arc_buf_contents_t	type = arc_buf_type(buf->b_hdr);
3754168404Spjd
3755168404Spjd	arc_adapt(size, state);
3756168404Spjd
3757168404Spjd	/*
3758286763Smav	 * If arc_size is currently overflowing, and has grown past our
3759286763Smav	 * upper limit, we must be adding data faster than the evict
3760286763Smav	 * thread can evict. Thus, to ensure we don't compound the
3761286763Smav	 * problem by adding more data and forcing arc_size to grow even
3762286763Smav	 * further past it's target size, we halt and wait for the
3763286763Smav	 * eviction thread to catch up.
3764286763Smav	 *
3765286763Smav	 * It's also possible that the reclaim thread is unable to evict
3766286763Smav	 * enough buffers to get arc_size below the overflow limit (e.g.
3767286763Smav	 * due to buffers being un-evictable, or hash lock collisions).
3768286763Smav	 * In this case, we want to proceed regardless if we're
3769286763Smav	 * overflowing; thus we don't use a while loop here.
3770168404Spjd	 */
3771286763Smav	if (arc_is_overflowing()) {
3772286763Smav		mutex_enter(&arc_reclaim_lock);
3773286763Smav
3774286763Smav		/*
3775286763Smav		 * Now that we've acquired the lock, we may no longer be
3776286763Smav		 * over the overflow limit, lets check.
3777286763Smav		 *
3778286763Smav		 * We're ignoring the case of spurious wake ups. If that
3779286763Smav		 * were to happen, it'd let this thread consume an ARC
3780286763Smav		 * buffer before it should have (i.e. before we're under
3781286763Smav		 * the overflow limit and were signalled by the reclaim
3782286763Smav		 * thread). As long as that is a rare occurrence, it
3783286763Smav		 * shouldn't cause any harm.
3784286763Smav		 */
3785286763Smav		if (arc_is_overflowing()) {
3786286763Smav			cv_signal(&arc_reclaim_thread_cv);
3787286763Smav			cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
3788168404Spjd		}
3789286763Smav
3790286763Smav		mutex_exit(&arc_reclaim_lock);
3791168404Spjd	}
3792168404Spjd
3793286763Smav	if (type == ARC_BUFC_METADATA) {
3794286763Smav		buf->b_data = zio_buf_alloc(size);
3795286763Smav		arc_space_consume(size, ARC_SPACE_META);
3796168404Spjd	} else {
3797286763Smav		ASSERT(type == ARC_BUFC_DATA);
3798286763Smav		buf->b_data = zio_data_buf_alloc(size);
3799286763Smav		arc_space_consume(size, ARC_SPACE_DATA);
3800168404Spjd	}
3801286763Smav
3802168404Spjd	/*
3803168404Spjd	 * Update the state size.  Note that ghost states have a
3804168404Spjd	 * "ghost size" and so don't need to be updated.
3805168404Spjd	 */
3806286570Smav	if (!GHOST_STATE(buf->b_hdr->b_l1hdr.b_state)) {
3807168404Spjd		arc_buf_hdr_t *hdr = buf->b_hdr;
3808168404Spjd
3809286570Smav		atomic_add_64(&hdr->b_l1hdr.b_state->arcs_size, size);
3810286763Smav
3811286763Smav		/*
3812286763Smav		 * If this is reached via arc_read, the link is
3813286763Smav		 * protected by the hash lock. If reached via
3814286763Smav		 * arc_buf_alloc, the header should not be accessed by
3815286763Smav		 * any other thread. And, if reached via arc_read_done,
3816286763Smav		 * the hash lock will protect it if it's found in the
3817286763Smav		 * hash table; otherwise no other thread should be
3818286763Smav		 * trying to [add|remove]_reference it.
3819286763Smav		 */
3820286763Smav		if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
3821286570Smav			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3822286570Smav			atomic_add_64(&hdr->b_l1hdr.b_state->arcs_lsize[type],
3823286570Smav			    size);
3824168404Spjd		}
3825168404Spjd		/*
3826168404Spjd		 * If we are growing the cache, and we are adding anonymous
3827168404Spjd		 * data, and we have outgrown arc_p, update arc_p
3828168404Spjd		 */
3829286570Smav		if (arc_size < arc_c && hdr->b_l1hdr.b_state == arc_anon &&
3830168404Spjd		    arc_anon->arcs_size + arc_mru->arcs_size > arc_p)
3831168404Spjd			arc_p = MIN(arc_c, arc_p + size);
3832168404Spjd	}
3833205231Skmacy	ARCSTAT_BUMP(arcstat_allocated);
3834168404Spjd}
3835168404Spjd
3836168404Spjd/*
3837168404Spjd * This routine is called whenever a buffer is accessed.
3838168404Spjd * NOTE: the hash lock is dropped in this function.
3839168404Spjd */
3840168404Spjdstatic void
3841275811Sdelphijarc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3842168404Spjd{
3843219089Spjd	clock_t now;
3844219089Spjd
3845168404Spjd	ASSERT(MUTEX_HELD(hash_lock));
3846286570Smav	ASSERT(HDR_HAS_L1HDR(hdr));
3847168404Spjd
3848286570Smav	if (hdr->b_l1hdr.b_state == arc_anon) {
3849168404Spjd		/*
3850168404Spjd		 * This buffer is not in the cache, and does not
3851168404Spjd		 * appear in our "ghost" list.  Add the new buffer
3852168404Spjd		 * to the MRU state.
3853168404Spjd		 */
3854168404Spjd
3855286570Smav		ASSERT0(hdr->b_l1hdr.b_arc_access);
3856286570Smav		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3857275811Sdelphij		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3858275811Sdelphij		arc_change_state(arc_mru, hdr, hash_lock);
3859168404Spjd
3860286570Smav	} else if (hdr->b_l1hdr.b_state == arc_mru) {
3861219089Spjd		now = ddi_get_lbolt();
3862219089Spjd
3863168404Spjd		/*
3864168404Spjd		 * If this buffer is here because of a prefetch, then either:
3865168404Spjd		 * - clear the flag if this is a "referencing" read
3866168404Spjd		 *   (any subsequent access will bump this into the MFU state).
3867168404Spjd		 * or
3868168404Spjd		 * - move the buffer to the head of the list if this is
3869168404Spjd		 *   another prefetch (to make it less likely to be evicted).
3870168404Spjd		 */
3871286570Smav		if (HDR_PREFETCH(hdr)) {
3872286570Smav			if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
3873286763Smav				/* link protected by hash lock */
3874286763Smav				ASSERT(multilist_link_active(
3875286570Smav				    &hdr->b_l1hdr.b_arc_node));
3876168404Spjd			} else {
3877275811Sdelphij				hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3878168404Spjd				ARCSTAT_BUMP(arcstat_mru_hits);
3879168404Spjd			}
3880286570Smav			hdr->b_l1hdr.b_arc_access = now;
3881168404Spjd			return;
3882168404Spjd		}
3883168404Spjd
3884168404Spjd		/*
3885168404Spjd		 * This buffer has been "accessed" only once so far,
3886168404Spjd		 * but it is still in the cache. Move it to the MFU
3887168404Spjd		 * state.
3888168404Spjd		 */
3889286570Smav		if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
3890168404Spjd			/*
3891168404Spjd			 * More than 125ms have passed since we
3892168404Spjd			 * instantiated this buffer.  Move it to the
3893168404Spjd			 * most frequently used state.
3894168404Spjd			 */
3895286570Smav			hdr->b_l1hdr.b_arc_access = now;
3896275811Sdelphij			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3897275811Sdelphij			arc_change_state(arc_mfu, hdr, hash_lock);
3898168404Spjd		}
3899168404Spjd		ARCSTAT_BUMP(arcstat_mru_hits);
3900286570Smav	} else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
3901168404Spjd		arc_state_t	*new_state;
3902168404Spjd		/*
3903168404Spjd		 * This buffer has been "accessed" recently, but
3904168404Spjd		 * was evicted from the cache.  Move it to the
3905168404Spjd		 * MFU state.
3906168404Spjd		 */
3907168404Spjd
3908286570Smav		if (HDR_PREFETCH(hdr)) {
3909168404Spjd			new_state = arc_mru;
3910286570Smav			if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0)
3911275811Sdelphij				hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3912275811Sdelphij			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3913168404Spjd		} else {
3914168404Spjd			new_state = arc_mfu;
3915275811Sdelphij			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3916168404Spjd		}
3917168404Spjd
3918286570Smav		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3919275811Sdelphij		arc_change_state(new_state, hdr, hash_lock);
3920168404Spjd
3921168404Spjd		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
3922286570Smav	} else if (hdr->b_l1hdr.b_state == arc_mfu) {
3923168404Spjd		/*
3924168404Spjd		 * This buffer has been accessed more than once and is
3925168404Spjd		 * still in the cache.  Keep it in the MFU state.
3926168404Spjd		 *
3927168404Spjd		 * NOTE: an add_reference() that occurred when we did
3928168404Spjd		 * the arc_read() will have kicked this off the list.
3929168404Spjd		 * If it was a prefetch, we will explicitly move it to
3930168404Spjd		 * the head of the list now.
3931168404Spjd		 */
3932286570Smav		if ((HDR_PREFETCH(hdr)) != 0) {
3933286570Smav			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3934286763Smav			/* link protected by hash_lock */
3935286763Smav			ASSERT(multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3936168404Spjd		}
3937168404Spjd		ARCSTAT_BUMP(arcstat_mfu_hits);
3938286570Smav		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3939286570Smav	} else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
3940168404Spjd		arc_state_t	*new_state = arc_mfu;
3941168404Spjd		/*
3942168404Spjd		 * This buffer has been accessed more than once but has
3943168404Spjd		 * been evicted from the cache.  Move it back to the
3944168404Spjd		 * MFU state.
3945168404Spjd		 */
3946168404Spjd
3947286570Smav		if (HDR_PREFETCH(hdr)) {
3948168404Spjd			/*
3949168404Spjd			 * This is a prefetch access...
3950168404Spjd			 * move this block back to the MRU state.
3951168404Spjd			 */
3952286570Smav			ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
3953168404Spjd			new_state = arc_mru;
3954168404Spjd		}
3955168404Spjd
3956286570Smav		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3957275811Sdelphij		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3958275811Sdelphij		arc_change_state(new_state, hdr, hash_lock);
3959168404Spjd
3960168404Spjd		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
3961286570Smav	} else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
3962185029Spjd		/*
3963185029Spjd		 * This buffer is on the 2nd Level ARC.
3964185029Spjd		 */
3965185029Spjd
3966286570Smav		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3967275811Sdelphij		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3968275811Sdelphij		arc_change_state(arc_mfu, hdr, hash_lock);
3969168404Spjd	} else {
3970168404Spjd		ASSERT(!"invalid arc state");
3971168404Spjd	}
3972168404Spjd}
3973168404Spjd
3974168404Spjd/* a generic arc_done_func_t which you can use */
3975168404Spjd/* ARGSUSED */
3976168404Spjdvoid
3977168404Spjdarc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
3978168404Spjd{
3979219089Spjd	if (zio == NULL || zio->io_error == 0)
3980219089Spjd		bcopy(buf->b_data, arg, buf->b_hdr->b_size);
3981248571Smm	VERIFY(arc_buf_remove_ref(buf, arg));
3982168404Spjd}
3983168404Spjd
3984185029Spjd/* a generic arc_done_func_t */
3985168404Spjdvoid
3986168404Spjdarc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
3987168404Spjd{
3988168404Spjd	arc_buf_t **bufp = arg;
3989168404Spjd	if (zio && zio->io_error) {
3990248571Smm		VERIFY(arc_buf_remove_ref(buf, arg));
3991168404Spjd		*bufp = NULL;
3992168404Spjd	} else {
3993168404Spjd		*bufp = buf;
3994219089Spjd		ASSERT(buf->b_data);
3995168404Spjd	}
3996168404Spjd}
3997168404Spjd
3998168404Spjdstatic void
3999168404Spjdarc_read_done(zio_t *zio)
4000168404Spjd{
4001268075Sdelphij	arc_buf_hdr_t	*hdr;
4002168404Spjd	arc_buf_t	*buf;
4003168404Spjd	arc_buf_t	*abuf;	/* buffer we're assigning to callback */
4004268075Sdelphij	kmutex_t	*hash_lock = NULL;
4005168404Spjd	arc_callback_t	*callback_list, *acb;
4006168404Spjd	int		freeable = FALSE;
4007168404Spjd
4008168404Spjd	buf = zio->io_private;
4009168404Spjd	hdr = buf->b_hdr;
4010168404Spjd
4011168404Spjd	/*
4012168404Spjd	 * The hdr was inserted into hash-table and removed from lists
4013168404Spjd	 * prior to starting I/O.  We should find this header, since
4014168404Spjd	 * it's in the hash table, and it should be legit since it's
4015168404Spjd	 * not possible to evict it during the I/O.  The only possible
4016168404Spjd	 * reason for it not to be found is if we were freed during the
4017168404Spjd	 * read.
4018168404Spjd	 */
4019268075Sdelphij	if (HDR_IN_HASH_TABLE(hdr)) {
4020268075Sdelphij		ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
4021268075Sdelphij		ASSERT3U(hdr->b_dva.dva_word[0], ==,
4022268075Sdelphij		    BP_IDENTITY(zio->io_bp)->dva_word[0]);
4023268075Sdelphij		ASSERT3U(hdr->b_dva.dva_word[1], ==,
4024268075Sdelphij		    BP_IDENTITY(zio->io_bp)->dva_word[1]);
4025168404Spjd
4026268075Sdelphij		arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
4027268075Sdelphij		    &hash_lock);
4028168404Spjd
4029268075Sdelphij		ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) &&
4030268075Sdelphij		    hash_lock == NULL) ||
4031268075Sdelphij		    (found == hdr &&
4032268075Sdelphij		    DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
4033268075Sdelphij		    (found == hdr && HDR_L2_READING(hdr)));
4034268075Sdelphij	}
4035268075Sdelphij
4036275811Sdelphij	hdr->b_flags &= ~ARC_FLAG_L2_EVICTED;
4037286570Smav	if (l2arc_noprefetch && HDR_PREFETCH(hdr))
4038275811Sdelphij		hdr->b_flags &= ~ARC_FLAG_L2CACHE;
4039206796Spjd
4040168404Spjd	/* byteswap if necessary */
4041286570Smav	callback_list = hdr->b_l1hdr.b_acb;
4042168404Spjd	ASSERT(callback_list != NULL);
4043209101Smm	if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
4044236884Smm		dmu_object_byteswap_t bswap =
4045236884Smm		    DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
4046185029Spjd		arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
4047185029Spjd		    byteswap_uint64_array :
4048236884Smm		    dmu_ot_byteswap[bswap].ob_func;
4049185029Spjd		func(buf->b_data, hdr->b_size);
4050185029Spjd	}
4051168404Spjd
4052185029Spjd	arc_cksum_compute(buf, B_FALSE);
4053240133Smm#ifdef illumos
4054240133Smm	arc_buf_watch(buf);
4055277300Ssmh#endif
4056168404Spjd
4057286570Smav	if (hash_lock && zio->io_error == 0 &&
4058286570Smav	    hdr->b_l1hdr.b_state == arc_anon) {
4059219089Spjd		/*
4060219089Spjd		 * Only call arc_access on anonymous buffers.  This is because
4061219089Spjd		 * if we've issued an I/O for an evicted buffer, we've already
4062219089Spjd		 * called arc_access (to prevent any simultaneous readers from
4063219089Spjd		 * getting confused).
4064219089Spjd		 */
4065219089Spjd		arc_access(hdr, hash_lock);
4066219089Spjd	}
4067219089Spjd
4068168404Spjd	/* create copies of the data buffer for the callers */
4069168404Spjd	abuf = buf;
4070168404Spjd	for (acb = callback_list; acb; acb = acb->acb_next) {
4071168404Spjd		if (acb->acb_done) {
4072242845Sdelphij			if (abuf == NULL) {
4073242845Sdelphij				ARCSTAT_BUMP(arcstat_duplicate_reads);
4074168404Spjd				abuf = arc_buf_clone(buf);
4075242845Sdelphij			}
4076168404Spjd			acb->acb_buf = abuf;
4077168404Spjd			abuf = NULL;
4078168404Spjd		}
4079168404Spjd	}
4080286570Smav	hdr->b_l1hdr.b_acb = NULL;
4081275811Sdelphij	hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
4082168404Spjd	ASSERT(!HDR_BUF_AVAILABLE(hdr));
4083219089Spjd	if (abuf == buf) {
4084219089Spjd		ASSERT(buf->b_efunc == NULL);
4085286570Smav		ASSERT(hdr->b_l1hdr.b_datacnt == 1);
4086275811Sdelphij		hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
4087219089Spjd	}
4088168404Spjd
4089286570Smav	ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
4090286570Smav	    callback_list != NULL);
4091168404Spjd
4092168404Spjd	if (zio->io_error != 0) {
4093275811Sdelphij		hdr->b_flags |= ARC_FLAG_IO_ERROR;
4094286570Smav		if (hdr->b_l1hdr.b_state != arc_anon)
4095168404Spjd			arc_change_state(arc_anon, hdr, hash_lock);
4096168404Spjd		if (HDR_IN_HASH_TABLE(hdr))
4097168404Spjd			buf_hash_remove(hdr);
4098286570Smav		freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4099168404Spjd	}
4100168404Spjd
4101168404Spjd	/*
4102168404Spjd	 * Broadcast before we drop the hash_lock to avoid the possibility
4103168404Spjd	 * that the hdr (and hence the cv) might be freed before we get to
4104168404Spjd	 * the cv_broadcast().
4105168404Spjd	 */
4106286570Smav	cv_broadcast(&hdr->b_l1hdr.b_cv);
4107168404Spjd
4108286570Smav	if (hash_lock != NULL) {
4109168404Spjd		mutex_exit(hash_lock);
4110168404Spjd	} else {
4111168404Spjd		/*
4112168404Spjd		 * This block was freed while we waited for the read to
4113168404Spjd		 * complete.  It has been removed from the hash table and
4114168404Spjd		 * moved to the anonymous state (so that it won't show up
4115168404Spjd		 * in the cache).
4116168404Spjd		 */
4117286570Smav		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
4118286570Smav		freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4119168404Spjd	}
4120168404Spjd
4121168404Spjd	/* execute each callback and free its structure */
4122168404Spjd	while ((acb = callback_list) != NULL) {
4123168404Spjd		if (acb->acb_done)
4124168404Spjd			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
4125168404Spjd
4126168404Spjd		if (acb->acb_zio_dummy != NULL) {
4127168404Spjd			acb->acb_zio_dummy->io_error = zio->io_error;
4128168404Spjd			zio_nowait(acb->acb_zio_dummy);
4129168404Spjd		}
4130168404Spjd
4131168404Spjd		callback_list = acb->acb_next;
4132168404Spjd		kmem_free(acb, sizeof (arc_callback_t));
4133168404Spjd	}
4134168404Spjd
4135168404Spjd	if (freeable)
4136168404Spjd		arc_hdr_destroy(hdr);
4137168404Spjd}
4138168404Spjd
4139168404Spjd/*
4140286762Smav * "Read" the block at the specified DVA (in bp) via the
4141168404Spjd * cache.  If the block is found in the cache, invoke the provided
4142168404Spjd * callback immediately and return.  Note that the `zio' parameter
4143168404Spjd * in the callback will be NULL in this case, since no IO was
4144168404Spjd * required.  If the block is not in the cache pass the read request
4145168404Spjd * on to the spa with a substitute callback function, so that the
4146168404Spjd * requested block will be added to the cache.
4147168404Spjd *
4148168404Spjd * If a read request arrives for a block that has a read in-progress,
4149168404Spjd * either wait for the in-progress read to complete (and return the
4150168404Spjd * results); or, if this is a read with a "done" func, add a record
4151168404Spjd * to the read to invoke the "done" func when the read completes,
4152168404Spjd * and return; or just return.
4153168404Spjd *
4154168404Spjd * arc_read_done() will invoke all the requested "done" functions
4155168404Spjd * for readers of this block.
4156168404Spjd */
4157168404Spjdint
4158246666Smmarc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
4159275811Sdelphij    void *private, zio_priority_t priority, int zio_flags,
4160275811Sdelphij    arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
4161168404Spjd{
4162268075Sdelphij	arc_buf_hdr_t *hdr = NULL;
4163247187Smm	arc_buf_t *buf = NULL;
4164268075Sdelphij	kmutex_t *hash_lock = NULL;
4165185029Spjd	zio_t *rzio;
4166228103Smm	uint64_t guid = spa_load_guid(spa);
4167168404Spjd
4168268075Sdelphij	ASSERT(!BP_IS_EMBEDDED(bp) ||
4169268075Sdelphij	    BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
4170268075Sdelphij
4171168404Spjdtop:
4172268075Sdelphij	if (!BP_IS_EMBEDDED(bp)) {
4173268075Sdelphij		/*
4174268075Sdelphij		 * Embedded BP's have no DVA and require no I/O to "read".
4175268075Sdelphij		 * Create an anonymous arc buf to back it.
4176268075Sdelphij		 */
4177268075Sdelphij		hdr = buf_hash_find(guid, bp, &hash_lock);
4178268075Sdelphij	}
4179168404Spjd
4180286570Smav	if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_datacnt > 0) {
4181268075Sdelphij
4182275811Sdelphij		*arc_flags |= ARC_FLAG_CACHED;
4183168404Spjd
4184168404Spjd		if (HDR_IO_IN_PROGRESS(hdr)) {
4185168404Spjd
4186275811Sdelphij			if (*arc_flags & ARC_FLAG_WAIT) {
4187286570Smav				cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
4188168404Spjd				mutex_exit(hash_lock);
4189168404Spjd				goto top;
4190168404Spjd			}
4191275811Sdelphij			ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
4192168404Spjd
4193168404Spjd			if (done) {
4194168404Spjd				arc_callback_t	*acb = NULL;
4195168404Spjd
4196168404Spjd				acb = kmem_zalloc(sizeof (arc_callback_t),
4197168404Spjd				    KM_SLEEP);
4198168404Spjd				acb->acb_done = done;
4199168404Spjd				acb->acb_private = private;
4200168404Spjd				if (pio != NULL)
4201168404Spjd					acb->acb_zio_dummy = zio_null(pio,
4202209962Smm					    spa, NULL, NULL, NULL, zio_flags);
4203168404Spjd
4204168404Spjd				ASSERT(acb->acb_done != NULL);
4205286570Smav				acb->acb_next = hdr->b_l1hdr.b_acb;
4206286570Smav				hdr->b_l1hdr.b_acb = acb;
4207168404Spjd				add_reference(hdr, hash_lock, private);
4208168404Spjd				mutex_exit(hash_lock);
4209168404Spjd				return (0);
4210168404Spjd			}
4211168404Spjd			mutex_exit(hash_lock);
4212168404Spjd			return (0);
4213168404Spjd		}
4214168404Spjd
4215286570Smav		ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
4216286570Smav		    hdr->b_l1hdr.b_state == arc_mfu);
4217168404Spjd
4218168404Spjd		if (done) {
4219168404Spjd			add_reference(hdr, hash_lock, private);
4220168404Spjd			/*
4221168404Spjd			 * If this block is already in use, create a new
4222168404Spjd			 * copy of the data so that we will be guaranteed
4223168404Spjd			 * that arc_release() will always succeed.
4224168404Spjd			 */
4225286570Smav			buf = hdr->b_l1hdr.b_buf;
4226168404Spjd			ASSERT(buf);
4227168404Spjd			ASSERT(buf->b_data);
4228168404Spjd			if (HDR_BUF_AVAILABLE(hdr)) {
4229168404Spjd				ASSERT(buf->b_efunc == NULL);
4230275811Sdelphij				hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
4231168404Spjd			} else {
4232168404Spjd				buf = arc_buf_clone(buf);
4233168404Spjd			}
4234219089Spjd
4235275811Sdelphij		} else if (*arc_flags & ARC_FLAG_PREFETCH &&
4236286570Smav		    refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4237275811Sdelphij			hdr->b_flags |= ARC_FLAG_PREFETCH;
4238168404Spjd		}
4239168404Spjd		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
4240168404Spjd		arc_access(hdr, hash_lock);
4241275811Sdelphij		if (*arc_flags & ARC_FLAG_L2CACHE)
4242275811Sdelphij			hdr->b_flags |= ARC_FLAG_L2CACHE;
4243275811Sdelphij		if (*arc_flags & ARC_FLAG_L2COMPRESS)
4244275811Sdelphij			hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4245168404Spjd		mutex_exit(hash_lock);
4246168404Spjd		ARCSTAT_BUMP(arcstat_hits);
4247286570Smav		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4248286570Smav		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
4249168404Spjd		    data, metadata, hits);
4250168404Spjd
4251168404Spjd		if (done)
4252168404Spjd			done(NULL, buf, private);
4253168404Spjd	} else {
4254168404Spjd		uint64_t size = BP_GET_LSIZE(bp);
4255268075Sdelphij		arc_callback_t *acb;
4256185029Spjd		vdev_t *vd = NULL;
4257247187Smm		uint64_t addr = 0;
4258208373Smm		boolean_t devw = B_FALSE;
4259258389Savg		enum zio_compress b_compress = ZIO_COMPRESS_OFF;
4260286570Smav		int32_t b_asize = 0;
4261168404Spjd
4262168404Spjd		if (hdr == NULL) {
4263168404Spjd			/* this block is not in the cache */
4264268075Sdelphij			arc_buf_hdr_t *exists = NULL;
4265168404Spjd			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
4266168404Spjd			buf = arc_buf_alloc(spa, size, private, type);
4267168404Spjd			hdr = buf->b_hdr;
4268268075Sdelphij			if (!BP_IS_EMBEDDED(bp)) {
4269268075Sdelphij				hdr->b_dva = *BP_IDENTITY(bp);
4270268075Sdelphij				hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
4271268075Sdelphij				exists = buf_hash_insert(hdr, &hash_lock);
4272268075Sdelphij			}
4273268075Sdelphij			if (exists != NULL) {
4274168404Spjd				/* somebody beat us to the hash insert */
4275168404Spjd				mutex_exit(hash_lock);
4276219089Spjd				buf_discard_identity(hdr);
4277168404Spjd				(void) arc_buf_remove_ref(buf, private);
4278168404Spjd				goto top; /* restart the IO request */
4279168404Spjd			}
4280275811Sdelphij
4281168404Spjd			/* if this is a prefetch, we don't have a reference */
4282275811Sdelphij			if (*arc_flags & ARC_FLAG_PREFETCH) {
4283168404Spjd				(void) remove_reference(hdr, hash_lock,
4284168404Spjd				    private);
4285275811Sdelphij				hdr->b_flags |= ARC_FLAG_PREFETCH;
4286168404Spjd			}
4287275811Sdelphij			if (*arc_flags & ARC_FLAG_L2CACHE)
4288275811Sdelphij				hdr->b_flags |= ARC_FLAG_L2CACHE;
4289275811Sdelphij			if (*arc_flags & ARC_FLAG_L2COMPRESS)
4290275811Sdelphij				hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4291168404Spjd			if (BP_GET_LEVEL(bp) > 0)
4292275811Sdelphij				hdr->b_flags |= ARC_FLAG_INDIRECT;
4293168404Spjd		} else {
4294286570Smav			/*
4295286570Smav			 * This block is in the ghost cache. If it was L2-only
4296286570Smav			 * (and thus didn't have an L1 hdr), we realloc the
4297286570Smav			 * header to add an L1 hdr.
4298286570Smav			 */
4299286570Smav			if (!HDR_HAS_L1HDR(hdr)) {
4300286570Smav				hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
4301286570Smav				    hdr_full_cache);
4302286570Smav			}
4303286570Smav
4304286570Smav			ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
4305168404Spjd			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4306286570Smav			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4307286763Smav			ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
4308168404Spjd
4309168404Spjd			/* if this is a prefetch, we don't have a reference */
4310275811Sdelphij			if (*arc_flags & ARC_FLAG_PREFETCH)
4311275811Sdelphij				hdr->b_flags |= ARC_FLAG_PREFETCH;
4312168404Spjd			else
4313168404Spjd				add_reference(hdr, hash_lock, private);
4314275811Sdelphij			if (*arc_flags & ARC_FLAG_L2CACHE)
4315275811Sdelphij				hdr->b_flags |= ARC_FLAG_L2CACHE;
4316275811Sdelphij			if (*arc_flags & ARC_FLAG_L2COMPRESS)
4317275811Sdelphij				hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4318185029Spjd			buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
4319168404Spjd			buf->b_hdr = hdr;
4320168404Spjd			buf->b_data = NULL;
4321168404Spjd			buf->b_efunc = NULL;
4322168404Spjd			buf->b_private = NULL;
4323168404Spjd			buf->b_next = NULL;
4324286570Smav			hdr->b_l1hdr.b_buf = buf;
4325286570Smav			ASSERT0(hdr->b_l1hdr.b_datacnt);
4326286570Smav			hdr->b_l1hdr.b_datacnt = 1;
4327219089Spjd			arc_get_data_buf(buf);
4328219089Spjd			arc_access(hdr, hash_lock);
4329168404Spjd		}
4330168404Spjd
4331286570Smav		ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
4332219089Spjd
4333168404Spjd		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
4334168404Spjd		acb->acb_done = done;
4335168404Spjd		acb->acb_private = private;
4336168404Spjd
4337286570Smav		ASSERT(hdr->b_l1hdr.b_acb == NULL);
4338286570Smav		hdr->b_l1hdr.b_acb = acb;
4339275811Sdelphij		hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
4340168404Spjd
4341286570Smav		if (HDR_HAS_L2HDR(hdr) &&
4342286570Smav		    (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
4343286570Smav			devw = hdr->b_l2hdr.b_dev->l2ad_writing;
4344286570Smav			addr = hdr->b_l2hdr.b_daddr;
4345286570Smav			b_compress = HDR_GET_COMPRESS(hdr);
4346286570Smav			b_asize = hdr->b_l2hdr.b_asize;
4347185029Spjd			/*
4348185029Spjd			 * Lock out device removal.
4349185029Spjd			 */
4350185029Spjd			if (vdev_is_dead(vd) ||
4351185029Spjd			    !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
4352185029Spjd				vd = NULL;
4353185029Spjd		}
4354185029Spjd
4355268075Sdelphij		if (hash_lock != NULL)
4356268075Sdelphij			mutex_exit(hash_lock);
4357168404Spjd
4358251629Sdelphij		/*
4359251629Sdelphij		 * At this point, we have a level 1 cache miss.  Try again in
4360251629Sdelphij		 * L2ARC if possible.
4361251629Sdelphij		 */
4362168404Spjd		ASSERT3U(hdr->b_size, ==, size);
4363219089Spjd		DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
4364268123Sdelphij		    uint64_t, size, zbookmark_phys_t *, zb);
4365168404Spjd		ARCSTAT_BUMP(arcstat_misses);
4366286570Smav		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4367286570Smav		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
4368168404Spjd		    data, metadata, misses);
4369228392Spjd#ifdef _KERNEL
4370228392Spjd		curthread->td_ru.ru_inblock++;
4371228392Spjd#endif
4372168404Spjd
4373208373Smm		if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
4374185029Spjd			/*
4375185029Spjd			 * Read from the L2ARC if the following are true:
4376185029Spjd			 * 1. The L2ARC vdev was previously cached.
4377185029Spjd			 * 2. This buffer still has L2ARC metadata.
4378185029Spjd			 * 3. This buffer isn't currently writing to the L2ARC.
4379185029Spjd			 * 4. The L2ARC entry wasn't evicted, which may
4380185029Spjd			 *    also have invalidated the vdev.
4381208373Smm			 * 5. This isn't prefetch and l2arc_noprefetch is set.
4382185029Spjd			 */
4383286570Smav			if (HDR_HAS_L2HDR(hdr) &&
4384208373Smm			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
4385208373Smm			    !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
4386185029Spjd				l2arc_read_callback_t *cb;
4387185029Spjd
4388185029Spjd				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
4389185029Spjd				ARCSTAT_BUMP(arcstat_l2_hits);
4390185029Spjd
4391185029Spjd				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
4392185029Spjd				    KM_SLEEP);
4393185029Spjd				cb->l2rcb_buf = buf;
4394185029Spjd				cb->l2rcb_spa = spa;
4395185029Spjd				cb->l2rcb_bp = *bp;
4396185029Spjd				cb->l2rcb_zb = *zb;
4397185029Spjd				cb->l2rcb_flags = zio_flags;
4398258389Savg				cb->l2rcb_compress = b_compress;
4399185029Spjd
4400247187Smm				ASSERT(addr >= VDEV_LABEL_START_SIZE &&
4401247187Smm				    addr + size < vd->vdev_psize -
4402247187Smm				    VDEV_LABEL_END_SIZE);
4403247187Smm
4404185029Spjd				/*
4405185029Spjd				 * l2arc read.  The SCL_L2ARC lock will be
4406185029Spjd				 * released by l2arc_read_done().
4407251478Sdelphij				 * Issue a null zio if the underlying buffer
4408251478Sdelphij				 * was squashed to zero size by compression.
4409185029Spjd				 */
4410258389Savg				if (b_compress == ZIO_COMPRESS_EMPTY) {
4411251478Sdelphij					rzio = zio_null(pio, spa, vd,
4412251478Sdelphij					    l2arc_read_done, cb,
4413251478Sdelphij					    zio_flags | ZIO_FLAG_DONT_CACHE |
4414251478Sdelphij					    ZIO_FLAG_CANFAIL |
4415251478Sdelphij					    ZIO_FLAG_DONT_PROPAGATE |
4416251478Sdelphij					    ZIO_FLAG_DONT_RETRY);
4417251478Sdelphij				} else {
4418251478Sdelphij					rzio = zio_read_phys(pio, vd, addr,
4419258389Savg					    b_asize, buf->b_data,
4420258389Savg					    ZIO_CHECKSUM_OFF,
4421251478Sdelphij					    l2arc_read_done, cb, priority,
4422251478Sdelphij					    zio_flags | ZIO_FLAG_DONT_CACHE |
4423251478Sdelphij					    ZIO_FLAG_CANFAIL |
4424251478Sdelphij					    ZIO_FLAG_DONT_PROPAGATE |
4425251478Sdelphij					    ZIO_FLAG_DONT_RETRY, B_FALSE);
4426251478Sdelphij				}
4427185029Spjd				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
4428185029Spjd				    zio_t *, rzio);
4429258389Savg				ARCSTAT_INCR(arcstat_l2_read_bytes, b_asize);
4430185029Spjd
4431275811Sdelphij				if (*arc_flags & ARC_FLAG_NOWAIT) {
4432185029Spjd					zio_nowait(rzio);
4433185029Spjd					return (0);
4434185029Spjd				}
4435185029Spjd
4436275811Sdelphij				ASSERT(*arc_flags & ARC_FLAG_WAIT);
4437185029Spjd				if (zio_wait(rzio) == 0)
4438185029Spjd					return (0);
4439185029Spjd
4440185029Spjd				/* l2arc read error; goto zio_read() */
4441185029Spjd			} else {
4442185029Spjd				DTRACE_PROBE1(l2arc__miss,
4443185029Spjd				    arc_buf_hdr_t *, hdr);
4444185029Spjd				ARCSTAT_BUMP(arcstat_l2_misses);
4445185029Spjd				if (HDR_L2_WRITING(hdr))
4446185029Spjd					ARCSTAT_BUMP(arcstat_l2_rw_clash);
4447185029Spjd				spa_config_exit(spa, SCL_L2ARC, vd);
4448185029Spjd			}
4449208373Smm		} else {
4450208373Smm			if (vd != NULL)
4451208373Smm				spa_config_exit(spa, SCL_L2ARC, vd);
4452208373Smm			if (l2arc_ndev != 0) {
4453208373Smm				DTRACE_PROBE1(l2arc__miss,
4454208373Smm				    arc_buf_hdr_t *, hdr);
4455208373Smm				ARCSTAT_BUMP(arcstat_l2_misses);
4456208373Smm			}
4457185029Spjd		}
4458185029Spjd
4459168404Spjd		rzio = zio_read(pio, spa, bp, buf->b_data, size,
4460185029Spjd		    arc_read_done, buf, priority, zio_flags, zb);
4461168404Spjd
4462275811Sdelphij		if (*arc_flags & ARC_FLAG_WAIT)
4463168404Spjd			return (zio_wait(rzio));
4464168404Spjd
4465275811Sdelphij		ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
4466168404Spjd		zio_nowait(rzio);
4467168404Spjd	}
4468168404Spjd	return (0);
4469168404Spjd}
4470168404Spjd
4471168404Spjdvoid
4472168404Spjdarc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
4473168404Spjd{
4474168404Spjd	ASSERT(buf->b_hdr != NULL);
4475286570Smav	ASSERT(buf->b_hdr->b_l1hdr.b_state != arc_anon);
4476286570Smav	ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt) ||
4477286570Smav	    func == NULL);
4478219089Spjd	ASSERT(buf->b_efunc == NULL);
4479219089Spjd	ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
4480219089Spjd
4481168404Spjd	buf->b_efunc = func;
4482168404Spjd	buf->b_private = private;
4483168404Spjd}
4484168404Spjd
4485168404Spjd/*
4486251520Sdelphij * Notify the arc that a block was freed, and thus will never be used again.
4487251520Sdelphij */
4488251520Sdelphijvoid
4489251520Sdelphijarc_freed(spa_t *spa, const blkptr_t *bp)
4490251520Sdelphij{
4491251520Sdelphij	arc_buf_hdr_t *hdr;
4492251520Sdelphij	kmutex_t *hash_lock;
4493251520Sdelphij	uint64_t guid = spa_load_guid(spa);
4494251520Sdelphij
4495268075Sdelphij	ASSERT(!BP_IS_EMBEDDED(bp));
4496268075Sdelphij
4497268075Sdelphij	hdr = buf_hash_find(guid, bp, &hash_lock);
4498251520Sdelphij	if (hdr == NULL)
4499251520Sdelphij		return;
4500251520Sdelphij	if (HDR_BUF_AVAILABLE(hdr)) {
4501286570Smav		arc_buf_t *buf = hdr->b_l1hdr.b_buf;
4502251520Sdelphij		add_reference(hdr, hash_lock, FTAG);
4503275811Sdelphij		hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
4504251520Sdelphij		mutex_exit(hash_lock);
4505251520Sdelphij
4506251520Sdelphij		arc_release(buf, FTAG);
4507251520Sdelphij		(void) arc_buf_remove_ref(buf, FTAG);
4508251520Sdelphij	} else {
4509251520Sdelphij		mutex_exit(hash_lock);
4510251520Sdelphij	}
4511251520Sdelphij
4512251520Sdelphij}
4513251520Sdelphij
4514251520Sdelphij/*
4515268858Sdelphij * Clear the user eviction callback set by arc_set_callback(), first calling
4516268858Sdelphij * it if it exists.  Because the presence of a callback keeps an arc_buf cached
4517268858Sdelphij * clearing the callback may result in the arc_buf being destroyed.  However,
4518268858Sdelphij * it will not result in the *last* arc_buf being destroyed, hence the data
4519268858Sdelphij * will remain cached in the ARC. We make a copy of the arc buffer here so
4520268858Sdelphij * that we can process the callback without holding any locks.
4521268858Sdelphij *
4522268858Sdelphij * It's possible that the callback is already in the process of being cleared
4523268858Sdelphij * by another thread.  In this case we can not clear the callback.
4524268858Sdelphij *
4525268858Sdelphij * Returns B_TRUE if the callback was successfully called and cleared.
4526168404Spjd */
4527268858Sdelphijboolean_t
4528268858Sdelphijarc_clear_callback(arc_buf_t *buf)
4529168404Spjd{
4530168404Spjd	arc_buf_hdr_t *hdr;
4531168404Spjd	kmutex_t *hash_lock;
4532268858Sdelphij	arc_evict_func_t *efunc = buf->b_efunc;
4533268858Sdelphij	void *private = buf->b_private;
4534206796Spjd
4535219089Spjd	mutex_enter(&buf->b_evict_lock);
4536168404Spjd	hdr = buf->b_hdr;
4537168404Spjd	if (hdr == NULL) {
4538168404Spjd		/*
4539168404Spjd		 * We are in arc_do_user_evicts().
4540168404Spjd		 */
4541168404Spjd		ASSERT(buf->b_data == NULL);
4542219089Spjd		mutex_exit(&buf->b_evict_lock);
4543268858Sdelphij		return (B_FALSE);
4544185029Spjd	} else if (buf->b_data == NULL) {
4545185029Spjd		/*
4546185029Spjd		 * We are on the eviction list; process this buffer now
4547185029Spjd		 * but let arc_do_user_evicts() do the reaping.
4548185029Spjd		 */
4549185029Spjd		buf->b_efunc = NULL;
4550219089Spjd		mutex_exit(&buf->b_evict_lock);
4551268858Sdelphij		VERIFY0(efunc(private));
4552268858Sdelphij		return (B_TRUE);
4553168404Spjd	}
4554168404Spjd	hash_lock = HDR_LOCK(hdr);
4555168404Spjd	mutex_enter(hash_lock);
4556219089Spjd	hdr = buf->b_hdr;
4557219089Spjd	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4558168404Spjd
4559286570Smav	ASSERT3U(refcount_count(&hdr->b_l1hdr.b_refcnt), <,
4560286570Smav	    hdr->b_l1hdr.b_datacnt);
4561286570Smav	ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
4562286570Smav	    hdr->b_l1hdr.b_state == arc_mfu);
4563168404Spjd
4564268858Sdelphij	buf->b_efunc = NULL;
4565268858Sdelphij	buf->b_private = NULL;
4566168404Spjd
4567286570Smav	if (hdr->b_l1hdr.b_datacnt > 1) {
4568268858Sdelphij		mutex_exit(&buf->b_evict_lock);
4569286763Smav		arc_buf_destroy(buf, TRUE);
4570268858Sdelphij	} else {
4571286570Smav		ASSERT(buf == hdr->b_l1hdr.b_buf);
4572275811Sdelphij		hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
4573268858Sdelphij		mutex_exit(&buf->b_evict_lock);
4574268858Sdelphij	}
4575168404Spjd
4576168404Spjd	mutex_exit(hash_lock);
4577268858Sdelphij	VERIFY0(efunc(private));
4578268858Sdelphij	return (B_TRUE);
4579168404Spjd}
4580168404Spjd
4581168404Spjd/*
4582251629Sdelphij * Release this buffer from the cache, making it an anonymous buffer.  This
4583251629Sdelphij * must be done after a read and prior to modifying the buffer contents.
4584168404Spjd * If the buffer has more than one reference, we must make
4585185029Spjd * a new hdr for the buffer.
4586168404Spjd */
4587168404Spjdvoid
4588168404Spjdarc_release(arc_buf_t *buf, void *tag)
4589168404Spjd{
4590286570Smav	arc_buf_hdr_t *hdr = buf->b_hdr;
4591168404Spjd
4592286763Smav	ASSERT(HDR_HAS_L1HDR(hdr));
4593286763Smav
4594219089Spjd	/*
4595219089Spjd	 * It would be nice to assert that if it's DMU metadata (level >
4596219089Spjd	 * 0 || it's the dnode file), then it must be syncing context.
4597219089Spjd	 * But we don't know that information at this level.
4598219089Spjd	 */
4599219089Spjd
4600219089Spjd	mutex_enter(&buf->b_evict_lock);
4601286570Smav	/*
4602286570Smav	 * We don't grab the hash lock prior to this check, because if
4603286570Smav	 * the buffer's header is in the arc_anon state, it won't be
4604286570Smav	 * linked into the hash table.
4605286570Smav	 */
4606286570Smav	if (hdr->b_l1hdr.b_state == arc_anon) {
4607286570Smav		mutex_exit(&buf->b_evict_lock);
4608286570Smav		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4609286570Smav		ASSERT(!HDR_IN_HASH_TABLE(hdr));
4610286570Smav		ASSERT(!HDR_HAS_L2HDR(hdr));
4611286570Smav		ASSERT(BUF_EMPTY(hdr));
4612286570Smav		ASSERT3U(hdr->b_l1hdr.b_datacnt, ==, 1);
4613286570Smav		ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
4614286570Smav		ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
4615185029Spjd
4616286570Smav		ASSERT3P(buf->b_efunc, ==, NULL);
4617286570Smav		ASSERT3P(buf->b_private, ==, NULL);
4618168404Spjd
4619286570Smav		hdr->b_l1hdr.b_arc_access = 0;
4620286570Smav		arc_buf_thaw(buf);
4621286570Smav
4622286570Smav		return;
4623168404Spjd	}
4624168404Spjd
4625286570Smav	kmutex_t *hash_lock = HDR_LOCK(hdr);
4626286570Smav	mutex_enter(hash_lock);
4627286570Smav
4628286570Smav	/*
4629286570Smav	 * This assignment is only valid as long as the hash_lock is
4630286570Smav	 * held, we must be careful not to reference state or the
4631286570Smav	 * b_state field after dropping the lock.
4632286570Smav	 */
4633286570Smav	arc_state_t *state = hdr->b_l1hdr.b_state;
4634286570Smav	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4635286570Smav	ASSERT3P(state, !=, arc_anon);
4636286570Smav
4637286570Smav	/* this buffer is not on any list */
4638286570Smav	ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) > 0);
4639286570Smav
4640286570Smav	if (HDR_HAS_L2HDR(hdr)) {
4641286570Smav		mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
4642286570Smav
4643286570Smav		/*
4644286598Smav		 * We have to recheck this conditional again now that
4645286598Smav		 * we're holding the l2ad_mtx to prevent a race with
4646286598Smav		 * another thread which might be concurrently calling
4647286598Smav		 * l2arc_evict(). In that case, l2arc_evict() might have
4648286598Smav		 * destroyed the header's L2 portion as we were waiting
4649286598Smav		 * to acquire the l2ad_mtx.
4650286570Smav		 */
4651286598Smav		if (HDR_HAS_L2HDR(hdr)) {
4652286647Smav			if (hdr->b_l2hdr.b_daddr != L2ARC_ADDR_UNSET)
4653286647Smav				trim_map_free(hdr->b_l2hdr.b_dev->l2ad_vdev,
4654286647Smav				    hdr->b_l2hdr.b_daddr,
4655286647Smav				    hdr->b_l2hdr.b_asize, 0);
4656286598Smav			arc_hdr_l2hdr_destroy(hdr);
4657286598Smav		}
4658286570Smav
4659286570Smav		mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
4660185029Spjd	}
4661185029Spjd
4662168404Spjd	/*
4663168404Spjd	 * Do we have more than one buf?
4664168404Spjd	 */
4665286570Smav	if (hdr->b_l1hdr.b_datacnt > 1) {
4666168404Spjd		arc_buf_hdr_t *nhdr;
4667168404Spjd		arc_buf_t **bufp;
4668168404Spjd		uint64_t blksz = hdr->b_size;
4669209962Smm		uint64_t spa = hdr->b_spa;
4670286570Smav		arc_buf_contents_t type = arc_buf_type(hdr);
4671185029Spjd		uint32_t flags = hdr->b_flags;
4672168404Spjd
4673286570Smav		ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
4674168404Spjd		/*
4675219089Spjd		 * Pull the data off of this hdr and attach it to
4676219089Spjd		 * a new anonymous hdr.
4677168404Spjd		 */
4678168404Spjd		(void) remove_reference(hdr, hash_lock, tag);
4679286570Smav		bufp = &hdr->b_l1hdr.b_buf;
4680168404Spjd		while (*bufp != buf)
4681168404Spjd			bufp = &(*bufp)->b_next;
4682219089Spjd		*bufp = buf->b_next;
4683168404Spjd		buf->b_next = NULL;
4684168404Spjd
4685286570Smav		ASSERT3P(state, !=, arc_l2c_only);
4686286570Smav		ASSERT3U(state->arcs_size, >=, hdr->b_size);
4687286570Smav		atomic_add_64(&state->arcs_size, -hdr->b_size);
4688286570Smav		if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
4689286570Smav			ASSERT3P(state, !=, arc_l2c_only);
4690286570Smav			uint64_t *size = &state->arcs_lsize[type];
4691185029Spjd			ASSERT3U(*size, >=, hdr->b_size);
4692185029Spjd			atomic_add_64(size, -hdr->b_size);
4693168404Spjd		}
4694242845Sdelphij
4695242845Sdelphij		/*
4696242845Sdelphij		 * We're releasing a duplicate user data buffer, update
4697242845Sdelphij		 * our statistics accordingly.
4698242845Sdelphij		 */
4699286570Smav		if (HDR_ISTYPE_DATA(hdr)) {
4700242845Sdelphij			ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
4701242845Sdelphij			ARCSTAT_INCR(arcstat_duplicate_buffers_size,
4702242845Sdelphij			    -hdr->b_size);
4703242845Sdelphij		}
4704286570Smav		hdr->b_l1hdr.b_datacnt -= 1;
4705168404Spjd		arc_cksum_verify(buf);
4706240133Smm#ifdef illumos
4707240133Smm		arc_buf_unwatch(buf);
4708277300Ssmh#endif
4709168404Spjd
4710168404Spjd		mutex_exit(hash_lock);
4711168404Spjd
4712286570Smav		nhdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
4713168404Spjd		nhdr->b_size = blksz;
4714168404Spjd		nhdr->b_spa = spa;
4715286570Smav
4716275811Sdelphij		nhdr->b_flags = flags & ARC_FLAG_L2_WRITING;
4717286570Smav		nhdr->b_flags |= arc_bufc_to_flags(type);
4718286570Smav		nhdr->b_flags |= ARC_FLAG_HAS_L1HDR;
4719286570Smav
4720286570Smav		nhdr->b_l1hdr.b_buf = buf;
4721286570Smav		nhdr->b_l1hdr.b_datacnt = 1;
4722286570Smav		nhdr->b_l1hdr.b_state = arc_anon;
4723286570Smav		nhdr->b_l1hdr.b_arc_access = 0;
4724286763Smav		nhdr->b_l1hdr.b_tmp_cdata = NULL;
4725168404Spjd		nhdr->b_freeze_cksum = NULL;
4726286570Smav
4727286570Smav		(void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
4728168404Spjd		buf->b_hdr = nhdr;
4729219089Spjd		mutex_exit(&buf->b_evict_lock);
4730168404Spjd		atomic_add_64(&arc_anon->arcs_size, blksz);
4731168404Spjd	} else {
4732219089Spjd		mutex_exit(&buf->b_evict_lock);
4733286570Smav		ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
4734286763Smav		/* protected by hash lock, or hdr is on arc_anon */
4735286763Smav		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
4736168404Spjd		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4737286570Smav		arc_change_state(arc_anon, hdr, hash_lock);
4738286570Smav		hdr->b_l1hdr.b_arc_access = 0;
4739286570Smav		mutex_exit(hash_lock);
4740185029Spjd
4741219089Spjd		buf_discard_identity(hdr);
4742168404Spjd		arc_buf_thaw(buf);
4743168404Spjd	}
4744168404Spjd	buf->b_efunc = NULL;
4745168404Spjd	buf->b_private = NULL;
4746168404Spjd}
4747168404Spjd
4748168404Spjdint
4749168404Spjdarc_released(arc_buf_t *buf)
4750168404Spjd{
4751185029Spjd	int released;
4752185029Spjd
4753219089Spjd	mutex_enter(&buf->b_evict_lock);
4754286570Smav	released = (buf->b_data != NULL &&
4755286570Smav	    buf->b_hdr->b_l1hdr.b_state == arc_anon);
4756219089Spjd	mutex_exit(&buf->b_evict_lock);
4757185029Spjd	return (released);
4758168404Spjd}
4759168404Spjd
4760168404Spjd#ifdef ZFS_DEBUG
4761168404Spjdint
4762168404Spjdarc_referenced(arc_buf_t *buf)
4763168404Spjd{
4764185029Spjd	int referenced;
4765185029Spjd
4766219089Spjd	mutex_enter(&buf->b_evict_lock);
4767286570Smav	referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
4768219089Spjd	mutex_exit(&buf->b_evict_lock);
4769185029Spjd	return (referenced);
4770168404Spjd}
4771168404Spjd#endif
4772168404Spjd
4773168404Spjdstatic void
4774168404Spjdarc_write_ready(zio_t *zio)
4775168404Spjd{
4776168404Spjd	arc_write_callback_t *callback = zio->io_private;
4777168404Spjd	arc_buf_t *buf = callback->awcb_buf;
4778185029Spjd	arc_buf_hdr_t *hdr = buf->b_hdr;
4779168404Spjd
4780286570Smav	ASSERT(HDR_HAS_L1HDR(hdr));
4781286570Smav	ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
4782286570Smav	ASSERT(hdr->b_l1hdr.b_datacnt > 0);
4783185029Spjd	callback->awcb_ready(zio, buf, callback->awcb_private);
4784185029Spjd
4785185029Spjd	/*
4786185029Spjd	 * If the IO is already in progress, then this is a re-write
4787185029Spjd	 * attempt, so we need to thaw and re-compute the cksum.
4788185029Spjd	 * It is the responsibility of the callback to handle the
4789185029Spjd	 * accounting for any re-write attempt.
4790185029Spjd	 */
4791185029Spjd	if (HDR_IO_IN_PROGRESS(hdr)) {
4792286570Smav		mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
4793185029Spjd		if (hdr->b_freeze_cksum != NULL) {
4794185029Spjd			kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
4795185029Spjd			hdr->b_freeze_cksum = NULL;
4796185029Spjd		}
4797286570Smav		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
4798168404Spjd	}
4799185029Spjd	arc_cksum_compute(buf, B_FALSE);
4800275811Sdelphij	hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
4801168404Spjd}
4802168404Spjd
4803258632Savg/*
4804258632Savg * The SPA calls this callback for each physical write that happens on behalf
4805258632Savg * of a logical write.  See the comment in dbuf_write_physdone() for details.
4806258632Savg */
4807168404Spjdstatic void
4808258632Savgarc_write_physdone(zio_t *zio)
4809258632Savg{
4810258632Savg	arc_write_callback_t *cb = zio->io_private;
4811258632Savg	if (cb->awcb_physdone != NULL)
4812258632Savg		cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
4813258632Savg}
4814258632Savg
4815258632Savgstatic void
4816168404Spjdarc_write_done(zio_t *zio)
4817168404Spjd{
4818168404Spjd	arc_write_callback_t *callback = zio->io_private;
4819168404Spjd	arc_buf_t *buf = callback->awcb_buf;
4820168404Spjd	arc_buf_hdr_t *hdr = buf->b_hdr;
4821168404Spjd
4822286570Smav	ASSERT(hdr->b_l1hdr.b_acb == NULL);
4823168404Spjd
4824219089Spjd	if (zio->io_error == 0) {
4825268075Sdelphij		if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
4826260150Sdelphij			buf_discard_identity(hdr);
4827260150Sdelphij		} else {
4828260150Sdelphij			hdr->b_dva = *BP_IDENTITY(zio->io_bp);
4829260150Sdelphij			hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
4830260150Sdelphij		}
4831219089Spjd	} else {
4832219089Spjd		ASSERT(BUF_EMPTY(hdr));
4833219089Spjd	}
4834219089Spjd
4835168404Spjd	/*
4836268075Sdelphij	 * If the block to be written was all-zero or compressed enough to be
4837268075Sdelphij	 * embedded in the BP, no write was performed so there will be no
4838268075Sdelphij	 * dva/birth/checksum.  The buffer must therefore remain anonymous
4839268075Sdelphij	 * (and uncached).
4840168404Spjd	 */
4841168404Spjd	if (!BUF_EMPTY(hdr)) {
4842168404Spjd		arc_buf_hdr_t *exists;
4843168404Spjd		kmutex_t *hash_lock;
4844168404Spjd
4845219089Spjd		ASSERT(zio->io_error == 0);
4846219089Spjd
4847168404Spjd		arc_cksum_verify(buf);
4848168404Spjd
4849168404Spjd		exists = buf_hash_insert(hdr, &hash_lock);
4850286570Smav		if (exists != NULL) {
4851168404Spjd			/*
4852168404Spjd			 * This can only happen if we overwrite for
4853168404Spjd			 * sync-to-convergence, because we remove
4854168404Spjd			 * buffers from the hash table when we arc_free().
4855168404Spjd			 */
4856219089Spjd			if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
4857219089Spjd				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
4858219089Spjd					panic("bad overwrite, hdr=%p exists=%p",
4859219089Spjd					    (void *)hdr, (void *)exists);
4860286570Smav				ASSERT(refcount_is_zero(
4861286570Smav				    &exists->b_l1hdr.b_refcnt));
4862219089Spjd				arc_change_state(arc_anon, exists, hash_lock);
4863219089Spjd				mutex_exit(hash_lock);
4864219089Spjd				arc_hdr_destroy(exists);
4865219089Spjd				exists = buf_hash_insert(hdr, &hash_lock);
4866219089Spjd				ASSERT3P(exists, ==, NULL);
4867243524Smm			} else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
4868243524Smm				/* nopwrite */
4869243524Smm				ASSERT(zio->io_prop.zp_nopwrite);
4870243524Smm				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
4871243524Smm					panic("bad nopwrite, hdr=%p exists=%p",
4872243524Smm					    (void *)hdr, (void *)exists);
4873219089Spjd			} else {
4874219089Spjd				/* Dedup */
4875286570Smav				ASSERT(hdr->b_l1hdr.b_datacnt == 1);
4876286570Smav				ASSERT(hdr->b_l1hdr.b_state == arc_anon);
4877219089Spjd				ASSERT(BP_GET_DEDUP(zio->io_bp));
4878219089Spjd				ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
4879219089Spjd			}
4880168404Spjd		}
4881275811Sdelphij		hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
4882185029Spjd		/* if it's not anon, we are doing a scrub */
4883286570Smav		if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
4884185029Spjd			arc_access(hdr, hash_lock);
4885168404Spjd		mutex_exit(hash_lock);
4886168404Spjd	} else {
4887275811Sdelphij		hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
4888168404Spjd	}
4889168404Spjd
4890286570Smav	ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4891219089Spjd	callback->awcb_done(zio, buf, callback->awcb_private);
4892168404Spjd
4893168404Spjd	kmem_free(callback, sizeof (arc_write_callback_t));
4894168404Spjd}
4895168404Spjd
4896168404Spjdzio_t *
4897219089Spjdarc_write(zio_t *pio, spa_t *spa, uint64_t txg,
4898251478Sdelphij    blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
4899258632Savg    const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *physdone,
4900258632Savg    arc_done_func_t *done, void *private, zio_priority_t priority,
4901268123Sdelphij    int zio_flags, const zbookmark_phys_t *zb)
4902168404Spjd{
4903168404Spjd	arc_buf_hdr_t *hdr = buf->b_hdr;
4904168404Spjd	arc_write_callback_t *callback;
4905185029Spjd	zio_t *zio;
4906168404Spjd
4907185029Spjd	ASSERT(ready != NULL);
4908219089Spjd	ASSERT(done != NULL);
4909168404Spjd	ASSERT(!HDR_IO_ERROR(hdr));
4910286570Smav	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4911286570Smav	ASSERT(hdr->b_l1hdr.b_acb == NULL);
4912286570Smav	ASSERT(hdr->b_l1hdr.b_datacnt > 0);
4913185029Spjd	if (l2arc)
4914275811Sdelphij		hdr->b_flags |= ARC_FLAG_L2CACHE;
4915251478Sdelphij	if (l2arc_compress)
4916275811Sdelphij		hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4917168404Spjd	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
4918168404Spjd	callback->awcb_ready = ready;
4919258632Savg	callback->awcb_physdone = physdone;
4920168404Spjd	callback->awcb_done = done;
4921168404Spjd	callback->awcb_private = private;
4922168404Spjd	callback->awcb_buf = buf;
4923168404Spjd
4924219089Spjd	zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
4925258632Savg	    arc_write_ready, arc_write_physdone, arc_write_done, callback,
4926258632Savg	    priority, zio_flags, zb);
4927185029Spjd
4928168404Spjd	return (zio);
4929168404Spjd}
4930168404Spjd
4931185029Spjdstatic int
4932258632Savgarc_memory_throttle(uint64_t reserve, uint64_t txg)
4933185029Spjd{
4934185029Spjd#ifdef _KERNEL
4935272483Ssmh	uint64_t available_memory = ptob(freemem);
4936185029Spjd	static uint64_t page_load = 0;
4937185029Spjd	static uint64_t last_txg = 0;
4938185029Spjd
4939272483Ssmh#if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
4940185029Spjd	available_memory =
4941272483Ssmh	    MIN(available_memory, ptob(vmem_size(heap_arena, VMEM_FREE)));
4942185029Spjd#endif
4943258632Savg
4944272483Ssmh	if (freemem > (uint64_t)physmem * arc_lotsfree_percent / 100)
4945185029Spjd		return (0);
4946185029Spjd
4947185029Spjd	if (txg > last_txg) {
4948185029Spjd		last_txg = txg;
4949185029Spjd		page_load = 0;
4950185029Spjd	}
4951185029Spjd	/*
4952185029Spjd	 * If we are in pageout, we know that memory is already tight,
4953185029Spjd	 * the arc is already going to be evicting, so we just want to
4954185029Spjd	 * continue to let page writes occur as quickly as possible.
4955185029Spjd	 */
4956185029Spjd	if (curproc == pageproc) {
4957272483Ssmh		if (page_load > MAX(ptob(minfree), available_memory) / 4)
4958249195Smm			return (SET_ERROR(ERESTART));
4959185029Spjd		/* Note: reserve is inflated, so we deflate */
4960185029Spjd		page_load += reserve / 8;
4961185029Spjd		return (0);
4962185029Spjd	} else if (page_load > 0 && arc_reclaim_needed()) {
4963185029Spjd		/* memory is low, delay before restarting */
4964185029Spjd		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
4965249195Smm		return (SET_ERROR(EAGAIN));
4966185029Spjd	}
4967185029Spjd	page_load = 0;
4968185029Spjd#endif
4969185029Spjd	return (0);
4970185029Spjd}
4971185029Spjd
4972168404Spjdvoid
4973185029Spjdarc_tempreserve_clear(uint64_t reserve)
4974168404Spjd{
4975185029Spjd	atomic_add_64(&arc_tempreserve, -reserve);
4976168404Spjd	ASSERT((int64_t)arc_tempreserve >= 0);
4977168404Spjd}
4978168404Spjd
4979168404Spjdint
4980185029Spjdarc_tempreserve_space(uint64_t reserve, uint64_t txg)
4981168404Spjd{
4982185029Spjd	int error;
4983209962Smm	uint64_t anon_size;
4984185029Spjd
4985272483Ssmh	if (reserve > arc_c/4 && !arc_no_grow) {
4986185029Spjd		arc_c = MIN(arc_c_max, reserve * 4);
4987272483Ssmh		DTRACE_PROBE1(arc__set_reserve, uint64_t, arc_c);
4988272483Ssmh	}
4989185029Spjd	if (reserve > arc_c)
4990249195Smm		return (SET_ERROR(ENOMEM));
4991168404Spjd
4992168404Spjd	/*
4993209962Smm	 * Don't count loaned bufs as in flight dirty data to prevent long
4994209962Smm	 * network delays from blocking transactions that are ready to be
4995209962Smm	 * assigned to a txg.
4996209962Smm	 */
4997209962Smm	anon_size = MAX((int64_t)(arc_anon->arcs_size - arc_loaned_bytes), 0);
4998209962Smm
4999209962Smm	/*
5000185029Spjd	 * Writes will, almost always, require additional memory allocations
5001251631Sdelphij	 * in order to compress/encrypt/etc the data.  We therefore need to
5002185029Spjd	 * make sure that there is sufficient available memory for this.
5003185029Spjd	 */
5004258632Savg	error = arc_memory_throttle(reserve, txg);
5005258632Savg	if (error != 0)
5006185029Spjd		return (error);
5007185029Spjd
5008185029Spjd	/*
5009168404Spjd	 * Throttle writes when the amount of dirty data in the cache
5010168404Spjd	 * gets too large.  We try to keep the cache less than half full
5011168404Spjd	 * of dirty blocks so that our sync times don't grow too large.
5012168404Spjd	 * Note: if two requests come in concurrently, we might let them
5013168404Spjd	 * both succeed, when one of them should fail.  Not a huge deal.
5014168404Spjd	 */
5015209962Smm
5016209962Smm	if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
5017209962Smm	    anon_size > arc_c / 4) {
5018185029Spjd		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
5019185029Spjd		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
5020185029Spjd		    arc_tempreserve>>10,
5021185029Spjd		    arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
5022185029Spjd		    arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
5023185029Spjd		    reserve>>10, arc_c>>10);
5024249195Smm		return (SET_ERROR(ERESTART));
5025168404Spjd	}
5026185029Spjd	atomic_add_64(&arc_tempreserve, reserve);
5027168404Spjd	return (0);
5028168404Spjd}
5029168404Spjd
5030286626Smavstatic void
5031286626Smavarc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
5032286626Smav    kstat_named_t *evict_data, kstat_named_t *evict_metadata)
5033286626Smav{
5034286626Smav	size->value.ui64 = state->arcs_size;
5035286626Smav	evict_data->value.ui64 = state->arcs_lsize[ARC_BUFC_DATA];
5036286626Smav	evict_metadata->value.ui64 = state->arcs_lsize[ARC_BUFC_METADATA];
5037286626Smav}
5038286626Smav
5039286626Smavstatic int
5040286626Smavarc_kstat_update(kstat_t *ksp, int rw)
5041286626Smav{
5042286626Smav	arc_stats_t *as = ksp->ks_data;
5043286626Smav
5044286626Smav	if (rw == KSTAT_WRITE) {
5045286626Smav		return (EACCES);
5046286626Smav	} else {
5047286626Smav		arc_kstat_update_state(arc_anon,
5048286626Smav		    &as->arcstat_anon_size,
5049286626Smav		    &as->arcstat_anon_evictable_data,
5050286626Smav		    &as->arcstat_anon_evictable_metadata);
5051286626Smav		arc_kstat_update_state(arc_mru,
5052286626Smav		    &as->arcstat_mru_size,
5053286626Smav		    &as->arcstat_mru_evictable_data,
5054286626Smav		    &as->arcstat_mru_evictable_metadata);
5055286626Smav		arc_kstat_update_state(arc_mru_ghost,
5056286626Smav		    &as->arcstat_mru_ghost_size,
5057286626Smav		    &as->arcstat_mru_ghost_evictable_data,
5058286626Smav		    &as->arcstat_mru_ghost_evictable_metadata);
5059286626Smav		arc_kstat_update_state(arc_mfu,
5060286626Smav		    &as->arcstat_mfu_size,
5061286626Smav		    &as->arcstat_mfu_evictable_data,
5062286626Smav		    &as->arcstat_mfu_evictable_metadata);
5063286626Smav		arc_kstat_update_state(arc_mfu_ghost,
5064286626Smav		    &as->arcstat_mfu_ghost_size,
5065286626Smav		    &as->arcstat_mfu_ghost_evictable_data,
5066286626Smav		    &as->arcstat_mfu_ghost_evictable_metadata);
5067286626Smav	}
5068286626Smav
5069286626Smav	return (0);
5070286626Smav}
5071286626Smav
5072286763Smav/*
5073286763Smav * This function *must* return indices evenly distributed between all
5074286763Smav * sublists of the multilist. This is needed due to how the ARC eviction
5075286763Smav * code is laid out; arc_evict_state() assumes ARC buffers are evenly
5076286763Smav * distributed between all sublists and uses this assumption when
5077286763Smav * deciding which sublist to evict from and how much to evict from it.
5078286763Smav */
5079286763Smavunsigned int
5080286763Smavarc_state_multilist_index_func(multilist_t *ml, void *obj)
5081286763Smav{
5082286763Smav	arc_buf_hdr_t *hdr = obj;
5083286763Smav
5084286763Smav	/*
5085286763Smav	 * We rely on b_dva to generate evenly distributed index
5086286763Smav	 * numbers using buf_hash below. So, as an added precaution,
5087286763Smav	 * let's make sure we never add empty buffers to the arc lists.
5088286763Smav	 */
5089286763Smav	ASSERT(!BUF_EMPTY(hdr));
5090286763Smav
5091286763Smav	/*
5092286763Smav	 * The assumption here, is the hash value for a given
5093286763Smav	 * arc_buf_hdr_t will remain constant throughout it's lifetime
5094286763Smav	 * (i.e. it's b_spa, b_dva, and b_birth fields don't change).
5095286763Smav	 * Thus, we don't need to store the header's sublist index
5096286763Smav	 * on insertion, as this index can be recalculated on removal.
5097286763Smav	 *
5098286763Smav	 * Also, the low order bits of the hash value are thought to be
5099286763Smav	 * distributed evenly. Otherwise, in the case that the multilist
5100286763Smav	 * has a power of two number of sublists, each sublists' usage
5101286763Smav	 * would not be evenly distributed.
5102286763Smav	 */
5103286763Smav	return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
5104286763Smav	    multilist_get_num_sublists(ml));
5105286763Smav}
5106286763Smav
5107168404Spjd#ifdef _KERNEL
5108168566Spjdstatic eventhandler_tag arc_event_lowmem = NULL;
5109168404Spjd
5110168404Spjdstatic void
5111168566Spjdarc_lowmem(void *arg __unused, int howto __unused)
5112168404Spjd{
5113168404Spjd
5114286763Smav	mutex_enter(&arc_reclaim_lock);
5115286625Smav	/* XXX: Memory deficit should be passed as argument. */
5116286625Smav	needfree = btoc(arc_c >> arc_shrink_shift);
5117272483Ssmh	DTRACE_PROBE(arc__needfree);
5118286763Smav	cv_signal(&arc_reclaim_thread_cv);
5119241773Savg
5120241773Savg	/*
5121241773Savg	 * It is unsafe to block here in arbitrary threads, because we can come
5122241773Savg	 * here from ARC itself and may hold ARC locks and thus risk a deadlock
5123241773Savg	 * with ARC reclaim thread.
5124241773Savg	 */
5125286623Smav	if (curproc == pageproc)
5126286763Smav		(void) cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
5127286763Smav	mutex_exit(&arc_reclaim_lock);
5128168404Spjd}
5129168404Spjd#endif
5130168404Spjd
5131168404Spjdvoid
5132168404Spjdarc_init(void)
5133168404Spjd{
5134219089Spjd	int i, prefetch_tunable_set = 0;
5135205231Skmacy
5136286763Smav	mutex_init(&arc_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
5137286763Smav	cv_init(&arc_reclaim_thread_cv, NULL, CV_DEFAULT, NULL);
5138286763Smav	cv_init(&arc_reclaim_waiters_cv, NULL, CV_DEFAULT, NULL);
5139168404Spjd
5140286763Smav	mutex_init(&arc_user_evicts_lock, NULL, MUTEX_DEFAULT, NULL);
5141286763Smav	cv_init(&arc_user_evicts_cv, NULL, CV_DEFAULT, NULL);
5142286763Smav
5143168404Spjd	/* Convert seconds to clock ticks */
5144168404Spjd	arc_min_prefetch_lifespan = 1 * hz;
5145168404Spjd
5146168404Spjd	/* Start out with 1/8 of all memory */
5147168566Spjd	arc_c = kmem_size() / 8;
5148219089Spjd
5149277300Ssmh#ifdef illumos
5150192360Skmacy#ifdef _KERNEL
5151192360Skmacy	/*
5152192360Skmacy	 * On architectures where the physical memory can be larger
5153192360Skmacy	 * than the addressable space (intel in 32-bit mode), we may
5154192360Skmacy	 * need to limit the cache to 1/8 of VM size.
5155192360Skmacy	 */
5156192360Skmacy	arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
5157192360Skmacy#endif
5158277300Ssmh#endif	/* illumos */
5159168566Spjd	/* set min cache to 1/32 of all memory, or 16MB, whichever is more */
5160280822Smav	arc_c_min = MAX(arc_c / 4, 16 << 20);
5161168566Spjd	/* set max to 1/2 of all memory, or all but 1GB, whichever is more */
5162280822Smav	if (arc_c * 8 >= 1 << 30)
5163280822Smav		arc_c_max = (arc_c * 8) - (1 << 30);
5164168404Spjd	else
5165168404Spjd		arc_c_max = arc_c_min;
5166175633Spjd	arc_c_max = MAX(arc_c * 5, arc_c_max);
5167219089Spjd
5168168481Spjd#ifdef _KERNEL
5169168404Spjd	/*
5170168404Spjd	 * Allow the tunables to override our calculations if they are
5171168566Spjd	 * reasonable (ie. over 16MB)
5172168404Spjd	 */
5173280822Smav	if (zfs_arc_max > 16 << 20 && zfs_arc_max < kmem_size())
5174168404Spjd		arc_c_max = zfs_arc_max;
5175280822Smav	if (zfs_arc_min > 16 << 20 && zfs_arc_min <= arc_c_max)
5176168404Spjd		arc_c_min = zfs_arc_min;
5177168481Spjd#endif
5178219089Spjd
5179168404Spjd	arc_c = arc_c_max;
5180168404Spjd	arc_p = (arc_c >> 1);
5181168404Spjd
5182185029Spjd	/* limit meta-data to 1/4 of the arc capacity */
5183185029Spjd	arc_meta_limit = arc_c_max / 4;
5184185029Spjd
5185185029Spjd	/* Allow the tunable to override if it is reasonable */
5186185029Spjd	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
5187185029Spjd		arc_meta_limit = zfs_arc_meta_limit;
5188185029Spjd
5189185029Spjd	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
5190185029Spjd		arc_c_min = arc_meta_limit / 2;
5191185029Spjd
5192275780Sdelphij	if (zfs_arc_meta_min > 0) {
5193275780Sdelphij		arc_meta_min = zfs_arc_meta_min;
5194275780Sdelphij	} else {
5195275780Sdelphij		arc_meta_min = arc_c_min / 2;
5196275780Sdelphij	}
5197275780Sdelphij
5198208373Smm	if (zfs_arc_grow_retry > 0)
5199208373Smm		arc_grow_retry = zfs_arc_grow_retry;
5200208373Smm
5201208373Smm	if (zfs_arc_shrink_shift > 0)
5202208373Smm		arc_shrink_shift = zfs_arc_shrink_shift;
5203208373Smm
5204286625Smav	/*
5205286625Smav	 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
5206286625Smav	 */
5207286625Smav	if (arc_no_grow_shift >= arc_shrink_shift)
5208286625Smav		arc_no_grow_shift = arc_shrink_shift - 1;
5209286625Smav
5210208373Smm	if (zfs_arc_p_min_shift > 0)
5211208373Smm		arc_p_min_shift = zfs_arc_p_min_shift;
5212208373Smm
5213286763Smav	if (zfs_arc_num_sublists_per_state < 1)
5214286763Smav		zfs_arc_num_sublists_per_state = MAX(max_ncpus, 1);
5215286763Smav
5216168404Spjd	/* if kmem_flags are set, lets try to use less memory */
5217168404Spjd	if (kmem_debugging())
5218168404Spjd		arc_c = arc_c / 2;
5219168404Spjd	if (arc_c < arc_c_min)
5220168404Spjd		arc_c = arc_c_min;
5221168404Spjd
5222168473Spjd	zfs_arc_min = arc_c_min;
5223168473Spjd	zfs_arc_max = arc_c_max;
5224168473Spjd
5225168404Spjd	arc_anon = &ARC_anon;
5226168404Spjd	arc_mru = &ARC_mru;
5227168404Spjd	arc_mru_ghost = &ARC_mru_ghost;
5228168404Spjd	arc_mfu = &ARC_mfu;
5229168404Spjd	arc_mfu_ghost = &ARC_mfu_ghost;
5230185029Spjd	arc_l2c_only = &ARC_l2c_only;
5231168404Spjd	arc_size = 0;
5232168404Spjd
5233286763Smav	multilist_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
5234286762Smav	    sizeof (arc_buf_hdr_t),
5235286763Smav	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5236286763Smav	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5237286763Smav	multilist_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
5238286762Smav	    sizeof (arc_buf_hdr_t),
5239286763Smav	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5240286763Smav	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5241286763Smav	multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
5242286762Smav	    sizeof (arc_buf_hdr_t),
5243286763Smav	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5244286763Smav	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5245286763Smav	multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
5246286762Smav	    sizeof (arc_buf_hdr_t),
5247286763Smav	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5248286763Smav	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5249286763Smav	multilist_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
5250286762Smav	    sizeof (arc_buf_hdr_t),
5251286763Smav	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5252286763Smav	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5253286763Smav	multilist_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
5254286762Smav	    sizeof (arc_buf_hdr_t),
5255286763Smav	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5256286763Smav	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5257286763Smav	multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
5258286762Smav	    sizeof (arc_buf_hdr_t),
5259286763Smav	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5260286763Smav	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5261286763Smav	multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
5262286762Smav	    sizeof (arc_buf_hdr_t),
5263286763Smav	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5264286763Smav	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5265286763Smav	multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
5266286762Smav	    sizeof (arc_buf_hdr_t),
5267286763Smav	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5268286763Smav	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5269286763Smav	multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
5270286762Smav	    sizeof (arc_buf_hdr_t),
5271286763Smav	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5272286763Smav	    zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5273168404Spjd
5274168404Spjd	buf_init();
5275168404Spjd
5276286763Smav	arc_reclaim_thread_exit = FALSE;
5277286763Smav	arc_user_evicts_thread_exit = FALSE;
5278168404Spjd	arc_eviction_list = NULL;
5279168404Spjd	bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
5280168404Spjd
5281168404Spjd	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
5282168404Spjd	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
5283168404Spjd
5284168404Spjd	if (arc_ksp != NULL) {
5285168404Spjd		arc_ksp->ks_data = &arc_stats;
5286286574Smav		arc_ksp->ks_update = arc_kstat_update;
5287168404Spjd		kstat_install(arc_ksp);
5288168404Spjd	}
5289168404Spjd
5290168404Spjd	(void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
5291168404Spjd	    TS_RUN, minclsyspri);
5292168404Spjd
5293168404Spjd#ifdef _KERNEL
5294168566Spjd	arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
5295168404Spjd	    EVENTHANDLER_PRI_FIRST);
5296168404Spjd#endif
5297168404Spjd
5298286763Smav	(void) thread_create(NULL, 0, arc_user_evicts_thread, NULL, 0, &p0,
5299286763Smav	    TS_RUN, minclsyspri);
5300286763Smav
5301168404Spjd	arc_dead = FALSE;
5302185029Spjd	arc_warm = B_FALSE;
5303168566Spjd
5304258632Savg	/*
5305258632Savg	 * Calculate maximum amount of dirty data per pool.
5306258632Savg	 *
5307258632Savg	 * If it has been set by /etc/system, take that.
5308258632Savg	 * Otherwise, use a percentage of physical memory defined by
5309258632Savg	 * zfs_dirty_data_max_percent (default 10%) with a cap at
5310258632Savg	 * zfs_dirty_data_max_max (default 4GB).
5311258632Savg	 */
5312258632Savg	if (zfs_dirty_data_max == 0) {
5313258632Savg		zfs_dirty_data_max = ptob(physmem) *
5314258632Savg		    zfs_dirty_data_max_percent / 100;
5315258632Savg		zfs_dirty_data_max = MIN(zfs_dirty_data_max,
5316258632Savg		    zfs_dirty_data_max_max);
5317258632Savg	}
5318185029Spjd
5319168566Spjd#ifdef _KERNEL
5320194043Skmacy	if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
5321193953Skmacy		prefetch_tunable_set = 1;
5322206796Spjd
5323193878Skmacy#ifdef __i386__
5324193953Skmacy	if (prefetch_tunable_set == 0) {
5325196863Strasz		printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
5326196863Strasz		    "-- to enable,\n");
5327196863Strasz		printf("            add \"vfs.zfs.prefetch_disable=0\" "
5328196863Strasz		    "to /boot/loader.conf.\n");
5329219089Spjd		zfs_prefetch_disable = 1;
5330193878Skmacy	}
5331206796Spjd#else
5332193878Skmacy	if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
5333193953Skmacy	    prefetch_tunable_set == 0) {
5334196863Strasz		printf("ZFS NOTICE: Prefetch is disabled by default if less "
5335196941Strasz		    "than 4GB of RAM is present;\n"
5336196863Strasz		    "            to enable, add \"vfs.zfs.prefetch_disable=0\" "
5337196863Strasz		    "to /boot/loader.conf.\n");
5338219089Spjd		zfs_prefetch_disable = 1;
5339193878Skmacy	}
5340206796Spjd#endif
5341175633Spjd	/* Warn about ZFS memory and address space requirements. */
5342168696Spjd	if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
5343168987Sbmah		printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
5344168987Sbmah		    "expect unstable behavior.\n");
5345175633Spjd	}
5346175633Spjd	if (kmem_size() < 512 * (1 << 20)) {
5347173419Spjd		printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
5348168987Sbmah		    "expect unstable behavior.\n");
5349185029Spjd		printf("             Consider tuning vm.kmem_size and "
5350173419Spjd		    "vm.kmem_size_max\n");
5351185029Spjd		printf("             in /boot/loader.conf.\n");
5352168566Spjd	}
5353168566Spjd#endif
5354168404Spjd}
5355168404Spjd
5356168404Spjdvoid
5357168404Spjdarc_fini(void)
5358168404Spjd{
5359286763Smav	mutex_enter(&arc_reclaim_lock);
5360286763Smav	arc_reclaim_thread_exit = TRUE;
5361286763Smav	/*
5362286763Smav	 * The reclaim thread will set arc_reclaim_thread_exit back to
5363286763Smav	 * FALSE when it is finished exiting; we're waiting for that.
5364286763Smav	 */
5365286763Smav	while (arc_reclaim_thread_exit) {
5366286763Smav		cv_signal(&arc_reclaim_thread_cv);
5367286763Smav		cv_wait(&arc_reclaim_thread_cv, &arc_reclaim_lock);
5368286763Smav	}
5369286763Smav	mutex_exit(&arc_reclaim_lock);
5370168404Spjd
5371286763Smav	mutex_enter(&arc_user_evicts_lock);
5372286763Smav	arc_user_evicts_thread_exit = TRUE;
5373286763Smav	/*
5374286763Smav	 * The user evicts thread will set arc_user_evicts_thread_exit
5375286763Smav	 * to FALSE when it is finished exiting; we're waiting for that.
5376286763Smav	 */
5377286763Smav	while (arc_user_evicts_thread_exit) {
5378286763Smav		cv_signal(&arc_user_evicts_cv);
5379286763Smav		cv_wait(&arc_user_evicts_cv, &arc_user_evicts_lock);
5380286763Smav	}
5381286763Smav	mutex_exit(&arc_user_evicts_lock);
5382168404Spjd
5383286763Smav	/* Use TRUE to ensure *all* buffers are evicted */
5384286763Smav	arc_flush(NULL, TRUE);
5385286763Smav
5386168404Spjd	arc_dead = TRUE;
5387168404Spjd
5388168404Spjd	if (arc_ksp != NULL) {
5389168404Spjd		kstat_delete(arc_ksp);
5390168404Spjd		arc_ksp = NULL;
5391168404Spjd	}
5392168404Spjd
5393286763Smav	mutex_destroy(&arc_reclaim_lock);
5394286763Smav	cv_destroy(&arc_reclaim_thread_cv);
5395286763Smav	cv_destroy(&arc_reclaim_waiters_cv);
5396168404Spjd
5397286763Smav	mutex_destroy(&arc_user_evicts_lock);
5398286763Smav	cv_destroy(&arc_user_evicts_cv);
5399168404Spjd
5400286763Smav	multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
5401286763Smav	multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
5402286763Smav	multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
5403286763Smav	multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
5404286763Smav	multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
5405286763Smav	multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
5406286763Smav	multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
5407286763Smav	multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
5408206796Spjd
5409168404Spjd	buf_fini();
5410168404Spjd
5411286570Smav	ASSERT0(arc_loaned_bytes);
5412209962Smm
5413168404Spjd#ifdef _KERNEL
5414168566Spjd	if (arc_event_lowmem != NULL)
5415168566Spjd		EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
5416168404Spjd#endif
5417168404Spjd}
5418185029Spjd
5419185029Spjd/*
5420185029Spjd * Level 2 ARC
5421185029Spjd *
5422185029Spjd * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
5423185029Spjd * It uses dedicated storage devices to hold cached data, which are populated
5424185029Spjd * using large infrequent writes.  The main role of this cache is to boost
5425185029Spjd * the performance of random read workloads.  The intended L2ARC devices
5426185029Spjd * include short-stroked disks, solid state disks, and other media with
5427185029Spjd * substantially faster read latency than disk.
5428185029Spjd *
5429185029Spjd *                 +-----------------------+
5430185029Spjd *                 |         ARC           |
5431185029Spjd *                 +-----------------------+
5432185029Spjd *                    |         ^     ^
5433185029Spjd *                    |         |     |
5434185029Spjd *      l2arc_feed_thread()    arc_read()
5435185029Spjd *                    |         |     |
5436185029Spjd *                    |  l2arc read   |
5437185029Spjd *                    V         |     |
5438185029Spjd *               +---------------+    |
5439185029Spjd *               |     L2ARC     |    |
5440185029Spjd *               +---------------+    |
5441185029Spjd *                   |    ^           |
5442185029Spjd *          l2arc_write() |           |
5443185029Spjd *                   |    |           |
5444185029Spjd *                   V    |           |
5445185029Spjd *                 +-------+      +-------+
5446185029Spjd *                 | vdev  |      | vdev  |
5447185029Spjd *                 | cache |      | cache |
5448185029Spjd *                 +-------+      +-------+
5449185029Spjd *                 +=========+     .-----.
5450185029Spjd *                 :  L2ARC  :    |-_____-|
5451185029Spjd *                 : devices :    | Disks |
5452185029Spjd *                 +=========+    `-_____-'
5453185029Spjd *
5454185029Spjd * Read requests are satisfied from the following sources, in order:
5455185029Spjd *
5456185029Spjd *	1) ARC
5457185029Spjd *	2) vdev cache of L2ARC devices
5458185029Spjd *	3) L2ARC devices
5459185029Spjd *	4) vdev cache of disks
5460185029Spjd *	5) disks
5461185029Spjd *
5462185029Spjd * Some L2ARC device types exhibit extremely slow write performance.
5463185029Spjd * To accommodate for this there are some significant differences between
5464185029Spjd * the L2ARC and traditional cache design:
5465185029Spjd *
5466185029Spjd * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
5467185029Spjd * the ARC behave as usual, freeing buffers and placing headers on ghost
5468185029Spjd * lists.  The ARC does not send buffers to the L2ARC during eviction as
5469185029Spjd * this would add inflated write latencies for all ARC memory pressure.
5470185029Spjd *
5471185029Spjd * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
5472185029Spjd * It does this by periodically scanning buffers from the eviction-end of
5473185029Spjd * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
5474251478Sdelphij * not already there. It scans until a headroom of buffers is satisfied,
5475251478Sdelphij * which itself is a buffer for ARC eviction. If a compressible buffer is
5476251478Sdelphij * found during scanning and selected for writing to an L2ARC device, we
5477251478Sdelphij * temporarily boost scanning headroom during the next scan cycle to make
5478251478Sdelphij * sure we adapt to compression effects (which might significantly reduce
5479251478Sdelphij * the data volume we write to L2ARC). The thread that does this is
5480185029Spjd * l2arc_feed_thread(), illustrated below; example sizes are included to
5481185029Spjd * provide a better sense of ratio than this diagram:
5482185029Spjd *
5483185029Spjd *	       head -->                        tail
5484185029Spjd *	        +---------------------+----------+
5485185029Spjd *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
5486185029Spjd *	        +---------------------+----------+   |   o L2ARC eligible
5487185029Spjd *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
5488185029Spjd *	        +---------------------+----------+   |
5489185029Spjd *	             15.9 Gbytes      ^ 32 Mbytes    |
5490185029Spjd *	                           headroom          |
5491185029Spjd *	                                      l2arc_feed_thread()
5492185029Spjd *	                                             |
5493185029Spjd *	                 l2arc write hand <--[oooo]--'
5494185029Spjd *	                         |           8 Mbyte
5495185029Spjd *	                         |          write max
5496185029Spjd *	                         V
5497185029Spjd *		  +==============================+
5498185029Spjd *	L2ARC dev |####|#|###|###|    |####| ... |
5499185029Spjd *	          +==============================+
5500185029Spjd *	                     32 Gbytes
5501185029Spjd *
5502185029Spjd * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
5503185029Spjd * evicted, then the L2ARC has cached a buffer much sooner than it probably
5504185029Spjd * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
5505185029Spjd * safe to say that this is an uncommon case, since buffers at the end of
5506185029Spjd * the ARC lists have moved there due to inactivity.
5507185029Spjd *
5508185029Spjd * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
5509185029Spjd * then the L2ARC simply misses copying some buffers.  This serves as a
5510185029Spjd * pressure valve to prevent heavy read workloads from both stalling the ARC
5511185029Spjd * with waits and clogging the L2ARC with writes.  This also helps prevent
5512185029Spjd * the potential for the L2ARC to churn if it attempts to cache content too
5513185029Spjd * quickly, such as during backups of the entire pool.
5514185029Spjd *
5515185029Spjd * 5. After system boot and before the ARC has filled main memory, there are
5516185029Spjd * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
5517185029Spjd * lists can remain mostly static.  Instead of searching from tail of these
5518185029Spjd * lists as pictured, the l2arc_feed_thread() will search from the list heads
5519185029Spjd * for eligible buffers, greatly increasing its chance of finding them.
5520185029Spjd *
5521185029Spjd * The L2ARC device write speed is also boosted during this time so that
5522185029Spjd * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
5523185029Spjd * there are no L2ARC reads, and no fear of degrading read performance
5524185029Spjd * through increased writes.
5525185029Spjd *
5526185029Spjd * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
5527185029Spjd * the vdev queue can aggregate them into larger and fewer writes.  Each
5528185029Spjd * device is written to in a rotor fashion, sweeping writes through
5529185029Spjd * available space then repeating.
5530185029Spjd *
5531185029Spjd * 7. The L2ARC does not store dirty content.  It never needs to flush
5532185029Spjd * write buffers back to disk based storage.
5533185029Spjd *
5534185029Spjd * 8. If an ARC buffer is written (and dirtied) which also exists in the
5535185029Spjd * L2ARC, the now stale L2ARC buffer is immediately dropped.
5536185029Spjd *
5537185029Spjd * The performance of the L2ARC can be tweaked by a number of tunables, which
5538185029Spjd * may be necessary for different workloads:
5539185029Spjd *
5540185029Spjd *	l2arc_write_max		max write bytes per interval
5541185029Spjd *	l2arc_write_boost	extra write bytes during device warmup
5542185029Spjd *	l2arc_noprefetch	skip caching prefetched buffers
5543185029Spjd *	l2arc_headroom		number of max device writes to precache
5544251478Sdelphij *	l2arc_headroom_boost	when we find compressed buffers during ARC
5545251478Sdelphij *				scanning, we multiply headroom by this
5546251478Sdelphij *				percentage factor for the next scan cycle,
5547251478Sdelphij *				since more compressed buffers are likely to
5548251478Sdelphij *				be present
5549185029Spjd *	l2arc_feed_secs		seconds between L2ARC writing
5550185029Spjd *
5551185029Spjd * Tunables may be removed or added as future performance improvements are
5552185029Spjd * integrated, and also may become zpool properties.
5553208373Smm *
5554208373Smm * There are three key functions that control how the L2ARC warms up:
5555208373Smm *
5556208373Smm *	l2arc_write_eligible()	check if a buffer is eligible to cache
5557208373Smm *	l2arc_write_size()	calculate how much to write
5558208373Smm *	l2arc_write_interval()	calculate sleep delay between writes
5559208373Smm *
5560208373Smm * These three functions determine what to write, how much, and how quickly
5561208373Smm * to send writes.
5562185029Spjd */
5563185029Spjd
5564208373Smmstatic boolean_t
5565275811Sdelphijl2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
5566208373Smm{
5567208373Smm	/*
5568208373Smm	 * A buffer is *not* eligible for the L2ARC if it:
5569208373Smm	 * 1. belongs to a different spa.
5570208373Smm	 * 2. is already cached on the L2ARC.
5571208373Smm	 * 3. has an I/O in progress (it may be an incomplete read).
5572208373Smm	 * 4. is flagged not eligible (zfs property).
5573208373Smm	 */
5574275811Sdelphij	if (hdr->b_spa != spa_guid) {
5575208373Smm		ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
5576208373Smm		return (B_FALSE);
5577208373Smm	}
5578286570Smav	if (HDR_HAS_L2HDR(hdr)) {
5579208373Smm		ARCSTAT_BUMP(arcstat_l2_write_in_l2);
5580208373Smm		return (B_FALSE);
5581208373Smm	}
5582275811Sdelphij	if (HDR_IO_IN_PROGRESS(hdr)) {
5583208373Smm		ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
5584208373Smm		return (B_FALSE);
5585208373Smm	}
5586275811Sdelphij	if (!HDR_L2CACHE(hdr)) {
5587208373Smm		ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
5588208373Smm		return (B_FALSE);
5589208373Smm	}
5590208373Smm
5591208373Smm	return (B_TRUE);
5592208373Smm}
5593208373Smm
5594208373Smmstatic uint64_t
5595251478Sdelphijl2arc_write_size(void)
5596208373Smm{
5597208373Smm	uint64_t size;
5598208373Smm
5599251478Sdelphij	/*
5600251478Sdelphij	 * Make sure our globals have meaningful values in case the user
5601251478Sdelphij	 * altered them.
5602251478Sdelphij	 */
5603251478Sdelphij	size = l2arc_write_max;
5604251478Sdelphij	if (size == 0) {
5605251478Sdelphij		cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
5606251478Sdelphij		    "be greater than zero, resetting it to the default (%d)",
5607251478Sdelphij		    L2ARC_WRITE_SIZE);
5608251478Sdelphij		size = l2arc_write_max = L2ARC_WRITE_SIZE;
5609251478Sdelphij	}
5610208373Smm
5611208373Smm	if (arc_warm == B_FALSE)
5612251478Sdelphij		size += l2arc_write_boost;
5613208373Smm
5614208373Smm	return (size);
5615208373Smm
5616208373Smm}
5617208373Smm
5618208373Smmstatic clock_t
5619208373Smml2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
5620208373Smm{
5621219089Spjd	clock_t interval, next, now;
5622208373Smm
5623208373Smm	/*
5624208373Smm	 * If the ARC lists are busy, increase our write rate; if the
5625208373Smm	 * lists are stale, idle back.  This is achieved by checking
5626208373Smm	 * how much we previously wrote - if it was more than half of
5627208373Smm	 * what we wanted, schedule the next write much sooner.
5628208373Smm	 */
5629208373Smm	if (l2arc_feed_again && wrote > (wanted / 2))
5630208373Smm		interval = (hz * l2arc_feed_min_ms) / 1000;
5631208373Smm	else
5632208373Smm		interval = hz * l2arc_feed_secs;
5633208373Smm
5634219089Spjd	now = ddi_get_lbolt();
5635219089Spjd	next = MAX(now, MIN(now + interval, began + interval));
5636208373Smm
5637208373Smm	return (next);
5638208373Smm}
5639208373Smm
5640185029Spjd/*
5641185029Spjd * Cycle through L2ARC devices.  This is how L2ARC load balances.
5642185029Spjd * If a device is returned, this also returns holding the spa config lock.
5643185029Spjd */
5644185029Spjdstatic l2arc_dev_t *
5645185029Spjdl2arc_dev_get_next(void)
5646185029Spjd{
5647185029Spjd	l2arc_dev_t *first, *next = NULL;
5648185029Spjd
5649185029Spjd	/*
5650185029Spjd	 * Lock out the removal of spas (spa_namespace_lock), then removal
5651185029Spjd	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
5652185029Spjd	 * both locks will be dropped and a spa config lock held instead.
5653185029Spjd	 */
5654185029Spjd	mutex_enter(&spa_namespace_lock);
5655185029Spjd	mutex_enter(&l2arc_dev_mtx);
5656185029Spjd
5657185029Spjd	/* if there are no vdevs, there is nothing to do */
5658185029Spjd	if (l2arc_ndev == 0)
5659185029Spjd		goto out;
5660185029Spjd
5661185029Spjd	first = NULL;
5662185029Spjd	next = l2arc_dev_last;
5663185029Spjd	do {
5664185029Spjd		/* loop around the list looking for a non-faulted vdev */
5665185029Spjd		if (next == NULL) {
5666185029Spjd			next = list_head(l2arc_dev_list);
5667185029Spjd		} else {
5668185029Spjd			next = list_next(l2arc_dev_list, next);
5669185029Spjd			if (next == NULL)
5670185029Spjd				next = list_head(l2arc_dev_list);
5671185029Spjd		}
5672185029Spjd
5673185029Spjd		/* if we have come back to the start, bail out */
5674185029Spjd		if (first == NULL)
5675185029Spjd			first = next;
5676185029Spjd		else if (next == first)
5677185029Spjd			break;
5678185029Spjd
5679185029Spjd	} while (vdev_is_dead(next->l2ad_vdev));
5680185029Spjd
5681185029Spjd	/* if we were unable to find any usable vdevs, return NULL */
5682185029Spjd	if (vdev_is_dead(next->l2ad_vdev))
5683185029Spjd		next = NULL;
5684185029Spjd
5685185029Spjd	l2arc_dev_last = next;
5686185029Spjd
5687185029Spjdout:
5688185029Spjd	mutex_exit(&l2arc_dev_mtx);
5689185029Spjd
5690185029Spjd	/*
5691185029Spjd	 * Grab the config lock to prevent the 'next' device from being
5692185029Spjd	 * removed while we are writing to it.
5693185029Spjd	 */
5694185029Spjd	if (next != NULL)
5695185029Spjd		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
5696185029Spjd	mutex_exit(&spa_namespace_lock);
5697185029Spjd
5698185029Spjd	return (next);
5699185029Spjd}
5700185029Spjd
5701185029Spjd/*
5702185029Spjd * Free buffers that were tagged for destruction.
5703185029Spjd */
5704185029Spjdstatic void
5705185029Spjdl2arc_do_free_on_write()
5706185029Spjd{
5707185029Spjd	list_t *buflist;
5708185029Spjd	l2arc_data_free_t *df, *df_prev;
5709185029Spjd
5710185029Spjd	mutex_enter(&l2arc_free_on_write_mtx);
5711185029Spjd	buflist = l2arc_free_on_write;
5712185029Spjd
5713185029Spjd	for (df = list_tail(buflist); df; df = df_prev) {
5714185029Spjd		df_prev = list_prev(buflist, df);
5715185029Spjd		ASSERT(df->l2df_data != NULL);
5716185029Spjd		ASSERT(df->l2df_func != NULL);
5717185029Spjd		df->l2df_func(df->l2df_data, df->l2df_size);
5718185029Spjd		list_remove(buflist, df);
5719185029Spjd		kmem_free(df, sizeof (l2arc_data_free_t));
5720185029Spjd	}
5721185029Spjd
5722185029Spjd	mutex_exit(&l2arc_free_on_write_mtx);
5723185029Spjd}
5724185029Spjd
5725185029Spjd/*
5726185029Spjd * A write to a cache device has completed.  Update all headers to allow
5727185029Spjd * reads from these buffers to begin.
5728185029Spjd */
5729185029Spjdstatic void
5730185029Spjdl2arc_write_done(zio_t *zio)
5731185029Spjd{
5732185029Spjd	l2arc_write_callback_t *cb;
5733185029Spjd	l2arc_dev_t *dev;
5734185029Spjd	list_t *buflist;
5735275811Sdelphij	arc_buf_hdr_t *head, *hdr, *hdr_prev;
5736185029Spjd	kmutex_t *hash_lock;
5737268085Sdelphij	int64_t bytes_dropped = 0;
5738185029Spjd
5739185029Spjd	cb = zio->io_private;
5740185029Spjd	ASSERT(cb != NULL);
5741185029Spjd	dev = cb->l2wcb_dev;
5742185029Spjd	ASSERT(dev != NULL);
5743185029Spjd	head = cb->l2wcb_head;
5744185029Spjd	ASSERT(head != NULL);
5745286570Smav	buflist = &dev->l2ad_buflist;
5746185029Spjd	ASSERT(buflist != NULL);
5747185029Spjd	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
5748185029Spjd	    l2arc_write_callback_t *, cb);
5749185029Spjd
5750185029Spjd	if (zio->io_error != 0)
5751185029Spjd		ARCSTAT_BUMP(arcstat_l2_writes_error);
5752185029Spjd
5753185029Spjd	/*
5754185029Spjd	 * All writes completed, or an error was hit.
5755185029Spjd	 */
5756286763Smavtop:
5757286763Smav	mutex_enter(&dev->l2ad_mtx);
5758275811Sdelphij	for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
5759275811Sdelphij		hdr_prev = list_prev(buflist, hdr);
5760185029Spjd
5761275811Sdelphij		hash_lock = HDR_LOCK(hdr);
5762286763Smav
5763286763Smav		/*
5764286763Smav		 * We cannot use mutex_enter or else we can deadlock
5765286763Smav		 * with l2arc_write_buffers (due to swapping the order
5766286763Smav		 * the hash lock and l2ad_mtx are taken).
5767286763Smav		 */
5768185029Spjd		if (!mutex_tryenter(hash_lock)) {
5769185029Spjd			/*
5770286763Smav			 * Missed the hash lock. We must retry so we
5771286763Smav			 * don't leave the ARC_FLAG_L2_WRITING bit set.
5772185029Spjd			 */
5773286763Smav			ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
5774286763Smav
5775286763Smav			/*
5776286763Smav			 * We don't want to rescan the headers we've
5777286763Smav			 * already marked as having been written out, so
5778286763Smav			 * we reinsert the head node so we can pick up
5779286763Smav			 * where we left off.
5780286763Smav			 */
5781286763Smav			list_remove(buflist, head);
5782286763Smav			list_insert_after(buflist, hdr, head);
5783286763Smav
5784286763Smav			mutex_exit(&dev->l2ad_mtx);
5785286763Smav
5786286763Smav			/*
5787286763Smav			 * We wait for the hash lock to become available
5788286763Smav			 * to try and prevent busy waiting, and increase
5789286763Smav			 * the chance we'll be able to acquire the lock
5790286763Smav			 * the next time around.
5791286763Smav			 */
5792286763Smav			mutex_enter(hash_lock);
5793286763Smav			mutex_exit(hash_lock);
5794286763Smav			goto top;
5795185029Spjd		}
5796185029Spjd
5797286570Smav		/*
5798286763Smav		 * We could not have been moved into the arc_l2c_only
5799286763Smav		 * state while in-flight due to our ARC_FLAG_L2_WRITING
5800286763Smav		 * bit being set. Let's just ensure that's being enforced.
5801286570Smav		 */
5802286763Smav		ASSERT(HDR_HAS_L1HDR(hdr));
5803286570Smav
5804286763Smav		/*
5805286763Smav		 * We may have allocated a buffer for L2ARC compression,
5806286763Smav		 * we must release it to avoid leaking this data.
5807286763Smav		 */
5808286763Smav		l2arc_release_cdata_buf(hdr);
5809286763Smav
5810185029Spjd		if (zio->io_error != 0) {
5811185029Spjd			/*
5812185029Spjd			 * Error - drop L2ARC entry.
5813185029Spjd			 */
5814286570Smav			trim_map_free(hdr->b_l2hdr.b_dev->l2ad_vdev,
5815286570Smav			    hdr->b_l2hdr.b_daddr, hdr->b_l2hdr.b_asize, 0);
5816286570Smav			hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
5817286570Smav
5818286570Smav			ARCSTAT_INCR(arcstat_l2_asize, -hdr->b_l2hdr.b_asize);
5819275811Sdelphij			ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
5820286598Smav
5821286598Smav			bytes_dropped += hdr->b_l2hdr.b_asize;
5822286598Smav			(void) refcount_remove_many(&dev->l2ad_alloc,
5823286598Smav			    hdr->b_l2hdr.b_asize, hdr);
5824185029Spjd		}
5825185029Spjd
5826185029Spjd		/*
5827286763Smav		 * Allow ARC to begin reads and ghost list evictions to
5828286763Smav		 * this L2ARC entry.
5829185029Spjd		 */
5830275811Sdelphij		hdr->b_flags &= ~ARC_FLAG_L2_WRITING;
5831185029Spjd
5832185029Spjd		mutex_exit(hash_lock);
5833185029Spjd	}
5834185029Spjd
5835185029Spjd	atomic_inc_64(&l2arc_writes_done);
5836185029Spjd	list_remove(buflist, head);
5837286570Smav	ASSERT(!HDR_HAS_L1HDR(head));
5838286570Smav	kmem_cache_free(hdr_l2only_cache, head);
5839286570Smav	mutex_exit(&dev->l2ad_mtx);
5840185029Spjd
5841268085Sdelphij	vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
5842268085Sdelphij
5843185029Spjd	l2arc_do_free_on_write();
5844185029Spjd
5845185029Spjd	kmem_free(cb, sizeof (l2arc_write_callback_t));
5846185029Spjd}
5847185029Spjd
5848185029Spjd/*
5849185029Spjd * A read to a cache device completed.  Validate buffer contents before
5850185029Spjd * handing over to the regular ARC routines.
5851185029Spjd */
5852185029Spjdstatic void
5853185029Spjdl2arc_read_done(zio_t *zio)
5854185029Spjd{
5855185029Spjd	l2arc_read_callback_t *cb;
5856185029Spjd	arc_buf_hdr_t *hdr;
5857185029Spjd	arc_buf_t *buf;
5858185029Spjd	kmutex_t *hash_lock;
5859185029Spjd	int equal;
5860185029Spjd
5861185029Spjd	ASSERT(zio->io_vd != NULL);
5862185029Spjd	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
5863185029Spjd
5864185029Spjd	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
5865185029Spjd
5866185029Spjd	cb = zio->io_private;
5867185029Spjd	ASSERT(cb != NULL);
5868185029Spjd	buf = cb->l2rcb_buf;
5869185029Spjd	ASSERT(buf != NULL);
5870185029Spjd
5871219089Spjd	hash_lock = HDR_LOCK(buf->b_hdr);
5872185029Spjd	mutex_enter(hash_lock);
5873219089Spjd	hdr = buf->b_hdr;
5874219089Spjd	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
5875185029Spjd
5876185029Spjd	/*
5877251478Sdelphij	 * If the buffer was compressed, decompress it first.
5878251478Sdelphij	 */
5879251478Sdelphij	if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
5880251478Sdelphij		l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
5881251478Sdelphij	ASSERT(zio->io_data != NULL);
5882251478Sdelphij
5883251478Sdelphij	/*
5884185029Spjd	 * Check this survived the L2ARC journey.
5885185029Spjd	 */
5886185029Spjd	equal = arc_cksum_equal(buf);
5887185029Spjd	if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
5888185029Spjd		mutex_exit(hash_lock);
5889185029Spjd		zio->io_private = buf;
5890185029Spjd		zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
5891185029Spjd		zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
5892185029Spjd		arc_read_done(zio);
5893185029Spjd	} else {
5894185029Spjd		mutex_exit(hash_lock);
5895185029Spjd		/*
5896185029Spjd		 * Buffer didn't survive caching.  Increment stats and
5897185029Spjd		 * reissue to the original storage device.
5898185029Spjd		 */
5899185029Spjd		if (zio->io_error != 0) {
5900185029Spjd			ARCSTAT_BUMP(arcstat_l2_io_error);
5901185029Spjd		} else {
5902249195Smm			zio->io_error = SET_ERROR(EIO);
5903185029Spjd		}
5904185029Spjd		if (!equal)
5905185029Spjd			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
5906185029Spjd
5907185029Spjd		/*
5908185029Spjd		 * If there's no waiter, issue an async i/o to the primary
5909185029Spjd		 * storage now.  If there *is* a waiter, the caller must
5910185029Spjd		 * issue the i/o in a context where it's OK to block.
5911185029Spjd		 */
5912209962Smm		if (zio->io_waiter == NULL) {
5913209962Smm			zio_t *pio = zio_unique_parent(zio);
5914209962Smm
5915209962Smm			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
5916209962Smm
5917209962Smm			zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
5918185029Spjd			    buf->b_data, zio->io_size, arc_read_done, buf,
5919185029Spjd			    zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
5920209962Smm		}
5921185029Spjd	}
5922185029Spjd
5923185029Spjd	kmem_free(cb, sizeof (l2arc_read_callback_t));
5924185029Spjd}
5925185029Spjd
5926185029Spjd/*
5927185029Spjd * This is the list priority from which the L2ARC will search for pages to
5928185029Spjd * cache.  This is used within loops (0..3) to cycle through lists in the
5929185029Spjd * desired order.  This order can have a significant effect on cache
5930185029Spjd * performance.
5931185029Spjd *
5932185029Spjd * Currently the metadata lists are hit first, MFU then MRU, followed by
5933185029Spjd * the data lists.  This function returns a locked list, and also returns
5934185029Spjd * the lock pointer.
5935185029Spjd */
5936286763Smavstatic multilist_sublist_t *
5937286763Smavl2arc_sublist_lock(int list_num)
5938185029Spjd{
5939286763Smav	multilist_t *ml = NULL;
5940286763Smav	unsigned int idx;
5941185029Spjd
5942286762Smav	ASSERT(list_num >= 0 && list_num <= 3);
5943206796Spjd
5944286762Smav	switch (list_num) {
5945286762Smav	case 0:
5946286763Smav		ml = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
5947286762Smav		break;
5948286762Smav	case 1:
5949286763Smav		ml = &arc_mru->arcs_list[ARC_BUFC_METADATA];
5950286762Smav		break;
5951286762Smav	case 2:
5952286763Smav		ml = &arc_mfu->arcs_list[ARC_BUFC_DATA];
5953286762Smav		break;
5954286762Smav	case 3:
5955286763Smav		ml = &arc_mru->arcs_list[ARC_BUFC_DATA];
5956286762Smav		break;
5957185029Spjd	}
5958185029Spjd
5959286763Smav	/*
5960286763Smav	 * Return a randomly-selected sublist. This is acceptable
5961286763Smav	 * because the caller feeds only a little bit of data for each
5962286763Smav	 * call (8MB). Subsequent calls will result in different
5963286763Smav	 * sublists being selected.
5964286763Smav	 */
5965286763Smav	idx = multilist_get_random_index(ml);
5966286763Smav	return (multilist_sublist_lock(ml, idx));
5967185029Spjd}
5968185029Spjd
5969185029Spjd/*
5970185029Spjd * Evict buffers from the device write hand to the distance specified in
5971185029Spjd * bytes.  This distance may span populated buffers, it may span nothing.
5972185029Spjd * This is clearing a region on the L2ARC device ready for writing.
5973185029Spjd * If the 'all' boolean is set, every buffer is evicted.
5974185029Spjd */
5975185029Spjdstatic void
5976185029Spjdl2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
5977185029Spjd{
5978185029Spjd	list_t *buflist;
5979275811Sdelphij	arc_buf_hdr_t *hdr, *hdr_prev;
5980185029Spjd	kmutex_t *hash_lock;
5981185029Spjd	uint64_t taddr;
5982185029Spjd
5983286570Smav	buflist = &dev->l2ad_buflist;
5984185029Spjd
5985185029Spjd	if (!all && dev->l2ad_first) {
5986185029Spjd		/*
5987185029Spjd		 * This is the first sweep through the device.  There is
5988185029Spjd		 * nothing to evict.
5989185029Spjd		 */
5990185029Spjd		return;
5991185029Spjd	}
5992185029Spjd
5993185029Spjd	if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
5994185029Spjd		/*
5995185029Spjd		 * When nearing the end of the device, evict to the end
5996185029Spjd		 * before the device write hand jumps to the start.
5997185029Spjd		 */
5998185029Spjd		taddr = dev->l2ad_end;
5999185029Spjd	} else {
6000185029Spjd		taddr = dev->l2ad_hand + distance;
6001185029Spjd	}
6002185029Spjd	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
6003185029Spjd	    uint64_t, taddr, boolean_t, all);
6004185029Spjd
6005185029Spjdtop:
6006286570Smav	mutex_enter(&dev->l2ad_mtx);
6007275811Sdelphij	for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
6008275811Sdelphij		hdr_prev = list_prev(buflist, hdr);
6009185029Spjd
6010275811Sdelphij		hash_lock = HDR_LOCK(hdr);
6011286763Smav
6012286763Smav		/*
6013286763Smav		 * We cannot use mutex_enter or else we can deadlock
6014286763Smav		 * with l2arc_write_buffers (due to swapping the order
6015286763Smav		 * the hash lock and l2ad_mtx are taken).
6016286763Smav		 */
6017185029Spjd		if (!mutex_tryenter(hash_lock)) {
6018185029Spjd			/*
6019185029Spjd			 * Missed the hash lock.  Retry.
6020185029Spjd			 */
6021185029Spjd			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
6022286570Smav			mutex_exit(&dev->l2ad_mtx);
6023185029Spjd			mutex_enter(hash_lock);
6024185029Spjd			mutex_exit(hash_lock);
6025185029Spjd			goto top;
6026185029Spjd		}
6027185029Spjd
6028275811Sdelphij		if (HDR_L2_WRITE_HEAD(hdr)) {
6029185029Spjd			/*
6030185029Spjd			 * We hit a write head node.  Leave it for
6031185029Spjd			 * l2arc_write_done().
6032185029Spjd			 */
6033275811Sdelphij			list_remove(buflist, hdr);
6034185029Spjd			mutex_exit(hash_lock);
6035185029Spjd			continue;
6036185029Spjd		}
6037185029Spjd
6038286570Smav		if (!all && HDR_HAS_L2HDR(hdr) &&
6039286570Smav		    (hdr->b_l2hdr.b_daddr > taddr ||
6040286570Smav		    hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
6041185029Spjd			/*
6042185029Spjd			 * We've evicted to the target address,
6043185029Spjd			 * or the end of the device.
6044185029Spjd			 */
6045185029Spjd			mutex_exit(hash_lock);
6046185029Spjd			break;
6047185029Spjd		}
6048185029Spjd
6049286570Smav		ASSERT(HDR_HAS_L2HDR(hdr));
6050286570Smav		if (!HDR_HAS_L1HDR(hdr)) {
6051275811Sdelphij			ASSERT(!HDR_L2_READING(hdr));
6052185029Spjd			/*
6053185029Spjd			 * This doesn't exist in the ARC.  Destroy.
6054185029Spjd			 * arc_hdr_destroy() will call list_remove()
6055185029Spjd			 * and decrement arcstat_l2_size.
6056185029Spjd			 */
6057275811Sdelphij			arc_change_state(arc_anon, hdr, hash_lock);
6058275811Sdelphij			arc_hdr_destroy(hdr);
6059185029Spjd		} else {
6060286570Smav			ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
6061286570Smav			ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
6062185029Spjd			/*
6063185029Spjd			 * Invalidate issued or about to be issued
6064185029Spjd			 * reads, since we may be about to write
6065185029Spjd			 * over this location.
6066185029Spjd			 */
6067275811Sdelphij			if (HDR_L2_READING(hdr)) {
6068185029Spjd				ARCSTAT_BUMP(arcstat_l2_evict_reading);
6069275811Sdelphij				hdr->b_flags |= ARC_FLAG_L2_EVICTED;
6070185029Spjd			}
6071185029Spjd
6072286763Smav			/* Ensure this header has finished being written */
6073286763Smav			ASSERT(!HDR_L2_WRITING(hdr));
6074286763Smav			ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
6075286763Smav
6076286598Smav			arc_hdr_l2hdr_destroy(hdr);
6077185029Spjd		}
6078185029Spjd		mutex_exit(hash_lock);
6079185029Spjd	}
6080286570Smav	mutex_exit(&dev->l2ad_mtx);
6081185029Spjd}
6082185029Spjd
6083185029Spjd/*
6084185029Spjd * Find and write ARC buffers to the L2ARC device.
6085185029Spjd *
6086275811Sdelphij * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
6087185029Spjd * for reading until they have completed writing.
6088251478Sdelphij * The headroom_boost is an in-out parameter used to maintain headroom boost
6089251478Sdelphij * state between calls to this function.
6090251478Sdelphij *
6091251478Sdelphij * Returns the number of bytes actually written (which may be smaller than
6092251478Sdelphij * the delta by which the device hand has changed due to alignment).
6093185029Spjd */
6094208373Smmstatic uint64_t
6095251478Sdelphijl2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
6096251478Sdelphij    boolean_t *headroom_boost)
6097185029Spjd{
6098275811Sdelphij	arc_buf_hdr_t *hdr, *hdr_prev, *head;
6099251478Sdelphij	uint64_t write_asize, write_psize, write_sz, headroom,
6100251478Sdelphij	    buf_compress_minsz;
6101185029Spjd	void *buf_data;
6102251478Sdelphij	boolean_t full;
6103185029Spjd	l2arc_write_callback_t *cb;
6104185029Spjd	zio_t *pio, *wzio;
6105228103Smm	uint64_t guid = spa_load_guid(spa);
6106251478Sdelphij	const boolean_t do_headroom_boost = *headroom_boost;
6107185029Spjd	int try;
6108185029Spjd
6109185029Spjd	ASSERT(dev->l2ad_vdev != NULL);
6110185029Spjd
6111251478Sdelphij	/* Lower the flag now, we might want to raise it again later. */
6112251478Sdelphij	*headroom_boost = B_FALSE;
6113251478Sdelphij
6114185029Spjd	pio = NULL;
6115251478Sdelphij	write_sz = write_asize = write_psize = 0;
6116185029Spjd	full = B_FALSE;
6117286570Smav	head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
6118275811Sdelphij	head->b_flags |= ARC_FLAG_L2_WRITE_HEAD;
6119286570Smav	head->b_flags |= ARC_FLAG_HAS_L2HDR;
6120185029Spjd
6121205231Skmacy	ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
6122185029Spjd	/*
6123251478Sdelphij	 * We will want to try to compress buffers that are at least 2x the
6124251478Sdelphij	 * device sector size.
6125251478Sdelphij	 */
6126251478Sdelphij	buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
6127251478Sdelphij
6128251478Sdelphij	/*
6129185029Spjd	 * Copy buffers for L2ARC writing.
6130185029Spjd	 */
6131286762Smav	for (try = 0; try <= 3; try++) {
6132286763Smav		multilist_sublist_t *mls = l2arc_sublist_lock(try);
6133251478Sdelphij		uint64_t passed_sz = 0;
6134251478Sdelphij
6135205231Skmacy		ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
6136185029Spjd
6137185029Spjd		/*
6138185029Spjd		 * L2ARC fast warmup.
6139185029Spjd		 *
6140185029Spjd		 * Until the ARC is warm and starts to evict, read from the
6141185029Spjd		 * head of the ARC lists rather than the tail.
6142185029Spjd		 */
6143185029Spjd		if (arc_warm == B_FALSE)
6144286763Smav			hdr = multilist_sublist_head(mls);
6145185029Spjd		else
6146286763Smav			hdr = multilist_sublist_tail(mls);
6147275811Sdelphij		if (hdr == NULL)
6148205231Skmacy			ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
6149185029Spjd
6150286762Smav		headroom = target_sz * l2arc_headroom;
6151251478Sdelphij		if (do_headroom_boost)
6152251478Sdelphij			headroom = (headroom * l2arc_headroom_boost) / 100;
6153251478Sdelphij
6154275811Sdelphij		for (; hdr; hdr = hdr_prev) {
6155251478Sdelphij			kmutex_t *hash_lock;
6156251478Sdelphij			uint64_t buf_sz;
6157251478Sdelphij
6158185029Spjd			if (arc_warm == B_FALSE)
6159286763Smav				hdr_prev = multilist_sublist_next(mls, hdr);
6160185029Spjd			else
6161286763Smav				hdr_prev = multilist_sublist_prev(mls, hdr);
6162275811Sdelphij			ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned, hdr->b_size);
6163206796Spjd
6164275811Sdelphij			hash_lock = HDR_LOCK(hdr);
6165251478Sdelphij			if (!mutex_tryenter(hash_lock)) {
6166205231Skmacy				ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
6167185029Spjd				/*
6168185029Spjd				 * Skip this buffer rather than waiting.
6169185029Spjd				 */
6170185029Spjd				continue;
6171185029Spjd			}
6172185029Spjd
6173275811Sdelphij			passed_sz += hdr->b_size;
6174185029Spjd			if (passed_sz > headroom) {
6175185029Spjd				/*
6176185029Spjd				 * Searched too far.
6177185029Spjd				 */
6178185029Spjd				mutex_exit(hash_lock);
6179205231Skmacy				ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
6180185029Spjd				break;
6181185029Spjd			}
6182185029Spjd
6183275811Sdelphij			if (!l2arc_write_eligible(guid, hdr)) {
6184185029Spjd				mutex_exit(hash_lock);
6185185029Spjd				continue;
6186185029Spjd			}
6187185029Spjd
6188275811Sdelphij			if ((write_sz + hdr->b_size) > target_sz) {
6189185029Spjd				full = B_TRUE;
6190185029Spjd				mutex_exit(hash_lock);
6191205231Skmacy				ARCSTAT_BUMP(arcstat_l2_write_full);
6192185029Spjd				break;
6193185029Spjd			}
6194185029Spjd
6195185029Spjd			if (pio == NULL) {
6196185029Spjd				/*
6197185029Spjd				 * Insert a dummy header on the buflist so
6198185029Spjd				 * l2arc_write_done() can find where the
6199185029Spjd				 * write buffers begin without searching.
6200185029Spjd				 */
6201286763Smav				mutex_enter(&dev->l2ad_mtx);
6202286570Smav				list_insert_head(&dev->l2ad_buflist, head);
6203286763Smav				mutex_exit(&dev->l2ad_mtx);
6204185029Spjd
6205185029Spjd				cb = kmem_alloc(
6206185029Spjd				    sizeof (l2arc_write_callback_t), KM_SLEEP);
6207185029Spjd				cb->l2wcb_dev = dev;
6208185029Spjd				cb->l2wcb_head = head;
6209185029Spjd				pio = zio_root(spa, l2arc_write_done, cb,
6210185029Spjd				    ZIO_FLAG_CANFAIL);
6211205231Skmacy				ARCSTAT_BUMP(arcstat_l2_write_pios);
6212185029Spjd			}
6213185029Spjd
6214185029Spjd			/*
6215185029Spjd			 * Create and add a new L2ARC header.
6216185029Spjd			 */
6217286570Smav			hdr->b_l2hdr.b_dev = dev;
6218275811Sdelphij			hdr->b_flags |= ARC_FLAG_L2_WRITING;
6219251478Sdelphij			/*
6220251478Sdelphij			 * Temporarily stash the data buffer in b_tmp_cdata.
6221251478Sdelphij			 * The subsequent write step will pick it up from
6222286570Smav			 * there. This is because can't access b_l1hdr.b_buf
6223251478Sdelphij			 * without holding the hash_lock, which we in turn
6224251478Sdelphij			 * can't access without holding the ARC list locks
6225251478Sdelphij			 * (which we want to avoid during compression/writing).
6226251478Sdelphij			 */
6227286570Smav			HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_OFF);
6228286570Smav			hdr->b_l2hdr.b_asize = hdr->b_size;
6229286570Smav			hdr->b_l1hdr.b_tmp_cdata = hdr->b_l1hdr.b_buf->b_data;
6230251478Sdelphij
6231286598Smav			/*
6232286598Smav			 * Explicitly set the b_daddr field to a known
6233286598Smav			 * value which means "invalid address". This
6234286598Smav			 * enables us to differentiate which stage of
6235286598Smav			 * l2arc_write_buffers() the particular header
6236286598Smav			 * is in (e.g. this loop, or the one below).
6237286598Smav			 * ARC_FLAG_L2_WRITING is not enough to make
6238286598Smav			 * this distinction, and we need to know in
6239286598Smav			 * order to do proper l2arc vdev accounting in
6240286598Smav			 * arc_release() and arc_hdr_destroy().
6241286598Smav			 *
6242286598Smav			 * Note, we can't use a new flag to distinguish
6243286598Smav			 * the two stages because we don't hold the
6244286598Smav			 * header's hash_lock below, in the second stage
6245286598Smav			 * of this function. Thus, we can't simply
6246286598Smav			 * change the b_flags field to denote that the
6247286598Smav			 * IO has been sent. We can change the b_daddr
6248286598Smav			 * field of the L2 portion, though, since we'll
6249286598Smav			 * be holding the l2ad_mtx; which is why we're
6250286598Smav			 * using it to denote the header's state change.
6251286598Smav			 */
6252286598Smav			hdr->b_l2hdr.b_daddr = L2ARC_ADDR_UNSET;
6253286598Smav
6254275811Sdelphij			buf_sz = hdr->b_size;
6255286570Smav			hdr->b_flags |= ARC_FLAG_HAS_L2HDR;
6256185029Spjd
6257286763Smav			mutex_enter(&dev->l2ad_mtx);
6258286570Smav			list_insert_head(&dev->l2ad_buflist, hdr);
6259286763Smav			mutex_exit(&dev->l2ad_mtx);
6260251478Sdelphij
6261185029Spjd			/*
6262185029Spjd			 * Compute and store the buffer cksum before
6263185029Spjd			 * writing.  On debug the cksum is verified first.
6264185029Spjd			 */
6265286570Smav			arc_cksum_verify(hdr->b_l1hdr.b_buf);
6266286570Smav			arc_cksum_compute(hdr->b_l1hdr.b_buf, B_TRUE);
6267185029Spjd
6268185029Spjd			mutex_exit(hash_lock);
6269185029Spjd
6270251478Sdelphij			write_sz += buf_sz;
6271251478Sdelphij		}
6272251478Sdelphij
6273286763Smav		multilist_sublist_unlock(mls);
6274251478Sdelphij
6275251478Sdelphij		if (full == B_TRUE)
6276251478Sdelphij			break;
6277251478Sdelphij	}
6278251478Sdelphij
6279251478Sdelphij	/* No buffers selected for writing? */
6280251478Sdelphij	if (pio == NULL) {
6281251478Sdelphij		ASSERT0(write_sz);
6282286570Smav		ASSERT(!HDR_HAS_L1HDR(head));
6283286570Smav		kmem_cache_free(hdr_l2only_cache, head);
6284251478Sdelphij		return (0);
6285251478Sdelphij	}
6286251478Sdelphij
6287286763Smav	mutex_enter(&dev->l2ad_mtx);
6288286763Smav
6289251478Sdelphij	/*
6290251478Sdelphij	 * Now start writing the buffers. We're starting at the write head
6291251478Sdelphij	 * and work backwards, retracing the course of the buffer selector
6292251478Sdelphij	 * loop above.
6293251478Sdelphij	 */
6294286570Smav	for (hdr = list_prev(&dev->l2ad_buflist, head); hdr;
6295286570Smav	    hdr = list_prev(&dev->l2ad_buflist, hdr)) {
6296251478Sdelphij		uint64_t buf_sz;
6297251478Sdelphij
6298251478Sdelphij		/*
6299286763Smav		 * We rely on the L1 portion of the header below, so
6300286763Smav		 * it's invalid for this header to have been evicted out
6301286763Smav		 * of the ghost cache, prior to being written out. The
6302286763Smav		 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
6303286763Smav		 */
6304286763Smav		ASSERT(HDR_HAS_L1HDR(hdr));
6305286763Smav
6306286763Smav		/*
6307251478Sdelphij		 * We shouldn't need to lock the buffer here, since we flagged
6308275811Sdelphij		 * it as ARC_FLAG_L2_WRITING in the previous step, but we must
6309275811Sdelphij		 * take care to only access its L2 cache parameters. In
6310286570Smav		 * particular, hdr->l1hdr.b_buf may be invalid by now due to
6311275811Sdelphij		 * ARC eviction.
6312251478Sdelphij		 */
6313286570Smav		hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
6314251478Sdelphij
6315286570Smav		if ((HDR_L2COMPRESS(hdr)) &&
6316286570Smav		    hdr->b_l2hdr.b_asize >= buf_compress_minsz) {
6317286570Smav			if (l2arc_compress_buf(hdr)) {
6318251478Sdelphij				/*
6319251478Sdelphij				 * If compression succeeded, enable headroom
6320251478Sdelphij				 * boost on the next scan cycle.
6321251478Sdelphij				 */
6322251478Sdelphij				*headroom_boost = B_TRUE;
6323251478Sdelphij			}
6324251478Sdelphij		}
6325251478Sdelphij
6326251478Sdelphij		/*
6327251478Sdelphij		 * Pick up the buffer data we had previously stashed away
6328251478Sdelphij		 * (and now potentially also compressed).
6329251478Sdelphij		 */
6330286570Smav		buf_data = hdr->b_l1hdr.b_tmp_cdata;
6331286570Smav		buf_sz = hdr->b_l2hdr.b_asize;
6332251478Sdelphij
6333274172Savg		/*
6334274172Savg		 * If the data has not been compressed, then clear b_tmp_cdata
6335274172Savg		 * to make sure that it points only to a temporary compression
6336274172Savg		 * buffer.
6337274172Savg		 */
6338286570Smav		if (!L2ARC_IS_VALID_COMPRESS(HDR_GET_COMPRESS(hdr)))
6339286570Smav			hdr->b_l1hdr.b_tmp_cdata = NULL;
6340274172Savg
6341286598Smav		/*
6342286598Smav		 * We need to do this regardless if buf_sz is zero or
6343286598Smav		 * not, otherwise, when this l2hdr is evicted we'll
6344286598Smav		 * remove a reference that was never added.
6345286598Smav		 */
6346286598Smav		(void) refcount_add_many(&dev->l2ad_alloc, buf_sz, hdr);
6347286598Smav
6348251478Sdelphij		/* Compression may have squashed the buffer to zero length. */
6349251478Sdelphij		if (buf_sz != 0) {
6350251478Sdelphij			uint64_t buf_p_sz;
6351251478Sdelphij
6352185029Spjd			wzio = zio_write_phys(pio, dev->l2ad_vdev,
6353185029Spjd			    dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
6354185029Spjd			    NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
6355185029Spjd			    ZIO_FLAG_CANFAIL, B_FALSE);
6356185029Spjd
6357185029Spjd			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
6358185029Spjd			    zio_t *, wzio);
6359185029Spjd			(void) zio_nowait(wzio);
6360185029Spjd
6361251478Sdelphij			write_asize += buf_sz;
6362286598Smav
6363185029Spjd			/*
6364185029Spjd			 * Keep the clock hand suitably device-aligned.
6365185029Spjd			 */
6366251478Sdelphij			buf_p_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
6367251478Sdelphij			write_psize += buf_p_sz;
6368251478Sdelphij			dev->l2ad_hand += buf_p_sz;
6369185029Spjd		}
6370251478Sdelphij	}
6371185029Spjd
6372286570Smav	mutex_exit(&dev->l2ad_mtx);
6373185029Spjd
6374251478Sdelphij	ASSERT3U(write_asize, <=, target_sz);
6375185029Spjd	ARCSTAT_BUMP(arcstat_l2_writes_sent);
6376251478Sdelphij	ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
6377185029Spjd	ARCSTAT_INCR(arcstat_l2_size, write_sz);
6378251478Sdelphij	ARCSTAT_INCR(arcstat_l2_asize, write_asize);
6379275096Sdelphij	vdev_space_update(dev->l2ad_vdev, write_asize, 0, 0);
6380185029Spjd
6381185029Spjd	/*
6382185029Spjd	 * Bump device hand to the device start if it is approaching the end.
6383185029Spjd	 * l2arc_evict() will already have evicted ahead for this case.
6384185029Spjd	 */
6385185029Spjd	if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
6386185029Spjd		dev->l2ad_hand = dev->l2ad_start;
6387185029Spjd		dev->l2ad_first = B_FALSE;
6388185029Spjd	}
6389185029Spjd
6390208373Smm	dev->l2ad_writing = B_TRUE;
6391185029Spjd	(void) zio_wait(pio);
6392208373Smm	dev->l2ad_writing = B_FALSE;
6393208373Smm
6394251478Sdelphij	return (write_asize);
6395185029Spjd}
6396185029Spjd
6397185029Spjd/*
6398251478Sdelphij * Compresses an L2ARC buffer.
6399286570Smav * The data to be compressed must be prefilled in l1hdr.b_tmp_cdata and its
6400251478Sdelphij * size in l2hdr->b_asize. This routine tries to compress the data and
6401251478Sdelphij * depending on the compression result there are three possible outcomes:
6402251478Sdelphij * *) The buffer was incompressible. The original l2hdr contents were left
6403251478Sdelphij *    untouched and are ready for writing to an L2 device.
6404251478Sdelphij * *) The buffer was all-zeros, so there is no need to write it to an L2
6405251478Sdelphij *    device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
6406251478Sdelphij *    set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
6407251478Sdelphij * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
6408251478Sdelphij *    data buffer which holds the compressed data to be written, and b_asize
6409251478Sdelphij *    tells us how much data there is. b_compress is set to the appropriate
6410251478Sdelphij *    compression algorithm. Once writing is done, invoke
6411251478Sdelphij *    l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
6412251478Sdelphij *
6413251478Sdelphij * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
6414251478Sdelphij * buffer was incompressible).
6415251478Sdelphij */
6416251478Sdelphijstatic boolean_t
6417286570Smavl2arc_compress_buf(arc_buf_hdr_t *hdr)
6418251478Sdelphij{
6419251478Sdelphij	void *cdata;
6420268075Sdelphij	size_t csize, len, rounded;
6421286570Smav	ASSERT(HDR_HAS_L2HDR(hdr));
6422286570Smav	l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
6423251478Sdelphij
6424286570Smav	ASSERT(HDR_HAS_L1HDR(hdr));
6425286570Smav	ASSERT(HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_OFF);
6426286570Smav	ASSERT(hdr->b_l1hdr.b_tmp_cdata != NULL);
6427251478Sdelphij
6428251478Sdelphij	len = l2hdr->b_asize;
6429251478Sdelphij	cdata = zio_data_buf_alloc(len);
6430286570Smav	ASSERT3P(cdata, !=, NULL);
6431286570Smav	csize = zio_compress_data(ZIO_COMPRESS_LZ4, hdr->b_l1hdr.b_tmp_cdata,
6432269086Sdelphij	    cdata, l2hdr->b_asize);
6433251478Sdelphij
6434251478Sdelphij	if (csize == 0) {
6435251478Sdelphij		/* zero block, indicate that there's nothing to write */
6436251478Sdelphij		zio_data_buf_free(cdata, len);
6437286570Smav		HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_EMPTY);
6438251478Sdelphij		l2hdr->b_asize = 0;
6439286570Smav		hdr->b_l1hdr.b_tmp_cdata = NULL;
6440251478Sdelphij		ARCSTAT_BUMP(arcstat_l2_compress_zeros);
6441251478Sdelphij		return (B_TRUE);
6442274628Savg	}
6443274628Savg
6444274628Savg	rounded = P2ROUNDUP(csize,
6445274628Savg	    (size_t)1 << l2hdr->b_dev->l2ad_vdev->vdev_ashift);
6446274628Savg	if (rounded < len) {
6447251478Sdelphij		/*
6448251478Sdelphij		 * Compression succeeded, we'll keep the cdata around for
6449251478Sdelphij		 * writing and release it afterwards.
6450251478Sdelphij		 */
6451274628Savg		if (rounded > csize) {
6452274628Savg			bzero((char *)cdata + csize, rounded - csize);
6453274628Savg			csize = rounded;
6454274628Savg		}
6455286570Smav		HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_LZ4);
6456251478Sdelphij		l2hdr->b_asize = csize;
6457286570Smav		hdr->b_l1hdr.b_tmp_cdata = cdata;
6458251478Sdelphij		ARCSTAT_BUMP(arcstat_l2_compress_successes);
6459251478Sdelphij		return (B_TRUE);
6460251478Sdelphij	} else {
6461251478Sdelphij		/*
6462251478Sdelphij		 * Compression failed, release the compressed buffer.
6463251478Sdelphij		 * l2hdr will be left unmodified.
6464251478Sdelphij		 */
6465251478Sdelphij		zio_data_buf_free(cdata, len);
6466251478Sdelphij		ARCSTAT_BUMP(arcstat_l2_compress_failures);
6467251478Sdelphij		return (B_FALSE);
6468251478Sdelphij	}
6469251478Sdelphij}
6470251478Sdelphij
6471251478Sdelphij/*
6472251478Sdelphij * Decompresses a zio read back from an l2arc device. On success, the
6473251478Sdelphij * underlying zio's io_data buffer is overwritten by the uncompressed
6474251478Sdelphij * version. On decompression error (corrupt compressed stream), the
6475251478Sdelphij * zio->io_error value is set to signal an I/O error.
6476251478Sdelphij *
6477251478Sdelphij * Please note that the compressed data stream is not checksummed, so
6478251478Sdelphij * if the underlying device is experiencing data corruption, we may feed
6479251478Sdelphij * corrupt data to the decompressor, so the decompressor needs to be
6480251478Sdelphij * able to handle this situation (LZ4 does).
6481251478Sdelphij */
6482251478Sdelphijstatic void
6483251478Sdelphijl2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
6484251478Sdelphij{
6485251478Sdelphij	ASSERT(L2ARC_IS_VALID_COMPRESS(c));
6486251478Sdelphij
6487251478Sdelphij	if (zio->io_error != 0) {
6488251478Sdelphij		/*
6489251478Sdelphij		 * An io error has occured, just restore the original io
6490251478Sdelphij		 * size in preparation for a main pool read.
6491251478Sdelphij		 */
6492251478Sdelphij		zio->io_orig_size = zio->io_size = hdr->b_size;
6493251478Sdelphij		return;
6494251478Sdelphij	}
6495251478Sdelphij
6496251478Sdelphij	if (c == ZIO_COMPRESS_EMPTY) {
6497251478Sdelphij		/*
6498251478Sdelphij		 * An empty buffer results in a null zio, which means we
6499251478Sdelphij		 * need to fill its io_data after we're done restoring the
6500251478Sdelphij		 * buffer's contents.
6501251478Sdelphij		 */
6502286570Smav		ASSERT(hdr->b_l1hdr.b_buf != NULL);
6503286570Smav		bzero(hdr->b_l1hdr.b_buf->b_data, hdr->b_size);
6504286570Smav		zio->io_data = zio->io_orig_data = hdr->b_l1hdr.b_buf->b_data;
6505251478Sdelphij	} else {
6506251478Sdelphij		ASSERT(zio->io_data != NULL);
6507251478Sdelphij		/*
6508251478Sdelphij		 * We copy the compressed data from the start of the arc buffer
6509251478Sdelphij		 * (the zio_read will have pulled in only what we need, the
6510251478Sdelphij		 * rest is garbage which we will overwrite at decompression)
6511251478Sdelphij		 * and then decompress back to the ARC data buffer. This way we
6512251478Sdelphij		 * can minimize copying by simply decompressing back over the
6513251478Sdelphij		 * original compressed data (rather than decompressing to an
6514251478Sdelphij		 * aux buffer and then copying back the uncompressed buffer,
6515251478Sdelphij		 * which is likely to be much larger).
6516251478Sdelphij		 */
6517251478Sdelphij		uint64_t csize;
6518251478Sdelphij		void *cdata;
6519251478Sdelphij
6520251478Sdelphij		csize = zio->io_size;
6521251478Sdelphij		cdata = zio_data_buf_alloc(csize);
6522251478Sdelphij		bcopy(zio->io_data, cdata, csize);
6523251478Sdelphij		if (zio_decompress_data(c, cdata, zio->io_data, csize,
6524251478Sdelphij		    hdr->b_size) != 0)
6525251478Sdelphij			zio->io_error = EIO;
6526251478Sdelphij		zio_data_buf_free(cdata, csize);
6527251478Sdelphij	}
6528251478Sdelphij
6529251478Sdelphij	/* Restore the expected uncompressed IO size. */
6530251478Sdelphij	zio->io_orig_size = zio->io_size = hdr->b_size;
6531251478Sdelphij}
6532251478Sdelphij
6533251478Sdelphij/*
6534251478Sdelphij * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
6535251478Sdelphij * This buffer serves as a temporary holder of compressed data while
6536251478Sdelphij * the buffer entry is being written to an l2arc device. Once that is
6537251478Sdelphij * done, we can dispose of it.
6538251478Sdelphij */
6539251478Sdelphijstatic void
6540275811Sdelphijl2arc_release_cdata_buf(arc_buf_hdr_t *hdr)
6541251478Sdelphij{
6542286763Smav	enum zio_compress comp = HDR_GET_COMPRESS(hdr);
6543286763Smav
6544286570Smav	ASSERT(HDR_HAS_L1HDR(hdr));
6545286763Smav	ASSERT(comp == ZIO_COMPRESS_OFF || L2ARC_IS_VALID_COMPRESS(comp));
6546286763Smav
6547286763Smav	if (comp == ZIO_COMPRESS_OFF) {
6548251478Sdelphij		/*
6549286763Smav		 * In this case, b_tmp_cdata points to the same buffer
6550286763Smav		 * as the arc_buf_t's b_data field. We don't want to
6551286763Smav		 * free it, since the arc_buf_t will handle that.
6552286763Smav		 */
6553286763Smav		hdr->b_l1hdr.b_tmp_cdata = NULL;
6554286763Smav	} else if (comp == ZIO_COMPRESS_EMPTY) {
6555286763Smav		/*
6556286763Smav		 * In this case, b_tmp_cdata was compressed to an empty
6557286763Smav		 * buffer, thus there's nothing to free and b_tmp_cdata
6558286763Smav		 * should have been set to NULL in l2arc_write_buffers().
6559286763Smav		 */
6560286763Smav		ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
6561286763Smav	} else {
6562286763Smav		/*
6563251478Sdelphij		 * If the data was compressed, then we've allocated a
6564251478Sdelphij		 * temporary buffer for it, so now we need to release it.
6565251478Sdelphij		 */
6566286570Smav		ASSERT(hdr->b_l1hdr.b_tmp_cdata != NULL);
6567286570Smav		zio_data_buf_free(hdr->b_l1hdr.b_tmp_cdata,
6568286570Smav		    hdr->b_size);
6569286570Smav		hdr->b_l1hdr.b_tmp_cdata = NULL;
6570251478Sdelphij	}
6571251478Sdelphij}
6572251478Sdelphij
6573251478Sdelphij/*
6574185029Spjd * This thread feeds the L2ARC at regular intervals.  This is the beating
6575185029Spjd * heart of the L2ARC.
6576185029Spjd */
6577185029Spjdstatic void
6578185029Spjdl2arc_feed_thread(void *dummy __unused)
6579185029Spjd{
6580185029Spjd	callb_cpr_t cpr;
6581185029Spjd	l2arc_dev_t *dev;
6582185029Spjd	spa_t *spa;
6583208373Smm	uint64_t size, wrote;
6584219089Spjd	clock_t begin, next = ddi_get_lbolt();
6585251478Sdelphij	boolean_t headroom_boost = B_FALSE;
6586185029Spjd
6587185029Spjd	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
6588185029Spjd
6589185029Spjd	mutex_enter(&l2arc_feed_thr_lock);
6590185029Spjd
6591185029Spjd	while (l2arc_thread_exit == 0) {
6592185029Spjd		CALLB_CPR_SAFE_BEGIN(&cpr);
6593185029Spjd		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
6594219089Spjd		    next - ddi_get_lbolt());
6595185029Spjd		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
6596219089Spjd		next = ddi_get_lbolt() + hz;
6597185029Spjd
6598185029Spjd		/*
6599185029Spjd		 * Quick check for L2ARC devices.
6600185029Spjd		 */
6601185029Spjd		mutex_enter(&l2arc_dev_mtx);
6602185029Spjd		if (l2arc_ndev == 0) {
6603185029Spjd			mutex_exit(&l2arc_dev_mtx);
6604185029Spjd			continue;
6605185029Spjd		}
6606185029Spjd		mutex_exit(&l2arc_dev_mtx);
6607219089Spjd		begin = ddi_get_lbolt();
6608185029Spjd
6609185029Spjd		/*
6610185029Spjd		 * This selects the next l2arc device to write to, and in
6611185029Spjd		 * doing so the next spa to feed from: dev->l2ad_spa.   This
6612185029Spjd		 * will return NULL if there are now no l2arc devices or if
6613185029Spjd		 * they are all faulted.
6614185029Spjd		 *
6615185029Spjd		 * If a device is returned, its spa's config lock is also
6616185029Spjd		 * held to prevent device removal.  l2arc_dev_get_next()
6617185029Spjd		 * will grab and release l2arc_dev_mtx.
6618185029Spjd		 */
6619185029Spjd		if ((dev = l2arc_dev_get_next()) == NULL)
6620185029Spjd			continue;
6621185029Spjd
6622185029Spjd		spa = dev->l2ad_spa;
6623185029Spjd		ASSERT(spa != NULL);
6624185029Spjd
6625185029Spjd		/*
6626219089Spjd		 * If the pool is read-only then force the feed thread to
6627219089Spjd		 * sleep a little longer.
6628219089Spjd		 */
6629219089Spjd		if (!spa_writeable(spa)) {
6630219089Spjd			next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
6631219089Spjd			spa_config_exit(spa, SCL_L2ARC, dev);
6632219089Spjd			continue;
6633219089Spjd		}
6634219089Spjd
6635219089Spjd		/*
6636185029Spjd		 * Avoid contributing to memory pressure.
6637185029Spjd		 */
6638185029Spjd		if (arc_reclaim_needed()) {
6639185029Spjd			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
6640185029Spjd			spa_config_exit(spa, SCL_L2ARC, dev);
6641185029Spjd			continue;
6642185029Spjd		}
6643185029Spjd
6644185029Spjd		ARCSTAT_BUMP(arcstat_l2_feeds);
6645185029Spjd
6646251478Sdelphij		size = l2arc_write_size();
6647185029Spjd
6648185029Spjd		/*
6649185029Spjd		 * Evict L2ARC buffers that will be overwritten.
6650185029Spjd		 */
6651185029Spjd		l2arc_evict(dev, size, B_FALSE);
6652185029Spjd
6653185029Spjd		/*
6654185029Spjd		 * Write ARC buffers.
6655185029Spjd		 */
6656251478Sdelphij		wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
6657208373Smm
6658208373Smm		/*
6659208373Smm		 * Calculate interval between writes.
6660208373Smm		 */
6661208373Smm		next = l2arc_write_interval(begin, size, wrote);
6662185029Spjd		spa_config_exit(spa, SCL_L2ARC, dev);
6663185029Spjd	}
6664185029Spjd
6665185029Spjd	l2arc_thread_exit = 0;
6666185029Spjd	cv_broadcast(&l2arc_feed_thr_cv);
6667185029Spjd	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
6668185029Spjd	thread_exit();
6669185029Spjd}
6670185029Spjd
6671185029Spjdboolean_t
6672185029Spjdl2arc_vdev_present(vdev_t *vd)
6673185029Spjd{
6674185029Spjd	l2arc_dev_t *dev;
6675185029Spjd
6676185029Spjd	mutex_enter(&l2arc_dev_mtx);
6677185029Spjd	for (dev = list_head(l2arc_dev_list); dev != NULL;
6678185029Spjd	    dev = list_next(l2arc_dev_list, dev)) {
6679185029Spjd		if (dev->l2ad_vdev == vd)
6680185029Spjd			break;
6681185029Spjd	}
6682185029Spjd	mutex_exit(&l2arc_dev_mtx);
6683185029Spjd
6684185029Spjd	return (dev != NULL);
6685185029Spjd}
6686185029Spjd
6687185029Spjd/*
6688185029Spjd * Add a vdev for use by the L2ARC.  By this point the spa has already
6689185029Spjd * validated the vdev and opened it.
6690185029Spjd */
6691185029Spjdvoid
6692219089Spjdl2arc_add_vdev(spa_t *spa, vdev_t *vd)
6693185029Spjd{
6694185029Spjd	l2arc_dev_t *adddev;
6695185029Spjd
6696185029Spjd	ASSERT(!l2arc_vdev_present(vd));
6697185029Spjd
6698255753Sgibbs	vdev_ashift_optimize(vd);
6699255753Sgibbs
6700185029Spjd	/*
6701185029Spjd	 * Create a new l2arc device entry.
6702185029Spjd	 */
6703185029Spjd	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
6704185029Spjd	adddev->l2ad_spa = spa;
6705185029Spjd	adddev->l2ad_vdev = vd;
6706219089Spjd	adddev->l2ad_start = VDEV_LABEL_START_SIZE;
6707219089Spjd	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
6708185029Spjd	adddev->l2ad_hand = adddev->l2ad_start;
6709185029Spjd	adddev->l2ad_first = B_TRUE;
6710208373Smm	adddev->l2ad_writing = B_FALSE;
6711185029Spjd
6712286570Smav	mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
6713185029Spjd	/*
6714185029Spjd	 * This is a list of all ARC buffers that are still valid on the
6715185029Spjd	 * device.
6716185029Spjd	 */
6717286570Smav	list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
6718286570Smav	    offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
6719185029Spjd
6720219089Spjd	vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
6721286598Smav	refcount_create(&adddev->l2ad_alloc);
6722185029Spjd
6723185029Spjd	/*
6724185029Spjd	 * Add device to global list
6725185029Spjd	 */
6726185029Spjd	mutex_enter(&l2arc_dev_mtx);
6727185029Spjd	list_insert_head(l2arc_dev_list, adddev);
6728185029Spjd	atomic_inc_64(&l2arc_ndev);
6729185029Spjd	mutex_exit(&l2arc_dev_mtx);
6730185029Spjd}
6731185029Spjd
6732185029Spjd/*
6733185029Spjd * Remove a vdev from the L2ARC.
6734185029Spjd */
6735185029Spjdvoid
6736185029Spjdl2arc_remove_vdev(vdev_t *vd)
6737185029Spjd{
6738185029Spjd	l2arc_dev_t *dev, *nextdev, *remdev = NULL;
6739185029Spjd
6740185029Spjd	/*
6741185029Spjd	 * Find the device by vdev
6742185029Spjd	 */
6743185029Spjd	mutex_enter(&l2arc_dev_mtx);
6744185029Spjd	for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
6745185029Spjd		nextdev = list_next(l2arc_dev_list, dev);
6746185029Spjd		if (vd == dev->l2ad_vdev) {
6747185029Spjd			remdev = dev;
6748185029Spjd			break;
6749185029Spjd		}
6750185029Spjd	}
6751185029Spjd	ASSERT(remdev != NULL);
6752185029Spjd
6753185029Spjd	/*
6754185029Spjd	 * Remove device from global list
6755185029Spjd	 */
6756185029Spjd	list_remove(l2arc_dev_list, remdev);
6757185029Spjd	l2arc_dev_last = NULL;		/* may have been invalidated */
6758185029Spjd	atomic_dec_64(&l2arc_ndev);
6759185029Spjd	mutex_exit(&l2arc_dev_mtx);
6760185029Spjd
6761185029Spjd	/*
6762185029Spjd	 * Clear all buflists and ARC references.  L2ARC device flush.
6763185029Spjd	 */
6764185029Spjd	l2arc_evict(remdev, 0, B_TRUE);
6765286570Smav	list_destroy(&remdev->l2ad_buflist);
6766286570Smav	mutex_destroy(&remdev->l2ad_mtx);
6767286598Smav	refcount_destroy(&remdev->l2ad_alloc);
6768185029Spjd	kmem_free(remdev, sizeof (l2arc_dev_t));
6769185029Spjd}
6770185029Spjd
6771185029Spjdvoid
6772185029Spjdl2arc_init(void)
6773185029Spjd{
6774185029Spjd	l2arc_thread_exit = 0;
6775185029Spjd	l2arc_ndev = 0;
6776185029Spjd	l2arc_writes_sent = 0;
6777185029Spjd	l2arc_writes_done = 0;
6778185029Spjd
6779185029Spjd	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
6780185029Spjd	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
6781185029Spjd	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
6782185029Spjd	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
6783185029Spjd
6784185029Spjd	l2arc_dev_list = &L2ARC_dev_list;
6785185029Spjd	l2arc_free_on_write = &L2ARC_free_on_write;
6786185029Spjd	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
6787185029Spjd	    offsetof(l2arc_dev_t, l2ad_node));
6788185029Spjd	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
6789185029Spjd	    offsetof(l2arc_data_free_t, l2df_list_node));
6790185029Spjd}
6791185029Spjd
6792185029Spjdvoid
6793185029Spjdl2arc_fini(void)
6794185029Spjd{
6795185029Spjd	/*
6796185029Spjd	 * This is called from dmu_fini(), which is called from spa_fini();
6797185029Spjd	 * Because of this, we can assume that all l2arc devices have
6798185029Spjd	 * already been removed when the pools themselves were removed.
6799185029Spjd	 */
6800185029Spjd
6801185029Spjd	l2arc_do_free_on_write();
6802185029Spjd
6803185029Spjd	mutex_destroy(&l2arc_feed_thr_lock);
6804185029Spjd	cv_destroy(&l2arc_feed_thr_cv);
6805185029Spjd	mutex_destroy(&l2arc_dev_mtx);
6806185029Spjd	mutex_destroy(&l2arc_free_on_write_mtx);
6807185029Spjd
6808185029Spjd	list_destroy(l2arc_dev_list);
6809185029Spjd	list_destroy(l2arc_free_on_write);
6810185029Spjd}
6811185029Spjd
6812185029Spjdvoid
6813185029Spjdl2arc_start(void)
6814185029Spjd{
6815209962Smm	if (!(spa_mode_global & FWRITE))
6816185029Spjd		return;
6817185029Spjd
6818185029Spjd	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
6819185029Spjd	    TS_RUN, minclsyspri);
6820185029Spjd}
6821185029Spjd
6822185029Spjdvoid
6823185029Spjdl2arc_stop(void)
6824185029Spjd{
6825209962Smm	if (!(spa_mode_global & FWRITE))
6826185029Spjd		return;
6827185029Spjd
6828185029Spjd	mutex_enter(&l2arc_feed_thr_lock);
6829185029Spjd	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
6830185029Spjd	l2arc_thread_exit = 1;
6831185029Spjd	while (l2arc_thread_exit != 0)
6832185029Spjd		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
6833185029Spjd	mutex_exit(&l2arc_feed_thr_lock);
6834185029Spjd}
6835