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 (c) 2012 by Delphix. All rights reserved.
  24  * Copyright (c) 2012, Joyent, Inc. All rights reserved.
  25  */
  26 
  27 #include <sys/dmu_objset.h>
  28 #include <sys/dsl_dataset.h>
  29 #include <sys/dsl_dir.h>
  30 #include <sys/dsl_prop.h>
  31 #include <sys/dsl_synctask.h>
  32 #include <sys/dmu_traverse.h>
  33 #include <sys/dmu_impl.h>
  34 #include <sys/dmu_tx.h>
  35 #include <sys/arc.h>
  36 #include <sys/zio.h>
  37 #include <sys/zap.h>
  38 #include <sys/zfeature.h>
  39 #include <sys/unique.h>
  40 #include <sys/zfs_context.h>
  41 #include <sys/zfs_ioctl.h>
  42 #include <sys/spa.h>
  43 #include <sys/zfs_znode.h>
  44 #include <sys/zfs_onexit.h>
  45 #include <sys/zvol.h>
  46 #include <sys/dsl_scan.h>
  47 #include <sys/dsl_deadlist.h>
  48 
  49 static char *dsl_reaper = "the grim reaper";
  50 
  51 static dsl_checkfunc_t dsl_dataset_destroy_begin_check;
  52 static dsl_syncfunc_t dsl_dataset_destroy_begin_sync;
  53 static dsl_syncfunc_t dsl_dataset_set_reservation_sync;
  54 
  55 #define SWITCH64(x, y) \
  56         { \
  57                 uint64_t __tmp = (x); \
  58                 (x) = (y); \
  59                 (y) = __tmp; \
  60         }
  61 
  62 #define DS_REF_MAX      (1ULL << 62)
  63 
  64 #define DSL_DEADLIST_BLOCKSIZE  SPA_MAXBLOCKSIZE
  65 
  66 #define DSL_DATASET_IS_DESTROYED(ds)    ((ds)->ds_owner == dsl_reaper)
  67 
  68 
  69 /*
  70  * Figure out how much of this delta should be propogated to the dsl_dir
  71  * layer.  If there's a refreservation, that space has already been
  72  * partially accounted for in our ancestors.
  73  */
  74 static int64_t
  75 parent_delta(dsl_dataset_t *ds, int64_t delta)
  76 {
  77         uint64_t old_bytes, new_bytes;
  78 
  79         if (ds->ds_reserved == 0)
  80                 return (delta);
  81 
  82         old_bytes = MAX(ds->ds_phys->ds_unique_bytes, ds->ds_reserved);
  83         new_bytes = MAX(ds->ds_phys->ds_unique_bytes + delta, ds->ds_reserved);
  84 
  85         ASSERT3U(ABS((int64_t)(new_bytes - old_bytes)), <=, ABS(delta));
  86         return (new_bytes - old_bytes);
  87 }
  88 
  89 void
  90 dsl_dataset_block_born(dsl_dataset_t *ds, const blkptr_t *bp, dmu_tx_t *tx)
  91 {
  92         int used = bp_get_dsize_sync(tx->tx_pool->dp_spa, bp);
  93         int compressed = BP_GET_PSIZE(bp);
  94         int uncompressed = BP_GET_UCSIZE(bp);
  95         int64_t delta;
  96 
  97         dprintf_bp(bp, "ds=%p", ds);
  98 
  99         ASSERT(dmu_tx_is_syncing(tx));
 100         /* It could have been compressed away to nothing */
 101         if (BP_IS_HOLE(bp))
 102                 return;
 103         ASSERT(BP_GET_TYPE(bp) != DMU_OT_NONE);
 104         ASSERT(DMU_OT_IS_VALID(BP_GET_TYPE(bp)));
 105         if (ds == NULL) {
 106                 /*
 107                  * Account for the meta-objset space in its placeholder
 108                  * dsl_dir.
 109                  */
 110                 ASSERT3U(compressed, ==, uncompressed); /* it's all metadata */
 111                 dsl_dir_diduse_space(tx->tx_pool->dp_mos_dir, DD_USED_HEAD,
 112                     used, compressed, uncompressed, tx);
 113                 dsl_dir_dirty(tx->tx_pool->dp_mos_dir, tx);
 114                 return;
 115         }
 116         dmu_buf_will_dirty(ds->ds_dbuf, tx);
 117 
 118         mutex_enter(&ds->ds_dir->dd_lock);
 119         mutex_enter(&ds->ds_lock);
 120         delta = parent_delta(ds, used);
 121         ds->ds_phys->ds_referenced_bytes += used;
 122         ds->ds_phys->ds_compressed_bytes += compressed;
 123         ds->ds_phys->ds_uncompressed_bytes += uncompressed;
 124         ds->ds_phys->ds_unique_bytes += used;
 125         mutex_exit(&ds->ds_lock);
 126         dsl_dir_diduse_space(ds->ds_dir, DD_USED_HEAD, delta,
 127             compressed, uncompressed, tx);
 128         dsl_dir_transfer_space(ds->ds_dir, used - delta,
 129             DD_USED_REFRSRV, DD_USED_HEAD, tx);
 130         mutex_exit(&ds->ds_dir->dd_lock);
 131 }
 132 
 133 int
 134 dsl_dataset_block_kill(dsl_dataset_t *ds, const blkptr_t *bp, dmu_tx_t *tx,
 135     boolean_t async)
 136 {
 137         if (BP_IS_HOLE(bp))
 138                 return (0);
 139 
 140         ASSERT(dmu_tx_is_syncing(tx));
 141         ASSERT(bp->blk_birth <= tx->tx_txg);
 142 
 143         int used = bp_get_dsize_sync(tx->tx_pool->dp_spa, bp);
 144         int compressed = BP_GET_PSIZE(bp);
 145         int uncompressed = BP_GET_UCSIZE(bp);
 146 
 147         ASSERT(used > 0);
 148         if (ds == NULL) {
 149                 /*
 150                  * Account for the meta-objset space in its placeholder
 151                  * dataset.
 152                  */
 153                 dsl_free(tx->tx_pool, tx->tx_txg, bp);
 154 
 155                 dsl_dir_diduse_space(tx->tx_pool->dp_mos_dir, DD_USED_HEAD,
 156                     -used, -compressed, -uncompressed, tx);
 157                 dsl_dir_dirty(tx->tx_pool->dp_mos_dir, tx);
 158                 return (used);
 159         }
 160         ASSERT3P(tx->tx_pool, ==, ds->ds_dir->dd_pool);
 161 
 162         ASSERT(!dsl_dataset_is_snapshot(ds));
 163         dmu_buf_will_dirty(ds->ds_dbuf, tx);
 164 
 165         if (bp->blk_birth > ds->ds_phys->ds_prev_snap_txg) {
 166                 int64_t delta;
 167 
 168                 dprintf_bp(bp, "freeing ds=%llu", ds->ds_object);
 169                 dsl_free(tx->tx_pool, tx->tx_txg, bp);
 170 
 171                 mutex_enter(&ds->ds_dir->dd_lock);
 172                 mutex_enter(&ds->ds_lock);
 173                 ASSERT(ds->ds_phys->ds_unique_bytes >= used ||
 174                     !DS_UNIQUE_IS_ACCURATE(ds));
 175                 delta = parent_delta(ds, -used);
 176                 ds->ds_phys->ds_unique_bytes -= used;
 177                 mutex_exit(&ds->ds_lock);
 178                 dsl_dir_diduse_space(ds->ds_dir, DD_USED_HEAD,
 179                     delta, -compressed, -uncompressed, tx);
 180                 dsl_dir_transfer_space(ds->ds_dir, -used - delta,
 181                     DD_USED_REFRSRV, DD_USED_HEAD, tx);
 182                 mutex_exit(&ds->ds_dir->dd_lock);
 183         } else {
 184                 dprintf_bp(bp, "putting on dead list: %s", "");
 185                 if (async) {
 186                         /*
 187                          * We are here as part of zio's write done callback,
 188                          * which means we're a zio interrupt thread.  We can't
 189                          * call dsl_deadlist_insert() now because it may block
 190                          * waiting for I/O.  Instead, put bp on the deferred
 191                          * queue and let dsl_pool_sync() finish the job.
 192                          */
 193                         bplist_append(&ds->ds_pending_deadlist, bp);
 194                 } else {
 195                         dsl_deadlist_insert(&ds->ds_deadlist, bp, tx);
 196                 }
 197                 ASSERT3U(ds->ds_prev->ds_object, ==,
 198                     ds->ds_phys->ds_prev_snap_obj);
 199                 ASSERT(ds->ds_prev->ds_phys->ds_num_children > 0);
 200                 /* if (bp->blk_birth > prev prev snap txg) prev unique += bs */
 201                 if (ds->ds_prev->ds_phys->ds_next_snap_obj ==
 202                     ds->ds_object && bp->blk_birth >
 203                     ds->ds_prev->ds_phys->ds_prev_snap_txg) {
 204                         dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
 205                         mutex_enter(&ds->ds_prev->ds_lock);
 206                         ds->ds_prev->ds_phys->ds_unique_bytes += used;
 207                         mutex_exit(&ds->ds_prev->ds_lock);
 208                 }
 209                 if (bp->blk_birth > ds->ds_dir->dd_origin_txg) {
 210                         dsl_dir_transfer_space(ds->ds_dir, used,
 211                             DD_USED_HEAD, DD_USED_SNAP, tx);
 212                 }
 213         }
 214         mutex_enter(&ds->ds_lock);
 215         ASSERT3U(ds->ds_phys->ds_referenced_bytes, >=, used);
 216         ds->ds_phys->ds_referenced_bytes -= used;
 217         ASSERT3U(ds->ds_phys->ds_compressed_bytes, >=, compressed);
 218         ds->ds_phys->ds_compressed_bytes -= compressed;
 219         ASSERT3U(ds->ds_phys->ds_uncompressed_bytes, >=, uncompressed);
 220         ds->ds_phys->ds_uncompressed_bytes -= uncompressed;
 221         mutex_exit(&ds->ds_lock);
 222 
 223         return (used);
 224 }
 225 
 226 uint64_t
 227 dsl_dataset_prev_snap_txg(dsl_dataset_t *ds)
 228 {
 229         uint64_t trysnap = 0;
 230 
 231         if (ds == NULL)
 232                 return (0);
 233         /*
 234          * The snapshot creation could fail, but that would cause an
 235          * incorrect FALSE return, which would only result in an
 236          * overestimation of the amount of space that an operation would
 237          * consume, which is OK.
 238          *
 239          * There's also a small window where we could miss a pending
 240          * snapshot, because we could set the sync task in the quiescing
 241          * phase.  So this should only be used as a guess.
 242          */
 243         if (ds->ds_trysnap_txg >
 244             spa_last_synced_txg(ds->ds_dir->dd_pool->dp_spa))
 245                 trysnap = ds->ds_trysnap_txg;
 246         return (MAX(ds->ds_phys->ds_prev_snap_txg, trysnap));
 247 }
 248 
 249 boolean_t
 250 dsl_dataset_block_freeable(dsl_dataset_t *ds, const blkptr_t *bp,
 251     uint64_t blk_birth)
 252 {
 253         if (blk_birth <= dsl_dataset_prev_snap_txg(ds))
 254                 return (B_FALSE);
 255 
 256         ddt_prefetch(dsl_dataset_get_spa(ds), bp);
 257 
 258         return (B_TRUE);
 259 }
 260 
 261 /* ARGSUSED */
 262 static void
 263 dsl_dataset_evict(dmu_buf_t *db, void *dsv)
 264 {
 265         dsl_dataset_t *ds = dsv;
 266 
 267         ASSERT(ds->ds_owner == NULL || DSL_DATASET_IS_DESTROYED(ds));
 268 
 269         unique_remove(ds->ds_fsid_guid);
 270 
 271         if (ds->ds_objset != NULL)
 272                 dmu_objset_evict(ds->ds_objset);
 273 
 274         if (ds->ds_prev) {
 275                 dsl_dataset_drop_ref(ds->ds_prev, ds);
 276                 ds->ds_prev = NULL;
 277         }
 278 
 279         bplist_destroy(&ds->ds_pending_deadlist);
 280         if (db != NULL) {
 281                 dsl_deadlist_close(&ds->ds_deadlist);
 282         } else {
 283                 ASSERT(ds->ds_deadlist.dl_dbuf == NULL);
 284                 ASSERT(!ds->ds_deadlist.dl_oldfmt);
 285         }
 286         if (ds->ds_dir)
 287                 dsl_dir_close(ds->ds_dir, ds);
 288 
 289         ASSERT(!list_link_active(&ds->ds_synced_link));
 290 
 291         mutex_destroy(&ds->ds_lock);
 292         mutex_destroy(&ds->ds_recvlock);
 293         mutex_destroy(&ds->ds_opening_lock);
 294         rw_destroy(&ds->ds_rwlock);
 295         cv_destroy(&ds->ds_exclusive_cv);
 296 
 297         kmem_free(ds, sizeof (dsl_dataset_t));
 298 }
 299 
 300 static int
 301 dsl_dataset_get_snapname(dsl_dataset_t *ds)
 302 {
 303         dsl_dataset_phys_t *headphys;
 304         int err;
 305         dmu_buf_t *headdbuf;
 306         dsl_pool_t *dp = ds->ds_dir->dd_pool;
 307         objset_t *mos = dp->dp_meta_objset;
 308 
 309         if (ds->ds_snapname[0])
 310                 return (0);
 311         if (ds->ds_phys->ds_next_snap_obj == 0)
 312                 return (0);
 313 
 314         err = dmu_bonus_hold(mos, ds->ds_dir->dd_phys->dd_head_dataset_obj,
 315             FTAG, &headdbuf);
 316         if (err)
 317                 return (err);
 318         headphys = headdbuf->db_data;
 319         err = zap_value_search(dp->dp_meta_objset,
 320             headphys->ds_snapnames_zapobj, ds->ds_object, 0, ds->ds_snapname);
 321         dmu_buf_rele(headdbuf, FTAG);
 322         return (err);
 323 }
 324 
 325 static int
 326 dsl_dataset_snap_lookup(dsl_dataset_t *ds, const char *name, uint64_t *value)
 327 {
 328         objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
 329         uint64_t snapobj = ds->ds_phys->ds_snapnames_zapobj;
 330         matchtype_t mt;
 331         int err;
 332 
 333         if (ds->ds_phys->ds_flags & DS_FLAG_CI_DATASET)
 334                 mt = MT_FIRST;
 335         else
 336                 mt = MT_EXACT;
 337 
 338         err = zap_lookup_norm(mos, snapobj, name, 8, 1,
 339             value, mt, NULL, 0, NULL);
 340         if (err == ENOTSUP && mt == MT_FIRST)
 341                 err = zap_lookup(mos, snapobj, name, 8, 1, value);
 342         return (err);
 343 }
 344 
 345 static int
 346 dsl_dataset_snap_remove(dsl_dataset_t *ds, char *name, dmu_tx_t *tx)
 347 {
 348         objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
 349         uint64_t snapobj = ds->ds_phys->ds_snapnames_zapobj;
 350         matchtype_t mt;
 351         int err;
 352 
 353         dsl_dir_snap_cmtime_update(ds->ds_dir);
 354 
 355         if (ds->ds_phys->ds_flags & DS_FLAG_CI_DATASET)
 356                 mt = MT_FIRST;
 357         else
 358                 mt = MT_EXACT;
 359 
 360         err = zap_remove_norm(mos, snapobj, name, mt, tx);
 361         if (err == ENOTSUP && mt == MT_FIRST)
 362                 err = zap_remove(mos, snapobj, name, tx);
 363         return (err);
 364 }
 365 
 366 static int
 367 dsl_dataset_get_ref(dsl_pool_t *dp, uint64_t dsobj, void *tag,
 368     dsl_dataset_t **dsp)
 369 {
 370         objset_t *mos = dp->dp_meta_objset;
 371         dmu_buf_t *dbuf;
 372         dsl_dataset_t *ds;
 373         int err;
 374         dmu_object_info_t doi;
 375 
 376         ASSERT(RW_LOCK_HELD(&dp->dp_config_rwlock) ||
 377             dsl_pool_sync_context(dp));
 378 
 379         err = dmu_bonus_hold(mos, dsobj, tag, &dbuf);
 380         if (err)
 381                 return (err);
 382 
 383         /* Make sure dsobj has the correct object type. */
 384         dmu_object_info_from_db(dbuf, &doi);
 385         if (doi.doi_type != DMU_OT_DSL_DATASET)
 386                 return (EINVAL);
 387 
 388         ds = dmu_buf_get_user(dbuf);
 389         if (ds == NULL) {
 390                 dsl_dataset_t *winner;
 391 
 392                 ds = kmem_zalloc(sizeof (dsl_dataset_t), KM_SLEEP);
 393                 ds->ds_dbuf = dbuf;
 394                 ds->ds_object = dsobj;
 395                 ds->ds_phys = dbuf->db_data;
 396 
 397                 mutex_init(&ds->ds_lock, NULL, MUTEX_DEFAULT, NULL);
 398                 mutex_init(&ds->ds_recvlock, NULL, MUTEX_DEFAULT, NULL);
 399                 mutex_init(&ds->ds_opening_lock, NULL, MUTEX_DEFAULT, NULL);
 400                 mutex_init(&ds->ds_sendstream_lock, NULL, MUTEX_DEFAULT, NULL);
 401 
 402                 rw_init(&ds->ds_rwlock, 0, 0, 0);
 403                 cv_init(&ds->ds_exclusive_cv, NULL, CV_DEFAULT, NULL);
 404 
 405                 bplist_create(&ds->ds_pending_deadlist);
 406                 dsl_deadlist_open(&ds->ds_deadlist,
 407                     mos, ds->ds_phys->ds_deadlist_obj);
 408 
 409                 list_create(&ds->ds_sendstreams, sizeof (dmu_sendarg_t),
 410                     offsetof(dmu_sendarg_t, dsa_link));
 411 
 412                 if (err == 0) {
 413                         err = dsl_dir_open_obj(dp,
 414                             ds->ds_phys->ds_dir_obj, NULL, ds, &ds->ds_dir);
 415                 }
 416                 if (err) {
 417                         mutex_destroy(&ds->ds_lock);
 418                         mutex_destroy(&ds->ds_recvlock);
 419                         mutex_destroy(&ds->ds_opening_lock);
 420                         rw_destroy(&ds->ds_rwlock);
 421                         cv_destroy(&ds->ds_exclusive_cv);
 422                         bplist_destroy(&ds->ds_pending_deadlist);
 423                         dsl_deadlist_close(&ds->ds_deadlist);
 424                         kmem_free(ds, sizeof (dsl_dataset_t));
 425                         dmu_buf_rele(dbuf, tag);
 426                         return (err);
 427                 }
 428 
 429                 if (!dsl_dataset_is_snapshot(ds)) {
 430                         ds->ds_snapname[0] = '\0';
 431                         if (ds->ds_phys->ds_prev_snap_obj) {
 432                                 err = dsl_dataset_get_ref(dp,
 433                                     ds->ds_phys->ds_prev_snap_obj,
 434                                     ds, &ds->ds_prev);
 435                         }
 436                 } else {
 437                         if (zfs_flags & ZFS_DEBUG_SNAPNAMES)
 438                                 err = dsl_dataset_get_snapname(ds);
 439                         if (err == 0 && ds->ds_phys->ds_userrefs_obj != 0) {
 440                                 err = zap_count(
 441                                     ds->ds_dir->dd_pool->dp_meta_objset,
 442                                     ds->ds_phys->ds_userrefs_obj,
 443                                     &ds->ds_userrefs);
 444                         }
 445                 }
 446 
 447                 if (err == 0 && !dsl_dataset_is_snapshot(ds)) {
 448                         /*
 449                          * In sync context, we're called with either no lock
 450                          * or with the write lock.  If we're not syncing,
 451                          * we're always called with the read lock held.
 452                          */
 453                         boolean_t need_lock =
 454                             !RW_WRITE_HELD(&dp->dp_config_rwlock) &&
 455                             dsl_pool_sync_context(dp);
 456 
 457                         if (need_lock)
 458                                 rw_enter(&dp->dp_config_rwlock, RW_READER);
 459 
 460                         err = dsl_prop_get_ds(ds,
 461                             "refreservation", sizeof (uint64_t), 1,
 462                             &ds->ds_reserved, NULL);
 463                         if (err == 0) {
 464                                 err = dsl_prop_get_ds(ds,
 465                                     "refquota", sizeof (uint64_t), 1,
 466                                     &ds->ds_quota, NULL);
 467                         }
 468 
 469                         if (need_lock)
 470                                 rw_exit(&dp->dp_config_rwlock);
 471                 } else {
 472                         ds->ds_reserved = ds->ds_quota = 0;
 473                 }
 474 
 475                 if (err == 0) {
 476                         winner = dmu_buf_set_user_ie(dbuf, ds, &ds->ds_phys,
 477                             dsl_dataset_evict);
 478                 }
 479                 if (err || winner) {
 480                         bplist_destroy(&ds->ds_pending_deadlist);
 481                         dsl_deadlist_close(&ds->ds_deadlist);
 482                         if (ds->ds_prev)
 483                                 dsl_dataset_drop_ref(ds->ds_prev, ds);
 484                         dsl_dir_close(ds->ds_dir, ds);
 485                         mutex_destroy(&ds->ds_lock);
 486                         mutex_destroy(&ds->ds_recvlock);
 487                         mutex_destroy(&ds->ds_opening_lock);
 488                         rw_destroy(&ds->ds_rwlock);
 489                         cv_destroy(&ds->ds_exclusive_cv);
 490                         kmem_free(ds, sizeof (dsl_dataset_t));
 491                         if (err) {
 492                                 dmu_buf_rele(dbuf, tag);
 493                                 return (err);
 494                         }
 495                         ds = winner;
 496                 } else {
 497                         ds->ds_fsid_guid =
 498                             unique_insert(ds->ds_phys->ds_fsid_guid);
 499                 }
 500         }
 501         ASSERT3P(ds->ds_dbuf, ==, dbuf);
 502         ASSERT3P(ds->ds_phys, ==, dbuf->db_data);
 503         ASSERT(ds->ds_phys->ds_prev_snap_obj != 0 ||
 504             spa_version(dp->dp_spa) < SPA_VERSION_ORIGIN ||
 505             dp->dp_origin_snap == NULL || ds == dp->dp_origin_snap);
 506         mutex_enter(&ds->ds_lock);
 507         if (!dsl_pool_sync_context(dp) && DSL_DATASET_IS_DESTROYED(ds)) {
 508                 mutex_exit(&ds->ds_lock);
 509                 dmu_buf_rele(ds->ds_dbuf, tag);
 510                 return (ENOENT);
 511         }
 512         mutex_exit(&ds->ds_lock);
 513         *dsp = ds;
 514         return (0);
 515 }
 516 
 517 static int
 518 dsl_dataset_hold_ref(dsl_dataset_t *ds, void *tag)
 519 {
 520         dsl_pool_t *dp = ds->ds_dir->dd_pool;
 521 
 522         /*
 523          * In syncing context we don't want the rwlock lock: there
 524          * may be an existing writer waiting for sync phase to
 525          * finish.  We don't need to worry about such writers, since
 526          * sync phase is single-threaded, so the writer can't be
 527          * doing anything while we are active.
 528          */
 529         if (dsl_pool_sync_context(dp)) {
 530                 ASSERT(!DSL_DATASET_IS_DESTROYED(ds));
 531                 return (0);
 532         }
 533 
 534         /*
 535          * Normal users will hold the ds_rwlock as a READER until they
 536          * are finished (i.e., call dsl_dataset_rele()).  "Owners" will
 537          * drop their READER lock after they set the ds_owner field.
 538          *
 539          * If the dataset is being destroyed, the destroy thread will
 540          * obtain a WRITER lock for exclusive access after it's done its
 541          * open-context work and then change the ds_owner to
 542          * dsl_reaper once destruction is assured.  So threads
 543          * may block here temporarily, until the "destructability" of
 544          * the dataset is determined.
 545          */
 546         ASSERT(!RW_WRITE_HELD(&dp->dp_config_rwlock));
 547         mutex_enter(&ds->ds_lock);
 548         while (!rw_tryenter(&ds->ds_rwlock, RW_READER)) {
 549                 rw_exit(&dp->dp_config_rwlock);
 550                 cv_wait(&ds->ds_exclusive_cv, &ds->ds_lock);
 551                 if (DSL_DATASET_IS_DESTROYED(ds)) {
 552                         mutex_exit(&ds->ds_lock);
 553                         dsl_dataset_drop_ref(ds, tag);
 554                         rw_enter(&dp->dp_config_rwlock, RW_READER);
 555                         return (ENOENT);
 556                 }
 557                 /*
 558                  * The dp_config_rwlock lives above the ds_lock. And
 559                  * we need to check DSL_DATASET_IS_DESTROYED() while
 560                  * holding the ds_lock, so we have to drop and reacquire
 561                  * the ds_lock here.
 562                  */
 563                 mutex_exit(&ds->ds_lock);
 564                 rw_enter(&dp->dp_config_rwlock, RW_READER);
 565                 mutex_enter(&ds->ds_lock);
 566         }
 567         mutex_exit(&ds->ds_lock);
 568         return (0);
 569 }
 570 
 571 int
 572 dsl_dataset_hold_obj(dsl_pool_t *dp, uint64_t dsobj, void *tag,
 573     dsl_dataset_t **dsp)
 574 {
 575         int err = dsl_dataset_get_ref(dp, dsobj, tag, dsp);
 576 
 577         if (err)
 578                 return (err);
 579         return (dsl_dataset_hold_ref(*dsp, tag));
 580 }
 581 
 582 int
 583 dsl_dataset_own_obj(dsl_pool_t *dp, uint64_t dsobj, boolean_t inconsistentok,
 584     void *tag, dsl_dataset_t **dsp)
 585 {
 586         int err = dsl_dataset_hold_obj(dp, dsobj, tag, dsp);
 587         if (err)
 588                 return (err);
 589         if (!dsl_dataset_tryown(*dsp, inconsistentok, tag)) {
 590                 dsl_dataset_rele(*dsp, tag);
 591                 *dsp = NULL;
 592                 return (EBUSY);
 593         }
 594         return (0);
 595 }
 596 
 597 int
 598 dsl_dataset_hold(const char *name, void *tag, dsl_dataset_t **dsp)
 599 {
 600         dsl_dir_t *dd;
 601         dsl_pool_t *dp;
 602         const char *snapname;
 603         uint64_t obj;
 604         int err = 0;
 605 
 606         err = dsl_dir_open_spa(NULL, name, FTAG, &dd, &snapname);
 607         if (err)
 608                 return (err);
 609 
 610         dp = dd->dd_pool;
 611         obj = dd->dd_phys->dd_head_dataset_obj;
 612         rw_enter(&dp->dp_config_rwlock, RW_READER);
 613         if (obj)
 614                 err = dsl_dataset_get_ref(dp, obj, tag, dsp);
 615         else
 616                 err = ENOENT;
 617         if (err)
 618                 goto out;
 619 
 620         err = dsl_dataset_hold_ref(*dsp, tag);
 621 
 622         /* we may be looking for a snapshot */
 623         if (err == 0 && snapname != NULL) {
 624                 dsl_dataset_t *ds = NULL;
 625 
 626                 if (*snapname++ != '@') {
 627                         dsl_dataset_rele(*dsp, tag);
 628                         err = ENOENT;
 629                         goto out;
 630                 }
 631 
 632                 dprintf("looking for snapshot '%s'\n", snapname);
 633                 err = dsl_dataset_snap_lookup(*dsp, snapname, &obj);
 634                 if (err == 0)
 635                         err = dsl_dataset_get_ref(dp, obj, tag, &ds);
 636                 dsl_dataset_rele(*dsp, tag);
 637 
 638                 ASSERT3U((err == 0), ==, (ds != NULL));
 639 
 640                 if (ds) {
 641                         mutex_enter(&ds->ds_lock);
 642                         if (ds->ds_snapname[0] == 0)
 643                                 (void) strlcpy(ds->ds_snapname, snapname,
 644                                     sizeof (ds->ds_snapname));
 645                         mutex_exit(&ds->ds_lock);
 646                         err = dsl_dataset_hold_ref(ds, tag);
 647                         *dsp = err ? NULL : ds;
 648                 }
 649         }
 650 out:
 651         rw_exit(&dp->dp_config_rwlock);
 652         dsl_dir_close(dd, FTAG);
 653         return (err);
 654 }
 655 
 656 int
 657 dsl_dataset_own(const char *name, boolean_t inconsistentok,
 658     void *tag, dsl_dataset_t **dsp)
 659 {
 660         int err = dsl_dataset_hold(name, tag, dsp);
 661         if (err)
 662                 return (err);
 663         if (!dsl_dataset_tryown(*dsp, inconsistentok, tag)) {
 664                 dsl_dataset_rele(*dsp, tag);
 665                 return (EBUSY);
 666         }
 667         return (0);
 668 }
 669 
 670 void
 671 dsl_dataset_name(dsl_dataset_t *ds, char *name)
 672 {
 673         if (ds == NULL) {
 674                 (void) strcpy(name, "mos");
 675         } else {
 676                 dsl_dir_name(ds->ds_dir, name);
 677                 VERIFY(0 == dsl_dataset_get_snapname(ds));
 678                 if (ds->ds_snapname[0]) {
 679                         (void) strcat(name, "@");
 680                         /*
 681                          * We use a "recursive" mutex so that we
 682                          * can call dprintf_ds() with ds_lock held.
 683                          */
 684                         if (!MUTEX_HELD(&ds->ds_lock)) {
 685                                 mutex_enter(&ds->ds_lock);
 686                                 (void) strcat(name, ds->ds_snapname);
 687                                 mutex_exit(&ds->ds_lock);
 688                         } else {
 689                                 (void) strcat(name, ds->ds_snapname);
 690                         }
 691                 }
 692         }
 693 }
 694 
 695 static int
 696 dsl_dataset_namelen(dsl_dataset_t *ds)
 697 {
 698         int result;
 699 
 700         if (ds == NULL) {
 701                 result = 3;     /* "mos" */
 702         } else {
 703                 result = dsl_dir_namelen(ds->ds_dir);
 704                 VERIFY(0 == dsl_dataset_get_snapname(ds));
 705                 if (ds->ds_snapname[0]) {
 706                         ++result;       /* adding one for the @-sign */
 707                         if (!MUTEX_HELD(&ds->ds_lock)) {
 708                                 mutex_enter(&ds->ds_lock);
 709                                 result += strlen(ds->ds_snapname);
 710                                 mutex_exit(&ds->ds_lock);
 711                         } else {
 712                                 result += strlen(ds->ds_snapname);
 713                         }
 714                 }
 715         }
 716 
 717         return (result);
 718 }
 719 
 720 void
 721 dsl_dataset_drop_ref(dsl_dataset_t *ds, void *tag)
 722 {
 723         dmu_buf_rele(ds->ds_dbuf, tag);
 724 }
 725 
 726 void
 727 dsl_dataset_rele(dsl_dataset_t *ds, void *tag)
 728 {
 729         if (!dsl_pool_sync_context(ds->ds_dir->dd_pool)) {
 730                 rw_exit(&ds->ds_rwlock);
 731         }
 732         dsl_dataset_drop_ref(ds, tag);
 733 }
 734 
 735 void
 736 dsl_dataset_disown(dsl_dataset_t *ds, void *tag)
 737 {
 738         ASSERT((ds->ds_owner == tag && ds->ds_dbuf) ||
 739             (DSL_DATASET_IS_DESTROYED(ds) && ds->ds_dbuf == NULL));
 740 
 741         mutex_enter(&ds->ds_lock);
 742         ds->ds_owner = NULL;
 743         if (RW_WRITE_HELD(&ds->ds_rwlock)) {
 744                 rw_exit(&ds->ds_rwlock);
 745                 cv_broadcast(&ds->ds_exclusive_cv);
 746         }
 747         mutex_exit(&ds->ds_lock);
 748         if (ds->ds_dbuf)
 749                 dsl_dataset_drop_ref(ds, tag);
 750         else
 751                 dsl_dataset_evict(NULL, ds);
 752 }
 753 
 754 boolean_t
 755 dsl_dataset_tryown(dsl_dataset_t *ds, boolean_t inconsistentok, void *tag)
 756 {
 757         boolean_t gotit = FALSE;
 758 
 759         mutex_enter(&ds->ds_lock);
 760         if (ds->ds_owner == NULL &&
 761             (!DS_IS_INCONSISTENT(ds) || inconsistentok)) {
 762                 ds->ds_owner = tag;
 763                 if (!dsl_pool_sync_context(ds->ds_dir->dd_pool))
 764                         rw_exit(&ds->ds_rwlock);
 765                 gotit = TRUE;
 766         }
 767         mutex_exit(&ds->ds_lock);
 768         return (gotit);
 769 }
 770 
 771 void
 772 dsl_dataset_make_exclusive(dsl_dataset_t *ds, void *owner)
 773 {
 774         ASSERT3P(owner, ==, ds->ds_owner);
 775         if (!RW_WRITE_HELD(&ds->ds_rwlock))
 776                 rw_enter(&ds->ds_rwlock, RW_WRITER);
 777 }
 778 
 779 uint64_t
 780 dsl_dataset_create_sync_dd(dsl_dir_t *dd, dsl_dataset_t *origin,
 781     uint64_t flags, dmu_tx_t *tx)
 782 {
 783         dsl_pool_t *dp = dd->dd_pool;
 784         dmu_buf_t *dbuf;
 785         dsl_dataset_phys_t *dsphys;
 786         uint64_t dsobj;
 787         objset_t *mos = dp->dp_meta_objset;
 788 
 789         if (origin == NULL)
 790                 origin = dp->dp_origin_snap;
 791 
 792         ASSERT(origin == NULL || origin->ds_dir->dd_pool == dp);
 793         ASSERT(origin == NULL || origin->ds_phys->ds_num_children > 0);
 794         ASSERT(dmu_tx_is_syncing(tx));
 795         ASSERT(dd->dd_phys->dd_head_dataset_obj == 0);
 796 
 797         dsobj = dmu_object_alloc(mos, DMU_OT_DSL_DATASET, 0,
 798             DMU_OT_DSL_DATASET, sizeof (dsl_dataset_phys_t), tx);
 799         VERIFY(0 == dmu_bonus_hold(mos, dsobj, FTAG, &dbuf));
 800         dmu_buf_will_dirty(dbuf, tx);
 801         dsphys = dbuf->db_data;
 802         bzero(dsphys, sizeof (dsl_dataset_phys_t));
 803         dsphys->ds_dir_obj = dd->dd_object;
 804         dsphys->ds_flags = flags;
 805         dsphys->ds_fsid_guid = unique_create();
 806         do {
 807                 (void) random_get_pseudo_bytes((void*)&dsphys->ds_guid,
 808                     sizeof (dsphys->ds_guid));
 809         } while (dsphys->ds_guid == 0);
 810         dsphys->ds_snapnames_zapobj =
 811             zap_create_norm(mos, U8_TEXTPREP_TOUPPER, DMU_OT_DSL_DS_SNAP_MAP,
 812             DMU_OT_NONE, 0, tx);
 813         dsphys->ds_creation_time = gethrestime_sec();
 814         dsphys->ds_creation_txg = tx->tx_txg == TXG_INITIAL ? 1 : tx->tx_txg;
 815 
 816         if (origin == NULL) {
 817                 dsphys->ds_deadlist_obj = dsl_deadlist_alloc(mos, tx);
 818         } else {
 819                 dsl_dataset_t *ohds;
 820 
 821                 dsphys->ds_prev_snap_obj = origin->ds_object;
 822                 dsphys->ds_prev_snap_txg =
 823                     origin->ds_phys->ds_creation_txg;
 824                 dsphys->ds_referenced_bytes =
 825                     origin->ds_phys->ds_referenced_bytes;
 826                 dsphys->ds_compressed_bytes =
 827                     origin->ds_phys->ds_compressed_bytes;
 828                 dsphys->ds_uncompressed_bytes =
 829                     origin->ds_phys->ds_uncompressed_bytes;
 830                 dsphys->ds_bp = origin->ds_phys->ds_bp;
 831                 dsphys->ds_flags |= origin->ds_phys->ds_flags;
 832 
 833                 dmu_buf_will_dirty(origin->ds_dbuf, tx);
 834                 origin->ds_phys->ds_num_children++;
 835 
 836                 VERIFY3U(0, ==, dsl_dataset_hold_obj(dp,
 837                     origin->ds_dir->dd_phys->dd_head_dataset_obj, FTAG, &ohds));
 838                 dsphys->ds_deadlist_obj = dsl_deadlist_clone(&ohds->ds_deadlist,
 839                     dsphys->ds_prev_snap_txg, dsphys->ds_prev_snap_obj, tx);
 840                 dsl_dataset_rele(ohds, FTAG);
 841 
 842                 if (spa_version(dp->dp_spa) >= SPA_VERSION_NEXT_CLONES) {
 843                         if (origin->ds_phys->ds_next_clones_obj == 0) {
 844                                 origin->ds_phys->ds_next_clones_obj =
 845                                     zap_create(mos,
 846                                     DMU_OT_NEXT_CLONES, DMU_OT_NONE, 0, tx);
 847                         }
 848                         VERIFY(0 == zap_add_int(mos,
 849                             origin->ds_phys->ds_next_clones_obj,
 850                             dsobj, tx));
 851                 }
 852 
 853                 dmu_buf_will_dirty(dd->dd_dbuf, tx);
 854                 dd->dd_phys->dd_origin_obj = origin->ds_object;
 855                 if (spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
 856                         if (origin->ds_dir->dd_phys->dd_clones == 0) {
 857                                 dmu_buf_will_dirty(origin->ds_dir->dd_dbuf, tx);
 858                                 origin->ds_dir->dd_phys->dd_clones =
 859                                     zap_create(mos,
 860                                     DMU_OT_DSL_CLONES, DMU_OT_NONE, 0, tx);
 861                         }
 862                         VERIFY3U(0, ==, zap_add_int(mos,
 863                             origin->ds_dir->dd_phys->dd_clones, dsobj, tx));
 864                 }
 865         }
 866 
 867         if (spa_version(dp->dp_spa) >= SPA_VERSION_UNIQUE_ACCURATE)
 868                 dsphys->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
 869 
 870         dmu_buf_rele(dbuf, FTAG);
 871 
 872         dmu_buf_will_dirty(dd->dd_dbuf, tx);
 873         dd->dd_phys->dd_head_dataset_obj = dsobj;
 874 
 875         return (dsobj);
 876 }
 877 
 878 uint64_t
 879 dsl_dataset_create_sync(dsl_dir_t *pdd, const char *lastname,
 880     dsl_dataset_t *origin, uint64_t flags, cred_t *cr, dmu_tx_t *tx)
 881 {
 882         dsl_pool_t *dp = pdd->dd_pool;
 883         uint64_t dsobj, ddobj;
 884         dsl_dir_t *dd;
 885 
 886         ASSERT(lastname[0] != '@');
 887 
 888         ddobj = dsl_dir_create_sync(dp, pdd, lastname, tx);
 889         VERIFY(0 == dsl_dir_open_obj(dp, ddobj, lastname, FTAG, &dd));
 890 
 891         dsobj = dsl_dataset_create_sync_dd(dd, origin, flags, tx);
 892 
 893         dsl_deleg_set_create_perms(dd, tx, cr);
 894 
 895         dsl_dir_close(dd, FTAG);
 896 
 897         /*
 898          * If we are creating a clone, make sure we zero out any stale
 899          * data from the origin snapshots zil header.
 900          */
 901         if (origin != NULL) {
 902                 dsl_dataset_t *ds;
 903                 objset_t *os;
 904 
 905                 VERIFY3U(0, ==, dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
 906                 VERIFY3U(0, ==, dmu_objset_from_ds(ds, &os));
 907                 bzero(&os->os_zil_header, sizeof (os->os_zil_header));
 908                 dsl_dataset_dirty(ds, tx);
 909                 dsl_dataset_rele(ds, FTAG);
 910         }
 911 
 912         return (dsobj);
 913 }
 914 
 915 /*
 916  * The snapshots must all be in the same pool.
 917  */
 918 int
 919 dmu_snapshots_destroy_nvl(nvlist_t *snaps, boolean_t defer, char *failed)
 920 {
 921         int err;
 922         dsl_sync_task_t *dst;
 923         spa_t *spa;
 924         nvpair_t *pair;
 925         dsl_sync_task_group_t *dstg;
 926 
 927         pair = nvlist_next_nvpair(snaps, NULL);
 928         if (pair == NULL)
 929                 return (0);
 930 
 931         err = spa_open(nvpair_name(pair), &spa, FTAG);
 932         if (err)
 933                 return (err);
 934         dstg = dsl_sync_task_group_create(spa_get_dsl(spa));
 935 
 936         for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
 937             pair = nvlist_next_nvpair(snaps, pair)) {
 938                 dsl_dataset_t *ds;
 939 
 940                 err = dsl_dataset_own(nvpair_name(pair), B_TRUE, dstg, &ds);
 941                 if (err == 0) {
 942                         struct dsl_ds_destroyarg *dsda;
 943 
 944                         dsl_dataset_make_exclusive(ds, dstg);
 945                         dsda = kmem_zalloc(sizeof (struct dsl_ds_destroyarg),
 946                             KM_SLEEP);
 947                         dsda->ds = ds;
 948                         dsda->defer = defer;
 949                         dsl_sync_task_create(dstg, dsl_dataset_destroy_check,
 950                             dsl_dataset_destroy_sync, dsda, dstg, 0);
 951                 } else if (err == ENOENT) {
 952                         err = 0;
 953                 } else {
 954                         (void) strcpy(failed, nvpair_name(pair));
 955                         break;
 956                 }
 957         }
 958 
 959         if (err == 0)
 960                 err = dsl_sync_task_group_wait(dstg);
 961 
 962         for (dst = list_head(&dstg->dstg_tasks); dst;
 963             dst = list_next(&dstg->dstg_tasks, dst)) {
 964                 struct dsl_ds_destroyarg *dsda = dst->dst_arg1;
 965                 dsl_dataset_t *ds = dsda->ds;
 966 
 967                 /*
 968                  * Return the file system name that triggered the error
 969                  */
 970                 if (dst->dst_err) {
 971                         dsl_dataset_name(ds, failed);
 972                 }
 973                 ASSERT3P(dsda->rm_origin, ==, NULL);
 974                 dsl_dataset_disown(ds, dstg);
 975                 kmem_free(dsda, sizeof (struct dsl_ds_destroyarg));
 976         }
 977 
 978         dsl_sync_task_group_destroy(dstg);
 979         spa_close(spa, FTAG);
 980         return (err);
 981 
 982 }
 983 
 984 static boolean_t
 985 dsl_dataset_might_destroy_origin(dsl_dataset_t *ds)
 986 {
 987         boolean_t might_destroy = B_FALSE;
 988 
 989         mutex_enter(&ds->ds_lock);
 990         if (ds->ds_phys->ds_num_children == 2 && ds->ds_userrefs == 0 &&
 991             DS_IS_DEFER_DESTROY(ds))
 992                 might_destroy = B_TRUE;
 993         mutex_exit(&ds->ds_lock);
 994 
 995         return (might_destroy);
 996 }
 997 
 998 /*
 999  * If we're removing a clone, and these three conditions are true:
1000  *      1) the clone's origin has no other children
1001  *      2) the clone's origin has no user references
1002  *      3) the clone's origin has been marked for deferred destruction
1003  * Then, prepare to remove the origin as part of this sync task group.
1004  */
1005 static int
1006 dsl_dataset_origin_rm_prep(struct dsl_ds_destroyarg *dsda, void *tag)
1007 {
1008         dsl_dataset_t *ds = dsda->ds;
1009         dsl_dataset_t *origin = ds->ds_prev;
1010 
1011         if (dsl_dataset_might_destroy_origin(origin)) {
1012                 char *name;
1013                 int namelen;
1014                 int error;
1015 
1016                 namelen = dsl_dataset_namelen(origin) + 1;
1017                 name = kmem_alloc(namelen, KM_SLEEP);
1018                 dsl_dataset_name(origin, name);
1019 #ifdef _KERNEL
1020                 error = zfs_unmount_snap(name, NULL);
1021                 if (error) {
1022                         kmem_free(name, namelen);
1023                         return (error);
1024                 }
1025 #endif
1026                 error = dsl_dataset_own(name, B_TRUE, tag, &origin);
1027                 kmem_free(name, namelen);
1028                 if (error)
1029                         return (error);
1030                 dsda->rm_origin = origin;
1031                 dsl_dataset_make_exclusive(origin, tag);
1032         }
1033 
1034         return (0);
1035 }
1036 
1037 /*
1038  * ds must be opened as OWNER.  On return (whether successful or not),
1039  * ds will be closed and caller can no longer dereference it.
1040  */
1041 int
1042 dsl_dataset_destroy(dsl_dataset_t *ds, void *tag, boolean_t defer)
1043 {
1044         int err;
1045         dsl_sync_task_group_t *dstg;
1046         objset_t *os;
1047         dsl_dir_t *dd;
1048         uint64_t obj;
1049         struct dsl_ds_destroyarg dsda = { 0 };
1050         dsl_dataset_t dummy_ds = { 0 };
1051 
1052         dsda.ds = ds;
1053 
1054         if (dsl_dataset_is_snapshot(ds)) {
1055                 /* Destroying a snapshot is simpler */
1056                 dsl_dataset_make_exclusive(ds, tag);
1057 
1058                 dsda.defer = defer;
1059                 err = dsl_sync_task_do(ds->ds_dir->dd_pool,
1060                     dsl_dataset_destroy_check, dsl_dataset_destroy_sync,
1061                     &dsda, tag, 0);
1062                 ASSERT3P(dsda.rm_origin, ==, NULL);
1063                 goto out;
1064         } else if (defer) {
1065                 err = EINVAL;
1066                 goto out;
1067         }
1068 
1069         dd = ds->ds_dir;
1070         dummy_ds.ds_dir = dd;
1071         dummy_ds.ds_object = ds->ds_object;
1072 
1073         /*
1074          * Check for errors and mark this ds as inconsistent, in
1075          * case we crash while freeing the objects.
1076          */
1077         err = dsl_sync_task_do(dd->dd_pool, dsl_dataset_destroy_begin_check,
1078             dsl_dataset_destroy_begin_sync, ds, NULL, 0);
1079         if (err)
1080                 goto out;
1081 
1082         err = dmu_objset_from_ds(ds, &os);
1083         if (err)
1084                 goto out;
1085 
1086         /*
1087          * If async destruction is not enabled try to remove all objects
1088          * while in the open context so that there is less work to do in
1089          * the syncing context.
1090          */
1091         if (!spa_feature_is_enabled(dsl_dataset_get_spa(ds),
1092             &spa_feature_table[SPA_FEATURE_ASYNC_DESTROY])) {
1093                 for (obj = 0; err == 0; err = dmu_object_next(os, &obj, FALSE,
1094                     ds->ds_phys->ds_prev_snap_txg)) {
1095                         /*
1096                          * Ignore errors, if there is not enough disk space
1097                          * we will deal with it in dsl_dataset_destroy_sync().
1098                          */
1099                         (void) dmu_free_object(os, obj);
1100                 }
1101                 if (err != ESRCH)
1102                         goto out;
1103         }
1104 
1105         /*
1106          * Only the ZIL knows how to free log blocks.
1107          */
1108         zil_destroy(dmu_objset_zil(os), B_FALSE);
1109 
1110         /*
1111          * Sync out all in-flight IO.
1112          */
1113         txg_wait_synced(dd->dd_pool, 0);
1114 
1115         /*
1116          * If we managed to free all the objects in open
1117          * context, the user space accounting should be zero.
1118          */
1119         if (ds->ds_phys->ds_bp.blk_fill == 0 &&
1120             dmu_objset_userused_enabled(os)) {
1121                 uint64_t count;
1122 
1123                 ASSERT(zap_count(os, DMU_USERUSED_OBJECT, &count) != 0 ||
1124                     count == 0);
1125                 ASSERT(zap_count(os, DMU_GROUPUSED_OBJECT, &count) != 0 ||
1126                     count == 0);
1127         }
1128 
1129         rw_enter(&dd->dd_pool->dp_config_rwlock, RW_READER);
1130         err = dsl_dir_open_obj(dd->dd_pool, dd->dd_object, NULL, FTAG, &dd);
1131         rw_exit(&dd->dd_pool->dp_config_rwlock);
1132 
1133         if (err)
1134                 goto out;
1135 
1136         /*
1137          * Blow away the dsl_dir + head dataset.
1138          */
1139         dsl_dataset_make_exclusive(ds, tag);
1140         /*
1141          * If we're removing a clone, we might also need to remove its
1142          * origin.
1143          */
1144         do {
1145                 dsda.need_prep = B_FALSE;
1146                 if (dsl_dir_is_clone(dd)) {
1147                         err = dsl_dataset_origin_rm_prep(&dsda, tag);
1148                         if (err) {
1149                                 dsl_dir_close(dd, FTAG);
1150                                 goto out;
1151                         }
1152                 }
1153 
1154                 dstg = dsl_sync_task_group_create(ds->ds_dir->dd_pool);
1155                 dsl_sync_task_create(dstg, dsl_dataset_destroy_check,
1156                     dsl_dataset_destroy_sync, &dsda, tag, 0);
1157                 dsl_sync_task_create(dstg, dsl_dir_destroy_check,
1158                     dsl_dir_destroy_sync, &dummy_ds, FTAG, 0);
1159                 err = dsl_sync_task_group_wait(dstg);
1160                 dsl_sync_task_group_destroy(dstg);
1161 
1162                 /*
1163                  * We could be racing against 'zfs release' or 'zfs destroy -d'
1164                  * on the origin snap, in which case we can get EBUSY if we
1165                  * needed to destroy the origin snap but were not ready to
1166                  * do so.
1167                  */
1168                 if (dsda.need_prep) {
1169                         ASSERT(err == EBUSY);
1170                         ASSERT(dsl_dir_is_clone(dd));
1171                         ASSERT(dsda.rm_origin == NULL);
1172                 }
1173         } while (dsda.need_prep);
1174 
1175         if (dsda.rm_origin != NULL)
1176                 dsl_dataset_disown(dsda.rm_origin, tag);
1177 
1178         /* if it is successful, dsl_dir_destroy_sync will close the dd */
1179         if (err)
1180                 dsl_dir_close(dd, FTAG);
1181 out:
1182         dsl_dataset_disown(ds, tag);
1183         return (err);
1184 }
1185 
1186 blkptr_t *
1187 dsl_dataset_get_blkptr(dsl_dataset_t *ds)
1188 {
1189         return (&ds->ds_phys->ds_bp);
1190 }
1191 
1192 void
1193 dsl_dataset_set_blkptr(dsl_dataset_t *ds, blkptr_t *bp, dmu_tx_t *tx)
1194 {
1195         ASSERT(dmu_tx_is_syncing(tx));
1196         /* If it's the meta-objset, set dp_meta_rootbp */
1197         if (ds == NULL) {
1198                 tx->tx_pool->dp_meta_rootbp = *bp;
1199         } else {
1200                 dmu_buf_will_dirty(ds->ds_dbuf, tx);
1201                 ds->ds_phys->ds_bp = *bp;
1202         }
1203 }
1204 
1205 spa_t *
1206 dsl_dataset_get_spa(dsl_dataset_t *ds)
1207 {
1208         return (ds->ds_dir->dd_pool->dp_spa);
1209 }
1210 
1211 void
1212 dsl_dataset_dirty(dsl_dataset_t *ds, dmu_tx_t *tx)
1213 {
1214         dsl_pool_t *dp;
1215 
1216         if (ds == NULL) /* this is the meta-objset */
1217                 return;
1218 
1219         ASSERT(ds->ds_objset != NULL);
1220 
1221         if (ds->ds_phys->ds_next_snap_obj != 0)
1222                 panic("dirtying snapshot!");
1223 
1224         dp = ds->ds_dir->dd_pool;
1225 
1226         if (txg_list_add(&dp->dp_dirty_datasets, ds, tx->tx_txg) == 0) {
1227                 /* up the hold count until we can be written out */
1228                 dmu_buf_add_ref(ds->ds_dbuf, ds);
1229         }
1230 }
1231 
1232 /*
1233  * The unique space in the head dataset can be calculated by subtracting
1234  * the space used in the most recent snapshot, that is still being used
1235  * in this file system, from the space currently in use.  To figure out
1236  * the space in the most recent snapshot still in use, we need to take
1237  * the total space used in the snapshot and subtract out the space that
1238  * has been freed up since the snapshot was taken.
1239  */
1240 static void
1241 dsl_dataset_recalc_head_uniq(dsl_dataset_t *ds)
1242 {
1243         uint64_t mrs_used;
1244         uint64_t dlused, dlcomp, dluncomp;
1245 
1246         ASSERT(!dsl_dataset_is_snapshot(ds));
1247 
1248         if (ds->ds_phys->ds_prev_snap_obj != 0)
1249                 mrs_used = ds->ds_prev->ds_phys->ds_referenced_bytes;
1250         else
1251                 mrs_used = 0;
1252 
1253         dsl_deadlist_space(&ds->ds_deadlist, &dlused, &dlcomp, &dluncomp);
1254 
1255         ASSERT3U(dlused, <=, mrs_used);
1256         ds->ds_phys->ds_unique_bytes =
1257             ds->ds_phys->ds_referenced_bytes - (mrs_used - dlused);
1258 
1259         if (spa_version(ds->ds_dir->dd_pool->dp_spa) >=
1260             SPA_VERSION_UNIQUE_ACCURATE)
1261                 ds->ds_phys->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
1262 }
1263 
1264 struct killarg {
1265         dsl_dataset_t *ds;
1266         dmu_tx_t *tx;
1267 };
1268 
1269 /* ARGSUSED */
1270 static int
1271 kill_blkptr(spa_t *spa, zilog_t *zilog, const blkptr_t *bp, arc_buf_t *pbuf,
1272     const zbookmark_t *zb, const dnode_phys_t *dnp, void *arg)
1273 {
1274         struct killarg *ka = arg;
1275         dmu_tx_t *tx = ka->tx;
1276 
1277         if (bp == NULL)
1278                 return (0);
1279 
1280         if (zb->zb_level == ZB_ZIL_LEVEL) {
1281                 ASSERT(zilog != NULL);
1282                 /*
1283                  * It's a block in the intent log.  It has no
1284                  * accounting, so just free it.
1285                  */
1286                 dsl_free(ka->tx->tx_pool, ka->tx->tx_txg, bp);
1287         } else {
1288                 ASSERT(zilog == NULL);
1289                 ASSERT3U(bp->blk_birth, >, ka->ds->ds_phys->ds_prev_snap_txg);
1290                 (void) dsl_dataset_block_kill(ka->ds, bp, tx, B_FALSE);
1291         }
1292 
1293         return (0);
1294 }
1295 
1296 /* ARGSUSED */
1297 static int
1298 dsl_dataset_destroy_begin_check(void *arg1, void *arg2, dmu_tx_t *tx)
1299 {
1300         dsl_dataset_t *ds = arg1;
1301         objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
1302         uint64_t count;
1303         int err;
1304 
1305         /*
1306          * Can't delete a head dataset if there are snapshots of it.
1307          * (Except if the only snapshots are from the branch we cloned
1308          * from.)
1309          */
1310         if (ds->ds_prev != NULL &&
1311             ds->ds_prev->ds_phys->ds_next_snap_obj == ds->ds_object)
1312                 return (EBUSY);
1313 
1314         /*
1315          * This is really a dsl_dir thing, but check it here so that
1316          * we'll be less likely to leave this dataset inconsistent &
1317          * nearly destroyed.
1318          */
1319         err = zap_count(mos, ds->ds_dir->dd_phys->dd_child_dir_zapobj, &count);
1320         if (err)
1321                 return (err);
1322         if (count != 0)
1323                 return (EEXIST);
1324 
1325         return (0);
1326 }
1327 
1328 /* ARGSUSED */
1329 static void
1330 dsl_dataset_destroy_begin_sync(void *arg1, void *arg2, dmu_tx_t *tx)
1331 {
1332         dsl_dataset_t *ds = arg1;
1333         dsl_pool_t *dp = ds->ds_dir->dd_pool;
1334 
1335         /* Mark it as inconsistent on-disk, in case we crash */
1336         dmu_buf_will_dirty(ds->ds_dbuf, tx);
1337         ds->ds_phys->ds_flags |= DS_FLAG_INCONSISTENT;
1338 
1339         spa_history_log_internal(LOG_DS_DESTROY_BEGIN, dp->dp_spa, tx,
1340             "dataset = %llu", ds->ds_object);
1341 }
1342 
1343 static int
1344 dsl_dataset_origin_check(struct dsl_ds_destroyarg *dsda, void *tag,
1345     dmu_tx_t *tx)
1346 {
1347         dsl_dataset_t *ds = dsda->ds;
1348         dsl_dataset_t *ds_prev = ds->ds_prev;
1349 
1350         if (dsl_dataset_might_destroy_origin(ds_prev)) {
1351                 struct dsl_ds_destroyarg ndsda = {0};
1352 
1353                 /*
1354                  * If we're not prepared to remove the origin, don't remove
1355                  * the clone either.
1356                  */
1357                 if (dsda->rm_origin == NULL) {
1358                         dsda->need_prep = B_TRUE;
1359                         return (EBUSY);
1360                 }
1361 
1362                 ndsda.ds = ds_prev;
1363                 ndsda.is_origin_rm = B_TRUE;
1364                 return (dsl_dataset_destroy_check(&ndsda, tag, tx));
1365         }
1366 
1367         /*
1368          * If we're not going to remove the origin after all,
1369          * undo the open context setup.
1370          */
1371         if (dsda->rm_origin != NULL) {
1372                 dsl_dataset_disown(dsda->rm_origin, tag);
1373                 dsda->rm_origin = NULL;
1374         }
1375 
1376         return (0);
1377 }
1378 
1379 /*
1380  * If you add new checks here, you may need to add
1381  * additional checks to the "temporary" case in
1382  * snapshot_check() in dmu_objset.c.
1383  */
1384 /* ARGSUSED */
1385 int
1386 dsl_dataset_destroy_check(void *arg1, void *arg2, dmu_tx_t *tx)
1387 {
1388         struct dsl_ds_destroyarg *dsda = arg1;
1389         dsl_dataset_t *ds = dsda->ds;
1390 
1391         /* we have an owner hold, so noone else can destroy us */
1392         ASSERT(!DSL_DATASET_IS_DESTROYED(ds));
1393 
1394         /*
1395          * Only allow deferred destroy on pools that support it.
1396          * NOTE: deferred destroy is only supported on snapshots.
1397          */
1398         if (dsda->defer) {
1399                 if (spa_version(ds->ds_dir->dd_pool->dp_spa) <
1400                     SPA_VERSION_USERREFS)
1401                         return (ENOTSUP);
1402                 ASSERT(dsl_dataset_is_snapshot(ds));
1403                 return (0);
1404         }
1405 
1406         /*
1407          * Can't delete a head dataset if there are snapshots of it.
1408          * (Except if the only snapshots are from the branch we cloned
1409          * from.)
1410          */
1411         if (ds->ds_prev != NULL &&
1412             ds->ds_prev->ds_phys->ds_next_snap_obj == ds->ds_object)
1413                 return (EBUSY);
1414 
1415         /*
1416          * If we made changes this txg, traverse_dsl_dataset won't find
1417          * them.  Try again.
1418          */
1419         if (ds->ds_phys->ds_bp.blk_birth >= tx->tx_txg)
1420                 return (EAGAIN);
1421 
1422         if (dsl_dataset_is_snapshot(ds)) {
1423                 /*
1424                  * If this snapshot has an elevated user reference count,
1425                  * we can't destroy it yet.
1426                  */
1427                 if (ds->ds_userrefs > 0 && !dsda->releasing)
1428                         return (EBUSY);
1429 
1430                 mutex_enter(&ds->ds_lock);
1431                 /*
1432                  * Can't delete a branch point. However, if we're destroying
1433                  * a clone and removing its origin due to it having a user
1434                  * hold count of 0 and having been marked for deferred destroy,
1435                  * it's OK for the origin to have a single clone.
1436                  */
1437                 if (ds->ds_phys->ds_num_children >
1438                     (dsda->is_origin_rm ? 2 : 1)) {
1439                         mutex_exit(&ds->ds_lock);
1440                         return (EEXIST);
1441                 }
1442                 mutex_exit(&ds->ds_lock);
1443         } else if (dsl_dir_is_clone(ds->ds_dir)) {
1444                 return (dsl_dataset_origin_check(dsda, arg2, tx));
1445         }
1446 
1447         /* XXX we should do some i/o error checking... */
1448         return (0);
1449 }
1450 
1451 struct refsarg {
1452         kmutex_t lock;
1453         boolean_t gone;
1454         kcondvar_t cv;
1455 };
1456 
1457 /* ARGSUSED */
1458 static void
1459 dsl_dataset_refs_gone(dmu_buf_t *db, void *argv)
1460 {
1461         struct refsarg *arg = argv;
1462 
1463         mutex_enter(&arg->lock);
1464         arg->gone = TRUE;
1465         cv_signal(&arg->cv);
1466         mutex_exit(&arg->lock);
1467 }
1468 
1469 static void
1470 dsl_dataset_drain_refs(dsl_dataset_t *ds, void *tag)
1471 {
1472         struct refsarg arg;
1473 
1474         mutex_init(&arg.lock, NULL, MUTEX_DEFAULT, NULL);
1475         cv_init(&arg.cv, NULL, CV_DEFAULT, NULL);
1476         arg.gone = FALSE;
1477         (void) dmu_buf_update_user(ds->ds_dbuf, ds, &arg, &ds->ds_phys,
1478             dsl_dataset_refs_gone);
1479         dmu_buf_rele(ds->ds_dbuf, tag);
1480         mutex_enter(&arg.lock);
1481         while (!arg.gone)
1482                 cv_wait(&arg.cv, &arg.lock);
1483         ASSERT(arg.gone);
1484         mutex_exit(&arg.lock);
1485         ds->ds_dbuf = NULL;
1486         ds->ds_phys = NULL;
1487         mutex_destroy(&arg.lock);
1488         cv_destroy(&arg.cv);
1489 }
1490 
1491 static void
1492 remove_from_next_clones(dsl_dataset_t *ds, uint64_t obj, dmu_tx_t *tx)
1493 {
1494         objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
1495         uint64_t count;
1496         int err;
1497 
1498         ASSERT(ds->ds_phys->ds_num_children >= 2);
1499         err = zap_remove_int(mos, ds->ds_phys->ds_next_clones_obj, obj, tx);
1500         /*
1501          * The err should not be ENOENT, but a bug in a previous version
1502          * of the code could cause upgrade_clones_cb() to not set
1503          * ds_next_snap_obj when it should, leading to a missing entry.
1504          * If we knew that the pool was created after
1505          * SPA_VERSION_NEXT_CLONES, we could assert that it isn't
1506          * ENOENT.  However, at least we can check that we don't have
1507          * too many entries in the next_clones_obj even after failing to
1508          * remove this one.
1509          */
1510         if (err != ENOENT) {
1511                 VERIFY3U(err, ==, 0);
1512         }
1513         ASSERT3U(0, ==, zap_count(mos, ds->ds_phys->ds_next_clones_obj,
1514             &count));
1515         ASSERT3U(count, <=, ds->ds_phys->ds_num_children - 2);
1516 }
1517 
1518 static void
1519 dsl_dataset_remove_clones_key(dsl_dataset_t *ds, uint64_t mintxg, dmu_tx_t *tx)
1520 {
1521         objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
1522         zap_cursor_t zc;
1523         zap_attribute_t za;
1524 
1525         /*
1526          * If it is the old version, dd_clones doesn't exist so we can't
1527          * find the clones, but deadlist_remove_key() is a no-op so it
1528          * doesn't matter.
1529          */
1530         if (ds->ds_dir->dd_phys->dd_clones == 0)
1531                 return;
1532 
1533         for (zap_cursor_init(&zc, mos, ds->ds_dir->dd_phys->dd_clones);
1534             zap_cursor_retrieve(&zc, &za) == 0;
1535             zap_cursor_advance(&zc)) {
1536                 dsl_dataset_t *clone;
1537 
1538                 VERIFY3U(0, ==, dsl_dataset_hold_obj(ds->ds_dir->dd_pool,
1539                     za.za_first_integer, FTAG, &clone));
1540                 if (clone->ds_dir->dd_origin_txg > mintxg) {
1541                         dsl_deadlist_remove_key(&clone->ds_deadlist,
1542                             mintxg, tx);
1543                         dsl_dataset_remove_clones_key(clone, mintxg, tx);
1544                 }
1545                 dsl_dataset_rele(clone, FTAG);
1546         }
1547         zap_cursor_fini(&zc);
1548 }
1549 
1550 struct process_old_arg {
1551         dsl_dataset_t *ds;
1552         dsl_dataset_t *ds_prev;
1553         boolean_t after_branch_point;
1554         zio_t *pio;
1555         uint64_t used, comp, uncomp;
1556 };
1557 
1558 static int
1559 process_old_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1560 {
1561         struct process_old_arg *poa = arg;
1562         dsl_pool_t *dp = poa->ds->ds_dir->dd_pool;
1563 
1564         if (bp->blk_birth <= poa->ds->ds_phys->ds_prev_snap_txg) {
1565                 dsl_deadlist_insert(&poa->ds->ds_deadlist, bp, tx);
1566                 if (poa->ds_prev && !poa->after_branch_point &&
1567                     bp->blk_birth >
1568                     poa->ds_prev->ds_phys->ds_prev_snap_txg) {
1569                         poa->ds_prev->ds_phys->ds_unique_bytes +=
1570                             bp_get_dsize_sync(dp->dp_spa, bp);
1571                 }
1572         } else {
1573                 poa->used += bp_get_dsize_sync(dp->dp_spa, bp);
1574                 poa->comp += BP_GET_PSIZE(bp);
1575                 poa->uncomp += BP_GET_UCSIZE(bp);
1576                 dsl_free_sync(poa->pio, dp, tx->tx_txg, bp);
1577         }
1578         return (0);
1579 }
1580 
1581 static void
1582 process_old_deadlist(dsl_dataset_t *ds, dsl_dataset_t *ds_prev,
1583     dsl_dataset_t *ds_next, boolean_t after_branch_point, dmu_tx_t *tx)
1584 {
1585         struct process_old_arg poa = { 0 };
1586         dsl_pool_t *dp = ds->ds_dir->dd_pool;
1587         objset_t *mos = dp->dp_meta_objset;
1588 
1589         ASSERT(ds->ds_deadlist.dl_oldfmt);
1590         ASSERT(ds_next->ds_deadlist.dl_oldfmt);
1591 
1592         poa.ds = ds;
1593         poa.ds_prev = ds_prev;
1594         poa.after_branch_point = after_branch_point;
1595         poa.pio = zio_root(dp->dp_spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
1596         VERIFY3U(0, ==, bpobj_iterate(&ds_next->ds_deadlist.dl_bpobj,
1597             process_old_cb, &poa, tx));
1598         VERIFY3U(zio_wait(poa.pio), ==, 0);
1599         ASSERT3U(poa.used, ==, ds->ds_phys->ds_unique_bytes);
1600 
1601         /* change snapused */
1602         dsl_dir_diduse_space(ds->ds_dir, DD_USED_SNAP,
1603             -poa.used, -poa.comp, -poa.uncomp, tx);
1604 
1605         /* swap next's deadlist to our deadlist */
1606         dsl_deadlist_close(&ds->ds_deadlist);
1607         dsl_deadlist_close(&ds_next->ds_deadlist);
1608         SWITCH64(ds_next->ds_phys->ds_deadlist_obj,
1609             ds->ds_phys->ds_deadlist_obj);
1610         dsl_deadlist_open(&ds->ds_deadlist, mos, ds->ds_phys->ds_deadlist_obj);
1611         dsl_deadlist_open(&ds_next->ds_deadlist, mos,
1612             ds_next->ds_phys->ds_deadlist_obj);
1613 }
1614 
1615 static int
1616 old_synchronous_dataset_destroy(dsl_dataset_t *ds, dmu_tx_t *tx)
1617 {
1618         int err;
1619         struct killarg ka;
1620 
1621         /*
1622          * Free everything that we point to (that's born after
1623          * the previous snapshot, if we are a clone)
1624          *
1625          * NB: this should be very quick, because we already
1626          * freed all the objects in open context.
1627          */
1628         ka.ds = ds;
1629         ka.tx = tx;
1630         err = traverse_dataset(ds,
1631             ds->ds_phys->ds_prev_snap_txg, TRAVERSE_POST,
1632             kill_blkptr, &ka);
1633         ASSERT3U(err, ==, 0);
1634         ASSERT(!DS_UNIQUE_IS_ACCURATE(ds) || ds->ds_phys->ds_unique_bytes == 0);
1635 
1636         return (err);
1637 }
1638 
1639 void
1640 dsl_dataset_destroy_sync(void *arg1, void *tag, dmu_tx_t *tx)
1641 {
1642         struct dsl_ds_destroyarg *dsda = arg1;
1643         dsl_dataset_t *ds = dsda->ds;
1644         int err;
1645         int after_branch_point = FALSE;
1646         dsl_pool_t *dp = ds->ds_dir->dd_pool;
1647         objset_t *mos = dp->dp_meta_objset;
1648         dsl_dataset_t *ds_prev = NULL;
1649         boolean_t wont_destroy;
1650         uint64_t obj;
1651 
1652         wont_destroy = (dsda->defer &&
1653             (ds->ds_userrefs > 0 || ds->ds_phys->ds_num_children > 1));
1654 
1655         ASSERT(ds->ds_owner || wont_destroy);
1656         ASSERT(dsda->defer || ds->ds_phys->ds_num_children <= 1);
1657         ASSERT(ds->ds_prev == NULL ||
1658             ds->ds_prev->ds_phys->ds_next_snap_obj != ds->ds_object);
1659         ASSERT3U(ds->ds_phys->ds_bp.blk_birth, <=, tx->tx_txg);
1660 
1661         if (wont_destroy) {
1662                 ASSERT(spa_version(dp->dp_spa) >= SPA_VERSION_USERREFS);
1663                 dmu_buf_will_dirty(ds->ds_dbuf, tx);
1664                 ds->ds_phys->ds_flags |= DS_FLAG_DEFER_DESTROY;
1665                 return;
1666         }
1667 
1668         /* signal any waiters that this dataset is going away */
1669         mutex_enter(&ds->ds_lock);
1670         ds->ds_owner = dsl_reaper;
1671         cv_broadcast(&ds->ds_exclusive_cv);
1672         mutex_exit(&ds->ds_lock);
1673 
1674         /* Remove our reservation */
1675         if (ds->ds_reserved != 0) {
1676                 dsl_prop_setarg_t psa;
1677                 uint64_t value = 0;
1678 
1679                 dsl_prop_setarg_init_uint64(&psa, "refreservation",
1680                     (ZPROP_SRC_NONE | ZPROP_SRC_LOCAL | ZPROP_SRC_RECEIVED),
1681                     &value);
1682                 psa.psa_effective_value = 0;    /* predict default value */
1683 
1684                 dsl_dataset_set_reservation_sync(ds, &psa, tx);
1685                 ASSERT3U(ds->ds_reserved, ==, 0);
1686         }
1687 
1688         ASSERT(RW_WRITE_HELD(&dp->dp_config_rwlock));
1689 
1690         dsl_scan_ds_destroyed(ds, tx);
1691 
1692         obj = ds->ds_object;
1693 
1694         if (ds->ds_phys->ds_prev_snap_obj != 0) {
1695                 if (ds->ds_prev) {
1696                         ds_prev = ds->ds_prev;
1697                 } else {
1698                         VERIFY(0 == dsl_dataset_hold_obj(dp,
1699                             ds->ds_phys->ds_prev_snap_obj, FTAG, &ds_prev));
1700                 }
1701                 after_branch_point =
1702                     (ds_prev->ds_phys->ds_next_snap_obj != obj);
1703 
1704                 dmu_buf_will_dirty(ds_prev->ds_dbuf, tx);
1705                 if (after_branch_point &&
1706                     ds_prev->ds_phys->ds_next_clones_obj != 0) {
1707                         remove_from_next_clones(ds_prev, obj, tx);
1708                         if (ds->ds_phys->ds_next_snap_obj != 0) {
1709                                 VERIFY(0 == zap_add_int(mos,
1710                                     ds_prev->ds_phys->ds_next_clones_obj,
1711                                     ds->ds_phys->ds_next_snap_obj, tx));
1712                         }
1713                 }
1714                 if (after_branch_point &&
1715                     ds->ds_phys->ds_next_snap_obj == 0) {
1716                         /* This clone is toast. */
1717                         ASSERT(ds_prev->ds_phys->ds_num_children > 1);
1718                         ds_prev->ds_phys->ds_num_children--;
1719 
1720                         /*
1721                          * If the clone's origin has no other clones, no
1722                          * user holds, and has been marked for deferred
1723                          * deletion, then we should have done the necessary
1724                          * destroy setup for it.
1725                          */
1726                         if (ds_prev->ds_phys->ds_num_children == 1 &&
1727                             ds_prev->ds_userrefs == 0 &&
1728                             DS_IS_DEFER_DESTROY(ds_prev)) {
1729                                 ASSERT3P(dsda->rm_origin, !=, NULL);
1730                         } else {
1731                                 ASSERT3P(dsda->rm_origin, ==, NULL);
1732                         }
1733                 } else if (!after_branch_point) {
1734                         ds_prev->ds_phys->ds_next_snap_obj =
1735                             ds->ds_phys->ds_next_snap_obj;
1736                 }
1737         }
1738 
1739         if (dsl_dataset_is_snapshot(ds)) {
1740                 dsl_dataset_t *ds_next;
1741                 uint64_t old_unique;
1742                 uint64_t used = 0, comp = 0, uncomp = 0;
1743 
1744                 VERIFY(0 == dsl_dataset_hold_obj(dp,
1745                     ds->ds_phys->ds_next_snap_obj, FTAG, &ds_next));
1746                 ASSERT3U(ds_next->ds_phys->ds_prev_snap_obj, ==, obj);
1747 
1748                 old_unique = ds_next->ds_phys->ds_unique_bytes;
1749 
1750                 dmu_buf_will_dirty(ds_next->ds_dbuf, tx);
1751                 ds_next->ds_phys->ds_prev_snap_obj =
1752                     ds->ds_phys->ds_prev_snap_obj;
1753                 ds_next->ds_phys->ds_prev_snap_txg =
1754                     ds->ds_phys->ds_prev_snap_txg;
1755                 ASSERT3U(ds->ds_phys->ds_prev_snap_txg, ==,
1756                     ds_prev ? ds_prev->ds_phys->ds_creation_txg : 0);
1757 
1758 
1759                 if (ds_next->ds_deadlist.dl_oldfmt) {
1760                         process_old_deadlist(ds, ds_prev, ds_next,
1761                             after_branch_point, tx);
1762                 } else {
1763                         /* Adjust prev's unique space. */
1764                         if (ds_prev && !after_branch_point) {
1765                                 dsl_deadlist_space_range(&ds_next->ds_deadlist,
1766                                     ds_prev->ds_phys->ds_prev_snap_txg,
1767                                     ds->ds_phys->ds_prev_snap_txg,
1768                                     &used, &comp, &uncomp);
1769                                 ds_prev->ds_phys->ds_unique_bytes += used;
1770                         }
1771 
1772                         /* Adjust snapused. */
1773                         dsl_deadlist_space_range(&ds_next->ds_deadlist,
1774                             ds->ds_phys->ds_prev_snap_txg, UINT64_MAX,
1775                             &used, &comp, &uncomp);
1776                         dsl_dir_diduse_space(ds->ds_dir, DD_USED_SNAP,
1777                             -used, -comp, -uncomp, tx);
1778 
1779                         /* Move blocks to be freed to pool's free list. */
1780                         dsl_deadlist_move_bpobj(&ds_next->ds_deadlist,
1781                             &dp->dp_free_bpobj, ds->ds_phys->ds_prev_snap_txg,
1782                             tx);
1783                         dsl_dir_diduse_space(tx->tx_pool->dp_free_dir,
1784                             DD_USED_HEAD, used, comp, uncomp, tx);
1785 
1786                         /* Merge our deadlist into next's and free it. */
1787                         dsl_deadlist_merge(&ds_next->ds_deadlist,
1788                             ds->ds_phys->ds_deadlist_obj, tx);
1789                 }
1790                 dsl_deadlist_close(&ds->ds_deadlist);
1791                 dsl_deadlist_free(mos, ds->ds_phys->ds_deadlist_obj, tx);
1792 
1793                 /* Collapse range in clone heads */
1794                 dsl_dataset_remove_clones_key(ds,
1795                     ds->ds_phys->ds_creation_txg, tx);
1796 
1797                 if (dsl_dataset_is_snapshot(ds_next)) {
1798                         dsl_dataset_t *ds_nextnext;
1799 
1800                         /*
1801                          * Update next's unique to include blocks which
1802                          * were previously shared by only this snapshot
1803                          * and it.  Those blocks will be born after the
1804                          * prev snap and before this snap, and will have
1805                          * died after the next snap and before the one
1806                          * after that (ie. be on the snap after next's
1807                          * deadlist).
1808                          */
1809                         VERIFY(0 == dsl_dataset_hold_obj(dp,
1810                             ds_next->ds_phys->ds_next_snap_obj,
1811                             FTAG, &ds_nextnext));
1812                         dsl_deadlist_space_range(&ds_nextnext->ds_deadlist,
1813                             ds->ds_phys->ds_prev_snap_txg,
1814                             ds->ds_phys->ds_creation_txg,
1815                             &used, &comp, &uncomp);
1816                         ds_next->ds_phys->ds_unique_bytes += used;
1817                         dsl_dataset_rele(ds_nextnext, FTAG);
1818                         ASSERT3P(ds_next->ds_prev, ==, NULL);
1819 
1820                         /* Collapse range in this head. */
1821                         dsl_dataset_t *hds;
1822                         VERIFY3U(0, ==, dsl_dataset_hold_obj(dp,
1823                             ds->ds_dir->dd_phys->dd_head_dataset_obj,
1824                             FTAG, &hds));
1825                         dsl_deadlist_remove_key(&hds->ds_deadlist,
1826                             ds->ds_phys->ds_creation_txg, tx);
1827                         dsl_dataset_rele(hds, FTAG);
1828 
1829                 } else {
1830                         ASSERT3P(ds_next->ds_prev, ==, ds);
1831                         dsl_dataset_drop_ref(ds_next->ds_prev, ds_next);
1832                         ds_next->ds_prev = NULL;
1833                         if (ds_prev) {
1834                                 VERIFY(0 == dsl_dataset_get_ref(dp,
1835                                     ds->ds_phys->ds_prev_snap_obj,
1836                                     ds_next, &ds_next->ds_prev));
1837                         }
1838 
1839                         dsl_dataset_recalc_head_uniq(ds_next);
1840 
1841                         /*
1842                          * Reduce the amount of our unconsmed refreservation
1843                          * being charged to our parent by the amount of
1844                          * new unique data we have gained.
1845                          */
1846                         if (old_unique < ds_next->ds_reserved) {
1847                                 int64_t mrsdelta;
1848                                 uint64_t new_unique =
1849                                     ds_next->ds_phys->ds_unique_bytes;
1850 
1851                                 ASSERT(old_unique <= new_unique);
1852                                 mrsdelta = MIN(new_unique - old_unique,
1853                                     ds_next->ds_reserved - old_unique);
1854                                 dsl_dir_diduse_space(ds->ds_dir,
1855                                     DD_USED_REFRSRV, -mrsdelta, 0, 0, tx);
1856                         }
1857                 }
1858                 dsl_dataset_rele(ds_next, FTAG);
1859         } else {
1860                 zfeature_info_t *async_destroy =
1861                     &spa_feature_table[SPA_FEATURE_ASYNC_DESTROY];
1862 
1863                 /*
1864                  * There's no next snapshot, so this is a head dataset.
1865                  * Destroy the deadlist.  Unless it's a clone, the
1866                  * deadlist should be empty.  (If it's a clone, it's
1867                  * safe to ignore the deadlist contents.)
1868                  */
1869                 dsl_deadlist_close(&ds->ds_deadlist);
1870                 dsl_deadlist_free(mos, ds->ds_phys->ds_deadlist_obj, tx);
1871                 ds->ds_phys->ds_deadlist_obj = 0;
1872 
1873                 if (!spa_feature_is_enabled(dp->dp_spa, async_destroy)) {
1874                         err = old_synchronous_dataset_destroy(ds, tx);
1875                 } else {
1876                         /*
1877                          * Move the bptree into the pool's list of trees to
1878                          * clean up and update space accounting information.
1879                          */
1880                         uint64_t used, comp, uncomp;
1881 
1882                         ASSERT(err == 0 || err == EBUSY);
1883                         if (!spa_feature_is_active(dp->dp_spa, async_destroy)) {
1884                                 spa_feature_incr(dp->dp_spa, async_destroy, tx);
1885                                 dp->dp_bptree_obj = bptree_alloc(
1886                                     dp->dp_meta_objset, tx);
1887                                 VERIFY(zap_add(dp->dp_meta_objset,
1888                                     DMU_POOL_DIRECTORY_OBJECT,
1889                                     DMU_POOL_BPTREE_OBJ, sizeof (uint64_t), 1,
1890                                     &dp->dp_bptree_obj, tx) == 0);
1891                         }
1892 
1893                         used = ds->ds_dir->dd_phys->dd_used_bytes;
1894                         comp = ds->ds_dir->dd_phys->dd_compressed_bytes;
1895                         uncomp = ds->ds_dir->dd_phys->dd_uncompressed_bytes;
1896 
1897                         ASSERT(!DS_UNIQUE_IS_ACCURATE(ds) ||
1898                             ds->ds_phys->ds_unique_bytes == used);
1899 
1900                         bptree_add(dp->dp_meta_objset, dp->dp_bptree_obj,
1901                             &ds->ds_phys->ds_bp, ds->ds_phys->ds_prev_snap_txg,
1902                             used, comp, uncomp, tx);
1903                         dsl_dir_diduse_space(ds->ds_dir, DD_USED_HEAD,
1904                             -used, -comp, -uncomp, tx);
1905                         dsl_dir_diduse_space(dp->dp_free_dir, DD_USED_HEAD,
1906                             used, comp, uncomp, tx);
1907                 }
1908 
1909                 if (ds->ds_prev != NULL) {
1910                         if (spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
1911                                 VERIFY3U(0, ==, zap_remove_int(mos,
1912                                     ds->ds_prev->ds_dir->dd_phys->dd_clones,
1913                                     ds->ds_object, tx));
1914                         }
1915                         dsl_dataset_rele(ds->ds_prev, ds);
1916                         ds->ds_prev = ds_prev = NULL;
1917                 }
1918         }
1919 
1920         /*
1921          * This must be done after the dsl_traverse(), because it will
1922          * re-open the objset.
1923          */
1924         if (ds->ds_objset) {
1925                 dmu_objset_evict(ds->ds_objset);
1926                 ds->ds_objset = NULL;
1927         }
1928 
1929         if (ds->ds_dir->dd_phys->dd_head_dataset_obj == ds->ds_object) {
1930                 /* Erase the link in the dir */
1931                 dmu_buf_will_dirty(ds->ds_dir->dd_dbuf, tx);
1932                 ds->ds_dir->dd_phys->dd_head_dataset_obj = 0;
1933                 ASSERT(ds->ds_phys->ds_snapnames_zapobj != 0);
1934                 err = zap_destroy(mos, ds->ds_phys->ds_snapnames_zapobj, tx);
1935                 ASSERT(err == 0);
1936         } else {
1937                 /* remove from snapshot namespace */
1938                 dsl_dataset_t *ds_head;
1939                 ASSERT(ds->ds_phys->ds_snapnames_zapobj == 0);
1940                 VERIFY(0 == dsl_dataset_hold_obj(dp,
1941                     ds->ds_dir->dd_phys->dd_head_dataset_obj, FTAG, &ds_head));
1942                 VERIFY(0 == dsl_dataset_get_snapname(ds));
1943 #ifdef ZFS_DEBUG
1944                 {
1945                         uint64_t val;
1946 
1947                         err = dsl_dataset_snap_lookup(ds_head,
1948                             ds->ds_snapname, &val);
1949                         ASSERT3U(err, ==, 0);
1950                         ASSERT3U(val, ==, obj);
1951                 }
1952 #endif
1953                 err = dsl_dataset_snap_remove(ds_head, ds->ds_snapname, tx);
1954                 ASSERT(err == 0);
1955                 dsl_dataset_rele(ds_head, FTAG);
1956         }
1957 
1958         if (ds_prev && ds->ds_prev != ds_prev)
1959                 dsl_dataset_rele(ds_prev, FTAG);
1960 
1961         spa_prop_clear_bootfs(dp->dp_spa, ds->ds_object, tx);
1962         spa_history_log_internal(LOG_DS_DESTROY, dp->dp_spa, tx,
1963             "dataset = %llu", ds->ds_object);
1964 
1965         if (ds->ds_phys->ds_next_clones_obj != 0) {
1966                 uint64_t count;
1967                 ASSERT(0 == zap_count(mos,
1968                     ds->ds_phys->ds_next_clones_obj, &count) && count == 0);
1969                 VERIFY(0 == dmu_object_free(mos,
1970                     ds->ds_phys->ds_next_clones_obj, tx));
1971         }
1972         if (ds->ds_phys->ds_props_obj != 0)
1973                 VERIFY(0 == zap_destroy(mos, ds->ds_phys->ds_props_obj, tx));
1974         if (ds->ds_phys->ds_userrefs_obj != 0)
1975                 VERIFY(0 == zap_destroy(mos, ds->ds_phys->ds_userrefs_obj, tx));
1976         dsl_dir_close(ds->ds_dir, ds);
1977         ds->ds_dir = NULL;
1978         dsl_dataset_drain_refs(ds, tag);
1979         VERIFY(0 == dmu_object_free(mos, obj, tx));
1980 
1981         if (dsda->rm_origin) {
1982                 /*
1983                  * Remove the origin of the clone we just destroyed.
1984                  */
1985                 struct dsl_ds_destroyarg ndsda = {0};
1986 
1987                 ndsda.ds = dsda->rm_origin;
1988                 dsl_dataset_destroy_sync(&ndsda, tag, tx);
1989         }
1990 }
1991 
1992 static int
1993 dsl_dataset_snapshot_reserve_space(dsl_dataset_t *ds, dmu_tx_t *tx)
1994 {
1995         uint64_t asize;
1996 
1997         if (!dmu_tx_is_syncing(tx))
1998                 return (0);
1999 
2000         /*
2001          * If there's an fs-only reservation, any blocks that might become
2002          * owned by the snapshot dataset must be accommodated by space
2003          * outside of the reservation.
2004          */
2005         ASSERT(ds->ds_reserved == 0 || DS_UNIQUE_IS_ACCURATE(ds));
2006         asize = MIN(ds->ds_phys->ds_unique_bytes, ds->ds_reserved);
2007         if (asize > dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE))
2008                 return (ENOSPC);
2009 
2010         /*
2011          * Propogate any reserved space for this snapshot to other
2012          * snapshot checks in this sync group.
2013          */
2014         if (asize > 0)
2015                 dsl_dir_willuse_space(ds->ds_dir, asize, tx);
2016 
2017         return (0);
2018 }
2019 
2020 int
2021 dsl_dataset_snapshot_check(void *arg1, void *arg2, dmu_tx_t *tx)
2022 {
2023         dsl_dataset_t *ds = arg1;
2024         const char *snapname = arg2;
2025         int err;
2026         uint64_t value;
2027 
2028         /*
2029          * We don't allow multiple snapshots of the same txg.  If there
2030          * is already one, try again.
2031          */
2032         if (ds->ds_phys->ds_prev_snap_txg >= tx->tx_txg)
2033                 return (EAGAIN);
2034 
2035         /*
2036          * Check for conflicting name snapshot name.
2037          */
2038         err = dsl_dataset_snap_lookup(ds, snapname, &value);
2039         if (err == 0)
2040                 return (EEXIST);
2041         if (err != ENOENT)
2042                 return (err);
2043 
2044         /*
2045          * Check that the dataset's name is not too long.  Name consists
2046          * of the dataset's length + 1 for the @-sign + snapshot name's length
2047          */
2048         if (dsl_dataset_namelen(ds) + 1 + strlen(snapname) >= MAXNAMELEN)
2049                 return (ENAMETOOLONG);
2050 
2051         err = dsl_dataset_snapshot_reserve_space(ds, tx);
2052         if (err)
2053                 return (err);
2054 
2055         ds->ds_trysnap_txg = tx->tx_txg;
2056         return (0);
2057 }
2058 
2059 void
2060 dsl_dataset_snapshot_sync(void *arg1, void *arg2, dmu_tx_t *tx)
2061 {
2062         dsl_dataset_t *ds = arg1;
2063         const char *snapname = arg2;
2064         dsl_pool_t *dp = ds->ds_dir->dd_pool;
2065         dmu_buf_t *dbuf;
2066         dsl_dataset_phys_t *dsphys;
2067         uint64_t dsobj, crtxg;
2068         objset_t *mos = dp->dp_meta_objset;
2069         int err;
2070 
2071         ASSERT(RW_WRITE_HELD(&dp->dp_config_rwlock));
2072 
2073         /*
2074          * The origin's ds_creation_txg has to be < TXG_INITIAL
2075          */
2076         if (strcmp(snapname, ORIGIN_DIR_NAME) == 0)
2077                 crtxg = 1;
2078         else
2079                 crtxg = tx->tx_txg;
2080 
2081         dsobj = dmu_object_alloc(mos, DMU_OT_DSL_DATASET, 0,
2082             DMU_OT_DSL_DATASET, sizeof (dsl_dataset_phys_t), tx);
2083         VERIFY(0 == dmu_bonus_hold(mos, dsobj, FTAG, &dbuf));
2084         dmu_buf_will_dirty(dbuf, tx);
2085         dsphys = dbuf->db_data;
2086         bzero(dsphys, sizeof (dsl_dataset_phys_t));
2087         dsphys->ds_dir_obj = ds->ds_dir->dd_object;
2088         dsphys->ds_fsid_guid = unique_create();
2089         do {
2090                 (void) random_get_pseudo_bytes((void*)&dsphys->ds_guid,
2091                     sizeof (dsphys->ds_guid));
2092         } while (dsphys->ds_guid == 0);
2093         dsphys->ds_prev_snap_obj = ds->ds_phys->ds_prev_snap_obj;
2094         dsphys->ds_prev_snap_txg = ds->ds_phys->ds_prev_snap_txg;
2095         dsphys->ds_next_snap_obj = ds->ds_object;
2096         dsphys->ds_num_children = 1;
2097         dsphys->ds_creation_time = gethrestime_sec();
2098         dsphys->ds_creation_txg = crtxg;
2099         dsphys->ds_deadlist_obj = ds->ds_phys->ds_deadlist_obj;
2100         dsphys->ds_referenced_bytes = ds->ds_phys->ds_referenced_bytes;
2101         dsphys->ds_compressed_bytes = ds->ds_phys->ds_compressed_bytes;
2102         dsphys->ds_uncompressed_bytes = ds->ds_phys->ds_uncompressed_bytes;
2103         dsphys->ds_flags = ds->ds_phys->ds_flags;
2104         dsphys->ds_bp = ds->ds_phys->ds_bp;
2105         dmu_buf_rele(dbuf, FTAG);
2106 
2107         ASSERT3U(ds->ds_prev != 0, ==, ds->ds_phys->ds_prev_snap_obj != 0);
2108         if (ds->ds_prev) {
2109                 uint64_t next_clones_obj =
2110                     ds->ds_prev->ds_phys->ds_next_clones_obj;
2111                 ASSERT(ds->ds_prev->ds_phys->ds_next_snap_obj ==
2112                     ds->ds_object ||
2113                     ds->ds_prev->ds_phys->ds_num_children > 1);
2114                 if (ds->ds_prev->ds_phys->ds_next_snap_obj == ds->ds_object) {
2115                         dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
2116                         ASSERT3U(ds->ds_phys->ds_prev_snap_txg, ==,
2117                             ds->ds_prev->ds_phys->ds_creation_txg);
2118                         ds->ds_prev->ds_phys->ds_next_snap_obj = dsobj;
2119                 } else if (next_clones_obj != 0) {
2120                         remove_from_next_clones(ds->ds_prev,
2121                             dsphys->ds_next_snap_obj, tx);
2122                         VERIFY3U(0, ==, zap_add_int(mos,
2123                             next_clones_obj, dsobj, tx));
2124                 }
2125         }
2126 
2127         /*
2128          * If we have a reference-reservation on this dataset, we will
2129          * need to increase the amount of refreservation being charged
2130          * since our unique space is going to zero.
2131          */
2132         if (ds->ds_reserved) {
2133                 int64_t delta;
2134                 ASSERT(DS_UNIQUE_IS_ACCURATE(ds));
2135                 delta = MIN(ds->ds_phys->ds_unique_bytes, ds->ds_reserved);
2136                 dsl_dir_diduse_space(ds->ds_dir, DD_USED_REFRSRV,
2137                     delta, 0, 0, tx);
2138         }
2139 
2140         dmu_buf_will_dirty(ds->ds_dbuf, tx);
2141         zfs_dbgmsg("taking snapshot %s@%s/%llu; newkey=%llu",
2142             ds->ds_dir->dd_myname, snapname, dsobj,
2143             ds->ds_phys->ds_prev_snap_txg);
2144         ds->ds_phys->ds_deadlist_obj = dsl_deadlist_clone(&ds->ds_deadlist,
2145             UINT64_MAX, ds->ds_phys->ds_prev_snap_obj, tx);
2146         dsl_deadlist_close(&ds->ds_deadlist);
2147         dsl_deadlist_open(&ds->ds_deadlist, mos, ds->ds_phys->ds_deadlist_obj);
2148         dsl_deadlist_add_key(&ds->ds_deadlist,
2149             ds->ds_phys->ds_prev_snap_txg, tx);
2150 
2151         ASSERT3U(ds->ds_phys->ds_prev_snap_txg, <, tx->tx_txg);
2152         ds->ds_phys->ds_prev_snap_obj = dsobj;
2153         ds->ds_phys->ds_prev_snap_txg = crtxg;
2154         ds->ds_phys->ds_unique_bytes = 0;
2155         if (spa_version(dp->dp_spa) >= SPA_VERSION_UNIQUE_ACCURATE)
2156                 ds->ds_phys->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
2157 
2158         err = zap_add(mos, ds->ds_phys->ds_snapnames_zapobj,
2159             snapname, 8, 1, &dsobj, tx);
2160         ASSERT(err == 0);
2161 
2162         if (ds->ds_prev)
2163                 dsl_dataset_drop_ref(ds->ds_prev, ds);
2164         VERIFY(0 == dsl_dataset_get_ref(dp,
2165             ds->ds_phys->ds_prev_snap_obj, ds, &ds->ds_prev));
2166 
2167         dsl_scan_ds_snapshotted(ds, tx);
2168 
2169         dsl_dir_snap_cmtime_update(ds->ds_dir);
2170 
2171         spa_history_log_internal(LOG_DS_SNAPSHOT, dp->dp_spa, tx,
2172             "dataset = %llu", dsobj);
2173 }
2174 
2175 void
2176 dsl_dataset_sync(dsl_dataset_t *ds, zio_t *zio, dmu_tx_t *tx)
2177 {
2178         ASSERT(dmu_tx_is_syncing(tx));
2179         ASSERT(ds->ds_objset != NULL);
2180         ASSERT(ds->ds_phys->ds_next_snap_obj == 0);
2181 
2182         /*
2183          * in case we had to change ds_fsid_guid when we opened it,
2184          * sync it out now.
2185          */
2186         dmu_buf_will_dirty(ds->ds_dbuf, tx);
2187         ds->ds_phys->ds_fsid_guid = ds->ds_fsid_guid;
2188 
2189         dsl_dir_dirty(ds->ds_dir, tx);
2190         dmu_objset_sync(ds->ds_objset, zio, tx);
2191 }
2192 
2193 static void
2194 get_clones_stat(dsl_dataset_t *ds, nvlist_t *nv)
2195 {
2196         uint64_t count = 0;
2197         objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
2198         zap_cursor_t zc;
2199         zap_attribute_t za;
2200         nvlist_t *propval;
2201         nvlist_t *val;
2202 
2203         rw_enter(&ds->ds_dir->dd_pool->dp_config_rwlock, RW_READER);
2204         VERIFY(nvlist_alloc(&propval, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2205         VERIFY(nvlist_alloc(&val, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2206 
2207         /*
2208          * There may me missing entries in ds_next_clones_obj
2209          * due to a bug in a previous version of the code.
2210          * Only trust it if it has the right number of entries.
2211          */
2212         if (ds->ds_phys->ds_next_clones_obj != 0) {
2213                 ASSERT3U(0, ==, zap_count(mos, ds->ds_phys->ds_next_clones_obj,
2214                     &count));
2215         }
2216         if (count != ds->ds_phys->ds_num_children - 1) {
2217                 goto fail;
2218         }
2219         for (zap_cursor_init(&zc, mos, ds->ds_phys->ds_next_clones_obj);
2220             zap_cursor_retrieve(&zc, &za) == 0;
2221             zap_cursor_advance(&zc)) {
2222                 dsl_dataset_t *clone;
2223                 char buf[ZFS_MAXNAMELEN];
2224                 /*
2225                  * Even though we hold the dp_config_rwlock, the dataset
2226                  * may fail to open, returning ENOENT.  If there is a
2227                  * thread concurrently attempting to destroy this
2228                  * dataset, it will have the ds_rwlock held for
2229                  * RW_WRITER.  Our call to dsl_dataset_hold_obj() ->
2230                  * dsl_dataset_hold_ref() will fail its
2231                  * rw_tryenter(&ds->ds_rwlock, RW_READER), drop the
2232                  * dp_config_rwlock, and wait for the destroy progress
2233                  * and signal ds_exclusive_cv.  If the destroy was
2234                  * successful, we will see that
2235                  * DSL_DATASET_IS_DESTROYED(), and return ENOENT.
2236                  */
2237                 if (dsl_dataset_hold_obj(ds->ds_dir->dd_pool,
2238                     za.za_first_integer, FTAG, &clone) != 0)
2239                         continue;
2240                 dsl_dir_name(clone->ds_dir, buf);
2241                 VERIFY(nvlist_add_boolean(val, buf) == 0);
2242                 dsl_dataset_rele(clone, FTAG);
2243         }
2244         zap_cursor_fini(&zc);
2245         VERIFY(nvlist_add_nvlist(propval, ZPROP_VALUE, val) == 0);
2246         VERIFY(nvlist_add_nvlist(nv, zfs_prop_to_name(ZFS_PROP_CLONES),
2247             propval) == 0);
2248 fail:
2249         nvlist_free(val);
2250         nvlist_free(propval);
2251         rw_exit(&ds->ds_dir->dd_pool->dp_config_rwlock);
2252 }
2253 
2254 void
2255 dsl_dataset_stats(dsl_dataset_t *ds, nvlist_t *nv)
2256 {
2257         uint64_t refd, avail, uobjs, aobjs, ratio;
2258 
2259         dsl_dir_stats(ds->ds_dir, nv);
2260 
2261         dsl_dataset_space(ds, &refd, &avail, &uobjs, &aobjs);
2262         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_AVAILABLE, avail);
2263         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFERENCED, refd);
2264 
2265         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_CREATION,
2266             ds->ds_phys->ds_creation_time);
2267         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_CREATETXG,
2268             ds->ds_phys->ds_creation_txg);
2269         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFQUOTA,
2270             ds->ds_quota);
2271         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFRESERVATION,
2272             ds->ds_reserved);
2273         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_GUID,
2274             ds->ds_phys->ds_guid);
2275         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_UNIQUE,
2276             ds->ds_phys->ds_unique_bytes);
2277         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_OBJSETID,
2278             ds->ds_object);
2279         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USERREFS,
2280             ds->ds_userrefs);
2281         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_DEFER_DESTROY,
2282             DS_IS_DEFER_DESTROY(ds) ? 1 : 0);
2283 
2284         if (ds->ds_phys->ds_prev_snap_obj != 0) {
2285                 uint64_t written, comp, uncomp;
2286                 dsl_pool_t *dp = ds->ds_dir->dd_pool;
2287                 dsl_dataset_t *prev;
2288 
2289                 rw_enter(&dp->dp_config_rwlock, RW_READER);
2290                 int err = dsl_dataset_hold_obj(dp,
2291                     ds->ds_phys->ds_prev_snap_obj, FTAG, &prev);
2292                 rw_exit(&dp->dp_config_rwlock);
2293                 if (err == 0) {
2294                         err = dsl_dataset_space_written(prev, ds, &written,
2295                             &comp, &uncomp);
2296                         dsl_dataset_rele(prev, FTAG);
2297                         if (err == 0) {
2298                                 dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_WRITTEN,
2299                                     written);
2300                         }
2301                 }
2302         }
2303 
2304         ratio = ds->ds_phys->ds_compressed_bytes == 0 ? 100 :
2305             (ds->ds_phys->ds_uncompressed_bytes * 100 /
2306             ds->ds_phys->ds_compressed_bytes);
2307         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFRATIO, ratio);
2308 
2309         if (ds->ds_phys->ds_next_snap_obj) {
2310                 /*
2311                  * This is a snapshot; override the dd's space used with
2312                  * our unique space and compression ratio.
2313                  */
2314                 dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USED,
2315                     ds->ds_phys->ds_unique_bytes);
2316                 dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_COMPRESSRATIO, ratio);
2317 
2318                 get_clones_stat(ds, nv);
2319         }
2320 }
2321 
2322 void
2323 dsl_dataset_fast_stat(dsl_dataset_t *ds, dmu_objset_stats_t *stat)
2324 {
2325         stat->dds_creation_txg = ds->ds_phys->ds_creation_txg;
2326         stat->dds_inconsistent = ds->ds_phys->ds_flags & DS_FLAG_INCONSISTENT;
2327         stat->dds_guid = ds->ds_phys->ds_guid;
2328         if (ds->ds_phys->ds_next_snap_obj) {
2329                 stat->dds_is_snapshot = B_TRUE;
2330                 stat->dds_num_clones = ds->ds_phys->ds_num_children - 1;
2331         } else {
2332                 stat->dds_is_snapshot = B_FALSE;
2333                 stat->dds_num_clones = 0;
2334         }
2335 
2336         /* clone origin is really a dsl_dir thing... */
2337         rw_enter(&ds->ds_dir->dd_pool->dp_config_rwlock, RW_READER);
2338         if (dsl_dir_is_clone(ds->ds_dir)) {
2339                 dsl_dataset_t *ods;
2340 
2341                 VERIFY(0 == dsl_dataset_get_ref(ds->ds_dir->dd_pool,
2342                     ds->ds_dir->dd_phys->dd_origin_obj, FTAG, &ods));
2343                 dsl_dataset_name(ods, stat->dds_origin);
2344                 dsl_dataset_drop_ref(ods, FTAG);
2345         } else {
2346                 stat->dds_origin[0] = '\0';
2347         }
2348         rw_exit(&ds->ds_dir->dd_pool->dp_config_rwlock);
2349 }
2350 
2351 uint64_t
2352 dsl_dataset_fsid_guid(dsl_dataset_t *ds)
2353 {
2354         return (ds->ds_fsid_guid);
2355 }
2356 
2357 void
2358 dsl_dataset_space(dsl_dataset_t *ds,
2359     uint64_t *refdbytesp, uint64_t *availbytesp,
2360     uint64_t *usedobjsp, uint64_t *availobjsp)
2361 {
2362         *refdbytesp = ds->ds_phys->ds_referenced_bytes;
2363         *availbytesp = dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE);
2364         if (ds->ds_reserved > ds->ds_phys->ds_unique_bytes)
2365                 *availbytesp += ds->ds_reserved - ds->ds_phys->ds_unique_bytes;
2366         if (ds->ds_quota != 0) {
2367                 /*
2368                  * Adjust available bytes according to refquota
2369                  */
2370                 if (*refdbytesp < ds->ds_quota)
2371                         *availbytesp = MIN(*availbytesp,
2372                             ds->ds_quota - *refdbytesp);
2373                 else
2374                         *availbytesp = 0;
2375         }
2376         *usedobjsp = ds->ds_phys->ds_bp.blk_fill;
2377         *availobjsp = DN_MAX_OBJECT - *usedobjsp;
2378 }
2379 
2380 boolean_t
2381 dsl_dataset_modified_since_lastsnap(dsl_dataset_t *ds)
2382 {
2383         dsl_pool_t *dp = ds->ds_dir->dd_pool;
2384 
2385         ASSERT(RW_LOCK_HELD(&dp->dp_config_rwlock) ||
2386             dsl_pool_sync_context(dp));
2387         if (ds->ds_prev == NULL)
2388                 return (B_FALSE);
2389         if (ds->ds_phys->ds_bp.blk_birth >
2390             ds->ds_prev->ds_phys->ds_creation_txg) {
2391                 objset_t *os, *os_prev;
2392                 /*
2393                  * It may be that only the ZIL differs, because it was
2394                  * reset in the head.  Don't count that as being
2395                  * modified.
2396                  */
2397                 if (dmu_objset_from_ds(ds, &os) != 0)
2398                         return (B_TRUE);
2399                 if (dmu_objset_from_ds(ds->ds_prev, &os_prev) != 0)
2400                         return (B_TRUE);
2401                 return (bcmp(&os->os_phys->os_meta_dnode,
2402                     &os_prev->os_phys->os_meta_dnode,
2403                     sizeof (os->os_phys->os_meta_dnode)) != 0);
2404         }
2405         return (B_FALSE);
2406 }
2407 
2408 /* ARGSUSED */
2409 static int
2410 dsl_dataset_snapshot_rename_check(void *arg1, void *arg2, dmu_tx_t *tx)
2411 {
2412         dsl_dataset_t *ds = arg1;
2413         char *newsnapname = arg2;
2414         dsl_dir_t *dd = ds->ds_dir;
2415         dsl_dataset_t *hds;
2416         uint64_t val;
2417         int err;
2418 
2419         err = dsl_dataset_hold_obj(dd->dd_pool,
2420             dd->dd_phys->dd_head_dataset_obj, FTAG, &hds);
2421         if (err)
2422                 return (err);
2423 
2424         /* new name better not be in use */
2425         err = dsl_dataset_snap_lookup(hds, newsnapname, &val);
2426         dsl_dataset_rele(hds, FTAG);
2427 
2428         if (err == 0)
2429                 err = EEXIST;
2430         else if (err == ENOENT)
2431                 err = 0;
2432 
2433         /* dataset name + 1 for the "@" + the new snapshot name must fit */
2434         if (dsl_dir_namelen(ds->ds_dir) + 1 + strlen(newsnapname) >= MAXNAMELEN)
2435                 err = ENAMETOOLONG;
2436 
2437         return (err);
2438 }
2439 
2440 static void
2441 dsl_dataset_snapshot_rename_sync(void *arg1, void *arg2, dmu_tx_t *tx)
2442 {
2443         dsl_dataset_t *ds = arg1;
2444         const char *newsnapname = arg2;
2445         dsl_dir_t *dd = ds->ds_dir;
2446         objset_t *mos = dd->dd_pool->dp_meta_objset;
2447         dsl_dataset_t *hds;
2448         int err;
2449 
2450         ASSERT(ds->ds_phys->ds_next_snap_obj != 0);
2451 
2452         VERIFY(0 == dsl_dataset_hold_obj(dd->dd_pool,
2453             dd->dd_phys->dd_head_dataset_obj, FTAG, &hds));
2454 
2455         VERIFY(0 == dsl_dataset_get_snapname(ds));
2456         err = dsl_dataset_snap_remove(hds, ds->ds_snapname, tx);
2457         ASSERT3U(err, ==, 0);
2458         mutex_enter(&ds->ds_lock);
2459         (void) strcpy(ds->ds_snapname, newsnapname);
2460         mutex_exit(&ds->ds_lock);
2461         err = zap_add(mos, hds->ds_phys->ds_snapnames_zapobj,
2462             ds->ds_snapname, 8, 1, &ds->ds_object, tx);
2463         ASSERT3U(err, ==, 0);
2464 
2465         spa_history_log_internal(LOG_DS_RENAME, dd->dd_pool->dp_spa, tx,
2466             "dataset = %llu", ds->ds_object);
2467         dsl_dataset_rele(hds, FTAG);
2468 }
2469 
2470 struct renamesnaparg {
2471         dsl_sync_task_group_t *dstg;
2472         char failed[MAXPATHLEN];
2473         char *oldsnap;
2474         char *newsnap;
2475 };
2476 
2477 static int
2478 dsl_snapshot_rename_one(const char *name, void *arg)
2479 {
2480         struct renamesnaparg *ra = arg;
2481         dsl_dataset_t *ds = NULL;
2482         char *snapname;
2483         int err;
2484 
2485         snapname = kmem_asprintf("%s@%s", name, ra->oldsnap);
2486         (void) strlcpy(ra->failed, snapname, sizeof (ra->failed));
2487 
2488         /*
2489          * For recursive snapshot renames the parent won't be changing
2490          * so we just pass name for both the to/from argument.
2491          */
2492         err = zfs_secpolicy_rename_perms(snapname, snapname, CRED());
2493         if (err != 0) {
2494                 strfree(snapname);
2495                 return (err == ENOENT ? 0 : err);
2496         }
2497 
2498 #ifdef _KERNEL
2499         /*
2500          * For all filesystems undergoing rename, we'll need to unmount it.
2501          */
2502         (void) zfs_unmount_snap(snapname, NULL);
2503 #endif
2504         err = dsl_dataset_hold(snapname, ra->dstg, &ds);
2505         strfree(snapname);
2506         if (err != 0)
2507                 return (err == ENOENT ? 0 : err);
2508 
2509         dsl_sync_task_create(ra->dstg, dsl_dataset_snapshot_rename_check,
2510             dsl_dataset_snapshot_rename_sync, ds, ra->newsnap, 0);
2511 
2512         return (0);
2513 }
2514 
2515 static int
2516 dsl_recursive_rename(char *oldname, const char *newname)
2517 {
2518         int err;
2519         struct renamesnaparg *ra;
2520         dsl_sync_task_t *dst;
2521         spa_t *spa;
2522         char *cp, *fsname = spa_strdup(oldname);
2523         int len = strlen(oldname) + 1;
2524 
2525         /* truncate the snapshot name to get the fsname */
2526         cp = strchr(fsname, '@');
2527         *cp = '\0';
2528 
2529         err = spa_open(fsname, &spa, FTAG);
2530         if (err) {
2531                 kmem_free(fsname, len);
2532                 return (err);
2533         }
2534         ra = kmem_alloc(sizeof (struct renamesnaparg), KM_SLEEP);
2535         ra->dstg = dsl_sync_task_group_create(spa_get_dsl(spa));
2536 
2537         ra->oldsnap = strchr(oldname, '@') + 1;
2538         ra->newsnap = strchr(newname, '@') + 1;
2539         *ra->failed = '\0';
2540 
2541         err = dmu_objset_find(fsname, dsl_snapshot_rename_one, ra,
2542             DS_FIND_CHILDREN);
2543         kmem_free(fsname, len);
2544 
2545         if (err == 0) {
2546                 err = dsl_sync_task_group_wait(ra->dstg);
2547         }
2548 
2549         for (dst = list_head(&ra->dstg->dstg_tasks); dst;
2550             dst = list_next(&ra->dstg->dstg_tasks, dst)) {
2551                 dsl_dataset_t *ds = dst->dst_arg1;
2552                 if (dst->dst_err) {
2553                         dsl_dir_name(ds->ds_dir, ra->failed);
2554                         (void) strlcat(ra->failed, "@", sizeof (ra->failed));
2555                         (void) strlcat(ra->failed, ra->newsnap,
2556                             sizeof (ra->failed));
2557                 }
2558                 dsl_dataset_rele(ds, ra->dstg);
2559         }
2560 
2561         if (err)
2562                 (void) strlcpy(oldname, ra->failed, sizeof (ra->failed));
2563 
2564         dsl_sync_task_group_destroy(ra->dstg);
2565         kmem_free(ra, sizeof (struct renamesnaparg));
2566         spa_close(spa, FTAG);
2567         return (err);
2568 }
2569 
2570 static int
2571 dsl_valid_rename(const char *oldname, void *arg)
2572 {
2573         int delta = *(int *)arg;
2574 
2575         if (strlen(oldname) + delta >= MAXNAMELEN)
2576                 return (ENAMETOOLONG);
2577 
2578         return (0);
2579 }
2580 
2581 #pragma weak dmu_objset_rename = dsl_dataset_rename
2582 int
2583 dsl_dataset_rename(char *oldname, const char *newname, boolean_t recursive)
2584 {
2585         dsl_dir_t *dd;
2586         dsl_dataset_t *ds;
2587         const char *tail;
2588         int err;
2589 
2590         err = dsl_dir_open(oldname, FTAG, &dd, &tail);
2591         if (err)
2592                 return (err);
2593 
2594         if (tail == NULL) {
2595                 int delta = strlen(newname) - strlen(oldname);
2596 
2597                 /* if we're growing, validate child name lengths */
2598                 if (delta > 0)
2599                         err = dmu_objset_find(oldname, dsl_valid_rename,
2600                             &delta, DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
2601 
2602                 if (err == 0)
2603                         err = dsl_dir_rename(dd, newname);
2604                 dsl_dir_close(dd, FTAG);
2605                 return (err);
2606         }
2607 
2608         if (tail[0] != '@') {
2609                 /* the name ended in a nonexistent component */
2610                 dsl_dir_close(dd, FTAG);
2611                 return (ENOENT);
2612         }
2613 
2614         dsl_dir_close(dd, FTAG);
2615 
2616         /* new name must be snapshot in same filesystem */
2617         tail = strchr(newname, '@');
2618         if (tail == NULL)
2619                 return (EINVAL);
2620         tail++;
2621         if (strncmp(oldname, newname, tail - newname) != 0)
2622                 return (EXDEV);
2623 
2624         if (recursive) {
2625                 err = dsl_recursive_rename(oldname, newname);
2626         } else {
2627                 err = dsl_dataset_hold(oldname, FTAG, &ds);
2628                 if (err)
2629                         return (err);
2630 
2631                 err = dsl_sync_task_do(ds->ds_dir->dd_pool,
2632                     dsl_dataset_snapshot_rename_check,
2633                     dsl_dataset_snapshot_rename_sync, ds, (char *)tail, 1);
2634 
2635                 dsl_dataset_rele(ds, FTAG);
2636         }
2637 
2638         return (err);
2639 }
2640 
2641 struct promotenode {
2642         list_node_t link;
2643         dsl_dataset_t *ds;
2644 };
2645 
2646 struct promotearg {
2647         list_t shared_snaps, origin_snaps, clone_snaps;
2648         dsl_dataset_t *origin_origin;
2649         uint64_t used, comp, uncomp, unique, cloneusedsnap, originusedsnap;
2650         char *err_ds;
2651 };
2652 
2653 static int snaplist_space(list_t *l, uint64_t mintxg, uint64_t *spacep);
2654 static boolean_t snaplist_unstable(list_t *l);
2655 
2656 static int
2657 dsl_dataset_promote_check(void *arg1, void *arg2, dmu_tx_t *tx)
2658 {
2659         dsl_dataset_t *hds = arg1;
2660         struct promotearg *pa = arg2;
2661         struct promotenode *snap = list_head(&pa->shared_snaps);
2662         dsl_dataset_t *origin_ds = snap->ds;
2663         int err;
2664         uint64_t unused;
2665 
2666         /* Check that it is a real clone */
2667         if (!dsl_dir_is_clone(hds->ds_dir))
2668                 return (EINVAL);
2669 
2670         /* Since this is so expensive, don't do the preliminary check */
2671         if (!dmu_tx_is_syncing(tx))
2672                 return (0);
2673 
2674         if (hds->ds_phys->ds_flags & DS_FLAG_NOPROMOTE)
2675                 return (EXDEV);
2676 
2677         /* compute origin's new unique space */
2678         snap = list_tail(&pa->clone_snaps);
2679         ASSERT3U(snap->ds->ds_phys->ds_prev_snap_obj, ==, origin_ds->ds_object);
2680         dsl_deadlist_space_range(&snap->ds->ds_deadlist,
2681             origin_ds->ds_phys->ds_prev_snap_txg, UINT64_MAX,
2682             &pa->unique, &unused, &unused);
2683 
2684         /*
2685          * Walk the snapshots that we are moving
2686          *
2687          * Compute space to transfer.  Consider the incremental changes
2688          * to used for each snapshot:
2689          * (my used) = (prev's used) + (blocks born) - (blocks killed)
2690          * So each snapshot gave birth to:
2691          * (blocks born) = (my used) - (prev's used) + (blocks killed)
2692          * So a sequence would look like:
2693          * (uN - u(N-1) + kN) + ... + (u1 - u0 + k1) + (u0 - 0 + k0)
2694          * Which simplifies to:
2695          * uN + kN + kN-1 + ... + k1 + k0
2696          * Note however, if we stop before we reach the ORIGIN we get:
2697          * uN + kN + kN-1 + ... + kM - uM-1
2698          */
2699         pa->used = origin_ds->ds_phys->ds_referenced_bytes;
2700         pa->comp = origin_ds->ds_phys->ds_compressed_bytes;
2701         pa->uncomp = origin_ds->ds_phys->ds_uncompressed_bytes;
2702         for (snap = list_head(&pa->shared_snaps); snap;
2703             snap = list_next(&pa->shared_snaps, snap)) {
2704                 uint64_t val, dlused, dlcomp, dluncomp;
2705                 dsl_dataset_t *ds = snap->ds;
2706 
2707                 /* Check that the snapshot name does not conflict */
2708                 VERIFY(0 == dsl_dataset_get_snapname(ds));
2709                 err = dsl_dataset_snap_lookup(hds, ds->ds_snapname, &val);
2710                 if (err == 0) {
2711                         err = EEXIST;
2712                         goto out;
2713                 }
2714                 if (err != ENOENT)
2715                         goto out;
2716 
2717                 /* The very first snapshot does not have a deadlist */
2718                 if (ds->ds_phys->ds_prev_snap_obj == 0)
2719                         continue;
2720 
2721                 dsl_deadlist_space(&ds->ds_deadlist,
2722                     &dlused, &dlcomp, &dluncomp);
2723                 pa->used += dlused;
2724                 pa->comp += dlcomp;
2725                 pa->uncomp += dluncomp;
2726         }
2727 
2728         /*
2729          * If we are a clone of a clone then we never reached ORIGIN,
2730          * so we need to subtract out the clone origin's used space.
2731          */
2732         if (pa->origin_origin) {
2733                 pa->used -= pa->origin_origin->ds_phys->ds_referenced_bytes;
2734                 pa->comp -= pa->origin_origin->ds_phys->ds_compressed_bytes;
2735                 pa->uncomp -= pa->origin_origin->ds_phys->ds_uncompressed_bytes;
2736         }
2737 
2738         /* Check that there is enough space here */
2739         err = dsl_dir_transfer_possible(origin_ds->ds_dir, hds->ds_dir,
2740             pa->used);
2741         if (err)
2742                 return (err);
2743 
2744         /*
2745          * Compute the amounts of space that will be used by snapshots
2746          * after the promotion (for both origin and clone).  For each,
2747          * it is the amount of space that will be on all of their
2748          * deadlists (that was not born before their new origin).
2749          */
2750         if (hds->ds_dir->dd_phys->dd_flags & DD_FLAG_USED_BREAKDOWN) {
2751                 uint64_t space;
2752 
2753                 /*
2754                  * Note, typically this will not be a clone of a clone,
2755                  * so dd_origin_txg will be < TXG_INITIAL, so
2756                  * these snaplist_space() -> dsl_deadlist_space_range()
2757                  * calls will be fast because they do not have to
2758                  * iterate over all bps.
2759                  */
2760                 snap = list_head(&pa->origin_snaps);
2761                 err = snaplist_space(&pa->shared_snaps,
2762                     snap->ds->ds_dir->dd_origin_txg, &pa->cloneusedsnap);
2763                 if (err)
2764                         return (err);
2765 
2766                 err = snaplist_space(&pa->clone_snaps,
2767                     snap->ds->ds_dir->dd_origin_txg, &space);
2768                 if (err)
2769                         return (err);
2770                 pa->cloneusedsnap += space;
2771         }
2772         if (origin_ds->ds_dir->dd_phys->dd_flags & DD_FLAG_USED_BREAKDOWN) {
2773                 err = snaplist_space(&pa->origin_snaps,
2774                     origin_ds->ds_phys->ds_creation_txg, &pa->originusedsnap);
2775                 if (err)
2776                         return (err);
2777         }
2778 
2779         return (0);
2780 out:
2781         pa->err_ds =  snap->ds->ds_snapname;
2782         return (err);
2783 }
2784 
2785 static void
2786 dsl_dataset_promote_sync(void *arg1, void *arg2, dmu_tx_t *tx)
2787 {
2788         dsl_dataset_t *hds = arg1;
2789         struct promotearg *pa = arg2;
2790         struct promotenode *snap = list_head(&pa->shared_snaps);
2791         dsl_dataset_t *origin_ds = snap->ds;
2792         dsl_dataset_t *origin_head;
2793         dsl_dir_t *dd = hds->ds_dir;
2794         dsl_pool_t *dp = hds->ds_dir->dd_pool;
2795         dsl_dir_t *odd = NULL;
2796         uint64_t oldnext_obj;
2797         int64_t delta;
2798 
2799         ASSERT(0 == (hds->ds_phys->ds_flags & DS_FLAG_NOPROMOTE));
2800 
2801         snap = list_head(&pa->origin_snaps);
2802         origin_head = snap->ds;
2803 
2804         /*
2805          * We need to explicitly open odd, since origin_ds's dd will be
2806          * changing.
2807          */
2808         VERIFY(0 == dsl_dir_open_obj(dp, origin_ds->ds_dir->dd_object,
2809             NULL, FTAG, &odd));
2810 
2811         /* change origin's next snap */
2812         dmu_buf_will_dirty(origin_ds->ds_dbuf, tx);
2813         oldnext_obj = origin_ds->ds_phys->ds_next_snap_obj;
2814         snap = list_tail(&pa->clone_snaps);
2815         ASSERT3U(snap->ds->ds_phys->ds_prev_snap_obj, ==, origin_ds->ds_object);
2816         origin_ds->ds_phys->ds_next_snap_obj = snap->ds->ds_object;
2817 
2818         /* change the origin's next clone */
2819         if (origin_ds->ds_phys->ds_next_clones_obj) {
2820                 remove_from_next_clones(origin_ds, snap->ds->ds_object, tx);
2821                 VERIFY3U(0, ==, zap_add_int(dp->dp_meta_objset,
2822                     origin_ds->ds_phys->ds_next_clones_obj,
2823                     oldnext_obj, tx));
2824         }
2825 
2826         /* change origin */
2827         dmu_buf_will_dirty(dd->dd_dbuf, tx);
2828         ASSERT3U(dd->dd_phys->dd_origin_obj, ==, origin_ds->ds_object);
2829         dd->dd_phys->dd_origin_obj = odd->dd_phys->dd_origin_obj;
2830         dd->dd_origin_txg = origin_head->ds_dir->dd_origin_txg;
2831         dmu_buf_will_dirty(odd->dd_dbuf, tx);
2832         odd->dd_phys->dd_origin_obj = origin_ds->ds_object;
2833         origin_head->ds_dir->dd_origin_txg =
2834             origin_ds->ds_phys->ds_creation_txg;
2835 
2836         /* change dd_clone entries */
2837         if (spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
2838                 VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
2839                     odd->dd_phys->dd_clones, hds->ds_object, tx));
2840                 VERIFY3U(0, ==, zap_add_int(dp->dp_meta_objset,
2841                     pa->origin_origin->ds_dir->dd_phys->dd_clones,
2842                     hds->ds_object, tx));
2843 
2844                 VERIFY3U(0, ==, zap_remove_int(dp->dp_meta_objset,
2845                     pa->origin_origin->ds_dir->dd_phys->dd_clones,
2846                     origin_head->ds_object, tx));
2847                 if (dd->dd_phys->dd_clones == 0) {
2848                         dd->dd_phys->dd_clones = zap_create(dp->dp_meta_objset,
2849                             DMU_OT_DSL_CLONES, DMU_OT_NONE, 0, tx);
2850                 }
2851                 VERIFY3U(0, ==, zap_add_int(dp->dp_meta_objset,
2852                     dd->dd_phys->dd_clones, origin_head->ds_object, tx));
2853 
2854         }
2855 
2856         /* move snapshots to this dir */
2857         for (snap = list_head(&pa->shared_snaps); snap;
2858             snap = list_next(&pa->shared_snaps, snap)) {
2859                 dsl_dataset_t *ds = snap->ds;
2860 
2861                 /* unregister props as dsl_dir is changing */
2862                 if (ds->ds_objset) {
2863                         dmu_objset_evict(ds->ds_objset);
2864                         ds->ds_objset = NULL;
2865                 }
2866                 /* move snap name entry */
2867                 VERIFY(0 == dsl_dataset_get_snapname(ds));
2868                 VERIFY(0 == dsl_dataset_snap_remove(origin_head,
2869                     ds->ds_snapname, tx));
2870                 VERIFY(0 == zap_add(dp->dp_meta_objset,
2871                     hds->ds_phys->ds_snapnames_zapobj, ds->ds_snapname,
2872                     8, 1, &ds->ds_object, tx));
2873 
2874                 /* change containing dsl_dir */
2875                 dmu_buf_will_dirty(ds->ds_dbuf, tx);
2876                 ASSERT3U(ds->ds_phys->ds_dir_obj, ==, odd->dd_object);
2877                 ds->ds_phys->ds_dir_obj = dd->dd_object;
2878                 ASSERT3P(ds->ds_dir, ==, odd);
2879                 dsl_dir_close(ds->ds_dir, ds);
2880                 VERIFY(0 == dsl_dir_open_obj(dp, dd->dd_object,
2881                     NULL, ds, &ds->ds_dir));
2882 
2883                 /* move any clone references */
2884                 if (ds->ds_phys->ds_next_clones_obj &&
2885                     spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
2886                         zap_cursor_t zc;
2887                         zap_attribute_t za;
2888 
2889                         for (zap_cursor_init(&zc, dp->dp_meta_objset,
2890                             ds->ds_phys->ds_next_clones_obj);
2891                             zap_cursor_retrieve(&zc, &za) == 0;
2892                             zap_cursor_advance(&zc)) {
2893                                 dsl_dataset_t *cnds;
2894                                 uint64_t o;
2895 
2896                                 if (za.za_first_integer == oldnext_obj) {
2897                                         /*
2898                                          * We've already moved the
2899                                          * origin's reference.
2900                                          */
2901                                         continue;
2902                                 }
2903 
2904                                 VERIFY3U(0, ==, dsl_dataset_hold_obj(dp,
2905                                     za.za_first_integer, FTAG, &cnds));
2906                                 o = cnds->ds_dir->dd_phys->dd_head_dataset_obj;
2907 
2908                                 VERIFY3U(zap_remove_int(dp->dp_meta_objset,
2909                                     odd->dd_phys->dd_clones, o, tx), ==, 0);
2910                                 VERIFY3U(zap_add_int(dp->dp_meta_objset,
2911                                     dd->dd_phys->dd_clones, o, tx), ==, 0);
2912                                 dsl_dataset_rele(cnds, FTAG);
2913                         }
2914                         zap_cursor_fini(&zc);
2915                 }
2916 
2917                 ASSERT3U(dsl_prop_numcb(ds), ==, 0);
2918         }
2919 
2920         /*
2921          * Change space accounting.
2922          * Note, pa->*usedsnap and dd_used_breakdown[SNAP] will either
2923          * both be valid, or both be 0 (resulting in delta == 0).  This
2924          * is true for each of {clone,origin} independently.
2925          */
2926 
2927         delta = pa->cloneusedsnap -
2928             dd->dd_phys->dd_used_breakdown[DD_USED_SNAP];
2929         ASSERT3S(delta, >=, 0);
2930         ASSERT3U(pa->used, >=, delta);
2931         dsl_dir_diduse_space(dd, DD_USED_SNAP, delta, 0, 0, tx);
2932         dsl_dir_diduse_space(dd, DD_USED_HEAD,
2933             pa->used - delta, pa->comp, pa->uncomp, tx);
2934 
2935         delta = pa->originusedsnap -
2936             odd->dd_phys->dd_used_breakdown[DD_USED_SNAP];
2937         ASSERT3S(delta, <=, 0);
2938         ASSERT3U(pa->used, >=, -delta);
2939         dsl_dir_diduse_space(odd, DD_USED_SNAP, delta, 0, 0, tx);
2940         dsl_dir_diduse_space(odd, DD_USED_HEAD,
2941             -pa->used - delta, -pa->comp, -pa->uncomp, tx);
2942 
2943         origin_ds->ds_phys->ds_unique_bytes = pa->unique;
2944 
2945         /* log history record */
2946         spa_history_log_internal(LOG_DS_PROMOTE, dd->dd_pool->dp_spa, tx,
2947             "dataset = %llu", hds->ds_object);
2948 
2949         dsl_dir_close(odd, FTAG);
2950 }
2951 
2952 static char *snaplist_tag = "snaplist";
2953 /*
2954  * Make a list of dsl_dataset_t's for the snapshots between first_obj
2955  * (exclusive) and last_obj (inclusive).  The list will be in reverse
2956  * order (last_obj will be the list_head()).  If first_obj == 0, do all
2957  * snapshots back to this dataset's origin.
2958  */
2959 static int
2960 snaplist_make(dsl_pool_t *dp, boolean_t own,
2961     uint64_t first_obj, uint64_t last_obj, list_t *l)
2962 {
2963         uint64_t obj = last_obj;
2964 
2965         ASSERT(RW_LOCK_HELD(&dp->dp_config_rwlock));
2966 
2967         list_create(l, sizeof (struct promotenode),
2968             offsetof(struct promotenode, link));
2969 
2970         while (obj != first_obj) {
2971                 dsl_dataset_t *ds;
2972                 struct promotenode *snap;
2973                 int err;
2974 
2975                 if (own) {
2976                         err = dsl_dataset_own_obj(dp, obj,
2977                             0, snaplist_tag, &ds);
2978                         if (err == 0)
2979                                 dsl_dataset_make_exclusive(ds, snaplist_tag);
2980                 } else {
2981                         err = dsl_dataset_hold_obj(dp, obj, snaplist_tag, &ds);
2982                 }
2983                 if (err == ENOENT) {
2984                         /* lost race with snapshot destroy */
2985                         struct promotenode *last = list_tail(l);
2986                         ASSERT(obj != last->ds->ds_phys->ds_prev_snap_obj);
2987                         obj = last->ds->ds_phys->ds_prev_snap_obj;
2988                         continue;
2989                 } else if (err) {
2990                         return (err);
2991                 }
2992 
2993                 if (first_obj == 0)
2994                         first_obj = ds->ds_dir->dd_phys->dd_origin_obj;
2995 
2996                 snap = kmem_alloc(sizeof (struct promotenode), KM_SLEEP);
2997                 snap->ds = ds;
2998                 list_insert_tail(l, snap);
2999                 obj = ds->ds_phys->ds_prev_snap_obj;
3000         }
3001 
3002         return (0);
3003 }
3004 
3005 static int
3006 snaplist_space(list_t *l, uint64_t mintxg, uint64_t *spacep)
3007 {
3008         struct promotenode *snap;
3009 
3010         *spacep = 0;
3011         for (snap = list_head(l); snap; snap = list_next(l, snap)) {
3012                 uint64_t used, comp, uncomp;
3013                 dsl_deadlist_space_range(&snap->ds->ds_deadlist,
3014                     mintxg, UINT64_MAX, &used, &comp, &uncomp);
3015                 *spacep += used;
3016         }
3017         return (0);
3018 }
3019 
3020 static void
3021 snaplist_destroy(list_t *l, boolean_t own)
3022 {
3023         struct promotenode *snap;
3024 
3025         if (!l || !list_link_active(&l->list_head))
3026                 return;
3027 
3028         while ((snap = list_tail(l)) != NULL) {
3029                 list_remove(l, snap);
3030                 if (own)
3031                         dsl_dataset_disown(snap->ds, snaplist_tag);
3032                 else
3033                         dsl_dataset_rele(snap->ds, snaplist_tag);
3034                 kmem_free(snap, sizeof (struct promotenode));
3035         }
3036         list_destroy(l);
3037 }
3038 
3039 /*
3040  * Promote a clone.  Nomenclature note:
3041  * "clone" or "cds": the original clone which is being promoted
3042  * "origin" or "ods": the snapshot which is originally clone's origin
3043  * "origin head" or "ohds": the dataset which is the head
3044  * (filesystem/volume) for the origin
3045  * "origin origin": the origin of the origin's filesystem (typically
3046  * NULL, indicating that the clone is not a clone of a clone).
3047  */
3048 int
3049 dsl_dataset_promote(const char *name, char *conflsnap)
3050 {
3051         dsl_dataset_t *ds;
3052         dsl_dir_t *dd;
3053         dsl_pool_t *dp;
3054         dmu_object_info_t doi;
3055         struct promotearg pa = { 0 };
3056         struct promotenode *snap;
3057         int err;
3058 
3059         err = dsl_dataset_hold(name, FTAG, &ds);
3060         if (err)
3061                 return (err);
3062         dd = ds->ds_dir;
3063         dp = dd->dd_pool;
3064 
3065         err = dmu_object_info(dp->dp_meta_objset,
3066             ds->ds_phys->ds_snapnames_zapobj, &doi);
3067         if (err) {
3068                 dsl_dataset_rele(ds, FTAG);
3069                 return (err);
3070         }
3071 
3072         if (dsl_dataset_is_snapshot(ds) || dd->dd_phys->dd_origin_obj == 0) {
3073                 dsl_dataset_rele(ds, FTAG);
3074                 return (EINVAL);
3075         }
3076 
3077         /*
3078          * We are going to inherit all the snapshots taken before our
3079          * origin (i.e., our new origin will be our parent's origin).
3080          * Take ownership of them so that we can rename them into our
3081          * namespace.
3082          */
3083         rw_enter(&dp->dp_config_rwlock, RW_READER);
3084 
3085         err = snaplist_make(dp, B_TRUE, 0, dd->dd_phys->dd_origin_obj,
3086             &pa.shared_snaps);
3087         if (err != 0)
3088                 goto out;
3089 
3090         err = snaplist_make(dp, B_FALSE, 0, ds->ds_object, &pa.clone_snaps);
3091         if (err != 0)
3092                 goto out;
3093 
3094         snap = list_head(&pa.shared_snaps);
3095         ASSERT3U(snap->ds->ds_object, ==, dd->dd_phys->dd_origin_obj);
3096         err = snaplist_make(dp, B_FALSE, dd->dd_phys->dd_origin_obj,
3097             snap->ds->ds_dir->dd_phys->dd_head_dataset_obj, &pa.origin_snaps);
3098         if (err != 0)
3099                 goto out;
3100 
3101         if (snap->ds->ds_dir->dd_phys->dd_origin_obj != 0) {
3102                 err = dsl_dataset_hold_obj(dp,
3103                     snap->ds->ds_dir->dd_phys->dd_origin_obj,
3104                     FTAG, &pa.origin_origin);
3105                 if (err != 0)
3106                         goto out;
3107         }
3108 
3109 out:
3110         rw_exit(&dp->dp_config_rwlock);
3111 
3112         /*
3113          * Add in 128x the snapnames zapobj size, since we will be moving
3114          * a bunch of snapnames to the promoted ds, and dirtying their
3115          * bonus buffers.
3116          */
3117         if (err == 0) {
3118                 err = dsl_sync_task_do(dp, dsl_dataset_promote_check,
3119                     dsl_dataset_promote_sync, ds, &pa,
3120                     2 + 2 * doi.doi_physical_blocks_512);
3121                 if (err && pa.err_ds && conflsnap)
3122                         (void) strncpy(conflsnap, pa.err_ds, MAXNAMELEN);
3123         }
3124 
3125         snaplist_destroy(&pa.shared_snaps, B_TRUE);
3126         snaplist_destroy(&pa.clone_snaps, B_FALSE);
3127         snaplist_destroy(&pa.origin_snaps, B_FALSE);
3128         if (pa.origin_origin)
3129                 dsl_dataset_rele(pa.origin_origin, FTAG);
3130         dsl_dataset_rele(ds, FTAG);
3131         return (err);
3132 }
3133 
3134 struct cloneswaparg {
3135         dsl_dataset_t *cds; /* clone dataset */
3136         dsl_dataset_t *ohds; /* origin's head dataset */
3137         boolean_t force;
3138         int64_t unused_refres_delta; /* change in unconsumed refreservation */
3139 };
3140 
3141 /* ARGSUSED */
3142 static int
3143 dsl_dataset_clone_swap_check(void *arg1, void *arg2, dmu_tx_t *tx)
3144 {
3145         struct cloneswaparg *csa = arg1;
3146 
3147         /* they should both be heads */
3148         if (dsl_dataset_is_snapshot(csa->cds) ||
3149             dsl_dataset_is_snapshot(csa->ohds))
3150                 return (EINVAL);
3151 
3152         /* the branch point should be just before them */
3153         if (csa->cds->ds_prev != csa->ohds->ds_prev)
3154                 return (EINVAL);
3155 
3156         /* cds should be the clone (unless they are unrelated) */
3157         if (csa->cds->ds_prev != NULL &&
3158             csa->cds->ds_prev != csa->cds->ds_dir->dd_pool->dp_origin_snap &&
3159             csa->ohds->ds_object !=
3160             csa->cds->ds_prev->ds_phys->ds_next_snap_obj)
3161                 return (EINVAL);
3162 
3163         /* the clone should be a child of the origin */
3164         if (csa->cds->ds_dir->dd_parent != csa->ohds->ds_dir)
3165                 return (EINVAL);
3166 
3167         /* ohds shouldn't be modified unless 'force' */
3168         if (!csa->force && dsl_dataset_modified_since_lastsnap(csa->ohds))
3169                 return (ETXTBSY);
3170 
3171         /* adjust amount of any unconsumed refreservation */
3172         csa->unused_refres_delta =
3173             (int64_t)MIN(csa->ohds->ds_reserved,
3174             csa->ohds->ds_phys->ds_unique_bytes) -
3175             (int64_t)MIN(csa->ohds->ds_reserved,
3176             csa->cds->ds_phys->ds_unique_bytes);
3177 
3178         if (csa->unused_refres_delta > 0 &&
3179             csa->unused_refres_delta >
3180             dsl_dir_space_available(csa->ohds->ds_dir, NULL, 0, TRUE))
3181                 return (ENOSPC);
3182 
3183         if (csa->ohds->ds_quota != 0 &&
3184             csa->cds->ds_phys->ds_unique_bytes > csa->ohds->ds_quota)
3185                 return (EDQUOT);
3186 
3187         return (0);
3188 }
3189 
3190 /* ARGSUSED */
3191 static void
3192 dsl_dataset_clone_swap_sync(void *arg1, void *arg2, dmu_tx_t *tx)
3193 {
3194         struct cloneswaparg *csa = arg1;
3195         dsl_pool_t *dp = csa->cds->ds_dir->dd_pool;
3196 
3197         ASSERT(csa->cds->ds_reserved == 0);
3198         ASSERT(csa->ohds->ds_quota == 0 ||
3199             csa->cds->ds_phys->ds_unique_bytes <= csa->ohds->ds_quota);
3200 
3201         dmu_buf_will_dirty(csa->cds->ds_dbuf, tx);
3202         dmu_buf_will_dirty(csa->ohds->ds_dbuf, tx);
3203 
3204         if (csa->cds->ds_objset != NULL) {
3205                 dmu_objset_evict(csa->cds->ds_objset);
3206                 csa->cds->ds_objset = NULL;
3207         }
3208 
3209         if (csa->ohds->ds_objset != NULL) {
3210                 dmu_objset_evict(csa->ohds->ds_objset);
3211                 csa->ohds->ds_objset = NULL;
3212         }
3213 
3214         /*
3215          * Reset origin's unique bytes, if it exists.
3216          */
3217         if (csa->cds->ds_prev) {
3218                 dsl_dataset_t *origin = csa->cds->ds_prev;
3219                 uint64_t comp, uncomp;
3220 
3221                 dmu_buf_will_dirty(origin->ds_dbuf, tx);
3222                 dsl_deadlist_space_range(&csa->cds->ds_deadlist,
3223                     origin->ds_phys->ds_prev_snap_txg, UINT64_MAX,
3224                     &origin->ds_phys->ds_unique_bytes, &comp, &uncomp);
3225         }
3226 
3227         /* swap blkptrs */
3228         {
3229                 blkptr_t tmp;
3230                 tmp = csa->ohds->ds_phys->ds_bp;
3231                 csa->ohds->ds_phys->ds_bp = csa->cds->ds_phys->ds_bp;
3232                 csa->cds->ds_phys->ds_bp = tmp;
3233         }
3234 
3235         /* set dd_*_bytes */
3236         {
3237                 int64_t dused, dcomp, duncomp;
3238                 uint64_t cdl_used, cdl_comp, cdl_uncomp;
3239                 uint64_t odl_used, odl_comp, odl_uncomp;
3240 
3241                 ASSERT3U(csa->cds->ds_dir->dd_phys->
3242                     dd_used_breakdown[DD_USED_SNAP], ==, 0);
3243 
3244                 dsl_deadlist_space(&csa->cds->ds_deadlist,
3245                     &cdl_used, &cdl_comp, &cdl_uncomp);
3246                 dsl_deadlist_space(&csa->ohds->ds_deadlist,
3247                     &odl_used, &odl_comp, &odl_uncomp);
3248 
3249                 dused = csa->cds->ds_phys->ds_referenced_bytes + cdl_used -
3250                     (csa->ohds->ds_phys->ds_referenced_bytes + odl_used);
3251                 dcomp = csa->cds->ds_phys->ds_compressed_bytes + cdl_comp -
3252                     (csa->ohds->ds_phys->ds_compressed_bytes + odl_comp);
3253                 duncomp = csa->cds->ds_phys->ds_uncompressed_bytes +
3254                     cdl_uncomp -
3255                     (csa->ohds->ds_phys->ds_uncompressed_bytes + odl_uncomp);
3256 
3257                 dsl_dir_diduse_space(csa->ohds->ds_dir, DD_USED_HEAD,
3258                     dused, dcomp, duncomp, tx);
3259                 dsl_dir_diduse_space(csa->cds->ds_dir, DD_USED_HEAD,
3260                     -dused, -dcomp, -duncomp, tx);
3261 
3262                 /*
3263                  * The difference in the space used by snapshots is the
3264                  * difference in snapshot space due to the head's
3265                  * deadlist (since that's the only thing that's
3266                  * changing that affects the snapused).
3267                  */
3268                 dsl_deadlist_space_range(&csa->cds->ds_deadlist,
3269                     csa->ohds->ds_dir->dd_origin_txg, UINT64_MAX,
3270                     &cdl_used, &cdl_comp, &cdl_uncomp);
3271                 dsl_deadlist_space_range(&csa->ohds->ds_deadlist,
3272                     csa->ohds->ds_dir->dd_origin_txg, UINT64_MAX,
3273                     &odl_used, &odl_comp, &odl_uncomp);
3274                 dsl_dir_transfer_space(csa->ohds->ds_dir, cdl_used - odl_used,
3275                     DD_USED_HEAD, DD_USED_SNAP, tx);
3276         }
3277 
3278         /* swap ds_*_bytes */
3279         SWITCH64(csa->ohds->ds_phys->ds_referenced_bytes,
3280             csa->cds->ds_phys->ds_referenced_bytes);
3281         SWITCH64(csa->ohds->ds_phys->ds_compressed_bytes,
3282             csa->cds->ds_phys->ds_compressed_bytes);
3283         SWITCH64(csa->ohds->ds_phys->ds_uncompressed_bytes,
3284             csa->cds->ds_phys->ds_uncompressed_bytes);
3285         SWITCH64(csa->ohds->ds_phys->ds_unique_bytes,
3286             csa->cds->ds_phys->ds_unique_bytes);
3287 
3288         /* apply any parent delta for change in unconsumed refreservation */
3289         dsl_dir_diduse_space(csa->ohds->ds_dir, DD_USED_REFRSRV,
3290             csa->unused_refres_delta, 0, 0, tx);
3291 
3292         /*
3293          * Swap deadlists.
3294          */
3295         dsl_deadlist_close(&csa->cds->ds_deadlist);
3296         dsl_deadlist_close(&csa->ohds->ds_deadlist);
3297         SWITCH64(csa->ohds->ds_phys->ds_deadlist_obj,
3298             csa->cds->ds_phys->ds_deadlist_obj);
3299         dsl_deadlist_open(&csa->cds->ds_deadlist, dp->dp_meta_objset,
3300             csa->cds->ds_phys->ds_deadlist_obj);
3301         dsl_deadlist_open(&csa->ohds->ds_deadlist, dp->dp_meta_objset,
3302             csa->ohds->ds_phys->ds_deadlist_obj);
3303 
3304         dsl_scan_ds_clone_swapped(csa->ohds, csa->cds, tx);
3305 }
3306 
3307 /*
3308  * Swap 'clone' with its origin head datasets.  Used at the end of "zfs
3309  * recv" into an existing fs to swizzle the file system to the new
3310  * version, and by "zfs rollback".  Can also be used to swap two
3311  * independent head datasets if neither has any snapshots.
3312  */
3313 int
3314 dsl_dataset_clone_swap(dsl_dataset_t *clone, dsl_dataset_t *origin_head,
3315     boolean_t force)
3316 {
3317         struct cloneswaparg csa;
3318         int error;
3319 
3320         ASSERT(clone->ds_owner);
3321         ASSERT(origin_head->ds_owner);
3322 retry:
3323         /*
3324          * Need exclusive access for the swap. If we're swapping these
3325          * datasets back after an error, we already hold the locks.
3326          */
3327         if (!RW_WRITE_HELD(&clone->ds_rwlock))
3328                 rw_enter(&clone->ds_rwlock, RW_WRITER);
3329         if (!RW_WRITE_HELD(&origin_head->ds_rwlock) &&
3330             !rw_tryenter(&origin_head->ds_rwlock, RW_WRITER)) {
3331                 rw_exit(&clone->ds_rwlock);
3332                 rw_enter(&origin_head->ds_rwlock, RW_WRITER);
3333                 if (!rw_tryenter(&clone->ds_rwlock, RW_WRITER)) {
3334                         rw_exit(&origin_head->ds_rwlock);
3335                         goto retry;
3336                 }
3337         }
3338         csa.cds = clone;
3339         csa.ohds = origin_head;
3340         csa.force = force;
3341         error = dsl_sync_task_do(clone->ds_dir->dd_pool,
3342             dsl_dataset_clone_swap_check,
3343             dsl_dataset_clone_swap_sync, &csa, NULL, 9);
3344         return (error);
3345 }
3346 
3347 /*
3348  * Given a pool name and a dataset object number in that pool,
3349  * return the name of that dataset.
3350  */
3351 int
3352 dsl_dsobj_to_dsname(char *pname, uint64_t obj, char *buf)
3353 {
3354         spa_t *spa;
3355         dsl_pool_t *dp;
3356         dsl_dataset_t *ds;
3357         int error;
3358 
3359         if ((error = spa_open(pname, &spa, FTAG)) != 0)
3360                 return (error);
3361         dp = spa_get_dsl(spa);
3362         rw_enter(&dp->dp_config_rwlock, RW_READER);
3363         if ((error = dsl_dataset_hold_obj(dp, obj, FTAG, &ds)) == 0) {
3364                 dsl_dataset_name(ds, buf);
3365                 dsl_dataset_rele(ds, FTAG);
3366         }
3367         rw_exit(&dp->dp_config_rwlock);
3368         spa_close(spa, FTAG);
3369 
3370         return (error);
3371 }
3372 
3373 int
3374 dsl_dataset_check_quota(dsl_dataset_t *ds, boolean_t check_quota,
3375     uint64_t asize, uint64_t inflight, uint64_t *used, uint64_t *ref_rsrv)
3376 {
3377         int error = 0;
3378 
3379         ASSERT3S(asize, >, 0);
3380 
3381         /*
3382          * *ref_rsrv is the portion of asize that will come from any
3383          * unconsumed refreservation space.
3384          */
3385         *ref_rsrv = 0;
3386 
3387         mutex_enter(&ds->ds_lock);
3388         /*
3389          * Make a space adjustment for reserved bytes.
3390          */
3391         if (ds->ds_reserved > ds->ds_phys->ds_unique_bytes) {
3392                 ASSERT3U(*used, >=,
3393                     ds->ds_reserved - ds->ds_phys->ds_unique_bytes);
3394                 *used -= (ds->ds_reserved - ds->ds_phys->ds_unique_bytes);
3395                 *ref_rsrv =
3396                     asize - MIN(asize, parent_delta(ds, asize + inflight));
3397         }
3398 
3399         if (!check_quota || ds->ds_quota == 0) {
3400                 mutex_exit(&ds->ds_lock);
3401                 return (0);
3402         }
3403         /*
3404          * If they are requesting more space, and our current estimate
3405          * is over quota, they get to try again unless the actual
3406          * on-disk is over quota and there are no pending changes (which
3407          * may free up space for us).
3408          */
3409         if (ds->ds_phys->ds_referenced_bytes + inflight >= ds->ds_quota) {
3410                 if (inflight > 0 ||
3411                     ds->ds_phys->ds_referenced_bytes < ds->ds_quota)
3412                         error = ERESTART;
3413                 else
3414                         error = EDQUOT;
3415         }
3416         mutex_exit(&ds->ds_lock);
3417 
3418         return (error);
3419 }
3420 
3421 /* ARGSUSED */
3422 static int
3423 dsl_dataset_set_quota_check(void *arg1, void *arg2, dmu_tx_t *tx)
3424 {
3425         dsl_dataset_t *ds = arg1;
3426         dsl_prop_setarg_t *psa = arg2;
3427         int err;
3428 
3429         if (spa_version(ds->ds_dir->dd_pool->dp_spa) < SPA_VERSION_REFQUOTA)
3430                 return (ENOTSUP);
3431 
3432         if ((err = dsl_prop_predict_sync(ds->ds_dir, psa)) != 0)
3433                 return (err);
3434 
3435         if (psa->psa_effective_value == 0)
3436                 return (0);
3437 
3438         if (psa->psa_effective_value < ds->ds_phys->ds_referenced_bytes ||
3439             psa->psa_effective_value < ds->ds_reserved)
3440                 return (ENOSPC);
3441 
3442         return (0);
3443 }
3444 
3445 extern void dsl_prop_set_sync(void *, void *, dmu_tx_t *);
3446 
3447 void
3448 dsl_dataset_set_quota_sync(void *arg1, void *arg2, dmu_tx_t *tx)
3449 {
3450         dsl_dataset_t *ds = arg1;
3451         dsl_prop_setarg_t *psa = arg2;
3452         uint64_t effective_value = psa->psa_effective_value;
3453 
3454         dsl_prop_set_sync(ds, psa, tx);
3455         DSL_PROP_CHECK_PREDICTION(ds->ds_dir, psa);
3456 
3457         if (ds->ds_quota != effective_value) {
3458                 dmu_buf_will_dirty(ds->ds_dbuf, tx);
3459                 ds->ds_quota = effective_value;
3460 
3461                 spa_history_log_internal(LOG_DS_REFQUOTA,
3462                     ds->ds_dir->dd_pool->dp_spa, tx, "%lld dataset = %llu ",
3463                     (longlong_t)ds->ds_quota, ds->ds_object);
3464         }
3465 }
3466 
3467 int
3468 dsl_dataset_set_quota(const char *dsname, zprop_source_t source, uint64_t quota)
3469 {
3470         dsl_dataset_t *ds;
3471         dsl_prop_setarg_t psa;
3472         int err;
3473 
3474         dsl_prop_setarg_init_uint64(&psa, "refquota", source, &quota);
3475 
3476         err = dsl_dataset_hold(dsname, FTAG, &ds);
3477         if (err)
3478                 return (err);
3479 
3480         /*
3481          * If someone removes a file, then tries to set the quota, we
3482          * want to make sure the file freeing takes effect.
3483          */
3484         txg_wait_open(ds->ds_dir->dd_pool, 0);
3485 
3486         err = dsl_sync_task_do(ds->ds_dir->dd_pool,
3487             dsl_dataset_set_quota_check, dsl_dataset_set_quota_sync,
3488             ds, &psa, 0);
3489 
3490         dsl_dataset_rele(ds, FTAG);
3491         return (err);
3492 }
3493 
3494 static int
3495 dsl_dataset_set_reservation_check(void *arg1, void *arg2, dmu_tx_t *tx)
3496 {
3497         dsl_dataset_t *ds = arg1;
3498         dsl_prop_setarg_t *psa = arg2;
3499         uint64_t effective_value;
3500         uint64_t unique;
3501         int err;
3502 
3503         if (spa_version(ds->ds_dir->dd_pool->dp_spa) <
3504             SPA_VERSION_REFRESERVATION)
3505                 return (ENOTSUP);
3506 
3507         if (dsl_dataset_is_snapshot(ds))
3508                 return (EINVAL);
3509 
3510         if ((err = dsl_prop_predict_sync(ds->ds_dir, psa)) != 0)
3511                 return (err);
3512 
3513         effective_value = psa->psa_effective_value;
3514 
3515         /*
3516          * If we are doing the preliminary check in open context, the
3517          * space estimates may be inaccurate.
3518          */
3519         if (!dmu_tx_is_syncing(tx))
3520                 return (0);
3521 
3522         mutex_enter(&ds->ds_lock);
3523         if (!DS_UNIQUE_IS_ACCURATE(ds))
3524                 dsl_dataset_recalc_head_uniq(ds);
3525         unique = ds->ds_phys->ds_unique_bytes;
3526         mutex_exit(&ds->ds_lock);
3527 
3528         if (MAX(unique, effective_value) > MAX(unique, ds->ds_reserved)) {
3529                 uint64_t delta = MAX(unique, effective_value) -
3530                     MAX(unique, ds->ds_reserved);
3531 
3532                 if (delta > dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE))
3533                         return (ENOSPC);
3534                 if (ds->ds_quota > 0 &&
3535                     effective_value > ds->ds_quota)
3536                         return (ENOSPC);
3537         }
3538 
3539         return (0);
3540 }
3541 
3542 static void
3543 dsl_dataset_set_reservation_sync(void *arg1, void *arg2, dmu_tx_t *tx)
3544 {
3545         dsl_dataset_t *ds = arg1;
3546         dsl_prop_setarg_t *psa = arg2;
3547         uint64_t effective_value = psa->psa_effective_value;
3548         uint64_t unique;
3549         int64_t delta;
3550 
3551         dsl_prop_set_sync(ds, psa, tx);
3552         DSL_PROP_CHECK_PREDICTION(ds->ds_dir, psa);
3553 
3554         dmu_buf_will_dirty(ds->ds_dbuf, tx);
3555 
3556         mutex_enter(&ds->ds_dir->dd_lock);
3557         mutex_enter(&ds->ds_lock);
3558         ASSERT(DS_UNIQUE_IS_ACCURATE(ds));
3559         unique = ds->ds_phys->ds_unique_bytes;
3560         delta = MAX(0, (int64_t)(effective_value - unique)) -
3561             MAX(0, (int64_t)(ds->ds_reserved - unique));
3562         ds->ds_reserved = effective_value;
3563         mutex_exit(&ds->ds_lock);
3564 
3565         dsl_dir_diduse_space(ds->ds_dir, DD_USED_REFRSRV, delta, 0, 0, tx);
3566         mutex_exit(&ds->ds_dir->dd_lock);
3567 
3568         spa_history_log_internal(LOG_DS_REFRESERV,
3569             ds->ds_dir->dd_pool->dp_spa, tx, "%lld dataset = %llu",
3570             (longlong_t)effective_value, ds->ds_object);
3571 }
3572 
3573 int
3574 dsl_dataset_set_reservation(const char *dsname, zprop_source_t source,
3575     uint64_t reservation)
3576 {
3577         dsl_dataset_t *ds;
3578         dsl_prop_setarg_t psa;
3579         int err;
3580 
3581         dsl_prop_setarg_init_uint64(&psa, "refreservation", source,
3582             &reservation);
3583 
3584         err = dsl_dataset_hold(dsname, FTAG, &ds);
3585         if (err)
3586                 return (err);
3587 
3588         err = dsl_sync_task_do(ds->ds_dir->dd_pool,
3589             dsl_dataset_set_reservation_check,
3590             dsl_dataset_set_reservation_sync, ds, &psa, 0);
3591 
3592         dsl_dataset_rele(ds, FTAG);
3593         return (err);
3594 }
3595 
3596 typedef struct zfs_hold_cleanup_arg {
3597         dsl_pool_t *dp;
3598         uint64_t dsobj;
3599         char htag[MAXNAMELEN];
3600 } zfs_hold_cleanup_arg_t;
3601 
3602 static void
3603 dsl_dataset_user_release_onexit(void *arg)
3604 {
3605         zfs_hold_cleanup_arg_t *ca = arg;
3606 
3607         (void) dsl_dataset_user_release_tmp(ca->dp, ca->dsobj, ca->htag,
3608             B_TRUE);
3609         kmem_free(ca, sizeof (zfs_hold_cleanup_arg_t));
3610 }
3611 
3612 void
3613 dsl_register_onexit_hold_cleanup(dsl_dataset_t *ds, const char *htag,
3614     minor_t minor)
3615 {
3616         zfs_hold_cleanup_arg_t *ca;
3617 
3618         ca = kmem_alloc(sizeof (zfs_hold_cleanup_arg_t), KM_SLEEP);
3619         ca->dp = ds->ds_dir->dd_pool;
3620         ca->dsobj = ds->ds_object;
3621         (void) strlcpy(ca->htag, htag, sizeof (ca->htag));
3622         VERIFY3U(0, ==, zfs_onexit_add_cb(minor,
3623             dsl_dataset_user_release_onexit, ca, NULL));
3624 }
3625 
3626 /*
3627  * If you add new checks here, you may need to add
3628  * additional checks to the "temporary" case in
3629  * snapshot_check() in dmu_objset.c.
3630  */
3631 static int
3632 dsl_dataset_user_hold_check(void *arg1, void *arg2, dmu_tx_t *tx)
3633 {
3634         dsl_dataset_t *ds = arg1;
3635         struct dsl_ds_holdarg *ha = arg2;
3636         char *htag = ha->htag;
3637         objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
3638         int error = 0;
3639 
3640         if (spa_version(ds->ds_dir->dd_pool->dp_spa) < SPA_VERSION_USERREFS)
3641                 return (ENOTSUP);
3642 
3643         if (!dsl_dataset_is_snapshot(ds))
3644                 return (EINVAL);
3645 
3646         /* tags must be unique */
3647         mutex_enter(&ds->ds_lock);
3648         if (ds->ds_phys->ds_userrefs_obj) {
3649                 error = zap_lookup(mos, ds->ds_phys->ds_userrefs_obj, htag,
3650                     8, 1, tx);
3651                 if (error == 0)
3652                         error = EEXIST;
3653                 else if (error == ENOENT)
3654                         error = 0;
3655         }
3656         mutex_exit(&ds->ds_lock);
3657 
3658         if (error == 0 && ha->temphold &&
3659             strlen(htag) + MAX_TAG_PREFIX_LEN >= MAXNAMELEN)
3660                 error = E2BIG;
3661 
3662         return (error);
3663 }
3664 
3665 void
3666 dsl_dataset_user_hold_sync(void *arg1, void *arg2, dmu_tx_t *tx)
3667 {
3668         dsl_dataset_t *ds = arg1;
3669         struct dsl_ds_holdarg *ha = arg2;
3670         char *htag = ha->htag;
3671         dsl_pool_t *dp = ds->ds_dir->dd_pool;
3672         objset_t *mos = dp->dp_meta_objset;
3673         uint64_t now = gethrestime_sec();
3674         uint64_t zapobj;
3675 
3676         mutex_enter(&ds->ds_lock);
3677         if (ds->ds_phys->ds_userrefs_obj == 0) {
3678                 /*
3679                  * This is the first user hold for this dataset.  Create
3680                  * the userrefs zap object.
3681                  */
3682                 dmu_buf_will_dirty(ds->ds_dbuf, tx);
3683                 zapobj = ds->ds_phys->ds_userrefs_obj =
3684                     zap_create(mos, DMU_OT_USERREFS, DMU_OT_NONE, 0, tx);
3685         } else {
3686                 zapobj = ds->ds_phys->ds_userrefs_obj;
3687         }
3688         ds->ds_userrefs++;
3689         mutex_exit(&ds->ds_lock);
3690 
3691         VERIFY(0 == zap_add(mos, zapobj, htag, 8, 1, &now, tx));
3692 
3693         if (ha->temphold) {
3694                 VERIFY(0 == dsl_pool_user_hold(dp, ds->ds_object,
3695                     htag, &now, tx));
3696         }
3697 
3698         spa_history_log_internal(LOG_DS_USER_HOLD,
3699             dp->dp_spa, tx, "<%s> temp = %d dataset = %llu", htag,
3700             (int)ha->temphold, ds->ds_object);
3701 }
3702 
3703 static int
3704 dsl_dataset_user_hold_one(const char *dsname, void *arg)
3705 {
3706         struct dsl_ds_holdarg *ha = arg;
3707         dsl_dataset_t *ds;
3708         int error;
3709         char *name;
3710 
3711         /* alloc a buffer to hold dsname@snapname plus terminating NULL */
3712         name = kmem_asprintf("%s@%s", dsname, ha->snapname);
3713         error = dsl_dataset_hold(name, ha->dstg, &ds);
3714         strfree(name);
3715         if (error == 0) {
3716                 ha->gotone = B_TRUE;
3717                 dsl_sync_task_create(ha->dstg, dsl_dataset_user_hold_check,
3718                     dsl_dataset_user_hold_sync, ds, ha, 0);
3719         } else if (error == ENOENT && ha->recursive) {
3720                 error = 0;
3721         } else {
3722                 (void) strlcpy(ha->failed, dsname, sizeof (ha->failed));
3723         }
3724         return (error);
3725 }
3726 
3727 int
3728 dsl_dataset_user_hold_for_send(dsl_dataset_t *ds, char *htag,
3729     boolean_t temphold)
3730 {
3731         struct dsl_ds_holdarg *ha;
3732         int error;
3733 
3734         ha = kmem_zalloc(sizeof (struct dsl_ds_holdarg), KM_SLEEP);
3735         ha->htag = htag;
3736         ha->temphold = temphold;
3737         error = dsl_sync_task_do(ds->ds_dir->dd_pool,
3738             dsl_dataset_user_hold_check, dsl_dataset_user_hold_sync,
3739             ds, ha, 0);
3740         kmem_free(ha, sizeof (struct dsl_ds_holdarg));
3741 
3742         return (error);
3743 }
3744 
3745 int
3746 dsl_dataset_user_hold(char *dsname, char *snapname, char *htag,
3747     boolean_t recursive, boolean_t temphold, int cleanup_fd)
3748 {
3749         struct dsl_ds_holdarg *ha;
3750         dsl_sync_task_t *dst;
3751         spa_t *spa;
3752         int error;
3753         minor_t minor = 0;
3754 
3755         if (cleanup_fd != -1) {
3756                 /* Currently we only support cleanup-on-exit of tempholds. */
3757                 if (!temphold)
3758                         return (EINVAL);
3759                 error = zfs_onexit_fd_hold(cleanup_fd, &minor);
3760                 if (error)
3761                         return (error);
3762         }
3763 
3764         ha = kmem_zalloc(sizeof (struct dsl_ds_holdarg), KM_SLEEP);
3765 
3766         (void) strlcpy(ha->failed, dsname, sizeof (ha->failed));
3767 
3768         error = spa_open(dsname, &spa, FTAG);
3769         if (error) {
3770                 kmem_free(ha, sizeof (struct dsl_ds_holdarg));
3771                 if (cleanup_fd != -1)
3772                         zfs_onexit_fd_rele(cleanup_fd);
3773                 return (error);
3774         }
3775 
3776         ha->dstg = dsl_sync_task_group_create(spa_get_dsl(spa));
3777         ha->htag = htag;
3778         ha->snapname = snapname;
3779         ha->recursive = recursive;
3780         ha->temphold = temphold;
3781 
3782         if (recursive) {
3783                 error = dmu_objset_find(dsname, dsl_dataset_user_hold_one,
3784                     ha, DS_FIND_CHILDREN);
3785         } else {
3786                 error = dsl_dataset_user_hold_one(dsname, ha);
3787         }
3788         if (error == 0)
3789                 error = dsl_sync_task_group_wait(ha->dstg);
3790 
3791         for (dst = list_head(&ha->dstg->dstg_tasks); dst;
3792             dst = list_next(&ha->dstg->dstg_tasks, dst)) {
3793                 dsl_dataset_t *ds = dst->dst_arg1;
3794 
3795                 if (dst->dst_err) {
3796                         dsl_dataset_name(ds, ha->failed);
3797                         *strchr(ha->failed, '@') = '\0';
3798                 } else if (error == 0 && minor != 0 && temphold) {
3799                         /*
3800                          * If this hold is to be released upon process exit,
3801                          * register that action now.
3802                          */
3803                         dsl_register_onexit_hold_cleanup(ds, htag, minor);
3804                 }
3805                 dsl_dataset_rele(ds, ha->dstg);
3806         }
3807 
3808         if (error == 0 && recursive && !ha->gotone)
3809                 error = ENOENT;
3810 
3811         if (error)
3812                 (void) strlcpy(dsname, ha->failed, sizeof (ha->failed));
3813 
3814         dsl_sync_task_group_destroy(ha->dstg);
3815 
3816         kmem_free(ha, sizeof (struct dsl_ds_holdarg));
3817         spa_close(spa, FTAG);
3818         if (cleanup_fd != -1)
3819                 zfs_onexit_fd_rele(cleanup_fd);
3820         return (error);
3821 }
3822 
3823 struct dsl_ds_releasearg {
3824         dsl_dataset_t *ds;
3825         const char *htag;
3826         boolean_t own;          /* do we own or just hold ds? */
3827 };
3828 
3829 static int
3830 dsl_dataset_release_might_destroy(dsl_dataset_t *ds, const char *htag,
3831     boolean_t *might_destroy)
3832 {
3833         objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
3834         uint64_t zapobj;
3835         uint64_t tmp;
3836         int error;
3837 
3838         *might_destroy = B_FALSE;
3839 
3840         mutex_enter(&ds->ds_lock);
3841         zapobj = ds->ds_phys->ds_userrefs_obj;
3842         if (zapobj == 0) {
3843                 /* The tag can't possibly exist */
3844                 mutex_exit(&ds->ds_lock);
3845                 return (ESRCH);
3846         }
3847 
3848         /* Make sure the tag exists */
3849         error = zap_lookup(mos, zapobj, htag, 8, 1, &tmp);
3850         if (error) {
3851                 mutex_exit(&ds->ds_lock);
3852                 if (error == ENOENT)
3853                         error = ESRCH;
3854                 return (error);
3855         }
3856 
3857         if (ds->ds_userrefs == 1 && ds->ds_phys->ds_num_children == 1 &&
3858             DS_IS_DEFER_DESTROY(ds))
3859                 *might_destroy = B_TRUE;
3860 
3861         mutex_exit(&ds->ds_lock);
3862         return (0);
3863 }
3864 
3865 static int
3866 dsl_dataset_user_release_check(void *arg1, void *tag, dmu_tx_t *tx)
3867 {
3868         struct dsl_ds_releasearg *ra = arg1;
3869         dsl_dataset_t *ds = ra->ds;
3870         boolean_t might_destroy;
3871         int error;
3872 
3873         if (spa_version(ds->ds_dir->dd_pool->dp_spa) < SPA_VERSION_USERREFS)
3874                 return (ENOTSUP);
3875 
3876         error = dsl_dataset_release_might_destroy(ds, ra->htag, &might_destroy);
3877         if (error)
3878                 return (error);
3879 
3880         if (might_destroy) {
3881                 struct dsl_ds_destroyarg dsda = {0};
3882 
3883                 if (dmu_tx_is_syncing(tx)) {
3884                         /*
3885                          * If we're not prepared to remove the snapshot,
3886                          * we can't allow the release to happen right now.
3887                          */
3888                         if (!ra->own)
3889                                 return (EBUSY);
3890                 }
3891                 dsda.ds = ds;
3892                 dsda.releasing = B_TRUE;
3893                 return (dsl_dataset_destroy_check(&dsda, tag, tx));
3894         }
3895 
3896         return (0);
3897 }
3898 
3899 static void
3900 dsl_dataset_user_release_sync(void *arg1, void *tag, dmu_tx_t *tx)
3901 {
3902         struct dsl_ds_releasearg *ra = arg1;
3903         dsl_dataset_t *ds = ra->ds;
3904         dsl_pool_t *dp = ds->ds_dir->dd_pool;
3905         objset_t *mos = dp->dp_meta_objset;
3906         uint64_t zapobj;
3907         uint64_t dsobj = ds->ds_object;
3908         uint64_t refs;
3909         int error;
3910 
3911         mutex_enter(&ds->ds_lock);
3912         ds->ds_userrefs--;
3913         refs = ds->ds_userrefs;
3914         mutex_exit(&ds->ds_lock);
3915         error = dsl_pool_user_release(dp, ds->ds_object, ra->htag, tx);
3916         VERIFY(error == 0 || error == ENOENT);
3917         zapobj = ds->ds_phys->ds_userrefs_obj;
3918         VERIFY(0 == zap_remove(mos, zapobj, ra->htag, tx));
3919         if (ds->ds_userrefs == 0 && ds->ds_phys->ds_num_children == 1 &&
3920             DS_IS_DEFER_DESTROY(ds)) {
3921                 struct dsl_ds_destroyarg dsda = {0};
3922 
3923                 ASSERT(ra->own);
3924                 dsda.ds = ds;
3925                 dsda.releasing = B_TRUE;
3926                 /* We already did the destroy_check */
3927                 dsl_dataset_destroy_sync(&dsda, tag, tx);
3928         }
3929 
3930         spa_history_log_internal(LOG_DS_USER_RELEASE,
3931             dp->dp_spa, tx, "<%s> %lld dataset = %llu",
3932             ra->htag, (longlong_t)refs, dsobj);
3933 }
3934 
3935 static int
3936 dsl_dataset_user_release_one(const char *dsname, void *arg)
3937 {
3938         struct dsl_ds_holdarg *ha = arg;
3939         struct dsl_ds_releasearg *ra;
3940         dsl_dataset_t *ds;
3941         int error;
3942         void *dtag = ha->dstg;
3943         char *name;
3944         boolean_t own = B_FALSE;
3945         boolean_t might_destroy;
3946 
3947         /* alloc a buffer to hold dsname@snapname, plus the terminating NULL */
3948         name = kmem_asprintf("%s@%s", dsname, ha->snapname);
3949         error = dsl_dataset_hold(name, dtag, &ds);
3950         strfree(name);
3951         if (error == ENOENT && ha->recursive)
3952                 return (0);
3953         (void) strlcpy(ha->failed, dsname, sizeof (ha->failed));
3954         if (error)
3955                 return (error);
3956 
3957         ha->gotone = B_TRUE;
3958 
3959         ASSERT(dsl_dataset_is_snapshot(ds));
3960 
3961         error = dsl_dataset_release_might_destroy(ds, ha->htag, &might_destroy);
3962         if (error) {
3963                 dsl_dataset_rele(ds, dtag);
3964                 return (error);
3965         }
3966 
3967         if (might_destroy) {
3968 #ifdef _KERNEL
3969                 name = kmem_asprintf("%s@%s", dsname, ha->snapname);
3970                 error = zfs_unmount_snap(name, NULL);
3971                 strfree(name);
3972                 if (error) {
3973                         dsl_dataset_rele(ds, dtag);
3974                         return (error);
3975                 }
3976 #endif
3977                 if (!dsl_dataset_tryown(ds, B_TRUE, dtag)) {
3978                         dsl_dataset_rele(ds, dtag);
3979                         return (EBUSY);
3980                 } else {
3981                         own = B_TRUE;
3982                         dsl_dataset_make_exclusive(ds, dtag);
3983                 }
3984         }
3985 
3986         ra = kmem_alloc(sizeof (struct dsl_ds_releasearg), KM_SLEEP);
3987         ra->ds = ds;
3988         ra->htag = ha->htag;
3989         ra->own = own;
3990         dsl_sync_task_create(ha->dstg, dsl_dataset_user_release_check,
3991             dsl_dataset_user_release_sync, ra, dtag, 0);
3992 
3993         return (0);
3994 }
3995 
3996 int
3997 dsl_dataset_user_release(char *dsname, char *snapname, char *htag,
3998     boolean_t recursive)
3999 {
4000         struct dsl_ds_holdarg *ha;
4001         dsl_sync_task_t *dst;
4002         spa_t *spa;
4003         int error;
4004 
4005 top:
4006         ha = kmem_zalloc(sizeof (struct dsl_ds_holdarg), KM_SLEEP);
4007 
4008         (void) strlcpy(ha->failed, dsname, sizeof (ha->failed));
4009 
4010         error = spa_open(dsname, &spa, FTAG);
4011         if (error) {
4012                 kmem_free(ha, sizeof (struct dsl_ds_holdarg));
4013                 return (error);
4014         }
4015 
4016         ha->dstg = dsl_sync_task_group_create(spa_get_dsl(spa));
4017         ha->htag = htag;
4018         ha->snapname = snapname;
4019         ha->recursive = recursive;
4020         if (recursive) {
4021                 error = dmu_objset_find(dsname, dsl_dataset_user_release_one,
4022                     ha, DS_FIND_CHILDREN);
4023         } else {
4024                 error = dsl_dataset_user_release_one(dsname, ha);
4025         }
4026         if (error == 0)
4027                 error = dsl_sync_task_group_wait(ha->dstg);
4028 
4029         for (dst = list_head(&ha->dstg->dstg_tasks); dst;
4030             dst = list_next(&ha->dstg->dstg_tasks, dst)) {
4031                 struct dsl_ds_releasearg *ra = dst->dst_arg1;
4032                 dsl_dataset_t *ds = ra->ds;
4033 
4034                 if (dst->dst_err)
4035                         dsl_dataset_name(ds, ha->failed);
4036 
4037                 if (ra->own)
4038                         dsl_dataset_disown(ds, ha->dstg);
4039                 else
4040                         dsl_dataset_rele(ds, ha->dstg);
4041 
4042                 kmem_free(ra, sizeof (struct dsl_ds_releasearg));
4043         }
4044 
4045         if (error == 0 && recursive && !ha->gotone)
4046                 error = ENOENT;
4047 
4048         if (error && error != EBUSY)
4049                 (void) strlcpy(dsname, ha->failed, sizeof (ha->failed));
4050 
4051         dsl_sync_task_group_destroy(ha->dstg);
4052         kmem_free(ha, sizeof (struct dsl_ds_holdarg));
4053         spa_close(spa, FTAG);
4054 
4055         /*
4056          * We can get EBUSY if we were racing with deferred destroy and
4057          * dsl_dataset_user_release_check() hadn't done the necessary
4058          * open context setup.  We can also get EBUSY if we're racing
4059          * with destroy and that thread is the ds_owner.  Either way
4060          * the busy condition should be transient, and we should retry
4061          * the release operation.
4062          */
4063         if (error == EBUSY)
4064                 goto top;
4065 
4066         return (error);
4067 }
4068 
4069 /*
4070  * Called at spa_load time (with retry == B_FALSE) to release a stale
4071  * temporary user hold. Also called by the onexit code (with retry == B_TRUE).
4072  */
4073 int
4074 dsl_dataset_user_release_tmp(dsl_pool_t *dp, uint64_t dsobj, char *htag,
4075     boolean_t retry)
4076 {
4077         dsl_dataset_t *ds;
4078         char *snap;
4079         char *name;
4080         int namelen;
4081         int error;
4082 
4083         do {
4084                 rw_enter(&dp->dp_config_rwlock, RW_READER);
4085                 error = dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds);
4086                 rw_exit(&dp->dp_config_rwlock);
4087                 if (error)
4088                         return (error);
4089                 namelen = dsl_dataset_namelen(ds)+1;
4090                 name = kmem_alloc(namelen, KM_SLEEP);
4091                 dsl_dataset_name(ds, name);
4092                 dsl_dataset_rele(ds, FTAG);
4093 
4094                 snap = strchr(name, '@');
4095                 *snap = '\0';
4096                 ++snap;
4097                 error = dsl_dataset_user_release(name, snap, htag, B_FALSE);
4098                 kmem_free(name, namelen);
4099 
4100                 /*
4101                  * The object can't have been destroyed because we have a hold,
4102                  * but it might have been renamed, resulting in ENOENT.  Retry
4103                  * if we've been requested to do so.
4104                  *
4105                  * It would be nice if we could use the dsobj all the way
4106                  * through and avoid ENOENT entirely.  But we might need to
4107                  * unmount the snapshot, and there's currently no way to lookup
4108                  * a vfsp using a ZFS object id.
4109                  */
4110         } while ((error == ENOENT) && retry);
4111 
4112         return (error);
4113 }
4114 
4115 int
4116 dsl_dataset_get_holds(const char *dsname, nvlist_t **nvp)
4117 {
4118         dsl_dataset_t *ds;
4119         int err;
4120 
4121         err = dsl_dataset_hold(dsname, FTAG, &ds);
4122         if (err)
4123                 return (err);
4124 
4125         VERIFY(0 == nvlist_alloc(nvp, NV_UNIQUE_NAME, KM_SLEEP));
4126         if (ds->ds_phys->ds_userrefs_obj != 0) {
4127                 zap_attribute_t *za;
4128                 zap_cursor_t zc;
4129 
4130                 za = kmem_alloc(sizeof (zap_attribute_t), KM_SLEEP);
4131                 for (zap_cursor_init(&zc, ds->ds_dir->dd_pool->dp_meta_objset,
4132                     ds->ds_phys->ds_userrefs_obj);
4133                     zap_cursor_retrieve(&zc, za) == 0;
4134                     zap_cursor_advance(&zc)) {
4135                         VERIFY(0 == nvlist_add_uint64(*nvp, za->za_name,
4136                             za->za_first_integer));
4137                 }
4138                 zap_cursor_fini(&zc);
4139                 kmem_free(za, sizeof (zap_attribute_t));
4140         }
4141         dsl_dataset_rele(ds, FTAG);
4142         return (0);
4143 }
4144 
4145 /*
4146  * Note, this function is used as the callback for dmu_objset_find().  We
4147  * always return 0 so that we will continue to find and process
4148  * inconsistent datasets, even if we encounter an error trying to
4149  * process one of them.
4150  */
4151 /* ARGSUSED */
4152 int
4153 dsl_destroy_inconsistent(const char *dsname, void *arg)
4154 {
4155         dsl_dataset_t *ds;
4156 
4157         if (dsl_dataset_own(dsname, B_TRUE, FTAG, &ds) == 0) {
4158                 if (DS_IS_INCONSISTENT(ds))
4159                         (void) dsl_dataset_destroy(ds, FTAG, B_FALSE);
4160                 else
4161                         dsl_dataset_disown(ds, FTAG);
4162         }
4163         return (0);
4164 }
4165 
4166 /*
4167  * Return (in *usedp) the amount of space written in new that is not
4168  * present in oldsnap.  New may be a snapshot or the head.  Old must be
4169  * a snapshot before new, in new's filesystem (or its origin).  If not then
4170  * fail and return EINVAL.
4171  *
4172  * The written space is calculated by considering two components:  First, we
4173  * ignore any freed space, and calculate the written as new's used space
4174  * minus old's used space.  Next, we add in the amount of space that was freed
4175  * between the two snapshots, thus reducing new's used space relative to old's.
4176  * Specifically, this is the space that was born before old->ds_creation_txg,
4177  * and freed before new (ie. on new's deadlist or a previous deadlist).
4178  *
4179  * space freed                         [---------------------]
4180  * snapshots                       ---O-------O--------O-------O------
4181  *                                         oldsnap            new
4182  */
4183 int
4184 dsl_dataset_space_written(dsl_dataset_t *oldsnap, dsl_dataset_t *new,
4185     uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4186 {
4187         int err = 0;
4188         uint64_t snapobj;
4189         dsl_pool_t *dp = new->ds_dir->dd_pool;
4190 
4191         *usedp = 0;
4192         *usedp += new->ds_phys->ds_referenced_bytes;
4193         *usedp -= oldsnap->ds_phys->ds_referenced_bytes;
4194 
4195         *compp = 0;
4196         *compp += new->ds_phys->ds_compressed_bytes;
4197         *compp -= oldsnap->ds_phys->ds_compressed_bytes;
4198 
4199         *uncompp = 0;
4200         *uncompp += new->ds_phys->ds_uncompressed_bytes;
4201         *uncompp -= oldsnap->ds_phys->ds_uncompressed_bytes;
4202 
4203         rw_enter(&dp->dp_config_rwlock, RW_READER);
4204         snapobj = new->ds_object;
4205         while (snapobj != oldsnap->ds_object) {
4206                 dsl_dataset_t *snap;
4207                 uint64_t used, comp, uncomp;
4208 
4209                 if (snapobj == new->ds_object) {
4210                         snap = new;
4211                 } else {
4212                         err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &snap);
4213                         if (err != 0)
4214                                 break;
4215                 }
4216 
4217                 if (snap->ds_phys->ds_prev_snap_txg ==
4218                     oldsnap->ds_phys->ds_creation_txg) {
4219                         /*
4220                          * The blocks in the deadlist can not be born after
4221                          * ds_prev_snap_txg, so get the whole deadlist space,
4222                          * which is more efficient (especially for old-format
4223                          * deadlists).  Unfortunately the deadlist code
4224                          * doesn't have enough information to make this
4225                          * optimization itself.
4226                          */
4227                         dsl_deadlist_space(&snap->ds_deadlist,
4228                             &used, &comp, &uncomp);
4229                 } else {
4230                         dsl_deadlist_space_range(&snap->ds_deadlist,
4231                             0, oldsnap->ds_phys->ds_creation_txg,
4232                             &used, &comp, &uncomp);
4233                 }
4234                 *usedp += used;
4235                 *compp += comp;
4236                 *uncompp += uncomp;
4237 
4238                 /*
4239                  * If we get to the beginning of the chain of snapshots
4240                  * (ds_prev_snap_obj == 0) before oldsnap, then oldsnap
4241                  * was not a snapshot of/before new.
4242                  */
4243                 snapobj = snap->ds_phys->ds_prev_snap_obj;
4244                 if (snap != new)
4245                         dsl_dataset_rele(snap, FTAG);
4246                 if (snapobj == 0) {
4247                         err = EINVAL;
4248                         break;
4249                 }
4250 
4251         }
4252         rw_exit(&dp->dp_config_rwlock);
4253         return (err);
4254 }
4255 
4256 /*
4257  * Return (in *usedp) the amount of space that will be reclaimed if firstsnap,
4258  * lastsnap, and all snapshots in between are deleted.
4259  *
4260  * blocks that would be freed            [---------------------------]
4261  * snapshots                       ---O-------O--------O-------O--------O
4262  *                                        firstsnap        lastsnap
4263  *
4264  * This is the set of blocks that were born after the snap before firstsnap,
4265  * (birth > firstsnap->prev_snap_txg) and died before the snap after the
4266  * last snap (ie, is on lastsnap->ds_next->ds_deadlist or an earlier deadlist).
4267  * We calculate this by iterating over the relevant deadlists (from the snap
4268  * after lastsnap, backward to the snap after firstsnap), summing up the
4269  * space on the deadlist that was born after the snap before firstsnap.
4270  */
4271 int
4272 dsl_dataset_space_wouldfree(dsl_dataset_t *firstsnap,
4273     dsl_dataset_t *lastsnap,
4274     uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4275 {
4276         int err = 0;
4277         uint64_t snapobj;
4278         dsl_pool_t *dp = firstsnap->ds_dir->dd_pool;
4279 
4280         ASSERT(dsl_dataset_is_snapshot(firstsnap));
4281         ASSERT(dsl_dataset_is_snapshot(lastsnap));
4282 
4283         /*
4284          * Check that the snapshots are in the same dsl_dir, and firstsnap
4285          * is before lastsnap.
4286          */
4287         if (firstsnap->ds_dir != lastsnap->ds_dir ||
4288             firstsnap->ds_phys->ds_creation_txg >
4289             lastsnap->ds_phys->ds_creation_txg)
4290                 return (EINVAL);
4291 
4292         *usedp = *compp = *uncompp = 0;
4293 
4294         rw_enter(&dp->dp_config_rwlock, RW_READER);
4295         snapobj = lastsnap->ds_phys->ds_next_snap_obj;
4296         while (snapobj != firstsnap->ds_object) {
4297                 dsl_dataset_t *ds;
4298                 uint64_t used, comp, uncomp;
4299 
4300                 err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &ds);
4301                 if (err != 0)
4302                         break;
4303 
4304                 dsl_deadlist_space_range(&ds->ds_deadlist,
4305                     firstsnap->ds_phys->ds_prev_snap_txg, UINT64_MAX,
4306                     &used, &comp, &uncomp);
4307                 *usedp += used;
4308                 *compp += comp;
4309                 *uncompp += uncomp;
4310 
4311                 snapobj = ds->ds_phys->ds_prev_snap_obj;
4312                 ASSERT3U(snapobj, !=, 0);
4313                 dsl_dataset_rele(ds, FTAG);
4314         }
4315         rw_exit(&dp->dp_config_rwlock);
4316         return (err);
4317 }