arc.c revision 277452
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.
23268123Sdelphij * Copyright (c) 2011, 2014 by Delphix. All rights reserved.
24260835Sdelphij * Copyright (c) 2014 by Saso Kiselkov. All rights reserved.
25268085Sdelphij * Copyright 2014 Nexenta Systems, Inc.  All rights reserved.
26168404Spjd */
27168404Spjd
28168404Spjd/*
29168404Spjd * DVA-based Adjustable Replacement Cache
30168404Spjd *
31168404Spjd * While much of the theory of operation used here is
32168404Spjd * based on the self-tuning, low overhead replacement cache
33168404Spjd * presented by Megiddo and Modha at FAST 2003, there are some
34168404Spjd * significant differences:
35168404Spjd *
36168404Spjd * 1. The Megiddo and Modha model assumes any page is evictable.
37168404Spjd * Pages in its cache cannot be "locked" into memory.  This makes
38168404Spjd * the eviction algorithm simple: evict the last page in the list.
39168404Spjd * This also make the performance characteristics easy to reason
40168404Spjd * about.  Our cache is not so simple.  At any given moment, some
41168404Spjd * subset of the blocks in the cache are un-evictable because we
42168404Spjd * have handed out a reference to them.  Blocks are only evictable
43168404Spjd * when there are no external references active.  This makes
44168404Spjd * eviction far more problematic:  we choose to evict the evictable
45168404Spjd * blocks that are the "lowest" in the list.
46168404Spjd *
47168404Spjd * There are times when it is not possible to evict the requested
48168404Spjd * space.  In these circumstances we are unable to adjust the cache
49168404Spjd * size.  To prevent the cache growing unbounded at these times we
50185029Spjd * implement a "cache throttle" that slows the flow of new data
51185029Spjd * into the cache until we can make space available.
52168404Spjd *
53168404Spjd * 2. The Megiddo and Modha model assumes a fixed cache size.
54168404Spjd * Pages are evicted when the cache is full and there is a cache
55168404Spjd * miss.  Our model has a variable sized cache.  It grows with
56185029Spjd * high use, but also tries to react to memory pressure from the
57168404Spjd * operating system: decreasing its size when system memory is
58168404Spjd * tight.
59168404Spjd *
60168404Spjd * 3. The Megiddo and Modha model assumes a fixed page size. All
61251631Sdelphij * elements of the cache are therefore exactly the same size.  So
62168404Spjd * when adjusting the cache size following a cache miss, its simply
63168404Spjd * a matter of choosing a single page to evict.  In our model, we
64168404Spjd * have variable sized cache blocks (rangeing from 512 bytes to
65251631Sdelphij * 128K bytes).  We therefore choose a set of blocks to evict to make
66168404Spjd * space for a cache miss that approximates as closely as possible
67168404Spjd * the space used by the new block.
68168404Spjd *
69168404Spjd * See also:  "ARC: A Self-Tuning, Low Overhead Replacement Cache"
70168404Spjd * by N. Megiddo & D. Modha, FAST 2003
71168404Spjd */
72168404Spjd
73168404Spjd/*
74168404Spjd * The locking model:
75168404Spjd *
76168404Spjd * A new reference to a cache buffer can be obtained in two
77168404Spjd * ways: 1) via a hash table lookup using the DVA as a key,
78185029Spjd * or 2) via one of the ARC lists.  The arc_read() interface
79168404Spjd * uses method 1, while the internal arc algorithms for
80251631Sdelphij * adjusting the cache use method 2.  We therefore provide two
81168404Spjd * types of locks: 1) the hash table lock array, and 2) the
82168404Spjd * arc list locks.
83168404Spjd *
84168404Spjd * Buffers do not have their own mutexs, rather they rely on the
85168404Spjd * hash table mutexs for the bulk of their protection (i.e. most
86168404Spjd * fields in the arc_buf_hdr_t are protected by these mutexs).
87168404Spjd *
88168404Spjd * buf_hash_find() returns the appropriate mutex (held) when it
89168404Spjd * locates the requested buffer in the hash table.  It returns
90168404Spjd * NULL for the mutex if the buffer was not in the table.
91168404Spjd *
92168404Spjd * buf_hash_remove() expects the appropriate hash mutex to be
93168404Spjd * already held before it is invoked.
94168404Spjd *
95168404Spjd * Each arc state also has a mutex which is used to protect the
96168404Spjd * buffer list associated with the state.  When attempting to
97168404Spjd * obtain a hash table lock while holding an arc list lock you
98168404Spjd * must use: mutex_tryenter() to avoid deadlock.  Also note that
99168404Spjd * the active state mutex must be held before the ghost state mutex.
100168404Spjd *
101168404Spjd * Arc buffers may have an associated eviction callback function.
102168404Spjd * This function will be invoked prior to removing the buffer (e.g.
103168404Spjd * in arc_do_user_evicts()).  Note however that the data associated
104168404Spjd * with the buffer may be evicted prior to the callback.  The callback
105168404Spjd * must be made with *no locks held* (to prevent deadlock).  Additionally,
106168404Spjd * the users of callbacks must ensure that their private data is
107268858Sdelphij * protected from simultaneous callbacks from arc_clear_callback()
108168404Spjd * and arc_do_user_evicts().
109168404Spjd *
110168404Spjd * Note that the majority of the performance stats are manipulated
111168404Spjd * with atomic operations.
112185029Spjd *
113185029Spjd * The L2ARC uses the l2arc_buflist_mtx global mutex for the following:
114185029Spjd *
115185029Spjd *	- L2ARC buflist creation
116185029Spjd *	- L2ARC buflist eviction
117185029Spjd *	- L2ARC write completion, which walks L2ARC buflists
118185029Spjd *	- ARC header destruction, as it removes from L2ARC buflists
119185029Spjd *	- ARC header release, as it removes from L2ARC buflists
120168404Spjd */
121168404Spjd
122168404Spjd#include <sys/spa.h>
123168404Spjd#include <sys/zio.h>
124251478Sdelphij#include <sys/zio_compress.h>
125168404Spjd#include <sys/zfs_context.h>
126168404Spjd#include <sys/arc.h>
127168404Spjd#include <sys/refcount.h>
128185029Spjd#include <sys/vdev.h>
129219089Spjd#include <sys/vdev_impl.h>
130258632Savg#include <sys/dsl_pool.h>
131168404Spjd#ifdef _KERNEL
132168404Spjd#include <sys/dnlc.h>
133168404Spjd#endif
134168404Spjd#include <sys/callb.h>
135168404Spjd#include <sys/kstat.h>
136248572Ssmh#include <sys/trim_map.h>
137219089Spjd#include <zfs_fletcher.h>
138168404Spjd#include <sys/sdt.h>
139168404Spjd
140191902Skmacy#include <vm/vm_pageout.h>
141272483Ssmh#include <machine/vmparam.h>
142191902Skmacy
143240133Smm#ifdef illumos
144240133Smm#ifndef _KERNEL
145240133Smm/* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
146240133Smmboolean_t arc_watch = B_FALSE;
147240133Smmint arc_procfd;
148240133Smm#endif
149240133Smm#endif /* illumos */
150240133Smm
151168404Spjdstatic kmutex_t		arc_reclaim_thr_lock;
152168404Spjdstatic kcondvar_t	arc_reclaim_thr_cv;	/* used to signal reclaim thr */
153168404Spjdstatic uint8_t		arc_thread_exit;
154168404Spjd
155168404Spjd#define	ARC_REDUCE_DNLC_PERCENT	3
156168404Spjduint_t arc_reduce_dnlc_percent = ARC_REDUCE_DNLC_PERCENT;
157168404Spjd
158168404Spjdtypedef enum arc_reclaim_strategy {
159168404Spjd	ARC_RECLAIM_AGGR,		/* Aggressive reclaim strategy */
160168404Spjd	ARC_RECLAIM_CONS		/* Conservative reclaim strategy */
161168404Spjd} arc_reclaim_strategy_t;
162168404Spjd
163258632Savg/*
164258632Savg * The number of iterations through arc_evict_*() before we
165258632Savg * drop & reacquire the lock.
166258632Savg */
167258632Savgint arc_evict_iterations = 100;
168258632Savg
169168404Spjd/* number of seconds before growing cache again */
170168404Spjdstatic int		arc_grow_retry = 60;
171168404Spjd
172208373Smm/* shift of arc_c for calculating both min and max arc_p */
173208373Smmstatic int		arc_p_min_shift = 4;
174208373Smm
175208373Smm/* log2(fraction of arc to reclaim) */
176208373Smmstatic int		arc_shrink_shift = 5;
177208373Smm
178168404Spjd/*
179168404Spjd * minimum lifespan of a prefetch block in clock ticks
180168404Spjd * (initialized in arc_init())
181168404Spjd */
182168404Spjdstatic int		arc_min_prefetch_lifespan;
183168404Spjd
184258632Savg/*
185258632Savg * If this percent of memory is free, don't throttle.
186258632Savg */
187258632Savgint arc_lotsfree_percent = 10;
188258632Savg
189208373Smmstatic int arc_dead;
190194043Skmacyextern int zfs_prefetch_disable;
191168404Spjd
192168404Spjd/*
193185029Spjd * The arc has filled available memory and has now warmed up.
194185029Spjd */
195185029Spjdstatic boolean_t arc_warm;
196185029Spjd
197185029Spjduint64_t zfs_arc_max;
198185029Spjduint64_t zfs_arc_min;
199185029Spjduint64_t zfs_arc_meta_limit = 0;
200275780Sdelphijuint64_t zfs_arc_meta_min = 0;
201208373Smmint zfs_arc_grow_retry = 0;
202208373Smmint zfs_arc_shrink_shift = 0;
203208373Smmint zfs_arc_p_min_shift = 0;
204242845Sdelphijint zfs_disable_dup_eviction = 0;
205269230Sdelphijuint64_t zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
206272483Ssmhu_int zfs_arc_free_target = 0;
207185029Spjd
208270759Ssmhstatic int sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS);
209275748Sdelphijstatic int sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS);
210270759Ssmh
211270759Ssmh#ifdef _KERNEL
212270759Ssmhstatic void
213270759Ssmharc_free_target_init(void *unused __unused)
214270759Ssmh{
215270759Ssmh
216272483Ssmh	zfs_arc_free_target = vm_pageout_wakeup_thresh;
217270759Ssmh}
218270759SsmhSYSINIT(arc_free_target_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_ANY,
219270759Ssmh    arc_free_target_init, NULL);
220270759Ssmh
221185029SpjdTUNABLE_QUAD("vfs.zfs.arc_meta_limit", &zfs_arc_meta_limit);
222275780SdelphijTUNABLE_QUAD("vfs.zfs.arc_meta_min", &zfs_arc_meta_min);
223273026SdelphijTUNABLE_INT("vfs.zfs.arc_shrink_shift", &zfs_arc_shrink_shift);
224168473SpjdSYSCTL_DECL(_vfs_zfs);
225217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_max, CTLFLAG_RDTUN, &zfs_arc_max, 0,
226168473Spjd    "Maximum ARC size");
227217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_min, CTLFLAG_RDTUN, &zfs_arc_min, 0,
228168473Spjd    "Minimum ARC size");
229269230SdelphijSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_average_blocksize, CTLFLAG_RDTUN,
230269230Sdelphij    &zfs_arc_average_blocksize, 0,
231269230Sdelphij    "ARC average blocksize");
232273026SdelphijSYSCTL_INT(_vfs_zfs, OID_AUTO, arc_shrink_shift, CTLFLAG_RW,
233273026Sdelphij    &arc_shrink_shift, 0,
234273026Sdelphij    "log2(fraction of arc to reclaim)");
235273026Sdelphij
236270759Ssmh/*
237270759Ssmh * We don't have a tunable for arc_free_target due to the dependency on
238270759Ssmh * pagedaemon initialisation.
239270759Ssmh */
240270759SsmhSYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_free_target,
241270759Ssmh    CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(u_int),
242270759Ssmh    sysctl_vfs_zfs_arc_free_target, "IU",
243270759Ssmh    "Desired number of free pages below which ARC triggers reclaim");
244168404Spjd
245270759Ssmhstatic int
246270759Ssmhsysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS)
247270759Ssmh{
248270759Ssmh	u_int val;
249270759Ssmh	int err;
250270759Ssmh
251270759Ssmh	val = zfs_arc_free_target;
252270759Ssmh	err = sysctl_handle_int(oidp, &val, 0, req);
253270759Ssmh	if (err != 0 || req->newptr == NULL)
254270759Ssmh		return (err);
255270759Ssmh
256272483Ssmh	if (val < minfree)
257270759Ssmh		return (EINVAL);
258272483Ssmh	if (val > vm_cnt.v_page_count)
259270759Ssmh		return (EINVAL);
260270759Ssmh
261270759Ssmh	zfs_arc_free_target = val;
262270759Ssmh
263270759Ssmh	return (0);
264270759Ssmh}
265275748Sdelphij
266275748Sdelphij/*
267275748Sdelphij * Must be declared here, before the definition of corresponding kstat
268275748Sdelphij * macro which uses the same names will confuse the compiler.
269275748Sdelphij */
270275748SdelphijSYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_meta_limit,
271275748Sdelphij    CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
272275748Sdelphij    sysctl_vfs_zfs_arc_meta_limit, "QU",
273275748Sdelphij    "ARC metadata limit");
274272483Ssmh#endif
275270759Ssmh
276168404Spjd/*
277185029Spjd * Note that buffers can be in one of 6 states:
278168404Spjd *	ARC_anon	- anonymous (discussed below)
279168404Spjd *	ARC_mru		- recently used, currently cached
280168404Spjd *	ARC_mru_ghost	- recentely used, no longer in cache
281168404Spjd *	ARC_mfu		- frequently used, currently cached
282168404Spjd *	ARC_mfu_ghost	- frequently used, no longer in cache
283185029Spjd *	ARC_l2c_only	- exists in L2ARC but not other states
284185029Spjd * When there are no active references to the buffer, they are
285185029Spjd * are linked onto a list in one of these arc states.  These are
286185029Spjd * the only buffers that can be evicted or deleted.  Within each
287185029Spjd * state there are multiple lists, one for meta-data and one for
288185029Spjd * non-meta-data.  Meta-data (indirect blocks, blocks of dnodes,
289185029Spjd * etc.) is tracked separately so that it can be managed more
290185029Spjd * explicitly: favored over data, limited explicitly.
291168404Spjd *
292168404Spjd * Anonymous buffers are buffers that are not associated with
293168404Spjd * a DVA.  These are buffers that hold dirty block copies
294168404Spjd * before they are written to stable storage.  By definition,
295168404Spjd * they are "ref'd" and are considered part of arc_mru
296168404Spjd * that cannot be freed.  Generally, they will aquire a DVA
297168404Spjd * as they are written and migrate onto the arc_mru list.
298185029Spjd *
299185029Spjd * The ARC_l2c_only state is for buffers that are in the second
300185029Spjd * level ARC but no longer in any of the ARC_m* lists.  The second
301185029Spjd * level ARC itself may also contain buffers that are in any of
302185029Spjd * the ARC_m* states - meaning that a buffer can exist in two
303185029Spjd * places.  The reason for the ARC_l2c_only state is to keep the
304185029Spjd * buffer header in the hash table, so that reads that hit the
305185029Spjd * second level ARC benefit from these fast lookups.
306168404Spjd */
307168404Spjd
308205264Skmacy#define	ARCS_LOCK_PAD		CACHE_LINE_SIZE
309205231Skmacystruct arcs_lock {
310205231Skmacy	kmutex_t	arcs_lock;
311205231Skmacy#ifdef _KERNEL
312205231Skmacy	unsigned char	pad[(ARCS_LOCK_PAD - sizeof (kmutex_t))];
313205231Skmacy#endif
314205231Skmacy};
315205231Skmacy
316205231Skmacy/*
317205231Skmacy * must be power of two for mask use to work
318205231Skmacy *
319205231Skmacy */
320205231Skmacy#define ARC_BUFC_NUMDATALISTS		16
321205231Skmacy#define ARC_BUFC_NUMMETADATALISTS	16
322206796Spjd#define ARC_BUFC_NUMLISTS	(ARC_BUFC_NUMMETADATALISTS + ARC_BUFC_NUMDATALISTS)
323205231Skmacy
324168404Spjdtypedef struct arc_state {
325185029Spjd	uint64_t arcs_lsize[ARC_BUFC_NUMTYPES];	/* amount of evictable data */
326185029Spjd	uint64_t arcs_size;	/* total amount of data in this state */
327205231Skmacy	list_t	arcs_lists[ARC_BUFC_NUMLISTS]; /* list of evictable buffers */
328205264Skmacy	struct arcs_lock arcs_locks[ARC_BUFC_NUMLISTS] __aligned(CACHE_LINE_SIZE);
329168404Spjd} arc_state_t;
330168404Spjd
331206796Spjd#define ARCS_LOCK(s, i)	(&((s)->arcs_locks[(i)].arcs_lock))
332205231Skmacy
333185029Spjd/* The 6 states: */
334168404Spjdstatic arc_state_t ARC_anon;
335168404Spjdstatic arc_state_t ARC_mru;
336168404Spjdstatic arc_state_t ARC_mru_ghost;
337168404Spjdstatic arc_state_t ARC_mfu;
338168404Spjdstatic arc_state_t ARC_mfu_ghost;
339185029Spjdstatic arc_state_t ARC_l2c_only;
340168404Spjd
341168404Spjdtypedef struct arc_stats {
342168404Spjd	kstat_named_t arcstat_hits;
343168404Spjd	kstat_named_t arcstat_misses;
344168404Spjd	kstat_named_t arcstat_demand_data_hits;
345168404Spjd	kstat_named_t arcstat_demand_data_misses;
346168404Spjd	kstat_named_t arcstat_demand_metadata_hits;
347168404Spjd	kstat_named_t arcstat_demand_metadata_misses;
348168404Spjd	kstat_named_t arcstat_prefetch_data_hits;
349168404Spjd	kstat_named_t arcstat_prefetch_data_misses;
350168404Spjd	kstat_named_t arcstat_prefetch_metadata_hits;
351168404Spjd	kstat_named_t arcstat_prefetch_metadata_misses;
352168404Spjd	kstat_named_t arcstat_mru_hits;
353168404Spjd	kstat_named_t arcstat_mru_ghost_hits;
354168404Spjd	kstat_named_t arcstat_mfu_hits;
355168404Spjd	kstat_named_t arcstat_mfu_ghost_hits;
356205231Skmacy	kstat_named_t arcstat_allocated;
357168404Spjd	kstat_named_t arcstat_deleted;
358205231Skmacy	kstat_named_t arcstat_stolen;
359168404Spjd	kstat_named_t arcstat_recycle_miss;
360251629Sdelphij	/*
361251629Sdelphij	 * Number of buffers that could not be evicted because the hash lock
362251629Sdelphij	 * was held by another thread.  The lock may not necessarily be held
363251629Sdelphij	 * by something using the same buffer, since hash locks are shared
364251629Sdelphij	 * by multiple buffers.
365251629Sdelphij	 */
366168404Spjd	kstat_named_t arcstat_mutex_miss;
367251629Sdelphij	/*
368251629Sdelphij	 * Number of buffers skipped because they have I/O in progress, are
369251629Sdelphij	 * indrect prefetch buffers that have not lived long enough, or are
370251629Sdelphij	 * not from the spa we're trying to evict from.
371251629Sdelphij	 */
372168404Spjd	kstat_named_t arcstat_evict_skip;
373208373Smm	kstat_named_t arcstat_evict_l2_cached;
374208373Smm	kstat_named_t arcstat_evict_l2_eligible;
375208373Smm	kstat_named_t arcstat_evict_l2_ineligible;
376168404Spjd	kstat_named_t arcstat_hash_elements;
377168404Spjd	kstat_named_t arcstat_hash_elements_max;
378168404Spjd	kstat_named_t arcstat_hash_collisions;
379168404Spjd	kstat_named_t arcstat_hash_chains;
380168404Spjd	kstat_named_t arcstat_hash_chain_max;
381168404Spjd	kstat_named_t arcstat_p;
382168404Spjd	kstat_named_t arcstat_c;
383168404Spjd	kstat_named_t arcstat_c_min;
384168404Spjd	kstat_named_t arcstat_c_max;
385168404Spjd	kstat_named_t arcstat_size;
386185029Spjd	kstat_named_t arcstat_hdr_size;
387208373Smm	kstat_named_t arcstat_data_size;
388208373Smm	kstat_named_t arcstat_other_size;
389185029Spjd	kstat_named_t arcstat_l2_hits;
390185029Spjd	kstat_named_t arcstat_l2_misses;
391185029Spjd	kstat_named_t arcstat_l2_feeds;
392185029Spjd	kstat_named_t arcstat_l2_rw_clash;
393208373Smm	kstat_named_t arcstat_l2_read_bytes;
394208373Smm	kstat_named_t arcstat_l2_write_bytes;
395185029Spjd	kstat_named_t arcstat_l2_writes_sent;
396185029Spjd	kstat_named_t arcstat_l2_writes_done;
397185029Spjd	kstat_named_t arcstat_l2_writes_error;
398185029Spjd	kstat_named_t arcstat_l2_writes_hdr_miss;
399185029Spjd	kstat_named_t arcstat_l2_evict_lock_retry;
400185029Spjd	kstat_named_t arcstat_l2_evict_reading;
401185029Spjd	kstat_named_t arcstat_l2_free_on_write;
402274172Savg	kstat_named_t arcstat_l2_cdata_free_on_write;
403185029Spjd	kstat_named_t arcstat_l2_abort_lowmem;
404185029Spjd	kstat_named_t arcstat_l2_cksum_bad;
405185029Spjd	kstat_named_t arcstat_l2_io_error;
406185029Spjd	kstat_named_t arcstat_l2_size;
407251478Sdelphij	kstat_named_t arcstat_l2_asize;
408185029Spjd	kstat_named_t arcstat_l2_hdr_size;
409251478Sdelphij	kstat_named_t arcstat_l2_compress_successes;
410251478Sdelphij	kstat_named_t arcstat_l2_compress_zeros;
411251478Sdelphij	kstat_named_t arcstat_l2_compress_failures;
412205231Skmacy	kstat_named_t arcstat_l2_write_trylock_fail;
413205231Skmacy	kstat_named_t arcstat_l2_write_passed_headroom;
414205231Skmacy	kstat_named_t arcstat_l2_write_spa_mismatch;
415206796Spjd	kstat_named_t arcstat_l2_write_in_l2;
416205231Skmacy	kstat_named_t arcstat_l2_write_hdr_io_in_progress;
417205231Skmacy	kstat_named_t arcstat_l2_write_not_cacheable;
418205231Skmacy	kstat_named_t arcstat_l2_write_full;
419205231Skmacy	kstat_named_t arcstat_l2_write_buffer_iter;
420205231Skmacy	kstat_named_t arcstat_l2_write_pios;
421205231Skmacy	kstat_named_t arcstat_l2_write_buffer_bytes_scanned;
422205231Skmacy	kstat_named_t arcstat_l2_write_buffer_list_iter;
423205231Skmacy	kstat_named_t arcstat_l2_write_buffer_list_null_iter;
424242845Sdelphij	kstat_named_t arcstat_memory_throttle_count;
425242845Sdelphij	kstat_named_t arcstat_duplicate_buffers;
426242845Sdelphij	kstat_named_t arcstat_duplicate_buffers_size;
427242845Sdelphij	kstat_named_t arcstat_duplicate_reads;
428275748Sdelphij	kstat_named_t arcstat_meta_used;
429275748Sdelphij	kstat_named_t arcstat_meta_limit;
430275748Sdelphij	kstat_named_t arcstat_meta_max;
431275780Sdelphij	kstat_named_t arcstat_meta_min;
432168404Spjd} arc_stats_t;
433168404Spjd
434168404Spjdstatic arc_stats_t arc_stats = {
435168404Spjd	{ "hits",			KSTAT_DATA_UINT64 },
436168404Spjd	{ "misses",			KSTAT_DATA_UINT64 },
437168404Spjd	{ "demand_data_hits",		KSTAT_DATA_UINT64 },
438168404Spjd	{ "demand_data_misses",		KSTAT_DATA_UINT64 },
439168404Spjd	{ "demand_metadata_hits",	KSTAT_DATA_UINT64 },
440168404Spjd	{ "demand_metadata_misses",	KSTAT_DATA_UINT64 },
441168404Spjd	{ "prefetch_data_hits",		KSTAT_DATA_UINT64 },
442168404Spjd	{ "prefetch_data_misses",	KSTAT_DATA_UINT64 },
443168404Spjd	{ "prefetch_metadata_hits",	KSTAT_DATA_UINT64 },
444168404Spjd	{ "prefetch_metadata_misses",	KSTAT_DATA_UINT64 },
445168404Spjd	{ "mru_hits",			KSTAT_DATA_UINT64 },
446168404Spjd	{ "mru_ghost_hits",		KSTAT_DATA_UINT64 },
447168404Spjd	{ "mfu_hits",			KSTAT_DATA_UINT64 },
448168404Spjd	{ "mfu_ghost_hits",		KSTAT_DATA_UINT64 },
449205231Skmacy	{ "allocated",			KSTAT_DATA_UINT64 },
450168404Spjd	{ "deleted",			KSTAT_DATA_UINT64 },
451205231Skmacy	{ "stolen",			KSTAT_DATA_UINT64 },
452168404Spjd	{ "recycle_miss",		KSTAT_DATA_UINT64 },
453168404Spjd	{ "mutex_miss",			KSTAT_DATA_UINT64 },
454168404Spjd	{ "evict_skip",			KSTAT_DATA_UINT64 },
455208373Smm	{ "evict_l2_cached",		KSTAT_DATA_UINT64 },
456208373Smm	{ "evict_l2_eligible",		KSTAT_DATA_UINT64 },
457208373Smm	{ "evict_l2_ineligible",	KSTAT_DATA_UINT64 },
458168404Spjd	{ "hash_elements",		KSTAT_DATA_UINT64 },
459168404Spjd	{ "hash_elements_max",		KSTAT_DATA_UINT64 },
460168404Spjd	{ "hash_collisions",		KSTAT_DATA_UINT64 },
461168404Spjd	{ "hash_chains",		KSTAT_DATA_UINT64 },
462168404Spjd	{ "hash_chain_max",		KSTAT_DATA_UINT64 },
463168404Spjd	{ "p",				KSTAT_DATA_UINT64 },
464168404Spjd	{ "c",				KSTAT_DATA_UINT64 },
465168404Spjd	{ "c_min",			KSTAT_DATA_UINT64 },
466168404Spjd	{ "c_max",			KSTAT_DATA_UINT64 },
467185029Spjd	{ "size",			KSTAT_DATA_UINT64 },
468185029Spjd	{ "hdr_size",			KSTAT_DATA_UINT64 },
469208373Smm	{ "data_size",			KSTAT_DATA_UINT64 },
470208373Smm	{ "other_size",			KSTAT_DATA_UINT64 },
471185029Spjd	{ "l2_hits",			KSTAT_DATA_UINT64 },
472185029Spjd	{ "l2_misses",			KSTAT_DATA_UINT64 },
473185029Spjd	{ "l2_feeds",			KSTAT_DATA_UINT64 },
474185029Spjd	{ "l2_rw_clash",		KSTAT_DATA_UINT64 },
475208373Smm	{ "l2_read_bytes",		KSTAT_DATA_UINT64 },
476208373Smm	{ "l2_write_bytes",		KSTAT_DATA_UINT64 },
477185029Spjd	{ "l2_writes_sent",		KSTAT_DATA_UINT64 },
478185029Spjd	{ "l2_writes_done",		KSTAT_DATA_UINT64 },
479185029Spjd	{ "l2_writes_error",		KSTAT_DATA_UINT64 },
480185029Spjd	{ "l2_writes_hdr_miss",		KSTAT_DATA_UINT64 },
481185029Spjd	{ "l2_evict_lock_retry",	KSTAT_DATA_UINT64 },
482185029Spjd	{ "l2_evict_reading",		KSTAT_DATA_UINT64 },
483185029Spjd	{ "l2_free_on_write",		KSTAT_DATA_UINT64 },
484274172Savg	{ "l2_cdata_free_on_write",	KSTAT_DATA_UINT64 },
485185029Spjd	{ "l2_abort_lowmem",		KSTAT_DATA_UINT64 },
486185029Spjd	{ "l2_cksum_bad",		KSTAT_DATA_UINT64 },
487185029Spjd	{ "l2_io_error",		KSTAT_DATA_UINT64 },
488185029Spjd	{ "l2_size",			KSTAT_DATA_UINT64 },
489251478Sdelphij	{ "l2_asize",			KSTAT_DATA_UINT64 },
490185029Spjd	{ "l2_hdr_size",		KSTAT_DATA_UINT64 },
491251478Sdelphij	{ "l2_compress_successes",	KSTAT_DATA_UINT64 },
492251478Sdelphij	{ "l2_compress_zeros",		KSTAT_DATA_UINT64 },
493251478Sdelphij	{ "l2_compress_failures",	KSTAT_DATA_UINT64 },
494206796Spjd	{ "l2_write_trylock_fail",	KSTAT_DATA_UINT64 },
495206796Spjd	{ "l2_write_passed_headroom",	KSTAT_DATA_UINT64 },
496206796Spjd	{ "l2_write_spa_mismatch",	KSTAT_DATA_UINT64 },
497206796Spjd	{ "l2_write_in_l2",		KSTAT_DATA_UINT64 },
498206796Spjd	{ "l2_write_io_in_progress",	KSTAT_DATA_UINT64 },
499206796Spjd	{ "l2_write_not_cacheable",	KSTAT_DATA_UINT64 },
500206796Spjd	{ "l2_write_full",		KSTAT_DATA_UINT64 },
501206796Spjd	{ "l2_write_buffer_iter",	KSTAT_DATA_UINT64 },
502206796Spjd	{ "l2_write_pios",		KSTAT_DATA_UINT64 },
503206796Spjd	{ "l2_write_buffer_bytes_scanned", KSTAT_DATA_UINT64 },
504206796Spjd	{ "l2_write_buffer_list_iter",	KSTAT_DATA_UINT64 },
505242845Sdelphij	{ "l2_write_buffer_list_null_iter", KSTAT_DATA_UINT64 },
506242845Sdelphij	{ "memory_throttle_count",	KSTAT_DATA_UINT64 },
507242845Sdelphij	{ "duplicate_buffers",		KSTAT_DATA_UINT64 },
508242845Sdelphij	{ "duplicate_buffers_size",	KSTAT_DATA_UINT64 },
509275748Sdelphij	{ "duplicate_reads",		KSTAT_DATA_UINT64 },
510275748Sdelphij	{ "arc_meta_used",		KSTAT_DATA_UINT64 },
511275748Sdelphij	{ "arc_meta_limit",		KSTAT_DATA_UINT64 },
512275780Sdelphij	{ "arc_meta_max",		KSTAT_DATA_UINT64 },
513275780Sdelphij	{ "arc_meta_min",		KSTAT_DATA_UINT64 }
514168404Spjd};
515168404Spjd
516168404Spjd#define	ARCSTAT(stat)	(arc_stats.stat.value.ui64)
517168404Spjd
518168404Spjd#define	ARCSTAT_INCR(stat, val) \
519251631Sdelphij	atomic_add_64(&arc_stats.stat.value.ui64, (val))
520168404Spjd
521206796Spjd#define	ARCSTAT_BUMP(stat)	ARCSTAT_INCR(stat, 1)
522168404Spjd#define	ARCSTAT_BUMPDOWN(stat)	ARCSTAT_INCR(stat, -1)
523168404Spjd
524168404Spjd#define	ARCSTAT_MAX(stat, val) {					\
525168404Spjd	uint64_t m;							\
526168404Spjd	while ((val) > (m = arc_stats.stat.value.ui64) &&		\
527168404Spjd	    (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val))))	\
528168404Spjd		continue;						\
529168404Spjd}
530168404Spjd
531168404Spjd#define	ARCSTAT_MAXSTAT(stat) \
532168404Spjd	ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
533168404Spjd
534168404Spjd/*
535168404Spjd * We define a macro to allow ARC hits/misses to be easily broken down by
536168404Spjd * two separate conditions, giving a total of four different subtypes for
537168404Spjd * each of hits and misses (so eight statistics total).
538168404Spjd */
539168404Spjd#define	ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
540168404Spjd	if (cond1) {							\
541168404Spjd		if (cond2) {						\
542168404Spjd			ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
543168404Spjd		} else {						\
544168404Spjd			ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
545168404Spjd		}							\
546168404Spjd	} else {							\
547168404Spjd		if (cond2) {						\
548168404Spjd			ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
549168404Spjd		} else {						\
550168404Spjd			ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
551168404Spjd		}							\
552168404Spjd	}
553168404Spjd
554168404Spjdkstat_t			*arc_ksp;
555206796Spjdstatic arc_state_t	*arc_anon;
556168404Spjdstatic arc_state_t	*arc_mru;
557168404Spjdstatic arc_state_t	*arc_mru_ghost;
558168404Spjdstatic arc_state_t	*arc_mfu;
559168404Spjdstatic arc_state_t	*arc_mfu_ghost;
560185029Spjdstatic arc_state_t	*arc_l2c_only;
561168404Spjd
562168404Spjd/*
563168404Spjd * There are several ARC variables that are critical to export as kstats --
564168404Spjd * but we don't want to have to grovel around in the kstat whenever we wish to
565168404Spjd * manipulate them.  For these variables, we therefore define them to be in
566168404Spjd * terms of the statistic variable.  This assures that we are not introducing
567168404Spjd * the possibility of inconsistency by having shadow copies of the variables,
568168404Spjd * while still allowing the code to be readable.
569168404Spjd */
570168404Spjd#define	arc_size	ARCSTAT(arcstat_size)	/* actual total arc size */
571168404Spjd#define	arc_p		ARCSTAT(arcstat_p)	/* target size of MRU */
572168404Spjd#define	arc_c		ARCSTAT(arcstat_c)	/* target size of cache */
573168404Spjd#define	arc_c_min	ARCSTAT(arcstat_c_min)	/* min target cache size */
574168404Spjd#define	arc_c_max	ARCSTAT(arcstat_c_max)	/* max target cache size */
575275748Sdelphij#define	arc_meta_limit	ARCSTAT(arcstat_meta_limit) /* max size for metadata */
576275780Sdelphij#define	arc_meta_min	ARCSTAT(arcstat_meta_min) /* min size for metadata */
577275748Sdelphij#define	arc_meta_used	ARCSTAT(arcstat_meta_used) /* size of metadata */
578275748Sdelphij#define	arc_meta_max	ARCSTAT(arcstat_meta_max) /* max size of metadata */
579168404Spjd
580251478Sdelphij#define	L2ARC_IS_VALID_COMPRESS(_c_) \
581251478Sdelphij	((_c_) == ZIO_COMPRESS_LZ4 || (_c_) == ZIO_COMPRESS_EMPTY)
582251478Sdelphij
583168404Spjdstatic int		arc_no_grow;	/* Don't try to grow cache size */
584168404Spjdstatic uint64_t		arc_tempreserve;
585209962Smmstatic uint64_t		arc_loaned_bytes;
586168404Spjd
587185029Spjdtypedef struct l2arc_buf_hdr l2arc_buf_hdr_t;
588185029Spjd
589168404Spjdtypedef struct arc_callback arc_callback_t;
590168404Spjd
591168404Spjdstruct arc_callback {
592168404Spjd	void			*acb_private;
593168404Spjd	arc_done_func_t		*acb_done;
594168404Spjd	arc_buf_t		*acb_buf;
595168404Spjd	zio_t			*acb_zio_dummy;
596168404Spjd	arc_callback_t		*acb_next;
597168404Spjd};
598168404Spjd
599168404Spjdtypedef struct arc_write_callback arc_write_callback_t;
600168404Spjd
601168404Spjdstruct arc_write_callback {
602168404Spjd	void		*awcb_private;
603168404Spjd	arc_done_func_t	*awcb_ready;
604258632Savg	arc_done_func_t	*awcb_physdone;
605168404Spjd	arc_done_func_t	*awcb_done;
606168404Spjd	arc_buf_t	*awcb_buf;
607168404Spjd};
608168404Spjd
609168404Spjdstruct arc_buf_hdr {
610168404Spjd	/* protected by hash lock */
611168404Spjd	dva_t			b_dva;
612168404Spjd	uint64_t		b_birth;
613168404Spjd	uint64_t		b_cksum0;
614168404Spjd
615168404Spjd	kmutex_t		b_freeze_lock;
616168404Spjd	zio_cksum_t		*b_freeze_cksum;
617219089Spjd	void			*b_thawed;
618168404Spjd
619168404Spjd	arc_buf_hdr_t		*b_hash_next;
620168404Spjd	arc_buf_t		*b_buf;
621275811Sdelphij	arc_flags_t		b_flags;
622168404Spjd	uint32_t		b_datacnt;
623168404Spjd
624168404Spjd	arc_callback_t		*b_acb;
625168404Spjd	kcondvar_t		b_cv;
626168404Spjd
627168404Spjd	/* immutable */
628168404Spjd	arc_buf_contents_t	b_type;
629168404Spjd	uint64_t		b_size;
630209962Smm	uint64_t		b_spa;
631168404Spjd
632168404Spjd	/* protected by arc state mutex */
633168404Spjd	arc_state_t		*b_state;
634168404Spjd	list_node_t		b_arc_node;
635168404Spjd
636168404Spjd	/* updated atomically */
637168404Spjd	clock_t			b_arc_access;
638168404Spjd
639168404Spjd	/* self protecting */
640168404Spjd	refcount_t		b_refcnt;
641185029Spjd
642185029Spjd	l2arc_buf_hdr_t		*b_l2hdr;
643185029Spjd	list_node_t		b_l2node;
644168404Spjd};
645168404Spjd
646275748Sdelphij#ifdef _KERNEL
647275748Sdelphijstatic int
648275748Sdelphijsysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS)
649275748Sdelphij{
650275748Sdelphij	uint64_t val;
651275748Sdelphij	int err;
652275748Sdelphij
653275748Sdelphij	val = arc_meta_limit;
654275748Sdelphij	err = sysctl_handle_64(oidp, &val, 0, req);
655275748Sdelphij	if (err != 0 || req->newptr == NULL)
656275748Sdelphij		return (err);
657275748Sdelphij
658275748Sdelphij        if (val <= 0 || val > arc_c_max)
659275748Sdelphij		return (EINVAL);
660275748Sdelphij
661275748Sdelphij	arc_meta_limit = val;
662275748Sdelphij	return (0);
663275748Sdelphij}
664275748Sdelphij#endif
665275748Sdelphij
666168404Spjdstatic arc_buf_t *arc_eviction_list;
667168404Spjdstatic kmutex_t arc_eviction_mtx;
668168404Spjdstatic arc_buf_hdr_t arc_eviction_hdr;
669168404Spjd
670168404Spjd#define	GHOST_STATE(state)	\
671185029Spjd	((state) == arc_mru_ghost || (state) == arc_mfu_ghost ||	\
672185029Spjd	(state) == arc_l2c_only)
673168404Spjd
674275811Sdelphij#define	HDR_IN_HASH_TABLE(hdr)	((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
675275811Sdelphij#define	HDR_IO_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
676275811Sdelphij#define	HDR_IO_ERROR(hdr)	((hdr)->b_flags & ARC_FLAG_IO_ERROR)
677275811Sdelphij#define	HDR_PREFETCH(hdr)	((hdr)->b_flags & ARC_FLAG_PREFETCH)
678275811Sdelphij#define	HDR_FREED_IN_READ(hdr)	((hdr)->b_flags & ARC_FLAG_FREED_IN_READ)
679275811Sdelphij#define	HDR_BUF_AVAILABLE(hdr)	((hdr)->b_flags & ARC_FLAG_BUF_AVAILABLE)
680275811Sdelphij#define	HDR_FREE_IN_PROGRESS(hdr)	\
681275811Sdelphij	((hdr)->b_flags & ARC_FLAG_FREE_IN_PROGRESS)
682275811Sdelphij#define	HDR_L2CACHE(hdr)	((hdr)->b_flags & ARC_FLAG_L2CACHE)
683275811Sdelphij#define	HDR_L2_READING(hdr)	\
684275811Sdelphij	((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS &&	\
685275811Sdelphij	    (hdr)->b_l2hdr != NULL)
686275811Sdelphij#define	HDR_L2_WRITING(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITING)
687275811Sdelphij#define	HDR_L2_EVICTED(hdr)	((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
688275811Sdelphij#define	HDR_L2_WRITE_HEAD(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
689168404Spjd
690168404Spjd/*
691185029Spjd * Other sizes
692185029Spjd */
693185029Spjd
694185029Spjd#define	HDR_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
695185029Spjd#define	L2HDR_SIZE ((int64_t)sizeof (l2arc_buf_hdr_t))
696185029Spjd
697185029Spjd/*
698168404Spjd * Hash table routines
699168404Spjd */
700168404Spjd
701205253Skmacy#define	HT_LOCK_PAD	CACHE_LINE_SIZE
702168404Spjd
703168404Spjdstruct ht_lock {
704168404Spjd	kmutex_t	ht_lock;
705168404Spjd#ifdef _KERNEL
706168404Spjd	unsigned char	pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
707168404Spjd#endif
708168404Spjd};
709168404Spjd
710168404Spjd#define	BUF_LOCKS 256
711168404Spjdtypedef struct buf_hash_table {
712168404Spjd	uint64_t ht_mask;
713168404Spjd	arc_buf_hdr_t **ht_table;
714205264Skmacy	struct ht_lock ht_locks[BUF_LOCKS] __aligned(CACHE_LINE_SIZE);
715168404Spjd} buf_hash_table_t;
716168404Spjd
717168404Spjdstatic buf_hash_table_t buf_hash_table;
718168404Spjd
719168404Spjd#define	BUF_HASH_INDEX(spa, dva, birth) \
720168404Spjd	(buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
721168404Spjd#define	BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
722168404Spjd#define	BUF_HASH_LOCK(idx)	(&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
723219089Spjd#define	HDR_LOCK(hdr) \
724219089Spjd	(BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
725168404Spjd
726168404Spjduint64_t zfs_crc64_table[256];
727168404Spjd
728185029Spjd/*
729185029Spjd * Level 2 ARC
730185029Spjd */
731185029Spjd
732272707Savg#define	L2ARC_WRITE_SIZE	(8 * 1024 * 1024)	/* initial write max */
733251478Sdelphij#define	L2ARC_HEADROOM		2			/* num of writes */
734251478Sdelphij/*
735251478Sdelphij * If we discover during ARC scan any buffers to be compressed, we boost
736251478Sdelphij * our headroom for the next scanning cycle by this percentage multiple.
737251478Sdelphij */
738251478Sdelphij#define	L2ARC_HEADROOM_BOOST	200
739208373Smm#define	L2ARC_FEED_SECS		1		/* caching interval secs */
740208373Smm#define	L2ARC_FEED_MIN_MS	200		/* min caching interval ms */
741185029Spjd
742185029Spjd#define	l2arc_writes_sent	ARCSTAT(arcstat_l2_writes_sent)
743185029Spjd#define	l2arc_writes_done	ARCSTAT(arcstat_l2_writes_done)
744185029Spjd
745251631Sdelphij/* L2ARC Performance Tunables */
746185029Spjduint64_t l2arc_write_max = L2ARC_WRITE_SIZE;	/* default max write size */
747185029Spjduint64_t l2arc_write_boost = L2ARC_WRITE_SIZE;	/* extra write during warmup */
748185029Spjduint64_t l2arc_headroom = L2ARC_HEADROOM;	/* number of dev writes */
749251478Sdelphijuint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
750185029Spjduint64_t l2arc_feed_secs = L2ARC_FEED_SECS;	/* interval seconds */
751208373Smmuint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS;	/* min interval milliseconds */
752219089Spjdboolean_t l2arc_noprefetch = B_TRUE;		/* don't cache prefetch bufs */
753208373Smmboolean_t l2arc_feed_again = B_TRUE;		/* turbo warmup */
754208373Smmboolean_t l2arc_norw = B_TRUE;			/* no reads during writes */
755185029Spjd
756217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RW,
757205231Skmacy    &l2arc_write_max, 0, "max write size");
758217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RW,
759205231Skmacy    &l2arc_write_boost, 0, "extra write during warmup");
760217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RW,
761205231Skmacy    &l2arc_headroom, 0, "number of dev writes");
762217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RW,
763205231Skmacy    &l2arc_feed_secs, 0, "interval seconds");
764217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RW,
765208373Smm    &l2arc_feed_min_ms, 0, "min interval milliseconds");
766205231Skmacy
767205231SkmacySYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RW,
768205231Skmacy    &l2arc_noprefetch, 0, "don't cache prefetch bufs");
769208373SmmSYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RW,
770208373Smm    &l2arc_feed_again, 0, "turbo warmup");
771208373SmmSYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RW,
772208373Smm    &l2arc_norw, 0, "no reads during writes");
773205231Skmacy
774217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
775205231Skmacy    &ARC_anon.arcs_size, 0, "size of anonymous state");
776217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_metadata_lsize, CTLFLAG_RD,
777205231Skmacy    &ARC_anon.arcs_lsize[ARC_BUFC_METADATA], 0, "size of anonymous state");
778217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_data_lsize, CTLFLAG_RD,
779205231Skmacy    &ARC_anon.arcs_lsize[ARC_BUFC_DATA], 0, "size of anonymous state");
780205231Skmacy
781217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
782205231Skmacy    &ARC_mru.arcs_size, 0, "size of mru state");
783217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_metadata_lsize, CTLFLAG_RD,
784205231Skmacy    &ARC_mru.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mru state");
785217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_data_lsize, CTLFLAG_RD,
786205231Skmacy    &ARC_mru.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mru state");
787205231Skmacy
788217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
789205231Skmacy    &ARC_mru_ghost.arcs_size, 0, "size of mru ghost state");
790217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_lsize, CTLFLAG_RD,
791205231Skmacy    &ARC_mru_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
792205231Skmacy    "size of metadata in mru ghost state");
793217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_lsize, CTLFLAG_RD,
794205231Skmacy    &ARC_mru_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
795205231Skmacy    "size of data in mru ghost state");
796205231Skmacy
797217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
798205231Skmacy    &ARC_mfu.arcs_size, 0, "size of mfu state");
799217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_metadata_lsize, CTLFLAG_RD,
800205231Skmacy    &ARC_mfu.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mfu state");
801217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_data_lsize, CTLFLAG_RD,
802205231Skmacy    &ARC_mfu.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mfu state");
803205231Skmacy
804217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
805205231Skmacy    &ARC_mfu_ghost.arcs_size, 0, "size of mfu ghost state");
806217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_lsize, CTLFLAG_RD,
807205231Skmacy    &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
808205231Skmacy    "size of metadata in mfu ghost state");
809217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_lsize, CTLFLAG_RD,
810205231Skmacy    &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
811205231Skmacy    "size of data in mfu ghost state");
812205231Skmacy
813217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
814205231Skmacy    &ARC_l2c_only.arcs_size, 0, "size of mru state");
815205231Skmacy
816185029Spjd/*
817185029Spjd * L2ARC Internals
818185029Spjd */
819185029Spjdtypedef struct l2arc_dev {
820185029Spjd	vdev_t			*l2ad_vdev;	/* vdev */
821185029Spjd	spa_t			*l2ad_spa;	/* spa */
822185029Spjd	uint64_t		l2ad_hand;	/* next write location */
823185029Spjd	uint64_t		l2ad_start;	/* first addr on device */
824185029Spjd	uint64_t		l2ad_end;	/* last addr on device */
825185029Spjd	uint64_t		l2ad_evict;	/* last addr eviction reached */
826185029Spjd	boolean_t		l2ad_first;	/* first sweep through */
827208373Smm	boolean_t		l2ad_writing;	/* currently writing */
828185029Spjd	list_t			*l2ad_buflist;	/* buffer list */
829185029Spjd	list_node_t		l2ad_node;	/* device list node */
830185029Spjd} l2arc_dev_t;
831185029Spjd
832185029Spjdstatic list_t L2ARC_dev_list;			/* device list */
833185029Spjdstatic list_t *l2arc_dev_list;			/* device list pointer */
834185029Spjdstatic kmutex_t l2arc_dev_mtx;			/* device list mutex */
835185029Spjdstatic l2arc_dev_t *l2arc_dev_last;		/* last device used */
836185029Spjdstatic kmutex_t l2arc_buflist_mtx;		/* mutex for all buflists */
837185029Spjdstatic list_t L2ARC_free_on_write;		/* free after write buf list */
838185029Spjdstatic list_t *l2arc_free_on_write;		/* free after write list ptr */
839185029Spjdstatic kmutex_t l2arc_free_on_write_mtx;	/* mutex for list */
840185029Spjdstatic uint64_t l2arc_ndev;			/* number of devices */
841185029Spjd
842185029Spjdtypedef struct l2arc_read_callback {
843251478Sdelphij	arc_buf_t		*l2rcb_buf;		/* read buffer */
844251478Sdelphij	spa_t			*l2rcb_spa;		/* spa */
845251478Sdelphij	blkptr_t		l2rcb_bp;		/* original blkptr */
846268123Sdelphij	zbookmark_phys_t	l2rcb_zb;		/* original bookmark */
847251478Sdelphij	int			l2rcb_flags;		/* original flags */
848251478Sdelphij	enum zio_compress	l2rcb_compress;		/* applied compress */
849185029Spjd} l2arc_read_callback_t;
850185029Spjd
851185029Spjdtypedef struct l2arc_write_callback {
852185029Spjd	l2arc_dev_t	*l2wcb_dev;		/* device info */
853185029Spjd	arc_buf_hdr_t	*l2wcb_head;		/* head of write buflist */
854185029Spjd} l2arc_write_callback_t;
855185029Spjd
856185029Spjdstruct l2arc_buf_hdr {
857185029Spjd	/* protected by arc_buf_hdr  mutex */
858251478Sdelphij	l2arc_dev_t		*b_dev;		/* L2ARC device */
859251478Sdelphij	uint64_t		b_daddr;	/* disk address, offset byte */
860251478Sdelphij	/* compression applied to buffer data */
861251478Sdelphij	enum zio_compress	b_compress;
862251478Sdelphij	/* real alloc'd buffer size depending on b_compress applied */
863251478Sdelphij	int			b_asize;
864251478Sdelphij	/* temporary buffer holder for in-flight compressed data */
865251478Sdelphij	void			*b_tmp_cdata;
866185029Spjd};
867185029Spjd
868185029Spjdtypedef struct l2arc_data_free {
869185029Spjd	/* protected by l2arc_free_on_write_mtx */
870185029Spjd	void		*l2df_data;
871185029Spjd	size_t		l2df_size;
872185029Spjd	void		(*l2df_func)(void *, size_t);
873185029Spjd	list_node_t	l2df_list_node;
874185029Spjd} l2arc_data_free_t;
875185029Spjd
876185029Spjdstatic kmutex_t l2arc_feed_thr_lock;
877185029Spjdstatic kcondvar_t l2arc_feed_thr_cv;
878185029Spjdstatic uint8_t l2arc_thread_exit;
879185029Spjd
880275811Sdelphijstatic void arc_get_data_buf(arc_buf_t *);
881275811Sdelphijstatic void arc_access(arc_buf_hdr_t *, kmutex_t *);
882275811Sdelphijstatic int arc_evict_needed(arc_buf_contents_t);
883275811Sdelphijstatic void arc_evict_ghost(arc_state_t *, uint64_t, int64_t);
884275811Sdelphijstatic void arc_buf_watch(arc_buf_t *);
885275811Sdelphij
886275811Sdelphijstatic boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
887275811Sdelphijstatic void l2arc_read_done(zio_t *);
888185029Spjdstatic void l2arc_hdr_stat_add(void);
889185029Spjdstatic void l2arc_hdr_stat_remove(void);
890185029Spjd
891275811Sdelphijstatic boolean_t l2arc_compress_buf(l2arc_buf_hdr_t *);
892275811Sdelphijstatic void l2arc_decompress_zio(zio_t *, arc_buf_hdr_t *, enum zio_compress);
893275811Sdelphijstatic void l2arc_release_cdata_buf(arc_buf_hdr_t *);
894251478Sdelphij
895168404Spjdstatic uint64_t
896209962Smmbuf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
897168404Spjd{
898168404Spjd	uint8_t *vdva = (uint8_t *)dva;
899168404Spjd	uint64_t crc = -1ULL;
900168404Spjd	int i;
901168404Spjd
902168404Spjd	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
903168404Spjd
904168404Spjd	for (i = 0; i < sizeof (dva_t); i++)
905168404Spjd		crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
906168404Spjd
907209962Smm	crc ^= (spa>>8) ^ birth;
908168404Spjd
909168404Spjd	return (crc);
910168404Spjd}
911168404Spjd
912168404Spjd#define	BUF_EMPTY(buf)						\
913168404Spjd	((buf)->b_dva.dva_word[0] == 0 &&			\
914168404Spjd	(buf)->b_dva.dva_word[1] == 0 &&			\
915260150Sdelphij	(buf)->b_cksum0 == 0)
916168404Spjd
917168404Spjd#define	BUF_EQUAL(spa, dva, birth, buf)				\
918168404Spjd	((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) &&	\
919168404Spjd	((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) &&	\
920168404Spjd	((buf)->b_birth == birth) && ((buf)->b_spa == spa)
921168404Spjd
922219089Spjdstatic void
923219089Spjdbuf_discard_identity(arc_buf_hdr_t *hdr)
924219089Spjd{
925219089Spjd	hdr->b_dva.dva_word[0] = 0;
926219089Spjd	hdr->b_dva.dva_word[1] = 0;
927219089Spjd	hdr->b_birth = 0;
928219089Spjd	hdr->b_cksum0 = 0;
929219089Spjd}
930219089Spjd
931168404Spjdstatic arc_buf_hdr_t *
932268075Sdelphijbuf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
933168404Spjd{
934268075Sdelphij	const dva_t *dva = BP_IDENTITY(bp);
935268075Sdelphij	uint64_t birth = BP_PHYSICAL_BIRTH(bp);
936168404Spjd	uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
937168404Spjd	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
938275811Sdelphij	arc_buf_hdr_t *hdr;
939168404Spjd
940168404Spjd	mutex_enter(hash_lock);
941275811Sdelphij	for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
942275811Sdelphij	    hdr = hdr->b_hash_next) {
943275811Sdelphij		if (BUF_EQUAL(spa, dva, birth, hdr)) {
944168404Spjd			*lockp = hash_lock;
945275811Sdelphij			return (hdr);
946168404Spjd		}
947168404Spjd	}
948168404Spjd	mutex_exit(hash_lock);
949168404Spjd	*lockp = NULL;
950168404Spjd	return (NULL);
951168404Spjd}
952168404Spjd
953168404Spjd/*
954168404Spjd * Insert an entry into the hash table.  If there is already an element
955168404Spjd * equal to elem in the hash table, then the already existing element
956168404Spjd * will be returned and the new element will not be inserted.
957168404Spjd * Otherwise returns NULL.
958168404Spjd */
959168404Spjdstatic arc_buf_hdr_t *
960275811Sdelphijbuf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
961168404Spjd{
962275811Sdelphij	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
963168404Spjd	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
964275811Sdelphij	arc_buf_hdr_t *fhdr;
965168404Spjd	uint32_t i;
966168404Spjd
967275811Sdelphij	ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
968275811Sdelphij	ASSERT(hdr->b_birth != 0);
969275811Sdelphij	ASSERT(!HDR_IN_HASH_TABLE(hdr));
970168404Spjd	*lockp = hash_lock;
971168404Spjd	mutex_enter(hash_lock);
972275811Sdelphij	for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
973275811Sdelphij	    fhdr = fhdr->b_hash_next, i++) {
974275811Sdelphij		if (BUF_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
975275811Sdelphij			return (fhdr);
976168404Spjd	}
977168404Spjd
978275811Sdelphij	hdr->b_hash_next = buf_hash_table.ht_table[idx];
979275811Sdelphij	buf_hash_table.ht_table[idx] = hdr;
980275811Sdelphij	hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
981168404Spjd
982168404Spjd	/* collect some hash table performance data */
983168404Spjd	if (i > 0) {
984168404Spjd		ARCSTAT_BUMP(arcstat_hash_collisions);
985168404Spjd		if (i == 1)
986168404Spjd			ARCSTAT_BUMP(arcstat_hash_chains);
987168404Spjd
988168404Spjd		ARCSTAT_MAX(arcstat_hash_chain_max, i);
989168404Spjd	}
990168404Spjd
991168404Spjd	ARCSTAT_BUMP(arcstat_hash_elements);
992168404Spjd	ARCSTAT_MAXSTAT(arcstat_hash_elements);
993168404Spjd
994168404Spjd	return (NULL);
995168404Spjd}
996168404Spjd
997168404Spjdstatic void
998275811Sdelphijbuf_hash_remove(arc_buf_hdr_t *hdr)
999168404Spjd{
1000275811Sdelphij	arc_buf_hdr_t *fhdr, **hdrp;
1001275811Sdelphij	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1002168404Spjd
1003168404Spjd	ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
1004275811Sdelphij	ASSERT(HDR_IN_HASH_TABLE(hdr));
1005168404Spjd
1006275811Sdelphij	hdrp = &buf_hash_table.ht_table[idx];
1007275811Sdelphij	while ((fhdr = *hdrp) != hdr) {
1008275811Sdelphij		ASSERT(fhdr != NULL);
1009275811Sdelphij		hdrp = &fhdr->b_hash_next;
1010168404Spjd	}
1011275811Sdelphij	*hdrp = hdr->b_hash_next;
1012275811Sdelphij	hdr->b_hash_next = NULL;
1013275811Sdelphij	hdr->b_flags &= ~ARC_FLAG_IN_HASH_TABLE;
1014168404Spjd
1015168404Spjd	/* collect some hash table performance data */
1016168404Spjd	ARCSTAT_BUMPDOWN(arcstat_hash_elements);
1017168404Spjd
1018168404Spjd	if (buf_hash_table.ht_table[idx] &&
1019168404Spjd	    buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1020168404Spjd		ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1021168404Spjd}
1022168404Spjd
1023168404Spjd/*
1024168404Spjd * Global data structures and functions for the buf kmem cache.
1025168404Spjd */
1026168404Spjdstatic kmem_cache_t *hdr_cache;
1027168404Spjdstatic kmem_cache_t *buf_cache;
1028168404Spjd
1029168404Spjdstatic void
1030168404Spjdbuf_fini(void)
1031168404Spjd{
1032168404Spjd	int i;
1033168404Spjd
1034168404Spjd	kmem_free(buf_hash_table.ht_table,
1035168404Spjd	    (buf_hash_table.ht_mask + 1) * sizeof (void *));
1036168404Spjd	for (i = 0; i < BUF_LOCKS; i++)
1037168404Spjd		mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
1038168404Spjd	kmem_cache_destroy(hdr_cache);
1039168404Spjd	kmem_cache_destroy(buf_cache);
1040168404Spjd}
1041168404Spjd
1042168404Spjd/*
1043168404Spjd * Constructor callback - called when the cache is empty
1044168404Spjd * and a new buf is requested.
1045168404Spjd */
1046168404Spjd/* ARGSUSED */
1047168404Spjdstatic int
1048168404Spjdhdr_cons(void *vbuf, void *unused, int kmflag)
1049168404Spjd{
1050275811Sdelphij	arc_buf_hdr_t *hdr = vbuf;
1051168404Spjd
1052275811Sdelphij	bzero(hdr, sizeof (arc_buf_hdr_t));
1053275811Sdelphij	refcount_create(&hdr->b_refcnt);
1054275811Sdelphij	cv_init(&hdr->b_cv, NULL, CV_DEFAULT, NULL);
1055275811Sdelphij	mutex_init(&hdr->b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1056208373Smm	arc_space_consume(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
1057185029Spjd
1058168404Spjd	return (0);
1059168404Spjd}
1060168404Spjd
1061185029Spjd/* ARGSUSED */
1062185029Spjdstatic int
1063185029Spjdbuf_cons(void *vbuf, void *unused, int kmflag)
1064185029Spjd{
1065185029Spjd	arc_buf_t *buf = vbuf;
1066185029Spjd
1067185029Spjd	bzero(buf, sizeof (arc_buf_t));
1068219089Spjd	mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1069208373Smm	arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1070208373Smm
1071185029Spjd	return (0);
1072185029Spjd}
1073185029Spjd
1074168404Spjd/*
1075168404Spjd * Destructor callback - called when a cached buf is
1076168404Spjd * no longer required.
1077168404Spjd */
1078168404Spjd/* ARGSUSED */
1079168404Spjdstatic void
1080168404Spjdhdr_dest(void *vbuf, void *unused)
1081168404Spjd{
1082275811Sdelphij	arc_buf_hdr_t *hdr = vbuf;
1083168404Spjd
1084275811Sdelphij	ASSERT(BUF_EMPTY(hdr));
1085275811Sdelphij	refcount_destroy(&hdr->b_refcnt);
1086275811Sdelphij	cv_destroy(&hdr->b_cv);
1087275811Sdelphij	mutex_destroy(&hdr->b_freeze_lock);
1088208373Smm	arc_space_return(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
1089168404Spjd}
1090168404Spjd
1091185029Spjd/* ARGSUSED */
1092185029Spjdstatic void
1093185029Spjdbuf_dest(void *vbuf, void *unused)
1094185029Spjd{
1095185029Spjd	arc_buf_t *buf = vbuf;
1096185029Spjd
1097219089Spjd	mutex_destroy(&buf->b_evict_lock);
1098208373Smm	arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1099185029Spjd}
1100185029Spjd
1101168404Spjd/*
1102168404Spjd * Reclaim callback -- invoked when memory is low.
1103168404Spjd */
1104168404Spjd/* ARGSUSED */
1105168404Spjdstatic void
1106168404Spjdhdr_recl(void *unused)
1107168404Spjd{
1108168404Spjd	dprintf("hdr_recl called\n");
1109168404Spjd	/*
1110168404Spjd	 * umem calls the reclaim func when we destroy the buf cache,
1111168404Spjd	 * which is after we do arc_fini().
1112168404Spjd	 */
1113168404Spjd	if (!arc_dead)
1114168404Spjd		cv_signal(&arc_reclaim_thr_cv);
1115168404Spjd}
1116168404Spjd
1117168404Spjdstatic void
1118168404Spjdbuf_init(void)
1119168404Spjd{
1120168404Spjd	uint64_t *ct;
1121168404Spjd	uint64_t hsize = 1ULL << 12;
1122168404Spjd	int i, j;
1123168404Spjd
1124168404Spjd	/*
1125168404Spjd	 * The hash table is big enough to fill all of physical memory
1126269230Sdelphij	 * with an average block size of zfs_arc_average_blocksize (default 8K).
1127269230Sdelphij	 * By default, the table will take up
1128269230Sdelphij	 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1129168404Spjd	 */
1130269230Sdelphij	while (hsize * zfs_arc_average_blocksize < (uint64_t)physmem * PAGESIZE)
1131168404Spjd		hsize <<= 1;
1132168404Spjdretry:
1133168404Spjd	buf_hash_table.ht_mask = hsize - 1;
1134168404Spjd	buf_hash_table.ht_table =
1135168404Spjd	    kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1136168404Spjd	if (buf_hash_table.ht_table == NULL) {
1137168404Spjd		ASSERT(hsize > (1ULL << 8));
1138168404Spjd		hsize >>= 1;
1139168404Spjd		goto retry;
1140168404Spjd	}
1141168404Spjd
1142168404Spjd	hdr_cache = kmem_cache_create("arc_buf_hdr_t", sizeof (arc_buf_hdr_t),
1143168404Spjd	    0, hdr_cons, hdr_dest, hdr_recl, NULL, NULL, 0);
1144168404Spjd	buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1145185029Spjd	    0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1146168404Spjd
1147168404Spjd	for (i = 0; i < 256; i++)
1148168404Spjd		for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1149168404Spjd			*ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1150168404Spjd
1151168404Spjd	for (i = 0; i < BUF_LOCKS; i++) {
1152168404Spjd		mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1153168404Spjd		    NULL, MUTEX_DEFAULT, NULL);
1154168404Spjd	}
1155168404Spjd}
1156168404Spjd
1157168404Spjd#define	ARC_MINTIME	(hz>>4) /* 62 ms */
1158168404Spjd
1159168404Spjdstatic void
1160168404Spjdarc_cksum_verify(arc_buf_t *buf)
1161168404Spjd{
1162168404Spjd	zio_cksum_t zc;
1163168404Spjd
1164168404Spjd	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1165168404Spjd		return;
1166168404Spjd
1167168404Spjd	mutex_enter(&buf->b_hdr->b_freeze_lock);
1168168404Spjd	if (buf->b_hdr->b_freeze_cksum == NULL ||
1169275811Sdelphij	    (buf->b_hdr->b_flags & ARC_FLAG_IO_ERROR)) {
1170168404Spjd		mutex_exit(&buf->b_hdr->b_freeze_lock);
1171168404Spjd		return;
1172168404Spjd	}
1173168404Spjd	fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1174168404Spjd	if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
1175168404Spjd		panic("buffer modified while frozen!");
1176168404Spjd	mutex_exit(&buf->b_hdr->b_freeze_lock);
1177168404Spjd}
1178168404Spjd
1179185029Spjdstatic int
1180185029Spjdarc_cksum_equal(arc_buf_t *buf)
1181185029Spjd{
1182185029Spjd	zio_cksum_t zc;
1183185029Spjd	int equal;
1184185029Spjd
1185185029Spjd	mutex_enter(&buf->b_hdr->b_freeze_lock);
1186185029Spjd	fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1187185029Spjd	equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
1188185029Spjd	mutex_exit(&buf->b_hdr->b_freeze_lock);
1189185029Spjd
1190185029Spjd	return (equal);
1191185029Spjd}
1192185029Spjd
1193168404Spjdstatic void
1194185029Spjdarc_cksum_compute(arc_buf_t *buf, boolean_t force)
1195168404Spjd{
1196185029Spjd	if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
1197168404Spjd		return;
1198168404Spjd
1199168404Spjd	mutex_enter(&buf->b_hdr->b_freeze_lock);
1200168404Spjd	if (buf->b_hdr->b_freeze_cksum != NULL) {
1201168404Spjd		mutex_exit(&buf->b_hdr->b_freeze_lock);
1202168404Spjd		return;
1203168404Spjd	}
1204168404Spjd	buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
1205168404Spjd	fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
1206168404Spjd	    buf->b_hdr->b_freeze_cksum);
1207168404Spjd	mutex_exit(&buf->b_hdr->b_freeze_lock);
1208240133Smm#ifdef illumos
1209240133Smm	arc_buf_watch(buf);
1210277300Ssmh#endif
1211168404Spjd}
1212168404Spjd
1213240133Smm#ifdef illumos
1214240133Smm#ifndef _KERNEL
1215240133Smmtypedef struct procctl {
1216240133Smm	long cmd;
1217240133Smm	prwatch_t prwatch;
1218240133Smm} procctl_t;
1219240133Smm#endif
1220240133Smm
1221240133Smm/* ARGSUSED */
1222240133Smmstatic void
1223240133Smmarc_buf_unwatch(arc_buf_t *buf)
1224240133Smm{
1225240133Smm#ifndef _KERNEL
1226240133Smm	if (arc_watch) {
1227240133Smm		int result;
1228240133Smm		procctl_t ctl;
1229240133Smm		ctl.cmd = PCWATCH;
1230240133Smm		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1231240133Smm		ctl.prwatch.pr_size = 0;
1232240133Smm		ctl.prwatch.pr_wflags = 0;
1233240133Smm		result = write(arc_procfd, &ctl, sizeof (ctl));
1234240133Smm		ASSERT3U(result, ==, sizeof (ctl));
1235240133Smm	}
1236240133Smm#endif
1237240133Smm}
1238240133Smm
1239240133Smm/* ARGSUSED */
1240240133Smmstatic void
1241240133Smmarc_buf_watch(arc_buf_t *buf)
1242240133Smm{
1243240133Smm#ifndef _KERNEL
1244240133Smm	if (arc_watch) {
1245240133Smm		int result;
1246240133Smm		procctl_t ctl;
1247240133Smm		ctl.cmd = PCWATCH;
1248240133Smm		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1249240133Smm		ctl.prwatch.pr_size = buf->b_hdr->b_size;
1250240133Smm		ctl.prwatch.pr_wflags = WA_WRITE;
1251240133Smm		result = write(arc_procfd, &ctl, sizeof (ctl));
1252240133Smm		ASSERT3U(result, ==, sizeof (ctl));
1253240133Smm	}
1254240133Smm#endif
1255240133Smm}
1256240133Smm#endif /* illumos */
1257240133Smm
1258168404Spjdvoid
1259168404Spjdarc_buf_thaw(arc_buf_t *buf)
1260168404Spjd{
1261185029Spjd	if (zfs_flags & ZFS_DEBUG_MODIFY) {
1262185029Spjd		if (buf->b_hdr->b_state != arc_anon)
1263185029Spjd			panic("modifying non-anon buffer!");
1264275811Sdelphij		if (buf->b_hdr->b_flags & ARC_FLAG_IO_IN_PROGRESS)
1265185029Spjd			panic("modifying buffer while i/o in progress!");
1266185029Spjd		arc_cksum_verify(buf);
1267185029Spjd	}
1268168404Spjd
1269168404Spjd	mutex_enter(&buf->b_hdr->b_freeze_lock);
1270168404Spjd	if (buf->b_hdr->b_freeze_cksum != NULL) {
1271168404Spjd		kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1272168404Spjd		buf->b_hdr->b_freeze_cksum = NULL;
1273168404Spjd	}
1274219089Spjd
1275219089Spjd	if (zfs_flags & ZFS_DEBUG_MODIFY) {
1276219089Spjd		if (buf->b_hdr->b_thawed)
1277219089Spjd			kmem_free(buf->b_hdr->b_thawed, 1);
1278219089Spjd		buf->b_hdr->b_thawed = kmem_alloc(1, KM_SLEEP);
1279219089Spjd	}
1280219089Spjd
1281168404Spjd	mutex_exit(&buf->b_hdr->b_freeze_lock);
1282240133Smm
1283240133Smm#ifdef illumos
1284240133Smm	arc_buf_unwatch(buf);
1285277300Ssmh#endif
1286168404Spjd}
1287168404Spjd
1288168404Spjdvoid
1289168404Spjdarc_buf_freeze(arc_buf_t *buf)
1290168404Spjd{
1291219089Spjd	kmutex_t *hash_lock;
1292219089Spjd
1293168404Spjd	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1294168404Spjd		return;
1295168404Spjd
1296219089Spjd	hash_lock = HDR_LOCK(buf->b_hdr);
1297219089Spjd	mutex_enter(hash_lock);
1298219089Spjd
1299168404Spjd	ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
1300168404Spjd	    buf->b_hdr->b_state == arc_anon);
1301185029Spjd	arc_cksum_compute(buf, B_FALSE);
1302219089Spjd	mutex_exit(hash_lock);
1303240133Smm
1304168404Spjd}
1305168404Spjd
1306168404Spjdstatic void
1307275811Sdelphijget_buf_info(arc_buf_hdr_t *hdr, arc_state_t *state, list_t **list, kmutex_t **lock)
1308205231Skmacy{
1309275811Sdelphij	uint64_t buf_hashid = buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1310205231Skmacy
1311275811Sdelphij	if (hdr->b_type == ARC_BUFC_METADATA)
1312206796Spjd		buf_hashid &= (ARC_BUFC_NUMMETADATALISTS - 1);
1313205231Skmacy	else {
1314206796Spjd		buf_hashid &= (ARC_BUFC_NUMDATALISTS - 1);
1315205231Skmacy		buf_hashid += ARC_BUFC_NUMMETADATALISTS;
1316205231Skmacy	}
1317205231Skmacy
1318205231Skmacy	*list = &state->arcs_lists[buf_hashid];
1319205231Skmacy	*lock = ARCS_LOCK(state, buf_hashid);
1320205231Skmacy}
1321205231Skmacy
1322205231Skmacy
1323205231Skmacystatic void
1324275811Sdelphijadd_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1325168404Spjd{
1326168404Spjd	ASSERT(MUTEX_HELD(hash_lock));
1327168404Spjd
1328275811Sdelphij	if ((refcount_add(&hdr->b_refcnt, tag) == 1) &&
1329275811Sdelphij	    (hdr->b_state != arc_anon)) {
1330275811Sdelphij		uint64_t delta = hdr->b_size * hdr->b_datacnt;
1331275811Sdelphij		uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
1332205231Skmacy		list_t *list;
1333205231Skmacy		kmutex_t *lock;
1334168404Spjd
1335275811Sdelphij		get_buf_info(hdr, hdr->b_state, &list, &lock);
1336205231Skmacy		ASSERT(!MUTEX_HELD(lock));
1337205231Skmacy		mutex_enter(lock);
1338275811Sdelphij		ASSERT(list_link_active(&hdr->b_arc_node));
1339275811Sdelphij		list_remove(list, hdr);
1340275811Sdelphij		if (GHOST_STATE(hdr->b_state)) {
1341275811Sdelphij			ASSERT0(hdr->b_datacnt);
1342275811Sdelphij			ASSERT3P(hdr->b_buf, ==, NULL);
1343275811Sdelphij			delta = hdr->b_size;
1344168404Spjd		}
1345168404Spjd		ASSERT(delta > 0);
1346185029Spjd		ASSERT3U(*size, >=, delta);
1347185029Spjd		atomic_add_64(size, -delta);
1348206794Spjd		mutex_exit(lock);
1349185029Spjd		/* remove the prefetch flag if we get a reference */
1350275811Sdelphij		if (hdr->b_flags & ARC_FLAG_PREFETCH)
1351275811Sdelphij			hdr->b_flags &= ~ARC_FLAG_PREFETCH;
1352168404Spjd	}
1353168404Spjd}
1354168404Spjd
1355168404Spjdstatic int
1356275811Sdelphijremove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1357168404Spjd{
1358168404Spjd	int cnt;
1359275811Sdelphij	arc_state_t *state = hdr->b_state;
1360168404Spjd
1361168404Spjd	ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
1362168404Spjd	ASSERT(!GHOST_STATE(state));
1363168404Spjd
1364275811Sdelphij	if (((cnt = refcount_remove(&hdr->b_refcnt, tag)) == 0) &&
1365168404Spjd	    (state != arc_anon)) {
1366275811Sdelphij		uint64_t *size = &state->arcs_lsize[hdr->b_type];
1367205231Skmacy		list_t *list;
1368205231Skmacy		kmutex_t *lock;
1369185029Spjd
1370275811Sdelphij		get_buf_info(hdr, state, &list, &lock);
1371205231Skmacy		ASSERT(!MUTEX_HELD(lock));
1372205231Skmacy		mutex_enter(lock);
1373275811Sdelphij		ASSERT(!list_link_active(&hdr->b_arc_node));
1374275811Sdelphij		list_insert_head(list, hdr);
1375275811Sdelphij		ASSERT(hdr->b_datacnt > 0);
1376275811Sdelphij		atomic_add_64(size, hdr->b_size * hdr->b_datacnt);
1377206794Spjd		mutex_exit(lock);
1378168404Spjd	}
1379168404Spjd	return (cnt);
1380168404Spjd}
1381168404Spjd
1382168404Spjd/*
1383168404Spjd * Move the supplied buffer to the indicated state.  The mutex
1384168404Spjd * for the buffer must be held by the caller.
1385168404Spjd */
1386168404Spjdstatic void
1387275811Sdelphijarc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
1388275811Sdelphij    kmutex_t *hash_lock)
1389168404Spjd{
1390275811Sdelphij	arc_state_t *old_state = hdr->b_state;
1391275811Sdelphij	int64_t refcnt = refcount_count(&hdr->b_refcnt);
1392168404Spjd	uint64_t from_delta, to_delta;
1393205231Skmacy	list_t *list;
1394205231Skmacy	kmutex_t *lock;
1395168404Spjd
1396168404Spjd	ASSERT(MUTEX_HELD(hash_lock));
1397258632Savg	ASSERT3P(new_state, !=, old_state);
1398275811Sdelphij	ASSERT(refcnt == 0 || hdr->b_datacnt > 0);
1399275811Sdelphij	ASSERT(hdr->b_datacnt == 0 || !GHOST_STATE(new_state));
1400275811Sdelphij	ASSERT(hdr->b_datacnt <= 1 || old_state != arc_anon);
1401168404Spjd
1402275811Sdelphij	from_delta = to_delta = hdr->b_datacnt * hdr->b_size;
1403168404Spjd
1404168404Spjd	/*
1405168404Spjd	 * If this buffer is evictable, transfer it from the
1406168404Spjd	 * old state list to the new state list.
1407168404Spjd	 */
1408168404Spjd	if (refcnt == 0) {
1409168404Spjd		if (old_state != arc_anon) {
1410205231Skmacy			int use_mutex;
1411275811Sdelphij			uint64_t *size = &old_state->arcs_lsize[hdr->b_type];
1412168404Spjd
1413275811Sdelphij			get_buf_info(hdr, old_state, &list, &lock);
1414205231Skmacy			use_mutex = !MUTEX_HELD(lock);
1415168404Spjd			if (use_mutex)
1416205231Skmacy				mutex_enter(lock);
1417168404Spjd
1418275811Sdelphij			ASSERT(list_link_active(&hdr->b_arc_node));
1419275811Sdelphij			list_remove(list, hdr);
1420168404Spjd
1421168404Spjd			/*
1422168404Spjd			 * If prefetching out of the ghost cache,
1423219089Spjd			 * we will have a non-zero datacnt.
1424168404Spjd			 */
1425275811Sdelphij			if (GHOST_STATE(old_state) && hdr->b_datacnt == 0) {
1426168404Spjd				/* ghost elements have a ghost size */
1427275811Sdelphij				ASSERT(hdr->b_buf == NULL);
1428275811Sdelphij				from_delta = hdr->b_size;
1429168404Spjd			}
1430185029Spjd			ASSERT3U(*size, >=, from_delta);
1431185029Spjd			atomic_add_64(size, -from_delta);
1432168404Spjd
1433168404Spjd			if (use_mutex)
1434205231Skmacy				mutex_exit(lock);
1435168404Spjd		}
1436168404Spjd		if (new_state != arc_anon) {
1437206796Spjd			int use_mutex;
1438275811Sdelphij			uint64_t *size = &new_state->arcs_lsize[hdr->b_type];
1439168404Spjd
1440275811Sdelphij			get_buf_info(hdr, new_state, &list, &lock);
1441205231Skmacy			use_mutex = !MUTEX_HELD(lock);
1442168404Spjd			if (use_mutex)
1443205231Skmacy				mutex_enter(lock);
1444168404Spjd
1445275811Sdelphij			list_insert_head(list, hdr);
1446168404Spjd
1447168404Spjd			/* ghost elements have a ghost size */
1448168404Spjd			if (GHOST_STATE(new_state)) {
1449275811Sdelphij				ASSERT(hdr->b_datacnt == 0);
1450275811Sdelphij				ASSERT(hdr->b_buf == NULL);
1451275811Sdelphij				to_delta = hdr->b_size;
1452168404Spjd			}
1453185029Spjd			atomic_add_64(size, to_delta);
1454168404Spjd
1455168404Spjd			if (use_mutex)
1456205231Skmacy				mutex_exit(lock);
1457168404Spjd		}
1458168404Spjd	}
1459168404Spjd
1460275811Sdelphij	ASSERT(!BUF_EMPTY(hdr));
1461275811Sdelphij	if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
1462275811Sdelphij		buf_hash_remove(hdr);
1463168404Spjd
1464168404Spjd	/* adjust state sizes */
1465168404Spjd	if (to_delta)
1466168404Spjd		atomic_add_64(&new_state->arcs_size, to_delta);
1467168404Spjd	if (from_delta) {
1468168404Spjd		ASSERT3U(old_state->arcs_size, >=, from_delta);
1469168404Spjd		atomic_add_64(&old_state->arcs_size, -from_delta);
1470168404Spjd	}
1471275811Sdelphij	hdr->b_state = new_state;
1472185029Spjd
1473185029Spjd	/* adjust l2arc hdr stats */
1474185029Spjd	if (new_state == arc_l2c_only)
1475185029Spjd		l2arc_hdr_stat_add();
1476185029Spjd	else if (old_state == arc_l2c_only)
1477185029Spjd		l2arc_hdr_stat_remove();
1478168404Spjd}
1479168404Spjd
1480185029Spjdvoid
1481208373Smmarc_space_consume(uint64_t space, arc_space_type_t type)
1482185029Spjd{
1483208373Smm	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1484208373Smm
1485208373Smm	switch (type) {
1486208373Smm	case ARC_SPACE_DATA:
1487208373Smm		ARCSTAT_INCR(arcstat_data_size, space);
1488208373Smm		break;
1489208373Smm	case ARC_SPACE_OTHER:
1490208373Smm		ARCSTAT_INCR(arcstat_other_size, space);
1491208373Smm		break;
1492208373Smm	case ARC_SPACE_HDRS:
1493208373Smm		ARCSTAT_INCR(arcstat_hdr_size, space);
1494208373Smm		break;
1495208373Smm	case ARC_SPACE_L2HDRS:
1496208373Smm		ARCSTAT_INCR(arcstat_l2_hdr_size, space);
1497208373Smm		break;
1498208373Smm	}
1499208373Smm
1500275748Sdelphij	ARCSTAT_INCR(arcstat_meta_used, space);
1501185029Spjd	atomic_add_64(&arc_size, space);
1502185029Spjd}
1503185029Spjd
1504185029Spjdvoid
1505208373Smmarc_space_return(uint64_t space, arc_space_type_t type)
1506185029Spjd{
1507208373Smm	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1508208373Smm
1509208373Smm	switch (type) {
1510208373Smm	case ARC_SPACE_DATA:
1511208373Smm		ARCSTAT_INCR(arcstat_data_size, -space);
1512208373Smm		break;
1513208373Smm	case ARC_SPACE_OTHER:
1514208373Smm		ARCSTAT_INCR(arcstat_other_size, -space);
1515208373Smm		break;
1516208373Smm	case ARC_SPACE_HDRS:
1517208373Smm		ARCSTAT_INCR(arcstat_hdr_size, -space);
1518208373Smm		break;
1519208373Smm	case ARC_SPACE_L2HDRS:
1520208373Smm		ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
1521208373Smm		break;
1522208373Smm	}
1523208373Smm
1524185029Spjd	ASSERT(arc_meta_used >= space);
1525185029Spjd	if (arc_meta_max < arc_meta_used)
1526185029Spjd		arc_meta_max = arc_meta_used;
1527275748Sdelphij	ARCSTAT_INCR(arcstat_meta_used, -space);
1528185029Spjd	ASSERT(arc_size >= space);
1529185029Spjd	atomic_add_64(&arc_size, -space);
1530185029Spjd}
1531185029Spjd
1532168404Spjdarc_buf_t *
1533168404Spjdarc_buf_alloc(spa_t *spa, int size, void *tag, arc_buf_contents_t type)
1534168404Spjd{
1535168404Spjd	arc_buf_hdr_t *hdr;
1536168404Spjd	arc_buf_t *buf;
1537168404Spjd
1538168404Spjd	ASSERT3U(size, >, 0);
1539185029Spjd	hdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
1540168404Spjd	ASSERT(BUF_EMPTY(hdr));
1541168404Spjd	hdr->b_size = size;
1542168404Spjd	hdr->b_type = type;
1543228103Smm	hdr->b_spa = spa_load_guid(spa);
1544168404Spjd	hdr->b_state = arc_anon;
1545168404Spjd	hdr->b_arc_access = 0;
1546185029Spjd	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1547168404Spjd	buf->b_hdr = hdr;
1548168404Spjd	buf->b_data = NULL;
1549168404Spjd	buf->b_efunc = NULL;
1550168404Spjd	buf->b_private = NULL;
1551168404Spjd	buf->b_next = NULL;
1552168404Spjd	hdr->b_buf = buf;
1553168404Spjd	arc_get_data_buf(buf);
1554168404Spjd	hdr->b_datacnt = 1;
1555168404Spjd	hdr->b_flags = 0;
1556168404Spjd	ASSERT(refcount_is_zero(&hdr->b_refcnt));
1557168404Spjd	(void) refcount_add(&hdr->b_refcnt, tag);
1558168404Spjd
1559168404Spjd	return (buf);
1560168404Spjd}
1561168404Spjd
1562209962Smmstatic char *arc_onloan_tag = "onloan";
1563209962Smm
1564209962Smm/*
1565209962Smm * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
1566209962Smm * flight data by arc_tempreserve_space() until they are "returned". Loaned
1567209962Smm * buffers must be returned to the arc before they can be used by the DMU or
1568209962Smm * freed.
1569209962Smm */
1570209962Smmarc_buf_t *
1571209962Smmarc_loan_buf(spa_t *spa, int size)
1572209962Smm{
1573209962Smm	arc_buf_t *buf;
1574209962Smm
1575209962Smm	buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
1576209962Smm
1577209962Smm	atomic_add_64(&arc_loaned_bytes, size);
1578209962Smm	return (buf);
1579209962Smm}
1580209962Smm
1581209962Smm/*
1582209962Smm * Return a loaned arc buffer to the arc.
1583209962Smm */
1584209962Smmvoid
1585209962Smmarc_return_buf(arc_buf_t *buf, void *tag)
1586209962Smm{
1587209962Smm	arc_buf_hdr_t *hdr = buf->b_hdr;
1588209962Smm
1589209962Smm	ASSERT(buf->b_data != NULL);
1590219089Spjd	(void) refcount_add(&hdr->b_refcnt, tag);
1591219089Spjd	(void) refcount_remove(&hdr->b_refcnt, arc_onloan_tag);
1592209962Smm
1593209962Smm	atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
1594209962Smm}
1595209962Smm
1596219089Spjd/* Detach an arc_buf from a dbuf (tag) */
1597219089Spjdvoid
1598219089Spjdarc_loan_inuse_buf(arc_buf_t *buf, void *tag)
1599219089Spjd{
1600219089Spjd	arc_buf_hdr_t *hdr;
1601219089Spjd
1602219089Spjd	ASSERT(buf->b_data != NULL);
1603219089Spjd	hdr = buf->b_hdr;
1604219089Spjd	(void) refcount_add(&hdr->b_refcnt, arc_onloan_tag);
1605219089Spjd	(void) refcount_remove(&hdr->b_refcnt, tag);
1606219089Spjd	buf->b_efunc = NULL;
1607219089Spjd	buf->b_private = NULL;
1608219089Spjd
1609219089Spjd	atomic_add_64(&arc_loaned_bytes, hdr->b_size);
1610219089Spjd}
1611219089Spjd
1612168404Spjdstatic arc_buf_t *
1613168404Spjdarc_buf_clone(arc_buf_t *from)
1614168404Spjd{
1615168404Spjd	arc_buf_t *buf;
1616168404Spjd	arc_buf_hdr_t *hdr = from->b_hdr;
1617168404Spjd	uint64_t size = hdr->b_size;
1618168404Spjd
1619219089Spjd	ASSERT(hdr->b_state != arc_anon);
1620219089Spjd
1621185029Spjd	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1622168404Spjd	buf->b_hdr = hdr;
1623168404Spjd	buf->b_data = NULL;
1624168404Spjd	buf->b_efunc = NULL;
1625168404Spjd	buf->b_private = NULL;
1626168404Spjd	buf->b_next = hdr->b_buf;
1627168404Spjd	hdr->b_buf = buf;
1628168404Spjd	arc_get_data_buf(buf);
1629168404Spjd	bcopy(from->b_data, buf->b_data, size);
1630242845Sdelphij
1631242845Sdelphij	/*
1632242845Sdelphij	 * This buffer already exists in the arc so create a duplicate
1633242845Sdelphij	 * copy for the caller.  If the buffer is associated with user data
1634242845Sdelphij	 * then track the size and number of duplicates.  These stats will be
1635242845Sdelphij	 * updated as duplicate buffers are created and destroyed.
1636242845Sdelphij	 */
1637242845Sdelphij	if (hdr->b_type == ARC_BUFC_DATA) {
1638242845Sdelphij		ARCSTAT_BUMP(arcstat_duplicate_buffers);
1639242845Sdelphij		ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
1640242845Sdelphij	}
1641168404Spjd	hdr->b_datacnt += 1;
1642168404Spjd	return (buf);
1643168404Spjd}
1644168404Spjd
1645168404Spjdvoid
1646168404Spjdarc_buf_add_ref(arc_buf_t *buf, void* tag)
1647168404Spjd{
1648168404Spjd	arc_buf_hdr_t *hdr;
1649168404Spjd	kmutex_t *hash_lock;
1650168404Spjd
1651168404Spjd	/*
1652185029Spjd	 * Check to see if this buffer is evicted.  Callers
1653185029Spjd	 * must verify b_data != NULL to know if the add_ref
1654185029Spjd	 * was successful.
1655168404Spjd	 */
1656219089Spjd	mutex_enter(&buf->b_evict_lock);
1657185029Spjd	if (buf->b_data == NULL) {
1658219089Spjd		mutex_exit(&buf->b_evict_lock);
1659168404Spjd		return;
1660168404Spjd	}
1661219089Spjd	hash_lock = HDR_LOCK(buf->b_hdr);
1662219089Spjd	mutex_enter(hash_lock);
1663185029Spjd	hdr = buf->b_hdr;
1664219089Spjd	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1665219089Spjd	mutex_exit(&buf->b_evict_lock);
1666168404Spjd
1667168404Spjd	ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
1668168404Spjd	add_reference(hdr, hash_lock, tag);
1669208373Smm	DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
1670168404Spjd	arc_access(hdr, hash_lock);
1671168404Spjd	mutex_exit(hash_lock);
1672168404Spjd	ARCSTAT_BUMP(arcstat_hits);
1673275811Sdelphij	ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_FLAG_PREFETCH),
1674168404Spjd	    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
1675168404Spjd	    data, metadata, hits);
1676168404Spjd}
1677168404Spjd
1678274172Savgstatic void
1679274172Savgarc_buf_free_on_write(void *data, size_t size,
1680274172Savg    void (*free_func)(void *, size_t))
1681274172Savg{
1682274172Savg	l2arc_data_free_t *df;
1683274172Savg
1684274172Savg	df = kmem_alloc(sizeof (l2arc_data_free_t), KM_SLEEP);
1685274172Savg	df->l2df_data = data;
1686274172Savg	df->l2df_size = size;
1687274172Savg	df->l2df_func = free_func;
1688274172Savg	mutex_enter(&l2arc_free_on_write_mtx);
1689274172Savg	list_insert_head(l2arc_free_on_write, df);
1690274172Savg	mutex_exit(&l2arc_free_on_write_mtx);
1691274172Savg}
1692274172Savg
1693185029Spjd/*
1694185029Spjd * Free the arc data buffer.  If it is an l2arc write in progress,
1695185029Spjd * the buffer is placed on l2arc_free_on_write to be freed later.
1696185029Spjd */
1697168404Spjdstatic void
1698240133Smmarc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
1699185029Spjd{
1700240133Smm	arc_buf_hdr_t *hdr = buf->b_hdr;
1701240133Smm
1702185029Spjd	if (HDR_L2_WRITING(hdr)) {
1703274172Savg		arc_buf_free_on_write(buf->b_data, hdr->b_size, free_func);
1704185029Spjd		ARCSTAT_BUMP(arcstat_l2_free_on_write);
1705185029Spjd	} else {
1706240133Smm		free_func(buf->b_data, hdr->b_size);
1707185029Spjd	}
1708185029Spjd}
1709185029Spjd
1710268858Sdelphij/*
1711268858Sdelphij * Free up buf->b_data and if 'remove' is set, then pull the
1712268858Sdelphij * arc_buf_t off of the the arc_buf_hdr_t's list and free it.
1713268858Sdelphij */
1714185029Spjdstatic void
1715274172Savgarc_buf_l2_cdata_free(arc_buf_hdr_t *hdr)
1716274172Savg{
1717274172Savg	l2arc_buf_hdr_t *l2hdr = hdr->b_l2hdr;
1718274172Savg
1719274172Savg	ASSERT(MUTEX_HELD(&l2arc_buflist_mtx));
1720274172Savg
1721274172Savg	if (l2hdr->b_tmp_cdata == NULL)
1722274172Savg		return;
1723274172Savg
1724274172Savg	ASSERT(HDR_L2_WRITING(hdr));
1725274172Savg	arc_buf_free_on_write(l2hdr->b_tmp_cdata, hdr->b_size,
1726274172Savg	    zio_data_buf_free);
1727274172Savg	ARCSTAT_BUMP(arcstat_l2_cdata_free_on_write);
1728274172Savg	l2hdr->b_tmp_cdata = NULL;
1729274172Savg}
1730274172Savg
1731274172Savgstatic void
1732268858Sdelphijarc_buf_destroy(arc_buf_t *buf, boolean_t recycle, boolean_t remove)
1733168404Spjd{
1734168404Spjd	arc_buf_t **bufp;
1735168404Spjd
1736168404Spjd	/* free up data associated with the buf */
1737168404Spjd	if (buf->b_data) {
1738168404Spjd		arc_state_t *state = buf->b_hdr->b_state;
1739168404Spjd		uint64_t size = buf->b_hdr->b_size;
1740168404Spjd		arc_buf_contents_t type = buf->b_hdr->b_type;
1741168404Spjd
1742168404Spjd		arc_cksum_verify(buf);
1743240133Smm#ifdef illumos
1744240133Smm		arc_buf_unwatch(buf);
1745277300Ssmh#endif
1746219089Spjd
1747168404Spjd		if (!recycle) {
1748168404Spjd			if (type == ARC_BUFC_METADATA) {
1749240133Smm				arc_buf_data_free(buf, zio_buf_free);
1750208373Smm				arc_space_return(size, ARC_SPACE_DATA);
1751168404Spjd			} else {
1752168404Spjd				ASSERT(type == ARC_BUFC_DATA);
1753240133Smm				arc_buf_data_free(buf, zio_data_buf_free);
1754208373Smm				ARCSTAT_INCR(arcstat_data_size, -size);
1755185029Spjd				atomic_add_64(&arc_size, -size);
1756168404Spjd			}
1757168404Spjd		}
1758168404Spjd		if (list_link_active(&buf->b_hdr->b_arc_node)) {
1759185029Spjd			uint64_t *cnt = &state->arcs_lsize[type];
1760185029Spjd
1761168404Spjd			ASSERT(refcount_is_zero(&buf->b_hdr->b_refcnt));
1762168404Spjd			ASSERT(state != arc_anon);
1763185029Spjd
1764185029Spjd			ASSERT3U(*cnt, >=, size);
1765185029Spjd			atomic_add_64(cnt, -size);
1766168404Spjd		}
1767168404Spjd		ASSERT3U(state->arcs_size, >=, size);
1768168404Spjd		atomic_add_64(&state->arcs_size, -size);
1769168404Spjd		buf->b_data = NULL;
1770242845Sdelphij
1771242845Sdelphij		/*
1772242845Sdelphij		 * If we're destroying a duplicate buffer make sure
1773242845Sdelphij		 * that the appropriate statistics are updated.
1774242845Sdelphij		 */
1775242845Sdelphij		if (buf->b_hdr->b_datacnt > 1 &&
1776242845Sdelphij		    buf->b_hdr->b_type == ARC_BUFC_DATA) {
1777242845Sdelphij			ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
1778242845Sdelphij			ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
1779242845Sdelphij		}
1780168404Spjd		ASSERT(buf->b_hdr->b_datacnt > 0);
1781168404Spjd		buf->b_hdr->b_datacnt -= 1;
1782168404Spjd	}
1783168404Spjd
1784168404Spjd	/* only remove the buf if requested */
1785268858Sdelphij	if (!remove)
1786168404Spjd		return;
1787168404Spjd
1788168404Spjd	/* remove the buf from the hdr list */
1789168404Spjd	for (bufp = &buf->b_hdr->b_buf; *bufp != buf; bufp = &(*bufp)->b_next)
1790168404Spjd		continue;
1791168404Spjd	*bufp = buf->b_next;
1792219089Spjd	buf->b_next = NULL;
1793168404Spjd
1794168404Spjd	ASSERT(buf->b_efunc == NULL);
1795168404Spjd
1796168404Spjd	/* clean up the buf */
1797168404Spjd	buf->b_hdr = NULL;
1798168404Spjd	kmem_cache_free(buf_cache, buf);
1799168404Spjd}
1800168404Spjd
1801168404Spjdstatic void
1802168404Spjdarc_hdr_destroy(arc_buf_hdr_t *hdr)
1803168404Spjd{
1804168404Spjd	ASSERT(refcount_is_zero(&hdr->b_refcnt));
1805168404Spjd	ASSERT3P(hdr->b_state, ==, arc_anon);
1806168404Spjd	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1807219089Spjd	l2arc_buf_hdr_t *l2hdr = hdr->b_l2hdr;
1808168404Spjd
1809219089Spjd	if (l2hdr != NULL) {
1810219089Spjd		boolean_t buflist_held = MUTEX_HELD(&l2arc_buflist_mtx);
1811219089Spjd		/*
1812219089Spjd		 * To prevent arc_free() and l2arc_evict() from
1813219089Spjd		 * attempting to free the same buffer at the same time,
1814219089Spjd		 * a FREE_IN_PROGRESS flag is given to arc_free() to
1815219089Spjd		 * give it priority.  l2arc_evict() can't destroy this
1816219089Spjd		 * header while we are waiting on l2arc_buflist_mtx.
1817219089Spjd		 *
1818219089Spjd		 * The hdr may be removed from l2ad_buflist before we
1819219089Spjd		 * grab l2arc_buflist_mtx, so b_l2hdr is rechecked.
1820219089Spjd		 */
1821219089Spjd		if (!buflist_held) {
1822185029Spjd			mutex_enter(&l2arc_buflist_mtx);
1823219089Spjd			l2hdr = hdr->b_l2hdr;
1824219089Spjd		}
1825219089Spjd
1826219089Spjd		if (l2hdr != NULL) {
1827248572Ssmh			trim_map_free(l2hdr->b_dev->l2ad_vdev, l2hdr->b_daddr,
1828248574Ssmh			    hdr->b_size, 0);
1829219089Spjd			list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
1830274172Savg			arc_buf_l2_cdata_free(hdr);
1831219089Spjd			ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
1832251478Sdelphij			ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
1833268085Sdelphij			vdev_space_update(l2hdr->b_dev->l2ad_vdev,
1834268085Sdelphij			    -l2hdr->b_asize, 0, 0);
1835219089Spjd			kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
1836219089Spjd			if (hdr->b_state == arc_l2c_only)
1837219089Spjd				l2arc_hdr_stat_remove();
1838219089Spjd			hdr->b_l2hdr = NULL;
1839219089Spjd		}
1840219089Spjd
1841219089Spjd		if (!buflist_held)
1842185029Spjd			mutex_exit(&l2arc_buflist_mtx);
1843185029Spjd	}
1844185029Spjd
1845168404Spjd	if (!BUF_EMPTY(hdr)) {
1846168404Spjd		ASSERT(!HDR_IN_HASH_TABLE(hdr));
1847219089Spjd		buf_discard_identity(hdr);
1848168404Spjd	}
1849168404Spjd	while (hdr->b_buf) {
1850168404Spjd		arc_buf_t *buf = hdr->b_buf;
1851168404Spjd
1852168404Spjd		if (buf->b_efunc) {
1853168404Spjd			mutex_enter(&arc_eviction_mtx);
1854219089Spjd			mutex_enter(&buf->b_evict_lock);
1855168404Spjd			ASSERT(buf->b_hdr != NULL);
1856168404Spjd			arc_buf_destroy(hdr->b_buf, FALSE, FALSE);
1857168404Spjd			hdr->b_buf = buf->b_next;
1858168404Spjd			buf->b_hdr = &arc_eviction_hdr;
1859168404Spjd			buf->b_next = arc_eviction_list;
1860168404Spjd			arc_eviction_list = buf;
1861219089Spjd			mutex_exit(&buf->b_evict_lock);
1862168404Spjd			mutex_exit(&arc_eviction_mtx);
1863168404Spjd		} else {
1864168404Spjd			arc_buf_destroy(hdr->b_buf, FALSE, TRUE);
1865168404Spjd		}
1866168404Spjd	}
1867168404Spjd	if (hdr->b_freeze_cksum != NULL) {
1868168404Spjd		kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1869168404Spjd		hdr->b_freeze_cksum = NULL;
1870168404Spjd	}
1871219089Spjd	if (hdr->b_thawed) {
1872219089Spjd		kmem_free(hdr->b_thawed, 1);
1873219089Spjd		hdr->b_thawed = NULL;
1874219089Spjd	}
1875168404Spjd
1876168404Spjd	ASSERT(!list_link_active(&hdr->b_arc_node));
1877168404Spjd	ASSERT3P(hdr->b_hash_next, ==, NULL);
1878168404Spjd	ASSERT3P(hdr->b_acb, ==, NULL);
1879168404Spjd	kmem_cache_free(hdr_cache, hdr);
1880168404Spjd}
1881168404Spjd
1882168404Spjdvoid
1883168404Spjdarc_buf_free(arc_buf_t *buf, void *tag)
1884168404Spjd{
1885168404Spjd	arc_buf_hdr_t *hdr = buf->b_hdr;
1886168404Spjd	int hashed = hdr->b_state != arc_anon;
1887168404Spjd
1888168404Spjd	ASSERT(buf->b_efunc == NULL);
1889168404Spjd	ASSERT(buf->b_data != NULL);
1890168404Spjd
1891168404Spjd	if (hashed) {
1892168404Spjd		kmutex_t *hash_lock = HDR_LOCK(hdr);
1893168404Spjd
1894168404Spjd		mutex_enter(hash_lock);
1895219089Spjd		hdr = buf->b_hdr;
1896219089Spjd		ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1897219089Spjd
1898168404Spjd		(void) remove_reference(hdr, hash_lock, tag);
1899219089Spjd		if (hdr->b_datacnt > 1) {
1900168404Spjd			arc_buf_destroy(buf, FALSE, TRUE);
1901219089Spjd		} else {
1902219089Spjd			ASSERT(buf == hdr->b_buf);
1903219089Spjd			ASSERT(buf->b_efunc == NULL);
1904275811Sdelphij			hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
1905219089Spjd		}
1906168404Spjd		mutex_exit(hash_lock);
1907168404Spjd	} else if (HDR_IO_IN_PROGRESS(hdr)) {
1908168404Spjd		int destroy_hdr;
1909168404Spjd		/*
1910168404Spjd		 * We are in the middle of an async write.  Don't destroy
1911168404Spjd		 * this buffer unless the write completes before we finish
1912168404Spjd		 * decrementing the reference count.
1913168404Spjd		 */
1914168404Spjd		mutex_enter(&arc_eviction_mtx);
1915168404Spjd		(void) remove_reference(hdr, NULL, tag);
1916168404Spjd		ASSERT(refcount_is_zero(&hdr->b_refcnt));
1917168404Spjd		destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
1918168404Spjd		mutex_exit(&arc_eviction_mtx);
1919168404Spjd		if (destroy_hdr)
1920168404Spjd			arc_hdr_destroy(hdr);
1921168404Spjd	} else {
1922219089Spjd		if (remove_reference(hdr, NULL, tag) > 0)
1923168404Spjd			arc_buf_destroy(buf, FALSE, TRUE);
1924219089Spjd		else
1925168404Spjd			arc_hdr_destroy(hdr);
1926168404Spjd	}
1927168404Spjd}
1928168404Spjd
1929248571Smmboolean_t
1930168404Spjdarc_buf_remove_ref(arc_buf_t *buf, void* tag)
1931168404Spjd{
1932168404Spjd	arc_buf_hdr_t *hdr = buf->b_hdr;
1933168404Spjd	kmutex_t *hash_lock = HDR_LOCK(hdr);
1934248571Smm	boolean_t no_callback = (buf->b_efunc == NULL);
1935168404Spjd
1936168404Spjd	if (hdr->b_state == arc_anon) {
1937219089Spjd		ASSERT(hdr->b_datacnt == 1);
1938168404Spjd		arc_buf_free(buf, tag);
1939168404Spjd		return (no_callback);
1940168404Spjd	}
1941168404Spjd
1942168404Spjd	mutex_enter(hash_lock);
1943219089Spjd	hdr = buf->b_hdr;
1944219089Spjd	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1945168404Spjd	ASSERT(hdr->b_state != arc_anon);
1946168404Spjd	ASSERT(buf->b_data != NULL);
1947168404Spjd
1948168404Spjd	(void) remove_reference(hdr, hash_lock, tag);
1949168404Spjd	if (hdr->b_datacnt > 1) {
1950168404Spjd		if (no_callback)
1951168404Spjd			arc_buf_destroy(buf, FALSE, TRUE);
1952168404Spjd	} else if (no_callback) {
1953168404Spjd		ASSERT(hdr->b_buf == buf && buf->b_next == NULL);
1954219089Spjd		ASSERT(buf->b_efunc == NULL);
1955275811Sdelphij		hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
1956168404Spjd	}
1957168404Spjd	ASSERT(no_callback || hdr->b_datacnt > 1 ||
1958168404Spjd	    refcount_is_zero(&hdr->b_refcnt));
1959168404Spjd	mutex_exit(hash_lock);
1960168404Spjd	return (no_callback);
1961168404Spjd}
1962168404Spjd
1963168404Spjdint
1964168404Spjdarc_buf_size(arc_buf_t *buf)
1965168404Spjd{
1966168404Spjd	return (buf->b_hdr->b_size);
1967168404Spjd}
1968168404Spjd
1969168404Spjd/*
1970242845Sdelphij * Called from the DMU to determine if the current buffer should be
1971242845Sdelphij * evicted. In order to ensure proper locking, the eviction must be initiated
1972242845Sdelphij * from the DMU. Return true if the buffer is associated with user data and
1973242845Sdelphij * duplicate buffers still exist.
1974242845Sdelphij */
1975242845Sdelphijboolean_t
1976242845Sdelphijarc_buf_eviction_needed(arc_buf_t *buf)
1977242845Sdelphij{
1978242845Sdelphij	arc_buf_hdr_t *hdr;
1979242845Sdelphij	boolean_t evict_needed = B_FALSE;
1980242845Sdelphij
1981242845Sdelphij	if (zfs_disable_dup_eviction)
1982242845Sdelphij		return (B_FALSE);
1983242845Sdelphij
1984242845Sdelphij	mutex_enter(&buf->b_evict_lock);
1985242845Sdelphij	hdr = buf->b_hdr;
1986242845Sdelphij	if (hdr == NULL) {
1987242845Sdelphij		/*
1988242845Sdelphij		 * We are in arc_do_user_evicts(); let that function
1989242845Sdelphij		 * perform the eviction.
1990242845Sdelphij		 */
1991242845Sdelphij		ASSERT(buf->b_data == NULL);
1992242845Sdelphij		mutex_exit(&buf->b_evict_lock);
1993242845Sdelphij		return (B_FALSE);
1994242845Sdelphij	} else if (buf->b_data == NULL) {
1995242845Sdelphij		/*
1996242845Sdelphij		 * We have already been added to the arc eviction list;
1997242845Sdelphij		 * recommend eviction.
1998242845Sdelphij		 */
1999242845Sdelphij		ASSERT3P(hdr, ==, &arc_eviction_hdr);
2000242845Sdelphij		mutex_exit(&buf->b_evict_lock);
2001242845Sdelphij		return (B_TRUE);
2002242845Sdelphij	}
2003242845Sdelphij
2004242845Sdelphij	if (hdr->b_datacnt > 1 && hdr->b_type == ARC_BUFC_DATA)
2005242845Sdelphij		evict_needed = B_TRUE;
2006242845Sdelphij
2007242845Sdelphij	mutex_exit(&buf->b_evict_lock);
2008242845Sdelphij	return (evict_needed);
2009242845Sdelphij}
2010242845Sdelphij
2011242845Sdelphij/*
2012168404Spjd * Evict buffers from list until we've removed the specified number of
2013168404Spjd * bytes.  Move the removed buffers to the appropriate evict state.
2014168404Spjd * If the recycle flag is set, then attempt to "recycle" a buffer:
2015168404Spjd * - look for a buffer to evict that is `bytes' long.
2016168404Spjd * - return the data block from this buffer rather than freeing it.
2017168404Spjd * This flag is used by callers that are trying to make space for a
2018168404Spjd * new buffer in a full arc cache.
2019185029Spjd *
2020185029Spjd * This function makes a "best effort".  It skips over any buffers
2021185029Spjd * it can't get a hash_lock on, and so may not catch all candidates.
2022185029Spjd * It may also return without evicting as much space as requested.
2023168404Spjd */
2024168404Spjdstatic void *
2025209962Smmarc_evict(arc_state_t *state, uint64_t spa, int64_t bytes, boolean_t recycle,
2026168404Spjd    arc_buf_contents_t type)
2027168404Spjd{
2028168404Spjd	arc_state_t *evicted_state;
2029168404Spjd	uint64_t bytes_evicted = 0, skipped = 0, missed = 0;
2030205231Skmacy	int64_t bytes_remaining;
2031275811Sdelphij	arc_buf_hdr_t *hdr, *hdr_prev = NULL;
2032205231Skmacy	list_t *evicted_list, *list, *evicted_list_start, *list_start;
2033205231Skmacy	kmutex_t *lock, *evicted_lock;
2034168404Spjd	kmutex_t *hash_lock;
2035168404Spjd	boolean_t have_lock;
2036168404Spjd	void *stolen = NULL;
2037258632Savg	arc_buf_hdr_t marker = { 0 };
2038258632Savg	int count = 0;
2039205231Skmacy	static int evict_metadata_offset, evict_data_offset;
2040258632Savg	int i, idx, offset, list_count, lists;
2041168404Spjd
2042168404Spjd	ASSERT(state == arc_mru || state == arc_mfu);
2043168404Spjd
2044168404Spjd	evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
2045206796Spjd
2046275780Sdelphij	/*
2047275780Sdelphij	 * Decide which "type" (data vs metadata) to recycle from.
2048275780Sdelphij	 *
2049275780Sdelphij	 * If we are over the metadata limit, recycle from metadata.
2050275780Sdelphij	 * If we are under the metadata minimum, recycle from data.
2051275780Sdelphij	 * Otherwise, recycle from whichever type has the oldest (least
2052275780Sdelphij	 * recently accessed) header.  This is not yet implemented.
2053275780Sdelphij	 */
2054275780Sdelphij	if (recycle) {
2055275780Sdelphij		arc_buf_contents_t realtype;
2056275780Sdelphij		if (state->arcs_lsize[ARC_BUFC_DATA] == 0) {
2057275780Sdelphij			realtype = ARC_BUFC_METADATA;
2058275780Sdelphij		} else if (state->arcs_lsize[ARC_BUFC_METADATA] == 0) {
2059275780Sdelphij			realtype = ARC_BUFC_DATA;
2060275780Sdelphij		} else if (arc_meta_used >= arc_meta_limit) {
2061275780Sdelphij			realtype = ARC_BUFC_METADATA;
2062275780Sdelphij		} else if (arc_meta_used <= arc_meta_min) {
2063275780Sdelphij			realtype = ARC_BUFC_DATA;
2064275780Sdelphij		} else {
2065275780Sdelphij#ifdef illumos
2066275780Sdelphij			if (data_hdr->b_arc_access <
2067275780Sdelphij			    metadata_hdr->b_arc_access) {
2068275780Sdelphij				realtype = ARC_BUFC_DATA;
2069275780Sdelphij			} else {
2070275780Sdelphij				realtype = ARC_BUFC_METADATA;
2071275780Sdelphij			}
2072275780Sdelphij#else
2073275780Sdelphij			/* TODO */
2074275780Sdelphij			realtype = type;
2075275780Sdelphij#endif
2076275780Sdelphij		}
2077275780Sdelphij		if (realtype != type) {
2078275780Sdelphij			/*
2079275780Sdelphij			 * If we want to evict from a different list,
2080275780Sdelphij			 * we can not recycle, because DATA vs METADATA
2081275780Sdelphij			 * buffers are segregated into different kmem
2082275780Sdelphij			 * caches (and vmem arenas).
2083275780Sdelphij			 */
2084275780Sdelphij			type = realtype;
2085275780Sdelphij			recycle = B_FALSE;
2086275780Sdelphij		}
2087275780Sdelphij	}
2088275780Sdelphij
2089205231Skmacy	if (type == ARC_BUFC_METADATA) {
2090205231Skmacy		offset = 0;
2091205231Skmacy		list_count = ARC_BUFC_NUMMETADATALISTS;
2092205231Skmacy		list_start = &state->arcs_lists[0];
2093205231Skmacy		evicted_list_start = &evicted_state->arcs_lists[0];
2094205231Skmacy		idx = evict_metadata_offset;
2095205231Skmacy	} else {
2096205231Skmacy		offset = ARC_BUFC_NUMMETADATALISTS;
2097205231Skmacy		list_start = &state->arcs_lists[offset];
2098205231Skmacy		evicted_list_start = &evicted_state->arcs_lists[offset];
2099205231Skmacy		list_count = ARC_BUFC_NUMDATALISTS;
2100205231Skmacy		idx = evict_data_offset;
2101205231Skmacy	}
2102205231Skmacy	bytes_remaining = evicted_state->arcs_lsize[type];
2103258632Savg	lists = 0;
2104206796Spjd
2105205231Skmacyevict_start:
2106205231Skmacy	list = &list_start[idx];
2107205231Skmacy	evicted_list = &evicted_list_start[idx];
2108205231Skmacy	lock = ARCS_LOCK(state, (offset + idx));
2109206796Spjd	evicted_lock = ARCS_LOCK(evicted_state, (offset + idx));
2110168404Spjd
2111205231Skmacy	mutex_enter(lock);
2112205231Skmacy	mutex_enter(evicted_lock);
2113205231Skmacy
2114275811Sdelphij	for (hdr = list_tail(list); hdr; hdr = hdr_prev) {
2115275811Sdelphij		hdr_prev = list_prev(list, hdr);
2116275811Sdelphij		bytes_remaining -= (hdr->b_size * hdr->b_datacnt);
2117168404Spjd		/* prefetch buffers have a minimum lifespan */
2118275811Sdelphij		if (HDR_IO_IN_PROGRESS(hdr) ||
2119275811Sdelphij		    (spa && hdr->b_spa != spa) ||
2120275811Sdelphij		    (hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT) &&
2121275811Sdelphij		    ddi_get_lbolt() - hdr->b_arc_access <
2122219089Spjd		    arc_min_prefetch_lifespan)) {
2123168404Spjd			skipped++;
2124168404Spjd			continue;
2125168404Spjd		}
2126168404Spjd		/* "lookahead" for better eviction candidate */
2127275811Sdelphij		if (recycle && hdr->b_size != bytes &&
2128275811Sdelphij		    hdr_prev && hdr_prev->b_size == bytes)
2129168404Spjd			continue;
2130258632Savg
2131258632Savg		/* ignore markers */
2132275811Sdelphij		if (hdr->b_spa == 0)
2133258632Savg			continue;
2134258632Savg
2135258632Savg		/*
2136258632Savg		 * It may take a long time to evict all the bufs requested.
2137258632Savg		 * To avoid blocking all arc activity, periodically drop
2138258632Savg		 * the arcs_mtx and give other threads a chance to run
2139258632Savg		 * before reacquiring the lock.
2140258632Savg		 *
2141258632Savg		 * If we are looking for a buffer to recycle, we are in
2142258632Savg		 * the hot code path, so don't sleep.
2143258632Savg		 */
2144258632Savg		if (!recycle && count++ > arc_evict_iterations) {
2145275811Sdelphij			list_insert_after(list, hdr, &marker);
2146258632Savg			mutex_exit(evicted_lock);
2147258632Savg			mutex_exit(lock);
2148258632Savg			kpreempt(KPREEMPT_SYNC);
2149258632Savg			mutex_enter(lock);
2150258632Savg			mutex_enter(evicted_lock);
2151275811Sdelphij			hdr_prev = list_prev(list, &marker);
2152258632Savg			list_remove(list, &marker);
2153258632Savg			count = 0;
2154258632Savg			continue;
2155258632Savg		}
2156258632Savg
2157275811Sdelphij		hash_lock = HDR_LOCK(hdr);
2158168404Spjd		have_lock = MUTEX_HELD(hash_lock);
2159168404Spjd		if (have_lock || mutex_tryenter(hash_lock)) {
2160275811Sdelphij			ASSERT0(refcount_count(&hdr->b_refcnt));
2161275811Sdelphij			ASSERT(hdr->b_datacnt > 0);
2162275811Sdelphij			while (hdr->b_buf) {
2163275811Sdelphij				arc_buf_t *buf = hdr->b_buf;
2164219089Spjd				if (!mutex_tryenter(&buf->b_evict_lock)) {
2165185029Spjd					missed += 1;
2166185029Spjd					break;
2167185029Spjd				}
2168168404Spjd				if (buf->b_data) {
2169275811Sdelphij					bytes_evicted += hdr->b_size;
2170275811Sdelphij					if (recycle && hdr->b_type == type &&
2171275811Sdelphij					    hdr->b_size == bytes &&
2172275811Sdelphij					    !HDR_L2_WRITING(hdr)) {
2173168404Spjd						stolen = buf->b_data;
2174168404Spjd						recycle = FALSE;
2175168404Spjd					}
2176168404Spjd				}
2177168404Spjd				if (buf->b_efunc) {
2178168404Spjd					mutex_enter(&arc_eviction_mtx);
2179168404Spjd					arc_buf_destroy(buf,
2180168404Spjd					    buf->b_data == stolen, FALSE);
2181275811Sdelphij					hdr->b_buf = buf->b_next;
2182168404Spjd					buf->b_hdr = &arc_eviction_hdr;
2183168404Spjd					buf->b_next = arc_eviction_list;
2184168404Spjd					arc_eviction_list = buf;
2185168404Spjd					mutex_exit(&arc_eviction_mtx);
2186219089Spjd					mutex_exit(&buf->b_evict_lock);
2187168404Spjd				} else {
2188219089Spjd					mutex_exit(&buf->b_evict_lock);
2189168404Spjd					arc_buf_destroy(buf,
2190168404Spjd					    buf->b_data == stolen, TRUE);
2191168404Spjd				}
2192168404Spjd			}
2193208373Smm
2194275811Sdelphij			if (hdr->b_l2hdr) {
2195208373Smm				ARCSTAT_INCR(arcstat_evict_l2_cached,
2196275811Sdelphij				    hdr->b_size);
2197208373Smm			} else {
2198275811Sdelphij				if (l2arc_write_eligible(hdr->b_spa, hdr)) {
2199208373Smm					ARCSTAT_INCR(arcstat_evict_l2_eligible,
2200275811Sdelphij					    hdr->b_size);
2201208373Smm				} else {
2202208373Smm					ARCSTAT_INCR(
2203208373Smm					    arcstat_evict_l2_ineligible,
2204275811Sdelphij					    hdr->b_size);
2205208373Smm				}
2206208373Smm			}
2207208373Smm
2208275811Sdelphij			if (hdr->b_datacnt == 0) {
2209275811Sdelphij				arc_change_state(evicted_state, hdr, hash_lock);
2210275811Sdelphij				ASSERT(HDR_IN_HASH_TABLE(hdr));
2211275811Sdelphij				hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
2212275811Sdelphij				hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
2213275811Sdelphij				DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
2214185029Spjd			}
2215168404Spjd			if (!have_lock)
2216168404Spjd				mutex_exit(hash_lock);
2217168404Spjd			if (bytes >= 0 && bytes_evicted >= bytes)
2218168404Spjd				break;
2219205231Skmacy			if (bytes_remaining > 0) {
2220205231Skmacy				mutex_exit(evicted_lock);
2221205231Skmacy				mutex_exit(lock);
2222206796Spjd				idx  = ((idx + 1) & (list_count - 1));
2223258632Savg				lists++;
2224205231Skmacy				goto evict_start;
2225205231Skmacy			}
2226168404Spjd		} else {
2227168404Spjd			missed += 1;
2228168404Spjd		}
2229168404Spjd	}
2230168404Spjd
2231205231Skmacy	mutex_exit(evicted_lock);
2232205231Skmacy	mutex_exit(lock);
2233206796Spjd
2234206796Spjd	idx  = ((idx + 1) & (list_count - 1));
2235258632Savg	lists++;
2236168404Spjd
2237205231Skmacy	if (bytes_evicted < bytes) {
2238258632Savg		if (lists < list_count)
2239205231Skmacy			goto evict_start;
2240205231Skmacy		else
2241205231Skmacy			dprintf("only evicted %lld bytes from %x",
2242205231Skmacy			    (longlong_t)bytes_evicted, state);
2243205231Skmacy	}
2244206796Spjd	if (type == ARC_BUFC_METADATA)
2245205231Skmacy		evict_metadata_offset = idx;
2246205231Skmacy	else
2247205231Skmacy		evict_data_offset = idx;
2248206796Spjd
2249168404Spjd	if (skipped)
2250168404Spjd		ARCSTAT_INCR(arcstat_evict_skip, skipped);
2251168404Spjd
2252168404Spjd	if (missed)
2253168404Spjd		ARCSTAT_INCR(arcstat_mutex_miss, missed);
2254168404Spjd
2255185029Spjd	/*
2256258632Savg	 * Note: we have just evicted some data into the ghost state,
2257258632Savg	 * potentially putting the ghost size over the desired size.  Rather
2258258632Savg	 * that evicting from the ghost list in this hot code path, leave
2259258632Savg	 * this chore to the arc_reclaim_thread().
2260185029Spjd	 */
2261185029Spjd
2262205231Skmacy	if (stolen)
2263205231Skmacy		ARCSTAT_BUMP(arcstat_stolen);
2264168404Spjd	return (stolen);
2265168404Spjd}
2266168404Spjd
2267168404Spjd/*
2268168404Spjd * Remove buffers from list until we've removed the specified number of
2269168404Spjd * bytes.  Destroy the buffers that are removed.
2270168404Spjd */
2271168404Spjdstatic void
2272209962Smmarc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes)
2273168404Spjd{
2274275811Sdelphij	arc_buf_hdr_t *hdr, *hdr_prev;
2275219089Spjd	arc_buf_hdr_t marker = { 0 };
2276205231Skmacy	list_t *list, *list_start;
2277205231Skmacy	kmutex_t *hash_lock, *lock;
2278168404Spjd	uint64_t bytes_deleted = 0;
2279168404Spjd	uint64_t bufs_skipped = 0;
2280258632Savg	int count = 0;
2281205231Skmacy	static int evict_offset;
2282205231Skmacy	int list_count, idx = evict_offset;
2283258632Savg	int offset, lists = 0;
2284168404Spjd
2285168404Spjd	ASSERT(GHOST_STATE(state));
2286205231Skmacy
2287205231Skmacy	/*
2288205231Skmacy	 * data lists come after metadata lists
2289205231Skmacy	 */
2290205231Skmacy	list_start = &state->arcs_lists[ARC_BUFC_NUMMETADATALISTS];
2291205231Skmacy	list_count = ARC_BUFC_NUMDATALISTS;
2292205231Skmacy	offset = ARC_BUFC_NUMMETADATALISTS;
2293206796Spjd
2294205231Skmacyevict_start:
2295205231Skmacy	list = &list_start[idx];
2296205231Skmacy	lock = ARCS_LOCK(state, idx + offset);
2297205231Skmacy
2298205231Skmacy	mutex_enter(lock);
2299275811Sdelphij	for (hdr = list_tail(list); hdr; hdr = hdr_prev) {
2300275811Sdelphij		hdr_prev = list_prev(list, hdr);
2301275811Sdelphij		if (hdr->b_type > ARC_BUFC_NUMTYPES)
2302275811Sdelphij			panic("invalid hdr=%p", (void *)hdr);
2303275811Sdelphij		if (spa && hdr->b_spa != spa)
2304185029Spjd			continue;
2305219089Spjd
2306219089Spjd		/* ignore markers */
2307275811Sdelphij		if (hdr->b_spa == 0)
2308219089Spjd			continue;
2309219089Spjd
2310275811Sdelphij		hash_lock = HDR_LOCK(hdr);
2311219089Spjd		/* caller may be trying to modify this buffer, skip it */
2312219089Spjd		if (MUTEX_HELD(hash_lock))
2313219089Spjd			continue;
2314258632Savg
2315258632Savg		/*
2316258632Savg		 * It may take a long time to evict all the bufs requested.
2317258632Savg		 * To avoid blocking all arc activity, periodically drop
2318258632Savg		 * the arcs_mtx and give other threads a chance to run
2319258632Savg		 * before reacquiring the lock.
2320258632Savg		 */
2321258632Savg		if (count++ > arc_evict_iterations) {
2322275811Sdelphij			list_insert_after(list, hdr, &marker);
2323258632Savg			mutex_exit(lock);
2324258632Savg			kpreempt(KPREEMPT_SYNC);
2325258632Savg			mutex_enter(lock);
2326275811Sdelphij			hdr_prev = list_prev(list, &marker);
2327258632Savg			list_remove(list, &marker);
2328258632Savg			count = 0;
2329258632Savg			continue;
2330258632Savg		}
2331168404Spjd		if (mutex_tryenter(hash_lock)) {
2332275811Sdelphij			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2333275811Sdelphij			ASSERT(hdr->b_buf == NULL);
2334168404Spjd			ARCSTAT_BUMP(arcstat_deleted);
2335275811Sdelphij			bytes_deleted += hdr->b_size;
2336185029Spjd
2337275811Sdelphij			if (hdr->b_l2hdr != NULL) {
2338185029Spjd				/*
2339185029Spjd				 * This buffer is cached on the 2nd Level ARC;
2340185029Spjd				 * don't destroy the header.
2341185029Spjd				 */
2342275811Sdelphij				arc_change_state(arc_l2c_only, hdr, hash_lock);
2343185029Spjd				mutex_exit(hash_lock);
2344185029Spjd			} else {
2345275811Sdelphij				arc_change_state(arc_anon, hdr, hash_lock);
2346185029Spjd				mutex_exit(hash_lock);
2347275811Sdelphij				arc_hdr_destroy(hdr);
2348185029Spjd			}
2349185029Spjd
2350275811Sdelphij			DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
2351168404Spjd			if (bytes >= 0 && bytes_deleted >= bytes)
2352168404Spjd				break;
2353219089Spjd		} else if (bytes < 0) {
2354219089Spjd			/*
2355219089Spjd			 * Insert a list marker and then wait for the
2356219089Spjd			 * hash lock to become available. Once its
2357219089Spjd			 * available, restart from where we left off.
2358219089Spjd			 */
2359275811Sdelphij			list_insert_after(list, hdr, &marker);
2360219089Spjd			mutex_exit(lock);
2361219089Spjd			mutex_enter(hash_lock);
2362219089Spjd			mutex_exit(hash_lock);
2363219089Spjd			mutex_enter(lock);
2364275811Sdelphij			hdr_prev = list_prev(list, &marker);
2365219089Spjd			list_remove(list, &marker);
2366258632Savg		} else {
2367168404Spjd			bufs_skipped += 1;
2368258632Savg		}
2369258632Savg
2370168404Spjd	}
2371205231Skmacy	mutex_exit(lock);
2372206796Spjd	idx  = ((idx + 1) & (ARC_BUFC_NUMDATALISTS - 1));
2373258632Savg	lists++;
2374206796Spjd
2375258632Savg	if (lists < list_count)
2376205231Skmacy		goto evict_start;
2377206796Spjd
2378205231Skmacy	evict_offset = idx;
2379205231Skmacy	if ((uintptr_t)list > (uintptr_t)&state->arcs_lists[ARC_BUFC_NUMMETADATALISTS] &&
2380185029Spjd	    (bytes < 0 || bytes_deleted < bytes)) {
2381205231Skmacy		list_start = &state->arcs_lists[0];
2382205231Skmacy		list_count = ARC_BUFC_NUMMETADATALISTS;
2383258632Savg		offset = lists = 0;
2384205231Skmacy		goto evict_start;
2385185029Spjd	}
2386185029Spjd
2387168404Spjd	if (bufs_skipped) {
2388168404Spjd		ARCSTAT_INCR(arcstat_mutex_miss, bufs_skipped);
2389168404Spjd		ASSERT(bytes >= 0);
2390168404Spjd	}
2391168404Spjd
2392168404Spjd	if (bytes_deleted < bytes)
2393168404Spjd		dprintf("only deleted %lld bytes from %p",
2394168404Spjd		    (longlong_t)bytes_deleted, state);
2395168404Spjd}
2396168404Spjd
2397168404Spjdstatic void
2398168404Spjdarc_adjust(void)
2399168404Spjd{
2400208373Smm	int64_t adjustment, delta;
2401168404Spjd
2402208373Smm	/*
2403208373Smm	 * Adjust MRU size
2404208373Smm	 */
2405168404Spjd
2406209275Smm	adjustment = MIN((int64_t)(arc_size - arc_c),
2407209275Smm	    (int64_t)(arc_anon->arcs_size + arc_mru->arcs_size + arc_meta_used -
2408209275Smm	    arc_p));
2409208373Smm
2410208373Smm	if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_DATA] > 0) {
2411208373Smm		delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_DATA], adjustment);
2412209962Smm		(void) arc_evict(arc_mru, 0, delta, FALSE, ARC_BUFC_DATA);
2413208373Smm		adjustment -= delta;
2414168404Spjd	}
2415168404Spjd
2416208373Smm	if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2417208373Smm		delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_METADATA], adjustment);
2418209962Smm		(void) arc_evict(arc_mru, 0, delta, FALSE,
2419185029Spjd		    ARC_BUFC_METADATA);
2420185029Spjd	}
2421185029Spjd
2422208373Smm	/*
2423208373Smm	 * Adjust MFU size
2424208373Smm	 */
2425168404Spjd
2426208373Smm	adjustment = arc_size - arc_c;
2427208373Smm
2428208373Smm	if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_DATA] > 0) {
2429208373Smm		delta = MIN(adjustment, arc_mfu->arcs_lsize[ARC_BUFC_DATA]);
2430209962Smm		(void) arc_evict(arc_mfu, 0, delta, FALSE, ARC_BUFC_DATA);
2431208373Smm		adjustment -= delta;
2432168404Spjd	}
2433168404Spjd
2434208373Smm	if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2435208373Smm		int64_t delta = MIN(adjustment,
2436208373Smm		    arc_mfu->arcs_lsize[ARC_BUFC_METADATA]);
2437209962Smm		(void) arc_evict(arc_mfu, 0, delta, FALSE,
2438208373Smm		    ARC_BUFC_METADATA);
2439208373Smm	}
2440168404Spjd
2441208373Smm	/*
2442208373Smm	 * Adjust ghost lists
2443208373Smm	 */
2444168404Spjd
2445208373Smm	adjustment = arc_mru->arcs_size + arc_mru_ghost->arcs_size - arc_c;
2446168404Spjd
2447208373Smm	if (adjustment > 0 && arc_mru_ghost->arcs_size > 0) {
2448208373Smm		delta = MIN(arc_mru_ghost->arcs_size, adjustment);
2449209962Smm		arc_evict_ghost(arc_mru_ghost, 0, delta);
2450208373Smm	}
2451185029Spjd
2452208373Smm	adjustment =
2453208373Smm	    arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size - arc_c;
2454208373Smm
2455208373Smm	if (adjustment > 0 && arc_mfu_ghost->arcs_size > 0) {
2456208373Smm		delta = MIN(arc_mfu_ghost->arcs_size, adjustment);
2457209962Smm		arc_evict_ghost(arc_mfu_ghost, 0, delta);
2458168404Spjd	}
2459168404Spjd}
2460168404Spjd
2461168404Spjdstatic void
2462168404Spjdarc_do_user_evicts(void)
2463168404Spjd{
2464191903Skmacy	static arc_buf_t *tmp_arc_eviction_list;
2465191903Skmacy
2466191903Skmacy	/*
2467191903Skmacy	 * Move list over to avoid LOR
2468191903Skmacy	 */
2469206796Spjdrestart:
2470168404Spjd	mutex_enter(&arc_eviction_mtx);
2471191903Skmacy	tmp_arc_eviction_list = arc_eviction_list;
2472191903Skmacy	arc_eviction_list = NULL;
2473191903Skmacy	mutex_exit(&arc_eviction_mtx);
2474191903Skmacy
2475191903Skmacy	while (tmp_arc_eviction_list != NULL) {
2476191903Skmacy		arc_buf_t *buf = tmp_arc_eviction_list;
2477191903Skmacy		tmp_arc_eviction_list = buf->b_next;
2478219089Spjd		mutex_enter(&buf->b_evict_lock);
2479168404Spjd		buf->b_hdr = NULL;
2480219089Spjd		mutex_exit(&buf->b_evict_lock);
2481168404Spjd
2482168404Spjd		if (buf->b_efunc != NULL)
2483268858Sdelphij			VERIFY0(buf->b_efunc(buf->b_private));
2484168404Spjd
2485168404Spjd		buf->b_efunc = NULL;
2486168404Spjd		buf->b_private = NULL;
2487168404Spjd		kmem_cache_free(buf_cache, buf);
2488168404Spjd	}
2489191903Skmacy
2490191903Skmacy	if (arc_eviction_list != NULL)
2491191903Skmacy		goto restart;
2492168404Spjd}
2493168404Spjd
2494168404Spjd/*
2495185029Spjd * Flush all *evictable* data from the cache for the given spa.
2496168404Spjd * NOTE: this will not touch "active" (i.e. referenced) data.
2497168404Spjd */
2498168404Spjdvoid
2499185029Spjdarc_flush(spa_t *spa)
2500168404Spjd{
2501209962Smm	uint64_t guid = 0;
2502209962Smm
2503209962Smm	if (spa)
2504228103Smm		guid = spa_load_guid(spa);
2505209962Smm
2506205231Skmacy	while (arc_mru->arcs_lsize[ARC_BUFC_DATA]) {
2507209962Smm		(void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_DATA);
2508185029Spjd		if (spa)
2509185029Spjd			break;
2510185029Spjd	}
2511205231Skmacy	while (arc_mru->arcs_lsize[ARC_BUFC_METADATA]) {
2512209962Smm		(void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_METADATA);
2513185029Spjd		if (spa)
2514185029Spjd			break;
2515185029Spjd	}
2516205231Skmacy	while (arc_mfu->arcs_lsize[ARC_BUFC_DATA]) {
2517209962Smm		(void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_DATA);
2518185029Spjd		if (spa)
2519185029Spjd			break;
2520185029Spjd	}
2521205231Skmacy	while (arc_mfu->arcs_lsize[ARC_BUFC_METADATA]) {
2522209962Smm		(void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_METADATA);
2523185029Spjd		if (spa)
2524185029Spjd			break;
2525185029Spjd	}
2526168404Spjd
2527209962Smm	arc_evict_ghost(arc_mru_ghost, guid, -1);
2528209962Smm	arc_evict_ghost(arc_mfu_ghost, guid, -1);
2529168404Spjd
2530168404Spjd	mutex_enter(&arc_reclaim_thr_lock);
2531168404Spjd	arc_do_user_evicts();
2532168404Spjd	mutex_exit(&arc_reclaim_thr_lock);
2533185029Spjd	ASSERT(spa || arc_eviction_list == NULL);
2534168404Spjd}
2535168404Spjd
2536168404Spjdvoid
2537168404Spjdarc_shrink(void)
2538168404Spjd{
2539270759Ssmh
2540168404Spjd	if (arc_c > arc_c_min) {
2541168404Spjd		uint64_t to_free;
2542168404Spjd
2543277452Swill		to_free = arc_c >> arc_shrink_shift;
2544272483Ssmh		DTRACE_PROBE4(arc__shrink, uint64_t, arc_c, uint64_t,
2545272483Ssmh			arc_c_min, uint64_t, arc_p, uint64_t, to_free);
2546168404Spjd		if (arc_c > arc_c_min + to_free)
2547168404Spjd			atomic_add_64(&arc_c, -to_free);
2548168404Spjd		else
2549168404Spjd			arc_c = arc_c_min;
2550168404Spjd
2551168404Spjd		atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
2552168404Spjd		if (arc_c > arc_size)
2553168404Spjd			arc_c = MAX(arc_size, arc_c_min);
2554168404Spjd		if (arc_p > arc_c)
2555168404Spjd			arc_p = (arc_c >> 1);
2556272483Ssmh
2557272483Ssmh		DTRACE_PROBE2(arc__shrunk, uint64_t, arc_c, uint64_t,
2558272483Ssmh			arc_p);
2559272483Ssmh
2560168404Spjd		ASSERT(arc_c >= arc_c_min);
2561168404Spjd		ASSERT((int64_t)arc_p >= 0);
2562168404Spjd	}
2563168404Spjd
2564270759Ssmh	if (arc_size > arc_c) {
2565270759Ssmh		DTRACE_PROBE2(arc__shrink_adjust, uint64_t, arc_size,
2566270759Ssmh			uint64_t, arc_c);
2567168404Spjd		arc_adjust();
2568270759Ssmh	}
2569168404Spjd}
2570168404Spjd
2571185029Spjdstatic int needfree = 0;
2572168404Spjd
2573168404Spjdstatic int
2574168404Spjdarc_reclaim_needed(void)
2575168404Spjd{
2576168404Spjd
2577168404Spjd#ifdef _KERNEL
2578219089Spjd
2579270759Ssmh	if (needfree) {
2580270759Ssmh		DTRACE_PROBE(arc__reclaim_needfree);
2581197816Skmacy		return (1);
2582270759Ssmh	}
2583168404Spjd
2584191902Skmacy	/*
2585212780Savg	 * Cooperate with pagedaemon when it's time for it to scan
2586212780Savg	 * and reclaim some pages.
2587191902Skmacy	 */
2588272483Ssmh	if (freemem < zfs_arc_free_target) {
2589272483Ssmh		DTRACE_PROBE2(arc__reclaim_freemem, uint64_t,
2590272483Ssmh		    freemem, uint64_t, zfs_arc_free_target);
2591191902Skmacy		return (1);
2592270759Ssmh	}
2593191902Skmacy
2594277300Ssmh#ifdef illumos
2595168404Spjd	/*
2596185029Spjd	 * take 'desfree' extra pages, so we reclaim sooner, rather than later
2597185029Spjd	 */
2598185029Spjd	extra = desfree;
2599185029Spjd
2600185029Spjd	/*
2601185029Spjd	 * check that we're out of range of the pageout scanner.  It starts to
2602185029Spjd	 * schedule paging if freemem is less than lotsfree and needfree.
2603185029Spjd	 * lotsfree is the high-water mark for pageout, and needfree is the
2604185029Spjd	 * number of needed free pages.  We add extra pages here to make sure
2605185029Spjd	 * the scanner doesn't start up while we're freeing memory.
2606185029Spjd	 */
2607185029Spjd	if (freemem < lotsfree + needfree + extra)
2608185029Spjd		return (1);
2609185029Spjd
2610185029Spjd	/*
2611168404Spjd	 * check to make sure that swapfs has enough space so that anon
2612185029Spjd	 * reservations can still succeed. anon_resvmem() checks that the
2613168404Spjd	 * availrmem is greater than swapfs_minfree, and the number of reserved
2614168404Spjd	 * swap pages.  We also add a bit of extra here just to prevent
2615168404Spjd	 * circumstances from getting really dire.
2616168404Spjd	 */
2617168404Spjd	if (availrmem < swapfs_minfree + swapfs_reserve + extra)
2618168404Spjd		return (1);
2619168404Spjd
2620168404Spjd	/*
2621272483Ssmh	 * Check that we have enough availrmem that memory locking (e.g., via
2622272483Ssmh	 * mlock(3C) or memcntl(2)) can still succeed.  (pages_pp_maximum
2623272483Ssmh	 * stores the number of pages that cannot be locked; when availrmem
2624272483Ssmh	 * drops below pages_pp_maximum, page locking mechanisms such as
2625272483Ssmh	 * page_pp_lock() will fail.)
2626272483Ssmh	 */
2627272483Ssmh	if (availrmem <= pages_pp_maximum)
2628272483Ssmh		return (1);
2629272483Ssmh
2630277300Ssmh#endif	/* illumos */
2631272483Ssmh#if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
2632272483Ssmh	/*
2633168404Spjd	 * If we're on an i386 platform, it's possible that we'll exhaust the
2634168404Spjd	 * kernel heap space before we ever run out of available physical
2635168404Spjd	 * memory.  Most checks of the size of the heap_area compare against
2636168404Spjd	 * tune.t_minarmem, which is the minimum available real memory that we
2637168404Spjd	 * can have in the system.  However, this is generally fixed at 25 pages
2638168404Spjd	 * which is so low that it's useless.  In this comparison, we seek to
2639168404Spjd	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
2640185029Spjd	 * heap is allocated.  (Or, in the calculation, if less than 1/4th is
2641168404Spjd	 * free)
2642168404Spjd	 */
2643272483Ssmh	if (vmem_size(heap_arena, VMEM_FREE) <
2644272483Ssmh	    (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2)) {
2645270861Ssmh		DTRACE_PROBE2(arc__reclaim_used, uint64_t,
2646272483Ssmh		    vmem_size(heap_arena, VMEM_FREE), uint64_t,
2647272483Ssmh		    (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC)) >> 2);
2648270861Ssmh		return (1);
2649270861Ssmh	}
2650270861Ssmh#endif
2651277300Ssmh#ifdef illumos
2652272483Ssmh	/*
2653272483Ssmh	 * If zio data pages are being allocated out of a separate heap segment,
2654272483Ssmh	 * then enforce that the size of available vmem for this arena remains
2655272483Ssmh	 * above about 1/16th free.
2656272483Ssmh	 *
2657272483Ssmh	 * Note: The 1/16th arena free requirement was put in place
2658272483Ssmh	 * to aggressively evict memory from the arc in order to avoid
2659272483Ssmh	 * memory fragmentation issues.
2660272483Ssmh	 */
2661272483Ssmh	if (zio_arena != NULL &&
2662272483Ssmh	    vmem_size(zio_arena, VMEM_FREE) <
2663272483Ssmh	    (vmem_size(zio_arena, VMEM_ALLOC) >> 4))
2664272483Ssmh		return (1);
2665277300Ssmh#endif	/* illumos */
2666272483Ssmh#else	/* _KERNEL */
2667168404Spjd	if (spa_get_random(100) == 0)
2668168404Spjd		return (1);
2669272483Ssmh#endif	/* _KERNEL */
2670270759Ssmh	DTRACE_PROBE(arc__reclaim_no);
2671270759Ssmh
2672168404Spjd	return (0);
2673168404Spjd}
2674168404Spjd
2675208454Spjdextern kmem_cache_t	*zio_buf_cache[];
2676208454Spjdextern kmem_cache_t	*zio_data_buf_cache[];
2677272527Sdelphijextern kmem_cache_t	*range_seg_cache;
2678208454Spjd
2679272483Ssmhstatic void __noinline
2680168404Spjdarc_kmem_reap_now(arc_reclaim_strategy_t strat)
2681168404Spjd{
2682168404Spjd	size_t			i;
2683168404Spjd	kmem_cache_t		*prev_cache = NULL;
2684168404Spjd	kmem_cache_t		*prev_data_cache = NULL;
2685168404Spjd
2686272483Ssmh	DTRACE_PROBE(arc__kmem_reap_start);
2687168404Spjd#ifdef _KERNEL
2688185029Spjd	if (arc_meta_used >= arc_meta_limit) {
2689185029Spjd		/*
2690185029Spjd		 * We are exceeding our meta-data cache limit.
2691185029Spjd		 * Purge some DNLC entries to release holds on meta-data.
2692185029Spjd		 */
2693185029Spjd		dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
2694185029Spjd	}
2695168404Spjd#if defined(__i386)
2696168404Spjd	/*
2697168404Spjd	 * Reclaim unused memory from all kmem caches.
2698168404Spjd	 */
2699168404Spjd	kmem_reap();
2700168404Spjd#endif
2701168404Spjd#endif
2702168404Spjd
2703168404Spjd	/*
2704185029Spjd	 * An aggressive reclamation will shrink the cache size as well as
2705168404Spjd	 * reap free buffers from the arc kmem caches.
2706168404Spjd	 */
2707168404Spjd	if (strat == ARC_RECLAIM_AGGR)
2708168404Spjd		arc_shrink();
2709168404Spjd
2710168404Spjd	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
2711168404Spjd		if (zio_buf_cache[i] != prev_cache) {
2712168404Spjd			prev_cache = zio_buf_cache[i];
2713168404Spjd			kmem_cache_reap_now(zio_buf_cache[i]);
2714168404Spjd		}
2715168404Spjd		if (zio_data_buf_cache[i] != prev_data_cache) {
2716168404Spjd			prev_data_cache = zio_data_buf_cache[i];
2717168404Spjd			kmem_cache_reap_now(zio_data_buf_cache[i]);
2718168404Spjd		}
2719168404Spjd	}
2720168404Spjd	kmem_cache_reap_now(buf_cache);
2721168404Spjd	kmem_cache_reap_now(hdr_cache);
2722272506Sdelphij	kmem_cache_reap_now(range_seg_cache);
2723272483Ssmh
2724277300Ssmh#ifdef illumos
2725272483Ssmh	/*
2726272483Ssmh	 * Ask the vmem arena to reclaim unused memory from its
2727272483Ssmh	 * quantum caches.
2728272483Ssmh	 */
2729272483Ssmh	if (zio_arena != NULL && strat == ARC_RECLAIM_AGGR)
2730272483Ssmh		vmem_qcache_reap(zio_arena);
2731272483Ssmh#endif
2732272483Ssmh	DTRACE_PROBE(arc__kmem_reap_end);
2733168404Spjd}
2734168404Spjd
2735168404Spjdstatic void
2736168404Spjdarc_reclaim_thread(void *dummy __unused)
2737168404Spjd{
2738168404Spjd	clock_t			growtime = 0;
2739168404Spjd	arc_reclaim_strategy_t	last_reclaim = ARC_RECLAIM_CONS;
2740168404Spjd	callb_cpr_t		cpr;
2741168404Spjd
2742168404Spjd	CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
2743168404Spjd
2744168404Spjd	mutex_enter(&arc_reclaim_thr_lock);
2745168404Spjd	while (arc_thread_exit == 0) {
2746168404Spjd		if (arc_reclaim_needed()) {
2747168404Spjd
2748168404Spjd			if (arc_no_grow) {
2749168404Spjd				if (last_reclaim == ARC_RECLAIM_CONS) {
2750272483Ssmh					DTRACE_PROBE(arc__reclaim_aggr_no_grow);
2751168404Spjd					last_reclaim = ARC_RECLAIM_AGGR;
2752168404Spjd				} else {
2753168404Spjd					last_reclaim = ARC_RECLAIM_CONS;
2754168404Spjd				}
2755168404Spjd			} else {
2756168404Spjd				arc_no_grow = TRUE;
2757168404Spjd				last_reclaim = ARC_RECLAIM_AGGR;
2758272483Ssmh				DTRACE_PROBE(arc__reclaim_aggr);
2759168404Spjd				membar_producer();
2760168404Spjd			}
2761168404Spjd
2762168404Spjd			/* reset the growth delay for every reclaim */
2763219089Spjd			growtime = ddi_get_lbolt() + (arc_grow_retry * hz);
2764168404Spjd
2765185029Spjd			if (needfree && last_reclaim == ARC_RECLAIM_CONS) {
2766168404Spjd				/*
2767185029Spjd				 * If needfree is TRUE our vm_lowmem hook
2768168404Spjd				 * was called and in that case we must free some
2769168404Spjd				 * memory, so switch to aggressive mode.
2770168404Spjd				 */
2771168404Spjd				arc_no_grow = TRUE;
2772168404Spjd				last_reclaim = ARC_RECLAIM_AGGR;
2773168404Spjd			}
2774168404Spjd			arc_kmem_reap_now(last_reclaim);
2775185029Spjd			arc_warm = B_TRUE;
2776185029Spjd
2777219089Spjd		} else if (arc_no_grow && ddi_get_lbolt() >= growtime) {
2778168404Spjd			arc_no_grow = FALSE;
2779168404Spjd		}
2780168404Spjd
2781209275Smm		arc_adjust();
2782168404Spjd
2783168404Spjd		if (arc_eviction_list != NULL)
2784168404Spjd			arc_do_user_evicts();
2785168404Spjd
2786211762Savg#ifdef _KERNEL
2787211762Savg		if (needfree) {
2788185029Spjd			needfree = 0;
2789185029Spjd			wakeup(&needfree);
2790211762Savg		}
2791168404Spjd#endif
2792168404Spjd
2793168404Spjd		/* block until needed, or one second, whichever is shorter */
2794168404Spjd		CALLB_CPR_SAFE_BEGIN(&cpr);
2795168404Spjd		(void) cv_timedwait(&arc_reclaim_thr_cv,
2796168404Spjd		    &arc_reclaim_thr_lock, hz);
2797168404Spjd		CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
2798168404Spjd	}
2799168404Spjd
2800168404Spjd	arc_thread_exit = 0;
2801168404Spjd	cv_broadcast(&arc_reclaim_thr_cv);
2802168404Spjd	CALLB_CPR_EXIT(&cpr);		/* drops arc_reclaim_thr_lock */
2803168404Spjd	thread_exit();
2804168404Spjd}
2805168404Spjd
2806168404Spjd/*
2807168404Spjd * Adapt arc info given the number of bytes we are trying to add and
2808168404Spjd * the state that we are comming from.  This function is only called
2809168404Spjd * when we are adding new content to the cache.
2810168404Spjd */
2811168404Spjdstatic void
2812168404Spjdarc_adapt(int bytes, arc_state_t *state)
2813168404Spjd{
2814168404Spjd	int mult;
2815208373Smm	uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
2816168404Spjd
2817185029Spjd	if (state == arc_l2c_only)
2818185029Spjd		return;
2819185029Spjd
2820168404Spjd	ASSERT(bytes > 0);
2821168404Spjd	/*
2822168404Spjd	 * Adapt the target size of the MRU list:
2823168404Spjd	 *	- if we just hit in the MRU ghost list, then increase
2824168404Spjd	 *	  the target size of the MRU list.
2825168404Spjd	 *	- if we just hit in the MFU ghost list, then increase
2826168404Spjd	 *	  the target size of the MFU list by decreasing the
2827168404Spjd	 *	  target size of the MRU list.
2828168404Spjd	 */
2829168404Spjd	if (state == arc_mru_ghost) {
2830168404Spjd		mult = ((arc_mru_ghost->arcs_size >= arc_mfu_ghost->arcs_size) ?
2831168404Spjd		    1 : (arc_mfu_ghost->arcs_size/arc_mru_ghost->arcs_size));
2832209275Smm		mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
2833168404Spjd
2834208373Smm		arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
2835168404Spjd	} else if (state == arc_mfu_ghost) {
2836208373Smm		uint64_t delta;
2837208373Smm
2838168404Spjd		mult = ((arc_mfu_ghost->arcs_size >= arc_mru_ghost->arcs_size) ?
2839168404Spjd		    1 : (arc_mru_ghost->arcs_size/arc_mfu_ghost->arcs_size));
2840209275Smm		mult = MIN(mult, 10);
2841168404Spjd
2842208373Smm		delta = MIN(bytes * mult, arc_p);
2843208373Smm		arc_p = MAX(arc_p_min, arc_p - delta);
2844168404Spjd	}
2845168404Spjd	ASSERT((int64_t)arc_p >= 0);
2846168404Spjd
2847168404Spjd	if (arc_reclaim_needed()) {
2848168404Spjd		cv_signal(&arc_reclaim_thr_cv);
2849168404Spjd		return;
2850168404Spjd	}
2851168404Spjd
2852168404Spjd	if (arc_no_grow)
2853168404Spjd		return;
2854168404Spjd
2855168404Spjd	if (arc_c >= arc_c_max)
2856168404Spjd		return;
2857168404Spjd
2858168404Spjd	/*
2859168404Spjd	 * If we're within (2 * maxblocksize) bytes of the target
2860168404Spjd	 * cache size, increment the target cache size
2861168404Spjd	 */
2862168404Spjd	if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
2863272483Ssmh		DTRACE_PROBE1(arc__inc_adapt, int, bytes);
2864168404Spjd		atomic_add_64(&arc_c, (int64_t)bytes);
2865168404Spjd		if (arc_c > arc_c_max)
2866168404Spjd			arc_c = arc_c_max;
2867168404Spjd		else if (state == arc_anon)
2868168404Spjd			atomic_add_64(&arc_p, (int64_t)bytes);
2869168404Spjd		if (arc_p > arc_c)
2870168404Spjd			arc_p = arc_c;
2871168404Spjd	}
2872168404Spjd	ASSERT((int64_t)arc_p >= 0);
2873168404Spjd}
2874168404Spjd
2875168404Spjd/*
2876168404Spjd * Check if the cache has reached its limits and eviction is required
2877168404Spjd * prior to insert.
2878168404Spjd */
2879168404Spjdstatic int
2880185029Spjdarc_evict_needed(arc_buf_contents_t type)
2881168404Spjd{
2882185029Spjd	if (type == ARC_BUFC_METADATA && arc_meta_used >= arc_meta_limit)
2883185029Spjd		return (1);
2884185029Spjd
2885168404Spjd	if (arc_reclaim_needed())
2886168404Spjd		return (1);
2887168404Spjd
2888168404Spjd	return (arc_size > arc_c);
2889168404Spjd}
2890168404Spjd
2891168404Spjd/*
2892168404Spjd * The buffer, supplied as the first argument, needs a data block.
2893168404Spjd * So, if we are at cache max, determine which cache should be victimized.
2894168404Spjd * We have the following cases:
2895168404Spjd *
2896168404Spjd * 1. Insert for MRU, p > sizeof(arc_anon + arc_mru) ->
2897168404Spjd * In this situation if we're out of space, but the resident size of the MFU is
2898168404Spjd * under the limit, victimize the MFU cache to satisfy this insertion request.
2899168404Spjd *
2900168404Spjd * 2. Insert for MRU, p <= sizeof(arc_anon + arc_mru) ->
2901168404Spjd * Here, we've used up all of the available space for the MRU, so we need to
2902168404Spjd * evict from our own cache instead.  Evict from the set of resident MRU
2903168404Spjd * entries.
2904168404Spjd *
2905168404Spjd * 3. Insert for MFU (c - p) > sizeof(arc_mfu) ->
2906168404Spjd * c minus p represents the MFU space in the cache, since p is the size of the
2907168404Spjd * cache that is dedicated to the MRU.  In this situation there's still space on
2908168404Spjd * the MFU side, so the MRU side needs to be victimized.
2909168404Spjd *
2910168404Spjd * 4. Insert for MFU (c - p) < sizeof(arc_mfu) ->
2911168404Spjd * MFU's resident set is consuming more space than it has been allotted.  In
2912168404Spjd * this situation, we must victimize our own cache, the MFU, for this insertion.
2913168404Spjd */
2914168404Spjdstatic void
2915168404Spjdarc_get_data_buf(arc_buf_t *buf)
2916168404Spjd{
2917168404Spjd	arc_state_t		*state = buf->b_hdr->b_state;
2918168404Spjd	uint64_t		size = buf->b_hdr->b_size;
2919168404Spjd	arc_buf_contents_t	type = buf->b_hdr->b_type;
2920168404Spjd
2921168404Spjd	arc_adapt(size, state);
2922168404Spjd
2923168404Spjd	/*
2924168404Spjd	 * We have not yet reached cache maximum size,
2925168404Spjd	 * just allocate a new buffer.
2926168404Spjd	 */
2927185029Spjd	if (!arc_evict_needed(type)) {
2928168404Spjd		if (type == ARC_BUFC_METADATA) {
2929168404Spjd			buf->b_data = zio_buf_alloc(size);
2930208373Smm			arc_space_consume(size, ARC_SPACE_DATA);
2931168404Spjd		} else {
2932168404Spjd			ASSERT(type == ARC_BUFC_DATA);
2933168404Spjd			buf->b_data = zio_data_buf_alloc(size);
2934208373Smm			ARCSTAT_INCR(arcstat_data_size, size);
2935185029Spjd			atomic_add_64(&arc_size, size);
2936168404Spjd		}
2937168404Spjd		goto out;
2938168404Spjd	}
2939168404Spjd
2940168404Spjd	/*
2941168404Spjd	 * If we are prefetching from the mfu ghost list, this buffer
2942168404Spjd	 * will end up on the mru list; so steal space from there.
2943168404Spjd	 */
2944168404Spjd	if (state == arc_mfu_ghost)
2945275811Sdelphij		state = buf->b_hdr->b_flags & ARC_FLAG_PREFETCH ?
2946275811Sdelphij		    arc_mru : arc_mfu;
2947168404Spjd	else if (state == arc_mru_ghost)
2948168404Spjd		state = arc_mru;
2949168404Spjd
2950168404Spjd	if (state == arc_mru || state == arc_anon) {
2951168404Spjd		uint64_t mru_used = arc_anon->arcs_size + arc_mru->arcs_size;
2952208373Smm		state = (arc_mfu->arcs_lsize[type] >= size &&
2953185029Spjd		    arc_p > mru_used) ? arc_mfu : arc_mru;
2954168404Spjd	} else {
2955168404Spjd		/* MFU cases */
2956168404Spjd		uint64_t mfu_space = arc_c - arc_p;
2957208373Smm		state =  (arc_mru->arcs_lsize[type] >= size &&
2958185029Spjd		    mfu_space > arc_mfu->arcs_size) ? arc_mru : arc_mfu;
2959168404Spjd	}
2960209962Smm	if ((buf->b_data = arc_evict(state, 0, size, TRUE, type)) == NULL) {
2961168404Spjd		if (type == ARC_BUFC_METADATA) {
2962168404Spjd			buf->b_data = zio_buf_alloc(size);
2963208373Smm			arc_space_consume(size, ARC_SPACE_DATA);
2964168404Spjd		} else {
2965168404Spjd			ASSERT(type == ARC_BUFC_DATA);
2966168404Spjd			buf->b_data = zio_data_buf_alloc(size);
2967208373Smm			ARCSTAT_INCR(arcstat_data_size, size);
2968185029Spjd			atomic_add_64(&arc_size, size);
2969168404Spjd		}
2970168404Spjd		ARCSTAT_BUMP(arcstat_recycle_miss);
2971168404Spjd	}
2972168404Spjd	ASSERT(buf->b_data != NULL);
2973168404Spjdout:
2974168404Spjd	/*
2975168404Spjd	 * Update the state size.  Note that ghost states have a
2976168404Spjd	 * "ghost size" and so don't need to be updated.
2977168404Spjd	 */
2978168404Spjd	if (!GHOST_STATE(buf->b_hdr->b_state)) {
2979168404Spjd		arc_buf_hdr_t *hdr = buf->b_hdr;
2980168404Spjd
2981168404Spjd		atomic_add_64(&hdr->b_state->arcs_size, size);
2982168404Spjd		if (list_link_active(&hdr->b_arc_node)) {
2983168404Spjd			ASSERT(refcount_is_zero(&hdr->b_refcnt));
2984185029Spjd			atomic_add_64(&hdr->b_state->arcs_lsize[type], size);
2985168404Spjd		}
2986168404Spjd		/*
2987168404Spjd		 * If we are growing the cache, and we are adding anonymous
2988168404Spjd		 * data, and we have outgrown arc_p, update arc_p
2989168404Spjd		 */
2990168404Spjd		if (arc_size < arc_c && hdr->b_state == arc_anon &&
2991168404Spjd		    arc_anon->arcs_size + arc_mru->arcs_size > arc_p)
2992168404Spjd			arc_p = MIN(arc_c, arc_p + size);
2993168404Spjd	}
2994205231Skmacy	ARCSTAT_BUMP(arcstat_allocated);
2995168404Spjd}
2996168404Spjd
2997168404Spjd/*
2998168404Spjd * This routine is called whenever a buffer is accessed.
2999168404Spjd * NOTE: the hash lock is dropped in this function.
3000168404Spjd */
3001168404Spjdstatic void
3002275811Sdelphijarc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3003168404Spjd{
3004219089Spjd	clock_t now;
3005219089Spjd
3006168404Spjd	ASSERT(MUTEX_HELD(hash_lock));
3007168404Spjd
3008275811Sdelphij	if (hdr->b_state == arc_anon) {
3009168404Spjd		/*
3010168404Spjd		 * This buffer is not in the cache, and does not
3011168404Spjd		 * appear in our "ghost" list.  Add the new buffer
3012168404Spjd		 * to the MRU state.
3013168404Spjd		 */
3014168404Spjd
3015275811Sdelphij		ASSERT(hdr->b_arc_access == 0);
3016275811Sdelphij		hdr->b_arc_access = ddi_get_lbolt();
3017275811Sdelphij		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3018275811Sdelphij		arc_change_state(arc_mru, hdr, hash_lock);
3019168404Spjd
3020275811Sdelphij	} else if (hdr->b_state == arc_mru) {
3021219089Spjd		now = ddi_get_lbolt();
3022219089Spjd
3023168404Spjd		/*
3024168404Spjd		 * If this buffer is here because of a prefetch, then either:
3025168404Spjd		 * - clear the flag if this is a "referencing" read
3026168404Spjd		 *   (any subsequent access will bump this into the MFU state).
3027168404Spjd		 * or
3028168404Spjd		 * - move the buffer to the head of the list if this is
3029168404Spjd		 *   another prefetch (to make it less likely to be evicted).
3030168404Spjd		 */
3031275811Sdelphij		if ((hdr->b_flags & ARC_FLAG_PREFETCH) != 0) {
3032275811Sdelphij			if (refcount_count(&hdr->b_refcnt) == 0) {
3033275811Sdelphij				ASSERT(list_link_active(&hdr->b_arc_node));
3034168404Spjd			} else {
3035275811Sdelphij				hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3036168404Spjd				ARCSTAT_BUMP(arcstat_mru_hits);
3037168404Spjd			}
3038275811Sdelphij			hdr->b_arc_access = now;
3039168404Spjd			return;
3040168404Spjd		}
3041168404Spjd
3042168404Spjd		/*
3043168404Spjd		 * This buffer has been "accessed" only once so far,
3044168404Spjd		 * but it is still in the cache. Move it to the MFU
3045168404Spjd		 * state.
3046168404Spjd		 */
3047275811Sdelphij		if (now > hdr->b_arc_access + ARC_MINTIME) {
3048168404Spjd			/*
3049168404Spjd			 * More than 125ms have passed since we
3050168404Spjd			 * instantiated this buffer.  Move it to the
3051168404Spjd			 * most frequently used state.
3052168404Spjd			 */
3053275811Sdelphij			hdr->b_arc_access = now;
3054275811Sdelphij			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3055275811Sdelphij			arc_change_state(arc_mfu, hdr, hash_lock);
3056168404Spjd		}
3057168404Spjd		ARCSTAT_BUMP(arcstat_mru_hits);
3058275811Sdelphij	} else if (hdr->b_state == arc_mru_ghost) {
3059168404Spjd		arc_state_t	*new_state;
3060168404Spjd		/*
3061168404Spjd		 * This buffer has been "accessed" recently, but
3062168404Spjd		 * was evicted from the cache.  Move it to the
3063168404Spjd		 * MFU state.
3064168404Spjd		 */
3065168404Spjd
3066275811Sdelphij		if (hdr->b_flags & ARC_FLAG_PREFETCH) {
3067168404Spjd			new_state = arc_mru;
3068275811Sdelphij			if (refcount_count(&hdr->b_refcnt) > 0)
3069275811Sdelphij				hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3070275811Sdelphij			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3071168404Spjd		} else {
3072168404Spjd			new_state = arc_mfu;
3073275811Sdelphij			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3074168404Spjd		}
3075168404Spjd
3076275811Sdelphij		hdr->b_arc_access = ddi_get_lbolt();
3077275811Sdelphij		arc_change_state(new_state, hdr, hash_lock);
3078168404Spjd
3079168404Spjd		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
3080275811Sdelphij	} else if (hdr->b_state == arc_mfu) {
3081168404Spjd		/*
3082168404Spjd		 * This buffer has been accessed more than once and is
3083168404Spjd		 * still in the cache.  Keep it in the MFU state.
3084168404Spjd		 *
3085168404Spjd		 * NOTE: an add_reference() that occurred when we did
3086168404Spjd		 * the arc_read() will have kicked this off the list.
3087168404Spjd		 * If it was a prefetch, we will explicitly move it to
3088168404Spjd		 * the head of the list now.
3089168404Spjd		 */
3090275811Sdelphij		if ((hdr->b_flags & ARC_FLAG_PREFETCH) != 0) {
3091275811Sdelphij			ASSERT(refcount_count(&hdr->b_refcnt) == 0);
3092275811Sdelphij			ASSERT(list_link_active(&hdr->b_arc_node));
3093168404Spjd		}
3094168404Spjd		ARCSTAT_BUMP(arcstat_mfu_hits);
3095275811Sdelphij		hdr->b_arc_access = ddi_get_lbolt();
3096275811Sdelphij	} else if (hdr->b_state == arc_mfu_ghost) {
3097168404Spjd		arc_state_t	*new_state = arc_mfu;
3098168404Spjd		/*
3099168404Spjd		 * This buffer has been accessed more than once but has
3100168404Spjd		 * been evicted from the cache.  Move it back to the
3101168404Spjd		 * MFU state.
3102168404Spjd		 */
3103168404Spjd
3104275811Sdelphij		if (hdr->b_flags & ARC_FLAG_PREFETCH) {
3105168404Spjd			/*
3106168404Spjd			 * This is a prefetch access...
3107168404Spjd			 * move this block back to the MRU state.
3108168404Spjd			 */
3109275811Sdelphij			ASSERT0(refcount_count(&hdr->b_refcnt));
3110168404Spjd			new_state = arc_mru;
3111168404Spjd		}
3112168404Spjd
3113275811Sdelphij		hdr->b_arc_access = ddi_get_lbolt();
3114275811Sdelphij		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3115275811Sdelphij		arc_change_state(new_state, hdr, hash_lock);
3116168404Spjd
3117168404Spjd		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
3118275811Sdelphij	} else if (hdr->b_state == arc_l2c_only) {
3119185029Spjd		/*
3120185029Spjd		 * This buffer is on the 2nd Level ARC.
3121185029Spjd		 */
3122185029Spjd
3123275811Sdelphij		hdr->b_arc_access = ddi_get_lbolt();
3124275811Sdelphij		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3125275811Sdelphij		arc_change_state(arc_mfu, hdr, hash_lock);
3126168404Spjd	} else {
3127168404Spjd		ASSERT(!"invalid arc state");
3128168404Spjd	}
3129168404Spjd}
3130168404Spjd
3131168404Spjd/* a generic arc_done_func_t which you can use */
3132168404Spjd/* ARGSUSED */
3133168404Spjdvoid
3134168404Spjdarc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
3135168404Spjd{
3136219089Spjd	if (zio == NULL || zio->io_error == 0)
3137219089Spjd		bcopy(buf->b_data, arg, buf->b_hdr->b_size);
3138248571Smm	VERIFY(arc_buf_remove_ref(buf, arg));
3139168404Spjd}
3140168404Spjd
3141185029Spjd/* a generic arc_done_func_t */
3142168404Spjdvoid
3143168404Spjdarc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
3144168404Spjd{
3145168404Spjd	arc_buf_t **bufp = arg;
3146168404Spjd	if (zio && zio->io_error) {
3147248571Smm		VERIFY(arc_buf_remove_ref(buf, arg));
3148168404Spjd		*bufp = NULL;
3149168404Spjd	} else {
3150168404Spjd		*bufp = buf;
3151219089Spjd		ASSERT(buf->b_data);
3152168404Spjd	}
3153168404Spjd}
3154168404Spjd
3155168404Spjdstatic void
3156168404Spjdarc_read_done(zio_t *zio)
3157168404Spjd{
3158268075Sdelphij	arc_buf_hdr_t	*hdr;
3159168404Spjd	arc_buf_t	*buf;
3160168404Spjd	arc_buf_t	*abuf;	/* buffer we're assigning to callback */
3161268075Sdelphij	kmutex_t	*hash_lock = NULL;
3162168404Spjd	arc_callback_t	*callback_list, *acb;
3163168404Spjd	int		freeable = FALSE;
3164168404Spjd
3165168404Spjd	buf = zio->io_private;
3166168404Spjd	hdr = buf->b_hdr;
3167168404Spjd
3168168404Spjd	/*
3169168404Spjd	 * The hdr was inserted into hash-table and removed from lists
3170168404Spjd	 * prior to starting I/O.  We should find this header, since
3171168404Spjd	 * it's in the hash table, and it should be legit since it's
3172168404Spjd	 * not possible to evict it during the I/O.  The only possible
3173168404Spjd	 * reason for it not to be found is if we were freed during the
3174168404Spjd	 * read.
3175168404Spjd	 */
3176268075Sdelphij	if (HDR_IN_HASH_TABLE(hdr)) {
3177268075Sdelphij		ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
3178268075Sdelphij		ASSERT3U(hdr->b_dva.dva_word[0], ==,
3179268075Sdelphij		    BP_IDENTITY(zio->io_bp)->dva_word[0]);
3180268075Sdelphij		ASSERT3U(hdr->b_dva.dva_word[1], ==,
3181268075Sdelphij		    BP_IDENTITY(zio->io_bp)->dva_word[1]);
3182168404Spjd
3183268075Sdelphij		arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
3184268075Sdelphij		    &hash_lock);
3185168404Spjd
3186268075Sdelphij		ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) &&
3187268075Sdelphij		    hash_lock == NULL) ||
3188268075Sdelphij		    (found == hdr &&
3189268075Sdelphij		    DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
3190268075Sdelphij		    (found == hdr && HDR_L2_READING(hdr)));
3191268075Sdelphij	}
3192268075Sdelphij
3193275811Sdelphij	hdr->b_flags &= ~ARC_FLAG_L2_EVICTED;
3194275811Sdelphij	if (l2arc_noprefetch && (hdr->b_flags & ARC_FLAG_PREFETCH))
3195275811Sdelphij		hdr->b_flags &= ~ARC_FLAG_L2CACHE;
3196206796Spjd
3197168404Spjd	/* byteswap if necessary */
3198168404Spjd	callback_list = hdr->b_acb;
3199168404Spjd	ASSERT(callback_list != NULL);
3200209101Smm	if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
3201236884Smm		dmu_object_byteswap_t bswap =
3202236884Smm		    DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
3203185029Spjd		arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
3204185029Spjd		    byteswap_uint64_array :
3205236884Smm		    dmu_ot_byteswap[bswap].ob_func;
3206185029Spjd		func(buf->b_data, hdr->b_size);
3207185029Spjd	}
3208168404Spjd
3209185029Spjd	arc_cksum_compute(buf, B_FALSE);
3210240133Smm#ifdef illumos
3211240133Smm	arc_buf_watch(buf);
3212277300Ssmh#endif
3213168404Spjd
3214219089Spjd	if (hash_lock && zio->io_error == 0 && hdr->b_state == arc_anon) {
3215219089Spjd		/*
3216219089Spjd		 * Only call arc_access on anonymous buffers.  This is because
3217219089Spjd		 * if we've issued an I/O for an evicted buffer, we've already
3218219089Spjd		 * called arc_access (to prevent any simultaneous readers from
3219219089Spjd		 * getting confused).
3220219089Spjd		 */
3221219089Spjd		arc_access(hdr, hash_lock);
3222219089Spjd	}
3223219089Spjd
3224168404Spjd	/* create copies of the data buffer for the callers */
3225168404Spjd	abuf = buf;
3226168404Spjd	for (acb = callback_list; acb; acb = acb->acb_next) {
3227168404Spjd		if (acb->acb_done) {
3228242845Sdelphij			if (abuf == NULL) {
3229242845Sdelphij				ARCSTAT_BUMP(arcstat_duplicate_reads);
3230168404Spjd				abuf = arc_buf_clone(buf);
3231242845Sdelphij			}
3232168404Spjd			acb->acb_buf = abuf;
3233168404Spjd			abuf = NULL;
3234168404Spjd		}
3235168404Spjd	}
3236168404Spjd	hdr->b_acb = NULL;
3237275811Sdelphij	hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
3238168404Spjd	ASSERT(!HDR_BUF_AVAILABLE(hdr));
3239219089Spjd	if (abuf == buf) {
3240219089Spjd		ASSERT(buf->b_efunc == NULL);
3241219089Spjd		ASSERT(hdr->b_datacnt == 1);
3242275811Sdelphij		hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
3243219089Spjd	}
3244168404Spjd
3245168404Spjd	ASSERT(refcount_is_zero(&hdr->b_refcnt) || callback_list != NULL);
3246168404Spjd
3247168404Spjd	if (zio->io_error != 0) {
3248275811Sdelphij		hdr->b_flags |= ARC_FLAG_IO_ERROR;
3249168404Spjd		if (hdr->b_state != arc_anon)
3250168404Spjd			arc_change_state(arc_anon, hdr, hash_lock);
3251168404Spjd		if (HDR_IN_HASH_TABLE(hdr))
3252168404Spjd			buf_hash_remove(hdr);
3253168404Spjd		freeable = refcount_is_zero(&hdr->b_refcnt);
3254168404Spjd	}
3255168404Spjd
3256168404Spjd	/*
3257168404Spjd	 * Broadcast before we drop the hash_lock to avoid the possibility
3258168404Spjd	 * that the hdr (and hence the cv) might be freed before we get to
3259168404Spjd	 * the cv_broadcast().
3260168404Spjd	 */
3261168404Spjd	cv_broadcast(&hdr->b_cv);
3262168404Spjd
3263168404Spjd	if (hash_lock) {
3264168404Spjd		mutex_exit(hash_lock);
3265168404Spjd	} else {
3266168404Spjd		/*
3267168404Spjd		 * This block was freed while we waited for the read to
3268168404Spjd		 * complete.  It has been removed from the hash table and
3269168404Spjd		 * moved to the anonymous state (so that it won't show up
3270168404Spjd		 * in the cache).
3271168404Spjd		 */
3272168404Spjd		ASSERT3P(hdr->b_state, ==, arc_anon);
3273168404Spjd		freeable = refcount_is_zero(&hdr->b_refcnt);
3274168404Spjd	}
3275168404Spjd
3276168404Spjd	/* execute each callback and free its structure */
3277168404Spjd	while ((acb = callback_list) != NULL) {
3278168404Spjd		if (acb->acb_done)
3279168404Spjd			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
3280168404Spjd
3281168404Spjd		if (acb->acb_zio_dummy != NULL) {
3282168404Spjd			acb->acb_zio_dummy->io_error = zio->io_error;
3283168404Spjd			zio_nowait(acb->acb_zio_dummy);
3284168404Spjd		}
3285168404Spjd
3286168404Spjd		callback_list = acb->acb_next;
3287168404Spjd		kmem_free(acb, sizeof (arc_callback_t));
3288168404Spjd	}
3289168404Spjd
3290168404Spjd	if (freeable)
3291168404Spjd		arc_hdr_destroy(hdr);
3292168404Spjd}
3293168404Spjd
3294168404Spjd/*
3295168404Spjd * "Read" the block block at the specified DVA (in bp) via the
3296168404Spjd * cache.  If the block is found in the cache, invoke the provided
3297168404Spjd * callback immediately and return.  Note that the `zio' parameter
3298168404Spjd * in the callback will be NULL in this case, since no IO was
3299168404Spjd * required.  If the block is not in the cache pass the read request
3300168404Spjd * on to the spa with a substitute callback function, so that the
3301168404Spjd * requested block will be added to the cache.
3302168404Spjd *
3303168404Spjd * If a read request arrives for a block that has a read in-progress,
3304168404Spjd * either wait for the in-progress read to complete (and return the
3305168404Spjd * results); or, if this is a read with a "done" func, add a record
3306168404Spjd * to the read to invoke the "done" func when the read completes,
3307168404Spjd * and return; or just return.
3308168404Spjd *
3309168404Spjd * arc_read_done() will invoke all the requested "done" functions
3310168404Spjd * for readers of this block.
3311168404Spjd */
3312168404Spjdint
3313246666Smmarc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
3314275811Sdelphij    void *private, zio_priority_t priority, int zio_flags,
3315275811Sdelphij    arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
3316168404Spjd{
3317268075Sdelphij	arc_buf_hdr_t *hdr = NULL;
3318247187Smm	arc_buf_t *buf = NULL;
3319268075Sdelphij	kmutex_t *hash_lock = NULL;
3320185029Spjd	zio_t *rzio;
3321228103Smm	uint64_t guid = spa_load_guid(spa);
3322168404Spjd
3323268075Sdelphij	ASSERT(!BP_IS_EMBEDDED(bp) ||
3324268075Sdelphij	    BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
3325268075Sdelphij
3326168404Spjdtop:
3327268075Sdelphij	if (!BP_IS_EMBEDDED(bp)) {
3328268075Sdelphij		/*
3329268075Sdelphij		 * Embedded BP's have no DVA and require no I/O to "read".
3330268075Sdelphij		 * Create an anonymous arc buf to back it.
3331268075Sdelphij		 */
3332268075Sdelphij		hdr = buf_hash_find(guid, bp, &hash_lock);
3333268075Sdelphij	}
3334168404Spjd
3335268075Sdelphij	if (hdr != NULL && hdr->b_datacnt > 0) {
3336268075Sdelphij
3337275811Sdelphij		*arc_flags |= ARC_FLAG_CACHED;
3338168404Spjd
3339168404Spjd		if (HDR_IO_IN_PROGRESS(hdr)) {
3340168404Spjd
3341275811Sdelphij			if (*arc_flags & ARC_FLAG_WAIT) {
3342168404Spjd				cv_wait(&hdr->b_cv, hash_lock);
3343168404Spjd				mutex_exit(hash_lock);
3344168404Spjd				goto top;
3345168404Spjd			}
3346275811Sdelphij			ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
3347168404Spjd
3348168404Spjd			if (done) {
3349168404Spjd				arc_callback_t	*acb = NULL;
3350168404Spjd
3351168404Spjd				acb = kmem_zalloc(sizeof (arc_callback_t),
3352168404Spjd				    KM_SLEEP);
3353168404Spjd				acb->acb_done = done;
3354168404Spjd				acb->acb_private = private;
3355168404Spjd				if (pio != NULL)
3356168404Spjd					acb->acb_zio_dummy = zio_null(pio,
3357209962Smm					    spa, NULL, NULL, NULL, zio_flags);
3358168404Spjd
3359168404Spjd				ASSERT(acb->acb_done != NULL);
3360168404Spjd				acb->acb_next = hdr->b_acb;
3361168404Spjd				hdr->b_acb = acb;
3362168404Spjd				add_reference(hdr, hash_lock, private);
3363168404Spjd				mutex_exit(hash_lock);
3364168404Spjd				return (0);
3365168404Spjd			}
3366168404Spjd			mutex_exit(hash_lock);
3367168404Spjd			return (0);
3368168404Spjd		}
3369168404Spjd
3370168404Spjd		ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3371168404Spjd
3372168404Spjd		if (done) {
3373168404Spjd			add_reference(hdr, hash_lock, private);
3374168404Spjd			/*
3375168404Spjd			 * If this block is already in use, create a new
3376168404Spjd			 * copy of the data so that we will be guaranteed
3377168404Spjd			 * that arc_release() will always succeed.
3378168404Spjd			 */
3379168404Spjd			buf = hdr->b_buf;
3380168404Spjd			ASSERT(buf);
3381168404Spjd			ASSERT(buf->b_data);
3382168404Spjd			if (HDR_BUF_AVAILABLE(hdr)) {
3383168404Spjd				ASSERT(buf->b_efunc == NULL);
3384275811Sdelphij				hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
3385168404Spjd			} else {
3386168404Spjd				buf = arc_buf_clone(buf);
3387168404Spjd			}
3388219089Spjd
3389275811Sdelphij		} else if (*arc_flags & ARC_FLAG_PREFETCH &&
3390168404Spjd		    refcount_count(&hdr->b_refcnt) == 0) {
3391275811Sdelphij			hdr->b_flags |= ARC_FLAG_PREFETCH;
3392168404Spjd		}
3393168404Spjd		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
3394168404Spjd		arc_access(hdr, hash_lock);
3395275811Sdelphij		if (*arc_flags & ARC_FLAG_L2CACHE)
3396275811Sdelphij			hdr->b_flags |= ARC_FLAG_L2CACHE;
3397275811Sdelphij		if (*arc_flags & ARC_FLAG_L2COMPRESS)
3398275811Sdelphij			hdr->b_flags |= ARC_FLAG_L2COMPRESS;
3399168404Spjd		mutex_exit(hash_lock);
3400168404Spjd		ARCSTAT_BUMP(arcstat_hits);
3401275811Sdelphij		ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_FLAG_PREFETCH),
3402168404Spjd		    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3403168404Spjd		    data, metadata, hits);
3404168404Spjd
3405168404Spjd		if (done)
3406168404Spjd			done(NULL, buf, private);
3407168404Spjd	} else {
3408168404Spjd		uint64_t size = BP_GET_LSIZE(bp);
3409268075Sdelphij		arc_callback_t *acb;
3410185029Spjd		vdev_t *vd = NULL;
3411247187Smm		uint64_t addr = 0;
3412208373Smm		boolean_t devw = B_FALSE;
3413258389Savg		enum zio_compress b_compress = ZIO_COMPRESS_OFF;
3414258389Savg		uint64_t b_asize = 0;
3415168404Spjd
3416168404Spjd		if (hdr == NULL) {
3417168404Spjd			/* this block is not in the cache */
3418268075Sdelphij			arc_buf_hdr_t *exists = NULL;
3419168404Spjd			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
3420168404Spjd			buf = arc_buf_alloc(spa, size, private, type);
3421168404Spjd			hdr = buf->b_hdr;
3422268075Sdelphij			if (!BP_IS_EMBEDDED(bp)) {
3423268075Sdelphij				hdr->b_dva = *BP_IDENTITY(bp);
3424268075Sdelphij				hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
3425268075Sdelphij				hdr->b_cksum0 = bp->blk_cksum.zc_word[0];
3426268075Sdelphij				exists = buf_hash_insert(hdr, &hash_lock);
3427268075Sdelphij			}
3428268075Sdelphij			if (exists != NULL) {
3429168404Spjd				/* somebody beat us to the hash insert */
3430168404Spjd				mutex_exit(hash_lock);
3431219089Spjd				buf_discard_identity(hdr);
3432168404Spjd				(void) arc_buf_remove_ref(buf, private);
3433168404Spjd				goto top; /* restart the IO request */
3434168404Spjd			}
3435275811Sdelphij
3436168404Spjd			/* if this is a prefetch, we don't have a reference */
3437275811Sdelphij			if (*arc_flags & ARC_FLAG_PREFETCH) {
3438168404Spjd				(void) remove_reference(hdr, hash_lock,
3439168404Spjd				    private);
3440275811Sdelphij				hdr->b_flags |= ARC_FLAG_PREFETCH;
3441168404Spjd			}
3442275811Sdelphij			if (*arc_flags & ARC_FLAG_L2CACHE)
3443275811Sdelphij				hdr->b_flags |= ARC_FLAG_L2CACHE;
3444275811Sdelphij			if (*arc_flags & ARC_FLAG_L2COMPRESS)
3445275811Sdelphij				hdr->b_flags |= ARC_FLAG_L2COMPRESS;
3446168404Spjd			if (BP_GET_LEVEL(bp) > 0)
3447275811Sdelphij				hdr->b_flags |= ARC_FLAG_INDIRECT;
3448168404Spjd		} else {
3449168404Spjd			/* this block is in the ghost cache */
3450168404Spjd			ASSERT(GHOST_STATE(hdr->b_state));
3451168404Spjd			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3452240415Smm			ASSERT0(refcount_count(&hdr->b_refcnt));
3453168404Spjd			ASSERT(hdr->b_buf == NULL);
3454168404Spjd
3455168404Spjd			/* if this is a prefetch, we don't have a reference */
3456275811Sdelphij			if (*arc_flags & ARC_FLAG_PREFETCH)
3457275811Sdelphij				hdr->b_flags |= ARC_FLAG_PREFETCH;
3458168404Spjd			else
3459168404Spjd				add_reference(hdr, hash_lock, private);
3460275811Sdelphij			if (*arc_flags & ARC_FLAG_L2CACHE)
3461275811Sdelphij				hdr->b_flags |= ARC_FLAG_L2CACHE;
3462275811Sdelphij			if (*arc_flags & ARC_FLAG_L2COMPRESS)
3463275811Sdelphij				hdr->b_flags |= ARC_FLAG_L2COMPRESS;
3464185029Spjd			buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
3465168404Spjd			buf->b_hdr = hdr;
3466168404Spjd			buf->b_data = NULL;
3467168404Spjd			buf->b_efunc = NULL;
3468168404Spjd			buf->b_private = NULL;
3469168404Spjd			buf->b_next = NULL;
3470168404Spjd			hdr->b_buf = buf;
3471168404Spjd			ASSERT(hdr->b_datacnt == 0);
3472168404Spjd			hdr->b_datacnt = 1;
3473219089Spjd			arc_get_data_buf(buf);
3474219089Spjd			arc_access(hdr, hash_lock);
3475168404Spjd		}
3476168404Spjd
3477219089Spjd		ASSERT(!GHOST_STATE(hdr->b_state));
3478219089Spjd
3479168404Spjd		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
3480168404Spjd		acb->acb_done = done;
3481168404Spjd		acb->acb_private = private;
3482168404Spjd
3483168404Spjd		ASSERT(hdr->b_acb == NULL);
3484168404Spjd		hdr->b_acb = acb;
3485275811Sdelphij		hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
3486168404Spjd
3487258389Savg		if (hdr->b_l2hdr != NULL &&
3488185029Spjd		    (vd = hdr->b_l2hdr->b_dev->l2ad_vdev) != NULL) {
3489208373Smm			devw = hdr->b_l2hdr->b_dev->l2ad_writing;
3490185029Spjd			addr = hdr->b_l2hdr->b_daddr;
3491258389Savg			b_compress = hdr->b_l2hdr->b_compress;
3492258389Savg			b_asize = hdr->b_l2hdr->b_asize;
3493185029Spjd			/*
3494185029Spjd			 * Lock out device removal.
3495185029Spjd			 */
3496185029Spjd			if (vdev_is_dead(vd) ||
3497185029Spjd			    !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
3498185029Spjd				vd = NULL;
3499185029Spjd		}
3500185029Spjd
3501268075Sdelphij		if (hash_lock != NULL)
3502268075Sdelphij			mutex_exit(hash_lock);
3503168404Spjd
3504251629Sdelphij		/*
3505251629Sdelphij		 * At this point, we have a level 1 cache miss.  Try again in
3506251629Sdelphij		 * L2ARC if possible.
3507251629Sdelphij		 */
3508168404Spjd		ASSERT3U(hdr->b_size, ==, size);
3509219089Spjd		DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
3510268123Sdelphij		    uint64_t, size, zbookmark_phys_t *, zb);
3511168404Spjd		ARCSTAT_BUMP(arcstat_misses);
3512275811Sdelphij		ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_FLAG_PREFETCH),
3513168404Spjd		    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3514168404Spjd		    data, metadata, misses);
3515228392Spjd#ifdef _KERNEL
3516228392Spjd		curthread->td_ru.ru_inblock++;
3517228392Spjd#endif
3518168404Spjd
3519208373Smm		if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
3520185029Spjd			/*
3521185029Spjd			 * Read from the L2ARC if the following are true:
3522185029Spjd			 * 1. The L2ARC vdev was previously cached.
3523185029Spjd			 * 2. This buffer still has L2ARC metadata.
3524185029Spjd			 * 3. This buffer isn't currently writing to the L2ARC.
3525185029Spjd			 * 4. The L2ARC entry wasn't evicted, which may
3526185029Spjd			 *    also have invalidated the vdev.
3527208373Smm			 * 5. This isn't prefetch and l2arc_noprefetch is set.
3528185029Spjd			 */
3529185029Spjd			if (hdr->b_l2hdr != NULL &&
3530208373Smm			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
3531208373Smm			    !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
3532185029Spjd				l2arc_read_callback_t *cb;
3533185029Spjd
3534185029Spjd				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
3535185029Spjd				ARCSTAT_BUMP(arcstat_l2_hits);
3536185029Spjd
3537185029Spjd				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
3538185029Spjd				    KM_SLEEP);
3539185029Spjd				cb->l2rcb_buf = buf;
3540185029Spjd				cb->l2rcb_spa = spa;
3541185029Spjd				cb->l2rcb_bp = *bp;
3542185029Spjd				cb->l2rcb_zb = *zb;
3543185029Spjd				cb->l2rcb_flags = zio_flags;
3544258389Savg				cb->l2rcb_compress = b_compress;
3545185029Spjd
3546247187Smm				ASSERT(addr >= VDEV_LABEL_START_SIZE &&
3547247187Smm				    addr + size < vd->vdev_psize -
3548247187Smm				    VDEV_LABEL_END_SIZE);
3549247187Smm
3550185029Spjd				/*
3551185029Spjd				 * l2arc read.  The SCL_L2ARC lock will be
3552185029Spjd				 * released by l2arc_read_done().
3553251478Sdelphij				 * Issue a null zio if the underlying buffer
3554251478Sdelphij				 * was squashed to zero size by compression.
3555185029Spjd				 */
3556258389Savg				if (b_compress == ZIO_COMPRESS_EMPTY) {
3557251478Sdelphij					rzio = zio_null(pio, spa, vd,
3558251478Sdelphij					    l2arc_read_done, cb,
3559251478Sdelphij					    zio_flags | ZIO_FLAG_DONT_CACHE |
3560251478Sdelphij					    ZIO_FLAG_CANFAIL |
3561251478Sdelphij					    ZIO_FLAG_DONT_PROPAGATE |
3562251478Sdelphij					    ZIO_FLAG_DONT_RETRY);
3563251478Sdelphij				} else {
3564251478Sdelphij					rzio = zio_read_phys(pio, vd, addr,
3565258389Savg					    b_asize, buf->b_data,
3566258389Savg					    ZIO_CHECKSUM_OFF,
3567251478Sdelphij					    l2arc_read_done, cb, priority,
3568251478Sdelphij					    zio_flags | ZIO_FLAG_DONT_CACHE |
3569251478Sdelphij					    ZIO_FLAG_CANFAIL |
3570251478Sdelphij					    ZIO_FLAG_DONT_PROPAGATE |
3571251478Sdelphij					    ZIO_FLAG_DONT_RETRY, B_FALSE);
3572251478Sdelphij				}
3573185029Spjd				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
3574185029Spjd				    zio_t *, rzio);
3575258389Savg				ARCSTAT_INCR(arcstat_l2_read_bytes, b_asize);
3576185029Spjd
3577275811Sdelphij				if (*arc_flags & ARC_FLAG_NOWAIT) {
3578185029Spjd					zio_nowait(rzio);
3579185029Spjd					return (0);
3580185029Spjd				}
3581185029Spjd
3582275811Sdelphij				ASSERT(*arc_flags & ARC_FLAG_WAIT);
3583185029Spjd				if (zio_wait(rzio) == 0)
3584185029Spjd					return (0);
3585185029Spjd
3586185029Spjd				/* l2arc read error; goto zio_read() */
3587185029Spjd			} else {
3588185029Spjd				DTRACE_PROBE1(l2arc__miss,
3589185029Spjd				    arc_buf_hdr_t *, hdr);
3590185029Spjd				ARCSTAT_BUMP(arcstat_l2_misses);
3591185029Spjd				if (HDR_L2_WRITING(hdr))
3592185029Spjd					ARCSTAT_BUMP(arcstat_l2_rw_clash);
3593185029Spjd				spa_config_exit(spa, SCL_L2ARC, vd);
3594185029Spjd			}
3595208373Smm		} else {
3596208373Smm			if (vd != NULL)
3597208373Smm				spa_config_exit(spa, SCL_L2ARC, vd);
3598208373Smm			if (l2arc_ndev != 0) {
3599208373Smm				DTRACE_PROBE1(l2arc__miss,
3600208373Smm				    arc_buf_hdr_t *, hdr);
3601208373Smm				ARCSTAT_BUMP(arcstat_l2_misses);
3602208373Smm			}
3603185029Spjd		}
3604185029Spjd
3605168404Spjd		rzio = zio_read(pio, spa, bp, buf->b_data, size,
3606185029Spjd		    arc_read_done, buf, priority, zio_flags, zb);
3607168404Spjd
3608275811Sdelphij		if (*arc_flags & ARC_FLAG_WAIT)
3609168404Spjd			return (zio_wait(rzio));
3610168404Spjd
3611275811Sdelphij		ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
3612168404Spjd		zio_nowait(rzio);
3613168404Spjd	}
3614168404Spjd	return (0);
3615168404Spjd}
3616168404Spjd
3617168404Spjdvoid
3618168404Spjdarc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
3619168404Spjd{
3620168404Spjd	ASSERT(buf->b_hdr != NULL);
3621168404Spjd	ASSERT(buf->b_hdr->b_state != arc_anon);
3622168404Spjd	ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt) || func == NULL);
3623219089Spjd	ASSERT(buf->b_efunc == NULL);
3624219089Spjd	ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
3625219089Spjd
3626168404Spjd	buf->b_efunc = func;
3627168404Spjd	buf->b_private = private;
3628168404Spjd}
3629168404Spjd
3630168404Spjd/*
3631251520Sdelphij * Notify the arc that a block was freed, and thus will never be used again.
3632251520Sdelphij */
3633251520Sdelphijvoid
3634251520Sdelphijarc_freed(spa_t *spa, const blkptr_t *bp)
3635251520Sdelphij{
3636251520Sdelphij	arc_buf_hdr_t *hdr;
3637251520Sdelphij	kmutex_t *hash_lock;
3638251520Sdelphij	uint64_t guid = spa_load_guid(spa);
3639251520Sdelphij
3640268075Sdelphij	ASSERT(!BP_IS_EMBEDDED(bp));
3641268075Sdelphij
3642268075Sdelphij	hdr = buf_hash_find(guid, bp, &hash_lock);
3643251520Sdelphij	if (hdr == NULL)
3644251520Sdelphij		return;
3645251520Sdelphij	if (HDR_BUF_AVAILABLE(hdr)) {
3646251520Sdelphij		arc_buf_t *buf = hdr->b_buf;
3647251520Sdelphij		add_reference(hdr, hash_lock, FTAG);
3648275811Sdelphij		hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
3649251520Sdelphij		mutex_exit(hash_lock);
3650251520Sdelphij
3651251520Sdelphij		arc_release(buf, FTAG);
3652251520Sdelphij		(void) arc_buf_remove_ref(buf, FTAG);
3653251520Sdelphij	} else {
3654251520Sdelphij		mutex_exit(hash_lock);
3655251520Sdelphij	}
3656251520Sdelphij
3657251520Sdelphij}
3658251520Sdelphij
3659251520Sdelphij/*
3660268858Sdelphij * Clear the user eviction callback set by arc_set_callback(), first calling
3661268858Sdelphij * it if it exists.  Because the presence of a callback keeps an arc_buf cached
3662268858Sdelphij * clearing the callback may result in the arc_buf being destroyed.  However,
3663268858Sdelphij * it will not result in the *last* arc_buf being destroyed, hence the data
3664268858Sdelphij * will remain cached in the ARC. We make a copy of the arc buffer here so
3665268858Sdelphij * that we can process the callback without holding any locks.
3666268858Sdelphij *
3667268858Sdelphij * It's possible that the callback is already in the process of being cleared
3668268858Sdelphij * by another thread.  In this case we can not clear the callback.
3669268858Sdelphij *
3670268858Sdelphij * Returns B_TRUE if the callback was successfully called and cleared.
3671168404Spjd */
3672268858Sdelphijboolean_t
3673268858Sdelphijarc_clear_callback(arc_buf_t *buf)
3674168404Spjd{
3675168404Spjd	arc_buf_hdr_t *hdr;
3676168404Spjd	kmutex_t *hash_lock;
3677268858Sdelphij	arc_evict_func_t *efunc = buf->b_efunc;
3678268858Sdelphij	void *private = buf->b_private;
3679205231Skmacy	list_t *list, *evicted_list;
3680205231Skmacy	kmutex_t *lock, *evicted_lock;
3681206796Spjd
3682219089Spjd	mutex_enter(&buf->b_evict_lock);
3683168404Spjd	hdr = buf->b_hdr;
3684168404Spjd	if (hdr == NULL) {
3685168404Spjd		/*
3686168404Spjd		 * We are in arc_do_user_evicts().
3687168404Spjd		 */
3688168404Spjd		ASSERT(buf->b_data == NULL);
3689219089Spjd		mutex_exit(&buf->b_evict_lock);
3690268858Sdelphij		return (B_FALSE);
3691185029Spjd	} else if (buf->b_data == NULL) {
3692185029Spjd		/*
3693185029Spjd		 * We are on the eviction list; process this buffer now
3694185029Spjd		 * but let arc_do_user_evicts() do the reaping.
3695185029Spjd		 */
3696185029Spjd		buf->b_efunc = NULL;
3697219089Spjd		mutex_exit(&buf->b_evict_lock);
3698268858Sdelphij		VERIFY0(efunc(private));
3699268858Sdelphij		return (B_TRUE);
3700168404Spjd	}
3701168404Spjd	hash_lock = HDR_LOCK(hdr);
3702168404Spjd	mutex_enter(hash_lock);
3703219089Spjd	hdr = buf->b_hdr;
3704219089Spjd	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3705168404Spjd
3706168404Spjd	ASSERT3U(refcount_count(&hdr->b_refcnt), <, hdr->b_datacnt);
3707168404Spjd	ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3708168404Spjd
3709268858Sdelphij	buf->b_efunc = NULL;
3710268858Sdelphij	buf->b_private = NULL;
3711168404Spjd
3712268858Sdelphij	if (hdr->b_datacnt > 1) {
3713268858Sdelphij		mutex_exit(&buf->b_evict_lock);
3714268858Sdelphij		arc_buf_destroy(buf, FALSE, TRUE);
3715268858Sdelphij	} else {
3716268858Sdelphij		ASSERT(buf == hdr->b_buf);
3717275811Sdelphij		hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
3718268858Sdelphij		mutex_exit(&buf->b_evict_lock);
3719268858Sdelphij	}
3720168404Spjd
3721168404Spjd	mutex_exit(hash_lock);
3722268858Sdelphij	VERIFY0(efunc(private));
3723268858Sdelphij	return (B_TRUE);
3724168404Spjd}
3725168404Spjd
3726168404Spjd/*
3727251629Sdelphij * Release this buffer from the cache, making it an anonymous buffer.  This
3728251629Sdelphij * must be done after a read and prior to modifying the buffer contents.
3729168404Spjd * If the buffer has more than one reference, we must make
3730185029Spjd * a new hdr for the buffer.
3731168404Spjd */
3732168404Spjdvoid
3733168404Spjdarc_release(arc_buf_t *buf, void *tag)
3734168404Spjd{
3735185029Spjd	arc_buf_hdr_t *hdr;
3736219089Spjd	kmutex_t *hash_lock = NULL;
3737185029Spjd	l2arc_buf_hdr_t *l2hdr;
3738185029Spjd	uint64_t buf_size;
3739168404Spjd
3740219089Spjd	/*
3741219089Spjd	 * It would be nice to assert that if it's DMU metadata (level >
3742219089Spjd	 * 0 || it's the dnode file), then it must be syncing context.
3743219089Spjd	 * But we don't know that information at this level.
3744219089Spjd	 */
3745219089Spjd
3746219089Spjd	mutex_enter(&buf->b_evict_lock);
3747185029Spjd	hdr = buf->b_hdr;
3748185029Spjd
3749168404Spjd	/* this buffer is not on any list */
3750168404Spjd	ASSERT(refcount_count(&hdr->b_refcnt) > 0);
3751168404Spjd
3752168404Spjd	if (hdr->b_state == arc_anon) {
3753168404Spjd		/* this buffer is already released */
3754168404Spjd		ASSERT(buf->b_efunc == NULL);
3755208373Smm	} else {
3756208373Smm		hash_lock = HDR_LOCK(hdr);
3757208373Smm		mutex_enter(hash_lock);
3758219089Spjd		hdr = buf->b_hdr;
3759219089Spjd		ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3760168404Spjd	}
3761168404Spjd
3762185029Spjd	l2hdr = hdr->b_l2hdr;
3763185029Spjd	if (l2hdr) {
3764185029Spjd		mutex_enter(&l2arc_buflist_mtx);
3765274172Savg		arc_buf_l2_cdata_free(hdr);
3766185029Spjd		hdr->b_l2hdr = NULL;
3767258388Savg		list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
3768185029Spjd	}
3769247187Smm	buf_size = hdr->b_size;
3770185029Spjd
3771168404Spjd	/*
3772168404Spjd	 * Do we have more than one buf?
3773168404Spjd	 */
3774185029Spjd	if (hdr->b_datacnt > 1) {
3775168404Spjd		arc_buf_hdr_t *nhdr;
3776168404Spjd		arc_buf_t **bufp;
3777168404Spjd		uint64_t blksz = hdr->b_size;
3778209962Smm		uint64_t spa = hdr->b_spa;
3779168404Spjd		arc_buf_contents_t type = hdr->b_type;
3780185029Spjd		uint32_t flags = hdr->b_flags;
3781168404Spjd
3782185029Spjd		ASSERT(hdr->b_buf != buf || buf->b_next != NULL);
3783168404Spjd		/*
3784219089Spjd		 * Pull the data off of this hdr and attach it to
3785219089Spjd		 * a new anonymous hdr.
3786168404Spjd		 */
3787168404Spjd		(void) remove_reference(hdr, hash_lock, tag);
3788168404Spjd		bufp = &hdr->b_buf;
3789168404Spjd		while (*bufp != buf)
3790168404Spjd			bufp = &(*bufp)->b_next;
3791219089Spjd		*bufp = buf->b_next;
3792168404Spjd		buf->b_next = NULL;
3793168404Spjd
3794168404Spjd		ASSERT3U(hdr->b_state->arcs_size, >=, hdr->b_size);
3795168404Spjd		atomic_add_64(&hdr->b_state->arcs_size, -hdr->b_size);
3796168404Spjd		if (refcount_is_zero(&hdr->b_refcnt)) {
3797185029Spjd			uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
3798185029Spjd			ASSERT3U(*size, >=, hdr->b_size);
3799185029Spjd			atomic_add_64(size, -hdr->b_size);
3800168404Spjd		}
3801242845Sdelphij
3802242845Sdelphij		/*
3803242845Sdelphij		 * We're releasing a duplicate user data buffer, update
3804242845Sdelphij		 * our statistics accordingly.
3805242845Sdelphij		 */
3806242845Sdelphij		if (hdr->b_type == ARC_BUFC_DATA) {
3807242845Sdelphij			ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
3808242845Sdelphij			ARCSTAT_INCR(arcstat_duplicate_buffers_size,
3809242845Sdelphij			    -hdr->b_size);
3810242845Sdelphij		}
3811168404Spjd		hdr->b_datacnt -= 1;
3812168404Spjd		arc_cksum_verify(buf);
3813240133Smm#ifdef illumos
3814240133Smm		arc_buf_unwatch(buf);
3815277300Ssmh#endif
3816168404Spjd
3817168404Spjd		mutex_exit(hash_lock);
3818168404Spjd
3819185029Spjd		nhdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
3820168404Spjd		nhdr->b_size = blksz;
3821168404Spjd		nhdr->b_spa = spa;
3822168404Spjd		nhdr->b_type = type;
3823168404Spjd		nhdr->b_buf = buf;
3824168404Spjd		nhdr->b_state = arc_anon;
3825168404Spjd		nhdr->b_arc_access = 0;
3826275811Sdelphij		nhdr->b_flags = flags & ARC_FLAG_L2_WRITING;
3827185029Spjd		nhdr->b_l2hdr = NULL;
3828168404Spjd		nhdr->b_datacnt = 1;
3829168404Spjd		nhdr->b_freeze_cksum = NULL;
3830168404Spjd		(void) refcount_add(&nhdr->b_refcnt, tag);
3831168404Spjd		buf->b_hdr = nhdr;
3832219089Spjd		mutex_exit(&buf->b_evict_lock);
3833168404Spjd		atomic_add_64(&arc_anon->arcs_size, blksz);
3834168404Spjd	} else {
3835219089Spjd		mutex_exit(&buf->b_evict_lock);
3836168404Spjd		ASSERT(refcount_count(&hdr->b_refcnt) == 1);
3837168404Spjd		ASSERT(!list_link_active(&hdr->b_arc_node));
3838168404Spjd		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3839219089Spjd		if (hdr->b_state != arc_anon)
3840219089Spjd			arc_change_state(arc_anon, hdr, hash_lock);
3841168404Spjd		hdr->b_arc_access = 0;
3842219089Spjd		if (hash_lock)
3843219089Spjd			mutex_exit(hash_lock);
3844185029Spjd
3845219089Spjd		buf_discard_identity(hdr);
3846168404Spjd		arc_buf_thaw(buf);
3847168404Spjd	}
3848168404Spjd	buf->b_efunc = NULL;
3849168404Spjd	buf->b_private = NULL;
3850185029Spjd
3851185029Spjd	if (l2hdr) {
3852251478Sdelphij		ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
3853268085Sdelphij		vdev_space_update(l2hdr->b_dev->l2ad_vdev,
3854268085Sdelphij		    -l2hdr->b_asize, 0, 0);
3855248572Ssmh		trim_map_free(l2hdr->b_dev->l2ad_vdev, l2hdr->b_daddr,
3856248574Ssmh		    hdr->b_size, 0);
3857185029Spjd		kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
3858185029Spjd		ARCSTAT_INCR(arcstat_l2_size, -buf_size);
3859185029Spjd		mutex_exit(&l2arc_buflist_mtx);
3860185029Spjd	}
3861168404Spjd}
3862168404Spjd
3863168404Spjdint
3864168404Spjdarc_released(arc_buf_t *buf)
3865168404Spjd{
3866185029Spjd	int released;
3867185029Spjd
3868219089Spjd	mutex_enter(&buf->b_evict_lock);
3869185029Spjd	released = (buf->b_data != NULL && buf->b_hdr->b_state == arc_anon);
3870219089Spjd	mutex_exit(&buf->b_evict_lock);
3871185029Spjd	return (released);
3872168404Spjd}
3873168404Spjd
3874168404Spjd#ifdef ZFS_DEBUG
3875168404Spjdint
3876168404Spjdarc_referenced(arc_buf_t *buf)
3877168404Spjd{
3878185029Spjd	int referenced;
3879185029Spjd
3880219089Spjd	mutex_enter(&buf->b_evict_lock);
3881185029Spjd	referenced = (refcount_count(&buf->b_hdr->b_refcnt));
3882219089Spjd	mutex_exit(&buf->b_evict_lock);
3883185029Spjd	return (referenced);
3884168404Spjd}
3885168404Spjd#endif
3886168404Spjd
3887168404Spjdstatic void
3888168404Spjdarc_write_ready(zio_t *zio)
3889168404Spjd{
3890168404Spjd	arc_write_callback_t *callback = zio->io_private;
3891168404Spjd	arc_buf_t *buf = callback->awcb_buf;
3892185029Spjd	arc_buf_hdr_t *hdr = buf->b_hdr;
3893168404Spjd
3894185029Spjd	ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt));
3895185029Spjd	callback->awcb_ready(zio, buf, callback->awcb_private);
3896185029Spjd
3897185029Spjd	/*
3898185029Spjd	 * If the IO is already in progress, then this is a re-write
3899185029Spjd	 * attempt, so we need to thaw and re-compute the cksum.
3900185029Spjd	 * It is the responsibility of the callback to handle the
3901185029Spjd	 * accounting for any re-write attempt.
3902185029Spjd	 */
3903185029Spjd	if (HDR_IO_IN_PROGRESS(hdr)) {
3904185029Spjd		mutex_enter(&hdr->b_freeze_lock);
3905185029Spjd		if (hdr->b_freeze_cksum != NULL) {
3906185029Spjd			kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
3907185029Spjd			hdr->b_freeze_cksum = NULL;
3908185029Spjd		}
3909185029Spjd		mutex_exit(&hdr->b_freeze_lock);
3910168404Spjd	}
3911185029Spjd	arc_cksum_compute(buf, B_FALSE);
3912275811Sdelphij	hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
3913168404Spjd}
3914168404Spjd
3915258632Savg/*
3916258632Savg * The SPA calls this callback for each physical write that happens on behalf
3917258632Savg * of a logical write.  See the comment in dbuf_write_physdone() for details.
3918258632Savg */
3919168404Spjdstatic void
3920258632Savgarc_write_physdone(zio_t *zio)
3921258632Savg{
3922258632Savg	arc_write_callback_t *cb = zio->io_private;
3923258632Savg	if (cb->awcb_physdone != NULL)
3924258632Savg		cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
3925258632Savg}
3926258632Savg
3927258632Savgstatic void
3928168404Spjdarc_write_done(zio_t *zio)
3929168404Spjd{
3930168404Spjd	arc_write_callback_t *callback = zio->io_private;
3931168404Spjd	arc_buf_t *buf = callback->awcb_buf;
3932168404Spjd	arc_buf_hdr_t *hdr = buf->b_hdr;
3933168404Spjd
3934219089Spjd	ASSERT(hdr->b_acb == NULL);
3935168404Spjd
3936219089Spjd	if (zio->io_error == 0) {
3937268075Sdelphij		if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
3938260150Sdelphij			buf_discard_identity(hdr);
3939260150Sdelphij		} else {
3940260150Sdelphij			hdr->b_dva = *BP_IDENTITY(zio->io_bp);
3941260150Sdelphij			hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
3942260150Sdelphij			hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
3943260150Sdelphij		}
3944219089Spjd	} else {
3945219089Spjd		ASSERT(BUF_EMPTY(hdr));
3946219089Spjd	}
3947219089Spjd
3948168404Spjd	/*
3949268075Sdelphij	 * If the block to be written was all-zero or compressed enough to be
3950268075Sdelphij	 * embedded in the BP, no write was performed so there will be no
3951268075Sdelphij	 * dva/birth/checksum.  The buffer must therefore remain anonymous
3952268075Sdelphij	 * (and uncached).
3953168404Spjd	 */
3954168404Spjd	if (!BUF_EMPTY(hdr)) {
3955168404Spjd		arc_buf_hdr_t *exists;
3956168404Spjd		kmutex_t *hash_lock;
3957168404Spjd
3958219089Spjd		ASSERT(zio->io_error == 0);
3959219089Spjd
3960168404Spjd		arc_cksum_verify(buf);
3961168404Spjd
3962168404Spjd		exists = buf_hash_insert(hdr, &hash_lock);
3963168404Spjd		if (exists) {
3964168404Spjd			/*
3965168404Spjd			 * This can only happen if we overwrite for
3966168404Spjd			 * sync-to-convergence, because we remove
3967168404Spjd			 * buffers from the hash table when we arc_free().
3968168404Spjd			 */
3969219089Spjd			if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
3970219089Spjd				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3971219089Spjd					panic("bad overwrite, hdr=%p exists=%p",
3972219089Spjd					    (void *)hdr, (void *)exists);
3973219089Spjd				ASSERT(refcount_is_zero(&exists->b_refcnt));
3974219089Spjd				arc_change_state(arc_anon, exists, hash_lock);
3975219089Spjd				mutex_exit(hash_lock);
3976219089Spjd				arc_hdr_destroy(exists);
3977219089Spjd				exists = buf_hash_insert(hdr, &hash_lock);
3978219089Spjd				ASSERT3P(exists, ==, NULL);
3979243524Smm			} else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
3980243524Smm				/* nopwrite */
3981243524Smm				ASSERT(zio->io_prop.zp_nopwrite);
3982243524Smm				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3983243524Smm					panic("bad nopwrite, hdr=%p exists=%p",
3984243524Smm					    (void *)hdr, (void *)exists);
3985219089Spjd			} else {
3986219089Spjd				/* Dedup */
3987219089Spjd				ASSERT(hdr->b_datacnt == 1);
3988219089Spjd				ASSERT(hdr->b_state == arc_anon);
3989219089Spjd				ASSERT(BP_GET_DEDUP(zio->io_bp));
3990219089Spjd				ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
3991219089Spjd			}
3992168404Spjd		}
3993275811Sdelphij		hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
3994185029Spjd		/* if it's not anon, we are doing a scrub */
3995219089Spjd		if (!exists && hdr->b_state == arc_anon)
3996185029Spjd			arc_access(hdr, hash_lock);
3997168404Spjd		mutex_exit(hash_lock);
3998168404Spjd	} else {
3999275811Sdelphij		hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
4000168404Spjd	}
4001168404Spjd
4002219089Spjd	ASSERT(!refcount_is_zero(&hdr->b_refcnt));
4003219089Spjd	callback->awcb_done(zio, buf, callback->awcb_private);
4004168404Spjd
4005168404Spjd	kmem_free(callback, sizeof (arc_write_callback_t));
4006168404Spjd}
4007168404Spjd
4008168404Spjdzio_t *
4009219089Spjdarc_write(zio_t *pio, spa_t *spa, uint64_t txg,
4010251478Sdelphij    blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
4011258632Savg    const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *physdone,
4012258632Savg    arc_done_func_t *done, void *private, zio_priority_t priority,
4013268123Sdelphij    int zio_flags, const zbookmark_phys_t *zb)
4014168404Spjd{
4015168404Spjd	arc_buf_hdr_t *hdr = buf->b_hdr;
4016168404Spjd	arc_write_callback_t *callback;
4017185029Spjd	zio_t *zio;
4018168404Spjd
4019185029Spjd	ASSERT(ready != NULL);
4020219089Spjd	ASSERT(done != NULL);
4021168404Spjd	ASSERT(!HDR_IO_ERROR(hdr));
4022275811Sdelphij	ASSERT((hdr->b_flags & ARC_FLAG_IO_IN_PROGRESS) == 0);
4023219089Spjd	ASSERT(hdr->b_acb == NULL);
4024185029Spjd	if (l2arc)
4025275811Sdelphij		hdr->b_flags |= ARC_FLAG_L2CACHE;
4026251478Sdelphij	if (l2arc_compress)
4027275811Sdelphij		hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4028168404Spjd	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
4029168404Spjd	callback->awcb_ready = ready;
4030258632Savg	callback->awcb_physdone = physdone;
4031168404Spjd	callback->awcb_done = done;
4032168404Spjd	callback->awcb_private = private;
4033168404Spjd	callback->awcb_buf = buf;
4034168404Spjd
4035219089Spjd	zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
4036258632Savg	    arc_write_ready, arc_write_physdone, arc_write_done, callback,
4037258632Savg	    priority, zio_flags, zb);
4038185029Spjd
4039168404Spjd	return (zio);
4040168404Spjd}
4041168404Spjd
4042185029Spjdstatic int
4043258632Savgarc_memory_throttle(uint64_t reserve, uint64_t txg)
4044185029Spjd{
4045185029Spjd#ifdef _KERNEL
4046272483Ssmh	uint64_t available_memory = ptob(freemem);
4047185029Spjd	static uint64_t page_load = 0;
4048185029Spjd	static uint64_t last_txg = 0;
4049185029Spjd
4050272483Ssmh#if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
4051185029Spjd	available_memory =
4052272483Ssmh	    MIN(available_memory, ptob(vmem_size(heap_arena, VMEM_FREE)));
4053185029Spjd#endif
4054258632Savg
4055272483Ssmh	if (freemem > (uint64_t)physmem * arc_lotsfree_percent / 100)
4056185029Spjd		return (0);
4057185029Spjd
4058185029Spjd	if (txg > last_txg) {
4059185029Spjd		last_txg = txg;
4060185029Spjd		page_load = 0;
4061185029Spjd	}
4062185029Spjd	/*
4063185029Spjd	 * If we are in pageout, we know that memory is already tight,
4064185029Spjd	 * the arc is already going to be evicting, so we just want to
4065185029Spjd	 * continue to let page writes occur as quickly as possible.
4066185029Spjd	 */
4067185029Spjd	if (curproc == pageproc) {
4068272483Ssmh		if (page_load > MAX(ptob(minfree), available_memory) / 4)
4069249195Smm			return (SET_ERROR(ERESTART));
4070185029Spjd		/* Note: reserve is inflated, so we deflate */
4071185029Spjd		page_load += reserve / 8;
4072185029Spjd		return (0);
4073185029Spjd	} else if (page_load > 0 && arc_reclaim_needed()) {
4074185029Spjd		/* memory is low, delay before restarting */
4075185029Spjd		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
4076249195Smm		return (SET_ERROR(EAGAIN));
4077185029Spjd	}
4078185029Spjd	page_load = 0;
4079185029Spjd#endif
4080185029Spjd	return (0);
4081185029Spjd}
4082185029Spjd
4083168404Spjdvoid
4084185029Spjdarc_tempreserve_clear(uint64_t reserve)
4085168404Spjd{
4086185029Spjd	atomic_add_64(&arc_tempreserve, -reserve);
4087168404Spjd	ASSERT((int64_t)arc_tempreserve >= 0);
4088168404Spjd}
4089168404Spjd
4090168404Spjdint
4091185029Spjdarc_tempreserve_space(uint64_t reserve, uint64_t txg)
4092168404Spjd{
4093185029Spjd	int error;
4094209962Smm	uint64_t anon_size;
4095185029Spjd
4096272483Ssmh	if (reserve > arc_c/4 && !arc_no_grow) {
4097185029Spjd		arc_c = MIN(arc_c_max, reserve * 4);
4098272483Ssmh		DTRACE_PROBE1(arc__set_reserve, uint64_t, arc_c);
4099272483Ssmh	}
4100185029Spjd	if (reserve > arc_c)
4101249195Smm		return (SET_ERROR(ENOMEM));
4102168404Spjd
4103168404Spjd	/*
4104209962Smm	 * Don't count loaned bufs as in flight dirty data to prevent long
4105209962Smm	 * network delays from blocking transactions that are ready to be
4106209962Smm	 * assigned to a txg.
4107209962Smm	 */
4108209962Smm	anon_size = MAX((int64_t)(arc_anon->arcs_size - arc_loaned_bytes), 0);
4109209962Smm
4110209962Smm	/*
4111185029Spjd	 * Writes will, almost always, require additional memory allocations
4112251631Sdelphij	 * in order to compress/encrypt/etc the data.  We therefore need to
4113185029Spjd	 * make sure that there is sufficient available memory for this.
4114185029Spjd	 */
4115258632Savg	error = arc_memory_throttle(reserve, txg);
4116258632Savg	if (error != 0)
4117185029Spjd		return (error);
4118185029Spjd
4119185029Spjd	/*
4120168404Spjd	 * Throttle writes when the amount of dirty data in the cache
4121168404Spjd	 * gets too large.  We try to keep the cache less than half full
4122168404Spjd	 * of dirty blocks so that our sync times don't grow too large.
4123168404Spjd	 * Note: if two requests come in concurrently, we might let them
4124168404Spjd	 * both succeed, when one of them should fail.  Not a huge deal.
4125168404Spjd	 */
4126209962Smm
4127209962Smm	if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
4128209962Smm	    anon_size > arc_c / 4) {
4129185029Spjd		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
4130185029Spjd		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
4131185029Spjd		    arc_tempreserve>>10,
4132185029Spjd		    arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
4133185029Spjd		    arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
4134185029Spjd		    reserve>>10, arc_c>>10);
4135249195Smm		return (SET_ERROR(ERESTART));
4136168404Spjd	}
4137185029Spjd	atomic_add_64(&arc_tempreserve, reserve);
4138168404Spjd	return (0);
4139168404Spjd}
4140168404Spjd
4141168582Spjdstatic kmutex_t arc_lowmem_lock;
4142168404Spjd#ifdef _KERNEL
4143168566Spjdstatic eventhandler_tag arc_event_lowmem = NULL;
4144168404Spjd
4145168404Spjdstatic void
4146168566Spjdarc_lowmem(void *arg __unused, int howto __unused)
4147168404Spjd{
4148168404Spjd
4149168566Spjd	/* Serialize access via arc_lowmem_lock. */
4150168566Spjd	mutex_enter(&arc_lowmem_lock);
4151219089Spjd	mutex_enter(&arc_reclaim_thr_lock);
4152185029Spjd	needfree = 1;
4153272483Ssmh	DTRACE_PROBE(arc__needfree);
4154168404Spjd	cv_signal(&arc_reclaim_thr_cv);
4155241773Savg
4156241773Savg	/*
4157241773Savg	 * It is unsafe to block here in arbitrary threads, because we can come
4158241773Savg	 * here from ARC itself and may hold ARC locks and thus risk a deadlock
4159241773Savg	 * with ARC reclaim thread.
4160241773Savg	 */
4161241773Savg	if (curproc == pageproc) {
4162241773Savg		while (needfree)
4163241773Savg			msleep(&needfree, &arc_reclaim_thr_lock, 0, "zfs:lowmem", 0);
4164241773Savg	}
4165219089Spjd	mutex_exit(&arc_reclaim_thr_lock);
4166168566Spjd	mutex_exit(&arc_lowmem_lock);
4167168404Spjd}
4168168404Spjd#endif
4169168404Spjd
4170168404Spjdvoid
4171168404Spjdarc_init(void)
4172168404Spjd{
4173219089Spjd	int i, prefetch_tunable_set = 0;
4174205231Skmacy
4175168404Spjd	mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
4176168404Spjd	cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
4177168566Spjd	mutex_init(&arc_lowmem_lock, NULL, MUTEX_DEFAULT, NULL);
4178168404Spjd
4179168404Spjd	/* Convert seconds to clock ticks */
4180168404Spjd	arc_min_prefetch_lifespan = 1 * hz;
4181168404Spjd
4182168404Spjd	/* Start out with 1/8 of all memory */
4183168566Spjd	arc_c = kmem_size() / 8;
4184219089Spjd
4185277300Ssmh#ifdef illumos
4186192360Skmacy#ifdef _KERNEL
4187192360Skmacy	/*
4188192360Skmacy	 * On architectures where the physical memory can be larger
4189192360Skmacy	 * than the addressable space (intel in 32-bit mode), we may
4190192360Skmacy	 * need to limit the cache to 1/8 of VM size.
4191192360Skmacy	 */
4192192360Skmacy	arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
4193192360Skmacy#endif
4194277300Ssmh#endif	/* illumos */
4195168566Spjd	/* set min cache to 1/32 of all memory, or 16MB, whichever is more */
4196168566Spjd	arc_c_min = MAX(arc_c / 4, 64<<18);
4197168566Spjd	/* set max to 1/2 of all memory, or all but 1GB, whichever is more */
4198168404Spjd	if (arc_c * 8 >= 1<<30)
4199168404Spjd		arc_c_max = (arc_c * 8) - (1<<30);
4200168404Spjd	else
4201168404Spjd		arc_c_max = arc_c_min;
4202175633Spjd	arc_c_max = MAX(arc_c * 5, arc_c_max);
4203219089Spjd
4204168481Spjd#ifdef _KERNEL
4205168404Spjd	/*
4206168404Spjd	 * Allow the tunables to override our calculations if they are
4207168566Spjd	 * reasonable (ie. over 16MB)
4208168404Spjd	 */
4209219089Spjd	if (zfs_arc_max > 64<<18 && zfs_arc_max < kmem_size())
4210168404Spjd		arc_c_max = zfs_arc_max;
4211219089Spjd	if (zfs_arc_min > 64<<18 && zfs_arc_min <= arc_c_max)
4212168404Spjd		arc_c_min = zfs_arc_min;
4213168481Spjd#endif
4214219089Spjd
4215168404Spjd	arc_c = arc_c_max;
4216168404Spjd	arc_p = (arc_c >> 1);
4217168404Spjd
4218185029Spjd	/* limit meta-data to 1/4 of the arc capacity */
4219185029Spjd	arc_meta_limit = arc_c_max / 4;
4220185029Spjd
4221185029Spjd	/* Allow the tunable to override if it is reasonable */
4222185029Spjd	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
4223185029Spjd		arc_meta_limit = zfs_arc_meta_limit;
4224185029Spjd
4225185029Spjd	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
4226185029Spjd		arc_c_min = arc_meta_limit / 2;
4227185029Spjd
4228275780Sdelphij	if (zfs_arc_meta_min > 0) {
4229275780Sdelphij		arc_meta_min = zfs_arc_meta_min;
4230275780Sdelphij	} else {
4231275780Sdelphij		arc_meta_min = arc_c_min / 2;
4232275780Sdelphij	}
4233275780Sdelphij
4234208373Smm	if (zfs_arc_grow_retry > 0)
4235208373Smm		arc_grow_retry = zfs_arc_grow_retry;
4236208373Smm
4237208373Smm	if (zfs_arc_shrink_shift > 0)
4238208373Smm		arc_shrink_shift = zfs_arc_shrink_shift;
4239208373Smm
4240208373Smm	if (zfs_arc_p_min_shift > 0)
4241208373Smm		arc_p_min_shift = zfs_arc_p_min_shift;
4242208373Smm
4243168404Spjd	/* if kmem_flags are set, lets try to use less memory */
4244168404Spjd	if (kmem_debugging())
4245168404Spjd		arc_c = arc_c / 2;
4246168404Spjd	if (arc_c < arc_c_min)
4247168404Spjd		arc_c = arc_c_min;
4248168404Spjd
4249168473Spjd	zfs_arc_min = arc_c_min;
4250168473Spjd	zfs_arc_max = arc_c_max;
4251168473Spjd
4252168404Spjd	arc_anon = &ARC_anon;
4253168404Spjd	arc_mru = &ARC_mru;
4254168404Spjd	arc_mru_ghost = &ARC_mru_ghost;
4255168404Spjd	arc_mfu = &ARC_mfu;
4256168404Spjd	arc_mfu_ghost = &ARC_mfu_ghost;
4257185029Spjd	arc_l2c_only = &ARC_l2c_only;
4258168404Spjd	arc_size = 0;
4259168404Spjd
4260205231Skmacy	for (i = 0; i < ARC_BUFC_NUMLISTS; i++) {
4261205231Skmacy		mutex_init(&arc_anon->arcs_locks[i].arcs_lock,
4262205231Skmacy		    NULL, MUTEX_DEFAULT, NULL);
4263205231Skmacy		mutex_init(&arc_mru->arcs_locks[i].arcs_lock,
4264205231Skmacy		    NULL, MUTEX_DEFAULT, NULL);
4265205231Skmacy		mutex_init(&arc_mru_ghost->arcs_locks[i].arcs_lock,
4266205231Skmacy		    NULL, MUTEX_DEFAULT, NULL);
4267205231Skmacy		mutex_init(&arc_mfu->arcs_locks[i].arcs_lock,
4268205231Skmacy		    NULL, MUTEX_DEFAULT, NULL);
4269205231Skmacy		mutex_init(&arc_mfu_ghost->arcs_locks[i].arcs_lock,
4270205231Skmacy		    NULL, MUTEX_DEFAULT, NULL);
4271205231Skmacy		mutex_init(&arc_l2c_only->arcs_locks[i].arcs_lock,
4272205231Skmacy		    NULL, MUTEX_DEFAULT, NULL);
4273206796Spjd
4274205231Skmacy		list_create(&arc_mru->arcs_lists[i],
4275205231Skmacy		    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4276205231Skmacy		list_create(&arc_mru_ghost->arcs_lists[i],
4277205231Skmacy		    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4278205231Skmacy		list_create(&arc_mfu->arcs_lists[i],
4279205231Skmacy		    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4280205231Skmacy		list_create(&arc_mfu_ghost->arcs_lists[i],
4281205231Skmacy		    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4282205231Skmacy		list_create(&arc_mfu_ghost->arcs_lists[i],
4283205231Skmacy		    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4284205231Skmacy		list_create(&arc_l2c_only->arcs_lists[i],
4285205231Skmacy		    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4286205231Skmacy	}
4287168404Spjd
4288168404Spjd	buf_init();
4289168404Spjd
4290168404Spjd	arc_thread_exit = 0;
4291168404Spjd	arc_eviction_list = NULL;
4292168404Spjd	mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
4293168404Spjd	bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
4294168404Spjd
4295168404Spjd	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
4296168404Spjd	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
4297168404Spjd
4298168404Spjd	if (arc_ksp != NULL) {
4299168404Spjd		arc_ksp->ks_data = &arc_stats;
4300168404Spjd		kstat_install(arc_ksp);
4301168404Spjd	}
4302168404Spjd
4303168404Spjd	(void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
4304168404Spjd	    TS_RUN, minclsyspri);
4305168404Spjd
4306168404Spjd#ifdef _KERNEL
4307168566Spjd	arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
4308168404Spjd	    EVENTHANDLER_PRI_FIRST);
4309168404Spjd#endif
4310168404Spjd
4311168404Spjd	arc_dead = FALSE;
4312185029Spjd	arc_warm = B_FALSE;
4313168566Spjd
4314258632Savg	/*
4315258632Savg	 * Calculate maximum amount of dirty data per pool.
4316258632Savg	 *
4317258632Savg	 * If it has been set by /etc/system, take that.
4318258632Savg	 * Otherwise, use a percentage of physical memory defined by
4319258632Savg	 * zfs_dirty_data_max_percent (default 10%) with a cap at
4320258632Savg	 * zfs_dirty_data_max_max (default 4GB).
4321258632Savg	 */
4322258632Savg	if (zfs_dirty_data_max == 0) {
4323258632Savg		zfs_dirty_data_max = ptob(physmem) *
4324258632Savg		    zfs_dirty_data_max_percent / 100;
4325258632Savg		zfs_dirty_data_max = MIN(zfs_dirty_data_max,
4326258632Savg		    zfs_dirty_data_max_max);
4327258632Savg	}
4328185029Spjd
4329168566Spjd#ifdef _KERNEL
4330194043Skmacy	if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
4331193953Skmacy		prefetch_tunable_set = 1;
4332206796Spjd
4333193878Skmacy#ifdef __i386__
4334193953Skmacy	if (prefetch_tunable_set == 0) {
4335196863Strasz		printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
4336196863Strasz		    "-- to enable,\n");
4337196863Strasz		printf("            add \"vfs.zfs.prefetch_disable=0\" "
4338196863Strasz		    "to /boot/loader.conf.\n");
4339219089Spjd		zfs_prefetch_disable = 1;
4340193878Skmacy	}
4341206796Spjd#else
4342193878Skmacy	if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
4343193953Skmacy	    prefetch_tunable_set == 0) {
4344196863Strasz		printf("ZFS NOTICE: Prefetch is disabled by default if less "
4345196941Strasz		    "than 4GB of RAM is present;\n"
4346196863Strasz		    "            to enable, add \"vfs.zfs.prefetch_disable=0\" "
4347196863Strasz		    "to /boot/loader.conf.\n");
4348219089Spjd		zfs_prefetch_disable = 1;
4349193878Skmacy	}
4350206796Spjd#endif
4351175633Spjd	/* Warn about ZFS memory and address space requirements. */
4352168696Spjd	if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
4353168987Sbmah		printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
4354168987Sbmah		    "expect unstable behavior.\n");
4355175633Spjd	}
4356175633Spjd	if (kmem_size() < 512 * (1 << 20)) {
4357173419Spjd		printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
4358168987Sbmah		    "expect unstable behavior.\n");
4359185029Spjd		printf("             Consider tuning vm.kmem_size and "
4360173419Spjd		    "vm.kmem_size_max\n");
4361185029Spjd		printf("             in /boot/loader.conf.\n");
4362168566Spjd	}
4363168566Spjd#endif
4364168404Spjd}
4365168404Spjd
4366168404Spjdvoid
4367168404Spjdarc_fini(void)
4368168404Spjd{
4369205231Skmacy	int i;
4370206796Spjd
4371168404Spjd	mutex_enter(&arc_reclaim_thr_lock);
4372168404Spjd	arc_thread_exit = 1;
4373168404Spjd	cv_signal(&arc_reclaim_thr_cv);
4374168404Spjd	while (arc_thread_exit != 0)
4375168404Spjd		cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
4376168404Spjd	mutex_exit(&arc_reclaim_thr_lock);
4377168404Spjd
4378185029Spjd	arc_flush(NULL);
4379168404Spjd
4380168404Spjd	arc_dead = TRUE;
4381168404Spjd
4382168404Spjd	if (arc_ksp != NULL) {
4383168404Spjd		kstat_delete(arc_ksp);
4384168404Spjd		arc_ksp = NULL;
4385168404Spjd	}
4386168404Spjd
4387168404Spjd	mutex_destroy(&arc_eviction_mtx);
4388168404Spjd	mutex_destroy(&arc_reclaim_thr_lock);
4389168404Spjd	cv_destroy(&arc_reclaim_thr_cv);
4390168404Spjd
4391205231Skmacy	for (i = 0; i < ARC_BUFC_NUMLISTS; i++) {
4392205231Skmacy		list_destroy(&arc_mru->arcs_lists[i]);
4393205231Skmacy		list_destroy(&arc_mru_ghost->arcs_lists[i]);
4394205231Skmacy		list_destroy(&arc_mfu->arcs_lists[i]);
4395205231Skmacy		list_destroy(&arc_mfu_ghost->arcs_lists[i]);
4396206795Spjd		list_destroy(&arc_l2c_only->arcs_lists[i]);
4397168404Spjd
4398205231Skmacy		mutex_destroy(&arc_anon->arcs_locks[i].arcs_lock);
4399205231Skmacy		mutex_destroy(&arc_mru->arcs_locks[i].arcs_lock);
4400205231Skmacy		mutex_destroy(&arc_mru_ghost->arcs_locks[i].arcs_lock);
4401205231Skmacy		mutex_destroy(&arc_mfu->arcs_locks[i].arcs_lock);
4402205231Skmacy		mutex_destroy(&arc_mfu_ghost->arcs_locks[i].arcs_lock);
4403206795Spjd		mutex_destroy(&arc_l2c_only->arcs_locks[i].arcs_lock);
4404205231Skmacy	}
4405206796Spjd
4406168404Spjd	buf_fini();
4407168404Spjd
4408209962Smm	ASSERT(arc_loaned_bytes == 0);
4409209962Smm
4410168582Spjd	mutex_destroy(&arc_lowmem_lock);
4411168404Spjd#ifdef _KERNEL
4412168566Spjd	if (arc_event_lowmem != NULL)
4413168566Spjd		EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
4414168404Spjd#endif
4415168404Spjd}
4416185029Spjd
4417185029Spjd/*
4418185029Spjd * Level 2 ARC
4419185029Spjd *
4420185029Spjd * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
4421185029Spjd * It uses dedicated storage devices to hold cached data, which are populated
4422185029Spjd * using large infrequent writes.  The main role of this cache is to boost
4423185029Spjd * the performance of random read workloads.  The intended L2ARC devices
4424185029Spjd * include short-stroked disks, solid state disks, and other media with
4425185029Spjd * substantially faster read latency than disk.
4426185029Spjd *
4427185029Spjd *                 +-----------------------+
4428185029Spjd *                 |         ARC           |
4429185029Spjd *                 +-----------------------+
4430185029Spjd *                    |         ^     ^
4431185029Spjd *                    |         |     |
4432185029Spjd *      l2arc_feed_thread()    arc_read()
4433185029Spjd *                    |         |     |
4434185029Spjd *                    |  l2arc read   |
4435185029Spjd *                    V         |     |
4436185029Spjd *               +---------------+    |
4437185029Spjd *               |     L2ARC     |    |
4438185029Spjd *               +---------------+    |
4439185029Spjd *                   |    ^           |
4440185029Spjd *          l2arc_write() |           |
4441185029Spjd *                   |    |           |
4442185029Spjd *                   V    |           |
4443185029Spjd *                 +-------+      +-------+
4444185029Spjd *                 | vdev  |      | vdev  |
4445185029Spjd *                 | cache |      | cache |
4446185029Spjd *                 +-------+      +-------+
4447185029Spjd *                 +=========+     .-----.
4448185029Spjd *                 :  L2ARC  :    |-_____-|
4449185029Spjd *                 : devices :    | Disks |
4450185029Spjd *                 +=========+    `-_____-'
4451185029Spjd *
4452185029Spjd * Read requests are satisfied from the following sources, in order:
4453185029Spjd *
4454185029Spjd *	1) ARC
4455185029Spjd *	2) vdev cache of L2ARC devices
4456185029Spjd *	3) L2ARC devices
4457185029Spjd *	4) vdev cache of disks
4458185029Spjd *	5) disks
4459185029Spjd *
4460185029Spjd * Some L2ARC device types exhibit extremely slow write performance.
4461185029Spjd * To accommodate for this there are some significant differences between
4462185029Spjd * the L2ARC and traditional cache design:
4463185029Spjd *
4464185029Spjd * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
4465185029Spjd * the ARC behave as usual, freeing buffers and placing headers on ghost
4466185029Spjd * lists.  The ARC does not send buffers to the L2ARC during eviction as
4467185029Spjd * this would add inflated write latencies for all ARC memory pressure.
4468185029Spjd *
4469185029Spjd * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
4470185029Spjd * It does this by periodically scanning buffers from the eviction-end of
4471185029Spjd * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
4472251478Sdelphij * not already there. It scans until a headroom of buffers is satisfied,
4473251478Sdelphij * which itself is a buffer for ARC eviction. If a compressible buffer is
4474251478Sdelphij * found during scanning and selected for writing to an L2ARC device, we
4475251478Sdelphij * temporarily boost scanning headroom during the next scan cycle to make
4476251478Sdelphij * sure we adapt to compression effects (which might significantly reduce
4477251478Sdelphij * the data volume we write to L2ARC). The thread that does this is
4478185029Spjd * l2arc_feed_thread(), illustrated below; example sizes are included to
4479185029Spjd * provide a better sense of ratio than this diagram:
4480185029Spjd *
4481185029Spjd *	       head -->                        tail
4482185029Spjd *	        +---------------------+----------+
4483185029Spjd *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
4484185029Spjd *	        +---------------------+----------+   |   o L2ARC eligible
4485185029Spjd *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
4486185029Spjd *	        +---------------------+----------+   |
4487185029Spjd *	             15.9 Gbytes      ^ 32 Mbytes    |
4488185029Spjd *	                           headroom          |
4489185029Spjd *	                                      l2arc_feed_thread()
4490185029Spjd *	                                             |
4491185029Spjd *	                 l2arc write hand <--[oooo]--'
4492185029Spjd *	                         |           8 Mbyte
4493185029Spjd *	                         |          write max
4494185029Spjd *	                         V
4495185029Spjd *		  +==============================+
4496185029Spjd *	L2ARC dev |####|#|###|###|    |####| ... |
4497185029Spjd *	          +==============================+
4498185029Spjd *	                     32 Gbytes
4499185029Spjd *
4500185029Spjd * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
4501185029Spjd * evicted, then the L2ARC has cached a buffer much sooner than it probably
4502185029Spjd * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
4503185029Spjd * safe to say that this is an uncommon case, since buffers at the end of
4504185029Spjd * the ARC lists have moved there due to inactivity.
4505185029Spjd *
4506185029Spjd * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
4507185029Spjd * then the L2ARC simply misses copying some buffers.  This serves as a
4508185029Spjd * pressure valve to prevent heavy read workloads from both stalling the ARC
4509185029Spjd * with waits and clogging the L2ARC with writes.  This also helps prevent
4510185029Spjd * the potential for the L2ARC to churn if it attempts to cache content too
4511185029Spjd * quickly, such as during backups of the entire pool.
4512185029Spjd *
4513185029Spjd * 5. After system boot and before the ARC has filled main memory, there are
4514185029Spjd * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
4515185029Spjd * lists can remain mostly static.  Instead of searching from tail of these
4516185029Spjd * lists as pictured, the l2arc_feed_thread() will search from the list heads
4517185029Spjd * for eligible buffers, greatly increasing its chance of finding them.
4518185029Spjd *
4519185029Spjd * The L2ARC device write speed is also boosted during this time so that
4520185029Spjd * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
4521185029Spjd * there are no L2ARC reads, and no fear of degrading read performance
4522185029Spjd * through increased writes.
4523185029Spjd *
4524185029Spjd * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
4525185029Spjd * the vdev queue can aggregate them into larger and fewer writes.  Each
4526185029Spjd * device is written to in a rotor fashion, sweeping writes through
4527185029Spjd * available space then repeating.
4528185029Spjd *
4529185029Spjd * 7. The L2ARC does not store dirty content.  It never needs to flush
4530185029Spjd * write buffers back to disk based storage.
4531185029Spjd *
4532185029Spjd * 8. If an ARC buffer is written (and dirtied) which also exists in the
4533185029Spjd * L2ARC, the now stale L2ARC buffer is immediately dropped.
4534185029Spjd *
4535185029Spjd * The performance of the L2ARC can be tweaked by a number of tunables, which
4536185029Spjd * may be necessary for different workloads:
4537185029Spjd *
4538185029Spjd *	l2arc_write_max		max write bytes per interval
4539185029Spjd *	l2arc_write_boost	extra write bytes during device warmup
4540185029Spjd *	l2arc_noprefetch	skip caching prefetched buffers
4541185029Spjd *	l2arc_headroom		number of max device writes to precache
4542251478Sdelphij *	l2arc_headroom_boost	when we find compressed buffers during ARC
4543251478Sdelphij *				scanning, we multiply headroom by this
4544251478Sdelphij *				percentage factor for the next scan cycle,
4545251478Sdelphij *				since more compressed buffers are likely to
4546251478Sdelphij *				be present
4547185029Spjd *	l2arc_feed_secs		seconds between L2ARC writing
4548185029Spjd *
4549185029Spjd * Tunables may be removed or added as future performance improvements are
4550185029Spjd * integrated, and also may become zpool properties.
4551208373Smm *
4552208373Smm * There are three key functions that control how the L2ARC warms up:
4553208373Smm *
4554208373Smm *	l2arc_write_eligible()	check if a buffer is eligible to cache
4555208373Smm *	l2arc_write_size()	calculate how much to write
4556208373Smm *	l2arc_write_interval()	calculate sleep delay between writes
4557208373Smm *
4558208373Smm * These three functions determine what to write, how much, and how quickly
4559208373Smm * to send writes.
4560185029Spjd */
4561185029Spjd
4562208373Smmstatic boolean_t
4563275811Sdelphijl2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
4564208373Smm{
4565208373Smm	/*
4566208373Smm	 * A buffer is *not* eligible for the L2ARC if it:
4567208373Smm	 * 1. belongs to a different spa.
4568208373Smm	 * 2. is already cached on the L2ARC.
4569208373Smm	 * 3. has an I/O in progress (it may be an incomplete read).
4570208373Smm	 * 4. is flagged not eligible (zfs property).
4571208373Smm	 */
4572275811Sdelphij	if (hdr->b_spa != spa_guid) {
4573208373Smm		ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
4574208373Smm		return (B_FALSE);
4575208373Smm	}
4576275811Sdelphij	if (hdr->b_l2hdr != NULL) {
4577208373Smm		ARCSTAT_BUMP(arcstat_l2_write_in_l2);
4578208373Smm		return (B_FALSE);
4579208373Smm	}
4580275811Sdelphij	if (HDR_IO_IN_PROGRESS(hdr)) {
4581208373Smm		ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
4582208373Smm		return (B_FALSE);
4583208373Smm	}
4584275811Sdelphij	if (!HDR_L2CACHE(hdr)) {
4585208373Smm		ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
4586208373Smm		return (B_FALSE);
4587208373Smm	}
4588208373Smm
4589208373Smm	return (B_TRUE);
4590208373Smm}
4591208373Smm
4592208373Smmstatic uint64_t
4593251478Sdelphijl2arc_write_size(void)
4594208373Smm{
4595208373Smm	uint64_t size;
4596208373Smm
4597251478Sdelphij	/*
4598251478Sdelphij	 * Make sure our globals have meaningful values in case the user
4599251478Sdelphij	 * altered them.
4600251478Sdelphij	 */
4601251478Sdelphij	size = l2arc_write_max;
4602251478Sdelphij	if (size == 0) {
4603251478Sdelphij		cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
4604251478Sdelphij		    "be greater than zero, resetting it to the default (%d)",
4605251478Sdelphij		    L2ARC_WRITE_SIZE);
4606251478Sdelphij		size = l2arc_write_max = L2ARC_WRITE_SIZE;
4607251478Sdelphij	}
4608208373Smm
4609208373Smm	if (arc_warm == B_FALSE)
4610251478Sdelphij		size += l2arc_write_boost;
4611208373Smm
4612208373Smm	return (size);
4613208373Smm
4614208373Smm}
4615208373Smm
4616208373Smmstatic clock_t
4617208373Smml2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
4618208373Smm{
4619219089Spjd	clock_t interval, next, now;
4620208373Smm
4621208373Smm	/*
4622208373Smm	 * If the ARC lists are busy, increase our write rate; if the
4623208373Smm	 * lists are stale, idle back.  This is achieved by checking
4624208373Smm	 * how much we previously wrote - if it was more than half of
4625208373Smm	 * what we wanted, schedule the next write much sooner.
4626208373Smm	 */
4627208373Smm	if (l2arc_feed_again && wrote > (wanted / 2))
4628208373Smm		interval = (hz * l2arc_feed_min_ms) / 1000;
4629208373Smm	else
4630208373Smm		interval = hz * l2arc_feed_secs;
4631208373Smm
4632219089Spjd	now = ddi_get_lbolt();
4633219089Spjd	next = MAX(now, MIN(now + interval, began + interval));
4634208373Smm
4635208373Smm	return (next);
4636208373Smm}
4637208373Smm
4638185029Spjdstatic void
4639185029Spjdl2arc_hdr_stat_add(void)
4640185029Spjd{
4641185029Spjd	ARCSTAT_INCR(arcstat_l2_hdr_size, HDR_SIZE + L2HDR_SIZE);
4642185029Spjd	ARCSTAT_INCR(arcstat_hdr_size, -HDR_SIZE);
4643185029Spjd}
4644185029Spjd
4645185029Spjdstatic void
4646185029Spjdl2arc_hdr_stat_remove(void)
4647185029Spjd{
4648185029Spjd	ARCSTAT_INCR(arcstat_l2_hdr_size, -(HDR_SIZE + L2HDR_SIZE));
4649185029Spjd	ARCSTAT_INCR(arcstat_hdr_size, HDR_SIZE);
4650185029Spjd}
4651185029Spjd
4652185029Spjd/*
4653185029Spjd * Cycle through L2ARC devices.  This is how L2ARC load balances.
4654185029Spjd * If a device is returned, this also returns holding the spa config lock.
4655185029Spjd */
4656185029Spjdstatic l2arc_dev_t *
4657185029Spjdl2arc_dev_get_next(void)
4658185029Spjd{
4659185029Spjd	l2arc_dev_t *first, *next = NULL;
4660185029Spjd
4661185029Spjd	/*
4662185029Spjd	 * Lock out the removal of spas (spa_namespace_lock), then removal
4663185029Spjd	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
4664185029Spjd	 * both locks will be dropped and a spa config lock held instead.
4665185029Spjd	 */
4666185029Spjd	mutex_enter(&spa_namespace_lock);
4667185029Spjd	mutex_enter(&l2arc_dev_mtx);
4668185029Spjd
4669185029Spjd	/* if there are no vdevs, there is nothing to do */
4670185029Spjd	if (l2arc_ndev == 0)
4671185029Spjd		goto out;
4672185029Spjd
4673185029Spjd	first = NULL;
4674185029Spjd	next = l2arc_dev_last;
4675185029Spjd	do {
4676185029Spjd		/* loop around the list looking for a non-faulted vdev */
4677185029Spjd		if (next == NULL) {
4678185029Spjd			next = list_head(l2arc_dev_list);
4679185029Spjd		} else {
4680185029Spjd			next = list_next(l2arc_dev_list, next);
4681185029Spjd			if (next == NULL)
4682185029Spjd				next = list_head(l2arc_dev_list);
4683185029Spjd		}
4684185029Spjd
4685185029Spjd		/* if we have come back to the start, bail out */
4686185029Spjd		if (first == NULL)
4687185029Spjd			first = next;
4688185029Spjd		else if (next == first)
4689185029Spjd			break;
4690185029Spjd
4691185029Spjd	} while (vdev_is_dead(next->l2ad_vdev));
4692185029Spjd
4693185029Spjd	/* if we were unable to find any usable vdevs, return NULL */
4694185029Spjd	if (vdev_is_dead(next->l2ad_vdev))
4695185029Spjd		next = NULL;
4696185029Spjd
4697185029Spjd	l2arc_dev_last = next;
4698185029Spjd
4699185029Spjdout:
4700185029Spjd	mutex_exit(&l2arc_dev_mtx);
4701185029Spjd
4702185029Spjd	/*
4703185029Spjd	 * Grab the config lock to prevent the 'next' device from being
4704185029Spjd	 * removed while we are writing to it.
4705185029Spjd	 */
4706185029Spjd	if (next != NULL)
4707185029Spjd		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
4708185029Spjd	mutex_exit(&spa_namespace_lock);
4709185029Spjd
4710185029Spjd	return (next);
4711185029Spjd}
4712185029Spjd
4713185029Spjd/*
4714185029Spjd * Free buffers that were tagged for destruction.
4715185029Spjd */
4716185029Spjdstatic void
4717185029Spjdl2arc_do_free_on_write()
4718185029Spjd{
4719185029Spjd	list_t *buflist;
4720185029Spjd	l2arc_data_free_t *df, *df_prev;
4721185029Spjd
4722185029Spjd	mutex_enter(&l2arc_free_on_write_mtx);
4723185029Spjd	buflist = l2arc_free_on_write;
4724185029Spjd
4725185029Spjd	for (df = list_tail(buflist); df; df = df_prev) {
4726185029Spjd		df_prev = list_prev(buflist, df);
4727185029Spjd		ASSERT(df->l2df_data != NULL);
4728185029Spjd		ASSERT(df->l2df_func != NULL);
4729185029Spjd		df->l2df_func(df->l2df_data, df->l2df_size);
4730185029Spjd		list_remove(buflist, df);
4731185029Spjd		kmem_free(df, sizeof (l2arc_data_free_t));
4732185029Spjd	}
4733185029Spjd
4734185029Spjd	mutex_exit(&l2arc_free_on_write_mtx);
4735185029Spjd}
4736185029Spjd
4737185029Spjd/*
4738185029Spjd * A write to a cache device has completed.  Update all headers to allow
4739185029Spjd * reads from these buffers to begin.
4740185029Spjd */
4741185029Spjdstatic void
4742185029Spjdl2arc_write_done(zio_t *zio)
4743185029Spjd{
4744185029Spjd	l2arc_write_callback_t *cb;
4745185029Spjd	l2arc_dev_t *dev;
4746185029Spjd	list_t *buflist;
4747275811Sdelphij	arc_buf_hdr_t *head, *hdr, *hdr_prev;
4748185029Spjd	l2arc_buf_hdr_t *abl2;
4749185029Spjd	kmutex_t *hash_lock;
4750268085Sdelphij	int64_t bytes_dropped = 0;
4751185029Spjd
4752185029Spjd	cb = zio->io_private;
4753185029Spjd	ASSERT(cb != NULL);
4754185029Spjd	dev = cb->l2wcb_dev;
4755185029Spjd	ASSERT(dev != NULL);
4756185029Spjd	head = cb->l2wcb_head;
4757185029Spjd	ASSERT(head != NULL);
4758185029Spjd	buflist = dev->l2ad_buflist;
4759185029Spjd	ASSERT(buflist != NULL);
4760185029Spjd	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
4761185029Spjd	    l2arc_write_callback_t *, cb);
4762185029Spjd
4763185029Spjd	if (zio->io_error != 0)
4764185029Spjd		ARCSTAT_BUMP(arcstat_l2_writes_error);
4765185029Spjd
4766185029Spjd	mutex_enter(&l2arc_buflist_mtx);
4767185029Spjd
4768185029Spjd	/*
4769185029Spjd	 * All writes completed, or an error was hit.
4770185029Spjd	 */
4771275811Sdelphij	for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
4772275811Sdelphij		hdr_prev = list_prev(buflist, hdr);
4773275811Sdelphij		abl2 = hdr->b_l2hdr;
4774185029Spjd
4775260835Sdelphij		/*
4776260835Sdelphij		 * Release the temporary compressed buffer as soon as possible.
4777260835Sdelphij		 */
4778260835Sdelphij		if (abl2->b_compress != ZIO_COMPRESS_OFF)
4779275811Sdelphij			l2arc_release_cdata_buf(hdr);
4780260835Sdelphij
4781275811Sdelphij		hash_lock = HDR_LOCK(hdr);
4782185029Spjd		if (!mutex_tryenter(hash_lock)) {
4783185029Spjd			/*
4784185029Spjd			 * This buffer misses out.  It may be in a stage
4785185029Spjd			 * of eviction.  Its ARC_L2_WRITING flag will be
4786185029Spjd			 * left set, denying reads to this buffer.
4787185029Spjd			 */
4788185029Spjd			ARCSTAT_BUMP(arcstat_l2_writes_hdr_miss);
4789185029Spjd			continue;
4790185029Spjd		}
4791185029Spjd
4792185029Spjd		if (zio->io_error != 0) {
4793185029Spjd			/*
4794185029Spjd			 * Error - drop L2ARC entry.
4795185029Spjd			 */
4796275811Sdelphij			list_remove(buflist, hdr);
4797251478Sdelphij			ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
4798268085Sdelphij			bytes_dropped += abl2->b_asize;
4799275811Sdelphij			hdr->b_l2hdr = NULL;
4800248572Ssmh			trim_map_free(abl2->b_dev->l2ad_vdev, abl2->b_daddr,
4801275811Sdelphij			    hdr->b_size, 0);
4802185029Spjd			kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
4803275811Sdelphij			ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
4804185029Spjd		}
4805185029Spjd
4806185029Spjd		/*
4807185029Spjd		 * Allow ARC to begin reads to this L2ARC entry.
4808185029Spjd		 */
4809275811Sdelphij		hdr->b_flags &= ~ARC_FLAG_L2_WRITING;
4810185029Spjd
4811185029Spjd		mutex_exit(hash_lock);
4812185029Spjd	}
4813185029Spjd
4814185029Spjd	atomic_inc_64(&l2arc_writes_done);
4815185029Spjd	list_remove(buflist, head);
4816185029Spjd	kmem_cache_free(hdr_cache, head);
4817185029Spjd	mutex_exit(&l2arc_buflist_mtx);
4818185029Spjd
4819268085Sdelphij	vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
4820268085Sdelphij
4821185029Spjd	l2arc_do_free_on_write();
4822185029Spjd
4823185029Spjd	kmem_free(cb, sizeof (l2arc_write_callback_t));
4824185029Spjd}
4825185029Spjd
4826185029Spjd/*
4827185029Spjd * A read to a cache device completed.  Validate buffer contents before
4828185029Spjd * handing over to the regular ARC routines.
4829185029Spjd */
4830185029Spjdstatic void
4831185029Spjdl2arc_read_done(zio_t *zio)
4832185029Spjd{
4833185029Spjd	l2arc_read_callback_t *cb;
4834185029Spjd	arc_buf_hdr_t *hdr;
4835185029Spjd	arc_buf_t *buf;
4836185029Spjd	kmutex_t *hash_lock;
4837185029Spjd	int equal;
4838185029Spjd
4839185029Spjd	ASSERT(zio->io_vd != NULL);
4840185029Spjd	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
4841185029Spjd
4842185029Spjd	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
4843185029Spjd
4844185029Spjd	cb = zio->io_private;
4845185029Spjd	ASSERT(cb != NULL);
4846185029Spjd	buf = cb->l2rcb_buf;
4847185029Spjd	ASSERT(buf != NULL);
4848185029Spjd
4849219089Spjd	hash_lock = HDR_LOCK(buf->b_hdr);
4850185029Spjd	mutex_enter(hash_lock);
4851219089Spjd	hdr = buf->b_hdr;
4852219089Spjd	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4853185029Spjd
4854185029Spjd	/*
4855251478Sdelphij	 * If the buffer was compressed, decompress it first.
4856251478Sdelphij	 */
4857251478Sdelphij	if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
4858251478Sdelphij		l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
4859251478Sdelphij	ASSERT(zio->io_data != NULL);
4860251478Sdelphij
4861251478Sdelphij	/*
4862185029Spjd	 * Check this survived the L2ARC journey.
4863185029Spjd	 */
4864185029Spjd	equal = arc_cksum_equal(buf);
4865185029Spjd	if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
4866185029Spjd		mutex_exit(hash_lock);
4867185029Spjd		zio->io_private = buf;
4868185029Spjd		zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
4869185029Spjd		zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
4870185029Spjd		arc_read_done(zio);
4871185029Spjd	} else {
4872185029Spjd		mutex_exit(hash_lock);
4873185029Spjd		/*
4874185029Spjd		 * Buffer didn't survive caching.  Increment stats and
4875185029Spjd		 * reissue to the original storage device.
4876185029Spjd		 */
4877185029Spjd		if (zio->io_error != 0) {
4878185029Spjd			ARCSTAT_BUMP(arcstat_l2_io_error);
4879185029Spjd		} else {
4880249195Smm			zio->io_error = SET_ERROR(EIO);
4881185029Spjd		}
4882185029Spjd		if (!equal)
4883185029Spjd			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
4884185029Spjd
4885185029Spjd		/*
4886185029Spjd		 * If there's no waiter, issue an async i/o to the primary
4887185029Spjd		 * storage now.  If there *is* a waiter, the caller must
4888185029Spjd		 * issue the i/o in a context where it's OK to block.
4889185029Spjd		 */
4890209962Smm		if (zio->io_waiter == NULL) {
4891209962Smm			zio_t *pio = zio_unique_parent(zio);
4892209962Smm
4893209962Smm			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
4894209962Smm
4895209962Smm			zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
4896185029Spjd			    buf->b_data, zio->io_size, arc_read_done, buf,
4897185029Spjd			    zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
4898209962Smm		}
4899185029Spjd	}
4900185029Spjd
4901185029Spjd	kmem_free(cb, sizeof (l2arc_read_callback_t));
4902185029Spjd}
4903185029Spjd
4904185029Spjd/*
4905185029Spjd * This is the list priority from which the L2ARC will search for pages to
4906185029Spjd * cache.  This is used within loops (0..3) to cycle through lists in the
4907185029Spjd * desired order.  This order can have a significant effect on cache
4908185029Spjd * performance.
4909185029Spjd *
4910185029Spjd * Currently the metadata lists are hit first, MFU then MRU, followed by
4911185029Spjd * the data lists.  This function returns a locked list, and also returns
4912185029Spjd * the lock pointer.
4913185029Spjd */
4914185029Spjdstatic list_t *
4915185029Spjdl2arc_list_locked(int list_num, kmutex_t **lock)
4916185029Spjd{
4917247187Smm	list_t *list = NULL;
4918205231Skmacy	int idx;
4919185029Spjd
4920206796Spjd	ASSERT(list_num >= 0 && list_num < 2 * ARC_BUFC_NUMLISTS);
4921206796Spjd
4922205231Skmacy	if (list_num < ARC_BUFC_NUMMETADATALISTS) {
4923205231Skmacy		idx = list_num;
4924205231Skmacy		list = &arc_mfu->arcs_lists[idx];
4925205231Skmacy		*lock = ARCS_LOCK(arc_mfu, idx);
4926206796Spjd	} else if (list_num < ARC_BUFC_NUMMETADATALISTS * 2) {
4927205231Skmacy		idx = list_num - ARC_BUFC_NUMMETADATALISTS;
4928205231Skmacy		list = &arc_mru->arcs_lists[idx];
4929205231Skmacy		*lock = ARCS_LOCK(arc_mru, idx);
4930206796Spjd	} else if (list_num < (ARC_BUFC_NUMMETADATALISTS * 2 +
4931205231Skmacy		ARC_BUFC_NUMDATALISTS)) {
4932205231Skmacy		idx = list_num - ARC_BUFC_NUMMETADATALISTS;
4933205231Skmacy		list = &arc_mfu->arcs_lists[idx];
4934205231Skmacy		*lock = ARCS_LOCK(arc_mfu, idx);
4935205231Skmacy	} else {
4936205231Skmacy		idx = list_num - ARC_BUFC_NUMLISTS;
4937205231Skmacy		list = &arc_mru->arcs_lists[idx];
4938205231Skmacy		*lock = ARCS_LOCK(arc_mru, idx);
4939185029Spjd	}
4940185029Spjd
4941185029Spjd	ASSERT(!(MUTEX_HELD(*lock)));
4942185029Spjd	mutex_enter(*lock);
4943185029Spjd	return (list);
4944185029Spjd}
4945185029Spjd
4946185029Spjd/*
4947185029Spjd * Evict buffers from the device write hand to the distance specified in
4948185029Spjd * bytes.  This distance may span populated buffers, it may span nothing.
4949185029Spjd * This is clearing a region on the L2ARC device ready for writing.
4950185029Spjd * If the 'all' boolean is set, every buffer is evicted.
4951185029Spjd */
4952185029Spjdstatic void
4953185029Spjdl2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
4954185029Spjd{
4955185029Spjd	list_t *buflist;
4956185029Spjd	l2arc_buf_hdr_t *abl2;
4957275811Sdelphij	arc_buf_hdr_t *hdr, *hdr_prev;
4958185029Spjd	kmutex_t *hash_lock;
4959185029Spjd	uint64_t taddr;
4960268085Sdelphij	int64_t bytes_evicted = 0;
4961185029Spjd
4962185029Spjd	buflist = dev->l2ad_buflist;
4963185029Spjd
4964185029Spjd	if (buflist == NULL)
4965185029Spjd		return;
4966185029Spjd
4967185029Spjd	if (!all && dev->l2ad_first) {
4968185029Spjd		/*
4969185029Spjd		 * This is the first sweep through the device.  There is
4970185029Spjd		 * nothing to evict.
4971185029Spjd		 */
4972185029Spjd		return;
4973185029Spjd	}
4974185029Spjd
4975185029Spjd	if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
4976185029Spjd		/*
4977185029Spjd		 * When nearing the end of the device, evict to the end
4978185029Spjd		 * before the device write hand jumps to the start.
4979185029Spjd		 */
4980185029Spjd		taddr = dev->l2ad_end;
4981185029Spjd	} else {
4982185029Spjd		taddr = dev->l2ad_hand + distance;
4983185029Spjd	}
4984185029Spjd	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
4985185029Spjd	    uint64_t, taddr, boolean_t, all);
4986185029Spjd
4987185029Spjdtop:
4988185029Spjd	mutex_enter(&l2arc_buflist_mtx);
4989275811Sdelphij	for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
4990275811Sdelphij		hdr_prev = list_prev(buflist, hdr);
4991185029Spjd
4992275811Sdelphij		hash_lock = HDR_LOCK(hdr);
4993185029Spjd		if (!mutex_tryenter(hash_lock)) {
4994185029Spjd			/*
4995185029Spjd			 * Missed the hash lock.  Retry.
4996185029Spjd			 */
4997185029Spjd			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
4998185029Spjd			mutex_exit(&l2arc_buflist_mtx);
4999185029Spjd			mutex_enter(hash_lock);
5000185029Spjd			mutex_exit(hash_lock);
5001185029Spjd			goto top;
5002185029Spjd		}
5003185029Spjd
5004275811Sdelphij		if (HDR_L2_WRITE_HEAD(hdr)) {
5005185029Spjd			/*
5006185029Spjd			 * We hit a write head node.  Leave it for
5007185029Spjd			 * l2arc_write_done().
5008185029Spjd			 */
5009275811Sdelphij			list_remove(buflist, hdr);
5010185029Spjd			mutex_exit(hash_lock);
5011185029Spjd			continue;
5012185029Spjd		}
5013185029Spjd
5014275811Sdelphij		if (!all && hdr->b_l2hdr != NULL &&
5015275811Sdelphij		    (hdr->b_l2hdr->b_daddr > taddr ||
5016275811Sdelphij		    hdr->b_l2hdr->b_daddr < dev->l2ad_hand)) {
5017185029Spjd			/*
5018185029Spjd			 * We've evicted to the target address,
5019185029Spjd			 * or the end of the device.
5020185029Spjd			 */
5021185029Spjd			mutex_exit(hash_lock);
5022185029Spjd			break;
5023185029Spjd		}
5024185029Spjd
5025275811Sdelphij		if (HDR_FREE_IN_PROGRESS(hdr)) {
5026185029Spjd			/*
5027185029Spjd			 * Already on the path to destruction.
5028185029Spjd			 */
5029185029Spjd			mutex_exit(hash_lock);
5030185029Spjd			continue;
5031185029Spjd		}
5032185029Spjd
5033275811Sdelphij		if (hdr->b_state == arc_l2c_only) {
5034275811Sdelphij			ASSERT(!HDR_L2_READING(hdr));
5035185029Spjd			/*
5036185029Spjd			 * This doesn't exist in the ARC.  Destroy.
5037185029Spjd			 * arc_hdr_destroy() will call list_remove()
5038185029Spjd			 * and decrement arcstat_l2_size.
5039185029Spjd			 */
5040275811Sdelphij			arc_change_state(arc_anon, hdr, hash_lock);
5041275811Sdelphij			arc_hdr_destroy(hdr);
5042185029Spjd		} else {
5043185029Spjd			/*
5044185029Spjd			 * Invalidate issued or about to be issued
5045185029Spjd			 * reads, since we may be about to write
5046185029Spjd			 * over this location.
5047185029Spjd			 */
5048275811Sdelphij			if (HDR_L2_READING(hdr)) {
5049185029Spjd				ARCSTAT_BUMP(arcstat_l2_evict_reading);
5050275811Sdelphij				hdr->b_flags |= ARC_FLAG_L2_EVICTED;
5051185029Spjd			}
5052185029Spjd
5053185029Spjd			/*
5054185029Spjd			 * Tell ARC this no longer exists in L2ARC.
5055185029Spjd			 */
5056275811Sdelphij			if (hdr->b_l2hdr != NULL) {
5057275811Sdelphij				abl2 = hdr->b_l2hdr;
5058251478Sdelphij				ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
5059268085Sdelphij				bytes_evicted += abl2->b_asize;
5060275811Sdelphij				hdr->b_l2hdr = NULL;
5061274172Savg				/*
5062274172Savg				 * We are destroying l2hdr, so ensure that
5063274172Savg				 * its compressed buffer, if any, is not leaked.
5064274172Savg				 */
5065274172Savg				ASSERT(abl2->b_tmp_cdata == NULL);
5066185029Spjd				kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
5067275811Sdelphij				ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
5068185029Spjd			}
5069275811Sdelphij			list_remove(buflist, hdr);
5070185029Spjd
5071185029Spjd			/*
5072185029Spjd			 * This may have been leftover after a
5073185029Spjd			 * failed write.
5074185029Spjd			 */
5075275811Sdelphij			hdr->b_flags &= ~ARC_FLAG_L2_WRITING;
5076185029Spjd		}
5077185029Spjd		mutex_exit(hash_lock);
5078185029Spjd	}
5079185029Spjd	mutex_exit(&l2arc_buflist_mtx);
5080185029Spjd
5081268085Sdelphij	vdev_space_update(dev->l2ad_vdev, -bytes_evicted, 0, 0);
5082185029Spjd	dev->l2ad_evict = taddr;
5083185029Spjd}
5084185029Spjd
5085185029Spjd/*
5086185029Spjd * Find and write ARC buffers to the L2ARC device.
5087185029Spjd *
5088275811Sdelphij * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
5089185029Spjd * for reading until they have completed writing.
5090251478Sdelphij * The headroom_boost is an in-out parameter used to maintain headroom boost
5091251478Sdelphij * state between calls to this function.
5092251478Sdelphij *
5093251478Sdelphij * Returns the number of bytes actually written (which may be smaller than
5094251478Sdelphij * the delta by which the device hand has changed due to alignment).
5095185029Spjd */
5096208373Smmstatic uint64_t
5097251478Sdelphijl2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
5098251478Sdelphij    boolean_t *headroom_boost)
5099185029Spjd{
5100275811Sdelphij	arc_buf_hdr_t *hdr, *hdr_prev, *head;
5101185029Spjd	list_t *list;
5102251478Sdelphij	uint64_t write_asize, write_psize, write_sz, headroom,
5103251478Sdelphij	    buf_compress_minsz;
5104185029Spjd	void *buf_data;
5105251478Sdelphij	kmutex_t *list_lock;
5106251478Sdelphij	boolean_t full;
5107185029Spjd	l2arc_write_callback_t *cb;
5108185029Spjd	zio_t *pio, *wzio;
5109228103Smm	uint64_t guid = spa_load_guid(spa);
5110251478Sdelphij	const boolean_t do_headroom_boost = *headroom_boost;
5111185029Spjd	int try;
5112185029Spjd
5113185029Spjd	ASSERT(dev->l2ad_vdev != NULL);
5114185029Spjd
5115251478Sdelphij	/* Lower the flag now, we might want to raise it again later. */
5116251478Sdelphij	*headroom_boost = B_FALSE;
5117251478Sdelphij
5118185029Spjd	pio = NULL;
5119251478Sdelphij	write_sz = write_asize = write_psize = 0;
5120185029Spjd	full = B_FALSE;
5121185029Spjd	head = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
5122275811Sdelphij	head->b_flags |= ARC_FLAG_L2_WRITE_HEAD;
5123185029Spjd
5124205231Skmacy	ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
5125185029Spjd	/*
5126251478Sdelphij	 * We will want to try to compress buffers that are at least 2x the
5127251478Sdelphij	 * device sector size.
5128251478Sdelphij	 */
5129251478Sdelphij	buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
5130251478Sdelphij
5131251478Sdelphij	/*
5132185029Spjd	 * Copy buffers for L2ARC writing.
5133185029Spjd	 */
5134185029Spjd	mutex_enter(&l2arc_buflist_mtx);
5135206796Spjd	for (try = 0; try < 2 * ARC_BUFC_NUMLISTS; try++) {
5136251478Sdelphij		uint64_t passed_sz = 0;
5137251478Sdelphij
5138185029Spjd		list = l2arc_list_locked(try, &list_lock);
5139205231Skmacy		ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
5140185029Spjd
5141185029Spjd		/*
5142185029Spjd		 * L2ARC fast warmup.
5143185029Spjd		 *
5144185029Spjd		 * Until the ARC is warm and starts to evict, read from the
5145185029Spjd		 * head of the ARC lists rather than the tail.
5146185029Spjd		 */
5147185029Spjd		if (arc_warm == B_FALSE)
5148275811Sdelphij			hdr = list_head(list);
5149185029Spjd		else
5150275811Sdelphij			hdr = list_tail(list);
5151275811Sdelphij		if (hdr == NULL)
5152205231Skmacy			ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
5153185029Spjd
5154272708Savg		headroom = target_sz * l2arc_headroom * 2 / ARC_BUFC_NUMLISTS;
5155251478Sdelphij		if (do_headroom_boost)
5156251478Sdelphij			headroom = (headroom * l2arc_headroom_boost) / 100;
5157251478Sdelphij
5158275811Sdelphij		for (; hdr; hdr = hdr_prev) {
5159251478Sdelphij			l2arc_buf_hdr_t *l2hdr;
5160251478Sdelphij			kmutex_t *hash_lock;
5161251478Sdelphij			uint64_t buf_sz;
5162251478Sdelphij
5163185029Spjd			if (arc_warm == B_FALSE)
5164275811Sdelphij				hdr_prev = list_next(list, hdr);
5165185029Spjd			else
5166275811Sdelphij				hdr_prev = list_prev(list, hdr);
5167275811Sdelphij			ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned, hdr->b_size);
5168206796Spjd
5169275811Sdelphij			hash_lock = HDR_LOCK(hdr);
5170251478Sdelphij			if (!mutex_tryenter(hash_lock)) {
5171205231Skmacy				ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
5172185029Spjd				/*
5173185029Spjd				 * Skip this buffer rather than waiting.
5174185029Spjd				 */
5175185029Spjd				continue;
5176185029Spjd			}
5177185029Spjd
5178275811Sdelphij			passed_sz += hdr->b_size;
5179185029Spjd			if (passed_sz > headroom) {
5180185029Spjd				/*
5181185029Spjd				 * Searched too far.
5182185029Spjd				 */
5183185029Spjd				mutex_exit(hash_lock);
5184205231Skmacy				ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
5185185029Spjd				break;
5186185029Spjd			}
5187185029Spjd
5188275811Sdelphij			if (!l2arc_write_eligible(guid, hdr)) {
5189185029Spjd				mutex_exit(hash_lock);
5190185029Spjd				continue;
5191185029Spjd			}
5192185029Spjd
5193275811Sdelphij			if ((write_sz + hdr->b_size) > target_sz) {
5194185029Spjd				full = B_TRUE;
5195185029Spjd				mutex_exit(hash_lock);
5196205231Skmacy				ARCSTAT_BUMP(arcstat_l2_write_full);
5197185029Spjd				break;
5198185029Spjd			}
5199185029Spjd
5200185029Spjd			if (pio == NULL) {
5201185029Spjd				/*
5202185029Spjd				 * Insert a dummy header on the buflist so
5203185029Spjd				 * l2arc_write_done() can find where the
5204185029Spjd				 * write buffers begin without searching.
5205185029Spjd				 */
5206185029Spjd				list_insert_head(dev->l2ad_buflist, head);
5207185029Spjd
5208185029Spjd				cb = kmem_alloc(
5209185029Spjd				    sizeof (l2arc_write_callback_t), KM_SLEEP);
5210185029Spjd				cb->l2wcb_dev = dev;
5211185029Spjd				cb->l2wcb_head = head;
5212185029Spjd				pio = zio_root(spa, l2arc_write_done, cb,
5213185029Spjd				    ZIO_FLAG_CANFAIL);
5214205231Skmacy				ARCSTAT_BUMP(arcstat_l2_write_pios);
5215185029Spjd			}
5216185029Spjd
5217185029Spjd			/*
5218185029Spjd			 * Create and add a new L2ARC header.
5219185029Spjd			 */
5220251478Sdelphij			l2hdr = kmem_zalloc(sizeof (l2arc_buf_hdr_t), KM_SLEEP);
5221251478Sdelphij			l2hdr->b_dev = dev;
5222275811Sdelphij			hdr->b_flags |= ARC_FLAG_L2_WRITING;
5223185029Spjd
5224251478Sdelphij			/*
5225251478Sdelphij			 * Temporarily stash the data buffer in b_tmp_cdata.
5226251478Sdelphij			 * The subsequent write step will pick it up from
5227275811Sdelphij			 * there. This is because can't access hdr->b_buf
5228251478Sdelphij			 * without holding the hash_lock, which we in turn
5229251478Sdelphij			 * can't access without holding the ARC list locks
5230251478Sdelphij			 * (which we want to avoid during compression/writing).
5231251478Sdelphij			 */
5232251478Sdelphij			l2hdr->b_compress = ZIO_COMPRESS_OFF;
5233275811Sdelphij			l2hdr->b_asize = hdr->b_size;
5234275811Sdelphij			l2hdr->b_tmp_cdata = hdr->b_buf->b_data;
5235251478Sdelphij
5236275811Sdelphij			buf_sz = hdr->b_size;
5237275811Sdelphij			hdr->b_l2hdr = l2hdr;
5238185029Spjd
5239275811Sdelphij			list_insert_head(dev->l2ad_buflist, hdr);
5240251478Sdelphij
5241185029Spjd			/*
5242185029Spjd			 * Compute and store the buffer cksum before
5243185029Spjd			 * writing.  On debug the cksum is verified first.
5244185029Spjd			 */
5245275811Sdelphij			arc_cksum_verify(hdr->b_buf);
5246275811Sdelphij			arc_cksum_compute(hdr->b_buf, B_TRUE);
5247185029Spjd
5248185029Spjd			mutex_exit(hash_lock);
5249185029Spjd
5250251478Sdelphij			write_sz += buf_sz;
5251251478Sdelphij		}
5252251478Sdelphij
5253251478Sdelphij		mutex_exit(list_lock);
5254251478Sdelphij
5255251478Sdelphij		if (full == B_TRUE)
5256251478Sdelphij			break;
5257251478Sdelphij	}
5258251478Sdelphij
5259251478Sdelphij	/* No buffers selected for writing? */
5260251478Sdelphij	if (pio == NULL) {
5261251478Sdelphij		ASSERT0(write_sz);
5262251478Sdelphij		mutex_exit(&l2arc_buflist_mtx);
5263251478Sdelphij		kmem_cache_free(hdr_cache, head);
5264251478Sdelphij		return (0);
5265251478Sdelphij	}
5266251478Sdelphij
5267251478Sdelphij	/*
5268251478Sdelphij	 * Now start writing the buffers. We're starting at the write head
5269251478Sdelphij	 * and work backwards, retracing the course of the buffer selector
5270251478Sdelphij	 * loop above.
5271251478Sdelphij	 */
5272275811Sdelphij	for (hdr = list_prev(dev->l2ad_buflist, head); hdr;
5273275811Sdelphij	    hdr = list_prev(dev->l2ad_buflist, hdr)) {
5274251478Sdelphij		l2arc_buf_hdr_t *l2hdr;
5275251478Sdelphij		uint64_t buf_sz;
5276251478Sdelphij
5277251478Sdelphij		/*
5278251478Sdelphij		 * We shouldn't need to lock the buffer here, since we flagged
5279275811Sdelphij		 * it as ARC_FLAG_L2_WRITING in the previous step, but we must
5280275811Sdelphij		 * take care to only access its L2 cache parameters. In
5281275811Sdelphij		 * particular, hdr->b_buf may be invalid by now due to
5282275811Sdelphij		 * ARC eviction.
5283251478Sdelphij		 */
5284275811Sdelphij		l2hdr = hdr->b_l2hdr;
5285251478Sdelphij		l2hdr->b_daddr = dev->l2ad_hand;
5286251478Sdelphij
5287275811Sdelphij		if ((hdr->b_flags & ARC_FLAG_L2COMPRESS) &&
5288251478Sdelphij		    l2hdr->b_asize >= buf_compress_minsz) {
5289251478Sdelphij			if (l2arc_compress_buf(l2hdr)) {
5290251478Sdelphij				/*
5291251478Sdelphij				 * If compression succeeded, enable headroom
5292251478Sdelphij				 * boost on the next scan cycle.
5293251478Sdelphij				 */
5294251478Sdelphij				*headroom_boost = B_TRUE;
5295251478Sdelphij			}
5296251478Sdelphij		}
5297251478Sdelphij
5298251478Sdelphij		/*
5299251478Sdelphij		 * Pick up the buffer data we had previously stashed away
5300251478Sdelphij		 * (and now potentially also compressed).
5301251478Sdelphij		 */
5302251478Sdelphij		buf_data = l2hdr->b_tmp_cdata;
5303251478Sdelphij		buf_sz = l2hdr->b_asize;
5304251478Sdelphij
5305274172Savg		/*
5306274172Savg		 * If the data has not been compressed, then clear b_tmp_cdata
5307274172Savg		 * to make sure that it points only to a temporary compression
5308274172Savg		 * buffer.
5309274172Savg		 */
5310274172Savg		if (!L2ARC_IS_VALID_COMPRESS(l2hdr->b_compress))
5311274172Savg			l2hdr->b_tmp_cdata = NULL;
5312274172Savg
5313251478Sdelphij		/* Compression may have squashed the buffer to zero length. */
5314251478Sdelphij		if (buf_sz != 0) {
5315251478Sdelphij			uint64_t buf_p_sz;
5316251478Sdelphij
5317185029Spjd			wzio = zio_write_phys(pio, dev->l2ad_vdev,
5318185029Spjd			    dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
5319185029Spjd			    NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
5320185029Spjd			    ZIO_FLAG_CANFAIL, B_FALSE);
5321185029Spjd
5322185029Spjd			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
5323185029Spjd			    zio_t *, wzio);
5324185029Spjd			(void) zio_nowait(wzio);
5325185029Spjd
5326251478Sdelphij			write_asize += buf_sz;
5327185029Spjd			/*
5328185029Spjd			 * Keep the clock hand suitably device-aligned.
5329185029Spjd			 */
5330251478Sdelphij			buf_p_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
5331251478Sdelphij			write_psize += buf_p_sz;
5332251478Sdelphij			dev->l2ad_hand += buf_p_sz;
5333185029Spjd		}
5334251478Sdelphij	}
5335185029Spjd
5336185029Spjd	mutex_exit(&l2arc_buflist_mtx);
5337185029Spjd
5338251478Sdelphij	ASSERT3U(write_asize, <=, target_sz);
5339185029Spjd	ARCSTAT_BUMP(arcstat_l2_writes_sent);
5340251478Sdelphij	ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
5341185029Spjd	ARCSTAT_INCR(arcstat_l2_size, write_sz);
5342251478Sdelphij	ARCSTAT_INCR(arcstat_l2_asize, write_asize);
5343275096Sdelphij	vdev_space_update(dev->l2ad_vdev, write_asize, 0, 0);
5344185029Spjd
5345185029Spjd	/*
5346185029Spjd	 * Bump device hand to the device start if it is approaching the end.
5347185029Spjd	 * l2arc_evict() will already have evicted ahead for this case.
5348185029Spjd	 */
5349185029Spjd	if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
5350185029Spjd		dev->l2ad_hand = dev->l2ad_start;
5351185029Spjd		dev->l2ad_evict = dev->l2ad_start;
5352185029Spjd		dev->l2ad_first = B_FALSE;
5353185029Spjd	}
5354185029Spjd
5355208373Smm	dev->l2ad_writing = B_TRUE;
5356185029Spjd	(void) zio_wait(pio);
5357208373Smm	dev->l2ad_writing = B_FALSE;
5358208373Smm
5359251478Sdelphij	return (write_asize);
5360185029Spjd}
5361185029Spjd
5362185029Spjd/*
5363251478Sdelphij * Compresses an L2ARC buffer.
5364251478Sdelphij * The data to be compressed must be prefilled in l2hdr->b_tmp_cdata and its
5365251478Sdelphij * size in l2hdr->b_asize. This routine tries to compress the data and
5366251478Sdelphij * depending on the compression result there are three possible outcomes:
5367251478Sdelphij * *) The buffer was incompressible. The original l2hdr contents were left
5368251478Sdelphij *    untouched and are ready for writing to an L2 device.
5369251478Sdelphij * *) The buffer was all-zeros, so there is no need to write it to an L2
5370251478Sdelphij *    device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
5371251478Sdelphij *    set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
5372251478Sdelphij * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
5373251478Sdelphij *    data buffer which holds the compressed data to be written, and b_asize
5374251478Sdelphij *    tells us how much data there is. b_compress is set to the appropriate
5375251478Sdelphij *    compression algorithm. Once writing is done, invoke
5376251478Sdelphij *    l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
5377251478Sdelphij *
5378251478Sdelphij * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
5379251478Sdelphij * buffer was incompressible).
5380251478Sdelphij */
5381251478Sdelphijstatic boolean_t
5382251478Sdelphijl2arc_compress_buf(l2arc_buf_hdr_t *l2hdr)
5383251478Sdelphij{
5384251478Sdelphij	void *cdata;
5385268075Sdelphij	size_t csize, len, rounded;
5386251478Sdelphij
5387251478Sdelphij	ASSERT(l2hdr->b_compress == ZIO_COMPRESS_OFF);
5388251478Sdelphij	ASSERT(l2hdr->b_tmp_cdata != NULL);
5389251478Sdelphij
5390251478Sdelphij	len = l2hdr->b_asize;
5391251478Sdelphij	cdata = zio_data_buf_alloc(len);
5392251478Sdelphij	csize = zio_compress_data(ZIO_COMPRESS_LZ4, l2hdr->b_tmp_cdata,
5393269086Sdelphij	    cdata, l2hdr->b_asize);
5394251478Sdelphij
5395251478Sdelphij	if (csize == 0) {
5396251478Sdelphij		/* zero block, indicate that there's nothing to write */
5397251478Sdelphij		zio_data_buf_free(cdata, len);
5398251478Sdelphij		l2hdr->b_compress = ZIO_COMPRESS_EMPTY;
5399251478Sdelphij		l2hdr->b_asize = 0;
5400251478Sdelphij		l2hdr->b_tmp_cdata = NULL;
5401251478Sdelphij		ARCSTAT_BUMP(arcstat_l2_compress_zeros);
5402251478Sdelphij		return (B_TRUE);
5403274628Savg	}
5404274628Savg
5405274628Savg	rounded = P2ROUNDUP(csize,
5406274628Savg	    (size_t)1 << l2hdr->b_dev->l2ad_vdev->vdev_ashift);
5407274628Savg	if (rounded < len) {
5408251478Sdelphij		/*
5409251478Sdelphij		 * Compression succeeded, we'll keep the cdata around for
5410251478Sdelphij		 * writing and release it afterwards.
5411251478Sdelphij		 */
5412274628Savg		if (rounded > csize) {
5413274628Savg			bzero((char *)cdata + csize, rounded - csize);
5414274628Savg			csize = rounded;
5415274628Savg		}
5416251478Sdelphij		l2hdr->b_compress = ZIO_COMPRESS_LZ4;
5417251478Sdelphij		l2hdr->b_asize = csize;
5418251478Sdelphij		l2hdr->b_tmp_cdata = cdata;
5419251478Sdelphij		ARCSTAT_BUMP(arcstat_l2_compress_successes);
5420251478Sdelphij		return (B_TRUE);
5421251478Sdelphij	} else {
5422251478Sdelphij		/*
5423251478Sdelphij		 * Compression failed, release the compressed buffer.
5424251478Sdelphij		 * l2hdr will be left unmodified.
5425251478Sdelphij		 */
5426251478Sdelphij		zio_data_buf_free(cdata, len);
5427251478Sdelphij		ARCSTAT_BUMP(arcstat_l2_compress_failures);
5428251478Sdelphij		return (B_FALSE);
5429251478Sdelphij	}
5430251478Sdelphij}
5431251478Sdelphij
5432251478Sdelphij/*
5433251478Sdelphij * Decompresses a zio read back from an l2arc device. On success, the
5434251478Sdelphij * underlying zio's io_data buffer is overwritten by the uncompressed
5435251478Sdelphij * version. On decompression error (corrupt compressed stream), the
5436251478Sdelphij * zio->io_error value is set to signal an I/O error.
5437251478Sdelphij *
5438251478Sdelphij * Please note that the compressed data stream is not checksummed, so
5439251478Sdelphij * if the underlying device is experiencing data corruption, we may feed
5440251478Sdelphij * corrupt data to the decompressor, so the decompressor needs to be
5441251478Sdelphij * able to handle this situation (LZ4 does).
5442251478Sdelphij */
5443251478Sdelphijstatic void
5444251478Sdelphijl2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
5445251478Sdelphij{
5446251478Sdelphij	ASSERT(L2ARC_IS_VALID_COMPRESS(c));
5447251478Sdelphij
5448251478Sdelphij	if (zio->io_error != 0) {
5449251478Sdelphij		/*
5450251478Sdelphij		 * An io error has occured, just restore the original io
5451251478Sdelphij		 * size in preparation for a main pool read.
5452251478Sdelphij		 */
5453251478Sdelphij		zio->io_orig_size = zio->io_size = hdr->b_size;
5454251478Sdelphij		return;
5455251478Sdelphij	}
5456251478Sdelphij
5457251478Sdelphij	if (c == ZIO_COMPRESS_EMPTY) {
5458251478Sdelphij		/*
5459251478Sdelphij		 * An empty buffer results in a null zio, which means we
5460251478Sdelphij		 * need to fill its io_data after we're done restoring the
5461251478Sdelphij		 * buffer's contents.
5462251478Sdelphij		 */
5463251478Sdelphij		ASSERT(hdr->b_buf != NULL);
5464251478Sdelphij		bzero(hdr->b_buf->b_data, hdr->b_size);
5465251478Sdelphij		zio->io_data = zio->io_orig_data = hdr->b_buf->b_data;
5466251478Sdelphij	} else {
5467251478Sdelphij		ASSERT(zio->io_data != NULL);
5468251478Sdelphij		/*
5469251478Sdelphij		 * We copy the compressed data from the start of the arc buffer
5470251478Sdelphij		 * (the zio_read will have pulled in only what we need, the
5471251478Sdelphij		 * rest is garbage which we will overwrite at decompression)
5472251478Sdelphij		 * and then decompress back to the ARC data buffer. This way we
5473251478Sdelphij		 * can minimize copying by simply decompressing back over the
5474251478Sdelphij		 * original compressed data (rather than decompressing to an
5475251478Sdelphij		 * aux buffer and then copying back the uncompressed buffer,
5476251478Sdelphij		 * which is likely to be much larger).
5477251478Sdelphij		 */
5478251478Sdelphij		uint64_t csize;
5479251478Sdelphij		void *cdata;
5480251478Sdelphij
5481251478Sdelphij		csize = zio->io_size;
5482251478Sdelphij		cdata = zio_data_buf_alloc(csize);
5483251478Sdelphij		bcopy(zio->io_data, cdata, csize);
5484251478Sdelphij		if (zio_decompress_data(c, cdata, zio->io_data, csize,
5485251478Sdelphij		    hdr->b_size) != 0)
5486251478Sdelphij			zio->io_error = EIO;
5487251478Sdelphij		zio_data_buf_free(cdata, csize);
5488251478Sdelphij	}
5489251478Sdelphij
5490251478Sdelphij	/* Restore the expected uncompressed IO size. */
5491251478Sdelphij	zio->io_orig_size = zio->io_size = hdr->b_size;
5492251478Sdelphij}
5493251478Sdelphij
5494251478Sdelphij/*
5495251478Sdelphij * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
5496251478Sdelphij * This buffer serves as a temporary holder of compressed data while
5497251478Sdelphij * the buffer entry is being written to an l2arc device. Once that is
5498251478Sdelphij * done, we can dispose of it.
5499251478Sdelphij */
5500251478Sdelphijstatic void
5501275811Sdelphijl2arc_release_cdata_buf(arc_buf_hdr_t *hdr)
5502251478Sdelphij{
5503275811Sdelphij	l2arc_buf_hdr_t *l2hdr = hdr->b_l2hdr;
5504251478Sdelphij
5505274172Savg	ASSERT(L2ARC_IS_VALID_COMPRESS(l2hdr->b_compress));
5506274172Savg	if (l2hdr->b_compress != ZIO_COMPRESS_EMPTY) {
5507251478Sdelphij		/*
5508251478Sdelphij		 * If the data was compressed, then we've allocated a
5509251478Sdelphij		 * temporary buffer for it, so now we need to release it.
5510251478Sdelphij		 */
5511251478Sdelphij		ASSERT(l2hdr->b_tmp_cdata != NULL);
5512275811Sdelphij		zio_data_buf_free(l2hdr->b_tmp_cdata, hdr->b_size);
5513274172Savg		l2hdr->b_tmp_cdata = NULL;
5514274172Savg	} else {
5515274172Savg		ASSERT(l2hdr->b_tmp_cdata == NULL);
5516251478Sdelphij	}
5517251478Sdelphij}
5518251478Sdelphij
5519251478Sdelphij/*
5520185029Spjd * This thread feeds the L2ARC at regular intervals.  This is the beating
5521185029Spjd * heart of the L2ARC.
5522185029Spjd */
5523185029Spjdstatic void
5524185029Spjdl2arc_feed_thread(void *dummy __unused)
5525185029Spjd{
5526185029Spjd	callb_cpr_t cpr;
5527185029Spjd	l2arc_dev_t *dev;
5528185029Spjd	spa_t *spa;
5529208373Smm	uint64_t size, wrote;
5530219089Spjd	clock_t begin, next = ddi_get_lbolt();
5531251478Sdelphij	boolean_t headroom_boost = B_FALSE;
5532185029Spjd
5533185029Spjd	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
5534185029Spjd
5535185029Spjd	mutex_enter(&l2arc_feed_thr_lock);
5536185029Spjd
5537185029Spjd	while (l2arc_thread_exit == 0) {
5538185029Spjd		CALLB_CPR_SAFE_BEGIN(&cpr);
5539185029Spjd		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
5540219089Spjd		    next - ddi_get_lbolt());
5541185029Spjd		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
5542219089Spjd		next = ddi_get_lbolt() + hz;
5543185029Spjd
5544185029Spjd		/*
5545185029Spjd		 * Quick check for L2ARC devices.
5546185029Spjd		 */
5547185029Spjd		mutex_enter(&l2arc_dev_mtx);
5548185029Spjd		if (l2arc_ndev == 0) {
5549185029Spjd			mutex_exit(&l2arc_dev_mtx);
5550185029Spjd			continue;
5551185029Spjd		}
5552185029Spjd		mutex_exit(&l2arc_dev_mtx);
5553219089Spjd		begin = ddi_get_lbolt();
5554185029Spjd
5555185029Spjd		/*
5556185029Spjd		 * This selects the next l2arc device to write to, and in
5557185029Spjd		 * doing so the next spa to feed from: dev->l2ad_spa.   This
5558185029Spjd		 * will return NULL if there are now no l2arc devices or if
5559185029Spjd		 * they are all faulted.
5560185029Spjd		 *
5561185029Spjd		 * If a device is returned, its spa's config lock is also
5562185029Spjd		 * held to prevent device removal.  l2arc_dev_get_next()
5563185029Spjd		 * will grab and release l2arc_dev_mtx.
5564185029Spjd		 */
5565185029Spjd		if ((dev = l2arc_dev_get_next()) == NULL)
5566185029Spjd			continue;
5567185029Spjd
5568185029Spjd		spa = dev->l2ad_spa;
5569185029Spjd		ASSERT(spa != NULL);
5570185029Spjd
5571185029Spjd		/*
5572219089Spjd		 * If the pool is read-only then force the feed thread to
5573219089Spjd		 * sleep a little longer.
5574219089Spjd		 */
5575219089Spjd		if (!spa_writeable(spa)) {
5576219089Spjd			next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
5577219089Spjd			spa_config_exit(spa, SCL_L2ARC, dev);
5578219089Spjd			continue;
5579219089Spjd		}
5580219089Spjd
5581219089Spjd		/*
5582185029Spjd		 * Avoid contributing to memory pressure.
5583185029Spjd		 */
5584185029Spjd		if (arc_reclaim_needed()) {
5585185029Spjd			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
5586185029Spjd			spa_config_exit(spa, SCL_L2ARC, dev);
5587185029Spjd			continue;
5588185029Spjd		}
5589185029Spjd
5590185029Spjd		ARCSTAT_BUMP(arcstat_l2_feeds);
5591185029Spjd
5592251478Sdelphij		size = l2arc_write_size();
5593185029Spjd
5594185029Spjd		/*
5595185029Spjd		 * Evict L2ARC buffers that will be overwritten.
5596185029Spjd		 */
5597185029Spjd		l2arc_evict(dev, size, B_FALSE);
5598185029Spjd
5599185029Spjd		/*
5600185029Spjd		 * Write ARC buffers.
5601185029Spjd		 */
5602251478Sdelphij		wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
5603208373Smm
5604208373Smm		/*
5605208373Smm		 * Calculate interval between writes.
5606208373Smm		 */
5607208373Smm		next = l2arc_write_interval(begin, size, wrote);
5608185029Spjd		spa_config_exit(spa, SCL_L2ARC, dev);
5609185029Spjd	}
5610185029Spjd
5611185029Spjd	l2arc_thread_exit = 0;
5612185029Spjd	cv_broadcast(&l2arc_feed_thr_cv);
5613185029Spjd	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
5614185029Spjd	thread_exit();
5615185029Spjd}
5616185029Spjd
5617185029Spjdboolean_t
5618185029Spjdl2arc_vdev_present(vdev_t *vd)
5619185029Spjd{
5620185029Spjd	l2arc_dev_t *dev;
5621185029Spjd
5622185029Spjd	mutex_enter(&l2arc_dev_mtx);
5623185029Spjd	for (dev = list_head(l2arc_dev_list); dev != NULL;
5624185029Spjd	    dev = list_next(l2arc_dev_list, dev)) {
5625185029Spjd		if (dev->l2ad_vdev == vd)
5626185029Spjd			break;
5627185029Spjd	}
5628185029Spjd	mutex_exit(&l2arc_dev_mtx);
5629185029Spjd
5630185029Spjd	return (dev != NULL);
5631185029Spjd}
5632185029Spjd
5633185029Spjd/*
5634185029Spjd * Add a vdev for use by the L2ARC.  By this point the spa has already
5635185029Spjd * validated the vdev and opened it.
5636185029Spjd */
5637185029Spjdvoid
5638219089Spjdl2arc_add_vdev(spa_t *spa, vdev_t *vd)
5639185029Spjd{
5640185029Spjd	l2arc_dev_t *adddev;
5641185029Spjd
5642185029Spjd	ASSERT(!l2arc_vdev_present(vd));
5643185029Spjd
5644255753Sgibbs	vdev_ashift_optimize(vd);
5645255753Sgibbs
5646185029Spjd	/*
5647185029Spjd	 * Create a new l2arc device entry.
5648185029Spjd	 */
5649185029Spjd	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
5650185029Spjd	adddev->l2ad_spa = spa;
5651185029Spjd	adddev->l2ad_vdev = vd;
5652219089Spjd	adddev->l2ad_start = VDEV_LABEL_START_SIZE;
5653219089Spjd	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
5654185029Spjd	adddev->l2ad_hand = adddev->l2ad_start;
5655185029Spjd	adddev->l2ad_evict = adddev->l2ad_start;
5656185029Spjd	adddev->l2ad_first = B_TRUE;
5657208373Smm	adddev->l2ad_writing = B_FALSE;
5658185029Spjd
5659185029Spjd	/*
5660185029Spjd	 * This is a list of all ARC buffers that are still valid on the
5661185029Spjd	 * device.
5662185029Spjd	 */
5663185029Spjd	adddev->l2ad_buflist = kmem_zalloc(sizeof (list_t), KM_SLEEP);
5664185029Spjd	list_create(adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
5665185029Spjd	    offsetof(arc_buf_hdr_t, b_l2node));
5666185029Spjd
5667219089Spjd	vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
5668185029Spjd
5669185029Spjd	/*
5670185029Spjd	 * Add device to global list
5671185029Spjd	 */
5672185029Spjd	mutex_enter(&l2arc_dev_mtx);
5673185029Spjd	list_insert_head(l2arc_dev_list, adddev);
5674185029Spjd	atomic_inc_64(&l2arc_ndev);
5675185029Spjd	mutex_exit(&l2arc_dev_mtx);
5676185029Spjd}
5677185029Spjd
5678185029Spjd/*
5679185029Spjd * Remove a vdev from the L2ARC.
5680185029Spjd */
5681185029Spjdvoid
5682185029Spjdl2arc_remove_vdev(vdev_t *vd)
5683185029Spjd{
5684185029Spjd	l2arc_dev_t *dev, *nextdev, *remdev = NULL;
5685185029Spjd
5686185029Spjd	/*
5687185029Spjd	 * Find the device by vdev
5688185029Spjd	 */
5689185029Spjd	mutex_enter(&l2arc_dev_mtx);
5690185029Spjd	for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
5691185029Spjd		nextdev = list_next(l2arc_dev_list, dev);
5692185029Spjd		if (vd == dev->l2ad_vdev) {
5693185029Spjd			remdev = dev;
5694185029Spjd			break;
5695185029Spjd		}
5696185029Spjd	}
5697185029Spjd	ASSERT(remdev != NULL);
5698185029Spjd
5699185029Spjd	/*
5700185029Spjd	 * Remove device from global list
5701185029Spjd	 */
5702185029Spjd	list_remove(l2arc_dev_list, remdev);
5703185029Spjd	l2arc_dev_last = NULL;		/* may have been invalidated */
5704185029Spjd	atomic_dec_64(&l2arc_ndev);
5705185029Spjd	mutex_exit(&l2arc_dev_mtx);
5706185029Spjd
5707185029Spjd	/*
5708185029Spjd	 * Clear all buflists and ARC references.  L2ARC device flush.
5709185029Spjd	 */
5710185029Spjd	l2arc_evict(remdev, 0, B_TRUE);
5711185029Spjd	list_destroy(remdev->l2ad_buflist);
5712185029Spjd	kmem_free(remdev->l2ad_buflist, sizeof (list_t));
5713185029Spjd	kmem_free(remdev, sizeof (l2arc_dev_t));
5714185029Spjd}
5715185029Spjd
5716185029Spjdvoid
5717185029Spjdl2arc_init(void)
5718185029Spjd{
5719185029Spjd	l2arc_thread_exit = 0;
5720185029Spjd	l2arc_ndev = 0;
5721185029Spjd	l2arc_writes_sent = 0;
5722185029Spjd	l2arc_writes_done = 0;
5723185029Spjd
5724185029Spjd	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
5725185029Spjd	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
5726185029Spjd	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
5727185029Spjd	mutex_init(&l2arc_buflist_mtx, NULL, MUTEX_DEFAULT, NULL);
5728185029Spjd	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
5729185029Spjd
5730185029Spjd	l2arc_dev_list = &L2ARC_dev_list;
5731185029Spjd	l2arc_free_on_write = &L2ARC_free_on_write;
5732185029Spjd	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
5733185029Spjd	    offsetof(l2arc_dev_t, l2ad_node));
5734185029Spjd	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
5735185029Spjd	    offsetof(l2arc_data_free_t, l2df_list_node));
5736185029Spjd}
5737185029Spjd
5738185029Spjdvoid
5739185029Spjdl2arc_fini(void)
5740185029Spjd{
5741185029Spjd	/*
5742185029Spjd	 * This is called from dmu_fini(), which is called from spa_fini();
5743185029Spjd	 * Because of this, we can assume that all l2arc devices have
5744185029Spjd	 * already been removed when the pools themselves were removed.
5745185029Spjd	 */
5746185029Spjd
5747185029Spjd	l2arc_do_free_on_write();
5748185029Spjd
5749185029Spjd	mutex_destroy(&l2arc_feed_thr_lock);
5750185029Spjd	cv_destroy(&l2arc_feed_thr_cv);
5751185029Spjd	mutex_destroy(&l2arc_dev_mtx);
5752185029Spjd	mutex_destroy(&l2arc_buflist_mtx);
5753185029Spjd	mutex_destroy(&l2arc_free_on_write_mtx);
5754185029Spjd
5755185029Spjd	list_destroy(l2arc_dev_list);
5756185029Spjd	list_destroy(l2arc_free_on_write);
5757185029Spjd}
5758185029Spjd
5759185029Spjdvoid
5760185029Spjdl2arc_start(void)
5761185029Spjd{
5762209962Smm	if (!(spa_mode_global & FWRITE))
5763185029Spjd		return;
5764185029Spjd
5765185029Spjd	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
5766185029Spjd	    TS_RUN, minclsyspri);
5767185029Spjd}
5768185029Spjd
5769185029Spjdvoid
5770185029Spjdl2arc_stop(void)
5771185029Spjd{
5772209962Smm	if (!(spa_mode_global & FWRITE))
5773185029Spjd		return;
5774185029Spjd
5775185029Spjd	mutex_enter(&l2arc_feed_thr_lock);
5776185029Spjd	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
5777185029Spjd	l2arc_thread_exit = 1;
5778185029Spjd	while (l2arc_thread_exit != 0)
5779185029Spjd		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
5780185029Spjd	mutex_exit(&l2arc_feed_thr_lock);
5781185029Spjd}
5782