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