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 2011 Nexenta Systems, Inc.  All rights reserved.
  24  * Copyright (c) 2012, 2015 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  */
  29 
  30 #include <sys/zfs_context.h>
  31 #include <sys/dmu.h>
  32 #include <sys/dmu_send.h>
  33 #include <sys/dmu_impl.h>
  34 #include <sys/dbuf.h>
  35 #include <sys/dmu_objset.h>
  36 #include <sys/dsl_dataset.h>
  37 #include <sys/dsl_dir.h>
  38 #include <sys/dmu_tx.h>
  39 #include <sys/spa.h>
  40 #include <sys/zio.h>
  41 #include <sys/dmu_zfetch.h>
  42 #include <sys/sa.h>
  43 #include <sys/sa_impl.h>
  44 #include <sys/zfeature.h>
  45 #include <sys/blkptr.h>
  46 #include <sys/range_tree.h>
  47 
  48 /*
  49  * Number of times that zfs_free_range() took the slow path while doing
  50  * a zfs receive.  A nonzero value indicates a potential performance problem.
  51  */
  52 uint64_t zfs_free_range_recv_miss;
  53 
  54 static void dbuf_destroy(dmu_buf_impl_t *db);
  55 static boolean_t dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx);
  56 static void dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx);
  57 
  58 #ifndef __lint
  59 extern inline void dmu_buf_init_user(dmu_buf_user_t *dbu,
  60     dmu_buf_evict_func_t *evict_func, dmu_buf_t **clear_on_evict_dbufp);
  61 #endif /* ! __lint */
  62 
  63 /*
  64  * Global data structures and functions for the dbuf cache.
  65  */
  66 static kmem_cache_t *dbuf_cache;
  67 static taskq_t *dbu_evict_taskq;
  68 
  69 /* ARGSUSED */
  70 static int
  71 dbuf_cons(void *vdb, void *unused, int kmflag)
  72 {
  73         dmu_buf_impl_t *db = vdb;
  74         bzero(db, sizeof (dmu_buf_impl_t));
  75 
  76         mutex_init(&db->db_mtx, NULL, MUTEX_DEFAULT, NULL);
  77         cv_init(&db->db_changed, NULL, CV_DEFAULT, NULL);
  78         refcount_create(&db->db_holds);
  79 
  80         return (0);
  81 }
  82 
  83 /* ARGSUSED */
  84 static void
  85 dbuf_dest(void *vdb, void *unused)
  86 {
  87         dmu_buf_impl_t *db = vdb;
  88         mutex_destroy(&db->db_mtx);
  89         cv_destroy(&db->db_changed);
  90         refcount_destroy(&db->db_holds);
  91 }
  92 
  93 /*
  94  * dbuf hash table routines
  95  */
  96 static dbuf_hash_table_t dbuf_hash_table;
  97 
  98 static uint64_t dbuf_hash_count;
  99 
 100 static uint64_t
 101 dbuf_hash(void *os, uint64_t obj, uint8_t lvl, uint64_t blkid)
 102 {
 103         uintptr_t osv = (uintptr_t)os;
 104         uint64_t crc = -1ULL;
 105 
 106         ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
 107         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (lvl)) & 0xFF];
 108         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (osv >> 6)) & 0xFF];
 109         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 0)) & 0xFF];
 110         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 8)) & 0xFF];
 111         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (blkid >> 0)) & 0xFF];
 112         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (blkid >> 8)) & 0xFF];
 113 
 114         crc ^= (osv>>14) ^ (obj>>16) ^ (blkid>>16);
 115 
 116         return (crc);
 117 }
 118 
 119 #define DBUF_HASH(os, obj, level, blkid) dbuf_hash(os, obj, level, blkid);
 120 
 121 #define DBUF_EQUAL(dbuf, os, obj, level, blkid)         \
 122         ((dbuf)->db.db_object == (obj) &&            \
 123         (dbuf)->db_objset == (os) &&                 \
 124         (dbuf)->db_level == (level) &&                       \
 125         (dbuf)->db_blkid == (blkid))
 126 
 127 dmu_buf_impl_t *
 128 dbuf_find(objset_t *os, uint64_t obj, uint8_t level, uint64_t blkid)
 129 {
 130         dbuf_hash_table_t *h = &dbuf_hash_table;
 131         uint64_t hv = DBUF_HASH(os, obj, level, blkid);
 132         uint64_t idx = hv & h->hash_table_mask;
 133         dmu_buf_impl_t *db;
 134 
 135         mutex_enter(DBUF_HASH_MUTEX(h, idx));
 136         for (db = h->hash_table[idx]; db != NULL; db = db->db_hash_next) {
 137                 if (DBUF_EQUAL(db, os, obj, level, blkid)) {
 138                         mutex_enter(&db->db_mtx);
 139                         if (db->db_state != DB_EVICTING) {
 140                                 mutex_exit(DBUF_HASH_MUTEX(h, idx));
 141                                 return (db);
 142                         }
 143                         mutex_exit(&db->db_mtx);
 144                 }
 145         }
 146         mutex_exit(DBUF_HASH_MUTEX(h, idx));
 147         return (NULL);
 148 }
 149 
 150 static dmu_buf_impl_t *
 151 dbuf_find_bonus(objset_t *os, uint64_t object)
 152 {
 153         dnode_t *dn;
 154         dmu_buf_impl_t *db = NULL;
 155 
 156         if (dnode_hold(os, object, FTAG, &dn) == 0) {
 157                 rw_enter(&dn->dn_struct_rwlock, RW_READER);
 158                 if (dn->dn_bonus != NULL) {
 159                         db = dn->dn_bonus;
 160                         mutex_enter(&db->db_mtx);
 161                 }
 162                 rw_exit(&dn->dn_struct_rwlock);
 163                 dnode_rele(dn, FTAG);
 164         }
 165         return (db);
 166 }
 167 
 168 /*
 169  * Insert an entry into the hash table.  If there is already an element
 170  * equal to elem in the hash table, then the already existing element
 171  * will be returned and the new element will not be inserted.
 172  * Otherwise returns NULL.
 173  */
 174 static dmu_buf_impl_t *
 175 dbuf_hash_insert(dmu_buf_impl_t *db)
 176 {
 177         dbuf_hash_table_t *h = &dbuf_hash_table;
 178         objset_t *os = db->db_objset;
 179         uint64_t obj = db->db.db_object;
 180         int level = db->db_level;
 181         uint64_t blkid = db->db_blkid;
 182         uint64_t hv = DBUF_HASH(os, obj, level, blkid);
 183         uint64_t idx = hv & h->hash_table_mask;
 184         dmu_buf_impl_t *dbf;
 185 
 186         mutex_enter(DBUF_HASH_MUTEX(h, idx));
 187         for (dbf = h->hash_table[idx]; dbf != NULL; dbf = dbf->db_hash_next) {
 188                 if (DBUF_EQUAL(dbf, os, obj, level, blkid)) {
 189                         mutex_enter(&dbf->db_mtx);
 190                         if (dbf->db_state != DB_EVICTING) {
 191                                 mutex_exit(DBUF_HASH_MUTEX(h, idx));
 192                                 return (dbf);
 193                         }
 194                         mutex_exit(&dbf->db_mtx);
 195                 }
 196         }
 197 
 198         mutex_enter(&db->db_mtx);
 199         db->db_hash_next = h->hash_table[idx];
 200         h->hash_table[idx] = db;
 201         mutex_exit(DBUF_HASH_MUTEX(h, idx));
 202         atomic_inc_64(&dbuf_hash_count);
 203 
 204         return (NULL);
 205 }
 206 
 207 /*
 208  * Remove an entry from the hash table.  It must be in the EVICTING state.
 209  */
 210 static void
 211 dbuf_hash_remove(dmu_buf_impl_t *db)
 212 {
 213         dbuf_hash_table_t *h = &dbuf_hash_table;
 214         uint64_t hv = DBUF_HASH(db->db_objset, db->db.db_object,
 215             db->db_level, db->db_blkid);
 216         uint64_t idx = hv & h->hash_table_mask;
 217         dmu_buf_impl_t *dbf, **dbp;
 218 
 219         /*
 220          * We musn't hold db_mtx to maintain lock ordering:
 221          * DBUF_HASH_MUTEX > db_mtx.
 222          */
 223         ASSERT(refcount_is_zero(&db->db_holds));
 224         ASSERT(db->db_state == DB_EVICTING);
 225         ASSERT(!MUTEX_HELD(&db->db_mtx));
 226 
 227         mutex_enter(DBUF_HASH_MUTEX(h, idx));
 228         dbp = &h->hash_table[idx];
 229         while ((dbf = *dbp) != db) {
 230                 dbp = &dbf->db_hash_next;
 231                 ASSERT(dbf != NULL);
 232         }
 233         *dbp = db->db_hash_next;
 234         db->db_hash_next = NULL;
 235         mutex_exit(DBUF_HASH_MUTEX(h, idx));
 236         atomic_dec_64(&dbuf_hash_count);
 237 }
 238 
 239 static arc_evict_func_t dbuf_do_evict;
 240 
 241 typedef enum {
 242         DBVU_EVICTING,
 243         DBVU_NOT_EVICTING
 244 } dbvu_verify_type_t;
 245 
 246 static void
 247 dbuf_verify_user(dmu_buf_impl_t *db, dbvu_verify_type_t verify_type)
 248 {
 249 #ifdef ZFS_DEBUG
 250         int64_t holds;
 251 
 252         if (db->db_user == NULL)
 253                 return;
 254 
 255         /* Only data blocks support the attachment of user data. */
 256         ASSERT(db->db_level == 0);
 257 
 258         /* Clients must resolve a dbuf before attaching user data. */
 259         ASSERT(db->db.db_data != NULL);
 260         ASSERT3U(db->db_state, ==, DB_CACHED);
 261 
 262         holds = refcount_count(&db->db_holds);
 263         if (verify_type == DBVU_EVICTING) {
 264                 /*
 265                  * Immediate eviction occurs when holds == dirtycnt.
 266                  * For normal eviction buffers, holds is zero on
 267                  * eviction, except when dbuf_fix_old_data() calls
 268                  * dbuf_clear_data().  However, the hold count can grow
 269                  * during eviction even though db_mtx is held (see
 270                  * dmu_bonus_hold() for an example), so we can only
 271                  * test the generic invariant that holds >= dirtycnt.
 272                  */
 273                 ASSERT3U(holds, >=, db->db_dirtycnt);
 274         } else {
 275                 if (db->db_user_immediate_evict == TRUE)
 276                         ASSERT3U(holds, >=, db->db_dirtycnt);
 277                 else
 278                         ASSERT3U(holds, >, 0);
 279         }
 280 #endif
 281 }
 282 
 283 static void
 284 dbuf_evict_user(dmu_buf_impl_t *db)
 285 {
 286         dmu_buf_user_t *dbu = db->db_user;
 287 
 288         ASSERT(MUTEX_HELD(&db->db_mtx));
 289 
 290         if (dbu == NULL)
 291                 return;
 292 
 293         dbuf_verify_user(db, DBVU_EVICTING);
 294         db->db_user = NULL;
 295 
 296 #ifdef ZFS_DEBUG
 297         if (dbu->dbu_clear_on_evict_dbufp != NULL)
 298                 *dbu->dbu_clear_on_evict_dbufp = NULL;
 299 #endif
 300 
 301         /*
 302          * Invoke the callback from a taskq to avoid lock order reversals
 303          * and limit stack depth.
 304          */
 305         taskq_dispatch_ent(dbu_evict_taskq, dbu->dbu_evict_func, dbu, 0,
 306             &dbu->dbu_tqent);
 307 }
 308 
 309 boolean_t
 310 dbuf_is_metadata(dmu_buf_impl_t *db)
 311 {
 312         if (db->db_level > 0) {
 313                 return (B_TRUE);
 314         } else {
 315                 boolean_t is_metadata;
 316 
 317                 DB_DNODE_ENTER(db);
 318                 is_metadata = DMU_OT_IS_METADATA(DB_DNODE(db)->dn_type);
 319                 DB_DNODE_EXIT(db);
 320 
 321                 return (is_metadata);
 322         }
 323 }
 324 
 325 void
 326 dbuf_evict(dmu_buf_impl_t *db)
 327 {
 328         ASSERT(MUTEX_HELD(&db->db_mtx));
 329         ASSERT(db->db_buf == NULL);
 330         ASSERT(db->db_data_pending == NULL);
 331 
 332         dbuf_clear(db);
 333         dbuf_destroy(db);
 334 }
 335 
 336 void
 337 dbuf_init(void)
 338 {
 339         uint64_t hsize = 1ULL << 16;
 340         dbuf_hash_table_t *h = &dbuf_hash_table;
 341         int i;
 342 
 343         /*
 344          * The hash table is big enough to fill all of physical memory
 345          * with an average 4K block size.  The table will take up
 346          * totalmem*sizeof(void*)/4K (i.e. 2MB/GB with 8-byte pointers).
 347          */
 348         while (hsize * 4096 < physmem * PAGESIZE)
 349                 hsize <<= 1;
 350 
 351 retry:
 352         h->hash_table_mask = hsize - 1;
 353         h->hash_table = kmem_zalloc(hsize * sizeof (void *), KM_NOSLEEP);
 354         if (h->hash_table == NULL) {
 355                 /* XXX - we should really return an error instead of assert */
 356                 ASSERT(hsize > (1ULL << 10));
 357                 hsize >>= 1;
 358                 goto retry;
 359         }
 360 
 361         dbuf_cache = kmem_cache_create("dmu_buf_impl_t",
 362             sizeof (dmu_buf_impl_t),
 363             0, dbuf_cons, dbuf_dest, NULL, NULL, NULL, 0);
 364 
 365         for (i = 0; i < DBUF_MUTEXES; i++)
 366                 mutex_init(&h->hash_mutexes[i], NULL, MUTEX_DEFAULT, NULL);
 367 
 368         /*
 369          * All entries are queued via taskq_dispatch_ent(), so min/maxalloc
 370          * configuration is not required.
 371          */
 372         dbu_evict_taskq = taskq_create("dbu_evict", 1, minclsyspri, 0, 0, 0);
 373 }
 374 
 375 void
 376 dbuf_fini(void)
 377 {
 378         dbuf_hash_table_t *h = &dbuf_hash_table;
 379         int i;
 380 
 381         for (i = 0; i < DBUF_MUTEXES; i++)
 382                 mutex_destroy(&h->hash_mutexes[i]);
 383         kmem_free(h->hash_table, (h->hash_table_mask + 1) * sizeof (void *));
 384         kmem_cache_destroy(dbuf_cache);
 385         taskq_destroy(dbu_evict_taskq);
 386 }
 387 
 388 /*
 389  * Other stuff.
 390  */
 391 
 392 #ifdef ZFS_DEBUG
 393 static void
 394 dbuf_verify(dmu_buf_impl_t *db)
 395 {
 396         dnode_t *dn;
 397         dbuf_dirty_record_t *dr;
 398 
 399         ASSERT(MUTEX_HELD(&db->db_mtx));
 400 
 401         if (!(zfs_flags & ZFS_DEBUG_DBUF_VERIFY))
 402                 return;
 403 
 404         ASSERT(db->db_objset != NULL);
 405         DB_DNODE_ENTER(db);
 406         dn = DB_DNODE(db);
 407         if (dn == NULL) {
 408                 ASSERT(db->db_parent == NULL);
 409                 ASSERT(db->db_blkptr == NULL);
 410         } else {
 411                 ASSERT3U(db->db.db_object, ==, dn->dn_object);
 412                 ASSERT3P(db->db_objset, ==, dn->dn_objset);
 413                 ASSERT3U(db->db_level, <, dn->dn_nlevels);
 414                 ASSERT(db->db_blkid == DMU_BONUS_BLKID ||
 415                     db->db_blkid == DMU_SPILL_BLKID ||
 416                     !avl_is_empty(&dn->dn_dbufs));
 417         }
 418         if (db->db_blkid == DMU_BONUS_BLKID) {
 419                 ASSERT(dn != NULL);
 420                 ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
 421                 ASSERT3U(db->db.db_offset, ==, DMU_BONUS_BLKID);
 422         } else if (db->db_blkid == DMU_SPILL_BLKID) {
 423                 ASSERT(dn != NULL);
 424                 ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
 425                 ASSERT0(db->db.db_offset);
 426         } else {
 427                 ASSERT3U(db->db.db_offset, ==, db->db_blkid * db->db.db_size);
 428         }
 429 
 430         for (dr = db->db_data_pending; dr != NULL; dr = dr->dr_next)
 431                 ASSERT(dr->dr_dbuf == db);
 432 
 433         for (dr = db->db_last_dirty; dr != NULL; dr = dr->dr_next)
 434                 ASSERT(dr->dr_dbuf == db);
 435 
 436         /*
 437          * We can't assert that db_size matches dn_datablksz because it
 438          * can be momentarily different when another thread is doing
 439          * dnode_set_blksz().
 440          */
 441         if (db->db_level == 0 && db->db.db_object == DMU_META_DNODE_OBJECT) {
 442                 dr = db->db_data_pending;
 443                 /*
 444                  * It should only be modified in syncing context, so
 445                  * make sure we only have one copy of the data.
 446                  */
 447                 ASSERT(dr == NULL || dr->dt.dl.dr_data == db->db_buf);
 448         }
 449 
 450         /* verify db->db_blkptr */
 451         if (db->db_blkptr) {
 452                 if (db->db_parent == dn->dn_dbuf) {
 453                         /* db is pointed to by the dnode */
 454                         /* ASSERT3U(db->db_blkid, <, dn->dn_nblkptr); */
 455                         if (DMU_OBJECT_IS_SPECIAL(db->db.db_object))
 456                                 ASSERT(db->db_parent == NULL);
 457                         else
 458                                 ASSERT(db->db_parent != NULL);
 459                         if (db->db_blkid != DMU_SPILL_BLKID)
 460                                 ASSERT3P(db->db_blkptr, ==,
 461                                     &dn->dn_phys->dn_blkptr[db->db_blkid]);
 462                 } else {
 463                         /* db is pointed to by an indirect block */
 464                         int epb = db->db_parent->db.db_size >> SPA_BLKPTRSHIFT;
 465                         ASSERT3U(db->db_parent->db_level, ==, db->db_level+1);
 466                         ASSERT3U(db->db_parent->db.db_object, ==,
 467                             db->db.db_object);
 468                         /*
 469                          * dnode_grow_indblksz() can make this fail if we don't
 470                          * have the struct_rwlock.  XXX indblksz no longer
 471                          * grows.  safe to do this now?
 472                          */
 473                         if (RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
 474                                 ASSERT3P(db->db_blkptr, ==,
 475                                     ((blkptr_t *)db->db_parent->db.db_data +
 476                                     db->db_blkid % epb));
 477                         }
 478                 }
 479         }
 480         if ((db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr)) &&
 481             (db->db_buf == NULL || db->db_buf->b_data) &&
 482             db->db.db_data && db->db_blkid != DMU_BONUS_BLKID &&
 483             db->db_state != DB_FILL && !dn->dn_free_txg) {
 484                 /*
 485                  * If the blkptr isn't set but they have nonzero data,
 486                  * it had better be dirty, otherwise we'll lose that
 487                  * data when we evict this buffer.
 488                  */
 489                 if (db->db_dirtycnt == 0) {
 490                         uint64_t *buf = db->db.db_data;
 491                         int i;
 492 
 493                         for (i = 0; i < db->db.db_size >> 3; i++) {
 494                                 ASSERT(buf[i] == 0);
 495                         }
 496                 }
 497         }
 498         DB_DNODE_EXIT(db);
 499 }
 500 #endif
 501 
 502 static void
 503 dbuf_clear_data(dmu_buf_impl_t *db)
 504 {
 505         ASSERT(MUTEX_HELD(&db->db_mtx));
 506         dbuf_evict_user(db);
 507         db->db_buf = NULL;
 508         db->db.db_data = NULL;
 509         if (db->db_state != DB_NOFILL)
 510                 db->db_state = DB_UNCACHED;
 511 }
 512 
 513 static void
 514 dbuf_set_data(dmu_buf_impl_t *db, arc_buf_t *buf)
 515 {
 516         ASSERT(MUTEX_HELD(&db->db_mtx));
 517         ASSERT(buf != NULL);
 518 
 519         db->db_buf = buf;
 520         ASSERT(buf->b_data != NULL);
 521         db->db.db_data = buf->b_data;
 522         if (!arc_released(buf))
 523                 arc_set_callback(buf, dbuf_do_evict, db);
 524 }
 525 
 526 /*
 527  * Loan out an arc_buf for read.  Return the loaned arc_buf.
 528  */
 529 arc_buf_t *
 530 dbuf_loan_arcbuf(dmu_buf_impl_t *db)
 531 {
 532         arc_buf_t *abuf;
 533 
 534         mutex_enter(&db->db_mtx);
 535         if (arc_released(db->db_buf) || refcount_count(&db->db_holds) > 1) {
 536                 int blksz = db->db.db_size;
 537                 spa_t *spa = db->db_objset->os_spa;
 538 
 539                 mutex_exit(&db->db_mtx);
 540                 abuf = arc_loan_buf(spa, blksz);
 541                 bcopy(db->db.db_data, abuf->b_data, blksz);
 542         } else {
 543                 abuf = db->db_buf;
 544                 arc_loan_inuse_buf(abuf, db);
 545                 dbuf_clear_data(db);
 546                 mutex_exit(&db->db_mtx);
 547         }
 548         return (abuf);
 549 }
 550 
 551 /*
 552  * Calculate which level n block references the data at the level 0 offset
 553  * provided.
 554  */
 555 uint64_t
 556 dbuf_whichblock(dnode_t *dn, int64_t level, uint64_t offset)
 557 {
 558         if (dn->dn_datablkshift != 0 && dn->dn_indblkshift != 0) {
 559                 /*
 560                  * The level n blkid is equal to the level 0 blkid divided by
 561                  * the number of level 0s in a level n block.
 562                  *
 563                  * The level 0 blkid is offset >> datablkshift =
 564                  * offset / 2^datablkshift.
 565                  *
 566                  * The number of level 0s in a level n is the number of block
 567                  * pointers in an indirect block, raised to the power of level.
 568                  * This is 2^(indblkshift - SPA_BLKPTRSHIFT)^level =
 569                  * 2^(level*(indblkshift - SPA_BLKPTRSHIFT)).
 570                  *
 571                  * Thus, the level n blkid is: offset /
 572                  * ((2^datablkshift)*(2^(level*(indblkshift - SPA_BLKPTRSHIFT)))
 573                  * = offset / 2^(datablkshift + level *
 574                  *   (indblkshift - SPA_BLKPTRSHIFT))
 575                  * = offset >> (datablkshift + level *
 576                  *   (indblkshift - SPA_BLKPTRSHIFT))
 577                  */
 578                 return (offset >> (dn->dn_datablkshift + level *
 579                     (dn->dn_indblkshift - SPA_BLKPTRSHIFT)));
 580         } else {
 581                 ASSERT3U(offset, <, dn->dn_datablksz);
 582                 return (0);
 583         }
 584 }
 585 
 586 static void
 587 dbuf_read_done(zio_t *zio, arc_buf_t *buf, void *vdb)
 588 {
 589         dmu_buf_impl_t *db = vdb;
 590 
 591         mutex_enter(&db->db_mtx);
 592         ASSERT3U(db->db_state, ==, DB_READ);
 593         /*
 594          * All reads are synchronous, so we must have a hold on the dbuf
 595          */
 596         ASSERT(refcount_count(&db->db_holds) > 0);
 597         ASSERT(db->db_buf == NULL);
 598         ASSERT(db->db.db_data == NULL);
 599         if (db->db_level == 0 && db->db_freed_in_flight) {
 600                 /* we were freed in flight; disregard any error */
 601                 arc_release(buf, db);
 602                 bzero(buf->b_data, db->db.db_size);
 603                 arc_buf_freeze(buf);
 604                 db->db_freed_in_flight = FALSE;
 605                 dbuf_set_data(db, buf);
 606                 db->db_state = DB_CACHED;
 607         } else if (zio == NULL || zio->io_error == 0) {
 608                 dbuf_set_data(db, buf);
 609                 db->db_state = DB_CACHED;
 610         } else {
 611                 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
 612                 ASSERT3P(db->db_buf, ==, NULL);
 613                 VERIFY(arc_buf_remove_ref(buf, db));
 614                 db->db_state = DB_UNCACHED;
 615         }
 616         cv_broadcast(&db->db_changed);
 617         dbuf_rele_and_unlock(db, NULL);
 618 }
 619 
 620 static void
 621 dbuf_read_impl(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
 622 {
 623         dnode_t *dn;
 624         zbookmark_phys_t zb;
 625         arc_flags_t aflags = ARC_FLAG_NOWAIT;
 626 
 627         DB_DNODE_ENTER(db);
 628         dn = DB_DNODE(db);
 629         ASSERT(!refcount_is_zero(&db->db_holds));
 630         /* We need the struct_rwlock to prevent db_blkptr from changing. */
 631         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
 632         ASSERT(MUTEX_HELD(&db->db_mtx));
 633         ASSERT(db->db_state == DB_UNCACHED);
 634         ASSERT(db->db_buf == NULL);
 635 
 636         if (db->db_blkid == DMU_BONUS_BLKID) {
 637                 int bonuslen = MIN(dn->dn_bonuslen, dn->dn_phys->dn_bonuslen);
 638 
 639                 ASSERT3U(bonuslen, <=, db->db.db_size);
 640                 db->db.db_data = zio_buf_alloc(DN_MAX_BONUSLEN);
 641                 arc_space_consume(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
 642                 if (bonuslen < DN_MAX_BONUSLEN)
 643                         bzero(db->db.db_data, DN_MAX_BONUSLEN);
 644                 if (bonuslen) {
 645                         /*
 646                          * Absent byzantine on-disk corruption, we fully expect
 647                          * our bonuslen to be no more than DN_MAX_BONUSLEN --
 648                          * but we nonetheless explicitly clamp it on the
 649                          * bcopy() to prevent any on-disk corruption from
 650                          * becoming rampant in-kernel corruption.
 651                          */
 652                         if (bonuslen > DN_MAX_BONUSLEN) {
 653                                 DTRACE_PROBE3(dbuf__read__impl__toolong, int,
 654                                     bonuslen, dnode_t *, dn, dmu_buf_impl_t *,
 655                                     db);
 656                                 bcopy(DN_BONUS(dn->dn_phys), db->db.db_data,
 657                                     DN_MAX_BONUSLEN);
 658                         } else {
 659                                 bcopy(DN_BONUS(dn->dn_phys), db->db.db_data,
 660                                     bonuslen);
 661                         }
 662                 }
 663                 DB_DNODE_EXIT(db);
 664                 db->db_state = DB_CACHED;
 665                 mutex_exit(&db->db_mtx);
 666                 return;
 667         }
 668 
 669         /*
 670          * Recheck BP_IS_HOLE() after dnode_block_freed() in case dnode_sync()
 671          * processes the delete record and clears the bp while we are waiting
 672          * for the dn_mtx (resulting in a "no" from block_freed).
 673          */
 674         if (db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr) ||
 675             (db->db_level == 0 && (dnode_block_freed(dn, db->db_blkid) ||
 676             BP_IS_HOLE(db->db_blkptr)))) {
 677                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
 678 
 679                 DB_DNODE_EXIT(db);
 680                 dbuf_set_data(db, arc_buf_alloc(db->db_objset->os_spa,
 681                     db->db.db_size, db, type));
 682                 bzero(db->db.db_data, db->db.db_size);
 683                 db->db_state = DB_CACHED;
 684                 mutex_exit(&db->db_mtx);
 685                 return;
 686         }
 687 
 688         DB_DNODE_EXIT(db);
 689 
 690         db->db_state = DB_READ;
 691         mutex_exit(&db->db_mtx);
 692 
 693         if (DBUF_IS_L2CACHEABLE(db))
 694                 aflags |= ARC_FLAG_L2CACHE;
 695         if (DBUF_IS_L2COMPRESSIBLE(db))
 696                 aflags |= ARC_FLAG_L2COMPRESS;
 697 
 698         SET_BOOKMARK(&zb, db->db_objset->os_dsl_dataset ?
 699             db->db_objset->os_dsl_dataset->ds_object : DMU_META_OBJSET,
 700             db->db.db_object, db->db_level, db->db_blkid);
 701 
 702         dbuf_add_ref(db, NULL);
 703 
 704         (void) arc_read(zio, db->db_objset->os_spa, db->db_blkptr,
 705             dbuf_read_done, db, ZIO_PRIORITY_SYNC_READ,
 706             (flags & DB_RF_CANFAIL) ? ZIO_FLAG_CANFAIL : ZIO_FLAG_MUSTSUCCEED,
 707             &aflags, &zb);
 708 }
 709 
 710 int
 711 dbuf_read(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
 712 {
 713         int err = 0;
 714         boolean_t havepzio = (zio != NULL);
 715         boolean_t prefetch;
 716         dnode_t *dn;
 717 
 718         /*
 719          * We don't have to hold the mutex to check db_state because it
 720          * can't be freed while we have a hold on the buffer.
 721          */
 722         ASSERT(!refcount_is_zero(&db->db_holds));
 723 
 724         if (db->db_state == DB_NOFILL)
 725                 return (SET_ERROR(EIO));
 726 
 727         DB_DNODE_ENTER(db);
 728         dn = DB_DNODE(db);
 729         if ((flags & DB_RF_HAVESTRUCT) == 0)
 730                 rw_enter(&dn->dn_struct_rwlock, RW_READER);
 731 
 732         prefetch = db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
 733             (flags & DB_RF_NOPREFETCH) == 0 && dn != NULL &&
 734             DBUF_IS_CACHEABLE(db);
 735 
 736         mutex_enter(&db->db_mtx);
 737         if (db->db_state == DB_CACHED) {
 738                 mutex_exit(&db->db_mtx);
 739                 if (prefetch)
 740                         dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1);
 741                 if ((flags & DB_RF_HAVESTRUCT) == 0)
 742                         rw_exit(&dn->dn_struct_rwlock);
 743                 DB_DNODE_EXIT(db);
 744         } else if (db->db_state == DB_UNCACHED) {
 745                 spa_t *spa = dn->dn_objset->os_spa;
 746 
 747                 if (zio == NULL)
 748                         zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
 749                 dbuf_read_impl(db, zio, flags);
 750 
 751                 /* dbuf_read_impl has dropped db_mtx for us */
 752 
 753                 if (prefetch)
 754                         dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1);
 755 
 756                 if ((flags & DB_RF_HAVESTRUCT) == 0)
 757                         rw_exit(&dn->dn_struct_rwlock);
 758                 DB_DNODE_EXIT(db);
 759 
 760                 if (!havepzio)
 761                         err = zio_wait(zio);
 762         } else {
 763                 /*
 764                  * Another reader came in while the dbuf was in flight
 765                  * between UNCACHED and CACHED.  Either a writer will finish
 766                  * writing the buffer (sending the dbuf to CACHED) or the
 767                  * first reader's request will reach the read_done callback
 768                  * and send the dbuf to CACHED.  Otherwise, a failure
 769                  * occurred and the dbuf went to UNCACHED.
 770                  */
 771                 mutex_exit(&db->db_mtx);
 772                 if (prefetch)
 773                         dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1);
 774                 if ((flags & DB_RF_HAVESTRUCT) == 0)
 775                         rw_exit(&dn->dn_struct_rwlock);
 776                 DB_DNODE_EXIT(db);
 777 
 778                 /* Skip the wait per the caller's request. */
 779                 mutex_enter(&db->db_mtx);
 780                 if ((flags & DB_RF_NEVERWAIT) == 0) {
 781                         while (db->db_state == DB_READ ||
 782                             db->db_state == DB_FILL) {
 783                                 ASSERT(db->db_state == DB_READ ||
 784                                     (flags & DB_RF_HAVESTRUCT) == 0);
 785                                 DTRACE_PROBE2(blocked__read, dmu_buf_impl_t *,
 786                                     db, zio_t *, zio);
 787                                 cv_wait(&db->db_changed, &db->db_mtx);
 788                         }
 789                         if (db->db_state == DB_UNCACHED)
 790                                 err = SET_ERROR(EIO);
 791                 }
 792                 mutex_exit(&db->db_mtx);
 793         }
 794 
 795         ASSERT(err || havepzio || db->db_state == DB_CACHED);
 796         return (err);
 797 }
 798 
 799 static void
 800 dbuf_noread(dmu_buf_impl_t *db)
 801 {
 802         ASSERT(!refcount_is_zero(&db->db_holds));
 803         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
 804         mutex_enter(&db->db_mtx);
 805         while (db->db_state == DB_READ || db->db_state == DB_FILL)
 806                 cv_wait(&db->db_changed, &db->db_mtx);
 807         if (db->db_state == DB_UNCACHED) {
 808                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
 809                 spa_t *spa = db->db_objset->os_spa;
 810 
 811                 ASSERT(db->db_buf == NULL);
 812                 ASSERT(db->db.db_data == NULL);
 813                 dbuf_set_data(db, arc_buf_alloc(spa, db->db.db_size, db, type));
 814                 db->db_state = DB_FILL;
 815         } else if (db->db_state == DB_NOFILL) {
 816                 dbuf_clear_data(db);
 817         } else {
 818                 ASSERT3U(db->db_state, ==, DB_CACHED);
 819         }
 820         mutex_exit(&db->db_mtx);
 821 }
 822 
 823 /*
 824  * This is our just-in-time copy function.  It makes a copy of
 825  * buffers, that have been modified in a previous transaction
 826  * group, before we modify them in the current active group.
 827  *
 828  * This function is used in two places: when we are dirtying a
 829  * buffer for the first time in a txg, and when we are freeing
 830  * a range in a dnode that includes this buffer.
 831  *
 832  * Note that when we are called from dbuf_free_range() we do
 833  * not put a hold on the buffer, we just traverse the active
 834  * dbuf list for the dnode.
 835  */
 836 static void
 837 dbuf_fix_old_data(dmu_buf_impl_t *db, uint64_t txg)
 838 {
 839         dbuf_dirty_record_t *dr = db->db_last_dirty;
 840 
 841         ASSERT(MUTEX_HELD(&db->db_mtx));
 842         ASSERT(db->db.db_data != NULL);
 843         ASSERT(db->db_level == 0);
 844         ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT);
 845 
 846         if (dr == NULL ||
 847             (dr->dt.dl.dr_data !=
 848             ((db->db_blkid  == DMU_BONUS_BLKID) ? db->db.db_data : db->db_buf)))
 849                 return;
 850 
 851         /*
 852          * If the last dirty record for this dbuf has not yet synced
 853          * and its referencing the dbuf data, either:
 854          *      reset the reference to point to a new copy,
 855          * or (if there a no active holders)
 856          *      just null out the current db_data pointer.
 857          */
 858         ASSERT(dr->dr_txg >= txg - 2);
 859         if (db->db_blkid == DMU_BONUS_BLKID) {
 860                 /* Note that the data bufs here are zio_bufs */
 861                 dr->dt.dl.dr_data = zio_buf_alloc(DN_MAX_BONUSLEN);
 862                 arc_space_consume(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
 863                 bcopy(db->db.db_data, dr->dt.dl.dr_data, DN_MAX_BONUSLEN);
 864         } else if (refcount_count(&db->db_holds) > db->db_dirtycnt) {
 865                 int size = db->db.db_size;
 866                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
 867                 spa_t *spa = db->db_objset->os_spa;
 868 
 869                 dr->dt.dl.dr_data = arc_buf_alloc(spa, size, db, type);
 870                 bcopy(db->db.db_data, dr->dt.dl.dr_data->b_data, size);
 871         } else {
 872                 dbuf_clear_data(db);
 873         }
 874 }
 875 
 876 void
 877 dbuf_unoverride(dbuf_dirty_record_t *dr)
 878 {
 879         dmu_buf_impl_t *db = dr->dr_dbuf;
 880         blkptr_t *bp = &dr->dt.dl.dr_overridden_by;
 881         uint64_t txg = dr->dr_txg;
 882 
 883         ASSERT(MUTEX_HELD(&db->db_mtx));
 884         ASSERT(dr->dt.dl.dr_override_state != DR_IN_DMU_SYNC);
 885         ASSERT(db->db_level == 0);
 886 
 887         if (db->db_blkid == DMU_BONUS_BLKID ||
 888             dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN)
 889                 return;
 890 
 891         ASSERT(db->db_data_pending != dr);
 892 
 893         /* free this block */
 894         if (!BP_IS_HOLE(bp) && !dr->dt.dl.dr_nopwrite)
 895                 zio_free(db->db_objset->os_spa, txg, bp);
 896 
 897         dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
 898         dr->dt.dl.dr_nopwrite = B_FALSE;
 899 
 900         /*
 901          * Release the already-written buffer, so we leave it in
 902          * a consistent dirty state.  Note that all callers are
 903          * modifying the buffer, so they will immediately do
 904          * another (redundant) arc_release().  Therefore, leave
 905          * the buf thawed to save the effort of freezing &
 906          * immediately re-thawing it.
 907          */
 908         arc_release(dr->dt.dl.dr_data, db);
 909 }
 910 
 911 /*
 912  * Evict (if its unreferenced) or clear (if its referenced) any level-0
 913  * data blocks in the free range, so that any future readers will find
 914  * empty blocks.
 915  *
 916  * This is a no-op if the dataset is in the middle of an incremental
 917  * receive; see comment below for details.
 918  */
 919 void
 920 dbuf_free_range(dnode_t *dn, uint64_t start_blkid, uint64_t end_blkid,
 921     dmu_tx_t *tx)
 922 {
 923         dmu_buf_impl_t db_search;
 924         dmu_buf_impl_t *db, *db_next;
 925         uint64_t txg = tx->tx_txg;
 926         avl_index_t where;
 927 
 928         if (end_blkid > dn->dn_maxblkid && (end_blkid != DMU_SPILL_BLKID))
 929                 end_blkid = dn->dn_maxblkid;
 930         dprintf_dnode(dn, "start=%llu end=%llu\n", start_blkid, end_blkid);
 931 
 932         db_search.db_level = 0;
 933         db_search.db_blkid = start_blkid;
 934         db_search.db_state = DB_SEARCH;
 935 
 936         mutex_enter(&dn->dn_dbufs_mtx);
 937         if (start_blkid >= dn->dn_unlisted_l0_blkid) {
 938                 /* There can't be any dbufs in this range; no need to search. */
 939 #ifdef DEBUG
 940                 db = avl_find(&dn->dn_dbufs, &db_search, &where);
 941                 ASSERT3P(db, ==, NULL);
 942                 db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
 943                 ASSERT(db == NULL || db->db_level > 0);
 944 #endif
 945                 mutex_exit(&dn->dn_dbufs_mtx);
 946                 return;
 947         } else if (dmu_objset_is_receiving(dn->dn_objset)) {
 948                 /*
 949                  * If we are receiving, we expect there to be no dbufs in
 950                  * the range to be freed, because receive modifies each
 951                  * block at most once, and in offset order.  If this is
 952                  * not the case, it can lead to performance problems,
 953                  * so note that we unexpectedly took the slow path.
 954                  */
 955                 atomic_inc_64(&zfs_free_range_recv_miss);
 956         }
 957 
 958         db = avl_find(&dn->dn_dbufs, &db_search, &where);
 959         ASSERT3P(db, ==, NULL);
 960         db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
 961 
 962         for (; db != NULL; db = db_next) {
 963                 db_next = AVL_NEXT(&dn->dn_dbufs, db);
 964                 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
 965 
 966                 if (db->db_level != 0 || db->db_blkid > end_blkid) {
 967                         break;
 968                 }
 969                 ASSERT3U(db->db_blkid, >=, start_blkid);
 970 
 971                 /* found a level 0 buffer in the range */
 972                 mutex_enter(&db->db_mtx);
 973                 if (dbuf_undirty(db, tx)) {
 974                         /* mutex has been dropped and dbuf destroyed */
 975                         continue;
 976                 }
 977 
 978                 if (db->db_state == DB_UNCACHED ||
 979                     db->db_state == DB_NOFILL ||
 980                     db->db_state == DB_EVICTING) {
 981                         ASSERT(db->db.db_data == NULL);
 982                         mutex_exit(&db->db_mtx);
 983                         continue;
 984                 }
 985                 if (db->db_state == DB_READ || db->db_state == DB_FILL) {
 986                         /* will be handled in dbuf_read_done or dbuf_rele */
 987                         db->db_freed_in_flight = TRUE;
 988                         mutex_exit(&db->db_mtx);
 989                         continue;
 990                 }
 991                 if (refcount_count(&db->db_holds) == 0) {
 992                         ASSERT(db->db_buf);
 993                         dbuf_clear(db);
 994                         continue;
 995                 }
 996                 /* The dbuf is referenced */
 997 
 998                 if (db->db_last_dirty != NULL) {
 999                         dbuf_dirty_record_t *dr = db->db_last_dirty;
1000 
1001                         if (dr->dr_txg == txg) {
1002                                 /*
1003                                  * This buffer is "in-use", re-adjust the file
1004                                  * size to reflect that this buffer may
1005                                  * contain new data when we sync.
1006                                  */
1007                                 if (db->db_blkid != DMU_SPILL_BLKID &&
1008                                     db->db_blkid > dn->dn_maxblkid)
1009                                         dn->dn_maxblkid = db->db_blkid;
1010                                 dbuf_unoverride(dr);
1011                         } else {
1012                                 /*
1013                                  * This dbuf is not dirty in the open context.
1014                                  * Either uncache it (if its not referenced in
1015                                  * the open context) or reset its contents to
1016                                  * empty.
1017                                  */
1018                                 dbuf_fix_old_data(db, txg);
1019                         }
1020                 }
1021                 /* clear the contents if its cached */
1022                 if (db->db_state == DB_CACHED) {
1023                         ASSERT(db->db.db_data != NULL);
1024                         arc_release(db->db_buf, db);
1025                         bzero(db->db.db_data, db->db.db_size);
1026                         arc_buf_freeze(db->db_buf);
1027                 }
1028 
1029                 mutex_exit(&db->db_mtx);
1030         }
1031         mutex_exit(&dn->dn_dbufs_mtx);
1032 }
1033 
1034 static int
1035 dbuf_block_freeable(dmu_buf_impl_t *db)
1036 {
1037         dsl_dataset_t *ds = db->db_objset->os_dsl_dataset;
1038         uint64_t birth_txg = 0;
1039 
1040         /*
1041          * We don't need any locking to protect db_blkptr:
1042          * If it's syncing, then db_last_dirty will be set
1043          * so we'll ignore db_blkptr.
1044          *
1045          * This logic ensures that only block births for
1046          * filled blocks are considered.
1047          */
1048         ASSERT(MUTEX_HELD(&db->db_mtx));
1049         if (db->db_last_dirty && (db->db_blkptr == NULL ||
1050             !BP_IS_HOLE(db->db_blkptr))) {
1051                 birth_txg = db->db_last_dirty->dr_txg;
1052         } else if (db->db_blkptr != NULL && !BP_IS_HOLE(db->db_blkptr)) {
1053                 birth_txg = db->db_blkptr->blk_birth;
1054         }
1055 
1056         /*
1057          * If this block don't exist or is in a snapshot, it can't be freed.
1058          * Don't pass the bp to dsl_dataset_block_freeable() since we
1059          * are holding the db_mtx lock and might deadlock if we are
1060          * prefetching a dedup-ed block.
1061          */
1062         if (birth_txg != 0)
1063                 return (ds == NULL ||
1064                     dsl_dataset_block_freeable(ds, NULL, birth_txg));
1065         else
1066                 return (B_FALSE);
1067 }
1068 
1069 void
1070 dbuf_new_size(dmu_buf_impl_t *db, int size, dmu_tx_t *tx)
1071 {
1072         arc_buf_t *buf, *obuf;
1073         int osize = db->db.db_size;
1074         arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1075         dnode_t *dn;
1076 
1077         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1078 
1079         DB_DNODE_ENTER(db);
1080         dn = DB_DNODE(db);
1081 
1082         /* XXX does *this* func really need the lock? */
1083         ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
1084 
1085         /*
1086          * This call to dmu_buf_will_dirty() with the dn_struct_rwlock held
1087          * is OK, because there can be no other references to the db
1088          * when we are changing its size, so no concurrent DB_FILL can
1089          * be happening.
1090          */
1091         /*
1092          * XXX we should be doing a dbuf_read, checking the return
1093          * value and returning that up to our callers
1094          */
1095         dmu_buf_will_dirty(&db->db, tx);
1096 
1097         /* create the data buffer for the new block */
1098         buf = arc_buf_alloc(dn->dn_objset->os_spa, size, db, type);
1099 
1100         /* copy old block data to the new block */
1101         obuf = db->db_buf;
1102         bcopy(obuf->b_data, buf->b_data, MIN(osize, size));
1103         /* zero the remainder */
1104         if (size > osize)
1105                 bzero((uint8_t *)buf->b_data + osize, size - osize);
1106 
1107         mutex_enter(&db->db_mtx);
1108         dbuf_set_data(db, buf);
1109         VERIFY(arc_buf_remove_ref(obuf, db));
1110         db->db.db_size = size;
1111 
1112         if (db->db_level == 0) {
1113                 ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
1114                 db->db_last_dirty->dt.dl.dr_data = buf;
1115         }
1116         mutex_exit(&db->db_mtx);
1117 
1118         dnode_willuse_space(dn, size-osize, tx);
1119         DB_DNODE_EXIT(db);
1120 }
1121 
1122 void
1123 dbuf_release_bp(dmu_buf_impl_t *db)
1124 {
1125         objset_t *os = db->db_objset;
1126 
1127         ASSERT(dsl_pool_sync_context(dmu_objset_pool(os)));
1128         ASSERT(arc_released(os->os_phys_buf) ||
1129             list_link_active(&os->os_dsl_dataset->ds_synced_link));
1130         ASSERT(db->db_parent == NULL || arc_released(db->db_parent->db_buf));
1131 
1132         (void) arc_release(db->db_buf, db);
1133 }
1134 
1135 /*
1136  * We already have a dirty record for this TXG, and we are being
1137  * dirtied again.
1138  */
1139 static void
1140 dbuf_redirty(dbuf_dirty_record_t *dr)
1141 {
1142         dmu_buf_impl_t *db = dr->dr_dbuf;
1143 
1144         ASSERT(MUTEX_HELD(&db->db_mtx));
1145 
1146         if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID) {
1147                 /*
1148                  * If this buffer has already been written out,
1149                  * we now need to reset its state.
1150                  */
1151                 dbuf_unoverride(dr);
1152                 if (db->db.db_object != DMU_META_DNODE_OBJECT &&
1153                     db->db_state != DB_NOFILL) {
1154                         /* Already released on initial dirty, so just thaw. */
1155                         ASSERT(arc_released(db->db_buf));
1156                         arc_buf_thaw(db->db_buf);
1157                 }
1158         }
1159 }
1160 
1161 dbuf_dirty_record_t *
1162 dbuf_dirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1163 {
1164         dnode_t *dn;
1165         objset_t *os;
1166         dbuf_dirty_record_t **drp, *dr;
1167         int drop_struct_lock = FALSE;
1168         boolean_t do_free_accounting = B_FALSE;
1169         int txgoff = tx->tx_txg & TXG_MASK;
1170 
1171         ASSERT(tx->tx_txg != 0);
1172         ASSERT(!refcount_is_zero(&db->db_holds));
1173         DMU_TX_DIRTY_BUF(tx, db);
1174 
1175         DB_DNODE_ENTER(db);
1176         dn = DB_DNODE(db);
1177         /*
1178          * Shouldn't dirty a regular buffer in syncing context.  Private
1179          * objects may be dirtied in syncing context, but only if they
1180          * were already pre-dirtied in open context.
1181          */
1182         ASSERT(!dmu_tx_is_syncing(tx) ||
1183             BP_IS_HOLE(dn->dn_objset->os_rootbp) ||
1184             DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1185             dn->dn_objset->os_dsl_dataset == NULL);
1186         /*
1187          * We make this assert for private objects as well, but after we
1188          * check if we're already dirty.  They are allowed to re-dirty
1189          * in syncing context.
1190          */
1191         ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
1192             dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1193             (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1194 
1195         mutex_enter(&db->db_mtx);
1196         /*
1197          * XXX make this true for indirects too?  The problem is that
1198          * transactions created with dmu_tx_create_assigned() from
1199          * syncing context don't bother holding ahead.
1200          */
1201         ASSERT(db->db_level != 0 ||
1202             db->db_state == DB_CACHED || db->db_state == DB_FILL ||
1203             db->db_state == DB_NOFILL);
1204 
1205         mutex_enter(&dn->dn_mtx);
1206         /*
1207          * Don't set dirtyctx to SYNC if we're just modifying this as we
1208          * initialize the objset.
1209          */
1210         if (dn->dn_dirtyctx == DN_UNDIRTIED &&
1211             !BP_IS_HOLE(dn->dn_objset->os_rootbp)) {
1212                 dn->dn_dirtyctx =
1213                     (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN);
1214                 ASSERT(dn->dn_dirtyctx_firstset == NULL);
1215                 dn->dn_dirtyctx_firstset = kmem_alloc(1, KM_SLEEP);
1216         }
1217         mutex_exit(&dn->dn_mtx);
1218 
1219         if (db->db_blkid == DMU_SPILL_BLKID)
1220                 dn->dn_have_spill = B_TRUE;
1221 
1222         /*
1223          * If this buffer is already dirty, we're done.
1224          */
1225         drp = &db->db_last_dirty;
1226         ASSERT(*drp == NULL || (*drp)->dr_txg <= tx->tx_txg ||
1227             db->db.db_object == DMU_META_DNODE_OBJECT);
1228         while ((dr = *drp) != NULL && dr->dr_txg > tx->tx_txg)
1229                 drp = &dr->dr_next;
1230         if (dr && dr->dr_txg == tx->tx_txg) {
1231                 DB_DNODE_EXIT(db);
1232 
1233                 dbuf_redirty(dr);
1234                 mutex_exit(&db->db_mtx);
1235                 return (dr);
1236         }
1237 
1238         /*
1239          * Only valid if not already dirty.
1240          */
1241         ASSERT(dn->dn_object == 0 ||
1242             dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1243             (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1244 
1245         ASSERT3U(dn->dn_nlevels, >, db->db_level);
1246         ASSERT((dn->dn_phys->dn_nlevels == 0 && db->db_level == 0) ||
1247             dn->dn_phys->dn_nlevels > db->db_level ||
1248             dn->dn_next_nlevels[txgoff] > db->db_level ||
1249             dn->dn_next_nlevels[(tx->tx_txg-1) & TXG_MASK] > db->db_level ||
1250             dn->dn_next_nlevels[(tx->tx_txg-2) & TXG_MASK] > db->db_level);
1251 
1252         /*
1253          * We should only be dirtying in syncing context if it's the
1254          * mos or we're initializing the os or it's a special object.
1255          * However, we are allowed to dirty in syncing context provided
1256          * we already dirtied it in open context.  Hence we must make
1257          * this assertion only if we're not already dirty.
1258          */
1259         os = dn->dn_objset;
1260         ASSERT(!dmu_tx_is_syncing(tx) || DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1261             os->os_dsl_dataset == NULL || BP_IS_HOLE(os->os_rootbp));
1262         ASSERT(db->db.db_size != 0);
1263 
1264         dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1265 
1266         if (db->db_blkid != DMU_BONUS_BLKID) {
1267                 /*
1268                  * Update the accounting.
1269                  * Note: we delay "free accounting" until after we drop
1270                  * the db_mtx.  This keeps us from grabbing other locks
1271                  * (and possibly deadlocking) in bp_get_dsize() while
1272                  * also holding the db_mtx.
1273                  */
1274                 dnode_willuse_space(dn, db->db.db_size, tx);
1275                 do_free_accounting = dbuf_block_freeable(db);
1276         }
1277 
1278         /*
1279          * If this buffer is dirty in an old transaction group we need
1280          * to make a copy of it so that the changes we make in this
1281          * transaction group won't leak out when we sync the older txg.
1282          */
1283         dr = kmem_zalloc(sizeof (dbuf_dirty_record_t), KM_SLEEP);
1284         if (db->db_level == 0) {
1285                 void *data_old = db->db_buf;
1286 
1287                 if (db->db_state != DB_NOFILL) {
1288                         if (db->db_blkid == DMU_BONUS_BLKID) {
1289                                 dbuf_fix_old_data(db, tx->tx_txg);
1290                                 data_old = db->db.db_data;
1291                         } else if (db->db.db_object != DMU_META_DNODE_OBJECT) {
1292                                 /*
1293                                  * Release the data buffer from the cache so
1294                                  * that we can modify it without impacting
1295                                  * possible other users of this cached data
1296                                  * block.  Note that indirect blocks and
1297                                  * private objects are not released until the
1298                                  * syncing state (since they are only modified
1299                                  * then).
1300                                  */
1301                                 arc_release(db->db_buf, db);
1302                                 dbuf_fix_old_data(db, tx->tx_txg);
1303                                 data_old = db->db_buf;
1304                         }
1305                         ASSERT(data_old != NULL);
1306                 }
1307                 dr->dt.dl.dr_data = data_old;
1308         } else {
1309                 mutex_init(&dr->dt.di.dr_mtx, NULL, MUTEX_DEFAULT, NULL);
1310                 list_create(&dr->dt.di.dr_children,
1311                     sizeof (dbuf_dirty_record_t),
1312                     offsetof(dbuf_dirty_record_t, dr_dirty_node));
1313         }
1314         if (db->db_blkid != DMU_BONUS_BLKID && os->os_dsl_dataset != NULL)
1315                 dr->dr_accounted = db->db.db_size;
1316         dr->dr_dbuf = db;
1317         dr->dr_txg = tx->tx_txg;
1318         dr->dr_next = *drp;
1319         *drp = dr;
1320 
1321         /*
1322          * We could have been freed_in_flight between the dbuf_noread
1323          * and dbuf_dirty.  We win, as though the dbuf_noread() had
1324          * happened after the free.
1325          */
1326         if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
1327             db->db_blkid != DMU_SPILL_BLKID) {
1328                 mutex_enter(&dn->dn_mtx);
1329                 if (dn->dn_free_ranges[txgoff] != NULL) {
1330                         range_tree_clear(dn->dn_free_ranges[txgoff],
1331                             db->db_blkid, 1);
1332                 }
1333                 mutex_exit(&dn->dn_mtx);
1334                 db->db_freed_in_flight = FALSE;
1335         }
1336 
1337         /*
1338          * This buffer is now part of this txg
1339          */
1340         dbuf_add_ref(db, (void *)(uintptr_t)tx->tx_txg);
1341         db->db_dirtycnt += 1;
1342         ASSERT3U(db->db_dirtycnt, <=, 3);
1343 
1344         mutex_exit(&db->db_mtx);
1345 
1346         if (db->db_blkid == DMU_BONUS_BLKID ||
1347             db->db_blkid == DMU_SPILL_BLKID) {
1348                 mutex_enter(&dn->dn_mtx);
1349                 ASSERT(!list_link_active(&dr->dr_dirty_node));
1350                 list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1351                 mutex_exit(&dn->dn_mtx);
1352                 dnode_setdirty(dn, tx);
1353                 DB_DNODE_EXIT(db);
1354                 return (dr);
1355         } else if (do_free_accounting) {
1356                 blkptr_t *bp = db->db_blkptr;
1357                 int64_t willfree = (bp && !BP_IS_HOLE(bp)) ?
1358                     bp_get_dsize(os->os_spa, bp) : db->db.db_size;
1359                 /*
1360                  * This is only a guess -- if the dbuf is dirty
1361                  * in a previous txg, we don't know how much
1362                  * space it will use on disk yet.  We should
1363                  * really have the struct_rwlock to access
1364                  * db_blkptr, but since this is just a guess,
1365                  * it's OK if we get an odd answer.
1366                  */
1367                 ddt_prefetch(os->os_spa, bp);
1368                 dnode_willuse_space(dn, -willfree, tx);
1369         }
1370 
1371         if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
1372                 rw_enter(&dn->dn_struct_rwlock, RW_READER);
1373                 drop_struct_lock = TRUE;
1374         }
1375 
1376         if (db->db_level == 0) {
1377                 dnode_new_blkid(dn, db->db_blkid, tx, drop_struct_lock);
1378                 ASSERT(dn->dn_maxblkid >= db->db_blkid);
1379         }
1380 
1381         if (db->db_level+1 < dn->dn_nlevels) {
1382                 dmu_buf_impl_t *parent = db->db_parent;
1383                 dbuf_dirty_record_t *di;
1384                 int parent_held = FALSE;
1385 
1386                 if (db->db_parent == NULL || db->db_parent == dn->dn_dbuf) {
1387                         int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1388 
1389                         parent = dbuf_hold_level(dn, db->db_level+1,
1390                             db->db_blkid >> epbs, FTAG);
1391                         ASSERT(parent != NULL);
1392                         parent_held = TRUE;
1393                 }
1394                 if (drop_struct_lock)
1395                         rw_exit(&dn->dn_struct_rwlock);
1396                 ASSERT3U(db->db_level+1, ==, parent->db_level);
1397                 di = dbuf_dirty(parent, tx);
1398                 if (parent_held)
1399                         dbuf_rele(parent, FTAG);
1400 
1401                 mutex_enter(&db->db_mtx);
1402                 /*
1403                  * Since we've dropped the mutex, it's possible that
1404                  * dbuf_undirty() might have changed this out from under us.
1405                  */
1406                 if (db->db_last_dirty == dr ||
1407                     dn->dn_object == DMU_META_DNODE_OBJECT) {
1408                         mutex_enter(&di->dt.di.dr_mtx);
1409                         ASSERT3U(di->dr_txg, ==, tx->tx_txg);
1410                         ASSERT(!list_link_active(&dr->dr_dirty_node));
1411                         list_insert_tail(&di->dt.di.dr_children, dr);
1412                         mutex_exit(&di->dt.di.dr_mtx);
1413                         dr->dr_parent = di;
1414                 }
1415                 mutex_exit(&db->db_mtx);
1416         } else {
1417                 ASSERT(db->db_level+1 == dn->dn_nlevels);
1418                 ASSERT(db->db_blkid < dn->dn_nblkptr);
1419                 ASSERT(db->db_parent == NULL || db->db_parent == dn->dn_dbuf);
1420                 mutex_enter(&dn->dn_mtx);
1421                 ASSERT(!list_link_active(&dr->dr_dirty_node));
1422                 list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1423                 mutex_exit(&dn->dn_mtx);
1424                 if (drop_struct_lock)
1425                         rw_exit(&dn->dn_struct_rwlock);
1426         }
1427 
1428         dnode_setdirty(dn, tx);
1429         DB_DNODE_EXIT(db);
1430         return (dr);
1431 }
1432 
1433 /*
1434  * Undirty a buffer in the transaction group referenced by the given
1435  * transaction.  Return whether this evicted the dbuf.
1436  */
1437 static boolean_t
1438 dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1439 {
1440         dnode_t *dn;
1441         uint64_t txg = tx->tx_txg;
1442         dbuf_dirty_record_t *dr, **drp;
1443 
1444         ASSERT(txg != 0);
1445 
1446         /*
1447          * Due to our use of dn_nlevels below, this can only be called
1448          * in open context, unless we are operating on the MOS.
1449          * From syncing context, dn_nlevels may be different from the
1450          * dn_nlevels used when dbuf was dirtied.
1451          */
1452         ASSERT(db->db_objset ==
1453             dmu_objset_pool(db->db_objset)->dp_meta_objset ||
1454             txg != spa_syncing_txg(dmu_objset_spa(db->db_objset)));
1455         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1456         ASSERT0(db->db_level);
1457         ASSERT(MUTEX_HELD(&db->db_mtx));
1458 
1459         /*
1460          * If this buffer is not dirty, we're done.
1461          */
1462         for (drp = &db->db_last_dirty; (dr = *drp) != NULL; drp = &dr->dr_next)
1463                 if (dr->dr_txg <= txg)
1464                         break;
1465         if (dr == NULL || dr->dr_txg < txg)
1466                 return (B_FALSE);
1467         ASSERT(dr->dr_txg == txg);
1468         ASSERT(dr->dr_dbuf == db);
1469 
1470         DB_DNODE_ENTER(db);
1471         dn = DB_DNODE(db);
1472 
1473         dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1474 
1475         ASSERT(db->db.db_size != 0);
1476 
1477         dsl_pool_undirty_space(dmu_objset_pool(dn->dn_objset),
1478             dr->dr_accounted, txg);
1479 
1480         *drp = dr->dr_next;
1481 
1482         /*
1483          * Note that there are three places in dbuf_dirty()
1484          * where this dirty record may be put on a list.
1485          * Make sure to do a list_remove corresponding to
1486          * every one of those list_insert calls.
1487          */
1488         if (dr->dr_parent) {
1489                 mutex_enter(&dr->dr_parent->dt.di.dr_mtx);
1490                 list_remove(&dr->dr_parent->dt.di.dr_children, dr);
1491                 mutex_exit(&dr->dr_parent->dt.di.dr_mtx);
1492         } else if (db->db_blkid == DMU_SPILL_BLKID ||
1493             db->db_level + 1 == dn->dn_nlevels) {
1494                 ASSERT(db->db_blkptr == NULL || db->db_parent == dn->dn_dbuf);
1495                 mutex_enter(&dn->dn_mtx);
1496                 list_remove(&dn->dn_dirty_records[txg & TXG_MASK], dr);
1497                 mutex_exit(&dn->dn_mtx);
1498         }
1499         DB_DNODE_EXIT(db);
1500 
1501         if (db->db_state != DB_NOFILL) {
1502                 dbuf_unoverride(dr);
1503 
1504                 ASSERT(db->db_buf != NULL);
1505                 ASSERT(dr->dt.dl.dr_data != NULL);
1506                 if (dr->dt.dl.dr_data != db->db_buf)
1507                         VERIFY(arc_buf_remove_ref(dr->dt.dl.dr_data, db));
1508         }
1509 
1510         kmem_free(dr, sizeof (dbuf_dirty_record_t));
1511 
1512         ASSERT(db->db_dirtycnt > 0);
1513         db->db_dirtycnt -= 1;
1514 
1515         if (refcount_remove(&db->db_holds, (void *)(uintptr_t)txg) == 0) {
1516                 arc_buf_t *buf = db->db_buf;
1517 
1518                 ASSERT(db->db_state == DB_NOFILL || arc_released(buf));
1519                 dbuf_clear_data(db);
1520                 VERIFY(arc_buf_remove_ref(buf, db));
1521                 dbuf_evict(db);
1522                 return (B_TRUE);
1523         }
1524 
1525         return (B_FALSE);
1526 }
1527 
1528 void
1529 dmu_buf_will_dirty(dmu_buf_t *db_fake, dmu_tx_t *tx)
1530 {
1531         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1532         int rf = DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH;
1533 
1534         ASSERT(tx->tx_txg != 0);
1535         ASSERT(!refcount_is_zero(&db->db_holds));
1536 
1537         /*
1538          * Quick check for dirtyness.  For already dirty blocks, this
1539          * reduces runtime of this function by >90%, and overall performance
1540          * by 50% for some workloads (e.g. file deletion with indirect blocks
1541          * cached).
1542          */
1543         mutex_enter(&db->db_mtx);
1544         dbuf_dirty_record_t *dr;
1545         for (dr = db->db_last_dirty;
1546             dr != NULL && dr->dr_txg >= tx->tx_txg; dr = dr->dr_next) {
1547                 /*
1548                  * It's possible that it is already dirty but not cached,
1549                  * because there are some calls to dbuf_dirty() that don't
1550                  * go through dmu_buf_will_dirty().
1551                  */
1552                 if (dr->dr_txg == tx->tx_txg && db->db_state == DB_CACHED) {
1553                         /* This dbuf is already dirty and cached. */
1554                         dbuf_redirty(dr);
1555                         mutex_exit(&db->db_mtx);
1556                         return;
1557                 }
1558         }
1559         mutex_exit(&db->db_mtx);
1560 
1561         DB_DNODE_ENTER(db);
1562         if (RW_WRITE_HELD(&DB_DNODE(db)->dn_struct_rwlock))
1563                 rf |= DB_RF_HAVESTRUCT;
1564         DB_DNODE_EXIT(db);
1565         (void) dbuf_read(db, NULL, rf);
1566         (void) dbuf_dirty(db, tx);
1567 }
1568 
1569 void
1570 dmu_buf_will_not_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1571 {
1572         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1573 
1574         db->db_state = DB_NOFILL;
1575 
1576         dmu_buf_will_fill(db_fake, tx);
1577 }
1578 
1579 void
1580 dmu_buf_will_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1581 {
1582         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1583 
1584         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1585         ASSERT(tx->tx_txg != 0);
1586         ASSERT(db->db_level == 0);
1587         ASSERT(!refcount_is_zero(&db->db_holds));
1588 
1589         ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT ||
1590             dmu_tx_private_ok(tx));
1591 
1592         dbuf_noread(db);
1593         (void) dbuf_dirty(db, tx);
1594 }
1595 
1596 #pragma weak dmu_buf_fill_done = dbuf_fill_done
1597 /* ARGSUSED */
1598 void
1599 dbuf_fill_done(dmu_buf_impl_t *db, dmu_tx_t *tx)
1600 {
1601         mutex_enter(&db->db_mtx);
1602         DBUF_VERIFY(db);
1603 
1604         if (db->db_state == DB_FILL) {
1605                 if (db->db_level == 0 && db->db_freed_in_flight) {
1606                         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1607                         /* we were freed while filling */
1608                         /* XXX dbuf_undirty? */
1609                         bzero(db->db.db_data, db->db.db_size);
1610                         db->db_freed_in_flight = FALSE;
1611                 }
1612                 db->db_state = DB_CACHED;
1613                 cv_broadcast(&db->db_changed);
1614         }
1615         mutex_exit(&db->db_mtx);
1616 }
1617 
1618 void
1619 dmu_buf_write_embedded(dmu_buf_t *dbuf, void *data,
1620     bp_embedded_type_t etype, enum zio_compress comp,
1621     int uncompressed_size, int compressed_size, int byteorder,
1622     dmu_tx_t *tx)
1623 {
1624         dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
1625         struct dirty_leaf *dl;
1626         dmu_object_type_t type;
1627 
1628         if (etype == BP_EMBEDDED_TYPE_DATA) {
1629                 ASSERT(spa_feature_is_active(dmu_objset_spa(db->db_objset),
1630                     SPA_FEATURE_EMBEDDED_DATA));
1631         }
1632 
1633         DB_DNODE_ENTER(db);
1634         type = DB_DNODE(db)->dn_type;
1635         DB_DNODE_EXIT(db);
1636 
1637         ASSERT0(db->db_level);
1638         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1639 
1640         dmu_buf_will_not_fill(dbuf, tx);
1641 
1642         ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
1643         dl = &db->db_last_dirty->dt.dl;
1644         encode_embedded_bp_compressed(&dl->dr_overridden_by,
1645             data, comp, uncompressed_size, compressed_size);
1646         BPE_SET_ETYPE(&dl->dr_overridden_by, etype);
1647         BP_SET_TYPE(&dl->dr_overridden_by, type);
1648         BP_SET_LEVEL(&dl->dr_overridden_by, 0);
1649         BP_SET_BYTEORDER(&dl->dr_overridden_by, byteorder);
1650 
1651         dl->dr_override_state = DR_OVERRIDDEN;
1652         dl->dr_overridden_by.blk_birth = db->db_last_dirty->dr_txg;
1653 }
1654 
1655 /*
1656  * Directly assign a provided arc buf to a given dbuf if it's not referenced
1657  * by anybody except our caller. Otherwise copy arcbuf's contents to dbuf.
1658  */
1659 void
1660 dbuf_assign_arcbuf(dmu_buf_impl_t *db, arc_buf_t *buf, dmu_tx_t *tx)
1661 {
1662         ASSERT(!refcount_is_zero(&db->db_holds));
1663         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1664         ASSERT(db->db_level == 0);
1665         ASSERT(DBUF_GET_BUFC_TYPE(db) == ARC_BUFC_DATA);
1666         ASSERT(buf != NULL);
1667         ASSERT(arc_buf_size(buf) == db->db.db_size);
1668         ASSERT(tx->tx_txg != 0);
1669 
1670         arc_return_buf(buf, db);
1671         ASSERT(arc_released(buf));
1672 
1673         mutex_enter(&db->db_mtx);
1674 
1675         while (db->db_state == DB_READ || db->db_state == DB_FILL)
1676                 cv_wait(&db->db_changed, &db->db_mtx);
1677 
1678         ASSERT(db->db_state == DB_CACHED || db->db_state == DB_UNCACHED);
1679 
1680         if (db->db_state == DB_CACHED &&
1681             refcount_count(&db->db_holds) - 1 > db->db_dirtycnt) {
1682                 mutex_exit(&db->db_mtx);
1683                 (void) dbuf_dirty(db, tx);
1684                 bcopy(buf->b_data, db->db.db_data, db->db.db_size);
1685                 VERIFY(arc_buf_remove_ref(buf, db));
1686                 xuio_stat_wbuf_copied();
1687                 return;
1688         }
1689 
1690         xuio_stat_wbuf_nocopy();
1691         if (db->db_state == DB_CACHED) {
1692                 dbuf_dirty_record_t *dr = db->db_last_dirty;
1693 
1694                 ASSERT(db->db_buf != NULL);
1695                 if (dr != NULL && dr->dr_txg == tx->tx_txg) {
1696                         ASSERT(dr->dt.dl.dr_data == db->db_buf);
1697                         if (!arc_released(db->db_buf)) {
1698                                 ASSERT(dr->dt.dl.dr_override_state ==
1699                                     DR_OVERRIDDEN);
1700                                 arc_release(db->db_buf, db);
1701                         }
1702                         dr->dt.dl.dr_data = buf;
1703                         VERIFY(arc_buf_remove_ref(db->db_buf, db));
1704                 } else if (dr == NULL || dr->dt.dl.dr_data != db->db_buf) {
1705                         arc_release(db->db_buf, db);
1706                         VERIFY(arc_buf_remove_ref(db->db_buf, db));
1707                 }
1708                 db->db_buf = NULL;
1709         }
1710         ASSERT(db->db_buf == NULL);
1711         dbuf_set_data(db, buf);
1712         db->db_state = DB_FILL;
1713         mutex_exit(&db->db_mtx);
1714         (void) dbuf_dirty(db, tx);
1715         dmu_buf_fill_done(&db->db, tx);
1716 }
1717 
1718 /*
1719  * "Clear" the contents of this dbuf.  This will mark the dbuf
1720  * EVICTING and clear *most* of its references.  Unfortunately,
1721  * when we are not holding the dn_dbufs_mtx, we can't clear the
1722  * entry in the dn_dbufs list.  We have to wait until dbuf_destroy()
1723  * in this case.  For callers from the DMU we will usually see:
1724  *      dbuf_clear()->arc_clear_callback()->dbuf_do_evict()->dbuf_destroy()
1725  * For the arc callback, we will usually see:
1726  *      dbuf_do_evict()->dbuf_clear();dbuf_destroy()
1727  * Sometimes, though, we will get a mix of these two:
1728  *      DMU: dbuf_clear()->arc_clear_callback()
1729  *      ARC: dbuf_do_evict()->dbuf_destroy()
1730  *
1731  * This routine will dissociate the dbuf from the arc, by calling
1732  * arc_clear_callback(), but will not evict the data from the ARC.
1733  */
1734 void
1735 dbuf_clear(dmu_buf_impl_t *db)
1736 {
1737         dnode_t *dn;
1738         dmu_buf_impl_t *parent = db->db_parent;
1739         dmu_buf_impl_t *dndb;
1740         boolean_t dbuf_gone = B_FALSE;
1741 
1742         ASSERT(MUTEX_HELD(&db->db_mtx));
1743         ASSERT(refcount_is_zero(&db->db_holds));
1744 
1745         dbuf_evict_user(db);
1746 
1747         if (db->db_state == DB_CACHED) {
1748                 ASSERT(db->db.db_data != NULL);
1749                 if (db->db_blkid == DMU_BONUS_BLKID) {
1750                         zio_buf_free(db->db.db_data, DN_MAX_BONUSLEN);
1751                         arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
1752                 }
1753                 db->db.db_data = NULL;
1754                 db->db_state = DB_UNCACHED;
1755         }
1756 
1757         ASSERT(db->db_state == DB_UNCACHED || db->db_state == DB_NOFILL);
1758         ASSERT(db->db_data_pending == NULL);
1759 
1760         db->db_state = DB_EVICTING;
1761         db->db_blkptr = NULL;
1762 
1763         DB_DNODE_ENTER(db);
1764         dn = DB_DNODE(db);
1765         dndb = dn->dn_dbuf;
1766         if (db->db_blkid != DMU_BONUS_BLKID && MUTEX_HELD(&dn->dn_dbufs_mtx)) {
1767                 avl_remove(&dn->dn_dbufs, db);
1768                 atomic_dec_32(&dn->dn_dbufs_count);
1769                 membar_producer();
1770                 DB_DNODE_EXIT(db);
1771                 /*
1772                  * Decrementing the dbuf count means that the hold corresponding
1773                  * to the removed dbuf is no longer discounted in dnode_move(),
1774                  * so the dnode cannot be moved until after we release the hold.
1775                  * The membar_producer() ensures visibility of the decremented
1776                  * value in dnode_move(), since DB_DNODE_EXIT doesn't actually
1777                  * release any lock.
1778                  */
1779                 dnode_rele(dn, db);
1780                 db->db_dnode_handle = NULL;
1781         } else {
1782                 DB_DNODE_EXIT(db);
1783         }
1784 
1785         if (db->db_buf)
1786                 dbuf_gone = arc_clear_callback(db->db_buf);
1787 
1788         if (!dbuf_gone)
1789                 mutex_exit(&db->db_mtx);
1790 
1791         /*
1792          * If this dbuf is referenced from an indirect dbuf,
1793          * decrement the ref count on the indirect dbuf.
1794          */
1795         if (parent && parent != dndb)
1796                 dbuf_rele(parent, db);
1797 }
1798 
1799 /*
1800  * Note: While bpp will always be updated if the function returns success,
1801  * parentp will not be updated if the dnode does not have dn_dbuf filled in;
1802  * this happens when the dnode is the meta-dnode, or a userused or groupused
1803  * object.
1804  */
1805 static int
1806 dbuf_findbp(dnode_t *dn, int level, uint64_t blkid, int fail_sparse,
1807     dmu_buf_impl_t **parentp, blkptr_t **bpp)
1808 {
1809         int nlevels, epbs;
1810 
1811         *parentp = NULL;
1812         *bpp = NULL;
1813 
1814         ASSERT(blkid != DMU_BONUS_BLKID);
1815 
1816         if (blkid == DMU_SPILL_BLKID) {
1817                 mutex_enter(&dn->dn_mtx);
1818                 if (dn->dn_have_spill &&
1819                     (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR))
1820                         *bpp = &dn->dn_phys->dn_spill;
1821                 else
1822                         *bpp = NULL;
1823                 dbuf_add_ref(dn->dn_dbuf, NULL);
1824                 *parentp = dn->dn_dbuf;
1825                 mutex_exit(&dn->dn_mtx);
1826                 return (0);
1827         }
1828 
1829         if (dn->dn_phys->dn_nlevels == 0)
1830                 nlevels = 1;
1831         else
1832                 nlevels = dn->dn_phys->dn_nlevels;
1833 
1834         epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1835 
1836         ASSERT3U(level * epbs, <, 64);
1837         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1838         if (level >= nlevels ||
1839             (blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))) {
1840                 /* the buffer has no parent yet */
1841                 return (SET_ERROR(ENOENT));
1842         } else if (level < nlevels-1) {
1843                 /* this block is referenced from an indirect block */
1844                 int err = dbuf_hold_impl(dn, level+1,
1845                     blkid >> epbs, fail_sparse, FALSE, NULL, parentp);
1846                 if (err)
1847                         return (err);
1848                 err = dbuf_read(*parentp, NULL,
1849                     (DB_RF_HAVESTRUCT | DB_RF_NOPREFETCH | DB_RF_CANFAIL));
1850                 if (err) {
1851                         dbuf_rele(*parentp, NULL);
1852                         *parentp = NULL;
1853                         return (err);
1854                 }
1855                 *bpp = ((blkptr_t *)(*parentp)->db.db_data) +
1856                     (blkid & ((1ULL << epbs) - 1));
1857                 return (0);
1858         } else {
1859                 /* the block is referenced from the dnode */
1860                 ASSERT3U(level, ==, nlevels-1);
1861                 ASSERT(dn->dn_phys->dn_nblkptr == 0 ||
1862                     blkid < dn->dn_phys->dn_nblkptr);
1863                 if (dn->dn_dbuf) {
1864                         dbuf_add_ref(dn->dn_dbuf, NULL);
1865                         *parentp = dn->dn_dbuf;
1866                 }
1867                 *bpp = &dn->dn_phys->dn_blkptr[blkid];
1868                 return (0);
1869         }
1870 }
1871 
1872 static dmu_buf_impl_t *
1873 dbuf_create(dnode_t *dn, uint8_t level, uint64_t blkid,
1874     dmu_buf_impl_t *parent, blkptr_t *blkptr)
1875 {
1876         objset_t *os = dn->dn_objset;
1877         dmu_buf_impl_t *db, *odb;
1878 
1879         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1880         ASSERT(dn->dn_type != DMU_OT_NONE);
1881 
1882         db = kmem_cache_alloc(dbuf_cache, KM_SLEEP);
1883 
1884         db->db_objset = os;
1885         db->db.db_object = dn->dn_object;
1886         db->db_level = level;
1887         db->db_blkid = blkid;
1888         db->db_last_dirty = NULL;
1889         db->db_dirtycnt = 0;
1890         db->db_dnode_handle = dn->dn_handle;
1891         db->db_parent = parent;
1892         db->db_blkptr = blkptr;
1893 
1894         db->db_user = NULL;
1895         db->db_user_immediate_evict = FALSE;
1896         db->db_freed_in_flight = FALSE;
1897         db->db_pending_evict = FALSE;
1898 
1899         if (blkid == DMU_BONUS_BLKID) {
1900                 ASSERT3P(parent, ==, dn->dn_dbuf);
1901                 db->db.db_size = DN_MAX_BONUSLEN -
1902                     (dn->dn_nblkptr-1) * sizeof (blkptr_t);
1903                 ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
1904                 db->db.db_offset = DMU_BONUS_BLKID;
1905                 db->db_state = DB_UNCACHED;
1906                 /* the bonus dbuf is not placed in the hash table */
1907                 arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
1908                 return (db);
1909         } else if (blkid == DMU_SPILL_BLKID) {
1910                 db->db.db_size = (blkptr != NULL) ?
1911                     BP_GET_LSIZE(blkptr) : SPA_MINBLOCKSIZE;
1912                 db->db.db_offset = 0;
1913         } else {
1914                 int blocksize =
1915                     db->db_level ? 1 << dn->dn_indblkshift : dn->dn_datablksz;
1916                 db->db.db_size = blocksize;
1917                 db->db.db_offset = db->db_blkid * blocksize;
1918         }
1919 
1920         /*
1921          * Hold the dn_dbufs_mtx while we get the new dbuf
1922          * in the hash table *and* added to the dbufs list.
1923          * This prevents a possible deadlock with someone
1924          * trying to look up this dbuf before its added to the
1925          * dn_dbufs list.
1926          */
1927         mutex_enter(&dn->dn_dbufs_mtx);
1928         db->db_state = DB_EVICTING;
1929         if ((odb = dbuf_hash_insert(db)) != NULL) {
1930                 /* someone else inserted it first */
1931                 kmem_cache_free(dbuf_cache, db);
1932                 mutex_exit(&dn->dn_dbufs_mtx);
1933                 return (odb);
1934         }
1935         avl_add(&dn->dn_dbufs, db);
1936         if (db->db_level == 0 && db->db_blkid >=
1937             dn->dn_unlisted_l0_blkid)
1938                 dn->dn_unlisted_l0_blkid = db->db_blkid + 1;
1939         db->db_state = DB_UNCACHED;
1940         mutex_exit(&dn->dn_dbufs_mtx);
1941         arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
1942 
1943         if (parent && parent != dn->dn_dbuf)
1944                 dbuf_add_ref(parent, db);
1945 
1946         ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
1947             refcount_count(&dn->dn_holds) > 0);
1948         (void) refcount_add(&dn->dn_holds, db);
1949         atomic_inc_32(&dn->dn_dbufs_count);
1950 
1951         dprintf_dbuf(db, "db=%p\n", db);
1952 
1953         return (db);
1954 }
1955 
1956 static int
1957 dbuf_do_evict(void *private)
1958 {
1959         dmu_buf_impl_t *db = private;
1960 
1961         if (!MUTEX_HELD(&db->db_mtx))
1962                 mutex_enter(&db->db_mtx);
1963 
1964         ASSERT(refcount_is_zero(&db->db_holds));
1965 
1966         if (db->db_state != DB_EVICTING) {
1967                 ASSERT(db->db_state == DB_CACHED);
1968                 DBUF_VERIFY(db);
1969                 db->db_buf = NULL;
1970                 dbuf_evict(db);
1971         } else {
1972                 mutex_exit(&db->db_mtx);
1973                 dbuf_destroy(db);
1974         }
1975         return (0);
1976 }
1977 
1978 static void
1979 dbuf_destroy(dmu_buf_impl_t *db)
1980 {
1981         ASSERT(refcount_is_zero(&db->db_holds));
1982 
1983         if (db->db_blkid != DMU_BONUS_BLKID) {
1984                 /*
1985                  * If this dbuf is still on the dn_dbufs list,
1986                  * remove it from that list.
1987                  */
1988                 if (db->db_dnode_handle != NULL) {
1989                         dnode_t *dn;
1990 
1991                         DB_DNODE_ENTER(db);
1992                         dn = DB_DNODE(db);
1993                         mutex_enter(&dn->dn_dbufs_mtx);
1994                         avl_remove(&dn->dn_dbufs, db);
1995                         atomic_dec_32(&dn->dn_dbufs_count);
1996                         mutex_exit(&dn->dn_dbufs_mtx);
1997                         DB_DNODE_EXIT(db);
1998                         /*
1999                          * Decrementing the dbuf count means that the hold
2000                          * corresponding to the removed dbuf is no longer
2001                          * discounted in dnode_move(), so the dnode cannot be
2002                          * moved until after we release the hold.
2003                          */
2004                         dnode_rele(dn, db);
2005                         db->db_dnode_handle = NULL;
2006                 }
2007                 dbuf_hash_remove(db);
2008         }
2009         db->db_parent = NULL;
2010         db->db_buf = NULL;
2011 
2012         ASSERT(db->db.db_data == NULL);
2013         ASSERT(db->db_hash_next == NULL);
2014         ASSERT(db->db_blkptr == NULL);
2015         ASSERT(db->db_data_pending == NULL);
2016 
2017         kmem_cache_free(dbuf_cache, db);
2018         arc_space_return(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
2019 }
2020 
2021 typedef struct dbuf_prefetch_arg {
2022         spa_t *dpa_spa; /* The spa to issue the prefetch in. */
2023         zbookmark_phys_t dpa_zb; /* The target block to prefetch. */
2024         int dpa_epbs; /* Entries (blkptr_t's) Per Block Shift. */
2025         int dpa_curlevel; /* The current level that we're reading */
2026         zio_priority_t dpa_prio; /* The priority I/Os should be issued at. */
2027         zio_t *dpa_zio; /* The parent zio_t for all prefetches. */
2028         arc_flags_t dpa_aflags; /* Flags to pass to the final prefetch. */
2029 } dbuf_prefetch_arg_t;
2030 
2031 /*
2032  * Actually issue the prefetch read for the block given.
2033  */
2034 static void
2035 dbuf_issue_final_prefetch(dbuf_prefetch_arg_t *dpa, blkptr_t *bp)
2036 {
2037         if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2038                 return;
2039 
2040         arc_flags_t aflags =
2041             dpa->dpa_aflags | ARC_FLAG_NOWAIT | ARC_FLAG_PREFETCH;
2042 
2043         ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
2044         ASSERT3U(dpa->dpa_curlevel, ==, dpa->dpa_zb.zb_level);
2045         ASSERT(dpa->dpa_zio != NULL);
2046         (void) arc_read(dpa->dpa_zio, dpa->dpa_spa, bp, NULL, NULL,
2047             dpa->dpa_prio, ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2048             &aflags, &dpa->dpa_zb);
2049 }
2050 
2051 /*
2052  * Called when an indirect block above our prefetch target is read in.  This
2053  * will either read in the next indirect block down the tree or issue the actual
2054  * prefetch if the next block down is our target.
2055  */
2056 static void
2057 dbuf_prefetch_indirect_done(zio_t *zio, arc_buf_t *abuf, void *private)
2058 {
2059         dbuf_prefetch_arg_t *dpa = private;
2060 
2061         ASSERT3S(dpa->dpa_zb.zb_level, <, dpa->dpa_curlevel);
2062         ASSERT3S(dpa->dpa_curlevel, >, 0);
2063         if (zio != NULL) {
2064                 ASSERT3S(BP_GET_LEVEL(zio->io_bp), ==, dpa->dpa_curlevel);
2065                 ASSERT3U(BP_GET_LSIZE(zio->io_bp), ==, zio->io_size);
2066                 ASSERT3P(zio->io_spa, ==, dpa->dpa_spa);
2067         }
2068 
2069         dpa->dpa_curlevel--;
2070 
2071         uint64_t nextblkid = dpa->dpa_zb.zb_blkid >>
2072             (dpa->dpa_epbs * (dpa->dpa_curlevel - dpa->dpa_zb.zb_level));
2073         blkptr_t *bp = ((blkptr_t *)abuf->b_data) +
2074             P2PHASE(nextblkid, 1ULL << dpa->dpa_epbs);
2075         if (BP_IS_HOLE(bp) || (zio != NULL && zio->io_error != 0)) {
2076                 kmem_free(dpa, sizeof (*dpa));
2077         } else if (dpa->dpa_curlevel == dpa->dpa_zb.zb_level) {
2078                 ASSERT3U(nextblkid, ==, dpa->dpa_zb.zb_blkid);
2079                 dbuf_issue_final_prefetch(dpa, bp);
2080                 kmem_free(dpa, sizeof (*dpa));
2081         } else {
2082                 arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
2083                 zbookmark_phys_t zb;
2084 
2085                 ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
2086 
2087                 SET_BOOKMARK(&zb, dpa->dpa_zb.zb_objset,
2088                     dpa->dpa_zb.zb_object, dpa->dpa_curlevel, nextblkid);
2089 
2090                 (void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
2091                     bp, dbuf_prefetch_indirect_done, dpa, dpa->dpa_prio,
2092                     ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2093                     &iter_aflags, &zb);
2094         }
2095         (void) arc_buf_remove_ref(abuf, private);
2096 }
2097 
2098 /*
2099  * Issue prefetch reads for the given block on the given level.  If the indirect
2100  * blocks above that block are not in memory, we will read them in
2101  * asynchronously.  As a result, this call never blocks waiting for a read to
2102  * complete.
2103  */
2104 void
2105 dbuf_prefetch(dnode_t *dn, int64_t level, uint64_t blkid, zio_priority_t prio,
2106     arc_flags_t aflags)
2107 {
2108         blkptr_t bp;
2109         int epbs, nlevels, curlevel;
2110         uint64_t curblkid;
2111 
2112         ASSERT(blkid != DMU_BONUS_BLKID);
2113         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2114 
2115         if (blkid > dn->dn_maxblkid)
2116                 return;
2117 
2118         if (dnode_block_freed(dn, blkid))
2119                 return;
2120 
2121         /*
2122          * This dnode hasn't been written to disk yet, so there's nothing to
2123          * prefetch.
2124          */
2125         nlevels = dn->dn_phys->dn_nlevels;
2126         if (level >= nlevels || dn->dn_phys->dn_nblkptr == 0)
2127                 return;
2128 
2129         epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2130         if (dn->dn_phys->dn_maxblkid < blkid << (epbs * level))
2131                 return;
2132 
2133         dmu_buf_impl_t *db = dbuf_find(dn->dn_objset, dn->dn_object,
2134             level, blkid);
2135         if (db != NULL) {
2136                 mutex_exit(&db->db_mtx);
2137                 /*
2138                  * This dbuf already exists.  It is either CACHED, or
2139                  * (we assume) about to be read or filled.
2140                  */
2141                 return;
2142         }
2143 
2144         /*
2145          * Find the closest ancestor (indirect block) of the target block
2146          * that is present in the cache.  In this indirect block, we will
2147          * find the bp that is at curlevel, curblkid.
2148          */
2149         curlevel = level;
2150         curblkid = blkid;
2151         while (curlevel < nlevels - 1) {
2152                 int parent_level = curlevel + 1;
2153                 uint64_t parent_blkid = curblkid >> epbs;
2154                 dmu_buf_impl_t *db;
2155 
2156                 if (dbuf_hold_impl(dn, parent_level, parent_blkid,
2157                     FALSE, TRUE, FTAG, &db) == 0) {
2158                         blkptr_t *bpp = db->db_buf->b_data;
2159                         bp = bpp[P2PHASE(curblkid, 1 << epbs)];
2160                         dbuf_rele(db, FTAG);
2161                         break;
2162                 }
2163 
2164                 curlevel = parent_level;
2165                 curblkid = parent_blkid;
2166         }
2167 
2168         if (curlevel == nlevels - 1) {
2169                 /* No cached indirect blocks found. */
2170                 ASSERT3U(curblkid, <, dn->dn_phys->dn_nblkptr);
2171                 bp = dn->dn_phys->dn_blkptr[curblkid];
2172         }
2173         if (BP_IS_HOLE(&bp))
2174                 return;
2175 
2176         ASSERT3U(curlevel, ==, BP_GET_LEVEL(&bp));
2177 
2178         zio_t *pio = zio_root(dmu_objset_spa(dn->dn_objset), NULL, NULL,
2179             ZIO_FLAG_CANFAIL);
2180 
2181         dbuf_prefetch_arg_t *dpa = kmem_zalloc(sizeof (*dpa), KM_SLEEP);
2182         dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
2183         SET_BOOKMARK(&dpa->dpa_zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
2184             dn->dn_object, level, blkid);
2185         dpa->dpa_curlevel = curlevel;
2186         dpa->dpa_prio = prio;
2187         dpa->dpa_aflags = aflags;
2188         dpa->dpa_spa = dn->dn_objset->os_spa;
2189         dpa->dpa_epbs = epbs;
2190         dpa->dpa_zio = pio;
2191 
2192         /*
2193          * If we have the indirect just above us, no need to do the asynchronous
2194          * prefetch chain; we'll just run the last step ourselves.  If we're at
2195          * a higher level, though, we want to issue the prefetches for all the
2196          * indirect blocks asynchronously, so we can go on with whatever we were
2197          * doing.
2198          */
2199         if (curlevel == level) {
2200                 ASSERT3U(curblkid, ==, blkid);
2201                 dbuf_issue_final_prefetch(dpa, &bp);
2202                 kmem_free(dpa, sizeof (*dpa));
2203         } else {
2204                 arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
2205                 zbookmark_phys_t zb;
2206 
2207                 SET_BOOKMARK(&zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
2208                     dn->dn_object, curlevel, curblkid);
2209                 (void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
2210                     &bp, dbuf_prefetch_indirect_done, dpa, prio,
2211                     ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2212                     &iter_aflags, &zb);
2213         }
2214         /*
2215          * We use pio here instead of dpa_zio since it's possible that
2216          * dpa may have already been freed.
2217          */
2218         zio_nowait(pio);
2219 }
2220 
2221 /*
2222  * Returns with db_holds incremented, and db_mtx not held.
2223  * Note: dn_struct_rwlock must be held.
2224  */
2225 int
2226 dbuf_hold_impl(dnode_t *dn, uint8_t level, uint64_t blkid,
2227     boolean_t fail_sparse, boolean_t fail_uncached,
2228     void *tag, dmu_buf_impl_t **dbp)
2229 {
2230         dmu_buf_impl_t *db, *parent = NULL;
2231 
2232         ASSERT(blkid != DMU_BONUS_BLKID);
2233         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2234         ASSERT3U(dn->dn_nlevels, >, level);
2235 
2236         *dbp = NULL;
2237 top:
2238         /* dbuf_find() returns with db_mtx held */
2239         db = dbuf_find(dn->dn_objset, dn->dn_object, level, blkid);
2240 
2241         if (db == NULL) {
2242                 blkptr_t *bp = NULL;
2243                 int err;
2244 
2245                 if (fail_uncached)
2246                         return (SET_ERROR(ENOENT));
2247 
2248                 ASSERT3P(parent, ==, NULL);
2249                 err = dbuf_findbp(dn, level, blkid, fail_sparse, &parent, &bp);
2250                 if (fail_sparse) {
2251                         if (err == 0 && bp && BP_IS_HOLE(bp))
2252                                 err = SET_ERROR(ENOENT);
2253                         if (err) {
2254                                 if (parent)
2255                                         dbuf_rele(parent, NULL);
2256                                 return (err);
2257                         }
2258                 }
2259                 if (err && err != ENOENT)
2260                         return (err);
2261                 db = dbuf_create(dn, level, blkid, parent, bp);
2262         }
2263 
2264         if (fail_uncached && db->db_state != DB_CACHED) {
2265                 mutex_exit(&db->db_mtx);
2266                 return (SET_ERROR(ENOENT));
2267         }
2268 
2269         if (db->db_buf && refcount_is_zero(&db->db_holds)) {
2270                 arc_buf_add_ref(db->db_buf, db);
2271                 if (db->db_buf->b_data == NULL) {
2272                         dbuf_clear(db);
2273                         if (parent) {
2274                                 dbuf_rele(parent, NULL);
2275                                 parent = NULL;
2276                         }
2277                         goto top;
2278                 }
2279                 ASSERT3P(db->db.db_data, ==, db->db_buf->b_data);
2280         }
2281 
2282         ASSERT(db->db_buf == NULL || arc_referenced(db->db_buf));
2283 
2284         /*
2285          * If this buffer is currently syncing out, and we are are
2286          * still referencing it from db_data, we need to make a copy
2287          * of it in case we decide we want to dirty it again in this txg.
2288          */
2289         if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
2290             dn->dn_object != DMU_META_DNODE_OBJECT &&
2291             db->db_state == DB_CACHED && db->db_data_pending) {
2292                 dbuf_dirty_record_t *dr = db->db_data_pending;
2293 
2294                 if (dr->dt.dl.dr_data == db->db_buf) {
2295                         arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
2296 
2297                         dbuf_set_data(db,
2298                             arc_buf_alloc(dn->dn_objset->os_spa,
2299                             db->db.db_size, db, type));
2300                         bcopy(dr->dt.dl.dr_data->b_data, db->db.db_data,
2301                             db->db.db_size);
2302                 }
2303         }
2304 
2305         (void) refcount_add(&db->db_holds, tag);
2306         DBUF_VERIFY(db);
2307         mutex_exit(&db->db_mtx);
2308 
2309         /* NOTE: we can't rele the parent until after we drop the db_mtx */
2310         if (parent)
2311                 dbuf_rele(parent, NULL);
2312 
2313         ASSERT3P(DB_DNODE(db), ==, dn);
2314         ASSERT3U(db->db_blkid, ==, blkid);
2315         ASSERT3U(db->db_level, ==, level);
2316         *dbp = db;
2317 
2318         return (0);
2319 }
2320 
2321 dmu_buf_impl_t *
2322 dbuf_hold(dnode_t *dn, uint64_t blkid, void *tag)
2323 {
2324         return (dbuf_hold_level(dn, 0, blkid, tag));
2325 }
2326 
2327 dmu_buf_impl_t *
2328 dbuf_hold_level(dnode_t *dn, int level, uint64_t blkid, void *tag)
2329 {
2330         dmu_buf_impl_t *db;
2331         int err = dbuf_hold_impl(dn, level, blkid, FALSE, FALSE, tag, &db);
2332         return (err ? NULL : db);
2333 }
2334 
2335 void
2336 dbuf_create_bonus(dnode_t *dn)
2337 {
2338         ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
2339 
2340         ASSERT(dn->dn_bonus == NULL);
2341         dn->dn_bonus = dbuf_create(dn, 0, DMU_BONUS_BLKID, dn->dn_dbuf, NULL);
2342 }
2343 
2344 int
2345 dbuf_spill_set_blksz(dmu_buf_t *db_fake, uint64_t blksz, dmu_tx_t *tx)
2346 {
2347         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2348         dnode_t *dn;
2349 
2350         if (db->db_blkid != DMU_SPILL_BLKID)
2351                 return (SET_ERROR(ENOTSUP));
2352         if (blksz == 0)
2353                 blksz = SPA_MINBLOCKSIZE;
2354         ASSERT3U(blksz, <=, spa_maxblocksize(dmu_objset_spa(db->db_objset)));
2355         blksz = P2ROUNDUP(blksz, SPA_MINBLOCKSIZE);
2356 
2357         DB_DNODE_ENTER(db);
2358         dn = DB_DNODE(db);
2359         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
2360         dbuf_new_size(db, blksz, tx);
2361         rw_exit(&dn->dn_struct_rwlock);
2362         DB_DNODE_EXIT(db);
2363 
2364         return (0);
2365 }
2366 
2367 void
2368 dbuf_rm_spill(dnode_t *dn, dmu_tx_t *tx)
2369 {
2370         dbuf_free_range(dn, DMU_SPILL_BLKID, DMU_SPILL_BLKID, tx);
2371 }
2372 
2373 #pragma weak dmu_buf_add_ref = dbuf_add_ref
2374 void
2375 dbuf_add_ref(dmu_buf_impl_t *db, void *tag)
2376 {
2377         int64_t holds = refcount_add(&db->db_holds, tag);
2378         ASSERT(holds > 1);
2379 }
2380 
2381 #pragma weak dmu_buf_try_add_ref = dbuf_try_add_ref
2382 boolean_t
2383 dbuf_try_add_ref(dmu_buf_t *db_fake, objset_t *os, uint64_t obj, uint64_t blkid,
2384     void *tag)
2385 {
2386         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2387         dmu_buf_impl_t *found_db;
2388         boolean_t result = B_FALSE;
2389 
2390         if (db->db_blkid == DMU_BONUS_BLKID)
2391                 found_db = dbuf_find_bonus(os, obj);
2392         else
2393                 found_db = dbuf_find(os, obj, 0, blkid);
2394 
2395         if (found_db != NULL) {
2396                 if (db == found_db && dbuf_refcount(db) > db->db_dirtycnt) {
2397                         (void) refcount_add(&db->db_holds, tag);
2398                         result = B_TRUE;
2399                 }
2400                 mutex_exit(&db->db_mtx);
2401         }
2402         return (result);
2403 }
2404 
2405 /*
2406  * If you call dbuf_rele() you had better not be referencing the dnode handle
2407  * unless you have some other direct or indirect hold on the dnode. (An indirect
2408  * hold is a hold on one of the dnode's dbufs, including the bonus buffer.)
2409  * Without that, the dbuf_rele() could lead to a dnode_rele() followed by the
2410  * dnode's parent dbuf evicting its dnode handles.
2411  */
2412 void
2413 dbuf_rele(dmu_buf_impl_t *db, void *tag)
2414 {
2415         mutex_enter(&db->db_mtx);
2416         dbuf_rele_and_unlock(db, tag);
2417 }
2418 
2419 void
2420 dmu_buf_rele(dmu_buf_t *db, void *tag)
2421 {
2422         dbuf_rele((dmu_buf_impl_t *)db, tag);
2423 }
2424 
2425 /*
2426  * dbuf_rele() for an already-locked dbuf.  This is necessary to allow
2427  * db_dirtycnt and db_holds to be updated atomically.
2428  */
2429 void
2430 dbuf_rele_and_unlock(dmu_buf_impl_t *db, void *tag)
2431 {
2432         int64_t holds;
2433 
2434         ASSERT(MUTEX_HELD(&db->db_mtx));
2435         DBUF_VERIFY(db);
2436 
2437         /*
2438          * Remove the reference to the dbuf before removing its hold on the
2439          * dnode so we can guarantee in dnode_move() that a referenced bonus
2440          * buffer has a corresponding dnode hold.
2441          */
2442         holds = refcount_remove(&db->db_holds, tag);
2443         ASSERT(holds >= 0);
2444 
2445         /*
2446          * We can't freeze indirects if there is a possibility that they
2447          * may be modified in the current syncing context.
2448          */
2449         if (db->db_buf && holds == (db->db_level == 0 ? db->db_dirtycnt : 0))
2450                 arc_buf_freeze(db->db_buf);
2451 
2452         if (holds == db->db_dirtycnt &&
2453             db->db_level == 0 && db->db_user_immediate_evict)
2454                 dbuf_evict_user(db);
2455 
2456         if (holds == 0) {
2457                 if (db->db_blkid == DMU_BONUS_BLKID) {
2458                         dnode_t *dn;
2459                         boolean_t evict_dbuf = db->db_pending_evict;
2460 
2461                         /*
2462                          * If the dnode moves here, we cannot cross this
2463                          * barrier until the move completes.
2464                          */
2465                         DB_DNODE_ENTER(db);
2466 
2467                         dn = DB_DNODE(db);
2468                         atomic_dec_32(&dn->dn_dbufs_count);
2469 
2470                         /*
2471                          * Decrementing the dbuf count means that the bonus
2472                          * buffer's dnode hold is no longer discounted in
2473                          * dnode_move(). The dnode cannot move until after
2474                          * the dnode_rele() below.
2475                          */
2476                         DB_DNODE_EXIT(db);
2477 
2478                         /*
2479                          * Do not reference db after its lock is dropped.
2480                          * Another thread may evict it.
2481                          */
2482                         mutex_exit(&db->db_mtx);
2483 
2484                         if (evict_dbuf)
2485                                 dnode_evict_bonus(dn);
2486 
2487                         dnode_rele(dn, db);
2488                 } else if (db->db_buf == NULL) {
2489                         /*
2490                          * This is a special case: we never associated this
2491                          * dbuf with any data allocated from the ARC.
2492                          */
2493                         ASSERT(db->db_state == DB_UNCACHED ||
2494                             db->db_state == DB_NOFILL);
2495                         dbuf_evict(db);
2496                 } else if (arc_released(db->db_buf)) {
2497                         arc_buf_t *buf = db->db_buf;
2498                         /*
2499                          * This dbuf has anonymous data associated with it.
2500                          */
2501                         dbuf_clear_data(db);
2502                         VERIFY(arc_buf_remove_ref(buf, db));
2503                         dbuf_evict(db);
2504                 } else {
2505                         VERIFY(!arc_buf_remove_ref(db->db_buf, db));
2506 
2507                         /*
2508                          * A dbuf will be eligible for eviction if either the
2509                          * 'primarycache' property is set or a duplicate
2510                          * copy of this buffer is already cached in the arc.
2511                          *
2512                          * In the case of the 'primarycache' a buffer
2513                          * is considered for eviction if it matches the
2514                          * criteria set in the property.
2515                          *
2516                          * To decide if our buffer is considered a
2517                          * duplicate, we must call into the arc to determine
2518                          * if multiple buffers are referencing the same
2519                          * block on-disk. If so, then we simply evict
2520                          * ourselves.
2521                          */
2522                         if (!DBUF_IS_CACHEABLE(db)) {
2523                                 if (db->db_blkptr != NULL &&
2524                                     !BP_IS_HOLE(db->db_blkptr) &&
2525                                     !BP_IS_EMBEDDED(db->db_blkptr)) {
2526                                         spa_t *spa =
2527                                             dmu_objset_spa(db->db_objset);
2528                                         blkptr_t bp = *db->db_blkptr;
2529                                         dbuf_clear(db);
2530                                         arc_freed(spa, &bp);
2531                                 } else {
2532                                         dbuf_clear(db);
2533                                 }
2534                         } else if (db->db_pending_evict ||
2535                             arc_buf_eviction_needed(db->db_buf)) {
2536                                 dbuf_clear(db);
2537                         } else {
2538                                 mutex_exit(&db->db_mtx);
2539                         }
2540                 }
2541         } else {
2542                 mutex_exit(&db->db_mtx);
2543         }
2544 }
2545 
2546 #pragma weak dmu_buf_refcount = dbuf_refcount
2547 uint64_t
2548 dbuf_refcount(dmu_buf_impl_t *db)
2549 {
2550         return (refcount_count(&db->db_holds));
2551 }
2552 
2553 void *
2554 dmu_buf_replace_user(dmu_buf_t *db_fake, dmu_buf_user_t *old_user,
2555     dmu_buf_user_t *new_user)
2556 {
2557         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2558 
2559         mutex_enter(&db->db_mtx);
2560         dbuf_verify_user(db, DBVU_NOT_EVICTING);
2561         if (db->db_user == old_user)
2562                 db->db_user = new_user;
2563         else
2564                 old_user = db->db_user;
2565         dbuf_verify_user(db, DBVU_NOT_EVICTING);
2566         mutex_exit(&db->db_mtx);
2567 
2568         return (old_user);
2569 }
2570 
2571 void *
2572 dmu_buf_set_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
2573 {
2574         return (dmu_buf_replace_user(db_fake, NULL, user));
2575 }
2576 
2577 void *
2578 dmu_buf_set_user_ie(dmu_buf_t *db_fake, dmu_buf_user_t *user)
2579 {
2580         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2581 
2582         db->db_user_immediate_evict = TRUE;
2583         return (dmu_buf_set_user(db_fake, user));
2584 }
2585 
2586 void *
2587 dmu_buf_remove_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
2588 {
2589         return (dmu_buf_replace_user(db_fake, user, NULL));
2590 }
2591 
2592 void *
2593 dmu_buf_get_user(dmu_buf_t *db_fake)
2594 {
2595         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2596 
2597         dbuf_verify_user(db, DBVU_NOT_EVICTING);
2598         return (db->db_user);
2599 }
2600 
2601 void
2602 dmu_buf_user_evict_wait()
2603 {
2604         taskq_wait(dbu_evict_taskq);
2605 }
2606 
2607 boolean_t
2608 dmu_buf_freeable(dmu_buf_t *dbuf)
2609 {
2610         boolean_t res = B_FALSE;
2611         dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
2612 
2613         if (db->db_blkptr)
2614                 res = dsl_dataset_block_freeable(db->db_objset->os_dsl_dataset,
2615                     db->db_blkptr, db->db_blkptr->blk_birth);
2616 
2617         return (res);
2618 }
2619 
2620 blkptr_t *
2621 dmu_buf_get_blkptr(dmu_buf_t *db)
2622 {
2623         dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
2624         return (dbi->db_blkptr);
2625 }
2626 
2627 static void
2628 dbuf_check_blkptr(dnode_t *dn, dmu_buf_impl_t *db)
2629 {
2630         /* ASSERT(dmu_tx_is_syncing(tx) */
2631         ASSERT(MUTEX_HELD(&db->db_mtx));
2632 
2633         if (db->db_blkptr != NULL)
2634                 return;
2635 
2636         if (db->db_blkid == DMU_SPILL_BLKID) {
2637                 db->db_blkptr = &dn->dn_phys->dn_spill;
2638                 BP_ZERO(db->db_blkptr);
2639                 return;
2640         }
2641         if (db->db_level == dn->dn_phys->dn_nlevels-1) {
2642                 /*
2643                  * This buffer was allocated at a time when there was
2644                  * no available blkptrs from the dnode, or it was
2645                  * inappropriate to hook it in (i.e., nlevels mis-match).
2646                  */
2647                 ASSERT(db->db_blkid < dn->dn_phys->dn_nblkptr);
2648                 ASSERT(db->db_parent == NULL);
2649                 db->db_parent = dn->dn_dbuf;
2650                 db->db_blkptr = &dn->dn_phys->dn_blkptr[db->db_blkid];
2651                 DBUF_VERIFY(db);
2652         } else {
2653                 dmu_buf_impl_t *parent = db->db_parent;
2654                 int epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2655 
2656                 ASSERT(dn->dn_phys->dn_nlevels > 1);
2657                 if (parent == NULL) {
2658                         mutex_exit(&db->db_mtx);
2659                         rw_enter(&dn->dn_struct_rwlock, RW_READER);
2660                         parent = dbuf_hold_level(dn, db->db_level + 1,
2661                             db->db_blkid >> epbs, db);
2662                         rw_exit(&dn->dn_struct_rwlock);
2663                         mutex_enter(&db->db_mtx);
2664                         db->db_parent = parent;
2665                 }
2666                 db->db_blkptr = (blkptr_t *)parent->db.db_data +
2667                     (db->db_blkid & ((1ULL << epbs) - 1));
2668                 DBUF_VERIFY(db);
2669         }
2670 }
2671 
2672 static void
2673 dbuf_sync_indirect(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
2674 {
2675         dmu_buf_impl_t *db = dr->dr_dbuf;
2676         dnode_t *dn;
2677         zio_t *zio;
2678 
2679         ASSERT(dmu_tx_is_syncing(tx));
2680 
2681         dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
2682 
2683         mutex_enter(&db->db_mtx);
2684 
2685         ASSERT(db->db_level > 0);
2686         DBUF_VERIFY(db);
2687 
2688         /* Read the block if it hasn't been read yet. */
2689         if (db->db_buf == NULL) {
2690                 mutex_exit(&db->db_mtx);
2691                 (void) dbuf_read(db, NULL, DB_RF_MUST_SUCCEED);
2692                 mutex_enter(&db->db_mtx);
2693         }
2694         ASSERT3U(db->db_state, ==, DB_CACHED);
2695         ASSERT(db->db_buf != NULL);
2696 
2697         DB_DNODE_ENTER(db);
2698         dn = DB_DNODE(db);
2699         /* Indirect block size must match what the dnode thinks it is. */
2700         ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
2701         dbuf_check_blkptr(dn, db);
2702         DB_DNODE_EXIT(db);
2703 
2704         /* Provide the pending dirty record to child dbufs */
2705         db->db_data_pending = dr;
2706 
2707         mutex_exit(&db->db_mtx);
2708         dbuf_write(dr, db->db_buf, tx);
2709 
2710         zio = dr->dr_zio;
2711         mutex_enter(&dr->dt.di.dr_mtx);
2712         dbuf_sync_list(&dr->dt.di.dr_children, db->db_level - 1, tx);
2713         ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
2714         mutex_exit(&dr->dt.di.dr_mtx);
2715         zio_nowait(zio);
2716 }
2717 
2718 static void
2719 dbuf_sync_leaf(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
2720 {
2721         arc_buf_t **datap = &dr->dt.dl.dr_data;
2722         dmu_buf_impl_t *db = dr->dr_dbuf;
2723         dnode_t *dn;
2724         objset_t *os;
2725         uint64_t txg = tx->tx_txg;
2726 
2727         ASSERT(dmu_tx_is_syncing(tx));
2728 
2729         dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
2730 
2731         mutex_enter(&db->db_mtx);
2732         /*
2733          * To be synced, we must be dirtied.  But we
2734          * might have been freed after the dirty.
2735          */
2736         if (db->db_state == DB_UNCACHED) {
2737                 /* This buffer has been freed since it was dirtied */
2738                 ASSERT(db->db.db_data == NULL);
2739         } else if (db->db_state == DB_FILL) {
2740                 /* This buffer was freed and is now being re-filled */
2741                 ASSERT(db->db.db_data != dr->dt.dl.dr_data);
2742         } else {
2743                 ASSERT(db->db_state == DB_CACHED || db->db_state == DB_NOFILL);
2744         }
2745         DBUF_VERIFY(db);
2746 
2747         DB_DNODE_ENTER(db);
2748         dn = DB_DNODE(db);
2749 
2750         if (db->db_blkid == DMU_SPILL_BLKID) {
2751                 mutex_enter(&dn->dn_mtx);
2752                 dn->dn_phys->dn_flags |= DNODE_FLAG_SPILL_BLKPTR;
2753                 mutex_exit(&dn->dn_mtx);
2754         }
2755 
2756         /*
2757          * If this is a bonus buffer, simply copy the bonus data into the
2758          * dnode.  It will be written out when the dnode is synced (and it
2759          * will be synced, since it must have been dirty for dbuf_sync to
2760          * be called).
2761          */
2762         if (db->db_blkid == DMU_BONUS_BLKID) {
2763                 dbuf_dirty_record_t **drp;
2764 
2765                 ASSERT(*datap != NULL);
2766                 ASSERT0(db->db_level);
2767                 ASSERT3U(dn->dn_phys->dn_bonuslen, <=, DN_MAX_BONUSLEN);
2768                 bcopy(*datap, DN_BONUS(dn->dn_phys), dn->dn_phys->dn_bonuslen);
2769                 DB_DNODE_EXIT(db);
2770 
2771                 if (*datap != db->db.db_data) {
2772                         zio_buf_free(*datap, DN_MAX_BONUSLEN);
2773                         arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
2774                 }
2775                 db->db_data_pending = NULL;
2776                 drp = &db->db_last_dirty;
2777                 while (*drp != dr)
2778                         drp = &(*drp)->dr_next;
2779                 ASSERT(dr->dr_next == NULL);
2780                 ASSERT(dr->dr_dbuf == db);
2781                 *drp = dr->dr_next;
2782                 kmem_free(dr, sizeof (dbuf_dirty_record_t));
2783                 ASSERT(db->db_dirtycnt > 0);
2784                 db->db_dirtycnt -= 1;
2785                 dbuf_rele_and_unlock(db, (void *)(uintptr_t)txg);
2786                 return;
2787         }
2788 
2789         os = dn->dn_objset;
2790 
2791         /*
2792          * This function may have dropped the db_mtx lock allowing a dmu_sync
2793          * operation to sneak in. As a result, we need to ensure that we
2794          * don't check the dr_override_state until we have returned from
2795          * dbuf_check_blkptr.
2796          */
2797         dbuf_check_blkptr(dn, db);
2798 
2799         /*
2800          * If this buffer is in the middle of an immediate write,
2801          * wait for the synchronous IO to complete.
2802          */
2803         while (dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC) {
2804                 ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
2805                 cv_wait(&db->db_changed, &db->db_mtx);
2806                 ASSERT(dr->dt.dl.dr_override_state != DR_NOT_OVERRIDDEN);
2807         }
2808 
2809         if (db->db_state != DB_NOFILL &&
2810             dn->dn_object != DMU_META_DNODE_OBJECT &&
2811             refcount_count(&db->db_holds) > 1 &&
2812             dr->dt.dl.dr_override_state != DR_OVERRIDDEN &&
2813             *datap == db->db_buf) {
2814                 /*
2815                  * If this buffer is currently "in use" (i.e., there
2816                  * are active holds and db_data still references it),
2817                  * then make a copy before we start the write so that
2818                  * any modifications from the open txg will not leak
2819                  * into this write.
2820                  *
2821                  * NOTE: this copy does not need to be made for
2822                  * objects only modified in the syncing context (e.g.
2823                  * DNONE_DNODE blocks).
2824                  */
2825                 int blksz = arc_buf_size(*datap);
2826                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
2827                 *datap = arc_buf_alloc(os->os_spa, blksz, db, type);
2828                 bcopy(db->db.db_data, (*datap)->b_data, blksz);
2829         }
2830         db->db_data_pending = dr;
2831 
2832         mutex_exit(&db->db_mtx);
2833 
2834         dbuf_write(dr, *datap, tx);
2835 
2836         ASSERT(!list_link_active(&dr->dr_dirty_node));
2837         if (dn->dn_object == DMU_META_DNODE_OBJECT) {
2838                 list_insert_tail(&dn->dn_dirty_records[txg&TXG_MASK], dr);
2839                 DB_DNODE_EXIT(db);
2840         } else {
2841                 /*
2842                  * Although zio_nowait() does not "wait for an IO", it does
2843                  * initiate the IO. If this is an empty write it seems plausible
2844                  * that the IO could actually be completed before the nowait
2845                  * returns. We need to DB_DNODE_EXIT() first in case
2846                  * zio_nowait() invalidates the dbuf.
2847                  */
2848                 DB_DNODE_EXIT(db);
2849                 zio_nowait(dr->dr_zio);
2850         }
2851 }
2852 
2853 void
2854 dbuf_sync_list(list_t *list, int level, dmu_tx_t *tx)
2855 {
2856         dbuf_dirty_record_t *dr;
2857 
2858         while (dr = list_head(list)) {
2859                 if (dr->dr_zio != NULL) {
2860                         /*
2861                          * If we find an already initialized zio then we
2862                          * are processing the meta-dnode, and we have finished.
2863                          * The dbufs for all dnodes are put back on the list
2864                          * during processing, so that we can zio_wait()
2865                          * these IOs after initiating all child IOs.
2866                          */
2867                         ASSERT3U(dr->dr_dbuf->db.db_object, ==,
2868                             DMU_META_DNODE_OBJECT);
2869                         break;
2870                 }
2871                 if (dr->dr_dbuf->db_blkid != DMU_BONUS_BLKID &&
2872                     dr->dr_dbuf->db_blkid != DMU_SPILL_BLKID) {
2873                         VERIFY3U(dr->dr_dbuf->db_level, ==, level);
2874                 }
2875                 list_remove(list, dr);
2876                 if (dr->dr_dbuf->db_level > 0)
2877                         dbuf_sync_indirect(dr, tx);
2878                 else
2879                         dbuf_sync_leaf(dr, tx);
2880         }
2881 }
2882 
2883 /* ARGSUSED */
2884 static void
2885 dbuf_write_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
2886 {
2887         dmu_buf_impl_t *db = vdb;
2888         dnode_t *dn;
2889         blkptr_t *bp = zio->io_bp;
2890         blkptr_t *bp_orig = &zio->io_bp_orig;
2891         spa_t *spa = zio->io_spa;
2892         int64_t delta;
2893         uint64_t fill = 0;
2894         int i;
2895 
2896         ASSERT3P(db->db_blkptr, ==, bp);
2897 
2898         DB_DNODE_ENTER(db);
2899         dn = DB_DNODE(db);
2900         delta = bp_get_dsize_sync(spa, bp) - bp_get_dsize_sync(spa, bp_orig);
2901         dnode_diduse_space(dn, delta - zio->io_prev_space_delta);
2902         zio->io_prev_space_delta = delta;
2903 
2904         if (bp->blk_birth != 0) {
2905                 ASSERT((db->db_blkid != DMU_SPILL_BLKID &&
2906                     BP_GET_TYPE(bp) == dn->dn_type) ||
2907                     (db->db_blkid == DMU_SPILL_BLKID &&
2908                     BP_GET_TYPE(bp) == dn->dn_bonustype) ||
2909                     BP_IS_EMBEDDED(bp));
2910                 ASSERT(BP_GET_LEVEL(bp) == db->db_level);
2911         }
2912 
2913         mutex_enter(&db->db_mtx);
2914 
2915 #ifdef ZFS_DEBUG
2916         if (db->db_blkid == DMU_SPILL_BLKID) {
2917                 ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
2918                 ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
2919                     db->db_blkptr == &dn->dn_phys->dn_spill);
2920         }
2921 #endif
2922 
2923         if (db->db_level == 0) {
2924                 mutex_enter(&dn->dn_mtx);
2925                 if (db->db_blkid > dn->dn_phys->dn_maxblkid &&
2926                     db->db_blkid != DMU_SPILL_BLKID)
2927                         dn->dn_phys->dn_maxblkid = db->db_blkid;
2928                 mutex_exit(&dn->dn_mtx);
2929 
2930                 if (dn->dn_type == DMU_OT_DNODE) {
2931                         dnode_phys_t *dnp = db->db.db_data;
2932                         for (i = db->db.db_size >> DNODE_SHIFT; i > 0;
2933                             i--, dnp++) {
2934                                 if (dnp->dn_type != DMU_OT_NONE)
2935                                         fill++;
2936                         }
2937                 } else {
2938                         if (BP_IS_HOLE(bp)) {
2939                                 fill = 0;
2940                         } else {
2941                                 fill = 1;
2942                         }
2943                 }
2944         } else {
2945                 blkptr_t *ibp = db->db.db_data;
2946                 ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
2947                 for (i = db->db.db_size >> SPA_BLKPTRSHIFT; i > 0; i--, ibp++) {
2948                         if (BP_IS_HOLE(ibp))
2949                                 continue;
2950                         fill += BP_GET_FILL(ibp);
2951                 }
2952         }
2953         DB_DNODE_EXIT(db);
2954 
2955         if (!BP_IS_EMBEDDED(bp))
2956                 bp->blk_fill = fill;
2957 
2958         mutex_exit(&db->db_mtx);
2959 }
2960 
2961 /*
2962  * The SPA will call this callback several times for each zio - once
2963  * for every physical child i/o (zio->io_phys_children times).  This
2964  * allows the DMU to monitor the progress of each logical i/o.  For example,
2965  * there may be 2 copies of an indirect block, or many fragments of a RAID-Z
2966  * block.  There may be a long delay before all copies/fragments are completed,
2967  * so this callback allows us to retire dirty space gradually, as the physical
2968  * i/os complete.
2969  */
2970 /* ARGSUSED */
2971 static void
2972 dbuf_write_physdone(zio_t *zio, arc_buf_t *buf, void *arg)
2973 {
2974         dmu_buf_impl_t *db = arg;
2975         objset_t *os = db->db_objset;
2976         dsl_pool_t *dp = dmu_objset_pool(os);
2977         dbuf_dirty_record_t *dr;
2978         int delta = 0;
2979 
2980         dr = db->db_data_pending;
2981         ASSERT3U(dr->dr_txg, ==, zio->io_txg);
2982 
2983         /*
2984          * The callback will be called io_phys_children times.  Retire one
2985          * portion of our dirty space each time we are called.  Any rounding
2986          * error will be cleaned up by dsl_pool_sync()'s call to
2987          * dsl_pool_undirty_space().
2988          */
2989         delta = dr->dr_accounted / zio->io_phys_children;
2990         dsl_pool_undirty_space(dp, delta, zio->io_txg);
2991 }
2992 
2993 /* ARGSUSED */
2994 static void
2995 dbuf_write_done(zio_t *zio, arc_buf_t *buf, void *vdb)
2996 {
2997         dmu_buf_impl_t *db = vdb;
2998         blkptr_t *bp_orig = &zio->io_bp_orig;
2999         blkptr_t *bp = db->db_blkptr;
3000         objset_t *os = db->db_objset;
3001         dmu_tx_t *tx = os->os_synctx;
3002         dbuf_dirty_record_t **drp, *dr;
3003 
3004         ASSERT0(zio->io_error);
3005         ASSERT(db->db_blkptr == bp);
3006 
3007         /*
3008          * For nopwrites and rewrites we ensure that the bp matches our
3009          * original and bypass all the accounting.
3010          */
3011         if (zio->io_flags & (ZIO_FLAG_IO_REWRITE | ZIO_FLAG_NOPWRITE)) {
3012                 ASSERT(BP_EQUAL(bp, bp_orig));
3013         } else {
3014                 dsl_dataset_t *ds = os->os_dsl_dataset;
3015                 (void) dsl_dataset_block_kill(ds, bp_orig, tx, B_TRUE);
3016                 dsl_dataset_block_born(ds, bp, tx);
3017         }
3018 
3019         mutex_enter(&db->db_mtx);
3020 
3021         DBUF_VERIFY(db);
3022 
3023         drp = &db->db_last_dirty;
3024         while ((dr = *drp) != db->db_data_pending)
3025                 drp = &dr->dr_next;
3026         ASSERT(!list_link_active(&dr->dr_dirty_node));
3027         ASSERT(dr->dr_dbuf == db);
3028         ASSERT(dr->dr_next == NULL);
3029         *drp = dr->dr_next;
3030 
3031 #ifdef ZFS_DEBUG
3032         if (db->db_blkid == DMU_SPILL_BLKID) {
3033                 dnode_t *dn;
3034 
3035                 DB_DNODE_ENTER(db);
3036                 dn = DB_DNODE(db);
3037                 ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
3038                 ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
3039                     db->db_blkptr == &dn->dn_phys->dn_spill);
3040                 DB_DNODE_EXIT(db);
3041         }
3042 #endif
3043 
3044         if (db->db_level == 0) {
3045                 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
3046                 ASSERT(dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN);
3047                 if (db->db_state != DB_NOFILL) {
3048                         if (dr->dt.dl.dr_data != db->db_buf)
3049                                 VERIFY(arc_buf_remove_ref(dr->dt.dl.dr_data,
3050                                     db));
3051                         else if (!arc_released(db->db_buf))
3052                                 arc_set_callback(db->db_buf, dbuf_do_evict, db);
3053                 }
3054         } else {
3055                 dnode_t *dn;
3056 
3057                 DB_DNODE_ENTER(db);
3058                 dn = DB_DNODE(db);
3059                 ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
3060                 ASSERT3U(db->db.db_size, ==, 1 << dn->dn_phys->dn_indblkshift);
3061                 if (!BP_IS_HOLE(db->db_blkptr)) {
3062                         int epbs =
3063                             dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3064                         ASSERT3U(db->db_blkid, <=,
3065                             dn->dn_phys->dn_maxblkid >> (db->db_level * epbs));
3066                         ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
3067                             db->db.db_size);
3068                         if (!arc_released(db->db_buf))
3069                                 arc_set_callback(db->db_buf, dbuf_do_evict, db);
3070                 }
3071                 DB_DNODE_EXIT(db);
3072                 mutex_destroy(&dr->dt.di.dr_mtx);
3073                 list_destroy(&dr->dt.di.dr_children);
3074         }
3075         kmem_free(dr, sizeof (dbuf_dirty_record_t));
3076 
3077         cv_broadcast(&db->db_changed);
3078         ASSERT(db->db_dirtycnt > 0);
3079         db->db_dirtycnt -= 1;
3080         db->db_data_pending = NULL;
3081         dbuf_rele_and_unlock(db, (void *)(uintptr_t)tx->tx_txg);
3082 }
3083 
3084 static void
3085 dbuf_write_nofill_ready(zio_t *zio)
3086 {
3087         dbuf_write_ready(zio, NULL, zio->io_private);
3088 }
3089 
3090 static void
3091 dbuf_write_nofill_done(zio_t *zio)
3092 {
3093         dbuf_write_done(zio, NULL, zio->io_private);
3094 }
3095 
3096 static void
3097 dbuf_write_override_ready(zio_t *zio)
3098 {
3099         dbuf_dirty_record_t *dr = zio->io_private;
3100         dmu_buf_impl_t *db = dr->dr_dbuf;
3101 
3102         dbuf_write_ready(zio, NULL, db);
3103 }
3104 
3105 static void
3106 dbuf_write_override_done(zio_t *zio)
3107 {
3108         dbuf_dirty_record_t *dr = zio->io_private;
3109         dmu_buf_impl_t *db = dr->dr_dbuf;
3110         blkptr_t *obp = &dr->dt.dl.dr_overridden_by;
3111 
3112         mutex_enter(&db->db_mtx);
3113         if (!BP_EQUAL(zio->io_bp, obp)) {
3114                 if (!BP_IS_HOLE(obp))
3115                         dsl_free(spa_get_dsl(zio->io_spa), zio->io_txg, obp);
3116                 arc_release(dr->dt.dl.dr_data, db);
3117         }
3118         mutex_exit(&db->db_mtx);
3119 
3120         dbuf_write_done(zio, NULL, db);
3121 }
3122 
3123 /* Issue I/O to commit a dirty buffer to disk. */
3124 static void
3125 dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx)
3126 {
3127         dmu_buf_impl_t *db = dr->dr_dbuf;
3128         dnode_t *dn;
3129         objset_t *os;
3130         dmu_buf_impl_t *parent = db->db_parent;
3131         uint64_t txg = tx->tx_txg;
3132         zbookmark_phys_t zb;
3133         zio_prop_t zp;
3134         zio_t *zio;
3135         int wp_flag = 0;
3136 
3137         DB_DNODE_ENTER(db);
3138         dn = DB_DNODE(db);
3139         os = dn->dn_objset;
3140 
3141         if (db->db_state != DB_NOFILL) {
3142                 if (db->db_level > 0 || dn->dn_type == DMU_OT_DNODE) {
3143                         /*
3144                          * Private object buffers are released here rather
3145                          * than in dbuf_dirty() since they are only modified
3146                          * in the syncing context and we don't want the
3147                          * overhead of making multiple copies of the data.
3148                          */
3149                         if (BP_IS_HOLE(db->db_blkptr)) {
3150                                 arc_buf_thaw(data);
3151                         } else {
3152                                 dbuf_release_bp(db);
3153                         }
3154                 }
3155         }
3156 
3157         if (parent != dn->dn_dbuf) {
3158                 /* Our parent is an indirect block. */
3159                 /* We have a dirty parent that has been scheduled for write. */
3160                 ASSERT(parent && parent->db_data_pending);
3161                 /* Our parent's buffer is one level closer to the dnode. */
3162                 ASSERT(db->db_level == parent->db_level-1);
3163                 /*
3164                  * We're about to modify our parent's db_data by modifying
3165                  * our block pointer, so the parent must be released.
3166                  */
3167                 ASSERT(arc_released(parent->db_buf));
3168                 zio = parent->db_data_pending->dr_zio;
3169         } else {
3170                 /* Our parent is the dnode itself. */
3171                 ASSERT((db->db_level == dn->dn_phys->dn_nlevels-1 &&
3172                     db->db_blkid != DMU_SPILL_BLKID) ||
3173                     (db->db_blkid == DMU_SPILL_BLKID && db->db_level == 0));
3174                 if (db->db_blkid != DMU_SPILL_BLKID)
3175                         ASSERT3P(db->db_blkptr, ==,
3176                             &dn->dn_phys->dn_blkptr[db->db_blkid]);
3177                 zio = dn->dn_zio;
3178         }
3179 
3180         ASSERT(db->db_level == 0 || data == db->db_buf);
3181         ASSERT3U(db->db_blkptr->blk_birth, <=, txg);
3182         ASSERT(zio);
3183 
3184         SET_BOOKMARK(&zb, os->os_dsl_dataset ?
3185             os->os_dsl_dataset->ds_object : DMU_META_OBJSET,
3186             db->db.db_object, db->db_level, db->db_blkid);
3187 
3188         if (db->db_blkid == DMU_SPILL_BLKID)
3189                 wp_flag = WP_SPILL;
3190         wp_flag |= (db->db_state == DB_NOFILL) ? WP_NOFILL : 0;
3191 
3192         dmu_write_policy(os, dn, db->db_level, wp_flag, &zp);
3193         DB_DNODE_EXIT(db);
3194 
3195         if (db->db_level == 0 &&
3196             dr->dt.dl.dr_override_state == DR_OVERRIDDEN) {
3197                 /*
3198                  * The BP for this block has been provided by open context
3199                  * (by dmu_sync() or dmu_buf_write_embedded()).
3200                  */
3201                 void *contents = (data != NULL) ? data->b_data : NULL;
3202 
3203                 dr->dr_zio = zio_write(zio, os->os_spa, txg,
3204                     db->db_blkptr, contents, db->db.db_size, &zp,
3205                     dbuf_write_override_ready, NULL, dbuf_write_override_done,
3206                     dr, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
3207                 mutex_enter(&db->db_mtx);
3208                 dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
3209                 zio_write_override(dr->dr_zio, &dr->dt.dl.dr_overridden_by,
3210                     dr->dt.dl.dr_copies, dr->dt.dl.dr_nopwrite);
3211                 mutex_exit(&db->db_mtx);
3212         } else if (db->db_state == DB_NOFILL) {
3213                 ASSERT(zp.zp_checksum == ZIO_CHECKSUM_OFF ||
3214                     zp.zp_checksum == ZIO_CHECKSUM_NOPARITY);
3215                 dr->dr_zio = zio_write(zio, os->os_spa, txg,
3216                     db->db_blkptr, NULL, db->db.db_size, &zp,
3217                     dbuf_write_nofill_ready, NULL, dbuf_write_nofill_done, db,
3218                     ZIO_PRIORITY_ASYNC_WRITE,
3219                     ZIO_FLAG_MUSTSUCCEED | ZIO_FLAG_NODATA, &zb);
3220         } else {
3221                 ASSERT(arc_released(data));
3222                 dr->dr_zio = arc_write(zio, os->os_spa, txg,
3223                     db->db_blkptr, data, DBUF_IS_L2CACHEABLE(db),
3224                     DBUF_IS_L2COMPRESSIBLE(db), &zp, dbuf_write_ready,
3225                     dbuf_write_physdone, dbuf_write_done, db,
3226                     ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
3227         }
3228 }