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, 2017 by Delphix. All rights reserved.
  24  * Copyright (c) 2013 Steven Hartland. All rights reserved.
  25  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
  26  * Copyright (c) 2014 Integros [integros.com]
  27  * Copyright 2016 Nexenta Systems, Inc. All rights reserved.
  28  */
  29 
  30 #include <sys/autosnap.h>
  31 #include <sys/dsl_pool.h>
  32 #include <sys/dsl_dataset.h>
  33 #include <sys/dsl_prop.h>
  34 #include <sys/dsl_dir.h>
  35 #include <sys/dsl_synctask.h>
  36 #include <sys/dsl_dataset.h>
  37 #include <sys/dsl_scan.h>
  38 #include <sys/dnode.h>
  39 #include <sys/dmu_tx.h>
  40 #include <sys/dmu_objset.h>
  41 #include <sys/dmu_traverse.h>
  42 #include <sys/arc.h>
  43 #include <sys/zap.h>
  44 #include <sys/zio.h>
  45 #include <sys/zfs_context.h>
  46 #include <sys/fs/zfs.h>
  47 #include <sys/zfs_znode.h>
  48 #include <sys/spa_impl.h>
  49 #include <sys/dsl_deadlist.h>
  50 #include <sys/bptree.h>
  51 #include <sys/zfeature.h>
  52 #include <sys/zil_impl.h>
  53 #include <sys/dsl_userhold.h>
  54 
  55 #include <sys/wbc.h>
  56 #include <sys/time.h>
  57 
  58 /*
  59  * ZFS Write Throttle
  60  * ------------------
  61  *
  62  * ZFS must limit the rate of incoming writes to the rate at which it is able
  63  * to sync data modifications to the backend storage. Throttling by too much
  64  * creates an artificial limit; throttling by too little can only be sustained
  65  * for short periods and would lead to highly lumpy performance. On a per-pool
  66  * basis, ZFS tracks the amount of modified (dirty) data. As operations change
  67  * data, the amount of dirty data increases; as ZFS syncs out data, the amount
  68  * of dirty data decreases. When the amount of dirty data exceeds a
  69  * predetermined threshold further modifications are blocked until the amount
  70  * of dirty data decreases (as data is synced out).
  71  *
  72  * The limit on dirty data is tunable, and should be adjusted according to
  73  * both the IO capacity and available memory of the system. The larger the
  74  * window, the more ZFS is able to aggregate and amortize metadata (and data)
  75  * changes. However, memory is a limited resource, and allowing for more dirty
  76  * data comes at the cost of keeping other useful data in memory (for example
  77  * ZFS data cached by the ARC).
  78  *
  79  * Implementation
  80  *
  81  * As buffers are modified dsl_pool_willuse_space() increments both the per-
  82  * txg (dp_dirty_pertxg[]) and poolwide (dp_dirty_total) accounting of
  83  * dirty space used; dsl_pool_dirty_space() decrements those values as data
  84  * is synced out from dsl_pool_sync(). While only the poolwide value is
  85  * relevant, the per-txg value is useful for debugging. The tunable
  86  * zfs_dirty_data_max determines the dirty space limit. Once that value is
  87  * exceeded, new writes are halted until space frees up.
  88  *
  89  * The zfs_dirty_data_sync tunable dictates the threshold at which we
  90  * ensure that there is a txg syncing (see the comment in txg.c for a full
  91  * description of transaction group stages).
  92  *
  93  * The IO scheduler uses both the dirty space limit and current amount of
  94  * dirty data as inputs. Those values affect the number of concurrent IOs ZFS
  95  * issues. See the comment in vdev_queue.c for details of the IO scheduler.
  96  *
  97  * The delay is also calculated based on the amount of dirty data.  See the
  98  * comment above dmu_tx_delay() for details.
  99  */
 100 
 101 /*
 102  * zfs_dirty_data_max will be set to zfs_dirty_data_max_percent% of all memory,
 103  * capped at zfs_dirty_data_max_max.  It can also be overridden in /etc/system.
 104  */
 105 uint64_t zfs_dirty_data_max;
 106 uint64_t zfs_dirty_data_max_max = 4ULL * 1024 * 1024 * 1024;
 107 int zfs_dirty_data_max_percent = 10;
 108 
 109 /*
 110  * If there is at least this much dirty data, push out a txg.
 111  */
 112 uint64_t zfs_dirty_data_sync = 64 * 1024 * 1024;
 113 
 114 /*
 115  * Once there is this amount of dirty data, the dmu_tx_delay() will kick in
 116  * and delay each transaction.
 117  * This value should be >= zfs_vdev_async_write_active_max_dirty_percent.
 118  */
 119 int zfs_delay_min_dirty_percent = 60;
 120 
 121 /*
 122  * This controls how quickly the delay approaches infinity.
 123  * Larger values cause it to delay more for a given amount of dirty data.
 124  * Therefore larger values will cause there to be less dirty data for a
 125  * given throughput.
 126  *
 127  * For the smoothest delay, this value should be about 1 billion divided
 128  * by the maximum number of operations per second.  This will smoothly
 129  * handle between 10x and 1/10th this number.
 130  *
 131  * Note: zfs_delay_scale * zfs_dirty_data_max must be < 2^64, due to the
 132  * multiply in dmu_tx_delay().
 133  */
 134 uint64_t zfs_delay_scale = 1000 * 1000 * 1000 / 2000;
 135 
 136 /*
 137  * This determines the number of threads used by the dp_sync_taskq.
 138  */
 139 int zfs_sync_taskq_batch_pct = 75;
 140 
 141 /*
 142  * These tunables determine the behavior of how zil_itxg_clean() is
 143  * called via zil_clean() in the context of spa_sync(). When an itxg
 144  * list needs to be cleaned, TQ_NOSLEEP will be used when dispatching.
 145  * If the dispatch fails, the call to zil_itxg_clean() will occur
 146  * synchronously in the context of spa_sync(), which can negatively
 147  * impact the performance of spa_sync() (e.g. in the case of the itxg
 148  * list having a large number of itxs that needs to be cleaned).
 149  *
 150  * Thus, these tunables can be used to manipulate the behavior of the
 151  * taskq used by zil_clean(); they determine the number of taskq entries
 152  * that are pre-populated when the taskq is first created (via the
 153  * "zfs_zil_clean_taskq_minalloc" tunable) and the maximum number of
 154  * taskq entries that are cached after an on-demand allocation (via the
 155  * "zfs_zil_clean_taskq_maxalloc").
 156  *
 157  * The idea being, we want to try reasonably hard to ensure there will
 158  * already be a taskq entry pre-allocated by the time that it is needed
 159  * by zil_clean(). This way, we can avoid the possibility of an
 160  * on-demand allocation of a new taskq entry from failing, which would
 161  * result in zil_itxg_clean() being called synchronously from zil_clean()
 162  * (which can adversely affect performance of spa_sync()).
 163  *
 164  * Additionally, the number of threads used by the taskq can be
 165  * configured via the "zfs_zil_clean_taskq_nthr_pct" tunable.
 166  */
 167 int zfs_zil_clean_taskq_nthr_pct = 100;
 168 int zfs_zil_clean_taskq_minalloc = 1024;
 169 int zfs_zil_clean_taskq_maxalloc = 1024 * 1024;
 170 
 171 /*
 172  * Tunable to control max number of tasks available for processing of
 173  * deferred deletes.
 174  */
 175 int zfs_vn_rele_max_tasks = 256;
 176 
 177 int
 178 dsl_pool_open_special_dir(dsl_pool_t *dp, const char *name, dsl_dir_t **ddp)
 179 {
 180         uint64_t obj;
 181         int err;
 182 
 183         err = zap_lookup(dp->dp_meta_objset,
 184             dsl_dir_phys(dp->dp_root_dir)->dd_child_dir_zapobj,
 185             name, sizeof (obj), 1, &obj);
 186         if (err)
 187                 return (err);
 188 
 189         return (dsl_dir_hold_obj(dp, obj, name, dp, ddp));
 190 }
 191 
 192 static dsl_pool_t *
 193 dsl_pool_open_impl(spa_t *spa, uint64_t txg)
 194 {
 195         dsl_pool_t *dp;
 196         blkptr_t *bp = spa_get_rootblkptr(spa);
 197 
 198         dp = kmem_zalloc(sizeof (dsl_pool_t), KM_SLEEP);
 199         dp->dp_spa = spa;
 200         dp->dp_meta_rootbp = *bp;
 201         rrw_init(&dp->dp_config_rwlock, B_TRUE);
 202 
 203         dp->dp_sync_history[0] = dp->dp_sync_history[1] = 0;
 204 
 205         txg_init(dp, txg);
 206 
 207         txg_list_create(&dp->dp_dirty_datasets, spa,
 208             offsetof(dsl_dataset_t, ds_dirty_link));
 209         txg_list_create(&dp->dp_dirty_zilogs, spa,
 210             offsetof(zilog_t, zl_dirty_link));
 211         txg_list_create(&dp->dp_dirty_dirs, spa,
 212             offsetof(dsl_dir_t, dd_dirty_link));
 213         txg_list_create(&dp->dp_sync_tasks, spa,
 214             offsetof(dsl_sync_task_t, dst_node));
 215 
 216         dp->dp_sync_taskq = taskq_create("dp_sync_taskq",
 217             zfs_sync_taskq_batch_pct, minclsyspri, 1, INT_MAX,
 218             TASKQ_THREADS_CPU_PCT);
 219 
 220         dp->dp_zil_clean_taskq = taskq_create("dp_zil_clean_taskq",
 221             zfs_zil_clean_taskq_nthr_pct, minclsyspri,
 222             zfs_zil_clean_taskq_minalloc,
 223             zfs_zil_clean_taskq_maxalloc,
 224             TASKQ_PREPOPULATE | TASKQ_THREADS_CPU_PCT);
 225 
 226         mutex_init(&dp->dp_lock, NULL, MUTEX_DEFAULT, NULL);
 227         cv_init(&dp->dp_spaceavail_cv, NULL, CV_DEFAULT, NULL);
 228 
 229         dp->dp_vnrele_taskq = taskq_create("zfs_vn_rele_taskq",
 230             zfs_vn_rele_max_tasks, minclsyspri,
 231             1, zfs_vn_rele_max_tasks, TASKQ_DYNAMIC);
 232 
 233         return (dp);
 234 }
 235 
 236 int
 237 dsl_pool_init(spa_t *spa, uint64_t txg, dsl_pool_t **dpp)
 238 {
 239         int err;
 240         dsl_pool_t *dp = dsl_pool_open_impl(spa, txg);
 241 
 242         err = dmu_objset_open_impl(spa, NULL, &dp->dp_meta_rootbp,
 243             &dp->dp_meta_objset);
 244         if (err != 0)
 245                 dsl_pool_close(dp);
 246         else
 247                 *dpp = dp;
 248 
 249         return (err);
 250 }
 251 
 252 int
 253 dsl_pool_open(dsl_pool_t *dp)
 254 {
 255         int err;
 256         dsl_dir_t *dd;
 257         dsl_dataset_t *ds;
 258         uint64_t obj;
 259 
 260         rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
 261         err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
 262             DMU_POOL_ROOT_DATASET, sizeof (uint64_t), 1,
 263             &dp->dp_root_dir_obj);
 264         if (err)
 265                 goto out;
 266 
 267         err = dsl_dir_hold_obj(dp, dp->dp_root_dir_obj,
 268             NULL, dp, &dp->dp_root_dir);
 269         if (err)
 270                 goto out;
 271 
 272         err = dsl_pool_open_special_dir(dp, MOS_DIR_NAME, &dp->dp_mos_dir);
 273         if (err)
 274                 goto out;
 275 
 276         if (spa_version(dp->dp_spa) >= SPA_VERSION_ORIGIN) {
 277                 err = dsl_pool_open_special_dir(dp, ORIGIN_DIR_NAME, &dd);
 278                 if (err)
 279                         goto out;
 280                 err = dsl_dataset_hold_obj(dp,
 281                     dsl_dir_phys(dd)->dd_head_dataset_obj, FTAG, &ds);
 282                 if (err == 0) {
 283                         err = dsl_dataset_hold_obj(dp,
 284                             dsl_dataset_phys(ds)->ds_prev_snap_obj, dp,
 285                             &dp->dp_origin_snap);
 286                         dsl_dataset_rele(ds, FTAG);
 287                 }
 288                 dsl_dir_rele(dd, dp);
 289                 if (err)
 290                         goto out;
 291         }
 292 
 293         if (spa_version(dp->dp_spa) >= SPA_VERSION_DEADLISTS) {
 294                 err = dsl_pool_open_special_dir(dp, FREE_DIR_NAME,
 295                     &dp->dp_free_dir);
 296                 if (err)
 297                         goto out;
 298 
 299                 err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
 300                     DMU_POOL_FREE_BPOBJ, sizeof (uint64_t), 1, &obj);
 301                 if (err)
 302                         goto out;
 303                 VERIFY0(bpobj_open(&dp->dp_free_bpobj,
 304                     dp->dp_meta_objset, obj));
 305         }
 306 
 307         /*
 308          * Note: errors ignored, because the leak dir will not exist if we
 309          * have not encountered a leak yet.
 310          */
 311         (void) dsl_pool_open_special_dir(dp, LEAK_DIR_NAME,
 312             &dp->dp_leak_dir);
 313 
 314         if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_ASYNC_DESTROY)) {
 315                 err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
 316                     DMU_POOL_BPTREE_OBJ, sizeof (uint64_t), 1,
 317                     &dp->dp_bptree_obj);
 318                 if (err != 0)
 319                         goto out;
 320         }
 321 
 322         if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_EMPTY_BPOBJ)) {
 323                 err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
 324                     DMU_POOL_EMPTY_BPOBJ, sizeof (uint64_t), 1,
 325                     &dp->dp_empty_bpobj);
 326                 if (err != 0)
 327                         goto out;
 328         }
 329 
 330         err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
 331             DMU_POOL_TMP_USERREFS, sizeof (uint64_t), 1,
 332             &dp->dp_tmp_userrefs_obj);
 333         if (err == ENOENT)
 334                 err = 0;
 335         if (err)
 336                 goto out;
 337 
 338         err = dsl_scan_init(dp, dp->dp_tx.tx_open_txg);
 339 
 340 out:
 341         rrw_exit(&dp->dp_config_rwlock, FTAG);
 342         return (err);
 343 }
 344 
 345 void
 346 dsl_pool_close(dsl_pool_t *dp)
 347 {
 348         /*
 349          * Drop our references from dsl_pool_open().
 350          *
 351          * Since we held the origin_snap from "syncing" context (which
 352          * includes pool-opening context), it actually only got a "ref"
 353          * and not a hold, so just drop that here.
 354          */
 355         if (dp->dp_origin_snap)
 356                 dsl_dataset_rele(dp->dp_origin_snap, dp);
 357         if (dp->dp_mos_dir)
 358                 dsl_dir_rele(dp->dp_mos_dir, dp);
 359         if (dp->dp_free_dir)
 360                 dsl_dir_rele(dp->dp_free_dir, dp);
 361         if (dp->dp_leak_dir)
 362                 dsl_dir_rele(dp->dp_leak_dir, dp);
 363         if (dp->dp_root_dir)
 364                 dsl_dir_rele(dp->dp_root_dir, dp);
 365 
 366         bpobj_close(&dp->dp_free_bpobj);
 367 
 368         /* undo the dmu_objset_open_impl(mos) from dsl_pool_open() */
 369         if (dp->dp_meta_objset)
 370                 dmu_objset_evict(dp->dp_meta_objset);
 371 
 372         txg_list_destroy(&dp->dp_dirty_datasets);
 373         txg_list_destroy(&dp->dp_dirty_zilogs);
 374         txg_list_destroy(&dp->dp_sync_tasks);
 375         txg_list_destroy(&dp->dp_dirty_dirs);
 376 
 377         taskq_destroy(dp->dp_zil_clean_taskq);
 378         taskq_destroy(dp->dp_sync_taskq);
 379 
 380         /*
 381          * We can't set retry to TRUE since we're explicitly specifying
 382          * a spa to flush. This is good enough; any missed buffers for
 383          * this spa won't cause trouble, and they'll eventually fall
 384          * out of the ARC just like any other unused buffer.
 385          */
 386         arc_flush(dp->dp_spa, B_FALSE);
 387         txg_fini(dp);
 388         dsl_scan_fini(dp);
 389         dmu_buf_user_evict_wait();
 390 
 391         rrw_destroy(&dp->dp_config_rwlock);
 392         mutex_destroy(&dp->dp_lock);
 393         taskq_destroy(dp->dp_vnrele_taskq);
 394         if (dp->dp_blkstats)
 395                 kmem_free(dp->dp_blkstats, sizeof (zfs_all_blkstats_t));
 396         kmem_free(dp, sizeof (dsl_pool_t));
 397 }
 398 
 399 dsl_pool_t *
 400 dsl_pool_create(spa_t *spa, nvlist_t *zplprops, uint64_t txg)
 401 {
 402         int err;
 403         dsl_pool_t *dp = dsl_pool_open_impl(spa, txg);
 404         dmu_tx_t *tx = dmu_tx_create_assigned(dp, txg);
 405         dsl_dataset_t *ds;
 406         uint64_t obj;
 407 
 408         rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
 409 
 410         /* create and open the MOS (meta-objset) */
 411         dp->dp_meta_objset = dmu_objset_create_impl(spa,
 412             NULL, &dp->dp_meta_rootbp, DMU_OST_META, tx);
 413 
 414         /* create the pool directory */
 415         err = zap_create_claim(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
 416             DMU_OT_OBJECT_DIRECTORY, DMU_OT_NONE, 0, tx);
 417         ASSERT0(err);
 418 
 419         /* Initialize scan structures */
 420         VERIFY0(dsl_scan_init(dp, txg));
 421 
 422         /* create and open the root dir */
 423         dp->dp_root_dir_obj = dsl_dir_create_sync(dp, NULL, NULL, tx);
 424         VERIFY0(dsl_dir_hold_obj(dp, dp->dp_root_dir_obj,
 425             NULL, dp, &dp->dp_root_dir));
 426 
 427         /* create and open the meta-objset dir */
 428         (void) dsl_dir_create_sync(dp, dp->dp_root_dir, MOS_DIR_NAME, tx);
 429         VERIFY0(dsl_pool_open_special_dir(dp,
 430             MOS_DIR_NAME, &dp->dp_mos_dir));
 431 
 432         if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
 433                 /* create and open the free dir */
 434                 (void) dsl_dir_create_sync(dp, dp->dp_root_dir,
 435                     FREE_DIR_NAME, tx);
 436                 VERIFY0(dsl_pool_open_special_dir(dp,
 437                     FREE_DIR_NAME, &dp->dp_free_dir));
 438 
 439                 /* create and open the free_bplist */
 440                 obj = bpobj_alloc(dp->dp_meta_objset, SPA_OLD_MAXBLOCKSIZE, tx);
 441                 VERIFY(zap_add(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
 442                     DMU_POOL_FREE_BPOBJ, sizeof (uint64_t), 1, &obj, tx) == 0);
 443                 VERIFY0(bpobj_open(&dp->dp_free_bpobj,
 444                     dp->dp_meta_objset, obj));
 445         }
 446 
 447         if (spa_version(spa) >= SPA_VERSION_DSL_SCRUB)
 448                 dsl_pool_create_origin(dp, tx);
 449 
 450         /* create the root dataset */
 451         obj = dsl_dataset_create_sync_dd(dp->dp_root_dir, NULL, 0, tx);
 452 
 453         /* create the root objset */
 454         VERIFY0(dsl_dataset_hold_obj(dp, obj, FTAG, &ds));
 455 #ifdef _KERNEL
 456         {
 457                 objset_t *os;
 458                 rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
 459                 os = dmu_objset_create_impl(dp->dp_spa, ds,
 460                     dsl_dataset_get_blkptr(ds), DMU_OST_ZFS, tx);
 461                 rrw_exit(&ds->ds_bp_rwlock, FTAG);
 462                 zfs_create_fs(os, kcred, zplprops, tx);
 463         }
 464 #endif
 465         dsl_dataset_rele(ds, FTAG);
 466 
 467         dmu_tx_commit(tx);
 468 
 469         rrw_exit(&dp->dp_config_rwlock, FTAG);
 470 
 471         return (dp);
 472 }
 473 
 474 /*
 475  * Account for the meta-objset space in its placeholder dsl_dir.
 476  */
 477 void
 478 dsl_pool_mos_diduse_space(dsl_pool_t *dp,
 479     int64_t used, int64_t comp, int64_t uncomp)
 480 {
 481         ASSERT3U(comp, ==, uncomp); /* it's all metadata */
 482         mutex_enter(&dp->dp_lock);
 483         dp->dp_mos_used_delta += used;
 484         dp->dp_mos_compressed_delta += comp;
 485         dp->dp_mos_uncompressed_delta += uncomp;
 486         mutex_exit(&dp->dp_lock);
 487 }
 488 
 489 static void
 490 dsl_pool_sync_mos(dsl_pool_t *dp, dmu_tx_t *tx)
 491 {
 492         zio_t *zio = zio_root(dp->dp_spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
 493         dmu_objset_sync(dp->dp_meta_objset, zio, tx);
 494         VERIFY0(zio_wait(zio));
 495         dprintf_bp(&dp->dp_meta_rootbp, "meta objset rootbp is %s", "");
 496         spa_set_rootblkptr(dp->dp_spa, &dp->dp_meta_rootbp);
 497 }
 498 
 499 static void
 500 dsl_pool_dirty_delta(dsl_pool_t *dp, int64_t delta)
 501 {
 502         ASSERT(MUTEX_HELD(&dp->dp_lock));
 503 
 504         if (delta < 0)
 505                 ASSERT3U(-delta, <=, dp->dp_dirty_total);
 506 
 507         dp->dp_dirty_total += delta;
 508 
 509         /*
 510          * Note: we signal even when increasing dp_dirty_total.
 511          * This ensures forward progress -- each thread wakes the next waiter.
 512          */
 513         if (dp->dp_dirty_total < zfs_dirty_data_max)
 514                 cv_signal(&dp->dp_spaceavail_cv);
 515 }
 516 
 517 void
 518 dsl_pool_sync(dsl_pool_t *dp, uint64_t txg)
 519 {
 520         zio_t *zio;
 521         dmu_tx_t *tx;
 522         dsl_dir_t *dd;
 523         dsl_dataset_t *ds;
 524         objset_t *mos = dp->dp_meta_objset;
 525         spa_t *spa = dp->dp_spa;
 526         list_t synced_datasets;
 527         dsl_sync_task_t *iter;
 528         boolean_t wbc_skip_txg = B_FALSE;
 529         boolean_t sync_ops = B_FALSE;
 530         boolean_t user_snap = B_FALSE;
 531         zfs_autosnap_t *autosnap = spa_get_autosnap(spa);
 532         boolean_t autosnap_initialized = autosnap->initialized;
 533         char snap[ZFS_MAX_DATASET_NAME_LEN];
 534 
 535         /* check if there are  ny sync ops in the txg */
 536         if (txg_list_head(&dp->dp_sync_tasks, txg) != NULL)
 537                 sync_ops = B_TRUE;
 538 
 539         /* check if there are user snaps in the txg */
 540         for (iter = txg_list_head(&dp->dp_sync_tasks, txg);
 541             iter != NULL;
 542             iter = txg_list_next(&dp->dp_sync_tasks, iter, txg)) {
 543                 if (iter->dst_syncfunc == dsl_dataset_snapshot_sync) {
 544                         user_snap = B_TRUE;
 545                         break;
 546                 }
 547         }
 548 
 549 
 550         list_create(&synced_datasets, sizeof (dsl_dataset_t),
 551             offsetof(dsl_dataset_t, ds_synced_link));
 552 
 553         tx = dmu_tx_create_assigned(dp, txg);
 554 
 555         (void) sprintf(snap, "%s%llu", AUTOSNAP_PREFIX,
 556             (unsigned long long int) txg);
 557 
 558         if (autosnap_initialized && spa->spa_sync_pass == 1) {
 559                 autosnap_zone_t *azone;
 560 
 561                 rrw_enter(&dp->dp_config_rwlock, RW_READER, FTAG);
 562                 mutex_enter(&autosnap->autosnap_lock);
 563 
 564                 /*
 565                  * WBC: the mechanism to ensure all WBC-ed dirty datasets
 566                  * are synchronously auto-snapshotted
 567                  * within (or by) the same TXG sync
 568                  * The "synchronicity" of the rightmost boundary of the WBC
 569                  * window is important to avoid used-space leakages
 570                  * on special vdev.
 571                  * Note that we skip here the WBC-ed datasets that are
 572                  * already fully migrated and don't have data on special
 573                  */
 574 
 575                 for (ds = txg_list_head(&dp->dp_dirty_datasets, txg);
 576                     ds != NULL;
 577                     ds = txg_list_next(&dp->dp_dirty_datasets, ds, txg)) {
 578                         char ds_name[ZFS_MAX_DATASET_NAME_LEN];
 579                         boolean_t wbc_azone;
 580 
 581                         dsl_dataset_name(ds, ds_name);
 582 
 583                         azone = autosnap_find_zone(autosnap, ds_name, B_TRUE);
 584                         if (azone == NULL)
 585                                 continue;
 586 
 587                         if ((azone->flags & AUTOSNAP_CREATOR) == 0)
 588                                 continue;
 589 
 590                         if (azone->created)
 591                                 continue;
 592 
 593                         azone->delayed = B_TRUE;
 594                         azone->dirty = B_TRUE;
 595                         wbc_azone = (azone->flags & AUTOSNAP_WBC) != 0;
 596 
 597                         if (autosnap_confirm_snap(azone, txg)) {
 598                                 if (!wbc_azone && !user_snap && !sync_ops) {
 599                                         autosnap_create_snapshot(azone,
 600                                             snap, dp, txg, tx);
 601                                 }
 602                         } else if (wbc_azone) {
 603                                 wbc_skip_txg = B_TRUE;
 604                         }
 605                 }
 606 
 607                 azone = list_head(&autosnap->autosnap_zones);
 608                 while (azone != NULL) {
 609                         boolean_t wbc_azone =
 610                             ((azone->flags & AUTOSNAP_WBC) != 0);
 611 
 612                         if (user_snap) {
 613                                 azone->delayed = B_TRUE;
 614                         } else if (!azone->dirty && azone->delayed) {
 615                                 if (autosnap_confirm_snap(azone, txg)) {
 616                                         if (!wbc_azone && !user_snap &&
 617                                             !sync_ops) {
 618                                                 autosnap_create_snapshot(azone,
 619                                                     snap, dp, txg, tx);
 620                                         }
 621                                 } else if (wbc_azone) {
 622                                         wbc_skip_txg = B_TRUE;
 623                                 }
 624                         }
 625 
 626                         azone = list_next(&autosnap->autosnap_zones, azone);
 627                 }
 628 
 629                 mutex_exit(&autosnap->autosnap_lock);
 630                 rrw_exit(&dp->dp_config_rwlock, FTAG);
 631         }
 632 
 633 
 634         /*
 635          * Write out all dirty blocks of dirty datasets.
 636          */
 637         zio = zio_root(dp->dp_spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
 638         while ((ds = txg_list_remove(&dp->dp_dirty_datasets, txg)) != NULL) {
 639 
 640                 /*
 641                  * We must not sync any non-MOS datasets twice, because
 642                  * we may have taken a snapshot of them.  However, we
 643                  * may sync newly-created datasets on pass 2.
 644                  */
 645                 ASSERT(!list_link_active(&ds->ds_synced_link));
 646                 list_insert_tail(&synced_datasets, ds);
 647                 dsl_dataset_sync(ds, zio, tx);
 648         }
 649 
 650         VERIFY0(zio_wait(zio));
 651 
 652         if (autosnap_initialized && spa->spa_sync_pass == 1 &&
 653             !user_snap) {
 654                 autosnap_zone_t *azone;
 655 
 656                 rrw_enter(&dp->dp_config_rwlock, RW_READER, FTAG);
 657                 mutex_enter(&autosnap->autosnap_lock);
 658 
 659                 /*
 660                  * At this stage we are walking over all delayed zones
 661                  * to create autosnaps
 662                  */
 663 
 664                 azone = list_head(&autosnap->autosnap_zones);
 665                 while (azone != NULL) {
 666                         boolean_t skip_zone =
 667                             ((azone->flags & AUTOSNAP_CREATOR) == 0);
 668 
 669                         if (azone->delayed && !skip_zone) {
 670                                 boolean_t wbc_azone =
 671                                     ((azone->flags & AUTOSNAP_WBC) != 0);
 672 
 673                                 if ((!wbc_azone || !wbc_skip_txg) &&
 674                                     autosnap_confirm_snap(azone, txg)) {
 675                                         autosnap_create_snapshot(azone,
 676                                             snap, dp, txg, tx);
 677                                 }
 678                         }
 679 
 680                         if (skip_zone)
 681                                 azone->delayed = B_FALSE;
 682 
 683                         azone = list_next(&autosnap->autosnap_zones, azone);
 684                 }
 685 
 686                 mutex_exit(&autosnap->autosnap_lock);
 687                 rrw_exit(&dp->dp_config_rwlock, FTAG);
 688         }
 689 
 690         /*
 691          * We have written all of the accounted dirty data, so our
 692          * dp_space_towrite should now be zero.  However, some seldom-used
 693          * code paths do not adhere to this (e.g. dbuf_undirty(), also
 694          * rounding error in dbuf_write_physdone).
 695          * Shore up the accounting of any dirtied space now.
 696          */
 697         dsl_pool_undirty_space(dp, dp->dp_dirty_pertxg[txg & TXG_MASK], txg);
 698 
 699         /*
 700          * Update the long range free counter after
 701          * we're done syncing user data
 702          */
 703         mutex_enter(&dp->dp_lock);
 704         ASSERT(spa_sync_pass(dp->dp_spa) == 1 ||
 705             dp->dp_long_free_dirty_pertxg[txg & TXG_MASK] == 0);
 706         dp->dp_long_freeing_total -=
 707             dp->dp_long_free_dirty_pertxg[txg & TXG_MASK];
 708         dp->dp_long_free_dirty_pertxg[txg & TXG_MASK] = 0;
 709         mutex_exit(&dp->dp_lock);
 710 
 711         /*
 712          * After the data blocks have been written (ensured by the zio_wait()
 713          * above), update the user/group space accounting.  This happens
 714          * in tasks dispatched to dp_sync_taskq, so wait for them before
 715          * continuing.
 716          */
 717         for (ds = list_head(&synced_datasets); ds != NULL;
 718             ds = list_next(&synced_datasets, ds)) {
 719                 dmu_objset_do_userquota_updates(ds->ds_objset, tx);
 720         }
 721         taskq_wait(dp->dp_sync_taskq);
 722 
 723         /*
 724          * Sync the datasets again to push out the changes due to
 725          * userspace updates.  This must be done before we process the
 726          * sync tasks, so that any snapshots will have the correct
 727          * user accounting information (and we won't get confused
 728          * about which blocks are part of the snapshot).
 729          */
 730 
 731         zio = zio_root(dp->dp_spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
 732         while ((ds = txg_list_remove(&dp->dp_dirty_datasets, txg)) != NULL) {
 733                 ASSERT(list_link_active(&ds->ds_synced_link));
 734                 dmu_buf_rele(ds->ds_dbuf, ds);
 735                 dsl_dataset_sync(ds, zio, tx);
 736         }
 737         VERIFY0(zio_wait(zio));
 738 
 739         /*
 740          * Now that the datasets have been completely synced, we can
 741          * clean up our in-memory structures accumulated while syncing:
 742          *
 743          *  - move dead blocks from the pending deadlist to the on-disk deadlist
 744          *  - release hold from dsl_dataset_dirty()
 745          */
 746         while ((ds = list_remove_head(&synced_datasets)) != NULL) {
 747                 dsl_dataset_sync_done(ds, tx);
 748         }
 749         while ((dd = txg_list_remove(&dp->dp_dirty_dirs, txg)) != NULL) {
 750                 dsl_dir_sync(dd, tx);
 751         }
 752 
 753         /*
 754          * The MOS's space is accounted for in the pool/$MOS
 755          * (dp_mos_dir).  We can't modify the mos while we're syncing
 756          * it, so we remember the deltas and apply them here.
 757          */
 758         if (dp->dp_mos_used_delta != 0 || dp->dp_mos_compressed_delta != 0 ||
 759             dp->dp_mos_uncompressed_delta != 0) {
 760                 dsl_dir_diduse_space(dp->dp_mos_dir, DD_USED_HEAD,
 761                     dp->dp_mos_used_delta,
 762                     dp->dp_mos_compressed_delta,
 763                     dp->dp_mos_uncompressed_delta, tx);
 764                 dp->dp_mos_used_delta = 0;
 765                 dp->dp_mos_compressed_delta = 0;
 766                 dp->dp_mos_uncompressed_delta = 0;
 767         }
 768 
 769         if (!multilist_is_empty(mos->os_dirty_dnodes[txg & TXG_MASK])) {
 770                 dsl_pool_sync_mos(dp, tx);
 771         }
 772 
 773         /*
 774          * If we modify a dataset in the same txg that we want to destroy it,
 775          * its dsl_dir's dd_dbuf will be dirty, and thus have a hold on it.
 776          * dsl_dir_destroy_check() will fail if there are unexpected holds.
 777          * Therefore, we want to sync the MOS (thus syncing the dd_dbuf
 778          * and clearing the hold on it) before we process the sync_tasks.
 779          * The MOS data dirtied by the sync_tasks will be synced on the next
 780          * pass.
 781          */
 782 
 783         if (!txg_list_empty(&dp->dp_sync_tasks, txg)) {
 784                 dsl_sync_task_t *dst;
 785                 /*
 786                  * No more sync tasks should have been added while we
 787                  * were syncing.
 788                  */
 789                 ASSERT3U(spa_sync_pass(dp->dp_spa), ==, 1);
 790                 while ((dst = txg_list_remove(&dp->dp_sync_tasks, txg)) != NULL)
 791                         dsl_sync_task_sync(dst, tx);
 792         }
 793 
 794         if (spa_feature_is_active(spa, SPA_FEATURE_WBC)) {
 795                 wbc_trigger_wbcthread(dp->dp_spa,
 796                     ((dp->dp_sync_history[0] + dp->dp_sync_history[1]) / 2));
 797         }
 798 
 799         dmu_tx_commit(tx);
 800 
 801         DTRACE_PROBE2(dsl_pool_sync__done, dsl_pool_t *dp, dp, uint64_t, txg);
 802 }
 803 
 804 void
 805 dsl_pool_sync_done(dsl_pool_t *dp, uint64_t txg)
 806 {
 807         zilog_t *zilog;
 808 
 809         while (zilog = txg_list_head(&dp->dp_dirty_zilogs, txg)) {
 810                 dsl_dataset_t *ds = dmu_objset_ds(zilog->zl_os);
 811                 /*
 812                  * We don't remove the zilog from the dp_dirty_zilogs
 813                  * list until after we've cleaned it. This ensures that
 814                  * callers of zilog_is_dirty() receive an accurate
 815                  * answer when they are racing with the spa sync thread.
 816                  */
 817                 zil_clean(zilog, txg);
 818                 (void) txg_list_remove_this(&dp->dp_dirty_zilogs, zilog, txg);
 819                 ASSERT(!dmu_objset_is_dirty(zilog->zl_os, txg));
 820                 dmu_buf_rele(ds->ds_dbuf, zilog);
 821         }
 822         ASSERT(!dmu_objset_is_dirty(dp->dp_meta_objset, txg));
 823 }
 824 
 825 /*
 826  * TRUE if the current thread is the tx_sync_thread or if we
 827  * are being called from SPA context during pool initialization.
 828  */
 829 int
 830 dsl_pool_sync_context(dsl_pool_t *dp)
 831 {
 832         return (curthread == dp->dp_tx.tx_sync_thread ||
 833             spa_is_initializing(dp->dp_spa) ||
 834             taskq_member(dp->dp_sync_taskq, curthread));
 835 }
 836 
 837 uint64_t
 838 dsl_pool_adjustedsize(dsl_pool_t *dp, boolean_t netfree)
 839 {
 840         uint64_t space, resv;
 841 
 842         /*
 843          * If we're trying to assess whether it's OK to do a free,
 844          * cut the reservation in half to allow forward progress
 845          * (e.g. make it possible to rm(1) files from a full pool).
 846          */
 847         space = spa_get_dspace(dp->dp_spa);
 848         resv = spa_get_slop_space(dp->dp_spa);
 849         if (netfree)
 850                 resv >>= 1;
 851 
 852         return (space - resv);
 853 }
 854 
 855 boolean_t
 856 dsl_pool_need_dirty_delay(dsl_pool_t *dp)
 857 {
 858         uint64_t delay_min_bytes =
 859             zfs_dirty_data_max * zfs_delay_min_dirty_percent / 100;
 860         boolean_t rv;
 861 
 862         if (dp->dp_dirty_total > zfs_dirty_data_sync)
 863                 txg_kick(dp);
 864         rv = (dp->dp_dirty_total > delay_min_bytes);
 865 
 866         return (rv);
 867 }
 868 
 869 void
 870 dsl_pool_dirty_space(dsl_pool_t *dp, int64_t space, dmu_tx_t *tx)
 871 {
 872         if (space > 0) {
 873                 mutex_enter(&dp->dp_lock);
 874                 dp->dp_dirty_pertxg[tx->tx_txg & TXG_MASK] += space;
 875                 dsl_pool_dirty_delta(dp, space);
 876                 mutex_exit(&dp->dp_lock);
 877         }
 878 }
 879 
 880 void
 881 dsl_pool_undirty_space(dsl_pool_t *dp, int64_t space, uint64_t txg)
 882 {
 883         ASSERT3S(space, >=, 0);
 884         if (space == 0)
 885                 return;
 886         mutex_enter(&dp->dp_lock);
 887         if (dp->dp_dirty_pertxg[txg & TXG_MASK] < space) {
 888                 /* XXX writing something we didn't dirty? */
 889                 space = dp->dp_dirty_pertxg[txg & TXG_MASK];
 890         }
 891         ASSERT3U(dp->dp_dirty_pertxg[txg & TXG_MASK], >=, space);
 892         dp->dp_dirty_pertxg[txg & TXG_MASK] -= space;
 893         ASSERT3U(dp->dp_dirty_total, >=, space);
 894         dsl_pool_dirty_delta(dp, -space);
 895         mutex_exit(&dp->dp_lock);
 896 }
 897 
 898 /* ARGSUSED */
 899 static int
 900 upgrade_clones_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)
 901 {
 902         dmu_tx_t *tx = arg;
 903         dsl_dataset_t *ds, *prev = NULL;
 904         int err;
 905 
 906         err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);
 907         if (err)
 908                 return (err);
 909 
 910         while (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {
 911                 err = dsl_dataset_hold_obj(dp,
 912                     dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);
 913                 if (err) {
 914                         dsl_dataset_rele(ds, FTAG);
 915                         return (err);
 916                 }
 917 
 918                 if (dsl_dataset_phys(prev)->ds_next_snap_obj != ds->ds_object)
 919                         break;
 920                 dsl_dataset_rele(ds, FTAG);
 921                 ds = prev;
 922                 prev = NULL;
 923         }
 924 
 925         if (prev == NULL) {
 926                 prev = dp->dp_origin_snap;
 927 
 928                 /*
 929                  * The $ORIGIN can't have any data, or the accounting
 930                  * will be wrong.
 931                  */
 932                 rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
 933                 ASSERT0(dsl_dataset_phys(prev)->ds_bp.blk_birth);
 934                 rrw_exit(&ds->ds_bp_rwlock, FTAG);
 935 
 936                 /* The origin doesn't get attached to itself */
 937                 if (ds->ds_object == prev->ds_object) {
 938                         dsl_dataset_rele(ds, FTAG);
 939                         return (0);
 940                 }
 941 
 942                 dmu_buf_will_dirty(ds->ds_dbuf, tx);
 943                 dsl_dataset_phys(ds)->ds_prev_snap_obj = prev->ds_object;
 944                 dsl_dataset_phys(ds)->ds_prev_snap_txg =
 945                     dsl_dataset_phys(prev)->ds_creation_txg;
 946 
 947                 dmu_buf_will_dirty(ds->ds_dir->dd_dbuf, tx);
 948                 dsl_dir_phys(ds->ds_dir)->dd_origin_obj = prev->ds_object;
 949 
 950                 dmu_buf_will_dirty(prev->ds_dbuf, tx);
 951                 dsl_dataset_phys(prev)->ds_num_children++;
 952 
 953                 if (dsl_dataset_phys(ds)->ds_next_snap_obj == 0) {
 954                         ASSERT(ds->ds_prev == NULL);
 955                         VERIFY0(dsl_dataset_hold_obj(dp,
 956                             dsl_dataset_phys(ds)->ds_prev_snap_obj,
 957                             ds, &ds->ds_prev));
 958                 }
 959         }
 960 
 961         ASSERT3U(dsl_dir_phys(ds->ds_dir)->dd_origin_obj, ==, prev->ds_object);
 962         ASSERT3U(dsl_dataset_phys(ds)->ds_prev_snap_obj, ==, prev->ds_object);
 963 
 964         if (dsl_dataset_phys(prev)->ds_next_clones_obj == 0) {
 965                 dmu_buf_will_dirty(prev->ds_dbuf, tx);
 966                 dsl_dataset_phys(prev)->ds_next_clones_obj =
 967                     zap_create(dp->dp_meta_objset,
 968                     DMU_OT_NEXT_CLONES, DMU_OT_NONE, 0, tx);
 969         }
 970         VERIFY0(zap_add_int(dp->dp_meta_objset,
 971             dsl_dataset_phys(prev)->ds_next_clones_obj, ds->ds_object, tx));
 972 
 973         dsl_dataset_rele(ds, FTAG);
 974         if (prev != dp->dp_origin_snap)
 975                 dsl_dataset_rele(prev, FTAG);
 976         return (0);
 977 }
 978 
 979 void
 980 dsl_pool_upgrade_clones(dsl_pool_t *dp, dmu_tx_t *tx)
 981 {
 982         ASSERT(dmu_tx_is_syncing(tx));
 983         ASSERT(dp->dp_origin_snap != NULL);
 984 
 985         VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj, upgrade_clones_cb,
 986             tx, DS_FIND_CHILDREN | DS_FIND_SERIALIZE));
 987 }
 988 
 989 /* ARGSUSED */
 990 static int
 991 upgrade_dir_clones_cb(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
 992 {
 993         dmu_tx_t *tx = arg;
 994         objset_t *mos = dp->dp_meta_objset;
 995 
 996         if (dsl_dir_phys(ds->ds_dir)->dd_origin_obj != 0) {
 997                 dsl_dataset_t *origin;
 998 
 999                 VERIFY0(dsl_dataset_hold_obj(dp,
1000                     dsl_dir_phys(ds->ds_dir)->dd_origin_obj, FTAG, &origin));
1001 
1002                 if (dsl_dir_phys(origin->ds_dir)->dd_clones == 0) {
1003                         dmu_buf_will_dirty(origin->ds_dir->dd_dbuf, tx);
1004                         dsl_dir_phys(origin->ds_dir)->dd_clones =
1005                             zap_create(mos, DMU_OT_DSL_CLONES, DMU_OT_NONE,
1006                             0, tx);
1007                 }
1008 
1009                 VERIFY0(zap_add_int(dp->dp_meta_objset,
1010                     dsl_dir_phys(origin->ds_dir)->dd_clones,
1011                     ds->ds_object, tx));
1012 
1013                 dsl_dataset_rele(origin, FTAG);
1014         }
1015         return (0);
1016 }
1017 
1018 void
1019 dsl_pool_upgrade_dir_clones(dsl_pool_t *dp, dmu_tx_t *tx)
1020 {
1021         ASSERT(dmu_tx_is_syncing(tx));
1022         uint64_t obj;
1023 
1024         (void) dsl_dir_create_sync(dp, dp->dp_root_dir, FREE_DIR_NAME, tx);
1025         VERIFY0(dsl_pool_open_special_dir(dp,
1026             FREE_DIR_NAME, &dp->dp_free_dir));
1027 
1028         /*
1029          * We can't use bpobj_alloc(), because spa_version() still
1030          * returns the old version, and we need a new-version bpobj with
1031          * subobj support.  So call dmu_object_alloc() directly.
1032          */
1033         obj = dmu_object_alloc(dp->dp_meta_objset, DMU_OT_BPOBJ,
1034             SPA_OLD_MAXBLOCKSIZE, DMU_OT_BPOBJ_HDR, sizeof (bpobj_phys_t), tx);
1035         VERIFY0(zap_add(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
1036             DMU_POOL_FREE_BPOBJ, sizeof (uint64_t), 1, &obj, tx));
1037         VERIFY0(bpobj_open(&dp->dp_free_bpobj, dp->dp_meta_objset, obj));
1038 
1039         VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
1040             upgrade_dir_clones_cb, tx, DS_FIND_CHILDREN | DS_FIND_SERIALIZE));
1041 }
1042 
1043 void
1044 dsl_pool_create_origin(dsl_pool_t *dp, dmu_tx_t *tx)
1045 {
1046         uint64_t dsobj;
1047         dsl_dataset_t *ds;
1048 
1049         ASSERT(dmu_tx_is_syncing(tx));
1050         ASSERT(dp->dp_origin_snap == NULL);
1051         ASSERT(rrw_held(&dp->dp_config_rwlock, RW_WRITER));
1052 
1053         /* create the origin dir, ds, & snap-ds */
1054         dsobj = dsl_dataset_create_sync(dp->dp_root_dir, ORIGIN_DIR_NAME,
1055             NULL, 0, kcred, tx);
1056         VERIFY0(dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
1057         dsl_dataset_snapshot_sync_impl(ds, ORIGIN_DIR_NAME, tx);
1058         VERIFY0(dsl_dataset_hold_obj(dp, dsl_dataset_phys(ds)->ds_prev_snap_obj,
1059             dp, &dp->dp_origin_snap));
1060         dsl_dataset_rele(ds, FTAG);
1061 }
1062 
1063 taskq_t *
1064 dsl_pool_vnrele_taskq(dsl_pool_t *dp)
1065 {
1066         return (dp->dp_vnrele_taskq);
1067 }
1068 
1069 /*
1070  * Walk through the pool-wide zap object of temporary snapshot user holds
1071  * and release them.
1072  */
1073 void
1074 dsl_pool_clean_tmp_userrefs(dsl_pool_t *dp)
1075 {
1076         zap_attribute_t za;
1077         zap_cursor_t zc;
1078         objset_t *mos = dp->dp_meta_objset;
1079         uint64_t zapobj = dp->dp_tmp_userrefs_obj;
1080         nvlist_t *holds;
1081 
1082         if (zapobj == 0)
1083                 return;
1084         ASSERT(spa_version(dp->dp_spa) >= SPA_VERSION_USERREFS);
1085 
1086         holds = fnvlist_alloc();
1087 
1088         for (zap_cursor_init(&zc, mos, zapobj);
1089             zap_cursor_retrieve(&zc, &za) == 0;
1090             zap_cursor_advance(&zc)) {
1091                 char *htag;
1092                 nvlist_t *tags;
1093 
1094                 htag = strchr(za.za_name, '-');
1095                 *htag = '\0';
1096                 ++htag;
1097                 if (nvlist_lookup_nvlist(holds, za.za_name, &tags) != 0) {
1098                         tags = fnvlist_alloc();
1099                         fnvlist_add_boolean(tags, htag);
1100                         fnvlist_add_nvlist(holds, za.za_name, tags);
1101                         fnvlist_free(tags);
1102                 } else {
1103                         fnvlist_add_boolean(tags, htag);
1104                 }
1105         }
1106         dsl_dataset_user_release_tmp(dp, holds);
1107         fnvlist_free(holds);
1108         zap_cursor_fini(&zc);
1109 }
1110 
1111 /*
1112  * Create the pool-wide zap object for storing temporary snapshot holds.
1113  */
1114 void
1115 dsl_pool_user_hold_create_obj(dsl_pool_t *dp, dmu_tx_t *tx)
1116 {
1117         objset_t *mos = dp->dp_meta_objset;
1118 
1119         ASSERT(dp->dp_tmp_userrefs_obj == 0);
1120         ASSERT(dmu_tx_is_syncing(tx));
1121 
1122         dp->dp_tmp_userrefs_obj = zap_create_link(mos, DMU_OT_USERREFS,
1123             DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_TMP_USERREFS, tx);
1124 }
1125 
1126 static int
1127 dsl_pool_user_hold_rele_impl(dsl_pool_t *dp, uint64_t dsobj,
1128     const char *tag, uint64_t now, dmu_tx_t *tx, boolean_t holding)
1129 {
1130         objset_t *mos = dp->dp_meta_objset;
1131         uint64_t zapobj = dp->dp_tmp_userrefs_obj;
1132         char *name;
1133         int error;
1134 
1135         ASSERT(spa_version(dp->dp_spa) >= SPA_VERSION_USERREFS);
1136         ASSERT(dmu_tx_is_syncing(tx));
1137 
1138         /*
1139          * If the pool was created prior to SPA_VERSION_USERREFS, the
1140          * zap object for temporary holds might not exist yet.
1141          */
1142         if (zapobj == 0) {
1143                 if (holding) {
1144                         dsl_pool_user_hold_create_obj(dp, tx);
1145                         zapobj = dp->dp_tmp_userrefs_obj;
1146                 } else {
1147                         return (SET_ERROR(ENOENT));
1148                 }
1149         }
1150 
1151         name = kmem_asprintf("%llx-%s", (u_longlong_t)dsobj, tag);
1152         if (holding)
1153                 error = zap_add(mos, zapobj, name, 8, 1, &now, tx);
1154         else
1155                 error = zap_remove(mos, zapobj, name, tx);
1156         strfree(name);
1157 
1158         return (error);
1159 }
1160 
1161 /*
1162  * Add a temporary hold for the given dataset object and tag.
1163  */
1164 int
1165 dsl_pool_user_hold(dsl_pool_t *dp, uint64_t dsobj, const char *tag,
1166     uint64_t now, dmu_tx_t *tx)
1167 {
1168         return (dsl_pool_user_hold_rele_impl(dp, dsobj, tag, now, tx, B_TRUE));
1169 }
1170 
1171 /*
1172  * Release a temporary hold for the given dataset object and tag.
1173  */
1174 int
1175 dsl_pool_user_release(dsl_pool_t *dp, uint64_t dsobj, const char *tag,
1176     dmu_tx_t *tx)
1177 {
1178         return (dsl_pool_user_hold_rele_impl(dp, dsobj, tag, NULL,
1179             tx, B_FALSE));
1180 }
1181 
1182 /*
1183  * DSL Pool Configuration Lock
1184  *
1185  * The dp_config_rwlock protects against changes to DSL state (e.g. dataset
1186  * creation / destruction / rename / property setting).  It must be held for
1187  * read to hold a dataset or dsl_dir.  I.e. you must call
1188  * dsl_pool_config_enter() or dsl_pool_hold() before calling
1189  * dsl_{dataset,dir}_hold{_obj}.  In most circumstances, the dp_config_rwlock
1190  * must be held continuously until all datasets and dsl_dirs are released.
1191  *
1192  * The only exception to this rule is that if a "long hold" is placed on
1193  * a dataset, then the dp_config_rwlock may be dropped while the dataset
1194  * is still held.  The long hold will prevent the dataset from being
1195  * destroyed -- the destroy will fail with EBUSY.  A long hold can be
1196  * obtained by calling dsl_dataset_long_hold(), or by "owning" a dataset
1197  * (by calling dsl_{dataset,objset}_{try}own{_obj}).
1198  *
1199  * Legitimate long-holders (including owners) should be long-running, cancelable
1200  * tasks that should cause "zfs destroy" to fail.  This includes DMU
1201  * consumers (i.e. a ZPL filesystem being mounted or ZVOL being open),
1202  * "zfs send", and "zfs diff".  There are several other long-holders whose
1203  * uses are suboptimal (e.g. "zfs promote", and zil_suspend()).
1204  *
1205  * The usual formula for long-holding would be:
1206  * dsl_pool_hold()
1207  * dsl_dataset_hold()
1208  * ... perform checks ...
1209  * dsl_dataset_long_hold()
1210  * dsl_pool_rele()
1211  * ... perform long-running task ...
1212  * dsl_dataset_long_rele()
1213  * dsl_dataset_rele()
1214  *
1215  * Note that when the long hold is released, the dataset is still held but
1216  * the pool is not held.  The dataset may change arbitrarily during this time
1217  * (e.g. it could be destroyed).  Therefore you shouldn't do anything to the
1218  * dataset except release it.
1219  *
1220  * User-initiated operations (e.g. ioctls, zfs_ioc_*()) are either read-only
1221  * or modifying operations.
1222  *
1223  * Modifying operations should generally use dsl_sync_task().  The synctask
1224  * infrastructure enforces proper locking strategy with respect to the
1225  * dp_config_rwlock.  See the comment above dsl_sync_task() for details.
1226  *
1227  * Read-only operations will manually hold the pool, then the dataset, obtain
1228  * information from the dataset, then release the pool and dataset.
1229  * dmu_objset_{hold,rele}() are convenience routines that also do the pool
1230  * hold/rele.
1231  */
1232 
1233 int
1234 dsl_pool_hold(const char *name, void *tag, dsl_pool_t **dp)
1235 {
1236         spa_t *spa;
1237         int error;
1238 
1239         error = spa_open(name, &spa, tag);
1240         if (error == 0) {
1241                 *dp = spa_get_dsl(spa);
1242                 dsl_pool_config_enter(*dp, tag);
1243         }
1244         return (error);
1245 }
1246 
1247 void
1248 dsl_pool_rele(dsl_pool_t *dp, void *tag)
1249 {
1250         dsl_pool_config_exit(dp, tag);
1251         spa_close(dp->dp_spa, tag);
1252 }
1253 
1254 void
1255 dsl_pool_config_enter(dsl_pool_t *dp, void *tag)
1256 {
1257         /*
1258          * We use a "reentrant" reader-writer lock, but not reentrantly.
1259          *
1260          * The rrwlock can (with the track_all flag) track all reading threads,
1261          * which is very useful for debugging which code path failed to release
1262          * the lock, and for verifying that the *current* thread does hold
1263          * the lock.
1264          *
1265          * (Unlike a rwlock, which knows that N threads hold it for
1266          * read, but not *which* threads, so rw_held(RW_READER) returns TRUE
1267          * if any thread holds it for read, even if this thread doesn't).
1268          */
1269         ASSERT(!rrw_held(&dp->dp_config_rwlock, RW_READER));
1270         rrw_enter(&dp->dp_config_rwlock, RW_READER, tag);
1271 }
1272 
1273 void
1274 dsl_pool_config_enter_prio(dsl_pool_t *dp, void *tag)
1275 {
1276         ASSERT(!rrw_held(&dp->dp_config_rwlock, RW_READER));
1277         rrw_enter_read_prio(&dp->dp_config_rwlock, tag);
1278 }
1279 
1280 void
1281 dsl_pool_config_exit(dsl_pool_t *dp, void *tag)
1282 {
1283         rrw_exit(&dp->dp_config_rwlock, tag);
1284 }
1285 
1286 boolean_t
1287 dsl_pool_config_held(dsl_pool_t *dp)
1288 {
1289         return (RRW_LOCK_HELD(&dp->dp_config_rwlock));
1290 }
1291 
1292 boolean_t
1293 dsl_pool_config_held_writer(dsl_pool_t *dp)
1294 {
1295         return (RRW_WRITE_HELD(&dp->dp_config_rwlock));
1296 }