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