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