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