arc.c revision 338456
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	 * Re-sum ARC stats after the first round of evictions.
4123	 */
4124	asize = aggsum_value(&arc_size);
4125	ameta = aggsum_value(&arc_meta_used);
4126
4127	/*
4128	 * Adjust MFU size
4129	 *
4130	 * Now that we've tried to evict enough from the MRU to get its
4131	 * size back to arc_p, if we're still above the target cache
4132	 * size, we evict the rest from the MFU.
4133	 */
4134	target = asize - arc_c;
4135
4136	if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
4137	    ameta > arc_meta_min) {
4138		bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4139		total_evicted += bytes;
4140
4141		/*
4142		 * If we couldn't evict our target number of bytes from
4143		 * metadata, we try to get the rest from data.
4144		 */
4145		target -= bytes;
4146
4147		total_evicted +=
4148		    arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
4149	} else {
4150		bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
4151		total_evicted += bytes;
4152
4153		/*
4154		 * If we couldn't evict our target number of bytes from
4155		 * data, we try to get the rest from data.
4156		 */
4157		target -= bytes;
4158
4159		total_evicted +=
4160		    arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4161	}
4162
4163	/*
4164	 * Adjust ghost lists
4165	 *
4166	 * In addition to the above, the ARC also defines target values
4167	 * for the ghost lists. The sum of the mru list and mru ghost
4168	 * list should never exceed the target size of the cache, and
4169	 * the sum of the mru list, mfu list, mru ghost list, and mfu
4170	 * ghost list should never exceed twice the target size of the
4171	 * cache. The following logic enforces these limits on the ghost
4172	 * caches, and evicts from them as needed.
4173	 */
4174	target = refcount_count(&arc_mru->arcs_size) +
4175	    refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
4176
4177	bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
4178	total_evicted += bytes;
4179
4180	target -= bytes;
4181
4182	total_evicted +=
4183	    arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
4184
4185	/*
4186	 * We assume the sum of the mru list and mfu list is less than
4187	 * or equal to arc_c (we enforced this above), which means we
4188	 * can use the simpler of the two equations below:
4189	 *
4190	 *	mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
4191	 *		    mru ghost + mfu ghost <= arc_c
4192	 */
4193	target = refcount_count(&arc_mru_ghost->arcs_size) +
4194	    refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
4195
4196	bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
4197	total_evicted += bytes;
4198
4199	target -= bytes;
4200
4201	total_evicted +=
4202	    arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
4203
4204	return (total_evicted);
4205}
4206
4207void
4208arc_flush(spa_t *spa, boolean_t retry)
4209{
4210	uint64_t guid = 0;
4211
4212	/*
4213	 * If retry is B_TRUE, a spa must not be specified since we have
4214	 * no good way to determine if all of a spa's buffers have been
4215	 * evicted from an arc state.
4216	 */
4217	ASSERT(!retry || spa == 0);
4218
4219	if (spa != NULL)
4220		guid = spa_load_guid(spa);
4221
4222	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
4223	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
4224
4225	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
4226	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
4227
4228	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
4229	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
4230
4231	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
4232	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
4233}
4234
4235void
4236arc_shrink(int64_t to_free)
4237{
4238	uint64_t asize = aggsum_value(&arc_size);
4239	if (arc_c > arc_c_min) {
4240		DTRACE_PROBE4(arc__shrink, uint64_t, arc_c, uint64_t,
4241			arc_c_min, uint64_t, arc_p, uint64_t, to_free);
4242		if (arc_c > arc_c_min + to_free)
4243			atomic_add_64(&arc_c, -to_free);
4244		else
4245			arc_c = arc_c_min;
4246
4247		atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
4248		if (asize < arc_c)
4249			arc_c = MAX(asize, arc_c_min);
4250		if (arc_p > arc_c)
4251			arc_p = (arc_c >> 1);
4252
4253		DTRACE_PROBE2(arc__shrunk, uint64_t, arc_c, uint64_t,
4254			arc_p);
4255
4256		ASSERT(arc_c >= arc_c_min);
4257		ASSERT((int64_t)arc_p >= 0);
4258	}
4259
4260	if (asize > arc_c) {
4261		DTRACE_PROBE2(arc__shrink_adjust, uint64_t, asize,
4262			uint64_t, arc_c);
4263		(void) arc_adjust();
4264	}
4265}
4266
4267typedef enum free_memory_reason_t {
4268	FMR_UNKNOWN,
4269	FMR_NEEDFREE,
4270	FMR_LOTSFREE,
4271	FMR_SWAPFS_MINFREE,
4272	FMR_PAGES_PP_MAXIMUM,
4273	FMR_HEAP_ARENA,
4274	FMR_ZIO_ARENA,
4275	FMR_ZIO_FRAG,
4276} free_memory_reason_t;
4277
4278int64_t last_free_memory;
4279free_memory_reason_t last_free_reason;
4280
4281/*
4282 * Additional reserve of pages for pp_reserve.
4283 */
4284int64_t arc_pages_pp_reserve = 64;
4285
4286/*
4287 * Additional reserve of pages for swapfs.
4288 */
4289int64_t arc_swapfs_reserve = 64;
4290
4291/*
4292 * Return the amount of memory that can be consumed before reclaim will be
4293 * needed.  Positive if there is sufficient free memory, negative indicates
4294 * the amount of memory that needs to be freed up.
4295 */
4296static int64_t
4297arc_available_memory(void)
4298{
4299	int64_t lowest = INT64_MAX;
4300	int64_t n;
4301	free_memory_reason_t r = FMR_UNKNOWN;
4302
4303#ifdef _KERNEL
4304#ifdef __FreeBSD__
4305	/*
4306	 * Cooperate with pagedaemon when it's time for it to scan
4307	 * and reclaim some pages.
4308	 */
4309	n = PAGESIZE * ((int64_t)freemem - zfs_arc_free_target);
4310	if (n < lowest) {
4311		lowest = n;
4312		r = FMR_LOTSFREE;
4313	}
4314
4315#else
4316	if (needfree > 0) {
4317		n = PAGESIZE * (-needfree);
4318		if (n < lowest) {
4319			lowest = n;
4320			r = FMR_NEEDFREE;
4321		}
4322	}
4323
4324	/*
4325	 * check that we're out of range of the pageout scanner.  It starts to
4326	 * schedule paging if freemem is less than lotsfree and needfree.
4327	 * lotsfree is the high-water mark for pageout, and needfree is the
4328	 * number of needed free pages.  We add extra pages here to make sure
4329	 * the scanner doesn't start up while we're freeing memory.
4330	 */
4331	n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
4332	if (n < lowest) {
4333		lowest = n;
4334		r = FMR_LOTSFREE;
4335	}
4336
4337	/*
4338	 * check to make sure that swapfs has enough space so that anon
4339	 * reservations can still succeed. anon_resvmem() checks that the
4340	 * availrmem is greater than swapfs_minfree, and the number of reserved
4341	 * swap pages.  We also add a bit of extra here just to prevent
4342	 * circumstances from getting really dire.
4343	 */
4344	n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
4345	    desfree - arc_swapfs_reserve);
4346	if (n < lowest) {
4347		lowest = n;
4348		r = FMR_SWAPFS_MINFREE;
4349	}
4350
4351
4352	/*
4353	 * Check that we have enough availrmem that memory locking (e.g., via
4354	 * mlock(3C) or memcntl(2)) can still succeed.  (pages_pp_maximum
4355	 * stores the number of pages that cannot be locked; when availrmem
4356	 * drops below pages_pp_maximum, page locking mechanisms such as
4357	 * page_pp_lock() will fail.)
4358	 */
4359	n = PAGESIZE * (availrmem - pages_pp_maximum -
4360	    arc_pages_pp_reserve);
4361	if (n < lowest) {
4362		lowest = n;
4363		r = FMR_PAGES_PP_MAXIMUM;
4364	}
4365
4366#endif	/* __FreeBSD__ */
4367#if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
4368	/*
4369	 * If we're on an i386 platform, it's possible that we'll exhaust the
4370	 * kernel heap space before we ever run out of available physical
4371	 * memory.  Most checks of the size of the heap_area compare against
4372	 * tune.t_minarmem, which is the minimum available real memory that we
4373	 * can have in the system.  However, this is generally fixed at 25 pages
4374	 * which is so low that it's useless.  In this comparison, we seek to
4375	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
4376	 * heap is allocated.  (Or, in the calculation, if less than 1/4th is
4377	 * free)
4378	 */
4379	n = (int64_t)vmem_size(heap_arena, VMEM_FREE) -
4380	    (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2);
4381	if (n < lowest) {
4382		lowest = n;
4383		r = FMR_HEAP_ARENA;
4384	}
4385#define	zio_arena	NULL
4386#else
4387#define	zio_arena	heap_arena
4388#endif
4389
4390	/*
4391	 * If zio data pages are being allocated out of a separate heap segment,
4392	 * then enforce that the size of available vmem for this arena remains
4393	 * above about 1/4th (1/(2^arc_zio_arena_free_shift)) free.
4394	 *
4395	 * Note that reducing the arc_zio_arena_free_shift keeps more virtual
4396	 * memory (in the zio_arena) free, which can avoid memory
4397	 * fragmentation issues.
4398	 */
4399	if (zio_arena != NULL) {
4400		n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
4401		    (vmem_size(zio_arena, VMEM_ALLOC) >>
4402		    arc_zio_arena_free_shift);
4403		if (n < lowest) {
4404			lowest = n;
4405			r = FMR_ZIO_ARENA;
4406		}
4407	}
4408
4409	/*
4410	 * Above limits know nothing about real level of KVA fragmentation.
4411	 * Start aggressive reclamation if too little sequential KVA left.
4412	 */
4413	if (lowest > 0) {
4414		n = (vmem_size(heap_arena, VMEM_MAXFREE) < SPA_MAXBLOCKSIZE) ?
4415		    -((int64_t)vmem_size(heap_arena, VMEM_ALLOC) >> 4) :
4416		    INT64_MAX;
4417		if (n < lowest) {
4418			lowest = n;
4419			r = FMR_ZIO_FRAG;
4420		}
4421	}
4422
4423#else	/* _KERNEL */
4424	/* Every 100 calls, free a small amount */
4425	if (spa_get_random(100) == 0)
4426		lowest = -1024;
4427#endif	/* _KERNEL */
4428
4429	last_free_memory = lowest;
4430	last_free_reason = r;
4431	DTRACE_PROBE2(arc__available_memory, int64_t, lowest, int, r);
4432	return (lowest);
4433}
4434
4435
4436/*
4437 * Determine if the system is under memory pressure and is asking
4438 * to reclaim memory. A return value of B_TRUE indicates that the system
4439 * is under memory pressure and that the arc should adjust accordingly.
4440 */
4441static boolean_t
4442arc_reclaim_needed(void)
4443{
4444	return (arc_available_memory() < 0);
4445}
4446
4447extern kmem_cache_t	*zio_buf_cache[];
4448extern kmem_cache_t	*zio_data_buf_cache[];
4449extern kmem_cache_t	*range_seg_cache;
4450extern kmem_cache_t	*abd_chunk_cache;
4451
4452static __noinline void
4453arc_kmem_reap_now(void)
4454{
4455	size_t			i;
4456	kmem_cache_t		*prev_cache = NULL;
4457	kmem_cache_t		*prev_data_cache = NULL;
4458
4459	DTRACE_PROBE(arc__kmem_reap_start);
4460#ifdef _KERNEL
4461	if (aggsum_compare(&arc_meta_used, arc_meta_limit) >= 0) {
4462		/*
4463		 * We are exceeding our meta-data cache limit.
4464		 * Purge some DNLC entries to release holds on meta-data.
4465		 */
4466		dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
4467	}
4468#if defined(__i386)
4469	/*
4470	 * Reclaim unused memory from all kmem caches.
4471	 */
4472	kmem_reap();
4473#endif
4474#endif
4475
4476	/*
4477	 * If a kmem reap is already active, don't schedule more.  We must
4478	 * check for this because kmem_cache_reap_soon() won't actually
4479	 * block on the cache being reaped (this is to prevent callers from
4480	 * becoming implicitly blocked by a system-wide kmem reap -- which,
4481	 * on a system with many, many full magazines, can take minutes).
4482	 */
4483	if (kmem_cache_reap_active())
4484		return;
4485
4486	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
4487		if (zio_buf_cache[i] != prev_cache) {
4488			prev_cache = zio_buf_cache[i];
4489			kmem_cache_reap_soon(zio_buf_cache[i]);
4490		}
4491		if (zio_data_buf_cache[i] != prev_data_cache) {
4492			prev_data_cache = zio_data_buf_cache[i];
4493			kmem_cache_reap_soon(zio_data_buf_cache[i]);
4494		}
4495	}
4496	kmem_cache_reap_soon(abd_chunk_cache);
4497	kmem_cache_reap_soon(buf_cache);
4498	kmem_cache_reap_soon(hdr_full_cache);
4499	kmem_cache_reap_soon(hdr_l2only_cache);
4500	kmem_cache_reap_soon(range_seg_cache);
4501
4502#ifdef illumos
4503	if (zio_arena != NULL) {
4504		/*
4505		 * Ask the vmem arena to reclaim unused memory from its
4506		 * quantum caches.
4507		 */
4508		vmem_qcache_reap(zio_arena);
4509	}
4510#endif
4511	DTRACE_PROBE(arc__kmem_reap_end);
4512}
4513
4514/*
4515 * Threads can block in arc_get_data_impl() waiting for this thread to evict
4516 * enough data and signal them to proceed. When this happens, the threads in
4517 * arc_get_data_impl() are sleeping while holding the hash lock for their
4518 * particular arc header. Thus, we must be careful to never sleep on a
4519 * hash lock in this thread. This is to prevent the following deadlock:
4520 *
4521 *  - Thread A sleeps on CV in arc_get_data_impl() holding hash lock "L",
4522 *    waiting for the reclaim thread to signal it.
4523 *
4524 *  - arc_reclaim_thread() tries to acquire hash lock "L" using mutex_enter,
4525 *    fails, and goes to sleep forever.
4526 *
4527 * This possible deadlock is avoided by always acquiring a hash lock
4528 * using mutex_tryenter() from arc_reclaim_thread().
4529 */
4530/* ARGSUSED */
4531static void
4532arc_reclaim_thread(void *unused __unused)
4533{
4534	hrtime_t		growtime = 0;
4535	hrtime_t		kmem_reap_time = 0;
4536	callb_cpr_t		cpr;
4537
4538	CALLB_CPR_INIT(&cpr, &arc_reclaim_lock, callb_generic_cpr, FTAG);
4539
4540	mutex_enter(&arc_reclaim_lock);
4541	while (!arc_reclaim_thread_exit) {
4542		uint64_t evicted = 0;
4543
4544		/*
4545		 * This is necessary in order for the mdb ::arc dcmd to
4546		 * show up to date information. Since the ::arc command
4547		 * does not call the kstat's update function, without
4548		 * this call, the command may show stale stats for the
4549		 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
4550		 * with this change, the data might be up to 1 second
4551		 * out of date; but that should suffice. The arc_state_t
4552		 * structures can be queried directly if more accurate
4553		 * information is needed.
4554		 */
4555		if (arc_ksp != NULL)
4556			arc_ksp->ks_update(arc_ksp, KSTAT_READ);
4557
4558		mutex_exit(&arc_reclaim_lock);
4559
4560		/*
4561		 * We call arc_adjust() before (possibly) calling
4562		 * arc_kmem_reap_now(), so that we can wake up
4563		 * arc_get_data_impl() sooner.
4564		 */
4565		evicted = arc_adjust();
4566
4567		int64_t free_memory = arc_available_memory();
4568		if (free_memory < 0) {
4569			hrtime_t curtime = gethrtime();
4570			arc_no_grow = B_TRUE;
4571			arc_warm = B_TRUE;
4572
4573			/*
4574			 * Wait at least zfs_grow_retry (default 60) seconds
4575			 * before considering growing.
4576			 */
4577			growtime = curtime + SEC2NSEC(arc_grow_retry);
4578
4579			/*
4580			 * Wait at least arc_kmem_cache_reap_retry_ms
4581			 * between arc_kmem_reap_now() calls. Without
4582			 * this check it is possible to end up in a
4583			 * situation where we spend lots of time
4584			 * reaping caches, while we're near arc_c_min.
4585			 */
4586			if (curtime >= kmem_reap_time) {
4587				arc_kmem_reap_now();
4588				kmem_reap_time = gethrtime() +
4589				    MSEC2NSEC(arc_kmem_cache_reap_retry_ms);
4590			}
4591
4592			/*
4593			 * If we are still low on memory, shrink the ARC
4594			 * so that we have arc_shrink_min free space.
4595			 */
4596			free_memory = arc_available_memory();
4597
4598			int64_t to_free =
4599			    (arc_c >> arc_shrink_shift) - free_memory;
4600			if (to_free > 0) {
4601#ifdef _KERNEL
4602#ifdef illumos
4603				to_free = MAX(to_free, ptob(needfree));
4604#endif
4605#endif
4606				arc_shrink(to_free);
4607			}
4608		} else if (free_memory < arc_c >> arc_no_grow_shift) {
4609			arc_no_grow = B_TRUE;
4610		} else if (gethrtime() >= growtime) {
4611			arc_no_grow = B_FALSE;
4612		}
4613
4614		mutex_enter(&arc_reclaim_lock);
4615
4616		/*
4617		 * If evicted is zero, we couldn't evict anything via
4618		 * arc_adjust(). This could be due to hash lock
4619		 * collisions, but more likely due to the majority of
4620		 * arc buffers being unevictable. Therefore, even if
4621		 * arc_size is above arc_c, another pass is unlikely to
4622		 * be helpful and could potentially cause us to enter an
4623		 * infinite loop.
4624		 */
4625		if (aggsum_compare(&arc_size, arc_c) <= 0|| evicted == 0) {
4626			/*
4627			 * We're either no longer overflowing, or we
4628			 * can't evict anything more, so we should wake
4629			 * up any threads before we go to sleep.
4630			 */
4631			cv_broadcast(&arc_reclaim_waiters_cv);
4632
4633			/*
4634			 * Block until signaled, or after one second (we
4635			 * might need to perform arc_kmem_reap_now()
4636			 * even if we aren't being signalled)
4637			 */
4638			CALLB_CPR_SAFE_BEGIN(&cpr);
4639			(void) cv_timedwait_hires(&arc_reclaim_thread_cv,
4640			    &arc_reclaim_lock, SEC2NSEC(1), MSEC2NSEC(1), 0);
4641			CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_lock);
4642		}
4643	}
4644
4645	arc_reclaim_thread_exit = B_FALSE;
4646	cv_broadcast(&arc_reclaim_thread_cv);
4647	CALLB_CPR_EXIT(&cpr);		/* drops arc_reclaim_lock */
4648	thread_exit();
4649}
4650
4651static u_int arc_dnlc_evicts_arg;
4652extern struct vfsops zfs_vfsops;
4653
4654static void
4655arc_dnlc_evicts_thread(void *dummy __unused)
4656{
4657	callb_cpr_t cpr;
4658	u_int percent;
4659
4660	CALLB_CPR_INIT(&cpr, &arc_dnlc_evicts_lock, callb_generic_cpr, FTAG);
4661
4662	mutex_enter(&arc_dnlc_evicts_lock);
4663	while (!arc_dnlc_evicts_thread_exit) {
4664		CALLB_CPR_SAFE_BEGIN(&cpr);
4665		(void) cv_wait(&arc_dnlc_evicts_cv, &arc_dnlc_evicts_lock);
4666		CALLB_CPR_SAFE_END(&cpr, &arc_dnlc_evicts_lock);
4667		if (arc_dnlc_evicts_arg != 0) {
4668			percent = arc_dnlc_evicts_arg;
4669			mutex_exit(&arc_dnlc_evicts_lock);
4670#ifdef _KERNEL
4671			vnlru_free(desiredvnodes * percent / 100, &zfs_vfsops);
4672#endif
4673			mutex_enter(&arc_dnlc_evicts_lock);
4674			/*
4675			 * Clear our token only after vnlru_free()
4676			 * pass is done, to avoid false queueing of
4677			 * the requests.
4678			 */
4679			arc_dnlc_evicts_arg = 0;
4680		}
4681	}
4682	arc_dnlc_evicts_thread_exit = FALSE;
4683	cv_broadcast(&arc_dnlc_evicts_cv);
4684	CALLB_CPR_EXIT(&cpr);
4685	thread_exit();
4686}
4687
4688void
4689dnlc_reduce_cache(void *arg)
4690{
4691	u_int percent;
4692
4693	percent = (u_int)(uintptr_t)arg;
4694	mutex_enter(&arc_dnlc_evicts_lock);
4695	if (arc_dnlc_evicts_arg == 0) {
4696		arc_dnlc_evicts_arg = percent;
4697		cv_broadcast(&arc_dnlc_evicts_cv);
4698	}
4699	mutex_exit(&arc_dnlc_evicts_lock);
4700}
4701
4702/*
4703 * Adapt arc info given the number of bytes we are trying to add and
4704 * the state that we are comming from.  This function is only called
4705 * when we are adding new content to the cache.
4706 */
4707static void
4708arc_adapt(int bytes, arc_state_t *state)
4709{
4710	int mult;
4711	uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
4712	int64_t mrug_size = refcount_count(&arc_mru_ghost->arcs_size);
4713	int64_t mfug_size = refcount_count(&arc_mfu_ghost->arcs_size);
4714
4715	if (state == arc_l2c_only)
4716		return;
4717
4718	ASSERT(bytes > 0);
4719	/*
4720	 * Adapt the target size of the MRU list:
4721	 *	- if we just hit in the MRU ghost list, then increase
4722	 *	  the target size of the MRU list.
4723	 *	- if we just hit in the MFU ghost list, then increase
4724	 *	  the target size of the MFU list by decreasing the
4725	 *	  target size of the MRU list.
4726	 */
4727	if (state == arc_mru_ghost) {
4728		mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
4729		mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
4730
4731		arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
4732	} else if (state == arc_mfu_ghost) {
4733		uint64_t delta;
4734
4735		mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
4736		mult = MIN(mult, 10);
4737
4738		delta = MIN(bytes * mult, arc_p);
4739		arc_p = MAX(arc_p_min, arc_p - delta);
4740	}
4741	ASSERT((int64_t)arc_p >= 0);
4742
4743	if (arc_reclaim_needed()) {
4744		cv_signal(&arc_reclaim_thread_cv);
4745		return;
4746	}
4747
4748	if (arc_no_grow)
4749		return;
4750
4751	if (arc_c >= arc_c_max)
4752		return;
4753
4754	/*
4755	 * If we're within (2 * maxblocksize) bytes of the target
4756	 * cache size, increment the target cache size
4757	 */
4758	if (aggsum_compare(&arc_size, arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) >
4759	    0) {
4760		DTRACE_PROBE1(arc__inc_adapt, int, bytes);
4761		atomic_add_64(&arc_c, (int64_t)bytes);
4762		if (arc_c > arc_c_max)
4763			arc_c = arc_c_max;
4764		else if (state == arc_anon)
4765			atomic_add_64(&arc_p, (int64_t)bytes);
4766		if (arc_p > arc_c)
4767			arc_p = arc_c;
4768	}
4769	ASSERT((int64_t)arc_p >= 0);
4770}
4771
4772/*
4773 * Check if arc_size has grown past our upper threshold, determined by
4774 * zfs_arc_overflow_shift.
4775 */
4776static boolean_t
4777arc_is_overflowing(void)
4778{
4779	/* Always allow at least one block of overflow */
4780	uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
4781	    arc_c >> zfs_arc_overflow_shift);
4782
4783	/*
4784	 * We just compare the lower bound here for performance reasons. Our
4785	 * primary goals are to make sure that the arc never grows without
4786	 * bound, and that it can reach its maximum size. This check
4787	 * accomplishes both goals. The maximum amount we could run over by is
4788	 * 2 * aggsum_borrow_multiplier * NUM_CPUS * the average size of a block
4789	 * in the ARC. In practice, that's in the tens of MB, which is low
4790	 * enough to be safe.
4791	 */
4792	return (aggsum_lower_bound(&arc_size) >= arc_c + overflow);
4793}
4794
4795static abd_t *
4796arc_get_data_abd(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4797{
4798	arc_buf_contents_t type = arc_buf_type(hdr);
4799
4800	arc_get_data_impl(hdr, size, tag);
4801	if (type == ARC_BUFC_METADATA) {
4802		return (abd_alloc(size, B_TRUE));
4803	} else {
4804		ASSERT(type == ARC_BUFC_DATA);
4805		return (abd_alloc(size, B_FALSE));
4806	}
4807}
4808
4809static void *
4810arc_get_data_buf(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4811{
4812	arc_buf_contents_t type = arc_buf_type(hdr);
4813
4814	arc_get_data_impl(hdr, size, tag);
4815	if (type == ARC_BUFC_METADATA) {
4816		return (zio_buf_alloc(size));
4817	} else {
4818		ASSERT(type == ARC_BUFC_DATA);
4819		return (zio_data_buf_alloc(size));
4820	}
4821}
4822
4823/*
4824 * Allocate a block and return it to the caller. If we are hitting the
4825 * hard limit for the cache size, we must sleep, waiting for the eviction
4826 * thread to catch up. If we're past the target size but below the hard
4827 * limit, we'll only signal the reclaim thread and continue on.
4828 */
4829static void
4830arc_get_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4831{
4832	arc_state_t *state = hdr->b_l1hdr.b_state;
4833	arc_buf_contents_t type = arc_buf_type(hdr);
4834
4835	arc_adapt(size, state);
4836
4837	/*
4838	 * If arc_size is currently overflowing, and has grown past our
4839	 * upper limit, we must be adding data faster than the evict
4840	 * thread can evict. Thus, to ensure we don't compound the
4841	 * problem by adding more data and forcing arc_size to grow even
4842	 * further past it's target size, we halt and wait for the
4843	 * eviction thread to catch up.
4844	 *
4845	 * It's also possible that the reclaim thread is unable to evict
4846	 * enough buffers to get arc_size below the overflow limit (e.g.
4847	 * due to buffers being un-evictable, or hash lock collisions).
4848	 * In this case, we want to proceed regardless if we're
4849	 * overflowing; thus we don't use a while loop here.
4850	 */
4851	if (arc_is_overflowing()) {
4852		mutex_enter(&arc_reclaim_lock);
4853
4854		/*
4855		 * Now that we've acquired the lock, we may no longer be
4856		 * over the overflow limit, lets check.
4857		 *
4858		 * We're ignoring the case of spurious wake ups. If that
4859		 * were to happen, it'd let this thread consume an ARC
4860		 * buffer before it should have (i.e. before we're under
4861		 * the overflow limit and were signalled by the reclaim
4862		 * thread). As long as that is a rare occurrence, it
4863		 * shouldn't cause any harm.
4864		 */
4865		if (arc_is_overflowing()) {
4866			cv_signal(&arc_reclaim_thread_cv);
4867			cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
4868		}
4869
4870		mutex_exit(&arc_reclaim_lock);
4871	}
4872
4873	VERIFY3U(hdr->b_type, ==, type);
4874	if (type == ARC_BUFC_METADATA) {
4875		arc_space_consume(size, ARC_SPACE_META);
4876	} else {
4877		arc_space_consume(size, ARC_SPACE_DATA);
4878	}
4879
4880	/*
4881	 * Update the state size.  Note that ghost states have a
4882	 * "ghost size" and so don't need to be updated.
4883	 */
4884	if (!GHOST_STATE(state)) {
4885
4886		(void) refcount_add_many(&state->arcs_size, size, tag);
4887
4888		/*
4889		 * If this is reached via arc_read, the link is
4890		 * protected by the hash lock. If reached via
4891		 * arc_buf_alloc, the header should not be accessed by
4892		 * any other thread. And, if reached via arc_read_done,
4893		 * the hash lock will protect it if it's found in the
4894		 * hash table; otherwise no other thread should be
4895		 * trying to [add|remove]_reference it.
4896		 */
4897		if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
4898			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4899			(void) refcount_add_many(&state->arcs_esize[type],
4900			    size, tag);
4901		}
4902
4903		/*
4904		 * If we are growing the cache, and we are adding anonymous
4905		 * data, and we have outgrown arc_p, update arc_p
4906		 */
4907		if (aggsum_compare(&arc_size, arc_c) < 0 &&
4908		    hdr->b_l1hdr.b_state == arc_anon &&
4909		    (refcount_count(&arc_anon->arcs_size) +
4910		    refcount_count(&arc_mru->arcs_size) > arc_p))
4911			arc_p = MIN(arc_c, arc_p + size);
4912	}
4913	ARCSTAT_BUMP(arcstat_allocated);
4914}
4915
4916static void
4917arc_free_data_abd(arc_buf_hdr_t *hdr, abd_t *abd, uint64_t size, void *tag)
4918{
4919	arc_free_data_impl(hdr, size, tag);
4920	abd_free(abd);
4921}
4922
4923static void
4924arc_free_data_buf(arc_buf_hdr_t *hdr, void *buf, uint64_t size, void *tag)
4925{
4926	arc_buf_contents_t type = arc_buf_type(hdr);
4927
4928	arc_free_data_impl(hdr, size, tag);
4929	if (type == ARC_BUFC_METADATA) {
4930		zio_buf_free(buf, size);
4931	} else {
4932		ASSERT(type == ARC_BUFC_DATA);
4933		zio_data_buf_free(buf, size);
4934	}
4935}
4936
4937/*
4938 * Free the arc data buffer.
4939 */
4940static void
4941arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4942{
4943	arc_state_t *state = hdr->b_l1hdr.b_state;
4944	arc_buf_contents_t type = arc_buf_type(hdr);
4945
4946	/* protected by hash lock, if in the hash table */
4947	if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
4948		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4949		ASSERT(state != arc_anon && state != arc_l2c_only);
4950
4951		(void) refcount_remove_many(&state->arcs_esize[type],
4952		    size, tag);
4953	}
4954	(void) refcount_remove_many(&state->arcs_size, size, tag);
4955
4956	VERIFY3U(hdr->b_type, ==, type);
4957	if (type == ARC_BUFC_METADATA) {
4958		arc_space_return(size, ARC_SPACE_META);
4959	} else {
4960		ASSERT(type == ARC_BUFC_DATA);
4961		arc_space_return(size, ARC_SPACE_DATA);
4962	}
4963}
4964
4965/*
4966 * This routine is called whenever a buffer is accessed.
4967 * NOTE: the hash lock is dropped in this function.
4968 */
4969static void
4970arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
4971{
4972	clock_t now;
4973
4974	ASSERT(MUTEX_HELD(hash_lock));
4975	ASSERT(HDR_HAS_L1HDR(hdr));
4976
4977	if (hdr->b_l1hdr.b_state == arc_anon) {
4978		/*
4979		 * This buffer is not in the cache, and does not
4980		 * appear in our "ghost" list.  Add the new buffer
4981		 * to the MRU state.
4982		 */
4983
4984		ASSERT0(hdr->b_l1hdr.b_arc_access);
4985		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4986		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
4987		arc_change_state(arc_mru, hdr, hash_lock);
4988
4989	} else if (hdr->b_l1hdr.b_state == arc_mru) {
4990		now = ddi_get_lbolt();
4991
4992		/*
4993		 * If this buffer is here because of a prefetch, then either:
4994		 * - clear the flag if this is a "referencing" read
4995		 *   (any subsequent access will bump this into the MFU state).
4996		 * or
4997		 * - move the buffer to the head of the list if this is
4998		 *   another prefetch (to make it less likely to be evicted).
4999		 */
5000		if (HDR_PREFETCH(hdr)) {
5001			if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
5002				/* link protected by hash lock */
5003				ASSERT(multilist_link_active(
5004				    &hdr->b_l1hdr.b_arc_node));
5005			} else {
5006				arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
5007				ARCSTAT_BUMP(arcstat_mru_hits);
5008			}
5009			hdr->b_l1hdr.b_arc_access = now;
5010			return;
5011		}
5012
5013		/*
5014		 * This buffer has been "accessed" only once so far,
5015		 * but it is still in the cache. Move it to the MFU
5016		 * state.
5017		 */
5018		if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
5019			/*
5020			 * More than 125ms have passed since we
5021			 * instantiated this buffer.  Move it to the
5022			 * most frequently used state.
5023			 */
5024			hdr->b_l1hdr.b_arc_access = now;
5025			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5026			arc_change_state(arc_mfu, hdr, hash_lock);
5027		}
5028		ARCSTAT_BUMP(arcstat_mru_hits);
5029	} else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
5030		arc_state_t	*new_state;
5031		/*
5032		 * This buffer has been "accessed" recently, but
5033		 * was evicted from the cache.  Move it to the
5034		 * MFU state.
5035		 */
5036
5037		if (HDR_PREFETCH(hdr)) {
5038			new_state = arc_mru;
5039			if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0)
5040				arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
5041			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
5042		} else {
5043			new_state = arc_mfu;
5044			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5045		}
5046
5047		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5048		arc_change_state(new_state, hdr, hash_lock);
5049
5050		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
5051	} else if (hdr->b_l1hdr.b_state == arc_mfu) {
5052		/*
5053		 * This buffer has been accessed more than once and is
5054		 * still in the cache.  Keep it in the MFU state.
5055		 *
5056		 * NOTE: an add_reference() that occurred when we did
5057		 * the arc_read() will have kicked this off the list.
5058		 * If it was a prefetch, we will explicitly move it to
5059		 * the head of the list now.
5060		 */
5061		if ((HDR_PREFETCH(hdr)) != 0) {
5062			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5063			/* link protected by hash_lock */
5064			ASSERT(multilist_link_active(&hdr->b_l1hdr.b_arc_node));
5065		}
5066		ARCSTAT_BUMP(arcstat_mfu_hits);
5067		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5068	} else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
5069		arc_state_t	*new_state = arc_mfu;
5070		/*
5071		 * This buffer has been accessed more than once but has
5072		 * been evicted from the cache.  Move it back to the
5073		 * MFU state.
5074		 */
5075
5076		if (HDR_PREFETCH(hdr)) {
5077			/*
5078			 * This is a prefetch access...
5079			 * move this block back to the MRU state.
5080			 */
5081			ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
5082			new_state = arc_mru;
5083		}
5084
5085		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5086		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5087		arc_change_state(new_state, hdr, hash_lock);
5088
5089		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
5090	} else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
5091		/*
5092		 * This buffer is on the 2nd Level ARC.
5093		 */
5094
5095		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5096		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5097		arc_change_state(arc_mfu, hdr, hash_lock);
5098	} else {
5099		ASSERT(!"invalid arc state");
5100	}
5101}
5102
5103/*
5104 * This routine is called by dbuf_hold() to update the arc_access() state
5105 * which otherwise would be skipped for entries in the dbuf cache.
5106 */
5107void
5108arc_buf_access(arc_buf_t *buf)
5109{
5110	mutex_enter(&buf->b_evict_lock);
5111	arc_buf_hdr_t *hdr = buf->b_hdr;
5112
5113	/*
5114	 * Avoid taking the hash_lock when possible as an optimization.
5115	 * The header must be checked again under the hash_lock in order
5116	 * to handle the case where it is concurrently being released.
5117	 */
5118	if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr)) {
5119		mutex_exit(&buf->b_evict_lock);
5120		ARCSTAT_BUMP(arcstat_access_skip);
5121		return;
5122	}
5123
5124	kmutex_t *hash_lock = HDR_LOCK(hdr);
5125	mutex_enter(hash_lock);
5126
5127	if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr)) {
5128		mutex_exit(hash_lock);
5129		mutex_exit(&buf->b_evict_lock);
5130		ARCSTAT_BUMP(arcstat_access_skip);
5131		return;
5132	}
5133
5134	mutex_exit(&buf->b_evict_lock);
5135
5136	ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
5137	    hdr->b_l1hdr.b_state == arc_mfu);
5138
5139	DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
5140	arc_access(hdr, hash_lock);
5141	mutex_exit(hash_lock);
5142
5143	ARCSTAT_BUMP(arcstat_hits);
5144	ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5145	    demand, prefetch, !HDR_ISTYPE_METADATA(hdr), data, metadata, hits);
5146}
5147
5148/* a generic arc_done_func_t which you can use */
5149/* ARGSUSED */
5150void
5151arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
5152{
5153	if (zio == NULL || zio->io_error == 0)
5154		bcopy(buf->b_data, arg, arc_buf_size(buf));
5155	arc_buf_destroy(buf, arg);
5156}
5157
5158/* a generic arc_done_func_t */
5159void
5160arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
5161{
5162	arc_buf_t **bufp = arg;
5163	if (zio && zio->io_error) {
5164		arc_buf_destroy(buf, arg);
5165		*bufp = NULL;
5166	} else {
5167		*bufp = buf;
5168		ASSERT(buf->b_data);
5169	}
5170}
5171
5172static void
5173arc_hdr_verify(arc_buf_hdr_t *hdr, blkptr_t *bp)
5174{
5175	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
5176		ASSERT3U(HDR_GET_PSIZE(hdr), ==, 0);
5177		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
5178	} else {
5179		if (HDR_COMPRESSION_ENABLED(hdr)) {
5180			ASSERT3U(HDR_GET_COMPRESS(hdr), ==,
5181			    BP_GET_COMPRESS(bp));
5182		}
5183		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
5184		ASSERT3U(HDR_GET_PSIZE(hdr), ==, BP_GET_PSIZE(bp));
5185	}
5186}
5187
5188static void
5189arc_read_done(zio_t *zio)
5190{
5191	arc_buf_hdr_t	*hdr = zio->io_private;
5192	kmutex_t	*hash_lock = NULL;
5193	arc_callback_t	*callback_list;
5194	arc_callback_t	*acb;
5195	boolean_t	freeable = B_FALSE;
5196	boolean_t	no_zio_error = (zio->io_error == 0);
5197
5198	/*
5199	 * The hdr was inserted into hash-table and removed from lists
5200	 * prior to starting I/O.  We should find this header, since
5201	 * it's in the hash table, and it should be legit since it's
5202	 * not possible to evict it during the I/O.  The only possible
5203	 * reason for it not to be found is if we were freed during the
5204	 * read.
5205	 */
5206	if (HDR_IN_HASH_TABLE(hdr)) {
5207		ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
5208		ASSERT3U(hdr->b_dva.dva_word[0], ==,
5209		    BP_IDENTITY(zio->io_bp)->dva_word[0]);
5210		ASSERT3U(hdr->b_dva.dva_word[1], ==,
5211		    BP_IDENTITY(zio->io_bp)->dva_word[1]);
5212
5213		arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
5214		    &hash_lock);
5215
5216		ASSERT((found == hdr &&
5217		    DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
5218		    (found == hdr && HDR_L2_READING(hdr)));
5219		ASSERT3P(hash_lock, !=, NULL);
5220	}
5221
5222	if (no_zio_error) {
5223		/* byteswap if necessary */
5224		if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
5225			if (BP_GET_LEVEL(zio->io_bp) > 0) {
5226				hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
5227			} else {
5228				hdr->b_l1hdr.b_byteswap =
5229				    DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
5230			}
5231		} else {
5232			hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
5233		}
5234	}
5235
5236	arc_hdr_clear_flags(hdr, ARC_FLAG_L2_EVICTED);
5237	if (l2arc_noprefetch && HDR_PREFETCH(hdr))
5238		arc_hdr_clear_flags(hdr, ARC_FLAG_L2CACHE);
5239
5240	callback_list = hdr->b_l1hdr.b_acb;
5241	ASSERT3P(callback_list, !=, NULL);
5242
5243	if (hash_lock && no_zio_error && hdr->b_l1hdr.b_state == arc_anon) {
5244		/*
5245		 * Only call arc_access on anonymous buffers.  This is because
5246		 * if we've issued an I/O for an evicted buffer, we've already
5247		 * called arc_access (to prevent any simultaneous readers from
5248		 * getting confused).
5249		 */
5250		arc_access(hdr, hash_lock);
5251	}
5252
5253	/*
5254	 * If a read request has a callback (i.e. acb_done is not NULL), then we
5255	 * make a buf containing the data according to the parameters which were
5256	 * passed in. The implementation of arc_buf_alloc_impl() ensures that we
5257	 * aren't needlessly decompressing the data multiple times.
5258	 */
5259	int callback_cnt = 0;
5260	for (acb = callback_list; acb != NULL; acb = acb->acb_next) {
5261		if (!acb->acb_done)
5262			continue;
5263
5264		/* This is a demand read since prefetches don't use callbacks */
5265		callback_cnt++;
5266
5267		int error = arc_buf_alloc_impl(hdr, acb->acb_private,
5268		    acb->acb_compressed, no_zio_error, &acb->acb_buf);
5269		if (no_zio_error) {
5270			zio->io_error = error;
5271		}
5272	}
5273	hdr->b_l1hdr.b_acb = NULL;
5274	arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5275	if (callback_cnt == 0) {
5276		ASSERT(HDR_PREFETCH(hdr));
5277		ASSERT0(hdr->b_l1hdr.b_bufcnt);
5278		ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
5279	}
5280
5281	ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
5282	    callback_list != NULL);
5283
5284	if (no_zio_error) {
5285		arc_hdr_verify(hdr, zio->io_bp);
5286	} else {
5287		arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
5288		if (hdr->b_l1hdr.b_state != arc_anon)
5289			arc_change_state(arc_anon, hdr, hash_lock);
5290		if (HDR_IN_HASH_TABLE(hdr))
5291			buf_hash_remove(hdr);
5292		freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5293	}
5294
5295	/*
5296	 * Broadcast before we drop the hash_lock to avoid the possibility
5297	 * that the hdr (and hence the cv) might be freed before we get to
5298	 * the cv_broadcast().
5299	 */
5300	cv_broadcast(&hdr->b_l1hdr.b_cv);
5301
5302	if (hash_lock != NULL) {
5303		mutex_exit(hash_lock);
5304	} else {
5305		/*
5306		 * This block was freed while we waited for the read to
5307		 * complete.  It has been removed from the hash table and
5308		 * moved to the anonymous state (so that it won't show up
5309		 * in the cache).
5310		 */
5311		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
5312		freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5313	}
5314
5315	/* execute each callback and free its structure */
5316	while ((acb = callback_list) != NULL) {
5317		if (acb->acb_done)
5318			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
5319
5320		if (acb->acb_zio_dummy != NULL) {
5321			acb->acb_zio_dummy->io_error = zio->io_error;
5322			zio_nowait(acb->acb_zio_dummy);
5323		}
5324
5325		callback_list = acb->acb_next;
5326		kmem_free(acb, sizeof (arc_callback_t));
5327	}
5328
5329	if (freeable)
5330		arc_hdr_destroy(hdr);
5331}
5332
5333/*
5334 * "Read" the block at the specified DVA (in bp) via the
5335 * cache.  If the block is found in the cache, invoke the provided
5336 * callback immediately and return.  Note that the `zio' parameter
5337 * in the callback will be NULL in this case, since no IO was
5338 * required.  If the block is not in the cache pass the read request
5339 * on to the spa with a substitute callback function, so that the
5340 * requested block will be added to the cache.
5341 *
5342 * If a read request arrives for a block that has a read in-progress,
5343 * either wait for the in-progress read to complete (and return the
5344 * results); or, if this is a read with a "done" func, add a record
5345 * to the read to invoke the "done" func when the read completes,
5346 * and return; or just return.
5347 *
5348 * arc_read_done() will invoke all the requested "done" functions
5349 * for readers of this block.
5350 */
5351int
5352arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
5353    void *private, zio_priority_t priority, int zio_flags,
5354    arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
5355{
5356	arc_buf_hdr_t *hdr = NULL;
5357	kmutex_t *hash_lock = NULL;
5358	zio_t *rzio;
5359	uint64_t guid = spa_load_guid(spa);
5360	boolean_t compressed_read = (zio_flags & ZIO_FLAG_RAW) != 0;
5361
5362	ASSERT(!BP_IS_EMBEDDED(bp) ||
5363	    BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
5364
5365top:
5366	if (!BP_IS_EMBEDDED(bp)) {
5367		/*
5368		 * Embedded BP's have no DVA and require no I/O to "read".
5369		 * Create an anonymous arc buf to back it.
5370		 */
5371		hdr = buf_hash_find(guid, bp, &hash_lock);
5372	}
5373
5374	if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_pabd != NULL) {
5375		arc_buf_t *buf = NULL;
5376		*arc_flags |= ARC_FLAG_CACHED;
5377
5378		if (HDR_IO_IN_PROGRESS(hdr)) {
5379
5380			if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
5381			    priority == ZIO_PRIORITY_SYNC_READ) {
5382				/*
5383				 * This sync read must wait for an
5384				 * in-progress async read (e.g. a predictive
5385				 * prefetch).  Async reads are queued
5386				 * separately at the vdev_queue layer, so
5387				 * this is a form of priority inversion.
5388				 * Ideally, we would "inherit" the demand
5389				 * i/o's priority by moving the i/o from
5390				 * the async queue to the synchronous queue,
5391				 * but there is currently no mechanism to do
5392				 * so.  Track this so that we can evaluate
5393				 * the magnitude of this potential performance
5394				 * problem.
5395				 *
5396				 * Note that if the prefetch i/o is already
5397				 * active (has been issued to the device),
5398				 * the prefetch improved performance, because
5399				 * we issued it sooner than we would have
5400				 * without the prefetch.
5401				 */
5402				DTRACE_PROBE1(arc__sync__wait__for__async,
5403				    arc_buf_hdr_t *, hdr);
5404				ARCSTAT_BUMP(arcstat_sync_wait_for_async);
5405			}
5406			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5407				arc_hdr_clear_flags(hdr,
5408				    ARC_FLAG_PREDICTIVE_PREFETCH);
5409			}
5410
5411			if (*arc_flags & ARC_FLAG_WAIT) {
5412				cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
5413				mutex_exit(hash_lock);
5414				goto top;
5415			}
5416			ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
5417
5418			if (done) {
5419				arc_callback_t *acb = NULL;
5420
5421				acb = kmem_zalloc(sizeof (arc_callback_t),
5422				    KM_SLEEP);
5423				acb->acb_done = done;
5424				acb->acb_private = private;
5425				acb->acb_compressed = compressed_read;
5426				if (pio != NULL)
5427					acb->acb_zio_dummy = zio_null(pio,
5428					    spa, NULL, NULL, NULL, zio_flags);
5429
5430				ASSERT3P(acb->acb_done, !=, NULL);
5431				acb->acb_next = hdr->b_l1hdr.b_acb;
5432				hdr->b_l1hdr.b_acb = acb;
5433				mutex_exit(hash_lock);
5434				return (0);
5435			}
5436			mutex_exit(hash_lock);
5437			return (0);
5438		}
5439
5440		ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
5441		    hdr->b_l1hdr.b_state == arc_mfu);
5442
5443		if (done) {
5444			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5445				/*
5446				 * This is a demand read which does not have to
5447				 * wait for i/o because we did a predictive
5448				 * prefetch i/o for it, which has completed.
5449				 */
5450				DTRACE_PROBE1(
5451				    arc__demand__hit__predictive__prefetch,
5452				    arc_buf_hdr_t *, hdr);
5453				ARCSTAT_BUMP(
5454				    arcstat_demand_hit_predictive_prefetch);
5455				arc_hdr_clear_flags(hdr,
5456				    ARC_FLAG_PREDICTIVE_PREFETCH);
5457			}
5458			ASSERT(!BP_IS_EMBEDDED(bp) || !BP_IS_HOLE(bp));
5459
5460			/* Get a buf with the desired data in it. */
5461			VERIFY0(arc_buf_alloc_impl(hdr, private,
5462			    compressed_read, B_TRUE, &buf));
5463		} else if (*arc_flags & ARC_FLAG_PREFETCH &&
5464		    refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
5465			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5466		}
5467		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
5468		arc_access(hdr, hash_lock);
5469		if (*arc_flags & ARC_FLAG_L2CACHE)
5470			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5471		mutex_exit(hash_lock);
5472		ARCSTAT_BUMP(arcstat_hits);
5473		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5474		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
5475		    data, metadata, hits);
5476
5477		if (done)
5478			done(NULL, buf, private);
5479	} else {
5480		uint64_t lsize = BP_GET_LSIZE(bp);
5481		uint64_t psize = BP_GET_PSIZE(bp);
5482		arc_callback_t *acb;
5483		vdev_t *vd = NULL;
5484		uint64_t addr = 0;
5485		boolean_t devw = B_FALSE;
5486		uint64_t size;
5487
5488		if (hdr == NULL) {
5489			/* this block is not in the cache */
5490			arc_buf_hdr_t *exists = NULL;
5491			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
5492			hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
5493			    BP_GET_COMPRESS(bp), type);
5494
5495			if (!BP_IS_EMBEDDED(bp)) {
5496				hdr->b_dva = *BP_IDENTITY(bp);
5497				hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
5498				exists = buf_hash_insert(hdr, &hash_lock);
5499			}
5500			if (exists != NULL) {
5501				/* somebody beat us to the hash insert */
5502				mutex_exit(hash_lock);
5503				buf_discard_identity(hdr);
5504				arc_hdr_destroy(hdr);
5505				goto top; /* restart the IO request */
5506			}
5507		} else {
5508			/*
5509			 * This block is in the ghost cache. If it was L2-only
5510			 * (and thus didn't have an L1 hdr), we realloc the
5511			 * header to add an L1 hdr.
5512			 */
5513			if (!HDR_HAS_L1HDR(hdr)) {
5514				hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
5515				    hdr_full_cache);
5516			}
5517			ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
5518			ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
5519			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5520			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5521			ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
5522			ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
5523
5524			/*
5525			 * This is a delicate dance that we play here.
5526			 * This hdr is in the ghost list so we access it
5527			 * to move it out of the ghost list before we
5528			 * initiate the read. If it's a prefetch then
5529			 * it won't have a callback so we'll remove the
5530			 * reference that arc_buf_alloc_impl() created. We
5531			 * do this after we've called arc_access() to
5532			 * avoid hitting an assert in remove_reference().
5533			 */
5534			arc_access(hdr, hash_lock);
5535			arc_hdr_alloc_pabd(hdr);
5536		}
5537		ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
5538		size = arc_hdr_size(hdr);
5539
5540		/*
5541		 * If compression is enabled on the hdr, then will do
5542		 * RAW I/O and will store the compressed data in the hdr's
5543		 * data block. Otherwise, the hdr's data block will contain
5544		 * the uncompressed data.
5545		 */
5546		if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
5547			zio_flags |= ZIO_FLAG_RAW;
5548		}
5549
5550		if (*arc_flags & ARC_FLAG_PREFETCH)
5551			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5552		if (*arc_flags & ARC_FLAG_L2CACHE)
5553			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5554		if (BP_GET_LEVEL(bp) > 0)
5555			arc_hdr_set_flags(hdr, ARC_FLAG_INDIRECT);
5556		if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
5557			arc_hdr_set_flags(hdr, ARC_FLAG_PREDICTIVE_PREFETCH);
5558		ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
5559
5560		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
5561		acb->acb_done = done;
5562		acb->acb_private = private;
5563		acb->acb_compressed = compressed_read;
5564
5565		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5566		hdr->b_l1hdr.b_acb = acb;
5567		arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5568
5569		if (HDR_HAS_L2HDR(hdr) &&
5570		    (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
5571			devw = hdr->b_l2hdr.b_dev->l2ad_writing;
5572			addr = hdr->b_l2hdr.b_daddr;
5573			/*
5574			 * Lock out L2ARC device removal.
5575			 */
5576			if (vdev_is_dead(vd) ||
5577			    !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
5578				vd = NULL;
5579		}
5580
5581		if (priority == ZIO_PRIORITY_ASYNC_READ)
5582			arc_hdr_set_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5583		else
5584			arc_hdr_clear_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5585
5586		if (hash_lock != NULL)
5587			mutex_exit(hash_lock);
5588
5589		/*
5590		 * At this point, we have a level 1 cache miss.  Try again in
5591		 * L2ARC if possible.
5592		 */
5593		ASSERT3U(HDR_GET_LSIZE(hdr), ==, lsize);
5594
5595		DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
5596		    uint64_t, lsize, zbookmark_phys_t *, zb);
5597		ARCSTAT_BUMP(arcstat_misses);
5598		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5599		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
5600		    data, metadata, misses);
5601#ifdef _KERNEL
5602#ifdef RACCT
5603		if (racct_enable) {
5604			PROC_LOCK(curproc);
5605			racct_add_force(curproc, RACCT_READBPS, size);
5606			racct_add_force(curproc, RACCT_READIOPS, 1);
5607			PROC_UNLOCK(curproc);
5608		}
5609#endif /* RACCT */
5610		curthread->td_ru.ru_inblock++;
5611#endif
5612
5613		if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
5614			/*
5615			 * Read from the L2ARC if the following are true:
5616			 * 1. The L2ARC vdev was previously cached.
5617			 * 2. This buffer still has L2ARC metadata.
5618			 * 3. This buffer isn't currently writing to the L2ARC.
5619			 * 4. The L2ARC entry wasn't evicted, which may
5620			 *    also have invalidated the vdev.
5621			 * 5. This isn't prefetch and l2arc_noprefetch is set.
5622			 */
5623			if (HDR_HAS_L2HDR(hdr) &&
5624			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
5625			    !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
5626				l2arc_read_callback_t *cb;
5627				abd_t *abd;
5628				uint64_t asize;
5629
5630				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
5631				ARCSTAT_BUMP(arcstat_l2_hits);
5632
5633				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
5634				    KM_SLEEP);
5635				cb->l2rcb_hdr = hdr;
5636				cb->l2rcb_bp = *bp;
5637				cb->l2rcb_zb = *zb;
5638				cb->l2rcb_flags = zio_flags;
5639
5640				asize = vdev_psize_to_asize(vd, size);
5641				if (asize != size) {
5642					abd = abd_alloc_for_io(asize,
5643					    HDR_ISTYPE_METADATA(hdr));
5644					cb->l2rcb_abd = abd;
5645				} else {
5646					abd = hdr->b_l1hdr.b_pabd;
5647				}
5648
5649				ASSERT(addr >= VDEV_LABEL_START_SIZE &&
5650				    addr + asize <= vd->vdev_psize -
5651				    VDEV_LABEL_END_SIZE);
5652
5653				/*
5654				 * l2arc read.  The SCL_L2ARC lock will be
5655				 * released by l2arc_read_done().
5656				 * Issue a null zio if the underlying buffer
5657				 * was squashed to zero size by compression.
5658				 */
5659				ASSERT3U(HDR_GET_COMPRESS(hdr), !=,
5660				    ZIO_COMPRESS_EMPTY);
5661				rzio = zio_read_phys(pio, vd, addr,
5662				    asize, abd,
5663				    ZIO_CHECKSUM_OFF,
5664				    l2arc_read_done, cb, priority,
5665				    zio_flags | ZIO_FLAG_DONT_CACHE |
5666				    ZIO_FLAG_CANFAIL |
5667				    ZIO_FLAG_DONT_PROPAGATE |
5668				    ZIO_FLAG_DONT_RETRY, B_FALSE);
5669				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
5670				    zio_t *, rzio);
5671				ARCSTAT_INCR(arcstat_l2_read_bytes, size);
5672
5673				if (*arc_flags & ARC_FLAG_NOWAIT) {
5674					zio_nowait(rzio);
5675					return (0);
5676				}
5677
5678				ASSERT(*arc_flags & ARC_FLAG_WAIT);
5679				if (zio_wait(rzio) == 0)
5680					return (0);
5681
5682				/* l2arc read error; goto zio_read() */
5683			} else {
5684				DTRACE_PROBE1(l2arc__miss,
5685				    arc_buf_hdr_t *, hdr);
5686				ARCSTAT_BUMP(arcstat_l2_misses);
5687				if (HDR_L2_WRITING(hdr))
5688					ARCSTAT_BUMP(arcstat_l2_rw_clash);
5689				spa_config_exit(spa, SCL_L2ARC, vd);
5690			}
5691		} else {
5692			if (vd != NULL)
5693				spa_config_exit(spa, SCL_L2ARC, vd);
5694			if (l2arc_ndev != 0) {
5695				DTRACE_PROBE1(l2arc__miss,
5696				    arc_buf_hdr_t *, hdr);
5697				ARCSTAT_BUMP(arcstat_l2_misses);
5698			}
5699		}
5700
5701		rzio = zio_read(pio, spa, bp, hdr->b_l1hdr.b_pabd, size,
5702		    arc_read_done, hdr, priority, zio_flags, zb);
5703
5704		if (*arc_flags & ARC_FLAG_WAIT)
5705			return (zio_wait(rzio));
5706
5707		ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
5708		zio_nowait(rzio);
5709	}
5710	return (0);
5711}
5712
5713/*
5714 * Notify the arc that a block was freed, and thus will never be used again.
5715 */
5716void
5717arc_freed(spa_t *spa, const blkptr_t *bp)
5718{
5719	arc_buf_hdr_t *hdr;
5720	kmutex_t *hash_lock;
5721	uint64_t guid = spa_load_guid(spa);
5722
5723	ASSERT(!BP_IS_EMBEDDED(bp));
5724
5725	hdr = buf_hash_find(guid, bp, &hash_lock);
5726	if (hdr == NULL)
5727		return;
5728
5729	/*
5730	 * We might be trying to free a block that is still doing I/O
5731	 * (i.e. prefetch) or has a reference (i.e. a dedup-ed,
5732	 * dmu_sync-ed block). If this block is being prefetched, then it
5733	 * would still have the ARC_FLAG_IO_IN_PROGRESS flag set on the hdr
5734	 * until the I/O completes. A block may also have a reference if it is
5735	 * part of a dedup-ed, dmu_synced write. The dmu_sync() function would
5736	 * have written the new block to its final resting place on disk but
5737	 * without the dedup flag set. This would have left the hdr in the MRU
5738	 * state and discoverable. When the txg finally syncs it detects that
5739	 * the block was overridden in open context and issues an override I/O.
5740	 * Since this is a dedup block, the override I/O will determine if the
5741	 * block is already in the DDT. If so, then it will replace the io_bp
5742	 * with the bp from the DDT and allow the I/O to finish. When the I/O
5743	 * reaches the done callback, dbuf_write_override_done, it will
5744	 * check to see if the io_bp and io_bp_override are identical.
5745	 * If they are not, then it indicates that the bp was replaced with
5746	 * the bp in the DDT and the override bp is freed. This allows
5747	 * us to arrive here with a reference on a block that is being
5748	 * freed. So if we have an I/O in progress, or a reference to
5749	 * this hdr, then we don't destroy the hdr.
5750	 */
5751	if (!HDR_HAS_L1HDR(hdr) || (!HDR_IO_IN_PROGRESS(hdr) &&
5752	    refcount_is_zero(&hdr->b_l1hdr.b_refcnt))) {
5753		arc_change_state(arc_anon, hdr, hash_lock);
5754		arc_hdr_destroy(hdr);
5755		mutex_exit(hash_lock);
5756	} else {
5757		mutex_exit(hash_lock);
5758	}
5759
5760}
5761
5762/*
5763 * Release this buffer from the cache, making it an anonymous buffer.  This
5764 * must be done after a read and prior to modifying the buffer contents.
5765 * If the buffer has more than one reference, we must make
5766 * a new hdr for the buffer.
5767 */
5768void
5769arc_release(arc_buf_t *buf, void *tag)
5770{
5771	arc_buf_hdr_t *hdr = buf->b_hdr;
5772
5773	/*
5774	 * It would be nice to assert that if it's DMU metadata (level >
5775	 * 0 || it's the dnode file), then it must be syncing context.
5776	 * But we don't know that information at this level.
5777	 */
5778
5779	mutex_enter(&buf->b_evict_lock);
5780
5781	ASSERT(HDR_HAS_L1HDR(hdr));
5782
5783	/*
5784	 * We don't grab the hash lock prior to this check, because if
5785	 * the buffer's header is in the arc_anon state, it won't be
5786	 * linked into the hash table.
5787	 */
5788	if (hdr->b_l1hdr.b_state == arc_anon) {
5789		mutex_exit(&buf->b_evict_lock);
5790		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5791		ASSERT(!HDR_IN_HASH_TABLE(hdr));
5792		ASSERT(!HDR_HAS_L2HDR(hdr));
5793		ASSERT(HDR_EMPTY(hdr));
5794		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
5795		ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
5796		ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
5797
5798		hdr->b_l1hdr.b_arc_access = 0;
5799
5800		/*
5801		 * If the buf is being overridden then it may already
5802		 * have a hdr that is not empty.
5803		 */
5804		buf_discard_identity(hdr);
5805		arc_buf_thaw(buf);
5806
5807		return;
5808	}
5809
5810	kmutex_t *hash_lock = HDR_LOCK(hdr);
5811	mutex_enter(hash_lock);
5812
5813	/*
5814	 * This assignment is only valid as long as the hash_lock is
5815	 * held, we must be careful not to reference state or the
5816	 * b_state field after dropping the lock.
5817	 */
5818	arc_state_t *state = hdr->b_l1hdr.b_state;
5819	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
5820	ASSERT3P(state, !=, arc_anon);
5821
5822	/* this buffer is not on any list */
5823	ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), >, 0);
5824
5825	if (HDR_HAS_L2HDR(hdr)) {
5826		mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
5827
5828		/*
5829		 * We have to recheck this conditional again now that
5830		 * we're holding the l2ad_mtx to prevent a race with
5831		 * another thread which might be concurrently calling
5832		 * l2arc_evict(). In that case, l2arc_evict() might have
5833		 * destroyed the header's L2 portion as we were waiting
5834		 * to acquire the l2ad_mtx.
5835		 */
5836		if (HDR_HAS_L2HDR(hdr)) {
5837			l2arc_trim(hdr);
5838			arc_hdr_l2hdr_destroy(hdr);
5839		}
5840
5841		mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
5842	}
5843
5844	/*
5845	 * Do we have more than one buf?
5846	 */
5847	if (hdr->b_l1hdr.b_bufcnt > 1) {
5848		arc_buf_hdr_t *nhdr;
5849		uint64_t spa = hdr->b_spa;
5850		uint64_t psize = HDR_GET_PSIZE(hdr);
5851		uint64_t lsize = HDR_GET_LSIZE(hdr);
5852		enum zio_compress compress = HDR_GET_COMPRESS(hdr);
5853		arc_buf_contents_t type = arc_buf_type(hdr);
5854		VERIFY3U(hdr->b_type, ==, type);
5855
5856		ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
5857		(void) remove_reference(hdr, hash_lock, tag);
5858
5859		if (arc_buf_is_shared(buf) && !ARC_BUF_COMPRESSED(buf)) {
5860			ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
5861			ASSERT(ARC_BUF_LAST(buf));
5862		}
5863
5864		/*
5865		 * Pull the data off of this hdr and attach it to
5866		 * a new anonymous hdr. Also find the last buffer
5867		 * in the hdr's buffer list.
5868		 */
5869		arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
5870		ASSERT3P(lastbuf, !=, NULL);
5871
5872		/*
5873		 * If the current arc_buf_t and the hdr are sharing their data
5874		 * buffer, then we must stop sharing that block.
5875		 */
5876		if (arc_buf_is_shared(buf)) {
5877			VERIFY(!arc_buf_is_shared(lastbuf));
5878
5879			/*
5880			 * First, sever the block sharing relationship between
5881			 * buf and the arc_buf_hdr_t.
5882			 */
5883			arc_unshare_buf(hdr, buf);
5884
5885			/*
5886			 * Now we need to recreate the hdr's b_pabd. Since we
5887			 * have lastbuf handy, we try to share with it, but if
5888			 * we can't then we allocate a new b_pabd and copy the
5889			 * data from buf into it.
5890			 */
5891			if (arc_can_share(hdr, lastbuf)) {
5892				arc_share_buf(hdr, lastbuf);
5893			} else {
5894				arc_hdr_alloc_pabd(hdr);
5895				abd_copy_from_buf(hdr->b_l1hdr.b_pabd,
5896				    buf->b_data, psize);
5897			}
5898			VERIFY3P(lastbuf->b_data, !=, NULL);
5899		} else if (HDR_SHARED_DATA(hdr)) {
5900			/*
5901			 * Uncompressed shared buffers are always at the end
5902			 * of the list. Compressed buffers don't have the
5903			 * same requirements. This makes it hard to
5904			 * simply assert that the lastbuf is shared so
5905			 * we rely on the hdr's compression flags to determine
5906			 * if we have a compressed, shared buffer.
5907			 */
5908			ASSERT(arc_buf_is_shared(lastbuf) ||
5909			    HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
5910			ASSERT(!ARC_BUF_SHARED(buf));
5911		}
5912		ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
5913		ASSERT3P(state, !=, arc_l2c_only);
5914
5915		(void) refcount_remove_many(&state->arcs_size,
5916		    arc_buf_size(buf), buf);
5917
5918		if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
5919			ASSERT3P(state, !=, arc_l2c_only);
5920			(void) refcount_remove_many(&state->arcs_esize[type],
5921			    arc_buf_size(buf), buf);
5922		}
5923
5924		hdr->b_l1hdr.b_bufcnt -= 1;
5925		arc_cksum_verify(buf);
5926#ifdef illumos
5927		arc_buf_unwatch(buf);
5928#endif
5929
5930		mutex_exit(hash_lock);
5931
5932		/*
5933		 * Allocate a new hdr. The new hdr will contain a b_pabd
5934		 * buffer which will be freed in arc_write().
5935		 */
5936		nhdr = arc_hdr_alloc(spa, psize, lsize, compress, type);
5937		ASSERT3P(nhdr->b_l1hdr.b_buf, ==, NULL);
5938		ASSERT0(nhdr->b_l1hdr.b_bufcnt);
5939		ASSERT0(refcount_count(&nhdr->b_l1hdr.b_refcnt));
5940		VERIFY3U(nhdr->b_type, ==, type);
5941		ASSERT(!HDR_SHARED_DATA(nhdr));
5942
5943		nhdr->b_l1hdr.b_buf = buf;
5944		nhdr->b_l1hdr.b_bufcnt = 1;
5945		(void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
5946		buf->b_hdr = nhdr;
5947
5948		mutex_exit(&buf->b_evict_lock);
5949		(void) refcount_add_many(&arc_anon->arcs_size,
5950		    arc_buf_size(buf), buf);
5951	} else {
5952		mutex_exit(&buf->b_evict_lock);
5953		ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
5954		/* protected by hash lock, or hdr is on arc_anon */
5955		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
5956		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5957		arc_change_state(arc_anon, hdr, hash_lock);
5958		hdr->b_l1hdr.b_arc_access = 0;
5959		mutex_exit(hash_lock);
5960
5961		buf_discard_identity(hdr);
5962		arc_buf_thaw(buf);
5963	}
5964}
5965
5966int
5967arc_released(arc_buf_t *buf)
5968{
5969	int released;
5970
5971	mutex_enter(&buf->b_evict_lock);
5972	released = (buf->b_data != NULL &&
5973	    buf->b_hdr->b_l1hdr.b_state == arc_anon);
5974	mutex_exit(&buf->b_evict_lock);
5975	return (released);
5976}
5977
5978#ifdef ZFS_DEBUG
5979int
5980arc_referenced(arc_buf_t *buf)
5981{
5982	int referenced;
5983
5984	mutex_enter(&buf->b_evict_lock);
5985	referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
5986	mutex_exit(&buf->b_evict_lock);
5987	return (referenced);
5988}
5989#endif
5990
5991static void
5992arc_write_ready(zio_t *zio)
5993{
5994	arc_write_callback_t *callback = zio->io_private;
5995	arc_buf_t *buf = callback->awcb_buf;
5996	arc_buf_hdr_t *hdr = buf->b_hdr;
5997	uint64_t psize = BP_IS_HOLE(zio->io_bp) ? 0 : BP_GET_PSIZE(zio->io_bp);
5998
5999	ASSERT(HDR_HAS_L1HDR(hdr));
6000	ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
6001	ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
6002
6003	/*
6004	 * If we're reexecuting this zio because the pool suspended, then
6005	 * cleanup any state that was previously set the first time the
6006	 * callback was invoked.
6007	 */
6008	if (zio->io_flags & ZIO_FLAG_REEXECUTED) {
6009		arc_cksum_free(hdr);
6010#ifdef illumos
6011		arc_buf_unwatch(buf);
6012#endif
6013		if (hdr->b_l1hdr.b_pabd != NULL) {
6014			if (arc_buf_is_shared(buf)) {
6015				arc_unshare_buf(hdr, buf);
6016			} else {
6017				arc_hdr_free_pabd(hdr);
6018			}
6019		}
6020	}
6021	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
6022	ASSERT(!HDR_SHARED_DATA(hdr));
6023	ASSERT(!arc_buf_is_shared(buf));
6024
6025	callback->awcb_ready(zio, buf, callback->awcb_private);
6026
6027	if (HDR_IO_IN_PROGRESS(hdr))
6028		ASSERT(zio->io_flags & ZIO_FLAG_REEXECUTED);
6029
6030	arc_cksum_compute(buf);
6031	arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6032
6033	enum zio_compress compress;
6034	if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
6035		compress = ZIO_COMPRESS_OFF;
6036	} else {
6037		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(zio->io_bp));
6038		compress = BP_GET_COMPRESS(zio->io_bp);
6039	}
6040	HDR_SET_PSIZE(hdr, psize);
6041	arc_hdr_set_compress(hdr, compress);
6042
6043
6044	/*
6045	 * Fill the hdr with data. If the hdr is compressed, the data we want
6046	 * is available from the zio, otherwise we can take it from the buf.
6047	 *
6048	 * We might be able to share the buf's data with the hdr here. However,
6049	 * doing so would cause the ARC to be full of linear ABDs if we write a
6050	 * lot of shareable data. As a compromise, we check whether scattered
6051	 * ABDs are allowed, and assume that if they are then the user wants
6052	 * the ARC to be primarily filled with them regardless of the data being
6053	 * written. Therefore, if they're allowed then we allocate one and copy
6054	 * the data into it; otherwise, we share the data directly if we can.
6055	 */
6056	if (zfs_abd_scatter_enabled || !arc_can_share(hdr, buf)) {
6057		arc_hdr_alloc_pabd(hdr);
6058
6059		/*
6060		 * Ideally, we would always copy the io_abd into b_pabd, but the
6061		 * user may have disabled compressed ARC, thus we must check the
6062		 * hdr's compression setting rather than the io_bp's.
6063		 */
6064		if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
6065			ASSERT3U(BP_GET_COMPRESS(zio->io_bp), !=,
6066			    ZIO_COMPRESS_OFF);
6067			ASSERT3U(psize, >, 0);
6068
6069			abd_copy(hdr->b_l1hdr.b_pabd, zio->io_abd, psize);
6070		} else {
6071			ASSERT3U(zio->io_orig_size, ==, arc_hdr_size(hdr));
6072
6073			abd_copy_from_buf(hdr->b_l1hdr.b_pabd, buf->b_data,
6074			    arc_buf_size(buf));
6075		}
6076	} else {
6077		ASSERT3P(buf->b_data, ==, abd_to_buf(zio->io_orig_abd));
6078		ASSERT3U(zio->io_orig_size, ==, arc_buf_size(buf));
6079		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
6080
6081		arc_share_buf(hdr, buf);
6082	}
6083
6084	arc_hdr_verify(hdr, zio->io_bp);
6085}
6086
6087static void
6088arc_write_children_ready(zio_t *zio)
6089{
6090	arc_write_callback_t *callback = zio->io_private;
6091	arc_buf_t *buf = callback->awcb_buf;
6092
6093	callback->awcb_children_ready(zio, buf, callback->awcb_private);
6094}
6095
6096/*
6097 * The SPA calls this callback for each physical write that happens on behalf
6098 * of a logical write.  See the comment in dbuf_write_physdone() for details.
6099 */
6100static void
6101arc_write_physdone(zio_t *zio)
6102{
6103	arc_write_callback_t *cb = zio->io_private;
6104	if (cb->awcb_physdone != NULL)
6105		cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
6106}
6107
6108static void
6109arc_write_done(zio_t *zio)
6110{
6111	arc_write_callback_t *callback = zio->io_private;
6112	arc_buf_t *buf = callback->awcb_buf;
6113	arc_buf_hdr_t *hdr = buf->b_hdr;
6114
6115	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
6116
6117	if (zio->io_error == 0) {
6118		arc_hdr_verify(hdr, zio->io_bp);
6119
6120		if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
6121			buf_discard_identity(hdr);
6122		} else {
6123			hdr->b_dva = *BP_IDENTITY(zio->io_bp);
6124			hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
6125		}
6126	} else {
6127		ASSERT(HDR_EMPTY(hdr));
6128	}
6129
6130	/*
6131	 * If the block to be written was all-zero or compressed enough to be
6132	 * embedded in the BP, no write was performed so there will be no
6133	 * dva/birth/checksum.  The buffer must therefore remain anonymous
6134	 * (and uncached).
6135	 */
6136	if (!HDR_EMPTY(hdr)) {
6137		arc_buf_hdr_t *exists;
6138		kmutex_t *hash_lock;
6139
6140		ASSERT3U(zio->io_error, ==, 0);
6141
6142		arc_cksum_verify(buf);
6143
6144		exists = buf_hash_insert(hdr, &hash_lock);
6145		if (exists != NULL) {
6146			/*
6147			 * This can only happen if we overwrite for
6148			 * sync-to-convergence, because we remove
6149			 * buffers from the hash table when we arc_free().
6150			 */
6151			if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
6152				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
6153					panic("bad overwrite, hdr=%p exists=%p",
6154					    (void *)hdr, (void *)exists);
6155				ASSERT(refcount_is_zero(
6156				    &exists->b_l1hdr.b_refcnt));
6157				arc_change_state(arc_anon, exists, hash_lock);
6158				mutex_exit(hash_lock);
6159				arc_hdr_destroy(exists);
6160				exists = buf_hash_insert(hdr, &hash_lock);
6161				ASSERT3P(exists, ==, NULL);
6162			} else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
6163				/* nopwrite */
6164				ASSERT(zio->io_prop.zp_nopwrite);
6165				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
6166					panic("bad nopwrite, hdr=%p exists=%p",
6167					    (void *)hdr, (void *)exists);
6168			} else {
6169				/* Dedup */
6170				ASSERT(hdr->b_l1hdr.b_bufcnt == 1);
6171				ASSERT(hdr->b_l1hdr.b_state == arc_anon);
6172				ASSERT(BP_GET_DEDUP(zio->io_bp));
6173				ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
6174			}
6175		}
6176		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6177		/* if it's not anon, we are doing a scrub */
6178		if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
6179			arc_access(hdr, hash_lock);
6180		mutex_exit(hash_lock);
6181	} else {
6182		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6183	}
6184
6185	ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
6186	callback->awcb_done(zio, buf, callback->awcb_private);
6187
6188	abd_put(zio->io_abd);
6189	kmem_free(callback, sizeof (arc_write_callback_t));
6190}
6191
6192zio_t *
6193arc_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
6194    boolean_t l2arc, const zio_prop_t *zp, arc_done_func_t *ready,
6195    arc_done_func_t *children_ready, arc_done_func_t *physdone,
6196    arc_done_func_t *done, void *private, zio_priority_t priority,
6197    int zio_flags, const zbookmark_phys_t *zb)
6198{
6199	arc_buf_hdr_t *hdr = buf->b_hdr;
6200	arc_write_callback_t *callback;
6201	zio_t *zio;
6202	zio_prop_t localprop = *zp;
6203
6204	ASSERT3P(ready, !=, NULL);
6205	ASSERT3P(done, !=, NULL);
6206	ASSERT(!HDR_IO_ERROR(hdr));
6207	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6208	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
6209	ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
6210	if (l2arc)
6211		arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
6212	if (ARC_BUF_COMPRESSED(buf)) {
6213		/*
6214		 * We're writing a pre-compressed buffer.  Make the
6215		 * compression algorithm requested by the zio_prop_t match
6216		 * the pre-compressed buffer's compression algorithm.
6217		 */
6218		localprop.zp_compress = HDR_GET_COMPRESS(hdr);
6219
6220		ASSERT3U(HDR_GET_LSIZE(hdr), !=, arc_buf_size(buf));
6221		zio_flags |= ZIO_FLAG_RAW;
6222	}
6223	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
6224	callback->awcb_ready = ready;
6225	callback->awcb_children_ready = children_ready;
6226	callback->awcb_physdone = physdone;
6227	callback->awcb_done = done;
6228	callback->awcb_private = private;
6229	callback->awcb_buf = buf;
6230
6231	/*
6232	 * The hdr's b_pabd is now stale, free it now. A new data block
6233	 * will be allocated when the zio pipeline calls arc_write_ready().
6234	 */
6235	if (hdr->b_l1hdr.b_pabd != NULL) {
6236		/*
6237		 * If the buf is currently sharing the data block with
6238		 * the hdr then we need to break that relationship here.
6239		 * The hdr will remain with a NULL data pointer and the
6240		 * buf will take sole ownership of the block.
6241		 */
6242		if (arc_buf_is_shared(buf)) {
6243			arc_unshare_buf(hdr, buf);
6244		} else {
6245			arc_hdr_free_pabd(hdr);
6246		}
6247		VERIFY3P(buf->b_data, !=, NULL);
6248		arc_hdr_set_compress(hdr, ZIO_COMPRESS_OFF);
6249	}
6250	ASSERT(!arc_buf_is_shared(buf));
6251	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
6252
6253	zio = zio_write(pio, spa, txg, bp,
6254	    abd_get_from_buf(buf->b_data, HDR_GET_LSIZE(hdr)),
6255	    HDR_GET_LSIZE(hdr), arc_buf_size(buf), &localprop, arc_write_ready,
6256	    (children_ready != NULL) ? arc_write_children_ready : NULL,
6257	    arc_write_physdone, arc_write_done, callback,
6258	    priority, zio_flags, zb);
6259
6260	return (zio);
6261}
6262
6263static int
6264arc_memory_throttle(uint64_t reserve, uint64_t txg)
6265{
6266#ifdef _KERNEL
6267	uint64_t available_memory = ptob(freemem);
6268	static uint64_t page_load = 0;
6269	static uint64_t last_txg = 0;
6270
6271#if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
6272	available_memory =
6273	    MIN(available_memory, ptob(vmem_size(heap_arena, VMEM_FREE)));
6274#endif
6275
6276	if (freemem > (uint64_t)physmem * arc_lotsfree_percent / 100)
6277		return (0);
6278
6279	if (txg > last_txg) {
6280		last_txg = txg;
6281		page_load = 0;
6282	}
6283	/*
6284	 * If we are in pageout, we know that memory is already tight,
6285	 * the arc is already going to be evicting, so we just want to
6286	 * continue to let page writes occur as quickly as possible.
6287	 */
6288	if (curproc == pageproc) {
6289		if (page_load > MAX(ptob(minfree), available_memory) / 4)
6290			return (SET_ERROR(ERESTART));
6291		/* Note: reserve is inflated, so we deflate */
6292		page_load += reserve / 8;
6293		return (0);
6294	} else if (page_load > 0 && arc_reclaim_needed()) {
6295		/* memory is low, delay before restarting */
6296		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
6297		return (SET_ERROR(EAGAIN));
6298	}
6299	page_load = 0;
6300#endif
6301	return (0);
6302}
6303
6304void
6305arc_tempreserve_clear(uint64_t reserve)
6306{
6307	atomic_add_64(&arc_tempreserve, -reserve);
6308	ASSERT((int64_t)arc_tempreserve >= 0);
6309}
6310
6311int
6312arc_tempreserve_space(uint64_t reserve, uint64_t txg)
6313{
6314	int error;
6315	uint64_t anon_size;
6316
6317	if (reserve > arc_c/4 && !arc_no_grow) {
6318		arc_c = MIN(arc_c_max, reserve * 4);
6319		DTRACE_PROBE1(arc__set_reserve, uint64_t, arc_c);
6320	}
6321	if (reserve > arc_c)
6322		return (SET_ERROR(ENOMEM));
6323
6324	/*
6325	 * Don't count loaned bufs as in flight dirty data to prevent long
6326	 * network delays from blocking transactions that are ready to be
6327	 * assigned to a txg.
6328	 */
6329
6330	/* assert that it has not wrapped around */
6331	ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
6332
6333	anon_size = MAX((int64_t)(refcount_count(&arc_anon->arcs_size) -
6334	    arc_loaned_bytes), 0);
6335
6336	/*
6337	 * Writes will, almost always, require additional memory allocations
6338	 * in order to compress/encrypt/etc the data.  We therefore need to
6339	 * make sure that there is sufficient available memory for this.
6340	 */
6341	error = arc_memory_throttle(reserve, txg);
6342	if (error != 0)
6343		return (error);
6344
6345	/*
6346	 * Throttle writes when the amount of dirty data in the cache
6347	 * gets too large.  We try to keep the cache less than half full
6348	 * of dirty blocks so that our sync times don't grow too large.
6349	 * Note: if two requests come in concurrently, we might let them
6350	 * both succeed, when one of them should fail.  Not a huge deal.
6351	 */
6352
6353	if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
6354	    anon_size > arc_c / 4) {
6355		uint64_t meta_esize =
6356		    refcount_count(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6357		uint64_t data_esize =
6358		    refcount_count(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6359		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
6360		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
6361		    arc_tempreserve >> 10, meta_esize >> 10,
6362		    data_esize >> 10, reserve >> 10, arc_c >> 10);
6363		return (SET_ERROR(ERESTART));
6364	}
6365	atomic_add_64(&arc_tempreserve, reserve);
6366	return (0);
6367}
6368
6369static void
6370arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
6371    kstat_named_t *evict_data, kstat_named_t *evict_metadata)
6372{
6373	size->value.ui64 = refcount_count(&state->arcs_size);
6374	evict_data->value.ui64 =
6375	    refcount_count(&state->arcs_esize[ARC_BUFC_DATA]);
6376	evict_metadata->value.ui64 =
6377	    refcount_count(&state->arcs_esize[ARC_BUFC_METADATA]);
6378}
6379
6380static int
6381arc_kstat_update(kstat_t *ksp, int rw)
6382{
6383	arc_stats_t *as = ksp->ks_data;
6384
6385	if (rw == KSTAT_WRITE) {
6386		return (EACCES);
6387	} else {
6388		arc_kstat_update_state(arc_anon,
6389		    &as->arcstat_anon_size,
6390		    &as->arcstat_anon_evictable_data,
6391		    &as->arcstat_anon_evictable_metadata);
6392		arc_kstat_update_state(arc_mru,
6393		    &as->arcstat_mru_size,
6394		    &as->arcstat_mru_evictable_data,
6395		    &as->arcstat_mru_evictable_metadata);
6396		arc_kstat_update_state(arc_mru_ghost,
6397		    &as->arcstat_mru_ghost_size,
6398		    &as->arcstat_mru_ghost_evictable_data,
6399		    &as->arcstat_mru_ghost_evictable_metadata);
6400		arc_kstat_update_state(arc_mfu,
6401		    &as->arcstat_mfu_size,
6402		    &as->arcstat_mfu_evictable_data,
6403		    &as->arcstat_mfu_evictable_metadata);
6404		arc_kstat_update_state(arc_mfu_ghost,
6405		    &as->arcstat_mfu_ghost_size,
6406		    &as->arcstat_mfu_ghost_evictable_data,
6407		    &as->arcstat_mfu_ghost_evictable_metadata);
6408
6409		ARCSTAT(arcstat_size) = aggsum_value(&arc_size);
6410		ARCSTAT(arcstat_meta_used) = aggsum_value(&arc_meta_used);
6411		ARCSTAT(arcstat_data_size) = aggsum_value(&astat_data_size);
6412		ARCSTAT(arcstat_metadata_size) =
6413		    aggsum_value(&astat_metadata_size);
6414		ARCSTAT(arcstat_hdr_size) = aggsum_value(&astat_hdr_size);
6415		ARCSTAT(arcstat_other_size) = aggsum_value(&astat_other_size);
6416		ARCSTAT(arcstat_l2_hdr_size) = aggsum_value(&astat_l2_hdr_size);
6417	}
6418
6419	return (0);
6420}
6421
6422/*
6423 * This function *must* return indices evenly distributed between all
6424 * sublists of the multilist. This is needed due to how the ARC eviction
6425 * code is laid out; arc_evict_state() assumes ARC buffers are evenly
6426 * distributed between all sublists and uses this assumption when
6427 * deciding which sublist to evict from and how much to evict from it.
6428 */
6429unsigned int
6430arc_state_multilist_index_func(multilist_t *ml, void *obj)
6431{
6432	arc_buf_hdr_t *hdr = obj;
6433
6434	/*
6435	 * We rely on b_dva to generate evenly distributed index
6436	 * numbers using buf_hash below. So, as an added precaution,
6437	 * let's make sure we never add empty buffers to the arc lists.
6438	 */
6439	ASSERT(!HDR_EMPTY(hdr));
6440
6441	/*
6442	 * The assumption here, is the hash value for a given
6443	 * arc_buf_hdr_t will remain constant throughout it's lifetime
6444	 * (i.e. it's b_spa, b_dva, and b_birth fields don't change).
6445	 * Thus, we don't need to store the header's sublist index
6446	 * on insertion, as this index can be recalculated on removal.
6447	 *
6448	 * Also, the low order bits of the hash value are thought to be
6449	 * distributed evenly. Otherwise, in the case that the multilist
6450	 * has a power of two number of sublists, each sublists' usage
6451	 * would not be evenly distributed.
6452	 */
6453	return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
6454	    multilist_get_num_sublists(ml));
6455}
6456
6457#ifdef _KERNEL
6458static eventhandler_tag arc_event_lowmem = NULL;
6459
6460static void
6461arc_lowmem(void *arg __unused, int howto __unused)
6462{
6463
6464	mutex_enter(&arc_reclaim_lock);
6465	DTRACE_PROBE1(arc__needfree, int64_t, ((int64_t)freemem - zfs_arc_free_target) * PAGESIZE);
6466	cv_signal(&arc_reclaim_thread_cv);
6467
6468	/*
6469	 * It is unsafe to block here in arbitrary threads, because we can come
6470	 * here from ARC itself and may hold ARC locks and thus risk a deadlock
6471	 * with ARC reclaim thread.
6472	 */
6473	if (curproc == pageproc)
6474		(void) cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
6475	mutex_exit(&arc_reclaim_lock);
6476}
6477#endif
6478
6479static void
6480arc_state_init(void)
6481{
6482	arc_anon = &ARC_anon;
6483	arc_mru = &ARC_mru;
6484	arc_mru_ghost = &ARC_mru_ghost;
6485	arc_mfu = &ARC_mfu;
6486	arc_mfu_ghost = &ARC_mfu_ghost;
6487	arc_l2c_only = &ARC_l2c_only;
6488
6489	arc_mru->arcs_list[ARC_BUFC_METADATA] =
6490	    multilist_create(sizeof (arc_buf_hdr_t),
6491	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6492	    arc_state_multilist_index_func);
6493	arc_mru->arcs_list[ARC_BUFC_DATA] =
6494	    multilist_create(sizeof (arc_buf_hdr_t),
6495	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6496	    arc_state_multilist_index_func);
6497	arc_mru_ghost->arcs_list[ARC_BUFC_METADATA] =
6498	    multilist_create(sizeof (arc_buf_hdr_t),
6499	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6500	    arc_state_multilist_index_func);
6501	arc_mru_ghost->arcs_list[ARC_BUFC_DATA] =
6502	    multilist_create(sizeof (arc_buf_hdr_t),
6503	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6504	    arc_state_multilist_index_func);
6505	arc_mfu->arcs_list[ARC_BUFC_METADATA] =
6506	    multilist_create(sizeof (arc_buf_hdr_t),
6507	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6508	    arc_state_multilist_index_func);
6509	arc_mfu->arcs_list[ARC_BUFC_DATA] =
6510	    multilist_create(sizeof (arc_buf_hdr_t),
6511	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6512	    arc_state_multilist_index_func);
6513	arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA] =
6514	    multilist_create(sizeof (arc_buf_hdr_t),
6515	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6516	    arc_state_multilist_index_func);
6517	arc_mfu_ghost->arcs_list[ARC_BUFC_DATA] =
6518	    multilist_create(sizeof (arc_buf_hdr_t),
6519	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6520	    arc_state_multilist_index_func);
6521	arc_l2c_only->arcs_list[ARC_BUFC_METADATA] =
6522	    multilist_create(sizeof (arc_buf_hdr_t),
6523	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6524	    arc_state_multilist_index_func);
6525	arc_l2c_only->arcs_list[ARC_BUFC_DATA] =
6526	    multilist_create(sizeof (arc_buf_hdr_t),
6527	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6528	    arc_state_multilist_index_func);
6529
6530	refcount_create(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6531	refcount_create(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6532	refcount_create(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
6533	refcount_create(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
6534	refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
6535	refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
6536	refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
6537	refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
6538	refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
6539	refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
6540	refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
6541	refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
6542
6543	refcount_create(&arc_anon->arcs_size);
6544	refcount_create(&arc_mru->arcs_size);
6545	refcount_create(&arc_mru_ghost->arcs_size);
6546	refcount_create(&arc_mfu->arcs_size);
6547	refcount_create(&arc_mfu_ghost->arcs_size);
6548	refcount_create(&arc_l2c_only->arcs_size);
6549
6550	aggsum_init(&arc_meta_used, 0);
6551	aggsum_init(&arc_size, 0);
6552	aggsum_init(&astat_data_size, 0);
6553	aggsum_init(&astat_metadata_size, 0);
6554	aggsum_init(&astat_hdr_size, 0);
6555	aggsum_init(&astat_other_size, 0);
6556	aggsum_init(&astat_l2_hdr_size, 0);
6557}
6558
6559static void
6560arc_state_fini(void)
6561{
6562	refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6563	refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6564	refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
6565	refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
6566	refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
6567	refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
6568	refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
6569	refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
6570	refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
6571	refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
6572	refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
6573	refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
6574
6575	refcount_destroy(&arc_anon->arcs_size);
6576	refcount_destroy(&arc_mru->arcs_size);
6577	refcount_destroy(&arc_mru_ghost->arcs_size);
6578	refcount_destroy(&arc_mfu->arcs_size);
6579	refcount_destroy(&arc_mfu_ghost->arcs_size);
6580	refcount_destroy(&arc_l2c_only->arcs_size);
6581
6582	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_METADATA]);
6583	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
6584	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_METADATA]);
6585	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
6586	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_DATA]);
6587	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
6588	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_DATA]);
6589	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
6590}
6591
6592uint64_t
6593arc_max_bytes(void)
6594{
6595	return (arc_c_max);
6596}
6597
6598void
6599arc_init(void)
6600{
6601	int i, prefetch_tunable_set = 0;
6602
6603	/*
6604	 * allmem is "all memory that we could possibly use".
6605	 */
6606#ifdef illumos
6607#ifdef _KERNEL
6608	uint64_t allmem = ptob(physmem - swapfs_minfree);
6609#else
6610	uint64_t allmem = (physmem * PAGESIZE) / 2;
6611#endif
6612#else
6613	uint64_t allmem = kmem_size();
6614#endif
6615
6616
6617	mutex_init(&arc_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
6618	cv_init(&arc_reclaim_thread_cv, NULL, CV_DEFAULT, NULL);
6619	cv_init(&arc_reclaim_waiters_cv, NULL, CV_DEFAULT, NULL);
6620
6621	mutex_init(&arc_dnlc_evicts_lock, NULL, MUTEX_DEFAULT, NULL);
6622	cv_init(&arc_dnlc_evicts_cv, NULL, CV_DEFAULT, NULL);
6623
6624	/* Convert seconds to clock ticks */
6625	arc_min_prefetch_lifespan = 1 * hz;
6626
6627	/* set min cache to 1/32 of all memory, or arc_abs_min, whichever is more */
6628	arc_c_min = MAX(allmem / 32, arc_abs_min);
6629	/* set max to 5/8 of all memory, or all but 1GB, whichever is more */
6630	if (allmem >= 1 << 30)
6631		arc_c_max = allmem - (1 << 30);
6632	else
6633		arc_c_max = arc_c_min;
6634	arc_c_max = MAX(allmem * 5 / 8, arc_c_max);
6635
6636	/*
6637	 * In userland, there's only the memory pressure that we artificially
6638	 * create (see arc_available_memory()).  Don't let arc_c get too
6639	 * small, because it can cause transactions to be larger than
6640	 * arc_c, causing arc_tempreserve_space() to fail.
6641	 */
6642#ifndef _KERNEL
6643	arc_c_min = arc_c_max / 2;
6644#endif
6645
6646#ifdef _KERNEL
6647	/*
6648	 * Allow the tunables to override our calculations if they are
6649	 * reasonable.
6650	 */
6651	if (zfs_arc_max > arc_abs_min && zfs_arc_max < allmem) {
6652		arc_c_max = zfs_arc_max;
6653		arc_c_min = MIN(arc_c_min, arc_c_max);
6654	}
6655	if (zfs_arc_min > arc_abs_min && zfs_arc_min <= arc_c_max)
6656		arc_c_min = zfs_arc_min;
6657#endif
6658
6659	arc_c = arc_c_max;
6660	arc_p = (arc_c >> 1);
6661
6662	/* limit meta-data to 1/4 of the arc capacity */
6663	arc_meta_limit = arc_c_max / 4;
6664
6665#ifdef _KERNEL
6666	/*
6667	 * Metadata is stored in the kernel's heap.  Don't let us
6668	 * use more than half the heap for the ARC.
6669	 */
6670	arc_meta_limit = MIN(arc_meta_limit,
6671	    vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 2);
6672#endif
6673
6674	/* Allow the tunable to override if it is reasonable */
6675	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
6676		arc_meta_limit = zfs_arc_meta_limit;
6677
6678	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
6679		arc_c_min = arc_meta_limit / 2;
6680
6681	if (zfs_arc_meta_min > 0) {
6682		arc_meta_min = zfs_arc_meta_min;
6683	} else {
6684		arc_meta_min = arc_c_min / 2;
6685	}
6686
6687	if (zfs_arc_grow_retry > 0)
6688		arc_grow_retry = zfs_arc_grow_retry;
6689
6690	if (zfs_arc_shrink_shift > 0)
6691		arc_shrink_shift = zfs_arc_shrink_shift;
6692
6693	if (zfs_arc_no_grow_shift > 0)
6694		arc_no_grow_shift = zfs_arc_no_grow_shift;
6695	/*
6696	 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
6697	 */
6698	if (arc_no_grow_shift >= arc_shrink_shift)
6699		arc_no_grow_shift = arc_shrink_shift - 1;
6700
6701	if (zfs_arc_p_min_shift > 0)
6702		arc_p_min_shift = zfs_arc_p_min_shift;
6703
6704	/* if kmem_flags are set, lets try to use less memory */
6705	if (kmem_debugging())
6706		arc_c = arc_c / 2;
6707	if (arc_c < arc_c_min)
6708		arc_c = arc_c_min;
6709
6710	zfs_arc_min = arc_c_min;
6711	zfs_arc_max = arc_c_max;
6712
6713	arc_state_init();
6714	buf_init();
6715
6716	arc_reclaim_thread_exit = B_FALSE;
6717	arc_dnlc_evicts_thread_exit = FALSE;
6718
6719	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
6720	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
6721
6722	if (arc_ksp != NULL) {
6723		arc_ksp->ks_data = &arc_stats;
6724		arc_ksp->ks_update = arc_kstat_update;
6725		kstat_install(arc_ksp);
6726	}
6727
6728	(void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
6729	    TS_RUN, minclsyspri);
6730
6731#ifdef _KERNEL
6732	arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
6733	    EVENTHANDLER_PRI_FIRST);
6734#endif
6735
6736	(void) thread_create(NULL, 0, arc_dnlc_evicts_thread, NULL, 0, &p0,
6737	    TS_RUN, minclsyspri);
6738
6739	arc_dead = B_FALSE;
6740	arc_warm = B_FALSE;
6741
6742	/*
6743	 * Calculate maximum amount of dirty data per pool.
6744	 *
6745	 * If it has been set by /etc/system, take that.
6746	 * Otherwise, use a percentage of physical memory defined by
6747	 * zfs_dirty_data_max_percent (default 10%) with a cap at
6748	 * zfs_dirty_data_max_max (default 4GB).
6749	 */
6750	if (zfs_dirty_data_max == 0) {
6751		zfs_dirty_data_max = ptob(physmem) *
6752		    zfs_dirty_data_max_percent / 100;
6753		zfs_dirty_data_max = MIN(zfs_dirty_data_max,
6754		    zfs_dirty_data_max_max);
6755	}
6756
6757#ifdef _KERNEL
6758	if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
6759		prefetch_tunable_set = 1;
6760
6761#ifdef __i386__
6762	if (prefetch_tunable_set == 0) {
6763		printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
6764		    "-- to enable,\n");
6765		printf("            add \"vfs.zfs.prefetch_disable=0\" "
6766		    "to /boot/loader.conf.\n");
6767		zfs_prefetch_disable = 1;
6768	}
6769#else
6770	if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
6771	    prefetch_tunable_set == 0) {
6772		printf("ZFS NOTICE: Prefetch is disabled by default if less "
6773		    "than 4GB of RAM is present;\n"
6774		    "            to enable, add \"vfs.zfs.prefetch_disable=0\" "
6775		    "to /boot/loader.conf.\n");
6776		zfs_prefetch_disable = 1;
6777	}
6778#endif
6779	/* Warn about ZFS memory and address space requirements. */
6780	if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
6781		printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
6782		    "expect unstable behavior.\n");
6783	}
6784	if (allmem < 512 * (1 << 20)) {
6785		printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
6786		    "expect unstable behavior.\n");
6787		printf("             Consider tuning vm.kmem_size and "
6788		    "vm.kmem_size_max\n");
6789		printf("             in /boot/loader.conf.\n");
6790	}
6791#endif
6792}
6793
6794void
6795arc_fini(void)
6796{
6797#ifdef _KERNEL
6798	if (arc_event_lowmem != NULL)
6799		EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
6800#endif
6801
6802	mutex_enter(&arc_reclaim_lock);
6803	arc_reclaim_thread_exit = B_TRUE;
6804	/*
6805	 * The reclaim thread will set arc_reclaim_thread_exit back to
6806	 * B_FALSE when it is finished exiting; we're waiting for that.
6807	 */
6808	while (arc_reclaim_thread_exit) {
6809		cv_signal(&arc_reclaim_thread_cv);
6810		cv_wait(&arc_reclaim_thread_cv, &arc_reclaim_lock);
6811	}
6812	mutex_exit(&arc_reclaim_lock);
6813
6814	/* Use B_TRUE to ensure *all* buffers are evicted */
6815	arc_flush(NULL, B_TRUE);
6816
6817	mutex_enter(&arc_dnlc_evicts_lock);
6818	arc_dnlc_evicts_thread_exit = TRUE;
6819	/*
6820	 * The user evicts thread will set arc_user_evicts_thread_exit
6821	 * to FALSE when it is finished exiting; we're waiting for that.
6822	 */
6823	while (arc_dnlc_evicts_thread_exit) {
6824		cv_signal(&arc_dnlc_evicts_cv);
6825		cv_wait(&arc_dnlc_evicts_cv, &arc_dnlc_evicts_lock);
6826	}
6827	mutex_exit(&arc_dnlc_evicts_lock);
6828
6829	arc_dead = B_TRUE;
6830
6831	if (arc_ksp != NULL) {
6832		kstat_delete(arc_ksp);
6833		arc_ksp = NULL;
6834	}
6835
6836	mutex_destroy(&arc_reclaim_lock);
6837	cv_destroy(&arc_reclaim_thread_cv);
6838	cv_destroy(&arc_reclaim_waiters_cv);
6839
6840	mutex_destroy(&arc_dnlc_evicts_lock);
6841	cv_destroy(&arc_dnlc_evicts_cv);
6842
6843	arc_state_fini();
6844	buf_fini();
6845
6846	ASSERT0(arc_loaned_bytes);
6847}
6848
6849/*
6850 * Level 2 ARC
6851 *
6852 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
6853 * It uses dedicated storage devices to hold cached data, which are populated
6854 * using large infrequent writes.  The main role of this cache is to boost
6855 * the performance of random read workloads.  The intended L2ARC devices
6856 * include short-stroked disks, solid state disks, and other media with
6857 * substantially faster read latency than disk.
6858 *
6859 *                 +-----------------------+
6860 *                 |         ARC           |
6861 *                 +-----------------------+
6862 *                    |         ^     ^
6863 *                    |         |     |
6864 *      l2arc_feed_thread()    arc_read()
6865 *                    |         |     |
6866 *                    |  l2arc read   |
6867 *                    V         |     |
6868 *               +---------------+    |
6869 *               |     L2ARC     |    |
6870 *               +---------------+    |
6871 *                   |    ^           |
6872 *          l2arc_write() |           |
6873 *                   |    |           |
6874 *                   V    |           |
6875 *                 +-------+      +-------+
6876 *                 | vdev  |      | vdev  |
6877 *                 | cache |      | cache |
6878 *                 +-------+      +-------+
6879 *                 +=========+     .-----.
6880 *                 :  L2ARC  :    |-_____-|
6881 *                 : devices :    | Disks |
6882 *                 +=========+    `-_____-'
6883 *
6884 * Read requests are satisfied from the following sources, in order:
6885 *
6886 *	1) ARC
6887 *	2) vdev cache of L2ARC devices
6888 *	3) L2ARC devices
6889 *	4) vdev cache of disks
6890 *	5) disks
6891 *
6892 * Some L2ARC device types exhibit extremely slow write performance.
6893 * To accommodate for this there are some significant differences between
6894 * the L2ARC and traditional cache design:
6895 *
6896 * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
6897 * the ARC behave as usual, freeing buffers and placing headers on ghost
6898 * lists.  The ARC does not send buffers to the L2ARC during eviction as
6899 * this would add inflated write latencies for all ARC memory pressure.
6900 *
6901 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
6902 * It does this by periodically scanning buffers from the eviction-end of
6903 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
6904 * not already there. It scans until a headroom of buffers is satisfied,
6905 * which itself is a buffer for ARC eviction. If a compressible buffer is
6906 * found during scanning and selected for writing to an L2ARC device, we
6907 * temporarily boost scanning headroom during the next scan cycle to make
6908 * sure we adapt to compression effects (which might significantly reduce
6909 * the data volume we write to L2ARC). The thread that does this is
6910 * l2arc_feed_thread(), illustrated below; example sizes are included to
6911 * provide a better sense of ratio than this diagram:
6912 *
6913 *	       head -->                        tail
6914 *	        +---------------------+----------+
6915 *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
6916 *	        +---------------------+----------+   |   o L2ARC eligible
6917 *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
6918 *	        +---------------------+----------+   |
6919 *	             15.9 Gbytes      ^ 32 Mbytes    |
6920 *	                           headroom          |
6921 *	                                      l2arc_feed_thread()
6922 *	                                             |
6923 *	                 l2arc write hand <--[oooo]--'
6924 *	                         |           8 Mbyte
6925 *	                         |          write max
6926 *	                         V
6927 *		  +==============================+
6928 *	L2ARC dev |####|#|###|###|    |####| ... |
6929 *	          +==============================+
6930 *	                     32 Gbytes
6931 *
6932 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
6933 * evicted, then the L2ARC has cached a buffer much sooner than it probably
6934 * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
6935 * safe to say that this is an uncommon case, since buffers at the end of
6936 * the ARC lists have moved there due to inactivity.
6937 *
6938 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
6939 * then the L2ARC simply misses copying some buffers.  This serves as a
6940 * pressure valve to prevent heavy read workloads from both stalling the ARC
6941 * with waits and clogging the L2ARC with writes.  This also helps prevent
6942 * the potential for the L2ARC to churn if it attempts to cache content too
6943 * quickly, such as during backups of the entire pool.
6944 *
6945 * 5. After system boot and before the ARC has filled main memory, there are
6946 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
6947 * lists can remain mostly static.  Instead of searching from tail of these
6948 * lists as pictured, the l2arc_feed_thread() will search from the list heads
6949 * for eligible buffers, greatly increasing its chance of finding them.
6950 *
6951 * The L2ARC device write speed is also boosted during this time so that
6952 * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
6953 * there are no L2ARC reads, and no fear of degrading read performance
6954 * through increased writes.
6955 *
6956 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
6957 * the vdev queue can aggregate them into larger and fewer writes.  Each
6958 * device is written to in a rotor fashion, sweeping writes through
6959 * available space then repeating.
6960 *
6961 * 7. The L2ARC does not store dirty content.  It never needs to flush
6962 * write buffers back to disk based storage.
6963 *
6964 * 8. If an ARC buffer is written (and dirtied) which also exists in the
6965 * L2ARC, the now stale L2ARC buffer is immediately dropped.
6966 *
6967 * The performance of the L2ARC can be tweaked by a number of tunables, which
6968 * may be necessary for different workloads:
6969 *
6970 *	l2arc_write_max		max write bytes per interval
6971 *	l2arc_write_boost	extra write bytes during device warmup
6972 *	l2arc_noprefetch	skip caching prefetched buffers
6973 *	l2arc_headroom		number of max device writes to precache
6974 *	l2arc_headroom_boost	when we find compressed buffers during ARC
6975 *				scanning, we multiply headroom by this
6976 *				percentage factor for the next scan cycle,
6977 *				since more compressed buffers are likely to
6978 *				be present
6979 *	l2arc_feed_secs		seconds between L2ARC writing
6980 *
6981 * Tunables may be removed or added as future performance improvements are
6982 * integrated, and also may become zpool properties.
6983 *
6984 * There are three key functions that control how the L2ARC warms up:
6985 *
6986 *	l2arc_write_eligible()	check if a buffer is eligible to cache
6987 *	l2arc_write_size()	calculate how much to write
6988 *	l2arc_write_interval()	calculate sleep delay between writes
6989 *
6990 * These three functions determine what to write, how much, and how quickly
6991 * to send writes.
6992 */
6993
6994static boolean_t
6995l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
6996{
6997	/*
6998	 * A buffer is *not* eligible for the L2ARC if it:
6999	 * 1. belongs to a different spa.
7000	 * 2. is already cached on the L2ARC.
7001	 * 3. has an I/O in progress (it may be an incomplete read).
7002	 * 4. is flagged not eligible (zfs property).
7003	 */
7004	if (hdr->b_spa != spa_guid) {
7005		ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
7006		return (B_FALSE);
7007	}
7008	if (HDR_HAS_L2HDR(hdr)) {
7009		ARCSTAT_BUMP(arcstat_l2_write_in_l2);
7010		return (B_FALSE);
7011	}
7012	if (HDR_IO_IN_PROGRESS(hdr)) {
7013		ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
7014		return (B_FALSE);
7015	}
7016	if (!HDR_L2CACHE(hdr)) {
7017		ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
7018		return (B_FALSE);
7019	}
7020
7021	return (B_TRUE);
7022}
7023
7024static uint64_t
7025l2arc_write_size(void)
7026{
7027	uint64_t size;
7028
7029	/*
7030	 * Make sure our globals have meaningful values in case the user
7031	 * altered them.
7032	 */
7033	size = l2arc_write_max;
7034	if (size == 0) {
7035		cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
7036		    "be greater than zero, resetting it to the default (%d)",
7037		    L2ARC_WRITE_SIZE);
7038		size = l2arc_write_max = L2ARC_WRITE_SIZE;
7039	}
7040
7041	if (arc_warm == B_FALSE)
7042		size += l2arc_write_boost;
7043
7044	return (size);
7045
7046}
7047
7048static clock_t
7049l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
7050{
7051	clock_t interval, next, now;
7052
7053	/*
7054	 * If the ARC lists are busy, increase our write rate; if the
7055	 * lists are stale, idle back.  This is achieved by checking
7056	 * how much we previously wrote - if it was more than half of
7057	 * what we wanted, schedule the next write much sooner.
7058	 */
7059	if (l2arc_feed_again && wrote > (wanted / 2))
7060		interval = (hz * l2arc_feed_min_ms) / 1000;
7061	else
7062		interval = hz * l2arc_feed_secs;
7063
7064	now = ddi_get_lbolt();
7065	next = MAX(now, MIN(now + interval, began + interval));
7066
7067	return (next);
7068}
7069
7070/*
7071 * Cycle through L2ARC devices.  This is how L2ARC load balances.
7072 * If a device is returned, this also returns holding the spa config lock.
7073 */
7074static l2arc_dev_t *
7075l2arc_dev_get_next(void)
7076{
7077	l2arc_dev_t *first, *next = NULL;
7078
7079	/*
7080	 * Lock out the removal of spas (spa_namespace_lock), then removal
7081	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
7082	 * both locks will be dropped and a spa config lock held instead.
7083	 */
7084	mutex_enter(&spa_namespace_lock);
7085	mutex_enter(&l2arc_dev_mtx);
7086
7087	/* if there are no vdevs, there is nothing to do */
7088	if (l2arc_ndev == 0)
7089		goto out;
7090
7091	first = NULL;
7092	next = l2arc_dev_last;
7093	do {
7094		/* loop around the list looking for a non-faulted vdev */
7095		if (next == NULL) {
7096			next = list_head(l2arc_dev_list);
7097		} else {
7098			next = list_next(l2arc_dev_list, next);
7099			if (next == NULL)
7100				next = list_head(l2arc_dev_list);
7101		}
7102
7103		/* if we have come back to the start, bail out */
7104		if (first == NULL)
7105			first = next;
7106		else if (next == first)
7107			break;
7108
7109	} while (vdev_is_dead(next->l2ad_vdev));
7110
7111	/* if we were unable to find any usable vdevs, return NULL */
7112	if (vdev_is_dead(next->l2ad_vdev))
7113		next = NULL;
7114
7115	l2arc_dev_last = next;
7116
7117out:
7118	mutex_exit(&l2arc_dev_mtx);
7119
7120	/*
7121	 * Grab the config lock to prevent the 'next' device from being
7122	 * removed while we are writing to it.
7123	 */
7124	if (next != NULL)
7125		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
7126	mutex_exit(&spa_namespace_lock);
7127
7128	return (next);
7129}
7130
7131/*
7132 * Free buffers that were tagged for destruction.
7133 */
7134static void
7135l2arc_do_free_on_write()
7136{
7137	list_t *buflist;
7138	l2arc_data_free_t *df, *df_prev;
7139
7140	mutex_enter(&l2arc_free_on_write_mtx);
7141	buflist = l2arc_free_on_write;
7142
7143	for (df = list_tail(buflist); df; df = df_prev) {
7144		df_prev = list_prev(buflist, df);
7145		ASSERT3P(df->l2df_abd, !=, NULL);
7146		abd_free(df->l2df_abd);
7147		list_remove(buflist, df);
7148		kmem_free(df, sizeof (l2arc_data_free_t));
7149	}
7150
7151	mutex_exit(&l2arc_free_on_write_mtx);
7152}
7153
7154/*
7155 * A write to a cache device has completed.  Update all headers to allow
7156 * reads from these buffers to begin.
7157 */
7158static void
7159l2arc_write_done(zio_t *zio)
7160{
7161	l2arc_write_callback_t *cb;
7162	l2arc_dev_t *dev;
7163	list_t *buflist;
7164	arc_buf_hdr_t *head, *hdr, *hdr_prev;
7165	kmutex_t *hash_lock;
7166	int64_t bytes_dropped = 0;
7167
7168	cb = zio->io_private;
7169	ASSERT3P(cb, !=, NULL);
7170	dev = cb->l2wcb_dev;
7171	ASSERT3P(dev, !=, NULL);
7172	head = cb->l2wcb_head;
7173	ASSERT3P(head, !=, NULL);
7174	buflist = &dev->l2ad_buflist;
7175	ASSERT3P(buflist, !=, NULL);
7176	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
7177	    l2arc_write_callback_t *, cb);
7178
7179	if (zio->io_error != 0)
7180		ARCSTAT_BUMP(arcstat_l2_writes_error);
7181
7182	/*
7183	 * All writes completed, or an error was hit.
7184	 */
7185top:
7186	mutex_enter(&dev->l2ad_mtx);
7187	for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
7188		hdr_prev = list_prev(buflist, hdr);
7189
7190		hash_lock = HDR_LOCK(hdr);
7191
7192		/*
7193		 * We cannot use mutex_enter or else we can deadlock
7194		 * with l2arc_write_buffers (due to swapping the order
7195		 * the hash lock and l2ad_mtx are taken).
7196		 */
7197		if (!mutex_tryenter(hash_lock)) {
7198			/*
7199			 * Missed the hash lock. We must retry so we
7200			 * don't leave the ARC_FLAG_L2_WRITING bit set.
7201			 */
7202			ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
7203
7204			/*
7205			 * We don't want to rescan the headers we've
7206			 * already marked as having been written out, so
7207			 * we reinsert the head node so we can pick up
7208			 * where we left off.
7209			 */
7210			list_remove(buflist, head);
7211			list_insert_after(buflist, hdr, head);
7212
7213			mutex_exit(&dev->l2ad_mtx);
7214
7215			/*
7216			 * We wait for the hash lock to become available
7217			 * to try and prevent busy waiting, and increase
7218			 * the chance we'll be able to acquire the lock
7219			 * the next time around.
7220			 */
7221			mutex_enter(hash_lock);
7222			mutex_exit(hash_lock);
7223			goto top;
7224		}
7225
7226		/*
7227		 * We could not have been moved into the arc_l2c_only
7228		 * state while in-flight due to our ARC_FLAG_L2_WRITING
7229		 * bit being set. Let's just ensure that's being enforced.
7230		 */
7231		ASSERT(HDR_HAS_L1HDR(hdr));
7232
7233		if (zio->io_error != 0) {
7234			/*
7235			 * Error - drop L2ARC entry.
7236			 */
7237			list_remove(buflist, hdr);
7238			l2arc_trim(hdr);
7239			arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
7240
7241			ARCSTAT_INCR(arcstat_l2_psize, -arc_hdr_size(hdr));
7242			ARCSTAT_INCR(arcstat_l2_lsize, -HDR_GET_LSIZE(hdr));
7243
7244			bytes_dropped += arc_hdr_size(hdr);
7245			(void) refcount_remove_many(&dev->l2ad_alloc,
7246			    arc_hdr_size(hdr), hdr);
7247		}
7248
7249		/*
7250		 * Allow ARC to begin reads and ghost list evictions to
7251		 * this L2ARC entry.
7252		 */
7253		arc_hdr_clear_flags(hdr, ARC_FLAG_L2_WRITING);
7254
7255		mutex_exit(hash_lock);
7256	}
7257
7258	atomic_inc_64(&l2arc_writes_done);
7259	list_remove(buflist, head);
7260	ASSERT(!HDR_HAS_L1HDR(head));
7261	kmem_cache_free(hdr_l2only_cache, head);
7262	mutex_exit(&dev->l2ad_mtx);
7263
7264	vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
7265
7266	l2arc_do_free_on_write();
7267
7268	kmem_free(cb, sizeof (l2arc_write_callback_t));
7269}
7270
7271/*
7272 * A read to a cache device completed.  Validate buffer contents before
7273 * handing over to the regular ARC routines.
7274 */
7275static void
7276l2arc_read_done(zio_t *zio)
7277{
7278	l2arc_read_callback_t *cb;
7279	arc_buf_hdr_t *hdr;
7280	kmutex_t *hash_lock;
7281	boolean_t valid_cksum;
7282
7283	ASSERT3P(zio->io_vd, !=, NULL);
7284	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
7285
7286	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
7287
7288	cb = zio->io_private;
7289	ASSERT3P(cb, !=, NULL);
7290	hdr = cb->l2rcb_hdr;
7291	ASSERT3P(hdr, !=, NULL);
7292
7293	hash_lock = HDR_LOCK(hdr);
7294	mutex_enter(hash_lock);
7295	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
7296
7297	/*
7298	 * If the data was read into a temporary buffer,
7299	 * move it and free the buffer.
7300	 */
7301	if (cb->l2rcb_abd != NULL) {
7302		ASSERT3U(arc_hdr_size(hdr), <, zio->io_size);
7303		if (zio->io_error == 0) {
7304			abd_copy(hdr->b_l1hdr.b_pabd, cb->l2rcb_abd,
7305			    arc_hdr_size(hdr));
7306		}
7307
7308		/*
7309		 * The following must be done regardless of whether
7310		 * there was an error:
7311		 * - free the temporary buffer
7312		 * - point zio to the real ARC buffer
7313		 * - set zio size accordingly
7314		 * These are required because zio is either re-used for
7315		 * an I/O of the block in the case of the error
7316		 * or the zio is passed to arc_read_done() and it
7317		 * needs real data.
7318		 */
7319		abd_free(cb->l2rcb_abd);
7320		zio->io_size = zio->io_orig_size = arc_hdr_size(hdr);
7321		zio->io_abd = zio->io_orig_abd = hdr->b_l1hdr.b_pabd;
7322	}
7323
7324	ASSERT3P(zio->io_abd, !=, NULL);
7325
7326	/*
7327	 * Check this survived the L2ARC journey.
7328	 */
7329	ASSERT3P(zio->io_abd, ==, hdr->b_l1hdr.b_pabd);
7330	zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
7331	zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
7332
7333	valid_cksum = arc_cksum_is_equal(hdr, zio);
7334	if (valid_cksum && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
7335		mutex_exit(hash_lock);
7336		zio->io_private = hdr;
7337		arc_read_done(zio);
7338	} else {
7339		mutex_exit(hash_lock);
7340		/*
7341		 * Buffer didn't survive caching.  Increment stats and
7342		 * reissue to the original storage device.
7343		 */
7344		if (zio->io_error != 0) {
7345			ARCSTAT_BUMP(arcstat_l2_io_error);
7346		} else {
7347			zio->io_error = SET_ERROR(EIO);
7348		}
7349		if (!valid_cksum)
7350			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
7351
7352		/*
7353		 * If there's no waiter, issue an async i/o to the primary
7354		 * storage now.  If there *is* a waiter, the caller must
7355		 * issue the i/o in a context where it's OK to block.
7356		 */
7357		if (zio->io_waiter == NULL) {
7358			zio_t *pio = zio_unique_parent(zio);
7359
7360			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
7361
7362			zio_nowait(zio_read(pio, zio->io_spa, zio->io_bp,
7363			    hdr->b_l1hdr.b_pabd, zio->io_size, arc_read_done,
7364			    hdr, zio->io_priority, cb->l2rcb_flags,
7365			    &cb->l2rcb_zb));
7366		}
7367	}
7368
7369	kmem_free(cb, sizeof (l2arc_read_callback_t));
7370}
7371
7372/*
7373 * This is the list priority from which the L2ARC will search for pages to
7374 * cache.  This is used within loops (0..3) to cycle through lists in the
7375 * desired order.  This order can have a significant effect on cache
7376 * performance.
7377 *
7378 * Currently the metadata lists are hit first, MFU then MRU, followed by
7379 * the data lists.  This function returns a locked list, and also returns
7380 * the lock pointer.
7381 */
7382static multilist_sublist_t *
7383l2arc_sublist_lock(int list_num)
7384{
7385	multilist_t *ml = NULL;
7386	unsigned int idx;
7387
7388	ASSERT(list_num >= 0 && list_num <= 3);
7389
7390	switch (list_num) {
7391	case 0:
7392		ml = arc_mfu->arcs_list[ARC_BUFC_METADATA];
7393		break;
7394	case 1:
7395		ml = arc_mru->arcs_list[ARC_BUFC_METADATA];
7396		break;
7397	case 2:
7398		ml = arc_mfu->arcs_list[ARC_BUFC_DATA];
7399		break;
7400	case 3:
7401		ml = arc_mru->arcs_list[ARC_BUFC_DATA];
7402		break;
7403	}
7404
7405	/*
7406	 * Return a randomly-selected sublist. This is acceptable
7407	 * because the caller feeds only a little bit of data for each
7408	 * call (8MB). Subsequent calls will result in different
7409	 * sublists being selected.
7410	 */
7411	idx = multilist_get_random_index(ml);
7412	return (multilist_sublist_lock(ml, idx));
7413}
7414
7415/*
7416 * Evict buffers from the device write hand to the distance specified in
7417 * bytes.  This distance may span populated buffers, it may span nothing.
7418 * This is clearing a region on the L2ARC device ready for writing.
7419 * If the 'all' boolean is set, every buffer is evicted.
7420 */
7421static void
7422l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
7423{
7424	list_t *buflist;
7425	arc_buf_hdr_t *hdr, *hdr_prev;
7426	kmutex_t *hash_lock;
7427	uint64_t taddr;
7428
7429	buflist = &dev->l2ad_buflist;
7430
7431	if (!all && dev->l2ad_first) {
7432		/*
7433		 * This is the first sweep through the device.  There is
7434		 * nothing to evict.
7435		 */
7436		return;
7437	}
7438
7439	if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
7440		/*
7441		 * When nearing the end of the device, evict to the end
7442		 * before the device write hand jumps to the start.
7443		 */
7444		taddr = dev->l2ad_end;
7445	} else {
7446		taddr = dev->l2ad_hand + distance;
7447	}
7448	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
7449	    uint64_t, taddr, boolean_t, all);
7450
7451top:
7452	mutex_enter(&dev->l2ad_mtx);
7453	for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
7454		hdr_prev = list_prev(buflist, hdr);
7455
7456		hash_lock = HDR_LOCK(hdr);
7457
7458		/*
7459		 * We cannot use mutex_enter or else we can deadlock
7460		 * with l2arc_write_buffers (due to swapping the order
7461		 * the hash lock and l2ad_mtx are taken).
7462		 */
7463		if (!mutex_tryenter(hash_lock)) {
7464			/*
7465			 * Missed the hash lock.  Retry.
7466			 */
7467			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
7468			mutex_exit(&dev->l2ad_mtx);
7469			mutex_enter(hash_lock);
7470			mutex_exit(hash_lock);
7471			goto top;
7472		}
7473
7474		/*
7475		 * A header can't be on this list if it doesn't have L2 header.
7476		 */
7477		ASSERT(HDR_HAS_L2HDR(hdr));
7478
7479		/* Ensure this header has finished being written. */
7480		ASSERT(!HDR_L2_WRITING(hdr));
7481		ASSERT(!HDR_L2_WRITE_HEAD(hdr));
7482
7483		if (!all && (hdr->b_l2hdr.b_daddr >= taddr ||
7484		    hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
7485			/*
7486			 * We've evicted to the target address,
7487			 * or the end of the device.
7488			 */
7489			mutex_exit(hash_lock);
7490			break;
7491		}
7492
7493		if (!HDR_HAS_L1HDR(hdr)) {
7494			ASSERT(!HDR_L2_READING(hdr));
7495			/*
7496			 * This doesn't exist in the ARC.  Destroy.
7497			 * arc_hdr_destroy() will call list_remove()
7498			 * and decrement arcstat_l2_lsize.
7499			 */
7500			arc_change_state(arc_anon, hdr, hash_lock);
7501			arc_hdr_destroy(hdr);
7502		} else {
7503			ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
7504			ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
7505			/*
7506			 * Invalidate issued or about to be issued
7507			 * reads, since we may be about to write
7508			 * over this location.
7509			 */
7510			if (HDR_L2_READING(hdr)) {
7511				ARCSTAT_BUMP(arcstat_l2_evict_reading);
7512				arc_hdr_set_flags(hdr, ARC_FLAG_L2_EVICTED);
7513			}
7514
7515			arc_hdr_l2hdr_destroy(hdr);
7516		}
7517		mutex_exit(hash_lock);
7518	}
7519	mutex_exit(&dev->l2ad_mtx);
7520}
7521
7522/*
7523 * Find and write ARC buffers to the L2ARC device.
7524 *
7525 * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
7526 * for reading until they have completed writing.
7527 * The headroom_boost is an in-out parameter used to maintain headroom boost
7528 * state between calls to this function.
7529 *
7530 * Returns the number of bytes actually written (which may be smaller than
7531 * the delta by which the device hand has changed due to alignment).
7532 */
7533static uint64_t
7534l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
7535{
7536	arc_buf_hdr_t *hdr, *hdr_prev, *head;
7537	uint64_t write_asize, write_psize, write_lsize, headroom;
7538	boolean_t full;
7539	l2arc_write_callback_t *cb;
7540	zio_t *pio, *wzio;
7541	uint64_t guid = spa_load_guid(spa);
7542	int try;
7543
7544	ASSERT3P(dev->l2ad_vdev, !=, NULL);
7545
7546	pio = NULL;
7547	write_lsize = write_asize = write_psize = 0;
7548	full = B_FALSE;
7549	head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
7550	arc_hdr_set_flags(head, ARC_FLAG_L2_WRITE_HEAD | ARC_FLAG_HAS_L2HDR);
7551
7552	ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
7553	/*
7554	 * Copy buffers for L2ARC writing.
7555	 */
7556	for (try = 0; try <= 3; try++) {
7557		multilist_sublist_t *mls = l2arc_sublist_lock(try);
7558		uint64_t passed_sz = 0;
7559
7560		ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
7561
7562		/*
7563		 * L2ARC fast warmup.
7564		 *
7565		 * Until the ARC is warm and starts to evict, read from the
7566		 * head of the ARC lists rather than the tail.
7567		 */
7568		if (arc_warm == B_FALSE)
7569			hdr = multilist_sublist_head(mls);
7570		else
7571			hdr = multilist_sublist_tail(mls);
7572		if (hdr == NULL)
7573			ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
7574
7575		headroom = target_sz * l2arc_headroom;
7576		if (zfs_compressed_arc_enabled)
7577			headroom = (headroom * l2arc_headroom_boost) / 100;
7578
7579		for (; hdr; hdr = hdr_prev) {
7580			kmutex_t *hash_lock;
7581
7582			if (arc_warm == B_FALSE)
7583				hdr_prev = multilist_sublist_next(mls, hdr);
7584			else
7585				hdr_prev = multilist_sublist_prev(mls, hdr);
7586			ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned,
7587			    HDR_GET_LSIZE(hdr));
7588
7589			hash_lock = HDR_LOCK(hdr);
7590			if (!mutex_tryenter(hash_lock)) {
7591				ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
7592				/*
7593				 * Skip this buffer rather than waiting.
7594				 */
7595				continue;
7596			}
7597
7598			passed_sz += HDR_GET_LSIZE(hdr);
7599			if (passed_sz > headroom) {
7600				/*
7601				 * Searched too far.
7602				 */
7603				mutex_exit(hash_lock);
7604				ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
7605				break;
7606			}
7607
7608			if (!l2arc_write_eligible(guid, hdr)) {
7609				mutex_exit(hash_lock);
7610				continue;
7611			}
7612
7613			/*
7614			 * We rely on the L1 portion of the header below, so
7615			 * it's invalid for this header to have been evicted out
7616			 * of the ghost cache, prior to being written out. The
7617			 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
7618			 */
7619			ASSERT(HDR_HAS_L1HDR(hdr));
7620
7621			ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
7622			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
7623			ASSERT3U(arc_hdr_size(hdr), >, 0);
7624			uint64_t psize = arc_hdr_size(hdr);
7625			uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev,
7626			    psize);
7627
7628			if ((write_asize + asize) > target_sz) {
7629				full = B_TRUE;
7630				mutex_exit(hash_lock);
7631				ARCSTAT_BUMP(arcstat_l2_write_full);
7632				break;
7633			}
7634
7635			if (pio == NULL) {
7636				/*
7637				 * Insert a dummy header on the buflist so
7638				 * l2arc_write_done() can find where the
7639				 * write buffers begin without searching.
7640				 */
7641				mutex_enter(&dev->l2ad_mtx);
7642				list_insert_head(&dev->l2ad_buflist, head);
7643				mutex_exit(&dev->l2ad_mtx);
7644
7645				cb = kmem_alloc(
7646				    sizeof (l2arc_write_callback_t), KM_SLEEP);
7647				cb->l2wcb_dev = dev;
7648				cb->l2wcb_head = head;
7649				pio = zio_root(spa, l2arc_write_done, cb,
7650				    ZIO_FLAG_CANFAIL);
7651				ARCSTAT_BUMP(arcstat_l2_write_pios);
7652			}
7653
7654			hdr->b_l2hdr.b_dev = dev;
7655			hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
7656			arc_hdr_set_flags(hdr,
7657			    ARC_FLAG_L2_WRITING | ARC_FLAG_HAS_L2HDR);
7658
7659			mutex_enter(&dev->l2ad_mtx);
7660			list_insert_head(&dev->l2ad_buflist, hdr);
7661			mutex_exit(&dev->l2ad_mtx);
7662
7663			(void) refcount_add_many(&dev->l2ad_alloc, psize, hdr);
7664
7665			/*
7666			 * Normally the L2ARC can use the hdr's data, but if
7667			 * we're sharing data between the hdr and one of its
7668			 * bufs, L2ARC needs its own copy of the data so that
7669			 * the ZIO below can't race with the buf consumer.
7670			 * Another case where we need to create a copy of the
7671			 * data is when the buffer size is not device-aligned
7672			 * and we need to pad the block to make it such.
7673			 * That also keeps the clock hand suitably aligned.
7674			 *
7675			 * To ensure that the copy will be available for the
7676			 * lifetime of the ZIO and be cleaned up afterwards, we
7677			 * add it to the l2arc_free_on_write queue.
7678			 */
7679			abd_t *to_write;
7680			if (!HDR_SHARED_DATA(hdr) && psize == asize) {
7681				to_write = hdr->b_l1hdr.b_pabd;
7682			} else {
7683				to_write = abd_alloc_for_io(asize,
7684				    HDR_ISTYPE_METADATA(hdr));
7685				abd_copy(to_write, hdr->b_l1hdr.b_pabd, psize);
7686				if (asize != psize) {
7687					abd_zero_off(to_write, psize,
7688					    asize - psize);
7689				}
7690				l2arc_free_abd_on_write(to_write, asize,
7691				    arc_buf_type(hdr));
7692			}
7693			wzio = zio_write_phys(pio, dev->l2ad_vdev,
7694			    hdr->b_l2hdr.b_daddr, asize, to_write,
7695			    ZIO_CHECKSUM_OFF, NULL, hdr,
7696			    ZIO_PRIORITY_ASYNC_WRITE,
7697			    ZIO_FLAG_CANFAIL, B_FALSE);
7698
7699			write_lsize += HDR_GET_LSIZE(hdr);
7700			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
7701			    zio_t *, wzio);
7702
7703			write_psize += psize;
7704			write_asize += asize;
7705			dev->l2ad_hand += asize;
7706
7707			mutex_exit(hash_lock);
7708
7709			(void) zio_nowait(wzio);
7710		}
7711
7712		multilist_sublist_unlock(mls);
7713
7714		if (full == B_TRUE)
7715			break;
7716	}
7717
7718	/* No buffers selected for writing? */
7719	if (pio == NULL) {
7720		ASSERT0(write_lsize);
7721		ASSERT(!HDR_HAS_L1HDR(head));
7722		kmem_cache_free(hdr_l2only_cache, head);
7723		return (0);
7724	}
7725
7726	ASSERT3U(write_psize, <=, target_sz);
7727	ARCSTAT_BUMP(arcstat_l2_writes_sent);
7728	ARCSTAT_INCR(arcstat_l2_write_bytes, write_psize);
7729	ARCSTAT_INCR(arcstat_l2_lsize, write_lsize);
7730	ARCSTAT_INCR(arcstat_l2_psize, write_psize);
7731	vdev_space_update(dev->l2ad_vdev, write_psize, 0, 0);
7732
7733	/*
7734	 * Bump device hand to the device start if it is approaching the end.
7735	 * l2arc_evict() will already have evicted ahead for this case.
7736	 */
7737	if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
7738		dev->l2ad_hand = dev->l2ad_start;
7739		dev->l2ad_first = B_FALSE;
7740	}
7741
7742	dev->l2ad_writing = B_TRUE;
7743	(void) zio_wait(pio);
7744	dev->l2ad_writing = B_FALSE;
7745
7746	return (write_asize);
7747}
7748
7749/*
7750 * This thread feeds the L2ARC at regular intervals.  This is the beating
7751 * heart of the L2ARC.
7752 */
7753/* ARGSUSED */
7754static void
7755l2arc_feed_thread(void *unused __unused)
7756{
7757	callb_cpr_t cpr;
7758	l2arc_dev_t *dev;
7759	spa_t *spa;
7760	uint64_t size, wrote;
7761	clock_t begin, next = ddi_get_lbolt();
7762
7763	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
7764
7765	mutex_enter(&l2arc_feed_thr_lock);
7766
7767	while (l2arc_thread_exit == 0) {
7768		CALLB_CPR_SAFE_BEGIN(&cpr);
7769		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
7770		    next - ddi_get_lbolt());
7771		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
7772		next = ddi_get_lbolt() + hz;
7773
7774		/*
7775		 * Quick check for L2ARC devices.
7776		 */
7777		mutex_enter(&l2arc_dev_mtx);
7778		if (l2arc_ndev == 0) {
7779			mutex_exit(&l2arc_dev_mtx);
7780			continue;
7781		}
7782		mutex_exit(&l2arc_dev_mtx);
7783		begin = ddi_get_lbolt();
7784
7785		/*
7786		 * This selects the next l2arc device to write to, and in
7787		 * doing so the next spa to feed from: dev->l2ad_spa.   This
7788		 * will return NULL if there are now no l2arc devices or if
7789		 * they are all faulted.
7790		 *
7791		 * If a device is returned, its spa's config lock is also
7792		 * held to prevent device removal.  l2arc_dev_get_next()
7793		 * will grab and release l2arc_dev_mtx.
7794		 */
7795		if ((dev = l2arc_dev_get_next()) == NULL)
7796			continue;
7797
7798		spa = dev->l2ad_spa;
7799		ASSERT3P(spa, !=, NULL);
7800
7801		/*
7802		 * If the pool is read-only then force the feed thread to
7803		 * sleep a little longer.
7804		 */
7805		if (!spa_writeable(spa)) {
7806			next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
7807			spa_config_exit(spa, SCL_L2ARC, dev);
7808			continue;
7809		}
7810
7811		/*
7812		 * Avoid contributing to memory pressure.
7813		 */
7814		if (arc_reclaim_needed()) {
7815			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
7816			spa_config_exit(spa, SCL_L2ARC, dev);
7817			continue;
7818		}
7819
7820		ARCSTAT_BUMP(arcstat_l2_feeds);
7821
7822		size = l2arc_write_size();
7823
7824		/*
7825		 * Evict L2ARC buffers that will be overwritten.
7826		 */
7827		l2arc_evict(dev, size, B_FALSE);
7828
7829		/*
7830		 * Write ARC buffers.
7831		 */
7832		wrote = l2arc_write_buffers(spa, dev, size);
7833
7834		/*
7835		 * Calculate interval between writes.
7836		 */
7837		next = l2arc_write_interval(begin, size, wrote);
7838		spa_config_exit(spa, SCL_L2ARC, dev);
7839	}
7840
7841	l2arc_thread_exit = 0;
7842	cv_broadcast(&l2arc_feed_thr_cv);
7843	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
7844	thread_exit();
7845}
7846
7847boolean_t
7848l2arc_vdev_present(vdev_t *vd)
7849{
7850	l2arc_dev_t *dev;
7851
7852	mutex_enter(&l2arc_dev_mtx);
7853	for (dev = list_head(l2arc_dev_list); dev != NULL;
7854	    dev = list_next(l2arc_dev_list, dev)) {
7855		if (dev->l2ad_vdev == vd)
7856			break;
7857	}
7858	mutex_exit(&l2arc_dev_mtx);
7859
7860	return (dev != NULL);
7861}
7862
7863/*
7864 * Add a vdev for use by the L2ARC.  By this point the spa has already
7865 * validated the vdev and opened it.
7866 */
7867void
7868l2arc_add_vdev(spa_t *spa, vdev_t *vd)
7869{
7870	l2arc_dev_t *adddev;
7871
7872	ASSERT(!l2arc_vdev_present(vd));
7873
7874	vdev_ashift_optimize(vd);
7875
7876	/*
7877	 * Create a new l2arc device entry.
7878	 */
7879	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
7880	adddev->l2ad_spa = spa;
7881	adddev->l2ad_vdev = vd;
7882	adddev->l2ad_start = VDEV_LABEL_START_SIZE;
7883	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
7884	adddev->l2ad_hand = adddev->l2ad_start;
7885	adddev->l2ad_first = B_TRUE;
7886	adddev->l2ad_writing = B_FALSE;
7887
7888	mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
7889	/*
7890	 * This is a list of all ARC buffers that are still valid on the
7891	 * device.
7892	 */
7893	list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
7894	    offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
7895
7896	vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
7897	refcount_create(&adddev->l2ad_alloc);
7898
7899	/*
7900	 * Add device to global list
7901	 */
7902	mutex_enter(&l2arc_dev_mtx);
7903	list_insert_head(l2arc_dev_list, adddev);
7904	atomic_inc_64(&l2arc_ndev);
7905	mutex_exit(&l2arc_dev_mtx);
7906}
7907
7908/*
7909 * Remove a vdev from the L2ARC.
7910 */
7911void
7912l2arc_remove_vdev(vdev_t *vd)
7913{
7914	l2arc_dev_t *dev, *nextdev, *remdev = NULL;
7915
7916	/*
7917	 * Find the device by vdev
7918	 */
7919	mutex_enter(&l2arc_dev_mtx);
7920	for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
7921		nextdev = list_next(l2arc_dev_list, dev);
7922		if (vd == dev->l2ad_vdev) {
7923			remdev = dev;
7924			break;
7925		}
7926	}
7927	ASSERT3P(remdev, !=, NULL);
7928
7929	/*
7930	 * Remove device from global list
7931	 */
7932	list_remove(l2arc_dev_list, remdev);
7933	l2arc_dev_last = NULL;		/* may have been invalidated */
7934	atomic_dec_64(&l2arc_ndev);
7935	mutex_exit(&l2arc_dev_mtx);
7936
7937	/*
7938	 * Clear all buflists and ARC references.  L2ARC device flush.
7939	 */
7940	l2arc_evict(remdev, 0, B_TRUE);
7941	list_destroy(&remdev->l2ad_buflist);
7942	mutex_destroy(&remdev->l2ad_mtx);
7943	refcount_destroy(&remdev->l2ad_alloc);
7944	kmem_free(remdev, sizeof (l2arc_dev_t));
7945}
7946
7947void
7948l2arc_init(void)
7949{
7950	l2arc_thread_exit = 0;
7951	l2arc_ndev = 0;
7952	l2arc_writes_sent = 0;
7953	l2arc_writes_done = 0;
7954
7955	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
7956	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
7957	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
7958	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
7959
7960	l2arc_dev_list = &L2ARC_dev_list;
7961	l2arc_free_on_write = &L2ARC_free_on_write;
7962	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
7963	    offsetof(l2arc_dev_t, l2ad_node));
7964	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
7965	    offsetof(l2arc_data_free_t, l2df_list_node));
7966}
7967
7968void
7969l2arc_fini(void)
7970{
7971	/*
7972	 * This is called from dmu_fini(), which is called from spa_fini();
7973	 * Because of this, we can assume that all l2arc devices have
7974	 * already been removed when the pools themselves were removed.
7975	 */
7976
7977	l2arc_do_free_on_write();
7978
7979	mutex_destroy(&l2arc_feed_thr_lock);
7980	cv_destroy(&l2arc_feed_thr_cv);
7981	mutex_destroy(&l2arc_dev_mtx);
7982	mutex_destroy(&l2arc_free_on_write_mtx);
7983
7984	list_destroy(l2arc_dev_list);
7985	list_destroy(l2arc_free_on_write);
7986}
7987
7988void
7989l2arc_start(void)
7990{
7991	if (!(spa_mode_global & FWRITE))
7992		return;
7993
7994	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
7995	    TS_RUN, minclsyspri);
7996}
7997
7998void
7999l2arc_stop(void)
8000{
8001	if (!(spa_mode_global & FWRITE))
8002		return;
8003
8004	mutex_enter(&l2arc_feed_thr_lock);
8005	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
8006	l2arc_thread_exit = 1;
8007	while (l2arc_thread_exit != 0)
8008		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
8009	mutex_exit(&l2arc_feed_thr_lock);
8010}
8011