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, 2014 by Delphix. All rights reserved.
  25  * Copyright (c) 2014 by Saso Kiselkov. All rights reserved.
  26  * Copyright 2014 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 l2arc_buflist_mtx global mutex 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 #ifdef _KERNEL
 133 #include <sys/vmsystm.h>
 134 #include <vm/anon.h>
 135 #include <sys/fs/swapnode.h>
 136 #include <sys/dnlc.h>
 137 #endif
 138 #include <sys/callb.h>
 139 #include <sys/kstat.h>
 140 #include <zfs_fletcher.h>
 141 
 142 #ifndef _KERNEL
 143 /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
 144 boolean_t arc_watch = B_FALSE;
 145 int arc_procfd;
 146 #endif
 147 
 148 static kmutex_t         arc_reclaim_thr_lock;
 149 static kcondvar_t       arc_reclaim_thr_cv;     /* used to signal reclaim thr */
 150 static uint8_t          arc_thread_exit;
 151 
 152 #define ARC_REDUCE_DNLC_PERCENT 3
 153 uint_t arc_reduce_dnlc_percent = ARC_REDUCE_DNLC_PERCENT;
 154 
 155 typedef enum arc_reclaim_strategy {
 156         ARC_RECLAIM_AGGR,               /* Aggressive reclaim strategy */
 157         ARC_RECLAIM_CONS                /* Conservative reclaim strategy */
 158 } arc_reclaim_strategy_t;
 159 
 160 /*
 161  * The number of iterations through arc_evict_*() before we
 162  * drop & reacquire the lock.
 163  */
 164 int arc_evict_iterations = 100;
 165 
 166 /* number of seconds before growing cache again */
 167 static int              arc_grow_retry = 60;
 168 
 169 /* shift of arc_c for calculating both min and max arc_p */
 170 static int              arc_p_min_shift = 4;
 171 
 172 /* log2(fraction of arc to reclaim) */
 173 static int              arc_shrink_shift = 5;
 174 
 175 /*
 176  * minimum lifespan of a prefetch block in clock ticks
 177  * (initialized in arc_init())
 178  */
 179 static int              arc_min_prefetch_lifespan;
 180 
 181 /*
 182  * If this percent of memory is free, don't throttle.
 183  */
 184 int arc_lotsfree_percent = 10;
 185 
 186 static int arc_dead;
 187 
 188 /*
 189  * The arc has filled available memory and has now warmed up.
 190  */
 191 static boolean_t arc_warm;
 192 
 193 /*
 194  * These tunables are for performance analysis.
 195  */
 196 uint64_t zfs_arc_max;
 197 uint64_t zfs_arc_min;
 198 uint64_t zfs_arc_meta_limit = 0;
 199 int zfs_arc_grow_retry = 0;
 200 int zfs_arc_shrink_shift = 0;
 201 int zfs_arc_p_min_shift = 0;
 202 int zfs_disable_dup_eviction = 0;
 203 int zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
 204 
 205 /*
 206  * Note that buffers can be in one of 6 states:
 207  *      ARC_anon        - anonymous (discussed below)
 208  *      ARC_mru         - recently used, currently cached
 209  *      ARC_mru_ghost   - recentely used, no longer in cache
 210  *      ARC_mfu         - frequently used, currently cached
 211  *      ARC_mfu_ghost   - frequently used, no longer in cache
 212  *      ARC_l2c_only    - exists in L2ARC but not other states
 213  * When there are no active references to the buffer, they are
 214  * are linked onto a list in one of these arc states.  These are
 215  * the only buffers that can be evicted or deleted.  Within each
 216  * state there are multiple lists, one for meta-data and one for
 217  * non-meta-data.  Meta-data (indirect blocks, blocks of dnodes,
 218  * etc.) is tracked separately so that it can be managed more
 219  * explicitly: favored over data, limited explicitly.
 220  *
 221  * Anonymous buffers are buffers that are not associated with
 222  * a DVA.  These are buffers that hold dirty block copies
 223  * before they are written to stable storage.  By definition,
 224  * they are "ref'd" and are considered part of arc_mru
 225  * that cannot be freed.  Generally, they will aquire a DVA
 226  * as they are written and migrate onto the arc_mru list.
 227  *
 228  * The ARC_l2c_only state is for buffers that are in the second
 229  * level ARC but no longer in any of the ARC_m* lists.  The second
 230  * level ARC itself may also contain buffers that are in any of
 231  * the ARC_m* states - meaning that a buffer can exist in two
 232  * places.  The reason for the ARC_l2c_only state is to keep the
 233  * buffer header in the hash table, so that reads that hit the
 234  * second level ARC benefit from these fast lookups.
 235  */
 236 
 237 typedef struct arc_state {
 238         list_t  arcs_list[ARC_BUFC_NUMTYPES];   /* list of evictable buffers */
 239         uint64_t arcs_lsize[ARC_BUFC_NUMTYPES]; /* amount of evictable data */
 240         uint64_t arcs_size;     /* total amount of data in this state */
 241         kmutex_t arcs_mtx;
 242 } arc_state_t;
 243 
 244 /* The 6 states: */
 245 static arc_state_t ARC_anon;
 246 static arc_state_t ARC_mru;
 247 static arc_state_t ARC_mru_ghost;
 248 static arc_state_t ARC_mfu;
 249 static arc_state_t ARC_mfu_ghost;
 250 static arc_state_t ARC_l2c_only;
 251 
 252 typedef struct arc_stats {
 253         kstat_named_t arcstat_hits;
 254         kstat_named_t arcstat_misses;
 255         kstat_named_t arcstat_demand_data_hits;
 256         kstat_named_t arcstat_demand_data_misses;
 257         kstat_named_t arcstat_demand_metadata_hits;
 258         kstat_named_t arcstat_demand_metadata_misses;
 259         kstat_named_t arcstat_prefetch_data_hits;
 260         kstat_named_t arcstat_prefetch_data_misses;
 261         kstat_named_t arcstat_prefetch_metadata_hits;
 262         kstat_named_t arcstat_prefetch_metadata_misses;
 263         kstat_named_t arcstat_mru_hits;
 264         kstat_named_t arcstat_mru_ghost_hits;
 265         kstat_named_t arcstat_mfu_hits;
 266         kstat_named_t arcstat_mfu_ghost_hits;
 267         kstat_named_t arcstat_deleted;
 268         kstat_named_t arcstat_recycle_miss;
 269         /*
 270          * Number of buffers that could not be evicted because the hash lock
 271          * was held by another thread.  The lock may not necessarily be held
 272          * by something using the same buffer, since hash locks are shared
 273          * by multiple buffers.
 274          */
 275         kstat_named_t arcstat_mutex_miss;
 276         /*
 277          * Number of buffers skipped because they have I/O in progress, are
 278          * indrect prefetch buffers that have not lived long enough, or are
 279          * not from the spa we're trying to evict from.
 280          */
 281         kstat_named_t arcstat_evict_skip;
 282         kstat_named_t arcstat_evict_l2_cached;
 283         kstat_named_t arcstat_evict_l2_eligible;
 284         kstat_named_t arcstat_evict_l2_ineligible;
 285         kstat_named_t arcstat_hash_elements;
 286         kstat_named_t arcstat_hash_elements_max;
 287         kstat_named_t arcstat_hash_collisions;
 288         kstat_named_t arcstat_hash_chains;
 289         kstat_named_t arcstat_hash_chain_max;
 290         kstat_named_t arcstat_p;
 291         kstat_named_t arcstat_c;
 292         kstat_named_t arcstat_c_min;
 293         kstat_named_t arcstat_c_max;
 294         kstat_named_t arcstat_size;
 295         kstat_named_t arcstat_hdr_size;
 296         kstat_named_t arcstat_data_size;
 297         kstat_named_t arcstat_other_size;
 298         kstat_named_t arcstat_l2_hits;
 299         kstat_named_t arcstat_l2_misses;
 300         kstat_named_t arcstat_l2_feeds;
 301         kstat_named_t arcstat_l2_rw_clash;
 302         kstat_named_t arcstat_l2_read_bytes;
 303         kstat_named_t arcstat_l2_write_bytes;
 304         kstat_named_t arcstat_l2_writes_sent;
 305         kstat_named_t arcstat_l2_writes_done;
 306         kstat_named_t arcstat_l2_writes_error;
 307         kstat_named_t arcstat_l2_writes_hdr_miss;
 308         kstat_named_t arcstat_l2_evict_lock_retry;
 309         kstat_named_t arcstat_l2_evict_reading;
 310         kstat_named_t arcstat_l2_free_on_write;
 311         kstat_named_t arcstat_l2_cdata_free_on_write;
 312         kstat_named_t arcstat_l2_abort_lowmem;
 313         kstat_named_t arcstat_l2_cksum_bad;
 314         kstat_named_t arcstat_l2_io_error;
 315         kstat_named_t arcstat_l2_size;
 316         kstat_named_t arcstat_l2_asize;
 317         kstat_named_t arcstat_l2_hdr_size;
 318         kstat_named_t arcstat_l2_compress_successes;
 319         kstat_named_t arcstat_l2_compress_zeros;
 320         kstat_named_t arcstat_l2_compress_failures;
 321         kstat_named_t arcstat_memory_throttle_count;
 322         kstat_named_t arcstat_duplicate_buffers;
 323         kstat_named_t arcstat_duplicate_buffers_size;
 324         kstat_named_t arcstat_duplicate_reads;
 325         kstat_named_t arcstat_meta_used;
 326         kstat_named_t arcstat_meta_limit;
 327         kstat_named_t arcstat_meta_max;
 328 } arc_stats_t;
 329 
 330 static arc_stats_t arc_stats = {
 331         { "hits",                       KSTAT_DATA_UINT64 },
 332         { "misses",                     KSTAT_DATA_UINT64 },
 333         { "demand_data_hits",           KSTAT_DATA_UINT64 },
 334         { "demand_data_misses",         KSTAT_DATA_UINT64 },
 335         { "demand_metadata_hits",       KSTAT_DATA_UINT64 },
 336         { "demand_metadata_misses",     KSTAT_DATA_UINT64 },
 337         { "prefetch_data_hits",         KSTAT_DATA_UINT64 },
 338         { "prefetch_data_misses",       KSTAT_DATA_UINT64 },
 339         { "prefetch_metadata_hits",     KSTAT_DATA_UINT64 },
 340         { "prefetch_metadata_misses",   KSTAT_DATA_UINT64 },
 341         { "mru_hits",                   KSTAT_DATA_UINT64 },
 342         { "mru_ghost_hits",             KSTAT_DATA_UINT64 },
 343         { "mfu_hits",                   KSTAT_DATA_UINT64 },
 344         { "mfu_ghost_hits",             KSTAT_DATA_UINT64 },
 345         { "deleted",                    KSTAT_DATA_UINT64 },
 346         { "recycle_miss",               KSTAT_DATA_UINT64 },
 347         { "mutex_miss",                 KSTAT_DATA_UINT64 },
 348         { "evict_skip",                 KSTAT_DATA_UINT64 },
 349         { "evict_l2_cached",            KSTAT_DATA_UINT64 },
 350         { "evict_l2_eligible",          KSTAT_DATA_UINT64 },
 351         { "evict_l2_ineligible",        KSTAT_DATA_UINT64 },
 352         { "hash_elements",              KSTAT_DATA_UINT64 },
 353         { "hash_elements_max",          KSTAT_DATA_UINT64 },
 354         { "hash_collisions",            KSTAT_DATA_UINT64 },
 355         { "hash_chains",                KSTAT_DATA_UINT64 },
 356         { "hash_chain_max",             KSTAT_DATA_UINT64 },
 357         { "p",                          KSTAT_DATA_UINT64 },
 358         { "c",                          KSTAT_DATA_UINT64 },
 359         { "c_min",                      KSTAT_DATA_UINT64 },
 360         { "c_max",                      KSTAT_DATA_UINT64 },
 361         { "size",                       KSTAT_DATA_UINT64 },
 362         { "hdr_size",                   KSTAT_DATA_UINT64 },
 363         { "data_size",                  KSTAT_DATA_UINT64 },
 364         { "other_size",                 KSTAT_DATA_UINT64 },
 365         { "l2_hits",                    KSTAT_DATA_UINT64 },
 366         { "l2_misses",                  KSTAT_DATA_UINT64 },
 367         { "l2_feeds",                   KSTAT_DATA_UINT64 },
 368         { "l2_rw_clash",                KSTAT_DATA_UINT64 },
 369         { "l2_read_bytes",              KSTAT_DATA_UINT64 },
 370         { "l2_write_bytes",             KSTAT_DATA_UINT64 },
 371         { "l2_writes_sent",             KSTAT_DATA_UINT64 },
 372         { "l2_writes_done",             KSTAT_DATA_UINT64 },
 373         { "l2_writes_error",            KSTAT_DATA_UINT64 },
 374         { "l2_writes_hdr_miss",         KSTAT_DATA_UINT64 },
 375         { "l2_evict_lock_retry",        KSTAT_DATA_UINT64 },
 376         { "l2_evict_reading",           KSTAT_DATA_UINT64 },
 377         { "l2_free_on_write",           KSTAT_DATA_UINT64 },
 378         { "l2_cdata_free_on_write",     KSTAT_DATA_UINT64 },
 379         { "l2_abort_lowmem",            KSTAT_DATA_UINT64 },
 380         { "l2_cksum_bad",               KSTAT_DATA_UINT64 },
 381         { "l2_io_error",                KSTAT_DATA_UINT64 },
 382         { "l2_size",                    KSTAT_DATA_UINT64 },
 383         { "l2_asize",                   KSTAT_DATA_UINT64 },
 384         { "l2_hdr_size",                KSTAT_DATA_UINT64 },
 385         { "l2_compress_successes",      KSTAT_DATA_UINT64 },
 386         { "l2_compress_zeros",          KSTAT_DATA_UINT64 },
 387         { "l2_compress_failures",       KSTAT_DATA_UINT64 },
 388         { "memory_throttle_count",      KSTAT_DATA_UINT64 },
 389         { "duplicate_buffers",          KSTAT_DATA_UINT64 },
 390         { "duplicate_buffers_size",     KSTAT_DATA_UINT64 },
 391         { "duplicate_reads",            KSTAT_DATA_UINT64 },
 392         { "arc_meta_used",              KSTAT_DATA_UINT64 },
 393         { "arc_meta_limit",             KSTAT_DATA_UINT64 },
 394         { "arc_meta_max",               KSTAT_DATA_UINT64 }
 395 };
 396 
 397 #define ARCSTAT(stat)   (arc_stats.stat.value.ui64)
 398 
 399 #define ARCSTAT_INCR(stat, val) \
 400         atomic_add_64(&arc_stats.stat.value.ui64, (val))
 401 
 402 #define ARCSTAT_BUMP(stat)      ARCSTAT_INCR(stat, 1)
 403 #define ARCSTAT_BUMPDOWN(stat)  ARCSTAT_INCR(stat, -1)
 404 
 405 #define ARCSTAT_MAX(stat, val) {                                        \
 406         uint64_t m;                                                     \
 407         while ((val) > (m = arc_stats.stat.value.ui64) &&            \
 408             (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val))))     \
 409                 continue;                                               \
 410 }
 411 
 412 #define ARCSTAT_MAXSTAT(stat) \
 413         ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
 414 
 415 /*
 416  * We define a macro to allow ARC hits/misses to be easily broken down by
 417  * two separate conditions, giving a total of four different subtypes for
 418  * each of hits and misses (so eight statistics total).
 419  */
 420 #define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
 421         if (cond1) {                                                    \
 422                 if (cond2) {                                            \
 423                         ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
 424                 } else {                                                \
 425                         ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
 426                 }                                                       \
 427         } else {                                                        \
 428                 if (cond2) {                                            \
 429                         ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
 430                 } else {                                                \
 431                         ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
 432                 }                                                       \
 433         }
 434 
 435 kstat_t                 *arc_ksp;
 436 static arc_state_t      *arc_anon;
 437 static arc_state_t      *arc_mru;
 438 static arc_state_t      *arc_mru_ghost;
 439 static arc_state_t      *arc_mfu;
 440 static arc_state_t      *arc_mfu_ghost;
 441 static arc_state_t      *arc_l2c_only;
 442 
 443 /*
 444  * There are several ARC variables that are critical to export as kstats --
 445  * but we don't want to have to grovel around in the kstat whenever we wish to
 446  * manipulate them.  For these variables, we therefore define them to be in
 447  * terms of the statistic variable.  This assures that we are not introducing
 448  * the possibility of inconsistency by having shadow copies of the variables,
 449  * while still allowing the code to be readable.
 450  */
 451 #define arc_size        ARCSTAT(arcstat_size)   /* actual total arc size */
 452 #define arc_p           ARCSTAT(arcstat_p)      /* target size of MRU */
 453 #define arc_c           ARCSTAT(arcstat_c)      /* target size of cache */
 454 #define arc_c_min       ARCSTAT(arcstat_c_min)  /* min target cache size */
 455 #define arc_c_max       ARCSTAT(arcstat_c_max)  /* max target cache size */
 456 #define arc_meta_limit  ARCSTAT(arcstat_meta_limit) /* max size for metadata */
 457 #define arc_meta_used   ARCSTAT(arcstat_meta_used) /* size of metadata */
 458 #define arc_meta_max    ARCSTAT(arcstat_meta_max) /* max size of metadata */
 459 
 460 #define L2ARC_IS_VALID_COMPRESS(_c_) \
 461         ((_c_) == ZIO_COMPRESS_LZ4 || (_c_) == ZIO_COMPRESS_EMPTY)
 462 
 463 static int              arc_no_grow;    /* Don't try to grow cache size */
 464 static uint64_t         arc_tempreserve;
 465 static uint64_t         arc_loaned_bytes;
 466 
 467 typedef struct l2arc_buf_hdr l2arc_buf_hdr_t;
 468 
 469 typedef struct arc_callback arc_callback_t;
 470 
 471 struct arc_callback {
 472         void                    *acb_private;
 473         arc_done_func_t         *acb_done;
 474         arc_buf_t               *acb_buf;
 475         zio_t                   *acb_zio_dummy;
 476         arc_callback_t          *acb_next;
 477 };
 478 
 479 typedef struct arc_write_callback arc_write_callback_t;
 480 
 481 struct arc_write_callback {
 482         void            *awcb_private;
 483         arc_done_func_t *awcb_ready;
 484         arc_done_func_t *awcb_physdone;
 485         arc_done_func_t *awcb_done;
 486         arc_buf_t       *awcb_buf;
 487 };
 488 
 489 struct arc_buf_hdr {
 490         /* protected by hash lock */
 491         dva_t                   b_dva;
 492         uint64_t                b_birth;
 493         uint64_t                b_cksum0;
 494 
 495         kmutex_t                b_freeze_lock;
 496         zio_cksum_t             *b_freeze_cksum;
 497         void                    *b_thawed;
 498 
 499         arc_buf_hdr_t           *b_hash_next;
 500         arc_buf_t               *b_buf;
 501         uint32_t                b_flags;
 502         uint32_t                b_datacnt;
 503 
 504         arc_callback_t          *b_acb;
 505         kcondvar_t              b_cv;
 506 
 507         /* immutable */
 508         arc_buf_contents_t      b_type;
 509         uint64_t                b_size;
 510         uint64_t                b_spa;
 511 
 512         /* protected by arc state mutex */
 513         arc_state_t             *b_state;
 514         list_node_t             b_arc_node;
 515 
 516         /* updated atomically */
 517         clock_t                 b_arc_access;
 518 
 519         /* self protecting */
 520         refcount_t              b_refcnt;
 521 
 522         l2arc_buf_hdr_t         *b_l2hdr;
 523         list_node_t             b_l2node;
 524 };
 525 
 526 static arc_buf_t *arc_eviction_list;
 527 static kmutex_t arc_eviction_mtx;
 528 static arc_buf_hdr_t arc_eviction_hdr;
 529 static void arc_get_data_buf(arc_buf_t *buf);
 530 static void arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock);
 531 static int arc_evict_needed(arc_buf_contents_t type);
 532 static void arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes);
 533 static void arc_buf_watch(arc_buf_t *buf);
 534 
 535 static boolean_t l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *ab);
 536 
 537 #define GHOST_STATE(state)      \
 538         ((state) == arc_mru_ghost || (state) == arc_mfu_ghost ||        \
 539         (state) == arc_l2c_only)
 540 
 541 /*
 542  * Private ARC flags.  These flags are private ARC only flags that will show up
 543  * in b_flags in the arc_hdr_buf_t.  Some flags are publicly declared, and can
 544  * be passed in as arc_flags in things like arc_read.  However, these flags
 545  * should never be passed and should only be set by ARC code.  When adding new
 546  * public flags, make sure not to smash the private ones.
 547  */
 548 
 549 #define ARC_IN_HASH_TABLE       (1 << 9)  /* this buffer is hashed */
 550 #define ARC_IO_IN_PROGRESS      (1 << 10) /* I/O in progress for buf */
 551 #define ARC_IO_ERROR            (1 << 11) /* I/O failed for buf */
 552 #define ARC_FREED_IN_READ       (1 << 12) /* buf freed while in read */
 553 #define ARC_BUF_AVAILABLE       (1 << 13) /* block not in active use */
 554 #define ARC_INDIRECT            (1 << 14) /* this is an indirect block */
 555 #define ARC_FREE_IN_PROGRESS    (1 << 15) /* hdr about to be freed */
 556 #define ARC_L2_WRITING          (1 << 16) /* L2ARC write in progress */
 557 #define ARC_L2_EVICTED          (1 << 17) /* evicted during I/O */
 558 #define ARC_L2_WRITE_HEAD       (1 << 18) /* head of write list */
 559 
 560 #define HDR_IN_HASH_TABLE(hdr)  ((hdr)->b_flags & ARC_IN_HASH_TABLE)
 561 #define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_IO_IN_PROGRESS)
 562 #define HDR_IO_ERROR(hdr)       ((hdr)->b_flags & ARC_IO_ERROR)
 563 #define HDR_PREFETCH(hdr)       ((hdr)->b_flags & ARC_PREFETCH)
 564 #define HDR_FREED_IN_READ(hdr)  ((hdr)->b_flags & ARC_FREED_IN_READ)
 565 #define HDR_BUF_AVAILABLE(hdr)  ((hdr)->b_flags & ARC_BUF_AVAILABLE)
 566 #define HDR_FREE_IN_PROGRESS(hdr)       ((hdr)->b_flags & ARC_FREE_IN_PROGRESS)
 567 #define HDR_L2CACHE(hdr)        ((hdr)->b_flags & ARC_L2CACHE)
 568 #define HDR_L2_READING(hdr)     ((hdr)->b_flags & ARC_IO_IN_PROGRESS &&  \
 569                                     (hdr)->b_l2hdr != NULL)
 570 #define HDR_L2_WRITING(hdr)     ((hdr)->b_flags & ARC_L2_WRITING)
 571 #define HDR_L2_EVICTED(hdr)     ((hdr)->b_flags & ARC_L2_EVICTED)
 572 #define HDR_L2_WRITE_HEAD(hdr)  ((hdr)->b_flags & ARC_L2_WRITE_HEAD)
 573 
 574 /*
 575  * Other sizes
 576  */
 577 
 578 #define HDR_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
 579 #define L2HDR_SIZE ((int64_t)sizeof (l2arc_buf_hdr_t))
 580 
 581 /*
 582  * Hash table routines
 583  */
 584 
 585 #define HT_LOCK_PAD     64
 586 
 587 struct ht_lock {
 588         kmutex_t        ht_lock;
 589 #ifdef _KERNEL
 590         unsigned char   pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
 591 #endif
 592 };
 593 
 594 #define BUF_LOCKS 256
 595 typedef struct buf_hash_table {
 596         uint64_t ht_mask;
 597         arc_buf_hdr_t **ht_table;
 598         struct ht_lock ht_locks[BUF_LOCKS];
 599 } buf_hash_table_t;
 600 
 601 static buf_hash_table_t buf_hash_table;
 602 
 603 #define BUF_HASH_INDEX(spa, dva, birth) \
 604         (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
 605 #define BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
 606 #define BUF_HASH_LOCK(idx)      (&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
 607 #define HDR_LOCK(hdr) \
 608         (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
 609 
 610 uint64_t zfs_crc64_table[256];
 611 
 612 /*
 613  * Level 2 ARC
 614  */
 615 
 616 #define L2ARC_WRITE_SIZE        (8 * 1024 * 1024)       /* initial write max */
 617 #define L2ARC_HEADROOM          2                       /* num of writes */
 618 /*
 619  * If we discover during ARC scan any buffers to be compressed, we boost
 620  * our headroom for the next scanning cycle by this percentage multiple.
 621  */
 622 #define L2ARC_HEADROOM_BOOST    200
 623 #define L2ARC_FEED_SECS         1               /* caching interval secs */
 624 #define L2ARC_FEED_MIN_MS       200             /* min caching interval ms */
 625 
 626 #define l2arc_writes_sent       ARCSTAT(arcstat_l2_writes_sent)
 627 #define l2arc_writes_done       ARCSTAT(arcstat_l2_writes_done)
 628 
 629 /* L2ARC Performance Tunables */
 630 uint64_t l2arc_write_max = L2ARC_WRITE_SIZE;    /* default max write size */
 631 uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE;  /* extra write during warmup */
 632 uint64_t l2arc_headroom = L2ARC_HEADROOM;       /* number of dev writes */
 633 uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
 634 uint64_t l2arc_feed_secs = L2ARC_FEED_SECS;     /* interval seconds */
 635 uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval milliseconds */
 636 boolean_t l2arc_noprefetch = B_TRUE;            /* don't cache prefetch bufs */
 637 boolean_t l2arc_feed_again = B_TRUE;            /* turbo warmup */
 638 boolean_t l2arc_norw = B_TRUE;                  /* no reads during writes */
 639 
 640 /*
 641  * L2ARC Internals
 642  */
 643 typedef struct l2arc_dev {
 644         vdev_t                  *l2ad_vdev;     /* vdev */
 645         spa_t                   *l2ad_spa;      /* spa */
 646         uint64_t                l2ad_hand;      /* next write location */
 647         uint64_t                l2ad_start;     /* first addr on device */
 648         uint64_t                l2ad_end;       /* last addr on device */
 649         uint64_t                l2ad_evict;     /* last addr eviction reached */
 650         boolean_t               l2ad_first;     /* first sweep through */
 651         boolean_t               l2ad_writing;   /* currently writing */
 652         list_t                  *l2ad_buflist;  /* buffer list */
 653         list_node_t             l2ad_node;      /* device list node */
 654 } l2arc_dev_t;
 655 
 656 static list_t L2ARC_dev_list;                   /* device list */
 657 static list_t *l2arc_dev_list;                  /* device list pointer */
 658 static kmutex_t l2arc_dev_mtx;                  /* device list mutex */
 659 static l2arc_dev_t *l2arc_dev_last;             /* last device used */
 660 static kmutex_t l2arc_buflist_mtx;              /* mutex for all buflists */
 661 static list_t L2ARC_free_on_write;              /* free after write buf list */
 662 static list_t *l2arc_free_on_write;             /* free after write list ptr */
 663 static kmutex_t l2arc_free_on_write_mtx;        /* mutex for list */
 664 static uint64_t l2arc_ndev;                     /* number of devices */
 665 
 666 typedef struct l2arc_read_callback {
 667         arc_buf_t               *l2rcb_buf;             /* read buffer */
 668         spa_t                   *l2rcb_spa;             /* spa */
 669         blkptr_t                l2rcb_bp;               /* original blkptr */
 670         zbookmark_phys_t        l2rcb_zb;               /* original bookmark */
 671         int                     l2rcb_flags;            /* original flags */
 672         enum zio_compress       l2rcb_compress;         /* applied compress */
 673 } l2arc_read_callback_t;
 674 
 675 typedef struct l2arc_write_callback {
 676         l2arc_dev_t     *l2wcb_dev;             /* device info */
 677         arc_buf_hdr_t   *l2wcb_head;            /* head of write buflist */
 678 } l2arc_write_callback_t;
 679 
 680 struct l2arc_buf_hdr {
 681         /* protected by arc_buf_hdr  mutex */
 682         l2arc_dev_t             *b_dev;         /* L2ARC device */
 683         uint64_t                b_daddr;        /* disk address, offset byte */
 684         /* compression applied to buffer data */
 685         enum zio_compress       b_compress;
 686         /* real alloc'd buffer size depending on b_compress applied */
 687         int                     b_asize;
 688         /* temporary buffer holder for in-flight compressed data */
 689         void                    *b_tmp_cdata;
 690 };
 691 
 692 typedef struct l2arc_data_free {
 693         /* protected by l2arc_free_on_write_mtx */
 694         void            *l2df_data;
 695         size_t          l2df_size;
 696         void            (*l2df_func)(void *, size_t);
 697         list_node_t     l2df_list_node;
 698 } l2arc_data_free_t;
 699 
 700 static kmutex_t l2arc_feed_thr_lock;
 701 static kcondvar_t l2arc_feed_thr_cv;
 702 static uint8_t l2arc_thread_exit;
 703 
 704 static void l2arc_read_done(zio_t *zio);
 705 static void l2arc_hdr_stat_add(void);
 706 static void l2arc_hdr_stat_remove(void);
 707 
 708 static boolean_t l2arc_compress_buf(l2arc_buf_hdr_t *l2hdr);
 709 static void l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr,
 710     enum zio_compress c);
 711 static void l2arc_release_cdata_buf(arc_buf_hdr_t *ab);
 712 
 713 static uint64_t
 714 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
 715 {
 716         uint8_t *vdva = (uint8_t *)dva;
 717         uint64_t crc = -1ULL;
 718         int i;
 719 
 720         ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
 721 
 722         for (i = 0; i < sizeof (dva_t); i++)
 723                 crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
 724 
 725         crc ^= (spa>>8) ^ birth;
 726 
 727         return (crc);
 728 }
 729 
 730 #define BUF_EMPTY(buf)                                          \
 731         ((buf)->b_dva.dva_word[0] == 0 &&                    \
 732         (buf)->b_dva.dva_word[1] == 0 &&                     \
 733         (buf)->b_cksum0 == 0)
 734 
 735 #define BUF_EQUAL(spa, dva, birth, buf)                         \
 736         ((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) &&       \
 737         ((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) &&       \
 738         ((buf)->b_birth == birth) && ((buf)->b_spa == spa)
 739 
 740 static void
 741 buf_discard_identity(arc_buf_hdr_t *hdr)
 742 {
 743         hdr->b_dva.dva_word[0] = 0;
 744         hdr->b_dva.dva_word[1] = 0;
 745         hdr->b_birth = 0;
 746         hdr->b_cksum0 = 0;
 747 }
 748 
 749 static arc_buf_hdr_t *
 750 buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
 751 {
 752         const dva_t *dva = BP_IDENTITY(bp);
 753         uint64_t birth = BP_PHYSICAL_BIRTH(bp);
 754         uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
 755         kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
 756         arc_buf_hdr_t *buf;
 757 
 758         mutex_enter(hash_lock);
 759         for (buf = buf_hash_table.ht_table[idx]; buf != NULL;
 760             buf = buf->b_hash_next) {
 761                 if (BUF_EQUAL(spa, dva, birth, buf)) {
 762                         *lockp = hash_lock;
 763                         return (buf);
 764                 }
 765         }
 766         mutex_exit(hash_lock);
 767         *lockp = NULL;
 768         return (NULL);
 769 }
 770 
 771 /*
 772  * Insert an entry into the hash table.  If there is already an element
 773  * equal to elem in the hash table, then the already existing element
 774  * will be returned and the new element will not be inserted.
 775  * Otherwise returns NULL.
 776  */
 777 static arc_buf_hdr_t *
 778 buf_hash_insert(arc_buf_hdr_t *buf, kmutex_t **lockp)
 779 {
 780         uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
 781         kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
 782         arc_buf_hdr_t *fbuf;
 783         uint32_t i;
 784 
 785         ASSERT(!DVA_IS_EMPTY(&buf->b_dva));
 786         ASSERT(buf->b_birth != 0);
 787         ASSERT(!HDR_IN_HASH_TABLE(buf));
 788         *lockp = hash_lock;
 789         mutex_enter(hash_lock);
 790         for (fbuf = buf_hash_table.ht_table[idx], i = 0; fbuf != NULL;
 791             fbuf = fbuf->b_hash_next, i++) {
 792                 if (BUF_EQUAL(buf->b_spa, &buf->b_dva, buf->b_birth, fbuf))
 793                         return (fbuf);
 794         }
 795 
 796         buf->b_hash_next = buf_hash_table.ht_table[idx];
 797         buf_hash_table.ht_table[idx] = buf;
 798         buf->b_flags |= ARC_IN_HASH_TABLE;
 799 
 800         /* collect some hash table performance data */
 801         if (i > 0) {
 802                 ARCSTAT_BUMP(arcstat_hash_collisions);
 803                 if (i == 1)
 804                         ARCSTAT_BUMP(arcstat_hash_chains);
 805 
 806                 ARCSTAT_MAX(arcstat_hash_chain_max, i);
 807         }
 808 
 809         ARCSTAT_BUMP(arcstat_hash_elements);
 810         ARCSTAT_MAXSTAT(arcstat_hash_elements);
 811 
 812         return (NULL);
 813 }
 814 
 815 static void
 816 buf_hash_remove(arc_buf_hdr_t *buf)
 817 {
 818         arc_buf_hdr_t *fbuf, **bufp;
 819         uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
 820 
 821         ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
 822         ASSERT(HDR_IN_HASH_TABLE(buf));
 823 
 824         bufp = &buf_hash_table.ht_table[idx];
 825         while ((fbuf = *bufp) != buf) {
 826                 ASSERT(fbuf != NULL);
 827                 bufp = &fbuf->b_hash_next;
 828         }
 829         *bufp = buf->b_hash_next;
 830         buf->b_hash_next = NULL;
 831         buf->b_flags &= ~ARC_IN_HASH_TABLE;
 832 
 833         /* collect some hash table performance data */
 834         ARCSTAT_BUMPDOWN(arcstat_hash_elements);
 835 
 836         if (buf_hash_table.ht_table[idx] &&
 837             buf_hash_table.ht_table[idx]->b_hash_next == NULL)
 838                 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
 839 }
 840 
 841 /*
 842  * Global data structures and functions for the buf kmem cache.
 843  */
 844 static kmem_cache_t *hdr_cache;
 845 static kmem_cache_t *buf_cache;
 846 
 847 static void
 848 buf_fini(void)
 849 {
 850         int i;
 851 
 852         kmem_free(buf_hash_table.ht_table,
 853             (buf_hash_table.ht_mask + 1) * sizeof (void *));
 854         for (i = 0; i < BUF_LOCKS; i++)
 855                 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
 856         kmem_cache_destroy(hdr_cache);
 857         kmem_cache_destroy(buf_cache);
 858 }
 859 
 860 /*
 861  * Constructor callback - called when the cache is empty
 862  * and a new buf is requested.
 863  */
 864 /* ARGSUSED */
 865 static int
 866 hdr_cons(void *vbuf, void *unused, int kmflag)
 867 {
 868         arc_buf_hdr_t *buf = vbuf;
 869 
 870         bzero(buf, sizeof (arc_buf_hdr_t));
 871         refcount_create(&buf->b_refcnt);
 872         cv_init(&buf->b_cv, NULL, CV_DEFAULT, NULL);
 873         mutex_init(&buf->b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
 874         arc_space_consume(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
 875 
 876         return (0);
 877 }
 878 
 879 /* ARGSUSED */
 880 static int
 881 buf_cons(void *vbuf, void *unused, int kmflag)
 882 {
 883         arc_buf_t *buf = vbuf;
 884 
 885         bzero(buf, sizeof (arc_buf_t));
 886         mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
 887         arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
 888 
 889         return (0);
 890 }
 891 
 892 /*
 893  * Destructor callback - called when a cached buf is
 894  * no longer required.
 895  */
 896 /* ARGSUSED */
 897 static void
 898 hdr_dest(void *vbuf, void *unused)
 899 {
 900         arc_buf_hdr_t *buf = vbuf;
 901 
 902         ASSERT(BUF_EMPTY(buf));
 903         refcount_destroy(&buf->b_refcnt);
 904         cv_destroy(&buf->b_cv);
 905         mutex_destroy(&buf->b_freeze_lock);
 906         arc_space_return(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
 907 }
 908 
 909 /* ARGSUSED */
 910 static void
 911 buf_dest(void *vbuf, void *unused)
 912 {
 913         arc_buf_t *buf = vbuf;
 914 
 915         mutex_destroy(&buf->b_evict_lock);
 916         arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
 917 }
 918 
 919 /*
 920  * Reclaim callback -- invoked when memory is low.
 921  */
 922 /* ARGSUSED */
 923 static void
 924 hdr_recl(void *unused)
 925 {
 926         dprintf("hdr_recl called\n");
 927         /*
 928          * umem calls the reclaim func when we destroy the buf cache,
 929          * which is after we do arc_fini().
 930          */
 931         if (!arc_dead)
 932                 cv_signal(&arc_reclaim_thr_cv);
 933 }
 934 
 935 static void
 936 buf_init(void)
 937 {
 938         uint64_t *ct;
 939         uint64_t hsize = 1ULL << 12;
 940         int i, j;
 941 
 942         /*
 943          * The hash table is big enough to fill all of physical memory
 944          * with an average block size of zfs_arc_average_blocksize (default 8K).
 945          * By default, the table will take up
 946          * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
 947          */
 948         while (hsize * zfs_arc_average_blocksize < physmem * PAGESIZE)
 949                 hsize <<= 1;
 950 retry:
 951         buf_hash_table.ht_mask = hsize - 1;
 952         buf_hash_table.ht_table =
 953             kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
 954         if (buf_hash_table.ht_table == NULL) {
 955                 ASSERT(hsize > (1ULL << 8));
 956                 hsize >>= 1;
 957                 goto retry;
 958         }
 959 
 960         hdr_cache = kmem_cache_create("arc_buf_hdr_t", sizeof (arc_buf_hdr_t),
 961             0, hdr_cons, hdr_dest, hdr_recl, NULL, NULL, 0);
 962         buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
 963             0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
 964 
 965         for (i = 0; i < 256; i++)
 966                 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
 967                         *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
 968 
 969         for (i = 0; i < BUF_LOCKS; i++) {
 970                 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
 971                     NULL, MUTEX_DEFAULT, NULL);
 972         }
 973 }
 974 
 975 #define ARC_MINTIME     (hz>>4) /* 62 ms */
 976 
 977 static void
 978 arc_cksum_verify(arc_buf_t *buf)
 979 {
 980         zio_cksum_t zc;
 981 
 982         if (!(zfs_flags & ZFS_DEBUG_MODIFY))
 983                 return;
 984 
 985         mutex_enter(&buf->b_hdr->b_freeze_lock);
 986         if (buf->b_hdr->b_freeze_cksum == NULL ||
 987             (buf->b_hdr->b_flags & ARC_IO_ERROR)) {
 988                 mutex_exit(&buf->b_hdr->b_freeze_lock);
 989                 return;
 990         }
 991         fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
 992         if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
 993                 panic("buffer modified while frozen!");
 994         mutex_exit(&buf->b_hdr->b_freeze_lock);
 995 }
 996 
 997 static int
 998 arc_cksum_equal(arc_buf_t *buf)
 999 {
1000         zio_cksum_t zc;
1001         int equal;
1002 
1003         mutex_enter(&buf->b_hdr->b_freeze_lock);
1004         fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1005         equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
1006         mutex_exit(&buf->b_hdr->b_freeze_lock);
1007 
1008         return (equal);
1009 }
1010 
1011 static void
1012 arc_cksum_compute(arc_buf_t *buf, boolean_t force)
1013 {
1014         if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
1015                 return;
1016 
1017         mutex_enter(&buf->b_hdr->b_freeze_lock);
1018         if (buf->b_hdr->b_freeze_cksum != NULL) {
1019                 mutex_exit(&buf->b_hdr->b_freeze_lock);
1020                 return;
1021         }
1022         buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
1023         fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
1024             buf->b_hdr->b_freeze_cksum);
1025         mutex_exit(&buf->b_hdr->b_freeze_lock);
1026         arc_buf_watch(buf);
1027 }
1028 
1029 #ifndef _KERNEL
1030 typedef struct procctl {
1031         long cmd;
1032         prwatch_t prwatch;
1033 } procctl_t;
1034 #endif
1035 
1036 /* ARGSUSED */
1037 static void
1038 arc_buf_unwatch(arc_buf_t *buf)
1039 {
1040 #ifndef _KERNEL
1041         if (arc_watch) {
1042                 int result;
1043                 procctl_t ctl;
1044                 ctl.cmd = PCWATCH;
1045                 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1046                 ctl.prwatch.pr_size = 0;
1047                 ctl.prwatch.pr_wflags = 0;
1048                 result = write(arc_procfd, &ctl, sizeof (ctl));
1049                 ASSERT3U(result, ==, sizeof (ctl));
1050         }
1051 #endif
1052 }
1053 
1054 /* ARGSUSED */
1055 static void
1056 arc_buf_watch(arc_buf_t *buf)
1057 {
1058 #ifndef _KERNEL
1059         if (arc_watch) {
1060                 int result;
1061                 procctl_t ctl;
1062                 ctl.cmd = PCWATCH;
1063                 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1064                 ctl.prwatch.pr_size = buf->b_hdr->b_size;
1065                 ctl.prwatch.pr_wflags = WA_WRITE;
1066                 result = write(arc_procfd, &ctl, sizeof (ctl));
1067                 ASSERT3U(result, ==, sizeof (ctl));
1068         }
1069 #endif
1070 }
1071 
1072 void
1073 arc_buf_thaw(arc_buf_t *buf)
1074 {
1075         if (zfs_flags & ZFS_DEBUG_MODIFY) {
1076                 if (buf->b_hdr->b_state != arc_anon)
1077                         panic("modifying non-anon buffer!");
1078                 if (buf->b_hdr->b_flags & ARC_IO_IN_PROGRESS)
1079                         panic("modifying buffer while i/o in progress!");
1080                 arc_cksum_verify(buf);
1081         }
1082 
1083         mutex_enter(&buf->b_hdr->b_freeze_lock);
1084         if (buf->b_hdr->b_freeze_cksum != NULL) {
1085                 kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1086                 buf->b_hdr->b_freeze_cksum = NULL;
1087         }
1088 
1089         if (zfs_flags & ZFS_DEBUG_MODIFY) {
1090                 if (buf->b_hdr->b_thawed)
1091                         kmem_free(buf->b_hdr->b_thawed, 1);
1092                 buf->b_hdr->b_thawed = kmem_alloc(1, KM_SLEEP);
1093         }
1094 
1095         mutex_exit(&buf->b_hdr->b_freeze_lock);
1096 
1097         arc_buf_unwatch(buf);
1098 }
1099 
1100 void
1101 arc_buf_freeze(arc_buf_t *buf)
1102 {
1103         kmutex_t *hash_lock;
1104 
1105         if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1106                 return;
1107 
1108         hash_lock = HDR_LOCK(buf->b_hdr);
1109         mutex_enter(hash_lock);
1110 
1111         ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
1112             buf->b_hdr->b_state == arc_anon);
1113         arc_cksum_compute(buf, B_FALSE);
1114         mutex_exit(hash_lock);
1115 
1116 }
1117 
1118 static void
1119 add_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
1120 {
1121         ASSERT(MUTEX_HELD(hash_lock));
1122 
1123         if ((refcount_add(&ab->b_refcnt, tag) == 1) &&
1124             (ab->b_state != arc_anon)) {
1125                 uint64_t delta = ab->b_size * ab->b_datacnt;
1126                 list_t *list = &ab->b_state->arcs_list[ab->b_type];
1127                 uint64_t *size = &ab->b_state->arcs_lsize[ab->b_type];
1128 
1129                 ASSERT(!MUTEX_HELD(&ab->b_state->arcs_mtx));
1130                 mutex_enter(&ab->b_state->arcs_mtx);
1131                 ASSERT(list_link_active(&ab->b_arc_node));
1132                 list_remove(list, ab);
1133                 if (GHOST_STATE(ab->b_state)) {
1134                         ASSERT0(ab->b_datacnt);
1135                         ASSERT3P(ab->b_buf, ==, NULL);
1136                         delta = ab->b_size;
1137                 }
1138                 ASSERT(delta > 0);
1139                 ASSERT3U(*size, >=, delta);
1140                 atomic_add_64(size, -delta);
1141                 mutex_exit(&ab->b_state->arcs_mtx);
1142                 /* remove the prefetch flag if we get a reference */
1143                 if (ab->b_flags & ARC_PREFETCH)
1144                         ab->b_flags &= ~ARC_PREFETCH;
1145         }
1146 }
1147 
1148 static int
1149 remove_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
1150 {
1151         int cnt;
1152         arc_state_t *state = ab->b_state;
1153 
1154         ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
1155         ASSERT(!GHOST_STATE(state));
1156 
1157         if (((cnt = refcount_remove(&ab->b_refcnt, tag)) == 0) &&
1158             (state != arc_anon)) {
1159                 uint64_t *size = &state->arcs_lsize[ab->b_type];
1160 
1161                 ASSERT(!MUTEX_HELD(&state->arcs_mtx));
1162                 mutex_enter(&state->arcs_mtx);
1163                 ASSERT(!list_link_active(&ab->b_arc_node));
1164                 list_insert_head(&state->arcs_list[ab->b_type], ab);
1165                 ASSERT(ab->b_datacnt > 0);
1166                 atomic_add_64(size, ab->b_size * ab->b_datacnt);
1167                 mutex_exit(&state->arcs_mtx);
1168         }
1169         return (cnt);
1170 }
1171 
1172 /*
1173  * Move the supplied buffer to the indicated state.  The mutex
1174  * for the buffer must be held by the caller.
1175  */
1176 static void
1177 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *ab, kmutex_t *hash_lock)
1178 {
1179         arc_state_t *old_state = ab->b_state;
1180         int64_t refcnt = refcount_count(&ab->b_refcnt);
1181         uint64_t from_delta, to_delta;
1182 
1183         ASSERT(MUTEX_HELD(hash_lock));
1184         ASSERT3P(new_state, !=, old_state);
1185         ASSERT(refcnt == 0 || ab->b_datacnt > 0);
1186         ASSERT(ab->b_datacnt == 0 || !GHOST_STATE(new_state));
1187         ASSERT(ab->b_datacnt <= 1 || old_state != arc_anon);
1188 
1189         from_delta = to_delta = ab->b_datacnt * ab->b_size;
1190 
1191         /*
1192          * If this buffer is evictable, transfer it from the
1193          * old state list to the new state list.
1194          */
1195         if (refcnt == 0) {
1196                 if (old_state != arc_anon) {
1197                         int use_mutex = !MUTEX_HELD(&old_state->arcs_mtx);
1198                         uint64_t *size = &old_state->arcs_lsize[ab->b_type];
1199 
1200                         if (use_mutex)
1201                                 mutex_enter(&old_state->arcs_mtx);
1202 
1203                         ASSERT(list_link_active(&ab->b_arc_node));
1204                         list_remove(&old_state->arcs_list[ab->b_type], ab);
1205 
1206                         /*
1207                          * If prefetching out of the ghost cache,
1208                          * we will have a non-zero datacnt.
1209                          */
1210                         if (GHOST_STATE(old_state) && ab->b_datacnt == 0) {
1211                                 /* ghost elements have a ghost size */
1212                                 ASSERT(ab->b_buf == NULL);
1213                                 from_delta = ab->b_size;
1214                         }
1215                         ASSERT3U(*size, >=, from_delta);
1216                         atomic_add_64(size, -from_delta);
1217 
1218                         if (use_mutex)
1219                                 mutex_exit(&old_state->arcs_mtx);
1220                 }
1221                 if (new_state != arc_anon) {
1222                         int use_mutex = !MUTEX_HELD(&new_state->arcs_mtx);
1223                         uint64_t *size = &new_state->arcs_lsize[ab->b_type];
1224 
1225                         if (use_mutex)
1226                                 mutex_enter(&new_state->arcs_mtx);
1227 
1228                         list_insert_head(&new_state->arcs_list[ab->b_type], ab);
1229 
1230                         /* ghost elements have a ghost size */
1231                         if (GHOST_STATE(new_state)) {
1232                                 ASSERT(ab->b_datacnt == 0);
1233                                 ASSERT(ab->b_buf == NULL);
1234                                 to_delta = ab->b_size;
1235                         }
1236                         atomic_add_64(size, to_delta);
1237 
1238                         if (use_mutex)
1239                                 mutex_exit(&new_state->arcs_mtx);
1240                 }
1241         }
1242 
1243         ASSERT(!BUF_EMPTY(ab));
1244         if (new_state == arc_anon && HDR_IN_HASH_TABLE(ab))
1245                 buf_hash_remove(ab);
1246 
1247         /* adjust state sizes */
1248         if (to_delta)
1249                 atomic_add_64(&new_state->arcs_size, to_delta);
1250         if (from_delta) {
1251                 ASSERT3U(old_state->arcs_size, >=, from_delta);
1252                 atomic_add_64(&old_state->arcs_size, -from_delta);
1253         }
1254         ab->b_state = new_state;
1255 
1256         /* adjust l2arc hdr stats */
1257         if (new_state == arc_l2c_only)
1258                 l2arc_hdr_stat_add();
1259         else if (old_state == arc_l2c_only)
1260                 l2arc_hdr_stat_remove();
1261 }
1262 
1263 void
1264 arc_space_consume(uint64_t space, arc_space_type_t type)
1265 {
1266         ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1267 
1268         switch (type) {
1269         case ARC_SPACE_DATA:
1270                 ARCSTAT_INCR(arcstat_data_size, space);
1271                 break;
1272         case ARC_SPACE_OTHER:
1273                 ARCSTAT_INCR(arcstat_other_size, space);
1274                 break;
1275         case ARC_SPACE_HDRS:
1276                 ARCSTAT_INCR(arcstat_hdr_size, space);
1277                 break;
1278         case ARC_SPACE_L2HDRS:
1279                 ARCSTAT_INCR(arcstat_l2_hdr_size, space);
1280                 break;
1281         }
1282 
1283         ARCSTAT_INCR(arcstat_meta_used, space);
1284         atomic_add_64(&arc_size, space);
1285 }
1286 
1287 void
1288 arc_space_return(uint64_t space, arc_space_type_t type)
1289 {
1290         ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1291 
1292         switch (type) {
1293         case ARC_SPACE_DATA:
1294                 ARCSTAT_INCR(arcstat_data_size, -space);
1295                 break;
1296         case ARC_SPACE_OTHER:
1297                 ARCSTAT_INCR(arcstat_other_size, -space);
1298                 break;
1299         case ARC_SPACE_HDRS:
1300                 ARCSTAT_INCR(arcstat_hdr_size, -space);
1301                 break;
1302         case ARC_SPACE_L2HDRS:
1303                 ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
1304                 break;
1305         }
1306 
1307         ASSERT(arc_meta_used >= space);
1308         if (arc_meta_max < arc_meta_used)
1309                 arc_meta_max = arc_meta_used;
1310         ARCSTAT_INCR(arcstat_meta_used, -space);
1311         ASSERT(arc_size >= space);
1312         atomic_add_64(&arc_size, -space);
1313 }
1314 
1315 void *
1316 arc_data_buf_alloc(uint64_t size)
1317 {
1318         if (arc_evict_needed(ARC_BUFC_DATA))
1319                 cv_signal(&arc_reclaim_thr_cv);
1320         atomic_add_64(&arc_size, size);
1321         return (zio_data_buf_alloc(size));
1322 }
1323 
1324 void
1325 arc_data_buf_free(void *buf, uint64_t size)
1326 {
1327         zio_data_buf_free(buf, size);
1328         ASSERT(arc_size >= size);
1329         atomic_add_64(&arc_size, -size);
1330 }
1331 
1332 arc_buf_t *
1333 arc_buf_alloc(spa_t *spa, int size, void *tag, arc_buf_contents_t type)
1334 {
1335         arc_buf_hdr_t *hdr;
1336         arc_buf_t *buf;
1337 
1338         ASSERT3U(size, >, 0);
1339         hdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
1340         ASSERT(BUF_EMPTY(hdr));
1341         hdr->b_size = size;
1342         hdr->b_type = type;
1343         hdr->b_spa = spa_load_guid(spa);
1344         hdr->b_state = arc_anon;
1345         hdr->b_arc_access = 0;
1346         buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1347         buf->b_hdr = hdr;
1348         buf->b_data = NULL;
1349         buf->b_efunc = NULL;
1350         buf->b_private = NULL;
1351         buf->b_next = NULL;
1352         hdr->b_buf = buf;
1353         arc_get_data_buf(buf);
1354         hdr->b_datacnt = 1;
1355         hdr->b_flags = 0;
1356         ASSERT(refcount_is_zero(&hdr->b_refcnt));
1357         (void) refcount_add(&hdr->b_refcnt, tag);
1358 
1359         return (buf);
1360 }
1361 
1362 static char *arc_onloan_tag = "onloan";
1363 
1364 /*
1365  * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
1366  * flight data by arc_tempreserve_space() until they are "returned". Loaned
1367  * buffers must be returned to the arc before they can be used by the DMU or
1368  * freed.
1369  */
1370 arc_buf_t *
1371 arc_loan_buf(spa_t *spa, int size)
1372 {
1373         arc_buf_t *buf;
1374 
1375         buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
1376 
1377         atomic_add_64(&arc_loaned_bytes, size);
1378         return (buf);
1379 }
1380 
1381 /*
1382  * Return a loaned arc buffer to the arc.
1383  */
1384 void
1385 arc_return_buf(arc_buf_t *buf, void *tag)
1386 {
1387         arc_buf_hdr_t *hdr = buf->b_hdr;
1388 
1389         ASSERT(buf->b_data != NULL);
1390         (void) refcount_add(&hdr->b_refcnt, tag);
1391         (void) refcount_remove(&hdr->b_refcnt, arc_onloan_tag);
1392 
1393         atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
1394 }
1395 
1396 /* Detach an arc_buf from a dbuf (tag) */
1397 void
1398 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
1399 {
1400         arc_buf_hdr_t *hdr;
1401 
1402         ASSERT(buf->b_data != NULL);
1403         hdr = buf->b_hdr;
1404         (void) refcount_add(&hdr->b_refcnt, arc_onloan_tag);
1405         (void) refcount_remove(&hdr->b_refcnt, tag);
1406         buf->b_efunc = NULL;
1407         buf->b_private = NULL;
1408 
1409         atomic_add_64(&arc_loaned_bytes, hdr->b_size);
1410 }
1411 
1412 static arc_buf_t *
1413 arc_buf_clone(arc_buf_t *from)
1414 {
1415         arc_buf_t *buf;
1416         arc_buf_hdr_t *hdr = from->b_hdr;
1417         uint64_t size = hdr->b_size;
1418 
1419         ASSERT(hdr->b_state != arc_anon);
1420 
1421         buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1422         buf->b_hdr = hdr;
1423         buf->b_data = NULL;
1424         buf->b_efunc = NULL;
1425         buf->b_private = NULL;
1426         buf->b_next = hdr->b_buf;
1427         hdr->b_buf = buf;
1428         arc_get_data_buf(buf);
1429         bcopy(from->b_data, buf->b_data, size);
1430 
1431         /*
1432          * This buffer already exists in the arc so create a duplicate
1433          * copy for the caller.  If the buffer is associated with user data
1434          * then track the size and number of duplicates.  These stats will be
1435          * updated as duplicate buffers are created and destroyed.
1436          */
1437         if (hdr->b_type == ARC_BUFC_DATA) {
1438                 ARCSTAT_BUMP(arcstat_duplicate_buffers);
1439                 ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
1440         }
1441         hdr->b_datacnt += 1;
1442         return (buf);
1443 }
1444 
1445 void
1446 arc_buf_add_ref(arc_buf_t *buf, void* tag)
1447 {
1448         arc_buf_hdr_t *hdr;
1449         kmutex_t *hash_lock;
1450 
1451         /*
1452          * Check to see if this buffer is evicted.  Callers
1453          * must verify b_data != NULL to know if the add_ref
1454          * was successful.
1455          */
1456         mutex_enter(&buf->b_evict_lock);
1457         if (buf->b_data == NULL) {
1458                 mutex_exit(&buf->b_evict_lock);
1459                 return;
1460         }
1461         hash_lock = HDR_LOCK(buf->b_hdr);
1462         mutex_enter(hash_lock);
1463         hdr = buf->b_hdr;
1464         ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1465         mutex_exit(&buf->b_evict_lock);
1466 
1467         ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
1468         add_reference(hdr, hash_lock, tag);
1469         DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
1470         arc_access(hdr, hash_lock);
1471         mutex_exit(hash_lock);
1472         ARCSTAT_BUMP(arcstat_hits);
1473         ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
1474             demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
1475             data, metadata, hits);
1476 }
1477 
1478 static void
1479 arc_buf_free_on_write(void *data, size_t size,
1480     void (*free_func)(void *, size_t))
1481 {
1482         l2arc_data_free_t *df;
1483 
1484         df = kmem_alloc(sizeof (l2arc_data_free_t), KM_SLEEP);
1485         df->l2df_data = data;
1486         df->l2df_size = size;
1487         df->l2df_func = free_func;
1488         mutex_enter(&l2arc_free_on_write_mtx);
1489         list_insert_head(l2arc_free_on_write, df);
1490         mutex_exit(&l2arc_free_on_write_mtx);
1491 }
1492 
1493 /*
1494  * Free the arc data buffer.  If it is an l2arc write in progress,
1495  * the buffer is placed on l2arc_free_on_write to be freed later.
1496  */
1497 static void
1498 arc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
1499 {
1500         arc_buf_hdr_t *hdr = buf->b_hdr;
1501 
1502         if (HDR_L2_WRITING(hdr)) {
1503                 arc_buf_free_on_write(buf->b_data, hdr->b_size, free_func);
1504                 ARCSTAT_BUMP(arcstat_l2_free_on_write);
1505         } else {
1506                 free_func(buf->b_data, hdr->b_size);
1507         }
1508 }
1509 
1510 /*
1511  * Free up buf->b_data and if 'remove' is set, then pull the
1512  * arc_buf_t off of the the arc_buf_hdr_t's list and free it.
1513  */
1514 static void
1515 arc_buf_l2_cdata_free(arc_buf_hdr_t *hdr)
1516 {
1517         l2arc_buf_hdr_t *l2hdr = hdr->b_l2hdr;
1518 
1519         ASSERT(MUTEX_HELD(&l2arc_buflist_mtx));
1520 
1521         if (l2hdr->b_tmp_cdata == NULL)
1522                 return;
1523 
1524         ASSERT(HDR_L2_WRITING(hdr));
1525         arc_buf_free_on_write(l2hdr->b_tmp_cdata, hdr->b_size,
1526             zio_data_buf_free);
1527         ARCSTAT_BUMP(arcstat_l2_cdata_free_on_write);
1528         l2hdr->b_tmp_cdata = NULL;
1529 }
1530 
1531 static void
1532 arc_buf_destroy(arc_buf_t *buf, boolean_t recycle, boolean_t remove)
1533 {
1534         arc_buf_t **bufp;
1535 
1536         /* free up data associated with the buf */
1537         if (buf->b_data) {
1538                 arc_state_t *state = buf->b_hdr->b_state;
1539                 uint64_t size = buf->b_hdr->b_size;
1540                 arc_buf_contents_t type = buf->b_hdr->b_type;
1541 
1542                 arc_cksum_verify(buf);
1543                 arc_buf_unwatch(buf);
1544 
1545                 if (!recycle) {
1546                         if (type == ARC_BUFC_METADATA) {
1547                                 arc_buf_data_free(buf, zio_buf_free);
1548                                 arc_space_return(size, ARC_SPACE_DATA);
1549                         } else {
1550                                 ASSERT(type == ARC_BUFC_DATA);
1551                                 arc_buf_data_free(buf, zio_data_buf_free);
1552                                 ARCSTAT_INCR(arcstat_data_size, -size);
1553                                 atomic_add_64(&arc_size, -size);
1554                         }
1555                 }
1556                 if (list_link_active(&buf->b_hdr->b_arc_node)) {
1557                         uint64_t *cnt = &state->arcs_lsize[type];
1558 
1559                         ASSERT(refcount_is_zero(&buf->b_hdr->b_refcnt));
1560                         ASSERT(state != arc_anon);
1561 
1562                         ASSERT3U(*cnt, >=, size);
1563                         atomic_add_64(cnt, -size);
1564                 }
1565                 ASSERT3U(state->arcs_size, >=, size);
1566                 atomic_add_64(&state->arcs_size, -size);
1567                 buf->b_data = NULL;
1568 
1569                 /*
1570                  * If we're destroying a duplicate buffer make sure
1571                  * that the appropriate statistics are updated.
1572                  */
1573                 if (buf->b_hdr->b_datacnt > 1 &&
1574                     buf->b_hdr->b_type == ARC_BUFC_DATA) {
1575                         ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
1576                         ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
1577                 }
1578                 ASSERT(buf->b_hdr->b_datacnt > 0);
1579                 buf->b_hdr->b_datacnt -= 1;
1580         }
1581 
1582         /* only remove the buf if requested */
1583         if (!remove)
1584                 return;
1585 
1586         /* remove the buf from the hdr list */
1587         for (bufp = &buf->b_hdr->b_buf; *bufp != buf; bufp = &(*bufp)->b_next)
1588                 continue;
1589         *bufp = buf->b_next;
1590         buf->b_next = NULL;
1591 
1592         ASSERT(buf->b_efunc == NULL);
1593 
1594         /* clean up the buf */
1595         buf->b_hdr = NULL;
1596         kmem_cache_free(buf_cache, buf);
1597 }
1598 
1599 static void
1600 arc_hdr_destroy(arc_buf_hdr_t *hdr)
1601 {
1602         ASSERT(refcount_is_zero(&hdr->b_refcnt));
1603         ASSERT3P(hdr->b_state, ==, arc_anon);
1604         ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1605         l2arc_buf_hdr_t *l2hdr = hdr->b_l2hdr;
1606 
1607         if (l2hdr != NULL) {
1608                 boolean_t buflist_held = MUTEX_HELD(&l2arc_buflist_mtx);
1609                 /*
1610                  * To prevent arc_free() and l2arc_evict() from
1611                  * attempting to free the same buffer at the same time,
1612                  * a FREE_IN_PROGRESS flag is given to arc_free() to
1613                  * give it priority.  l2arc_evict() can't destroy this
1614                  * header while we are waiting on l2arc_buflist_mtx.
1615                  *
1616                  * The hdr may be removed from l2ad_buflist before we
1617                  * grab l2arc_buflist_mtx, so b_l2hdr is rechecked.
1618                  */
1619                 if (!buflist_held) {
1620                         mutex_enter(&l2arc_buflist_mtx);
1621                         l2hdr = hdr->b_l2hdr;
1622                 }
1623 
1624                 if (l2hdr != NULL) {
1625                         list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
1626                         arc_buf_l2_cdata_free(hdr);
1627                         ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
1628                         ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
1629                         vdev_space_update(l2hdr->b_dev->l2ad_vdev,
1630                             -l2hdr->b_asize, 0, 0);
1631                         kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
1632                         if (hdr->b_state == arc_l2c_only)
1633                                 l2arc_hdr_stat_remove();
1634                         hdr->b_l2hdr = NULL;
1635                 }
1636 
1637                 if (!buflist_held)
1638                         mutex_exit(&l2arc_buflist_mtx);
1639         }
1640 
1641         if (!BUF_EMPTY(hdr)) {
1642                 ASSERT(!HDR_IN_HASH_TABLE(hdr));
1643                 buf_discard_identity(hdr);
1644         }
1645         while (hdr->b_buf) {
1646                 arc_buf_t *buf = hdr->b_buf;
1647 
1648                 if (buf->b_efunc) {
1649                         mutex_enter(&arc_eviction_mtx);
1650                         mutex_enter(&buf->b_evict_lock);
1651                         ASSERT(buf->b_hdr != NULL);
1652                         arc_buf_destroy(hdr->b_buf, FALSE, FALSE);
1653                         hdr->b_buf = buf->b_next;
1654                         buf->b_hdr = &arc_eviction_hdr;
1655                         buf->b_next = arc_eviction_list;
1656                         arc_eviction_list = buf;
1657                         mutex_exit(&buf->b_evict_lock);
1658                         mutex_exit(&arc_eviction_mtx);
1659                 } else {
1660                         arc_buf_destroy(hdr->b_buf, FALSE, TRUE);
1661                 }
1662         }
1663         if (hdr->b_freeze_cksum != NULL) {
1664                 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1665                 hdr->b_freeze_cksum = NULL;
1666         }
1667         if (hdr->b_thawed) {
1668                 kmem_free(hdr->b_thawed, 1);
1669                 hdr->b_thawed = NULL;
1670         }
1671 
1672         ASSERT(!list_link_active(&hdr->b_arc_node));
1673         ASSERT3P(hdr->b_hash_next, ==, NULL);
1674         ASSERT3P(hdr->b_acb, ==, NULL);
1675         kmem_cache_free(hdr_cache, hdr);
1676 }
1677 
1678 void
1679 arc_buf_free(arc_buf_t *buf, void *tag)
1680 {
1681         arc_buf_hdr_t *hdr = buf->b_hdr;
1682         int hashed = hdr->b_state != arc_anon;
1683 
1684         ASSERT(buf->b_efunc == NULL);
1685         ASSERT(buf->b_data != NULL);
1686 
1687         if (hashed) {
1688                 kmutex_t *hash_lock = HDR_LOCK(hdr);
1689 
1690                 mutex_enter(hash_lock);
1691                 hdr = buf->b_hdr;
1692                 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1693 
1694                 (void) remove_reference(hdr, hash_lock, tag);
1695                 if (hdr->b_datacnt > 1) {
1696                         arc_buf_destroy(buf, FALSE, TRUE);
1697                 } else {
1698                         ASSERT(buf == hdr->b_buf);
1699                         ASSERT(buf->b_efunc == NULL);
1700                         hdr->b_flags |= ARC_BUF_AVAILABLE;
1701                 }
1702                 mutex_exit(hash_lock);
1703         } else if (HDR_IO_IN_PROGRESS(hdr)) {
1704                 int destroy_hdr;
1705                 /*
1706                  * We are in the middle of an async write.  Don't destroy
1707                  * this buffer unless the write completes before we finish
1708                  * decrementing the reference count.
1709                  */
1710                 mutex_enter(&arc_eviction_mtx);
1711                 (void) remove_reference(hdr, NULL, tag);
1712                 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1713                 destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
1714                 mutex_exit(&arc_eviction_mtx);
1715                 if (destroy_hdr)
1716                         arc_hdr_destroy(hdr);
1717         } else {
1718                 if (remove_reference(hdr, NULL, tag) > 0)
1719                         arc_buf_destroy(buf, FALSE, TRUE);
1720                 else
1721                         arc_hdr_destroy(hdr);
1722         }
1723 }
1724 
1725 boolean_t
1726 arc_buf_remove_ref(arc_buf_t *buf, void* tag)
1727 {
1728         arc_buf_hdr_t *hdr = buf->b_hdr;
1729         kmutex_t *hash_lock = HDR_LOCK(hdr);
1730         boolean_t no_callback = (buf->b_efunc == NULL);
1731 
1732         if (hdr->b_state == arc_anon) {
1733                 ASSERT(hdr->b_datacnt == 1);
1734                 arc_buf_free(buf, tag);
1735                 return (no_callback);
1736         }
1737 
1738         mutex_enter(hash_lock);
1739         hdr = buf->b_hdr;
1740         ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1741         ASSERT(hdr->b_state != arc_anon);
1742         ASSERT(buf->b_data != NULL);
1743 
1744         (void) remove_reference(hdr, hash_lock, tag);
1745         if (hdr->b_datacnt > 1) {
1746                 if (no_callback)
1747                         arc_buf_destroy(buf, FALSE, TRUE);
1748         } else if (no_callback) {
1749                 ASSERT(hdr->b_buf == buf && buf->b_next == NULL);
1750                 ASSERT(buf->b_efunc == NULL);
1751                 hdr->b_flags |= ARC_BUF_AVAILABLE;
1752         }
1753         ASSERT(no_callback || hdr->b_datacnt > 1 ||
1754             refcount_is_zero(&hdr->b_refcnt));
1755         mutex_exit(hash_lock);
1756         return (no_callback);
1757 }
1758 
1759 int
1760 arc_buf_size(arc_buf_t *buf)
1761 {
1762         return (buf->b_hdr->b_size);
1763 }
1764 
1765 /*
1766  * Called from the DMU to determine if the current buffer should be
1767  * evicted. In order to ensure proper locking, the eviction must be initiated
1768  * from the DMU. Return true if the buffer is associated with user data and
1769  * duplicate buffers still exist.
1770  */
1771 boolean_t
1772 arc_buf_eviction_needed(arc_buf_t *buf)
1773 {
1774         arc_buf_hdr_t *hdr;
1775         boolean_t evict_needed = B_FALSE;
1776 
1777         if (zfs_disable_dup_eviction)
1778                 return (B_FALSE);
1779 
1780         mutex_enter(&buf->b_evict_lock);
1781         hdr = buf->b_hdr;
1782         if (hdr == NULL) {
1783                 /*
1784                  * We are in arc_do_user_evicts(); let that function
1785                  * perform the eviction.
1786                  */
1787                 ASSERT(buf->b_data == NULL);
1788                 mutex_exit(&buf->b_evict_lock);
1789                 return (B_FALSE);
1790         } else if (buf->b_data == NULL) {
1791                 /*
1792                  * We have already been added to the arc eviction list;
1793                  * recommend eviction.
1794                  */
1795                 ASSERT3P(hdr, ==, &arc_eviction_hdr);
1796                 mutex_exit(&buf->b_evict_lock);
1797                 return (B_TRUE);
1798         }
1799 
1800         if (hdr->b_datacnt > 1 && hdr->b_type == ARC_BUFC_DATA)
1801                 evict_needed = B_TRUE;
1802 
1803         mutex_exit(&buf->b_evict_lock);
1804         return (evict_needed);
1805 }
1806 
1807 /*
1808  * Evict buffers from list until we've removed the specified number of
1809  * bytes.  Move the removed buffers to the appropriate evict state.
1810  * If the recycle flag is set, then attempt to "recycle" a buffer:
1811  * - look for a buffer to evict that is `bytes' long.
1812  * - return the data block from this buffer rather than freeing it.
1813  * This flag is used by callers that are trying to make space for a
1814  * new buffer in a full arc cache.
1815  *
1816  * This function makes a "best effort".  It skips over any buffers
1817  * it can't get a hash_lock on, and so may not catch all candidates.
1818  * It may also return without evicting as much space as requested.
1819  */
1820 static void *
1821 arc_evict(arc_state_t *state, uint64_t spa, int64_t bytes, boolean_t recycle,
1822     arc_buf_contents_t type)
1823 {
1824         arc_state_t *evicted_state;
1825         uint64_t bytes_evicted = 0, skipped = 0, missed = 0;
1826         arc_buf_hdr_t *ab, *ab_prev = NULL;
1827         list_t *list = &state->arcs_list[type];
1828         kmutex_t *hash_lock;
1829         boolean_t have_lock;
1830         void *stolen = NULL;
1831         arc_buf_hdr_t marker = { 0 };
1832         int count = 0;
1833 
1834         ASSERT(state == arc_mru || state == arc_mfu);
1835 
1836         evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
1837 
1838         mutex_enter(&state->arcs_mtx);
1839         mutex_enter(&evicted_state->arcs_mtx);
1840 
1841         for (ab = list_tail(list); ab; ab = ab_prev) {
1842                 ab_prev = list_prev(list, ab);
1843                 /* prefetch buffers have a minimum lifespan */
1844                 if (HDR_IO_IN_PROGRESS(ab) ||
1845                     (spa && ab->b_spa != spa) ||
1846                     (ab->b_flags & (ARC_PREFETCH|ARC_INDIRECT) &&
1847                     ddi_get_lbolt() - ab->b_arc_access <
1848                     arc_min_prefetch_lifespan)) {
1849                         skipped++;
1850                         continue;
1851                 }
1852                 /* "lookahead" for better eviction candidate */
1853                 if (recycle && ab->b_size != bytes &&
1854                     ab_prev && ab_prev->b_size == bytes)
1855                         continue;
1856 
1857                 /* ignore markers */
1858                 if (ab->b_spa == 0)
1859                         continue;
1860 
1861                 /*
1862                  * It may take a long time to evict all the bufs requested.
1863                  * To avoid blocking all arc activity, periodically drop
1864                  * the arcs_mtx and give other threads a chance to run
1865                  * before reacquiring the lock.
1866                  *
1867                  * If we are looking for a buffer to recycle, we are in
1868                  * the hot code path, so don't sleep.
1869                  */
1870                 if (!recycle && count++ > arc_evict_iterations) {
1871                         list_insert_after(list, ab, &marker);
1872                         mutex_exit(&evicted_state->arcs_mtx);
1873                         mutex_exit(&state->arcs_mtx);
1874                         kpreempt(KPREEMPT_SYNC);
1875                         mutex_enter(&state->arcs_mtx);
1876                         mutex_enter(&evicted_state->arcs_mtx);
1877                         ab_prev = list_prev(list, &marker);
1878                         list_remove(list, &marker);
1879                         count = 0;
1880                         continue;
1881                 }
1882 
1883                 hash_lock = HDR_LOCK(ab);
1884                 have_lock = MUTEX_HELD(hash_lock);
1885                 if (have_lock || mutex_tryenter(hash_lock)) {
1886                         ASSERT0(refcount_count(&ab->b_refcnt));
1887                         ASSERT(ab->b_datacnt > 0);
1888                         while (ab->b_buf) {
1889                                 arc_buf_t *buf = ab->b_buf;
1890                                 if (!mutex_tryenter(&buf->b_evict_lock)) {
1891                                         missed += 1;
1892                                         break;
1893                                 }
1894                                 if (buf->b_data) {
1895                                         bytes_evicted += ab->b_size;
1896                                         if (recycle && ab->b_type == type &&
1897                                             ab->b_size == bytes &&
1898                                             !HDR_L2_WRITING(ab)) {
1899                                                 stolen = buf->b_data;
1900                                                 recycle = FALSE;
1901                                         }
1902                                 }
1903                                 if (buf->b_efunc) {
1904                                         mutex_enter(&arc_eviction_mtx);
1905                                         arc_buf_destroy(buf,
1906                                             buf->b_data == stolen, FALSE);
1907                                         ab->b_buf = buf->b_next;
1908                                         buf->b_hdr = &arc_eviction_hdr;
1909                                         buf->b_next = arc_eviction_list;
1910                                         arc_eviction_list = buf;
1911                                         mutex_exit(&arc_eviction_mtx);
1912                                         mutex_exit(&buf->b_evict_lock);
1913                                 } else {
1914                                         mutex_exit(&buf->b_evict_lock);
1915                                         arc_buf_destroy(buf,
1916                                             buf->b_data == stolen, TRUE);
1917                                 }
1918                         }
1919 
1920                         if (ab->b_l2hdr) {
1921                                 ARCSTAT_INCR(arcstat_evict_l2_cached,
1922                                     ab->b_size);
1923                         } else {
1924                                 if (l2arc_write_eligible(ab->b_spa, ab)) {
1925                                         ARCSTAT_INCR(arcstat_evict_l2_eligible,
1926                                             ab->b_size);
1927                                 } else {
1928                                         ARCSTAT_INCR(
1929                                             arcstat_evict_l2_ineligible,
1930                                             ab->b_size);
1931                                 }
1932                         }
1933 
1934                         if (ab->b_datacnt == 0) {
1935                                 arc_change_state(evicted_state, ab, hash_lock);
1936                                 ASSERT(HDR_IN_HASH_TABLE(ab));
1937                                 ab->b_flags |= ARC_IN_HASH_TABLE;
1938                                 ab->b_flags &= ~ARC_BUF_AVAILABLE;
1939                                 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, ab);
1940                         }
1941                         if (!have_lock)
1942                                 mutex_exit(hash_lock);
1943                         if (bytes >= 0 && bytes_evicted >= bytes)
1944                                 break;
1945                 } else {
1946                         missed += 1;
1947                 }
1948         }
1949 
1950         mutex_exit(&evicted_state->arcs_mtx);
1951         mutex_exit(&state->arcs_mtx);
1952 
1953         if (bytes_evicted < bytes)
1954                 dprintf("only evicted %lld bytes from %x",
1955                     (longlong_t)bytes_evicted, state);
1956 
1957         if (skipped)
1958                 ARCSTAT_INCR(arcstat_evict_skip, skipped);
1959 
1960         if (missed)
1961                 ARCSTAT_INCR(arcstat_mutex_miss, missed);
1962 
1963         /*
1964          * Note: we have just evicted some data into the ghost state,
1965          * potentially putting the ghost size over the desired size.  Rather
1966          * that evicting from the ghost list in this hot code path, leave
1967          * this chore to the arc_reclaim_thread().
1968          */
1969 
1970         return (stolen);
1971 }
1972 
1973 /*
1974  * Remove buffers from list until we've removed the specified number of
1975  * bytes.  Destroy the buffers that are removed.
1976  */
1977 static void
1978 arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes)
1979 {
1980         arc_buf_hdr_t *ab, *ab_prev;
1981         arc_buf_hdr_t marker = { 0 };
1982         list_t *list = &state->arcs_list[ARC_BUFC_DATA];
1983         kmutex_t *hash_lock;
1984         uint64_t bytes_deleted = 0;
1985         uint64_t bufs_skipped = 0;
1986         int count = 0;
1987 
1988         ASSERT(GHOST_STATE(state));
1989 top:
1990         mutex_enter(&state->arcs_mtx);
1991         for (ab = list_tail(list); ab; ab = ab_prev) {
1992                 ab_prev = list_prev(list, ab);
1993                 if (ab->b_type > ARC_BUFC_NUMTYPES)
1994                         panic("invalid ab=%p", (void *)ab);
1995                 if (spa && ab->b_spa != spa)
1996                         continue;
1997 
1998                 /* ignore markers */
1999                 if (ab->b_spa == 0)
2000                         continue;
2001 
2002                 hash_lock = HDR_LOCK(ab);
2003                 /* caller may be trying to modify this buffer, skip it */
2004                 if (MUTEX_HELD(hash_lock))
2005                         continue;
2006 
2007                 /*
2008                  * It may take a long time to evict all the bufs requested.
2009                  * To avoid blocking all arc activity, periodically drop
2010                  * the arcs_mtx and give other threads a chance to run
2011                  * before reacquiring the lock.
2012                  */
2013                 if (count++ > arc_evict_iterations) {
2014                         list_insert_after(list, ab, &marker);
2015                         mutex_exit(&state->arcs_mtx);
2016                         kpreempt(KPREEMPT_SYNC);
2017                         mutex_enter(&state->arcs_mtx);
2018                         ab_prev = list_prev(list, &marker);
2019                         list_remove(list, &marker);
2020                         count = 0;
2021                         continue;
2022                 }
2023                 if (mutex_tryenter(hash_lock)) {
2024                         ASSERT(!HDR_IO_IN_PROGRESS(ab));
2025                         ASSERT(ab->b_buf == NULL);
2026                         ARCSTAT_BUMP(arcstat_deleted);
2027                         bytes_deleted += ab->b_size;
2028 
2029                         if (ab->b_l2hdr != NULL) {
2030                                 /*
2031                                  * This buffer is cached on the 2nd Level ARC;
2032                                  * don't destroy the header.
2033                                  */
2034                                 arc_change_state(arc_l2c_only, ab, hash_lock);
2035                                 mutex_exit(hash_lock);
2036                         } else {
2037                                 arc_change_state(arc_anon, ab, hash_lock);
2038                                 mutex_exit(hash_lock);
2039                                 arc_hdr_destroy(ab);
2040                         }
2041 
2042                         DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, ab);
2043                         if (bytes >= 0 && bytes_deleted >= bytes)
2044                                 break;
2045                 } else if (bytes < 0) {
2046                         /*
2047                          * Insert a list marker and then wait for the
2048                          * hash lock to become available. Once its
2049                          * available, restart from where we left off.
2050                          */
2051                         list_insert_after(list, ab, &marker);
2052                         mutex_exit(&state->arcs_mtx);
2053                         mutex_enter(hash_lock);
2054                         mutex_exit(hash_lock);
2055                         mutex_enter(&state->arcs_mtx);
2056                         ab_prev = list_prev(list, &marker);
2057                         list_remove(list, &marker);
2058                 } else {
2059                         bufs_skipped += 1;
2060                 }
2061 
2062         }
2063         mutex_exit(&state->arcs_mtx);
2064 
2065         if (list == &state->arcs_list[ARC_BUFC_DATA] &&
2066             (bytes < 0 || bytes_deleted < bytes)) {
2067                 list = &state->arcs_list[ARC_BUFC_METADATA];
2068                 goto top;
2069         }
2070 
2071         if (bufs_skipped) {
2072                 ARCSTAT_INCR(arcstat_mutex_miss, bufs_skipped);
2073                 ASSERT(bytes >= 0);
2074         }
2075 
2076         if (bytes_deleted < bytes)
2077                 dprintf("only deleted %lld bytes from %p",
2078                     (longlong_t)bytes_deleted, state);
2079 }
2080 
2081 static void
2082 arc_adjust(void)
2083 {
2084         int64_t adjustment, delta;
2085 
2086         /*
2087          * Adjust MRU size
2088          */
2089 
2090         adjustment = MIN((int64_t)(arc_size - arc_c),
2091             (int64_t)(arc_anon->arcs_size + arc_mru->arcs_size + arc_meta_used -
2092             arc_p));
2093 
2094         if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_DATA] > 0) {
2095                 delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_DATA], adjustment);
2096                 (void) arc_evict(arc_mru, NULL, delta, FALSE, ARC_BUFC_DATA);
2097                 adjustment -= delta;
2098         }
2099 
2100         if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2101                 delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_METADATA], adjustment);
2102                 (void) arc_evict(arc_mru, NULL, delta, FALSE,
2103                     ARC_BUFC_METADATA);
2104         }
2105 
2106         /*
2107          * Adjust MFU size
2108          */
2109 
2110         adjustment = arc_size - arc_c;
2111 
2112         if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_DATA] > 0) {
2113                 delta = MIN(adjustment, arc_mfu->arcs_lsize[ARC_BUFC_DATA]);
2114                 (void) arc_evict(arc_mfu, NULL, delta, FALSE, ARC_BUFC_DATA);
2115                 adjustment -= delta;
2116         }
2117 
2118         if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2119                 int64_t delta = MIN(adjustment,
2120                     arc_mfu->arcs_lsize[ARC_BUFC_METADATA]);
2121                 (void) arc_evict(arc_mfu, NULL, delta, FALSE,
2122                     ARC_BUFC_METADATA);
2123         }
2124 
2125         /*
2126          * Adjust ghost lists
2127          */
2128 
2129         adjustment = arc_mru->arcs_size + arc_mru_ghost->arcs_size - arc_c;
2130 
2131         if (adjustment > 0 && arc_mru_ghost->arcs_size > 0) {
2132                 delta = MIN(arc_mru_ghost->arcs_size, adjustment);
2133                 arc_evict_ghost(arc_mru_ghost, NULL, delta);
2134         }
2135 
2136         adjustment =
2137             arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size - arc_c;
2138 
2139         if (adjustment > 0 && arc_mfu_ghost->arcs_size > 0) {
2140                 delta = MIN(arc_mfu_ghost->arcs_size, adjustment);
2141                 arc_evict_ghost(arc_mfu_ghost, NULL, delta);
2142         }
2143 }
2144 
2145 static void
2146 arc_do_user_evicts(void)
2147 {
2148         mutex_enter(&arc_eviction_mtx);
2149         while (arc_eviction_list != NULL) {
2150                 arc_buf_t *buf = arc_eviction_list;
2151                 arc_eviction_list = buf->b_next;
2152                 mutex_enter(&buf->b_evict_lock);
2153                 buf->b_hdr = NULL;
2154                 mutex_exit(&buf->b_evict_lock);
2155                 mutex_exit(&arc_eviction_mtx);
2156 
2157                 if (buf->b_efunc != NULL)
2158                         VERIFY0(buf->b_efunc(buf->b_private));
2159 
2160                 buf->b_efunc = NULL;
2161                 buf->b_private = NULL;
2162                 kmem_cache_free(buf_cache, buf);
2163                 mutex_enter(&arc_eviction_mtx);
2164         }
2165         mutex_exit(&arc_eviction_mtx);
2166 }
2167 
2168 /*
2169  * Flush all *evictable* data from the cache for the given spa.
2170  * NOTE: this will not touch "active" (i.e. referenced) data.
2171  */
2172 void
2173 arc_flush(spa_t *spa)
2174 {
2175         uint64_t guid = 0;
2176 
2177         if (spa)
2178                 guid = spa_load_guid(spa);
2179 
2180         while (list_head(&arc_mru->arcs_list[ARC_BUFC_DATA])) {
2181                 (void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_DATA);
2182                 if (spa)
2183                         break;
2184         }
2185         while (list_head(&arc_mru->arcs_list[ARC_BUFC_METADATA])) {
2186                 (void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_METADATA);
2187                 if (spa)
2188                         break;
2189         }
2190         while (list_head(&arc_mfu->arcs_list[ARC_BUFC_DATA])) {
2191                 (void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_DATA);
2192                 if (spa)
2193                         break;
2194         }
2195         while (list_head(&arc_mfu->arcs_list[ARC_BUFC_METADATA])) {
2196                 (void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_METADATA);
2197                 if (spa)
2198                         break;
2199         }
2200 
2201         arc_evict_ghost(arc_mru_ghost, guid, -1);
2202         arc_evict_ghost(arc_mfu_ghost, guid, -1);
2203 
2204         mutex_enter(&arc_reclaim_thr_lock);
2205         arc_do_user_evicts();
2206         mutex_exit(&arc_reclaim_thr_lock);
2207         ASSERT(spa || arc_eviction_list == NULL);
2208 }
2209 
2210 void
2211 arc_shrink(void)
2212 {
2213         if (arc_c > arc_c_min) {
2214                 uint64_t to_free;
2215 
2216 #ifdef _KERNEL
2217                 to_free = MAX(arc_c >> arc_shrink_shift, ptob(needfree));
2218 #else
2219                 to_free = arc_c >> arc_shrink_shift;
2220 #endif
2221                 if (arc_c > arc_c_min + to_free)
2222                         atomic_add_64(&arc_c, -to_free);
2223                 else
2224                         arc_c = arc_c_min;
2225 
2226                 atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
2227                 if (arc_c > arc_size)
2228                         arc_c = MAX(arc_size, arc_c_min);
2229                 if (arc_p > arc_c)
2230                         arc_p = (arc_c >> 1);
2231                 ASSERT(arc_c >= arc_c_min);
2232                 ASSERT((int64_t)arc_p >= 0);
2233         }
2234 
2235         if (arc_size > arc_c)
2236                 arc_adjust();
2237 }
2238 
2239 /*
2240  * Determine if the system is under memory pressure and is asking
2241  * to reclaim memory. A return value of 1 indicates that the system
2242  * is under memory pressure and that the arc should adjust accordingly.
2243  */
2244 static int
2245 arc_reclaim_needed(void)
2246 {
2247         uint64_t extra;
2248 
2249 #ifdef _KERNEL
2250 
2251         if (needfree)
2252                 return (1);
2253 
2254         /*
2255          * take 'desfree' extra pages, so we reclaim sooner, rather than later
2256          */
2257         extra = desfree;
2258 
2259         /*
2260          * check that we're out of range of the pageout scanner.  It starts to
2261          * schedule paging if freemem is less than lotsfree and needfree.
2262          * lotsfree is the high-water mark for pageout, and needfree is the
2263          * number of needed free pages.  We add extra pages here to make sure
2264          * the scanner doesn't start up while we're freeing memory.
2265          */
2266         if (freemem < lotsfree + needfree + extra)
2267                 return (1);
2268 
2269         /*
2270          * check to make sure that swapfs has enough space so that anon
2271          * reservations can still succeed. anon_resvmem() checks that the
2272          * availrmem is greater than swapfs_minfree, and the number of reserved
2273          * swap pages.  We also add a bit of extra here just to prevent
2274          * circumstances from getting really dire.
2275          */
2276         if (availrmem < swapfs_minfree + swapfs_reserve + extra)
2277                 return (1);
2278 
2279         /*
2280          * Check that we have enough availrmem that memory locking (e.g., via
2281          * mlock(3C) or memcntl(2)) can still succeed.  (pages_pp_maximum
2282          * stores the number of pages that cannot be locked; when availrmem
2283          * drops below pages_pp_maximum, page locking mechanisms such as
2284          * page_pp_lock() will fail.)
2285          */
2286         if (availrmem <= pages_pp_maximum)
2287                 return (1);
2288 
2289 #if defined(__i386)
2290         /*
2291          * If we're on an i386 platform, it's possible that we'll exhaust the
2292          * kernel heap space before we ever run out of available physical
2293          * memory.  Most checks of the size of the heap_area compare against
2294          * tune.t_minarmem, which is the minimum available real memory that we
2295          * can have in the system.  However, this is generally fixed at 25 pages
2296          * which is so low that it's useless.  In this comparison, we seek to
2297          * calculate the total heap-size, and reclaim if more than 3/4ths of the
2298          * heap is allocated.  (Or, in the calculation, if less than 1/4th is
2299          * free)
2300          */
2301         if (vmem_size(heap_arena, VMEM_FREE) <
2302             (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2))
2303                 return (1);
2304 #endif
2305 
2306         /*
2307          * If zio data pages are being allocated out of a separate heap segment,
2308          * then enforce that the size of available vmem for this arena remains
2309          * above about 1/16th free.
2310          *
2311          * Note: The 1/16th arena free requirement was put in place
2312          * to aggressively evict memory from the arc in order to avoid
2313          * memory fragmentation issues.
2314          */
2315         if (zio_arena != NULL &&
2316             vmem_size(zio_arena, VMEM_FREE) <
2317             (vmem_size(zio_arena, VMEM_ALLOC) >> 4))
2318                 return (1);
2319 #else
2320         if (spa_get_random(100) == 0)
2321                 return (1);
2322 #endif
2323         return (0);
2324 }
2325 
2326 static void
2327 arc_kmem_reap_now(arc_reclaim_strategy_t strat)
2328 {
2329         size_t                  i;
2330         kmem_cache_t            *prev_cache = NULL;
2331         kmem_cache_t            *prev_data_cache = NULL;
2332         extern kmem_cache_t     *zio_buf_cache[];
2333         extern kmem_cache_t     *zio_data_buf_cache[];
2334         extern kmem_cache_t     *range_seg_cache;
2335 
2336 #ifdef _KERNEL
2337         if (arc_meta_used >= arc_meta_limit) {
2338                 /*
2339                  * We are exceeding our meta-data cache limit.
2340                  * Purge some DNLC entries to release holds on meta-data.
2341                  */
2342                 dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
2343         }
2344 #if defined(__i386)
2345         /*
2346          * Reclaim unused memory from all kmem caches.
2347          */
2348         kmem_reap();
2349 #endif
2350 #endif
2351 
2352         /*
2353          * An aggressive reclamation will shrink the cache size as well as
2354          * reap free buffers from the arc kmem caches.
2355          */
2356         if (strat == ARC_RECLAIM_AGGR)
2357                 arc_shrink();
2358 
2359         for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
2360                 if (zio_buf_cache[i] != prev_cache) {
2361                         prev_cache = zio_buf_cache[i];
2362                         kmem_cache_reap_now(zio_buf_cache[i]);
2363                 }
2364                 if (zio_data_buf_cache[i] != prev_data_cache) {
2365                         prev_data_cache = zio_data_buf_cache[i];
2366                         kmem_cache_reap_now(zio_data_buf_cache[i]);
2367                 }
2368         }
2369         kmem_cache_reap_now(buf_cache);
2370         kmem_cache_reap_now(hdr_cache);
2371         kmem_cache_reap_now(range_seg_cache);
2372 
2373         /*
2374          * Ask the vmem areana to reclaim unused memory from its
2375          * quantum caches.
2376          */
2377         if (zio_arena != NULL && strat == ARC_RECLAIM_AGGR)
2378                 vmem_qcache_reap(zio_arena);
2379 }
2380 
2381 static void
2382 arc_reclaim_thread(void)
2383 {
2384         clock_t                 growtime = 0;
2385         arc_reclaim_strategy_t  last_reclaim = ARC_RECLAIM_CONS;
2386         callb_cpr_t             cpr;
2387 
2388         CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
2389 
2390         mutex_enter(&arc_reclaim_thr_lock);
2391         while (arc_thread_exit == 0) {
2392                 if (arc_reclaim_needed()) {
2393 
2394                         if (arc_no_grow) {
2395                                 if (last_reclaim == ARC_RECLAIM_CONS) {
2396                                         last_reclaim = ARC_RECLAIM_AGGR;
2397                                 } else {
2398                                         last_reclaim = ARC_RECLAIM_CONS;
2399                                 }
2400                         } else {
2401                                 arc_no_grow = TRUE;
2402                                 last_reclaim = ARC_RECLAIM_AGGR;
2403                                 membar_producer();
2404                         }
2405 
2406                         /* reset the growth delay for every reclaim */
2407                         growtime = ddi_get_lbolt() + (arc_grow_retry * hz);
2408 
2409                         arc_kmem_reap_now(last_reclaim);
2410                         arc_warm = B_TRUE;
2411 
2412                 } else if (arc_no_grow && ddi_get_lbolt() >= growtime) {
2413                         arc_no_grow = FALSE;
2414                 }
2415 
2416                 arc_adjust();
2417 
2418                 if (arc_eviction_list != NULL)
2419                         arc_do_user_evicts();
2420 
2421                 /* block until needed, or one second, whichever is shorter */
2422                 CALLB_CPR_SAFE_BEGIN(&cpr);
2423                 (void) cv_timedwait(&arc_reclaim_thr_cv,
2424                     &arc_reclaim_thr_lock, (ddi_get_lbolt() + hz));
2425                 CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
2426         }
2427 
2428         arc_thread_exit = 0;
2429         cv_broadcast(&arc_reclaim_thr_cv);
2430         CALLB_CPR_EXIT(&cpr);               /* drops arc_reclaim_thr_lock */
2431         thread_exit();
2432 }
2433 
2434 /*
2435  * Adapt arc info given the number of bytes we are trying to add and
2436  * the state that we are comming from.  This function is only called
2437  * when we are adding new content to the cache.
2438  */
2439 static void
2440 arc_adapt(int bytes, arc_state_t *state)
2441 {
2442         int mult;
2443         uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
2444 
2445         if (state == arc_l2c_only)
2446                 return;
2447 
2448         ASSERT(bytes > 0);
2449         /*
2450          * Adapt the target size of the MRU list:
2451          *      - if we just hit in the MRU ghost list, then increase
2452          *        the target size of the MRU list.
2453          *      - if we just hit in the MFU ghost list, then increase
2454          *        the target size of the MFU list by decreasing the
2455          *        target size of the MRU list.
2456          */
2457         if (state == arc_mru_ghost) {
2458                 mult = ((arc_mru_ghost->arcs_size >= arc_mfu_ghost->arcs_size) ?
2459                     1 : (arc_mfu_ghost->arcs_size/arc_mru_ghost->arcs_size));
2460                 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
2461 
2462                 arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
2463         } else if (state == arc_mfu_ghost) {
2464                 uint64_t delta;
2465 
2466                 mult = ((arc_mfu_ghost->arcs_size >= arc_mru_ghost->arcs_size) ?
2467                     1 : (arc_mru_ghost->arcs_size/arc_mfu_ghost->arcs_size));
2468                 mult = MIN(mult, 10);
2469 
2470                 delta = MIN(bytes * mult, arc_p);
2471                 arc_p = MAX(arc_p_min, arc_p - delta);
2472         }
2473         ASSERT((int64_t)arc_p >= 0);
2474 
2475         if (arc_reclaim_needed()) {
2476                 cv_signal(&arc_reclaim_thr_cv);
2477                 return;
2478         }
2479 
2480         if (arc_no_grow)
2481                 return;
2482 
2483         if (arc_c >= arc_c_max)
2484                 return;
2485 
2486         /*
2487          * If we're within (2 * maxblocksize) bytes of the target
2488          * cache size, increment the target cache size
2489          */
2490         if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
2491                 atomic_add_64(&arc_c, (int64_t)bytes);
2492                 if (arc_c > arc_c_max)
2493                         arc_c = arc_c_max;
2494                 else if (state == arc_anon)
2495                         atomic_add_64(&arc_p, (int64_t)bytes);
2496                 if (arc_p > arc_c)
2497                         arc_p = arc_c;
2498         }
2499         ASSERT((int64_t)arc_p >= 0);
2500 }
2501 
2502 /*
2503  * Check if the cache has reached its limits and eviction is required
2504  * prior to insert.
2505  */
2506 static int
2507 arc_evict_needed(arc_buf_contents_t type)
2508 {
2509         if (type == ARC_BUFC_METADATA && arc_meta_used >= arc_meta_limit)
2510                 return (1);
2511 
2512         if (arc_reclaim_needed())
2513                 return (1);
2514 
2515         return (arc_size > arc_c);
2516 }
2517 
2518 /*
2519  * The buffer, supplied as the first argument, needs a data block.
2520  * So, if we are at cache max, determine which cache should be victimized.
2521  * We have the following cases:
2522  *
2523  * 1. Insert for MRU, p > sizeof(arc_anon + arc_mru) ->
2524  * In this situation if we're out of space, but the resident size of the MFU is
2525  * under the limit, victimize the MFU cache to satisfy this insertion request.
2526  *
2527  * 2. Insert for MRU, p <= sizeof(arc_anon + arc_mru) ->
2528  * Here, we've used up all of the available space for the MRU, so we need to
2529  * evict from our own cache instead.  Evict from the set of resident MRU
2530  * entries.
2531  *
2532  * 3. Insert for MFU (c - p) > sizeof(arc_mfu) ->
2533  * c minus p represents the MFU space in the cache, since p is the size of the
2534  * cache that is dedicated to the MRU.  In this situation there's still space on
2535  * the MFU side, so the MRU side needs to be victimized.
2536  *
2537  * 4. Insert for MFU (c - p) < sizeof(arc_mfu) ->
2538  * MFU's resident set is consuming more space than it has been allotted.  In
2539  * this situation, we must victimize our own cache, the MFU, for this insertion.
2540  */
2541 static void
2542 arc_get_data_buf(arc_buf_t *buf)
2543 {
2544         arc_state_t             *state = buf->b_hdr->b_state;
2545         uint64_t                size = buf->b_hdr->b_size;
2546         arc_buf_contents_t      type = buf->b_hdr->b_type;
2547 
2548         arc_adapt(size, state);
2549 
2550         /*
2551          * We have not yet reached cache maximum size,
2552          * just allocate a new buffer.
2553          */
2554         if (!arc_evict_needed(type)) {
2555                 if (type == ARC_BUFC_METADATA) {
2556                         buf->b_data = zio_buf_alloc(size);
2557                         arc_space_consume(size, ARC_SPACE_DATA);
2558                 } else {
2559                         ASSERT(type == ARC_BUFC_DATA);
2560                         buf->b_data = zio_data_buf_alloc(size);
2561                         ARCSTAT_INCR(arcstat_data_size, size);
2562                         atomic_add_64(&arc_size, size);
2563                 }
2564                 goto out;
2565         }
2566 
2567         /*
2568          * If we are prefetching from the mfu ghost list, this buffer
2569          * will end up on the mru list; so steal space from there.
2570          */
2571         if (state == arc_mfu_ghost)
2572                 state = buf->b_hdr->b_flags & ARC_PREFETCH ? arc_mru : arc_mfu;
2573         else if (state == arc_mru_ghost)
2574                 state = arc_mru;
2575 
2576         if (state == arc_mru || state == arc_anon) {
2577                 uint64_t mru_used = arc_anon->arcs_size + arc_mru->arcs_size;
2578                 state = (arc_mfu->arcs_lsize[type] >= size &&
2579                     arc_p > mru_used) ? arc_mfu : arc_mru;
2580         } else {
2581                 /* MFU cases */
2582                 uint64_t mfu_space = arc_c - arc_p;
2583                 state =  (arc_mru->arcs_lsize[type] >= size &&
2584                     mfu_space > arc_mfu->arcs_size) ? arc_mru : arc_mfu;
2585         }
2586         if ((buf->b_data = arc_evict(state, NULL, size, TRUE, type)) == NULL) {
2587                 if (type == ARC_BUFC_METADATA) {
2588                         buf->b_data = zio_buf_alloc(size);
2589                         arc_space_consume(size, ARC_SPACE_DATA);
2590                 } else {
2591                         ASSERT(type == ARC_BUFC_DATA);
2592                         buf->b_data = zio_data_buf_alloc(size);
2593                         ARCSTAT_INCR(arcstat_data_size, size);
2594                         atomic_add_64(&arc_size, size);
2595                 }
2596                 ARCSTAT_BUMP(arcstat_recycle_miss);
2597         }
2598         ASSERT(buf->b_data != NULL);
2599 out:
2600         /*
2601          * Update the state size.  Note that ghost states have a
2602          * "ghost size" and so don't need to be updated.
2603          */
2604         if (!GHOST_STATE(buf->b_hdr->b_state)) {
2605                 arc_buf_hdr_t *hdr = buf->b_hdr;
2606 
2607                 atomic_add_64(&hdr->b_state->arcs_size, size);
2608                 if (list_link_active(&hdr->b_arc_node)) {
2609                         ASSERT(refcount_is_zero(&hdr->b_refcnt));
2610                         atomic_add_64(&hdr->b_state->arcs_lsize[type], size);
2611                 }
2612                 /*
2613                  * If we are growing the cache, and we are adding anonymous
2614                  * data, and we have outgrown arc_p, update arc_p
2615                  */
2616                 if (arc_size < arc_c && hdr->b_state == arc_anon &&
2617                     arc_anon->arcs_size + arc_mru->arcs_size > arc_p)
2618                         arc_p = MIN(arc_c, arc_p + size);
2619         }
2620 }
2621 
2622 /*
2623  * This routine is called whenever a buffer is accessed.
2624  * NOTE: the hash lock is dropped in this function.
2625  */
2626 static void
2627 arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock)
2628 {
2629         clock_t now;
2630 
2631         ASSERT(MUTEX_HELD(hash_lock));
2632 
2633         if (buf->b_state == arc_anon) {
2634                 /*
2635                  * This buffer is not in the cache, and does not
2636                  * appear in our "ghost" list.  Add the new buffer
2637                  * to the MRU state.
2638                  */
2639 
2640                 ASSERT(buf->b_arc_access == 0);
2641                 buf->b_arc_access = ddi_get_lbolt();
2642                 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2643                 arc_change_state(arc_mru, buf, hash_lock);
2644 
2645         } else if (buf->b_state == arc_mru) {
2646                 now = ddi_get_lbolt();
2647 
2648                 /*
2649                  * If this buffer is here because of a prefetch, then either:
2650                  * - clear the flag if this is a "referencing" read
2651                  *   (any subsequent access will bump this into the MFU state).
2652                  * or
2653                  * - move the buffer to the head of the list if this is
2654                  *   another prefetch (to make it less likely to be evicted).
2655                  */
2656                 if ((buf->b_flags & ARC_PREFETCH) != 0) {
2657                         if (refcount_count(&buf->b_refcnt) == 0) {
2658                                 ASSERT(list_link_active(&buf->b_arc_node));
2659                         } else {
2660                                 buf->b_flags &= ~ARC_PREFETCH;
2661                                 ARCSTAT_BUMP(arcstat_mru_hits);
2662                         }
2663                         buf->b_arc_access = now;
2664                         return;
2665                 }
2666 
2667                 /*
2668                  * This buffer has been "accessed" only once so far,
2669                  * but it is still in the cache. Move it to the MFU
2670                  * state.
2671                  */
2672                 if (now > buf->b_arc_access + ARC_MINTIME) {
2673                         /*
2674                          * More than 125ms have passed since we
2675                          * instantiated this buffer.  Move it to the
2676                          * most frequently used state.
2677                          */
2678                         buf->b_arc_access = now;
2679                         DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2680                         arc_change_state(arc_mfu, buf, hash_lock);
2681                 }
2682                 ARCSTAT_BUMP(arcstat_mru_hits);
2683         } else if (buf->b_state == arc_mru_ghost) {
2684                 arc_state_t     *new_state;
2685                 /*
2686                  * This buffer has been "accessed" recently, but
2687                  * was evicted from the cache.  Move it to the
2688                  * MFU state.
2689                  */
2690 
2691                 if (buf->b_flags & ARC_PREFETCH) {
2692                         new_state = arc_mru;
2693                         if (refcount_count(&buf->b_refcnt) > 0)
2694                                 buf->b_flags &= ~ARC_PREFETCH;
2695                         DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2696                 } else {
2697                         new_state = arc_mfu;
2698                         DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2699                 }
2700 
2701                 buf->b_arc_access = ddi_get_lbolt();
2702                 arc_change_state(new_state, buf, hash_lock);
2703 
2704                 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
2705         } else if (buf->b_state == arc_mfu) {
2706                 /*
2707                  * This buffer has been accessed more than once and is
2708                  * still in the cache.  Keep it in the MFU state.
2709                  *
2710                  * NOTE: an add_reference() that occurred when we did
2711                  * the arc_read() will have kicked this off the list.
2712                  * If it was a prefetch, we will explicitly move it to
2713                  * the head of the list now.
2714                  */
2715                 if ((buf->b_flags & ARC_PREFETCH) != 0) {
2716                         ASSERT(refcount_count(&buf->b_refcnt) == 0);
2717                         ASSERT(list_link_active(&buf->b_arc_node));
2718                 }
2719                 ARCSTAT_BUMP(arcstat_mfu_hits);
2720                 buf->b_arc_access = ddi_get_lbolt();
2721         } else if (buf->b_state == arc_mfu_ghost) {
2722                 arc_state_t     *new_state = arc_mfu;
2723                 /*
2724                  * This buffer has been accessed more than once but has
2725                  * been evicted from the cache.  Move it back to the
2726                  * MFU state.
2727                  */
2728 
2729                 if (buf->b_flags & ARC_PREFETCH) {
2730                         /*
2731                          * This is a prefetch access...
2732                          * move this block back to the MRU state.
2733                          */
2734                         ASSERT0(refcount_count(&buf->b_refcnt));
2735                         new_state = arc_mru;
2736                 }
2737 
2738                 buf->b_arc_access = ddi_get_lbolt();
2739                 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2740                 arc_change_state(new_state, buf, hash_lock);
2741 
2742                 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
2743         } else if (buf->b_state == arc_l2c_only) {
2744                 /*
2745                  * This buffer is on the 2nd Level ARC.
2746                  */
2747 
2748                 buf->b_arc_access = ddi_get_lbolt();
2749                 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2750                 arc_change_state(arc_mfu, buf, hash_lock);
2751         } else {
2752                 ASSERT(!"invalid arc state");
2753         }
2754 }
2755 
2756 /* a generic arc_done_func_t which you can use */
2757 /* ARGSUSED */
2758 void
2759 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
2760 {
2761         if (zio == NULL || zio->io_error == 0)
2762                 bcopy(buf->b_data, arg, buf->b_hdr->b_size);
2763         VERIFY(arc_buf_remove_ref(buf, arg));
2764 }
2765 
2766 /* a generic arc_done_func_t */
2767 void
2768 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
2769 {
2770         arc_buf_t **bufp = arg;
2771         if (zio && zio->io_error) {
2772                 VERIFY(arc_buf_remove_ref(buf, arg));
2773                 *bufp = NULL;
2774         } else {
2775                 *bufp = buf;
2776                 ASSERT(buf->b_data);
2777         }
2778 }
2779 
2780 static void
2781 arc_read_done(zio_t *zio)
2782 {
2783         arc_buf_hdr_t   *hdr;
2784         arc_buf_t       *buf;
2785         arc_buf_t       *abuf;  /* buffer we're assigning to callback */
2786         kmutex_t        *hash_lock = NULL;
2787         arc_callback_t  *callback_list, *acb;
2788         int             freeable = FALSE;
2789 
2790         buf = zio->io_private;
2791         hdr = buf->b_hdr;
2792 
2793         /*
2794          * The hdr was inserted into hash-table and removed from lists
2795          * prior to starting I/O.  We should find this header, since
2796          * it's in the hash table, and it should be legit since it's
2797          * not possible to evict it during the I/O.  The only possible
2798          * reason for it not to be found is if we were freed during the
2799          * read.
2800          */
2801         if (HDR_IN_HASH_TABLE(hdr)) {
2802                 ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
2803                 ASSERT3U(hdr->b_dva.dva_word[0], ==,
2804                     BP_IDENTITY(zio->io_bp)->dva_word[0]);
2805                 ASSERT3U(hdr->b_dva.dva_word[1], ==,
2806                     BP_IDENTITY(zio->io_bp)->dva_word[1]);
2807 
2808                 arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
2809                     &hash_lock);
2810 
2811                 ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) &&
2812                     hash_lock == NULL) ||
2813                     (found == hdr &&
2814                     DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
2815                     (found == hdr && HDR_L2_READING(hdr)));
2816         }
2817 
2818         hdr->b_flags &= ~ARC_L2_EVICTED;
2819         if (l2arc_noprefetch && (hdr->b_flags & ARC_PREFETCH))
2820                 hdr->b_flags &= ~ARC_L2CACHE;
2821 
2822         /* byteswap if necessary */
2823         callback_list = hdr->b_acb;
2824         ASSERT(callback_list != NULL);
2825         if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
2826                 dmu_object_byteswap_t bswap =
2827                     DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
2828                 arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
2829                     byteswap_uint64_array :
2830                     dmu_ot_byteswap[bswap].ob_func;
2831                 func(buf->b_data, hdr->b_size);
2832         }
2833 
2834         arc_cksum_compute(buf, B_FALSE);
2835         arc_buf_watch(buf);
2836 
2837         if (hash_lock && zio->io_error == 0 && hdr->b_state == arc_anon) {
2838                 /*
2839                  * Only call arc_access on anonymous buffers.  This is because
2840                  * if we've issued an I/O for an evicted buffer, we've already
2841                  * called arc_access (to prevent any simultaneous readers from
2842                  * getting confused).
2843                  */
2844                 arc_access(hdr, hash_lock);
2845         }
2846 
2847         /* create copies of the data buffer for the callers */
2848         abuf = buf;
2849         for (acb = callback_list; acb; acb = acb->acb_next) {
2850                 if (acb->acb_done) {
2851                         if (abuf == NULL) {
2852                                 ARCSTAT_BUMP(arcstat_duplicate_reads);
2853                                 abuf = arc_buf_clone(buf);
2854                         }
2855                         acb->acb_buf = abuf;
2856                         abuf = NULL;
2857                 }
2858         }
2859         hdr->b_acb = NULL;
2860         hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
2861         ASSERT(!HDR_BUF_AVAILABLE(hdr));
2862         if (abuf == buf) {
2863                 ASSERT(buf->b_efunc == NULL);
2864                 ASSERT(hdr->b_datacnt == 1);
2865                 hdr->b_flags |= ARC_BUF_AVAILABLE;
2866         }
2867 
2868         ASSERT(refcount_is_zero(&hdr->b_refcnt) || callback_list != NULL);
2869 
2870         if (zio->io_error != 0) {
2871                 hdr->b_flags |= ARC_IO_ERROR;
2872                 if (hdr->b_state != arc_anon)
2873                         arc_change_state(arc_anon, hdr, hash_lock);
2874                 if (HDR_IN_HASH_TABLE(hdr))
2875                         buf_hash_remove(hdr);
2876                 freeable = refcount_is_zero(&hdr->b_refcnt);
2877         }
2878 
2879         /*
2880          * Broadcast before we drop the hash_lock to avoid the possibility
2881          * that the hdr (and hence the cv) might be freed before we get to
2882          * the cv_broadcast().
2883          */
2884         cv_broadcast(&hdr->b_cv);
2885 
2886         if (hash_lock) {
2887                 mutex_exit(hash_lock);
2888         } else {
2889                 /*
2890                  * This block was freed while we waited for the read to
2891                  * complete.  It has been removed from the hash table and
2892                  * moved to the anonymous state (so that it won't show up
2893                  * in the cache).
2894                  */
2895                 ASSERT3P(hdr->b_state, ==, arc_anon);
2896                 freeable = refcount_is_zero(&hdr->b_refcnt);
2897         }
2898 
2899         /* execute each callback and free its structure */
2900         while ((acb = callback_list) != NULL) {
2901                 if (acb->acb_done)
2902                         acb->acb_done(zio, acb->acb_buf, acb->acb_private);
2903 
2904                 if (acb->acb_zio_dummy != NULL) {
2905                         acb->acb_zio_dummy->io_error = zio->io_error;
2906                         zio_nowait(acb->acb_zio_dummy);
2907                 }
2908 
2909                 callback_list = acb->acb_next;
2910                 kmem_free(acb, sizeof (arc_callback_t));
2911         }
2912 
2913         if (freeable)
2914                 arc_hdr_destroy(hdr);
2915 }
2916 
2917 /*
2918  * "Read" the block at the specified DVA (in bp) via the
2919  * cache.  If the block is found in the cache, invoke the provided
2920  * callback immediately and return.  Note that the `zio' parameter
2921  * in the callback will be NULL in this case, since no IO was
2922  * required.  If the block is not in the cache pass the read request
2923  * on to the spa with a substitute callback function, so that the
2924  * requested block will be added to the cache.
2925  *
2926  * If a read request arrives for a block that has a read in-progress,
2927  * either wait for the in-progress read to complete (and return the
2928  * results); or, if this is a read with a "done" func, add a record
2929  * to the read to invoke the "done" func when the read completes,
2930  * and return; or just return.
2931  *
2932  * arc_read_done() will invoke all the requested "done" functions
2933  * for readers of this block.
2934  */
2935 int
2936 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
2937     void *private, zio_priority_t priority, int zio_flags, uint32_t *arc_flags,
2938     const zbookmark_phys_t *zb)
2939 {
2940         arc_buf_hdr_t *hdr = NULL;
2941         arc_buf_t *buf = NULL;
2942         kmutex_t *hash_lock = NULL;
2943         zio_t *rzio;
2944         uint64_t guid = spa_load_guid(spa);
2945 
2946         ASSERT(!BP_IS_EMBEDDED(bp) ||
2947             BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
2948 
2949 top:
2950         if (!BP_IS_EMBEDDED(bp)) {
2951                 /*
2952                  * Embedded BP's have no DVA and require no I/O to "read".
2953                  * Create an anonymous arc buf to back it.
2954                  */
2955                 hdr = buf_hash_find(guid, bp, &hash_lock);
2956         }
2957 
2958         if (hdr != NULL && hdr->b_datacnt > 0) {
2959 
2960                 *arc_flags |= ARC_CACHED;
2961 
2962                 if (HDR_IO_IN_PROGRESS(hdr)) {
2963 
2964                         if (*arc_flags & ARC_WAIT) {
2965                                 cv_wait(&hdr->b_cv, hash_lock);
2966                                 mutex_exit(hash_lock);
2967                                 goto top;
2968                         }
2969                         ASSERT(*arc_flags & ARC_NOWAIT);
2970 
2971                         if (done) {
2972                                 arc_callback_t  *acb = NULL;
2973 
2974                                 acb = kmem_zalloc(sizeof (arc_callback_t),
2975                                     KM_SLEEP);
2976                                 acb->acb_done = done;
2977                                 acb->acb_private = private;
2978                                 if (pio != NULL)
2979                                         acb->acb_zio_dummy = zio_null(pio,
2980                                             spa, NULL, NULL, NULL, zio_flags);
2981 
2982                                 ASSERT(acb->acb_done != NULL);
2983                                 acb->acb_next = hdr->b_acb;
2984                                 hdr->b_acb = acb;
2985                                 add_reference(hdr, hash_lock, private);
2986                                 mutex_exit(hash_lock);
2987                                 return (0);
2988                         }
2989                         mutex_exit(hash_lock);
2990                         return (0);
2991                 }
2992 
2993                 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
2994 
2995                 if (done) {
2996                         add_reference(hdr, hash_lock, private);
2997                         /*
2998                          * If this block is already in use, create a new
2999                          * copy of the data so that we will be guaranteed
3000                          * that arc_release() will always succeed.
3001                          */
3002                         buf = hdr->b_buf;
3003                         ASSERT(buf);
3004                         ASSERT(buf->b_data);
3005                         if (HDR_BUF_AVAILABLE(hdr)) {
3006                                 ASSERT(buf->b_efunc == NULL);
3007                                 hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3008                         } else {
3009                                 buf = arc_buf_clone(buf);
3010                         }
3011 
3012                 } else if (*arc_flags & ARC_PREFETCH &&
3013                     refcount_count(&hdr->b_refcnt) == 0) {
3014                         hdr->b_flags |= ARC_PREFETCH;
3015                 }
3016                 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
3017                 arc_access(hdr, hash_lock);
3018                 if (*arc_flags & ARC_L2CACHE)
3019                         hdr->b_flags |= ARC_L2CACHE;
3020                 if (*arc_flags & ARC_L2COMPRESS)
3021                         hdr->b_flags |= ARC_L2COMPRESS;
3022                 mutex_exit(hash_lock);
3023                 ARCSTAT_BUMP(arcstat_hits);
3024                 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
3025                     demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3026                     data, metadata, hits);
3027 
3028                 if (done)
3029                         done(NULL, buf, private);
3030         } else {
3031                 uint64_t size = BP_GET_LSIZE(bp);
3032                 arc_callback_t *acb;
3033                 vdev_t *vd = NULL;
3034                 uint64_t addr = 0;
3035                 boolean_t devw = B_FALSE;
3036                 enum zio_compress b_compress = ZIO_COMPRESS_OFF;
3037                 uint64_t b_asize = 0;
3038 
3039                 if (hdr == NULL) {
3040                         /* this block is not in the cache */
3041                         arc_buf_hdr_t *exists = NULL;
3042                         arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
3043                         buf = arc_buf_alloc(spa, size, private, type);
3044                         hdr = buf->b_hdr;
3045                         if (!BP_IS_EMBEDDED(bp)) {
3046                                 hdr->b_dva = *BP_IDENTITY(bp);
3047                                 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
3048                                 hdr->b_cksum0 = bp->blk_cksum.zc_word[0];
3049                                 exists = buf_hash_insert(hdr, &hash_lock);
3050                         }
3051                         if (exists != NULL) {
3052                                 /* somebody beat us to the hash insert */
3053                                 mutex_exit(hash_lock);
3054                                 buf_discard_identity(hdr);
3055                                 (void) arc_buf_remove_ref(buf, private);
3056                                 goto top; /* restart the IO request */
3057                         }
3058                         /* if this is a prefetch, we don't have a reference */
3059                         if (*arc_flags & ARC_PREFETCH) {
3060                                 (void) remove_reference(hdr, hash_lock,
3061                                     private);
3062                                 hdr->b_flags |= ARC_PREFETCH;
3063                         }
3064                         if (*arc_flags & ARC_L2CACHE)
3065                                 hdr->b_flags |= ARC_L2CACHE;
3066                         if (*arc_flags & ARC_L2COMPRESS)
3067                                 hdr->b_flags |= ARC_L2COMPRESS;
3068                         if (BP_GET_LEVEL(bp) > 0)
3069                                 hdr->b_flags |= ARC_INDIRECT;
3070                 } else {
3071                         /* this block is in the ghost cache */
3072                         ASSERT(GHOST_STATE(hdr->b_state));
3073                         ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3074                         ASSERT0(refcount_count(&hdr->b_refcnt));
3075                         ASSERT(hdr->b_buf == NULL);
3076 
3077                         /* if this is a prefetch, we don't have a reference */
3078                         if (*arc_flags & ARC_PREFETCH)
3079                                 hdr->b_flags |= ARC_PREFETCH;
3080                         else
3081                                 add_reference(hdr, hash_lock, private);
3082                         if (*arc_flags & ARC_L2CACHE)
3083                                 hdr->b_flags |= ARC_L2CACHE;
3084                         if (*arc_flags & ARC_L2COMPRESS)
3085                                 hdr->b_flags |= ARC_L2COMPRESS;
3086                         buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
3087                         buf->b_hdr = hdr;
3088                         buf->b_data = NULL;
3089                         buf->b_efunc = NULL;
3090                         buf->b_private = NULL;
3091                         buf->b_next = NULL;
3092                         hdr->b_buf = buf;
3093                         ASSERT(hdr->b_datacnt == 0);
3094                         hdr->b_datacnt = 1;
3095                         arc_get_data_buf(buf);
3096                         arc_access(hdr, hash_lock);
3097                 }
3098 
3099                 ASSERT(!GHOST_STATE(hdr->b_state));
3100 
3101                 acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
3102                 acb->acb_done = done;
3103                 acb->acb_private = private;
3104 
3105                 ASSERT(hdr->b_acb == NULL);
3106                 hdr->b_acb = acb;
3107                 hdr->b_flags |= ARC_IO_IN_PROGRESS;
3108 
3109                 if (hdr->b_l2hdr != NULL &&
3110                     (vd = hdr->b_l2hdr->b_dev->l2ad_vdev) != NULL) {
3111                         devw = hdr->b_l2hdr->b_dev->l2ad_writing;
3112                         addr = hdr->b_l2hdr->b_daddr;
3113                         b_compress = hdr->b_l2hdr->b_compress;
3114                         b_asize = hdr->b_l2hdr->b_asize;
3115                         /*
3116                          * Lock out device removal.
3117                          */
3118                         if (vdev_is_dead(vd) ||
3119                             !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
3120                                 vd = NULL;
3121                 }
3122 
3123                 if (hash_lock != NULL)
3124                         mutex_exit(hash_lock);
3125 
3126                 /*
3127                  * At this point, we have a level 1 cache miss.  Try again in
3128                  * L2ARC if possible.
3129                  */
3130                 ASSERT3U(hdr->b_size, ==, size);
3131                 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
3132                     uint64_t, size, zbookmark_phys_t *, zb);
3133                 ARCSTAT_BUMP(arcstat_misses);
3134                 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
3135                     demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3136                     data, metadata, misses);
3137 
3138                 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
3139                         /*
3140                          * Read from the L2ARC if the following are true:
3141                          * 1. The L2ARC vdev was previously cached.
3142                          * 2. This buffer still has L2ARC metadata.
3143                          * 3. This buffer isn't currently writing to the L2ARC.
3144                          * 4. The L2ARC entry wasn't evicted, which may
3145                          *    also have invalidated the vdev.
3146                          * 5. This isn't prefetch and l2arc_noprefetch is set.
3147                          */
3148                         if (hdr->b_l2hdr != NULL &&
3149                             !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
3150                             !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
3151                                 l2arc_read_callback_t *cb;
3152 
3153                                 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
3154                                 ARCSTAT_BUMP(arcstat_l2_hits);
3155 
3156                                 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
3157                                     KM_SLEEP);
3158                                 cb->l2rcb_buf = buf;
3159                                 cb->l2rcb_spa = spa;
3160                                 cb->l2rcb_bp = *bp;
3161                                 cb->l2rcb_zb = *zb;
3162                                 cb->l2rcb_flags = zio_flags;
3163                                 cb->l2rcb_compress = b_compress;
3164 
3165                                 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
3166                                     addr + size < vd->vdev_psize -
3167                                     VDEV_LABEL_END_SIZE);
3168 
3169                                 /*
3170                                  * l2arc read.  The SCL_L2ARC lock will be
3171                                  * released by l2arc_read_done().
3172                                  * Issue a null zio if the underlying buffer
3173                                  * was squashed to zero size by compression.
3174                                  */
3175                                 if (b_compress == ZIO_COMPRESS_EMPTY) {
3176                                         rzio = zio_null(pio, spa, vd,
3177                                             l2arc_read_done, cb,
3178                                             zio_flags | ZIO_FLAG_DONT_CACHE |
3179                                             ZIO_FLAG_CANFAIL |
3180                                             ZIO_FLAG_DONT_PROPAGATE |
3181                                             ZIO_FLAG_DONT_RETRY);
3182                                 } else {
3183                                         rzio = zio_read_phys(pio, vd, addr,
3184                                             b_asize, buf->b_data,
3185                                             ZIO_CHECKSUM_OFF,
3186                                             l2arc_read_done, cb, priority,
3187                                             zio_flags | ZIO_FLAG_DONT_CACHE |
3188                                             ZIO_FLAG_CANFAIL |
3189                                             ZIO_FLAG_DONT_PROPAGATE |
3190                                             ZIO_FLAG_DONT_RETRY, B_FALSE);
3191                                 }
3192                                 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
3193                                     zio_t *, rzio);
3194                                 ARCSTAT_INCR(arcstat_l2_read_bytes, b_asize);
3195 
3196                                 if (*arc_flags & ARC_NOWAIT) {
3197                                         zio_nowait(rzio);
3198                                         return (0);
3199                                 }
3200 
3201                                 ASSERT(*arc_flags & ARC_WAIT);
3202                                 if (zio_wait(rzio) == 0)
3203                                         return (0);
3204 
3205                                 /* l2arc read error; goto zio_read() */
3206                         } else {
3207                                 DTRACE_PROBE1(l2arc__miss,
3208                                     arc_buf_hdr_t *, hdr);
3209                                 ARCSTAT_BUMP(arcstat_l2_misses);
3210                                 if (HDR_L2_WRITING(hdr))
3211                                         ARCSTAT_BUMP(arcstat_l2_rw_clash);
3212                                 spa_config_exit(spa, SCL_L2ARC, vd);
3213                         }
3214                 } else {
3215                         if (vd != NULL)
3216                                 spa_config_exit(spa, SCL_L2ARC, vd);
3217                         if (l2arc_ndev != 0) {
3218                                 DTRACE_PROBE1(l2arc__miss,
3219                                     arc_buf_hdr_t *, hdr);
3220                                 ARCSTAT_BUMP(arcstat_l2_misses);
3221                         }
3222                 }
3223 
3224                 rzio = zio_read(pio, spa, bp, buf->b_data, size,
3225                     arc_read_done, buf, priority, zio_flags, zb);
3226 
3227                 if (*arc_flags & ARC_WAIT)
3228                         return (zio_wait(rzio));
3229 
3230                 ASSERT(*arc_flags & ARC_NOWAIT);
3231                 zio_nowait(rzio);
3232         }
3233         return (0);
3234 }
3235 
3236 void
3237 arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
3238 {
3239         ASSERT(buf->b_hdr != NULL);
3240         ASSERT(buf->b_hdr->b_state != arc_anon);
3241         ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt) || func == NULL);
3242         ASSERT(buf->b_efunc == NULL);
3243         ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
3244 
3245         buf->b_efunc = func;
3246         buf->b_private = private;
3247 }
3248 
3249 /*
3250  * Notify the arc that a block was freed, and thus will never be used again.
3251  */
3252 void
3253 arc_freed(spa_t *spa, const blkptr_t *bp)
3254 {
3255         arc_buf_hdr_t *hdr;
3256         kmutex_t *hash_lock;
3257         uint64_t guid = spa_load_guid(spa);
3258 
3259         ASSERT(!BP_IS_EMBEDDED(bp));
3260 
3261         hdr = buf_hash_find(guid, bp, &hash_lock);
3262         if (hdr == NULL)
3263                 return;
3264         if (HDR_BUF_AVAILABLE(hdr)) {
3265                 arc_buf_t *buf = hdr->b_buf;
3266                 add_reference(hdr, hash_lock, FTAG);
3267                 hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3268                 mutex_exit(hash_lock);
3269 
3270                 arc_release(buf, FTAG);
3271                 (void) arc_buf_remove_ref(buf, FTAG);
3272         } else {
3273                 mutex_exit(hash_lock);
3274         }
3275 
3276 }
3277 
3278 /*
3279  * Clear the user eviction callback set by arc_set_callback(), first calling
3280  * it if it exists.  Because the presence of a callback keeps an arc_buf cached
3281  * clearing the callback may result in the arc_buf being destroyed.  However,
3282  * it will not result in the *last* arc_buf being destroyed, hence the data
3283  * will remain cached in the ARC. We make a copy of the arc buffer here so
3284  * that we can process the callback without holding any locks.
3285  *
3286  * It's possible that the callback is already in the process of being cleared
3287  * by another thread.  In this case we can not clear the callback.
3288  *
3289  * Returns B_TRUE if the callback was successfully called and cleared.
3290  */
3291 boolean_t
3292 arc_clear_callback(arc_buf_t *buf)
3293 {
3294         arc_buf_hdr_t *hdr;
3295         kmutex_t *hash_lock;
3296         arc_evict_func_t *efunc = buf->b_efunc;
3297         void *private = buf->b_private;
3298 
3299         mutex_enter(&buf->b_evict_lock);
3300         hdr = buf->b_hdr;
3301         if (hdr == NULL) {
3302                 /*
3303                  * We are in arc_do_user_evicts().
3304                  */
3305                 ASSERT(buf->b_data == NULL);
3306                 mutex_exit(&buf->b_evict_lock);
3307                 return (B_FALSE);
3308         } else if (buf->b_data == NULL) {
3309                 /*
3310                  * We are on the eviction list; process this buffer now
3311                  * but let arc_do_user_evicts() do the reaping.
3312                  */
3313                 buf->b_efunc = NULL;
3314                 mutex_exit(&buf->b_evict_lock);
3315                 VERIFY0(efunc(private));
3316                 return (B_TRUE);
3317         }
3318         hash_lock = HDR_LOCK(hdr);
3319         mutex_enter(hash_lock);
3320         hdr = buf->b_hdr;
3321         ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3322 
3323         ASSERT3U(refcount_count(&hdr->b_refcnt), <, hdr->b_datacnt);
3324         ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3325 
3326         buf->b_efunc = NULL;
3327         buf->b_private = NULL;
3328 
3329         if (hdr->b_datacnt > 1) {
3330                 mutex_exit(&buf->b_evict_lock);
3331                 arc_buf_destroy(buf, FALSE, TRUE);
3332         } else {
3333                 ASSERT(buf == hdr->b_buf);
3334                 hdr->b_flags |= ARC_BUF_AVAILABLE;
3335                 mutex_exit(&buf->b_evict_lock);
3336         }
3337 
3338         mutex_exit(hash_lock);
3339         VERIFY0(efunc(private));
3340         return (B_TRUE);
3341 }
3342 
3343 /*
3344  * Release this buffer from the cache, making it an anonymous buffer.  This
3345  * must be done after a read and prior to modifying the buffer contents.
3346  * If the buffer has more than one reference, we must make
3347  * a new hdr for the buffer.
3348  */
3349 void
3350 arc_release(arc_buf_t *buf, void *tag)
3351 {
3352         arc_buf_hdr_t *hdr;
3353         kmutex_t *hash_lock = NULL;
3354         l2arc_buf_hdr_t *l2hdr;
3355         uint64_t buf_size;
3356 
3357         /*
3358          * It would be nice to assert that if it's DMU metadata (level >
3359          * 0 || it's the dnode file), then it must be syncing context.
3360          * But we don't know that information at this level.
3361          */
3362 
3363         mutex_enter(&buf->b_evict_lock);
3364         hdr = buf->b_hdr;
3365 
3366         /* this buffer is not on any list */
3367         ASSERT(refcount_count(&hdr->b_refcnt) > 0);
3368 
3369         if (hdr->b_state == arc_anon) {
3370                 /* this buffer is already released */
3371                 ASSERT(buf->b_efunc == NULL);
3372         } else {
3373                 hash_lock = HDR_LOCK(hdr);
3374                 mutex_enter(hash_lock);
3375                 hdr = buf->b_hdr;
3376                 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3377         }
3378 
3379         l2hdr = hdr->b_l2hdr;
3380         if (l2hdr) {
3381                 mutex_enter(&l2arc_buflist_mtx);
3382                 arc_buf_l2_cdata_free(hdr);
3383                 hdr->b_l2hdr = NULL;
3384                 list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
3385         }
3386         buf_size = hdr->b_size;
3387 
3388         /*
3389          * Do we have more than one buf?
3390          */
3391         if (hdr->b_datacnt > 1) {
3392                 arc_buf_hdr_t *nhdr;
3393                 arc_buf_t **bufp;
3394                 uint64_t blksz = hdr->b_size;
3395                 uint64_t spa = hdr->b_spa;
3396                 arc_buf_contents_t type = hdr->b_type;
3397                 uint32_t flags = hdr->b_flags;
3398 
3399                 ASSERT(hdr->b_buf != buf || buf->b_next != NULL);
3400                 /*
3401                  * Pull the data off of this hdr and attach it to
3402                  * a new anonymous hdr.
3403                  */
3404                 (void) remove_reference(hdr, hash_lock, tag);
3405                 bufp = &hdr->b_buf;
3406                 while (*bufp != buf)
3407                         bufp = &(*bufp)->b_next;
3408                 *bufp = buf->b_next;
3409                 buf->b_next = NULL;
3410 
3411                 ASSERT3U(hdr->b_state->arcs_size, >=, hdr->b_size);
3412                 atomic_add_64(&hdr->b_state->arcs_size, -hdr->b_size);
3413                 if (refcount_is_zero(&hdr->b_refcnt)) {
3414                         uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
3415                         ASSERT3U(*size, >=, hdr->b_size);
3416                         atomic_add_64(size, -hdr->b_size);
3417                 }
3418 
3419                 /*
3420                  * We're releasing a duplicate user data buffer, update
3421                  * our statistics accordingly.
3422                  */
3423                 if (hdr->b_type == ARC_BUFC_DATA) {
3424                         ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
3425                         ARCSTAT_INCR(arcstat_duplicate_buffers_size,
3426                             -hdr->b_size);
3427                 }
3428                 hdr->b_datacnt -= 1;
3429                 arc_cksum_verify(buf);
3430                 arc_buf_unwatch(buf);
3431 
3432                 mutex_exit(hash_lock);
3433 
3434                 nhdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
3435                 nhdr->b_size = blksz;
3436                 nhdr->b_spa = spa;
3437                 nhdr->b_type = type;
3438                 nhdr->b_buf = buf;
3439                 nhdr->b_state = arc_anon;
3440                 nhdr->b_arc_access = 0;
3441                 nhdr->b_flags = flags & ARC_L2_WRITING;
3442                 nhdr->b_l2hdr = NULL;
3443                 nhdr->b_datacnt = 1;
3444                 nhdr->b_freeze_cksum = NULL;
3445                 (void) refcount_add(&nhdr->b_refcnt, tag);
3446                 buf->b_hdr = nhdr;
3447                 mutex_exit(&buf->b_evict_lock);
3448                 atomic_add_64(&arc_anon->arcs_size, blksz);
3449         } else {
3450                 mutex_exit(&buf->b_evict_lock);
3451                 ASSERT(refcount_count(&hdr->b_refcnt) == 1);
3452                 ASSERT(!list_link_active(&hdr->b_arc_node));
3453                 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3454                 if (hdr->b_state != arc_anon)
3455                         arc_change_state(arc_anon, hdr, hash_lock);
3456                 hdr->b_arc_access = 0;
3457                 if (hash_lock)
3458                         mutex_exit(hash_lock);
3459 
3460                 buf_discard_identity(hdr);
3461                 arc_buf_thaw(buf);
3462         }
3463         buf->b_efunc = NULL;
3464         buf->b_private = NULL;
3465 
3466         if (l2hdr) {
3467                 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
3468                 vdev_space_update(l2hdr->b_dev->l2ad_vdev,
3469                     -l2hdr->b_asize, 0, 0);
3470                 kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
3471                 ARCSTAT_INCR(arcstat_l2_size, -buf_size);
3472                 mutex_exit(&l2arc_buflist_mtx);
3473         }
3474 }
3475 
3476 int
3477 arc_released(arc_buf_t *buf)
3478 {
3479         int released;
3480 
3481         mutex_enter(&buf->b_evict_lock);
3482         released = (buf->b_data != NULL && buf->b_hdr->b_state == arc_anon);
3483         mutex_exit(&buf->b_evict_lock);
3484         return (released);
3485 }
3486 
3487 #ifdef ZFS_DEBUG
3488 int
3489 arc_referenced(arc_buf_t *buf)
3490 {
3491         int referenced;
3492 
3493         mutex_enter(&buf->b_evict_lock);
3494         referenced = (refcount_count(&buf->b_hdr->b_refcnt));
3495         mutex_exit(&buf->b_evict_lock);
3496         return (referenced);
3497 }
3498 #endif
3499 
3500 static void
3501 arc_write_ready(zio_t *zio)
3502 {
3503         arc_write_callback_t *callback = zio->io_private;
3504         arc_buf_t *buf = callback->awcb_buf;
3505         arc_buf_hdr_t *hdr = buf->b_hdr;
3506 
3507         ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt));
3508         callback->awcb_ready(zio, buf, callback->awcb_private);
3509 
3510         /*
3511          * If the IO is already in progress, then this is a re-write
3512          * attempt, so we need to thaw and re-compute the cksum.
3513          * It is the responsibility of the callback to handle the
3514          * accounting for any re-write attempt.
3515          */
3516         if (HDR_IO_IN_PROGRESS(hdr)) {
3517                 mutex_enter(&hdr->b_freeze_lock);
3518                 if (hdr->b_freeze_cksum != NULL) {
3519                         kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
3520                         hdr->b_freeze_cksum = NULL;
3521                 }
3522                 mutex_exit(&hdr->b_freeze_lock);
3523         }
3524         arc_cksum_compute(buf, B_FALSE);
3525         hdr->b_flags |= ARC_IO_IN_PROGRESS;
3526 }
3527 
3528 /*
3529  * The SPA calls this callback for each physical write that happens on behalf
3530  * of a logical write.  See the comment in dbuf_write_physdone() for details.
3531  */
3532 static void
3533 arc_write_physdone(zio_t *zio)
3534 {
3535         arc_write_callback_t *cb = zio->io_private;
3536         if (cb->awcb_physdone != NULL)
3537                 cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
3538 }
3539 
3540 static void
3541 arc_write_done(zio_t *zio)
3542 {
3543         arc_write_callback_t *callback = zio->io_private;
3544         arc_buf_t *buf = callback->awcb_buf;
3545         arc_buf_hdr_t *hdr = buf->b_hdr;
3546 
3547         ASSERT(hdr->b_acb == NULL);
3548 
3549         if (zio->io_error == 0) {
3550                 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
3551                         buf_discard_identity(hdr);
3552                 } else {
3553                         hdr->b_dva = *BP_IDENTITY(zio->io_bp);
3554                         hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
3555                         hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
3556                 }
3557         } else {
3558                 ASSERT(BUF_EMPTY(hdr));
3559         }
3560 
3561         /*
3562          * If the block to be written was all-zero or compressed enough to be
3563          * embedded in the BP, no write was performed so there will be no
3564          * dva/birth/checksum.  The buffer must therefore remain anonymous
3565          * (and uncached).
3566          */
3567         if (!BUF_EMPTY(hdr)) {
3568                 arc_buf_hdr_t *exists;
3569                 kmutex_t *hash_lock;
3570 
3571                 ASSERT(zio->io_error == 0);
3572 
3573                 arc_cksum_verify(buf);
3574 
3575                 exists = buf_hash_insert(hdr, &hash_lock);
3576                 if (exists) {
3577                         /*
3578                          * This can only happen if we overwrite for
3579                          * sync-to-convergence, because we remove
3580                          * buffers from the hash table when we arc_free().
3581                          */
3582                         if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
3583                                 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3584                                         panic("bad overwrite, hdr=%p exists=%p",
3585                                             (void *)hdr, (void *)exists);
3586                                 ASSERT(refcount_is_zero(&exists->b_refcnt));
3587                                 arc_change_state(arc_anon, exists, hash_lock);
3588                                 mutex_exit(hash_lock);
3589                                 arc_hdr_destroy(exists);
3590                                 exists = buf_hash_insert(hdr, &hash_lock);
3591                                 ASSERT3P(exists, ==, NULL);
3592                         } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
3593                                 /* nopwrite */
3594                                 ASSERT(zio->io_prop.zp_nopwrite);
3595                                 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3596                                         panic("bad nopwrite, hdr=%p exists=%p",
3597                                             (void *)hdr, (void *)exists);
3598                         } else {
3599                                 /* Dedup */
3600                                 ASSERT(hdr->b_datacnt == 1);
3601                                 ASSERT(hdr->b_state == arc_anon);
3602                                 ASSERT(BP_GET_DEDUP(zio->io_bp));
3603                                 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
3604                         }
3605                 }
3606                 hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3607                 /* if it's not anon, we are doing a scrub */
3608                 if (!exists && hdr->b_state == arc_anon)
3609                         arc_access(hdr, hash_lock);
3610                 mutex_exit(hash_lock);
3611         } else {
3612                 hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3613         }
3614 
3615         ASSERT(!refcount_is_zero(&hdr->b_refcnt));
3616         callback->awcb_done(zio, buf, callback->awcb_private);
3617 
3618         kmem_free(callback, sizeof (arc_write_callback_t));
3619 }
3620 
3621 zio_t *
3622 arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
3623     blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
3624     const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *physdone,
3625     arc_done_func_t *done, void *private, zio_priority_t priority,
3626     int zio_flags, const zbookmark_phys_t *zb)
3627 {
3628         arc_buf_hdr_t *hdr = buf->b_hdr;
3629         arc_write_callback_t *callback;
3630         zio_t *zio;
3631 
3632         ASSERT(ready != NULL);
3633         ASSERT(done != NULL);
3634         ASSERT(!HDR_IO_ERROR(hdr));
3635         ASSERT((hdr->b_flags & ARC_IO_IN_PROGRESS) == 0);
3636         ASSERT(hdr->b_acb == NULL);
3637         if (l2arc)
3638                 hdr->b_flags |= ARC_L2CACHE;
3639         if (l2arc_compress)
3640                 hdr->b_flags |= ARC_L2COMPRESS;
3641         callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
3642         callback->awcb_ready = ready;
3643         callback->awcb_physdone = physdone;
3644         callback->awcb_done = done;
3645         callback->awcb_private = private;
3646         callback->awcb_buf = buf;
3647 
3648         zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
3649             arc_write_ready, arc_write_physdone, arc_write_done, callback,
3650             priority, zio_flags, zb);
3651 
3652         return (zio);
3653 }
3654 
3655 static int
3656 arc_memory_throttle(uint64_t reserve, uint64_t txg)
3657 {
3658 #ifdef _KERNEL
3659         uint64_t available_memory = ptob(freemem);
3660         static uint64_t page_load = 0;
3661         static uint64_t last_txg = 0;
3662 
3663 #if defined(__i386)
3664         available_memory =
3665             MIN(available_memory, vmem_size(heap_arena, VMEM_FREE));
3666 #endif
3667 
3668         if (freemem > physmem * arc_lotsfree_percent / 100)
3669                 return (0);
3670 
3671         if (txg > last_txg) {
3672                 last_txg = txg;
3673                 page_load = 0;
3674         }
3675         /*
3676          * If we are in pageout, we know that memory is already tight,
3677          * the arc is already going to be evicting, so we just want to
3678          * continue to let page writes occur as quickly as possible.
3679          */
3680         if (curproc == proc_pageout) {
3681                 if (page_load > MAX(ptob(minfree), available_memory) / 4)
3682                         return (SET_ERROR(ERESTART));
3683                 /* Note: reserve is inflated, so we deflate */
3684                 page_load += reserve / 8;
3685                 return (0);
3686         } else if (page_load > 0 && arc_reclaim_needed()) {
3687                 /* memory is low, delay before restarting */
3688                 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
3689                 return (SET_ERROR(EAGAIN));
3690         }
3691         page_load = 0;
3692 #endif
3693         return (0);
3694 }
3695 
3696 void
3697 arc_tempreserve_clear(uint64_t reserve)
3698 {
3699         atomic_add_64(&arc_tempreserve, -reserve);
3700         ASSERT((int64_t)arc_tempreserve >= 0);
3701 }
3702 
3703 int
3704 arc_tempreserve_space(uint64_t reserve, uint64_t txg)
3705 {
3706         int error;
3707         uint64_t anon_size;
3708 
3709         if (reserve > arc_c/4 && !arc_no_grow)
3710                 arc_c = MIN(arc_c_max, reserve * 4);
3711         if (reserve > arc_c)
3712                 return (SET_ERROR(ENOMEM));
3713 
3714         /*
3715          * Don't count loaned bufs as in flight dirty data to prevent long
3716          * network delays from blocking transactions that are ready to be
3717          * assigned to a txg.
3718          */
3719         anon_size = MAX((int64_t)(arc_anon->arcs_size - arc_loaned_bytes), 0);
3720 
3721         /*
3722          * Writes will, almost always, require additional memory allocations
3723          * in order to compress/encrypt/etc the data.  We therefore need to
3724          * make sure that there is sufficient available memory for this.
3725          */
3726         error = arc_memory_throttle(reserve, txg);
3727         if (error != 0)
3728                 return (error);
3729 
3730         /*
3731          * Throttle writes when the amount of dirty data in the cache
3732          * gets too large.  We try to keep the cache less than half full
3733          * of dirty blocks so that our sync times don't grow too large.
3734          * Note: if two requests come in concurrently, we might let them
3735          * both succeed, when one of them should fail.  Not a huge deal.
3736          */
3737 
3738         if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
3739             anon_size > arc_c / 4) {
3740                 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
3741                     "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
3742                     arc_tempreserve>>10,
3743                     arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
3744                     arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
3745                     reserve>>10, arc_c>>10);
3746                 return (SET_ERROR(ERESTART));
3747         }
3748         atomic_add_64(&arc_tempreserve, reserve);
3749         return (0);
3750 }
3751 
3752 void
3753 arc_init(void)
3754 {
3755         mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
3756         cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
3757 
3758         /* Convert seconds to clock ticks */
3759         arc_min_prefetch_lifespan = 1 * hz;
3760 
3761         /* Start out with 1/8 of all memory */
3762         arc_c = physmem * PAGESIZE / 8;
3763 
3764 #ifdef _KERNEL
3765         /*
3766          * On architectures where the physical memory can be larger
3767          * than the addressable space (intel in 32-bit mode), we may
3768          * need to limit the cache to 1/8 of VM size.
3769          */
3770         arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
3771 #endif
3772 
3773         /* set min cache to 1/32 of all memory, or 64MB, whichever is more */
3774         arc_c_min = MAX(arc_c / 4, 64<<20);
3775         /* set max to 3/4 of all memory, or all but 1GB, whichever is more */
3776         if (arc_c * 8 >= 1<<30)
3777                 arc_c_max = (arc_c * 8) - (1<<30);
3778         else
3779                 arc_c_max = arc_c_min;
3780         arc_c_max = MAX(arc_c * 6, arc_c_max);
3781 
3782         /*
3783          * Allow the tunables to override our calculations if they are
3784          * reasonable (ie. over 64MB)
3785          */
3786         if (zfs_arc_max > 64<<20 && zfs_arc_max < physmem * PAGESIZE)
3787                 arc_c_max = zfs_arc_max;
3788         if (zfs_arc_min > 64<<20 && zfs_arc_min <= arc_c_max)
3789                 arc_c_min = zfs_arc_min;
3790 
3791         arc_c = arc_c_max;
3792         arc_p = (arc_c >> 1);
3793 
3794         /* limit meta-data to 1/4 of the arc capacity */
3795         arc_meta_limit = arc_c_max / 4;
3796 
3797         /* Allow the tunable to override if it is reasonable */
3798         if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
3799                 arc_meta_limit = zfs_arc_meta_limit;
3800 
3801         if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
3802                 arc_c_min = arc_meta_limit / 2;
3803 
3804         if (zfs_arc_grow_retry > 0)
3805                 arc_grow_retry = zfs_arc_grow_retry;
3806 
3807         if (zfs_arc_shrink_shift > 0)
3808                 arc_shrink_shift = zfs_arc_shrink_shift;
3809 
3810         if (zfs_arc_p_min_shift > 0)
3811                 arc_p_min_shift = zfs_arc_p_min_shift;
3812 
3813         /* if kmem_flags are set, lets try to use less memory */
3814         if (kmem_debugging())
3815                 arc_c = arc_c / 2;
3816         if (arc_c < arc_c_min)
3817                 arc_c = arc_c_min;
3818 
3819         arc_anon = &ARC_anon;
3820         arc_mru = &ARC_mru;
3821         arc_mru_ghost = &ARC_mru_ghost;
3822         arc_mfu = &ARC_mfu;
3823         arc_mfu_ghost = &ARC_mfu_ghost;
3824         arc_l2c_only = &ARC_l2c_only;
3825         arc_size = 0;
3826 
3827         mutex_init(&arc_anon->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3828         mutex_init(&arc_mru->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3829         mutex_init(&arc_mru_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3830         mutex_init(&arc_mfu->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3831         mutex_init(&arc_mfu_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3832         mutex_init(&arc_l2c_only->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3833 
3834         list_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
3835             sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3836         list_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
3837             sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3838         list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
3839             sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3840         list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
3841             sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3842         list_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
3843             sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3844         list_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
3845             sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3846         list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
3847             sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3848         list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
3849             sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3850         list_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
3851             sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3852         list_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
3853             sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3854 
3855         buf_init();
3856 
3857         arc_thread_exit = 0;
3858         arc_eviction_list = NULL;
3859         mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
3860         bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
3861 
3862         arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
3863             sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
3864 
3865         if (arc_ksp != NULL) {
3866                 arc_ksp->ks_data = &arc_stats;
3867                 kstat_install(arc_ksp);
3868         }
3869 
3870         (void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
3871             TS_RUN, minclsyspri);
3872 
3873         arc_dead = FALSE;
3874         arc_warm = B_FALSE;
3875 
3876         /*
3877          * Calculate maximum amount of dirty data per pool.
3878          *
3879          * If it has been set by /etc/system, take that.
3880          * Otherwise, use a percentage of physical memory defined by
3881          * zfs_dirty_data_max_percent (default 10%) with a cap at
3882          * zfs_dirty_data_max_max (default 4GB).
3883          */
3884         if (zfs_dirty_data_max == 0) {
3885                 zfs_dirty_data_max = physmem * PAGESIZE *
3886                     zfs_dirty_data_max_percent / 100;
3887                 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
3888                     zfs_dirty_data_max_max);
3889         }
3890 }
3891 
3892 void
3893 arc_fini(void)
3894 {
3895         mutex_enter(&arc_reclaim_thr_lock);
3896         arc_thread_exit = 1;
3897         while (arc_thread_exit != 0)
3898                 cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
3899         mutex_exit(&arc_reclaim_thr_lock);
3900 
3901         arc_flush(NULL);
3902 
3903         arc_dead = TRUE;
3904 
3905         if (arc_ksp != NULL) {
3906                 kstat_delete(arc_ksp);
3907                 arc_ksp = NULL;
3908         }
3909 
3910         mutex_destroy(&arc_eviction_mtx);
3911         mutex_destroy(&arc_reclaim_thr_lock);
3912         cv_destroy(&arc_reclaim_thr_cv);
3913 
3914         list_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
3915         list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
3916         list_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
3917         list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
3918         list_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
3919         list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
3920         list_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
3921         list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
3922 
3923         mutex_destroy(&arc_anon->arcs_mtx);
3924         mutex_destroy(&arc_mru->arcs_mtx);
3925         mutex_destroy(&arc_mru_ghost->arcs_mtx);
3926         mutex_destroy(&arc_mfu->arcs_mtx);
3927         mutex_destroy(&arc_mfu_ghost->arcs_mtx);
3928         mutex_destroy(&arc_l2c_only->arcs_mtx);
3929 
3930         buf_fini();
3931 
3932         ASSERT(arc_loaned_bytes == 0);
3933 }
3934 
3935 /*
3936  * Level 2 ARC
3937  *
3938  * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
3939  * It uses dedicated storage devices to hold cached data, which are populated
3940  * using large infrequent writes.  The main role of this cache is to boost
3941  * the performance of random read workloads.  The intended L2ARC devices
3942  * include short-stroked disks, solid state disks, and other media with
3943  * substantially faster read latency than disk.
3944  *
3945  *                 +-----------------------+
3946  *                 |         ARC           |
3947  *                 +-----------------------+
3948  *                    |         ^     ^
3949  *                    |         |     |
3950  *      l2arc_feed_thread()    arc_read()
3951  *                    |         |     |
3952  *                    |  l2arc read   |
3953  *                    V         |     |
3954  *               +---------------+    |
3955  *               |     L2ARC     |    |
3956  *               +---------------+    |
3957  *                   |    ^           |
3958  *          l2arc_write() |           |
3959  *                   |    |           |
3960  *                   V    |           |
3961  *                 +-------+      +-------+
3962  *                 | vdev  |      | vdev  |
3963  *                 | cache |      | cache |
3964  *                 +-------+      +-------+
3965  *                 +=========+     .-----.
3966  *                 :  L2ARC  :    |-_____-|
3967  *                 : devices :    | Disks |
3968  *                 +=========+    `-_____-'
3969  *
3970  * Read requests are satisfied from the following sources, in order:
3971  *
3972  *      1) ARC
3973  *      2) vdev cache of L2ARC devices
3974  *      3) L2ARC devices
3975  *      4) vdev cache of disks
3976  *      5) disks
3977  *
3978  * Some L2ARC device types exhibit extremely slow write performance.
3979  * To accommodate for this there are some significant differences between
3980  * the L2ARC and traditional cache design:
3981  *
3982  * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
3983  * the ARC behave as usual, freeing buffers and placing headers on ghost
3984  * lists.  The ARC does not send buffers to the L2ARC during eviction as
3985  * this would add inflated write latencies for all ARC memory pressure.
3986  *
3987  * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
3988  * It does this by periodically scanning buffers from the eviction-end of
3989  * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
3990  * not already there. It scans until a headroom of buffers is satisfied,
3991  * which itself is a buffer for ARC eviction. If a compressible buffer is
3992  * found during scanning and selected for writing to an L2ARC device, we
3993  * temporarily boost scanning headroom during the next scan cycle to make
3994  * sure we adapt to compression effects (which might significantly reduce
3995  * the data volume we write to L2ARC). The thread that does this is
3996  * l2arc_feed_thread(), illustrated below; example sizes are included to
3997  * provide a better sense of ratio than this diagram:
3998  *
3999  *             head -->                        tail
4000  *              +---------------------+----------+
4001  *      ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
4002  *              +---------------------+----------+   |   o L2ARC eligible
4003  *      ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
4004  *              +---------------------+----------+   |
4005  *                   15.9 Gbytes      ^ 32 Mbytes    |
4006  *                                 headroom          |
4007  *                                            l2arc_feed_thread()
4008  *                                                   |
4009  *                       l2arc write hand <--[oooo]--'
4010  *                               |           8 Mbyte
4011  *                               |          write max
4012  *                               V
4013  *                +==============================+
4014  *      L2ARC dev |####|#|###|###|    |####| ... |
4015  *                +==============================+
4016  *                           32 Gbytes
4017  *
4018  * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
4019  * evicted, then the L2ARC has cached a buffer much sooner than it probably
4020  * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
4021  * safe to say that this is an uncommon case, since buffers at the end of
4022  * the ARC lists have moved there due to inactivity.
4023  *
4024  * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
4025  * then the L2ARC simply misses copying some buffers.  This serves as a
4026  * pressure valve to prevent heavy read workloads from both stalling the ARC
4027  * with waits and clogging the L2ARC with writes.  This also helps prevent
4028  * the potential for the L2ARC to churn if it attempts to cache content too
4029  * quickly, such as during backups of the entire pool.
4030  *
4031  * 5. After system boot and before the ARC has filled main memory, there are
4032  * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
4033  * lists can remain mostly static.  Instead of searching from tail of these
4034  * lists as pictured, the l2arc_feed_thread() will search from the list heads
4035  * for eligible buffers, greatly increasing its chance of finding them.
4036  *
4037  * The L2ARC device write speed is also boosted during this time so that
4038  * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
4039  * there are no L2ARC reads, and no fear of degrading read performance
4040  * through increased writes.
4041  *
4042  * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
4043  * the vdev queue can aggregate them into larger and fewer writes.  Each
4044  * device is written to in a rotor fashion, sweeping writes through
4045  * available space then repeating.
4046  *
4047  * 7. The L2ARC does not store dirty content.  It never needs to flush
4048  * write buffers back to disk based storage.
4049  *
4050  * 8. If an ARC buffer is written (and dirtied) which also exists in the
4051  * L2ARC, the now stale L2ARC buffer is immediately dropped.
4052  *
4053  * The performance of the L2ARC can be tweaked by a number of tunables, which
4054  * may be necessary for different workloads:
4055  *
4056  *      l2arc_write_max         max write bytes per interval
4057  *      l2arc_write_boost       extra write bytes during device warmup
4058  *      l2arc_noprefetch        skip caching prefetched buffers
4059  *      l2arc_headroom          number of max device writes to precache
4060  *      l2arc_headroom_boost    when we find compressed buffers during ARC
4061  *                              scanning, we multiply headroom by this
4062  *                              percentage factor for the next scan cycle,
4063  *                              since more compressed buffers are likely to
4064  *                              be present
4065  *      l2arc_feed_secs         seconds between L2ARC writing
4066  *
4067  * Tunables may be removed or added as future performance improvements are
4068  * integrated, and also may become zpool properties.
4069  *
4070  * There are three key functions that control how the L2ARC warms up:
4071  *
4072  *      l2arc_write_eligible()  check if a buffer is eligible to cache
4073  *      l2arc_write_size()      calculate how much to write
4074  *      l2arc_write_interval()  calculate sleep delay between writes
4075  *
4076  * These three functions determine what to write, how much, and how quickly
4077  * to send writes.
4078  */
4079 
4080 static boolean_t
4081 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *ab)
4082 {
4083         /*
4084          * A buffer is *not* eligible for the L2ARC if it:
4085          * 1. belongs to a different spa.
4086          * 2. is already cached on the L2ARC.
4087          * 3. has an I/O in progress (it may be an incomplete read).
4088          * 4. is flagged not eligible (zfs property).
4089          */
4090         if (ab->b_spa != spa_guid || ab->b_l2hdr != NULL ||
4091             HDR_IO_IN_PROGRESS(ab) || !HDR_L2CACHE(ab))
4092                 return (B_FALSE);
4093 
4094         return (B_TRUE);
4095 }
4096 
4097 static uint64_t
4098 l2arc_write_size(void)
4099 {
4100         uint64_t size;
4101 
4102         /*
4103          * Make sure our globals have meaningful values in case the user
4104          * altered them.
4105          */
4106         size = l2arc_write_max;
4107         if (size == 0) {
4108                 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
4109                     "be greater than zero, resetting it to the default (%d)",
4110                     L2ARC_WRITE_SIZE);
4111                 size = l2arc_write_max = L2ARC_WRITE_SIZE;
4112         }
4113 
4114         if (arc_warm == B_FALSE)
4115                 size += l2arc_write_boost;
4116 
4117         return (size);
4118 
4119 }
4120 
4121 static clock_t
4122 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
4123 {
4124         clock_t interval, next, now;
4125 
4126         /*
4127          * If the ARC lists are busy, increase our write rate; if the
4128          * lists are stale, idle back.  This is achieved by checking
4129          * how much we previously wrote - if it was more than half of
4130          * what we wanted, schedule the next write much sooner.
4131          */
4132         if (l2arc_feed_again && wrote > (wanted / 2))
4133                 interval = (hz * l2arc_feed_min_ms) / 1000;
4134         else
4135                 interval = hz * l2arc_feed_secs;
4136 
4137         now = ddi_get_lbolt();
4138         next = MAX(now, MIN(now + interval, began + interval));
4139 
4140         return (next);
4141 }
4142 
4143 static void
4144 l2arc_hdr_stat_add(void)
4145 {
4146         ARCSTAT_INCR(arcstat_l2_hdr_size, HDR_SIZE + L2HDR_SIZE);
4147         ARCSTAT_INCR(arcstat_hdr_size, -HDR_SIZE);
4148 }
4149 
4150 static void
4151 l2arc_hdr_stat_remove(void)
4152 {
4153         ARCSTAT_INCR(arcstat_l2_hdr_size, -(HDR_SIZE + L2HDR_SIZE));
4154         ARCSTAT_INCR(arcstat_hdr_size, HDR_SIZE);
4155 }
4156 
4157 /*
4158  * Cycle through L2ARC devices.  This is how L2ARC load balances.
4159  * If a device is returned, this also returns holding the spa config lock.
4160  */
4161 static l2arc_dev_t *
4162 l2arc_dev_get_next(void)
4163 {
4164         l2arc_dev_t *first, *next = NULL;
4165 
4166         /*
4167          * Lock out the removal of spas (spa_namespace_lock), then removal
4168          * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
4169          * both locks will be dropped and a spa config lock held instead.
4170          */
4171         mutex_enter(&spa_namespace_lock);
4172         mutex_enter(&l2arc_dev_mtx);
4173 
4174         /* if there are no vdevs, there is nothing to do */
4175         if (l2arc_ndev == 0)
4176                 goto out;
4177 
4178         first = NULL;
4179         next = l2arc_dev_last;
4180         do {
4181                 /* loop around the list looking for a non-faulted vdev */
4182                 if (next == NULL) {
4183                         next = list_head(l2arc_dev_list);
4184                 } else {
4185                         next = list_next(l2arc_dev_list, next);
4186                         if (next == NULL)
4187                                 next = list_head(l2arc_dev_list);
4188                 }
4189 
4190                 /* if we have come back to the start, bail out */
4191                 if (first == NULL)
4192                         first = next;
4193                 else if (next == first)
4194                         break;
4195 
4196         } while (vdev_is_dead(next->l2ad_vdev));
4197 
4198         /* if we were unable to find any usable vdevs, return NULL */
4199         if (vdev_is_dead(next->l2ad_vdev))
4200                 next = NULL;
4201 
4202         l2arc_dev_last = next;
4203 
4204 out:
4205         mutex_exit(&l2arc_dev_mtx);
4206 
4207         /*
4208          * Grab the config lock to prevent the 'next' device from being
4209          * removed while we are writing to it.
4210          */
4211         if (next != NULL)
4212                 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
4213         mutex_exit(&spa_namespace_lock);
4214 
4215         return (next);
4216 }
4217 
4218 /*
4219  * Free buffers that were tagged for destruction.
4220  */
4221 static void
4222 l2arc_do_free_on_write()
4223 {
4224         list_t *buflist;
4225         l2arc_data_free_t *df, *df_prev;
4226 
4227         mutex_enter(&l2arc_free_on_write_mtx);
4228         buflist = l2arc_free_on_write;
4229 
4230         for (df = list_tail(buflist); df; df = df_prev) {
4231                 df_prev = list_prev(buflist, df);
4232                 ASSERT(df->l2df_data != NULL);
4233                 ASSERT(df->l2df_func != NULL);
4234                 df->l2df_func(df->l2df_data, df->l2df_size);
4235                 list_remove(buflist, df);
4236                 kmem_free(df, sizeof (l2arc_data_free_t));
4237         }
4238 
4239         mutex_exit(&l2arc_free_on_write_mtx);
4240 }
4241 
4242 /*
4243  * A write to a cache device has completed.  Update all headers to allow
4244  * reads from these buffers to begin.
4245  */
4246 static void
4247 l2arc_write_done(zio_t *zio)
4248 {
4249         l2arc_write_callback_t *cb;
4250         l2arc_dev_t *dev;
4251         list_t *buflist;
4252         arc_buf_hdr_t *head, *ab, *ab_prev;
4253         l2arc_buf_hdr_t *abl2;
4254         kmutex_t *hash_lock;
4255         int64_t bytes_dropped = 0;
4256 
4257         cb = zio->io_private;
4258         ASSERT(cb != NULL);
4259         dev = cb->l2wcb_dev;
4260         ASSERT(dev != NULL);
4261         head = cb->l2wcb_head;
4262         ASSERT(head != NULL);
4263         buflist = dev->l2ad_buflist;
4264         ASSERT(buflist != NULL);
4265         DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
4266             l2arc_write_callback_t *, cb);
4267 
4268         if (zio->io_error != 0)
4269                 ARCSTAT_BUMP(arcstat_l2_writes_error);
4270 
4271         mutex_enter(&l2arc_buflist_mtx);
4272 
4273         /*
4274          * All writes completed, or an error was hit.
4275          */
4276         for (ab = list_prev(buflist, head); ab; ab = ab_prev) {
4277                 ab_prev = list_prev(buflist, ab);
4278                 abl2 = ab->b_l2hdr;
4279 
4280                 /*
4281                  * Release the temporary compressed buffer as soon as possible.
4282                  */
4283                 if (abl2->b_compress != ZIO_COMPRESS_OFF)
4284                         l2arc_release_cdata_buf(ab);
4285 
4286                 hash_lock = HDR_LOCK(ab);
4287                 if (!mutex_tryenter(hash_lock)) {
4288                         /*
4289                          * This buffer misses out.  It may be in a stage
4290                          * of eviction.  Its ARC_L2_WRITING flag will be
4291                          * left set, denying reads to this buffer.
4292                          */
4293                         ARCSTAT_BUMP(arcstat_l2_writes_hdr_miss);
4294                         continue;
4295                 }
4296 
4297                 if (zio->io_error != 0) {
4298                         /*
4299                          * Error - drop L2ARC entry.
4300                          */
4301                         list_remove(buflist, ab);
4302                         ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
4303                         bytes_dropped += abl2->b_asize;
4304                         ab->b_l2hdr = NULL;
4305                         kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
4306                         ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
4307                 }
4308 
4309                 /*
4310                  * Allow ARC to begin reads to this L2ARC entry.
4311                  */
4312                 ab->b_flags &= ~ARC_L2_WRITING;
4313 
4314                 mutex_exit(hash_lock);
4315         }
4316 
4317         atomic_inc_64(&l2arc_writes_done);
4318         list_remove(buflist, head);
4319         kmem_cache_free(hdr_cache, head);
4320         mutex_exit(&l2arc_buflist_mtx);
4321 
4322         vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
4323 
4324         l2arc_do_free_on_write();
4325 
4326         kmem_free(cb, sizeof (l2arc_write_callback_t));
4327 }
4328 
4329 /*
4330  * A read to a cache device completed.  Validate buffer contents before
4331  * handing over to the regular ARC routines.
4332  */
4333 static void
4334 l2arc_read_done(zio_t *zio)
4335 {
4336         l2arc_read_callback_t *cb;
4337         arc_buf_hdr_t *hdr;
4338         arc_buf_t *buf;
4339         kmutex_t *hash_lock;
4340         int equal;
4341 
4342         ASSERT(zio->io_vd != NULL);
4343         ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
4344 
4345         spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
4346 
4347         cb = zio->io_private;
4348         ASSERT(cb != NULL);
4349         buf = cb->l2rcb_buf;
4350         ASSERT(buf != NULL);
4351 
4352         hash_lock = HDR_LOCK(buf->b_hdr);
4353         mutex_enter(hash_lock);
4354         hdr = buf->b_hdr;
4355         ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4356 
4357         /*
4358          * If the buffer was compressed, decompress it first.
4359          */
4360         if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
4361                 l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
4362         ASSERT(zio->io_data != NULL);
4363 
4364         /*
4365          * Check this survived the L2ARC journey.
4366          */
4367         equal = arc_cksum_equal(buf);
4368         if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
4369                 mutex_exit(hash_lock);
4370                 zio->io_private = buf;
4371                 zio->io_bp_copy = cb->l2rcb_bp;   /* XXX fix in L2ARC 2.0 */
4372                 zio->io_bp = &zio->io_bp_copy;        /* XXX fix in L2ARC 2.0 */
4373                 arc_read_done(zio);
4374         } else {
4375                 mutex_exit(hash_lock);
4376                 /*
4377                  * Buffer didn't survive caching.  Increment stats and
4378                  * reissue to the original storage device.
4379                  */
4380                 if (zio->io_error != 0) {
4381                         ARCSTAT_BUMP(arcstat_l2_io_error);
4382                 } else {
4383                         zio->io_error = SET_ERROR(EIO);
4384                 }
4385                 if (!equal)
4386                         ARCSTAT_BUMP(arcstat_l2_cksum_bad);
4387 
4388                 /*
4389                  * If there's no waiter, issue an async i/o to the primary
4390                  * storage now.  If there *is* a waiter, the caller must
4391                  * issue the i/o in a context where it's OK to block.
4392                  */
4393                 if (zio->io_waiter == NULL) {
4394                         zio_t *pio = zio_unique_parent(zio);
4395 
4396                         ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
4397 
4398                         zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
4399                             buf->b_data, zio->io_size, arc_read_done, buf,
4400                             zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
4401                 }
4402         }
4403 
4404         kmem_free(cb, sizeof (l2arc_read_callback_t));
4405 }
4406 
4407 /*
4408  * This is the list priority from which the L2ARC will search for pages to
4409  * cache.  This is used within loops (0..3) to cycle through lists in the
4410  * desired order.  This order can have a significant effect on cache
4411  * performance.
4412  *
4413  * Currently the metadata lists are hit first, MFU then MRU, followed by
4414  * the data lists.  This function returns a locked list, and also returns
4415  * the lock pointer.
4416  */
4417 static list_t *
4418 l2arc_list_locked(int list_num, kmutex_t **lock)
4419 {
4420         list_t *list = NULL;
4421 
4422         ASSERT(list_num >= 0 && list_num <= 3);
4423 
4424         switch (list_num) {
4425         case 0:
4426                 list = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
4427                 *lock = &arc_mfu->arcs_mtx;
4428                 break;
4429         case 1:
4430                 list = &arc_mru->arcs_list[ARC_BUFC_METADATA];
4431                 *lock = &arc_mru->arcs_mtx;
4432                 break;
4433         case 2:
4434                 list = &arc_mfu->arcs_list[ARC_BUFC_DATA];
4435                 *lock = &arc_mfu->arcs_mtx;
4436                 break;
4437         case 3:
4438                 list = &arc_mru->arcs_list[ARC_BUFC_DATA];
4439                 *lock = &arc_mru->arcs_mtx;
4440                 break;
4441         }
4442 
4443         ASSERT(!(MUTEX_HELD(*lock)));
4444         mutex_enter(*lock);
4445         return (list);
4446 }
4447 
4448 /*
4449  * Evict buffers from the device write hand to the distance specified in
4450  * bytes.  This distance may span populated buffers, it may span nothing.
4451  * This is clearing a region on the L2ARC device ready for writing.
4452  * If the 'all' boolean is set, every buffer is evicted.
4453  */
4454 static void
4455 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
4456 {
4457         list_t *buflist;
4458         l2arc_buf_hdr_t *abl2;
4459         arc_buf_hdr_t *ab, *ab_prev;
4460         kmutex_t *hash_lock;
4461         uint64_t taddr;
4462         int64_t bytes_evicted = 0;
4463 
4464         buflist = dev->l2ad_buflist;
4465 
4466         if (buflist == NULL)
4467                 return;
4468 
4469         if (!all && dev->l2ad_first) {
4470                 /*
4471                  * This is the first sweep through the device.  There is
4472                  * nothing to evict.
4473                  */
4474                 return;
4475         }
4476 
4477         if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
4478                 /*
4479                  * When nearing the end of the device, evict to the end
4480                  * before the device write hand jumps to the start.
4481                  */
4482                 taddr = dev->l2ad_end;
4483         } else {
4484                 taddr = dev->l2ad_hand + distance;
4485         }
4486         DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
4487             uint64_t, taddr, boolean_t, all);
4488 
4489 top:
4490         mutex_enter(&l2arc_buflist_mtx);
4491         for (ab = list_tail(buflist); ab; ab = ab_prev) {
4492                 ab_prev = list_prev(buflist, ab);
4493 
4494                 hash_lock = HDR_LOCK(ab);
4495                 if (!mutex_tryenter(hash_lock)) {
4496                         /*
4497                          * Missed the hash lock.  Retry.
4498                          */
4499                         ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
4500                         mutex_exit(&l2arc_buflist_mtx);
4501                         mutex_enter(hash_lock);
4502                         mutex_exit(hash_lock);
4503                         goto top;
4504                 }
4505 
4506                 if (HDR_L2_WRITE_HEAD(ab)) {
4507                         /*
4508                          * We hit a write head node.  Leave it for
4509                          * l2arc_write_done().
4510                          */
4511                         list_remove(buflist, ab);
4512                         mutex_exit(hash_lock);
4513                         continue;
4514                 }
4515 
4516                 if (!all && ab->b_l2hdr != NULL &&
4517                     (ab->b_l2hdr->b_daddr > taddr ||
4518                     ab->b_l2hdr->b_daddr < dev->l2ad_hand)) {
4519                         /*
4520                          * We've evicted to the target address,
4521                          * or the end of the device.
4522                          */
4523                         mutex_exit(hash_lock);
4524                         break;
4525                 }
4526 
4527                 if (HDR_FREE_IN_PROGRESS(ab)) {
4528                         /*
4529                          * Already on the path to destruction.
4530                          */
4531                         mutex_exit(hash_lock);
4532                         continue;
4533                 }
4534 
4535                 if (ab->b_state == arc_l2c_only) {
4536                         ASSERT(!HDR_L2_READING(ab));
4537                         /*
4538                          * This doesn't exist in the ARC.  Destroy.
4539                          * arc_hdr_destroy() will call list_remove()
4540                          * and decrement arcstat_l2_size.
4541                          */
4542                         arc_change_state(arc_anon, ab, hash_lock);
4543                         arc_hdr_destroy(ab);
4544                 } else {
4545                         /*
4546                          * Invalidate issued or about to be issued
4547                          * reads, since we may be about to write
4548                          * over this location.
4549                          */
4550                         if (HDR_L2_READING(ab)) {
4551                                 ARCSTAT_BUMP(arcstat_l2_evict_reading);
4552                                 ab->b_flags |= ARC_L2_EVICTED;
4553                         }
4554 
4555                         /*
4556                          * Tell ARC this no longer exists in L2ARC.
4557                          */
4558                         if (ab->b_l2hdr != NULL) {
4559                                 abl2 = ab->b_l2hdr;
4560                                 ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
4561                                 bytes_evicted += abl2->b_asize;
4562                                 ab->b_l2hdr = NULL;
4563                                 /*
4564                                  * We are destroying l2hdr, so ensure that
4565                                  * its compressed buffer, if any, is not leaked.
4566                                  */
4567                                 ASSERT(abl2->b_tmp_cdata == NULL);
4568                                 kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
4569                                 ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
4570                         }
4571                         list_remove(buflist, ab);
4572 
4573                         /*
4574                          * This may have been leftover after a
4575                          * failed write.
4576                          */
4577                         ab->b_flags &= ~ARC_L2_WRITING;
4578                 }
4579                 mutex_exit(hash_lock);
4580         }
4581         mutex_exit(&l2arc_buflist_mtx);
4582 
4583         vdev_space_update(dev->l2ad_vdev, -bytes_evicted, 0, 0);
4584         dev->l2ad_evict = taddr;
4585 }
4586 
4587 /*
4588  * Find and write ARC buffers to the L2ARC device.
4589  *
4590  * An ARC_L2_WRITING flag is set so that the L2ARC buffers are not valid
4591  * for reading until they have completed writing.
4592  * The headroom_boost is an in-out parameter used to maintain headroom boost
4593  * state between calls to this function.
4594  *
4595  * Returns the number of bytes actually written (which may be smaller than
4596  * the delta by which the device hand has changed due to alignment).
4597  */
4598 static uint64_t
4599 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
4600     boolean_t *headroom_boost)
4601 {
4602         arc_buf_hdr_t *ab, *ab_prev, *head;
4603         list_t *list;
4604         uint64_t write_asize, write_psize, write_sz, headroom,
4605             buf_compress_minsz;
4606         void *buf_data;
4607         kmutex_t *list_lock;
4608         boolean_t full;
4609         l2arc_write_callback_t *cb;
4610         zio_t *pio, *wzio;
4611         uint64_t guid = spa_load_guid(spa);
4612         const boolean_t do_headroom_boost = *headroom_boost;
4613 
4614         ASSERT(dev->l2ad_vdev != NULL);
4615 
4616         /* Lower the flag now, we might want to raise it again later. */
4617         *headroom_boost = B_FALSE;
4618 
4619         pio = NULL;
4620         write_sz = write_asize = write_psize = 0;
4621         full = B_FALSE;
4622         head = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
4623         head->b_flags |= ARC_L2_WRITE_HEAD;
4624 
4625         /*
4626          * We will want to try to compress buffers that are at least 2x the
4627          * device sector size.
4628          */
4629         buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
4630 
4631         /*
4632          * Copy buffers for L2ARC writing.
4633          */
4634         mutex_enter(&l2arc_buflist_mtx);
4635         for (int try = 0; try <= 3; try++) {
4636                 uint64_t passed_sz = 0;
4637 
4638                 list = l2arc_list_locked(try, &list_lock);
4639 
4640                 /*
4641                  * L2ARC fast warmup.
4642                  *
4643                  * Until the ARC is warm and starts to evict, read from the
4644                  * head of the ARC lists rather than the tail.
4645                  */
4646                 if (arc_warm == B_FALSE)
4647                         ab = list_head(list);
4648                 else
4649                         ab = list_tail(list);
4650 
4651                 headroom = target_sz * l2arc_headroom;
4652                 if (do_headroom_boost)
4653                         headroom = (headroom * l2arc_headroom_boost) / 100;
4654 
4655                 for (; ab; ab = ab_prev) {
4656                         l2arc_buf_hdr_t *l2hdr;
4657                         kmutex_t *hash_lock;
4658                         uint64_t buf_sz;
4659 
4660                         if (arc_warm == B_FALSE)
4661                                 ab_prev = list_next(list, ab);
4662                         else
4663                                 ab_prev = list_prev(list, ab);
4664 
4665                         hash_lock = HDR_LOCK(ab);
4666                         if (!mutex_tryenter(hash_lock)) {
4667                                 /*
4668                                  * Skip this buffer rather than waiting.
4669                                  */
4670                                 continue;
4671                         }
4672 
4673                         passed_sz += ab->b_size;
4674                         if (passed_sz > headroom) {
4675                                 /*
4676                                  * Searched too far.
4677                                  */
4678                                 mutex_exit(hash_lock);
4679                                 break;
4680                         }
4681 
4682                         if (!l2arc_write_eligible(guid, ab)) {
4683                                 mutex_exit(hash_lock);
4684                                 continue;
4685                         }
4686 
4687                         if ((write_sz + ab->b_size) > target_sz) {
4688                                 full = B_TRUE;
4689                                 mutex_exit(hash_lock);
4690                                 break;
4691                         }
4692 
4693                         if (pio == NULL) {
4694                                 /*
4695                                  * Insert a dummy header on the buflist so
4696                                  * l2arc_write_done() can find where the
4697                                  * write buffers begin without searching.
4698                                  */
4699                                 list_insert_head(dev->l2ad_buflist, head);
4700 
4701                                 cb = kmem_alloc(
4702                                     sizeof (l2arc_write_callback_t), KM_SLEEP);
4703                                 cb->l2wcb_dev = dev;
4704                                 cb->l2wcb_head = head;
4705                                 pio = zio_root(spa, l2arc_write_done, cb,
4706                                     ZIO_FLAG_CANFAIL);
4707                         }
4708 
4709                         /*
4710                          * Create and add a new L2ARC header.
4711                          */
4712                         l2hdr = kmem_zalloc(sizeof (l2arc_buf_hdr_t), KM_SLEEP);
4713                         l2hdr->b_dev = dev;
4714                         ab->b_flags |= ARC_L2_WRITING;
4715 
4716                         /*
4717                          * Temporarily stash the data buffer in b_tmp_cdata.
4718                          * The subsequent write step will pick it up from
4719                          * there. This is because can't access ab->b_buf
4720                          * without holding the hash_lock, which we in turn
4721                          * can't access without holding the ARC list locks
4722                          * (which we want to avoid during compression/writing).
4723                          */
4724                         l2hdr->b_compress = ZIO_COMPRESS_OFF;
4725                         l2hdr->b_asize = ab->b_size;
4726                         l2hdr->b_tmp_cdata = ab->b_buf->b_data;
4727 
4728                         buf_sz = ab->b_size;
4729                         ab->b_l2hdr = l2hdr;
4730 
4731                         list_insert_head(dev->l2ad_buflist, ab);
4732 
4733                         /*
4734                          * Compute and store the buffer cksum before
4735                          * writing.  On debug the cksum is verified first.
4736                          */
4737                         arc_cksum_verify(ab->b_buf);
4738                         arc_cksum_compute(ab->b_buf, B_TRUE);
4739 
4740                         mutex_exit(hash_lock);
4741 
4742                         write_sz += buf_sz;
4743                 }
4744 
4745                 mutex_exit(list_lock);
4746 
4747                 if (full == B_TRUE)
4748                         break;
4749         }
4750 
4751         /* No buffers selected for writing? */
4752         if (pio == NULL) {
4753                 ASSERT0(write_sz);
4754                 mutex_exit(&l2arc_buflist_mtx);
4755                 kmem_cache_free(hdr_cache, head);
4756                 return (0);
4757         }
4758 
4759         /*
4760          * Now start writing the buffers. We're starting at the write head
4761          * and work backwards, retracing the course of the buffer selector
4762          * loop above.
4763          */
4764         for (ab = list_prev(dev->l2ad_buflist, head); ab;
4765             ab = list_prev(dev->l2ad_buflist, ab)) {
4766                 l2arc_buf_hdr_t *l2hdr;
4767                 uint64_t buf_sz;
4768 
4769                 /*
4770                  * We shouldn't need to lock the buffer here, since we flagged
4771                  * it as ARC_L2_WRITING in the previous step, but we must take
4772                  * care to only access its L2 cache parameters. In particular,
4773                  * ab->b_buf may be invalid by now due to ARC eviction.
4774                  */
4775                 l2hdr = ab->b_l2hdr;
4776                 l2hdr->b_daddr = dev->l2ad_hand;
4777 
4778                 if ((ab->b_flags & ARC_L2COMPRESS) &&
4779                     l2hdr->b_asize >= buf_compress_minsz) {
4780                         if (l2arc_compress_buf(l2hdr)) {
4781                                 /*
4782                                  * If compression succeeded, enable headroom
4783                                  * boost on the next scan cycle.
4784                                  */
4785                                 *headroom_boost = B_TRUE;
4786                         }
4787                 }
4788 
4789                 /*
4790                  * Pick up the buffer data we had previously stashed away
4791                  * (and now potentially also compressed).
4792                  */
4793                 buf_data = l2hdr->b_tmp_cdata;
4794                 buf_sz = l2hdr->b_asize;
4795 
4796                 /*
4797                  * If the data has not been compressed, then clear b_tmp_cdata
4798                  * to make sure that it points only to a temporary compression
4799                  * buffer.
4800                  */
4801                 if (!L2ARC_IS_VALID_COMPRESS(l2hdr->b_compress))
4802                         l2hdr->b_tmp_cdata = NULL;
4803 
4804                 /* Compression may have squashed the buffer to zero length. */
4805                 if (buf_sz != 0) {
4806                         uint64_t buf_p_sz;
4807 
4808                         wzio = zio_write_phys(pio, dev->l2ad_vdev,
4809                             dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
4810                             NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
4811                             ZIO_FLAG_CANFAIL, B_FALSE);
4812 
4813                         DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
4814                             zio_t *, wzio);
4815                         (void) zio_nowait(wzio);
4816 
4817                         write_asize += buf_sz;
4818                         /*
4819                          * Keep the clock hand suitably device-aligned.
4820                          */
4821                         buf_p_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
4822                         write_psize += buf_p_sz;
4823                         dev->l2ad_hand += buf_p_sz;
4824                 }
4825         }
4826 
4827         mutex_exit(&l2arc_buflist_mtx);
4828 
4829         ASSERT3U(write_asize, <=, target_sz);
4830         ARCSTAT_BUMP(arcstat_l2_writes_sent);
4831         ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
4832         ARCSTAT_INCR(arcstat_l2_size, write_sz);
4833         ARCSTAT_INCR(arcstat_l2_asize, write_asize);
4834         vdev_space_update(dev->l2ad_vdev, write_asize, 0, 0);
4835 
4836         /*
4837          * Bump device hand to the device start if it is approaching the end.
4838          * l2arc_evict() will already have evicted ahead for this case.
4839          */
4840         if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
4841                 dev->l2ad_hand = dev->l2ad_start;
4842                 dev->l2ad_evict = dev->l2ad_start;
4843                 dev->l2ad_first = B_FALSE;
4844         }
4845 
4846         dev->l2ad_writing = B_TRUE;
4847         (void) zio_wait(pio);
4848         dev->l2ad_writing = B_FALSE;
4849 
4850         return (write_asize);
4851 }
4852 
4853 /*
4854  * Compresses an L2ARC buffer.
4855  * The data to be compressed must be prefilled in l2hdr->b_tmp_cdata and its
4856  * size in l2hdr->b_asize. This routine tries to compress the data and
4857  * depending on the compression result there are three possible outcomes:
4858  * *) The buffer was incompressible. The original l2hdr contents were left
4859  *    untouched and are ready for writing to an L2 device.
4860  * *) The buffer was all-zeros, so there is no need to write it to an L2
4861  *    device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
4862  *    set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
4863  * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
4864  *    data buffer which holds the compressed data to be written, and b_asize
4865  *    tells us how much data there is. b_compress is set to the appropriate
4866  *    compression algorithm. Once writing is done, invoke
4867  *    l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
4868  *
4869  * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
4870  * buffer was incompressible).
4871  */
4872 static boolean_t
4873 l2arc_compress_buf(l2arc_buf_hdr_t *l2hdr)
4874 {
4875         void *cdata;
4876         size_t csize, len, rounded;
4877 
4878         ASSERT(l2hdr->b_compress == ZIO_COMPRESS_OFF);
4879         ASSERT(l2hdr->b_tmp_cdata != NULL);
4880 
4881         len = l2hdr->b_asize;
4882         cdata = zio_data_buf_alloc(len);
4883         csize = zio_compress_data(ZIO_COMPRESS_LZ4, l2hdr->b_tmp_cdata,
4884             cdata, l2hdr->b_asize);
4885 
4886         rounded = P2ROUNDUP(csize, (size_t)SPA_MINBLOCKSIZE);
4887         if (rounded > csize) {
4888                 bzero((char *)cdata + csize, rounded - csize);
4889                 csize = rounded;
4890         }
4891 
4892         if (csize == 0) {
4893                 /* zero block, indicate that there's nothing to write */
4894                 zio_data_buf_free(cdata, len);
4895                 l2hdr->b_compress = ZIO_COMPRESS_EMPTY;
4896                 l2hdr->b_asize = 0;
4897                 l2hdr->b_tmp_cdata = NULL;
4898                 ARCSTAT_BUMP(arcstat_l2_compress_zeros);
4899                 return (B_TRUE);
4900         } else if (csize > 0 && csize < len) {
4901                 /*
4902                  * Compression succeeded, we'll keep the cdata around for
4903                  * writing and release it afterwards.
4904                  */
4905                 l2hdr->b_compress = ZIO_COMPRESS_LZ4;
4906                 l2hdr->b_asize = csize;
4907                 l2hdr->b_tmp_cdata = cdata;
4908                 ARCSTAT_BUMP(arcstat_l2_compress_successes);
4909                 return (B_TRUE);
4910         } else {
4911                 /*
4912                  * Compression failed, release the compressed buffer.
4913                  * l2hdr will be left unmodified.
4914                  */
4915                 zio_data_buf_free(cdata, len);
4916                 ARCSTAT_BUMP(arcstat_l2_compress_failures);
4917                 return (B_FALSE);
4918         }
4919 }
4920 
4921 /*
4922  * Decompresses a zio read back from an l2arc device. On success, the
4923  * underlying zio's io_data buffer is overwritten by the uncompressed
4924  * version. On decompression error (corrupt compressed stream), the
4925  * zio->io_error value is set to signal an I/O error.
4926  *
4927  * Please note that the compressed data stream is not checksummed, so
4928  * if the underlying device is experiencing data corruption, we may feed
4929  * corrupt data to the decompressor, so the decompressor needs to be
4930  * able to handle this situation (LZ4 does).
4931  */
4932 static void
4933 l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
4934 {
4935         ASSERT(L2ARC_IS_VALID_COMPRESS(c));
4936 
4937         if (zio->io_error != 0) {
4938                 /*
4939                  * An io error has occured, just restore the original io
4940                  * size in preparation for a main pool read.
4941                  */
4942                 zio->io_orig_size = zio->io_size = hdr->b_size;
4943                 return;
4944         }
4945 
4946         if (c == ZIO_COMPRESS_EMPTY) {
4947                 /*
4948                  * An empty buffer results in a null zio, which means we
4949                  * need to fill its io_data after we're done restoring the
4950                  * buffer's contents.
4951                  */
4952                 ASSERT(hdr->b_buf != NULL);
4953                 bzero(hdr->b_buf->b_data, hdr->b_size);
4954                 zio->io_data = zio->io_orig_data = hdr->b_buf->b_data;
4955         } else {
4956                 ASSERT(zio->io_data != NULL);
4957                 /*
4958                  * We copy the compressed data from the start of the arc buffer
4959                  * (the zio_read will have pulled in only what we need, the
4960                  * rest is garbage which we will overwrite at decompression)
4961                  * and then decompress back to the ARC data buffer. This way we
4962                  * can minimize copying by simply decompressing back over the
4963                  * original compressed data (rather than decompressing to an
4964                  * aux buffer and then copying back the uncompressed buffer,
4965                  * which is likely to be much larger).
4966                  */
4967                 uint64_t csize;
4968                 void *cdata;
4969 
4970                 csize = zio->io_size;
4971                 cdata = zio_data_buf_alloc(csize);
4972                 bcopy(zio->io_data, cdata, csize);
4973                 if (zio_decompress_data(c, cdata, zio->io_data, csize,
4974                     hdr->b_size) != 0)
4975                         zio->io_error = EIO;
4976                 zio_data_buf_free(cdata, csize);
4977         }
4978 
4979         /* Restore the expected uncompressed IO size. */
4980         zio->io_orig_size = zio->io_size = hdr->b_size;
4981 }
4982 
4983 /*
4984  * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
4985  * This buffer serves as a temporary holder of compressed data while
4986  * the buffer entry is being written to an l2arc device. Once that is
4987  * done, we can dispose of it.
4988  */
4989 static void
4990 l2arc_release_cdata_buf(arc_buf_hdr_t *ab)
4991 {
4992         l2arc_buf_hdr_t *l2hdr = ab->b_l2hdr;
4993 
4994         ASSERT(L2ARC_IS_VALID_COMPRESS(l2hdr->b_compress));
4995         if (l2hdr->b_compress != ZIO_COMPRESS_EMPTY) {
4996                 /*
4997                  * If the data was compressed, then we've allocated a
4998                  * temporary buffer for it, so now we need to release it.
4999                  */
5000                 ASSERT(l2hdr->b_tmp_cdata != NULL);
5001                 zio_data_buf_free(l2hdr->b_tmp_cdata, ab->b_size);
5002                 l2hdr->b_tmp_cdata = NULL;
5003         } else {
5004                 ASSERT(l2hdr->b_tmp_cdata == NULL);
5005         }
5006 }
5007 
5008 /*
5009  * This thread feeds the L2ARC at regular intervals.  This is the beating
5010  * heart of the L2ARC.
5011  */
5012 static void
5013 l2arc_feed_thread(void)
5014 {
5015         callb_cpr_t cpr;
5016         l2arc_dev_t *dev;
5017         spa_t *spa;
5018         uint64_t size, wrote;
5019         clock_t begin, next = ddi_get_lbolt();
5020         boolean_t headroom_boost = B_FALSE;
5021 
5022         CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
5023 
5024         mutex_enter(&l2arc_feed_thr_lock);
5025 
5026         while (l2arc_thread_exit == 0) {
5027                 CALLB_CPR_SAFE_BEGIN(&cpr);
5028                 (void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
5029                     next);
5030                 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
5031                 next = ddi_get_lbolt() + hz;
5032 
5033                 /*
5034                  * Quick check for L2ARC devices.
5035                  */
5036                 mutex_enter(&l2arc_dev_mtx);
5037                 if (l2arc_ndev == 0) {
5038                         mutex_exit(&l2arc_dev_mtx);
5039                         continue;
5040                 }
5041                 mutex_exit(&l2arc_dev_mtx);
5042                 begin = ddi_get_lbolt();
5043 
5044                 /*
5045                  * This selects the next l2arc device to write to, and in
5046                  * doing so the next spa to feed from: dev->l2ad_spa.   This
5047                  * will return NULL if there are now no l2arc devices or if
5048                  * they are all faulted.
5049                  *
5050                  * If a device is returned, its spa's config lock is also
5051                  * held to prevent device removal.  l2arc_dev_get_next()
5052                  * will grab and release l2arc_dev_mtx.
5053                  */
5054                 if ((dev = l2arc_dev_get_next()) == NULL)
5055                         continue;
5056 
5057                 spa = dev->l2ad_spa;
5058                 ASSERT(spa != NULL);
5059 
5060                 /*
5061                  * If the pool is read-only then force the feed thread to
5062                  * sleep a little longer.
5063                  */
5064                 if (!spa_writeable(spa)) {
5065                         next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
5066                         spa_config_exit(spa, SCL_L2ARC, dev);
5067                         continue;
5068                 }
5069 
5070                 /*
5071                  * Avoid contributing to memory pressure.
5072                  */
5073                 if (arc_reclaim_needed()) {
5074                         ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
5075                         spa_config_exit(spa, SCL_L2ARC, dev);
5076                         continue;
5077                 }
5078 
5079                 ARCSTAT_BUMP(arcstat_l2_feeds);
5080 
5081                 size = l2arc_write_size();
5082 
5083                 /*
5084                  * Evict L2ARC buffers that will be overwritten.
5085                  */
5086                 l2arc_evict(dev, size, B_FALSE);
5087 
5088                 /*
5089                  * Write ARC buffers.
5090                  */
5091                 wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
5092 
5093                 /*
5094                  * Calculate interval between writes.
5095                  */
5096                 next = l2arc_write_interval(begin, size, wrote);
5097                 spa_config_exit(spa, SCL_L2ARC, dev);
5098         }
5099 
5100         l2arc_thread_exit = 0;
5101         cv_broadcast(&l2arc_feed_thr_cv);
5102         CALLB_CPR_EXIT(&cpr);               /* drops l2arc_feed_thr_lock */
5103         thread_exit();
5104 }
5105 
5106 boolean_t
5107 l2arc_vdev_present(vdev_t *vd)
5108 {
5109         l2arc_dev_t *dev;
5110 
5111         mutex_enter(&l2arc_dev_mtx);
5112         for (dev = list_head(l2arc_dev_list); dev != NULL;
5113             dev = list_next(l2arc_dev_list, dev)) {
5114                 if (dev->l2ad_vdev == vd)
5115                         break;
5116         }
5117         mutex_exit(&l2arc_dev_mtx);
5118 
5119         return (dev != NULL);
5120 }
5121 
5122 /*
5123  * Add a vdev for use by the L2ARC.  By this point the spa has already
5124  * validated the vdev and opened it.
5125  */
5126 void
5127 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
5128 {
5129         l2arc_dev_t *adddev;
5130 
5131         ASSERT(!l2arc_vdev_present(vd));
5132 
5133         /*
5134          * Create a new l2arc device entry.
5135          */
5136         adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
5137         adddev->l2ad_spa = spa;
5138         adddev->l2ad_vdev = vd;
5139         adddev->l2ad_start = VDEV_LABEL_START_SIZE;
5140         adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
5141         adddev->l2ad_hand = adddev->l2ad_start;
5142         adddev->l2ad_evict = adddev->l2ad_start;
5143         adddev->l2ad_first = B_TRUE;
5144         adddev->l2ad_writing = B_FALSE;
5145 
5146         /*
5147          * This is a list of all ARC buffers that are still valid on the
5148          * device.
5149          */
5150         adddev->l2ad_buflist = kmem_zalloc(sizeof (list_t), KM_SLEEP);
5151         list_create(adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
5152             offsetof(arc_buf_hdr_t, b_l2node));
5153 
5154         vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
5155 
5156         /*
5157          * Add device to global list
5158          */
5159         mutex_enter(&l2arc_dev_mtx);
5160         list_insert_head(l2arc_dev_list, adddev);
5161         atomic_inc_64(&l2arc_ndev);
5162         mutex_exit(&l2arc_dev_mtx);
5163 }
5164 
5165 /*
5166  * Remove a vdev from the L2ARC.
5167  */
5168 void
5169 l2arc_remove_vdev(vdev_t *vd)
5170 {
5171         l2arc_dev_t *dev, *nextdev, *remdev = NULL;
5172 
5173         /*
5174          * Find the device by vdev
5175          */
5176         mutex_enter(&l2arc_dev_mtx);
5177         for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
5178                 nextdev = list_next(l2arc_dev_list, dev);
5179                 if (vd == dev->l2ad_vdev) {
5180                         remdev = dev;
5181                         break;
5182                 }
5183         }
5184         ASSERT(remdev != NULL);
5185 
5186         /*
5187          * Remove device from global list
5188          */
5189         list_remove(l2arc_dev_list, remdev);
5190         l2arc_dev_last = NULL;          /* may have been invalidated */
5191         atomic_dec_64(&l2arc_ndev);
5192         mutex_exit(&l2arc_dev_mtx);
5193 
5194         /*
5195          * Clear all buflists and ARC references.  L2ARC device flush.
5196          */
5197         l2arc_evict(remdev, 0, B_TRUE);
5198         list_destroy(remdev->l2ad_buflist);
5199         kmem_free(remdev->l2ad_buflist, sizeof (list_t));
5200         kmem_free(remdev, sizeof (l2arc_dev_t));
5201 }
5202 
5203 void
5204 l2arc_init(void)
5205 {
5206         l2arc_thread_exit = 0;
5207         l2arc_ndev = 0;
5208         l2arc_writes_sent = 0;
5209         l2arc_writes_done = 0;
5210 
5211         mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
5212         cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
5213         mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
5214         mutex_init(&l2arc_buflist_mtx, NULL, MUTEX_DEFAULT, NULL);
5215         mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
5216 
5217         l2arc_dev_list = &L2ARC_dev_list;
5218         l2arc_free_on_write = &L2ARC_free_on_write;
5219         list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
5220             offsetof(l2arc_dev_t, l2ad_node));
5221         list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
5222             offsetof(l2arc_data_free_t, l2df_list_node));
5223 }
5224 
5225 void
5226 l2arc_fini(void)
5227 {
5228         /*
5229          * This is called from dmu_fini(), which is called from spa_fini();
5230          * Because of this, we can assume that all l2arc devices have
5231          * already been removed when the pools themselves were removed.
5232          */
5233 
5234         l2arc_do_free_on_write();
5235 
5236         mutex_destroy(&l2arc_feed_thr_lock);
5237         cv_destroy(&l2arc_feed_thr_cv);
5238         mutex_destroy(&l2arc_dev_mtx);
5239         mutex_destroy(&l2arc_buflist_mtx);
5240         mutex_destroy(&l2arc_free_on_write_mtx);
5241 
5242         list_destroy(l2arc_dev_list);
5243         list_destroy(l2arc_free_on_write);
5244 }
5245 
5246 void
5247 l2arc_start(void)
5248 {
5249         if (!(spa_mode_global & FWRITE))
5250                 return;
5251 
5252         (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
5253             TS_RUN, minclsyspri);
5254 }
5255 
5256 void
5257 l2arc_stop(void)
5258 {
5259         if (!(spa_mode_global & FWRITE))
5260                 return;
5261 
5262         mutex_enter(&l2arc_feed_thr_lock);
5263         cv_signal(&l2arc_feed_thr_cv);      /* kick thread out of startup */
5264         l2arc_thread_exit = 1;
5265         while (l2arc_thread_exit != 0)
5266                 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
5267         mutex_exit(&l2arc_feed_thr_lock);
5268 }