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