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