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