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) 2011, 2015 by Delphix. All rights reserved.
  24  * Copyright (c) 2014, Joyent, Inc. All rights reserved.
  25  * Copyright (c) 2014 RackTop Systems.
  26  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
  27  * Copyright (c) 2014 Integros [integros.com]
  28  * Copyright 2016, OmniTI Computer Consulting, Inc. All rights reserved.
  29  */
  30 
  31 #include <sys/dmu_objset.h>
  32 #include <sys/dsl_dataset.h>
  33 #include <sys/dsl_dir.h>
  34 #include <sys/dsl_prop.h>
  35 #include <sys/dsl_synctask.h>
  36 #include <sys/dmu_traverse.h>
  37 #include <sys/dmu_impl.h>
  38 #include <sys/dmu_tx.h>
  39 #include <sys/arc.h>
  40 #include <sys/zio.h>
  41 #include <sys/zap.h>
  42 #include <sys/zfeature.h>
  43 #include <sys/unique.h>
  44 #include <sys/zfs_context.h>
  45 #include <sys/zfs_ioctl.h>
  46 #include <sys/spa.h>
  47 #include <sys/zfs_znode.h>
  48 #include <sys/zfs_onexit.h>
  49 #include <sys/zvol.h>
  50 #include <sys/dsl_scan.h>
  51 #include <sys/dsl_deadlist.h>
  52 #include <sys/dsl_destroy.h>
  53 #include <sys/dsl_userhold.h>
  54 #include <sys/dsl_bookmark.h>
  55 #include <sys/dmu_send.h>
  56 #include <sys/zio_checksum.h>
  57 #include <sys/zio_compress.h>
  58 #include <zfs_fletcher.h>
  59 
  60 /*
  61  * The SPA supports block sizes up to 16MB.  However, very large blocks
  62  * can have an impact on i/o latency (e.g. tying up a spinning disk for
  63  * ~300ms), and also potentially on the memory allocator.  Therefore,
  64  * we do not allow the recordsize to be set larger than zfs_max_recordsize
  65  * (default 1MB).  Larger blocks can be created by changing this tunable,
  66  * and pools with larger blocks can always be imported and used, regardless
  67  * of this setting.
  68  */
  69 int zfs_max_recordsize = 1 * 1024 * 1024;
  70 
  71 #define SWITCH64(x, y) \
  72         { \
  73                 uint64_t __tmp = (x); \
  74                 (x) = (y); \
  75                 (y) = __tmp; \
  76         }
  77 
  78 #define DS_REF_MAX      (1ULL << 62)
  79 
  80 extern inline dsl_dataset_phys_t *dsl_dataset_phys(dsl_dataset_t *ds);
  81 
  82 extern int spa_asize_inflation;
  83 
  84 /*
  85  * Figure out how much of this delta should be propogated to the dsl_dir
  86  * layer.  If there's a refreservation, that space has already been
  87  * partially accounted for in our ancestors.
  88  */
  89 static int64_t
  90 parent_delta(dsl_dataset_t *ds, int64_t delta)
  91 {
  92         dsl_dataset_phys_t *ds_phys;
  93         uint64_t old_bytes, new_bytes;
  94 
  95         if (ds->ds_reserved == 0)
  96                 return (delta);
  97 
  98         ds_phys = dsl_dataset_phys(ds);
  99         old_bytes = MAX(ds_phys->ds_unique_bytes, ds->ds_reserved);
 100         new_bytes = MAX(ds_phys->ds_unique_bytes + delta, ds->ds_reserved);
 101 
 102         ASSERT3U(ABS((int64_t)(new_bytes - old_bytes)), <=, ABS(delta));
 103         return (new_bytes - old_bytes);
 104 }
 105 
 106 void
 107 dsl_dataset_block_born(dsl_dataset_t *ds, const blkptr_t *bp, dmu_tx_t *tx)
 108 {
 109         int used = bp_get_dsize_sync(tx->tx_pool->dp_spa, bp);
 110         int compressed = BP_GET_PSIZE(bp);
 111         int uncompressed = BP_GET_UCSIZE(bp);
 112         int64_t delta;
 113 
 114         dprintf_bp(bp, "ds=%p", ds);
 115 
 116         ASSERT(dmu_tx_is_syncing(tx));
 117         /* It could have been compressed away to nothing */
 118         if (BP_IS_HOLE(bp))
 119                 return;
 120         ASSERT(BP_GET_TYPE(bp) != DMU_OT_NONE);
 121         ASSERT(DMU_OT_IS_VALID(BP_GET_TYPE(bp)));
 122         if (ds == NULL) {
 123                 dsl_pool_mos_diduse_space(tx->tx_pool,
 124                     used, compressed, uncompressed);
 125                 return;
 126         }
 127 
 128         dmu_buf_will_dirty(ds->ds_dbuf, tx);
 129         mutex_enter(&ds->ds_lock);
 130         delta = parent_delta(ds, used);
 131         dsl_dataset_phys(ds)->ds_referenced_bytes += used;
 132         dsl_dataset_phys(ds)->ds_compressed_bytes += compressed;
 133         dsl_dataset_phys(ds)->ds_uncompressed_bytes += uncompressed;
 134         dsl_dataset_phys(ds)->ds_unique_bytes += used;
 135 
 136         if (BP_GET_LSIZE(bp) > SPA_OLD_MAXBLOCKSIZE) {
 137                 ds->ds_feature_activation_needed[SPA_FEATURE_LARGE_BLOCKS] =
 138                     B_TRUE;
 139         }
 140 
 141         spa_feature_t f = zio_checksum_to_feature(BP_GET_CHECKSUM(bp));
 142         if (f != SPA_FEATURE_NONE)
 143                 ds->ds_feature_activation_needed[f] = B_TRUE;
 144 
 145         mutex_exit(&ds->ds_lock);
 146         dsl_dir_diduse_space(ds->ds_dir, DD_USED_HEAD, delta,
 147             compressed, uncompressed, tx);
 148         dsl_dir_transfer_space(ds->ds_dir, used - delta,
 149             DD_USED_REFRSRV, DD_USED_HEAD, tx);
 150 }
 151 
 152 int
 153 dsl_dataset_block_kill(dsl_dataset_t *ds, const blkptr_t *bp, dmu_tx_t *tx,
 154     boolean_t async)
 155 {
 156         int used = bp_get_dsize_sync(tx->tx_pool->dp_spa, bp);
 157         int compressed = BP_GET_PSIZE(bp);
 158         int uncompressed = BP_GET_UCSIZE(bp);
 159 
 160         if (BP_IS_HOLE(bp))
 161                 return (0);
 162 
 163         ASSERT(dmu_tx_is_syncing(tx));
 164         ASSERT(bp->blk_birth <= tx->tx_txg);
 165 
 166         if (ds == NULL) {
 167                 dsl_free(tx->tx_pool, tx->tx_txg, bp);
 168                 dsl_pool_mos_diduse_space(tx->tx_pool,
 169                     -used, -compressed, -uncompressed);
 170                 return (used);
 171         }
 172         ASSERT3P(tx->tx_pool, ==, ds->ds_dir->dd_pool);
 173 
 174         ASSERT(!ds->ds_is_snapshot);
 175         dmu_buf_will_dirty(ds->ds_dbuf, tx);
 176 
 177         if (bp->blk_birth > dsl_dataset_phys(ds)->ds_prev_snap_txg) {
 178                 int64_t delta;
 179 
 180                 dprintf_bp(bp, "freeing ds=%llu", ds->ds_object);
 181                 dsl_free(tx->tx_pool, tx->tx_txg, bp);
 182 
 183                 mutex_enter(&ds->ds_lock);
 184                 ASSERT(dsl_dataset_phys(ds)->ds_unique_bytes >= used ||
 185                     !DS_UNIQUE_IS_ACCURATE(ds));
 186                 delta = parent_delta(ds, -used);
 187                 dsl_dataset_phys(ds)->ds_unique_bytes -= used;
 188                 mutex_exit(&ds->ds_lock);
 189                 dsl_dir_diduse_space(ds->ds_dir, DD_USED_HEAD,
 190                     delta, -compressed, -uncompressed, tx);
 191                 dsl_dir_transfer_space(ds->ds_dir, -used - delta,
 192                     DD_USED_REFRSRV, DD_USED_HEAD, tx);
 193         } else {
 194                 dprintf_bp(bp, "putting on dead list: %s", "");
 195                 if (async) {
 196                         /*
 197                          * We are here as part of zio's write done callback,
 198                          * which means we're a zio interrupt thread.  We can't
 199                          * call dsl_deadlist_insert() now because it may block
 200                          * waiting for I/O.  Instead, put bp on the deferred
 201                          * queue and let dsl_pool_sync() finish the job.
 202                          */
 203                         bplist_append(&ds->ds_pending_deadlist, bp);
 204                 } else {
 205                         dsl_deadlist_insert(&ds->ds_deadlist, bp, tx);
 206                 }
 207                 ASSERT3U(ds->ds_prev->ds_object, ==,
 208                     dsl_dataset_phys(ds)->ds_prev_snap_obj);
 209                 ASSERT(dsl_dataset_phys(ds->ds_prev)->ds_num_children > 0);
 210                 /* if (bp->blk_birth > prev prev snap txg) prev unique += bs */
 211                 if (dsl_dataset_phys(ds->ds_prev)->ds_next_snap_obj ==
 212                     ds->ds_object && bp->blk_birth >
 213                     dsl_dataset_phys(ds->ds_prev)->ds_prev_snap_txg) {
 214                         dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
 215                         mutex_enter(&ds->ds_prev->ds_lock);
 216                         dsl_dataset_phys(ds->ds_prev)->ds_unique_bytes += used;
 217                         mutex_exit(&ds->ds_prev->ds_lock);
 218                 }
 219                 if (bp->blk_birth > ds->ds_dir->dd_origin_txg) {
 220                         dsl_dir_transfer_space(ds->ds_dir, used,
 221                             DD_USED_HEAD, DD_USED_SNAP, tx);
 222                 }
 223         }
 224         mutex_enter(&ds->ds_lock);
 225         ASSERT3U(dsl_dataset_phys(ds)->ds_referenced_bytes, >=, used);
 226         dsl_dataset_phys(ds)->ds_referenced_bytes -= used;
 227         ASSERT3U(dsl_dataset_phys(ds)->ds_compressed_bytes, >=, compressed);
 228         dsl_dataset_phys(ds)->ds_compressed_bytes -= compressed;
 229         ASSERT3U(dsl_dataset_phys(ds)->ds_uncompressed_bytes, >=, uncompressed);
 230         dsl_dataset_phys(ds)->ds_uncompressed_bytes -= uncompressed;
 231         mutex_exit(&ds->ds_lock);
 232 
 233         return (used);
 234 }
 235 
 236 uint64_t
 237 dsl_dataset_prev_snap_txg(dsl_dataset_t *ds)
 238 {
 239         uint64_t trysnap = 0;
 240 
 241         if (ds == NULL)
 242                 return (0);
 243         /*
 244          * The snapshot creation could fail, but that would cause an
 245          * incorrect FALSE return, which would only result in an
 246          * overestimation of the amount of space that an operation would
 247          * consume, which is OK.
 248          *
 249          * There's also a small window where we could miss a pending
 250          * snapshot, because we could set the sync task in the quiescing
 251          * phase.  So this should only be used as a guess.
 252          */
 253         if (ds->ds_trysnap_txg >
 254             spa_last_synced_txg(ds->ds_dir->dd_pool->dp_spa))
 255                 trysnap = ds->ds_trysnap_txg;
 256         return (MAX(dsl_dataset_phys(ds)->ds_prev_snap_txg, trysnap));
 257 }
 258 
 259 boolean_t
 260 dsl_dataset_block_freeable(dsl_dataset_t *ds, const blkptr_t *bp,
 261     uint64_t blk_birth)
 262 {
 263         if (blk_birth <= dsl_dataset_prev_snap_txg(ds) ||
 264             (bp != NULL && BP_IS_HOLE(bp)))
 265                 return (B_FALSE);
 266 
 267         ddt_prefetch(dsl_dataset_get_spa(ds), bp);
 268 
 269         return (B_TRUE);
 270 }
 271 
 272 static void
 273 dsl_dataset_evict(void *dbu)
 274 {
 275         dsl_dataset_t *ds = dbu;
 276 
 277         ASSERT(ds->ds_owner == NULL);
 278 
 279         ds->ds_dbuf = NULL;
 280 
 281         unique_remove(ds->ds_fsid_guid);
 282 
 283         if (ds->ds_objset != NULL)
 284                 dmu_objset_evict(ds->ds_objset);
 285 
 286         if (ds->ds_prev) {
 287                 dsl_dataset_rele(ds->ds_prev, ds);
 288                 ds->ds_prev = NULL;
 289         }
 290 
 291         bplist_destroy(&ds->ds_pending_deadlist);
 292         if (ds->ds_deadlist.dl_os != NULL)
 293                 dsl_deadlist_close(&ds->ds_deadlist);
 294         if (ds->ds_dir)
 295                 dsl_dir_async_rele(ds->ds_dir, ds);
 296 
 297         ASSERT(!list_link_active(&ds->ds_synced_link));
 298 
 299         list_destroy(&ds->ds_prop_cbs);
 300         mutex_destroy(&ds->ds_lock);
 301         mutex_destroy(&ds->ds_opening_lock);
 302         mutex_destroy(&ds->ds_sendstream_lock);
 303         refcount_destroy(&ds->ds_longholds);
 304 
 305         kmem_free(ds, sizeof (dsl_dataset_t));
 306 }
 307 
 308 int
 309 dsl_dataset_get_snapname(dsl_dataset_t *ds)
 310 {
 311         dsl_dataset_phys_t *headphys;
 312         int err;
 313         dmu_buf_t *headdbuf;
 314         dsl_pool_t *dp = ds->ds_dir->dd_pool;
 315         objset_t *mos = dp->dp_meta_objset;
 316 
 317         if (ds->ds_snapname[0])
 318                 return (0);
 319         if (dsl_dataset_phys(ds)->ds_next_snap_obj == 0)
 320                 return (0);
 321 
 322         err = dmu_bonus_hold(mos, dsl_dir_phys(ds->ds_dir)->dd_head_dataset_obj,
 323             FTAG, &headdbuf);
 324         if (err != 0)
 325                 return (err);
 326         headphys = headdbuf->db_data;
 327         err = zap_value_search(dp->dp_meta_objset,
 328             headphys->ds_snapnames_zapobj, ds->ds_object, 0, ds->ds_snapname);
 329         dmu_buf_rele(headdbuf, FTAG);
 330         return (err);
 331 }
 332 
 333 int
 334 dsl_dataset_snap_lookup(dsl_dataset_t *ds, const char *name, uint64_t *value)
 335 {
 336         objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
 337         uint64_t snapobj = dsl_dataset_phys(ds)->ds_snapnames_zapobj;
 338         matchtype_t mt;
 339         int err;
 340 
 341         if (dsl_dataset_phys(ds)->ds_flags & DS_FLAG_CI_DATASET)
 342                 mt = MT_FIRST;
 343         else
 344                 mt = MT_EXACT;
 345 
 346         err = zap_lookup_norm(mos, snapobj, name, 8, 1,
 347             value, mt, NULL, 0, NULL);
 348         if (err == ENOTSUP && mt == MT_FIRST)
 349                 err = zap_lookup(mos, snapobj, name, 8, 1, value);
 350         return (err);
 351 }
 352 
 353 int
 354 dsl_dataset_snap_remove(dsl_dataset_t *ds, const char *name, dmu_tx_t *tx,
 355     boolean_t adj_cnt)
 356 {
 357         objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
 358         uint64_t snapobj = dsl_dataset_phys(ds)->ds_snapnames_zapobj;
 359         matchtype_t mt;
 360         int err;
 361 
 362         dsl_dir_snap_cmtime_update(ds->ds_dir);
 363 
 364         if (dsl_dataset_phys(ds)->ds_flags & DS_FLAG_CI_DATASET)
 365                 mt = MT_FIRST;
 366         else
 367                 mt = MT_EXACT;
 368 
 369         err = zap_remove_norm(mos, snapobj, name, mt, tx);
 370         if (err == ENOTSUP && mt == MT_FIRST)
 371                 err = zap_remove(mos, snapobj, name, tx);
 372 
 373         if (err == 0 && adj_cnt)
 374                 dsl_fs_ss_count_adjust(ds->ds_dir, -1,
 375                     DD_FIELD_SNAPSHOT_COUNT, tx);
 376 
 377         return (err);
 378 }
 379 
 380 boolean_t
 381 dsl_dataset_try_add_ref(dsl_pool_t *dp, dsl_dataset_t *ds, void *tag)
 382 {
 383         dmu_buf_t *dbuf = ds->ds_dbuf;
 384         boolean_t result = B_FALSE;
 385 
 386         if (dbuf != NULL && dmu_buf_try_add_ref(dbuf, dp->dp_meta_objset,
 387             ds->ds_object, DMU_BONUS_BLKID, tag)) {
 388 
 389                 if (ds == dmu_buf_get_user(dbuf))
 390                         result = B_TRUE;
 391                 else
 392                         dmu_buf_rele(dbuf, tag);
 393         }
 394 
 395         return (result);
 396 }
 397 
 398 int
 399 dsl_dataset_hold_obj(dsl_pool_t *dp, uint64_t dsobj, void *tag,
 400     dsl_dataset_t **dsp)
 401 {
 402         objset_t *mos = dp->dp_meta_objset;
 403         dmu_buf_t *dbuf;
 404         dsl_dataset_t *ds;
 405         int err;
 406         dmu_object_info_t doi;
 407 
 408         ASSERT(dsl_pool_config_held(dp));
 409 
 410         err = dmu_bonus_hold(mos, dsobj, tag, &dbuf);
 411         if (err != 0)
 412                 return (err);
 413 
 414         /* Make sure dsobj has the correct object type. */
 415         dmu_object_info_from_db(dbuf, &doi);
 416         if (doi.doi_bonus_type != DMU_OT_DSL_DATASET) {
 417                 dmu_buf_rele(dbuf, tag);
 418                 return (SET_ERROR(EINVAL));
 419         }
 420 
 421         ds = dmu_buf_get_user(dbuf);
 422         if (ds == NULL) {
 423                 dsl_dataset_t *winner = NULL;
 424 
 425                 ds = kmem_zalloc(sizeof (dsl_dataset_t), KM_SLEEP);
 426                 ds->ds_dbuf = dbuf;
 427                 ds->ds_object = dsobj;
 428                 ds->ds_is_snapshot = dsl_dataset_phys(ds)->ds_num_children != 0;
 429 
 430                 mutex_init(&ds->ds_lock, NULL, MUTEX_DEFAULT, NULL);
 431                 mutex_init(&ds->ds_opening_lock, NULL, MUTEX_DEFAULT, NULL);
 432                 mutex_init(&ds->ds_sendstream_lock, NULL, MUTEX_DEFAULT, NULL);
 433                 refcount_create(&ds->ds_longholds);
 434 
 435                 bplist_create(&ds->ds_pending_deadlist);
 436                 dsl_deadlist_open(&ds->ds_deadlist,
 437                     mos, dsl_dataset_phys(ds)->ds_deadlist_obj);
 438 
 439                 list_create(&ds->ds_sendstreams, sizeof (dmu_sendarg_t),
 440                     offsetof(dmu_sendarg_t, dsa_link));
 441 
 442                 list_create(&ds->ds_prop_cbs, sizeof (dsl_prop_cb_record_t),
 443                     offsetof(dsl_prop_cb_record_t, cbr_ds_node));
 444 
 445                 if (doi.doi_type == DMU_OTN_ZAP_METADATA) {
 446                         for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
 447                                 if (!(spa_feature_table[f].fi_flags &
 448                                     ZFEATURE_FLAG_PER_DATASET))
 449                                         continue;
 450                                 err = zap_contains(mos, dsobj,
 451                                     spa_feature_table[f].fi_guid);
 452                                 if (err == 0) {
 453                                         ds->ds_feature_inuse[f] = B_TRUE;
 454                                 } else {
 455                                         ASSERT3U(err, ==, ENOENT);
 456                                         err = 0;
 457                                 }
 458                         }
 459                 }
 460 
 461                 err = dsl_dir_hold_obj(dp,
 462                     dsl_dataset_phys(ds)->ds_dir_obj, NULL, ds, &ds->ds_dir);
 463                 if (err != 0) {
 464                         mutex_destroy(&ds->ds_lock);
 465                         mutex_destroy(&ds->ds_opening_lock);
 466                         mutex_destroy(&ds->ds_sendstream_lock);
 467                         refcount_destroy(&ds->ds_longholds);
 468                         bplist_destroy(&ds->ds_pending_deadlist);
 469                         dsl_deadlist_close(&ds->ds_deadlist);
 470                         kmem_free(ds, sizeof (dsl_dataset_t));
 471                         dmu_buf_rele(dbuf, tag);
 472                         return (err);
 473                 }
 474 
 475                 if (!ds->ds_is_snapshot) {
 476                         ds->ds_snapname[0] = '\0';
 477                         if (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {
 478                                 err = dsl_dataset_hold_obj(dp,
 479                                     dsl_dataset_phys(ds)->ds_prev_snap_obj,
 480                                     ds, &ds->ds_prev);
 481                         }
 482                         if (doi.doi_type == DMU_OTN_ZAP_METADATA) {
 483                                 int zaperr = zap_lookup(mos, ds->ds_object,
 484                                     DS_FIELD_BOOKMARK_NAMES,
 485                                     sizeof (ds->ds_bookmarks), 1,
 486                                     &ds->ds_bookmarks);
 487                                 if (zaperr != ENOENT)
 488                                         VERIFY0(zaperr);
 489                         }
 490                 } else {
 491                         if (zfs_flags & ZFS_DEBUG_SNAPNAMES)
 492                                 err = dsl_dataset_get_snapname(ds);
 493                         if (err == 0 &&
 494                             dsl_dataset_phys(ds)->ds_userrefs_obj != 0) {
 495                                 err = zap_count(
 496                                     ds->ds_dir->dd_pool->dp_meta_objset,
 497                                     dsl_dataset_phys(ds)->ds_userrefs_obj,
 498                                     &ds->ds_userrefs);
 499                         }
 500                 }
 501 
 502                 if (err == 0 && !ds->ds_is_snapshot) {
 503                         err = dsl_prop_get_int_ds(ds,
 504                             zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
 505                             &ds->ds_reserved);
 506                         if (err == 0) {
 507                                 err = dsl_prop_get_int_ds(ds,
 508                                     zfs_prop_to_name(ZFS_PROP_REFQUOTA),
 509                                     &ds->ds_quota);
 510                         }
 511                 } else {
 512                         ds->ds_reserved = ds->ds_quota = 0;
 513                 }
 514 
 515                 dmu_buf_init_user(&ds->ds_dbu, dsl_dataset_evict, &ds->ds_dbuf);
 516                 if (err == 0)
 517                         winner = dmu_buf_set_user_ie(dbuf, &ds->ds_dbu);
 518 
 519                 if (err != 0 || winner != NULL) {
 520                         bplist_destroy(&ds->ds_pending_deadlist);
 521                         dsl_deadlist_close(&ds->ds_deadlist);
 522                         if (ds->ds_prev)
 523                                 dsl_dataset_rele(ds->ds_prev, ds);
 524                         dsl_dir_rele(ds->ds_dir, ds);
 525                         mutex_destroy(&ds->ds_lock);
 526                         mutex_destroy(&ds->ds_opening_lock);
 527                         mutex_destroy(&ds->ds_sendstream_lock);
 528                         refcount_destroy(&ds->ds_longholds);
 529                         kmem_free(ds, sizeof (dsl_dataset_t));
 530                         if (err != 0) {
 531                                 dmu_buf_rele(dbuf, tag);
 532                                 return (err);
 533                         }
 534                         ds = winner;
 535                 } else {
 536                         ds->ds_fsid_guid =
 537                             unique_insert(dsl_dataset_phys(ds)->ds_fsid_guid);
 538                 }
 539         }
 540         ASSERT3P(ds->ds_dbuf, ==, dbuf);
 541         ASSERT3P(dsl_dataset_phys(ds), ==, dbuf->db_data);
 542         ASSERT(dsl_dataset_phys(ds)->ds_prev_snap_obj != 0 ||
 543             spa_version(dp->dp_spa) < SPA_VERSION_ORIGIN ||
 544             dp->dp_origin_snap == NULL || ds == dp->dp_origin_snap);
 545         *dsp = ds;
 546         return (0);
 547 }
 548 
 549 int
 550 dsl_dataset_hold(dsl_pool_t *dp, const char *name,
 551     void *tag, dsl_dataset_t **dsp)
 552 {
 553         dsl_dir_t *dd;
 554         const char *snapname;
 555         uint64_t obj;
 556         int err = 0;
 557         dsl_dataset_t *ds;
 558 
 559         err = dsl_dir_hold(dp, name, FTAG, &dd, &snapname);
 560         if (err != 0)
 561                 return (err);
 562 
 563         ASSERT(dsl_pool_config_held(dp));
 564         obj = dsl_dir_phys(dd)->dd_head_dataset_obj;
 565         if (obj != 0)
 566                 err = dsl_dataset_hold_obj(dp, obj, tag, &ds);
 567         else
 568                 err = SET_ERROR(ENOENT);
 569 
 570         /* we may be looking for a snapshot */
 571         if (err == 0 && snapname != NULL) {
 572                 dsl_dataset_t *snap_ds;
 573 
 574                 if (*snapname++ != '@') {
 575                         dsl_dataset_rele(ds, tag);
 576                         dsl_dir_rele(dd, FTAG);
 577                         return (SET_ERROR(ENOENT));
 578                 }
 579 
 580                 dprintf("looking for snapshot '%s'\n", snapname);
 581                 err = dsl_dataset_snap_lookup(ds, snapname, &obj);
 582                 if (err == 0)
 583                         err = dsl_dataset_hold_obj(dp, obj, tag, &snap_ds);
 584                 dsl_dataset_rele(ds, tag);
 585 
 586                 if (err == 0) {
 587                         mutex_enter(&snap_ds->ds_lock);
 588                         if (snap_ds->ds_snapname[0] == 0)
 589                                 (void) strlcpy(snap_ds->ds_snapname, snapname,
 590                                     sizeof (snap_ds->ds_snapname));
 591                         mutex_exit(&snap_ds->ds_lock);
 592                         ds = snap_ds;
 593                 }
 594         }
 595         if (err == 0)
 596                 *dsp = ds;
 597         dsl_dir_rele(dd, FTAG);
 598         return (err);
 599 }
 600 
 601 int
 602 dsl_dataset_own_obj(dsl_pool_t *dp, uint64_t dsobj,
 603     void *tag, dsl_dataset_t **dsp)
 604 {
 605         int err = dsl_dataset_hold_obj(dp, dsobj, tag, dsp);
 606         if (err != 0)
 607                 return (err);
 608         if (!dsl_dataset_tryown(*dsp, tag)) {
 609                 dsl_dataset_rele(*dsp, tag);
 610                 *dsp = NULL;
 611                 return (SET_ERROR(EBUSY));
 612         }
 613         return (0);
 614 }
 615 
 616 int
 617 dsl_dataset_own(dsl_pool_t *dp, const char *name,
 618     void *tag, dsl_dataset_t **dsp)
 619 {
 620         int err = dsl_dataset_hold(dp, name, tag, dsp);
 621         if (err != 0)
 622                 return (err);
 623         if (!dsl_dataset_tryown(*dsp, tag)) {
 624                 dsl_dataset_rele(*dsp, tag);
 625                 return (SET_ERROR(EBUSY));
 626         }
 627         return (0);
 628 }
 629 
 630 /*
 631  * See the comment above dsl_pool_hold() for details.  In summary, a long
 632  * hold is used to prevent destruction of a dataset while the pool hold
 633  * is dropped, allowing other concurrent operations (e.g. spa_sync()).
 634  *
 635  * The dataset and pool must be held when this function is called.  After it
 636  * is called, the pool hold may be released while the dataset is still held
 637  * and accessed.
 638  */
 639 void
 640 dsl_dataset_long_hold(dsl_dataset_t *ds, void *tag)
 641 {
 642         ASSERT(dsl_pool_config_held(ds->ds_dir->dd_pool));
 643         (void) refcount_add(&ds->ds_longholds, tag);
 644 }
 645 
 646 void
 647 dsl_dataset_long_rele(dsl_dataset_t *ds, void *tag)
 648 {
 649         (void) refcount_remove(&ds->ds_longholds, tag);
 650 }
 651 
 652 /* Return B_TRUE if there are any long holds on this dataset. */
 653 boolean_t
 654 dsl_dataset_long_held(dsl_dataset_t *ds)
 655 {
 656         return (!refcount_is_zero(&ds->ds_longholds));
 657 }
 658 
 659 void
 660 dsl_dataset_name(dsl_dataset_t *ds, char *name)
 661 {
 662         if (ds == NULL) {
 663                 (void) strcpy(name, "mos");
 664         } else {
 665                 dsl_dir_name(ds->ds_dir, name);
 666                 VERIFY0(dsl_dataset_get_snapname(ds));
 667                 if (ds->ds_snapname[0]) {
 668                         (void) strcat(name, "@");
 669                         /*
 670                          * We use a "recursive" mutex so that we
 671                          * can call dprintf_ds() with ds_lock held.
 672                          */
 673                         if (!MUTEX_HELD(&ds->ds_lock)) {
 674                                 mutex_enter(&ds->ds_lock);
 675                                 (void) strcat(name, ds->ds_snapname);
 676                                 mutex_exit(&ds->ds_lock);
 677                         } else {
 678                                 (void) strcat(name, ds->ds_snapname);
 679                         }
 680                 }
 681         }
 682 }
 683 
 684 void
 685 dsl_dataset_rele(dsl_dataset_t *ds, void *tag)
 686 {
 687         dmu_buf_rele(ds->ds_dbuf, tag);
 688 }
 689 
 690 void
 691 dsl_dataset_disown(dsl_dataset_t *ds, void *tag)
 692 {
 693         ASSERT3P(ds->ds_owner, ==, tag);
 694         ASSERT(ds->ds_dbuf != NULL);
 695 
 696         mutex_enter(&ds->ds_lock);
 697         ds->ds_owner = NULL;
 698         mutex_exit(&ds->ds_lock);
 699         dsl_dataset_long_rele(ds, tag);
 700         dsl_dataset_rele(ds, tag);
 701 }
 702 
 703 boolean_t
 704 dsl_dataset_tryown(dsl_dataset_t *ds, void *tag)
 705 {
 706         boolean_t gotit = FALSE;
 707 
 708         ASSERT(dsl_pool_config_held(ds->ds_dir->dd_pool));
 709         mutex_enter(&ds->ds_lock);
 710         if (ds->ds_owner == NULL && !DS_IS_INCONSISTENT(ds)) {
 711                 ds->ds_owner = tag;
 712                 dsl_dataset_long_hold(ds, tag);
 713                 gotit = TRUE;
 714         }
 715         mutex_exit(&ds->ds_lock);
 716         return (gotit);
 717 }
 718 
 719 boolean_t
 720 dsl_dataset_has_owner(dsl_dataset_t *ds)
 721 {
 722         boolean_t rv;
 723         mutex_enter(&ds->ds_lock);
 724         rv = (ds->ds_owner != NULL);
 725         mutex_exit(&ds->ds_lock);
 726         return (rv);
 727 }
 728 
 729 static void
 730 dsl_dataset_activate_feature(uint64_t dsobj, spa_feature_t f, dmu_tx_t *tx)
 731 {
 732         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
 733         objset_t *mos = dmu_tx_pool(tx)->dp_meta_objset;
 734         uint64_t zero = 0;
 735 
 736         VERIFY(spa_feature_table[f].fi_flags & ZFEATURE_FLAG_PER_DATASET);
 737 
 738         spa_feature_incr(spa, f, tx);
 739         dmu_object_zapify(mos, dsobj, DMU_OT_DSL_DATASET, tx);
 740 
 741         VERIFY0(zap_add(mos, dsobj, spa_feature_table[f].fi_guid,
 742             sizeof (zero), 1, &zero, tx));
 743 }
 744 
 745 void
 746 dsl_dataset_deactivate_feature(uint64_t dsobj, spa_feature_t f, dmu_tx_t *tx)
 747 {
 748         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
 749         objset_t *mos = dmu_tx_pool(tx)->dp_meta_objset;
 750 
 751         VERIFY(spa_feature_table[f].fi_flags & ZFEATURE_FLAG_PER_DATASET);
 752 
 753         VERIFY0(zap_remove(mos, dsobj, spa_feature_table[f].fi_guid, tx));
 754         spa_feature_decr(spa, f, tx);
 755 }
 756 
 757 uint64_t
 758 dsl_dataset_create_sync_dd(dsl_dir_t *dd, dsl_dataset_t *origin,
 759     uint64_t flags, dmu_tx_t *tx)
 760 {
 761         dsl_pool_t *dp = dd->dd_pool;
 762         dmu_buf_t *dbuf;
 763         dsl_dataset_phys_t *dsphys;
 764         uint64_t dsobj;
 765         objset_t *mos = dp->dp_meta_objset;
 766 
 767         if (origin == NULL)
 768                 origin = dp->dp_origin_snap;
 769 
 770         ASSERT(origin == NULL || origin->ds_dir->dd_pool == dp);
 771         ASSERT(origin == NULL || dsl_dataset_phys(origin)->ds_num_children > 0);
 772         ASSERT(dmu_tx_is_syncing(tx));
 773         ASSERT(dsl_dir_phys(dd)->dd_head_dataset_obj == 0);
 774 
 775         dsobj = dmu_object_alloc(mos, DMU_OT_DSL_DATASET, 0,
 776             DMU_OT_DSL_DATASET, sizeof (dsl_dataset_phys_t), tx);
 777         VERIFY0(dmu_bonus_hold(mos, dsobj, FTAG, &dbuf));
 778         dmu_buf_will_dirty(dbuf, tx);
 779         dsphys = dbuf->db_data;
 780         bzero(dsphys, sizeof (dsl_dataset_phys_t));
 781         dsphys->ds_dir_obj = dd->dd_object;
 782         dsphys->ds_flags = flags;
 783         dsphys->ds_fsid_guid = unique_create();
 784         (void) random_get_pseudo_bytes((void*)&dsphys->ds_guid,
 785             sizeof (dsphys->ds_guid));
 786         dsphys->ds_snapnames_zapobj =
 787             zap_create_norm(mos, U8_TEXTPREP_TOUPPER, DMU_OT_DSL_DS_SNAP_MAP,
 788             DMU_OT_NONE, 0, tx);
 789         dsphys->ds_creation_time = gethrestime_sec();
 790         dsphys->ds_creation_txg = tx->tx_txg == TXG_INITIAL ? 1 : tx->tx_txg;
 791 
 792         if (origin == NULL) {
 793                 dsphys->ds_deadlist_obj = dsl_deadlist_alloc(mos, tx);
 794         } else {
 795                 dsl_dataset_t *ohds; /* head of the origin snapshot */
 796 
 797                 dsphys->ds_prev_snap_obj = origin->ds_object;
 798                 dsphys->ds_prev_snap_txg =
 799                     dsl_dataset_phys(origin)->ds_creation_txg;
 800                 dsphys->ds_referenced_bytes =
 801                     dsl_dataset_phys(origin)->ds_referenced_bytes;
 802                 dsphys->ds_compressed_bytes =
 803                     dsl_dataset_phys(origin)->ds_compressed_bytes;
 804                 dsphys->ds_uncompressed_bytes =
 805                     dsl_dataset_phys(origin)->ds_uncompressed_bytes;
 806                 dsphys->ds_bp = dsl_dataset_phys(origin)->ds_bp;
 807 
 808                 /*
 809                  * Inherit flags that describe the dataset's contents
 810                  * (INCONSISTENT) or properties (Case Insensitive).
 811                  */
 812                 dsphys->ds_flags |= dsl_dataset_phys(origin)->ds_flags &
 813                     (DS_FLAG_INCONSISTENT | DS_FLAG_CI_DATASET);
 814 
 815                 for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
 816                         if (origin->ds_feature_inuse[f])
 817                                 dsl_dataset_activate_feature(dsobj, f, tx);
 818                 }
 819 
 820                 dmu_buf_will_dirty(origin->ds_dbuf, tx);
 821                 dsl_dataset_phys(origin)->ds_num_children++;
 822 
 823                 VERIFY0(dsl_dataset_hold_obj(dp,
 824                     dsl_dir_phys(origin->ds_dir)->dd_head_dataset_obj,
 825                     FTAG, &ohds));
 826                 dsphys->ds_deadlist_obj = dsl_deadlist_clone(&ohds->ds_deadlist,
 827                     dsphys->ds_prev_snap_txg, dsphys->ds_prev_snap_obj, tx);
 828                 dsl_dataset_rele(ohds, FTAG);
 829 
 830                 if (spa_version(dp->dp_spa) >= SPA_VERSION_NEXT_CLONES) {
 831                         if (dsl_dataset_phys(origin)->ds_next_clones_obj == 0) {
 832                                 dsl_dataset_phys(origin)->ds_next_clones_obj =
 833                                     zap_create(mos,
 834                                     DMU_OT_NEXT_CLONES, DMU_OT_NONE, 0, tx);
 835                         }
 836                         VERIFY0(zap_add_int(mos,
 837                             dsl_dataset_phys(origin)->ds_next_clones_obj,
 838                             dsobj, tx));
 839                 }
 840 
 841                 dmu_buf_will_dirty(dd->dd_dbuf, tx);
 842                 dsl_dir_phys(dd)->dd_origin_obj = origin->ds_object;
 843                 if (spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
 844                         if (dsl_dir_phys(origin->ds_dir)->dd_clones == 0) {
 845                                 dmu_buf_will_dirty(origin->ds_dir->dd_dbuf, tx);
 846                                 dsl_dir_phys(origin->ds_dir)->dd_clones =
 847                                     zap_create(mos,
 848                                     DMU_OT_DSL_CLONES, DMU_OT_NONE, 0, tx);
 849                         }
 850                         VERIFY0(zap_add_int(mos,
 851                             dsl_dir_phys(origin->ds_dir)->dd_clones,
 852                             dsobj, tx));
 853                 }
 854         }
 855 
 856         if (spa_version(dp->dp_spa) >= SPA_VERSION_UNIQUE_ACCURATE)
 857                 dsphys->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
 858 
 859         dmu_buf_rele(dbuf, FTAG);
 860 
 861         dmu_buf_will_dirty(dd->dd_dbuf, tx);
 862         dsl_dir_phys(dd)->dd_head_dataset_obj = dsobj;
 863 
 864         return (dsobj);
 865 }
 866 
 867 static void
 868 dsl_dataset_zero_zil(dsl_dataset_t *ds, dmu_tx_t *tx)
 869 {
 870         objset_t *os;
 871 
 872         VERIFY0(dmu_objset_from_ds(ds, &os));
 873         bzero(&os->os_zil_header, sizeof (os->os_zil_header));
 874         dsl_dataset_dirty(ds, tx);
 875 }
 876 
 877 uint64_t
 878 dsl_dataset_create_sync(dsl_dir_t *pdd, const char *lastname,
 879     dsl_dataset_t *origin, uint64_t flags, cred_t *cr, dmu_tx_t *tx)
 880 {
 881         dsl_pool_t *dp = pdd->dd_pool;
 882         uint64_t dsobj, ddobj;
 883         dsl_dir_t *dd;
 884 
 885         ASSERT(dmu_tx_is_syncing(tx));
 886         ASSERT(lastname[0] != '@');
 887 
 888         ddobj = dsl_dir_create_sync(dp, pdd, lastname, tx);
 889         VERIFY0(dsl_dir_hold_obj(dp, ddobj, lastname, FTAG, &dd));
 890 
 891         dsobj = dsl_dataset_create_sync_dd(dd, origin,
 892             flags & ~DS_CREATE_FLAG_NODIRTY, tx);
 893 
 894         dsl_deleg_set_create_perms(dd, tx, cr);
 895 
 896         /*
 897          * Since we're creating a new node we know it's a leaf, so we can
 898          * initialize the counts if the limit feature is active.
 899          */
 900         if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_FS_SS_LIMIT)) {
 901                 uint64_t cnt = 0;
 902                 objset_t *os = dd->dd_pool->dp_meta_objset;
 903 
 904                 dsl_dir_zapify(dd, tx);
 905                 VERIFY0(zap_add(os, dd->dd_object, DD_FIELD_FILESYSTEM_COUNT,
 906                     sizeof (cnt), 1, &cnt, tx));
 907                 VERIFY0(zap_add(os, dd->dd_object, DD_FIELD_SNAPSHOT_COUNT,
 908                     sizeof (cnt), 1, &cnt, tx));
 909         }
 910 
 911         dsl_dir_rele(dd, FTAG);
 912 
 913         /*
 914          * If we are creating a clone, make sure we zero out any stale
 915          * data from the origin snapshots zil header.
 916          */
 917         if (origin != NULL && !(flags & DS_CREATE_FLAG_NODIRTY)) {
 918                 dsl_dataset_t *ds;
 919 
 920                 VERIFY0(dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
 921                 dsl_dataset_zero_zil(ds, tx);
 922                 dsl_dataset_rele(ds, FTAG);
 923         }
 924 
 925         return (dsobj);
 926 }
 927 
 928 /*
 929  * The unique space in the head dataset can be calculated by subtracting
 930  * the space used in the most recent snapshot, that is still being used
 931  * in this file system, from the space currently in use.  To figure out
 932  * the space in the most recent snapshot still in use, we need to take
 933  * the total space used in the snapshot and subtract out the space that
 934  * has been freed up since the snapshot was taken.
 935  */
 936 void
 937 dsl_dataset_recalc_head_uniq(dsl_dataset_t *ds)
 938 {
 939         uint64_t mrs_used;
 940         uint64_t dlused, dlcomp, dluncomp;
 941 
 942         ASSERT(!ds->ds_is_snapshot);
 943 
 944         if (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0)
 945                 mrs_used = dsl_dataset_phys(ds->ds_prev)->ds_referenced_bytes;
 946         else
 947                 mrs_used = 0;
 948 
 949         dsl_deadlist_space(&ds->ds_deadlist, &dlused, &dlcomp, &dluncomp);
 950 
 951         ASSERT3U(dlused, <=, mrs_used);
 952         dsl_dataset_phys(ds)->ds_unique_bytes =
 953             dsl_dataset_phys(ds)->ds_referenced_bytes - (mrs_used - dlused);
 954 
 955         if (spa_version(ds->ds_dir->dd_pool->dp_spa) >=
 956             SPA_VERSION_UNIQUE_ACCURATE)
 957                 dsl_dataset_phys(ds)->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
 958 }
 959 
 960 void
 961 dsl_dataset_remove_from_next_clones(dsl_dataset_t *ds, uint64_t obj,
 962     dmu_tx_t *tx)
 963 {
 964         objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
 965         uint64_t count;
 966         int err;
 967 
 968         ASSERT(dsl_dataset_phys(ds)->ds_num_children >= 2);
 969         err = zap_remove_int(mos, dsl_dataset_phys(ds)->ds_next_clones_obj,
 970             obj, tx);
 971         /*
 972          * The err should not be ENOENT, but a bug in a previous version
 973          * of the code could cause upgrade_clones_cb() to not set
 974          * ds_next_snap_obj when it should, leading to a missing entry.
 975          * If we knew that the pool was created after
 976          * SPA_VERSION_NEXT_CLONES, we could assert that it isn't
 977          * ENOENT.  However, at least we can check that we don't have
 978          * too many entries in the next_clones_obj even after failing to
 979          * remove this one.
 980          */
 981         if (err != ENOENT)
 982                 VERIFY0(err);
 983         ASSERT0(zap_count(mos, dsl_dataset_phys(ds)->ds_next_clones_obj,
 984             &count));
 985         ASSERT3U(count, <=, dsl_dataset_phys(ds)->ds_num_children - 2);
 986 }
 987 
 988 
 989 blkptr_t *
 990 dsl_dataset_get_blkptr(dsl_dataset_t *ds)
 991 {
 992         return (&dsl_dataset_phys(ds)->ds_bp);
 993 }
 994 
 995 void
 996 dsl_dataset_set_blkptr(dsl_dataset_t *ds, blkptr_t *bp, dmu_tx_t *tx)
 997 {
 998         ASSERT(dmu_tx_is_syncing(tx));
 999         /* If it's the meta-objset, set dp_meta_rootbp */
1000         if (ds == NULL) {
1001                 tx->tx_pool->dp_meta_rootbp = *bp;
1002         } else {
1003                 dmu_buf_will_dirty(ds->ds_dbuf, tx);
1004                 dsl_dataset_phys(ds)->ds_bp = *bp;
1005         }
1006 }
1007 
1008 spa_t *
1009 dsl_dataset_get_spa(dsl_dataset_t *ds)
1010 {
1011         return (ds->ds_dir->dd_pool->dp_spa);
1012 }
1013 
1014 void
1015 dsl_dataset_dirty(dsl_dataset_t *ds, dmu_tx_t *tx)
1016 {
1017         dsl_pool_t *dp;
1018 
1019         if (ds == NULL) /* this is the meta-objset */
1020                 return;
1021 
1022         ASSERT(ds->ds_objset != NULL);
1023 
1024         if (dsl_dataset_phys(ds)->ds_next_snap_obj != 0)
1025                 panic("dirtying snapshot!");
1026 
1027         dp = ds->ds_dir->dd_pool;
1028 
1029         if (txg_list_add(&dp->dp_dirty_datasets, ds, tx->tx_txg)) {
1030                 /* up the hold count until we can be written out */
1031                 dmu_buf_add_ref(ds->ds_dbuf, ds);
1032         }
1033 }
1034 
1035 boolean_t
1036 dsl_dataset_is_dirty(dsl_dataset_t *ds)
1037 {
1038         for (int t = 0; t < TXG_SIZE; t++) {
1039                 if (txg_list_member(&ds->ds_dir->dd_pool->dp_dirty_datasets,
1040                     ds, t))
1041                         return (B_TRUE);
1042         }
1043         return (B_FALSE);
1044 }
1045 
1046 static int
1047 dsl_dataset_snapshot_reserve_space(dsl_dataset_t *ds, dmu_tx_t *tx)
1048 {
1049         uint64_t asize;
1050 
1051         if (!dmu_tx_is_syncing(tx))
1052                 return (0);
1053 
1054         /*
1055          * If there's an fs-only reservation, any blocks that might become
1056          * owned by the snapshot dataset must be accommodated by space
1057          * outside of the reservation.
1058          */
1059         ASSERT(ds->ds_reserved == 0 || DS_UNIQUE_IS_ACCURATE(ds));
1060         asize = MIN(dsl_dataset_phys(ds)->ds_unique_bytes, ds->ds_reserved);
1061         if (asize > dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE))
1062                 return (SET_ERROR(ENOSPC));
1063 
1064         /*
1065          * Propagate any reserved space for this snapshot to other
1066          * snapshot checks in this sync group.
1067          */
1068         if (asize > 0)
1069                 dsl_dir_willuse_space(ds->ds_dir, asize, tx);
1070 
1071         return (0);
1072 }
1073 
1074 typedef struct dsl_dataset_snapshot_arg {
1075         nvlist_t *ddsa_snaps;
1076         nvlist_t *ddsa_props;
1077         nvlist_t *ddsa_errors;
1078         cred_t *ddsa_cr;
1079 } dsl_dataset_snapshot_arg_t;
1080 
1081 int
1082 dsl_dataset_snapshot_check_impl(dsl_dataset_t *ds, const char *snapname,
1083     dmu_tx_t *tx, boolean_t recv, uint64_t cnt, cred_t *cr)
1084 {
1085         int error;
1086         uint64_t value;
1087 
1088         ds->ds_trysnap_txg = tx->tx_txg;
1089 
1090         if (!dmu_tx_is_syncing(tx))
1091                 return (0);
1092 
1093         /*
1094          * We don't allow multiple snapshots of the same txg.  If there
1095          * is already one, try again.
1096          */
1097         if (dsl_dataset_phys(ds)->ds_prev_snap_txg >= tx->tx_txg)
1098                 return (SET_ERROR(EAGAIN));
1099 
1100         /*
1101          * Check for conflicting snapshot name.
1102          */
1103         error = dsl_dataset_snap_lookup(ds, snapname, &value);
1104         if (error == 0)
1105                 return (SET_ERROR(EEXIST));
1106         if (error != ENOENT)
1107                 return (error);
1108 
1109         /*
1110          * We don't allow taking snapshots of inconsistent datasets, such as
1111          * those into which we are currently receiving.  However, if we are
1112          * creating this snapshot as part of a receive, this check will be
1113          * executed atomically with respect to the completion of the receive
1114          * itself but prior to the clearing of DS_FLAG_INCONSISTENT; in this
1115          * case we ignore this, knowing it will be fixed up for us shortly in
1116          * dmu_recv_end_sync().
1117          */
1118         if (!recv && DS_IS_INCONSISTENT(ds))
1119                 return (SET_ERROR(EBUSY));
1120 
1121         /*
1122          * Skip the check for temporary snapshots or if we have already checked
1123          * the counts in dsl_dataset_snapshot_check. This means we really only
1124          * check the count here when we're receiving a stream.
1125          */
1126         if (cnt != 0 && cr != NULL) {
1127                 error = dsl_fs_ss_limit_check(ds->ds_dir, cnt,
1128                     ZFS_PROP_SNAPSHOT_LIMIT, NULL, cr);
1129                 if (error != 0)
1130                         return (error);
1131         }
1132 
1133         error = dsl_dataset_snapshot_reserve_space(ds, tx);
1134         if (error != 0)
1135                 return (error);
1136 
1137         return (0);
1138 }
1139 
1140 static int
1141 dsl_dataset_snapshot_check(void *arg, dmu_tx_t *tx)
1142 {
1143         dsl_dataset_snapshot_arg_t *ddsa = arg;
1144         dsl_pool_t *dp = dmu_tx_pool(tx);
1145         nvpair_t *pair;
1146         int rv = 0;
1147 
1148         /*
1149          * Pre-compute how many total new snapshots will be created for each
1150          * level in the tree and below. This is needed for validating the
1151          * snapshot limit when either taking a recursive snapshot or when
1152          * taking multiple snapshots.
1153          *
1154          * The problem is that the counts are not actually adjusted when
1155          * we are checking, only when we finally sync. For a single snapshot,
1156          * this is easy, the count will increase by 1 at each node up the tree,
1157          * but its more complicated for the recursive/multiple snapshot case.
1158          *
1159          * The dsl_fs_ss_limit_check function does recursively check the count
1160          * at each level up the tree but since it is validating each snapshot
1161          * independently we need to be sure that we are validating the complete
1162          * count for the entire set of snapshots. We do this by rolling up the
1163          * counts for each component of the name into an nvlist and then
1164          * checking each of those cases with the aggregated count.
1165          *
1166          * This approach properly handles not only the recursive snapshot
1167          * case (where we get all of those on the ddsa_snaps list) but also
1168          * the sibling case (e.g. snapshot a/b and a/c so that we will also
1169          * validate the limit on 'a' using a count of 2).
1170          *
1171          * We validate the snapshot names in the third loop and only report
1172          * name errors once.
1173          */
1174         if (dmu_tx_is_syncing(tx)) {
1175                 nvlist_t *cnt_track = NULL;
1176                 cnt_track = fnvlist_alloc();
1177 
1178                 /* Rollup aggregated counts into the cnt_track list */
1179                 for (pair = nvlist_next_nvpair(ddsa->ddsa_snaps, NULL);
1180                     pair != NULL;
1181                     pair = nvlist_next_nvpair(ddsa->ddsa_snaps, pair)) {
1182                         char *pdelim;
1183                         uint64_t val;
1184                         char nm[MAXPATHLEN];
1185 
1186                         (void) strlcpy(nm, nvpair_name(pair), sizeof (nm));
1187                         pdelim = strchr(nm, '@');
1188                         if (pdelim == NULL)
1189                                 continue;
1190                         *pdelim = '\0';
1191 
1192                         do {
1193                                 if (nvlist_lookup_uint64(cnt_track, nm,
1194                                     &val) == 0) {
1195                                         /* update existing entry */
1196                                         fnvlist_add_uint64(cnt_track, nm,
1197                                             val + 1);
1198                                 } else {
1199                                         /* add to list */
1200                                         fnvlist_add_uint64(cnt_track, nm, 1);
1201                                 }
1202 
1203                                 pdelim = strrchr(nm, '/');
1204                                 if (pdelim != NULL)
1205                                         *pdelim = '\0';
1206                         } while (pdelim != NULL);
1207                 }
1208 
1209                 /* Check aggregated counts at each level */
1210                 for (pair = nvlist_next_nvpair(cnt_track, NULL);
1211                     pair != NULL; pair = nvlist_next_nvpair(cnt_track, pair)) {
1212                         int error = 0;
1213                         char *name;
1214                         uint64_t cnt = 0;
1215                         dsl_dataset_t *ds;
1216 
1217                         name = nvpair_name(pair);
1218                         cnt = fnvpair_value_uint64(pair);
1219                         ASSERT(cnt > 0);
1220 
1221                         error = dsl_dataset_hold(dp, name, FTAG, &ds);
1222                         if (error == 0) {
1223                                 error = dsl_fs_ss_limit_check(ds->ds_dir, cnt,
1224                                     ZFS_PROP_SNAPSHOT_LIMIT, NULL,
1225                                     ddsa->ddsa_cr);
1226                                 dsl_dataset_rele(ds, FTAG);
1227                         }
1228 
1229                         if (error != 0) {
1230                                 if (ddsa->ddsa_errors != NULL)
1231                                         fnvlist_add_int32(ddsa->ddsa_errors,
1232                                             name, error);
1233                                 rv = error;
1234                                 /* only report one error for this check */
1235                                 break;
1236                         }
1237                 }
1238                 nvlist_free(cnt_track);
1239         }
1240 
1241         for (pair = nvlist_next_nvpair(ddsa->ddsa_snaps, NULL);
1242             pair != NULL; pair = nvlist_next_nvpair(ddsa->ddsa_snaps, pair)) {
1243                 int error = 0;
1244                 dsl_dataset_t *ds;
1245                 char *name, *atp;
1246                 char dsname[MAXNAMELEN];
1247 
1248                 name = nvpair_name(pair);
1249                 if (strlen(name) >= MAXNAMELEN)
1250                         error = SET_ERROR(ENAMETOOLONG);
1251                 if (error == 0) {
1252                         atp = strchr(name, '@');
1253                         if (atp == NULL)
1254                                 error = SET_ERROR(EINVAL);
1255                         if (error == 0)
1256                                 (void) strlcpy(dsname, name, atp - name + 1);
1257                 }
1258                 if (error == 0)
1259                         error = dsl_dataset_hold(dp, dsname, FTAG, &ds);
1260                 if (error == 0) {
1261                         /* passing 0/NULL skips dsl_fs_ss_limit_check */
1262                         error = dsl_dataset_snapshot_check_impl(ds,
1263                             atp + 1, tx, B_FALSE, 0, NULL);
1264                         dsl_dataset_rele(ds, FTAG);
1265                 }
1266 
1267                 if (error != 0) {
1268                         if (ddsa->ddsa_errors != NULL) {
1269                                 fnvlist_add_int32(ddsa->ddsa_errors,
1270                                     name, error);
1271                         }
1272                         rv = error;
1273                 }
1274         }
1275 
1276         return (rv);
1277 }
1278 
1279 void
1280 dsl_dataset_snapshot_sync_impl(dsl_dataset_t *ds, const char *snapname,
1281     dmu_tx_t *tx)
1282 {
1283         static zil_header_t zero_zil;
1284 
1285         dsl_pool_t *dp = ds->ds_dir->dd_pool;
1286         dmu_buf_t *dbuf;
1287         dsl_dataset_phys_t *dsphys;
1288         uint64_t dsobj, crtxg;
1289         objset_t *mos = dp->dp_meta_objset;
1290         objset_t *os;
1291 
1292         ASSERT(RRW_WRITE_HELD(&dp->dp_config_rwlock));
1293 
1294         /*
1295          * If we are on an old pool, the zil must not be active, in which
1296          * case it will be zeroed.  Usually zil_suspend() accomplishes this.
1297          */
1298         ASSERT(spa_version(dmu_tx_pool(tx)->dp_spa) >= SPA_VERSION_FAST_SNAP ||
1299             dmu_objset_from_ds(ds, &os) != 0 ||
1300             bcmp(&os->os_phys->os_zil_header, &zero_zil,
1301             sizeof (zero_zil)) == 0);
1302 
1303         dsl_fs_ss_count_adjust(ds->ds_dir, 1, DD_FIELD_SNAPSHOT_COUNT, tx);
1304 
1305         /*
1306          * The origin's ds_creation_txg has to be < TXG_INITIAL
1307          */
1308         if (strcmp(snapname, ORIGIN_DIR_NAME) == 0)
1309                 crtxg = 1;
1310         else
1311                 crtxg = tx->tx_txg;
1312 
1313         dsobj = dmu_object_alloc(mos, DMU_OT_DSL_DATASET, 0,
1314             DMU_OT_DSL_DATASET, sizeof (dsl_dataset_phys_t), tx);
1315         VERIFY0(dmu_bonus_hold(mos, dsobj, FTAG, &dbuf));
1316         dmu_buf_will_dirty(dbuf, tx);
1317         dsphys = dbuf->db_data;
1318         bzero(dsphys, sizeof (dsl_dataset_phys_t));
1319         dsphys->ds_dir_obj = ds->ds_dir->dd_object;
1320         dsphys->ds_fsid_guid = unique_create();
1321         (void) random_get_pseudo_bytes((void*)&dsphys->ds_guid,
1322             sizeof (dsphys->ds_guid));
1323         dsphys->ds_prev_snap_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
1324         dsphys->ds_prev_snap_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;
1325         dsphys->ds_next_snap_obj = ds->ds_object;
1326         dsphys->ds_num_children = 1;
1327         dsphys->ds_creation_time = gethrestime_sec();
1328         dsphys->ds_creation_txg = crtxg;
1329         dsphys->ds_deadlist_obj = dsl_dataset_phys(ds)->ds_deadlist_obj;
1330         dsphys->ds_referenced_bytes = dsl_dataset_phys(ds)->ds_referenced_bytes;
1331         dsphys->ds_compressed_bytes = dsl_dataset_phys(ds)->ds_compressed_bytes;
1332         dsphys->ds_uncompressed_bytes =
1333             dsl_dataset_phys(ds)->ds_uncompressed_bytes;
1334         dsphys->ds_flags = dsl_dataset_phys(ds)->ds_flags;
1335         dsphys->ds_bp = dsl_dataset_phys(ds)->ds_bp;
1336         dmu_buf_rele(dbuf, FTAG);
1337 
1338         for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
1339                 if (ds->ds_feature_inuse[f])
1340                         dsl_dataset_activate_feature(dsobj, f, tx);
1341         }
1342 
1343         ASSERT3U(ds->ds_prev != 0, ==,
1344             dsl_dataset_phys(ds)->ds_prev_snap_obj != 0);
1345         if (ds->ds_prev) {
1346                 uint64_t next_clones_obj =
1347                     dsl_dataset_phys(ds->ds_prev)->ds_next_clones_obj;
1348                 ASSERT(dsl_dataset_phys(ds->ds_prev)->ds_next_snap_obj ==
1349                     ds->ds_object ||
1350                     dsl_dataset_phys(ds->ds_prev)->ds_num_children > 1);
1351                 if (dsl_dataset_phys(ds->ds_prev)->ds_next_snap_obj ==
1352                     ds->ds_object) {
1353                         dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
1354                         ASSERT3U(dsl_dataset_phys(ds)->ds_prev_snap_txg, ==,
1355                             dsl_dataset_phys(ds->ds_prev)->ds_creation_txg);
1356                         dsl_dataset_phys(ds->ds_prev)->ds_next_snap_obj = dsobj;
1357                 } else if (next_clones_obj != 0) {
1358                         dsl_dataset_remove_from_next_clones(ds->ds_prev,
1359                             dsphys->ds_next_snap_obj, tx);
1360                         VERIFY0(zap_add_int(mos,
1361                             next_clones_obj, dsobj, tx));
1362                 }
1363         }
1364 
1365         /*
1366          * If we have a reference-reservation on this dataset, we will
1367          * need to increase the amount of refreservation being charged
1368          * since our unique space is going to zero.
1369          */
1370         if (ds->ds_reserved) {
1371                 int64_t delta;
1372                 ASSERT(DS_UNIQUE_IS_ACCURATE(ds));
1373                 delta = MIN(dsl_dataset_phys(ds)->ds_unique_bytes,
1374                     ds->ds_reserved);
1375                 dsl_dir_diduse_space(ds->ds_dir, DD_USED_REFRSRV,
1376                     delta, 0, 0, tx);
1377         }
1378 
1379         dmu_buf_will_dirty(ds->ds_dbuf, tx);
1380         dsl_dataset_phys(ds)->ds_deadlist_obj =
1381             dsl_deadlist_clone(&ds->ds_deadlist, UINT64_MAX,
1382             dsl_dataset_phys(ds)->ds_prev_snap_obj, tx);
1383         dsl_deadlist_close(&ds->ds_deadlist);
1384         dsl_deadlist_open(&ds->ds_deadlist, mos,
1385             dsl_dataset_phys(ds)->ds_deadlist_obj);
1386         dsl_deadlist_add_key(&ds->ds_deadlist,
1387             dsl_dataset_phys(ds)->ds_prev_snap_txg, tx);
1388 
1389         ASSERT3U(dsl_dataset_phys(ds)->ds_prev_snap_txg, <, tx->tx_txg);
1390         dsl_dataset_phys(ds)->ds_prev_snap_obj = dsobj;
1391         dsl_dataset_phys(ds)->ds_prev_snap_txg = crtxg;
1392         dsl_dataset_phys(ds)->ds_unique_bytes = 0;
1393         if (spa_version(dp->dp_spa) >= SPA_VERSION_UNIQUE_ACCURATE)
1394                 dsl_dataset_phys(ds)->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
1395 
1396         VERIFY0(zap_add(mos, dsl_dataset_phys(ds)->ds_snapnames_zapobj,
1397             snapname, 8, 1, &dsobj, tx));
1398 
1399         if (ds->ds_prev)
1400                 dsl_dataset_rele(ds->ds_prev, ds);
1401         VERIFY0(dsl_dataset_hold_obj(dp,
1402             dsl_dataset_phys(ds)->ds_prev_snap_obj, ds, &ds->ds_prev));
1403 
1404         dsl_scan_ds_snapshotted(ds, tx);
1405 
1406         dsl_dir_snap_cmtime_update(ds->ds_dir);
1407 
1408         spa_history_log_internal_ds(ds->ds_prev, "snapshot", tx, "");
1409 }
1410 
1411 static void
1412 dsl_dataset_snapshot_sync(void *arg, dmu_tx_t *tx)
1413 {
1414         dsl_dataset_snapshot_arg_t *ddsa = arg;
1415         dsl_pool_t *dp = dmu_tx_pool(tx);
1416         nvpair_t *pair;
1417 
1418         for (pair = nvlist_next_nvpair(ddsa->ddsa_snaps, NULL);
1419             pair != NULL; pair = nvlist_next_nvpair(ddsa->ddsa_snaps, pair)) {
1420                 dsl_dataset_t *ds;
1421                 char *name, *atp;
1422                 char dsname[MAXNAMELEN];
1423 
1424                 name = nvpair_name(pair);
1425                 atp = strchr(name, '@');
1426                 (void) strlcpy(dsname, name, atp - name + 1);
1427                 VERIFY0(dsl_dataset_hold(dp, dsname, FTAG, &ds));
1428 
1429                 dsl_dataset_snapshot_sync_impl(ds, atp + 1, tx);
1430                 if (ddsa->ddsa_props != NULL) {
1431                         dsl_props_set_sync_impl(ds->ds_prev,
1432                             ZPROP_SRC_LOCAL, ddsa->ddsa_props, tx);
1433                 }
1434                 dsl_dataset_rele(ds, FTAG);
1435         }
1436 }
1437 
1438 /*
1439  * The snapshots must all be in the same pool.
1440  * All-or-nothing: if there are any failures, nothing will be modified.
1441  */
1442 int
1443 dsl_dataset_snapshot(nvlist_t *snaps, nvlist_t *props, nvlist_t *errors)
1444 {
1445         dsl_dataset_snapshot_arg_t ddsa;
1446         nvpair_t *pair;
1447         boolean_t needsuspend;
1448         int error;
1449         spa_t *spa;
1450         char *firstname;
1451         nvlist_t *suspended = NULL;
1452 
1453         pair = nvlist_next_nvpair(snaps, NULL);
1454         if (pair == NULL)
1455                 return (0);
1456         firstname = nvpair_name(pair);
1457 
1458         error = spa_open(firstname, &spa, FTAG);
1459         if (error != 0)
1460                 return (error);
1461         needsuspend = (spa_version(spa) < SPA_VERSION_FAST_SNAP);
1462         spa_close(spa, FTAG);
1463 
1464         if (needsuspend) {
1465                 suspended = fnvlist_alloc();
1466                 for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
1467                     pair = nvlist_next_nvpair(snaps, pair)) {
1468                         char fsname[MAXNAMELEN];
1469                         char *snapname = nvpair_name(pair);
1470                         char *atp;
1471                         void *cookie;
1472 
1473                         atp = strchr(snapname, '@');
1474                         if (atp == NULL) {
1475                                 error = SET_ERROR(EINVAL);
1476                                 break;
1477                         }
1478                         (void) strlcpy(fsname, snapname, atp - snapname + 1);
1479 
1480                         error = zil_suspend(fsname, &cookie);
1481                         if (error != 0)
1482                                 break;
1483                         fnvlist_add_uint64(suspended, fsname,
1484                             (uintptr_t)cookie);
1485                 }
1486         }
1487 
1488         ddsa.ddsa_snaps = snaps;
1489         ddsa.ddsa_props = props;
1490         ddsa.ddsa_errors = errors;
1491         ddsa.ddsa_cr = CRED();
1492 
1493         if (error == 0) {
1494                 error = dsl_sync_task(firstname, dsl_dataset_snapshot_check,
1495                     dsl_dataset_snapshot_sync, &ddsa,
1496                     fnvlist_num_pairs(snaps) * 3, ZFS_SPACE_CHECK_NORMAL);
1497         }
1498 
1499         if (suspended != NULL) {
1500                 for (pair = nvlist_next_nvpair(suspended, NULL); pair != NULL;
1501                     pair = nvlist_next_nvpair(suspended, pair)) {
1502                         zil_resume((void *)(uintptr_t)
1503                             fnvpair_value_uint64(pair));
1504                 }
1505                 fnvlist_free(suspended);
1506         }
1507 
1508         return (error);
1509 }
1510 
1511 typedef struct dsl_dataset_snapshot_tmp_arg {
1512         const char *ddsta_fsname;
1513         const char *ddsta_snapname;
1514         minor_t ddsta_cleanup_minor;
1515         const char *ddsta_htag;
1516 } dsl_dataset_snapshot_tmp_arg_t;
1517 
1518 static int
1519 dsl_dataset_snapshot_tmp_check(void *arg, dmu_tx_t *tx)
1520 {
1521         dsl_dataset_snapshot_tmp_arg_t *ddsta = arg;
1522         dsl_pool_t *dp = dmu_tx_pool(tx);
1523         dsl_dataset_t *ds;
1524         int error;
1525 
1526         error = dsl_dataset_hold(dp, ddsta->ddsta_fsname, FTAG, &ds);
1527         if (error != 0)
1528                 return (error);
1529 
1530         /* NULL cred means no limit check for tmp snapshot */
1531         error = dsl_dataset_snapshot_check_impl(ds, ddsta->ddsta_snapname,
1532             tx, B_FALSE, 0, NULL);
1533         if (error != 0) {
1534                 dsl_dataset_rele(ds, FTAG);
1535                 return (error);
1536         }
1537 
1538         if (spa_version(dp->dp_spa) < SPA_VERSION_USERREFS) {
1539                 dsl_dataset_rele(ds, FTAG);
1540                 return (SET_ERROR(ENOTSUP));
1541         }
1542         error = dsl_dataset_user_hold_check_one(NULL, ddsta->ddsta_htag,
1543             B_TRUE, tx);
1544         if (error != 0) {
1545                 dsl_dataset_rele(ds, FTAG);
1546                 return (error);
1547         }
1548 
1549         dsl_dataset_rele(ds, FTAG);
1550         return (0);
1551 }
1552 
1553 static void
1554 dsl_dataset_snapshot_tmp_sync(void *arg, dmu_tx_t *tx)
1555 {
1556         dsl_dataset_snapshot_tmp_arg_t *ddsta = arg;
1557         dsl_pool_t *dp = dmu_tx_pool(tx);
1558         dsl_dataset_t *ds;
1559 
1560         VERIFY0(dsl_dataset_hold(dp, ddsta->ddsta_fsname, FTAG, &ds));
1561 
1562         dsl_dataset_snapshot_sync_impl(ds, ddsta->ddsta_snapname, tx);
1563         dsl_dataset_user_hold_sync_one(ds->ds_prev, ddsta->ddsta_htag,
1564             ddsta->ddsta_cleanup_minor, gethrestime_sec(), tx);
1565         dsl_destroy_snapshot_sync_impl(ds->ds_prev, B_TRUE, tx);
1566 
1567         dsl_dataset_rele(ds, FTAG);
1568 }
1569 
1570 int
1571 dsl_dataset_snapshot_tmp(const char *fsname, const char *snapname,
1572     minor_t cleanup_minor, const char *htag)
1573 {
1574         dsl_dataset_snapshot_tmp_arg_t ddsta;
1575         int error;
1576         spa_t *spa;
1577         boolean_t needsuspend;
1578         void *cookie;
1579 
1580         ddsta.ddsta_fsname = fsname;
1581         ddsta.ddsta_snapname = snapname;
1582         ddsta.ddsta_cleanup_minor = cleanup_minor;
1583         ddsta.ddsta_htag = htag;
1584 
1585         error = spa_open(fsname, &spa, FTAG);
1586         if (error != 0)
1587                 return (error);
1588         needsuspend = (spa_version(spa) < SPA_VERSION_FAST_SNAP);
1589         spa_close(spa, FTAG);
1590 
1591         if (needsuspend) {
1592                 error = zil_suspend(fsname, &cookie);
1593                 if (error != 0)
1594                         return (error);
1595         }
1596 
1597         error = dsl_sync_task(fsname, dsl_dataset_snapshot_tmp_check,
1598             dsl_dataset_snapshot_tmp_sync, &ddsta, 3, ZFS_SPACE_CHECK_RESERVED);
1599 
1600         if (needsuspend)
1601                 zil_resume(cookie);
1602         return (error);
1603 }
1604 
1605 
1606 void
1607 dsl_dataset_sync(dsl_dataset_t *ds, zio_t *zio, dmu_tx_t *tx)
1608 {
1609         ASSERT(dmu_tx_is_syncing(tx));
1610         ASSERT(ds->ds_objset != NULL);
1611         ASSERT(dsl_dataset_phys(ds)->ds_next_snap_obj == 0);
1612 
1613         /*
1614          * in case we had to change ds_fsid_guid when we opened it,
1615          * sync it out now.
1616          */
1617         dmu_buf_will_dirty(ds->ds_dbuf, tx);
1618         dsl_dataset_phys(ds)->ds_fsid_guid = ds->ds_fsid_guid;
1619 
1620         if (ds->ds_resume_bytes[tx->tx_txg & TXG_MASK] != 0) {
1621                 VERIFY0(zap_update(tx->tx_pool->dp_meta_objset,
1622                     ds->ds_object, DS_FIELD_RESUME_OBJECT, 8, 1,
1623                     &ds->ds_resume_object[tx->tx_txg & TXG_MASK], tx));
1624                 VERIFY0(zap_update(tx->tx_pool->dp_meta_objset,
1625                     ds->ds_object, DS_FIELD_RESUME_OFFSET, 8, 1,
1626                     &ds->ds_resume_offset[tx->tx_txg & TXG_MASK], tx));
1627                 VERIFY0(zap_update(tx->tx_pool->dp_meta_objset,
1628                     ds->ds_object, DS_FIELD_RESUME_BYTES, 8, 1,
1629                     &ds->ds_resume_bytes[tx->tx_txg & TXG_MASK], tx));
1630                 ds->ds_resume_object[tx->tx_txg & TXG_MASK] = 0;
1631                 ds->ds_resume_offset[tx->tx_txg & TXG_MASK] = 0;
1632                 ds->ds_resume_bytes[tx->tx_txg & TXG_MASK] = 0;
1633         }
1634 
1635         dmu_objset_sync(ds->ds_objset, zio, tx);
1636 
1637         for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
1638                 if (ds->ds_feature_activation_needed[f]) {
1639                         if (ds->ds_feature_inuse[f])
1640                                 continue;
1641                         dsl_dataset_activate_feature(ds->ds_object, f, tx);
1642                         ds->ds_feature_inuse[f] = B_TRUE;
1643                 }
1644         }
1645 }
1646 
1647 static void
1648 get_clones_stat(dsl_dataset_t *ds, nvlist_t *nv)
1649 {
1650         uint64_t count = 0;
1651         objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
1652         zap_cursor_t zc;
1653         zap_attribute_t za;
1654         nvlist_t *propval = fnvlist_alloc();
1655         nvlist_t *val = fnvlist_alloc();
1656 
1657         ASSERT(dsl_pool_config_held(ds->ds_dir->dd_pool));
1658 
1659         /*
1660          * There may be missing entries in ds_next_clones_obj
1661          * due to a bug in a previous version of the code.
1662          * Only trust it if it has the right number of entries.
1663          */
1664         if (dsl_dataset_phys(ds)->ds_next_clones_obj != 0) {
1665                 VERIFY0(zap_count(mos, dsl_dataset_phys(ds)->ds_next_clones_obj,
1666                     &count));
1667         }
1668         if (count != dsl_dataset_phys(ds)->ds_num_children - 1)
1669                 goto fail;
1670         for (zap_cursor_init(&zc, mos,
1671             dsl_dataset_phys(ds)->ds_next_clones_obj);
1672             zap_cursor_retrieve(&zc, &za) == 0;
1673             zap_cursor_advance(&zc)) {
1674                 dsl_dataset_t *clone;
1675                 char buf[ZFS_MAXNAMELEN];
1676                 VERIFY0(dsl_dataset_hold_obj(ds->ds_dir->dd_pool,
1677                     za.za_first_integer, FTAG, &clone));
1678                 dsl_dir_name(clone->ds_dir, buf);
1679                 fnvlist_add_boolean(val, buf);
1680                 dsl_dataset_rele(clone, FTAG);
1681         }
1682         zap_cursor_fini(&zc);
1683         fnvlist_add_nvlist(propval, ZPROP_VALUE, val);
1684         fnvlist_add_nvlist(nv, zfs_prop_to_name(ZFS_PROP_CLONES), propval);
1685 fail:
1686         nvlist_free(val);
1687         nvlist_free(propval);
1688 }
1689 
1690 static void
1691 get_receive_resume_stats(dsl_dataset_t *ds, nvlist_t *nv)
1692 {
1693         dsl_pool_t *dp = ds->ds_dir->dd_pool;
1694 
1695         if (dsl_dataset_has_resume_receive_state(ds)) {
1696                 char *str;
1697                 void *packed;
1698                 uint8_t *compressed;
1699                 uint64_t val;
1700                 nvlist_t *token_nv = fnvlist_alloc();
1701                 size_t packed_size, compressed_size;
1702 
1703                 if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
1704                     DS_FIELD_RESUME_FROMGUID, sizeof (val), 1, &val) == 0) {
1705                         fnvlist_add_uint64(token_nv, "fromguid", val);
1706                 }
1707                 if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
1708                     DS_FIELD_RESUME_OBJECT, sizeof (val), 1, &val) == 0) {
1709                         fnvlist_add_uint64(token_nv, "object", val);
1710                 }
1711                 if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
1712                     DS_FIELD_RESUME_OFFSET, sizeof (val), 1, &val) == 0) {
1713                         fnvlist_add_uint64(token_nv, "offset", val);
1714                 }
1715                 if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
1716                     DS_FIELD_RESUME_BYTES, sizeof (val), 1, &val) == 0) {
1717                         fnvlist_add_uint64(token_nv, "bytes", val);
1718                 }
1719                 if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
1720                     DS_FIELD_RESUME_TOGUID, sizeof (val), 1, &val) == 0) {
1721                         fnvlist_add_uint64(token_nv, "toguid", val);
1722                 }
1723                 char buf[256];
1724                 if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
1725                     DS_FIELD_RESUME_TONAME, 1, sizeof (buf), buf) == 0) {
1726                         fnvlist_add_string(token_nv, "toname", buf);
1727                 }
1728                 if (zap_contains(dp->dp_meta_objset, ds->ds_object,
1729                     DS_FIELD_RESUME_EMBEDOK) == 0) {
1730                         fnvlist_add_boolean(token_nv, "embedok");
1731                 }
1732                 packed = fnvlist_pack(token_nv, &packed_size);
1733                 fnvlist_free(token_nv);
1734                 compressed = kmem_alloc(packed_size, KM_SLEEP);
1735 
1736                 compressed_size = gzip_compress(packed, compressed,
1737                     packed_size, packed_size, 6);
1738 
1739                 zio_cksum_t cksum;
1740                 fletcher_4_native(compressed, compressed_size, NULL, &cksum);
1741 
1742                 str = kmem_alloc(compressed_size * 2 + 1, KM_SLEEP);
1743                 for (int i = 0; i < compressed_size; i++) {
1744                         (void) sprintf(str + i * 2, "%02x", compressed[i]);
1745                 }
1746                 str[compressed_size * 2] = '\0';
1747                 char *propval = kmem_asprintf("%u-%llx-%llx-%s",
1748                     ZFS_SEND_RESUME_TOKEN_VERSION,
1749                     (longlong_t)cksum.zc_word[0],
1750                     (longlong_t)packed_size, str);
1751                 dsl_prop_nvlist_add_string(nv,
1752                     ZFS_PROP_RECEIVE_RESUME_TOKEN, propval);
1753                 kmem_free(packed, packed_size);
1754                 kmem_free(str, compressed_size * 2 + 1);
1755                 kmem_free(compressed, packed_size);
1756                 strfree(propval);
1757         }
1758 }
1759 
1760 void
1761 dsl_dataset_stats(dsl_dataset_t *ds, nvlist_t *nv)
1762 {
1763         dsl_pool_t *dp = ds->ds_dir->dd_pool;
1764         uint64_t refd, avail, uobjs, aobjs, ratio;
1765 
1766         ASSERT(dsl_pool_config_held(dp));
1767 
1768         ratio = dsl_dataset_phys(ds)->ds_compressed_bytes == 0 ? 100 :
1769             (dsl_dataset_phys(ds)->ds_uncompressed_bytes * 100 /
1770             dsl_dataset_phys(ds)->ds_compressed_bytes);
1771 
1772         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFRATIO, ratio);
1773         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_LOGICALREFERENCED,
1774             dsl_dataset_phys(ds)->ds_uncompressed_bytes);
1775 
1776         if (ds->ds_is_snapshot) {
1777                 dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_COMPRESSRATIO, ratio);
1778                 dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USED,
1779                     dsl_dataset_phys(ds)->ds_unique_bytes);
1780                 get_clones_stat(ds, nv);
1781         } else {
1782                 if (ds->ds_prev != NULL && ds->ds_prev != dp->dp_origin_snap) {
1783                         char buf[MAXNAMELEN];
1784                         dsl_dataset_name(ds->ds_prev, buf);
1785                         dsl_prop_nvlist_add_string(nv, ZFS_PROP_PREV_SNAP, buf);
1786                 }
1787 
1788                 dsl_dir_stats(ds->ds_dir, nv);
1789         }
1790 
1791         dsl_dataset_space(ds, &refd, &avail, &uobjs, &aobjs);
1792         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_AVAILABLE, avail);
1793         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFERENCED, refd);
1794 
1795         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_CREATION,
1796             dsl_dataset_phys(ds)->ds_creation_time);
1797         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_CREATETXG,
1798             dsl_dataset_phys(ds)->ds_creation_txg);
1799         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFQUOTA,
1800             ds->ds_quota);
1801         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFRESERVATION,
1802             ds->ds_reserved);
1803         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_GUID,
1804             dsl_dataset_phys(ds)->ds_guid);
1805         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_UNIQUE,
1806             dsl_dataset_phys(ds)->ds_unique_bytes);
1807         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_OBJSETID,
1808             ds->ds_object);
1809         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USERREFS,
1810             ds->ds_userrefs);
1811         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_DEFER_DESTROY,
1812             DS_IS_DEFER_DESTROY(ds) ? 1 : 0);
1813 
1814         if (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {
1815                 uint64_t written, comp, uncomp;
1816                 dsl_pool_t *dp = ds->ds_dir->dd_pool;
1817                 dsl_dataset_t *prev;
1818 
1819                 int err = dsl_dataset_hold_obj(dp,
1820                     dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);
1821                 if (err == 0) {
1822                         err = dsl_dataset_space_written(prev, ds, &written,
1823                             &comp, &uncomp);
1824                         dsl_dataset_rele(prev, FTAG);
1825                         if (err == 0) {
1826                                 dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_WRITTEN,
1827                                     written);
1828                         }
1829                 }
1830         }
1831 
1832         if (!dsl_dataset_is_snapshot(ds)) {
1833                 /*
1834                  * A failed "newfs" (e.g. full) resumable receive leaves
1835                  * the stats set on this dataset.  Check here for the prop.
1836                  */
1837                 get_receive_resume_stats(ds, nv);
1838 
1839                 /*
1840                  * A failed incremental resumable receive leaves the
1841                  * stats set on our child named "%recv".  Check the child
1842                  * for the prop.
1843                  */
1844                 char recvname[ZFS_MAXNAMELEN];
1845                 dsl_dataset_t *recv_ds;
1846                 dsl_dataset_name(ds, recvname);
1847                 (void) strcat(recvname, "/");
1848                 (void) strcat(recvname, recv_clone_name);
1849                 if (dsl_dataset_hold(dp, recvname, FTAG, &recv_ds) == 0) {
1850                         get_receive_resume_stats(recv_ds, nv);
1851                         dsl_dataset_rele(recv_ds, FTAG);
1852                 }
1853         }
1854 }
1855 
1856 void
1857 dsl_dataset_fast_stat(dsl_dataset_t *ds, dmu_objset_stats_t *stat)
1858 {
1859         dsl_pool_t *dp = ds->ds_dir->dd_pool;
1860         ASSERT(dsl_pool_config_held(dp));
1861 
1862         stat->dds_creation_txg = dsl_dataset_phys(ds)->ds_creation_txg;
1863         stat->dds_inconsistent =
1864             dsl_dataset_phys(ds)->ds_flags & DS_FLAG_INCONSISTENT;
1865         stat->dds_guid = dsl_dataset_phys(ds)->ds_guid;
1866         stat->dds_origin[0] = '\0';
1867         if (ds->ds_is_snapshot) {
1868                 stat->dds_is_snapshot = B_TRUE;
1869                 stat->dds_num_clones =
1870                     dsl_dataset_phys(ds)->ds_num_children - 1;
1871         } else {
1872                 stat->dds_is_snapshot = B_FALSE;
1873                 stat->dds_num_clones = 0;
1874 
1875                 if (dsl_dir_is_clone(ds->ds_dir)) {
1876                         dsl_dataset_t *ods;
1877 
1878                         VERIFY0(dsl_dataset_hold_obj(dp,
1879                             dsl_dir_phys(ds->ds_dir)->dd_origin_obj,
1880                             FTAG, &ods));
1881                         dsl_dataset_name(ods, stat->dds_origin);
1882                         dsl_dataset_rele(ods, FTAG);
1883                 }
1884         }
1885 }
1886 
1887 uint64_t
1888 dsl_dataset_fsid_guid(dsl_dataset_t *ds)
1889 {
1890         return (ds->ds_fsid_guid);
1891 }
1892 
1893 void
1894 dsl_dataset_space(dsl_dataset_t *ds,
1895     uint64_t *refdbytesp, uint64_t *availbytesp,
1896     uint64_t *usedobjsp, uint64_t *availobjsp)
1897 {
1898         *refdbytesp = dsl_dataset_phys(ds)->ds_referenced_bytes;
1899         *availbytesp = dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE);
1900         if (ds->ds_reserved > dsl_dataset_phys(ds)->ds_unique_bytes)
1901                 *availbytesp +=
1902                     ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes;
1903         if (ds->ds_quota != 0) {
1904                 /*
1905                  * Adjust available bytes according to refquota
1906                  */
1907                 if (*refdbytesp < ds->ds_quota)
1908                         *availbytesp = MIN(*availbytesp,
1909                             ds->ds_quota - *refdbytesp);
1910                 else
1911                         *availbytesp = 0;
1912         }
1913         *usedobjsp = BP_GET_FILL(&dsl_dataset_phys(ds)->ds_bp);
1914         *availobjsp = DN_MAX_OBJECT - *usedobjsp;
1915 }
1916 
1917 boolean_t
1918 dsl_dataset_modified_since_snap(dsl_dataset_t *ds, dsl_dataset_t *snap)
1919 {
1920         dsl_pool_t *dp = ds->ds_dir->dd_pool;
1921 
1922         ASSERT(dsl_pool_config_held(dp));
1923         if (snap == NULL)
1924                 return (B_FALSE);
1925         if (dsl_dataset_phys(ds)->ds_bp.blk_birth >
1926             dsl_dataset_phys(snap)->ds_creation_txg) {
1927                 objset_t *os, *os_snap;
1928                 /*
1929                  * It may be that only the ZIL differs, because it was
1930                  * reset in the head.  Don't count that as being
1931                  * modified.
1932                  */
1933                 if (dmu_objset_from_ds(ds, &os) != 0)
1934                         return (B_TRUE);
1935                 if (dmu_objset_from_ds(snap, &os_snap) != 0)
1936                         return (B_TRUE);
1937                 return (bcmp(&os->os_phys->os_meta_dnode,
1938                     &os_snap->os_phys->os_meta_dnode,
1939                     sizeof (os->os_phys->os_meta_dnode)) != 0);
1940         }
1941         return (B_FALSE);
1942 }
1943 
1944 typedef struct dsl_dataset_rename_snapshot_arg {
1945         const char *ddrsa_fsname;
1946         const char *ddrsa_oldsnapname;
1947         const char *ddrsa_newsnapname;
1948         boolean_t ddrsa_recursive;
1949         dmu_tx_t *ddrsa_tx;
1950 } dsl_dataset_rename_snapshot_arg_t;
1951 
1952 /* ARGSUSED */
1953 static int
1954 dsl_dataset_rename_snapshot_check_impl(dsl_pool_t *dp,
1955     dsl_dataset_t *hds, void *arg)
1956 {
1957         dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
1958         int error;
1959         uint64_t val;
1960 
1961         error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_oldsnapname, &val);
1962         if (error != 0) {
1963                 /* ignore nonexistent snapshots */
1964                 return (error == ENOENT ? 0 : error);
1965         }
1966 
1967         /* new name should not exist */
1968         error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_newsnapname, &val);
1969         if (error == 0)
1970                 error = SET_ERROR(EEXIST);
1971         else if (error == ENOENT)
1972                 error = 0;
1973 
1974         /* dataset name + 1 for the "@" + the new snapshot name must fit */
1975         if (dsl_dir_namelen(hds->ds_dir) + 1 +
1976             strlen(ddrsa->ddrsa_newsnapname) >= MAXNAMELEN)
1977                 error = SET_ERROR(ENAMETOOLONG);
1978 
1979         return (error);
1980 }
1981 
1982 static int
1983 dsl_dataset_rename_snapshot_check(void *arg, dmu_tx_t *tx)
1984 {
1985         dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
1986         dsl_pool_t *dp = dmu_tx_pool(tx);
1987         dsl_dataset_t *hds;
1988         int error;
1989 
1990         error = dsl_dataset_hold(dp, ddrsa->ddrsa_fsname, FTAG, &hds);
1991         if (error != 0)
1992                 return (error);
1993 
1994         if (ddrsa->ddrsa_recursive) {
1995                 error = dmu_objset_find_dp(dp, hds->ds_dir->dd_object,
1996                     dsl_dataset_rename_snapshot_check_impl, ddrsa,
1997                     DS_FIND_CHILDREN);
1998         } else {
1999                 error = dsl_dataset_rename_snapshot_check_impl(dp, hds, ddrsa);
2000         }
2001         dsl_dataset_rele(hds, FTAG);
2002         return (error);
2003 }
2004 
2005 static int
2006 dsl_dataset_rename_snapshot_sync_impl(dsl_pool_t *dp,
2007     dsl_dataset_t *hds, void *arg)
2008 {
2009         dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
2010         dsl_dataset_t *ds;
2011         uint64_t val;
2012         dmu_tx_t *tx = ddrsa->ddrsa_tx;
2013         int error;
2014 
2015         error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_oldsnapname, &val);
2016         ASSERT(error == 0 || error == ENOENT);
2017         if (error == ENOENT) {
2018                 /* ignore nonexistent snapshots */
2019                 return (0);
2020         }
2021 
2022         VERIFY0(dsl_dataset_hold_obj(dp, val, FTAG, &ds));
2023 
2024         /* log before we change the name */
2025         spa_history_log_internal_ds(ds, "rename", tx,
2026             "-> @%s", ddrsa->ddrsa_newsnapname);
2027 
2028         VERIFY0(dsl_dataset_snap_remove(hds, ddrsa->ddrsa_oldsnapname, tx,
2029             B_FALSE));
2030         mutex_enter(&ds->ds_lock);
2031         (void) strcpy(ds->ds_snapname, ddrsa->ddrsa_newsnapname);
2032         mutex_exit(&ds->ds_lock);
2033         VERIFY0(zap_add(dp->dp_meta_objset,
2034             dsl_dataset_phys(hds)->ds_snapnames_zapobj,
2035             ds->ds_snapname, 8, 1, &ds->ds_object, tx));
2036 
2037         dsl_dataset_rele(ds, FTAG);
2038         return (0);
2039 }
2040 
2041 static void
2042 dsl_dataset_rename_snapshot_sync(void *arg, dmu_tx_t *tx)
2043 {
2044         dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
2045         dsl_pool_t *dp = dmu_tx_pool(tx);
2046         dsl_dataset_t *hds;
2047 
2048         VERIFY0(dsl_dataset_hold(dp, ddrsa->ddrsa_fsname, FTAG, &hds));
2049         ddrsa->ddrsa_tx = tx;
2050         if (ddrsa->ddrsa_recursive) {
2051                 VERIFY0(dmu_objset_find_dp(dp, hds->ds_dir->dd_object,
2052                     dsl_dataset_rename_snapshot_sync_impl, ddrsa,
2053                     DS_FIND_CHILDREN));
2054         } else {
2055                 VERIFY0(dsl_dataset_rename_snapshot_sync_impl(dp, hds, ddrsa));
2056         }
2057         dsl_dataset_rele(hds, FTAG);
2058 }
2059 
2060 int
2061 dsl_dataset_rename_snapshot(const char *fsname,
2062     const char *oldsnapname, const char *newsnapname, boolean_t recursive)
2063 {
2064         dsl_dataset_rename_snapshot_arg_t ddrsa;
2065 
2066         ddrsa.ddrsa_fsname = fsname;
2067         ddrsa.ddrsa_oldsnapname = oldsnapname;
2068         ddrsa.ddrsa_newsnapname = newsnapname;
2069         ddrsa.ddrsa_recursive = recursive;
2070 
2071         return (dsl_sync_task(fsname, dsl_dataset_rename_snapshot_check,
2072             dsl_dataset_rename_snapshot_sync, &ddrsa,
2073             1, ZFS_SPACE_CHECK_RESERVED));
2074 }
2075 
2076 /*
2077  * If we're doing an ownership handoff, we need to make sure that there is
2078  * only one long hold on the dataset.  We're not allowed to change anything here
2079  * so we don't permanently release the long hold or regular hold here.  We want
2080  * to do this only when syncing to avoid the dataset unexpectedly going away
2081  * when we release the long hold.
2082  */
2083 static int
2084 dsl_dataset_handoff_check(dsl_dataset_t *ds, void *owner, dmu_tx_t *tx)
2085 {
2086         boolean_t held;
2087 
2088         if (!dmu_tx_is_syncing(tx))
2089                 return (0);
2090 
2091         if (owner != NULL) {
2092                 VERIFY3P(ds->ds_owner, ==, owner);
2093                 dsl_dataset_long_rele(ds, owner);
2094         }
2095 
2096         held = dsl_dataset_long_held(ds);
2097 
2098         if (owner != NULL)
2099                 dsl_dataset_long_hold(ds, owner);
2100 
2101         if (held)
2102                 return (SET_ERROR(EBUSY));
2103 
2104         return (0);
2105 }
2106 
2107 typedef struct dsl_dataset_rollback_arg {
2108         const char *ddra_fsname;
2109         void *ddra_owner;
2110         nvlist_t *ddra_result;
2111 } dsl_dataset_rollback_arg_t;
2112 
2113 static int
2114 dsl_dataset_rollback_check(void *arg, dmu_tx_t *tx)
2115 {
2116         dsl_dataset_rollback_arg_t *ddra = arg;
2117         dsl_pool_t *dp = dmu_tx_pool(tx);
2118         dsl_dataset_t *ds;
2119         int64_t unused_refres_delta;
2120         int error;
2121 
2122         error = dsl_dataset_hold(dp, ddra->ddra_fsname, FTAG, &ds);
2123         if (error != 0)
2124                 return (error);
2125 
2126         /* must not be a snapshot */
2127         if (ds->ds_is_snapshot) {
2128                 dsl_dataset_rele(ds, FTAG);
2129                 return (SET_ERROR(EINVAL));
2130         }
2131 
2132         /* must have a most recent snapshot */
2133         if (dsl_dataset_phys(ds)->ds_prev_snap_txg < TXG_INITIAL) {
2134                 dsl_dataset_rele(ds, FTAG);
2135                 return (SET_ERROR(EINVAL));
2136         }
2137 
2138         /* must not have any bookmarks after the most recent snapshot */
2139         nvlist_t *proprequest = fnvlist_alloc();
2140         fnvlist_add_boolean(proprequest, zfs_prop_to_name(ZFS_PROP_CREATETXG));
2141         nvlist_t *bookmarks = fnvlist_alloc();
2142         error = dsl_get_bookmarks_impl(ds, proprequest, bookmarks);
2143         fnvlist_free(proprequest);
2144         if (error != 0)
2145                 return (error);
2146         for (nvpair_t *pair = nvlist_next_nvpair(bookmarks, NULL);
2147             pair != NULL; pair = nvlist_next_nvpair(bookmarks, pair)) {
2148                 nvlist_t *valuenv =
2149                     fnvlist_lookup_nvlist(fnvpair_value_nvlist(pair),
2150                     zfs_prop_to_name(ZFS_PROP_CREATETXG));
2151                 uint64_t createtxg = fnvlist_lookup_uint64(valuenv, "value");
2152                 if (createtxg > dsl_dataset_phys(ds)->ds_prev_snap_txg) {
2153                         fnvlist_free(bookmarks);
2154                         dsl_dataset_rele(ds, FTAG);
2155                         return (SET_ERROR(EEXIST));
2156                 }
2157         }
2158         fnvlist_free(bookmarks);
2159 
2160         error = dsl_dataset_handoff_check(ds, ddra->ddra_owner, tx);
2161         if (error != 0) {
2162                 dsl_dataset_rele(ds, FTAG);
2163                 return (error);
2164         }
2165 
2166         /*
2167          * Check if the snap we are rolling back to uses more than
2168          * the refquota.
2169          */
2170         if (ds->ds_quota != 0 &&
2171             dsl_dataset_phys(ds->ds_prev)->ds_referenced_bytes > ds->ds_quota) {
2172                 dsl_dataset_rele(ds, FTAG);
2173                 return (SET_ERROR(EDQUOT));
2174         }
2175 
2176         /*
2177          * When we do the clone swap, we will temporarily use more space
2178          * due to the refreservation (the head will no longer have any
2179          * unique space, so the entire amount of the refreservation will need
2180          * to be free).  We will immediately destroy the clone, freeing
2181          * this space, but the freeing happens over many txg's.
2182          */
2183         unused_refres_delta = (int64_t)MIN(ds->ds_reserved,
2184             dsl_dataset_phys(ds)->ds_unique_bytes);
2185 
2186         if (unused_refres_delta > 0 &&
2187             unused_refres_delta >
2188             dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE)) {
2189                 dsl_dataset_rele(ds, FTAG);
2190                 return (SET_ERROR(ENOSPC));
2191         }
2192 
2193         dsl_dataset_rele(ds, FTAG);
2194         return (0);
2195 }
2196 
2197 static void
2198 dsl_dataset_rollback_sync(void *arg, dmu_tx_t *tx)
2199 {
2200         dsl_dataset_rollback_arg_t *ddra = arg;
2201         dsl_pool_t *dp = dmu_tx_pool(tx);
2202         dsl_dataset_t *ds, *clone;
2203         uint64_t cloneobj;
2204         char namebuf[ZFS_MAXNAMELEN];
2205 
2206         VERIFY0(dsl_dataset_hold(dp, ddra->ddra_fsname, FTAG, &ds));
2207 
2208         dsl_dataset_name(ds->ds_prev, namebuf);
2209         fnvlist_add_string(ddra->ddra_result, "target", namebuf);
2210 
2211         cloneobj = dsl_dataset_create_sync(ds->ds_dir, "%rollback",
2212             ds->ds_prev, DS_CREATE_FLAG_NODIRTY, kcred, tx);
2213 
2214         VERIFY0(dsl_dataset_hold_obj(dp, cloneobj, FTAG, &clone));
2215 
2216         dsl_dataset_clone_swap_sync_impl(clone, ds, tx);
2217         dsl_dataset_zero_zil(ds, tx);
2218 
2219         dsl_destroy_head_sync_impl(clone, tx);
2220 
2221         dsl_dataset_rele(clone, FTAG);
2222         dsl_dataset_rele(ds, FTAG);
2223 }
2224 
2225 /*
2226  * Rolls back the given filesystem or volume to the most recent snapshot.
2227  * The name of the most recent snapshot will be returned under key "target"
2228  * in the result nvlist.
2229  *
2230  * If owner != NULL:
2231  * - The existing dataset MUST be owned by the specified owner at entry
2232  * - Upon return, dataset will still be held by the same owner, whether we
2233  *   succeed or not.
2234  *
2235  * This mode is required any time the existing filesystem is mounted.  See
2236  * notes above zfs_suspend_fs() for further details.
2237  */
2238 int
2239 dsl_dataset_rollback(const char *fsname, void *owner, nvlist_t *result)
2240 {
2241         dsl_dataset_rollback_arg_t ddra;
2242 
2243         ddra.ddra_fsname = fsname;
2244         ddra.ddra_owner = owner;
2245         ddra.ddra_result = result;
2246 
2247         return (dsl_sync_task(fsname, dsl_dataset_rollback_check,
2248             dsl_dataset_rollback_sync, &ddra,
2249             1, ZFS_SPACE_CHECK_RESERVED));
2250 }
2251 
2252 struct promotenode {
2253         list_node_t link;
2254         dsl_dataset_t *ds;
2255 };
2256 
2257 typedef struct dsl_dataset_promote_arg {
2258         const char *ddpa_clonename;
2259         dsl_dataset_t *ddpa_clone;
2260         list_t shared_snaps, origin_snaps, clone_snaps;
2261         dsl_dataset_t *origin_origin; /* origin of the origin */
2262         uint64_t used, comp, uncomp, unique, cloneusedsnap, originusedsnap;
2263         char *err_ds;
2264         cred_t *cr;
2265 } dsl_dataset_promote_arg_t;
2266 
2267 static int snaplist_space(list_t *l, uint64_t mintxg, uint64_t *spacep);
2268 static int promote_hold(dsl_dataset_promote_arg_t *ddpa, dsl_pool_t *dp,
2269     void *tag);
2270 static void promote_rele(dsl_dataset_promote_arg_t *ddpa, void *tag);
2271 
2272 static int
2273 dsl_dataset_promote_check(void *arg, dmu_tx_t *tx)
2274 {
2275         dsl_dataset_promote_arg_t *ddpa = arg;
2276         dsl_pool_t *dp = dmu_tx_pool(tx);
2277         dsl_dataset_t *hds;
2278         struct promotenode *snap;
2279         dsl_dataset_t *origin_ds;
2280         int err;
2281         uint64_t unused;
2282         uint64_t ss_mv_cnt;
2283         size_t max_snap_len;
2284 
2285         err = promote_hold(ddpa, dp, FTAG);
2286         if (err != 0)
2287                 return (err);
2288 
2289         hds = ddpa->ddpa_clone;
2290         max_snap_len = MAXNAMELEN - strlen(ddpa->ddpa_clonename) - 1;
2291 
2292         if (dsl_dataset_phys(hds)->ds_flags & DS_FLAG_NOPROMOTE) {
2293                 promote_rele(ddpa, FTAG);
2294                 return (SET_ERROR(EXDEV));
2295         }
2296 
2297         /*
2298          * Compute and check the amount of space to transfer.  Since this is
2299          * so expensive, don't do the preliminary check.
2300          */
2301         if (!dmu_tx_is_syncing(tx)) {
2302                 promote_rele(ddpa, FTAG);
2303                 return (0);
2304         }
2305 
2306         snap = list_head(&ddpa->shared_snaps);
2307         origin_ds = snap->ds;
2308 
2309         /* compute origin's new unique space */
2310         snap = list_tail(&ddpa->clone_snaps);
2311         ASSERT3U(dsl_dataset_phys(snap->ds)->ds_prev_snap_obj, ==,
2312             origin_ds->ds_object);
2313         dsl_deadlist_space_range(&snap->ds->ds_deadlist,
2314             dsl_dataset_phys(origin_ds)->ds_prev_snap_txg, UINT64_MAX,
2315             &ddpa->unique, &unused, &unused);
2316 
2317         /*
2318          * Walk the snapshots that we are moving
2319          *
2320          * Compute space to transfer.  Consider the incremental changes
2321          * to used by each snapshot:
2322          * (my used) = (prev's used) + (blocks born) - (blocks killed)
2323          * So each snapshot gave birth to:
2324          * (blocks born) = (my used) - (prev's used) + (blocks killed)
2325          * So a sequence would look like:
2326          * (uN - u(N-1) + kN) + ... + (u1 - u0 + k1) + (u0 - 0 + k0)
2327          * Which simplifies to:
2328          * uN + kN + kN-1 + ... + k1 + k0
2329          * Note however, if we stop before we reach the ORIGIN we get:
2330          * uN + kN + kN-1 + ... + kM - uM-1
2331          */
2332         ss_mv_cnt = 0;
2333         ddpa->used = dsl_dataset_phys(origin_ds)->ds_referenced_bytes;
2334         ddpa->comp = dsl_dataset_phys(origin_ds)->ds_compressed_bytes;
2335         ddpa->uncomp = dsl_dataset_phys(origin_ds)->ds_uncompressed_bytes;
2336         for (snap = list_head(&ddpa->shared_snaps); snap;
2337             snap = list_next(&ddpa->shared_snaps, snap)) {
2338                 uint64_t val, dlused, dlcomp, dluncomp;
2339                 dsl_dataset_t *ds = snap->ds;
2340 
2341                 ss_mv_cnt++;
2342 
2343                 /*
2344                  * If there are long holds, we won't be able to evict
2345                  * the objset.
2346                  */
2347                 if (dsl_dataset_long_held(ds)) {
2348                         err = SET_ERROR(EBUSY);
2349                         goto out;
2350                 }
2351 
2352                 /* Check that the snapshot name does not conflict */
2353                 VERIFY0(dsl_dataset_get_snapname(ds));
2354                 if (strlen(ds->ds_snapname) >= max_snap_len) {
2355                         err = SET_ERROR(ENAMETOOLONG);
2356                         goto out;
2357                 }
2358                 err = dsl_dataset_snap_lookup(hds, ds->ds_snapname, &val);
2359                 if (err == 0) {
2360                         (void) strcpy(ddpa->err_ds, snap->ds->ds_snapname);
2361                         err = SET_ERROR(EEXIST);
2362                         goto out;
2363                 }
2364                 if (err != ENOENT)
2365                         goto out;
2366 
2367                 /* The very first snapshot does not have a deadlist */
2368                 if (dsl_dataset_phys(ds)->ds_prev_snap_obj == 0)
2369                         continue;
2370 
2371                 dsl_deadlist_space(&ds->ds_deadlist,
2372                     &dlused, &dlcomp, &dluncomp);
2373                 ddpa->used += dlused;
2374                 ddpa->comp += dlcomp;
2375                 ddpa->uncomp += dluncomp;
2376         }
2377 
2378         /*
2379          * If we are a clone of a clone then we never reached ORIGIN,
2380          * so we need to subtract out the clone origin's used space.
2381          */
2382         if (ddpa->origin_origin) {
2383                 ddpa->used -=
2384                     dsl_dataset_phys(ddpa->origin_origin)->ds_referenced_bytes;
2385                 ddpa->comp -=
2386                     dsl_dataset_phys(ddpa->origin_origin)->ds_compressed_bytes;
2387                 ddpa->uncomp -=
2388                     dsl_dataset_phys(ddpa->origin_origin)->
2389                     ds_uncompressed_bytes;
2390         }
2391 
2392         /* Check that there is enough space and limit headroom here */
2393         err = dsl_dir_transfer_possible(origin_ds->ds_dir, hds->ds_dir,
2394             0, ss_mv_cnt, ddpa->used, ddpa->cr);
2395         if (err != 0)
2396                 goto out;
2397 
2398         /*
2399          * Compute the amounts of space that will be used by snapshots
2400          * after the promotion (for both origin and clone).  For each,
2401          * it is the amount of space that will be on all of their
2402          * deadlists (that was not born before their new origin).
2403          */
2404         if (dsl_dir_phys(hds->ds_dir)->dd_flags & DD_FLAG_USED_BREAKDOWN) {
2405                 uint64_t space;
2406 
2407                 /*
2408                  * Note, typically this will not be a clone of a clone,
2409                  * so dd_origin_txg will be < TXG_INITIAL, so
2410                  * these snaplist_space() -> dsl_deadlist_space_range()
2411                  * calls will be fast because they do not have to
2412                  * iterate over all bps.
2413                  */
2414                 snap = list_head(&ddpa->origin_snaps);
2415                 err = snaplist_space(&ddpa->shared_snaps,
2416                     snap->ds->ds_dir->dd_origin_txg, &ddpa->cloneusedsnap);
2417                 if (err != 0)
2418                         goto out;
2419 
2420                 err = snaplist_space(&ddpa->clone_snaps,
2421                     snap->ds->ds_dir->dd_origin_txg, &space);
2422                 if (err != 0)
2423                         goto out;
2424                 ddpa->cloneusedsnap += space;
2425         }
2426         if (dsl_dir_phys(origin_ds->ds_dir)->dd_flags &
2427             DD_FLAG_USED_BREAKDOWN) {
2428                 err = snaplist_space(&ddpa->origin_snaps,
2429                     dsl_dataset_phys(origin_ds)->ds_creation_txg,
2430                     &ddpa->originusedsnap);
2431                 if (err != 0)
2432                         goto out;
2433         }
2434 
2435 out:
2436         promote_rele(ddpa, FTAG);
2437         return (err);
2438 }
2439 
2440 static void
2441 dsl_dataset_promote_sync(void *arg, dmu_tx_t *tx)
2442 {
2443         dsl_dataset_promote_arg_t *ddpa = arg;
2444         dsl_pool_t *dp = dmu_tx_pool(tx);
2445         dsl_dataset_t *hds;
2446         struct promotenode *snap;
2447         dsl_dataset_t *origin_ds;
2448         dsl_dataset_t *origin_head;
2449         dsl_dir_t *dd;
2450         dsl_dir_t *odd = NULL;
2451         uint64_t oldnext_obj;
2452         int64_t delta;
2453 
2454         VERIFY0(promote_hold(ddpa, dp, FTAG));
2455         hds = ddpa->ddpa_clone;
2456 
2457         ASSERT0(dsl_dataset_phys(hds)->ds_flags & DS_FLAG_NOPROMOTE);
2458 
2459         snap = list_head(&ddpa->shared_snaps);
2460         origin_ds = snap->ds;
2461         dd = hds->ds_dir;
2462 
2463         snap = list_head(&ddpa->origin_snaps);
2464         origin_head = snap->ds;
2465 
2466         /*
2467          * We need to explicitly open odd, since origin_ds's dd will be
2468          * changing.
2469          */
2470         VERIFY0(dsl_dir_hold_obj(dp, origin_ds->ds_dir->dd_object,
2471             NULL, FTAG, &odd));
2472 
2473         /* change origin's next snap */
2474         dmu_buf_will_dirty(origin_ds->ds_dbuf, tx);
2475         oldnext_obj = dsl_dataset_phys(origin_ds)->ds_next_snap_obj;
2476         snap = list_tail(&ddpa->clone_snaps);
2477         ASSERT3U(dsl_dataset_phys(snap->ds)->ds_prev_snap_obj, ==,
2478             origin_ds->ds_object);
2479         dsl_dataset_phys(origin_ds)->ds_next_snap_obj = snap->ds->ds_object;
2480 
2481         /* change the origin's next clone */
2482         if (dsl_dataset_phys(origin_ds)->ds_next_clones_obj) {
2483                 dsl_dataset_remove_from_next_clones(origin_ds,
2484                     snap->ds->ds_object, tx);
2485                 VERIFY0(zap_add_int(dp->dp_meta_objset,
2486                     dsl_dataset_phys(origin_ds)->ds_next_clones_obj,
2487                     oldnext_obj, tx));
2488         }
2489 
2490         /* change origin */
2491         dmu_buf_will_dirty(dd->dd_dbuf, tx);
2492         ASSERT3U(dsl_dir_phys(dd)->dd_origin_obj, ==, origin_ds->ds_object);
2493         dsl_dir_phys(dd)->dd_origin_obj = dsl_dir_phys(odd)->dd_origin_obj;
2494         dd->dd_origin_txg = origin_head->ds_dir->dd_origin_txg;
2495         dmu_buf_will_dirty(odd->dd_dbuf, tx);
2496         dsl_dir_phys(odd)->dd_origin_obj = origin_ds->ds_object;
2497         origin_head->ds_dir->dd_origin_txg =
2498             dsl_dataset_phys(origin_ds)->ds_creation_txg;
2499 
2500         /* change dd_clone entries */
2501         if (spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
2502                 VERIFY0(zap_remove_int(dp->dp_meta_objset,
2503                     dsl_dir_phys(odd)->dd_clones, hds->ds_object, tx));
2504                 VERIFY0(zap_add_int(dp->dp_meta_objset,
2505                     dsl_dir_phys(ddpa->origin_origin->ds_dir)->dd_clones,
2506                     hds->ds_object, tx));
2507 
2508                 VERIFY0(zap_remove_int(dp->dp_meta_objset,
2509                     dsl_dir_phys(ddpa->origin_origin->ds_dir)->dd_clones,
2510                     origin_head->ds_object, tx));
2511                 if (dsl_dir_phys(dd)->dd_clones == 0) {
2512                         dsl_dir_phys(dd)->dd_clones =
2513                             zap_create(dp->dp_meta_objset, DMU_OT_DSL_CLONES,
2514                             DMU_OT_NONE, 0, tx);
2515                 }
2516                 VERIFY0(zap_add_int(dp->dp_meta_objset,
2517                     dsl_dir_phys(dd)->dd_clones, origin_head->ds_object, tx));
2518         }
2519 
2520         /* move snapshots to this dir */
2521         for (snap = list_head(&ddpa->shared_snaps); snap;
2522             snap = list_next(&ddpa->shared_snaps, snap)) {
2523                 dsl_dataset_t *ds = snap->ds;
2524 
2525                 /*
2526                  * Property callbacks are registered to a particular
2527                  * dsl_dir.  Since ours is changing, evict the objset
2528                  * so that they will be unregistered from the old dsl_dir.
2529                  */
2530                 if (ds->ds_objset) {
2531                         dmu_objset_evict(ds->ds_objset);
2532                         ds->ds_objset = NULL;
2533                 }
2534 
2535                 /* move snap name entry */
2536                 VERIFY0(dsl_dataset_get_snapname(ds));
2537                 VERIFY0(dsl_dataset_snap_remove(origin_head,
2538                     ds->ds_snapname, tx, B_TRUE));
2539                 VERIFY0(zap_add(dp->dp_meta_objset,
2540                     dsl_dataset_phys(hds)->ds_snapnames_zapobj, ds->ds_snapname,
2541                     8, 1, &ds->ds_object, tx));
2542                 dsl_fs_ss_count_adjust(hds->ds_dir, 1,
2543                     DD_FIELD_SNAPSHOT_COUNT, tx);
2544 
2545                 /* change containing dsl_dir */
2546                 dmu_buf_will_dirty(ds->ds_dbuf, tx);
2547                 ASSERT3U(dsl_dataset_phys(ds)->ds_dir_obj, ==, odd->dd_object);
2548                 dsl_dataset_phys(ds)->ds_dir_obj = dd->dd_object;
2549                 ASSERT3P(ds->ds_dir, ==, odd);
2550                 dsl_dir_rele(ds->ds_dir, ds);
2551                 VERIFY0(dsl_dir_hold_obj(dp, dd->dd_object,
2552                     NULL, ds, &ds->ds_dir));
2553 
2554                 /* move any clone references */
2555                 if (dsl_dataset_phys(ds)->ds_next_clones_obj &&
2556                     spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
2557                         zap_cursor_t zc;
2558                         zap_attribute_t za;
2559 
2560                         for (zap_cursor_init(&zc, dp->dp_meta_objset,
2561                             dsl_dataset_phys(ds)->ds_next_clones_obj);
2562                             zap_cursor_retrieve(&zc, &za) == 0;
2563                             zap_cursor_advance(&zc)) {
2564                                 dsl_dataset_t *cnds;
2565                                 uint64_t o;
2566 
2567                                 if (za.za_first_integer == oldnext_obj) {
2568                                         /*
2569                                          * We've already moved the
2570                                          * origin's reference.
2571                                          */
2572                                         continue;
2573                                 }
2574 
2575                                 VERIFY0(dsl_dataset_hold_obj(dp,
2576                                     za.za_first_integer, FTAG, &cnds));
2577                                 o = dsl_dir_phys(cnds->ds_dir)->
2578                                     dd_head_dataset_obj;
2579 
2580                                 VERIFY0(zap_remove_int(dp->dp_meta_objset,
2581                                     dsl_dir_phys(odd)->dd_clones, o, tx));
2582                                 VERIFY0(zap_add_int(dp->dp_meta_objset,
2583                                     dsl_dir_phys(dd)->dd_clones, o, tx));
2584                                 dsl_dataset_rele(cnds, FTAG);
2585                         }
2586                         zap_cursor_fini(&zc);
2587                 }
2588 
2589                 ASSERT(!dsl_prop_hascb(ds));
2590         }
2591 
2592         /*
2593          * Change space accounting.
2594          * Note, pa->*usedsnap and dd_used_breakdown[SNAP] will either
2595          * both be valid, or both be 0 (resulting in delta == 0).  This
2596          * is true for each of {clone,origin} independently.
2597          */
2598 
2599         delta = ddpa->cloneusedsnap -
2600             dsl_dir_phys(dd)->dd_used_breakdown[DD_USED_SNAP];
2601         ASSERT3S(delta, >=, 0);
2602         ASSERT3U(ddpa->used, >=, delta);
2603         dsl_dir_diduse_space(dd, DD_USED_SNAP, delta, 0, 0, tx);
2604         dsl_dir_diduse_space(dd, DD_USED_HEAD,
2605             ddpa->used - delta, ddpa->comp, ddpa->uncomp, tx);
2606 
2607         delta = ddpa->originusedsnap -
2608             dsl_dir_phys(odd)->dd_used_breakdown[DD_USED_SNAP];
2609         ASSERT3S(delta, <=, 0);
2610         ASSERT3U(ddpa->used, >=, -delta);
2611         dsl_dir_diduse_space(odd, DD_USED_SNAP, delta, 0, 0, tx);
2612         dsl_dir_diduse_space(odd, DD_USED_HEAD,
2613             -ddpa->used - delta, -ddpa->comp, -ddpa->uncomp, tx);
2614 
2615         dsl_dataset_phys(origin_ds)->ds_unique_bytes = ddpa->unique;
2616 
2617         /* log history record */
2618         spa_history_log_internal_ds(hds, "promote", tx, "");
2619 
2620         dsl_dir_rele(odd, FTAG);
2621         promote_rele(ddpa, FTAG);
2622 }
2623 
2624 /*
2625  * Make a list of dsl_dataset_t's for the snapshots between first_obj
2626  * (exclusive) and last_obj (inclusive).  The list will be in reverse
2627  * order (last_obj will be the list_head()).  If first_obj == 0, do all
2628  * snapshots back to this dataset's origin.
2629  */
2630 static int
2631 snaplist_make(dsl_pool_t *dp,
2632     uint64_t first_obj, uint64_t last_obj, list_t *l, void *tag)
2633 {
2634         uint64_t obj = last_obj;
2635 
2636         list_create(l, sizeof (struct promotenode),
2637             offsetof(struct promotenode, link));
2638 
2639         while (obj != first_obj) {
2640                 dsl_dataset_t *ds;
2641                 struct promotenode *snap;
2642                 int err;
2643 
2644                 err = dsl_dataset_hold_obj(dp, obj, tag, &ds);
2645                 ASSERT(err != ENOENT);
2646                 if (err != 0)
2647                         return (err);
2648 
2649                 if (first_obj == 0)
2650                         first_obj = dsl_dir_phys(ds->ds_dir)->dd_origin_obj;
2651 
2652                 snap = kmem_alloc(sizeof (*snap), KM_SLEEP);
2653                 snap->ds = ds;
2654                 list_insert_tail(l, snap);
2655                 obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
2656         }
2657 
2658         return (0);
2659 }
2660 
2661 static int
2662 snaplist_space(list_t *l, uint64_t mintxg, uint64_t *spacep)
2663 {
2664         struct promotenode *snap;
2665 
2666         *spacep = 0;
2667         for (snap = list_head(l); snap; snap = list_next(l, snap)) {
2668                 uint64_t used, comp, uncomp;
2669                 dsl_deadlist_space_range(&snap->ds->ds_deadlist,
2670                     mintxg, UINT64_MAX, &used, &comp, &uncomp);
2671                 *spacep += used;
2672         }
2673         return (0);
2674 }
2675 
2676 static void
2677 snaplist_destroy(list_t *l, void *tag)
2678 {
2679         struct promotenode *snap;
2680 
2681         if (l == NULL || !list_link_active(&l->list_head))
2682                 return;
2683 
2684         while ((snap = list_tail(l)) != NULL) {
2685                 list_remove(l, snap);
2686                 dsl_dataset_rele(snap->ds, tag);
2687                 kmem_free(snap, sizeof (*snap));
2688         }
2689         list_destroy(l);
2690 }
2691 
2692 static int
2693 promote_hold(dsl_dataset_promote_arg_t *ddpa, dsl_pool_t *dp, void *tag)
2694 {
2695         int error;
2696         dsl_dir_t *dd;
2697         struct promotenode *snap;
2698 
2699         error = dsl_dataset_hold(dp, ddpa->ddpa_clonename, tag,
2700             &ddpa->ddpa_clone);
2701         if (error != 0)
2702                 return (error);
2703         dd = ddpa->ddpa_clone->ds_dir;
2704 
2705         if (ddpa->ddpa_clone->ds_is_snapshot ||
2706             !dsl_dir_is_clone(dd)) {
2707                 dsl_dataset_rele(ddpa->ddpa_clone, tag);
2708                 return (SET_ERROR(EINVAL));
2709         }
2710 
2711         error = snaplist_make(dp, 0, dsl_dir_phys(dd)->dd_origin_obj,
2712             &ddpa->shared_snaps, tag);
2713         if (error != 0)
2714                 goto out;
2715 
2716         error = snaplist_make(dp, 0, ddpa->ddpa_clone->ds_object,
2717             &ddpa->clone_snaps, tag);
2718         if (error != 0)
2719                 goto out;
2720 
2721         snap = list_head(&ddpa->shared_snaps);
2722         ASSERT3U(snap->ds->ds_object, ==, dsl_dir_phys(dd)->dd_origin_obj);
2723         error = snaplist_make(dp, dsl_dir_phys(dd)->dd_origin_obj,
2724             dsl_dir_phys(snap->ds->ds_dir)->dd_head_dataset_obj,
2725             &ddpa->origin_snaps, tag);
2726         if (error != 0)
2727                 goto out;
2728 
2729         if (dsl_dir_phys(snap->ds->ds_dir)->dd_origin_obj != 0) {
2730                 error = dsl_dataset_hold_obj(dp,
2731                     dsl_dir_phys(snap->ds->ds_dir)->dd_origin_obj,
2732                     tag, &ddpa->origin_origin);
2733                 if (error != 0)
2734                         goto out;
2735         }
2736 out:
2737         if (error != 0)
2738                 promote_rele(ddpa, tag);
2739         return (error);
2740 }
2741 
2742 static void
2743 promote_rele(dsl_dataset_promote_arg_t *ddpa, void *tag)
2744 {
2745         snaplist_destroy(&ddpa->shared_snaps, tag);
2746         snaplist_destroy(&ddpa->clone_snaps, tag);
2747         snaplist_destroy(&ddpa->origin_snaps, tag);
2748         if (ddpa->origin_origin != NULL)
2749                 dsl_dataset_rele(ddpa->origin_origin, tag);
2750         dsl_dataset_rele(ddpa->ddpa_clone, tag);
2751 }
2752 
2753 /*
2754  * Promote a clone.
2755  *
2756  * If it fails due to a conflicting snapshot name, "conflsnap" will be filled
2757  * in with the name.  (It must be at least MAXNAMELEN bytes long.)
2758  */
2759 int
2760 dsl_dataset_promote(const char *name, char *conflsnap)
2761 {
2762         dsl_dataset_promote_arg_t ddpa = { 0 };
2763         uint64_t numsnaps;
2764         int error;
2765         objset_t *os;
2766 
2767         /*
2768          * We will modify space proportional to the number of
2769          * snapshots.  Compute numsnaps.
2770          */
2771         error = dmu_objset_hold(name, FTAG, &os);
2772         if (error != 0)
2773                 return (error);
2774         error = zap_count(dmu_objset_pool(os)->dp_meta_objset,
2775             dsl_dataset_phys(dmu_objset_ds(os))->ds_snapnames_zapobj,
2776             &numsnaps);
2777         dmu_objset_rele(os, FTAG);
2778         if (error != 0)
2779                 return (error);
2780 
2781         ddpa.ddpa_clonename = name;
2782         ddpa.err_ds = conflsnap;
2783         ddpa.cr = CRED();
2784 
2785         return (dsl_sync_task(name, dsl_dataset_promote_check,
2786             dsl_dataset_promote_sync, &ddpa,
2787             2 + numsnaps, ZFS_SPACE_CHECK_RESERVED));
2788 }
2789 
2790 int
2791 dsl_dataset_clone_swap_check_impl(dsl_dataset_t *clone,
2792     dsl_dataset_t *origin_head, boolean_t force, void *owner, dmu_tx_t *tx)
2793 {
2794         /*
2795          * "slack" factor for received datasets with refquota set on them.
2796          * See the bottom of this function for details on its use.
2797          */
2798         uint64_t refquota_slack = DMU_MAX_ACCESS * spa_asize_inflation;
2799         int64_t unused_refres_delta;
2800 
2801         /* they should both be heads */
2802         if (clone->ds_is_snapshot ||
2803             origin_head->ds_is_snapshot)
2804                 return (SET_ERROR(EINVAL));
2805 
2806         /* if we are not forcing, the branch point should be just before them */
2807         if (!force && clone->ds_prev != origin_head->ds_prev)
2808                 return (SET_ERROR(EINVAL));
2809 
2810         /* clone should be the clone (unless they are unrelated) */
2811         if (clone->ds_prev != NULL &&
2812             clone->ds_prev != clone->ds_dir->dd_pool->dp_origin_snap &&
2813             origin_head->ds_dir != clone->ds_prev->ds_dir)
2814                 return (SET_ERROR(EINVAL));
2815 
2816         /* the clone should be a child of the origin */
2817         if (clone->ds_dir->dd_parent != origin_head->ds_dir)
2818                 return (SET_ERROR(EINVAL));
2819 
2820         /* origin_head shouldn't be modified unless 'force' */
2821         if (!force &&
2822             dsl_dataset_modified_since_snap(origin_head, origin_head->ds_prev))
2823                 return (SET_ERROR(ETXTBSY));
2824 
2825         /* origin_head should have no long holds (e.g. is not mounted) */
2826         if (dsl_dataset_handoff_check(origin_head, owner, tx))
2827                 return (SET_ERROR(EBUSY));
2828 
2829         /* check amount of any unconsumed refreservation */
2830         unused_refres_delta =
2831             (int64_t)MIN(origin_head->ds_reserved,
2832             dsl_dataset_phys(origin_head)->ds_unique_bytes) -
2833             (int64_t)MIN(origin_head->ds_reserved,
2834             dsl_dataset_phys(clone)->ds_unique_bytes);
2835 
2836         if (unused_refres_delta > 0 &&
2837             unused_refres_delta >
2838             dsl_dir_space_available(origin_head->ds_dir, NULL, 0, TRUE))
2839                 return (SET_ERROR(ENOSPC));
2840 
2841         /*
2842          * The clone can't be too much over the head's refquota.
2843          *
2844          * To ensure that the entire refquota can be used, we allow one
2845          * transaction to exceed the the refquota.  Therefore, this check
2846          * needs to also allow for the space referenced to be more than the
2847          * refquota.  The maximum amount of space that one transaction can use
2848          * on disk is DMU_MAX_ACCESS * spa_asize_inflation.  Allowing this
2849          * overage ensures that we are able to receive a filesystem that
2850          * exceeds the refquota on the source system.
2851          *
2852          * So that overage is the refquota_slack we use below.
2853          */
2854         if (origin_head->ds_quota != 0 &&
2855             dsl_dataset_phys(clone)->ds_referenced_bytes >
2856             origin_head->ds_quota + refquota_slack)
2857                 return (SET_ERROR(EDQUOT));
2858 
2859         return (0);
2860 }
2861 
2862 void
2863 dsl_dataset_clone_swap_sync_impl(dsl_dataset_t *clone,
2864     dsl_dataset_t *origin_head, dmu_tx_t *tx)
2865 {
2866         dsl_pool_t *dp = dmu_tx_pool(tx);
2867         int64_t unused_refres_delta;
2868 
2869         ASSERT(clone->ds_reserved == 0);
2870         /*
2871          * NOTE: On DEBUG kernels there could be a race between this and
2872          * the check function if spa_asize_inflation is adjusted...
2873          */
2874         ASSERT(origin_head->ds_quota == 0 ||
2875             dsl_dataset_phys(clone)->ds_unique_bytes <= origin_head->ds_quota +
2876             DMU_MAX_ACCESS * spa_asize_inflation);
2877         ASSERT3P(clone->ds_prev, ==, origin_head->ds_prev);
2878 
2879         /*
2880          * Swap per-dataset feature flags.
2881          */
2882         for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
2883                 if (!(spa_feature_table[f].fi_flags &
2884                     ZFEATURE_FLAG_PER_DATASET)) {
2885                         ASSERT(!clone->ds_feature_inuse[f]);
2886                         ASSERT(!origin_head->ds_feature_inuse[f]);
2887                         continue;
2888                 }
2889 
2890                 boolean_t clone_inuse = clone->ds_feature_inuse[f];
2891                 boolean_t origin_head_inuse = origin_head->ds_feature_inuse[f];
2892 
2893                 if (clone_inuse) {
2894                         dsl_dataset_deactivate_feature(clone->ds_object, f, tx);
2895                         clone->ds_feature_inuse[f] = B_FALSE;
2896                 }
2897                 if (origin_head_inuse) {
2898                         dsl_dataset_deactivate_feature(origin_head->ds_object,
2899                             f, tx);
2900                         origin_head->ds_feature_inuse[f] = B_FALSE;
2901                 }
2902                 if (clone_inuse) {
2903                         dsl_dataset_activate_feature(origin_head->ds_object,
2904                             f, tx);
2905                         origin_head->ds_feature_inuse[f] = B_TRUE;
2906                 }
2907                 if (origin_head_inuse) {
2908                         dsl_dataset_activate_feature(clone->ds_object, f, tx);
2909                         clone->ds_feature_inuse[f] = B_TRUE;
2910                 }
2911         }
2912 
2913         dmu_buf_will_dirty(clone->ds_dbuf, tx);
2914         dmu_buf_will_dirty(origin_head->ds_dbuf, tx);
2915 
2916         if (clone->ds_objset != NULL) {
2917                 dmu_objset_evict(clone->ds_objset);
2918                 clone->ds_objset = NULL;
2919         }
2920 
2921         if (origin_head->ds_objset != NULL) {
2922                 dmu_objset_evict(origin_head->ds_objset);
2923                 origin_head->ds_objset = NULL;
2924         }
2925 
2926         unused_refres_delta =
2927             (int64_t)MIN(origin_head->ds_reserved,
2928             dsl_dataset_phys(origin_head)->ds_unique_bytes) -
2929             (int64_t)MIN(origin_head->ds_reserved,
2930             dsl_dataset_phys(clone)->ds_unique_bytes);
2931 
2932         /*
2933          * Reset origin's unique bytes, if it exists.
2934          */
2935         if (clone->ds_prev) {
2936                 dsl_dataset_t *origin = clone->ds_prev;
2937                 uint64_t comp, uncomp;
2938 
2939                 dmu_buf_will_dirty(origin->ds_dbuf, tx);
2940                 dsl_deadlist_space_range(&clone->ds_deadlist,
2941                     dsl_dataset_phys(origin)->ds_prev_snap_txg, UINT64_MAX,
2942                     &dsl_dataset_phys(origin)->ds_unique_bytes, &comp, &uncomp);
2943         }
2944 
2945         /* swap blkptrs */
2946         {
2947                 blkptr_t tmp;
2948                 tmp = dsl_dataset_phys(origin_head)->ds_bp;
2949                 dsl_dataset_phys(origin_head)->ds_bp =
2950                     dsl_dataset_phys(clone)->ds_bp;
2951                 dsl_dataset_phys(clone)->ds_bp = tmp;
2952         }
2953 
2954         /* set dd_*_bytes */
2955         {
2956                 int64_t dused, dcomp, duncomp;
2957                 uint64_t cdl_used, cdl_comp, cdl_uncomp;
2958                 uint64_t odl_used, odl_comp, odl_uncomp;
2959 
2960                 ASSERT3U(dsl_dir_phys(clone->ds_dir)->
2961                     dd_used_breakdown[DD_USED_SNAP], ==, 0);
2962 
2963                 dsl_deadlist_space(&clone->ds_deadlist,
2964                     &cdl_used, &cdl_comp, &cdl_uncomp);
2965                 dsl_deadlist_space(&origin_head->ds_deadlist,
2966                     &odl_used, &odl_comp, &odl_uncomp);
2967 
2968                 dused = dsl_dataset_phys(clone)->ds_referenced_bytes +
2969                     cdl_used -
2970                     (dsl_dataset_phys(origin_head)->ds_referenced_bytes +
2971                     odl_used);
2972                 dcomp = dsl_dataset_phys(clone)->ds_compressed_bytes +
2973                     cdl_comp -
2974                     (dsl_dataset_phys(origin_head)->ds_compressed_bytes +
2975                     odl_comp);
2976                 duncomp = dsl_dataset_phys(clone)->ds_uncompressed_bytes +
2977                     cdl_uncomp -
2978                     (dsl_dataset_phys(origin_head)->ds_uncompressed_bytes +
2979                     odl_uncomp);
2980 
2981                 dsl_dir_diduse_space(origin_head->ds_dir, DD_USED_HEAD,
2982                     dused, dcomp, duncomp, tx);
2983                 dsl_dir_diduse_space(clone->ds_dir, DD_USED_HEAD,
2984                     -dused, -dcomp, -duncomp, tx);
2985 
2986                 /*
2987                  * The difference in the space used by snapshots is the
2988                  * difference in snapshot space due to the head's
2989                  * deadlist (since that's the only thing that's
2990                  * changing that affects the snapused).
2991                  */
2992                 dsl_deadlist_space_range(&clone->ds_deadlist,
2993                     origin_head->ds_dir->dd_origin_txg, UINT64_MAX,
2994                     &cdl_used, &cdl_comp, &cdl_uncomp);
2995                 dsl_deadlist_space_range(&origin_head->ds_deadlist,
2996                     origin_head->ds_dir->dd_origin_txg, UINT64_MAX,
2997                     &odl_used, &odl_comp, &odl_uncomp);
2998                 dsl_dir_transfer_space(origin_head->ds_dir, cdl_used - odl_used,
2999                     DD_USED_HEAD, DD_USED_SNAP, tx);
3000         }
3001 
3002         /* swap ds_*_bytes */
3003         SWITCH64(dsl_dataset_phys(origin_head)->ds_referenced_bytes,
3004             dsl_dataset_phys(clone)->ds_referenced_bytes);
3005         SWITCH64(dsl_dataset_phys(origin_head)->ds_compressed_bytes,
3006             dsl_dataset_phys(clone)->ds_compressed_bytes);
3007         SWITCH64(dsl_dataset_phys(origin_head)->ds_uncompressed_bytes,
3008             dsl_dataset_phys(clone)->ds_uncompressed_bytes);
3009         SWITCH64(dsl_dataset_phys(origin_head)->ds_unique_bytes,
3010             dsl_dataset_phys(clone)->ds_unique_bytes);
3011 
3012         /* apply any parent delta for change in unconsumed refreservation */
3013         dsl_dir_diduse_space(origin_head->ds_dir, DD_USED_REFRSRV,
3014             unused_refres_delta, 0, 0, tx);
3015 
3016         /*
3017          * Swap deadlists.
3018          */
3019         dsl_deadlist_close(&clone->ds_deadlist);
3020         dsl_deadlist_close(&origin_head->ds_deadlist);
3021         SWITCH64(dsl_dataset_phys(origin_head)->ds_deadlist_obj,
3022             dsl_dataset_phys(clone)->ds_deadlist_obj);
3023         dsl_deadlist_open(&clone->ds_deadlist, dp->dp_meta_objset,
3024             dsl_dataset_phys(clone)->ds_deadlist_obj);
3025         dsl_deadlist_open(&origin_head->ds_deadlist, dp->dp_meta_objset,
3026             dsl_dataset_phys(origin_head)->ds_deadlist_obj);
3027 
3028         dsl_scan_ds_clone_swapped(origin_head, clone, tx);
3029 
3030         spa_history_log_internal_ds(clone, "clone swap", tx,
3031             "parent=%s", origin_head->ds_dir->dd_myname);
3032 }
3033 
3034 /*
3035  * Given a pool name and a dataset object number in that pool,
3036  * return the name of that dataset.
3037  */
3038 int
3039 dsl_dsobj_to_dsname(char *pname, uint64_t obj, char *buf)
3040 {
3041         dsl_pool_t *dp;
3042         dsl_dataset_t *ds;
3043         int error;
3044 
3045         error = dsl_pool_hold(pname, FTAG, &dp);
3046         if (error != 0)
3047                 return (error);
3048 
3049         error = dsl_dataset_hold_obj(dp, obj, FTAG, &ds);
3050         if (error == 0) {
3051                 dsl_dataset_name(ds, buf);
3052                 dsl_dataset_rele(ds, FTAG);
3053         }
3054         dsl_pool_rele(dp, FTAG);
3055 
3056         return (error);
3057 }
3058 
3059 int
3060 dsl_dataset_check_quota(dsl_dataset_t *ds, boolean_t check_quota,
3061     uint64_t asize, uint64_t inflight, uint64_t *used, uint64_t *ref_rsrv)
3062 {
3063         int error = 0;
3064 
3065         ASSERT3S(asize, >, 0);
3066 
3067         /*
3068          * *ref_rsrv is the portion of asize that will come from any
3069          * unconsumed refreservation space.
3070          */
3071         *ref_rsrv = 0;
3072 
3073         mutex_enter(&ds->ds_lock);
3074         /*
3075          * Make a space adjustment for reserved bytes.
3076          */
3077         if (ds->ds_reserved > dsl_dataset_phys(ds)->ds_unique_bytes) {
3078                 ASSERT3U(*used, >=,
3079                     ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes);
3080                 *used -=
3081                     (ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes);
3082                 *ref_rsrv =
3083                     asize - MIN(asize, parent_delta(ds, asize + inflight));
3084         }
3085 
3086         if (!check_quota || ds->ds_quota == 0) {
3087                 mutex_exit(&ds->ds_lock);
3088                 return (0);
3089         }
3090         /*
3091          * If they are requesting more space, and our current estimate
3092          * is over quota, they get to try again unless the actual
3093          * on-disk is over quota and there are no pending changes (which
3094          * may free up space for us).
3095          */
3096         if (dsl_dataset_phys(ds)->ds_referenced_bytes + inflight >=
3097             ds->ds_quota) {
3098                 if (inflight > 0 ||
3099                     dsl_dataset_phys(ds)->ds_referenced_bytes < ds->ds_quota)
3100                         error = SET_ERROR(ERESTART);
3101                 else
3102                         error = SET_ERROR(EDQUOT);
3103         }
3104         mutex_exit(&ds->ds_lock);
3105 
3106         return (error);
3107 }
3108 
3109 typedef struct dsl_dataset_set_qr_arg {
3110         const char *ddsqra_name;
3111         zprop_source_t ddsqra_source;
3112         uint64_t ddsqra_value;
3113 } dsl_dataset_set_qr_arg_t;
3114 
3115 
3116 /* ARGSUSED */
3117 static int
3118 dsl_dataset_set_refquota_check(void *arg, dmu_tx_t *tx)
3119 {
3120         dsl_dataset_set_qr_arg_t *ddsqra = arg;
3121         dsl_pool_t *dp = dmu_tx_pool(tx);
3122         dsl_dataset_t *ds;
3123         int error;
3124         uint64_t newval;
3125 
3126         if (spa_version(dp->dp_spa) < SPA_VERSION_REFQUOTA)
3127                 return (SET_ERROR(ENOTSUP));
3128 
3129         error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
3130         if (error != 0)
3131                 return (error);
3132 
3133         if (ds->ds_is_snapshot) {
3134                 dsl_dataset_rele(ds, FTAG);
3135                 return (SET_ERROR(EINVAL));
3136         }
3137 
3138         error = dsl_prop_predict(ds->ds_dir,
3139             zfs_prop_to_name(ZFS_PROP_REFQUOTA),
3140             ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
3141         if (error != 0) {
3142                 dsl_dataset_rele(ds, FTAG);
3143                 return (error);
3144         }
3145 
3146         if (newval == 0) {
3147                 dsl_dataset_rele(ds, FTAG);
3148                 return (0);
3149         }
3150 
3151         if (newval < dsl_dataset_phys(ds)->ds_referenced_bytes ||
3152             newval < ds->ds_reserved) {
3153                 dsl_dataset_rele(ds, FTAG);
3154                 return (SET_ERROR(ENOSPC));
3155         }
3156 
3157         dsl_dataset_rele(ds, FTAG);
3158         return (0);
3159 }
3160 
3161 static void
3162 dsl_dataset_set_refquota_sync(void *arg, dmu_tx_t *tx)
3163 {
3164         dsl_dataset_set_qr_arg_t *ddsqra = arg;
3165         dsl_pool_t *dp = dmu_tx_pool(tx);
3166         dsl_dataset_t *ds;
3167         uint64_t newval;
3168 
3169         VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
3170 
3171         dsl_prop_set_sync_impl(ds,
3172             zfs_prop_to_name(ZFS_PROP_REFQUOTA),
3173             ddsqra->ddsqra_source, sizeof (ddsqra->ddsqra_value), 1,
3174             &ddsqra->ddsqra_value, tx);
3175 
3176         VERIFY0(dsl_prop_get_int_ds(ds,
3177             zfs_prop_to_name(ZFS_PROP_REFQUOTA), &newval));
3178 
3179         if (ds->ds_quota != newval) {
3180                 dmu_buf_will_dirty(ds->ds_dbuf, tx);
3181                 ds->ds_quota = newval;
3182         }
3183         dsl_dataset_rele(ds, FTAG);
3184 }
3185 
3186 int
3187 dsl_dataset_set_refquota(const char *dsname, zprop_source_t source,
3188     uint64_t refquota)
3189 {
3190         dsl_dataset_set_qr_arg_t ddsqra;
3191 
3192         ddsqra.ddsqra_name = dsname;
3193         ddsqra.ddsqra_source = source;
3194         ddsqra.ddsqra_value = refquota;
3195 
3196         return (dsl_sync_task(dsname, dsl_dataset_set_refquota_check,
3197             dsl_dataset_set_refquota_sync, &ddsqra, 0, ZFS_SPACE_CHECK_NONE));
3198 }
3199 
3200 static int
3201 dsl_dataset_set_refreservation_check(void *arg, dmu_tx_t *tx)
3202 {
3203         dsl_dataset_set_qr_arg_t *ddsqra = arg;
3204         dsl_pool_t *dp = dmu_tx_pool(tx);
3205         dsl_dataset_t *ds;
3206         int error;
3207         uint64_t newval, unique;
3208 
3209         if (spa_version(dp->dp_spa) < SPA_VERSION_REFRESERVATION)
3210                 return (SET_ERROR(ENOTSUP));
3211 
3212         error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
3213         if (error != 0)
3214                 return (error);
3215 
3216         if (ds->ds_is_snapshot) {
3217                 dsl_dataset_rele(ds, FTAG);
3218                 return (SET_ERROR(EINVAL));
3219         }
3220 
3221         error = dsl_prop_predict(ds->ds_dir,
3222             zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
3223             ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
3224         if (error != 0) {
3225                 dsl_dataset_rele(ds, FTAG);
3226                 return (error);
3227         }
3228 
3229         /*
3230          * If we are doing the preliminary check in open context, the
3231          * space estimates may be inaccurate.
3232          */
3233         if (!dmu_tx_is_syncing(tx)) {
3234                 dsl_dataset_rele(ds, FTAG);
3235                 return (0);
3236         }
3237 
3238         mutex_enter(&ds->ds_lock);
3239         if (!DS_UNIQUE_IS_ACCURATE(ds))
3240                 dsl_dataset_recalc_head_uniq(ds);
3241         unique = dsl_dataset_phys(ds)->ds_unique_bytes;
3242         mutex_exit(&ds->ds_lock);
3243 
3244         if (MAX(unique, newval) > MAX(unique, ds->ds_reserved)) {
3245                 uint64_t delta = MAX(unique, newval) -
3246                     MAX(unique, ds->ds_reserved);
3247 
3248                 if (delta >
3249                     dsl_dir_space_available(ds->ds_dir, NULL, 0, B_TRUE) ||
3250                     (ds->ds_quota > 0 && newval > ds->ds_quota)) {
3251                         dsl_dataset_rele(ds, FTAG);
3252                         return (SET_ERROR(ENOSPC));
3253                 }
3254         }
3255 
3256         dsl_dataset_rele(ds, FTAG);
3257         return (0);
3258 }
3259 
3260 void
3261 dsl_dataset_set_refreservation_sync_impl(dsl_dataset_t *ds,
3262     zprop_source_t source, uint64_t value, dmu_tx_t *tx)
3263 {
3264         uint64_t newval;
3265         uint64_t unique;
3266         int64_t delta;
3267 
3268         dsl_prop_set_sync_impl(ds, zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
3269             source, sizeof (value), 1, &value, tx);
3270 
3271         VERIFY0(dsl_prop_get_int_ds(ds,
3272             zfs_prop_to_name(ZFS_PROP_REFRESERVATION), &newval));
3273 
3274         dmu_buf_will_dirty(ds->ds_dbuf, tx);
3275         mutex_enter(&ds->ds_dir->dd_lock);
3276         mutex_enter(&ds->ds_lock);
3277         ASSERT(DS_UNIQUE_IS_ACCURATE(ds));
3278         unique = dsl_dataset_phys(ds)->ds_unique_bytes;
3279         delta = MAX(0, (int64_t)(newval - unique)) -
3280             MAX(0, (int64_t)(ds->ds_reserved - unique));
3281         ds->ds_reserved = newval;
3282         mutex_exit(&ds->ds_lock);
3283 
3284         dsl_dir_diduse_space(ds->ds_dir, DD_USED_REFRSRV, delta, 0, 0, tx);
3285         mutex_exit(&ds->ds_dir->dd_lock);
3286 }
3287 
3288 static void
3289 dsl_dataset_set_refreservation_sync(void *arg, dmu_tx_t *tx)
3290 {
3291         dsl_dataset_set_qr_arg_t *ddsqra = arg;
3292         dsl_pool_t *dp = dmu_tx_pool(tx);
3293         dsl_dataset_t *ds;
3294 
3295         VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
3296         dsl_dataset_set_refreservation_sync_impl(ds,
3297             ddsqra->ddsqra_source, ddsqra->ddsqra_value, tx);
3298         dsl_dataset_rele(ds, FTAG);
3299 }
3300 
3301 int
3302 dsl_dataset_set_refreservation(const char *dsname, zprop_source_t source,
3303     uint64_t refreservation)
3304 {
3305         dsl_dataset_set_qr_arg_t ddsqra;
3306 
3307         ddsqra.ddsqra_name = dsname;
3308         ddsqra.ddsqra_source = source;
3309         ddsqra.ddsqra_value = refreservation;
3310 
3311         return (dsl_sync_task(dsname, dsl_dataset_set_refreservation_check,
3312             dsl_dataset_set_refreservation_sync, &ddsqra,
3313             0, ZFS_SPACE_CHECK_NONE));
3314 }
3315 
3316 /*
3317  * Return (in *usedp) the amount of space written in new that is not
3318  * present in oldsnap.  New may be a snapshot or the head.  Old must be
3319  * a snapshot before new, in new's filesystem (or its origin).  If not then
3320  * fail and return EINVAL.
3321  *
3322  * The written space is calculated by considering two components:  First, we
3323  * ignore any freed space, and calculate the written as new's used space
3324  * minus old's used space.  Next, we add in the amount of space that was freed
3325  * between the two snapshots, thus reducing new's used space relative to old's.
3326  * Specifically, this is the space that was born before old->ds_creation_txg,
3327  * and freed before new (ie. on new's deadlist or a previous deadlist).
3328  *
3329  * space freed                         [---------------------]
3330  * snapshots                       ---O-------O--------O-------O------
3331  *                                         oldsnap            new
3332  */
3333 int
3334 dsl_dataset_space_written(dsl_dataset_t *oldsnap, dsl_dataset_t *new,
3335     uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
3336 {
3337         int err = 0;
3338         uint64_t snapobj;
3339         dsl_pool_t *dp = new->ds_dir->dd_pool;
3340 
3341         ASSERT(dsl_pool_config_held(dp));
3342 
3343         *usedp = 0;
3344         *usedp += dsl_dataset_phys(new)->ds_referenced_bytes;
3345         *usedp -= dsl_dataset_phys(oldsnap)->ds_referenced_bytes;
3346 
3347         *compp = 0;
3348         *compp += dsl_dataset_phys(new)->ds_compressed_bytes;
3349         *compp -= dsl_dataset_phys(oldsnap)->ds_compressed_bytes;
3350 
3351         *uncompp = 0;
3352         *uncompp += dsl_dataset_phys(new)->ds_uncompressed_bytes;
3353         *uncompp -= dsl_dataset_phys(oldsnap)->ds_uncompressed_bytes;
3354 
3355         snapobj = new->ds_object;
3356         while (snapobj != oldsnap->ds_object) {
3357                 dsl_dataset_t *snap;
3358                 uint64_t used, comp, uncomp;
3359 
3360                 if (snapobj == new->ds_object) {
3361                         snap = new;
3362                 } else {
3363                         err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &snap);
3364                         if (err != 0)
3365                                 break;
3366                 }
3367 
3368                 if (dsl_dataset_phys(snap)->ds_prev_snap_txg ==
3369                     dsl_dataset_phys(oldsnap)->ds_creation_txg) {
3370                         /*
3371                          * The blocks in the deadlist can not be born after
3372                          * ds_prev_snap_txg, so get the whole deadlist space,
3373                          * which is more efficient (especially for old-format
3374                          * deadlists).  Unfortunately the deadlist code
3375                          * doesn't have enough information to make this
3376                          * optimization itself.
3377                          */
3378                         dsl_deadlist_space(&snap->ds_deadlist,
3379                             &used, &comp, &uncomp);
3380                 } else {
3381                         dsl_deadlist_space_range(&snap->ds_deadlist,
3382                             0, dsl_dataset_phys(oldsnap)->ds_creation_txg,
3383                             &used, &comp, &uncomp);
3384                 }
3385                 *usedp += used;
3386                 *compp += comp;
3387                 *uncompp += uncomp;
3388 
3389                 /*
3390                  * If we get to the beginning of the chain of snapshots
3391                  * (ds_prev_snap_obj == 0) before oldsnap, then oldsnap
3392                  * was not a snapshot of/before new.
3393                  */
3394                 snapobj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
3395                 if (snap != new)
3396                         dsl_dataset_rele(snap, FTAG);
3397                 if (snapobj == 0) {
3398                         err = SET_ERROR(EINVAL);
3399                         break;
3400                 }
3401 
3402         }
3403         return (err);
3404 }
3405 
3406 /*
3407  * Return (in *usedp) the amount of space that will be reclaimed if firstsnap,
3408  * lastsnap, and all snapshots in between are deleted.
3409  *
3410  * blocks that would be freed            [---------------------------]
3411  * snapshots                       ---O-------O--------O-------O--------O
3412  *                                        firstsnap        lastsnap
3413  *
3414  * This is the set of blocks that were born after the snap before firstsnap,
3415  * (birth > firstsnap->prev_snap_txg) and died before the snap after the
3416  * last snap (ie, is on lastsnap->ds_next->ds_deadlist or an earlier deadlist).
3417  * We calculate this by iterating over the relevant deadlists (from the snap
3418  * after lastsnap, backward to the snap after firstsnap), summing up the
3419  * space on the deadlist that was born after the snap before firstsnap.
3420  */
3421 int
3422 dsl_dataset_space_wouldfree(dsl_dataset_t *firstsnap,
3423     dsl_dataset_t *lastsnap,
3424     uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
3425 {
3426         int err = 0;
3427         uint64_t snapobj;
3428         dsl_pool_t *dp = firstsnap->ds_dir->dd_pool;
3429 
3430         ASSERT(firstsnap->ds_is_snapshot);
3431         ASSERT(lastsnap->ds_is_snapshot);
3432 
3433         /*
3434          * Check that the snapshots are in the same dsl_dir, and firstsnap
3435          * is before lastsnap.
3436          */
3437         if (firstsnap->ds_dir != lastsnap->ds_dir ||
3438             dsl_dataset_phys(firstsnap)->ds_creation_txg >
3439             dsl_dataset_phys(lastsnap)->ds_creation_txg)
3440                 return (SET_ERROR(EINVAL));
3441 
3442         *usedp = *compp = *uncompp = 0;
3443 
3444         snapobj = dsl_dataset_phys(lastsnap)->ds_next_snap_obj;
3445         while (snapobj != firstsnap->ds_object) {
3446                 dsl_dataset_t *ds;
3447                 uint64_t used, comp, uncomp;
3448 
3449                 err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &ds);
3450                 if (err != 0)
3451                         break;
3452 
3453                 dsl_deadlist_space_range(&ds->ds_deadlist,
3454                     dsl_dataset_phys(firstsnap)->ds_prev_snap_txg, UINT64_MAX,
3455                     &used, &comp, &uncomp);
3456                 *usedp += used;
3457                 *compp += comp;
3458                 *uncompp += uncomp;
3459 
3460                 snapobj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
3461                 ASSERT3U(snapobj, !=, 0);
3462                 dsl_dataset_rele(ds, FTAG);
3463         }
3464         return (err);
3465 }
3466 
3467 /*
3468  * Return TRUE if 'earlier' is an earlier snapshot in 'later's timeline.
3469  * For example, they could both be snapshots of the same filesystem, and
3470  * 'earlier' is before 'later'.  Or 'earlier' could be the origin of
3471  * 'later's filesystem.  Or 'earlier' could be an older snapshot in the origin's
3472  * filesystem.  Or 'earlier' could be the origin's origin.
3473  *
3474  * If non-zero, earlier_txg is used instead of earlier's ds_creation_txg.
3475  */
3476 boolean_t
3477 dsl_dataset_is_before(dsl_dataset_t *later, dsl_dataset_t *earlier,
3478     uint64_t earlier_txg)
3479 {
3480         dsl_pool_t *dp = later->ds_dir->dd_pool;
3481         int error;
3482         boolean_t ret;
3483 
3484         ASSERT(dsl_pool_config_held(dp));
3485         ASSERT(earlier->ds_is_snapshot || earlier_txg != 0);
3486 
3487         if (earlier_txg == 0)
3488                 earlier_txg = dsl_dataset_phys(earlier)->ds_creation_txg;
3489 
3490         if (later->ds_is_snapshot &&
3491             earlier_txg >= dsl_dataset_phys(later)->ds_creation_txg)
3492                 return (B_FALSE);
3493 
3494         if (later->ds_dir == earlier->ds_dir)
3495                 return (B_TRUE);
3496         if (!dsl_dir_is_clone(later->ds_dir))
3497                 return (B_FALSE);
3498 
3499         if (dsl_dir_phys(later->ds_dir)->dd_origin_obj == earlier->ds_object)
3500                 return (B_TRUE);
3501         dsl_dataset_t *origin;
3502         error = dsl_dataset_hold_obj(dp,
3503             dsl_dir_phys(later->ds_dir)->dd_origin_obj, FTAG, &origin);
3504         if (error != 0)
3505                 return (B_FALSE);
3506         ret = dsl_dataset_is_before(origin, earlier, earlier_txg);
3507         dsl_dataset_rele(origin, FTAG);
3508         return (ret);
3509 }
3510 
3511 void
3512 dsl_dataset_zapify(dsl_dataset_t *ds, dmu_tx_t *tx)
3513 {
3514         objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
3515         dmu_object_zapify(mos, ds->ds_object, DMU_OT_DSL_DATASET, tx);
3516 }
3517 
3518 boolean_t
3519 dsl_dataset_is_zapified(dsl_dataset_t *ds)
3520 {
3521         dmu_object_info_t doi;
3522 
3523         dmu_object_info_from_db(ds->ds_dbuf, &doi);
3524         return (doi.doi_type == DMU_OTN_ZAP_METADATA);
3525 }
3526 
3527 boolean_t
3528 dsl_dataset_has_resume_receive_state(dsl_dataset_t *ds)
3529 {
3530         return (dsl_dataset_is_zapified(ds) &&
3531             zap_contains(ds->ds_dir->dd_pool->dp_meta_objset,
3532             ds->ds_object, DS_FIELD_RESUME_TOGUID) == 0);
3533 }