arc.c revision 269230
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>
141191902Skmacy
142240133Smm#ifdef illumos
143240133Smm#ifndef _KERNEL
144240133Smm/* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
145240133Smmboolean_t arc_watch = B_FALSE;
146240133Smmint arc_procfd;
147240133Smm#endif
148240133Smm#endif /* illumos */
149240133Smm
150168404Spjdstatic kmutex_t		arc_reclaim_thr_lock;
151168404Spjdstatic kcondvar_t	arc_reclaim_thr_cv;	/* used to signal reclaim thr */
152168404Spjdstatic uint8_t		arc_thread_exit;
153168404Spjd
154168404Spjd#define	ARC_REDUCE_DNLC_PERCENT	3
155168404Spjduint_t arc_reduce_dnlc_percent = ARC_REDUCE_DNLC_PERCENT;
156168404Spjd
157168404Spjdtypedef enum arc_reclaim_strategy {
158168404Spjd	ARC_RECLAIM_AGGR,		/* Aggressive reclaim strategy */
159168404Spjd	ARC_RECLAIM_CONS		/* Conservative reclaim strategy */
160168404Spjd} arc_reclaim_strategy_t;
161168404Spjd
162258632Savg/*
163258632Savg * The number of iterations through arc_evict_*() before we
164258632Savg * drop & reacquire the lock.
165258632Savg */
166258632Savgint arc_evict_iterations = 100;
167258632Savg
168168404Spjd/* number of seconds before growing cache again */
169168404Spjdstatic int		arc_grow_retry = 60;
170168404Spjd
171208373Smm/* shift of arc_c for calculating both min and max arc_p */
172208373Smmstatic int		arc_p_min_shift = 4;
173208373Smm
174208373Smm/* log2(fraction of arc to reclaim) */
175208373Smmstatic int		arc_shrink_shift = 5;
176208373Smm
177168404Spjd/*
178168404Spjd * minimum lifespan of a prefetch block in clock ticks
179168404Spjd * (initialized in arc_init())
180168404Spjd */
181168404Spjdstatic int		arc_min_prefetch_lifespan;
182168404Spjd
183258632Savg/*
184258632Savg * If this percent of memory is free, don't throttle.
185258632Savg */
186258632Savgint arc_lotsfree_percent = 10;
187258632Savg
188208373Smmstatic int arc_dead;
189194043Skmacyextern int zfs_prefetch_disable;
190168404Spjd
191168404Spjd/*
192185029Spjd * The arc has filled available memory and has now warmed up.
193185029Spjd */
194185029Spjdstatic boolean_t arc_warm;
195185029Spjd
196185029Spjd/*
197168404Spjd * These tunables are for performance analysis.
198168404Spjd */
199185029Spjduint64_t zfs_arc_max;
200185029Spjduint64_t zfs_arc_min;
201185029Spjduint64_t zfs_arc_meta_limit = 0;
202208373Smmint zfs_arc_grow_retry = 0;
203208373Smmint zfs_arc_shrink_shift = 0;
204208373Smmint zfs_arc_p_min_shift = 0;
205242845Sdelphijint zfs_disable_dup_eviction = 0;
206269230Sdelphijuint64_t zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
207185029Spjd
208185029SpjdTUNABLE_QUAD("vfs.zfs.arc_meta_limit", &zfs_arc_meta_limit);
209168473SpjdSYSCTL_DECL(_vfs_zfs);
210217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_max, CTLFLAG_RDTUN, &zfs_arc_max, 0,
211168473Spjd    "Maximum ARC size");
212217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_min, CTLFLAG_RDTUN, &zfs_arc_min, 0,
213168473Spjd    "Minimum ARC size");
214269230SdelphijSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_average_blocksize, CTLFLAG_RDTUN,
215269230Sdelphij    &zfs_arc_average_blocksize, 0,
216269230Sdelphij    "ARC average blocksize");
217168404Spjd
218168404Spjd/*
219185029Spjd * Note that buffers can be in one of 6 states:
220168404Spjd *	ARC_anon	- anonymous (discussed below)
221168404Spjd *	ARC_mru		- recently used, currently cached
222168404Spjd *	ARC_mru_ghost	- recentely used, no longer in cache
223168404Spjd *	ARC_mfu		- frequently used, currently cached
224168404Spjd *	ARC_mfu_ghost	- frequently used, no longer in cache
225185029Spjd *	ARC_l2c_only	- exists in L2ARC but not other states
226185029Spjd * When there are no active references to the buffer, they are
227185029Spjd * are linked onto a list in one of these arc states.  These are
228185029Spjd * the only buffers that can be evicted or deleted.  Within each
229185029Spjd * state there are multiple lists, one for meta-data and one for
230185029Spjd * non-meta-data.  Meta-data (indirect blocks, blocks of dnodes,
231185029Spjd * etc.) is tracked separately so that it can be managed more
232185029Spjd * explicitly: favored over data, limited explicitly.
233168404Spjd *
234168404Spjd * Anonymous buffers are buffers that are not associated with
235168404Spjd * a DVA.  These are buffers that hold dirty block copies
236168404Spjd * before they are written to stable storage.  By definition,
237168404Spjd * they are "ref'd" and are considered part of arc_mru
238168404Spjd * that cannot be freed.  Generally, they will aquire a DVA
239168404Spjd * as they are written and migrate onto the arc_mru list.
240185029Spjd *
241185029Spjd * The ARC_l2c_only state is for buffers that are in the second
242185029Spjd * level ARC but no longer in any of the ARC_m* lists.  The second
243185029Spjd * level ARC itself may also contain buffers that are in any of
244185029Spjd * the ARC_m* states - meaning that a buffer can exist in two
245185029Spjd * places.  The reason for the ARC_l2c_only state is to keep the
246185029Spjd * buffer header in the hash table, so that reads that hit the
247185029Spjd * second level ARC benefit from these fast lookups.
248168404Spjd */
249168404Spjd
250205264Skmacy#define	ARCS_LOCK_PAD		CACHE_LINE_SIZE
251205231Skmacystruct arcs_lock {
252205231Skmacy	kmutex_t	arcs_lock;
253205231Skmacy#ifdef _KERNEL
254205231Skmacy	unsigned char	pad[(ARCS_LOCK_PAD - sizeof (kmutex_t))];
255205231Skmacy#endif
256205231Skmacy};
257205231Skmacy
258205231Skmacy/*
259205231Skmacy * must be power of two for mask use to work
260205231Skmacy *
261205231Skmacy */
262205231Skmacy#define ARC_BUFC_NUMDATALISTS		16
263205231Skmacy#define ARC_BUFC_NUMMETADATALISTS	16
264206796Spjd#define ARC_BUFC_NUMLISTS	(ARC_BUFC_NUMMETADATALISTS + ARC_BUFC_NUMDATALISTS)
265205231Skmacy
266168404Spjdtypedef struct arc_state {
267185029Spjd	uint64_t arcs_lsize[ARC_BUFC_NUMTYPES];	/* amount of evictable data */
268185029Spjd	uint64_t arcs_size;	/* total amount of data in this state */
269205231Skmacy	list_t	arcs_lists[ARC_BUFC_NUMLISTS]; /* list of evictable buffers */
270205264Skmacy	struct arcs_lock arcs_locks[ARC_BUFC_NUMLISTS] __aligned(CACHE_LINE_SIZE);
271168404Spjd} arc_state_t;
272168404Spjd
273206796Spjd#define ARCS_LOCK(s, i)	(&((s)->arcs_locks[(i)].arcs_lock))
274205231Skmacy
275185029Spjd/* The 6 states: */
276168404Spjdstatic arc_state_t ARC_anon;
277168404Spjdstatic arc_state_t ARC_mru;
278168404Spjdstatic arc_state_t ARC_mru_ghost;
279168404Spjdstatic arc_state_t ARC_mfu;
280168404Spjdstatic arc_state_t ARC_mfu_ghost;
281185029Spjdstatic arc_state_t ARC_l2c_only;
282168404Spjd
283168404Spjdtypedef struct arc_stats {
284168404Spjd	kstat_named_t arcstat_hits;
285168404Spjd	kstat_named_t arcstat_misses;
286168404Spjd	kstat_named_t arcstat_demand_data_hits;
287168404Spjd	kstat_named_t arcstat_demand_data_misses;
288168404Spjd	kstat_named_t arcstat_demand_metadata_hits;
289168404Spjd	kstat_named_t arcstat_demand_metadata_misses;
290168404Spjd	kstat_named_t arcstat_prefetch_data_hits;
291168404Spjd	kstat_named_t arcstat_prefetch_data_misses;
292168404Spjd	kstat_named_t arcstat_prefetch_metadata_hits;
293168404Spjd	kstat_named_t arcstat_prefetch_metadata_misses;
294168404Spjd	kstat_named_t arcstat_mru_hits;
295168404Spjd	kstat_named_t arcstat_mru_ghost_hits;
296168404Spjd	kstat_named_t arcstat_mfu_hits;
297168404Spjd	kstat_named_t arcstat_mfu_ghost_hits;
298205231Skmacy	kstat_named_t arcstat_allocated;
299168404Spjd	kstat_named_t arcstat_deleted;
300205231Skmacy	kstat_named_t arcstat_stolen;
301168404Spjd	kstat_named_t arcstat_recycle_miss;
302251629Sdelphij	/*
303251629Sdelphij	 * Number of buffers that could not be evicted because the hash lock
304251629Sdelphij	 * was held by another thread.  The lock may not necessarily be held
305251629Sdelphij	 * by something using the same buffer, since hash locks are shared
306251629Sdelphij	 * by multiple buffers.
307251629Sdelphij	 */
308168404Spjd	kstat_named_t arcstat_mutex_miss;
309251629Sdelphij	/*
310251629Sdelphij	 * Number of buffers skipped because they have I/O in progress, are
311251629Sdelphij	 * indrect prefetch buffers that have not lived long enough, or are
312251629Sdelphij	 * not from the spa we're trying to evict from.
313251629Sdelphij	 */
314168404Spjd	kstat_named_t arcstat_evict_skip;
315208373Smm	kstat_named_t arcstat_evict_l2_cached;
316208373Smm	kstat_named_t arcstat_evict_l2_eligible;
317208373Smm	kstat_named_t arcstat_evict_l2_ineligible;
318168404Spjd	kstat_named_t arcstat_hash_elements;
319168404Spjd	kstat_named_t arcstat_hash_elements_max;
320168404Spjd	kstat_named_t arcstat_hash_collisions;
321168404Spjd	kstat_named_t arcstat_hash_chains;
322168404Spjd	kstat_named_t arcstat_hash_chain_max;
323168404Spjd	kstat_named_t arcstat_p;
324168404Spjd	kstat_named_t arcstat_c;
325168404Spjd	kstat_named_t arcstat_c_min;
326168404Spjd	kstat_named_t arcstat_c_max;
327168404Spjd	kstat_named_t arcstat_size;
328185029Spjd	kstat_named_t arcstat_hdr_size;
329208373Smm	kstat_named_t arcstat_data_size;
330208373Smm	kstat_named_t arcstat_other_size;
331185029Spjd	kstat_named_t arcstat_l2_hits;
332185029Spjd	kstat_named_t arcstat_l2_misses;
333185029Spjd	kstat_named_t arcstat_l2_feeds;
334185029Spjd	kstat_named_t arcstat_l2_rw_clash;
335208373Smm	kstat_named_t arcstat_l2_read_bytes;
336208373Smm	kstat_named_t arcstat_l2_write_bytes;
337185029Spjd	kstat_named_t arcstat_l2_writes_sent;
338185029Spjd	kstat_named_t arcstat_l2_writes_done;
339185029Spjd	kstat_named_t arcstat_l2_writes_error;
340185029Spjd	kstat_named_t arcstat_l2_writes_hdr_miss;
341185029Spjd	kstat_named_t arcstat_l2_evict_lock_retry;
342185029Spjd	kstat_named_t arcstat_l2_evict_reading;
343185029Spjd	kstat_named_t arcstat_l2_free_on_write;
344185029Spjd	kstat_named_t arcstat_l2_abort_lowmem;
345185029Spjd	kstat_named_t arcstat_l2_cksum_bad;
346185029Spjd	kstat_named_t arcstat_l2_io_error;
347185029Spjd	kstat_named_t arcstat_l2_size;
348251478Sdelphij	kstat_named_t arcstat_l2_asize;
349185029Spjd	kstat_named_t arcstat_l2_hdr_size;
350251478Sdelphij	kstat_named_t arcstat_l2_compress_successes;
351251478Sdelphij	kstat_named_t arcstat_l2_compress_zeros;
352251478Sdelphij	kstat_named_t arcstat_l2_compress_failures;
353205231Skmacy	kstat_named_t arcstat_l2_write_trylock_fail;
354205231Skmacy	kstat_named_t arcstat_l2_write_passed_headroom;
355205231Skmacy	kstat_named_t arcstat_l2_write_spa_mismatch;
356206796Spjd	kstat_named_t arcstat_l2_write_in_l2;
357205231Skmacy	kstat_named_t arcstat_l2_write_hdr_io_in_progress;
358205231Skmacy	kstat_named_t arcstat_l2_write_not_cacheable;
359205231Skmacy	kstat_named_t arcstat_l2_write_full;
360205231Skmacy	kstat_named_t arcstat_l2_write_buffer_iter;
361205231Skmacy	kstat_named_t arcstat_l2_write_pios;
362205231Skmacy	kstat_named_t arcstat_l2_write_buffer_bytes_scanned;
363205231Skmacy	kstat_named_t arcstat_l2_write_buffer_list_iter;
364205231Skmacy	kstat_named_t arcstat_l2_write_buffer_list_null_iter;
365242845Sdelphij	kstat_named_t arcstat_memory_throttle_count;
366242845Sdelphij	kstat_named_t arcstat_duplicate_buffers;
367242845Sdelphij	kstat_named_t arcstat_duplicate_buffers_size;
368242845Sdelphij	kstat_named_t arcstat_duplicate_reads;
369168404Spjd} arc_stats_t;
370168404Spjd
371168404Spjdstatic arc_stats_t arc_stats = {
372168404Spjd	{ "hits",			KSTAT_DATA_UINT64 },
373168404Spjd	{ "misses",			KSTAT_DATA_UINT64 },
374168404Spjd	{ "demand_data_hits",		KSTAT_DATA_UINT64 },
375168404Spjd	{ "demand_data_misses",		KSTAT_DATA_UINT64 },
376168404Spjd	{ "demand_metadata_hits",	KSTAT_DATA_UINT64 },
377168404Spjd	{ "demand_metadata_misses",	KSTAT_DATA_UINT64 },
378168404Spjd	{ "prefetch_data_hits",		KSTAT_DATA_UINT64 },
379168404Spjd	{ "prefetch_data_misses",	KSTAT_DATA_UINT64 },
380168404Spjd	{ "prefetch_metadata_hits",	KSTAT_DATA_UINT64 },
381168404Spjd	{ "prefetch_metadata_misses",	KSTAT_DATA_UINT64 },
382168404Spjd	{ "mru_hits",			KSTAT_DATA_UINT64 },
383168404Spjd	{ "mru_ghost_hits",		KSTAT_DATA_UINT64 },
384168404Spjd	{ "mfu_hits",			KSTAT_DATA_UINT64 },
385168404Spjd	{ "mfu_ghost_hits",		KSTAT_DATA_UINT64 },
386205231Skmacy	{ "allocated",			KSTAT_DATA_UINT64 },
387168404Spjd	{ "deleted",			KSTAT_DATA_UINT64 },
388205231Skmacy	{ "stolen",			KSTAT_DATA_UINT64 },
389168404Spjd	{ "recycle_miss",		KSTAT_DATA_UINT64 },
390168404Spjd	{ "mutex_miss",			KSTAT_DATA_UINT64 },
391168404Spjd	{ "evict_skip",			KSTAT_DATA_UINT64 },
392208373Smm	{ "evict_l2_cached",		KSTAT_DATA_UINT64 },
393208373Smm	{ "evict_l2_eligible",		KSTAT_DATA_UINT64 },
394208373Smm	{ "evict_l2_ineligible",	KSTAT_DATA_UINT64 },
395168404Spjd	{ "hash_elements",		KSTAT_DATA_UINT64 },
396168404Spjd	{ "hash_elements_max",		KSTAT_DATA_UINT64 },
397168404Spjd	{ "hash_collisions",		KSTAT_DATA_UINT64 },
398168404Spjd	{ "hash_chains",		KSTAT_DATA_UINT64 },
399168404Spjd	{ "hash_chain_max",		KSTAT_DATA_UINT64 },
400168404Spjd	{ "p",				KSTAT_DATA_UINT64 },
401168404Spjd	{ "c",				KSTAT_DATA_UINT64 },
402168404Spjd	{ "c_min",			KSTAT_DATA_UINT64 },
403168404Spjd	{ "c_max",			KSTAT_DATA_UINT64 },
404185029Spjd	{ "size",			KSTAT_DATA_UINT64 },
405185029Spjd	{ "hdr_size",			KSTAT_DATA_UINT64 },
406208373Smm	{ "data_size",			KSTAT_DATA_UINT64 },
407208373Smm	{ "other_size",			KSTAT_DATA_UINT64 },
408185029Spjd	{ "l2_hits",			KSTAT_DATA_UINT64 },
409185029Spjd	{ "l2_misses",			KSTAT_DATA_UINT64 },
410185029Spjd	{ "l2_feeds",			KSTAT_DATA_UINT64 },
411185029Spjd	{ "l2_rw_clash",		KSTAT_DATA_UINT64 },
412208373Smm	{ "l2_read_bytes",		KSTAT_DATA_UINT64 },
413208373Smm	{ "l2_write_bytes",		KSTAT_DATA_UINT64 },
414185029Spjd	{ "l2_writes_sent",		KSTAT_DATA_UINT64 },
415185029Spjd	{ "l2_writes_done",		KSTAT_DATA_UINT64 },
416185029Spjd	{ "l2_writes_error",		KSTAT_DATA_UINT64 },
417185029Spjd	{ "l2_writes_hdr_miss",		KSTAT_DATA_UINT64 },
418185029Spjd	{ "l2_evict_lock_retry",	KSTAT_DATA_UINT64 },
419185029Spjd	{ "l2_evict_reading",		KSTAT_DATA_UINT64 },
420185029Spjd	{ "l2_free_on_write",		KSTAT_DATA_UINT64 },
421185029Spjd	{ "l2_abort_lowmem",		KSTAT_DATA_UINT64 },
422185029Spjd	{ "l2_cksum_bad",		KSTAT_DATA_UINT64 },
423185029Spjd	{ "l2_io_error",		KSTAT_DATA_UINT64 },
424185029Spjd	{ "l2_size",			KSTAT_DATA_UINT64 },
425251478Sdelphij	{ "l2_asize",			KSTAT_DATA_UINT64 },
426185029Spjd	{ "l2_hdr_size",		KSTAT_DATA_UINT64 },
427251478Sdelphij	{ "l2_compress_successes",	KSTAT_DATA_UINT64 },
428251478Sdelphij	{ "l2_compress_zeros",		KSTAT_DATA_UINT64 },
429251478Sdelphij	{ "l2_compress_failures",	KSTAT_DATA_UINT64 },
430206796Spjd	{ "l2_write_trylock_fail",	KSTAT_DATA_UINT64 },
431206796Spjd	{ "l2_write_passed_headroom",	KSTAT_DATA_UINT64 },
432206796Spjd	{ "l2_write_spa_mismatch",	KSTAT_DATA_UINT64 },
433206796Spjd	{ "l2_write_in_l2",		KSTAT_DATA_UINT64 },
434206796Spjd	{ "l2_write_io_in_progress",	KSTAT_DATA_UINT64 },
435206796Spjd	{ "l2_write_not_cacheable",	KSTAT_DATA_UINT64 },
436206796Spjd	{ "l2_write_full",		KSTAT_DATA_UINT64 },
437206796Spjd	{ "l2_write_buffer_iter",	KSTAT_DATA_UINT64 },
438206796Spjd	{ "l2_write_pios",		KSTAT_DATA_UINT64 },
439206796Spjd	{ "l2_write_buffer_bytes_scanned", KSTAT_DATA_UINT64 },
440206796Spjd	{ "l2_write_buffer_list_iter",	KSTAT_DATA_UINT64 },
441242845Sdelphij	{ "l2_write_buffer_list_null_iter", KSTAT_DATA_UINT64 },
442242845Sdelphij	{ "memory_throttle_count",	KSTAT_DATA_UINT64 },
443242845Sdelphij	{ "duplicate_buffers",		KSTAT_DATA_UINT64 },
444242845Sdelphij	{ "duplicate_buffers_size",	KSTAT_DATA_UINT64 },
445242845Sdelphij	{ "duplicate_reads",		KSTAT_DATA_UINT64 }
446168404Spjd};
447168404Spjd
448168404Spjd#define	ARCSTAT(stat)	(arc_stats.stat.value.ui64)
449168404Spjd
450168404Spjd#define	ARCSTAT_INCR(stat, val) \
451251631Sdelphij	atomic_add_64(&arc_stats.stat.value.ui64, (val))
452168404Spjd
453206796Spjd#define	ARCSTAT_BUMP(stat)	ARCSTAT_INCR(stat, 1)
454168404Spjd#define	ARCSTAT_BUMPDOWN(stat)	ARCSTAT_INCR(stat, -1)
455168404Spjd
456168404Spjd#define	ARCSTAT_MAX(stat, val) {					\
457168404Spjd	uint64_t m;							\
458168404Spjd	while ((val) > (m = arc_stats.stat.value.ui64) &&		\
459168404Spjd	    (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val))))	\
460168404Spjd		continue;						\
461168404Spjd}
462168404Spjd
463168404Spjd#define	ARCSTAT_MAXSTAT(stat) \
464168404Spjd	ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
465168404Spjd
466168404Spjd/*
467168404Spjd * We define a macro to allow ARC hits/misses to be easily broken down by
468168404Spjd * two separate conditions, giving a total of four different subtypes for
469168404Spjd * each of hits and misses (so eight statistics total).
470168404Spjd */
471168404Spjd#define	ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
472168404Spjd	if (cond1) {							\
473168404Spjd		if (cond2) {						\
474168404Spjd			ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
475168404Spjd		} else {						\
476168404Spjd			ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
477168404Spjd		}							\
478168404Spjd	} else {							\
479168404Spjd		if (cond2) {						\
480168404Spjd			ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
481168404Spjd		} else {						\
482168404Spjd			ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
483168404Spjd		}							\
484168404Spjd	}
485168404Spjd
486168404Spjdkstat_t			*arc_ksp;
487206796Spjdstatic arc_state_t	*arc_anon;
488168404Spjdstatic arc_state_t	*arc_mru;
489168404Spjdstatic arc_state_t	*arc_mru_ghost;
490168404Spjdstatic arc_state_t	*arc_mfu;
491168404Spjdstatic arc_state_t	*arc_mfu_ghost;
492185029Spjdstatic arc_state_t	*arc_l2c_only;
493168404Spjd
494168404Spjd/*
495168404Spjd * There are several ARC variables that are critical to export as kstats --
496168404Spjd * but we don't want to have to grovel around in the kstat whenever we wish to
497168404Spjd * manipulate them.  For these variables, we therefore define them to be in
498168404Spjd * terms of the statistic variable.  This assures that we are not introducing
499168404Spjd * the possibility of inconsistency by having shadow copies of the variables,
500168404Spjd * while still allowing the code to be readable.
501168404Spjd */
502168404Spjd#define	arc_size	ARCSTAT(arcstat_size)	/* actual total arc size */
503168404Spjd#define	arc_p		ARCSTAT(arcstat_p)	/* target size of MRU */
504168404Spjd#define	arc_c		ARCSTAT(arcstat_c)	/* target size of cache */
505168404Spjd#define	arc_c_min	ARCSTAT(arcstat_c_min)	/* min target cache size */
506168404Spjd#define	arc_c_max	ARCSTAT(arcstat_c_max)	/* max target cache size */
507168404Spjd
508251478Sdelphij#define	L2ARC_IS_VALID_COMPRESS(_c_) \
509251478Sdelphij	((_c_) == ZIO_COMPRESS_LZ4 || (_c_) == ZIO_COMPRESS_EMPTY)
510251478Sdelphij
511168404Spjdstatic int		arc_no_grow;	/* Don't try to grow cache size */
512168404Spjdstatic uint64_t		arc_tempreserve;
513209962Smmstatic uint64_t		arc_loaned_bytes;
514185029Spjdstatic uint64_t		arc_meta_used;
515185029Spjdstatic uint64_t		arc_meta_limit;
516185029Spjdstatic uint64_t		arc_meta_max = 0;
517229663SpjdSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_meta_used, CTLFLAG_RD, &arc_meta_used, 0,
518229663Spjd    "ARC metadata used");
519229663SpjdSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_meta_limit, CTLFLAG_RW, &arc_meta_limit, 0,
520229663Spjd    "ARC metadata limit");
521168404Spjd
522185029Spjdtypedef struct l2arc_buf_hdr l2arc_buf_hdr_t;
523185029Spjd
524168404Spjdtypedef struct arc_callback arc_callback_t;
525168404Spjd
526168404Spjdstruct arc_callback {
527168404Spjd	void			*acb_private;
528168404Spjd	arc_done_func_t		*acb_done;
529168404Spjd	arc_buf_t		*acb_buf;
530168404Spjd	zio_t			*acb_zio_dummy;
531168404Spjd	arc_callback_t		*acb_next;
532168404Spjd};
533168404Spjd
534168404Spjdtypedef struct arc_write_callback arc_write_callback_t;
535168404Spjd
536168404Spjdstruct arc_write_callback {
537168404Spjd	void		*awcb_private;
538168404Spjd	arc_done_func_t	*awcb_ready;
539258632Savg	arc_done_func_t	*awcb_physdone;
540168404Spjd	arc_done_func_t	*awcb_done;
541168404Spjd	arc_buf_t	*awcb_buf;
542168404Spjd};
543168404Spjd
544168404Spjdstruct arc_buf_hdr {
545168404Spjd	/* protected by hash lock */
546168404Spjd	dva_t			b_dva;
547168404Spjd	uint64_t		b_birth;
548168404Spjd	uint64_t		b_cksum0;
549168404Spjd
550168404Spjd	kmutex_t		b_freeze_lock;
551168404Spjd	zio_cksum_t		*b_freeze_cksum;
552219089Spjd	void			*b_thawed;
553168404Spjd
554168404Spjd	arc_buf_hdr_t		*b_hash_next;
555168404Spjd	arc_buf_t		*b_buf;
556168404Spjd	uint32_t		b_flags;
557168404Spjd	uint32_t		b_datacnt;
558168404Spjd
559168404Spjd	arc_callback_t		*b_acb;
560168404Spjd	kcondvar_t		b_cv;
561168404Spjd
562168404Spjd	/* immutable */
563168404Spjd	arc_buf_contents_t	b_type;
564168404Spjd	uint64_t		b_size;
565209962Smm	uint64_t		b_spa;
566168404Spjd
567168404Spjd	/* protected by arc state mutex */
568168404Spjd	arc_state_t		*b_state;
569168404Spjd	list_node_t		b_arc_node;
570168404Spjd
571168404Spjd	/* updated atomically */
572168404Spjd	clock_t			b_arc_access;
573168404Spjd
574168404Spjd	/* self protecting */
575168404Spjd	refcount_t		b_refcnt;
576185029Spjd
577185029Spjd	l2arc_buf_hdr_t		*b_l2hdr;
578185029Spjd	list_node_t		b_l2node;
579168404Spjd};
580168404Spjd
581168404Spjdstatic arc_buf_t *arc_eviction_list;
582168404Spjdstatic kmutex_t arc_eviction_mtx;
583168404Spjdstatic arc_buf_hdr_t arc_eviction_hdr;
584168404Spjdstatic void arc_get_data_buf(arc_buf_t *buf);
585168404Spjdstatic void arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock);
586185029Spjdstatic int arc_evict_needed(arc_buf_contents_t type);
587209962Smmstatic void arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes);
588240133Smm#ifdef illumos
589240133Smmstatic void arc_buf_watch(arc_buf_t *buf);
590240133Smm#endif /* illumos */
591168404Spjd
592209962Smmstatic boolean_t l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *ab);
593208373Smm
594168404Spjd#define	GHOST_STATE(state)	\
595185029Spjd	((state) == arc_mru_ghost || (state) == arc_mfu_ghost ||	\
596185029Spjd	(state) == arc_l2c_only)
597168404Spjd
598168404Spjd/*
599168404Spjd * Private ARC flags.  These flags are private ARC only flags that will show up
600168404Spjd * in b_flags in the arc_hdr_buf_t.  Some flags are publicly declared, and can
601168404Spjd * be passed in as arc_flags in things like arc_read.  However, these flags
602168404Spjd * should never be passed and should only be set by ARC code.  When adding new
603168404Spjd * public flags, make sure not to smash the private ones.
604168404Spjd */
605168404Spjd
606168404Spjd#define	ARC_IN_HASH_TABLE	(1 << 9)	/* this buffer is hashed */
607168404Spjd#define	ARC_IO_IN_PROGRESS	(1 << 10)	/* I/O in progress for buf */
608168404Spjd#define	ARC_IO_ERROR		(1 << 11)	/* I/O failed for buf */
609168404Spjd#define	ARC_FREED_IN_READ	(1 << 12)	/* buf freed while in read */
610168404Spjd#define	ARC_BUF_AVAILABLE	(1 << 13)	/* block not in active use */
611168404Spjd#define	ARC_INDIRECT		(1 << 14)	/* this is an indirect block */
612185029Spjd#define	ARC_FREE_IN_PROGRESS	(1 << 15)	/* hdr about to be freed */
613185029Spjd#define	ARC_L2_WRITING		(1 << 16)	/* L2ARC write in progress */
614185029Spjd#define	ARC_L2_EVICTED		(1 << 17)	/* evicted during I/O */
615185029Spjd#define	ARC_L2_WRITE_HEAD	(1 << 18)	/* head of write list */
616168404Spjd
617168404Spjd#define	HDR_IN_HASH_TABLE(hdr)	((hdr)->b_flags & ARC_IN_HASH_TABLE)
618168404Spjd#define	HDR_IO_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_IO_IN_PROGRESS)
619168404Spjd#define	HDR_IO_ERROR(hdr)	((hdr)->b_flags & ARC_IO_ERROR)
620208373Smm#define	HDR_PREFETCH(hdr)	((hdr)->b_flags & ARC_PREFETCH)
621168404Spjd#define	HDR_FREED_IN_READ(hdr)	((hdr)->b_flags & ARC_FREED_IN_READ)
622168404Spjd#define	HDR_BUF_AVAILABLE(hdr)	((hdr)->b_flags & ARC_BUF_AVAILABLE)
623185029Spjd#define	HDR_FREE_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_FREE_IN_PROGRESS)
624185029Spjd#define	HDR_L2CACHE(hdr)	((hdr)->b_flags & ARC_L2CACHE)
625185029Spjd#define	HDR_L2_READING(hdr)	((hdr)->b_flags & ARC_IO_IN_PROGRESS &&	\
626185029Spjd				    (hdr)->b_l2hdr != NULL)
627185029Spjd#define	HDR_L2_WRITING(hdr)	((hdr)->b_flags & ARC_L2_WRITING)
628185029Spjd#define	HDR_L2_EVICTED(hdr)	((hdr)->b_flags & ARC_L2_EVICTED)
629185029Spjd#define	HDR_L2_WRITE_HEAD(hdr)	((hdr)->b_flags & ARC_L2_WRITE_HEAD)
630168404Spjd
631168404Spjd/*
632185029Spjd * Other sizes
633185029Spjd */
634185029Spjd
635185029Spjd#define	HDR_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
636185029Spjd#define	L2HDR_SIZE ((int64_t)sizeof (l2arc_buf_hdr_t))
637185029Spjd
638185029Spjd/*
639168404Spjd * Hash table routines
640168404Spjd */
641168404Spjd
642205253Skmacy#define	HT_LOCK_PAD	CACHE_LINE_SIZE
643168404Spjd
644168404Spjdstruct ht_lock {
645168404Spjd	kmutex_t	ht_lock;
646168404Spjd#ifdef _KERNEL
647168404Spjd	unsigned char	pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
648168404Spjd#endif
649168404Spjd};
650168404Spjd
651168404Spjd#define	BUF_LOCKS 256
652168404Spjdtypedef struct buf_hash_table {
653168404Spjd	uint64_t ht_mask;
654168404Spjd	arc_buf_hdr_t **ht_table;
655205264Skmacy	struct ht_lock ht_locks[BUF_LOCKS] __aligned(CACHE_LINE_SIZE);
656168404Spjd} buf_hash_table_t;
657168404Spjd
658168404Spjdstatic buf_hash_table_t buf_hash_table;
659168404Spjd
660168404Spjd#define	BUF_HASH_INDEX(spa, dva, birth) \
661168404Spjd	(buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
662168404Spjd#define	BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
663168404Spjd#define	BUF_HASH_LOCK(idx)	(&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
664219089Spjd#define	HDR_LOCK(hdr) \
665219089Spjd	(BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
666168404Spjd
667168404Spjduint64_t zfs_crc64_table[256];
668168404Spjd
669185029Spjd/*
670185029Spjd * Level 2 ARC
671185029Spjd */
672185029Spjd
673208373Smm#define	L2ARC_WRITE_SIZE	(8 * 1024 * 1024)	/* initial write max */
674251478Sdelphij#define	L2ARC_HEADROOM		2			/* num of writes */
675251478Sdelphij/*
676251478Sdelphij * If we discover during ARC scan any buffers to be compressed, we boost
677251478Sdelphij * our headroom for the next scanning cycle by this percentage multiple.
678251478Sdelphij */
679251478Sdelphij#define	L2ARC_HEADROOM_BOOST	200
680208373Smm#define	L2ARC_FEED_SECS		1		/* caching interval secs */
681208373Smm#define	L2ARC_FEED_MIN_MS	200		/* min caching interval ms */
682185029Spjd
683185029Spjd#define	l2arc_writes_sent	ARCSTAT(arcstat_l2_writes_sent)
684185029Spjd#define	l2arc_writes_done	ARCSTAT(arcstat_l2_writes_done)
685185029Spjd
686251631Sdelphij/* L2ARC Performance Tunables */
687185029Spjduint64_t l2arc_write_max = L2ARC_WRITE_SIZE;	/* default max write size */
688185029Spjduint64_t l2arc_write_boost = L2ARC_WRITE_SIZE;	/* extra write during warmup */
689185029Spjduint64_t l2arc_headroom = L2ARC_HEADROOM;	/* number of dev writes */
690251478Sdelphijuint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
691185029Spjduint64_t l2arc_feed_secs = L2ARC_FEED_SECS;	/* interval seconds */
692208373Smmuint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS;	/* min interval milliseconds */
693219089Spjdboolean_t l2arc_noprefetch = B_TRUE;		/* don't cache prefetch bufs */
694208373Smmboolean_t l2arc_feed_again = B_TRUE;		/* turbo warmup */
695208373Smmboolean_t l2arc_norw = B_TRUE;			/* no reads during writes */
696185029Spjd
697217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RW,
698205231Skmacy    &l2arc_write_max, 0, "max write size");
699217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RW,
700205231Skmacy    &l2arc_write_boost, 0, "extra write during warmup");
701217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RW,
702205231Skmacy    &l2arc_headroom, 0, "number of dev writes");
703217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RW,
704205231Skmacy    &l2arc_feed_secs, 0, "interval seconds");
705217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RW,
706208373Smm    &l2arc_feed_min_ms, 0, "min interval milliseconds");
707205231Skmacy
708205231SkmacySYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RW,
709205231Skmacy    &l2arc_noprefetch, 0, "don't cache prefetch bufs");
710208373SmmSYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RW,
711208373Smm    &l2arc_feed_again, 0, "turbo warmup");
712208373SmmSYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RW,
713208373Smm    &l2arc_norw, 0, "no reads during writes");
714205231Skmacy
715217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
716205231Skmacy    &ARC_anon.arcs_size, 0, "size of anonymous state");
717217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_metadata_lsize, CTLFLAG_RD,
718205231Skmacy    &ARC_anon.arcs_lsize[ARC_BUFC_METADATA], 0, "size of anonymous state");
719217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_data_lsize, CTLFLAG_RD,
720205231Skmacy    &ARC_anon.arcs_lsize[ARC_BUFC_DATA], 0, "size of anonymous state");
721205231Skmacy
722217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
723205231Skmacy    &ARC_mru.arcs_size, 0, "size of mru state");
724217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_metadata_lsize, CTLFLAG_RD,
725205231Skmacy    &ARC_mru.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mru state");
726217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_data_lsize, CTLFLAG_RD,
727205231Skmacy    &ARC_mru.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mru state");
728205231Skmacy
729217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
730205231Skmacy    &ARC_mru_ghost.arcs_size, 0, "size of mru ghost state");
731217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_lsize, CTLFLAG_RD,
732205231Skmacy    &ARC_mru_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
733205231Skmacy    "size of metadata in mru ghost state");
734217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_lsize, CTLFLAG_RD,
735205231Skmacy    &ARC_mru_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
736205231Skmacy    "size of data in mru ghost state");
737205231Skmacy
738217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
739205231Skmacy    &ARC_mfu.arcs_size, 0, "size of mfu state");
740217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_metadata_lsize, CTLFLAG_RD,
741205231Skmacy    &ARC_mfu.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mfu state");
742217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_data_lsize, CTLFLAG_RD,
743205231Skmacy    &ARC_mfu.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mfu state");
744205231Skmacy
745217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
746205231Skmacy    &ARC_mfu_ghost.arcs_size, 0, "size of mfu ghost state");
747217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_lsize, CTLFLAG_RD,
748205231Skmacy    &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
749205231Skmacy    "size of metadata in mfu ghost state");
750217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_lsize, CTLFLAG_RD,
751205231Skmacy    &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
752205231Skmacy    "size of data in mfu ghost state");
753205231Skmacy
754217367SmdfSYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
755205231Skmacy    &ARC_l2c_only.arcs_size, 0, "size of mru state");
756205231Skmacy
757185029Spjd/*
758185029Spjd * L2ARC Internals
759185029Spjd */
760185029Spjdtypedef struct l2arc_dev {
761185029Spjd	vdev_t			*l2ad_vdev;	/* vdev */
762185029Spjd	spa_t			*l2ad_spa;	/* spa */
763185029Spjd	uint64_t		l2ad_hand;	/* next write location */
764185029Spjd	uint64_t		l2ad_start;	/* first addr on device */
765185029Spjd	uint64_t		l2ad_end;	/* last addr on device */
766185029Spjd	uint64_t		l2ad_evict;	/* last addr eviction reached */
767185029Spjd	boolean_t		l2ad_first;	/* first sweep through */
768208373Smm	boolean_t		l2ad_writing;	/* currently writing */
769185029Spjd	list_t			*l2ad_buflist;	/* buffer list */
770185029Spjd	list_node_t		l2ad_node;	/* device list node */
771185029Spjd} l2arc_dev_t;
772185029Spjd
773185029Spjdstatic list_t L2ARC_dev_list;			/* device list */
774185029Spjdstatic list_t *l2arc_dev_list;			/* device list pointer */
775185029Spjdstatic kmutex_t l2arc_dev_mtx;			/* device list mutex */
776185029Spjdstatic l2arc_dev_t *l2arc_dev_last;		/* last device used */
777185029Spjdstatic kmutex_t l2arc_buflist_mtx;		/* mutex for all buflists */
778185029Spjdstatic list_t L2ARC_free_on_write;		/* free after write buf list */
779185029Spjdstatic list_t *l2arc_free_on_write;		/* free after write list ptr */
780185029Spjdstatic kmutex_t l2arc_free_on_write_mtx;	/* mutex for list */
781185029Spjdstatic uint64_t l2arc_ndev;			/* number of devices */
782185029Spjd
783185029Spjdtypedef struct l2arc_read_callback {
784251478Sdelphij	arc_buf_t		*l2rcb_buf;		/* read buffer */
785251478Sdelphij	spa_t			*l2rcb_spa;		/* spa */
786251478Sdelphij	blkptr_t		l2rcb_bp;		/* original blkptr */
787268123Sdelphij	zbookmark_phys_t	l2rcb_zb;		/* original bookmark */
788251478Sdelphij	int			l2rcb_flags;		/* original flags */
789251478Sdelphij	enum zio_compress	l2rcb_compress;		/* applied compress */
790185029Spjd} l2arc_read_callback_t;
791185029Spjd
792185029Spjdtypedef struct l2arc_write_callback {
793185029Spjd	l2arc_dev_t	*l2wcb_dev;		/* device info */
794185029Spjd	arc_buf_hdr_t	*l2wcb_head;		/* head of write buflist */
795185029Spjd} l2arc_write_callback_t;
796185029Spjd
797185029Spjdstruct l2arc_buf_hdr {
798185029Spjd	/* protected by arc_buf_hdr  mutex */
799251478Sdelphij	l2arc_dev_t		*b_dev;		/* L2ARC device */
800251478Sdelphij	uint64_t		b_daddr;	/* disk address, offset byte */
801251478Sdelphij	/* compression applied to buffer data */
802251478Sdelphij	enum zio_compress	b_compress;
803251478Sdelphij	/* real alloc'd buffer size depending on b_compress applied */
804251478Sdelphij	int			b_asize;
805251478Sdelphij	/* temporary buffer holder for in-flight compressed data */
806251478Sdelphij	void			*b_tmp_cdata;
807185029Spjd};
808185029Spjd
809185029Spjdtypedef struct l2arc_data_free {
810185029Spjd	/* protected by l2arc_free_on_write_mtx */
811185029Spjd	void		*l2df_data;
812185029Spjd	size_t		l2df_size;
813185029Spjd	void		(*l2df_func)(void *, size_t);
814185029Spjd	list_node_t	l2df_list_node;
815185029Spjd} l2arc_data_free_t;
816185029Spjd
817185029Spjdstatic kmutex_t l2arc_feed_thr_lock;
818185029Spjdstatic kcondvar_t l2arc_feed_thr_cv;
819185029Spjdstatic uint8_t l2arc_thread_exit;
820185029Spjd
821185029Spjdstatic void l2arc_read_done(zio_t *zio);
822185029Spjdstatic void l2arc_hdr_stat_add(void);
823185029Spjdstatic void l2arc_hdr_stat_remove(void);
824185029Spjd
825251478Sdelphijstatic boolean_t l2arc_compress_buf(l2arc_buf_hdr_t *l2hdr);
826251478Sdelphijstatic void l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr,
827251478Sdelphij    enum zio_compress c);
828251478Sdelphijstatic void l2arc_release_cdata_buf(arc_buf_hdr_t *ab);
829251478Sdelphij
830168404Spjdstatic uint64_t
831209962Smmbuf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
832168404Spjd{
833168404Spjd	uint8_t *vdva = (uint8_t *)dva;
834168404Spjd	uint64_t crc = -1ULL;
835168404Spjd	int i;
836168404Spjd
837168404Spjd	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
838168404Spjd
839168404Spjd	for (i = 0; i < sizeof (dva_t); i++)
840168404Spjd		crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
841168404Spjd
842209962Smm	crc ^= (spa>>8) ^ birth;
843168404Spjd
844168404Spjd	return (crc);
845168404Spjd}
846168404Spjd
847168404Spjd#define	BUF_EMPTY(buf)						\
848168404Spjd	((buf)->b_dva.dva_word[0] == 0 &&			\
849168404Spjd	(buf)->b_dva.dva_word[1] == 0 &&			\
850260150Sdelphij	(buf)->b_cksum0 == 0)
851168404Spjd
852168404Spjd#define	BUF_EQUAL(spa, dva, birth, buf)				\
853168404Spjd	((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) &&	\
854168404Spjd	((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) &&	\
855168404Spjd	((buf)->b_birth == birth) && ((buf)->b_spa == spa)
856168404Spjd
857219089Spjdstatic void
858219089Spjdbuf_discard_identity(arc_buf_hdr_t *hdr)
859219089Spjd{
860219089Spjd	hdr->b_dva.dva_word[0] = 0;
861219089Spjd	hdr->b_dva.dva_word[1] = 0;
862219089Spjd	hdr->b_birth = 0;
863219089Spjd	hdr->b_cksum0 = 0;
864219089Spjd}
865219089Spjd
866168404Spjdstatic arc_buf_hdr_t *
867268075Sdelphijbuf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
868168404Spjd{
869268075Sdelphij	const dva_t *dva = BP_IDENTITY(bp);
870268075Sdelphij	uint64_t birth = BP_PHYSICAL_BIRTH(bp);
871168404Spjd	uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
872168404Spjd	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
873168404Spjd	arc_buf_hdr_t *buf;
874168404Spjd
875168404Spjd	mutex_enter(hash_lock);
876168404Spjd	for (buf = buf_hash_table.ht_table[idx]; buf != NULL;
877168404Spjd	    buf = buf->b_hash_next) {
878168404Spjd		if (BUF_EQUAL(spa, dva, birth, buf)) {
879168404Spjd			*lockp = hash_lock;
880168404Spjd			return (buf);
881168404Spjd		}
882168404Spjd	}
883168404Spjd	mutex_exit(hash_lock);
884168404Spjd	*lockp = NULL;
885168404Spjd	return (NULL);
886168404Spjd}
887168404Spjd
888168404Spjd/*
889168404Spjd * Insert an entry into the hash table.  If there is already an element
890168404Spjd * equal to elem in the hash table, then the already existing element
891168404Spjd * will be returned and the new element will not be inserted.
892168404Spjd * Otherwise returns NULL.
893168404Spjd */
894168404Spjdstatic arc_buf_hdr_t *
895168404Spjdbuf_hash_insert(arc_buf_hdr_t *buf, kmutex_t **lockp)
896168404Spjd{
897168404Spjd	uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
898168404Spjd	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
899168404Spjd	arc_buf_hdr_t *fbuf;
900168404Spjd	uint32_t i;
901168404Spjd
902268075Sdelphij	ASSERT(!DVA_IS_EMPTY(&buf->b_dva));
903268075Sdelphij	ASSERT(buf->b_birth != 0);
904168404Spjd	ASSERT(!HDR_IN_HASH_TABLE(buf));
905168404Spjd	*lockp = hash_lock;
906168404Spjd	mutex_enter(hash_lock);
907168404Spjd	for (fbuf = buf_hash_table.ht_table[idx], i = 0; fbuf != NULL;
908168404Spjd	    fbuf = fbuf->b_hash_next, i++) {
909168404Spjd		if (BUF_EQUAL(buf->b_spa, &buf->b_dva, buf->b_birth, fbuf))
910168404Spjd			return (fbuf);
911168404Spjd	}
912168404Spjd
913168404Spjd	buf->b_hash_next = buf_hash_table.ht_table[idx];
914168404Spjd	buf_hash_table.ht_table[idx] = buf;
915168404Spjd	buf->b_flags |= ARC_IN_HASH_TABLE;
916168404Spjd
917168404Spjd	/* collect some hash table performance data */
918168404Spjd	if (i > 0) {
919168404Spjd		ARCSTAT_BUMP(arcstat_hash_collisions);
920168404Spjd		if (i == 1)
921168404Spjd			ARCSTAT_BUMP(arcstat_hash_chains);
922168404Spjd
923168404Spjd		ARCSTAT_MAX(arcstat_hash_chain_max, i);
924168404Spjd	}
925168404Spjd
926168404Spjd	ARCSTAT_BUMP(arcstat_hash_elements);
927168404Spjd	ARCSTAT_MAXSTAT(arcstat_hash_elements);
928168404Spjd
929168404Spjd	return (NULL);
930168404Spjd}
931168404Spjd
932168404Spjdstatic void
933168404Spjdbuf_hash_remove(arc_buf_hdr_t *buf)
934168404Spjd{
935168404Spjd	arc_buf_hdr_t *fbuf, **bufp;
936168404Spjd	uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
937168404Spjd
938168404Spjd	ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
939168404Spjd	ASSERT(HDR_IN_HASH_TABLE(buf));
940168404Spjd
941168404Spjd	bufp = &buf_hash_table.ht_table[idx];
942168404Spjd	while ((fbuf = *bufp) != buf) {
943168404Spjd		ASSERT(fbuf != NULL);
944168404Spjd		bufp = &fbuf->b_hash_next;
945168404Spjd	}
946168404Spjd	*bufp = buf->b_hash_next;
947168404Spjd	buf->b_hash_next = NULL;
948168404Spjd	buf->b_flags &= ~ARC_IN_HASH_TABLE;
949168404Spjd
950168404Spjd	/* collect some hash table performance data */
951168404Spjd	ARCSTAT_BUMPDOWN(arcstat_hash_elements);
952168404Spjd
953168404Spjd	if (buf_hash_table.ht_table[idx] &&
954168404Spjd	    buf_hash_table.ht_table[idx]->b_hash_next == NULL)
955168404Spjd		ARCSTAT_BUMPDOWN(arcstat_hash_chains);
956168404Spjd}
957168404Spjd
958168404Spjd/*
959168404Spjd * Global data structures and functions for the buf kmem cache.
960168404Spjd */
961168404Spjdstatic kmem_cache_t *hdr_cache;
962168404Spjdstatic kmem_cache_t *buf_cache;
963168404Spjd
964168404Spjdstatic void
965168404Spjdbuf_fini(void)
966168404Spjd{
967168404Spjd	int i;
968168404Spjd
969168404Spjd	kmem_free(buf_hash_table.ht_table,
970168404Spjd	    (buf_hash_table.ht_mask + 1) * sizeof (void *));
971168404Spjd	for (i = 0; i < BUF_LOCKS; i++)
972168404Spjd		mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
973168404Spjd	kmem_cache_destroy(hdr_cache);
974168404Spjd	kmem_cache_destroy(buf_cache);
975168404Spjd}
976168404Spjd
977168404Spjd/*
978168404Spjd * Constructor callback - called when the cache is empty
979168404Spjd * and a new buf is requested.
980168404Spjd */
981168404Spjd/* ARGSUSED */
982168404Spjdstatic int
983168404Spjdhdr_cons(void *vbuf, void *unused, int kmflag)
984168404Spjd{
985168404Spjd	arc_buf_hdr_t *buf = vbuf;
986168404Spjd
987168404Spjd	bzero(buf, sizeof (arc_buf_hdr_t));
988168404Spjd	refcount_create(&buf->b_refcnt);
989168404Spjd	cv_init(&buf->b_cv, NULL, CV_DEFAULT, NULL);
990185029Spjd	mutex_init(&buf->b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
991208373Smm	arc_space_consume(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
992185029Spjd
993168404Spjd	return (0);
994168404Spjd}
995168404Spjd
996185029Spjd/* ARGSUSED */
997185029Spjdstatic int
998185029Spjdbuf_cons(void *vbuf, void *unused, int kmflag)
999185029Spjd{
1000185029Spjd	arc_buf_t *buf = vbuf;
1001185029Spjd
1002185029Spjd	bzero(buf, sizeof (arc_buf_t));
1003219089Spjd	mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1004208373Smm	arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1005208373Smm
1006185029Spjd	return (0);
1007185029Spjd}
1008185029Spjd
1009168404Spjd/*
1010168404Spjd * Destructor callback - called when a cached buf is
1011168404Spjd * no longer required.
1012168404Spjd */
1013168404Spjd/* ARGSUSED */
1014168404Spjdstatic void
1015168404Spjdhdr_dest(void *vbuf, void *unused)
1016168404Spjd{
1017168404Spjd	arc_buf_hdr_t *buf = vbuf;
1018168404Spjd
1019219089Spjd	ASSERT(BUF_EMPTY(buf));
1020168404Spjd	refcount_destroy(&buf->b_refcnt);
1021168404Spjd	cv_destroy(&buf->b_cv);
1022185029Spjd	mutex_destroy(&buf->b_freeze_lock);
1023208373Smm	arc_space_return(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
1024168404Spjd}
1025168404Spjd
1026185029Spjd/* ARGSUSED */
1027185029Spjdstatic void
1028185029Spjdbuf_dest(void *vbuf, void *unused)
1029185029Spjd{
1030185029Spjd	arc_buf_t *buf = vbuf;
1031185029Spjd
1032219089Spjd	mutex_destroy(&buf->b_evict_lock);
1033208373Smm	arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1034185029Spjd}
1035185029Spjd
1036168404Spjd/*
1037168404Spjd * Reclaim callback -- invoked when memory is low.
1038168404Spjd */
1039168404Spjd/* ARGSUSED */
1040168404Spjdstatic void
1041168404Spjdhdr_recl(void *unused)
1042168404Spjd{
1043168404Spjd	dprintf("hdr_recl called\n");
1044168404Spjd	/*
1045168404Spjd	 * umem calls the reclaim func when we destroy the buf cache,
1046168404Spjd	 * which is after we do arc_fini().
1047168404Spjd	 */
1048168404Spjd	if (!arc_dead)
1049168404Spjd		cv_signal(&arc_reclaim_thr_cv);
1050168404Spjd}
1051168404Spjd
1052168404Spjdstatic void
1053168404Spjdbuf_init(void)
1054168404Spjd{
1055168404Spjd	uint64_t *ct;
1056168404Spjd	uint64_t hsize = 1ULL << 12;
1057168404Spjd	int i, j;
1058168404Spjd
1059168404Spjd	/*
1060168404Spjd	 * The hash table is big enough to fill all of physical memory
1061269230Sdelphij	 * with an average block size of zfs_arc_average_blocksize (default 8K).
1062269230Sdelphij	 * By default, the table will take up
1063269230Sdelphij	 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1064168404Spjd	 */
1065269230Sdelphij	while (hsize * zfs_arc_average_blocksize < (uint64_t)physmem * PAGESIZE)
1066168404Spjd		hsize <<= 1;
1067168404Spjdretry:
1068168404Spjd	buf_hash_table.ht_mask = hsize - 1;
1069168404Spjd	buf_hash_table.ht_table =
1070168404Spjd	    kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1071168404Spjd	if (buf_hash_table.ht_table == NULL) {
1072168404Spjd		ASSERT(hsize > (1ULL << 8));
1073168404Spjd		hsize >>= 1;
1074168404Spjd		goto retry;
1075168404Spjd	}
1076168404Spjd
1077168404Spjd	hdr_cache = kmem_cache_create("arc_buf_hdr_t", sizeof (arc_buf_hdr_t),
1078168404Spjd	    0, hdr_cons, hdr_dest, hdr_recl, NULL, NULL, 0);
1079168404Spjd	buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1080185029Spjd	    0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1081168404Spjd
1082168404Spjd	for (i = 0; i < 256; i++)
1083168404Spjd		for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1084168404Spjd			*ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1085168404Spjd
1086168404Spjd	for (i = 0; i < BUF_LOCKS; i++) {
1087168404Spjd		mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1088168404Spjd		    NULL, MUTEX_DEFAULT, NULL);
1089168404Spjd	}
1090168404Spjd}
1091168404Spjd
1092168404Spjd#define	ARC_MINTIME	(hz>>4) /* 62 ms */
1093168404Spjd
1094168404Spjdstatic void
1095168404Spjdarc_cksum_verify(arc_buf_t *buf)
1096168404Spjd{
1097168404Spjd	zio_cksum_t zc;
1098168404Spjd
1099168404Spjd	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1100168404Spjd		return;
1101168404Spjd
1102168404Spjd	mutex_enter(&buf->b_hdr->b_freeze_lock);
1103168404Spjd	if (buf->b_hdr->b_freeze_cksum == NULL ||
1104168404Spjd	    (buf->b_hdr->b_flags & ARC_IO_ERROR)) {
1105168404Spjd		mutex_exit(&buf->b_hdr->b_freeze_lock);
1106168404Spjd		return;
1107168404Spjd	}
1108168404Spjd	fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1109168404Spjd	if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
1110168404Spjd		panic("buffer modified while frozen!");
1111168404Spjd	mutex_exit(&buf->b_hdr->b_freeze_lock);
1112168404Spjd}
1113168404Spjd
1114185029Spjdstatic int
1115185029Spjdarc_cksum_equal(arc_buf_t *buf)
1116185029Spjd{
1117185029Spjd	zio_cksum_t zc;
1118185029Spjd	int equal;
1119185029Spjd
1120185029Spjd	mutex_enter(&buf->b_hdr->b_freeze_lock);
1121185029Spjd	fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1122185029Spjd	equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
1123185029Spjd	mutex_exit(&buf->b_hdr->b_freeze_lock);
1124185029Spjd
1125185029Spjd	return (equal);
1126185029Spjd}
1127185029Spjd
1128168404Spjdstatic void
1129185029Spjdarc_cksum_compute(arc_buf_t *buf, boolean_t force)
1130168404Spjd{
1131185029Spjd	if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
1132168404Spjd		return;
1133168404Spjd
1134168404Spjd	mutex_enter(&buf->b_hdr->b_freeze_lock);
1135168404Spjd	if (buf->b_hdr->b_freeze_cksum != NULL) {
1136168404Spjd		mutex_exit(&buf->b_hdr->b_freeze_lock);
1137168404Spjd		return;
1138168404Spjd	}
1139168404Spjd	buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
1140168404Spjd	fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
1141168404Spjd	    buf->b_hdr->b_freeze_cksum);
1142168404Spjd	mutex_exit(&buf->b_hdr->b_freeze_lock);
1143240133Smm#ifdef illumos
1144240133Smm	arc_buf_watch(buf);
1145240133Smm#endif /* illumos */
1146168404Spjd}
1147168404Spjd
1148240133Smm#ifdef illumos
1149240133Smm#ifndef _KERNEL
1150240133Smmtypedef struct procctl {
1151240133Smm	long cmd;
1152240133Smm	prwatch_t prwatch;
1153240133Smm} procctl_t;
1154240133Smm#endif
1155240133Smm
1156240133Smm/* ARGSUSED */
1157240133Smmstatic void
1158240133Smmarc_buf_unwatch(arc_buf_t *buf)
1159240133Smm{
1160240133Smm#ifndef _KERNEL
1161240133Smm	if (arc_watch) {
1162240133Smm		int result;
1163240133Smm		procctl_t ctl;
1164240133Smm		ctl.cmd = PCWATCH;
1165240133Smm		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1166240133Smm		ctl.prwatch.pr_size = 0;
1167240133Smm		ctl.prwatch.pr_wflags = 0;
1168240133Smm		result = write(arc_procfd, &ctl, sizeof (ctl));
1169240133Smm		ASSERT3U(result, ==, sizeof (ctl));
1170240133Smm	}
1171240133Smm#endif
1172240133Smm}
1173240133Smm
1174240133Smm/* ARGSUSED */
1175240133Smmstatic void
1176240133Smmarc_buf_watch(arc_buf_t *buf)
1177240133Smm{
1178240133Smm#ifndef _KERNEL
1179240133Smm	if (arc_watch) {
1180240133Smm		int result;
1181240133Smm		procctl_t ctl;
1182240133Smm		ctl.cmd = PCWATCH;
1183240133Smm		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1184240133Smm		ctl.prwatch.pr_size = buf->b_hdr->b_size;
1185240133Smm		ctl.prwatch.pr_wflags = WA_WRITE;
1186240133Smm		result = write(arc_procfd, &ctl, sizeof (ctl));
1187240133Smm		ASSERT3U(result, ==, sizeof (ctl));
1188240133Smm	}
1189240133Smm#endif
1190240133Smm}
1191240133Smm#endif /* illumos */
1192240133Smm
1193168404Spjdvoid
1194168404Spjdarc_buf_thaw(arc_buf_t *buf)
1195168404Spjd{
1196185029Spjd	if (zfs_flags & ZFS_DEBUG_MODIFY) {
1197185029Spjd		if (buf->b_hdr->b_state != arc_anon)
1198185029Spjd			panic("modifying non-anon buffer!");
1199185029Spjd		if (buf->b_hdr->b_flags & ARC_IO_IN_PROGRESS)
1200185029Spjd			panic("modifying buffer while i/o in progress!");
1201185029Spjd		arc_cksum_verify(buf);
1202185029Spjd	}
1203168404Spjd
1204168404Spjd	mutex_enter(&buf->b_hdr->b_freeze_lock);
1205168404Spjd	if (buf->b_hdr->b_freeze_cksum != NULL) {
1206168404Spjd		kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1207168404Spjd		buf->b_hdr->b_freeze_cksum = NULL;
1208168404Spjd	}
1209219089Spjd
1210219089Spjd	if (zfs_flags & ZFS_DEBUG_MODIFY) {
1211219089Spjd		if (buf->b_hdr->b_thawed)
1212219089Spjd			kmem_free(buf->b_hdr->b_thawed, 1);
1213219089Spjd		buf->b_hdr->b_thawed = kmem_alloc(1, KM_SLEEP);
1214219089Spjd	}
1215219089Spjd
1216168404Spjd	mutex_exit(&buf->b_hdr->b_freeze_lock);
1217240133Smm
1218240133Smm#ifdef illumos
1219240133Smm	arc_buf_unwatch(buf);
1220240133Smm#endif /* illumos */
1221168404Spjd}
1222168404Spjd
1223168404Spjdvoid
1224168404Spjdarc_buf_freeze(arc_buf_t *buf)
1225168404Spjd{
1226219089Spjd	kmutex_t *hash_lock;
1227219089Spjd
1228168404Spjd	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1229168404Spjd		return;
1230168404Spjd
1231219089Spjd	hash_lock = HDR_LOCK(buf->b_hdr);
1232219089Spjd	mutex_enter(hash_lock);
1233219089Spjd
1234168404Spjd	ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
1235168404Spjd	    buf->b_hdr->b_state == arc_anon);
1236185029Spjd	arc_cksum_compute(buf, B_FALSE);
1237219089Spjd	mutex_exit(hash_lock);
1238240133Smm
1239168404Spjd}
1240168404Spjd
1241168404Spjdstatic void
1242205231Skmacyget_buf_info(arc_buf_hdr_t *ab, arc_state_t *state, list_t **list, kmutex_t **lock)
1243205231Skmacy{
1244205231Skmacy	uint64_t buf_hashid = buf_hash(ab->b_spa, &ab->b_dva, ab->b_birth);
1245205231Skmacy
1246206796Spjd	if (ab->b_type == ARC_BUFC_METADATA)
1247206796Spjd		buf_hashid &= (ARC_BUFC_NUMMETADATALISTS - 1);
1248205231Skmacy	else {
1249206796Spjd		buf_hashid &= (ARC_BUFC_NUMDATALISTS - 1);
1250205231Skmacy		buf_hashid += ARC_BUFC_NUMMETADATALISTS;
1251205231Skmacy	}
1252205231Skmacy
1253205231Skmacy	*list = &state->arcs_lists[buf_hashid];
1254205231Skmacy	*lock = ARCS_LOCK(state, buf_hashid);
1255205231Skmacy}
1256205231Skmacy
1257205231Skmacy
1258205231Skmacystatic void
1259168404Spjdadd_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
1260168404Spjd{
1261168404Spjd	ASSERT(MUTEX_HELD(hash_lock));
1262168404Spjd
1263168404Spjd	if ((refcount_add(&ab->b_refcnt, tag) == 1) &&
1264168404Spjd	    (ab->b_state != arc_anon)) {
1265206796Spjd		uint64_t delta = ab->b_size * ab->b_datacnt;
1266206796Spjd		uint64_t *size = &ab->b_state->arcs_lsize[ab->b_type];
1267205231Skmacy		list_t *list;
1268205231Skmacy		kmutex_t *lock;
1269168404Spjd
1270205231Skmacy		get_buf_info(ab, ab->b_state, &list, &lock);
1271205231Skmacy		ASSERT(!MUTEX_HELD(lock));
1272205231Skmacy		mutex_enter(lock);
1273168404Spjd		ASSERT(list_link_active(&ab->b_arc_node));
1274185029Spjd		list_remove(list, ab);
1275168404Spjd		if (GHOST_STATE(ab->b_state)) {
1276240415Smm			ASSERT0(ab->b_datacnt);
1277168404Spjd			ASSERT3P(ab->b_buf, ==, NULL);
1278168404Spjd			delta = ab->b_size;
1279168404Spjd		}
1280168404Spjd		ASSERT(delta > 0);
1281185029Spjd		ASSERT3U(*size, >=, delta);
1282185029Spjd		atomic_add_64(size, -delta);
1283206794Spjd		mutex_exit(lock);
1284185029Spjd		/* remove the prefetch flag if we get a reference */
1285168404Spjd		if (ab->b_flags & ARC_PREFETCH)
1286168404Spjd			ab->b_flags &= ~ARC_PREFETCH;
1287168404Spjd	}
1288168404Spjd}
1289168404Spjd
1290168404Spjdstatic int
1291168404Spjdremove_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
1292168404Spjd{
1293168404Spjd	int cnt;
1294168404Spjd	arc_state_t *state = ab->b_state;
1295168404Spjd
1296168404Spjd	ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
1297168404Spjd	ASSERT(!GHOST_STATE(state));
1298168404Spjd
1299168404Spjd	if (((cnt = refcount_remove(&ab->b_refcnt, tag)) == 0) &&
1300168404Spjd	    (state != arc_anon)) {
1301185029Spjd		uint64_t *size = &state->arcs_lsize[ab->b_type];
1302205231Skmacy		list_t *list;
1303205231Skmacy		kmutex_t *lock;
1304185029Spjd
1305205231Skmacy		get_buf_info(ab, state, &list, &lock);
1306205231Skmacy		ASSERT(!MUTEX_HELD(lock));
1307205231Skmacy		mutex_enter(lock);
1308168404Spjd		ASSERT(!list_link_active(&ab->b_arc_node));
1309205231Skmacy		list_insert_head(list, ab);
1310168404Spjd		ASSERT(ab->b_datacnt > 0);
1311185029Spjd		atomic_add_64(size, ab->b_size * ab->b_datacnt);
1312206794Spjd		mutex_exit(lock);
1313168404Spjd	}
1314168404Spjd	return (cnt);
1315168404Spjd}
1316168404Spjd
1317168404Spjd/*
1318168404Spjd * Move the supplied buffer to the indicated state.  The mutex
1319168404Spjd * for the buffer must be held by the caller.
1320168404Spjd */
1321168404Spjdstatic void
1322168404Spjdarc_change_state(arc_state_t *new_state, arc_buf_hdr_t *ab, kmutex_t *hash_lock)
1323168404Spjd{
1324168404Spjd	arc_state_t *old_state = ab->b_state;
1325168404Spjd	int64_t refcnt = refcount_count(&ab->b_refcnt);
1326168404Spjd	uint64_t from_delta, to_delta;
1327205231Skmacy	list_t *list;
1328205231Skmacy	kmutex_t *lock;
1329168404Spjd
1330168404Spjd	ASSERT(MUTEX_HELD(hash_lock));
1331258632Savg	ASSERT3P(new_state, !=, old_state);
1332168404Spjd	ASSERT(refcnt == 0 || ab->b_datacnt > 0);
1333168404Spjd	ASSERT(ab->b_datacnt == 0 || !GHOST_STATE(new_state));
1334219089Spjd	ASSERT(ab->b_datacnt <= 1 || old_state != arc_anon);
1335168404Spjd
1336168404Spjd	from_delta = to_delta = ab->b_datacnt * ab->b_size;
1337168404Spjd
1338168404Spjd	/*
1339168404Spjd	 * If this buffer is evictable, transfer it from the
1340168404Spjd	 * old state list to the new state list.
1341168404Spjd	 */
1342168404Spjd	if (refcnt == 0) {
1343168404Spjd		if (old_state != arc_anon) {
1344205231Skmacy			int use_mutex;
1345185029Spjd			uint64_t *size = &old_state->arcs_lsize[ab->b_type];
1346168404Spjd
1347205231Skmacy			get_buf_info(ab, old_state, &list, &lock);
1348205231Skmacy			use_mutex = !MUTEX_HELD(lock);
1349168404Spjd			if (use_mutex)
1350205231Skmacy				mutex_enter(lock);
1351168404Spjd
1352168404Spjd			ASSERT(list_link_active(&ab->b_arc_node));
1353205231Skmacy			list_remove(list, ab);
1354168404Spjd
1355168404Spjd			/*
1356168404Spjd			 * If prefetching out of the ghost cache,
1357219089Spjd			 * we will have a non-zero datacnt.
1358168404Spjd			 */
1359168404Spjd			if (GHOST_STATE(old_state) && ab->b_datacnt == 0) {
1360168404Spjd				/* ghost elements have a ghost size */
1361168404Spjd				ASSERT(ab->b_buf == NULL);
1362168404Spjd				from_delta = ab->b_size;
1363168404Spjd			}
1364185029Spjd			ASSERT3U(*size, >=, from_delta);
1365185029Spjd			atomic_add_64(size, -from_delta);
1366168404Spjd
1367168404Spjd			if (use_mutex)
1368205231Skmacy				mutex_exit(lock);
1369168404Spjd		}
1370168404Spjd		if (new_state != arc_anon) {
1371206796Spjd			int use_mutex;
1372185029Spjd			uint64_t *size = &new_state->arcs_lsize[ab->b_type];
1373168404Spjd
1374205231Skmacy			get_buf_info(ab, new_state, &list, &lock);
1375205231Skmacy			use_mutex = !MUTEX_HELD(lock);
1376168404Spjd			if (use_mutex)
1377205231Skmacy				mutex_enter(lock);
1378168404Spjd
1379205231Skmacy			list_insert_head(list, ab);
1380168404Spjd
1381168404Spjd			/* ghost elements have a ghost size */
1382168404Spjd			if (GHOST_STATE(new_state)) {
1383168404Spjd				ASSERT(ab->b_datacnt == 0);
1384168404Spjd				ASSERT(ab->b_buf == NULL);
1385168404Spjd				to_delta = ab->b_size;
1386168404Spjd			}
1387185029Spjd			atomic_add_64(size, to_delta);
1388168404Spjd
1389168404Spjd			if (use_mutex)
1390205231Skmacy				mutex_exit(lock);
1391168404Spjd		}
1392168404Spjd	}
1393168404Spjd
1394168404Spjd	ASSERT(!BUF_EMPTY(ab));
1395219089Spjd	if (new_state == arc_anon && HDR_IN_HASH_TABLE(ab))
1396168404Spjd		buf_hash_remove(ab);
1397168404Spjd
1398168404Spjd	/* adjust state sizes */
1399168404Spjd	if (to_delta)
1400168404Spjd		atomic_add_64(&new_state->arcs_size, to_delta);
1401168404Spjd	if (from_delta) {
1402168404Spjd		ASSERT3U(old_state->arcs_size, >=, from_delta);
1403168404Spjd		atomic_add_64(&old_state->arcs_size, -from_delta);
1404168404Spjd	}
1405168404Spjd	ab->b_state = new_state;
1406185029Spjd
1407185029Spjd	/* adjust l2arc hdr stats */
1408185029Spjd	if (new_state == arc_l2c_only)
1409185029Spjd		l2arc_hdr_stat_add();
1410185029Spjd	else if (old_state == arc_l2c_only)
1411185029Spjd		l2arc_hdr_stat_remove();
1412168404Spjd}
1413168404Spjd
1414185029Spjdvoid
1415208373Smmarc_space_consume(uint64_t space, arc_space_type_t type)
1416185029Spjd{
1417208373Smm	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1418208373Smm
1419208373Smm	switch (type) {
1420208373Smm	case ARC_SPACE_DATA:
1421208373Smm		ARCSTAT_INCR(arcstat_data_size, space);
1422208373Smm		break;
1423208373Smm	case ARC_SPACE_OTHER:
1424208373Smm		ARCSTAT_INCR(arcstat_other_size, space);
1425208373Smm		break;
1426208373Smm	case ARC_SPACE_HDRS:
1427208373Smm		ARCSTAT_INCR(arcstat_hdr_size, space);
1428208373Smm		break;
1429208373Smm	case ARC_SPACE_L2HDRS:
1430208373Smm		ARCSTAT_INCR(arcstat_l2_hdr_size, space);
1431208373Smm		break;
1432208373Smm	}
1433208373Smm
1434185029Spjd	atomic_add_64(&arc_meta_used, space);
1435185029Spjd	atomic_add_64(&arc_size, space);
1436185029Spjd}
1437185029Spjd
1438185029Spjdvoid
1439208373Smmarc_space_return(uint64_t space, arc_space_type_t type)
1440185029Spjd{
1441208373Smm	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1442208373Smm
1443208373Smm	switch (type) {
1444208373Smm	case ARC_SPACE_DATA:
1445208373Smm		ARCSTAT_INCR(arcstat_data_size, -space);
1446208373Smm		break;
1447208373Smm	case ARC_SPACE_OTHER:
1448208373Smm		ARCSTAT_INCR(arcstat_other_size, -space);
1449208373Smm		break;
1450208373Smm	case ARC_SPACE_HDRS:
1451208373Smm		ARCSTAT_INCR(arcstat_hdr_size, -space);
1452208373Smm		break;
1453208373Smm	case ARC_SPACE_L2HDRS:
1454208373Smm		ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
1455208373Smm		break;
1456208373Smm	}
1457208373Smm
1458185029Spjd	ASSERT(arc_meta_used >= space);
1459185029Spjd	if (arc_meta_max < arc_meta_used)
1460185029Spjd		arc_meta_max = arc_meta_used;
1461185029Spjd	atomic_add_64(&arc_meta_used, -space);
1462185029Spjd	ASSERT(arc_size >= space);
1463185029Spjd	atomic_add_64(&arc_size, -space);
1464185029Spjd}
1465185029Spjd
1466185029Spjdvoid *
1467185029Spjdarc_data_buf_alloc(uint64_t size)
1468185029Spjd{
1469185029Spjd	if (arc_evict_needed(ARC_BUFC_DATA))
1470185029Spjd		cv_signal(&arc_reclaim_thr_cv);
1471185029Spjd	atomic_add_64(&arc_size, size);
1472185029Spjd	return (zio_data_buf_alloc(size));
1473185029Spjd}
1474185029Spjd
1475185029Spjdvoid
1476185029Spjdarc_data_buf_free(void *buf, uint64_t size)
1477185029Spjd{
1478185029Spjd	zio_data_buf_free(buf, size);
1479185029Spjd	ASSERT(arc_size >= size);
1480185029Spjd	atomic_add_64(&arc_size, -size);
1481185029Spjd}
1482185029Spjd
1483168404Spjdarc_buf_t *
1484168404Spjdarc_buf_alloc(spa_t *spa, int size, void *tag, arc_buf_contents_t type)
1485168404Spjd{
1486168404Spjd	arc_buf_hdr_t *hdr;
1487168404Spjd	arc_buf_t *buf;
1488168404Spjd
1489168404Spjd	ASSERT3U(size, >, 0);
1490185029Spjd	hdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
1491168404Spjd	ASSERT(BUF_EMPTY(hdr));
1492168404Spjd	hdr->b_size = size;
1493168404Spjd	hdr->b_type = type;
1494228103Smm	hdr->b_spa = spa_load_guid(spa);
1495168404Spjd	hdr->b_state = arc_anon;
1496168404Spjd	hdr->b_arc_access = 0;
1497185029Spjd	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1498168404Spjd	buf->b_hdr = hdr;
1499168404Spjd	buf->b_data = NULL;
1500168404Spjd	buf->b_efunc = NULL;
1501168404Spjd	buf->b_private = NULL;
1502168404Spjd	buf->b_next = NULL;
1503168404Spjd	hdr->b_buf = buf;
1504168404Spjd	arc_get_data_buf(buf);
1505168404Spjd	hdr->b_datacnt = 1;
1506168404Spjd	hdr->b_flags = 0;
1507168404Spjd	ASSERT(refcount_is_zero(&hdr->b_refcnt));
1508168404Spjd	(void) refcount_add(&hdr->b_refcnt, tag);
1509168404Spjd
1510168404Spjd	return (buf);
1511168404Spjd}
1512168404Spjd
1513209962Smmstatic char *arc_onloan_tag = "onloan";
1514209962Smm
1515209962Smm/*
1516209962Smm * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
1517209962Smm * flight data by arc_tempreserve_space() until they are "returned". Loaned
1518209962Smm * buffers must be returned to the arc before they can be used by the DMU or
1519209962Smm * freed.
1520209962Smm */
1521209962Smmarc_buf_t *
1522209962Smmarc_loan_buf(spa_t *spa, int size)
1523209962Smm{
1524209962Smm	arc_buf_t *buf;
1525209962Smm
1526209962Smm	buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
1527209962Smm
1528209962Smm	atomic_add_64(&arc_loaned_bytes, size);
1529209962Smm	return (buf);
1530209962Smm}
1531209962Smm
1532209962Smm/*
1533209962Smm * Return a loaned arc buffer to the arc.
1534209962Smm */
1535209962Smmvoid
1536209962Smmarc_return_buf(arc_buf_t *buf, void *tag)
1537209962Smm{
1538209962Smm	arc_buf_hdr_t *hdr = buf->b_hdr;
1539209962Smm
1540209962Smm	ASSERT(buf->b_data != NULL);
1541219089Spjd	(void) refcount_add(&hdr->b_refcnt, tag);
1542219089Spjd	(void) refcount_remove(&hdr->b_refcnt, arc_onloan_tag);
1543209962Smm
1544209962Smm	atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
1545209962Smm}
1546209962Smm
1547219089Spjd/* Detach an arc_buf from a dbuf (tag) */
1548219089Spjdvoid
1549219089Spjdarc_loan_inuse_buf(arc_buf_t *buf, void *tag)
1550219089Spjd{
1551219089Spjd	arc_buf_hdr_t *hdr;
1552219089Spjd
1553219089Spjd	ASSERT(buf->b_data != NULL);
1554219089Spjd	hdr = buf->b_hdr;
1555219089Spjd	(void) refcount_add(&hdr->b_refcnt, arc_onloan_tag);
1556219089Spjd	(void) refcount_remove(&hdr->b_refcnt, tag);
1557219089Spjd	buf->b_efunc = NULL;
1558219089Spjd	buf->b_private = NULL;
1559219089Spjd
1560219089Spjd	atomic_add_64(&arc_loaned_bytes, hdr->b_size);
1561219089Spjd}
1562219089Spjd
1563168404Spjdstatic arc_buf_t *
1564168404Spjdarc_buf_clone(arc_buf_t *from)
1565168404Spjd{
1566168404Spjd	arc_buf_t *buf;
1567168404Spjd	arc_buf_hdr_t *hdr = from->b_hdr;
1568168404Spjd	uint64_t size = hdr->b_size;
1569168404Spjd
1570219089Spjd	ASSERT(hdr->b_state != arc_anon);
1571219089Spjd
1572185029Spjd	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1573168404Spjd	buf->b_hdr = hdr;
1574168404Spjd	buf->b_data = NULL;
1575168404Spjd	buf->b_efunc = NULL;
1576168404Spjd	buf->b_private = NULL;
1577168404Spjd	buf->b_next = hdr->b_buf;
1578168404Spjd	hdr->b_buf = buf;
1579168404Spjd	arc_get_data_buf(buf);
1580168404Spjd	bcopy(from->b_data, buf->b_data, size);
1581242845Sdelphij
1582242845Sdelphij	/*
1583242845Sdelphij	 * This buffer already exists in the arc so create a duplicate
1584242845Sdelphij	 * copy for the caller.  If the buffer is associated with user data
1585242845Sdelphij	 * then track the size and number of duplicates.  These stats will be
1586242845Sdelphij	 * updated as duplicate buffers are created and destroyed.
1587242845Sdelphij	 */
1588242845Sdelphij	if (hdr->b_type == ARC_BUFC_DATA) {
1589242845Sdelphij		ARCSTAT_BUMP(arcstat_duplicate_buffers);
1590242845Sdelphij		ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
1591242845Sdelphij	}
1592168404Spjd	hdr->b_datacnt += 1;
1593168404Spjd	return (buf);
1594168404Spjd}
1595168404Spjd
1596168404Spjdvoid
1597168404Spjdarc_buf_add_ref(arc_buf_t *buf, void* tag)
1598168404Spjd{
1599168404Spjd	arc_buf_hdr_t *hdr;
1600168404Spjd	kmutex_t *hash_lock;
1601168404Spjd
1602168404Spjd	/*
1603185029Spjd	 * Check to see if this buffer is evicted.  Callers
1604185029Spjd	 * must verify b_data != NULL to know if the add_ref
1605185029Spjd	 * was successful.
1606168404Spjd	 */
1607219089Spjd	mutex_enter(&buf->b_evict_lock);
1608185029Spjd	if (buf->b_data == NULL) {
1609219089Spjd		mutex_exit(&buf->b_evict_lock);
1610168404Spjd		return;
1611168404Spjd	}
1612219089Spjd	hash_lock = HDR_LOCK(buf->b_hdr);
1613219089Spjd	mutex_enter(hash_lock);
1614185029Spjd	hdr = buf->b_hdr;
1615219089Spjd	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1616219089Spjd	mutex_exit(&buf->b_evict_lock);
1617168404Spjd
1618168404Spjd	ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
1619168404Spjd	add_reference(hdr, hash_lock, tag);
1620208373Smm	DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
1621168404Spjd	arc_access(hdr, hash_lock);
1622168404Spjd	mutex_exit(hash_lock);
1623168404Spjd	ARCSTAT_BUMP(arcstat_hits);
1624168404Spjd	ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
1625168404Spjd	    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
1626168404Spjd	    data, metadata, hits);
1627168404Spjd}
1628168404Spjd
1629185029Spjd/*
1630185029Spjd * Free the arc data buffer.  If it is an l2arc write in progress,
1631185029Spjd * the buffer is placed on l2arc_free_on_write to be freed later.
1632185029Spjd */
1633168404Spjdstatic void
1634240133Smmarc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
1635185029Spjd{
1636240133Smm	arc_buf_hdr_t *hdr = buf->b_hdr;
1637240133Smm
1638185029Spjd	if (HDR_L2_WRITING(hdr)) {
1639185029Spjd		l2arc_data_free_t *df;
1640185029Spjd		df = kmem_alloc(sizeof (l2arc_data_free_t), KM_SLEEP);
1641240133Smm		df->l2df_data = buf->b_data;
1642240133Smm		df->l2df_size = hdr->b_size;
1643185029Spjd		df->l2df_func = free_func;
1644185029Spjd		mutex_enter(&l2arc_free_on_write_mtx);
1645185029Spjd		list_insert_head(l2arc_free_on_write, df);
1646185029Spjd		mutex_exit(&l2arc_free_on_write_mtx);
1647185029Spjd		ARCSTAT_BUMP(arcstat_l2_free_on_write);
1648185029Spjd	} else {
1649240133Smm		free_func(buf->b_data, hdr->b_size);
1650185029Spjd	}
1651185029Spjd}
1652185029Spjd
1653268858Sdelphij/*
1654268858Sdelphij * Free up buf->b_data and if 'remove' is set, then pull the
1655268858Sdelphij * arc_buf_t off of the the arc_buf_hdr_t's list and free it.
1656268858Sdelphij */
1657185029Spjdstatic void
1658268858Sdelphijarc_buf_destroy(arc_buf_t *buf, boolean_t recycle, boolean_t remove)
1659168404Spjd{
1660168404Spjd	arc_buf_t **bufp;
1661168404Spjd
1662168404Spjd	/* free up data associated with the buf */
1663168404Spjd	if (buf->b_data) {
1664168404Spjd		arc_state_t *state = buf->b_hdr->b_state;
1665168404Spjd		uint64_t size = buf->b_hdr->b_size;
1666168404Spjd		arc_buf_contents_t type = buf->b_hdr->b_type;
1667168404Spjd
1668168404Spjd		arc_cksum_verify(buf);
1669240133Smm#ifdef illumos
1670240133Smm		arc_buf_unwatch(buf);
1671240133Smm#endif /* illumos */
1672219089Spjd
1673168404Spjd		if (!recycle) {
1674168404Spjd			if (type == ARC_BUFC_METADATA) {
1675240133Smm				arc_buf_data_free(buf, zio_buf_free);
1676208373Smm				arc_space_return(size, ARC_SPACE_DATA);
1677168404Spjd			} else {
1678168404Spjd				ASSERT(type == ARC_BUFC_DATA);
1679240133Smm				arc_buf_data_free(buf, zio_data_buf_free);
1680208373Smm				ARCSTAT_INCR(arcstat_data_size, -size);
1681185029Spjd				atomic_add_64(&arc_size, -size);
1682168404Spjd			}
1683168404Spjd		}
1684168404Spjd		if (list_link_active(&buf->b_hdr->b_arc_node)) {
1685185029Spjd			uint64_t *cnt = &state->arcs_lsize[type];
1686185029Spjd
1687168404Spjd			ASSERT(refcount_is_zero(&buf->b_hdr->b_refcnt));
1688168404Spjd			ASSERT(state != arc_anon);
1689185029Spjd
1690185029Spjd			ASSERT3U(*cnt, >=, size);
1691185029Spjd			atomic_add_64(cnt, -size);
1692168404Spjd		}
1693168404Spjd		ASSERT3U(state->arcs_size, >=, size);
1694168404Spjd		atomic_add_64(&state->arcs_size, -size);
1695168404Spjd		buf->b_data = NULL;
1696242845Sdelphij
1697242845Sdelphij		/*
1698242845Sdelphij		 * If we're destroying a duplicate buffer make sure
1699242845Sdelphij		 * that the appropriate statistics are updated.
1700242845Sdelphij		 */
1701242845Sdelphij		if (buf->b_hdr->b_datacnt > 1 &&
1702242845Sdelphij		    buf->b_hdr->b_type == ARC_BUFC_DATA) {
1703242845Sdelphij			ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
1704242845Sdelphij			ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
1705242845Sdelphij		}
1706168404Spjd		ASSERT(buf->b_hdr->b_datacnt > 0);
1707168404Spjd		buf->b_hdr->b_datacnt -= 1;
1708168404Spjd	}
1709168404Spjd
1710168404Spjd	/* only remove the buf if requested */
1711268858Sdelphij	if (!remove)
1712168404Spjd		return;
1713168404Spjd
1714168404Spjd	/* remove the buf from the hdr list */
1715168404Spjd	for (bufp = &buf->b_hdr->b_buf; *bufp != buf; bufp = &(*bufp)->b_next)
1716168404Spjd		continue;
1717168404Spjd	*bufp = buf->b_next;
1718219089Spjd	buf->b_next = NULL;
1719168404Spjd
1720168404Spjd	ASSERT(buf->b_efunc == NULL);
1721168404Spjd
1722168404Spjd	/* clean up the buf */
1723168404Spjd	buf->b_hdr = NULL;
1724168404Spjd	kmem_cache_free(buf_cache, buf);
1725168404Spjd}
1726168404Spjd
1727168404Spjdstatic void
1728168404Spjdarc_hdr_destroy(arc_buf_hdr_t *hdr)
1729168404Spjd{
1730168404Spjd	ASSERT(refcount_is_zero(&hdr->b_refcnt));
1731168404Spjd	ASSERT3P(hdr->b_state, ==, arc_anon);
1732168404Spjd	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1733219089Spjd	l2arc_buf_hdr_t *l2hdr = hdr->b_l2hdr;
1734168404Spjd
1735219089Spjd	if (l2hdr != NULL) {
1736219089Spjd		boolean_t buflist_held = MUTEX_HELD(&l2arc_buflist_mtx);
1737219089Spjd		/*
1738219089Spjd		 * To prevent arc_free() and l2arc_evict() from
1739219089Spjd		 * attempting to free the same buffer at the same time,
1740219089Spjd		 * a FREE_IN_PROGRESS flag is given to arc_free() to
1741219089Spjd		 * give it priority.  l2arc_evict() can't destroy this
1742219089Spjd		 * header while we are waiting on l2arc_buflist_mtx.
1743219089Spjd		 *
1744219089Spjd		 * The hdr may be removed from l2ad_buflist before we
1745219089Spjd		 * grab l2arc_buflist_mtx, so b_l2hdr is rechecked.
1746219089Spjd		 */
1747219089Spjd		if (!buflist_held) {
1748185029Spjd			mutex_enter(&l2arc_buflist_mtx);
1749219089Spjd			l2hdr = hdr->b_l2hdr;
1750219089Spjd		}
1751219089Spjd
1752219089Spjd		if (l2hdr != NULL) {
1753248572Ssmh			trim_map_free(l2hdr->b_dev->l2ad_vdev, l2hdr->b_daddr,
1754248574Ssmh			    hdr->b_size, 0);
1755219089Spjd			list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
1756219089Spjd			ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
1757251478Sdelphij			ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
1758268085Sdelphij			vdev_space_update(l2hdr->b_dev->l2ad_vdev,
1759268085Sdelphij			    -l2hdr->b_asize, 0, 0);
1760219089Spjd			kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
1761219089Spjd			if (hdr->b_state == arc_l2c_only)
1762219089Spjd				l2arc_hdr_stat_remove();
1763219089Spjd			hdr->b_l2hdr = NULL;
1764219089Spjd		}
1765219089Spjd
1766219089Spjd		if (!buflist_held)
1767185029Spjd			mutex_exit(&l2arc_buflist_mtx);
1768185029Spjd	}
1769185029Spjd
1770168404Spjd	if (!BUF_EMPTY(hdr)) {
1771168404Spjd		ASSERT(!HDR_IN_HASH_TABLE(hdr));
1772219089Spjd		buf_discard_identity(hdr);
1773168404Spjd	}
1774168404Spjd	while (hdr->b_buf) {
1775168404Spjd		arc_buf_t *buf = hdr->b_buf;
1776168404Spjd
1777168404Spjd		if (buf->b_efunc) {
1778168404Spjd			mutex_enter(&arc_eviction_mtx);
1779219089Spjd			mutex_enter(&buf->b_evict_lock);
1780168404Spjd			ASSERT(buf->b_hdr != NULL);
1781168404Spjd			arc_buf_destroy(hdr->b_buf, FALSE, FALSE);
1782168404Spjd			hdr->b_buf = buf->b_next;
1783168404Spjd			buf->b_hdr = &arc_eviction_hdr;
1784168404Spjd			buf->b_next = arc_eviction_list;
1785168404Spjd			arc_eviction_list = buf;
1786219089Spjd			mutex_exit(&buf->b_evict_lock);
1787168404Spjd			mutex_exit(&arc_eviction_mtx);
1788168404Spjd		} else {
1789168404Spjd			arc_buf_destroy(hdr->b_buf, FALSE, TRUE);
1790168404Spjd		}
1791168404Spjd	}
1792168404Spjd	if (hdr->b_freeze_cksum != NULL) {
1793168404Spjd		kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1794168404Spjd		hdr->b_freeze_cksum = NULL;
1795168404Spjd	}
1796219089Spjd	if (hdr->b_thawed) {
1797219089Spjd		kmem_free(hdr->b_thawed, 1);
1798219089Spjd		hdr->b_thawed = NULL;
1799219089Spjd	}
1800168404Spjd
1801168404Spjd	ASSERT(!list_link_active(&hdr->b_arc_node));
1802168404Spjd	ASSERT3P(hdr->b_hash_next, ==, NULL);
1803168404Spjd	ASSERT3P(hdr->b_acb, ==, NULL);
1804168404Spjd	kmem_cache_free(hdr_cache, hdr);
1805168404Spjd}
1806168404Spjd
1807168404Spjdvoid
1808168404Spjdarc_buf_free(arc_buf_t *buf, void *tag)
1809168404Spjd{
1810168404Spjd	arc_buf_hdr_t *hdr = buf->b_hdr;
1811168404Spjd	int hashed = hdr->b_state != arc_anon;
1812168404Spjd
1813168404Spjd	ASSERT(buf->b_efunc == NULL);
1814168404Spjd	ASSERT(buf->b_data != NULL);
1815168404Spjd
1816168404Spjd	if (hashed) {
1817168404Spjd		kmutex_t *hash_lock = HDR_LOCK(hdr);
1818168404Spjd
1819168404Spjd		mutex_enter(hash_lock);
1820219089Spjd		hdr = buf->b_hdr;
1821219089Spjd		ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1822219089Spjd
1823168404Spjd		(void) remove_reference(hdr, hash_lock, tag);
1824219089Spjd		if (hdr->b_datacnt > 1) {
1825168404Spjd			arc_buf_destroy(buf, FALSE, TRUE);
1826219089Spjd		} else {
1827219089Spjd			ASSERT(buf == hdr->b_buf);
1828219089Spjd			ASSERT(buf->b_efunc == NULL);
1829168404Spjd			hdr->b_flags |= ARC_BUF_AVAILABLE;
1830219089Spjd		}
1831168404Spjd		mutex_exit(hash_lock);
1832168404Spjd	} else if (HDR_IO_IN_PROGRESS(hdr)) {
1833168404Spjd		int destroy_hdr;
1834168404Spjd		/*
1835168404Spjd		 * We are in the middle of an async write.  Don't destroy
1836168404Spjd		 * this buffer unless the write completes before we finish
1837168404Spjd		 * decrementing the reference count.
1838168404Spjd		 */
1839168404Spjd		mutex_enter(&arc_eviction_mtx);
1840168404Spjd		(void) remove_reference(hdr, NULL, tag);
1841168404Spjd		ASSERT(refcount_is_zero(&hdr->b_refcnt));
1842168404Spjd		destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
1843168404Spjd		mutex_exit(&arc_eviction_mtx);
1844168404Spjd		if (destroy_hdr)
1845168404Spjd			arc_hdr_destroy(hdr);
1846168404Spjd	} else {
1847219089Spjd		if (remove_reference(hdr, NULL, tag) > 0)
1848168404Spjd			arc_buf_destroy(buf, FALSE, TRUE);
1849219089Spjd		else
1850168404Spjd			arc_hdr_destroy(hdr);
1851168404Spjd	}
1852168404Spjd}
1853168404Spjd
1854248571Smmboolean_t
1855168404Spjdarc_buf_remove_ref(arc_buf_t *buf, void* tag)
1856168404Spjd{
1857168404Spjd	arc_buf_hdr_t *hdr = buf->b_hdr;
1858168404Spjd	kmutex_t *hash_lock = HDR_LOCK(hdr);
1859248571Smm	boolean_t no_callback = (buf->b_efunc == NULL);
1860168404Spjd
1861168404Spjd	if (hdr->b_state == arc_anon) {
1862219089Spjd		ASSERT(hdr->b_datacnt == 1);
1863168404Spjd		arc_buf_free(buf, tag);
1864168404Spjd		return (no_callback);
1865168404Spjd	}
1866168404Spjd
1867168404Spjd	mutex_enter(hash_lock);
1868219089Spjd	hdr = buf->b_hdr;
1869219089Spjd	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1870168404Spjd	ASSERT(hdr->b_state != arc_anon);
1871168404Spjd	ASSERT(buf->b_data != NULL);
1872168404Spjd
1873168404Spjd	(void) remove_reference(hdr, hash_lock, tag);
1874168404Spjd	if (hdr->b_datacnt > 1) {
1875168404Spjd		if (no_callback)
1876168404Spjd			arc_buf_destroy(buf, FALSE, TRUE);
1877168404Spjd	} else if (no_callback) {
1878168404Spjd		ASSERT(hdr->b_buf == buf && buf->b_next == NULL);
1879219089Spjd		ASSERT(buf->b_efunc == NULL);
1880168404Spjd		hdr->b_flags |= ARC_BUF_AVAILABLE;
1881168404Spjd	}
1882168404Spjd	ASSERT(no_callback || hdr->b_datacnt > 1 ||
1883168404Spjd	    refcount_is_zero(&hdr->b_refcnt));
1884168404Spjd	mutex_exit(hash_lock);
1885168404Spjd	return (no_callback);
1886168404Spjd}
1887168404Spjd
1888168404Spjdint
1889168404Spjdarc_buf_size(arc_buf_t *buf)
1890168404Spjd{
1891168404Spjd	return (buf->b_hdr->b_size);
1892168404Spjd}
1893168404Spjd
1894168404Spjd/*
1895242845Sdelphij * Called from the DMU to determine if the current buffer should be
1896242845Sdelphij * evicted. In order to ensure proper locking, the eviction must be initiated
1897242845Sdelphij * from the DMU. Return true if the buffer is associated with user data and
1898242845Sdelphij * duplicate buffers still exist.
1899242845Sdelphij */
1900242845Sdelphijboolean_t
1901242845Sdelphijarc_buf_eviction_needed(arc_buf_t *buf)
1902242845Sdelphij{
1903242845Sdelphij	arc_buf_hdr_t *hdr;
1904242845Sdelphij	boolean_t evict_needed = B_FALSE;
1905242845Sdelphij
1906242845Sdelphij	if (zfs_disable_dup_eviction)
1907242845Sdelphij		return (B_FALSE);
1908242845Sdelphij
1909242845Sdelphij	mutex_enter(&buf->b_evict_lock);
1910242845Sdelphij	hdr = buf->b_hdr;
1911242845Sdelphij	if (hdr == NULL) {
1912242845Sdelphij		/*
1913242845Sdelphij		 * We are in arc_do_user_evicts(); let that function
1914242845Sdelphij		 * perform the eviction.
1915242845Sdelphij		 */
1916242845Sdelphij		ASSERT(buf->b_data == NULL);
1917242845Sdelphij		mutex_exit(&buf->b_evict_lock);
1918242845Sdelphij		return (B_FALSE);
1919242845Sdelphij	} else if (buf->b_data == NULL) {
1920242845Sdelphij		/*
1921242845Sdelphij		 * We have already been added to the arc eviction list;
1922242845Sdelphij		 * recommend eviction.
1923242845Sdelphij		 */
1924242845Sdelphij		ASSERT3P(hdr, ==, &arc_eviction_hdr);
1925242845Sdelphij		mutex_exit(&buf->b_evict_lock);
1926242845Sdelphij		return (B_TRUE);
1927242845Sdelphij	}
1928242845Sdelphij
1929242845Sdelphij	if (hdr->b_datacnt > 1 && hdr->b_type == ARC_BUFC_DATA)
1930242845Sdelphij		evict_needed = B_TRUE;
1931242845Sdelphij
1932242845Sdelphij	mutex_exit(&buf->b_evict_lock);
1933242845Sdelphij	return (evict_needed);
1934242845Sdelphij}
1935242845Sdelphij
1936242845Sdelphij/*
1937168404Spjd * Evict buffers from list until we've removed the specified number of
1938168404Spjd * bytes.  Move the removed buffers to the appropriate evict state.
1939168404Spjd * If the recycle flag is set, then attempt to "recycle" a buffer:
1940168404Spjd * - look for a buffer to evict that is `bytes' long.
1941168404Spjd * - return the data block from this buffer rather than freeing it.
1942168404Spjd * This flag is used by callers that are trying to make space for a
1943168404Spjd * new buffer in a full arc cache.
1944185029Spjd *
1945185029Spjd * This function makes a "best effort".  It skips over any buffers
1946185029Spjd * it can't get a hash_lock on, and so may not catch all candidates.
1947185029Spjd * It may also return without evicting as much space as requested.
1948168404Spjd */
1949168404Spjdstatic void *
1950209962Smmarc_evict(arc_state_t *state, uint64_t spa, int64_t bytes, boolean_t recycle,
1951168404Spjd    arc_buf_contents_t type)
1952168404Spjd{
1953168404Spjd	arc_state_t *evicted_state;
1954168404Spjd	uint64_t bytes_evicted = 0, skipped = 0, missed = 0;
1955205231Skmacy	int64_t bytes_remaining;
1956168404Spjd	arc_buf_hdr_t *ab, *ab_prev = NULL;
1957205231Skmacy	list_t *evicted_list, *list, *evicted_list_start, *list_start;
1958205231Skmacy	kmutex_t *lock, *evicted_lock;
1959168404Spjd	kmutex_t *hash_lock;
1960168404Spjd	boolean_t have_lock;
1961168404Spjd	void *stolen = NULL;
1962258632Savg	arc_buf_hdr_t marker = { 0 };
1963258632Savg	int count = 0;
1964205231Skmacy	static int evict_metadata_offset, evict_data_offset;
1965258632Savg	int i, idx, offset, list_count, lists;
1966168404Spjd
1967168404Spjd	ASSERT(state == arc_mru || state == arc_mfu);
1968168404Spjd
1969168404Spjd	evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
1970206796Spjd
1971205231Skmacy	if (type == ARC_BUFC_METADATA) {
1972205231Skmacy		offset = 0;
1973205231Skmacy		list_count = ARC_BUFC_NUMMETADATALISTS;
1974205231Skmacy		list_start = &state->arcs_lists[0];
1975205231Skmacy		evicted_list_start = &evicted_state->arcs_lists[0];
1976205231Skmacy		idx = evict_metadata_offset;
1977205231Skmacy	} else {
1978205231Skmacy		offset = ARC_BUFC_NUMMETADATALISTS;
1979205231Skmacy		list_start = &state->arcs_lists[offset];
1980205231Skmacy		evicted_list_start = &evicted_state->arcs_lists[offset];
1981205231Skmacy		list_count = ARC_BUFC_NUMDATALISTS;
1982205231Skmacy		idx = evict_data_offset;
1983205231Skmacy	}
1984205231Skmacy	bytes_remaining = evicted_state->arcs_lsize[type];
1985258632Savg	lists = 0;
1986206796Spjd
1987205231Skmacyevict_start:
1988205231Skmacy	list = &list_start[idx];
1989205231Skmacy	evicted_list = &evicted_list_start[idx];
1990205231Skmacy	lock = ARCS_LOCK(state, (offset + idx));
1991206796Spjd	evicted_lock = ARCS_LOCK(evicted_state, (offset + idx));
1992168404Spjd
1993205231Skmacy	mutex_enter(lock);
1994205231Skmacy	mutex_enter(evicted_lock);
1995205231Skmacy
1996185029Spjd	for (ab = list_tail(list); ab; ab = ab_prev) {
1997185029Spjd		ab_prev = list_prev(list, ab);
1998205231Skmacy		bytes_remaining -= (ab->b_size * ab->b_datacnt);
1999168404Spjd		/* prefetch buffers have a minimum lifespan */
2000168404Spjd		if (HDR_IO_IN_PROGRESS(ab) ||
2001185029Spjd		    (spa && ab->b_spa != spa) ||
2002168404Spjd		    (ab->b_flags & (ARC_PREFETCH|ARC_INDIRECT) &&
2003219089Spjd		    ddi_get_lbolt() - ab->b_arc_access <
2004219089Spjd		    arc_min_prefetch_lifespan)) {
2005168404Spjd			skipped++;
2006168404Spjd			continue;
2007168404Spjd		}
2008168404Spjd		/* "lookahead" for better eviction candidate */
2009168404Spjd		if (recycle && ab->b_size != bytes &&
2010168404Spjd		    ab_prev && ab_prev->b_size == bytes)
2011168404Spjd			continue;
2012258632Savg
2013258632Savg		/* ignore markers */
2014258632Savg		if (ab->b_spa == 0)
2015258632Savg			continue;
2016258632Savg
2017258632Savg		/*
2018258632Savg		 * It may take a long time to evict all the bufs requested.
2019258632Savg		 * To avoid blocking all arc activity, periodically drop
2020258632Savg		 * the arcs_mtx and give other threads a chance to run
2021258632Savg		 * before reacquiring the lock.
2022258632Savg		 *
2023258632Savg		 * If we are looking for a buffer to recycle, we are in
2024258632Savg		 * the hot code path, so don't sleep.
2025258632Savg		 */
2026258632Savg		if (!recycle && count++ > arc_evict_iterations) {
2027258632Savg			list_insert_after(list, ab, &marker);
2028258632Savg			mutex_exit(evicted_lock);
2029258632Savg			mutex_exit(lock);
2030258632Savg			kpreempt(KPREEMPT_SYNC);
2031258632Savg			mutex_enter(lock);
2032258632Savg			mutex_enter(evicted_lock);
2033258632Savg			ab_prev = list_prev(list, &marker);
2034258632Savg			list_remove(list, &marker);
2035258632Savg			count = 0;
2036258632Savg			continue;
2037258632Savg		}
2038258632Savg
2039168404Spjd		hash_lock = HDR_LOCK(ab);
2040168404Spjd		have_lock = MUTEX_HELD(hash_lock);
2041168404Spjd		if (have_lock || mutex_tryenter(hash_lock)) {
2042240415Smm			ASSERT0(refcount_count(&ab->b_refcnt));
2043168404Spjd			ASSERT(ab->b_datacnt > 0);
2044168404Spjd			while (ab->b_buf) {
2045168404Spjd				arc_buf_t *buf = ab->b_buf;
2046219089Spjd				if (!mutex_tryenter(&buf->b_evict_lock)) {
2047185029Spjd					missed += 1;
2048185029Spjd					break;
2049185029Spjd				}
2050168404Spjd				if (buf->b_data) {
2051168404Spjd					bytes_evicted += ab->b_size;
2052168404Spjd					if (recycle && ab->b_type == type &&
2053185029Spjd					    ab->b_size == bytes &&
2054185029Spjd					    !HDR_L2_WRITING(ab)) {
2055168404Spjd						stolen = buf->b_data;
2056168404Spjd						recycle = FALSE;
2057168404Spjd					}
2058168404Spjd				}
2059168404Spjd				if (buf->b_efunc) {
2060168404Spjd					mutex_enter(&arc_eviction_mtx);
2061168404Spjd					arc_buf_destroy(buf,
2062168404Spjd					    buf->b_data == stolen, FALSE);
2063168404Spjd					ab->b_buf = buf->b_next;
2064168404Spjd					buf->b_hdr = &arc_eviction_hdr;
2065168404Spjd					buf->b_next = arc_eviction_list;
2066168404Spjd					arc_eviction_list = buf;
2067168404Spjd					mutex_exit(&arc_eviction_mtx);
2068219089Spjd					mutex_exit(&buf->b_evict_lock);
2069168404Spjd				} else {
2070219089Spjd					mutex_exit(&buf->b_evict_lock);
2071168404Spjd					arc_buf_destroy(buf,
2072168404Spjd					    buf->b_data == stolen, TRUE);
2073168404Spjd				}
2074168404Spjd			}
2075208373Smm
2076208373Smm			if (ab->b_l2hdr) {
2077208373Smm				ARCSTAT_INCR(arcstat_evict_l2_cached,
2078208373Smm				    ab->b_size);
2079208373Smm			} else {
2080208373Smm				if (l2arc_write_eligible(ab->b_spa, ab)) {
2081208373Smm					ARCSTAT_INCR(arcstat_evict_l2_eligible,
2082208373Smm					    ab->b_size);
2083208373Smm				} else {
2084208373Smm					ARCSTAT_INCR(
2085208373Smm					    arcstat_evict_l2_ineligible,
2086208373Smm					    ab->b_size);
2087208373Smm				}
2088208373Smm			}
2089208373Smm
2090185029Spjd			if (ab->b_datacnt == 0) {
2091185029Spjd				arc_change_state(evicted_state, ab, hash_lock);
2092185029Spjd				ASSERT(HDR_IN_HASH_TABLE(ab));
2093185029Spjd				ab->b_flags |= ARC_IN_HASH_TABLE;
2094185029Spjd				ab->b_flags &= ~ARC_BUF_AVAILABLE;
2095185029Spjd				DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, ab);
2096185029Spjd			}
2097168404Spjd			if (!have_lock)
2098168404Spjd				mutex_exit(hash_lock);
2099168404Spjd			if (bytes >= 0 && bytes_evicted >= bytes)
2100168404Spjd				break;
2101205231Skmacy			if (bytes_remaining > 0) {
2102205231Skmacy				mutex_exit(evicted_lock);
2103205231Skmacy				mutex_exit(lock);
2104206796Spjd				idx  = ((idx + 1) & (list_count - 1));
2105258632Savg				lists++;
2106205231Skmacy				goto evict_start;
2107205231Skmacy			}
2108168404Spjd		} else {
2109168404Spjd			missed += 1;
2110168404Spjd		}
2111168404Spjd	}
2112168404Spjd
2113205231Skmacy	mutex_exit(evicted_lock);
2114205231Skmacy	mutex_exit(lock);
2115206796Spjd
2116206796Spjd	idx  = ((idx + 1) & (list_count - 1));
2117258632Savg	lists++;
2118168404Spjd
2119205231Skmacy	if (bytes_evicted < bytes) {
2120258632Savg		if (lists < list_count)
2121205231Skmacy			goto evict_start;
2122205231Skmacy		else
2123205231Skmacy			dprintf("only evicted %lld bytes from %x",
2124205231Skmacy			    (longlong_t)bytes_evicted, state);
2125205231Skmacy	}
2126206796Spjd	if (type == ARC_BUFC_METADATA)
2127205231Skmacy		evict_metadata_offset = idx;
2128205231Skmacy	else
2129205231Skmacy		evict_data_offset = idx;
2130206796Spjd
2131168404Spjd	if (skipped)
2132168404Spjd		ARCSTAT_INCR(arcstat_evict_skip, skipped);
2133168404Spjd
2134168404Spjd	if (missed)
2135168404Spjd		ARCSTAT_INCR(arcstat_mutex_miss, missed);
2136168404Spjd
2137185029Spjd	/*
2138258632Savg	 * Note: we have just evicted some data into the ghost state,
2139258632Savg	 * potentially putting the ghost size over the desired size.  Rather
2140258632Savg	 * that evicting from the ghost list in this hot code path, leave
2141258632Savg	 * this chore to the arc_reclaim_thread().
2142185029Spjd	 */
2143185029Spjd
2144205231Skmacy	if (stolen)
2145205231Skmacy		ARCSTAT_BUMP(arcstat_stolen);
2146168404Spjd	return (stolen);
2147168404Spjd}
2148168404Spjd
2149168404Spjd/*
2150168404Spjd * Remove buffers from list until we've removed the specified number of
2151168404Spjd * bytes.  Destroy the buffers that are removed.
2152168404Spjd */
2153168404Spjdstatic void
2154209962Smmarc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes)
2155168404Spjd{
2156168404Spjd	arc_buf_hdr_t *ab, *ab_prev;
2157219089Spjd	arc_buf_hdr_t marker = { 0 };
2158205231Skmacy	list_t *list, *list_start;
2159205231Skmacy	kmutex_t *hash_lock, *lock;
2160168404Spjd	uint64_t bytes_deleted = 0;
2161168404Spjd	uint64_t bufs_skipped = 0;
2162258632Savg	int count = 0;
2163205231Skmacy	static int evict_offset;
2164205231Skmacy	int list_count, idx = evict_offset;
2165258632Savg	int offset, lists = 0;
2166168404Spjd
2167168404Spjd	ASSERT(GHOST_STATE(state));
2168205231Skmacy
2169205231Skmacy	/*
2170205231Skmacy	 * data lists come after metadata lists
2171205231Skmacy	 */
2172205231Skmacy	list_start = &state->arcs_lists[ARC_BUFC_NUMMETADATALISTS];
2173205231Skmacy	list_count = ARC_BUFC_NUMDATALISTS;
2174205231Skmacy	offset = ARC_BUFC_NUMMETADATALISTS;
2175206796Spjd
2176205231Skmacyevict_start:
2177205231Skmacy	list = &list_start[idx];
2178205231Skmacy	lock = ARCS_LOCK(state, idx + offset);
2179205231Skmacy
2180205231Skmacy	mutex_enter(lock);
2181185029Spjd	for (ab = list_tail(list); ab; ab = ab_prev) {
2182185029Spjd		ab_prev = list_prev(list, ab);
2183258632Savg		if (ab->b_type > ARC_BUFC_NUMTYPES)
2184258632Savg			panic("invalid ab=%p", (void *)ab);
2185185029Spjd		if (spa && ab->b_spa != spa)
2186185029Spjd			continue;
2187219089Spjd
2188219089Spjd		/* ignore markers */
2189219089Spjd		if (ab->b_spa == 0)
2190219089Spjd			continue;
2191219089Spjd
2192168404Spjd		hash_lock = HDR_LOCK(ab);
2193219089Spjd		/* caller may be trying to modify this buffer, skip it */
2194219089Spjd		if (MUTEX_HELD(hash_lock))
2195219089Spjd			continue;
2196258632Savg
2197258632Savg		/*
2198258632Savg		 * It may take a long time to evict all the bufs requested.
2199258632Savg		 * To avoid blocking all arc activity, periodically drop
2200258632Savg		 * the arcs_mtx and give other threads a chance to run
2201258632Savg		 * before reacquiring the lock.
2202258632Savg		 */
2203258632Savg		if (count++ > arc_evict_iterations) {
2204258632Savg			list_insert_after(list, ab, &marker);
2205258632Savg			mutex_exit(lock);
2206258632Savg			kpreempt(KPREEMPT_SYNC);
2207258632Savg			mutex_enter(lock);
2208258632Savg			ab_prev = list_prev(list, &marker);
2209258632Savg			list_remove(list, &marker);
2210258632Savg			count = 0;
2211258632Savg			continue;
2212258632Savg		}
2213168404Spjd		if (mutex_tryenter(hash_lock)) {
2214168404Spjd			ASSERT(!HDR_IO_IN_PROGRESS(ab));
2215168404Spjd			ASSERT(ab->b_buf == NULL);
2216168404Spjd			ARCSTAT_BUMP(arcstat_deleted);
2217168404Spjd			bytes_deleted += ab->b_size;
2218185029Spjd
2219185029Spjd			if (ab->b_l2hdr != NULL) {
2220185029Spjd				/*
2221185029Spjd				 * This buffer is cached on the 2nd Level ARC;
2222185029Spjd				 * don't destroy the header.
2223185029Spjd				 */
2224185029Spjd				arc_change_state(arc_l2c_only, ab, hash_lock);
2225185029Spjd				mutex_exit(hash_lock);
2226185029Spjd			} else {
2227185029Spjd				arc_change_state(arc_anon, ab, hash_lock);
2228185029Spjd				mutex_exit(hash_lock);
2229185029Spjd				arc_hdr_destroy(ab);
2230185029Spjd			}
2231185029Spjd
2232168404Spjd			DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, ab);
2233168404Spjd			if (bytes >= 0 && bytes_deleted >= bytes)
2234168404Spjd				break;
2235219089Spjd		} else if (bytes < 0) {
2236219089Spjd			/*
2237219089Spjd			 * Insert a list marker and then wait for the
2238219089Spjd			 * hash lock to become available. Once its
2239219089Spjd			 * available, restart from where we left off.
2240219089Spjd			 */
2241219089Spjd			list_insert_after(list, ab, &marker);
2242219089Spjd			mutex_exit(lock);
2243219089Spjd			mutex_enter(hash_lock);
2244219089Spjd			mutex_exit(hash_lock);
2245219089Spjd			mutex_enter(lock);
2246219089Spjd			ab_prev = list_prev(list, &marker);
2247219089Spjd			list_remove(list, &marker);
2248258632Savg		} else {
2249168404Spjd			bufs_skipped += 1;
2250258632Savg		}
2251258632Savg
2252168404Spjd	}
2253205231Skmacy	mutex_exit(lock);
2254206796Spjd	idx  = ((idx + 1) & (ARC_BUFC_NUMDATALISTS - 1));
2255258632Savg	lists++;
2256206796Spjd
2257258632Savg	if (lists < list_count)
2258205231Skmacy		goto evict_start;
2259206796Spjd
2260205231Skmacy	evict_offset = idx;
2261205231Skmacy	if ((uintptr_t)list > (uintptr_t)&state->arcs_lists[ARC_BUFC_NUMMETADATALISTS] &&
2262185029Spjd	    (bytes < 0 || bytes_deleted < bytes)) {
2263205231Skmacy		list_start = &state->arcs_lists[0];
2264205231Skmacy		list_count = ARC_BUFC_NUMMETADATALISTS;
2265258632Savg		offset = lists = 0;
2266205231Skmacy		goto evict_start;
2267185029Spjd	}
2268185029Spjd
2269168404Spjd	if (bufs_skipped) {
2270168404Spjd		ARCSTAT_INCR(arcstat_mutex_miss, bufs_skipped);
2271168404Spjd		ASSERT(bytes >= 0);
2272168404Spjd	}
2273168404Spjd
2274168404Spjd	if (bytes_deleted < bytes)
2275168404Spjd		dprintf("only deleted %lld bytes from %p",
2276168404Spjd		    (longlong_t)bytes_deleted, state);
2277168404Spjd}
2278168404Spjd
2279168404Spjdstatic void
2280168404Spjdarc_adjust(void)
2281168404Spjd{
2282208373Smm	int64_t adjustment, delta;
2283168404Spjd
2284208373Smm	/*
2285208373Smm	 * Adjust MRU size
2286208373Smm	 */
2287168404Spjd
2288209275Smm	adjustment = MIN((int64_t)(arc_size - arc_c),
2289209275Smm	    (int64_t)(arc_anon->arcs_size + arc_mru->arcs_size + arc_meta_used -
2290209275Smm	    arc_p));
2291208373Smm
2292208373Smm	if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_DATA] > 0) {
2293208373Smm		delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_DATA], adjustment);
2294209962Smm		(void) arc_evict(arc_mru, 0, delta, FALSE, ARC_BUFC_DATA);
2295208373Smm		adjustment -= delta;
2296168404Spjd	}
2297168404Spjd
2298208373Smm	if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2299208373Smm		delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_METADATA], adjustment);
2300209962Smm		(void) arc_evict(arc_mru, 0, delta, FALSE,
2301185029Spjd		    ARC_BUFC_METADATA);
2302185029Spjd	}
2303185029Spjd
2304208373Smm	/*
2305208373Smm	 * Adjust MFU size
2306208373Smm	 */
2307168404Spjd
2308208373Smm	adjustment = arc_size - arc_c;
2309208373Smm
2310208373Smm	if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_DATA] > 0) {
2311208373Smm		delta = MIN(adjustment, arc_mfu->arcs_lsize[ARC_BUFC_DATA]);
2312209962Smm		(void) arc_evict(arc_mfu, 0, delta, FALSE, ARC_BUFC_DATA);
2313208373Smm		adjustment -= delta;
2314168404Spjd	}
2315168404Spjd
2316208373Smm	if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2317208373Smm		int64_t delta = MIN(adjustment,
2318208373Smm		    arc_mfu->arcs_lsize[ARC_BUFC_METADATA]);
2319209962Smm		(void) arc_evict(arc_mfu, 0, delta, FALSE,
2320208373Smm		    ARC_BUFC_METADATA);
2321208373Smm	}
2322168404Spjd
2323208373Smm	/*
2324208373Smm	 * Adjust ghost lists
2325208373Smm	 */
2326168404Spjd
2327208373Smm	adjustment = arc_mru->arcs_size + arc_mru_ghost->arcs_size - arc_c;
2328168404Spjd
2329208373Smm	if (adjustment > 0 && arc_mru_ghost->arcs_size > 0) {
2330208373Smm		delta = MIN(arc_mru_ghost->arcs_size, adjustment);
2331209962Smm		arc_evict_ghost(arc_mru_ghost, 0, delta);
2332208373Smm	}
2333185029Spjd
2334208373Smm	adjustment =
2335208373Smm	    arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size - arc_c;
2336208373Smm
2337208373Smm	if (adjustment > 0 && arc_mfu_ghost->arcs_size > 0) {
2338208373Smm		delta = MIN(arc_mfu_ghost->arcs_size, adjustment);
2339209962Smm		arc_evict_ghost(arc_mfu_ghost, 0, delta);
2340168404Spjd	}
2341168404Spjd}
2342168404Spjd
2343168404Spjdstatic void
2344168404Spjdarc_do_user_evicts(void)
2345168404Spjd{
2346191903Skmacy	static arc_buf_t *tmp_arc_eviction_list;
2347191903Skmacy
2348191903Skmacy	/*
2349191903Skmacy	 * Move list over to avoid LOR
2350191903Skmacy	 */
2351206796Spjdrestart:
2352168404Spjd	mutex_enter(&arc_eviction_mtx);
2353191903Skmacy	tmp_arc_eviction_list = arc_eviction_list;
2354191903Skmacy	arc_eviction_list = NULL;
2355191903Skmacy	mutex_exit(&arc_eviction_mtx);
2356191903Skmacy
2357191903Skmacy	while (tmp_arc_eviction_list != NULL) {
2358191903Skmacy		arc_buf_t *buf = tmp_arc_eviction_list;
2359191903Skmacy		tmp_arc_eviction_list = buf->b_next;
2360219089Spjd		mutex_enter(&buf->b_evict_lock);
2361168404Spjd		buf->b_hdr = NULL;
2362219089Spjd		mutex_exit(&buf->b_evict_lock);
2363168404Spjd
2364168404Spjd		if (buf->b_efunc != NULL)
2365268858Sdelphij			VERIFY0(buf->b_efunc(buf->b_private));
2366168404Spjd
2367168404Spjd		buf->b_efunc = NULL;
2368168404Spjd		buf->b_private = NULL;
2369168404Spjd		kmem_cache_free(buf_cache, buf);
2370168404Spjd	}
2371191903Skmacy
2372191903Skmacy	if (arc_eviction_list != NULL)
2373191903Skmacy		goto restart;
2374168404Spjd}
2375168404Spjd
2376168404Spjd/*
2377185029Spjd * Flush all *evictable* data from the cache for the given spa.
2378168404Spjd * NOTE: this will not touch "active" (i.e. referenced) data.
2379168404Spjd */
2380168404Spjdvoid
2381185029Spjdarc_flush(spa_t *spa)
2382168404Spjd{
2383209962Smm	uint64_t guid = 0;
2384209962Smm
2385209962Smm	if (spa)
2386228103Smm		guid = spa_load_guid(spa);
2387209962Smm
2388205231Skmacy	while (arc_mru->arcs_lsize[ARC_BUFC_DATA]) {
2389209962Smm		(void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_DATA);
2390185029Spjd		if (spa)
2391185029Spjd			break;
2392185029Spjd	}
2393205231Skmacy	while (arc_mru->arcs_lsize[ARC_BUFC_METADATA]) {
2394209962Smm		(void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_METADATA);
2395185029Spjd		if (spa)
2396185029Spjd			break;
2397185029Spjd	}
2398205231Skmacy	while (arc_mfu->arcs_lsize[ARC_BUFC_DATA]) {
2399209962Smm		(void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_DATA);
2400185029Spjd		if (spa)
2401185029Spjd			break;
2402185029Spjd	}
2403205231Skmacy	while (arc_mfu->arcs_lsize[ARC_BUFC_METADATA]) {
2404209962Smm		(void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_METADATA);
2405185029Spjd		if (spa)
2406185029Spjd			break;
2407185029Spjd	}
2408168404Spjd
2409209962Smm	arc_evict_ghost(arc_mru_ghost, guid, -1);
2410209962Smm	arc_evict_ghost(arc_mfu_ghost, guid, -1);
2411168404Spjd
2412168404Spjd	mutex_enter(&arc_reclaim_thr_lock);
2413168404Spjd	arc_do_user_evicts();
2414168404Spjd	mutex_exit(&arc_reclaim_thr_lock);
2415185029Spjd	ASSERT(spa || arc_eviction_list == NULL);
2416168404Spjd}
2417168404Spjd
2418168404Spjdvoid
2419168404Spjdarc_shrink(void)
2420168404Spjd{
2421168404Spjd	if (arc_c > arc_c_min) {
2422168404Spjd		uint64_t to_free;
2423168404Spjd
2424168404Spjd#ifdef _KERNEL
2425168404Spjd		to_free = arc_c >> arc_shrink_shift;
2426168404Spjd#else
2427168404Spjd		to_free = arc_c >> arc_shrink_shift;
2428168404Spjd#endif
2429168404Spjd		if (arc_c > arc_c_min + to_free)
2430168404Spjd			atomic_add_64(&arc_c, -to_free);
2431168404Spjd		else
2432168404Spjd			arc_c = arc_c_min;
2433168404Spjd
2434168404Spjd		atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
2435168404Spjd		if (arc_c > arc_size)
2436168404Spjd			arc_c = MAX(arc_size, arc_c_min);
2437168404Spjd		if (arc_p > arc_c)
2438168404Spjd			arc_p = (arc_c >> 1);
2439168404Spjd		ASSERT(arc_c >= arc_c_min);
2440168404Spjd		ASSERT((int64_t)arc_p >= 0);
2441168404Spjd	}
2442168404Spjd
2443168404Spjd	if (arc_size > arc_c)
2444168404Spjd		arc_adjust();
2445168404Spjd}
2446168404Spjd
2447185029Spjdstatic int needfree = 0;
2448168404Spjd
2449168404Spjdstatic int
2450168404Spjdarc_reclaim_needed(void)
2451168404Spjd{
2452168404Spjd
2453168404Spjd#ifdef _KERNEL
2454219089Spjd
2455197816Skmacy	if (needfree)
2456197816Skmacy		return (1);
2457168404Spjd
2458191902Skmacy	/*
2459212780Savg	 * Cooperate with pagedaemon when it's time for it to scan
2460212780Savg	 * and reclaim some pages.
2461191902Skmacy	 */
2462212783Savg	if (vm_paging_needed())
2463191902Skmacy		return (1);
2464191902Skmacy
2465219089Spjd#ifdef sun
2466168404Spjd	/*
2467185029Spjd	 * take 'desfree' extra pages, so we reclaim sooner, rather than later
2468185029Spjd	 */
2469185029Spjd	extra = desfree;
2470185029Spjd
2471185029Spjd	/*
2472185029Spjd	 * check that we're out of range of the pageout scanner.  It starts to
2473185029Spjd	 * schedule paging if freemem is less than lotsfree and needfree.
2474185029Spjd	 * lotsfree is the high-water mark for pageout, and needfree is the
2475185029Spjd	 * number of needed free pages.  We add extra pages here to make sure
2476185029Spjd	 * the scanner doesn't start up while we're freeing memory.
2477185029Spjd	 */
2478185029Spjd	if (freemem < lotsfree + needfree + extra)
2479185029Spjd		return (1);
2480185029Spjd
2481185029Spjd	/*
2482168404Spjd	 * check to make sure that swapfs has enough space so that anon
2483185029Spjd	 * reservations can still succeed. anon_resvmem() checks that the
2484168404Spjd	 * availrmem is greater than swapfs_minfree, and the number of reserved
2485168404Spjd	 * swap pages.  We also add a bit of extra here just to prevent
2486168404Spjd	 * circumstances from getting really dire.
2487168404Spjd	 */
2488168404Spjd	if (availrmem < swapfs_minfree + swapfs_reserve + extra)
2489168404Spjd		return (1);
2490168404Spjd
2491168404Spjd#if defined(__i386)
2492168404Spjd	/*
2493168404Spjd	 * If we're on an i386 platform, it's possible that we'll exhaust the
2494168404Spjd	 * kernel heap space before we ever run out of available physical
2495168404Spjd	 * memory.  Most checks of the size of the heap_area compare against
2496168404Spjd	 * tune.t_minarmem, which is the minimum available real memory that we
2497168404Spjd	 * can have in the system.  However, this is generally fixed at 25 pages
2498168404Spjd	 * which is so low that it's useless.  In this comparison, we seek to
2499168404Spjd	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
2500185029Spjd	 * heap is allocated.  (Or, in the calculation, if less than 1/4th is
2501168404Spjd	 * free)
2502168404Spjd	 */
2503168404Spjd	if (btop(vmem_size(heap_arena, VMEM_FREE)) <
2504168404Spjd	    (btop(vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC)) >> 2))
2505168404Spjd		return (1);
2506168404Spjd#endif
2507219089Spjd#else	/* !sun */
2508175633Spjd	if (kmem_used() > (kmem_size() * 3) / 4)
2509168404Spjd		return (1);
2510219089Spjd#endif	/* sun */
2511168404Spjd
2512168404Spjd#else
2513168404Spjd	if (spa_get_random(100) == 0)
2514168404Spjd		return (1);
2515168404Spjd#endif
2516168404Spjd	return (0);
2517168404Spjd}
2518168404Spjd
2519208454Spjdextern kmem_cache_t	*zio_buf_cache[];
2520208454Spjdextern kmem_cache_t	*zio_data_buf_cache[];
2521208454Spjd
2522168404Spjdstatic void
2523168404Spjdarc_kmem_reap_now(arc_reclaim_strategy_t strat)
2524168404Spjd{
2525168404Spjd	size_t			i;
2526168404Spjd	kmem_cache_t		*prev_cache = NULL;
2527168404Spjd	kmem_cache_t		*prev_data_cache = NULL;
2528168404Spjd
2529168404Spjd#ifdef _KERNEL
2530185029Spjd	if (arc_meta_used >= arc_meta_limit) {
2531185029Spjd		/*
2532185029Spjd		 * We are exceeding our meta-data cache limit.
2533185029Spjd		 * Purge some DNLC entries to release holds on meta-data.
2534185029Spjd		 */
2535185029Spjd		dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
2536185029Spjd	}
2537168404Spjd#if defined(__i386)
2538168404Spjd	/*
2539168404Spjd	 * Reclaim unused memory from all kmem caches.
2540168404Spjd	 */
2541168404Spjd	kmem_reap();
2542168404Spjd#endif
2543168404Spjd#endif
2544168404Spjd
2545168404Spjd	/*
2546185029Spjd	 * An aggressive reclamation will shrink the cache size as well as
2547168404Spjd	 * reap free buffers from the arc kmem caches.
2548168404Spjd	 */
2549168404Spjd	if (strat == ARC_RECLAIM_AGGR)
2550168404Spjd		arc_shrink();
2551168404Spjd
2552168404Spjd	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
2553168404Spjd		if (zio_buf_cache[i] != prev_cache) {
2554168404Spjd			prev_cache = zio_buf_cache[i];
2555168404Spjd			kmem_cache_reap_now(zio_buf_cache[i]);
2556168404Spjd		}
2557168404Spjd		if (zio_data_buf_cache[i] != prev_data_cache) {
2558168404Spjd			prev_data_cache = zio_data_buf_cache[i];
2559168404Spjd			kmem_cache_reap_now(zio_data_buf_cache[i]);
2560168404Spjd		}
2561168404Spjd	}
2562168404Spjd	kmem_cache_reap_now(buf_cache);
2563168404Spjd	kmem_cache_reap_now(hdr_cache);
2564168404Spjd}
2565168404Spjd
2566168404Spjdstatic void
2567168404Spjdarc_reclaim_thread(void *dummy __unused)
2568168404Spjd{
2569168404Spjd	clock_t			growtime = 0;
2570168404Spjd	arc_reclaim_strategy_t	last_reclaim = ARC_RECLAIM_CONS;
2571168404Spjd	callb_cpr_t		cpr;
2572168404Spjd
2573168404Spjd	CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
2574168404Spjd
2575168404Spjd	mutex_enter(&arc_reclaim_thr_lock);
2576168404Spjd	while (arc_thread_exit == 0) {
2577168404Spjd		if (arc_reclaim_needed()) {
2578168404Spjd
2579168404Spjd			if (arc_no_grow) {
2580168404Spjd				if (last_reclaim == ARC_RECLAIM_CONS) {
2581168404Spjd					last_reclaim = ARC_RECLAIM_AGGR;
2582168404Spjd				} else {
2583168404Spjd					last_reclaim = ARC_RECLAIM_CONS;
2584168404Spjd				}
2585168404Spjd			} else {
2586168404Spjd				arc_no_grow = TRUE;
2587168404Spjd				last_reclaim = ARC_RECLAIM_AGGR;
2588168404Spjd				membar_producer();
2589168404Spjd			}
2590168404Spjd
2591168404Spjd			/* reset the growth delay for every reclaim */
2592219089Spjd			growtime = ddi_get_lbolt() + (arc_grow_retry * hz);
2593168404Spjd
2594185029Spjd			if (needfree && last_reclaim == ARC_RECLAIM_CONS) {
2595168404Spjd				/*
2596185029Spjd				 * If needfree is TRUE our vm_lowmem hook
2597168404Spjd				 * was called and in that case we must free some
2598168404Spjd				 * memory, so switch to aggressive mode.
2599168404Spjd				 */
2600168404Spjd				arc_no_grow = TRUE;
2601168404Spjd				last_reclaim = ARC_RECLAIM_AGGR;
2602168404Spjd			}
2603168404Spjd			arc_kmem_reap_now(last_reclaim);
2604185029Spjd			arc_warm = B_TRUE;
2605185029Spjd
2606219089Spjd		} else if (arc_no_grow && ddi_get_lbolt() >= growtime) {
2607168404Spjd			arc_no_grow = FALSE;
2608168404Spjd		}
2609168404Spjd
2610209275Smm		arc_adjust();
2611168404Spjd
2612168404Spjd		if (arc_eviction_list != NULL)
2613168404Spjd			arc_do_user_evicts();
2614168404Spjd
2615211762Savg#ifdef _KERNEL
2616211762Savg		if (needfree) {
2617185029Spjd			needfree = 0;
2618185029Spjd			wakeup(&needfree);
2619211762Savg		}
2620168404Spjd#endif
2621168404Spjd
2622168404Spjd		/* block until needed, or one second, whichever is shorter */
2623168404Spjd		CALLB_CPR_SAFE_BEGIN(&cpr);
2624168404Spjd		(void) cv_timedwait(&arc_reclaim_thr_cv,
2625168404Spjd		    &arc_reclaim_thr_lock, hz);
2626168404Spjd		CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
2627168404Spjd	}
2628168404Spjd
2629168404Spjd	arc_thread_exit = 0;
2630168404Spjd	cv_broadcast(&arc_reclaim_thr_cv);
2631168404Spjd	CALLB_CPR_EXIT(&cpr);		/* drops arc_reclaim_thr_lock */
2632168404Spjd	thread_exit();
2633168404Spjd}
2634168404Spjd
2635168404Spjd/*
2636168404Spjd * Adapt arc info given the number of bytes we are trying to add and
2637168404Spjd * the state that we are comming from.  This function is only called
2638168404Spjd * when we are adding new content to the cache.
2639168404Spjd */
2640168404Spjdstatic void
2641168404Spjdarc_adapt(int bytes, arc_state_t *state)
2642168404Spjd{
2643168404Spjd	int mult;
2644208373Smm	uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
2645168404Spjd
2646185029Spjd	if (state == arc_l2c_only)
2647185029Spjd		return;
2648185029Spjd
2649168404Spjd	ASSERT(bytes > 0);
2650168404Spjd	/*
2651168404Spjd	 * Adapt the target size of the MRU list:
2652168404Spjd	 *	- if we just hit in the MRU ghost list, then increase
2653168404Spjd	 *	  the target size of the MRU list.
2654168404Spjd	 *	- if we just hit in the MFU ghost list, then increase
2655168404Spjd	 *	  the target size of the MFU list by decreasing the
2656168404Spjd	 *	  target size of the MRU list.
2657168404Spjd	 */
2658168404Spjd	if (state == arc_mru_ghost) {
2659168404Spjd		mult = ((arc_mru_ghost->arcs_size >= arc_mfu_ghost->arcs_size) ?
2660168404Spjd		    1 : (arc_mfu_ghost->arcs_size/arc_mru_ghost->arcs_size));
2661209275Smm		mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
2662168404Spjd
2663208373Smm		arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
2664168404Spjd	} else if (state == arc_mfu_ghost) {
2665208373Smm		uint64_t delta;
2666208373Smm
2667168404Spjd		mult = ((arc_mfu_ghost->arcs_size >= arc_mru_ghost->arcs_size) ?
2668168404Spjd		    1 : (arc_mru_ghost->arcs_size/arc_mfu_ghost->arcs_size));
2669209275Smm		mult = MIN(mult, 10);
2670168404Spjd
2671208373Smm		delta = MIN(bytes * mult, arc_p);
2672208373Smm		arc_p = MAX(arc_p_min, arc_p - delta);
2673168404Spjd	}
2674168404Spjd	ASSERT((int64_t)arc_p >= 0);
2675168404Spjd
2676168404Spjd	if (arc_reclaim_needed()) {
2677168404Spjd		cv_signal(&arc_reclaim_thr_cv);
2678168404Spjd		return;
2679168404Spjd	}
2680168404Spjd
2681168404Spjd	if (arc_no_grow)
2682168404Spjd		return;
2683168404Spjd
2684168404Spjd	if (arc_c >= arc_c_max)
2685168404Spjd		return;
2686168404Spjd
2687168404Spjd	/*
2688168404Spjd	 * If we're within (2 * maxblocksize) bytes of the target
2689168404Spjd	 * cache size, increment the target cache size
2690168404Spjd	 */
2691168404Spjd	if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
2692168404Spjd		atomic_add_64(&arc_c, (int64_t)bytes);
2693168404Spjd		if (arc_c > arc_c_max)
2694168404Spjd			arc_c = arc_c_max;
2695168404Spjd		else if (state == arc_anon)
2696168404Spjd			atomic_add_64(&arc_p, (int64_t)bytes);
2697168404Spjd		if (arc_p > arc_c)
2698168404Spjd			arc_p = arc_c;
2699168404Spjd	}
2700168404Spjd	ASSERT((int64_t)arc_p >= 0);
2701168404Spjd}
2702168404Spjd
2703168404Spjd/*
2704168404Spjd * Check if the cache has reached its limits and eviction is required
2705168404Spjd * prior to insert.
2706168404Spjd */
2707168404Spjdstatic int
2708185029Spjdarc_evict_needed(arc_buf_contents_t type)
2709168404Spjd{
2710185029Spjd	if (type == ARC_BUFC_METADATA && arc_meta_used >= arc_meta_limit)
2711185029Spjd		return (1);
2712185029Spjd
2713219089Spjd#ifdef sun
2714185029Spjd#ifdef _KERNEL
2715185029Spjd	/*
2716185029Spjd	 * If zio data pages are being allocated out of a separate heap segment,
2717185029Spjd	 * then enforce that the size of available vmem for this area remains
2718185029Spjd	 * above about 1/32nd free.
2719185029Spjd	 */
2720185029Spjd	if (type == ARC_BUFC_DATA && zio_arena != NULL &&
2721185029Spjd	    vmem_size(zio_arena, VMEM_FREE) <
2722185029Spjd	    (vmem_size(zio_arena, VMEM_ALLOC) >> 5))
2723185029Spjd		return (1);
2724185029Spjd#endif
2725219089Spjd#endif	/* sun */
2726185029Spjd
2727168404Spjd	if (arc_reclaim_needed())
2728168404Spjd		return (1);
2729168404Spjd
2730168404Spjd	return (arc_size > arc_c);
2731168404Spjd}
2732168404Spjd
2733168404Spjd/*
2734168404Spjd * The buffer, supplied as the first argument, needs a data block.
2735168404Spjd * So, if we are at cache max, determine which cache should be victimized.
2736168404Spjd * We have the following cases:
2737168404Spjd *
2738168404Spjd * 1. Insert for MRU, p > sizeof(arc_anon + arc_mru) ->
2739168404Spjd * In this situation if we're out of space, but the resident size of the MFU is
2740168404Spjd * under the limit, victimize the MFU cache to satisfy this insertion request.
2741168404Spjd *
2742168404Spjd * 2. Insert for MRU, p <= sizeof(arc_anon + arc_mru) ->
2743168404Spjd * Here, we've used up all of the available space for the MRU, so we need to
2744168404Spjd * evict from our own cache instead.  Evict from the set of resident MRU
2745168404Spjd * entries.
2746168404Spjd *
2747168404Spjd * 3. Insert for MFU (c - p) > sizeof(arc_mfu) ->
2748168404Spjd * c minus p represents the MFU space in the cache, since p is the size of the
2749168404Spjd * cache that is dedicated to the MRU.  In this situation there's still space on
2750168404Spjd * the MFU side, so the MRU side needs to be victimized.
2751168404Spjd *
2752168404Spjd * 4. Insert for MFU (c - p) < sizeof(arc_mfu) ->
2753168404Spjd * MFU's resident set is consuming more space than it has been allotted.  In
2754168404Spjd * this situation, we must victimize our own cache, the MFU, for this insertion.
2755168404Spjd */
2756168404Spjdstatic void
2757168404Spjdarc_get_data_buf(arc_buf_t *buf)
2758168404Spjd{
2759168404Spjd	arc_state_t		*state = buf->b_hdr->b_state;
2760168404Spjd	uint64_t		size = buf->b_hdr->b_size;
2761168404Spjd	arc_buf_contents_t	type = buf->b_hdr->b_type;
2762168404Spjd
2763168404Spjd	arc_adapt(size, state);
2764168404Spjd
2765168404Spjd	/*
2766168404Spjd	 * We have not yet reached cache maximum size,
2767168404Spjd	 * just allocate a new buffer.
2768168404Spjd	 */
2769185029Spjd	if (!arc_evict_needed(type)) {
2770168404Spjd		if (type == ARC_BUFC_METADATA) {
2771168404Spjd			buf->b_data = zio_buf_alloc(size);
2772208373Smm			arc_space_consume(size, ARC_SPACE_DATA);
2773168404Spjd		} else {
2774168404Spjd			ASSERT(type == ARC_BUFC_DATA);
2775168404Spjd			buf->b_data = zio_data_buf_alloc(size);
2776208373Smm			ARCSTAT_INCR(arcstat_data_size, size);
2777185029Spjd			atomic_add_64(&arc_size, size);
2778168404Spjd		}
2779168404Spjd		goto out;
2780168404Spjd	}
2781168404Spjd
2782168404Spjd	/*
2783168404Spjd	 * If we are prefetching from the mfu ghost list, this buffer
2784168404Spjd	 * will end up on the mru list; so steal space from there.
2785168404Spjd	 */
2786168404Spjd	if (state == arc_mfu_ghost)
2787168404Spjd		state = buf->b_hdr->b_flags & ARC_PREFETCH ? arc_mru : arc_mfu;
2788168404Spjd	else if (state == arc_mru_ghost)
2789168404Spjd		state = arc_mru;
2790168404Spjd
2791168404Spjd	if (state == arc_mru || state == arc_anon) {
2792168404Spjd		uint64_t mru_used = arc_anon->arcs_size + arc_mru->arcs_size;
2793208373Smm		state = (arc_mfu->arcs_lsize[type] >= size &&
2794185029Spjd		    arc_p > mru_used) ? arc_mfu : arc_mru;
2795168404Spjd	} else {
2796168404Spjd		/* MFU cases */
2797168404Spjd		uint64_t mfu_space = arc_c - arc_p;
2798208373Smm		state =  (arc_mru->arcs_lsize[type] >= size &&
2799185029Spjd		    mfu_space > arc_mfu->arcs_size) ? arc_mru : arc_mfu;
2800168404Spjd	}
2801209962Smm	if ((buf->b_data = arc_evict(state, 0, size, TRUE, type)) == NULL) {
2802168404Spjd		if (type == ARC_BUFC_METADATA) {
2803168404Spjd			buf->b_data = zio_buf_alloc(size);
2804208373Smm			arc_space_consume(size, ARC_SPACE_DATA);
2805168404Spjd		} else {
2806168404Spjd			ASSERT(type == ARC_BUFC_DATA);
2807168404Spjd			buf->b_data = zio_data_buf_alloc(size);
2808208373Smm			ARCSTAT_INCR(arcstat_data_size, size);
2809185029Spjd			atomic_add_64(&arc_size, size);
2810168404Spjd		}
2811168404Spjd		ARCSTAT_BUMP(arcstat_recycle_miss);
2812168404Spjd	}
2813168404Spjd	ASSERT(buf->b_data != NULL);
2814168404Spjdout:
2815168404Spjd	/*
2816168404Spjd	 * Update the state size.  Note that ghost states have a
2817168404Spjd	 * "ghost size" and so don't need to be updated.
2818168404Spjd	 */
2819168404Spjd	if (!GHOST_STATE(buf->b_hdr->b_state)) {
2820168404Spjd		arc_buf_hdr_t *hdr = buf->b_hdr;
2821168404Spjd
2822168404Spjd		atomic_add_64(&hdr->b_state->arcs_size, size);
2823168404Spjd		if (list_link_active(&hdr->b_arc_node)) {
2824168404Spjd			ASSERT(refcount_is_zero(&hdr->b_refcnt));
2825185029Spjd			atomic_add_64(&hdr->b_state->arcs_lsize[type], size);
2826168404Spjd		}
2827168404Spjd		/*
2828168404Spjd		 * If we are growing the cache, and we are adding anonymous
2829168404Spjd		 * data, and we have outgrown arc_p, update arc_p
2830168404Spjd		 */
2831168404Spjd		if (arc_size < arc_c && hdr->b_state == arc_anon &&
2832168404Spjd		    arc_anon->arcs_size + arc_mru->arcs_size > arc_p)
2833168404Spjd			arc_p = MIN(arc_c, arc_p + size);
2834168404Spjd	}
2835205231Skmacy	ARCSTAT_BUMP(arcstat_allocated);
2836168404Spjd}
2837168404Spjd
2838168404Spjd/*
2839168404Spjd * This routine is called whenever a buffer is accessed.
2840168404Spjd * NOTE: the hash lock is dropped in this function.
2841168404Spjd */
2842168404Spjdstatic void
2843168404Spjdarc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock)
2844168404Spjd{
2845219089Spjd	clock_t now;
2846219089Spjd
2847168404Spjd	ASSERT(MUTEX_HELD(hash_lock));
2848168404Spjd
2849168404Spjd	if (buf->b_state == arc_anon) {
2850168404Spjd		/*
2851168404Spjd		 * This buffer is not in the cache, and does not
2852168404Spjd		 * appear in our "ghost" list.  Add the new buffer
2853168404Spjd		 * to the MRU state.
2854168404Spjd		 */
2855168404Spjd
2856168404Spjd		ASSERT(buf->b_arc_access == 0);
2857219089Spjd		buf->b_arc_access = ddi_get_lbolt();
2858168404Spjd		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2859168404Spjd		arc_change_state(arc_mru, buf, hash_lock);
2860168404Spjd
2861168404Spjd	} else if (buf->b_state == arc_mru) {
2862219089Spjd		now = ddi_get_lbolt();
2863219089Spjd
2864168404Spjd		/*
2865168404Spjd		 * If this buffer is here because of a prefetch, then either:
2866168404Spjd		 * - clear the flag if this is a "referencing" read
2867168404Spjd		 *   (any subsequent access will bump this into the MFU state).
2868168404Spjd		 * or
2869168404Spjd		 * - move the buffer to the head of the list if this is
2870168404Spjd		 *   another prefetch (to make it less likely to be evicted).
2871168404Spjd		 */
2872168404Spjd		if ((buf->b_flags & ARC_PREFETCH) != 0) {
2873168404Spjd			if (refcount_count(&buf->b_refcnt) == 0) {
2874168404Spjd				ASSERT(list_link_active(&buf->b_arc_node));
2875168404Spjd			} else {
2876168404Spjd				buf->b_flags &= ~ARC_PREFETCH;
2877168404Spjd				ARCSTAT_BUMP(arcstat_mru_hits);
2878168404Spjd			}
2879219089Spjd			buf->b_arc_access = now;
2880168404Spjd			return;
2881168404Spjd		}
2882168404Spjd
2883168404Spjd		/*
2884168404Spjd		 * This buffer has been "accessed" only once so far,
2885168404Spjd		 * but it is still in the cache. Move it to the MFU
2886168404Spjd		 * state.
2887168404Spjd		 */
2888219089Spjd		if (now > buf->b_arc_access + ARC_MINTIME) {
2889168404Spjd			/*
2890168404Spjd			 * More than 125ms have passed since we
2891168404Spjd			 * instantiated this buffer.  Move it to the
2892168404Spjd			 * most frequently used state.
2893168404Spjd			 */
2894219089Spjd			buf->b_arc_access = now;
2895168404Spjd			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2896168404Spjd			arc_change_state(arc_mfu, buf, hash_lock);
2897168404Spjd		}
2898168404Spjd		ARCSTAT_BUMP(arcstat_mru_hits);
2899168404Spjd	} else if (buf->b_state == arc_mru_ghost) {
2900168404Spjd		arc_state_t	*new_state;
2901168404Spjd		/*
2902168404Spjd		 * This buffer has been "accessed" recently, but
2903168404Spjd		 * was evicted from the cache.  Move it to the
2904168404Spjd		 * MFU state.
2905168404Spjd		 */
2906168404Spjd
2907168404Spjd		if (buf->b_flags & ARC_PREFETCH) {
2908168404Spjd			new_state = arc_mru;
2909168404Spjd			if (refcount_count(&buf->b_refcnt) > 0)
2910168404Spjd				buf->b_flags &= ~ARC_PREFETCH;
2911168404Spjd			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2912168404Spjd		} else {
2913168404Spjd			new_state = arc_mfu;
2914168404Spjd			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2915168404Spjd		}
2916168404Spjd
2917219089Spjd		buf->b_arc_access = ddi_get_lbolt();
2918168404Spjd		arc_change_state(new_state, buf, hash_lock);
2919168404Spjd
2920168404Spjd		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
2921168404Spjd	} else if (buf->b_state == arc_mfu) {
2922168404Spjd		/*
2923168404Spjd		 * This buffer has been accessed more than once and is
2924168404Spjd		 * still in the cache.  Keep it in the MFU state.
2925168404Spjd		 *
2926168404Spjd		 * NOTE: an add_reference() that occurred when we did
2927168404Spjd		 * the arc_read() will have kicked this off the list.
2928168404Spjd		 * If it was a prefetch, we will explicitly move it to
2929168404Spjd		 * the head of the list now.
2930168404Spjd		 */
2931168404Spjd		if ((buf->b_flags & ARC_PREFETCH) != 0) {
2932168404Spjd			ASSERT(refcount_count(&buf->b_refcnt) == 0);
2933168404Spjd			ASSERT(list_link_active(&buf->b_arc_node));
2934168404Spjd		}
2935168404Spjd		ARCSTAT_BUMP(arcstat_mfu_hits);
2936219089Spjd		buf->b_arc_access = ddi_get_lbolt();
2937168404Spjd	} else if (buf->b_state == arc_mfu_ghost) {
2938168404Spjd		arc_state_t	*new_state = arc_mfu;
2939168404Spjd		/*
2940168404Spjd		 * This buffer has been accessed more than once but has
2941168404Spjd		 * been evicted from the cache.  Move it back to the
2942168404Spjd		 * MFU state.
2943168404Spjd		 */
2944168404Spjd
2945168404Spjd		if (buf->b_flags & ARC_PREFETCH) {
2946168404Spjd			/*
2947168404Spjd			 * This is a prefetch access...
2948168404Spjd			 * move this block back to the MRU state.
2949168404Spjd			 */
2950240415Smm			ASSERT0(refcount_count(&buf->b_refcnt));
2951168404Spjd			new_state = arc_mru;
2952168404Spjd		}
2953168404Spjd
2954219089Spjd		buf->b_arc_access = ddi_get_lbolt();
2955168404Spjd		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2956168404Spjd		arc_change_state(new_state, buf, hash_lock);
2957168404Spjd
2958168404Spjd		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
2959185029Spjd	} else if (buf->b_state == arc_l2c_only) {
2960185029Spjd		/*
2961185029Spjd		 * This buffer is on the 2nd Level ARC.
2962185029Spjd		 */
2963185029Spjd
2964219089Spjd		buf->b_arc_access = ddi_get_lbolt();
2965185029Spjd		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2966185029Spjd		arc_change_state(arc_mfu, buf, hash_lock);
2967168404Spjd	} else {
2968168404Spjd		ASSERT(!"invalid arc state");
2969168404Spjd	}
2970168404Spjd}
2971168404Spjd
2972168404Spjd/* a generic arc_done_func_t which you can use */
2973168404Spjd/* ARGSUSED */
2974168404Spjdvoid
2975168404Spjdarc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
2976168404Spjd{
2977219089Spjd	if (zio == NULL || zio->io_error == 0)
2978219089Spjd		bcopy(buf->b_data, arg, buf->b_hdr->b_size);
2979248571Smm	VERIFY(arc_buf_remove_ref(buf, arg));
2980168404Spjd}
2981168404Spjd
2982185029Spjd/* a generic arc_done_func_t */
2983168404Spjdvoid
2984168404Spjdarc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
2985168404Spjd{
2986168404Spjd	arc_buf_t **bufp = arg;
2987168404Spjd	if (zio && zio->io_error) {
2988248571Smm		VERIFY(arc_buf_remove_ref(buf, arg));
2989168404Spjd		*bufp = NULL;
2990168404Spjd	} else {
2991168404Spjd		*bufp = buf;
2992219089Spjd		ASSERT(buf->b_data);
2993168404Spjd	}
2994168404Spjd}
2995168404Spjd
2996168404Spjdstatic void
2997168404Spjdarc_read_done(zio_t *zio)
2998168404Spjd{
2999268075Sdelphij	arc_buf_hdr_t	*hdr;
3000168404Spjd	arc_buf_t	*buf;
3001168404Spjd	arc_buf_t	*abuf;	/* buffer we're assigning to callback */
3002268075Sdelphij	kmutex_t	*hash_lock = NULL;
3003168404Spjd	arc_callback_t	*callback_list, *acb;
3004168404Spjd	int		freeable = FALSE;
3005168404Spjd
3006168404Spjd	buf = zio->io_private;
3007168404Spjd	hdr = buf->b_hdr;
3008168404Spjd
3009168404Spjd	/*
3010168404Spjd	 * The hdr was inserted into hash-table and removed from lists
3011168404Spjd	 * prior to starting I/O.  We should find this header, since
3012168404Spjd	 * it's in the hash table, and it should be legit since it's
3013168404Spjd	 * not possible to evict it during the I/O.  The only possible
3014168404Spjd	 * reason for it not to be found is if we were freed during the
3015168404Spjd	 * read.
3016168404Spjd	 */
3017268075Sdelphij	if (HDR_IN_HASH_TABLE(hdr)) {
3018268075Sdelphij		ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
3019268075Sdelphij		ASSERT3U(hdr->b_dva.dva_word[0], ==,
3020268075Sdelphij		    BP_IDENTITY(zio->io_bp)->dva_word[0]);
3021268075Sdelphij		ASSERT3U(hdr->b_dva.dva_word[1], ==,
3022268075Sdelphij		    BP_IDENTITY(zio->io_bp)->dva_word[1]);
3023168404Spjd
3024268075Sdelphij		arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
3025268075Sdelphij		    &hash_lock);
3026168404Spjd
3027268075Sdelphij		ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) &&
3028268075Sdelphij		    hash_lock == NULL) ||
3029268075Sdelphij		    (found == hdr &&
3030268075Sdelphij		    DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
3031268075Sdelphij		    (found == hdr && HDR_L2_READING(hdr)));
3032268075Sdelphij	}
3033268075Sdelphij
3034185029Spjd	hdr->b_flags &= ~ARC_L2_EVICTED;
3035185029Spjd	if (l2arc_noprefetch && (hdr->b_flags & ARC_PREFETCH))
3036185029Spjd		hdr->b_flags &= ~ARC_L2CACHE;
3037206796Spjd
3038168404Spjd	/* byteswap if necessary */
3039168404Spjd	callback_list = hdr->b_acb;
3040168404Spjd	ASSERT(callback_list != NULL);
3041209101Smm	if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
3042236884Smm		dmu_object_byteswap_t bswap =
3043236884Smm		    DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
3044185029Spjd		arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
3045185029Spjd		    byteswap_uint64_array :
3046236884Smm		    dmu_ot_byteswap[bswap].ob_func;
3047185029Spjd		func(buf->b_data, hdr->b_size);
3048185029Spjd	}
3049168404Spjd
3050185029Spjd	arc_cksum_compute(buf, B_FALSE);
3051240133Smm#ifdef illumos
3052240133Smm	arc_buf_watch(buf);
3053240133Smm#endif /* illumos */
3054168404Spjd
3055219089Spjd	if (hash_lock && zio->io_error == 0 && hdr->b_state == arc_anon) {
3056219089Spjd		/*
3057219089Spjd		 * Only call arc_access on anonymous buffers.  This is because
3058219089Spjd		 * if we've issued an I/O for an evicted buffer, we've already
3059219089Spjd		 * called arc_access (to prevent any simultaneous readers from
3060219089Spjd		 * getting confused).
3061219089Spjd		 */
3062219089Spjd		arc_access(hdr, hash_lock);
3063219089Spjd	}
3064219089Spjd
3065168404Spjd	/* create copies of the data buffer for the callers */
3066168404Spjd	abuf = buf;
3067168404Spjd	for (acb = callback_list; acb; acb = acb->acb_next) {
3068168404Spjd		if (acb->acb_done) {
3069242845Sdelphij			if (abuf == NULL) {
3070242845Sdelphij				ARCSTAT_BUMP(arcstat_duplicate_reads);
3071168404Spjd				abuf = arc_buf_clone(buf);
3072242845Sdelphij			}
3073168404Spjd			acb->acb_buf = abuf;
3074168404Spjd			abuf = NULL;
3075168404Spjd		}
3076168404Spjd	}
3077168404Spjd	hdr->b_acb = NULL;
3078168404Spjd	hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3079168404Spjd	ASSERT(!HDR_BUF_AVAILABLE(hdr));
3080219089Spjd	if (abuf == buf) {
3081219089Spjd		ASSERT(buf->b_efunc == NULL);
3082219089Spjd		ASSERT(hdr->b_datacnt == 1);
3083168404Spjd		hdr->b_flags |= ARC_BUF_AVAILABLE;
3084219089Spjd	}
3085168404Spjd
3086168404Spjd	ASSERT(refcount_is_zero(&hdr->b_refcnt) || callback_list != NULL);
3087168404Spjd
3088168404Spjd	if (zio->io_error != 0) {
3089168404Spjd		hdr->b_flags |= ARC_IO_ERROR;
3090168404Spjd		if (hdr->b_state != arc_anon)
3091168404Spjd			arc_change_state(arc_anon, hdr, hash_lock);
3092168404Spjd		if (HDR_IN_HASH_TABLE(hdr))
3093168404Spjd			buf_hash_remove(hdr);
3094168404Spjd		freeable = refcount_is_zero(&hdr->b_refcnt);
3095168404Spjd	}
3096168404Spjd
3097168404Spjd	/*
3098168404Spjd	 * Broadcast before we drop the hash_lock to avoid the possibility
3099168404Spjd	 * that the hdr (and hence the cv) might be freed before we get to
3100168404Spjd	 * the cv_broadcast().
3101168404Spjd	 */
3102168404Spjd	cv_broadcast(&hdr->b_cv);
3103168404Spjd
3104168404Spjd	if (hash_lock) {
3105168404Spjd		mutex_exit(hash_lock);
3106168404Spjd	} else {
3107168404Spjd		/*
3108168404Spjd		 * This block was freed while we waited for the read to
3109168404Spjd		 * complete.  It has been removed from the hash table and
3110168404Spjd		 * moved to the anonymous state (so that it won't show up
3111168404Spjd		 * in the cache).
3112168404Spjd		 */
3113168404Spjd		ASSERT3P(hdr->b_state, ==, arc_anon);
3114168404Spjd		freeable = refcount_is_zero(&hdr->b_refcnt);
3115168404Spjd	}
3116168404Spjd
3117168404Spjd	/* execute each callback and free its structure */
3118168404Spjd	while ((acb = callback_list) != NULL) {
3119168404Spjd		if (acb->acb_done)
3120168404Spjd			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
3121168404Spjd
3122168404Spjd		if (acb->acb_zio_dummy != NULL) {
3123168404Spjd			acb->acb_zio_dummy->io_error = zio->io_error;
3124168404Spjd			zio_nowait(acb->acb_zio_dummy);
3125168404Spjd		}
3126168404Spjd
3127168404Spjd		callback_list = acb->acb_next;
3128168404Spjd		kmem_free(acb, sizeof (arc_callback_t));
3129168404Spjd	}
3130168404Spjd
3131168404Spjd	if (freeable)
3132168404Spjd		arc_hdr_destroy(hdr);
3133168404Spjd}
3134168404Spjd
3135168404Spjd/*
3136168404Spjd * "Read" the block block at the specified DVA (in bp) via the
3137168404Spjd * cache.  If the block is found in the cache, invoke the provided
3138168404Spjd * callback immediately and return.  Note that the `zio' parameter
3139168404Spjd * in the callback will be NULL in this case, since no IO was
3140168404Spjd * required.  If the block is not in the cache pass the read request
3141168404Spjd * on to the spa with a substitute callback function, so that the
3142168404Spjd * requested block will be added to the cache.
3143168404Spjd *
3144168404Spjd * If a read request arrives for a block that has a read in-progress,
3145168404Spjd * either wait for the in-progress read to complete (and return the
3146168404Spjd * results); or, if this is a read with a "done" func, add a record
3147168404Spjd * to the read to invoke the "done" func when the read completes,
3148168404Spjd * and return; or just return.
3149168404Spjd *
3150168404Spjd * arc_read_done() will invoke all the requested "done" functions
3151168404Spjd * for readers of this block.
3152168404Spjd */
3153168404Spjdint
3154246666Smmarc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
3155258632Savg    void *private, zio_priority_t priority, int zio_flags, uint32_t *arc_flags,
3156268123Sdelphij    const zbookmark_phys_t *zb)
3157168404Spjd{
3158268075Sdelphij	arc_buf_hdr_t *hdr = NULL;
3159247187Smm	arc_buf_t *buf = NULL;
3160268075Sdelphij	kmutex_t *hash_lock = NULL;
3161185029Spjd	zio_t *rzio;
3162228103Smm	uint64_t guid = spa_load_guid(spa);
3163168404Spjd
3164268075Sdelphij	ASSERT(!BP_IS_EMBEDDED(bp) ||
3165268075Sdelphij	    BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
3166268075Sdelphij
3167168404Spjdtop:
3168268075Sdelphij	if (!BP_IS_EMBEDDED(bp)) {
3169268075Sdelphij		/*
3170268075Sdelphij		 * Embedded BP's have no DVA and require no I/O to "read".
3171268075Sdelphij		 * Create an anonymous arc buf to back it.
3172268075Sdelphij		 */
3173268075Sdelphij		hdr = buf_hash_find(guid, bp, &hash_lock);
3174268075Sdelphij	}
3175168404Spjd
3176268075Sdelphij	if (hdr != NULL && hdr->b_datacnt > 0) {
3177268075Sdelphij
3178168404Spjd		*arc_flags |= ARC_CACHED;
3179168404Spjd
3180168404Spjd		if (HDR_IO_IN_PROGRESS(hdr)) {
3181168404Spjd
3182168404Spjd			if (*arc_flags & ARC_WAIT) {
3183168404Spjd				cv_wait(&hdr->b_cv, hash_lock);
3184168404Spjd				mutex_exit(hash_lock);
3185168404Spjd				goto top;
3186168404Spjd			}
3187168404Spjd			ASSERT(*arc_flags & ARC_NOWAIT);
3188168404Spjd
3189168404Spjd			if (done) {
3190168404Spjd				arc_callback_t	*acb = NULL;
3191168404Spjd
3192168404Spjd				acb = kmem_zalloc(sizeof (arc_callback_t),
3193168404Spjd				    KM_SLEEP);
3194168404Spjd				acb->acb_done = done;
3195168404Spjd				acb->acb_private = private;
3196168404Spjd				if (pio != NULL)
3197168404Spjd					acb->acb_zio_dummy = zio_null(pio,
3198209962Smm					    spa, NULL, NULL, NULL, zio_flags);
3199168404Spjd
3200168404Spjd				ASSERT(acb->acb_done != NULL);
3201168404Spjd				acb->acb_next = hdr->b_acb;
3202168404Spjd				hdr->b_acb = acb;
3203168404Spjd				add_reference(hdr, hash_lock, private);
3204168404Spjd				mutex_exit(hash_lock);
3205168404Spjd				return (0);
3206168404Spjd			}
3207168404Spjd			mutex_exit(hash_lock);
3208168404Spjd			return (0);
3209168404Spjd		}
3210168404Spjd
3211168404Spjd		ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3212168404Spjd
3213168404Spjd		if (done) {
3214168404Spjd			add_reference(hdr, hash_lock, private);
3215168404Spjd			/*
3216168404Spjd			 * If this block is already in use, create a new
3217168404Spjd			 * copy of the data so that we will be guaranteed
3218168404Spjd			 * that arc_release() will always succeed.
3219168404Spjd			 */
3220168404Spjd			buf = hdr->b_buf;
3221168404Spjd			ASSERT(buf);
3222168404Spjd			ASSERT(buf->b_data);
3223168404Spjd			if (HDR_BUF_AVAILABLE(hdr)) {
3224168404Spjd				ASSERT(buf->b_efunc == NULL);
3225168404Spjd				hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3226168404Spjd			} else {
3227168404Spjd				buf = arc_buf_clone(buf);
3228168404Spjd			}
3229219089Spjd
3230168404Spjd		} else if (*arc_flags & ARC_PREFETCH &&
3231168404Spjd		    refcount_count(&hdr->b_refcnt) == 0) {
3232168404Spjd			hdr->b_flags |= ARC_PREFETCH;
3233168404Spjd		}
3234168404Spjd		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
3235168404Spjd		arc_access(hdr, hash_lock);
3236185029Spjd		if (*arc_flags & ARC_L2CACHE)
3237185029Spjd			hdr->b_flags |= ARC_L2CACHE;
3238251478Sdelphij		if (*arc_flags & ARC_L2COMPRESS)
3239251478Sdelphij			hdr->b_flags |= ARC_L2COMPRESS;
3240168404Spjd		mutex_exit(hash_lock);
3241168404Spjd		ARCSTAT_BUMP(arcstat_hits);
3242168404Spjd		ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
3243168404Spjd		    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3244168404Spjd		    data, metadata, hits);
3245168404Spjd
3246168404Spjd		if (done)
3247168404Spjd			done(NULL, buf, private);
3248168404Spjd	} else {
3249168404Spjd		uint64_t size = BP_GET_LSIZE(bp);
3250268075Sdelphij		arc_callback_t *acb;
3251185029Spjd		vdev_t *vd = NULL;
3252247187Smm		uint64_t addr = 0;
3253208373Smm		boolean_t devw = B_FALSE;
3254258389Savg		enum zio_compress b_compress = ZIO_COMPRESS_OFF;
3255258389Savg		uint64_t b_asize = 0;
3256168404Spjd
3257168404Spjd		if (hdr == NULL) {
3258168404Spjd			/* this block is not in the cache */
3259268075Sdelphij			arc_buf_hdr_t *exists = NULL;
3260168404Spjd			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
3261168404Spjd			buf = arc_buf_alloc(spa, size, private, type);
3262168404Spjd			hdr = buf->b_hdr;
3263268075Sdelphij			if (!BP_IS_EMBEDDED(bp)) {
3264268075Sdelphij				hdr->b_dva = *BP_IDENTITY(bp);
3265268075Sdelphij				hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
3266268075Sdelphij				hdr->b_cksum0 = bp->blk_cksum.zc_word[0];
3267268075Sdelphij				exists = buf_hash_insert(hdr, &hash_lock);
3268268075Sdelphij			}
3269268075Sdelphij			if (exists != NULL) {
3270168404Spjd				/* somebody beat us to the hash insert */
3271168404Spjd				mutex_exit(hash_lock);
3272219089Spjd				buf_discard_identity(hdr);
3273168404Spjd				(void) arc_buf_remove_ref(buf, private);
3274168404Spjd				goto top; /* restart the IO request */
3275168404Spjd			}
3276168404Spjd			/* if this is a prefetch, we don't have a reference */
3277168404Spjd			if (*arc_flags & ARC_PREFETCH) {
3278168404Spjd				(void) remove_reference(hdr, hash_lock,
3279168404Spjd				    private);
3280168404Spjd				hdr->b_flags |= ARC_PREFETCH;
3281168404Spjd			}
3282185029Spjd			if (*arc_flags & ARC_L2CACHE)
3283185029Spjd				hdr->b_flags |= ARC_L2CACHE;
3284251478Sdelphij			if (*arc_flags & ARC_L2COMPRESS)
3285251478Sdelphij				hdr->b_flags |= ARC_L2COMPRESS;
3286168404Spjd			if (BP_GET_LEVEL(bp) > 0)
3287168404Spjd				hdr->b_flags |= ARC_INDIRECT;
3288168404Spjd		} else {
3289168404Spjd			/* this block is in the ghost cache */
3290168404Spjd			ASSERT(GHOST_STATE(hdr->b_state));
3291168404Spjd			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3292240415Smm			ASSERT0(refcount_count(&hdr->b_refcnt));
3293168404Spjd			ASSERT(hdr->b_buf == NULL);
3294168404Spjd
3295168404Spjd			/* if this is a prefetch, we don't have a reference */
3296168404Spjd			if (*arc_flags & ARC_PREFETCH)
3297168404Spjd				hdr->b_flags |= ARC_PREFETCH;
3298168404Spjd			else
3299168404Spjd				add_reference(hdr, hash_lock, private);
3300185029Spjd			if (*arc_flags & ARC_L2CACHE)
3301185029Spjd				hdr->b_flags |= ARC_L2CACHE;
3302251478Sdelphij			if (*arc_flags & ARC_L2COMPRESS)
3303251478Sdelphij				hdr->b_flags |= ARC_L2COMPRESS;
3304185029Spjd			buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
3305168404Spjd			buf->b_hdr = hdr;
3306168404Spjd			buf->b_data = NULL;
3307168404Spjd			buf->b_efunc = NULL;
3308168404Spjd			buf->b_private = NULL;
3309168404Spjd			buf->b_next = NULL;
3310168404Spjd			hdr->b_buf = buf;
3311168404Spjd			ASSERT(hdr->b_datacnt == 0);
3312168404Spjd			hdr->b_datacnt = 1;
3313219089Spjd			arc_get_data_buf(buf);
3314219089Spjd			arc_access(hdr, hash_lock);
3315168404Spjd		}
3316168404Spjd
3317219089Spjd		ASSERT(!GHOST_STATE(hdr->b_state));
3318219089Spjd
3319168404Spjd		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
3320168404Spjd		acb->acb_done = done;
3321168404Spjd		acb->acb_private = private;
3322168404Spjd
3323168404Spjd		ASSERT(hdr->b_acb == NULL);
3324168404Spjd		hdr->b_acb = acb;
3325168404Spjd		hdr->b_flags |= ARC_IO_IN_PROGRESS;
3326168404Spjd
3327258389Savg		if (hdr->b_l2hdr != NULL &&
3328185029Spjd		    (vd = hdr->b_l2hdr->b_dev->l2ad_vdev) != NULL) {
3329208373Smm			devw = hdr->b_l2hdr->b_dev->l2ad_writing;
3330185029Spjd			addr = hdr->b_l2hdr->b_daddr;
3331258389Savg			b_compress = hdr->b_l2hdr->b_compress;
3332258389Savg			b_asize = hdr->b_l2hdr->b_asize;
3333185029Spjd			/*
3334185029Spjd			 * Lock out device removal.
3335185029Spjd			 */
3336185029Spjd			if (vdev_is_dead(vd) ||
3337185029Spjd			    !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
3338185029Spjd				vd = NULL;
3339185029Spjd		}
3340185029Spjd
3341268075Sdelphij		if (hash_lock != NULL)
3342268075Sdelphij			mutex_exit(hash_lock);
3343168404Spjd
3344251629Sdelphij		/*
3345251629Sdelphij		 * At this point, we have a level 1 cache miss.  Try again in
3346251629Sdelphij		 * L2ARC if possible.
3347251629Sdelphij		 */
3348168404Spjd		ASSERT3U(hdr->b_size, ==, size);
3349219089Spjd		DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
3350268123Sdelphij		    uint64_t, size, zbookmark_phys_t *, zb);
3351168404Spjd		ARCSTAT_BUMP(arcstat_misses);
3352168404Spjd		ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
3353168404Spjd		    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3354168404Spjd		    data, metadata, misses);
3355228392Spjd#ifdef _KERNEL
3356228392Spjd		curthread->td_ru.ru_inblock++;
3357228392Spjd#endif
3358168404Spjd
3359208373Smm		if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
3360185029Spjd			/*
3361185029Spjd			 * Read from the L2ARC if the following are true:
3362185029Spjd			 * 1. The L2ARC vdev was previously cached.
3363185029Spjd			 * 2. This buffer still has L2ARC metadata.
3364185029Spjd			 * 3. This buffer isn't currently writing to the L2ARC.
3365185029Spjd			 * 4. The L2ARC entry wasn't evicted, which may
3366185029Spjd			 *    also have invalidated the vdev.
3367208373Smm			 * 5. This isn't prefetch and l2arc_noprefetch is set.
3368185029Spjd			 */
3369185029Spjd			if (hdr->b_l2hdr != NULL &&
3370208373Smm			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
3371208373Smm			    !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
3372185029Spjd				l2arc_read_callback_t *cb;
3373185029Spjd
3374185029Spjd				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
3375185029Spjd				ARCSTAT_BUMP(arcstat_l2_hits);
3376185029Spjd
3377185029Spjd				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
3378185029Spjd				    KM_SLEEP);
3379185029Spjd				cb->l2rcb_buf = buf;
3380185029Spjd				cb->l2rcb_spa = spa;
3381185029Spjd				cb->l2rcb_bp = *bp;
3382185029Spjd				cb->l2rcb_zb = *zb;
3383185029Spjd				cb->l2rcb_flags = zio_flags;
3384258389Savg				cb->l2rcb_compress = b_compress;
3385185029Spjd
3386247187Smm				ASSERT(addr >= VDEV_LABEL_START_SIZE &&
3387247187Smm				    addr + size < vd->vdev_psize -
3388247187Smm				    VDEV_LABEL_END_SIZE);
3389247187Smm
3390185029Spjd				/*
3391185029Spjd				 * l2arc read.  The SCL_L2ARC lock will be
3392185029Spjd				 * released by l2arc_read_done().
3393251478Sdelphij				 * Issue a null zio if the underlying buffer
3394251478Sdelphij				 * was squashed to zero size by compression.
3395185029Spjd				 */
3396258389Savg				if (b_compress == ZIO_COMPRESS_EMPTY) {
3397251478Sdelphij					rzio = zio_null(pio, spa, vd,
3398251478Sdelphij					    l2arc_read_done, cb,
3399251478Sdelphij					    zio_flags | ZIO_FLAG_DONT_CACHE |
3400251478Sdelphij					    ZIO_FLAG_CANFAIL |
3401251478Sdelphij					    ZIO_FLAG_DONT_PROPAGATE |
3402251478Sdelphij					    ZIO_FLAG_DONT_RETRY);
3403251478Sdelphij				} else {
3404251478Sdelphij					rzio = zio_read_phys(pio, vd, addr,
3405258389Savg					    b_asize, buf->b_data,
3406258389Savg					    ZIO_CHECKSUM_OFF,
3407251478Sdelphij					    l2arc_read_done, cb, priority,
3408251478Sdelphij					    zio_flags | ZIO_FLAG_DONT_CACHE |
3409251478Sdelphij					    ZIO_FLAG_CANFAIL |
3410251478Sdelphij					    ZIO_FLAG_DONT_PROPAGATE |
3411251478Sdelphij					    ZIO_FLAG_DONT_RETRY, B_FALSE);
3412251478Sdelphij				}
3413185029Spjd				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
3414185029Spjd				    zio_t *, rzio);
3415258389Savg				ARCSTAT_INCR(arcstat_l2_read_bytes, b_asize);
3416185029Spjd
3417185029Spjd				if (*arc_flags & ARC_NOWAIT) {
3418185029Spjd					zio_nowait(rzio);
3419185029Spjd					return (0);
3420185029Spjd				}
3421185029Spjd
3422185029Spjd				ASSERT(*arc_flags & ARC_WAIT);
3423185029Spjd				if (zio_wait(rzio) == 0)
3424185029Spjd					return (0);
3425185029Spjd
3426185029Spjd				/* l2arc read error; goto zio_read() */
3427185029Spjd			} else {
3428185029Spjd				DTRACE_PROBE1(l2arc__miss,
3429185029Spjd				    arc_buf_hdr_t *, hdr);
3430185029Spjd				ARCSTAT_BUMP(arcstat_l2_misses);
3431185029Spjd				if (HDR_L2_WRITING(hdr))
3432185029Spjd					ARCSTAT_BUMP(arcstat_l2_rw_clash);
3433185029Spjd				spa_config_exit(spa, SCL_L2ARC, vd);
3434185029Spjd			}
3435208373Smm		} else {
3436208373Smm			if (vd != NULL)
3437208373Smm				spa_config_exit(spa, SCL_L2ARC, vd);
3438208373Smm			if (l2arc_ndev != 0) {
3439208373Smm				DTRACE_PROBE1(l2arc__miss,
3440208373Smm				    arc_buf_hdr_t *, hdr);
3441208373Smm				ARCSTAT_BUMP(arcstat_l2_misses);
3442208373Smm			}
3443185029Spjd		}
3444185029Spjd
3445168404Spjd		rzio = zio_read(pio, spa, bp, buf->b_data, size,
3446185029Spjd		    arc_read_done, buf, priority, zio_flags, zb);
3447168404Spjd
3448168404Spjd		if (*arc_flags & ARC_WAIT)
3449168404Spjd			return (zio_wait(rzio));
3450168404Spjd
3451168404Spjd		ASSERT(*arc_flags & ARC_NOWAIT);
3452168404Spjd		zio_nowait(rzio);
3453168404Spjd	}
3454168404Spjd	return (0);
3455168404Spjd}
3456168404Spjd
3457168404Spjdvoid
3458168404Spjdarc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
3459168404Spjd{
3460168404Spjd	ASSERT(buf->b_hdr != NULL);
3461168404Spjd	ASSERT(buf->b_hdr->b_state != arc_anon);
3462168404Spjd	ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt) || func == NULL);
3463219089Spjd	ASSERT(buf->b_efunc == NULL);
3464219089Spjd	ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
3465219089Spjd
3466168404Spjd	buf->b_efunc = func;
3467168404Spjd	buf->b_private = private;
3468168404Spjd}
3469168404Spjd
3470168404Spjd/*
3471251520Sdelphij * Notify the arc that a block was freed, and thus will never be used again.
3472251520Sdelphij */
3473251520Sdelphijvoid
3474251520Sdelphijarc_freed(spa_t *spa, const blkptr_t *bp)
3475251520Sdelphij{
3476251520Sdelphij	arc_buf_hdr_t *hdr;
3477251520Sdelphij	kmutex_t *hash_lock;
3478251520Sdelphij	uint64_t guid = spa_load_guid(spa);
3479251520Sdelphij
3480268075Sdelphij	ASSERT(!BP_IS_EMBEDDED(bp));
3481268075Sdelphij
3482268075Sdelphij	hdr = buf_hash_find(guid, bp, &hash_lock);
3483251520Sdelphij	if (hdr == NULL)
3484251520Sdelphij		return;
3485251520Sdelphij	if (HDR_BUF_AVAILABLE(hdr)) {
3486251520Sdelphij		arc_buf_t *buf = hdr->b_buf;
3487251520Sdelphij		add_reference(hdr, hash_lock, FTAG);
3488251520Sdelphij		hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3489251520Sdelphij		mutex_exit(hash_lock);
3490251520Sdelphij
3491251520Sdelphij		arc_release(buf, FTAG);
3492251520Sdelphij		(void) arc_buf_remove_ref(buf, FTAG);
3493251520Sdelphij	} else {
3494251520Sdelphij		mutex_exit(hash_lock);
3495251520Sdelphij	}
3496251520Sdelphij
3497251520Sdelphij}
3498251520Sdelphij
3499251520Sdelphij/*
3500268858Sdelphij * Clear the user eviction callback set by arc_set_callback(), first calling
3501268858Sdelphij * it if it exists.  Because the presence of a callback keeps an arc_buf cached
3502268858Sdelphij * clearing the callback may result in the arc_buf being destroyed.  However,
3503268858Sdelphij * it will not result in the *last* arc_buf being destroyed, hence the data
3504268858Sdelphij * will remain cached in the ARC. We make a copy of the arc buffer here so
3505268858Sdelphij * that we can process the callback without holding any locks.
3506268858Sdelphij *
3507268858Sdelphij * It's possible that the callback is already in the process of being cleared
3508268858Sdelphij * by another thread.  In this case we can not clear the callback.
3509268858Sdelphij *
3510268858Sdelphij * Returns B_TRUE if the callback was successfully called and cleared.
3511168404Spjd */
3512268858Sdelphijboolean_t
3513268858Sdelphijarc_clear_callback(arc_buf_t *buf)
3514168404Spjd{
3515168404Spjd	arc_buf_hdr_t *hdr;
3516168404Spjd	kmutex_t *hash_lock;
3517268858Sdelphij	arc_evict_func_t *efunc = buf->b_efunc;
3518268858Sdelphij	void *private = buf->b_private;
3519205231Skmacy	list_t *list, *evicted_list;
3520205231Skmacy	kmutex_t *lock, *evicted_lock;
3521206796Spjd
3522219089Spjd	mutex_enter(&buf->b_evict_lock);
3523168404Spjd	hdr = buf->b_hdr;
3524168404Spjd	if (hdr == NULL) {
3525168404Spjd		/*
3526168404Spjd		 * We are in arc_do_user_evicts().
3527168404Spjd		 */
3528168404Spjd		ASSERT(buf->b_data == NULL);
3529219089Spjd		mutex_exit(&buf->b_evict_lock);
3530268858Sdelphij		return (B_FALSE);
3531185029Spjd	} else if (buf->b_data == NULL) {
3532185029Spjd		/*
3533185029Spjd		 * We are on the eviction list; process this buffer now
3534185029Spjd		 * but let arc_do_user_evicts() do the reaping.
3535185029Spjd		 */
3536185029Spjd		buf->b_efunc = NULL;
3537219089Spjd		mutex_exit(&buf->b_evict_lock);
3538268858Sdelphij		VERIFY0(efunc(private));
3539268858Sdelphij		return (B_TRUE);
3540168404Spjd	}
3541168404Spjd	hash_lock = HDR_LOCK(hdr);
3542168404Spjd	mutex_enter(hash_lock);
3543219089Spjd	hdr = buf->b_hdr;
3544219089Spjd	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3545168404Spjd
3546168404Spjd	ASSERT3U(refcount_count(&hdr->b_refcnt), <, hdr->b_datacnt);
3547168404Spjd	ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3548168404Spjd
3549268858Sdelphij	buf->b_efunc = NULL;
3550268858Sdelphij	buf->b_private = NULL;
3551168404Spjd
3552268858Sdelphij	if (hdr->b_datacnt > 1) {
3553268858Sdelphij		mutex_exit(&buf->b_evict_lock);
3554268858Sdelphij		arc_buf_destroy(buf, FALSE, TRUE);
3555268858Sdelphij	} else {
3556268858Sdelphij		ASSERT(buf == hdr->b_buf);
3557268858Sdelphij		hdr->b_flags |= ARC_BUF_AVAILABLE;
3558268858Sdelphij		mutex_exit(&buf->b_evict_lock);
3559268858Sdelphij	}
3560168404Spjd
3561168404Spjd	mutex_exit(hash_lock);
3562268858Sdelphij	VERIFY0(efunc(private));
3563268858Sdelphij	return (B_TRUE);
3564168404Spjd}
3565168404Spjd
3566168404Spjd/*
3567251629Sdelphij * Release this buffer from the cache, making it an anonymous buffer.  This
3568251629Sdelphij * must be done after a read and prior to modifying the buffer contents.
3569168404Spjd * If the buffer has more than one reference, we must make
3570185029Spjd * a new hdr for the buffer.
3571168404Spjd */
3572168404Spjdvoid
3573168404Spjdarc_release(arc_buf_t *buf, void *tag)
3574168404Spjd{
3575185029Spjd	arc_buf_hdr_t *hdr;
3576219089Spjd	kmutex_t *hash_lock = NULL;
3577185029Spjd	l2arc_buf_hdr_t *l2hdr;
3578185029Spjd	uint64_t buf_size;
3579168404Spjd
3580219089Spjd	/*
3581219089Spjd	 * It would be nice to assert that if it's DMU metadata (level >
3582219089Spjd	 * 0 || it's the dnode file), then it must be syncing context.
3583219089Spjd	 * But we don't know that information at this level.
3584219089Spjd	 */
3585219089Spjd
3586219089Spjd	mutex_enter(&buf->b_evict_lock);
3587185029Spjd	hdr = buf->b_hdr;
3588185029Spjd
3589168404Spjd	/* this buffer is not on any list */
3590168404Spjd	ASSERT(refcount_count(&hdr->b_refcnt) > 0);
3591168404Spjd
3592168404Spjd	if (hdr->b_state == arc_anon) {
3593168404Spjd		/* this buffer is already released */
3594168404Spjd		ASSERT(buf->b_efunc == NULL);
3595208373Smm	} else {
3596208373Smm		hash_lock = HDR_LOCK(hdr);
3597208373Smm		mutex_enter(hash_lock);
3598219089Spjd		hdr = buf->b_hdr;
3599219089Spjd		ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3600168404Spjd	}
3601168404Spjd
3602185029Spjd	l2hdr = hdr->b_l2hdr;
3603185029Spjd	if (l2hdr) {
3604185029Spjd		mutex_enter(&l2arc_buflist_mtx);
3605185029Spjd		hdr->b_l2hdr = NULL;
3606258388Savg		list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
3607185029Spjd	}
3608247187Smm	buf_size = hdr->b_size;
3609185029Spjd
3610168404Spjd	/*
3611168404Spjd	 * Do we have more than one buf?
3612168404Spjd	 */
3613185029Spjd	if (hdr->b_datacnt > 1) {
3614168404Spjd		arc_buf_hdr_t *nhdr;
3615168404Spjd		arc_buf_t **bufp;
3616168404Spjd		uint64_t blksz = hdr->b_size;
3617209962Smm		uint64_t spa = hdr->b_spa;
3618168404Spjd		arc_buf_contents_t type = hdr->b_type;
3619185029Spjd		uint32_t flags = hdr->b_flags;
3620168404Spjd
3621185029Spjd		ASSERT(hdr->b_buf != buf || buf->b_next != NULL);
3622168404Spjd		/*
3623219089Spjd		 * Pull the data off of this hdr and attach it to
3624219089Spjd		 * a new anonymous hdr.
3625168404Spjd		 */
3626168404Spjd		(void) remove_reference(hdr, hash_lock, tag);
3627168404Spjd		bufp = &hdr->b_buf;
3628168404Spjd		while (*bufp != buf)
3629168404Spjd			bufp = &(*bufp)->b_next;
3630219089Spjd		*bufp = buf->b_next;
3631168404Spjd		buf->b_next = NULL;
3632168404Spjd
3633168404Spjd		ASSERT3U(hdr->b_state->arcs_size, >=, hdr->b_size);
3634168404Spjd		atomic_add_64(&hdr->b_state->arcs_size, -hdr->b_size);
3635168404Spjd		if (refcount_is_zero(&hdr->b_refcnt)) {
3636185029Spjd			uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
3637185029Spjd			ASSERT3U(*size, >=, hdr->b_size);
3638185029Spjd			atomic_add_64(size, -hdr->b_size);
3639168404Spjd		}
3640242845Sdelphij
3641242845Sdelphij		/*
3642242845Sdelphij		 * We're releasing a duplicate user data buffer, update
3643242845Sdelphij		 * our statistics accordingly.
3644242845Sdelphij		 */
3645242845Sdelphij		if (hdr->b_type == ARC_BUFC_DATA) {
3646242845Sdelphij			ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
3647242845Sdelphij			ARCSTAT_INCR(arcstat_duplicate_buffers_size,
3648242845Sdelphij			    -hdr->b_size);
3649242845Sdelphij		}
3650168404Spjd		hdr->b_datacnt -= 1;
3651168404Spjd		arc_cksum_verify(buf);
3652240133Smm#ifdef illumos
3653240133Smm		arc_buf_unwatch(buf);
3654240133Smm#endif /* illumos */
3655168404Spjd
3656168404Spjd		mutex_exit(hash_lock);
3657168404Spjd
3658185029Spjd		nhdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
3659168404Spjd		nhdr->b_size = blksz;
3660168404Spjd		nhdr->b_spa = spa;
3661168404Spjd		nhdr->b_type = type;
3662168404Spjd		nhdr->b_buf = buf;
3663168404Spjd		nhdr->b_state = arc_anon;
3664168404Spjd		nhdr->b_arc_access = 0;
3665185029Spjd		nhdr->b_flags = flags & ARC_L2_WRITING;
3666185029Spjd		nhdr->b_l2hdr = NULL;
3667168404Spjd		nhdr->b_datacnt = 1;
3668168404Spjd		nhdr->b_freeze_cksum = NULL;
3669168404Spjd		(void) refcount_add(&nhdr->b_refcnt, tag);
3670168404Spjd		buf->b_hdr = nhdr;
3671219089Spjd		mutex_exit(&buf->b_evict_lock);
3672168404Spjd		atomic_add_64(&arc_anon->arcs_size, blksz);
3673168404Spjd	} else {
3674219089Spjd		mutex_exit(&buf->b_evict_lock);
3675168404Spjd		ASSERT(refcount_count(&hdr->b_refcnt) == 1);
3676168404Spjd		ASSERT(!list_link_active(&hdr->b_arc_node));
3677168404Spjd		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3678219089Spjd		if (hdr->b_state != arc_anon)
3679219089Spjd			arc_change_state(arc_anon, hdr, hash_lock);
3680168404Spjd		hdr->b_arc_access = 0;
3681219089Spjd		if (hash_lock)
3682219089Spjd			mutex_exit(hash_lock);
3683185029Spjd
3684219089Spjd		buf_discard_identity(hdr);
3685168404Spjd		arc_buf_thaw(buf);
3686168404Spjd	}
3687168404Spjd	buf->b_efunc = NULL;
3688168404Spjd	buf->b_private = NULL;
3689185029Spjd
3690185029Spjd	if (l2hdr) {
3691251478Sdelphij		ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
3692268085Sdelphij		vdev_space_update(l2hdr->b_dev->l2ad_vdev,
3693268085Sdelphij		    -l2hdr->b_asize, 0, 0);
3694248572Ssmh		trim_map_free(l2hdr->b_dev->l2ad_vdev, l2hdr->b_daddr,
3695248574Ssmh		    hdr->b_size, 0);
3696185029Spjd		kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
3697185029Spjd		ARCSTAT_INCR(arcstat_l2_size, -buf_size);
3698185029Spjd		mutex_exit(&l2arc_buflist_mtx);
3699185029Spjd	}
3700168404Spjd}
3701168404Spjd
3702168404Spjdint
3703168404Spjdarc_released(arc_buf_t *buf)
3704168404Spjd{
3705185029Spjd	int released;
3706185029Spjd
3707219089Spjd	mutex_enter(&buf->b_evict_lock);
3708185029Spjd	released = (buf->b_data != NULL && buf->b_hdr->b_state == arc_anon);
3709219089Spjd	mutex_exit(&buf->b_evict_lock);
3710185029Spjd	return (released);
3711168404Spjd}
3712168404Spjd
3713168404Spjd#ifdef ZFS_DEBUG
3714168404Spjdint
3715168404Spjdarc_referenced(arc_buf_t *buf)
3716168404Spjd{
3717185029Spjd	int referenced;
3718185029Spjd
3719219089Spjd	mutex_enter(&buf->b_evict_lock);
3720185029Spjd	referenced = (refcount_count(&buf->b_hdr->b_refcnt));
3721219089Spjd	mutex_exit(&buf->b_evict_lock);
3722185029Spjd	return (referenced);
3723168404Spjd}
3724168404Spjd#endif
3725168404Spjd
3726168404Spjdstatic void
3727168404Spjdarc_write_ready(zio_t *zio)
3728168404Spjd{
3729168404Spjd	arc_write_callback_t *callback = zio->io_private;
3730168404Spjd	arc_buf_t *buf = callback->awcb_buf;
3731185029Spjd	arc_buf_hdr_t *hdr = buf->b_hdr;
3732168404Spjd
3733185029Spjd	ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt));
3734185029Spjd	callback->awcb_ready(zio, buf, callback->awcb_private);
3735185029Spjd
3736185029Spjd	/*
3737185029Spjd	 * If the IO is already in progress, then this is a re-write
3738185029Spjd	 * attempt, so we need to thaw and re-compute the cksum.
3739185029Spjd	 * It is the responsibility of the callback to handle the
3740185029Spjd	 * accounting for any re-write attempt.
3741185029Spjd	 */
3742185029Spjd	if (HDR_IO_IN_PROGRESS(hdr)) {
3743185029Spjd		mutex_enter(&hdr->b_freeze_lock);
3744185029Spjd		if (hdr->b_freeze_cksum != NULL) {
3745185029Spjd			kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
3746185029Spjd			hdr->b_freeze_cksum = NULL;
3747185029Spjd		}
3748185029Spjd		mutex_exit(&hdr->b_freeze_lock);
3749168404Spjd	}
3750185029Spjd	arc_cksum_compute(buf, B_FALSE);
3751185029Spjd	hdr->b_flags |= ARC_IO_IN_PROGRESS;
3752168404Spjd}
3753168404Spjd
3754258632Savg/*
3755258632Savg * The SPA calls this callback for each physical write that happens on behalf
3756258632Savg * of a logical write.  See the comment in dbuf_write_physdone() for details.
3757258632Savg */
3758168404Spjdstatic void
3759258632Savgarc_write_physdone(zio_t *zio)
3760258632Savg{
3761258632Savg	arc_write_callback_t *cb = zio->io_private;
3762258632Savg	if (cb->awcb_physdone != NULL)
3763258632Savg		cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
3764258632Savg}
3765258632Savg
3766258632Savgstatic void
3767168404Spjdarc_write_done(zio_t *zio)
3768168404Spjd{
3769168404Spjd	arc_write_callback_t *callback = zio->io_private;
3770168404Spjd	arc_buf_t *buf = callback->awcb_buf;
3771168404Spjd	arc_buf_hdr_t *hdr = buf->b_hdr;
3772168404Spjd
3773219089Spjd	ASSERT(hdr->b_acb == NULL);
3774168404Spjd
3775219089Spjd	if (zio->io_error == 0) {
3776268075Sdelphij		if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
3777260150Sdelphij			buf_discard_identity(hdr);
3778260150Sdelphij		} else {
3779260150Sdelphij			hdr->b_dva = *BP_IDENTITY(zio->io_bp);
3780260150Sdelphij			hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
3781260150Sdelphij			hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
3782260150Sdelphij		}
3783219089Spjd	} else {
3784219089Spjd		ASSERT(BUF_EMPTY(hdr));
3785219089Spjd	}
3786219089Spjd
3787168404Spjd	/*
3788268075Sdelphij	 * If the block to be written was all-zero or compressed enough to be
3789268075Sdelphij	 * embedded in the BP, no write was performed so there will be no
3790268075Sdelphij	 * dva/birth/checksum.  The buffer must therefore remain anonymous
3791268075Sdelphij	 * (and uncached).
3792168404Spjd	 */
3793168404Spjd	if (!BUF_EMPTY(hdr)) {
3794168404Spjd		arc_buf_hdr_t *exists;
3795168404Spjd		kmutex_t *hash_lock;
3796168404Spjd
3797219089Spjd		ASSERT(zio->io_error == 0);
3798219089Spjd
3799168404Spjd		arc_cksum_verify(buf);
3800168404Spjd
3801168404Spjd		exists = buf_hash_insert(hdr, &hash_lock);
3802168404Spjd		if (exists) {
3803168404Spjd			/*
3804168404Spjd			 * This can only happen if we overwrite for
3805168404Spjd			 * sync-to-convergence, because we remove
3806168404Spjd			 * buffers from the hash table when we arc_free().
3807168404Spjd			 */
3808219089Spjd			if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
3809219089Spjd				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3810219089Spjd					panic("bad overwrite, hdr=%p exists=%p",
3811219089Spjd					    (void *)hdr, (void *)exists);
3812219089Spjd				ASSERT(refcount_is_zero(&exists->b_refcnt));
3813219089Spjd				arc_change_state(arc_anon, exists, hash_lock);
3814219089Spjd				mutex_exit(hash_lock);
3815219089Spjd				arc_hdr_destroy(exists);
3816219089Spjd				exists = buf_hash_insert(hdr, &hash_lock);
3817219089Spjd				ASSERT3P(exists, ==, NULL);
3818243524Smm			} else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
3819243524Smm				/* nopwrite */
3820243524Smm				ASSERT(zio->io_prop.zp_nopwrite);
3821243524Smm				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3822243524Smm					panic("bad nopwrite, hdr=%p exists=%p",
3823243524Smm					    (void *)hdr, (void *)exists);
3824219089Spjd			} else {
3825219089Spjd				/* Dedup */
3826219089Spjd				ASSERT(hdr->b_datacnt == 1);
3827219089Spjd				ASSERT(hdr->b_state == arc_anon);
3828219089Spjd				ASSERT(BP_GET_DEDUP(zio->io_bp));
3829219089Spjd				ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
3830219089Spjd			}
3831168404Spjd		}
3832168404Spjd		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3833185029Spjd		/* if it's not anon, we are doing a scrub */
3834219089Spjd		if (!exists && hdr->b_state == arc_anon)
3835185029Spjd			arc_access(hdr, hash_lock);
3836168404Spjd		mutex_exit(hash_lock);
3837168404Spjd	} else {
3838168404Spjd		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3839168404Spjd	}
3840168404Spjd
3841219089Spjd	ASSERT(!refcount_is_zero(&hdr->b_refcnt));
3842219089Spjd	callback->awcb_done(zio, buf, callback->awcb_private);
3843168404Spjd
3844168404Spjd	kmem_free(callback, sizeof (arc_write_callback_t));
3845168404Spjd}
3846168404Spjd
3847168404Spjdzio_t *
3848219089Spjdarc_write(zio_t *pio, spa_t *spa, uint64_t txg,
3849251478Sdelphij    blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
3850258632Savg    const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *physdone,
3851258632Savg    arc_done_func_t *done, void *private, zio_priority_t priority,
3852268123Sdelphij    int zio_flags, const zbookmark_phys_t *zb)
3853168404Spjd{
3854168404Spjd	arc_buf_hdr_t *hdr = buf->b_hdr;
3855168404Spjd	arc_write_callback_t *callback;
3856185029Spjd	zio_t *zio;
3857168404Spjd
3858185029Spjd	ASSERT(ready != NULL);
3859219089Spjd	ASSERT(done != NULL);
3860168404Spjd	ASSERT(!HDR_IO_ERROR(hdr));
3861168404Spjd	ASSERT((hdr->b_flags & ARC_IO_IN_PROGRESS) == 0);
3862219089Spjd	ASSERT(hdr->b_acb == NULL);
3863185029Spjd	if (l2arc)
3864185029Spjd		hdr->b_flags |= ARC_L2CACHE;
3865251478Sdelphij	if (l2arc_compress)
3866251478Sdelphij		hdr->b_flags |= ARC_L2COMPRESS;
3867168404Spjd	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
3868168404Spjd	callback->awcb_ready = ready;
3869258632Savg	callback->awcb_physdone = physdone;
3870168404Spjd	callback->awcb_done = done;
3871168404Spjd	callback->awcb_private = private;
3872168404Spjd	callback->awcb_buf = buf;
3873168404Spjd
3874219089Spjd	zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
3875258632Savg	    arc_write_ready, arc_write_physdone, arc_write_done, callback,
3876258632Savg	    priority, zio_flags, zb);
3877185029Spjd
3878168404Spjd	return (zio);
3879168404Spjd}
3880168404Spjd
3881185029Spjdstatic int
3882258632Savgarc_memory_throttle(uint64_t reserve, uint64_t txg)
3883185029Spjd{
3884185029Spjd#ifdef _KERNEL
3885219089Spjd	uint64_t available_memory =
3886263620Sbdrewery	    ptoa((uintmax_t)vm_cnt.v_free_count + vm_cnt.v_cache_count);
3887185029Spjd	static uint64_t page_load = 0;
3888185029Spjd	static uint64_t last_txg = 0;
3889185029Spjd
3890219089Spjd#ifdef sun
3891185029Spjd#if defined(__i386)
3892185029Spjd	available_memory =
3893185029Spjd	    MIN(available_memory, vmem_size(heap_arena, VMEM_FREE));
3894185029Spjd#endif
3895219089Spjd#endif	/* sun */
3896258632Savg
3897263620Sbdrewery	if (vm_cnt.v_free_count + vm_cnt.v_cache_count >
3898258632Savg	    (uint64_t)physmem * arc_lotsfree_percent / 100)
3899185029Spjd		return (0);
3900185029Spjd
3901185029Spjd	if (txg > last_txg) {
3902185029Spjd		last_txg = txg;
3903185029Spjd		page_load = 0;
3904185029Spjd	}
3905185029Spjd	/*
3906185029Spjd	 * If we are in pageout, we know that memory is already tight,
3907185029Spjd	 * the arc is already going to be evicting, so we just want to
3908185029Spjd	 * continue to let page writes occur as quickly as possible.
3909185029Spjd	 */
3910185029Spjd	if (curproc == pageproc) {
3911185029Spjd		if (page_load > available_memory / 4)
3912249195Smm			return (SET_ERROR(ERESTART));
3913185029Spjd		/* Note: reserve is inflated, so we deflate */
3914185029Spjd		page_load += reserve / 8;
3915185029Spjd		return (0);
3916185029Spjd	} else if (page_load > 0 && arc_reclaim_needed()) {
3917185029Spjd		/* memory is low, delay before restarting */
3918185029Spjd		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
3919249195Smm		return (SET_ERROR(EAGAIN));
3920185029Spjd	}
3921185029Spjd	page_load = 0;
3922185029Spjd#endif
3923185029Spjd	return (0);
3924185029Spjd}
3925185029Spjd
3926168404Spjdvoid
3927185029Spjdarc_tempreserve_clear(uint64_t reserve)
3928168404Spjd{
3929185029Spjd	atomic_add_64(&arc_tempreserve, -reserve);
3930168404Spjd	ASSERT((int64_t)arc_tempreserve >= 0);
3931168404Spjd}
3932168404Spjd
3933168404Spjdint
3934185029Spjdarc_tempreserve_space(uint64_t reserve, uint64_t txg)
3935168404Spjd{
3936185029Spjd	int error;
3937209962Smm	uint64_t anon_size;
3938185029Spjd
3939185029Spjd	if (reserve > arc_c/4 && !arc_no_grow)
3940185029Spjd		arc_c = MIN(arc_c_max, reserve * 4);
3941185029Spjd	if (reserve > arc_c)
3942249195Smm		return (SET_ERROR(ENOMEM));
3943168404Spjd
3944168404Spjd	/*
3945209962Smm	 * Don't count loaned bufs as in flight dirty data to prevent long
3946209962Smm	 * network delays from blocking transactions that are ready to be
3947209962Smm	 * assigned to a txg.
3948209962Smm	 */
3949209962Smm	anon_size = MAX((int64_t)(arc_anon->arcs_size - arc_loaned_bytes), 0);
3950209962Smm
3951209962Smm	/*
3952185029Spjd	 * Writes will, almost always, require additional memory allocations
3953251631Sdelphij	 * in order to compress/encrypt/etc the data.  We therefore need to
3954185029Spjd	 * make sure that there is sufficient available memory for this.
3955185029Spjd	 */
3956258632Savg	error = arc_memory_throttle(reserve, txg);
3957258632Savg	if (error != 0)
3958185029Spjd		return (error);
3959185029Spjd
3960185029Spjd	/*
3961168404Spjd	 * Throttle writes when the amount of dirty data in the cache
3962168404Spjd	 * gets too large.  We try to keep the cache less than half full
3963168404Spjd	 * of dirty blocks so that our sync times don't grow too large.
3964168404Spjd	 * Note: if two requests come in concurrently, we might let them
3965168404Spjd	 * both succeed, when one of them should fail.  Not a huge deal.
3966168404Spjd	 */
3967209962Smm
3968209962Smm	if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
3969209962Smm	    anon_size > arc_c / 4) {
3970185029Spjd		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
3971185029Spjd		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
3972185029Spjd		    arc_tempreserve>>10,
3973185029Spjd		    arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
3974185029Spjd		    arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
3975185029Spjd		    reserve>>10, arc_c>>10);
3976249195Smm		return (SET_ERROR(ERESTART));
3977168404Spjd	}
3978185029Spjd	atomic_add_64(&arc_tempreserve, reserve);
3979168404Spjd	return (0);
3980168404Spjd}
3981168404Spjd
3982168582Spjdstatic kmutex_t arc_lowmem_lock;
3983168404Spjd#ifdef _KERNEL
3984168566Spjdstatic eventhandler_tag arc_event_lowmem = NULL;
3985168404Spjd
3986168404Spjdstatic void
3987168566Spjdarc_lowmem(void *arg __unused, int howto __unused)
3988168404Spjd{
3989168404Spjd
3990168566Spjd	/* Serialize access via arc_lowmem_lock. */
3991168566Spjd	mutex_enter(&arc_lowmem_lock);
3992219089Spjd	mutex_enter(&arc_reclaim_thr_lock);
3993185029Spjd	needfree = 1;
3994168404Spjd	cv_signal(&arc_reclaim_thr_cv);
3995241773Savg
3996241773Savg	/*
3997241773Savg	 * It is unsafe to block here in arbitrary threads, because we can come
3998241773Savg	 * here from ARC itself and may hold ARC locks and thus risk a deadlock
3999241773Savg	 * with ARC reclaim thread.
4000241773Savg	 */
4001241773Savg	if (curproc == pageproc) {
4002241773Savg		while (needfree)
4003241773Savg			msleep(&needfree, &arc_reclaim_thr_lock, 0, "zfs:lowmem", 0);
4004241773Savg	}
4005219089Spjd	mutex_exit(&arc_reclaim_thr_lock);
4006168566Spjd	mutex_exit(&arc_lowmem_lock);
4007168404Spjd}
4008168404Spjd#endif
4009168404Spjd
4010168404Spjdvoid
4011168404Spjdarc_init(void)
4012168404Spjd{
4013219089Spjd	int i, prefetch_tunable_set = 0;
4014205231Skmacy
4015168404Spjd	mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
4016168404Spjd	cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
4017168566Spjd	mutex_init(&arc_lowmem_lock, NULL, MUTEX_DEFAULT, NULL);
4018168404Spjd
4019168404Spjd	/* Convert seconds to clock ticks */
4020168404Spjd	arc_min_prefetch_lifespan = 1 * hz;
4021168404Spjd
4022168404Spjd	/* Start out with 1/8 of all memory */
4023168566Spjd	arc_c = kmem_size() / 8;
4024219089Spjd
4025219089Spjd#ifdef sun
4026192360Skmacy#ifdef _KERNEL
4027192360Skmacy	/*
4028192360Skmacy	 * On architectures where the physical memory can be larger
4029192360Skmacy	 * than the addressable space (intel in 32-bit mode), we may
4030192360Skmacy	 * need to limit the cache to 1/8 of VM size.
4031192360Skmacy	 */
4032192360Skmacy	arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
4033192360Skmacy#endif
4034219089Spjd#endif	/* sun */
4035168566Spjd	/* set min cache to 1/32 of all memory, or 16MB, whichever is more */
4036168566Spjd	arc_c_min = MAX(arc_c / 4, 64<<18);
4037168566Spjd	/* set max to 1/2 of all memory, or all but 1GB, whichever is more */
4038168404Spjd	if (arc_c * 8 >= 1<<30)
4039168404Spjd		arc_c_max = (arc_c * 8) - (1<<30);
4040168404Spjd	else
4041168404Spjd		arc_c_max = arc_c_min;
4042175633Spjd	arc_c_max = MAX(arc_c * 5, arc_c_max);
4043219089Spjd
4044168481Spjd#ifdef _KERNEL
4045168404Spjd	/*
4046168404Spjd	 * Allow the tunables to override our calculations if they are
4047168566Spjd	 * reasonable (ie. over 16MB)
4048168404Spjd	 */
4049219089Spjd	if (zfs_arc_max > 64<<18 && zfs_arc_max < kmem_size())
4050168404Spjd		arc_c_max = zfs_arc_max;
4051219089Spjd	if (zfs_arc_min > 64<<18 && zfs_arc_min <= arc_c_max)
4052168404Spjd		arc_c_min = zfs_arc_min;
4053168481Spjd#endif
4054219089Spjd
4055168404Spjd	arc_c = arc_c_max;
4056168404Spjd	arc_p = (arc_c >> 1);
4057168404Spjd
4058185029Spjd	/* limit meta-data to 1/4 of the arc capacity */
4059185029Spjd	arc_meta_limit = arc_c_max / 4;
4060185029Spjd
4061185029Spjd	/* Allow the tunable to override if it is reasonable */
4062185029Spjd	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
4063185029Spjd		arc_meta_limit = zfs_arc_meta_limit;
4064185029Spjd
4065185029Spjd	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
4066185029Spjd		arc_c_min = arc_meta_limit / 2;
4067185029Spjd
4068208373Smm	if (zfs_arc_grow_retry > 0)
4069208373Smm		arc_grow_retry = zfs_arc_grow_retry;
4070208373Smm
4071208373Smm	if (zfs_arc_shrink_shift > 0)
4072208373Smm		arc_shrink_shift = zfs_arc_shrink_shift;
4073208373Smm
4074208373Smm	if (zfs_arc_p_min_shift > 0)
4075208373Smm		arc_p_min_shift = zfs_arc_p_min_shift;
4076208373Smm
4077168404Spjd	/* if kmem_flags are set, lets try to use less memory */
4078168404Spjd	if (kmem_debugging())
4079168404Spjd		arc_c = arc_c / 2;
4080168404Spjd	if (arc_c < arc_c_min)
4081168404Spjd		arc_c = arc_c_min;
4082168404Spjd
4083168473Spjd	zfs_arc_min = arc_c_min;
4084168473Spjd	zfs_arc_max = arc_c_max;
4085168473Spjd
4086168404Spjd	arc_anon = &ARC_anon;
4087168404Spjd	arc_mru = &ARC_mru;
4088168404Spjd	arc_mru_ghost = &ARC_mru_ghost;
4089168404Spjd	arc_mfu = &ARC_mfu;
4090168404Spjd	arc_mfu_ghost = &ARC_mfu_ghost;
4091185029Spjd	arc_l2c_only = &ARC_l2c_only;
4092168404Spjd	arc_size = 0;
4093168404Spjd
4094205231Skmacy	for (i = 0; i < ARC_BUFC_NUMLISTS; i++) {
4095205231Skmacy		mutex_init(&arc_anon->arcs_locks[i].arcs_lock,
4096205231Skmacy		    NULL, MUTEX_DEFAULT, NULL);
4097205231Skmacy		mutex_init(&arc_mru->arcs_locks[i].arcs_lock,
4098205231Skmacy		    NULL, MUTEX_DEFAULT, NULL);
4099205231Skmacy		mutex_init(&arc_mru_ghost->arcs_locks[i].arcs_lock,
4100205231Skmacy		    NULL, MUTEX_DEFAULT, NULL);
4101205231Skmacy		mutex_init(&arc_mfu->arcs_locks[i].arcs_lock,
4102205231Skmacy		    NULL, MUTEX_DEFAULT, NULL);
4103205231Skmacy		mutex_init(&arc_mfu_ghost->arcs_locks[i].arcs_lock,
4104205231Skmacy		    NULL, MUTEX_DEFAULT, NULL);
4105205231Skmacy		mutex_init(&arc_l2c_only->arcs_locks[i].arcs_lock,
4106205231Skmacy		    NULL, MUTEX_DEFAULT, NULL);
4107206796Spjd
4108205231Skmacy		list_create(&arc_mru->arcs_lists[i],
4109205231Skmacy		    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4110205231Skmacy		list_create(&arc_mru_ghost->arcs_lists[i],
4111205231Skmacy		    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4112205231Skmacy		list_create(&arc_mfu->arcs_lists[i],
4113205231Skmacy		    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4114205231Skmacy		list_create(&arc_mfu_ghost->arcs_lists[i],
4115205231Skmacy		    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4116205231Skmacy		list_create(&arc_mfu_ghost->arcs_lists[i],
4117205231Skmacy		    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4118205231Skmacy		list_create(&arc_l2c_only->arcs_lists[i],
4119205231Skmacy		    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4120205231Skmacy	}
4121168404Spjd
4122168404Spjd	buf_init();
4123168404Spjd
4124168404Spjd	arc_thread_exit = 0;
4125168404Spjd	arc_eviction_list = NULL;
4126168404Spjd	mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
4127168404Spjd	bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
4128168404Spjd
4129168404Spjd	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
4130168404Spjd	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
4131168404Spjd
4132168404Spjd	if (arc_ksp != NULL) {
4133168404Spjd		arc_ksp->ks_data = &arc_stats;
4134168404Spjd		kstat_install(arc_ksp);
4135168404Spjd	}
4136168404Spjd
4137168404Spjd	(void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
4138168404Spjd	    TS_RUN, minclsyspri);
4139168404Spjd
4140168404Spjd#ifdef _KERNEL
4141168566Spjd	arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
4142168404Spjd	    EVENTHANDLER_PRI_FIRST);
4143168404Spjd#endif
4144168404Spjd
4145168404Spjd	arc_dead = FALSE;
4146185029Spjd	arc_warm = B_FALSE;
4147168566Spjd
4148258632Savg	/*
4149258632Savg	 * Calculate maximum amount of dirty data per pool.
4150258632Savg	 *
4151258632Savg	 * If it has been set by /etc/system, take that.
4152258632Savg	 * Otherwise, use a percentage of physical memory defined by
4153258632Savg	 * zfs_dirty_data_max_percent (default 10%) with a cap at
4154258632Savg	 * zfs_dirty_data_max_max (default 4GB).
4155258632Savg	 */
4156258632Savg	if (zfs_dirty_data_max == 0) {
4157258632Savg		zfs_dirty_data_max = ptob(physmem) *
4158258632Savg		    zfs_dirty_data_max_percent / 100;
4159258632Savg		zfs_dirty_data_max = MIN(zfs_dirty_data_max,
4160258632Savg		    zfs_dirty_data_max_max);
4161258632Savg	}
4162185029Spjd
4163168566Spjd#ifdef _KERNEL
4164194043Skmacy	if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
4165193953Skmacy		prefetch_tunable_set = 1;
4166206796Spjd
4167193878Skmacy#ifdef __i386__
4168193953Skmacy	if (prefetch_tunable_set == 0) {
4169196863Strasz		printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
4170196863Strasz		    "-- to enable,\n");
4171196863Strasz		printf("            add \"vfs.zfs.prefetch_disable=0\" "
4172196863Strasz		    "to /boot/loader.conf.\n");
4173219089Spjd		zfs_prefetch_disable = 1;
4174193878Skmacy	}
4175206796Spjd#else
4176193878Skmacy	if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
4177193953Skmacy	    prefetch_tunable_set == 0) {
4178196863Strasz		printf("ZFS NOTICE: Prefetch is disabled by default if less "
4179196941Strasz		    "than 4GB of RAM is present;\n"
4180196863Strasz		    "            to enable, add \"vfs.zfs.prefetch_disable=0\" "
4181196863Strasz		    "to /boot/loader.conf.\n");
4182219089Spjd		zfs_prefetch_disable = 1;
4183193878Skmacy	}
4184206796Spjd#endif
4185175633Spjd	/* Warn about ZFS memory and address space requirements. */
4186168696Spjd	if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
4187168987Sbmah		printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
4188168987Sbmah		    "expect unstable behavior.\n");
4189175633Spjd	}
4190175633Spjd	if (kmem_size() < 512 * (1 << 20)) {
4191173419Spjd		printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
4192168987Sbmah		    "expect unstable behavior.\n");
4193185029Spjd		printf("             Consider tuning vm.kmem_size and "
4194173419Spjd		    "vm.kmem_size_max\n");
4195185029Spjd		printf("             in /boot/loader.conf.\n");
4196168566Spjd	}
4197168566Spjd#endif
4198168404Spjd}
4199168404Spjd
4200168404Spjdvoid
4201168404Spjdarc_fini(void)
4202168404Spjd{
4203205231Skmacy	int i;
4204206796Spjd
4205168404Spjd	mutex_enter(&arc_reclaim_thr_lock);
4206168404Spjd	arc_thread_exit = 1;
4207168404Spjd	cv_signal(&arc_reclaim_thr_cv);
4208168404Spjd	while (arc_thread_exit != 0)
4209168404Spjd		cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
4210168404Spjd	mutex_exit(&arc_reclaim_thr_lock);
4211168404Spjd
4212185029Spjd	arc_flush(NULL);
4213168404Spjd
4214168404Spjd	arc_dead = TRUE;
4215168404Spjd
4216168404Spjd	if (arc_ksp != NULL) {
4217168404Spjd		kstat_delete(arc_ksp);
4218168404Spjd		arc_ksp = NULL;
4219168404Spjd	}
4220168404Spjd
4221168404Spjd	mutex_destroy(&arc_eviction_mtx);
4222168404Spjd	mutex_destroy(&arc_reclaim_thr_lock);
4223168404Spjd	cv_destroy(&arc_reclaim_thr_cv);
4224168404Spjd
4225205231Skmacy	for (i = 0; i < ARC_BUFC_NUMLISTS; i++) {
4226205231Skmacy		list_destroy(&arc_mru->arcs_lists[i]);
4227205231Skmacy		list_destroy(&arc_mru_ghost->arcs_lists[i]);
4228205231Skmacy		list_destroy(&arc_mfu->arcs_lists[i]);
4229205231Skmacy		list_destroy(&arc_mfu_ghost->arcs_lists[i]);
4230206795Spjd		list_destroy(&arc_l2c_only->arcs_lists[i]);
4231168404Spjd
4232205231Skmacy		mutex_destroy(&arc_anon->arcs_locks[i].arcs_lock);
4233205231Skmacy		mutex_destroy(&arc_mru->arcs_locks[i].arcs_lock);
4234205231Skmacy		mutex_destroy(&arc_mru_ghost->arcs_locks[i].arcs_lock);
4235205231Skmacy		mutex_destroy(&arc_mfu->arcs_locks[i].arcs_lock);
4236205231Skmacy		mutex_destroy(&arc_mfu_ghost->arcs_locks[i].arcs_lock);
4237206795Spjd		mutex_destroy(&arc_l2c_only->arcs_locks[i].arcs_lock);
4238205231Skmacy	}
4239206796Spjd
4240168404Spjd	buf_fini();
4241168404Spjd
4242209962Smm	ASSERT(arc_loaned_bytes == 0);
4243209962Smm
4244168582Spjd	mutex_destroy(&arc_lowmem_lock);
4245168404Spjd#ifdef _KERNEL
4246168566Spjd	if (arc_event_lowmem != NULL)
4247168566Spjd		EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
4248168404Spjd#endif
4249168404Spjd}
4250185029Spjd
4251185029Spjd/*
4252185029Spjd * Level 2 ARC
4253185029Spjd *
4254185029Spjd * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
4255185029Spjd * It uses dedicated storage devices to hold cached data, which are populated
4256185029Spjd * using large infrequent writes.  The main role of this cache is to boost
4257185029Spjd * the performance of random read workloads.  The intended L2ARC devices
4258185029Spjd * include short-stroked disks, solid state disks, and other media with
4259185029Spjd * substantially faster read latency than disk.
4260185029Spjd *
4261185029Spjd *                 +-----------------------+
4262185029Spjd *                 |         ARC           |
4263185029Spjd *                 +-----------------------+
4264185029Spjd *                    |         ^     ^
4265185029Spjd *                    |         |     |
4266185029Spjd *      l2arc_feed_thread()    arc_read()
4267185029Spjd *                    |         |     |
4268185029Spjd *                    |  l2arc read   |
4269185029Spjd *                    V         |     |
4270185029Spjd *               +---------------+    |
4271185029Spjd *               |     L2ARC     |    |
4272185029Spjd *               +---------------+    |
4273185029Spjd *                   |    ^           |
4274185029Spjd *          l2arc_write() |           |
4275185029Spjd *                   |    |           |
4276185029Spjd *                   V    |           |
4277185029Spjd *                 +-------+      +-------+
4278185029Spjd *                 | vdev  |      | vdev  |
4279185029Spjd *                 | cache |      | cache |
4280185029Spjd *                 +-------+      +-------+
4281185029Spjd *                 +=========+     .-----.
4282185029Spjd *                 :  L2ARC  :    |-_____-|
4283185029Spjd *                 : devices :    | Disks |
4284185029Spjd *                 +=========+    `-_____-'
4285185029Spjd *
4286185029Spjd * Read requests are satisfied from the following sources, in order:
4287185029Spjd *
4288185029Spjd *	1) ARC
4289185029Spjd *	2) vdev cache of L2ARC devices
4290185029Spjd *	3) L2ARC devices
4291185029Spjd *	4) vdev cache of disks
4292185029Spjd *	5) disks
4293185029Spjd *
4294185029Spjd * Some L2ARC device types exhibit extremely slow write performance.
4295185029Spjd * To accommodate for this there are some significant differences between
4296185029Spjd * the L2ARC and traditional cache design:
4297185029Spjd *
4298185029Spjd * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
4299185029Spjd * the ARC behave as usual, freeing buffers and placing headers on ghost
4300185029Spjd * lists.  The ARC does not send buffers to the L2ARC during eviction as
4301185029Spjd * this would add inflated write latencies for all ARC memory pressure.
4302185029Spjd *
4303185029Spjd * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
4304185029Spjd * It does this by periodically scanning buffers from the eviction-end of
4305185029Spjd * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
4306251478Sdelphij * not already there. It scans until a headroom of buffers is satisfied,
4307251478Sdelphij * which itself is a buffer for ARC eviction. If a compressible buffer is
4308251478Sdelphij * found during scanning and selected for writing to an L2ARC device, we
4309251478Sdelphij * temporarily boost scanning headroom during the next scan cycle to make
4310251478Sdelphij * sure we adapt to compression effects (which might significantly reduce
4311251478Sdelphij * the data volume we write to L2ARC). The thread that does this is
4312185029Spjd * l2arc_feed_thread(), illustrated below; example sizes are included to
4313185029Spjd * provide a better sense of ratio than this diagram:
4314185029Spjd *
4315185029Spjd *	       head -->                        tail
4316185029Spjd *	        +---------------------+----------+
4317185029Spjd *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
4318185029Spjd *	        +---------------------+----------+   |   o L2ARC eligible
4319185029Spjd *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
4320185029Spjd *	        +---------------------+----------+   |
4321185029Spjd *	             15.9 Gbytes      ^ 32 Mbytes    |
4322185029Spjd *	                           headroom          |
4323185029Spjd *	                                      l2arc_feed_thread()
4324185029Spjd *	                                             |
4325185029Spjd *	                 l2arc write hand <--[oooo]--'
4326185029Spjd *	                         |           8 Mbyte
4327185029Spjd *	                         |          write max
4328185029Spjd *	                         V
4329185029Spjd *		  +==============================+
4330185029Spjd *	L2ARC dev |####|#|###|###|    |####| ... |
4331185029Spjd *	          +==============================+
4332185029Spjd *	                     32 Gbytes
4333185029Spjd *
4334185029Spjd * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
4335185029Spjd * evicted, then the L2ARC has cached a buffer much sooner than it probably
4336185029Spjd * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
4337185029Spjd * safe to say that this is an uncommon case, since buffers at the end of
4338185029Spjd * the ARC lists have moved there due to inactivity.
4339185029Spjd *
4340185029Spjd * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
4341185029Spjd * then the L2ARC simply misses copying some buffers.  This serves as a
4342185029Spjd * pressure valve to prevent heavy read workloads from both stalling the ARC
4343185029Spjd * with waits and clogging the L2ARC with writes.  This also helps prevent
4344185029Spjd * the potential for the L2ARC to churn if it attempts to cache content too
4345185029Spjd * quickly, such as during backups of the entire pool.
4346185029Spjd *
4347185029Spjd * 5. After system boot and before the ARC has filled main memory, there are
4348185029Spjd * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
4349185029Spjd * lists can remain mostly static.  Instead of searching from tail of these
4350185029Spjd * lists as pictured, the l2arc_feed_thread() will search from the list heads
4351185029Spjd * for eligible buffers, greatly increasing its chance of finding them.
4352185029Spjd *
4353185029Spjd * The L2ARC device write speed is also boosted during this time so that
4354185029Spjd * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
4355185029Spjd * there are no L2ARC reads, and no fear of degrading read performance
4356185029Spjd * through increased writes.
4357185029Spjd *
4358185029Spjd * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
4359185029Spjd * the vdev queue can aggregate them into larger and fewer writes.  Each
4360185029Spjd * device is written to in a rotor fashion, sweeping writes through
4361185029Spjd * available space then repeating.
4362185029Spjd *
4363185029Spjd * 7. The L2ARC does not store dirty content.  It never needs to flush
4364185029Spjd * write buffers back to disk based storage.
4365185029Spjd *
4366185029Spjd * 8. If an ARC buffer is written (and dirtied) which also exists in the
4367185029Spjd * L2ARC, the now stale L2ARC buffer is immediately dropped.
4368185029Spjd *
4369185029Spjd * The performance of the L2ARC can be tweaked by a number of tunables, which
4370185029Spjd * may be necessary for different workloads:
4371185029Spjd *
4372185029Spjd *	l2arc_write_max		max write bytes per interval
4373185029Spjd *	l2arc_write_boost	extra write bytes during device warmup
4374185029Spjd *	l2arc_noprefetch	skip caching prefetched buffers
4375185029Spjd *	l2arc_headroom		number of max device writes to precache
4376251478Sdelphij *	l2arc_headroom_boost	when we find compressed buffers during ARC
4377251478Sdelphij *				scanning, we multiply headroom by this
4378251478Sdelphij *				percentage factor for the next scan cycle,
4379251478Sdelphij *				since more compressed buffers are likely to
4380251478Sdelphij *				be present
4381185029Spjd *	l2arc_feed_secs		seconds between L2ARC writing
4382185029Spjd *
4383185029Spjd * Tunables may be removed or added as future performance improvements are
4384185029Spjd * integrated, and also may become zpool properties.
4385208373Smm *
4386208373Smm * There are three key functions that control how the L2ARC warms up:
4387208373Smm *
4388208373Smm *	l2arc_write_eligible()	check if a buffer is eligible to cache
4389208373Smm *	l2arc_write_size()	calculate how much to write
4390208373Smm *	l2arc_write_interval()	calculate sleep delay between writes
4391208373Smm *
4392208373Smm * These three functions determine what to write, how much, and how quickly
4393208373Smm * to send writes.
4394185029Spjd */
4395185029Spjd
4396208373Smmstatic boolean_t
4397209962Smml2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *ab)
4398208373Smm{
4399208373Smm	/*
4400208373Smm	 * A buffer is *not* eligible for the L2ARC if it:
4401208373Smm	 * 1. belongs to a different spa.
4402208373Smm	 * 2. is already cached on the L2ARC.
4403208373Smm	 * 3. has an I/O in progress (it may be an incomplete read).
4404208373Smm	 * 4. is flagged not eligible (zfs property).
4405208373Smm	 */
4406209962Smm	if (ab->b_spa != spa_guid) {
4407208373Smm		ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
4408208373Smm		return (B_FALSE);
4409208373Smm	}
4410208373Smm	if (ab->b_l2hdr != NULL) {
4411208373Smm		ARCSTAT_BUMP(arcstat_l2_write_in_l2);
4412208373Smm		return (B_FALSE);
4413208373Smm	}
4414208373Smm	if (HDR_IO_IN_PROGRESS(ab)) {
4415208373Smm		ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
4416208373Smm		return (B_FALSE);
4417208373Smm	}
4418208373Smm	if (!HDR_L2CACHE(ab)) {
4419208373Smm		ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
4420208373Smm		return (B_FALSE);
4421208373Smm	}
4422208373Smm
4423208373Smm	return (B_TRUE);
4424208373Smm}
4425208373Smm
4426208373Smmstatic uint64_t
4427251478Sdelphijl2arc_write_size(void)
4428208373Smm{
4429208373Smm	uint64_t size;
4430208373Smm
4431251478Sdelphij	/*
4432251478Sdelphij	 * Make sure our globals have meaningful values in case the user
4433251478Sdelphij	 * altered them.
4434251478Sdelphij	 */
4435251478Sdelphij	size = l2arc_write_max;
4436251478Sdelphij	if (size == 0) {
4437251478Sdelphij		cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
4438251478Sdelphij		    "be greater than zero, resetting it to the default (%d)",
4439251478Sdelphij		    L2ARC_WRITE_SIZE);
4440251478Sdelphij		size = l2arc_write_max = L2ARC_WRITE_SIZE;
4441251478Sdelphij	}
4442208373Smm
4443208373Smm	if (arc_warm == B_FALSE)
4444251478Sdelphij		size += l2arc_write_boost;
4445208373Smm
4446208373Smm	return (size);
4447208373Smm
4448208373Smm}
4449208373Smm
4450208373Smmstatic clock_t
4451208373Smml2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
4452208373Smm{
4453219089Spjd	clock_t interval, next, now;
4454208373Smm
4455208373Smm	/*
4456208373Smm	 * If the ARC lists are busy, increase our write rate; if the
4457208373Smm	 * lists are stale, idle back.  This is achieved by checking
4458208373Smm	 * how much we previously wrote - if it was more than half of
4459208373Smm	 * what we wanted, schedule the next write much sooner.
4460208373Smm	 */
4461208373Smm	if (l2arc_feed_again && wrote > (wanted / 2))
4462208373Smm		interval = (hz * l2arc_feed_min_ms) / 1000;
4463208373Smm	else
4464208373Smm		interval = hz * l2arc_feed_secs;
4465208373Smm
4466219089Spjd	now = ddi_get_lbolt();
4467219089Spjd	next = MAX(now, MIN(now + interval, began + interval));
4468208373Smm
4469208373Smm	return (next);
4470208373Smm}
4471208373Smm
4472185029Spjdstatic void
4473185029Spjdl2arc_hdr_stat_add(void)
4474185029Spjd{
4475185029Spjd	ARCSTAT_INCR(arcstat_l2_hdr_size, HDR_SIZE + L2HDR_SIZE);
4476185029Spjd	ARCSTAT_INCR(arcstat_hdr_size, -HDR_SIZE);
4477185029Spjd}
4478185029Spjd
4479185029Spjdstatic void
4480185029Spjdl2arc_hdr_stat_remove(void)
4481185029Spjd{
4482185029Spjd	ARCSTAT_INCR(arcstat_l2_hdr_size, -(HDR_SIZE + L2HDR_SIZE));
4483185029Spjd	ARCSTAT_INCR(arcstat_hdr_size, HDR_SIZE);
4484185029Spjd}
4485185029Spjd
4486185029Spjd/*
4487185029Spjd * Cycle through L2ARC devices.  This is how L2ARC load balances.
4488185029Spjd * If a device is returned, this also returns holding the spa config lock.
4489185029Spjd */
4490185029Spjdstatic l2arc_dev_t *
4491185029Spjdl2arc_dev_get_next(void)
4492185029Spjd{
4493185029Spjd	l2arc_dev_t *first, *next = NULL;
4494185029Spjd
4495185029Spjd	/*
4496185029Spjd	 * Lock out the removal of spas (spa_namespace_lock), then removal
4497185029Spjd	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
4498185029Spjd	 * both locks will be dropped and a spa config lock held instead.
4499185029Spjd	 */
4500185029Spjd	mutex_enter(&spa_namespace_lock);
4501185029Spjd	mutex_enter(&l2arc_dev_mtx);
4502185029Spjd
4503185029Spjd	/* if there are no vdevs, there is nothing to do */
4504185029Spjd	if (l2arc_ndev == 0)
4505185029Spjd		goto out;
4506185029Spjd
4507185029Spjd	first = NULL;
4508185029Spjd	next = l2arc_dev_last;
4509185029Spjd	do {
4510185029Spjd		/* loop around the list looking for a non-faulted vdev */
4511185029Spjd		if (next == NULL) {
4512185029Spjd			next = list_head(l2arc_dev_list);
4513185029Spjd		} else {
4514185029Spjd			next = list_next(l2arc_dev_list, next);
4515185029Spjd			if (next == NULL)
4516185029Spjd				next = list_head(l2arc_dev_list);
4517185029Spjd		}
4518185029Spjd
4519185029Spjd		/* if we have come back to the start, bail out */
4520185029Spjd		if (first == NULL)
4521185029Spjd			first = next;
4522185029Spjd		else if (next == first)
4523185029Spjd			break;
4524185029Spjd
4525185029Spjd	} while (vdev_is_dead(next->l2ad_vdev));
4526185029Spjd
4527185029Spjd	/* if we were unable to find any usable vdevs, return NULL */
4528185029Spjd	if (vdev_is_dead(next->l2ad_vdev))
4529185029Spjd		next = NULL;
4530185029Spjd
4531185029Spjd	l2arc_dev_last = next;
4532185029Spjd
4533185029Spjdout:
4534185029Spjd	mutex_exit(&l2arc_dev_mtx);
4535185029Spjd
4536185029Spjd	/*
4537185029Spjd	 * Grab the config lock to prevent the 'next' device from being
4538185029Spjd	 * removed while we are writing to it.
4539185029Spjd	 */
4540185029Spjd	if (next != NULL)
4541185029Spjd		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
4542185029Spjd	mutex_exit(&spa_namespace_lock);
4543185029Spjd
4544185029Spjd	return (next);
4545185029Spjd}
4546185029Spjd
4547185029Spjd/*
4548185029Spjd * Free buffers that were tagged for destruction.
4549185029Spjd */
4550185029Spjdstatic void
4551185029Spjdl2arc_do_free_on_write()
4552185029Spjd{
4553185029Spjd	list_t *buflist;
4554185029Spjd	l2arc_data_free_t *df, *df_prev;
4555185029Spjd
4556185029Spjd	mutex_enter(&l2arc_free_on_write_mtx);
4557185029Spjd	buflist = l2arc_free_on_write;
4558185029Spjd
4559185029Spjd	for (df = list_tail(buflist); df; df = df_prev) {
4560185029Spjd		df_prev = list_prev(buflist, df);
4561185029Spjd		ASSERT(df->l2df_data != NULL);
4562185029Spjd		ASSERT(df->l2df_func != NULL);
4563185029Spjd		df->l2df_func(df->l2df_data, df->l2df_size);
4564185029Spjd		list_remove(buflist, df);
4565185029Spjd		kmem_free(df, sizeof (l2arc_data_free_t));
4566185029Spjd	}
4567185029Spjd
4568185029Spjd	mutex_exit(&l2arc_free_on_write_mtx);
4569185029Spjd}
4570185029Spjd
4571185029Spjd/*
4572185029Spjd * A write to a cache device has completed.  Update all headers to allow
4573185029Spjd * reads from these buffers to begin.
4574185029Spjd */
4575185029Spjdstatic void
4576185029Spjdl2arc_write_done(zio_t *zio)
4577185029Spjd{
4578185029Spjd	l2arc_write_callback_t *cb;
4579185029Spjd	l2arc_dev_t *dev;
4580185029Spjd	list_t *buflist;
4581185029Spjd	arc_buf_hdr_t *head, *ab, *ab_prev;
4582185029Spjd	l2arc_buf_hdr_t *abl2;
4583185029Spjd	kmutex_t *hash_lock;
4584268085Sdelphij	int64_t bytes_dropped = 0;
4585185029Spjd
4586185029Spjd	cb = zio->io_private;
4587185029Spjd	ASSERT(cb != NULL);
4588185029Spjd	dev = cb->l2wcb_dev;
4589185029Spjd	ASSERT(dev != NULL);
4590185029Spjd	head = cb->l2wcb_head;
4591185029Spjd	ASSERT(head != NULL);
4592185029Spjd	buflist = dev->l2ad_buflist;
4593185029Spjd	ASSERT(buflist != NULL);
4594185029Spjd	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
4595185029Spjd	    l2arc_write_callback_t *, cb);
4596185029Spjd
4597185029Spjd	if (zio->io_error != 0)
4598185029Spjd		ARCSTAT_BUMP(arcstat_l2_writes_error);
4599185029Spjd
4600185029Spjd	mutex_enter(&l2arc_buflist_mtx);
4601185029Spjd
4602185029Spjd	/*
4603185029Spjd	 * All writes completed, or an error was hit.
4604185029Spjd	 */
4605185029Spjd	for (ab = list_prev(buflist, head); ab; ab = ab_prev) {
4606185029Spjd		ab_prev = list_prev(buflist, ab);
4607260835Sdelphij		abl2 = ab->b_l2hdr;
4608185029Spjd
4609260835Sdelphij		/*
4610260835Sdelphij		 * Release the temporary compressed buffer as soon as possible.
4611260835Sdelphij		 */
4612260835Sdelphij		if (abl2->b_compress != ZIO_COMPRESS_OFF)
4613260835Sdelphij			l2arc_release_cdata_buf(ab);
4614260835Sdelphij
4615185029Spjd		hash_lock = HDR_LOCK(ab);
4616185029Spjd		if (!mutex_tryenter(hash_lock)) {
4617185029Spjd			/*
4618185029Spjd			 * This buffer misses out.  It may be in a stage
4619185029Spjd			 * of eviction.  Its ARC_L2_WRITING flag will be
4620185029Spjd			 * left set, denying reads to this buffer.
4621185029Spjd			 */
4622185029Spjd			ARCSTAT_BUMP(arcstat_l2_writes_hdr_miss);
4623185029Spjd			continue;
4624185029Spjd		}
4625185029Spjd
4626185029Spjd		if (zio->io_error != 0) {
4627185029Spjd			/*
4628185029Spjd			 * Error - drop L2ARC entry.
4629185029Spjd			 */
4630185029Spjd			list_remove(buflist, ab);
4631251478Sdelphij			ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
4632268085Sdelphij			bytes_dropped += abl2->b_asize;
4633185029Spjd			ab->b_l2hdr = NULL;
4634248572Ssmh			trim_map_free(abl2->b_dev->l2ad_vdev, abl2->b_daddr,
4635248574Ssmh			    ab->b_size, 0);
4636185029Spjd			kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
4637185029Spjd			ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
4638185029Spjd		}
4639185029Spjd
4640185029Spjd		/*
4641185029Spjd		 * Allow ARC to begin reads to this L2ARC entry.
4642185029Spjd		 */
4643185029Spjd		ab->b_flags &= ~ARC_L2_WRITING;
4644185029Spjd
4645185029Spjd		mutex_exit(hash_lock);
4646185029Spjd	}
4647185029Spjd
4648185029Spjd	atomic_inc_64(&l2arc_writes_done);
4649185029Spjd	list_remove(buflist, head);
4650185029Spjd	kmem_cache_free(hdr_cache, head);
4651185029Spjd	mutex_exit(&l2arc_buflist_mtx);
4652185029Spjd
4653268085Sdelphij	vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
4654268085Sdelphij
4655185029Spjd	l2arc_do_free_on_write();
4656185029Spjd
4657185029Spjd	kmem_free(cb, sizeof (l2arc_write_callback_t));
4658185029Spjd}
4659185029Spjd
4660185029Spjd/*
4661185029Spjd * A read to a cache device completed.  Validate buffer contents before
4662185029Spjd * handing over to the regular ARC routines.
4663185029Spjd */
4664185029Spjdstatic void
4665185029Spjdl2arc_read_done(zio_t *zio)
4666185029Spjd{
4667185029Spjd	l2arc_read_callback_t *cb;
4668185029Spjd	arc_buf_hdr_t *hdr;
4669185029Spjd	arc_buf_t *buf;
4670185029Spjd	kmutex_t *hash_lock;
4671185029Spjd	int equal;
4672185029Spjd
4673185029Spjd	ASSERT(zio->io_vd != NULL);
4674185029Spjd	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
4675185029Spjd
4676185029Spjd	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
4677185029Spjd
4678185029Spjd	cb = zio->io_private;
4679185029Spjd	ASSERT(cb != NULL);
4680185029Spjd	buf = cb->l2rcb_buf;
4681185029Spjd	ASSERT(buf != NULL);
4682185029Spjd
4683219089Spjd	hash_lock = HDR_LOCK(buf->b_hdr);
4684185029Spjd	mutex_enter(hash_lock);
4685219089Spjd	hdr = buf->b_hdr;
4686219089Spjd	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4687185029Spjd
4688185029Spjd	/*
4689251478Sdelphij	 * If the buffer was compressed, decompress it first.
4690251478Sdelphij	 */
4691251478Sdelphij	if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
4692251478Sdelphij		l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
4693251478Sdelphij	ASSERT(zio->io_data != NULL);
4694251478Sdelphij
4695251478Sdelphij	/*
4696185029Spjd	 * Check this survived the L2ARC journey.
4697185029Spjd	 */
4698185029Spjd	equal = arc_cksum_equal(buf);
4699185029Spjd	if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
4700185029Spjd		mutex_exit(hash_lock);
4701185029Spjd		zio->io_private = buf;
4702185029Spjd		zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
4703185029Spjd		zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
4704185029Spjd		arc_read_done(zio);
4705185029Spjd	} else {
4706185029Spjd		mutex_exit(hash_lock);
4707185029Spjd		/*
4708185029Spjd		 * Buffer didn't survive caching.  Increment stats and
4709185029Spjd		 * reissue to the original storage device.
4710185029Spjd		 */
4711185029Spjd		if (zio->io_error != 0) {
4712185029Spjd			ARCSTAT_BUMP(arcstat_l2_io_error);
4713185029Spjd		} else {
4714249195Smm			zio->io_error = SET_ERROR(EIO);
4715185029Spjd		}
4716185029Spjd		if (!equal)
4717185029Spjd			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
4718185029Spjd
4719185029Spjd		/*
4720185029Spjd		 * If there's no waiter, issue an async i/o to the primary
4721185029Spjd		 * storage now.  If there *is* a waiter, the caller must
4722185029Spjd		 * issue the i/o in a context where it's OK to block.
4723185029Spjd		 */
4724209962Smm		if (zio->io_waiter == NULL) {
4725209962Smm			zio_t *pio = zio_unique_parent(zio);
4726209962Smm
4727209962Smm			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
4728209962Smm
4729209962Smm			zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
4730185029Spjd			    buf->b_data, zio->io_size, arc_read_done, buf,
4731185029Spjd			    zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
4732209962Smm		}
4733185029Spjd	}
4734185029Spjd
4735185029Spjd	kmem_free(cb, sizeof (l2arc_read_callback_t));
4736185029Spjd}
4737185029Spjd
4738185029Spjd/*
4739185029Spjd * This is the list priority from which the L2ARC will search for pages to
4740185029Spjd * cache.  This is used within loops (0..3) to cycle through lists in the
4741185029Spjd * desired order.  This order can have a significant effect on cache
4742185029Spjd * performance.
4743185029Spjd *
4744185029Spjd * Currently the metadata lists are hit first, MFU then MRU, followed by
4745185029Spjd * the data lists.  This function returns a locked list, and also returns
4746185029Spjd * the lock pointer.
4747185029Spjd */
4748185029Spjdstatic list_t *
4749185029Spjdl2arc_list_locked(int list_num, kmutex_t **lock)
4750185029Spjd{
4751247187Smm	list_t *list = NULL;
4752205231Skmacy	int idx;
4753185029Spjd
4754206796Spjd	ASSERT(list_num >= 0 && list_num < 2 * ARC_BUFC_NUMLISTS);
4755206796Spjd
4756205231Skmacy	if (list_num < ARC_BUFC_NUMMETADATALISTS) {
4757205231Skmacy		idx = list_num;
4758205231Skmacy		list = &arc_mfu->arcs_lists[idx];
4759205231Skmacy		*lock = ARCS_LOCK(arc_mfu, idx);
4760206796Spjd	} else if (list_num < ARC_BUFC_NUMMETADATALISTS * 2) {
4761205231Skmacy		idx = list_num - ARC_BUFC_NUMMETADATALISTS;
4762205231Skmacy		list = &arc_mru->arcs_lists[idx];
4763205231Skmacy		*lock = ARCS_LOCK(arc_mru, idx);
4764206796Spjd	} else if (list_num < (ARC_BUFC_NUMMETADATALISTS * 2 +
4765205231Skmacy		ARC_BUFC_NUMDATALISTS)) {
4766205231Skmacy		idx = list_num - ARC_BUFC_NUMMETADATALISTS;
4767205231Skmacy		list = &arc_mfu->arcs_lists[idx];
4768205231Skmacy		*lock = ARCS_LOCK(arc_mfu, idx);
4769205231Skmacy	} else {
4770205231Skmacy		idx = list_num - ARC_BUFC_NUMLISTS;
4771205231Skmacy		list = &arc_mru->arcs_lists[idx];
4772205231Skmacy		*lock = ARCS_LOCK(arc_mru, idx);
4773185029Spjd	}
4774185029Spjd
4775185029Spjd	ASSERT(!(MUTEX_HELD(*lock)));
4776185029Spjd	mutex_enter(*lock);
4777185029Spjd	return (list);
4778185029Spjd}
4779185029Spjd
4780185029Spjd/*
4781185029Spjd * Evict buffers from the device write hand to the distance specified in
4782185029Spjd * bytes.  This distance may span populated buffers, it may span nothing.
4783185029Spjd * This is clearing a region on the L2ARC device ready for writing.
4784185029Spjd * If the 'all' boolean is set, every buffer is evicted.
4785185029Spjd */
4786185029Spjdstatic void
4787185029Spjdl2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
4788185029Spjd{
4789185029Spjd	list_t *buflist;
4790185029Spjd	l2arc_buf_hdr_t *abl2;
4791185029Spjd	arc_buf_hdr_t *ab, *ab_prev;
4792185029Spjd	kmutex_t *hash_lock;
4793185029Spjd	uint64_t taddr;
4794268085Sdelphij	int64_t bytes_evicted = 0;
4795185029Spjd
4796185029Spjd	buflist = dev->l2ad_buflist;
4797185029Spjd
4798185029Spjd	if (buflist == NULL)
4799185029Spjd		return;
4800185029Spjd
4801185029Spjd	if (!all && dev->l2ad_first) {
4802185029Spjd		/*
4803185029Spjd		 * This is the first sweep through the device.  There is
4804185029Spjd		 * nothing to evict.
4805185029Spjd		 */
4806185029Spjd		return;
4807185029Spjd	}
4808185029Spjd
4809185029Spjd	if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
4810185029Spjd		/*
4811185029Spjd		 * When nearing the end of the device, evict to the end
4812185029Spjd		 * before the device write hand jumps to the start.
4813185029Spjd		 */
4814185029Spjd		taddr = dev->l2ad_end;
4815185029Spjd	} else {
4816185029Spjd		taddr = dev->l2ad_hand + distance;
4817185029Spjd	}
4818185029Spjd	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
4819185029Spjd	    uint64_t, taddr, boolean_t, all);
4820185029Spjd
4821185029Spjdtop:
4822185029Spjd	mutex_enter(&l2arc_buflist_mtx);
4823185029Spjd	for (ab = list_tail(buflist); ab; ab = ab_prev) {
4824185029Spjd		ab_prev = list_prev(buflist, ab);
4825185029Spjd
4826185029Spjd		hash_lock = HDR_LOCK(ab);
4827185029Spjd		if (!mutex_tryenter(hash_lock)) {
4828185029Spjd			/*
4829185029Spjd			 * Missed the hash lock.  Retry.
4830185029Spjd			 */
4831185029Spjd			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
4832185029Spjd			mutex_exit(&l2arc_buflist_mtx);
4833185029Spjd			mutex_enter(hash_lock);
4834185029Spjd			mutex_exit(hash_lock);
4835185029Spjd			goto top;
4836185029Spjd		}
4837185029Spjd
4838185029Spjd		if (HDR_L2_WRITE_HEAD(ab)) {
4839185029Spjd			/*
4840185029Spjd			 * We hit a write head node.  Leave it for
4841185029Spjd			 * l2arc_write_done().
4842185029Spjd			 */
4843185029Spjd			list_remove(buflist, ab);
4844185029Spjd			mutex_exit(hash_lock);
4845185029Spjd			continue;
4846185029Spjd		}
4847185029Spjd
4848185029Spjd		if (!all && ab->b_l2hdr != NULL &&
4849185029Spjd		    (ab->b_l2hdr->b_daddr > taddr ||
4850185029Spjd		    ab->b_l2hdr->b_daddr < dev->l2ad_hand)) {
4851185029Spjd			/*
4852185029Spjd			 * We've evicted to the target address,
4853185029Spjd			 * or the end of the device.
4854185029Spjd			 */
4855185029Spjd			mutex_exit(hash_lock);
4856185029Spjd			break;
4857185029Spjd		}
4858185029Spjd
4859185029Spjd		if (HDR_FREE_IN_PROGRESS(ab)) {
4860185029Spjd			/*
4861185029Spjd			 * Already on the path to destruction.
4862185029Spjd			 */
4863185029Spjd			mutex_exit(hash_lock);
4864185029Spjd			continue;
4865185029Spjd		}
4866185029Spjd
4867185029Spjd		if (ab->b_state == arc_l2c_only) {
4868185029Spjd			ASSERT(!HDR_L2_READING(ab));
4869185029Spjd			/*
4870185029Spjd			 * This doesn't exist in the ARC.  Destroy.
4871185029Spjd			 * arc_hdr_destroy() will call list_remove()
4872185029Spjd			 * and decrement arcstat_l2_size.
4873185029Spjd			 */
4874185029Spjd			arc_change_state(arc_anon, ab, hash_lock);
4875185029Spjd			arc_hdr_destroy(ab);
4876185029Spjd		} else {
4877185029Spjd			/*
4878185029Spjd			 * Invalidate issued or about to be issued
4879185029Spjd			 * reads, since we may be about to write
4880185029Spjd			 * over this location.
4881185029Spjd			 */
4882185029Spjd			if (HDR_L2_READING(ab)) {
4883185029Spjd				ARCSTAT_BUMP(arcstat_l2_evict_reading);
4884185029Spjd				ab->b_flags |= ARC_L2_EVICTED;
4885185029Spjd			}
4886185029Spjd
4887185029Spjd			/*
4888185029Spjd			 * Tell ARC this no longer exists in L2ARC.
4889185029Spjd			 */
4890185029Spjd			if (ab->b_l2hdr != NULL) {
4891185029Spjd				abl2 = ab->b_l2hdr;
4892251478Sdelphij				ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
4893268085Sdelphij				bytes_evicted += abl2->b_asize;
4894185029Spjd				ab->b_l2hdr = NULL;
4895185029Spjd				kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
4896185029Spjd				ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
4897185029Spjd			}
4898185029Spjd			list_remove(buflist, ab);
4899185029Spjd
4900185029Spjd			/*
4901185029Spjd			 * This may have been leftover after a
4902185029Spjd			 * failed write.
4903185029Spjd			 */
4904185029Spjd			ab->b_flags &= ~ARC_L2_WRITING;
4905185029Spjd		}
4906185029Spjd		mutex_exit(hash_lock);
4907185029Spjd	}
4908185029Spjd	mutex_exit(&l2arc_buflist_mtx);
4909185029Spjd
4910268085Sdelphij	vdev_space_update(dev->l2ad_vdev, -bytes_evicted, 0, 0);
4911185029Spjd	dev->l2ad_evict = taddr;
4912185029Spjd}
4913185029Spjd
4914185029Spjd/*
4915185029Spjd * Find and write ARC buffers to the L2ARC device.
4916185029Spjd *
4917185029Spjd * An ARC_L2_WRITING flag is set so that the L2ARC buffers are not valid
4918185029Spjd * for reading until they have completed writing.
4919251478Sdelphij * The headroom_boost is an in-out parameter used to maintain headroom boost
4920251478Sdelphij * state between calls to this function.
4921251478Sdelphij *
4922251478Sdelphij * Returns the number of bytes actually written (which may be smaller than
4923251478Sdelphij * the delta by which the device hand has changed due to alignment).
4924185029Spjd */
4925208373Smmstatic uint64_t
4926251478Sdelphijl2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
4927251478Sdelphij    boolean_t *headroom_boost)
4928185029Spjd{
4929185029Spjd	arc_buf_hdr_t *ab, *ab_prev, *head;
4930185029Spjd	list_t *list;
4931251478Sdelphij	uint64_t write_asize, write_psize, write_sz, headroom,
4932251478Sdelphij	    buf_compress_minsz;
4933185029Spjd	void *buf_data;
4934251478Sdelphij	kmutex_t *list_lock;
4935251478Sdelphij	boolean_t full;
4936185029Spjd	l2arc_write_callback_t *cb;
4937185029Spjd	zio_t *pio, *wzio;
4938228103Smm	uint64_t guid = spa_load_guid(spa);
4939251478Sdelphij	const boolean_t do_headroom_boost = *headroom_boost;
4940185029Spjd	int try;
4941185029Spjd
4942185029Spjd	ASSERT(dev->l2ad_vdev != NULL);
4943185029Spjd
4944251478Sdelphij	/* Lower the flag now, we might want to raise it again later. */
4945251478Sdelphij	*headroom_boost = B_FALSE;
4946251478Sdelphij
4947185029Spjd	pio = NULL;
4948251478Sdelphij	write_sz = write_asize = write_psize = 0;
4949185029Spjd	full = B_FALSE;
4950185029Spjd	head = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
4951185029Spjd	head->b_flags |= ARC_L2_WRITE_HEAD;
4952185029Spjd
4953205231Skmacy	ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
4954185029Spjd	/*
4955251478Sdelphij	 * We will want to try to compress buffers that are at least 2x the
4956251478Sdelphij	 * device sector size.
4957251478Sdelphij	 */
4958251478Sdelphij	buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
4959251478Sdelphij
4960251478Sdelphij	/*
4961185029Spjd	 * Copy buffers for L2ARC writing.
4962185029Spjd	 */
4963185029Spjd	mutex_enter(&l2arc_buflist_mtx);
4964206796Spjd	for (try = 0; try < 2 * ARC_BUFC_NUMLISTS; try++) {
4965251478Sdelphij		uint64_t passed_sz = 0;
4966251478Sdelphij
4967185029Spjd		list = l2arc_list_locked(try, &list_lock);
4968205231Skmacy		ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
4969185029Spjd
4970185029Spjd		/*
4971185029Spjd		 * L2ARC fast warmup.
4972185029Spjd		 *
4973185029Spjd		 * Until the ARC is warm and starts to evict, read from the
4974185029Spjd		 * head of the ARC lists rather than the tail.
4975185029Spjd		 */
4976185029Spjd		if (arc_warm == B_FALSE)
4977185029Spjd			ab = list_head(list);
4978185029Spjd		else
4979185029Spjd			ab = list_tail(list);
4980206796Spjd		if (ab == NULL)
4981205231Skmacy			ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
4982185029Spjd
4983251478Sdelphij		headroom = target_sz * l2arc_headroom;
4984251478Sdelphij		if (do_headroom_boost)
4985251478Sdelphij			headroom = (headroom * l2arc_headroom_boost) / 100;
4986251478Sdelphij
4987185029Spjd		for (; ab; ab = ab_prev) {
4988251478Sdelphij			l2arc_buf_hdr_t *l2hdr;
4989251478Sdelphij			kmutex_t *hash_lock;
4990251478Sdelphij			uint64_t buf_sz;
4991251478Sdelphij
4992185029Spjd			if (arc_warm == B_FALSE)
4993185029Spjd				ab_prev = list_next(list, ab);
4994185029Spjd			else
4995185029Spjd				ab_prev = list_prev(list, ab);
4996205231Skmacy			ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned, ab->b_size);
4997206796Spjd
4998185029Spjd			hash_lock = HDR_LOCK(ab);
4999251478Sdelphij			if (!mutex_tryenter(hash_lock)) {
5000205231Skmacy				ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
5001185029Spjd				/*
5002185029Spjd				 * Skip this buffer rather than waiting.
5003185029Spjd				 */
5004185029Spjd				continue;
5005185029Spjd			}
5006185029Spjd
5007185029Spjd			passed_sz += ab->b_size;
5008185029Spjd			if (passed_sz > headroom) {
5009185029Spjd				/*
5010185029Spjd				 * Searched too far.
5011185029Spjd				 */
5012185029Spjd				mutex_exit(hash_lock);
5013205231Skmacy				ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
5014185029Spjd				break;
5015185029Spjd			}
5016185029Spjd
5017209962Smm			if (!l2arc_write_eligible(guid, ab)) {
5018185029Spjd				mutex_exit(hash_lock);
5019185029Spjd				continue;
5020185029Spjd			}
5021185029Spjd
5022185029Spjd			if ((write_sz + ab->b_size) > target_sz) {
5023185029Spjd				full = B_TRUE;
5024185029Spjd				mutex_exit(hash_lock);
5025205231Skmacy				ARCSTAT_BUMP(arcstat_l2_write_full);
5026185029Spjd				break;
5027185029Spjd			}
5028185029Spjd
5029185029Spjd			if (pio == NULL) {
5030185029Spjd				/*
5031185029Spjd				 * Insert a dummy header on the buflist so
5032185029Spjd				 * l2arc_write_done() can find where the
5033185029Spjd				 * write buffers begin without searching.
5034185029Spjd				 */
5035185029Spjd				list_insert_head(dev->l2ad_buflist, head);
5036185029Spjd
5037185029Spjd				cb = kmem_alloc(
5038185029Spjd				    sizeof (l2arc_write_callback_t), KM_SLEEP);
5039185029Spjd				cb->l2wcb_dev = dev;
5040185029Spjd				cb->l2wcb_head = head;
5041185029Spjd				pio = zio_root(spa, l2arc_write_done, cb,
5042185029Spjd				    ZIO_FLAG_CANFAIL);
5043205231Skmacy				ARCSTAT_BUMP(arcstat_l2_write_pios);
5044185029Spjd			}
5045185029Spjd
5046185029Spjd			/*
5047185029Spjd			 * Create and add a new L2ARC header.
5048185029Spjd			 */
5049251478Sdelphij			l2hdr = kmem_zalloc(sizeof (l2arc_buf_hdr_t), KM_SLEEP);
5050251478Sdelphij			l2hdr->b_dev = dev;
5051251478Sdelphij			ab->b_flags |= ARC_L2_WRITING;
5052185029Spjd
5053251478Sdelphij			/*
5054251478Sdelphij			 * Temporarily stash the data buffer in b_tmp_cdata.
5055251478Sdelphij			 * The subsequent write step will pick it up from
5056251478Sdelphij			 * there. This is because can't access ab->b_buf
5057251478Sdelphij			 * without holding the hash_lock, which we in turn
5058251478Sdelphij			 * can't access without holding the ARC list locks
5059251478Sdelphij			 * (which we want to avoid during compression/writing).
5060251478Sdelphij			 */
5061251478Sdelphij			l2hdr->b_compress = ZIO_COMPRESS_OFF;
5062251478Sdelphij			l2hdr->b_asize = ab->b_size;
5063251478Sdelphij			l2hdr->b_tmp_cdata = ab->b_buf->b_data;
5064251478Sdelphij
5065185029Spjd			buf_sz = ab->b_size;
5066251478Sdelphij			ab->b_l2hdr = l2hdr;
5067185029Spjd
5068251478Sdelphij			list_insert_head(dev->l2ad_buflist, ab);
5069251478Sdelphij
5070185029Spjd			/*
5071185029Spjd			 * Compute and store the buffer cksum before
5072185029Spjd			 * writing.  On debug the cksum is verified first.
5073185029Spjd			 */
5074185029Spjd			arc_cksum_verify(ab->b_buf);
5075185029Spjd			arc_cksum_compute(ab->b_buf, B_TRUE);
5076185029Spjd
5077185029Spjd			mutex_exit(hash_lock);
5078185029Spjd
5079251478Sdelphij			write_sz += buf_sz;
5080251478Sdelphij		}
5081251478Sdelphij
5082251478Sdelphij		mutex_exit(list_lock);
5083251478Sdelphij
5084251478Sdelphij		if (full == B_TRUE)
5085251478Sdelphij			break;
5086251478Sdelphij	}
5087251478Sdelphij
5088251478Sdelphij	/* No buffers selected for writing? */
5089251478Sdelphij	if (pio == NULL) {
5090251478Sdelphij		ASSERT0(write_sz);
5091251478Sdelphij		mutex_exit(&l2arc_buflist_mtx);
5092251478Sdelphij		kmem_cache_free(hdr_cache, head);
5093251478Sdelphij		return (0);
5094251478Sdelphij	}
5095251478Sdelphij
5096251478Sdelphij	/*
5097251478Sdelphij	 * Now start writing the buffers. We're starting at the write head
5098251478Sdelphij	 * and work backwards, retracing the course of the buffer selector
5099251478Sdelphij	 * loop above.
5100251478Sdelphij	 */
5101251478Sdelphij	for (ab = list_prev(dev->l2ad_buflist, head); ab;
5102251478Sdelphij	    ab = list_prev(dev->l2ad_buflist, ab)) {
5103251478Sdelphij		l2arc_buf_hdr_t *l2hdr;
5104251478Sdelphij		uint64_t buf_sz;
5105251478Sdelphij
5106251478Sdelphij		/*
5107251478Sdelphij		 * We shouldn't need to lock the buffer here, since we flagged
5108251478Sdelphij		 * it as ARC_L2_WRITING in the previous step, but we must take
5109251478Sdelphij		 * care to only access its L2 cache parameters. In particular,
5110251478Sdelphij		 * ab->b_buf may be invalid by now due to ARC eviction.
5111251478Sdelphij		 */
5112251478Sdelphij		l2hdr = ab->b_l2hdr;
5113251478Sdelphij		l2hdr->b_daddr = dev->l2ad_hand;
5114251478Sdelphij
5115251478Sdelphij		if ((ab->b_flags & ARC_L2COMPRESS) &&
5116251478Sdelphij		    l2hdr->b_asize >= buf_compress_minsz) {
5117251478Sdelphij			if (l2arc_compress_buf(l2hdr)) {
5118251478Sdelphij				/*
5119251478Sdelphij				 * If compression succeeded, enable headroom
5120251478Sdelphij				 * boost on the next scan cycle.
5121251478Sdelphij				 */
5122251478Sdelphij				*headroom_boost = B_TRUE;
5123251478Sdelphij			}
5124251478Sdelphij		}
5125251478Sdelphij
5126251478Sdelphij		/*
5127251478Sdelphij		 * Pick up the buffer data we had previously stashed away
5128251478Sdelphij		 * (and now potentially also compressed).
5129251478Sdelphij		 */
5130251478Sdelphij		buf_data = l2hdr->b_tmp_cdata;
5131251478Sdelphij		buf_sz = l2hdr->b_asize;
5132251478Sdelphij
5133251478Sdelphij		/* Compression may have squashed the buffer to zero length. */
5134251478Sdelphij		if (buf_sz != 0) {
5135251478Sdelphij			uint64_t buf_p_sz;
5136251478Sdelphij
5137185029Spjd			wzio = zio_write_phys(pio, dev->l2ad_vdev,
5138185029Spjd			    dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
5139185029Spjd			    NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
5140185029Spjd			    ZIO_FLAG_CANFAIL, B_FALSE);
5141185029Spjd
5142185029Spjd			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
5143185029Spjd			    zio_t *, wzio);
5144185029Spjd			(void) zio_nowait(wzio);
5145185029Spjd
5146251478Sdelphij			write_asize += buf_sz;
5147185029Spjd			/*
5148185029Spjd			 * Keep the clock hand suitably device-aligned.
5149185029Spjd			 */
5150251478Sdelphij			buf_p_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
5151251478Sdelphij			write_psize += buf_p_sz;
5152251478Sdelphij			dev->l2ad_hand += buf_p_sz;
5153185029Spjd		}
5154251478Sdelphij	}
5155185029Spjd
5156185029Spjd	mutex_exit(&l2arc_buflist_mtx);
5157185029Spjd
5158251478Sdelphij	ASSERT3U(write_asize, <=, target_sz);
5159185029Spjd	ARCSTAT_BUMP(arcstat_l2_writes_sent);
5160251478Sdelphij	ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
5161185029Spjd	ARCSTAT_INCR(arcstat_l2_size, write_sz);
5162251478Sdelphij	ARCSTAT_INCR(arcstat_l2_asize, write_asize);
5163268085Sdelphij	vdev_space_update(dev->l2ad_vdev, write_asize, 0, 0);
5164185029Spjd
5165185029Spjd	/*
5166185029Spjd	 * Bump device hand to the device start if it is approaching the end.
5167185029Spjd	 * l2arc_evict() will already have evicted ahead for this case.
5168185029Spjd	 */
5169185029Spjd	if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
5170185029Spjd		dev->l2ad_hand = dev->l2ad_start;
5171185029Spjd		dev->l2ad_evict = dev->l2ad_start;
5172185029Spjd		dev->l2ad_first = B_FALSE;
5173185029Spjd	}
5174185029Spjd
5175208373Smm	dev->l2ad_writing = B_TRUE;
5176185029Spjd	(void) zio_wait(pio);
5177208373Smm	dev->l2ad_writing = B_FALSE;
5178208373Smm
5179251478Sdelphij	return (write_asize);
5180185029Spjd}
5181185029Spjd
5182185029Spjd/*
5183251478Sdelphij * Compresses an L2ARC buffer.
5184251478Sdelphij * The data to be compressed must be prefilled in l2hdr->b_tmp_cdata and its
5185251478Sdelphij * size in l2hdr->b_asize. This routine tries to compress the data and
5186251478Sdelphij * depending on the compression result there are three possible outcomes:
5187251478Sdelphij * *) The buffer was incompressible. The original l2hdr contents were left
5188251478Sdelphij *    untouched and are ready for writing to an L2 device.
5189251478Sdelphij * *) The buffer was all-zeros, so there is no need to write it to an L2
5190251478Sdelphij *    device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
5191251478Sdelphij *    set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
5192251478Sdelphij * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
5193251478Sdelphij *    data buffer which holds the compressed data to be written, and b_asize
5194251478Sdelphij *    tells us how much data there is. b_compress is set to the appropriate
5195251478Sdelphij *    compression algorithm. Once writing is done, invoke
5196251478Sdelphij *    l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
5197251478Sdelphij *
5198251478Sdelphij * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
5199251478Sdelphij * buffer was incompressible).
5200251478Sdelphij */
5201251478Sdelphijstatic boolean_t
5202251478Sdelphijl2arc_compress_buf(l2arc_buf_hdr_t *l2hdr)
5203251478Sdelphij{
5204251478Sdelphij	void *cdata;
5205268075Sdelphij	size_t csize, len, rounded;
5206251478Sdelphij
5207251478Sdelphij	ASSERT(l2hdr->b_compress == ZIO_COMPRESS_OFF);
5208251478Sdelphij	ASSERT(l2hdr->b_tmp_cdata != NULL);
5209251478Sdelphij
5210251478Sdelphij	len = l2hdr->b_asize;
5211251478Sdelphij	cdata = zio_data_buf_alloc(len);
5212251478Sdelphij	csize = zio_compress_data(ZIO_COMPRESS_LZ4, l2hdr->b_tmp_cdata,
5213269086Sdelphij	    cdata, l2hdr->b_asize);
5214251478Sdelphij
5215268075Sdelphij	rounded = P2ROUNDUP(csize, (size_t)SPA_MINBLOCKSIZE);
5216268075Sdelphij	if (rounded > csize) {
5217268075Sdelphij		bzero((char *)cdata + csize, rounded - csize);
5218268075Sdelphij		csize = rounded;
5219268075Sdelphij	}
5220268075Sdelphij
5221251478Sdelphij	if (csize == 0) {
5222251478Sdelphij		/* zero block, indicate that there's nothing to write */
5223251478Sdelphij		zio_data_buf_free(cdata, len);
5224251478Sdelphij		l2hdr->b_compress = ZIO_COMPRESS_EMPTY;
5225251478Sdelphij		l2hdr->b_asize = 0;
5226251478Sdelphij		l2hdr->b_tmp_cdata = NULL;
5227251478Sdelphij		ARCSTAT_BUMP(arcstat_l2_compress_zeros);
5228251478Sdelphij		return (B_TRUE);
5229251478Sdelphij	} else if (csize > 0 && csize < len) {
5230251478Sdelphij		/*
5231251478Sdelphij		 * Compression succeeded, we'll keep the cdata around for
5232251478Sdelphij		 * writing and release it afterwards.
5233251478Sdelphij		 */
5234251478Sdelphij		l2hdr->b_compress = ZIO_COMPRESS_LZ4;
5235251478Sdelphij		l2hdr->b_asize = csize;
5236251478Sdelphij		l2hdr->b_tmp_cdata = cdata;
5237251478Sdelphij		ARCSTAT_BUMP(arcstat_l2_compress_successes);
5238251478Sdelphij		return (B_TRUE);
5239251478Sdelphij	} else {
5240251478Sdelphij		/*
5241251478Sdelphij		 * Compression failed, release the compressed buffer.
5242251478Sdelphij		 * l2hdr will be left unmodified.
5243251478Sdelphij		 */
5244251478Sdelphij		zio_data_buf_free(cdata, len);
5245251478Sdelphij		ARCSTAT_BUMP(arcstat_l2_compress_failures);
5246251478Sdelphij		return (B_FALSE);
5247251478Sdelphij	}
5248251478Sdelphij}
5249251478Sdelphij
5250251478Sdelphij/*
5251251478Sdelphij * Decompresses a zio read back from an l2arc device. On success, the
5252251478Sdelphij * underlying zio's io_data buffer is overwritten by the uncompressed
5253251478Sdelphij * version. On decompression error (corrupt compressed stream), the
5254251478Sdelphij * zio->io_error value is set to signal an I/O error.
5255251478Sdelphij *
5256251478Sdelphij * Please note that the compressed data stream is not checksummed, so
5257251478Sdelphij * if the underlying device is experiencing data corruption, we may feed
5258251478Sdelphij * corrupt data to the decompressor, so the decompressor needs to be
5259251478Sdelphij * able to handle this situation (LZ4 does).
5260251478Sdelphij */
5261251478Sdelphijstatic void
5262251478Sdelphijl2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
5263251478Sdelphij{
5264251478Sdelphij	ASSERT(L2ARC_IS_VALID_COMPRESS(c));
5265251478Sdelphij
5266251478Sdelphij	if (zio->io_error != 0) {
5267251478Sdelphij		/*
5268251478Sdelphij		 * An io error has occured, just restore the original io
5269251478Sdelphij		 * size in preparation for a main pool read.
5270251478Sdelphij		 */
5271251478Sdelphij		zio->io_orig_size = zio->io_size = hdr->b_size;
5272251478Sdelphij		return;
5273251478Sdelphij	}
5274251478Sdelphij
5275251478Sdelphij	if (c == ZIO_COMPRESS_EMPTY) {
5276251478Sdelphij		/*
5277251478Sdelphij		 * An empty buffer results in a null zio, which means we
5278251478Sdelphij		 * need to fill its io_data after we're done restoring the
5279251478Sdelphij		 * buffer's contents.
5280251478Sdelphij		 */
5281251478Sdelphij		ASSERT(hdr->b_buf != NULL);
5282251478Sdelphij		bzero(hdr->b_buf->b_data, hdr->b_size);
5283251478Sdelphij		zio->io_data = zio->io_orig_data = hdr->b_buf->b_data;
5284251478Sdelphij	} else {
5285251478Sdelphij		ASSERT(zio->io_data != NULL);
5286251478Sdelphij		/*
5287251478Sdelphij		 * We copy the compressed data from the start of the arc buffer
5288251478Sdelphij		 * (the zio_read will have pulled in only what we need, the
5289251478Sdelphij		 * rest is garbage which we will overwrite at decompression)
5290251478Sdelphij		 * and then decompress back to the ARC data buffer. This way we
5291251478Sdelphij		 * can minimize copying by simply decompressing back over the
5292251478Sdelphij		 * original compressed data (rather than decompressing to an
5293251478Sdelphij		 * aux buffer and then copying back the uncompressed buffer,
5294251478Sdelphij		 * which is likely to be much larger).
5295251478Sdelphij		 */
5296251478Sdelphij		uint64_t csize;
5297251478Sdelphij		void *cdata;
5298251478Sdelphij
5299251478Sdelphij		csize = zio->io_size;
5300251478Sdelphij		cdata = zio_data_buf_alloc(csize);
5301251478Sdelphij		bcopy(zio->io_data, cdata, csize);
5302251478Sdelphij		if (zio_decompress_data(c, cdata, zio->io_data, csize,
5303251478Sdelphij		    hdr->b_size) != 0)
5304251478Sdelphij			zio->io_error = EIO;
5305251478Sdelphij		zio_data_buf_free(cdata, csize);
5306251478Sdelphij	}
5307251478Sdelphij
5308251478Sdelphij	/* Restore the expected uncompressed IO size. */
5309251478Sdelphij	zio->io_orig_size = zio->io_size = hdr->b_size;
5310251478Sdelphij}
5311251478Sdelphij
5312251478Sdelphij/*
5313251478Sdelphij * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
5314251478Sdelphij * This buffer serves as a temporary holder of compressed data while
5315251478Sdelphij * the buffer entry is being written to an l2arc device. Once that is
5316251478Sdelphij * done, we can dispose of it.
5317251478Sdelphij */
5318251478Sdelphijstatic void
5319251478Sdelphijl2arc_release_cdata_buf(arc_buf_hdr_t *ab)
5320251478Sdelphij{
5321251478Sdelphij	l2arc_buf_hdr_t *l2hdr = ab->b_l2hdr;
5322251478Sdelphij
5323251478Sdelphij	if (l2hdr->b_compress == ZIO_COMPRESS_LZ4) {
5324251478Sdelphij		/*
5325251478Sdelphij		 * If the data was compressed, then we've allocated a
5326251478Sdelphij		 * temporary buffer for it, so now we need to release it.
5327251478Sdelphij		 */
5328251478Sdelphij		ASSERT(l2hdr->b_tmp_cdata != NULL);
5329251478Sdelphij		zio_data_buf_free(l2hdr->b_tmp_cdata, ab->b_size);
5330251478Sdelphij	}
5331251478Sdelphij	l2hdr->b_tmp_cdata = NULL;
5332251478Sdelphij}
5333251478Sdelphij
5334251478Sdelphij/*
5335185029Spjd * This thread feeds the L2ARC at regular intervals.  This is the beating
5336185029Spjd * heart of the L2ARC.
5337185029Spjd */
5338185029Spjdstatic void
5339185029Spjdl2arc_feed_thread(void *dummy __unused)
5340185029Spjd{
5341185029Spjd	callb_cpr_t cpr;
5342185029Spjd	l2arc_dev_t *dev;
5343185029Spjd	spa_t *spa;
5344208373Smm	uint64_t size, wrote;
5345219089Spjd	clock_t begin, next = ddi_get_lbolt();
5346251478Sdelphij	boolean_t headroom_boost = B_FALSE;
5347185029Spjd
5348185029Spjd	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
5349185029Spjd
5350185029Spjd	mutex_enter(&l2arc_feed_thr_lock);
5351185029Spjd
5352185029Spjd	while (l2arc_thread_exit == 0) {
5353185029Spjd		CALLB_CPR_SAFE_BEGIN(&cpr);
5354185029Spjd		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
5355219089Spjd		    next - ddi_get_lbolt());
5356185029Spjd		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
5357219089Spjd		next = ddi_get_lbolt() + hz;
5358185029Spjd
5359185029Spjd		/*
5360185029Spjd		 * Quick check for L2ARC devices.
5361185029Spjd		 */
5362185029Spjd		mutex_enter(&l2arc_dev_mtx);
5363185029Spjd		if (l2arc_ndev == 0) {
5364185029Spjd			mutex_exit(&l2arc_dev_mtx);
5365185029Spjd			continue;
5366185029Spjd		}
5367185029Spjd		mutex_exit(&l2arc_dev_mtx);
5368219089Spjd		begin = ddi_get_lbolt();
5369185029Spjd
5370185029Spjd		/*
5371185029Spjd		 * This selects the next l2arc device to write to, and in
5372185029Spjd		 * doing so the next spa to feed from: dev->l2ad_spa.   This
5373185029Spjd		 * will return NULL if there are now no l2arc devices or if
5374185029Spjd		 * they are all faulted.
5375185029Spjd		 *
5376185029Spjd		 * If a device is returned, its spa's config lock is also
5377185029Spjd		 * held to prevent device removal.  l2arc_dev_get_next()
5378185029Spjd		 * will grab and release l2arc_dev_mtx.
5379185029Spjd		 */
5380185029Spjd		if ((dev = l2arc_dev_get_next()) == NULL)
5381185029Spjd			continue;
5382185029Spjd
5383185029Spjd		spa = dev->l2ad_spa;
5384185029Spjd		ASSERT(spa != NULL);
5385185029Spjd
5386185029Spjd		/*
5387219089Spjd		 * If the pool is read-only then force the feed thread to
5388219089Spjd		 * sleep a little longer.
5389219089Spjd		 */
5390219089Spjd		if (!spa_writeable(spa)) {
5391219089Spjd			next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
5392219089Spjd			spa_config_exit(spa, SCL_L2ARC, dev);
5393219089Spjd			continue;
5394219089Spjd		}
5395219089Spjd
5396219089Spjd		/*
5397185029Spjd		 * Avoid contributing to memory pressure.
5398185029Spjd		 */
5399185029Spjd		if (arc_reclaim_needed()) {
5400185029Spjd			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
5401185029Spjd			spa_config_exit(spa, SCL_L2ARC, dev);
5402185029Spjd			continue;
5403185029Spjd		}
5404185029Spjd
5405185029Spjd		ARCSTAT_BUMP(arcstat_l2_feeds);
5406185029Spjd
5407251478Sdelphij		size = l2arc_write_size();
5408185029Spjd
5409185029Spjd		/*
5410185029Spjd		 * Evict L2ARC buffers that will be overwritten.
5411185029Spjd		 */
5412185029Spjd		l2arc_evict(dev, size, B_FALSE);
5413185029Spjd
5414185029Spjd		/*
5415185029Spjd		 * Write ARC buffers.
5416185029Spjd		 */
5417251478Sdelphij		wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
5418208373Smm
5419208373Smm		/*
5420208373Smm		 * Calculate interval between writes.
5421208373Smm		 */
5422208373Smm		next = l2arc_write_interval(begin, size, wrote);
5423185029Spjd		spa_config_exit(spa, SCL_L2ARC, dev);
5424185029Spjd	}
5425185029Spjd
5426185029Spjd	l2arc_thread_exit = 0;
5427185029Spjd	cv_broadcast(&l2arc_feed_thr_cv);
5428185029Spjd	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
5429185029Spjd	thread_exit();
5430185029Spjd}
5431185029Spjd
5432185029Spjdboolean_t
5433185029Spjdl2arc_vdev_present(vdev_t *vd)
5434185029Spjd{
5435185029Spjd	l2arc_dev_t *dev;
5436185029Spjd
5437185029Spjd	mutex_enter(&l2arc_dev_mtx);
5438185029Spjd	for (dev = list_head(l2arc_dev_list); dev != NULL;
5439185029Spjd	    dev = list_next(l2arc_dev_list, dev)) {
5440185029Spjd		if (dev->l2ad_vdev == vd)
5441185029Spjd			break;
5442185029Spjd	}
5443185029Spjd	mutex_exit(&l2arc_dev_mtx);
5444185029Spjd
5445185029Spjd	return (dev != NULL);
5446185029Spjd}
5447185029Spjd
5448185029Spjd/*
5449185029Spjd * Add a vdev for use by the L2ARC.  By this point the spa has already
5450185029Spjd * validated the vdev and opened it.
5451185029Spjd */
5452185029Spjdvoid
5453219089Spjdl2arc_add_vdev(spa_t *spa, vdev_t *vd)
5454185029Spjd{
5455185029Spjd	l2arc_dev_t *adddev;
5456185029Spjd
5457185029Spjd	ASSERT(!l2arc_vdev_present(vd));
5458185029Spjd
5459255753Sgibbs	vdev_ashift_optimize(vd);
5460255753Sgibbs
5461185029Spjd	/*
5462185029Spjd	 * Create a new l2arc device entry.
5463185029Spjd	 */
5464185029Spjd	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
5465185029Spjd	adddev->l2ad_spa = spa;
5466185029Spjd	adddev->l2ad_vdev = vd;
5467219089Spjd	adddev->l2ad_start = VDEV_LABEL_START_SIZE;
5468219089Spjd	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
5469185029Spjd	adddev->l2ad_hand = adddev->l2ad_start;
5470185029Spjd	adddev->l2ad_evict = adddev->l2ad_start;
5471185029Spjd	adddev->l2ad_first = B_TRUE;
5472208373Smm	adddev->l2ad_writing = B_FALSE;
5473185029Spjd
5474185029Spjd	/*
5475185029Spjd	 * This is a list of all ARC buffers that are still valid on the
5476185029Spjd	 * device.
5477185029Spjd	 */
5478185029Spjd	adddev->l2ad_buflist = kmem_zalloc(sizeof (list_t), KM_SLEEP);
5479185029Spjd	list_create(adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
5480185029Spjd	    offsetof(arc_buf_hdr_t, b_l2node));
5481185029Spjd
5482219089Spjd	vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
5483185029Spjd
5484185029Spjd	/*
5485185029Spjd	 * Add device to global list
5486185029Spjd	 */
5487185029Spjd	mutex_enter(&l2arc_dev_mtx);
5488185029Spjd	list_insert_head(l2arc_dev_list, adddev);
5489185029Spjd	atomic_inc_64(&l2arc_ndev);
5490185029Spjd	mutex_exit(&l2arc_dev_mtx);
5491185029Spjd}
5492185029Spjd
5493185029Spjd/*
5494185029Spjd * Remove a vdev from the L2ARC.
5495185029Spjd */
5496185029Spjdvoid
5497185029Spjdl2arc_remove_vdev(vdev_t *vd)
5498185029Spjd{
5499185029Spjd	l2arc_dev_t *dev, *nextdev, *remdev = NULL;
5500185029Spjd
5501185029Spjd	/*
5502185029Spjd	 * Find the device by vdev
5503185029Spjd	 */
5504185029Spjd	mutex_enter(&l2arc_dev_mtx);
5505185029Spjd	for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
5506185029Spjd		nextdev = list_next(l2arc_dev_list, dev);
5507185029Spjd		if (vd == dev->l2ad_vdev) {
5508185029Spjd			remdev = dev;
5509185029Spjd			break;
5510185029Spjd		}
5511185029Spjd	}
5512185029Spjd	ASSERT(remdev != NULL);
5513185029Spjd
5514185029Spjd	/*
5515185029Spjd	 * Remove device from global list
5516185029Spjd	 */
5517185029Spjd	list_remove(l2arc_dev_list, remdev);
5518185029Spjd	l2arc_dev_last = NULL;		/* may have been invalidated */
5519185029Spjd	atomic_dec_64(&l2arc_ndev);
5520185029Spjd	mutex_exit(&l2arc_dev_mtx);
5521185029Spjd
5522185029Spjd	/*
5523185029Spjd	 * Clear all buflists and ARC references.  L2ARC device flush.
5524185029Spjd	 */
5525185029Spjd	l2arc_evict(remdev, 0, B_TRUE);
5526185029Spjd	list_destroy(remdev->l2ad_buflist);
5527185029Spjd	kmem_free(remdev->l2ad_buflist, sizeof (list_t));
5528185029Spjd	kmem_free(remdev, sizeof (l2arc_dev_t));
5529185029Spjd}
5530185029Spjd
5531185029Spjdvoid
5532185029Spjdl2arc_init(void)
5533185029Spjd{
5534185029Spjd	l2arc_thread_exit = 0;
5535185029Spjd	l2arc_ndev = 0;
5536185029Spjd	l2arc_writes_sent = 0;
5537185029Spjd	l2arc_writes_done = 0;
5538185029Spjd
5539185029Spjd	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
5540185029Spjd	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
5541185029Spjd	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
5542185029Spjd	mutex_init(&l2arc_buflist_mtx, NULL, MUTEX_DEFAULT, NULL);
5543185029Spjd	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
5544185029Spjd
5545185029Spjd	l2arc_dev_list = &L2ARC_dev_list;
5546185029Spjd	l2arc_free_on_write = &L2ARC_free_on_write;
5547185029Spjd	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
5548185029Spjd	    offsetof(l2arc_dev_t, l2ad_node));
5549185029Spjd	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
5550185029Spjd	    offsetof(l2arc_data_free_t, l2df_list_node));
5551185029Spjd}
5552185029Spjd
5553185029Spjdvoid
5554185029Spjdl2arc_fini(void)
5555185029Spjd{
5556185029Spjd	/*
5557185029Spjd	 * This is called from dmu_fini(), which is called from spa_fini();
5558185029Spjd	 * Because of this, we can assume that all l2arc devices have
5559185029Spjd	 * already been removed when the pools themselves were removed.
5560185029Spjd	 */
5561185029Spjd
5562185029Spjd	l2arc_do_free_on_write();
5563185029Spjd
5564185029Spjd	mutex_destroy(&l2arc_feed_thr_lock);
5565185029Spjd	cv_destroy(&l2arc_feed_thr_cv);
5566185029Spjd	mutex_destroy(&l2arc_dev_mtx);
5567185029Spjd	mutex_destroy(&l2arc_buflist_mtx);
5568185029Spjd	mutex_destroy(&l2arc_free_on_write_mtx);
5569185029Spjd
5570185029Spjd	list_destroy(l2arc_dev_list);
5571185029Spjd	list_destroy(l2arc_free_on_write);
5572185029Spjd}
5573185029Spjd
5574185029Spjdvoid
5575185029Spjdl2arc_start(void)
5576185029Spjd{
5577209962Smm	if (!(spa_mode_global & FWRITE))
5578185029Spjd		return;
5579185029Spjd
5580185029Spjd	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
5581185029Spjd	    TS_RUN, minclsyspri);
5582185029Spjd}
5583185029Spjd
5584185029Spjdvoid
5585185029Spjdl2arc_stop(void)
5586185029Spjd{
5587209962Smm	if (!(spa_mode_global & FWRITE))
5588185029Spjd		return;
5589185029Spjd
5590185029Spjd	mutex_enter(&l2arc_feed_thr_lock);
5591185029Spjd	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
5592185029Spjd	l2arc_thread_exit = 1;
5593185029Spjd	while (l2arc_thread_exit != 0)
5594185029Spjd		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
5595185029Spjd	mutex_exit(&l2arc_feed_thr_lock);
5596185029Spjd}
5597