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 2018 Nexenta Systems, Inc.  All rights reserved.
  24  * Copyright (c) 2012, 2017 by Delphix. All rights reserved.
  25  * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
  26  * Copyright (c) 2013, Joyent, Inc. All rights reserved.
  27  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
  28  * Copyright (c) 2014 Integros [integros.com]
  29  */
  30 
  31 #include <sys/zfs_context.h>
  32 #include <sys/dmu.h>
  33 #include <sys/dmu_send.h>
  34 #include <sys/dmu_impl.h>
  35 #include <sys/dbuf.h>
  36 #include <sys/dmu_objset.h>
  37 #include <sys/dsl_dataset.h>
  38 #include <sys/dsl_dir.h>
  39 #include <sys/dmu_tx.h>
  40 #include <sys/spa.h>
  41 #include <sys/spa_impl.h>
  42 #include <sys/zio.h>
  43 #include <sys/dmu_zfetch.h>
  44 #include <sys/sa.h>
  45 #include <sys/sa_impl.h>
  46 #include <sys/zfeature.h>
  47 #include <sys/blkptr.h>
  48 #include <sys/range_tree.h>
  49 #include <sys/callb.h>
  50 #include <sys/abd.h>
  51 
  52 uint_t zfs_dbuf_evict_key;
  53 
  54 static boolean_t dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx);
  55 static void dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx);
  56 
  57 #ifndef __lint
  58 extern inline void dmu_buf_init_user(dmu_buf_user_t *dbu,
  59     dmu_buf_evict_func_t *evict_func_sync,
  60     dmu_buf_evict_func_t *evict_func_async,
  61     dmu_buf_t **clear_on_evict_dbufp);
  62 #endif /* ! __lint */
  63 
  64 /*
  65  * Global data structures and functions for the dbuf cache.
  66  */
  67 static kmem_cache_t *dbuf_kmem_cache;
  68 static taskq_t *dbu_evict_taskq;
  69 
  70 static kthread_t *dbuf_cache_evict_thread;
  71 static kmutex_t dbuf_evict_lock;
  72 static kcondvar_t dbuf_evict_cv;
  73 static boolean_t dbuf_evict_thread_exit;
  74 
  75 /*
  76  * There are two dbuf caches; each dbuf can only be in one of them at a time.
  77  *
  78  * 1. Cache of metadata dbufs, to help make read-heavy administrative commands
  79  *    from /sbin/zfs run faster. The "metadata cache" specifically stores dbufs
  80  *    that represent the metadata that describes filesystems/snapshots/
  81  *    bookmarks/properties/etc. We only evict from this cache when we export a
  82  *    pool, to short-circuit as much I/O as possible for all administrative
  83  *    commands that need the metadata. There is no eviction policy for this
  84  *    cache, because we try to only include types in it which would occupy a
  85  *    very small amount of space per object but create a large impact on the
  86  *    performance of these commands. Instead, after it reaches a maximum size
  87  *    (which should only happen on very small memory systems with a very large
  88  *    number of filesystem objects), we stop taking new dbufs into the
  89  *    metadata cache, instead putting them in the normal dbuf cache.
  90  *
  91  * 2. LRU cache of dbufs. The "dbuf cache" maintains a list of dbufs that
  92  *    are not currently held but have been recently released. These dbufs
  93  *    are not eligible for arc eviction until they are aged out of the cache.
  94  *    Dbufs that are aged out of the cache will be immediately destroyed and
  95  *    become eligible for arc eviction.
  96  *
  97  * Dbufs are added to these caches once the last hold is released. If a dbuf is
  98  * later accessed and still exists in the dbuf cache, then it will be removed
  99  * from the cache and later re-added to the head of the cache.
 100  *
 101  * If a given dbuf meets the requirements for the metadata cache, it will go
 102  * there, otherwise it will be considered for the generic LRU dbuf cache. The
 103  * caches and the refcounts tracking their sizes are stored in an array indexed
 104  * by those caches' matching enum values (from dbuf_cached_state_t).
 105  */
 106 typedef struct dbuf_cache {
 107         multilist_t *cache;
 108         refcount_t size;
 109 } dbuf_cache_t;
 110 dbuf_cache_t dbuf_caches[DB_CACHE_MAX];
 111 
 112 /* Size limits for the caches */
 113 uint64_t dbuf_cache_max_bytes = 0;
 114 uint64_t dbuf_metadata_cache_max_bytes = 0;
 115 /* Set the default sizes of the caches to log2 fraction of arc size */
 116 int dbuf_cache_shift = 5;
 117 int dbuf_metadata_cache_shift = 6;
 118 
 119 /*
 120  * For diagnostic purposes, this is incremented whenever we can't add
 121  * something to the metadata cache because it's full, and instead put
 122  * the data in the regular dbuf cache.
 123  */
 124 uint64_t dbuf_metadata_cache_overflow;
 125 
 126 /*
 127  * The LRU dbuf cache uses a three-stage eviction policy:
 128  *      - A low water marker designates when the dbuf eviction thread
 129  *      should stop evicting from the dbuf cache.
 130  *      - When we reach the maximum size (aka mid water mark), we
 131  *      signal the eviction thread to run.
 132  *      - The high water mark indicates when the eviction thread
 133  *      is unable to keep up with the incoming load and eviction must
 134  *      happen in the context of the calling thread.
 135  *
 136  * The dbuf cache:
 137  *                                                 (max size)
 138  *                                      low water   mid water   hi water
 139  * +----------------------------------------+----------+----------+
 140  * |                                        |          |          |
 141  * |                                        |          |          |
 142  * |                                        |          |          |
 143  * |                                        |          |          |
 144  * +----------------------------------------+----------+----------+
 145  *                                        stop        signal     evict
 146  *                                      evicting     eviction   directly
 147  *                                                    thread
 148  *
 149  * The high and low water marks indicate the operating range for the eviction
 150  * thread. The low water mark is, by default, 90% of the total size of the
 151  * cache and the high water mark is at 110% (both of these percentages can be
 152  * changed by setting dbuf_cache_lowater_pct and dbuf_cache_hiwater_pct,
 153  * respectively). The eviction thread will try to ensure that the cache remains
 154  * within this range by waking up every second and checking if the cache is
 155  * above the low water mark. The thread can also be woken up by callers adding
 156  * elements into the cache if the cache is larger than the mid water (i.e max
 157  * cache size). Once the eviction thread is woken up and eviction is required,
 158  * it will continue evicting buffers until it's able to reduce the cache size
 159  * to the low water mark. If the cache size continues to grow and hits the high
 160  * water mark, then callers adding elments to the cache will begin to evict
 161  * directly from the cache until the cache is no longer above the high water
 162  * mark.
 163  */
 164 
 165 /*
 166  * The percentage above and below the maximum cache size.
 167  */
 168 uint_t dbuf_cache_hiwater_pct = 10;
 169 uint_t dbuf_cache_lowater_pct = 10;
 170 
 171 /* ARGSUSED */
 172 static int
 173 dbuf_cons(void *vdb, void *unused, int kmflag)
 174 {
 175         dmu_buf_impl_t *db = vdb;
 176         bzero(db, sizeof (dmu_buf_impl_t));
 177 
 178         mutex_init(&db->db_mtx, NULL, MUTEX_DEFAULT, NULL);
 179         cv_init(&db->db_changed, NULL, CV_DEFAULT, NULL);
 180         multilist_link_init(&db->db_cache_link);
 181         refcount_create(&db->db_holds);
 182 
 183         return (0);
 184 }
 185 
 186 /* ARGSUSED */
 187 static void
 188 dbuf_dest(void *vdb, void *unused)
 189 {
 190         dmu_buf_impl_t *db = vdb;
 191         mutex_destroy(&db->db_mtx);
 192         cv_destroy(&db->db_changed);
 193         ASSERT(!multilist_link_active(&db->db_cache_link));
 194         refcount_destroy(&db->db_holds);
 195 }
 196 
 197 /*
 198  * dbuf hash table routines
 199  */
 200 #pragma align 64(dbuf_hash_table)
 201 static dbuf_hash_table_t dbuf_hash_table;
 202 
 203 static uint64_t dbuf_hash_count;
 204 
 205 static uint64_t
 206 dbuf_hash(void *os, uint64_t obj, uint8_t lvl, uint64_t blkid)
 207 {
 208         uintptr_t osv = (uintptr_t)os;
 209         uint64_t crc = -1ULL;
 210 
 211         ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
 212         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (lvl)) & 0xFF];
 213         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (osv >> 6)) & 0xFF];
 214         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 0)) & 0xFF];
 215         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 8)) & 0xFF];
 216         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (blkid >> 0)) & 0xFF];
 217         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (blkid >> 8)) & 0xFF];
 218 
 219         crc ^= (osv>>14) ^ (obj>>16) ^ (blkid>>16);
 220 
 221         return (crc);
 222 }
 223 
 224 #define DBUF_EQUAL(dbuf, os, obj, level, blkid)         \
 225         ((dbuf)->db.db_object == (obj) &&            \
 226         (dbuf)->db_objset == (os) &&                 \
 227         (dbuf)->db_level == (level) &&                       \
 228         (dbuf)->db_blkid == (blkid))
 229 
 230 dmu_buf_impl_t *
 231 dbuf_find(objset_t *os, uint64_t obj, uint8_t level, uint64_t blkid)
 232 {
 233         dbuf_hash_table_t *h = &dbuf_hash_table;
 234         uint64_t hv = dbuf_hash(os, obj, level, blkid);
 235         uint64_t idx = hv & h->hash_table_mask;
 236         dmu_buf_impl_t *db;
 237 
 238         mutex_enter(DBUF_HASH_MUTEX(h, idx));
 239         for (db = h->hash_table[idx]; db != NULL; db = db->db_hash_next) {
 240                 if (DBUF_EQUAL(db, os, obj, level, blkid)) {
 241                         mutex_enter(&db->db_mtx);
 242                         if (db->db_state != DB_EVICTING) {
 243                                 mutex_exit(DBUF_HASH_MUTEX(h, idx));
 244                                 return (db);
 245                         }
 246                         mutex_exit(&db->db_mtx);
 247                 }
 248         }
 249         mutex_exit(DBUF_HASH_MUTEX(h, idx));
 250         return (NULL);
 251 }
 252 
 253 static dmu_buf_impl_t *
 254 dbuf_find_bonus(objset_t *os, uint64_t object)
 255 {
 256         dnode_t *dn;
 257         dmu_buf_impl_t *db = NULL;
 258 
 259         if (dnode_hold(os, object, FTAG, &dn) == 0) {
 260                 rw_enter(&dn->dn_struct_rwlock, RW_READER);
 261                 if (dn->dn_bonus != NULL) {
 262                         db = dn->dn_bonus;
 263                         mutex_enter(&db->db_mtx);
 264                 }
 265                 rw_exit(&dn->dn_struct_rwlock);
 266                 dnode_rele(dn, FTAG);
 267         }
 268         return (db);
 269 }
 270 
 271 /*
 272  * Insert an entry into the hash table.  If there is already an element
 273  * equal to elem in the hash table, then the already existing element
 274  * will be returned and the new element will not be inserted.
 275  * Otherwise returns NULL.
 276  */
 277 static dmu_buf_impl_t *
 278 dbuf_hash_insert(dmu_buf_impl_t *db)
 279 {
 280         dbuf_hash_table_t *h = &dbuf_hash_table;
 281         objset_t *os = db->db_objset;
 282         uint64_t obj = db->db.db_object;
 283         int level = db->db_level;
 284         uint64_t blkid = db->db_blkid;
 285         uint64_t hv = dbuf_hash(os, obj, level, blkid);
 286         uint64_t idx = hv & h->hash_table_mask;
 287         dmu_buf_impl_t *dbf;
 288 
 289         mutex_enter(DBUF_HASH_MUTEX(h, idx));
 290         for (dbf = h->hash_table[idx]; dbf != NULL; dbf = dbf->db_hash_next) {
 291                 if (DBUF_EQUAL(dbf, os, obj, level, blkid)) {
 292                         mutex_enter(&dbf->db_mtx);
 293                         if (dbf->db_state != DB_EVICTING) {
 294                                 mutex_exit(DBUF_HASH_MUTEX(h, idx));
 295                                 return (dbf);
 296                         }
 297                         mutex_exit(&dbf->db_mtx);
 298                 }
 299         }
 300 
 301         mutex_enter(&db->db_mtx);
 302         db->db_hash_next = h->hash_table[idx];
 303         h->hash_table[idx] = db;
 304         mutex_exit(DBUF_HASH_MUTEX(h, idx));
 305         atomic_inc_64(&dbuf_hash_count);
 306 
 307         return (NULL);
 308 }
 309 
 310 /*
 311  * Remove an entry from the hash table.  It must be in the EVICTING state.
 312  */
 313 static void
 314 dbuf_hash_remove(dmu_buf_impl_t *db)
 315 {
 316         dbuf_hash_table_t *h = &dbuf_hash_table;
 317         uint64_t hv = dbuf_hash(db->db_objset, db->db.db_object,
 318             db->db_level, db->db_blkid);
 319         uint64_t idx = hv & h->hash_table_mask;
 320         dmu_buf_impl_t *dbf, **dbp;
 321 
 322         /*
 323          * We musn't hold db_mtx to maintain lock ordering:
 324          * DBUF_HASH_MUTEX > db_mtx.
 325          */
 326         ASSERT(refcount_is_zero(&db->db_holds));
 327         ASSERT(db->db_state == DB_EVICTING);
 328         ASSERT(!MUTEX_HELD(&db->db_mtx));
 329 
 330         mutex_enter(DBUF_HASH_MUTEX(h, idx));
 331         dbp = &h->hash_table[idx];
 332         while ((dbf = *dbp) != db) {
 333                 dbp = &dbf->db_hash_next;
 334                 ASSERT(dbf != NULL);
 335         }
 336         *dbp = db->db_hash_next;
 337         db->db_hash_next = NULL;
 338         mutex_exit(DBUF_HASH_MUTEX(h, idx));
 339         atomic_dec_64(&dbuf_hash_count);
 340 }
 341 
 342 typedef enum {
 343         DBVU_EVICTING,
 344         DBVU_NOT_EVICTING
 345 } dbvu_verify_type_t;
 346 
 347 static void
 348 dbuf_verify_user(dmu_buf_impl_t *db, dbvu_verify_type_t verify_type)
 349 {
 350 #ifdef ZFS_DEBUG
 351         int64_t holds;
 352 
 353         if (db->db_user == NULL)
 354                 return;
 355 
 356         /* Only data blocks support the attachment of user data. */
 357         ASSERT(db->db_level == 0);
 358 
 359         /* Clients must resolve a dbuf before attaching user data. */
 360         ASSERT(db->db.db_data != NULL);
 361         ASSERT3U(db->db_state, ==, DB_CACHED);
 362 
 363         holds = refcount_count(&db->db_holds);
 364         if (verify_type == DBVU_EVICTING) {
 365                 /*
 366                  * Immediate eviction occurs when holds == dirtycnt.
 367                  * For normal eviction buffers, holds is zero on
 368                  * eviction, except when dbuf_fix_old_data() calls
 369                  * dbuf_clear_data().  However, the hold count can grow
 370                  * during eviction even though db_mtx is held (see
 371                  * dmu_bonus_hold() for an example), so we can only
 372                  * test the generic invariant that holds >= dirtycnt.
 373                  */
 374                 ASSERT3U(holds, >=, db->db_dirtycnt);
 375         } else {
 376                 if (db->db_user_immediate_evict == TRUE)
 377                         ASSERT3U(holds, >=, db->db_dirtycnt);
 378                 else
 379                         ASSERT3U(holds, >, 0);
 380         }
 381 #endif
 382 }
 383 
 384 static void
 385 dbuf_evict_user(dmu_buf_impl_t *db)
 386 {
 387         dmu_buf_user_t *dbu = db->db_user;
 388 
 389         ASSERT(MUTEX_HELD(&db->db_mtx));
 390 
 391         if (dbu == NULL)
 392                 return;
 393 
 394         dbuf_verify_user(db, DBVU_EVICTING);
 395         db->db_user = NULL;
 396 
 397 #ifdef ZFS_DEBUG
 398         if (dbu->dbu_clear_on_evict_dbufp != NULL)
 399                 *dbu->dbu_clear_on_evict_dbufp = NULL;
 400 #endif
 401 
 402         /*
 403          * There are two eviction callbacks - one that we call synchronously
 404          * and one that we invoke via a taskq.  The async one is useful for
 405          * avoiding lock order reversals and limiting stack depth.
 406          *
 407          * Note that if we have a sync callback but no async callback,
 408          * it's likely that the sync callback will free the structure
 409          * containing the dbu.  In that case we need to take care to not
 410          * dereference dbu after calling the sync evict func.
 411          */
 412         boolean_t has_async = (dbu->dbu_evict_func_async != NULL);
 413 
 414         if (dbu->dbu_evict_func_sync != NULL)
 415                 dbu->dbu_evict_func_sync(dbu);
 416 
 417         if (has_async) {
 418                 taskq_dispatch_ent(dbu_evict_taskq, dbu->dbu_evict_func_async,
 419                     dbu, 0, &dbu->dbu_tqent);
 420         }
 421 }
 422 
 423 boolean_t
 424 dbuf_is_metadata(dmu_buf_impl_t *db)
 425 {
 426         if (db->db_level > 0) {
 427                 return (B_TRUE);
 428         } else {
 429                 boolean_t is_metadata;
 430 
 431                 DB_DNODE_ENTER(db);
 432                 is_metadata = DMU_OT_IS_METADATA(DB_DNODE(db)->dn_type);
 433                 DB_DNODE_EXIT(db);
 434 
 435                 return (is_metadata);
 436         }
 437 }
 438 
 439 boolean_t
 440 dbuf_is_ddt(dmu_buf_impl_t *db)
 441 {
 442         boolean_t is_ddt;
 443 
 444         DB_DNODE_ENTER(db);
 445         is_ddt = (DB_DNODE(db)->dn_type == DMU_OT_DDT_ZAP) ||
 446             (DB_DNODE(db)->dn_type == DMU_OT_DDT_STATS);
 447         DB_DNODE_EXIT(db);
 448 
 449         return (is_ddt);
 450 }
 451 
 452 /*
 453  * This returns whether this dbuf should be stored in the metadata cache, which
 454  * is based on whether it's from one of the dnode types that store data related
 455  * to traversing dataset hierarchies.
 456  */
 457 static boolean_t
 458 dbuf_include_in_metadata_cache(dmu_buf_impl_t *db)
 459 {
 460         DB_DNODE_ENTER(db);
 461         dmu_object_type_t type = DB_DNODE(db)->dn_type;
 462         DB_DNODE_EXIT(db);
 463 
 464         /* Check if this dbuf is one of the types we care about */
 465         if (DMU_OT_IS_METADATA_CACHED(type)) {
 466                 /* If we hit this, then we set something up wrong in dmu_ot */
 467                 ASSERT(DMU_OT_IS_METADATA(type));
 468 
 469                 /*
 470                  * Sanity check for small-memory systems: don't allocate too
 471                  * much memory for this purpose.
 472                  */
 473                 if (refcount_count(&dbuf_caches[DB_DBUF_METADATA_CACHE].size) >
 474                     dbuf_metadata_cache_max_bytes) {
 475                         dbuf_metadata_cache_overflow++;
 476                         DTRACE_PROBE1(dbuf__metadata__cache__overflow,
 477                             dmu_buf_impl_t *, db);
 478                         return (B_FALSE);
 479                 }
 480 
 481                 return (B_TRUE);
 482         }
 483 
 484         return (B_FALSE);
 485 }
 486 
 487 /*
 488  * This function *must* return indices evenly distributed between all
 489  * sublists of the multilist. This is needed due to how the dbuf eviction
 490  * code is laid out; dbuf_evict_thread() assumes dbufs are evenly
 491  * distributed between all sublists and uses this assumption when
 492  * deciding which sublist to evict from and how much to evict from it.
 493  */
 494 unsigned int
 495 dbuf_cache_multilist_index_func(multilist_t *ml, void *obj)
 496 {
 497         dmu_buf_impl_t *db = obj;
 498 
 499         /*
 500          * The assumption here, is the hash value for a given
 501          * dmu_buf_impl_t will remain constant throughout it's lifetime
 502          * (i.e. it's objset, object, level and blkid fields don't change).
 503          * Thus, we don't need to store the dbuf's sublist index
 504          * on insertion, as this index can be recalculated on removal.
 505          *
 506          * Also, the low order bits of the hash value are thought to be
 507          * distributed evenly. Otherwise, in the case that the multilist
 508          * has a power of two number of sublists, each sublists' usage
 509          * would not be evenly distributed.
 510          */
 511         return (dbuf_hash(db->db_objset, db->db.db_object,
 512             db->db_level, db->db_blkid) %
 513             multilist_get_num_sublists(ml));
 514 }
 515 
 516 static inline boolean_t
 517 dbuf_cache_above_hiwater(void)
 518 {
 519         uint64_t dbuf_cache_hiwater_bytes =
 520             (dbuf_cache_max_bytes * dbuf_cache_hiwater_pct) / 100;
 521 
 522         return (refcount_count(&dbuf_caches[DB_DBUF_CACHE].size) >
 523             dbuf_cache_max_bytes + dbuf_cache_hiwater_bytes);
 524 }
 525 
 526 static inline boolean_t
 527 dbuf_cache_above_lowater(void)
 528 {
 529         uint64_t dbuf_cache_lowater_bytes =
 530             (dbuf_cache_max_bytes * dbuf_cache_lowater_pct) / 100;
 531 
 532         return (refcount_count(&dbuf_caches[DB_DBUF_CACHE].size) >
 533             dbuf_cache_max_bytes - dbuf_cache_lowater_bytes);
 534 }
 535 
 536 /*
 537  * Evict the oldest eligible dbuf from the dbuf cache.
 538  */
 539 static void
 540 dbuf_evict_one(void)
 541 {
 542         int idx = multilist_get_random_index(dbuf_caches[DB_DBUF_CACHE].cache);
 543         multilist_sublist_t *mls = multilist_sublist_lock(
 544             dbuf_caches[DB_DBUF_CACHE].cache, idx);
 545 
 546         ASSERT(!MUTEX_HELD(&dbuf_evict_lock));
 547 
 548         /*
 549          * Set the thread's tsd to indicate that it's processing evictions.
 550          * Once a thread stops evicting from the dbuf cache it will
 551          * reset its tsd to NULL.
 552          */
 553         ASSERT3P(tsd_get(zfs_dbuf_evict_key), ==, NULL);
 554         (void) tsd_set(zfs_dbuf_evict_key, (void *)B_TRUE);
 555 
 556         dmu_buf_impl_t *db = multilist_sublist_tail(mls);
 557         while (db != NULL && mutex_tryenter(&db->db_mtx) == 0) {
 558                 db = multilist_sublist_prev(mls, db);
 559         }
 560 
 561         DTRACE_PROBE2(dbuf__evict__one, dmu_buf_impl_t *, db,
 562             multilist_sublist_t *, mls);
 563 
 564         if (db != NULL) {
 565                 multilist_sublist_remove(mls, db);
 566                 multilist_sublist_unlock(mls);
 567                 (void) refcount_remove_many(&dbuf_caches[DB_DBUF_CACHE].size,
 568                     db->db.db_size, db);
 569                 ASSERT3U(db->db_caching_status, ==, DB_DBUF_CACHE);
 570                 db->db_caching_status = DB_NO_CACHE;
 571                 dbuf_destroy(db);
 572         } else {
 573                 multilist_sublist_unlock(mls);
 574         }
 575         (void) tsd_set(zfs_dbuf_evict_key, NULL);
 576 }
 577 
 578 /*
 579  * The dbuf evict thread is responsible for aging out dbufs from the
 580  * cache. Once the cache has reached it's maximum size, dbufs are removed
 581  * and destroyed. The eviction thread will continue running until the size
 582  * of the dbuf cache is at or below the maximum size. Once the dbuf is aged
 583  * out of the cache it is destroyed and becomes eligible for arc eviction.
 584  */
 585 /* ARGSUSED */
 586 static void
 587 dbuf_evict_thread(void *unused)
 588 {
 589         callb_cpr_t cpr;
 590 
 591         CALLB_CPR_INIT(&cpr, &dbuf_evict_lock, callb_generic_cpr, FTAG);
 592 
 593         mutex_enter(&dbuf_evict_lock);
 594         while (!dbuf_evict_thread_exit) {
 595                 while (!dbuf_cache_above_lowater() && !dbuf_evict_thread_exit) {
 596                         CALLB_CPR_SAFE_BEGIN(&cpr);
 597                         (void) cv_timedwait_hires(&dbuf_evict_cv,
 598                             &dbuf_evict_lock, SEC2NSEC(1), MSEC2NSEC(1), 0);
 599                         CALLB_CPR_SAFE_END(&cpr, &dbuf_evict_lock);
 600                 }
 601                 mutex_exit(&dbuf_evict_lock);
 602 
 603                 /*
 604                  * Keep evicting as long as we're above the low water mark
 605                  * for the cache. We do this without holding the locks to
 606                  * minimize lock contention.
 607                  */
 608                 while (dbuf_cache_above_lowater() && !dbuf_evict_thread_exit) {
 609                         dbuf_evict_one();
 610                 }
 611 
 612                 mutex_enter(&dbuf_evict_lock);
 613         }
 614 
 615         dbuf_evict_thread_exit = B_FALSE;
 616         cv_broadcast(&dbuf_evict_cv);
 617         CALLB_CPR_EXIT(&cpr);       /* drops dbuf_evict_lock */
 618         thread_exit();
 619 }
 620 
 621 /*
 622  * Wake up the dbuf eviction thread if the dbuf cache is at its max size.
 623  *
 624  * Direct eviction (dbuf_evict_one()) is not called here, because
 625  * the function doesn't care about the selected dbuf, so the following
 626  * case is possible which will cause a deadlock-panic:
 627  *
 628  * Thread A is evicting dbufs that are related to dnodeA
 629  * dnode_evict_dbufs(dnoneA) enters dn_dbufs_mtx and after that walks
 630  * its own AVL of dbufs and calls dbuf_destroy():
 631  * dbuf_destroy() ->...-> dbuf_evict_notify() -> dbuf_evict_one() ->
 632  *  -> select a dbuf from cache -> dbuf_destroy() ->
 633  *   -> mutex_enter(dn_dbufs_mtx of dnoneB)
 634  *
 635  * Thread B is evicting dbufs that are related to dnodeB
 636  * dnode_evict_dbufs(dnoneB) enters dn_dbufs_mtx and after that walks
 637  * its own AVL of dbufs and calls dbuf_destroy():
 638  * dbuf_destroy() ->...-> dbuf_evict_notify() -> dbuf_evict_one() ->
 639  *  -> select a dbuf from cache -> dbuf_destroy() ->
 640  *   -> mutex_enter(dn_dbufs_mtx of dnoneA)
 641  */
 642 static void
 643 dbuf_evict_notify(void)
 644 {
 645 
 646         /*
 647          * We use thread specific data to track when a thread has
 648          * started processing evictions. This allows us to avoid deeply
 649          * nested stacks that would have a call flow similar to this:
 650          *
 651          * dbuf_rele()-->dbuf_rele_and_unlock()-->dbuf_evict_notify()
 652          *      ^                                               |
 653          *      |                                               |
 654          *      +-----dbuf_destroy()<--dbuf_evict_one()<--------+
 655          *
 656          * The dbuf_eviction_thread will always have its tsd set until
 657          * that thread exits. All other threads will only set their tsd
 658          * if they are participating in the eviction process. This only
 659          * happens if the eviction thread is unable to process evictions
 660          * fast enough. To keep the dbuf cache size in check, other threads
 661          * can evict from the dbuf cache directly. Those threads will set
 662          * their tsd values so that we ensure that they only evict one dbuf
 663          * from the dbuf cache.
 664          */
 665         if (tsd_get(zfs_dbuf_evict_key) != NULL)
 666                 return;
 667 
 668         /*
 669          * We check if we should evict without holding the dbuf_evict_lock,
 670          * because it's OK to occasionally make the wrong decision here,
 671          * and grabbing the lock results in massive lock contention.
 672          */
 673         if (refcount_count(&dbuf_caches[DB_DBUF_CACHE].size) >
 674             dbuf_cache_max_bytes) {
 675                 if (dbuf_cache_above_hiwater())
 676                         dbuf_evict_one();
 677                 cv_signal(&dbuf_evict_cv);
 678         }
 679 }
 680 
 681 void
 682 dbuf_init(void)
 683 {
 684         uint64_t hsize = 1ULL << 16;
 685         dbuf_hash_table_t *h = &dbuf_hash_table;
 686         int i;
 687 
 688         /*
 689          * The hash table is big enough to fill all of physical memory
 690          * with an average 4K block size.  The table will take up
 691          * totalmem*sizeof(void*)/4K (i.e. 2MB/GB with 8-byte pointers).
 692          */
 693         while (hsize * 4096 < physmem * PAGESIZE)
 694                 hsize <<= 1;
 695 
 696 retry:
 697         h->hash_table_mask = hsize - 1;
 698         h->hash_table = kmem_zalloc(hsize * sizeof (void *), KM_NOSLEEP);
 699         if (h->hash_table == NULL) {
 700                 /* XXX - we should really return an error instead of assert */
 701                 ASSERT(hsize > (1ULL << 10));
 702                 hsize >>= 1;
 703                 goto retry;
 704         }
 705 
 706         dbuf_kmem_cache = kmem_cache_create("dmu_buf_impl_t",
 707             sizeof (dmu_buf_impl_t),
 708             0, dbuf_cons, dbuf_dest, NULL, NULL, NULL, 0);
 709 
 710         for (i = 0; i < DBUF_MUTEXES; i++)
 711                 mutex_init(DBUF_HASH_MUTEX(h, i), NULL, MUTEX_DEFAULT, NULL);
 712 
 713 
 714         /*
 715          * Setup the parameters for the dbuf caches. We set the sizes of the
 716          * dbuf cache and the metadata cache to 1/32nd and 1/16th (default)
 717          * of the size of the ARC, respectively.
 718          */
 719         if (dbuf_cache_max_bytes == 0 ||
 720             dbuf_cache_max_bytes >= arc_max_bytes())  {
 721                 dbuf_cache_max_bytes = arc_max_bytes() >> dbuf_cache_shift;
 722         }
 723         if (dbuf_metadata_cache_max_bytes == 0 ||
 724             dbuf_metadata_cache_max_bytes >= arc_max_bytes()) {
 725                 dbuf_metadata_cache_max_bytes =
 726                     arc_max_bytes() >> dbuf_metadata_cache_shift;
 727         }
 728 
 729         /*
 730          * The combined size of both caches should be less
 731          * the size of ARC, otherwise need to set them to
 732          * the default values.
 733          *
 734          * divide by 2 is a simple overflow protection
 735          */
 736         if (((dbuf_cache_max_bytes / 2) +
 737             (dbuf_metadata_cache_max_bytes / 2)) >= (arc_max_bytes() / 2)) {
 738                 dbuf_cache_max_bytes = arc_max_bytes() >> dbuf_cache_shift;
 739                 dbuf_metadata_cache_max_bytes =
 740                     arc_max_bytes() >> dbuf_metadata_cache_shift;
 741         }
 742 
 743 
 744         /*
 745          * All entries are queued via taskq_dispatch_ent(), so min/maxalloc
 746          * configuration is not required.
 747          */
 748         dbu_evict_taskq = taskq_create("dbu_evict", 1, minclsyspri, 0, 0, 0);
 749 
 750         for (dbuf_cached_state_t dcs = 0; dcs < DB_CACHE_MAX; dcs++) {
 751                 dbuf_caches[dcs].cache =
 752                     multilist_create(sizeof (dmu_buf_impl_t),
 753                     offsetof(dmu_buf_impl_t, db_cache_link),
 754                     dbuf_cache_multilist_index_func);
 755                 refcount_create(&dbuf_caches[dcs].size);
 756         }
 757 
 758         tsd_create(&zfs_dbuf_evict_key, NULL);
 759         dbuf_evict_thread_exit = B_FALSE;
 760         mutex_init(&dbuf_evict_lock, NULL, MUTEX_DEFAULT, NULL);
 761         cv_init(&dbuf_evict_cv, NULL, CV_DEFAULT, NULL);
 762         dbuf_cache_evict_thread = thread_create(NULL, 0, dbuf_evict_thread,
 763             NULL, 0, &p0, TS_RUN, minclsyspri);
 764 }
 765 
 766 void
 767 dbuf_fini(void)
 768 {
 769         dbuf_hash_table_t *h = &dbuf_hash_table;
 770         int i;
 771 
 772         for (i = 0; i < DBUF_MUTEXES; i++)
 773                 mutex_destroy(DBUF_HASH_MUTEX(h, i));
 774         kmem_free(h->hash_table, (h->hash_table_mask + 1) * sizeof (void *));
 775         kmem_cache_destroy(dbuf_kmem_cache);
 776         taskq_destroy(dbu_evict_taskq);
 777 
 778         mutex_enter(&dbuf_evict_lock);
 779         dbuf_evict_thread_exit = B_TRUE;
 780         while (dbuf_evict_thread_exit) {
 781                 cv_signal(&dbuf_evict_cv);
 782                 cv_wait(&dbuf_evict_cv, &dbuf_evict_lock);
 783         }
 784         mutex_exit(&dbuf_evict_lock);
 785         tsd_destroy(&zfs_dbuf_evict_key);
 786 
 787         mutex_destroy(&dbuf_evict_lock);
 788         cv_destroy(&dbuf_evict_cv);
 789 
 790         for (dbuf_cached_state_t dcs = 0; dcs < DB_CACHE_MAX; dcs++) {
 791                 refcount_destroy(&dbuf_caches[dcs].size);
 792                 multilist_destroy(dbuf_caches[dcs].cache);
 793         }
 794 }
 795 
 796 /*
 797  * Other stuff.
 798  */
 799 
 800 #ifdef ZFS_DEBUG
 801 static void
 802 dbuf_verify(dmu_buf_impl_t *db)
 803 {
 804         dnode_t *dn;
 805         dbuf_dirty_record_t *dr;
 806 
 807         ASSERT(MUTEX_HELD(&db->db_mtx));
 808 
 809         if (!(zfs_flags & ZFS_DEBUG_DBUF_VERIFY))
 810                 return;
 811 
 812         ASSERT(db->db_objset != NULL);
 813         DB_DNODE_ENTER(db);
 814         dn = DB_DNODE(db);
 815         if (dn == NULL) {
 816                 ASSERT(db->db_parent == NULL);
 817                 ASSERT(db->db_blkptr == NULL);
 818         } else {
 819                 ASSERT3U(db->db.db_object, ==, dn->dn_object);
 820                 ASSERT3P(db->db_objset, ==, dn->dn_objset);
 821                 ASSERT3U(db->db_level, <, dn->dn_nlevels);
 822                 ASSERT(db->db_blkid == DMU_BONUS_BLKID ||
 823                     db->db_blkid == DMU_SPILL_BLKID ||
 824                     !avl_is_empty(&dn->dn_dbufs));
 825         }
 826         if (db->db_blkid == DMU_BONUS_BLKID) {
 827                 ASSERT(dn != NULL);
 828                 ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
 829                 ASSERT3U(db->db.db_offset, ==, DMU_BONUS_BLKID);
 830         } else if (db->db_blkid == DMU_SPILL_BLKID) {
 831                 ASSERT(dn != NULL);
 832                 ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
 833                 ASSERT0(db->db.db_offset);
 834         } else {
 835                 ASSERT3U(db->db.db_offset, ==, db->db_blkid * db->db.db_size);
 836         }
 837 
 838         for (dr = db->db_data_pending; dr != NULL; dr = dr->dr_next)
 839                 ASSERT(dr->dr_dbuf == db);
 840 
 841         for (dr = db->db_last_dirty; dr != NULL; dr = dr->dr_next)
 842                 ASSERT(dr->dr_dbuf == db);
 843 
 844         /*
 845          * We can't assert that db_size matches dn_datablksz because it
 846          * can be momentarily different when another thread is doing
 847          * dnode_set_blksz().
 848          */
 849         if (db->db_level == 0 && db->db.db_object == DMU_META_DNODE_OBJECT) {
 850                 dr = db->db_data_pending;
 851                 /*
 852                  * It should only be modified in syncing context, so
 853                  * make sure we only have one copy of the data.
 854                  */
 855                 ASSERT(dr == NULL || dr->dt.dl.dr_data == db->db_buf);
 856         }
 857 
 858         /* verify db->db_blkptr */
 859         if (db->db_blkptr) {
 860                 if (db->db_parent == dn->dn_dbuf) {
 861                         /* db is pointed to by the dnode */
 862                         /* ASSERT3U(db->db_blkid, <, dn->dn_nblkptr); */
 863                         if (DMU_OBJECT_IS_SPECIAL(db->db.db_object))
 864                                 ASSERT(db->db_parent == NULL);
 865                         else
 866                                 ASSERT(db->db_parent != NULL);
 867                         if (db->db_blkid != DMU_SPILL_BLKID)
 868                                 ASSERT3P(db->db_blkptr, ==,
 869                                     &dn->dn_phys->dn_blkptr[db->db_blkid]);
 870                 } else {
 871                         /* db is pointed to by an indirect block */
 872                         int epb = db->db_parent->db.db_size >> SPA_BLKPTRSHIFT;
 873                         ASSERT3U(db->db_parent->db_level, ==, db->db_level+1);
 874                         ASSERT3U(db->db_parent->db.db_object, ==,
 875                             db->db.db_object);
 876                         /*
 877                          * dnode_grow_indblksz() can make this fail if we don't
 878                          * have the struct_rwlock.  XXX indblksz no longer
 879                          * grows.  safe to do this now?
 880                          */
 881                         if (RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
 882                                 ASSERT3P(db->db_blkptr, ==,
 883                                     ((blkptr_t *)db->db_parent->db.db_data +
 884                                     db->db_blkid % epb));
 885                         }
 886                 }
 887         }
 888         if ((db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr)) &&
 889             (db->db_buf == NULL || db->db_buf->b_data) &&
 890             db->db.db_data && db->db_blkid != DMU_BONUS_BLKID &&
 891             db->db_state != DB_FILL && !dn->dn_free_txg) {
 892                 /*
 893                  * If the blkptr isn't set but they have nonzero data,
 894                  * it had better be dirty, otherwise we'll lose that
 895                  * data when we evict this buffer.
 896                  *
 897                  * There is an exception to this rule for indirect blocks; in
 898                  * this case, if the indirect block is a hole, we fill in a few
 899                  * fields on each of the child blocks (importantly, birth time)
 900                  * to prevent hole birth times from being lost when you
 901                  * partially fill in a hole.
 902                  */
 903                 if (db->db_dirtycnt == 0) {
 904                         if (db->db_level == 0) {
 905                                 uint64_t *buf = db->db.db_data;
 906                                 int i;
 907 
 908                                 for (i = 0; i < db->db.db_size >> 3; i++) {
 909                                         ASSERT(buf[i] == 0);
 910                                 }
 911                         } else {
 912                                 blkptr_t *bps = db->db.db_data;
 913                                 ASSERT3U(1 << DB_DNODE(db)->dn_indblkshift, ==,
 914                                     db->db.db_size);
 915                                 /*
 916                                  * We want to verify that all the blkptrs in the
 917                                  * indirect block are holes, but we may have
 918                                  * automatically set up a few fields for them.
 919                                  * We iterate through each blkptr and verify
 920                                  * they only have those fields set.
 921                                  */
 922                                 for (int i = 0;
 923                                     i < db->db.db_size / sizeof (blkptr_t);
 924                                     i++) {
 925                                         blkptr_t *bp = &bps[i];
 926                                         ASSERT(ZIO_CHECKSUM_IS_ZERO(
 927                                             &bp->blk_cksum));
 928                                         ASSERT(
 929                                             DVA_IS_EMPTY(&bp->blk_dva[0]) &&
 930                                             DVA_IS_EMPTY(&bp->blk_dva[1]) &&
 931                                             DVA_IS_EMPTY(&bp->blk_dva[2]));
 932                                         ASSERT0(bp->blk_fill);
 933                                         ASSERT0(bp->blk_pad[0]);
 934                                         ASSERT0(bp->blk_pad[1]);
 935                                         ASSERT(!BP_IS_EMBEDDED(bp));
 936                                         ASSERT(BP_IS_HOLE(bp));
 937                                         ASSERT0(bp->blk_phys_birth);
 938                                 }
 939                         }
 940                 }
 941         }
 942         DB_DNODE_EXIT(db);
 943 }
 944 #endif
 945 
 946 static void
 947 dbuf_clear_data(dmu_buf_impl_t *db)
 948 {
 949         ASSERT(MUTEX_HELD(&db->db_mtx));
 950         dbuf_evict_user(db);
 951         ASSERT3P(db->db_buf, ==, NULL);
 952         db->db.db_data = NULL;
 953         if (db->db_state != DB_NOFILL)
 954                 db->db_state = DB_UNCACHED;
 955 }
 956 
 957 static void
 958 dbuf_set_data(dmu_buf_impl_t *db, arc_buf_t *buf)
 959 {
 960         ASSERT(MUTEX_HELD(&db->db_mtx));
 961         ASSERT(buf != NULL);
 962 
 963         db->db_buf = buf;
 964         ASSERT(buf->b_data != NULL);
 965         db->db.db_data = buf->b_data;
 966 }
 967 
 968 /*
 969  * Loan out an arc_buf for read.  Return the loaned arc_buf.
 970  */
 971 arc_buf_t *
 972 dbuf_loan_arcbuf(dmu_buf_impl_t *db)
 973 {
 974         arc_buf_t *abuf;
 975 
 976         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
 977         mutex_enter(&db->db_mtx);
 978         if (arc_released(db->db_buf) || refcount_count(&db->db_holds) > 1) {
 979                 int blksz = db->db.db_size;
 980                 spa_t *spa = db->db_objset->os_spa;
 981 
 982                 mutex_exit(&db->db_mtx);
 983                 abuf = arc_loan_buf(spa, B_FALSE, blksz);
 984                 bcopy(db->db.db_data, abuf->b_data, blksz);
 985         } else {
 986                 abuf = db->db_buf;
 987                 arc_loan_inuse_buf(abuf, db);
 988                 db->db_buf = NULL;
 989                 dbuf_clear_data(db);
 990                 mutex_exit(&db->db_mtx);
 991         }
 992         return (abuf);
 993 }
 994 
 995 /*
 996  * Calculate which level n block references the data at the level 0 offset
 997  * provided.
 998  */
 999 uint64_t
1000 dbuf_whichblock(dnode_t *dn, int64_t level, uint64_t offset)
1001 {
1002         if (dn->dn_datablkshift != 0 && dn->dn_indblkshift != 0) {
1003                 /*
1004                  * The level n blkid is equal to the level 0 blkid divided by
1005                  * the number of level 0s in a level n block.
1006                  *
1007                  * The level 0 blkid is offset >> datablkshift =
1008                  * offset / 2^datablkshift.
1009                  *
1010                  * The number of level 0s in a level n is the number of block
1011                  * pointers in an indirect block, raised to the power of level.
1012                  * This is 2^(indblkshift - SPA_BLKPTRSHIFT)^level =
1013                  * 2^(level*(indblkshift - SPA_BLKPTRSHIFT)).
1014                  *
1015                  * Thus, the level n blkid is: offset /
1016                  * ((2^datablkshift)*(2^(level*(indblkshift - SPA_BLKPTRSHIFT)))
1017                  * = offset / 2^(datablkshift + level *
1018                  *   (indblkshift - SPA_BLKPTRSHIFT))
1019                  * = offset >> (datablkshift + level *
1020                  *   (indblkshift - SPA_BLKPTRSHIFT))
1021                  */
1022                 return (offset >> (dn->dn_datablkshift + level *
1023                     (dn->dn_indblkshift - SPA_BLKPTRSHIFT)));
1024         } else {
1025                 ASSERT3U(offset, <, dn->dn_datablksz);
1026                 return (0);
1027         }
1028 }
1029 
1030 static void
1031 dbuf_read_done(zio_t *zio, arc_buf_t *buf, void *vdb)
1032 {
1033         dmu_buf_impl_t *db = vdb;
1034 
1035         mutex_enter(&db->db_mtx);
1036         ASSERT3U(db->db_state, ==, DB_READ);
1037         /*
1038          * All reads are synchronous, so we must have a hold on the dbuf
1039          */
1040         ASSERT(refcount_count(&db->db_holds) > 0);
1041         ASSERT(db->db_buf == NULL);
1042         ASSERT(db->db.db_data == NULL);
1043         if (db->db_level == 0 && db->db_freed_in_flight) {
1044                 /* we were freed in flight; disregard any error */
1045                 arc_release(buf, db);
1046                 bzero(buf->b_data, db->db.db_size);
1047                 arc_buf_freeze(buf);
1048                 db->db_freed_in_flight = FALSE;
1049                 dbuf_set_data(db, buf);
1050                 db->db_state = DB_CACHED;
1051         } else if (zio == NULL || zio->io_error == 0) {
1052                 dbuf_set_data(db, buf);
1053                 db->db_state = DB_CACHED;
1054         } else {
1055                 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1056                 ASSERT3P(db->db_buf, ==, NULL);
1057                 arc_buf_destroy(buf, db);
1058                 db->db_state = DB_UNCACHED;
1059         }
1060         cv_broadcast(&db->db_changed);
1061         dbuf_rele_and_unlock(db, NULL);
1062 }
1063 
1064 static void
1065 dbuf_read_impl(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
1066 {
1067         dnode_t *dn;
1068         zbookmark_phys_t zb;
1069         arc_flags_t aflags = ARC_FLAG_NOWAIT;
1070 
1071         DB_DNODE_ENTER(db);
1072         dn = DB_DNODE(db);
1073         ASSERT(!refcount_is_zero(&db->db_holds));
1074         /* We need the struct_rwlock to prevent db_blkptr from changing. */
1075         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1076         ASSERT(MUTEX_HELD(&db->db_mtx));
1077         ASSERT(db->db_state == DB_UNCACHED);
1078         ASSERT(db->db_buf == NULL);
1079 
1080         if (db->db_blkid == DMU_BONUS_BLKID) {
1081                 int bonuslen = MIN(dn->dn_bonuslen, dn->dn_phys->dn_bonuslen);
1082 
1083                 ASSERT3U(bonuslen, <=, db->db.db_size);
1084                 db->db.db_data = zio_buf_alloc(DN_MAX_BONUSLEN);
1085                 arc_space_consume(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
1086                 if (bonuslen < DN_MAX_BONUSLEN)
1087                         bzero(db->db.db_data, DN_MAX_BONUSLEN);
1088                 if (bonuslen)
1089                         bcopy(DN_BONUS(dn->dn_phys), db->db.db_data, bonuslen);
1090                 DB_DNODE_EXIT(db);
1091                 db->db_state = DB_CACHED;
1092                 mutex_exit(&db->db_mtx);
1093                 return;
1094         }
1095 
1096         /*
1097          * Recheck BP_IS_HOLE() after dnode_block_freed() in case dnode_sync()
1098          * processes the delete record and clears the bp while we are waiting
1099          * for the dn_mtx (resulting in a "no" from block_freed).
1100          */
1101         if (db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr) ||
1102             (db->db_level == 0 && (dnode_block_freed(dn, db->db_blkid) ||
1103             BP_IS_HOLE(db->db_blkptr)))) {
1104                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1105 
1106                 dbuf_set_data(db, arc_alloc_buf(db->db_objset->os_spa, db, type,
1107                     db->db.db_size));
1108                 bzero(db->db.db_data, db->db.db_size);
1109 
1110                 if (db->db_blkptr != NULL && db->db_level > 0 &&
1111                     BP_IS_HOLE(db->db_blkptr) &&
1112                     db->db_blkptr->blk_birth != 0) {
1113                         blkptr_t *bps = db->db.db_data;
1114                         for (int i = 0; i < ((1 <<
1115                             DB_DNODE(db)->dn_indblkshift) / sizeof (blkptr_t));
1116                             i++) {
1117                                 blkptr_t *bp = &bps[i];
1118                                 ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
1119                                     1 << dn->dn_indblkshift);
1120                                 BP_SET_LSIZE(bp,
1121                                     BP_GET_LEVEL(db->db_blkptr) == 1 ?
1122                                     dn->dn_datablksz :
1123                                     BP_GET_LSIZE(db->db_blkptr));
1124                                 BP_SET_TYPE(bp, BP_GET_TYPE(db->db_blkptr));
1125                                 BP_SET_LEVEL(bp,
1126                                     BP_GET_LEVEL(db->db_blkptr) - 1);
1127                                 BP_SET_BIRTH(bp, db->db_blkptr->blk_birth, 0);
1128                         }
1129                 }
1130                 DB_DNODE_EXIT(db);
1131                 db->db_state = DB_CACHED;
1132                 mutex_exit(&db->db_mtx);
1133                 return;
1134         }
1135 
1136         DB_DNODE_EXIT(db);
1137 
1138         db->db_state = DB_READ;
1139         mutex_exit(&db->db_mtx);
1140 
1141         if (DBUF_IS_L2CACHEABLE(db))
1142                 aflags |= ARC_FLAG_L2CACHE;
1143 
1144         SET_BOOKMARK(&zb, db->db_objset->os_dsl_dataset ?
1145             db->db_objset->os_dsl_dataset->ds_object : DMU_META_OBJSET,
1146             db->db.db_object, db->db_level, db->db_blkid);
1147 
1148         dbuf_add_ref(db, NULL);
1149 
1150         (void) arc_read(zio, db->db_objset->os_spa, db->db_blkptr,
1151             dbuf_read_done, db, ZIO_PRIORITY_SYNC_READ,
1152             (flags & DB_RF_CANFAIL) ? ZIO_FLAG_CANFAIL : ZIO_FLAG_MUSTSUCCEED,
1153             &aflags, &zb);
1154 }
1155 
1156 /*
1157  * This is our just-in-time copy function.  It makes a copy of buffers that
1158  * have been modified in a previous transaction group before we access them in
1159  * the current active group.
1160  *
1161  * This function is used in three places: when we are dirtying a buffer for the
1162  * first time in a txg, when we are freeing a range in a dnode that includes
1163  * this buffer, and when we are accessing a buffer which was received compressed
1164  * and later referenced in a WRITE_BYREF record.
1165  *
1166  * Note that when we are called from dbuf_free_range() we do not put a hold on
1167  * the buffer, we just traverse the active dbuf list for the dnode.
1168  */
1169 static void
1170 dbuf_fix_old_data(dmu_buf_impl_t *db, uint64_t txg)
1171 {
1172         dbuf_dirty_record_t *dr = db->db_last_dirty;
1173 
1174         ASSERT(MUTEX_HELD(&db->db_mtx));
1175         ASSERT(db->db.db_data != NULL);
1176         ASSERT(db->db_level == 0);
1177         ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT);
1178 
1179         if (dr == NULL ||
1180             (dr->dt.dl.dr_data !=
1181             ((db->db_blkid  == DMU_BONUS_BLKID) ? db->db.db_data : db->db_buf)))
1182                 return;
1183 
1184         /*
1185          * If the last dirty record for this dbuf has not yet synced
1186          * and its referencing the dbuf data, either:
1187          *      reset the reference to point to a new copy,
1188          * or (if there a no active holders)
1189          *      just null out the current db_data pointer.
1190          */
1191         ASSERT(dr->dr_txg >= txg - 2);
1192         if (db->db_blkid == DMU_BONUS_BLKID) {
1193                 /* Note that the data bufs here are zio_bufs */
1194                 dr->dt.dl.dr_data = zio_buf_alloc(DN_MAX_BONUSLEN);
1195                 arc_space_consume(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
1196                 bcopy(db->db.db_data, dr->dt.dl.dr_data, DN_MAX_BONUSLEN);
1197         } else if (refcount_count(&db->db_holds) > db->db_dirtycnt) {
1198                 int size = arc_buf_size(db->db_buf);
1199                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1200                 spa_t *spa = db->db_objset->os_spa;
1201                 enum zio_compress compress_type =
1202                     arc_get_compression(db->db_buf);
1203 
1204                 if (compress_type == ZIO_COMPRESS_OFF) {
1205                         dr->dt.dl.dr_data = arc_alloc_buf(spa, db, type, size);
1206                 } else {
1207                         ASSERT3U(type, ==, ARC_BUFC_DATA);
1208                         dr->dt.dl.dr_data = arc_alloc_compressed_buf(spa, db,
1209                             size, arc_buf_lsize(db->db_buf), compress_type);
1210                 }
1211                 bcopy(db->db.db_data, dr->dt.dl.dr_data->b_data, size);
1212         } else {
1213                 db->db_buf = NULL;
1214                 dbuf_clear_data(db);
1215         }
1216 }
1217 
1218 int
1219 dbuf_read(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
1220 {
1221         int err = 0;
1222         boolean_t prefetch;
1223         dnode_t *dn;
1224 
1225         /*
1226          * We don't have to hold the mutex to check db_state because it
1227          * can't be freed while we have a hold on the buffer.
1228          */
1229         ASSERT(!refcount_is_zero(&db->db_holds));
1230 
1231         if (db->db_state == DB_NOFILL)
1232                 return (SET_ERROR(EIO));
1233 
1234         DB_DNODE_ENTER(db);
1235         dn = DB_DNODE(db);
1236         if ((flags & DB_RF_HAVESTRUCT) == 0)
1237                 rw_enter(&dn->dn_struct_rwlock, RW_READER);
1238 
1239         prefetch = db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
1240             (flags & DB_RF_NOPREFETCH) == 0 && dn != NULL &&
1241             DBUF_IS_CACHEABLE(db);
1242 
1243         mutex_enter(&db->db_mtx);
1244         if (db->db_state == DB_CACHED) {
1245                 /*
1246                  * If the arc buf is compressed, we need to decompress it to
1247                  * read the data. This could happen during the "zfs receive" of
1248                  * a stream which is compressed and deduplicated.
1249                  */
1250                 if (db->db_buf != NULL &&
1251                     arc_get_compression(db->db_buf) != ZIO_COMPRESS_OFF) {
1252                         dbuf_fix_old_data(db,
1253                             spa_syncing_txg(dmu_objset_spa(db->db_objset)));
1254                         err = arc_decompress(db->db_buf);
1255                         dbuf_set_data(db, db->db_buf);
1256                 }
1257                 mutex_exit(&db->db_mtx);
1258                 if (prefetch)
1259                         dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
1260                 if ((flags & DB_RF_HAVESTRUCT) == 0)
1261                         rw_exit(&dn->dn_struct_rwlock);
1262                 DB_DNODE_EXIT(db);
1263         } else if (db->db_state == DB_UNCACHED) {
1264                 spa_t *spa = dn->dn_objset->os_spa;
1265                 boolean_t need_wait = B_FALSE;
1266 
1267                 if (zio == NULL &&
1268                     db->db_blkptr != NULL && !BP_IS_HOLE(db->db_blkptr)) {
1269                         zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
1270                         need_wait = B_TRUE;
1271                 }
1272                 dbuf_read_impl(db, zio, flags);
1273 
1274                 /* dbuf_read_impl has dropped db_mtx for us */
1275 
1276                 if (prefetch)
1277                         dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
1278 
1279                 if ((flags & DB_RF_HAVESTRUCT) == 0)
1280                         rw_exit(&dn->dn_struct_rwlock);
1281                 DB_DNODE_EXIT(db);
1282 
1283                 if (need_wait)
1284                         err = zio_wait(zio);
1285         } else {
1286                 /*
1287                  * Another reader came in while the dbuf was in flight
1288                  * between UNCACHED and CACHED.  Either a writer will finish
1289                  * writing the buffer (sending the dbuf to CACHED) or the
1290                  * first reader's request will reach the read_done callback
1291                  * and send the dbuf to CACHED.  Otherwise, a failure
1292                  * occurred and the dbuf went to UNCACHED.
1293                  */
1294                 mutex_exit(&db->db_mtx);
1295                 if (prefetch)
1296                         dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
1297                 if ((flags & DB_RF_HAVESTRUCT) == 0)
1298                         rw_exit(&dn->dn_struct_rwlock);
1299                 DB_DNODE_EXIT(db);
1300 
1301                 /* Skip the wait per the caller's request. */
1302                 mutex_enter(&db->db_mtx);
1303                 if ((flags & DB_RF_NEVERWAIT) == 0) {
1304                         while (db->db_state == DB_READ ||
1305                             db->db_state == DB_FILL) {
1306                                 ASSERT(db->db_state == DB_READ ||
1307                                     (flags & DB_RF_HAVESTRUCT) == 0);
1308                                 DTRACE_PROBE2(blocked__read, dmu_buf_impl_t *,
1309                                     db, zio_t *, zio);
1310                                 cv_wait(&db->db_changed, &db->db_mtx);
1311                         }
1312                         if (db->db_state == DB_UNCACHED)
1313                                 err = SET_ERROR(EIO);
1314                 }
1315                 mutex_exit(&db->db_mtx);
1316         }
1317 
1318         return (err);
1319 }
1320 
1321 static void
1322 dbuf_noread(dmu_buf_impl_t *db)
1323 {
1324         ASSERT(!refcount_is_zero(&db->db_holds));
1325         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1326         mutex_enter(&db->db_mtx);
1327         while (db->db_state == DB_READ || db->db_state == DB_FILL)
1328                 cv_wait(&db->db_changed, &db->db_mtx);
1329         if (db->db_state == DB_UNCACHED) {
1330                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1331                 spa_t *spa = db->db_objset->os_spa;
1332 
1333                 ASSERT(db->db_buf == NULL);
1334                 ASSERT(db->db.db_data == NULL);
1335                 dbuf_set_data(db, arc_alloc_buf(spa, db, type, db->db.db_size));
1336                 db->db_state = DB_FILL;
1337         } else if (db->db_state == DB_NOFILL) {
1338                 dbuf_clear_data(db);
1339         } else {
1340                 ASSERT3U(db->db_state, ==, DB_CACHED);
1341         }
1342         mutex_exit(&db->db_mtx);
1343 }
1344 
1345 void
1346 dbuf_unoverride(dbuf_dirty_record_t *dr)
1347 {
1348         dmu_buf_impl_t *db = dr->dr_dbuf;
1349         blkptr_t *bp = &dr->dt.dl.dr_overridden_by;
1350         uint64_t txg = dr->dr_txg;
1351 
1352         ASSERT(MUTEX_HELD(&db->db_mtx));
1353         /*
1354          * This assert is valid because dmu_sync() expects to be called by
1355          * a zilog's get_data while holding a range lock.  This call only
1356          * comes from dbuf_dirty() callers who must also hold a range lock.
1357          */
1358         ASSERT(dr->dt.dl.dr_override_state != DR_IN_DMU_SYNC);
1359         ASSERT(db->db_level == 0);
1360 
1361         if (db->db_blkid == DMU_BONUS_BLKID ||
1362             dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN)
1363                 return;
1364 
1365         ASSERT(db->db_data_pending != dr);
1366 
1367         /* free this block */
1368         if (!BP_IS_HOLE(bp) && !dr->dt.dl.dr_nopwrite)
1369                 zio_free(db->db_objset->os_spa, txg, bp);
1370 
1371         dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
1372         dr->dt.dl.dr_nopwrite = B_FALSE;
1373 
1374         /*
1375          * Release the already-written buffer, so we leave it in
1376          * a consistent dirty state.  Note that all callers are
1377          * modifying the buffer, so they will immediately do
1378          * another (redundant) arc_release().  Therefore, leave
1379          * the buf thawed to save the effort of freezing &
1380          * immediately re-thawing it.
1381          */
1382         arc_release(dr->dt.dl.dr_data, db);
1383 }
1384 
1385 /*
1386  * Evict (if its unreferenced) or clear (if its referenced) any level-0
1387  * data blocks in the free range, so that any future readers will find
1388  * empty blocks.
1389  */
1390 void
1391 dbuf_free_range(dnode_t *dn, uint64_t start_blkid, uint64_t end_blkid,
1392     dmu_tx_t *tx)
1393 {
1394         dmu_buf_impl_t db_search;
1395         dmu_buf_impl_t *db, *db_next;
1396         uint64_t txg = tx->tx_txg;
1397         avl_index_t where;
1398 
1399         if (end_blkid > dn->dn_maxblkid &&
1400             !(start_blkid == DMU_SPILL_BLKID || end_blkid == DMU_SPILL_BLKID))
1401                 end_blkid = dn->dn_maxblkid;
1402         dprintf_dnode(dn, "start=%llu end=%llu\n", start_blkid, end_blkid);
1403 
1404         db_search.db_level = 0;
1405         db_search.db_blkid = start_blkid;
1406         db_search.db_state = DB_SEARCH;
1407 
1408         mutex_enter(&dn->dn_dbufs_mtx);
1409         db = avl_find(&dn->dn_dbufs, &db_search, &where);
1410         ASSERT3P(db, ==, NULL);
1411 
1412         db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
1413 
1414         for (; db != NULL; db = db_next) {
1415                 db_next = AVL_NEXT(&dn->dn_dbufs, db);
1416                 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1417 
1418                 if (db->db_level != 0 || db->db_blkid > end_blkid) {
1419                         break;
1420                 }
1421                 ASSERT3U(db->db_blkid, >=, start_blkid);
1422 
1423                 /* found a level 0 buffer in the range */
1424                 mutex_enter(&db->db_mtx);
1425                 if (dbuf_undirty(db, tx)) {
1426                         /* mutex has been dropped and dbuf destroyed */
1427                         continue;
1428                 }
1429 
1430                 if (db->db_state == DB_UNCACHED ||
1431                     db->db_state == DB_NOFILL ||
1432                     db->db_state == DB_EVICTING) {
1433                         ASSERT(db->db.db_data == NULL);
1434                         mutex_exit(&db->db_mtx);
1435                         continue;
1436                 }
1437                 if (db->db_state == DB_READ || db->db_state == DB_FILL) {
1438                         /* will be handled in dbuf_read_done or dbuf_rele */
1439                         db->db_freed_in_flight = TRUE;
1440                         mutex_exit(&db->db_mtx);
1441                         continue;
1442                 }
1443                 if (refcount_count(&db->db_holds) == 0) {
1444                         ASSERT(db->db_buf);
1445                         dbuf_destroy(db);
1446                         continue;
1447                 }
1448                 /* The dbuf is referenced */
1449 
1450                 if (db->db_last_dirty != NULL) {
1451                         dbuf_dirty_record_t *dr = db->db_last_dirty;
1452 
1453                         if (dr->dr_txg == txg) {
1454                                 /*
1455                                  * This buffer is "in-use", re-adjust the file
1456                                  * size to reflect that this buffer may
1457                                  * contain new data when we sync.
1458                                  */
1459                                 if (db->db_blkid != DMU_SPILL_BLKID &&
1460                                     db->db_blkid > dn->dn_maxblkid)
1461                                         dn->dn_maxblkid = db->db_blkid;
1462                                 dbuf_unoverride(dr);
1463                         } else {
1464                                 /*
1465                                  * This dbuf is not dirty in the open context.
1466                                  * Either uncache it (if its not referenced in
1467                                  * the open context) or reset its contents to
1468                                  * empty.
1469                                  */
1470                                 dbuf_fix_old_data(db, txg);
1471                         }
1472                 }
1473                 /* clear the contents if its cached */
1474                 if (db->db_state == DB_CACHED) {
1475                         ASSERT(db->db.db_data != NULL);
1476                         arc_release(db->db_buf, db);
1477                         bzero(db->db.db_data, db->db.db_size);
1478                         arc_buf_freeze(db->db_buf);
1479                 }
1480 
1481                 mutex_exit(&db->db_mtx);
1482         }
1483         mutex_exit(&dn->dn_dbufs_mtx);
1484 }
1485 
1486 void
1487 dbuf_new_size(dmu_buf_impl_t *db, int size, dmu_tx_t *tx)
1488 {
1489         arc_buf_t *buf, *obuf;
1490         int osize = db->db.db_size;
1491         arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1492         dnode_t *dn;
1493 
1494         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1495 
1496         DB_DNODE_ENTER(db);
1497         dn = DB_DNODE(db);
1498 
1499         /* XXX does *this* func really need the lock? */
1500         ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
1501 
1502         /*
1503          * This call to dmu_buf_will_dirty() with the dn_struct_rwlock held
1504          * is OK, because there can be no other references to the db
1505          * when we are changing its size, so no concurrent DB_FILL can
1506          * be happening.
1507          */
1508         /*
1509          * XXX we should be doing a dbuf_read, checking the return
1510          * value and returning that up to our callers
1511          */
1512         dmu_buf_will_dirty(&db->db, tx);
1513 
1514         /* create the data buffer for the new block */
1515         buf = arc_alloc_buf(dn->dn_objset->os_spa, db, type, size);
1516 
1517         /* copy old block data to the new block */
1518         obuf = db->db_buf;
1519         bcopy(obuf->b_data, buf->b_data, MIN(osize, size));
1520         /* zero the remainder */
1521         if (size > osize)
1522                 bzero((uint8_t *)buf->b_data + osize, size - osize);
1523 
1524         mutex_enter(&db->db_mtx);
1525         dbuf_set_data(db, buf);
1526         arc_buf_destroy(obuf, db);
1527         db->db.db_size = size;
1528 
1529         if (db->db_level == 0) {
1530                 ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
1531                 db->db_last_dirty->dt.dl.dr_data = buf;
1532         }
1533         mutex_exit(&db->db_mtx);
1534 
1535         dmu_objset_willuse_space(dn->dn_objset, size - osize, tx);
1536         DB_DNODE_EXIT(db);
1537 }
1538 
1539 void
1540 dbuf_release_bp(dmu_buf_impl_t *db)
1541 {
1542         objset_t *os = db->db_objset;
1543 
1544         ASSERT(dsl_pool_sync_context(dmu_objset_pool(os)));
1545         ASSERT(arc_released(os->os_phys_buf) ||
1546             list_link_active(&os->os_dsl_dataset->ds_synced_link));
1547         ASSERT(db->db_parent == NULL || arc_released(db->db_parent->db_buf));
1548 
1549         (void) arc_release(db->db_buf, db);
1550 }
1551 
1552 /*
1553  * We already have a dirty record for this TXG, and we are being
1554  * dirtied again.
1555  */
1556 static void
1557 dbuf_redirty(dbuf_dirty_record_t *dr, boolean_t usesc)
1558 {
1559         dmu_buf_impl_t *db = dr->dr_dbuf;
1560 
1561         ASSERT(MUTEX_HELD(&db->db_mtx));
1562 
1563         if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID) {
1564                 /*
1565                  * If this buffer has already been written out,
1566                  * we now need to reset its state.
1567                  */
1568                 dbuf_unoverride(dr);
1569                 if (db->db.db_object != DMU_META_DNODE_OBJECT &&
1570                     db->db_state != DB_NOFILL) {
1571                         /* Already released on initial dirty, so just thaw. */
1572                         ASSERT(arc_released(db->db_buf));
1573                         arc_buf_thaw(db->db_buf);
1574                 }
1575         }
1576         /*
1577          * Special class usage of dirty dbuf could be changed,
1578          * update the dirty entry.
1579          */
1580         dr->dr_usesc = usesc;
1581 }
1582 
1583 dbuf_dirty_record_t *
1584 dbuf_dirty_sc(dmu_buf_impl_t *db, dmu_tx_t *tx, boolean_t usesc)
1585 {
1586         dnode_t *dn;
1587         objset_t *os;
1588         dbuf_dirty_record_t **drp, *dr;
1589         int drop_struct_lock = FALSE;
1590         int txgoff = tx->tx_txg & TXG_MASK;
1591 
1592         ASSERT(tx->tx_txg != 0);
1593         ASSERT(!refcount_is_zero(&db->db_holds));
1594         DMU_TX_DIRTY_BUF(tx, db);
1595 
1596         DB_DNODE_ENTER(db);
1597         dn = DB_DNODE(db);
1598         /*
1599          * Shouldn't dirty a regular buffer in syncing context.  Private
1600          * objects may be dirtied in syncing context, but only if they
1601          * were already pre-dirtied in open context.
1602          */
1603 #ifdef DEBUG
1604         if (dn->dn_objset->os_dsl_dataset != NULL) {
1605                 rrw_enter(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1606                     RW_READER, FTAG);
1607         }
1608         ASSERT(!dmu_tx_is_syncing(tx) ||
1609             BP_IS_HOLE(dn->dn_objset->os_rootbp) ||
1610             DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1611             dn->dn_objset->os_dsl_dataset == NULL);
1612         if (dn->dn_objset->os_dsl_dataset != NULL)
1613                 rrw_exit(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock, FTAG);
1614 #endif
1615         /*
1616          * We make this assert for private objects as well, but after we
1617          * check if we're already dirty.  They are allowed to re-dirty
1618          * in syncing context.
1619          */
1620         ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
1621             dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1622             (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1623 
1624         mutex_enter(&db->db_mtx);
1625         /*
1626          * XXX make this true for indirects too?  The problem is that
1627          * transactions created with dmu_tx_create_assigned() from
1628          * syncing context don't bother holding ahead.
1629          */
1630         ASSERT(db->db_level != 0 ||
1631             db->db_state == DB_CACHED || db->db_state == DB_FILL ||
1632             db->db_state == DB_NOFILL);
1633 
1634         mutex_enter(&dn->dn_mtx);
1635         /*
1636          * Don't set dirtyctx to SYNC if we're just modifying this as we
1637          * initialize the objset.
1638          */
1639         if (dn->dn_dirtyctx == DN_UNDIRTIED) {
1640                 if (dn->dn_objset->os_dsl_dataset != NULL) {
1641                         rrw_enter(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1642                             RW_READER, FTAG);
1643                 }
1644                 if (!BP_IS_HOLE(dn->dn_objset->os_rootbp)) {
1645                         dn->dn_dirtyctx = (dmu_tx_is_syncing(tx) ?
1646                             DN_DIRTY_SYNC : DN_DIRTY_OPEN);
1647                         ASSERT(dn->dn_dirtyctx_firstset == NULL);
1648                         dn->dn_dirtyctx_firstset = kmem_alloc(1, KM_SLEEP);
1649                 }
1650                 if (dn->dn_objset->os_dsl_dataset != NULL) {
1651                         rrw_exit(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1652                             FTAG);
1653                 }
1654         }
1655         mutex_exit(&dn->dn_mtx);
1656 
1657         if (db->db_blkid == DMU_SPILL_BLKID)
1658                 dn->dn_have_spill = B_TRUE;
1659 
1660         /*
1661          * If this buffer is already dirty, we're done.
1662          */
1663         drp = &db->db_last_dirty;
1664         ASSERT(*drp == NULL || (*drp)->dr_txg <= tx->tx_txg ||
1665             db->db.db_object == DMU_META_DNODE_OBJECT);
1666         while ((dr = *drp) != NULL && dr->dr_txg > tx->tx_txg)
1667                 drp = &dr->dr_next;
1668         if (dr && dr->dr_txg == tx->tx_txg) {
1669                 DB_DNODE_EXIT(db);
1670 
1671                 dbuf_redirty(dr, usesc);
1672                 mutex_exit(&db->db_mtx);
1673                 return (dr);
1674         }
1675 
1676         /*
1677          * Only valid if not already dirty.
1678          */
1679         ASSERT(dn->dn_object == 0 ||
1680             dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1681             (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1682 
1683         ASSERT3U(dn->dn_nlevels, >, db->db_level);
1684 
1685         /*
1686          * We should only be dirtying in syncing context if it's the
1687          * mos or we're initializing the os or it's a special object.
1688          * However, we are allowed to dirty in syncing context provided
1689          * we already dirtied it in open context.  Hence we must make
1690          * this assertion only if we're not already dirty.
1691          */
1692         os = dn->dn_objset;
1693         VERIFY3U(tx->tx_txg, <=, spa_final_dirty_txg(os->os_spa));
1694 #ifdef DEBUG
1695         if (dn->dn_objset->os_dsl_dataset != NULL)
1696                 rrw_enter(&os->os_dsl_dataset->ds_bp_rwlock, RW_READER, FTAG);
1697         ASSERT(!dmu_tx_is_syncing(tx) || DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1698             os->os_dsl_dataset == NULL || BP_IS_HOLE(os->os_rootbp));
1699         if (dn->dn_objset->os_dsl_dataset != NULL)
1700                 rrw_exit(&os->os_dsl_dataset->ds_bp_rwlock, FTAG);
1701 #endif
1702         ASSERT(db->db.db_size != 0);
1703 
1704         dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1705 
1706         if (db->db_blkid != DMU_BONUS_BLKID) {
1707                 dmu_objset_willuse_space(os, db->db.db_size, tx);
1708         }
1709 
1710         /*
1711          * If this buffer is dirty in an old transaction group we need
1712          * to make a copy of it so that the changes we make in this
1713          * transaction group won't leak out when we sync the older txg.
1714          */
1715         dr = kmem_zalloc(sizeof (dbuf_dirty_record_t), KM_SLEEP);
1716         if (db->db_level == 0) {
1717                 void *data_old = db->db_buf;
1718 
1719                 if (db->db_state != DB_NOFILL) {
1720                         if (db->db_blkid == DMU_BONUS_BLKID) {
1721                                 dbuf_fix_old_data(db, tx->tx_txg);
1722                                 data_old = db->db.db_data;
1723                         } else if (db->db.db_object != DMU_META_DNODE_OBJECT) {
1724                                 /*
1725                                  * Release the data buffer from the cache so
1726                                  * that we can modify it without impacting
1727                                  * possible other users of this cached data
1728                                  * block.  Note that indirect blocks and
1729                                  * private objects are not released until the
1730                                  * syncing state (since they are only modified
1731                                  * then).
1732                                  */
1733                                 arc_release(db->db_buf, db);
1734                                 dbuf_fix_old_data(db, tx->tx_txg);
1735                                 data_old = db->db_buf;
1736                         }
1737                         ASSERT(data_old != NULL);
1738                 }
1739                 dr->dt.dl.dr_data = data_old;
1740         } else {
1741                 mutex_init(&dr->dt.di.dr_mtx, NULL, MUTEX_DEFAULT, NULL);
1742                 list_create(&dr->dt.di.dr_children,
1743                     sizeof (dbuf_dirty_record_t),
1744                     offsetof(dbuf_dirty_record_t, dr_dirty_node));
1745         }
1746         if (db->db_blkid != DMU_BONUS_BLKID && os->os_dsl_dataset != NULL)
1747                 dr->dr_accounted = db->db.db_size;
1748         dr->dr_dbuf = db;
1749         dr->dr_txg = tx->tx_txg;
1750         dr->dr_next = *drp;
1751         dr->dr_usesc = usesc;
1752         *drp = dr;
1753 
1754         /*
1755          * We could have been freed_in_flight between the dbuf_noread
1756          * and dbuf_dirty.  We win, as though the dbuf_noread() had
1757          * happened after the free.
1758          */
1759         if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
1760             db->db_blkid != DMU_SPILL_BLKID) {
1761                 mutex_enter(&dn->dn_mtx);
1762                 if (dn->dn_free_ranges[txgoff] != NULL) {
1763                         range_tree_clear(dn->dn_free_ranges[txgoff],
1764                             db->db_blkid, 1);
1765                 }
1766                 mutex_exit(&dn->dn_mtx);
1767                 db->db_freed_in_flight = FALSE;
1768         }
1769 
1770         /*
1771          * This buffer is now part of this txg
1772          */
1773         dbuf_add_ref(db, (void *)(uintptr_t)tx->tx_txg);
1774         db->db_dirtycnt += 1;
1775         ASSERT3U(db->db_dirtycnt, <=, 3);
1776 
1777         mutex_exit(&db->db_mtx);
1778 
1779         if (db->db_blkid == DMU_BONUS_BLKID ||
1780             db->db_blkid == DMU_SPILL_BLKID) {
1781                 mutex_enter(&dn->dn_mtx);
1782                 ASSERT(!list_link_active(&dr->dr_dirty_node));
1783                 list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1784                 mutex_exit(&dn->dn_mtx);
1785                 dnode_setdirty_sc(dn, tx, usesc);
1786                 DB_DNODE_EXIT(db);
1787                 return (dr);
1788         }
1789 
1790         /*
1791          * The dn_struct_rwlock prevents db_blkptr from changing
1792          * due to a write from syncing context completing
1793          * while we are running, so we want to acquire it before
1794          * looking at db_blkptr.
1795          */
1796         if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
1797                 rw_enter(&dn->dn_struct_rwlock, RW_READER);
1798                 drop_struct_lock = TRUE;
1799         }
1800 
1801         /*
1802          * We need to hold the dn_struct_rwlock to make this assertion,
1803          * because it protects dn_phys / dn_next_nlevels from changing.
1804          */
1805         ASSERT((dn->dn_phys->dn_nlevels == 0 && db->db_level == 0) ||
1806             dn->dn_phys->dn_nlevels > db->db_level ||
1807             dn->dn_next_nlevels[txgoff] > db->db_level ||
1808             dn->dn_next_nlevels[(tx->tx_txg-1) & TXG_MASK] > db->db_level ||
1809             dn->dn_next_nlevels[(tx->tx_txg-2) & TXG_MASK] > db->db_level);
1810 
1811         /*
1812          * If we are overwriting a dedup BP, then unless it is snapshotted,
1813          * when we get to syncing context we will need to decrement its
1814          * refcount in the DDT.  Prefetch the relevant DDT block so that
1815          * syncing context won't have to wait for the i/o.
1816          */
1817         ddt_prefetch(os->os_spa, db->db_blkptr);
1818 
1819         if (db->db_level == 0) {
1820                 dnode_new_blkid(dn, db->db_blkid, tx, usesc, drop_struct_lock);
1821                 ASSERT(dn->dn_maxblkid >= db->db_blkid);
1822         }
1823 
1824         if (db->db_level+1 < dn->dn_nlevels) {
1825                 dmu_buf_impl_t *parent = db->db_parent;
1826                 dbuf_dirty_record_t *di;
1827                 int parent_held = FALSE;
1828 
1829                 if (db->db_parent == NULL || db->db_parent == dn->dn_dbuf) {
1830                         int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1831 
1832                         parent = dbuf_hold_level(dn, db->db_level+1,
1833                             db->db_blkid >> epbs, FTAG);
1834                         ASSERT(parent != NULL);
1835                         parent_held = TRUE;
1836                 }
1837                 if (drop_struct_lock)
1838                         rw_exit(&dn->dn_struct_rwlock);
1839                 ASSERT3U(db->db_level+1, ==, parent->db_level);
1840                 di = dbuf_dirty_sc(parent, tx, usesc);
1841                 if (parent_held)
1842                         dbuf_rele(parent, FTAG);
1843 
1844                 mutex_enter(&db->db_mtx);
1845                 /*
1846                  * Since we've dropped the mutex, it's possible that
1847                  * dbuf_undirty() might have changed this out from under us.
1848                  */
1849                 if (db->db_last_dirty == dr ||
1850                     dn->dn_object == DMU_META_DNODE_OBJECT) {
1851                         mutex_enter(&di->dt.di.dr_mtx);
1852                         ASSERT3U(di->dr_txg, ==, tx->tx_txg);
1853                         ASSERT(!list_link_active(&dr->dr_dirty_node));
1854                         list_insert_tail(&di->dt.di.dr_children, dr);
1855                         mutex_exit(&di->dt.di.dr_mtx);
1856                         dr->dr_parent = di;
1857                 }
1858 
1859                 /*
1860                  * Special class usage of dirty dbuf could be changed,
1861                  * update the dirty entry.
1862                  */
1863                 dr->dr_usesc = usesc;
1864                 mutex_exit(&db->db_mtx);
1865         } else {
1866                 ASSERT(db->db_level+1 == dn->dn_nlevels);
1867                 ASSERT(db->db_blkid < dn->dn_nblkptr);
1868                 ASSERT(db->db_parent == NULL || db->db_parent == dn->dn_dbuf);
1869                 mutex_enter(&dn->dn_mtx);
1870                 ASSERT(!list_link_active(&dr->dr_dirty_node));
1871                 list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1872                 mutex_exit(&dn->dn_mtx);
1873                 if (drop_struct_lock)
1874                         rw_exit(&dn->dn_struct_rwlock);
1875         }
1876 
1877         dnode_setdirty_sc(dn, tx, usesc);
1878         DB_DNODE_EXIT(db);
1879         return (dr);
1880 }
1881 
1882 dbuf_dirty_record_t *
1883 dbuf_dirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1884 {
1885         spa_t *spa;
1886 
1887         ASSERT(db->db_objset != NULL);
1888         spa = db->db_objset->os_spa;
1889 
1890         return (dbuf_dirty_sc(db, tx, spa->spa_usesc));
1891 }
1892 
1893 /*
1894  * Undirty a buffer in the transaction group referenced by the given
1895  * transaction.  Return whether this evicted the dbuf.
1896  */
1897 static boolean_t
1898 dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1899 {
1900         dnode_t *dn;
1901         uint64_t txg = tx->tx_txg;
1902         dbuf_dirty_record_t *dr, **drp;
1903 
1904         ASSERT(txg != 0);
1905 
1906         /*
1907          * Due to our use of dn_nlevels below, this can only be called
1908          * in open context, unless we are operating on the MOS.
1909          * From syncing context, dn_nlevels may be different from the
1910          * dn_nlevels used when dbuf was dirtied.
1911          */
1912         ASSERT(db->db_objset ==
1913             dmu_objset_pool(db->db_objset)->dp_meta_objset ||
1914             txg != spa_syncing_txg(dmu_objset_spa(db->db_objset)));
1915         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1916         ASSERT0(db->db_level);
1917         ASSERT(MUTEX_HELD(&db->db_mtx));
1918 
1919         /*
1920          * If this buffer is not dirty, we're done.
1921          */
1922         for (drp = &db->db_last_dirty; (dr = *drp) != NULL; drp = &dr->dr_next)
1923                 if (dr->dr_txg <= txg)
1924                         break;
1925         if (dr == NULL || dr->dr_txg < txg)
1926                 return (B_FALSE);
1927         ASSERT(dr->dr_txg == txg);
1928         ASSERT(dr->dr_dbuf == db);
1929 
1930         DB_DNODE_ENTER(db);
1931         dn = DB_DNODE(db);
1932 
1933         dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1934 
1935         ASSERT(db->db.db_size != 0);
1936 
1937         dsl_pool_undirty_space(dmu_objset_pool(dn->dn_objset),
1938             dr->dr_accounted, txg);
1939 
1940         *drp = dr->dr_next;
1941 
1942         /*
1943          * Note that there are three places in dbuf_dirty()
1944          * where this dirty record may be put on a list.
1945          * Make sure to do a list_remove corresponding to
1946          * every one of those list_insert calls.
1947          */
1948         if (dr->dr_parent) {
1949                 mutex_enter(&dr->dr_parent->dt.di.dr_mtx);
1950                 list_remove(&dr->dr_parent->dt.di.dr_children, dr);
1951                 mutex_exit(&dr->dr_parent->dt.di.dr_mtx);
1952         } else if (db->db_blkid == DMU_SPILL_BLKID ||
1953             db->db_level + 1 == dn->dn_nlevels) {
1954                 ASSERT(db->db_blkptr == NULL || db->db_parent == dn->dn_dbuf);
1955                 mutex_enter(&dn->dn_mtx);
1956                 list_remove(&dn->dn_dirty_records[txg & TXG_MASK], dr);
1957                 mutex_exit(&dn->dn_mtx);
1958         }
1959         DB_DNODE_EXIT(db);
1960 
1961         if (db->db_state != DB_NOFILL) {
1962                 dbuf_unoverride(dr);
1963 
1964                 ASSERT(db->db_buf != NULL);
1965                 ASSERT(dr->dt.dl.dr_data != NULL);
1966                 if (dr->dt.dl.dr_data != db->db_buf)
1967                         arc_buf_destroy(dr->dt.dl.dr_data, db);
1968         }
1969 
1970         kmem_free(dr, sizeof (dbuf_dirty_record_t));
1971 
1972         ASSERT(db->db_dirtycnt > 0);
1973         db->db_dirtycnt -= 1;
1974 
1975         if (refcount_remove(&db->db_holds, (void *)(uintptr_t)txg) == 0) {
1976                 ASSERT(db->db_state == DB_NOFILL || arc_released(db->db_buf));
1977                 dbuf_destroy(db);
1978                 return (B_TRUE);
1979         }
1980 
1981         return (B_FALSE);
1982 }
1983 
1984 void
1985 dmu_buf_will_dirty(dmu_buf_t *db_fake, dmu_tx_t *tx)
1986 {
1987         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1988         spa_t *spa = db->db_objset->os_spa;
1989         dmu_buf_will_dirty_sc(db_fake, tx, spa->spa_usesc);
1990 }
1991 
1992 void
1993 dmu_buf_will_dirty_sc(dmu_buf_t *db_fake, dmu_tx_t *tx, boolean_t usesc)
1994 {
1995         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1996         int rf = DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH;
1997 
1998         ASSERT(tx->tx_txg != 0);
1999         ASSERT(!refcount_is_zero(&db->db_holds));
2000 
2001         /*
2002          * Quick check for dirtyness.  For already dirty blocks, this
2003          * reduces runtime of this function by >90%, and overall performance
2004          * by 50% for some workloads (e.g. file deletion with indirect blocks
2005          * cached).
2006          */
2007         mutex_enter(&db->db_mtx);
2008         dbuf_dirty_record_t *dr;
2009         for (dr = db->db_last_dirty;
2010             dr != NULL && dr->dr_txg >= tx->tx_txg; dr = dr->dr_next) {
2011                 /*
2012                  * It's possible that it is already dirty but not cached,
2013                  * because there are some calls to dbuf_dirty() that don't
2014                  * go through dmu_buf_will_dirty().
2015                  */
2016                 if (dr->dr_txg == tx->tx_txg && db->db_state == DB_CACHED) {
2017                         /* This dbuf is already dirty and cached. */
2018                         dbuf_redirty(dr, usesc);
2019                         mutex_exit(&db->db_mtx);
2020                         return;
2021                 }
2022         }
2023         mutex_exit(&db->db_mtx);
2024 
2025         DB_DNODE_ENTER(db);
2026         if (RW_WRITE_HELD(&DB_DNODE(db)->dn_struct_rwlock))
2027                 rf |= DB_RF_HAVESTRUCT;
2028         DB_DNODE_EXIT(db);
2029         (void) dbuf_read(db, NULL, rf);
2030         (void) dbuf_dirty_sc(db, tx, usesc);
2031 }
2032 
2033 
2034 void
2035 dmu_buf_will_not_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
2036 {
2037         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2038 
2039         db->db_state = DB_NOFILL;
2040 
2041         dmu_buf_will_fill(db_fake, tx);
2042 }
2043 
2044 void
2045 dmu_buf_will_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
2046 {
2047         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2048 
2049         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2050         ASSERT(tx->tx_txg != 0);
2051         ASSERT(db->db_level == 0);
2052         ASSERT(!refcount_is_zero(&db->db_holds));
2053 
2054         ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT ||
2055             dmu_tx_private_ok(tx));
2056 
2057         dbuf_noread(db);
2058         (void) dbuf_dirty(db, tx);
2059 }
2060 
2061 #pragma weak dmu_buf_fill_done = dbuf_fill_done
2062 /* ARGSUSED */
2063 void
2064 dbuf_fill_done(dmu_buf_impl_t *db, dmu_tx_t *tx)
2065 {
2066         mutex_enter(&db->db_mtx);
2067         DBUF_VERIFY(db);
2068 
2069         if (db->db_state == DB_FILL) {
2070                 if (db->db_level == 0 && db->db_freed_in_flight) {
2071                         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2072                         /* we were freed while filling */
2073                         /* XXX dbuf_undirty? */
2074                         bzero(db->db.db_data, db->db.db_size);
2075                         db->db_freed_in_flight = FALSE;
2076                 }
2077                 db->db_state = DB_CACHED;
2078                 cv_broadcast(&db->db_changed);
2079         }
2080         mutex_exit(&db->db_mtx);
2081 }
2082 
2083 void
2084 dmu_buf_write_embedded(dmu_buf_t *dbuf, void *data,
2085     bp_embedded_type_t etype, enum zio_compress comp,
2086     int uncompressed_size, int compressed_size, int byteorder,
2087     dmu_tx_t *tx)
2088 {
2089         dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
2090         struct dirty_leaf *dl;
2091         dmu_object_type_t type;
2092 
2093         if (etype == BP_EMBEDDED_TYPE_DATA) {
2094                 ASSERT(spa_feature_is_active(dmu_objset_spa(db->db_objset),
2095                     SPA_FEATURE_EMBEDDED_DATA));
2096         }
2097 
2098         DB_DNODE_ENTER(db);
2099         type = DB_DNODE(db)->dn_type;
2100         DB_DNODE_EXIT(db);
2101 
2102         ASSERT0(db->db_level);
2103         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2104 
2105         dmu_buf_will_not_fill(dbuf, tx);
2106 
2107         ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
2108         dl = &db->db_last_dirty->dt.dl;
2109         encode_embedded_bp_compressed(&dl->dr_overridden_by,
2110             data, comp, uncompressed_size, compressed_size);
2111         BPE_SET_ETYPE(&dl->dr_overridden_by, etype);
2112         BP_SET_TYPE(&dl->dr_overridden_by, type);
2113         BP_SET_LEVEL(&dl->dr_overridden_by, 0);
2114         BP_SET_BYTEORDER(&dl->dr_overridden_by, byteorder);
2115 
2116         dl->dr_override_state = DR_OVERRIDDEN;
2117         dl->dr_overridden_by.blk_birth = db->db_last_dirty->dr_txg;
2118 }
2119 
2120 /*
2121  * Directly assign a provided arc buf to a given dbuf if it's not referenced
2122  * by anybody except our caller. Otherwise copy arcbuf's contents to dbuf.
2123  */
2124 void
2125 dbuf_assign_arcbuf(dmu_buf_impl_t *db, arc_buf_t *buf, dmu_tx_t *tx)
2126 {
2127         ASSERT(!refcount_is_zero(&db->db_holds));
2128         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2129         ASSERT(db->db_level == 0);
2130         ASSERT3U(dbuf_is_metadata(db), ==, arc_is_metadata(buf));
2131         ASSERT(buf != NULL);
2132         ASSERT(arc_buf_lsize(buf) == db->db.db_size);
2133         ASSERT(tx->tx_txg != 0);
2134 
2135         arc_return_buf(buf, db);
2136         ASSERT(arc_released(buf));
2137 
2138         mutex_enter(&db->db_mtx);
2139 
2140         while (db->db_state == DB_READ || db->db_state == DB_FILL)
2141                 cv_wait(&db->db_changed, &db->db_mtx);
2142 
2143         ASSERT(db->db_state == DB_CACHED || db->db_state == DB_UNCACHED);
2144 
2145         if (db->db_state == DB_CACHED &&
2146             refcount_count(&db->db_holds) - 1 > db->db_dirtycnt) {
2147                 mutex_exit(&db->db_mtx);
2148                 (void) dbuf_dirty(db, tx);
2149                 bcopy(buf->b_data, db->db.db_data, db->db.db_size);
2150                 arc_buf_destroy(buf, db);
2151                 xuio_stat_wbuf_copied();
2152                 return;
2153         }
2154 
2155         xuio_stat_wbuf_nocopy();
2156         if (db->db_state == DB_CACHED) {
2157                 dbuf_dirty_record_t *dr = db->db_last_dirty;
2158 
2159                 ASSERT(db->db_buf != NULL);
2160                 if (dr != NULL && dr->dr_txg == tx->tx_txg) {
2161                         ASSERT(dr->dt.dl.dr_data == db->db_buf);
2162                         if (!arc_released(db->db_buf)) {
2163                                 ASSERT(dr->dt.dl.dr_override_state ==
2164                                     DR_OVERRIDDEN);
2165                                 arc_release(db->db_buf, db);
2166                         }
2167                         dr->dt.dl.dr_data = buf;
2168                         arc_buf_destroy(db->db_buf, db);
2169                 } else if (dr == NULL || dr->dt.dl.dr_data != db->db_buf) {
2170                         arc_release(db->db_buf, db);
2171                         arc_buf_destroy(db->db_buf, db);
2172                 }
2173                 db->db_buf = NULL;
2174         }
2175         ASSERT(db->db_buf == NULL);
2176         dbuf_set_data(db, buf);
2177         db->db_state = DB_FILL;
2178         mutex_exit(&db->db_mtx);
2179         (void) dbuf_dirty(db, tx);
2180         dmu_buf_fill_done(&db->db, tx);
2181 }
2182 
2183 void
2184 dbuf_destroy(dmu_buf_impl_t *db)
2185 {
2186         dnode_t *dn;
2187         dmu_buf_impl_t *parent = db->db_parent;
2188         dmu_buf_impl_t *dndb;
2189 
2190         ASSERT(MUTEX_HELD(&db->db_mtx));
2191         ASSERT(refcount_is_zero(&db->db_holds));
2192 
2193         if (db->db_buf != NULL) {
2194                 arc_buf_destroy(db->db_buf, db);
2195                 db->db_buf = NULL;
2196         }
2197 
2198         if (db->db_blkid == DMU_BONUS_BLKID) {
2199                 ASSERT(db->db.db_data != NULL);
2200                 zio_buf_free(db->db.db_data, DN_MAX_BONUSLEN);
2201                 arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
2202                 db->db_state = DB_UNCACHED;
2203         }
2204 
2205         dbuf_clear_data(db);
2206 
2207         if (multilist_link_active(&db->db_cache_link)) {
2208                 ASSERT(db->db_caching_status == DB_DBUF_CACHE ||
2209                     db->db_caching_status == DB_DBUF_METADATA_CACHE);
2210 
2211                 multilist_remove(dbuf_caches[db->db_caching_status].cache, db);
2212                 (void) refcount_remove_many(
2213                     &dbuf_caches[db->db_caching_status].size,
2214                     db->db.db_size, db);
2215 
2216                 db->db_caching_status = DB_NO_CACHE;
2217         }
2218 
2219         ASSERT(db->db_state == DB_UNCACHED || db->db_state == DB_NOFILL);
2220         ASSERT(db->db_data_pending == NULL);
2221 
2222         db->db_state = DB_EVICTING;
2223         db->db_blkptr = NULL;
2224 
2225         /*
2226          * Now that db_state is DB_EVICTING, nobody else can find this via
2227          * the hash table.  We can now drop db_mtx, which allows us to
2228          * acquire the dn_dbufs_mtx.
2229          */
2230         mutex_exit(&db->db_mtx);
2231 
2232         DB_DNODE_ENTER(db);
2233         dn = DB_DNODE(db);
2234         dndb = dn->dn_dbuf;
2235         if (db->db_blkid != DMU_BONUS_BLKID) {
2236                 boolean_t needlock = !MUTEX_HELD(&dn->dn_dbufs_mtx);
2237                 if (needlock)
2238                         mutex_enter(&dn->dn_dbufs_mtx);
2239                 avl_remove(&dn->dn_dbufs, db);
2240                 atomic_dec_32(&dn->dn_dbufs_count);
2241                 membar_producer();
2242                 DB_DNODE_EXIT(db);
2243                 if (needlock)
2244                         mutex_exit(&dn->dn_dbufs_mtx);
2245                 /*
2246                  * Decrementing the dbuf count means that the hold corresponding
2247                  * to the removed dbuf is no longer discounted in dnode_move(),
2248                  * so the dnode cannot be moved until after we release the hold.
2249                  * The membar_producer() ensures visibility of the decremented
2250                  * value in dnode_move(), since DB_DNODE_EXIT doesn't actually
2251                  * release any lock.
2252                  */
2253                 dnode_rele(dn, db);
2254                 db->db_dnode_handle = NULL;
2255 
2256                 dbuf_hash_remove(db);
2257         } else {
2258                 DB_DNODE_EXIT(db);
2259         }
2260 
2261         ASSERT(refcount_is_zero(&db->db_holds));
2262 
2263         db->db_parent = NULL;
2264 
2265         ASSERT(db->db_buf == NULL);
2266         ASSERT(db->db.db_data == NULL);
2267         ASSERT(db->db_hash_next == NULL);
2268         ASSERT(db->db_blkptr == NULL);
2269         ASSERT(db->db_data_pending == NULL);
2270         ASSERT3U(db->db_caching_status, ==, DB_NO_CACHE);
2271         ASSERT(!multilist_link_active(&db->db_cache_link));
2272 
2273         kmem_cache_free(dbuf_kmem_cache, db);
2274         arc_space_return(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
2275 
2276         /*
2277          * If this dbuf is referenced from an indirect dbuf,
2278          * decrement the ref count on the indirect dbuf.
2279          */
2280         if (parent && parent != dndb)
2281                 dbuf_rele(parent, db);
2282 }
2283 
2284 /*
2285  * Note: While bpp will always be updated if the function returns success,
2286  * parentp will not be updated if the dnode does not have dn_dbuf filled in;
2287  * this happens when the dnode is the meta-dnode, or a userused or groupused
2288  * object.
2289  */
2290 static int
2291 dbuf_findbp(dnode_t *dn, int level, uint64_t blkid, int fail_sparse,
2292     dmu_buf_impl_t **parentp, blkptr_t **bpp)
2293 {
2294         *parentp = NULL;
2295         *bpp = NULL;
2296 
2297         ASSERT(blkid != DMU_BONUS_BLKID);
2298 
2299         if (blkid == DMU_SPILL_BLKID) {
2300                 mutex_enter(&dn->dn_mtx);
2301                 if (dn->dn_have_spill &&
2302                     (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR))
2303                         *bpp = &dn->dn_phys->dn_spill;
2304                 else
2305                         *bpp = NULL;
2306                 dbuf_add_ref(dn->dn_dbuf, NULL);
2307                 *parentp = dn->dn_dbuf;
2308                 mutex_exit(&dn->dn_mtx);
2309                 return (0);
2310         }
2311 
2312         int nlevels =
2313             (dn->dn_phys->dn_nlevels == 0) ? 1 : dn->dn_phys->dn_nlevels;
2314         int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
2315 
2316         ASSERT3U(level * epbs, <, 64);
2317         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2318         /*
2319          * This assertion shouldn't trip as long as the max indirect block size
2320          * is less than 1M.  The reason for this is that up to that point,
2321          * the number of levels required to address an entire object with blocks
2322          * of size SPA_MINBLOCKSIZE satisfies nlevels * epbs + 1 <= 64.  In
2323          * other words, if N * epbs + 1 > 64, then if (N-1) * epbs + 1 > 55
2324          * (i.e. we can address the entire object), objects will all use at most
2325          * N-1 levels and the assertion won't overflow.  However, once epbs is
2326          * 13, 4 * 13 + 1 = 53, but 5 * 13 + 1 = 66.  Then, 4 levels will not be
2327          * enough to address an entire object, so objects will have 5 levels,
2328          * but then this assertion will overflow.
2329          *
2330          * All this is to say that if we ever increase DN_MAX_INDBLKSHIFT, we
2331          * need to redo this logic to handle overflows.
2332          */
2333         ASSERT(level >= nlevels ||
2334             ((nlevels - level - 1) * epbs) +
2335             highbit64(dn->dn_phys->dn_nblkptr) <= 64);
2336         if (level >= nlevels ||
2337             blkid >= ((uint64_t)dn->dn_phys->dn_nblkptr <<
2338             ((nlevels - level - 1) * epbs)) ||
2339             (fail_sparse &&
2340             blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))) {
2341                 /* the buffer has no parent yet */
2342                 return (SET_ERROR(ENOENT));
2343         } else if (level < nlevels-1) {
2344                 /* this block is referenced from an indirect block */
2345                 int err = dbuf_hold_impl(dn, level+1,
2346                     blkid >> epbs, fail_sparse, FALSE, NULL, parentp);
2347                 if (err)
2348                         return (err);
2349                 err = dbuf_read(*parentp, NULL,
2350                     (DB_RF_HAVESTRUCT | DB_RF_NOPREFETCH | DB_RF_CANFAIL));
2351                 if (err) {
2352                         dbuf_rele(*parentp, NULL);
2353                         *parentp = NULL;
2354                         return (err);
2355                 }
2356                 *bpp = ((blkptr_t *)(*parentp)->db.db_data) +
2357                     (blkid & ((1ULL << epbs) - 1));
2358                 if (blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))
2359                         ASSERT(BP_IS_HOLE(*bpp));
2360                 return (0);
2361         } else {
2362                 /* the block is referenced from the dnode */
2363                 ASSERT3U(level, ==, nlevels-1);
2364                 ASSERT(dn->dn_phys->dn_nblkptr == 0 ||
2365                     blkid < dn->dn_phys->dn_nblkptr);
2366                 if (dn->dn_dbuf) {
2367                         dbuf_add_ref(dn->dn_dbuf, NULL);
2368                         *parentp = dn->dn_dbuf;
2369                 }
2370                 *bpp = &dn->dn_phys->dn_blkptr[blkid];
2371                 return (0);
2372         }
2373 }
2374 
2375 static dmu_buf_impl_t *
2376 dbuf_create(dnode_t *dn, uint8_t level, uint64_t blkid,
2377     dmu_buf_impl_t *parent, blkptr_t *blkptr)
2378 {
2379         objset_t *os = dn->dn_objset;
2380         dmu_buf_impl_t *db, *odb;
2381 
2382         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2383         ASSERT(dn->dn_type != DMU_OT_NONE);
2384 
2385         db = kmem_cache_alloc(dbuf_kmem_cache, KM_SLEEP);
2386 
2387         db->db_objset = os;
2388         db->db.db_object = dn->dn_object;
2389         db->db_level = level;
2390         db->db_blkid = blkid;
2391         db->db_last_dirty = NULL;
2392         db->db_dirtycnt = 0;
2393         db->db_dnode_handle = dn->dn_handle;
2394         db->db_parent = parent;
2395         db->db_blkptr = blkptr;
2396 
2397         db->db_user = NULL;
2398         db->db_user_immediate_evict = FALSE;
2399         db->db_freed_in_flight = FALSE;
2400         db->db_pending_evict = FALSE;
2401 
2402         if (blkid == DMU_BONUS_BLKID) {
2403                 ASSERT3P(parent, ==, dn->dn_dbuf);
2404                 db->db.db_size = DN_MAX_BONUSLEN -
2405                     (dn->dn_nblkptr-1) * sizeof (blkptr_t);
2406                 ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
2407                 db->db.db_offset = DMU_BONUS_BLKID;
2408                 db->db_state = DB_UNCACHED;
2409                 db->db_caching_status = DB_NO_CACHE;
2410                 /* the bonus dbuf is not placed in the hash table */
2411                 arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
2412                 return (db);
2413         } else if (blkid == DMU_SPILL_BLKID) {
2414                 db->db.db_size = (blkptr != NULL) ?
2415                     BP_GET_LSIZE(blkptr) : SPA_MINBLOCKSIZE;
2416                 db->db.db_offset = 0;
2417         } else {
2418                 int blocksize =
2419                     db->db_level ? 1 << dn->dn_indblkshift : dn->dn_datablksz;
2420                 db->db.db_size = blocksize;
2421                 db->db.db_offset = db->db_blkid * blocksize;
2422         }
2423 
2424         /*
2425          * Hold the dn_dbufs_mtx while we get the new dbuf
2426          * in the hash table *and* added to the dbufs list.
2427          * This prevents a possible deadlock with someone
2428          * trying to look up this dbuf before its added to the
2429          * dn_dbufs list.
2430          */
2431         mutex_enter(&dn->dn_dbufs_mtx);
2432         db->db_state = DB_EVICTING;
2433         if ((odb = dbuf_hash_insert(db)) != NULL) {
2434                 /* someone else inserted it first */
2435                 kmem_cache_free(dbuf_kmem_cache, db);
2436                 mutex_exit(&dn->dn_dbufs_mtx);
2437                 return (odb);
2438         }
2439         avl_add(&dn->dn_dbufs, db);
2440 
2441         db->db_state = DB_UNCACHED;
2442         db->db_caching_status = DB_NO_CACHE;
2443         mutex_exit(&dn->dn_dbufs_mtx);
2444         arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
2445 
2446         if (parent && parent != dn->dn_dbuf)
2447                 dbuf_add_ref(parent, db);
2448 
2449         ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
2450             refcount_count(&dn->dn_holds) > 0);
2451         (void) refcount_add(&dn->dn_holds, db);
2452         atomic_inc_32(&dn->dn_dbufs_count);
2453 
2454         dprintf_dbuf(db, "db=%p\n", db);
2455 
2456         return (db);
2457 }
2458 
2459 typedef struct dbuf_prefetch_arg {
2460         spa_t *dpa_spa; /* The spa to issue the prefetch in. */
2461         zbookmark_phys_t dpa_zb; /* The target block to prefetch. */
2462         int dpa_epbs; /* Entries (blkptr_t's) Per Block Shift. */
2463         int dpa_curlevel; /* The current level that we're reading */
2464         dnode_t *dpa_dnode; /* The dnode associated with the prefetch */
2465         zio_priority_t dpa_prio; /* The priority I/Os should be issued at. */
2466         zio_t *dpa_zio; /* The parent zio_t for all prefetches. */
2467         arc_flags_t dpa_aflags; /* Flags to pass to the final prefetch. */
2468 } dbuf_prefetch_arg_t;
2469 
2470 /*
2471  * Actually issue the prefetch read for the block given.
2472  */
2473 static void
2474 dbuf_issue_final_prefetch(dbuf_prefetch_arg_t *dpa, blkptr_t *bp)
2475 {
2476         if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2477                 return;
2478 
2479         arc_flags_t aflags =
2480             dpa->dpa_aflags | ARC_FLAG_NOWAIT | ARC_FLAG_PREFETCH;
2481 
2482         ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
2483         ASSERT3U(dpa->dpa_curlevel, ==, dpa->dpa_zb.zb_level);
2484         ASSERT(dpa->dpa_zio != NULL);
2485         (void) arc_read(dpa->dpa_zio, dpa->dpa_spa, bp, NULL, NULL,
2486             dpa->dpa_prio, ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2487             &aflags, &dpa->dpa_zb);
2488 }
2489 
2490 /*
2491  * Called when an indirect block above our prefetch target is read in.  This
2492  * will either read in the next indirect block down the tree or issue the actual
2493  * prefetch if the next block down is our target.
2494  */
2495 static void
2496 dbuf_prefetch_indirect_done(zio_t *zio, arc_buf_t *abuf, void *private)
2497 {
2498         dbuf_prefetch_arg_t *dpa = private;
2499 
2500         ASSERT3S(dpa->dpa_zb.zb_level, <, dpa->dpa_curlevel);
2501         ASSERT3S(dpa->dpa_curlevel, >, 0);
2502 
2503         /*
2504          * The dpa_dnode is only valid if we are called with a NULL
2505          * zio. This indicates that the arc_read() returned without
2506          * first calling zio_read() to issue a physical read. Once
2507          * a physical read is made the dpa_dnode must be invalidated
2508          * as the locks guarding it may have been dropped. If the
2509          * dpa_dnode is still valid, then we want to add it to the dbuf
2510          * cache. To do so, we must hold the dbuf associated with the block
2511          * we just prefetched, read its contents so that we associate it
2512          * with an arc_buf_t, and then release it.
2513          */
2514         if (zio != NULL) {
2515                 ASSERT3S(BP_GET_LEVEL(zio->io_bp), ==, dpa->dpa_curlevel);
2516                 if (zio->io_flags & ZIO_FLAG_RAW) {
2517                         ASSERT3U(BP_GET_PSIZE(zio->io_bp), ==, zio->io_size);
2518                 } else {
2519                         ASSERT3U(BP_GET_LSIZE(zio->io_bp), ==, zio->io_size);
2520                 }
2521                 ASSERT3P(zio->io_spa, ==, dpa->dpa_spa);
2522 
2523                 dpa->dpa_dnode = NULL;
2524         } else if (dpa->dpa_dnode != NULL) {
2525                 uint64_t curblkid = dpa->dpa_zb.zb_blkid >>
2526                     (dpa->dpa_epbs * (dpa->dpa_curlevel -
2527                     dpa->dpa_zb.zb_level));
2528                 dmu_buf_impl_t *db = dbuf_hold_level(dpa->dpa_dnode,
2529                     dpa->dpa_curlevel, curblkid, FTAG);
2530                 (void) dbuf_read(db, NULL,
2531                     DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH | DB_RF_HAVESTRUCT);
2532                 dbuf_rele(db, FTAG);
2533         }
2534 
2535         dpa->dpa_curlevel--;
2536 
2537         uint64_t nextblkid = dpa->dpa_zb.zb_blkid >>
2538             (dpa->dpa_epbs * (dpa->dpa_curlevel - dpa->dpa_zb.zb_level));
2539         blkptr_t *bp = ((blkptr_t *)abuf->b_data) +
2540             P2PHASE(nextblkid, 1ULL << dpa->dpa_epbs);
2541         if (BP_IS_HOLE(bp) || (zio != NULL && zio->io_error != 0)) {
2542                 kmem_free(dpa, sizeof (*dpa));
2543         } else if (dpa->dpa_curlevel == dpa->dpa_zb.zb_level) {
2544                 ASSERT3U(nextblkid, ==, dpa->dpa_zb.zb_blkid);
2545                 dbuf_issue_final_prefetch(dpa, bp);
2546                 kmem_free(dpa, sizeof (*dpa));
2547         } else {
2548                 arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
2549                 zbookmark_phys_t zb;
2550 
2551                 /* flag if L2ARC eligible, l2arc_noprefetch then decides */
2552                 if (dpa->dpa_aflags & ARC_FLAG_L2CACHE)
2553                         iter_aflags |= ARC_FLAG_L2CACHE;
2554 
2555                 ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
2556 
2557                 SET_BOOKMARK(&zb, dpa->dpa_zb.zb_objset,
2558                     dpa->dpa_zb.zb_object, dpa->dpa_curlevel, nextblkid);
2559 
2560                 (void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
2561                     bp, dbuf_prefetch_indirect_done, dpa, dpa->dpa_prio,
2562                     ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2563                     &iter_aflags, &zb);
2564         }
2565 
2566         arc_buf_destroy(abuf, private);
2567 }
2568 
2569 /*
2570  * Issue prefetch reads for the given block on the given level.  If the indirect
2571  * blocks above that block are not in memory, we will read them in
2572  * asynchronously.  As a result, this call never blocks waiting for a read to
2573  * complete.
2574  */
2575 void
2576 dbuf_prefetch(dnode_t *dn, int64_t level, uint64_t blkid, zio_priority_t prio,
2577     arc_flags_t aflags)
2578 {
2579         blkptr_t bp;
2580         int epbs, nlevels, curlevel;
2581         uint64_t curblkid;
2582 
2583         ASSERT(blkid != DMU_BONUS_BLKID);
2584         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2585 
2586         if (blkid > dn->dn_maxblkid)
2587                 return;
2588 
2589         if (dnode_block_freed(dn, blkid))
2590                 return;
2591 
2592         /*
2593          * This dnode hasn't been written to disk yet, so there's nothing to
2594          * prefetch.
2595          */
2596         nlevels = dn->dn_phys->dn_nlevels;
2597         if (level >= nlevels || dn->dn_phys->dn_nblkptr == 0)
2598                 return;
2599 
2600         epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2601         if (dn->dn_phys->dn_maxblkid < blkid << (epbs * level))
2602                 return;
2603 
2604         dmu_buf_impl_t *db = dbuf_find(dn->dn_objset, dn->dn_object,
2605             level, blkid);
2606         if (db != NULL) {
2607                 mutex_exit(&db->db_mtx);
2608                 /*
2609                  * This dbuf already exists.  It is either CACHED, or
2610                  * (we assume) about to be read or filled.
2611                  */
2612                 return;
2613         }
2614 
2615         /*
2616          * Find the closest ancestor (indirect block) of the target block
2617          * that is present in the cache.  In this indirect block, we will
2618          * find the bp that is at curlevel, curblkid.
2619          */
2620         curlevel = level;
2621         curblkid = blkid;
2622         while (curlevel < nlevels - 1) {
2623                 int parent_level = curlevel + 1;
2624                 uint64_t parent_blkid = curblkid >> epbs;
2625                 dmu_buf_impl_t *db;
2626 
2627                 if (dbuf_hold_impl(dn, parent_level, parent_blkid,
2628                     FALSE, TRUE, FTAG, &db) == 0) {
2629                         blkptr_t *bpp = db->db_buf->b_data;
2630                         bp = bpp[P2PHASE(curblkid, 1 << epbs)];
2631                         dbuf_rele(db, FTAG);
2632                         break;
2633                 }
2634 
2635                 curlevel = parent_level;
2636                 curblkid = parent_blkid;
2637         }
2638 
2639         if (curlevel == nlevels - 1) {
2640                 /* No cached indirect blocks found. */
2641                 ASSERT3U(curblkid, <, dn->dn_phys->dn_nblkptr);
2642                 bp = dn->dn_phys->dn_blkptr[curblkid];
2643         }
2644         if (BP_IS_HOLE(&bp))
2645                 return;
2646 
2647         ASSERT3U(curlevel, ==, BP_GET_LEVEL(&bp));
2648 
2649         zio_t *pio = zio_root(dmu_objset_spa(dn->dn_objset), NULL, NULL,
2650             ZIO_FLAG_CANFAIL);
2651 
2652         dbuf_prefetch_arg_t *dpa = kmem_zalloc(sizeof (*dpa), KM_SLEEP);
2653         dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
2654         SET_BOOKMARK(&dpa->dpa_zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
2655             dn->dn_object, level, blkid);
2656         dpa->dpa_curlevel = curlevel;
2657         dpa->dpa_prio = prio;
2658         dpa->dpa_aflags = aflags;
2659         dpa->dpa_spa = dn->dn_objset->os_spa;
2660         dpa->dpa_dnode = dn;
2661         dpa->dpa_epbs = epbs;
2662         dpa->dpa_zio = pio;
2663 
2664         /* flag if L2ARC eligible, l2arc_noprefetch then decides */
2665         if (DNODE_LEVEL_IS_L2CACHEABLE(dn, level))
2666                 dpa->dpa_aflags |= ARC_FLAG_L2CACHE;
2667 
2668         /*
2669          * If we have the indirect just above us, no need to do the asynchronous
2670          * prefetch chain; we'll just run the last step ourselves.  If we're at
2671          * a higher level, though, we want to issue the prefetches for all the
2672          * indirect blocks asynchronously, so we can go on with whatever we were
2673          * doing.
2674          */
2675         if (curlevel == level) {
2676                 ASSERT3U(curblkid, ==, blkid);
2677                 dbuf_issue_final_prefetch(dpa, &bp);
2678                 kmem_free(dpa, sizeof (*dpa));
2679         } else {
2680                 arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
2681                 zbookmark_phys_t zb;
2682 
2683                 /* flag if L2ARC eligible, l2arc_noprefetch then decides */
2684                 if (DNODE_LEVEL_IS_L2CACHEABLE(dn, level))
2685                         iter_aflags |= ARC_FLAG_L2CACHE;
2686 
2687                 SET_BOOKMARK(&zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
2688                     dn->dn_object, curlevel, curblkid);
2689                 (void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
2690                     &bp, dbuf_prefetch_indirect_done, dpa, prio,
2691                     ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2692                     &iter_aflags, &zb);
2693         }
2694         /*
2695          * We use pio here instead of dpa_zio since it's possible that
2696          * dpa may have already been freed.
2697          */
2698         zio_nowait(pio);
2699 }
2700 
2701 /*
2702  * Returns with db_holds incremented, and db_mtx not held.
2703  * Note: dn_struct_rwlock must be held.
2704  */
2705 int
2706 dbuf_hold_impl(dnode_t *dn, uint8_t level, uint64_t blkid,
2707     boolean_t fail_sparse, boolean_t fail_uncached,
2708     void *tag, dmu_buf_impl_t **dbp)
2709 {
2710         dmu_buf_impl_t *db, *parent = NULL;
2711 
2712         ASSERT(blkid != DMU_BONUS_BLKID);
2713         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2714         ASSERT3U(dn->dn_nlevels, >, level);
2715 
2716         *dbp = NULL;
2717 top:
2718         /* dbuf_find() returns with db_mtx held */
2719         db = dbuf_find(dn->dn_objset, dn->dn_object, level, blkid);
2720 
2721         if (db == NULL) {
2722                 blkptr_t *bp = NULL;
2723                 int err;
2724 
2725                 if (fail_uncached)
2726                         return (SET_ERROR(ENOENT));
2727 
2728                 ASSERT3P(parent, ==, NULL);
2729                 err = dbuf_findbp(dn, level, blkid, fail_sparse, &parent, &bp);
2730                 if (fail_sparse) {
2731                         if (err == 0 && bp && BP_IS_HOLE(bp))
2732                                 err = SET_ERROR(ENOENT);
2733                         if (err) {
2734                                 if (parent)
2735                                         dbuf_rele(parent, NULL);
2736                                 return (err);
2737                         }
2738                 }
2739                 if (err && err != ENOENT)
2740                         return (err);
2741                 db = dbuf_create(dn, level, blkid, parent, bp);
2742         }
2743 
2744         if (fail_uncached && db->db_state != DB_CACHED) {
2745                 mutex_exit(&db->db_mtx);
2746                 return (SET_ERROR(ENOENT));
2747         }
2748 
2749         if (db->db_buf != NULL) {
2750                 arc_buf_access(db->db_buf);
2751                 ASSERT3P(db->db.db_data, ==, db->db_buf->b_data);
2752         }
2753 
2754         ASSERT(db->db_buf == NULL || arc_referenced(db->db_buf));
2755 
2756         /*
2757          * If this buffer is currently syncing out, and we are are
2758          * still referencing it from db_data, we need to make a copy
2759          * of it in case we decide we want to dirty it again in this txg.
2760          */
2761         if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
2762             dn->dn_object != DMU_META_DNODE_OBJECT &&
2763             db->db_state == DB_CACHED && db->db_data_pending) {
2764                 dbuf_dirty_record_t *dr = db->db_data_pending;
2765 
2766                 if (dr->dt.dl.dr_data == db->db_buf) {
2767                         arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
2768 
2769                         dbuf_set_data(db,
2770                             arc_alloc_buf(dn->dn_objset->os_spa, db, type,
2771                             db->db.db_size));
2772                         bcopy(dr->dt.dl.dr_data->b_data, db->db.db_data,
2773                             db->db.db_size);
2774                 }
2775         }
2776 
2777         if (multilist_link_active(&db->db_cache_link)) {
2778                 ASSERT(refcount_is_zero(&db->db_holds));
2779                 ASSERT(db->db_caching_status == DB_DBUF_CACHE ||
2780                     db->db_caching_status == DB_DBUF_METADATA_CACHE);
2781 
2782                 multilist_remove(dbuf_caches[db->db_caching_status].cache, db);
2783                 (void) refcount_remove_many(
2784                     &dbuf_caches[db->db_caching_status].size,
2785                     db->db.db_size, db);
2786 
2787                 db->db_caching_status = DB_NO_CACHE;
2788         }
2789         (void) refcount_add(&db->db_holds, tag);
2790         DBUF_VERIFY(db);
2791         mutex_exit(&db->db_mtx);
2792 
2793         /* NOTE: we can't rele the parent until after we drop the db_mtx */
2794         if (parent)
2795                 dbuf_rele(parent, NULL);
2796 
2797         ASSERT3P(DB_DNODE(db), ==, dn);
2798         ASSERT3U(db->db_blkid, ==, blkid);
2799         ASSERT3U(db->db_level, ==, level);
2800         *dbp = db;
2801 
2802         return (0);
2803 }
2804 
2805 dmu_buf_impl_t *
2806 dbuf_hold(dnode_t *dn, uint64_t blkid, void *tag)
2807 {
2808         return (dbuf_hold_level(dn, 0, blkid, tag));
2809 }
2810 
2811 dmu_buf_impl_t *
2812 dbuf_hold_level(dnode_t *dn, int level, uint64_t blkid, void *tag)
2813 {
2814         dmu_buf_impl_t *db;
2815         int err = dbuf_hold_impl(dn, level, blkid, FALSE, FALSE, tag, &db);
2816         return (err ? NULL : db);
2817 }
2818 
2819 void
2820 dbuf_create_bonus(dnode_t *dn)
2821 {
2822         ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
2823 
2824         ASSERT(dn->dn_bonus == NULL);
2825         dn->dn_bonus = dbuf_create(dn, 0, DMU_BONUS_BLKID, dn->dn_dbuf, NULL);
2826 }
2827 
2828 int
2829 dbuf_spill_set_blksz(dmu_buf_t *db_fake, uint64_t blksz, dmu_tx_t *tx)
2830 {
2831         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2832         dnode_t *dn;
2833 
2834         if (db->db_blkid != DMU_SPILL_BLKID)
2835                 return (SET_ERROR(ENOTSUP));
2836         if (blksz == 0)
2837                 blksz = SPA_MINBLOCKSIZE;
2838         ASSERT3U(blksz, <=, spa_maxblocksize(dmu_objset_spa(db->db_objset)));
2839         blksz = P2ROUNDUP(blksz, SPA_MINBLOCKSIZE);
2840 
2841         DB_DNODE_ENTER(db);
2842         dn = DB_DNODE(db);
2843         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
2844         dbuf_new_size(db, blksz, tx);
2845         rw_exit(&dn->dn_struct_rwlock);
2846         DB_DNODE_EXIT(db);
2847 
2848         return (0);
2849 }
2850 
2851 void
2852 dbuf_rm_spill(dnode_t *dn, dmu_tx_t *tx)
2853 {
2854         dbuf_free_range(dn, DMU_SPILL_BLKID, DMU_SPILL_BLKID, tx);
2855 }
2856 
2857 #pragma weak dmu_buf_add_ref = dbuf_add_ref
2858 void
2859 dbuf_add_ref(dmu_buf_impl_t *db, void *tag)
2860 {
2861         int64_t holds = refcount_add(&db->db_holds, tag);
2862         ASSERT3S(holds, >, 1);
2863 }
2864 
2865 #pragma weak dmu_buf_try_add_ref = dbuf_try_add_ref
2866 boolean_t
2867 dbuf_try_add_ref(dmu_buf_t *db_fake, objset_t *os, uint64_t obj, uint64_t blkid,
2868     void *tag)
2869 {
2870         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2871         dmu_buf_impl_t *found_db;
2872         boolean_t result = B_FALSE;
2873 
2874         if (db->db_blkid == DMU_BONUS_BLKID)
2875                 found_db = dbuf_find_bonus(os, obj);
2876         else
2877                 found_db = dbuf_find(os, obj, 0, blkid);
2878 
2879         if (found_db != NULL) {
2880                 if (db == found_db && dbuf_refcount(db) > db->db_dirtycnt) {
2881                         (void) refcount_add(&db->db_holds, tag);
2882                         result = B_TRUE;
2883                 }
2884                 mutex_exit(&db->db_mtx);
2885         }
2886         return (result);
2887 }
2888 
2889 /*
2890  * If you call dbuf_rele() you had better not be referencing the dnode handle
2891  * unless you have some other direct or indirect hold on the dnode. (An indirect
2892  * hold is a hold on one of the dnode's dbufs, including the bonus buffer.)
2893  * Without that, the dbuf_rele() could lead to a dnode_rele() followed by the
2894  * dnode's parent dbuf evicting its dnode handles.
2895  */
2896 void
2897 dbuf_rele(dmu_buf_impl_t *db, void *tag)
2898 {
2899         mutex_enter(&db->db_mtx);
2900         dbuf_rele_and_unlock(db, tag);
2901 }
2902 
2903 void
2904 dmu_buf_rele(dmu_buf_t *db, void *tag)
2905 {
2906         dbuf_rele((dmu_buf_impl_t *)db, tag);
2907 }
2908 
2909 /*
2910  * dbuf_rele() for an already-locked dbuf.  This is necessary to allow
2911  * db_dirtycnt and db_holds to be updated atomically.
2912  */
2913 void
2914 dbuf_rele_and_unlock(dmu_buf_impl_t *db, void *tag)
2915 {
2916         int64_t holds;
2917 
2918         ASSERT(MUTEX_HELD(&db->db_mtx));
2919         DBUF_VERIFY(db);
2920 
2921         /*
2922          * Remove the reference to the dbuf before removing its hold on the
2923          * dnode so we can guarantee in dnode_move() that a referenced bonus
2924          * buffer has a corresponding dnode hold.
2925          */
2926         holds = refcount_remove(&db->db_holds, tag);
2927         ASSERT(holds >= 0);
2928 
2929         /*
2930          * We can't freeze indirects if there is a possibility that they
2931          * may be modified in the current syncing context.
2932          */
2933         if (db->db_buf != NULL &&
2934             holds == (db->db_level == 0 ? db->db_dirtycnt : 0)) {
2935                 arc_buf_freeze(db->db_buf);
2936         }
2937 
2938         if (holds == db->db_dirtycnt &&
2939             db->db_level == 0 && db->db_user_immediate_evict)
2940                 dbuf_evict_user(db);
2941 
2942         if (holds == 0) {
2943                 if (db->db_blkid == DMU_BONUS_BLKID) {
2944                         dnode_t *dn;
2945                         boolean_t evict_dbuf = db->db_pending_evict;
2946 
2947                         /*
2948                          * If the dnode moves here, we cannot cross this
2949                          * barrier until the move completes.
2950                          */
2951                         DB_DNODE_ENTER(db);
2952 
2953                         dn = DB_DNODE(db);
2954                         atomic_dec_32(&dn->dn_dbufs_count);
2955 
2956                         /*
2957                          * Decrementing the dbuf count means that the bonus
2958                          * buffer's dnode hold is no longer discounted in
2959                          * dnode_move(). The dnode cannot move until after
2960                          * the dnode_rele() below.
2961                          */
2962                         DB_DNODE_EXIT(db);
2963 
2964                         /*
2965                          * Do not reference db after its lock is dropped.
2966                          * Another thread may evict it.
2967                          */
2968                         mutex_exit(&db->db_mtx);
2969 
2970                         if (evict_dbuf)
2971                                 dnode_evict_bonus(dn);
2972 
2973                         dnode_rele(dn, db);
2974                 } else if (db->db_buf == NULL) {
2975                         /*
2976                          * This is a special case: we never associated this
2977                          * dbuf with any data allocated from the ARC.
2978                          */
2979                         ASSERT(db->db_state == DB_UNCACHED ||
2980                             db->db_state == DB_NOFILL);
2981                         dbuf_destroy(db);
2982                 } else if (arc_released(db->db_buf)) {
2983                         /*
2984                          * This dbuf has anonymous data associated with it.
2985                          */
2986                         dbuf_destroy(db);
2987                 } else {
2988                         boolean_t do_arc_evict = B_FALSE;
2989                         blkptr_t bp;
2990                         spa_t *spa = dmu_objset_spa(db->db_objset);
2991 
2992                         if (!DBUF_IS_CACHEABLE(db) &&
2993                             db->db_blkptr != NULL &&
2994                             !BP_IS_HOLE(db->db_blkptr) &&
2995                             !BP_IS_EMBEDDED(db->db_blkptr)) {
2996                                 do_arc_evict = B_TRUE;
2997                                 bp = *db->db_blkptr;
2998                         }
2999 
3000                         if (!DBUF_IS_CACHEABLE(db) ||
3001                             db->db_pending_evict) {
3002                                 dbuf_destroy(db);
3003                         } else if (!multilist_link_active(&db->db_cache_link)) {
3004                                 ASSERT3U(db->db_caching_status, ==,
3005                                     DB_NO_CACHE);
3006 
3007                                 dbuf_cached_state_t dcs =
3008                                     dbuf_include_in_metadata_cache(db) ?
3009                                     DB_DBUF_METADATA_CACHE : DB_DBUF_CACHE;
3010                                 db->db_caching_status = dcs;
3011 
3012                                 multilist_insert(dbuf_caches[dcs].cache, db);
3013                                 (void) refcount_add_many(&dbuf_caches[dcs].size,
3014                                     db->db.db_size, db);
3015                                 mutex_exit(&db->db_mtx);
3016 
3017                                 if (db->db_caching_status == DB_DBUF_CACHE) {
3018                                         dbuf_evict_notify();
3019                                 }
3020                         }
3021 
3022                         if (do_arc_evict)
3023                                 arc_freed(spa, &bp);
3024                 }
3025         } else {
3026                 mutex_exit(&db->db_mtx);
3027         }
3028 
3029 }
3030 
3031 #pragma weak dmu_buf_refcount = dbuf_refcount
3032 uint64_t
3033 dbuf_refcount(dmu_buf_impl_t *db)
3034 {
3035         return (refcount_count(&db->db_holds));
3036 }
3037 
3038 void *
3039 dmu_buf_replace_user(dmu_buf_t *db_fake, dmu_buf_user_t *old_user,
3040     dmu_buf_user_t *new_user)
3041 {
3042         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3043 
3044         mutex_enter(&db->db_mtx);
3045         dbuf_verify_user(db, DBVU_NOT_EVICTING);
3046         if (db->db_user == old_user)
3047                 db->db_user = new_user;
3048         else
3049                 old_user = db->db_user;
3050         dbuf_verify_user(db, DBVU_NOT_EVICTING);
3051         mutex_exit(&db->db_mtx);
3052 
3053         return (old_user);
3054 }
3055 
3056 void *
3057 dmu_buf_set_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
3058 {
3059         return (dmu_buf_replace_user(db_fake, NULL, user));
3060 }
3061 
3062 void *
3063 dmu_buf_set_user_ie(dmu_buf_t *db_fake, dmu_buf_user_t *user)
3064 {
3065         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3066 
3067         db->db_user_immediate_evict = TRUE;
3068         return (dmu_buf_set_user(db_fake, user));
3069 }
3070 
3071 void *
3072 dmu_buf_remove_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
3073 {
3074         return (dmu_buf_replace_user(db_fake, user, NULL));
3075 }
3076 
3077 void *
3078 dmu_buf_get_user(dmu_buf_t *db_fake)
3079 {
3080         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3081 
3082         dbuf_verify_user(db, DBVU_NOT_EVICTING);
3083         return (db->db_user);
3084 }
3085 
3086 void
3087 dmu_buf_user_evict_wait()
3088 {
3089         taskq_wait(dbu_evict_taskq);
3090 }
3091 
3092 blkptr_t *
3093 dmu_buf_get_blkptr(dmu_buf_t *db)
3094 {
3095         dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3096         return (dbi->db_blkptr);
3097 }
3098 
3099 objset_t *
3100 dmu_buf_get_objset(dmu_buf_t *db)
3101 {
3102         dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3103         return (dbi->db_objset);
3104 }
3105 
3106 dnode_t *
3107 dmu_buf_dnode_enter(dmu_buf_t *db)
3108 {
3109         dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3110         DB_DNODE_ENTER(dbi);
3111         return (DB_DNODE(dbi));
3112 }
3113 
3114 void
3115 dmu_buf_dnode_exit(dmu_buf_t *db)
3116 {
3117         dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3118         DB_DNODE_EXIT(dbi);
3119 }
3120 
3121 static void
3122 dbuf_check_blkptr(dnode_t *dn, dmu_buf_impl_t *db)
3123 {
3124         /* ASSERT(dmu_tx_is_syncing(tx) */
3125         ASSERT(MUTEX_HELD(&db->db_mtx));
3126 
3127         if (db->db_blkptr != NULL)
3128                 return;
3129 
3130         if (db->db_blkid == DMU_SPILL_BLKID) {
3131                 db->db_blkptr = &dn->dn_phys->dn_spill;
3132                 BP_ZERO(db->db_blkptr);
3133                 return;
3134         }
3135         if (db->db_level == dn->dn_phys->dn_nlevels-1) {
3136                 /*
3137                  * This buffer was allocated at a time when there was
3138                  * no available blkptrs from the dnode, or it was
3139                  * inappropriate to hook it in (i.e., nlevels mis-match).
3140                  */
3141                 ASSERT(db->db_blkid < dn->dn_phys->dn_nblkptr);
3142                 ASSERT(db->db_parent == NULL);
3143                 db->db_parent = dn->dn_dbuf;
3144                 db->db_blkptr = &dn->dn_phys->dn_blkptr[db->db_blkid];
3145                 DBUF_VERIFY(db);
3146         } else {
3147                 dmu_buf_impl_t *parent = db->db_parent;
3148                 int epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3149 
3150                 ASSERT(dn->dn_phys->dn_nlevels > 1);
3151                 if (parent == NULL) {
3152                         mutex_exit(&db->db_mtx);
3153                         rw_enter(&dn->dn_struct_rwlock, RW_READER);
3154                         parent = dbuf_hold_level(dn, db->db_level + 1,
3155                             db->db_blkid >> epbs, db);
3156                         rw_exit(&dn->dn_struct_rwlock);
3157                         mutex_enter(&db->db_mtx);
3158                         db->db_parent = parent;
3159                 }
3160                 db->db_blkptr = (blkptr_t *)parent->db.db_data +
3161                     (db->db_blkid & ((1ULL << epbs) - 1));
3162                 DBUF_VERIFY(db);
3163         }
3164 }
3165 
3166 static void
3167 dbuf_sync_indirect(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
3168 {
3169         dmu_buf_impl_t *db = dr->dr_dbuf;
3170         dnode_t *dn;
3171         zio_t *zio;
3172 
3173         ASSERT(dmu_tx_is_syncing(tx));
3174 
3175         dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
3176 
3177         mutex_enter(&db->db_mtx);
3178 
3179         ASSERT(db->db_level > 0);
3180         DBUF_VERIFY(db);
3181 
3182         /* Read the block if it hasn't been read yet. */
3183         if (db->db_buf == NULL) {
3184                 mutex_exit(&db->db_mtx);
3185                 (void) dbuf_read(db, NULL, DB_RF_MUST_SUCCEED);
3186                 mutex_enter(&db->db_mtx);
3187         }
3188         ASSERT3U(db->db_state, ==, DB_CACHED);
3189         ASSERT(db->db_buf != NULL);
3190 
3191         DB_DNODE_ENTER(db);
3192         dn = DB_DNODE(db);
3193         /* Indirect block size must match what the dnode thinks it is. */
3194         ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
3195         dbuf_check_blkptr(dn, db);
3196         DB_DNODE_EXIT(db);
3197 
3198         /* Provide the pending dirty record to child dbufs */
3199         db->db_data_pending = dr;
3200 
3201         mutex_exit(&db->db_mtx);
3202         dbuf_write(dr, db->db_buf, tx);
3203 
3204         zio = dr->dr_zio;
3205         mutex_enter(&dr->dt.di.dr_mtx);
3206         dbuf_sync_list(&dr->dt.di.dr_children, db->db_level - 1, tx);
3207         ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
3208         mutex_exit(&dr->dt.di.dr_mtx);
3209         zio_nowait(zio);
3210 }
3211 
3212 static void
3213 dbuf_sync_leaf(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
3214 {
3215         arc_buf_t **datap = &dr->dt.dl.dr_data;
3216         dmu_buf_impl_t *db = dr->dr_dbuf;
3217         dnode_t *dn;
3218         objset_t *os;
3219         uint64_t txg = tx->tx_txg;
3220 
3221         ASSERT(dmu_tx_is_syncing(tx));
3222 
3223         dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
3224 
3225         mutex_enter(&db->db_mtx);
3226         /*
3227          * To be synced, we must be dirtied.  But we
3228          * might have been freed after the dirty.
3229          */
3230         if (db->db_state == DB_UNCACHED) {
3231                 /* This buffer has been freed since it was dirtied */
3232                 ASSERT(db->db.db_data == NULL);
3233         } else if (db->db_state == DB_FILL) {
3234                 /* This buffer was freed and is now being re-filled */
3235                 ASSERT(db->db.db_data != dr->dt.dl.dr_data);
3236         } else {
3237                 ASSERT(db->db_state == DB_CACHED || db->db_state == DB_NOFILL);
3238         }
3239         DBUF_VERIFY(db);
3240 
3241         DB_DNODE_ENTER(db);
3242         dn = DB_DNODE(db);
3243 
3244         if (db->db_blkid == DMU_SPILL_BLKID) {
3245                 mutex_enter(&dn->dn_mtx);
3246                 dn->dn_phys->dn_flags |= DNODE_FLAG_SPILL_BLKPTR;
3247                 mutex_exit(&dn->dn_mtx);
3248         }
3249 
3250         /*
3251          * If this is a bonus buffer, simply copy the bonus data into the
3252          * dnode.  It will be written out when the dnode is synced (and it
3253          * will be synced, since it must have been dirty for dbuf_sync to
3254          * be called).
3255          */
3256         if (db->db_blkid == DMU_BONUS_BLKID) {
3257                 dbuf_dirty_record_t **drp;
3258 
3259                 ASSERT(*datap != NULL);
3260                 ASSERT0(db->db_level);
3261                 ASSERT3U(dn->dn_phys->dn_bonuslen, <=, DN_MAX_BONUSLEN);
3262                 bcopy(*datap, DN_BONUS(dn->dn_phys), dn->dn_phys->dn_bonuslen);
3263                 DB_DNODE_EXIT(db);
3264 
3265                 if (*datap != db->db.db_data) {
3266                         zio_buf_free(*datap, DN_MAX_BONUSLEN);
3267                         arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
3268                 }
3269                 db->db_data_pending = NULL;
3270                 drp = &db->db_last_dirty;
3271                 while (*drp != dr)
3272                         drp = &(*drp)->dr_next;
3273                 ASSERT(dr->dr_next == NULL);
3274                 ASSERT(dr->dr_dbuf == db);
3275                 *drp = dr->dr_next;
3276                 kmem_free(dr, sizeof (dbuf_dirty_record_t));
3277                 ASSERT(db->db_dirtycnt > 0);
3278                 db->db_dirtycnt -= 1;
3279                 dbuf_rele_and_unlock(db, (void *)(uintptr_t)txg);
3280                 return;
3281         }
3282 
3283         os = dn->dn_objset;
3284 
3285         /*
3286          * This function may have dropped the db_mtx lock allowing a dmu_sync
3287          * operation to sneak in. As a result, we need to ensure that we
3288          * don't check the dr_override_state until we have returned from
3289          * dbuf_check_blkptr.
3290          */
3291         dbuf_check_blkptr(dn, db);
3292 
3293         /*
3294          * If this buffer is in the middle of an immediate write,
3295          * wait for the synchronous IO to complete.
3296          */
3297         while (dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC) {
3298                 ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
3299                 cv_wait(&db->db_changed, &db->db_mtx);
3300                 ASSERT(dr->dt.dl.dr_override_state != DR_NOT_OVERRIDDEN);
3301         }
3302 
3303         if (db->db_state != DB_NOFILL &&
3304             dn->dn_object != DMU_META_DNODE_OBJECT &&
3305             refcount_count(&db->db_holds) > 1 &&
3306             dr->dt.dl.dr_override_state != DR_OVERRIDDEN &&
3307             *datap == db->db_buf) {
3308                 /*
3309                  * If this buffer is currently "in use" (i.e., there
3310                  * are active holds and db_data still references it),
3311                  * then make a copy before we start the write so that
3312                  * any modifications from the open txg will not leak
3313                  * into this write.
3314                  *
3315                  * NOTE: this copy does not need to be made for
3316                  * objects only modified in the syncing context (e.g.
3317                  * DNONE_DNODE blocks).
3318                  */
3319                 int psize = arc_buf_size(*datap);
3320                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
3321                 enum zio_compress compress_type = arc_get_compression(*datap);
3322 
3323                 if (compress_type == ZIO_COMPRESS_OFF) {
3324                         *datap = arc_alloc_buf(os->os_spa, db, type, psize);
3325                 } else {
3326                         ASSERT3U(type, ==, ARC_BUFC_DATA);
3327                         int lsize = arc_buf_lsize(*datap);
3328                         *datap = arc_alloc_compressed_buf(os->os_spa, db,
3329                             psize, lsize, compress_type);
3330                 }
3331                 bcopy(db->db.db_data, (*datap)->b_data, psize);
3332         }
3333         db->db_data_pending = dr;
3334 
3335         mutex_exit(&db->db_mtx);
3336 
3337         dbuf_write(dr, *datap, tx);
3338 
3339         ASSERT(!list_link_active(&dr->dr_dirty_node));
3340         if (dn->dn_object == DMU_META_DNODE_OBJECT) {
3341                 list_insert_tail(&dn->dn_dirty_records[txg&TXG_MASK], dr);
3342                 DB_DNODE_EXIT(db);
3343         } else {
3344                 /*
3345                  * Although zio_nowait() does not "wait for an IO", it does
3346                  * initiate the IO. If this is an empty write it seems plausible
3347                  * that the IO could actually be completed before the nowait
3348                  * returns. We need to DB_DNODE_EXIT() first in case
3349                  * zio_nowait() invalidates the dbuf.
3350                  */
3351                 DB_DNODE_EXIT(db);
3352                 zio_nowait(dr->dr_zio);
3353         }
3354 }
3355 
3356 void
3357 dbuf_sync_list(list_t *list, int level, dmu_tx_t *tx)
3358 {
3359         dbuf_dirty_record_t *dr;
3360 
3361         while (dr = list_head(list)) {
3362                 if (dr->dr_zio != NULL) {
3363                         /*
3364                          * If we find an already initialized zio then we
3365                          * are processing the meta-dnode, and we have finished.
3366                          * The dbufs for all dnodes are put back on the list
3367                          * during processing, so that we can zio_wait()
3368                          * these IOs after initiating all child IOs.
3369                          */
3370                         ASSERT3U(dr->dr_dbuf->db.db_object, ==,
3371                             DMU_META_DNODE_OBJECT);
3372                         break;
3373                 }
3374                 if (dr->dr_dbuf->db_blkid != DMU_BONUS_BLKID &&
3375                     dr->dr_dbuf->db_blkid != DMU_SPILL_BLKID) {
3376                         VERIFY3U(dr->dr_dbuf->db_level, ==, level);
3377                 }
3378                 list_remove(list, dr);
3379                 if (dr->dr_dbuf->db_level > 0)
3380                         dbuf_sync_indirect(dr, tx);
3381                 else
3382                         dbuf_sync_leaf(dr, tx);
3383         }
3384 }
3385 
3386 /* ARGSUSED */
3387 static void
3388 dbuf_write_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
3389 {
3390         dmu_buf_impl_t *db = vdb;
3391         dnode_t *dn;
3392         blkptr_t *bp = zio->io_bp;
3393         blkptr_t *bp_orig = &zio->io_bp_orig;
3394         spa_t *spa = zio->io_spa;
3395         int64_t delta;
3396         uint64_t fill = 0;
3397         int i;
3398 
3399         ASSERT3P(db->db_blkptr, !=, NULL);
3400         ASSERT3P(&db->db_data_pending->dr_bp_copy, ==, bp);
3401 
3402         DB_DNODE_ENTER(db);
3403         dn = DB_DNODE(db);
3404         delta = bp_get_dsize_sync(spa, bp) - bp_get_dsize_sync(spa, bp_orig);
3405         dnode_diduse_space(dn, delta - zio->io_prev_space_delta);
3406         zio->io_prev_space_delta = delta;
3407 
3408         if (bp->blk_birth != 0) {
3409                 ASSERT((db->db_blkid != DMU_SPILL_BLKID &&
3410                     BP_GET_TYPE(bp) == dn->dn_type) ||
3411                     (db->db_blkid == DMU_SPILL_BLKID &&
3412                     BP_GET_TYPE(bp) == dn->dn_bonustype) ||
3413                     BP_IS_EMBEDDED(bp));
3414                 ASSERT(BP_GET_LEVEL(bp) == db->db_level);
3415         }
3416 
3417         mutex_enter(&db->db_mtx);
3418 
3419 #ifdef ZFS_DEBUG
3420         if (db->db_blkid == DMU_SPILL_BLKID) {
3421                 ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
3422                 ASSERT(!(BP_IS_HOLE(bp)) &&
3423                     db->db_blkptr == &dn->dn_phys->dn_spill);
3424         }
3425 #endif
3426 
3427         if (db->db_level == 0) {
3428                 mutex_enter(&dn->dn_mtx);
3429                 if (db->db_blkid > dn->dn_phys->dn_maxblkid &&
3430                     db->db_blkid != DMU_SPILL_BLKID)
3431                         dn->dn_phys->dn_maxblkid = db->db_blkid;
3432                 mutex_exit(&dn->dn_mtx);
3433 
3434                 if (dn->dn_type == DMU_OT_DNODE) {
3435                         dnode_phys_t *dnp = db->db.db_data;
3436                         for (i = db->db.db_size >> DNODE_SHIFT; i > 0;
3437                             i--, dnp++) {
3438                                 if (dnp->dn_type != DMU_OT_NONE)
3439                                         fill++;
3440                         }
3441                 } else {
3442                         if (BP_IS_HOLE(bp)) {
3443                                 fill = 0;
3444                         } else {
3445                                 fill = 1;
3446                         }
3447                 }
3448         } else {
3449                 blkptr_t *ibp = db->db.db_data;
3450                 ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
3451                 for (i = db->db.db_size >> SPA_BLKPTRSHIFT; i > 0; i--, ibp++) {
3452                         if (BP_IS_HOLE(ibp))
3453                                 continue;
3454                         fill += BP_GET_FILL(ibp);
3455                 }
3456         }
3457         DB_DNODE_EXIT(db);
3458 
3459         if (!BP_IS_EMBEDDED(bp))
3460                 bp->blk_fill = fill;
3461 
3462         mutex_exit(&db->db_mtx);
3463 
3464         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
3465         *db->db_blkptr = *bp;
3466         rw_exit(&dn->dn_struct_rwlock);
3467 }
3468 
3469 /* ARGSUSED */
3470 /*
3471  * This function gets called just prior to running through the compression
3472  * stage of the zio pipeline. If we're an indirect block comprised of only
3473  * holes, then we want this indirect to be compressed away to a hole. In
3474  * order to do that we must zero out any information about the holes that
3475  * this indirect points to prior to before we try to compress it.
3476  */
3477 static void
3478 dbuf_write_children_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
3479 {
3480         dmu_buf_impl_t *db = vdb;
3481         dnode_t *dn;
3482         blkptr_t *bp;
3483         unsigned int epbs, i;
3484 
3485         ASSERT3U(db->db_level, >, 0);
3486         DB_DNODE_ENTER(db);
3487         dn = DB_DNODE(db);
3488         epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3489         ASSERT3U(epbs, <, 31);
3490 
3491         /* Determine if all our children are holes */
3492         for (i = 0, bp = db->db.db_data; i < 1 << epbs; i++, bp++) {
3493                 if (!BP_IS_HOLE(bp))
3494                         break;
3495         }
3496 
3497         /*
3498          * If all the children are holes, then zero them all out so that
3499          * we may get compressed away.
3500          */
3501         if (i == 1 << epbs) {
3502                 /*
3503                  * We only found holes. Grab the rwlock to prevent
3504                  * anybody from reading the blocks we're about to
3505                  * zero out.
3506                  */
3507                 rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
3508                 bzero(db->db.db_data, db->db.db_size);
3509                 rw_exit(&dn->dn_struct_rwlock);
3510         }
3511         DB_DNODE_EXIT(db);
3512 }
3513 
3514 /*
3515  * The SPA will call this callback several times for each zio - once
3516  * for every physical child i/o (zio->io_phys_children times).  This
3517  * allows the DMU to monitor the progress of each logical i/o.  For example,
3518  * there may be 2 copies of an indirect block, or many fragments of a RAID-Z
3519  * block.  There may be a long delay before all copies/fragments are completed,
3520  * so this callback allows us to retire dirty space gradually, as the physical
3521  * i/os complete.
3522  */
3523 /* ARGSUSED */
3524 static void
3525 dbuf_write_physdone(zio_t *zio, arc_buf_t *buf, void *arg)
3526 {
3527         dmu_buf_impl_t *db = arg;
3528         objset_t *os = db->db_objset;
3529         dsl_pool_t *dp = dmu_objset_pool(os);
3530         dbuf_dirty_record_t *dr;
3531         int delta = 0;
3532 
3533         dr = db->db_data_pending;
3534         ASSERT3U(dr->dr_txg, ==, zio->io_txg);
3535 
3536         /*
3537          * The callback will be called io_phys_children times.  Retire one
3538          * portion of our dirty space each time we are called.  Any rounding
3539          * error will be cleaned up by dsl_pool_sync()'s call to
3540          * dsl_pool_undirty_space().
3541          */
3542         delta = dr->dr_accounted / zio->io_phys_children;
3543         dsl_pool_undirty_space(dp, delta, zio->io_txg);
3544 }
3545 
3546 /* ARGSUSED */
3547 static void
3548 dbuf_write_done(zio_t *zio, arc_buf_t *buf, void *vdb)
3549 {
3550         dmu_buf_impl_t *db = vdb;
3551         blkptr_t *bp_orig = &zio->io_bp_orig;
3552         blkptr_t *bp = db->db_blkptr;
3553         objset_t *os = db->db_objset;
3554         dmu_tx_t *tx = os->os_synctx;
3555         dbuf_dirty_record_t **drp, *dr;
3556 
3557         ASSERT0(zio->io_error);
3558         ASSERT(db->db_blkptr == bp);
3559 
3560         /*
3561          * For nopwrites and rewrites we ensure that the bp matches our
3562          * original and bypass all the accounting.
3563          */
3564         if (zio->io_flags & (ZIO_FLAG_IO_REWRITE | ZIO_FLAG_NOPWRITE)) {
3565                 ASSERT(BP_EQUAL(bp, bp_orig));
3566         } else {
3567                 dsl_dataset_t *ds = os->os_dsl_dataset;
3568                 (void) dsl_dataset_block_kill(ds, bp_orig, tx, B_TRUE);
3569                 dsl_dataset_block_born(ds, bp, tx);
3570         }
3571 
3572         mutex_enter(&db->db_mtx);
3573 
3574         DBUF_VERIFY(db);
3575 
3576         drp = &db->db_last_dirty;
3577         while ((dr = *drp) != db->db_data_pending)
3578                 drp = &dr->dr_next;
3579         ASSERT(!list_link_active(&dr->dr_dirty_node));
3580         ASSERT(dr->dr_dbuf == db);
3581         ASSERT(dr->dr_next == NULL);
3582         *drp = dr->dr_next;
3583 
3584 #ifdef ZFS_DEBUG
3585         if (db->db_blkid == DMU_SPILL_BLKID) {
3586                 dnode_t *dn;
3587 
3588                 DB_DNODE_ENTER(db);
3589                 dn = DB_DNODE(db);
3590                 ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
3591                 ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
3592                     db->db_blkptr == &dn->dn_phys->dn_spill);
3593                 DB_DNODE_EXIT(db);
3594         }
3595 #endif
3596 
3597         if (db->db_level == 0) {
3598                 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
3599                 ASSERT(dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN);
3600                 if (db->db_state != DB_NOFILL) {
3601                         if (dr->dt.dl.dr_data != db->db_buf)
3602                                 arc_buf_destroy(dr->dt.dl.dr_data, db);
3603                 }
3604         } else {
3605                 dnode_t *dn;
3606 
3607                 DB_DNODE_ENTER(db);
3608                 dn = DB_DNODE(db);
3609                 ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
3610                 ASSERT3U(db->db.db_size, ==, 1 << dn->dn_phys->dn_indblkshift);
3611                 if (!BP_IS_HOLE(db->db_blkptr)) {
3612                         int epbs =
3613                             dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3614                         ASSERT3U(db->db_blkid, <=,
3615                             dn->dn_phys->dn_maxblkid >> (db->db_level * epbs));
3616                         ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
3617                             db->db.db_size);
3618                 }
3619                 DB_DNODE_EXIT(db);
3620                 mutex_destroy(&dr->dt.di.dr_mtx);
3621                 list_destroy(&dr->dt.di.dr_children);
3622         }
3623         kmem_free(dr, sizeof (dbuf_dirty_record_t));
3624 
3625         cv_broadcast(&db->db_changed);
3626         ASSERT(db->db_dirtycnt > 0);
3627         db->db_dirtycnt -= 1;
3628         db->db_data_pending = NULL;
3629         dbuf_rele_and_unlock(db, (void *)(uintptr_t)tx->tx_txg);
3630 }
3631 
3632 static void
3633 dbuf_write_nofill_ready(zio_t *zio)
3634 {
3635         dbuf_write_ready(zio, NULL, zio->io_private);
3636 }
3637 
3638 static void
3639 dbuf_write_nofill_done(zio_t *zio)
3640 {
3641         dbuf_write_done(zio, NULL, zio->io_private);
3642 }
3643 
3644 static void
3645 dbuf_write_override_ready(zio_t *zio)
3646 {
3647         dbuf_dirty_record_t *dr = zio->io_private;
3648         dmu_buf_impl_t *db = dr->dr_dbuf;
3649 
3650         dbuf_write_ready(zio, NULL, db);
3651 }
3652 
3653 static void
3654 dbuf_write_override_done(zio_t *zio)
3655 {
3656         dbuf_dirty_record_t *dr = zio->io_private;
3657         dmu_buf_impl_t *db = dr->dr_dbuf;
3658         blkptr_t *obp = &dr->dt.dl.dr_overridden_by;
3659 
3660         mutex_enter(&db->db_mtx);
3661         if (!BP_EQUAL(zio->io_bp, obp)) {
3662                 if (!BP_IS_HOLE(obp))
3663                         dsl_free(spa_get_dsl(zio->io_spa), zio->io_txg, obp);
3664                 arc_release(dr->dt.dl.dr_data, db);
3665         }
3666         mutex_exit(&db->db_mtx);
3667         dbuf_write_done(zio, NULL, db);
3668 
3669         if (zio->io_abd != NULL)
3670                 abd_put(zio->io_abd);
3671 }
3672 
3673 /* Issue I/O to commit a dirty buffer to disk. */
3674 static void
3675 dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx)
3676 {
3677         dmu_buf_impl_t *db = dr->dr_dbuf;
3678         dnode_t *dn;
3679         objset_t *os;
3680         dmu_buf_impl_t *parent = db->db_parent;
3681         uint64_t txg = tx->tx_txg;
3682         zbookmark_phys_t zb;
3683         zio_prop_t zp;
3684         zio_t *zio;
3685         int wp_flag = 0;
3686         zio_smartcomp_info_t sc;
3687 
3688         ASSERT(dmu_tx_is_syncing(tx));
3689 
3690         DB_DNODE_ENTER(db);
3691         dn = DB_DNODE(db);
3692         os = dn->dn_objset;
3693 
3694         dnode_setup_zio_smartcomp(db, &sc);
3695 
3696         if (db->db_state != DB_NOFILL) {
3697                 if (db->db_level > 0 || dn->dn_type == DMU_OT_DNODE) {
3698                         /*
3699                          * Private object buffers are released here rather
3700                          * than in dbuf_dirty() since they are only modified
3701                          * in the syncing context and we don't want the
3702                          * overhead of making multiple copies of the data.
3703                          */
3704                         if (BP_IS_HOLE(db->db_blkptr)) {
3705                                 arc_buf_thaw(data);
3706                         } else {
3707                                 dbuf_release_bp(db);
3708                         }
3709                 }
3710         }
3711 
3712         if (parent != dn->dn_dbuf) {
3713                 /* Our parent is an indirect block. */
3714                 /* We have a dirty parent that has been scheduled for write. */
3715                 ASSERT(parent && parent->db_data_pending);
3716                 /* Our parent's buffer is one level closer to the dnode. */
3717                 ASSERT(db->db_level == parent->db_level-1);
3718                 /*
3719                  * We're about to modify our parent's db_data by modifying
3720                  * our block pointer, so the parent must be released.
3721                  */
3722                 ASSERT(arc_released(parent->db_buf));
3723                 zio = parent->db_data_pending->dr_zio;
3724         } else {
3725                 /* Our parent is the dnode itself. */
3726                 ASSERT((db->db_level == dn->dn_phys->dn_nlevels-1 &&
3727                     db->db_blkid != DMU_SPILL_BLKID) ||
3728                     (db->db_blkid == DMU_SPILL_BLKID && db->db_level == 0));
3729                 if (db->db_blkid != DMU_SPILL_BLKID)
3730                         ASSERT3P(db->db_blkptr, ==,
3731                             &dn->dn_phys->dn_blkptr[db->db_blkid]);
3732                 zio = dn->dn_zio;
3733         }
3734 
3735         ASSERT(db->db_level == 0 || data == db->db_buf);
3736         ASSERT3U(db->db_blkptr->blk_birth, <=, txg);
3737         ASSERT(zio);
3738 
3739         SET_BOOKMARK(&zb, os->os_dsl_dataset ?
3740             os->os_dsl_dataset->ds_object : DMU_META_OBJSET,
3741             db->db.db_object, db->db_level, db->db_blkid);
3742 
3743         if (db->db_blkid == DMU_SPILL_BLKID)
3744                 wp_flag = WP_SPILL;
3745         wp_flag |= (db->db_state == DB_NOFILL) ? WP_NOFILL : 0;
3746         WP_SET_SPECIALCLASS(wp_flag, dr->dr_usesc);
3747 
3748         dmu_write_policy(os, dn, db->db_level, wp_flag, &zp);
3749         DB_DNODE_EXIT(db);
3750 
3751         /*
3752          * We copy the blkptr now (rather than when we instantiate the dirty
3753          * record), because its value can change between open context and
3754          * syncing context. We do not need to hold dn_struct_rwlock to read
3755          * db_blkptr because we are in syncing context.
3756          */
3757         dr->dr_bp_copy = *db->db_blkptr;
3758 
3759         if (db->db_level == 0 &&
3760             dr->dt.dl.dr_override_state == DR_OVERRIDDEN) {
3761                 /*
3762                  * The BP for this block has been provided by open context
3763                  * (by dmu_sync() or dmu_buf_write_embedded()).
3764                  */
3765                 abd_t *contents = (data != NULL) ?
3766                     abd_get_from_buf(data->b_data, arc_buf_size(data)) : NULL;
3767 
3768                 dr->dr_zio = zio_write(zio, os->os_spa, txg, &dr->dr_bp_copy,
3769                     contents, db->db.db_size, db->db.db_size, &zp,
3770                     dbuf_write_override_ready, NULL, NULL,
3771                     dbuf_write_override_done,
3772                     dr, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb,
3773                     &sc);
3774                 mutex_enter(&db->db_mtx);
3775                 dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
3776                 zio_write_override(dr->dr_zio, &dr->dt.dl.dr_overridden_by,
3777                     dr->dt.dl.dr_copies, dr->dt.dl.dr_nopwrite);
3778                 mutex_exit(&db->db_mtx);
3779         } else if (db->db_state == DB_NOFILL) {
3780                 ASSERT(zp.zp_checksum == ZIO_CHECKSUM_OFF ||
3781                     zp.zp_checksum == ZIO_CHECKSUM_NOPARITY);
3782                 dr->dr_zio = zio_write(zio, os->os_spa, txg,
3783                     &dr->dr_bp_copy, NULL, db->db.db_size, db->db.db_size, &zp,
3784                     dbuf_write_nofill_ready, NULL, NULL,
3785                     dbuf_write_nofill_done, db,
3786                     ZIO_PRIORITY_ASYNC_WRITE,
3787                     ZIO_FLAG_MUSTSUCCEED | ZIO_FLAG_NODATA, &zb, &sc);
3788         } else {
3789                 ASSERT(arc_released(data));
3790 
3791                 /*
3792                  * For indirect blocks, we want to setup the children
3793                  * ready callback so that we can properly handle an indirect
3794                  * block that only contains holes.
3795                  */
3796                 arc_done_func_t *children_ready_cb = NULL;
3797                 if (db->db_level != 0)
3798                         children_ready_cb = dbuf_write_children_ready;
3799 
3800                 dr->dr_zio = arc_write(zio, os->os_spa, txg,
3801                     &dr->dr_bp_copy, data, DBUF_IS_L2CACHEABLE(db),
3802                     &zp, dbuf_write_ready, children_ready_cb,
3803                     dbuf_write_physdone, dbuf_write_done, db,
3804                     ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb, &sc);
3805         }
3806 }