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