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