xref: /freebsd/sys/contrib/openzfs/module/zfs/dsl_dataset.c (revision 61145dc2b94f12f6a47344fb9aac702321880e43)
1  // SPDX-License-Identifier: CDDL-1.0
2  /*
3   * CDDL HEADER START
4   *
5   * The contents of this file are subject to the terms of the
6   * Common Development and Distribution License (the "License").
7   * You may not use this file except in compliance with the License.
8   *
9   * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10   * or https://opensource.org/licenses/CDDL-1.0.
11   * See the License for the specific language governing permissions
12   * and limitations under the License.
13   *
14   * When distributing Covered Code, include this CDDL HEADER in each
15   * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16   * If applicable, add the following below this CDDL HEADER, with the
17   * fields enclosed by brackets "[]" replaced with your own identifying
18   * information: Portions Copyright [yyyy] [name of copyright owner]
19   *
20   * CDDL HEADER END
21   */
22  
23  /*
24   * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
25   * Copyright (c) 2011, 2020 by Delphix. All rights reserved.
26   * Copyright (c) 2014, Joyent, Inc. All rights reserved.
27   * Copyright (c) 2014 RackTop Systems.
28   * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
29   * Copyright (c) 2016 Actifio, Inc. All rights reserved.
30   * Copyright 2016, OmniTI Computer Consulting, Inc. All rights reserved.
31   * Copyright 2017 Nexenta Systems, Inc.
32   * Copyright (c) 2019, Klara Inc.
33   * Copyright (c) 2019, Allan Jude
34   * Copyright (c) 2020 The FreeBSD Foundation [1]
35   *
36   * [1] Portions of this software were developed by Allan Jude
37   *     under sponsorship from the FreeBSD Foundation.
38   */
39  
40  #include <sys/dmu_objset.h>
41  #include <sys/dsl_dataset.h>
42  #include <sys/dsl_dir.h>
43  #include <sys/dsl_prop.h>
44  #include <sys/dsl_synctask.h>
45  #include <sys/dmu_traverse.h>
46  #include <sys/dmu_impl.h>
47  #include <sys/dmu_tx.h>
48  #include <sys/arc.h>
49  #include <sys/zio.h>
50  #include <sys/zap.h>
51  #include <sys/zfeature.h>
52  #include <sys/unique.h>
53  #include <sys/zfs_context.h>
54  #include <sys/zfs_ioctl.h>
55  #include <sys/spa.h>
56  #include <sys/spa_impl.h>
57  #include <sys/vdev.h>
58  #include <sys/zfs_znode.h>
59  #include <sys/zfs_onexit.h>
60  #include <sys/zvol.h>
61  #include <sys/dsl_scan.h>
62  #include <sys/dsl_deadlist.h>
63  #include <sys/dsl_destroy.h>
64  #include <sys/dsl_userhold.h>
65  #include <sys/dsl_bookmark.h>
66  #include <sys/policy.h>
67  #include <sys/dmu_send.h>
68  #include <sys/dmu_recv.h>
69  #include <sys/zio_compress.h>
70  #include <zfs_fletcher.h>
71  #include <sys/zio_checksum.h>
72  #include <sys/brt.h>
73  
74  /*
75   * The SPA supports block sizes up to 16MB.  However, very large blocks
76   * can have an impact on i/o latency (e.g. tying up a spinning disk for
77   * ~300ms), and also potentially on the memory allocator.  Therefore,
78   * we did not allow the recordsize to be set larger than zfs_max_recordsize
79   * (former default: 1MB).  Larger blocks could be created by changing this
80   * tunable, and pools with larger blocks could always be imported and used,
81   * regardless of this setting.
82   *
83   * We do, however, still limit it by default to 1M on x86_32, because Linux's
84   * 3/1 memory split doesn't leave much room for 16M chunks.
85   */
86  #ifdef _ILP32
87  uint_t zfs_max_recordsize =  1 * 1024 * 1024;
88  #else
89  uint_t zfs_max_recordsize = 16 * 1024 * 1024;
90  #endif
91  static int zfs_allow_redacted_dataset_mount = 0;
92  
93  int zfs_snapshot_history_enabled = 1;
94  
95  #define	SWITCH64(x, y) \
96  	{ \
97  		uint64_t __tmp = (x); \
98  		(x) = (y); \
99  		(y) = __tmp; \
100  	}
101  
102  #define	DS_REF_MAX	(1ULL << 62)
103  
104  static void dsl_dataset_set_remap_deadlist_object(dsl_dataset_t *ds,
105      uint64_t obj, dmu_tx_t *tx);
106  static void dsl_dataset_unset_remap_deadlist_object(dsl_dataset_t *ds,
107      dmu_tx_t *tx);
108  
109  static void unload_zfeature(dsl_dataset_t *ds, spa_feature_t f);
110  
111  extern uint_t spa_asize_inflation;
112  
113  static zil_header_t zero_zil;
114  
115  /*
116   * Figure out how much of this delta should be propagated to the dsl_dir
117   * layer.  If there's a refreservation, that space has already been
118   * partially accounted for in our ancestors.
119   */
120  static int64_t
parent_delta(dsl_dataset_t * ds,int64_t delta)121  parent_delta(dsl_dataset_t *ds, int64_t delta)
122  {
123  	dsl_dataset_phys_t *ds_phys;
124  	uint64_t old_bytes, new_bytes;
125  
126  	if (ds->ds_reserved == 0)
127  		return (delta);
128  
129  	ds_phys = dsl_dataset_phys(ds);
130  	old_bytes = MAX(ds_phys->ds_unique_bytes, ds->ds_reserved);
131  	new_bytes = MAX(ds_phys->ds_unique_bytes + delta, ds->ds_reserved);
132  
133  	ASSERT3U(ABS((int64_t)(new_bytes - old_bytes)), <=, ABS(delta));
134  	return (new_bytes - old_bytes);
135  }
136  
137  void
dsl_dataset_block_born(dsl_dataset_t * ds,const blkptr_t * bp,dmu_tx_t * tx)138  dsl_dataset_block_born(dsl_dataset_t *ds, const blkptr_t *bp, dmu_tx_t *tx)
139  {
140  	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
141  	int used = bp_get_dsize_sync(spa, bp);
142  	int compressed = BP_GET_PSIZE(bp);
143  	int uncompressed = BP_GET_UCSIZE(bp);
144  	int64_t delta;
145  	spa_feature_t f;
146  
147  	dprintf_bp(bp, "ds=%p", ds);
148  
149  	ASSERT(dmu_tx_is_syncing(tx));
150  	/* It could have been compressed away to nothing */
151  	if (BP_IS_HOLE(bp) || BP_IS_REDACTED(bp))
152  		return;
153  	ASSERT(BP_GET_TYPE(bp) != DMU_OT_NONE);
154  	ASSERT(DMU_OT_IS_VALID(BP_GET_TYPE(bp)));
155  	if (ds == NULL) {
156  		dsl_pool_mos_diduse_space(tx->tx_pool,
157  		    used, compressed, uncompressed);
158  		return;
159  	}
160  
161  	ASSERT3U(BP_GET_LOGICAL_BIRTH(bp), >,
162  	    dsl_dataset_phys(ds)->ds_prev_snap_txg);
163  	dmu_buf_will_dirty(ds->ds_dbuf, tx);
164  	mutex_enter(&ds->ds_lock);
165  	delta = parent_delta(ds, used);
166  	dsl_dataset_phys(ds)->ds_referenced_bytes += used;
167  	dsl_dataset_phys(ds)->ds_compressed_bytes += compressed;
168  	dsl_dataset_phys(ds)->ds_uncompressed_bytes += uncompressed;
169  	dsl_dataset_phys(ds)->ds_unique_bytes += used;
170  
171  	if (BP_GET_LSIZE(bp) > SPA_OLD_MAXBLOCKSIZE) {
172  		ds->ds_feature_activation[SPA_FEATURE_LARGE_BLOCKS] =
173  		    (void *)B_TRUE;
174  	}
175  
176  
177  	f = zio_checksum_to_feature(BP_GET_CHECKSUM(bp));
178  	if (f != SPA_FEATURE_NONE) {
179  		ASSERT3S(spa_feature_table[f].fi_type, ==,
180  		    ZFEATURE_TYPE_BOOLEAN);
181  		ds->ds_feature_activation[f] = (void *)B_TRUE;
182  	}
183  
184  	f = zio_compress_to_feature(BP_GET_COMPRESS(bp));
185  	if (f != SPA_FEATURE_NONE) {
186  		ASSERT3S(spa_feature_table[f].fi_type, ==,
187  		    ZFEATURE_TYPE_BOOLEAN);
188  		ds->ds_feature_activation[f] = (void *)B_TRUE;
189  	}
190  
191  	/*
192  	 * Track block for livelist, but ignore embedded blocks because
193  	 * they do not need to be freed.
194  	 */
195  	if (dsl_deadlist_is_open(&ds->ds_dir->dd_livelist) &&
196  	    BP_GET_LOGICAL_BIRTH(bp) > ds->ds_dir->dd_origin_txg &&
197  	    !(BP_IS_EMBEDDED(bp))) {
198  		ASSERT(dsl_dir_is_clone(ds->ds_dir));
199  		ASSERT(spa_feature_is_enabled(spa,
200  		    SPA_FEATURE_LIVELIST));
201  		bplist_append(&ds->ds_dir->dd_pending_allocs, bp);
202  	}
203  
204  	mutex_exit(&ds->ds_lock);
205  	dsl_dir_diduse_transfer_space(ds->ds_dir, delta,
206  	    compressed, uncompressed, used,
207  	    DD_USED_REFRSRV, DD_USED_HEAD, tx);
208  }
209  
210  /*
211   * Called when the specified segment has been remapped, and is thus no
212   * longer referenced in the head dataset.  The vdev must be indirect.
213   *
214   * If the segment is referenced by a snapshot, put it on the remap deadlist.
215   * Otherwise, add this segment to the obsolete spacemap.
216   */
217  void
dsl_dataset_block_remapped(dsl_dataset_t * ds,uint64_t vdev,uint64_t offset,uint64_t size,uint64_t birth,dmu_tx_t * tx)218  dsl_dataset_block_remapped(dsl_dataset_t *ds, uint64_t vdev, uint64_t offset,
219      uint64_t size, uint64_t birth, dmu_tx_t *tx)
220  {
221  	spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
222  
223  	ASSERT(dmu_tx_is_syncing(tx));
224  	ASSERT(birth <= tx->tx_txg);
225  	ASSERT(!ds->ds_is_snapshot);
226  
227  	if (birth > dsl_dataset_phys(ds)->ds_prev_snap_txg) {
228  		spa_vdev_indirect_mark_obsolete(spa, vdev, offset, size, tx);
229  	} else {
230  		blkptr_t fakebp;
231  		dva_t *dva = &fakebp.blk_dva[0];
232  
233  		ASSERT(ds != NULL);
234  
235  		mutex_enter(&ds->ds_remap_deadlist_lock);
236  		if (!dsl_dataset_remap_deadlist_exists(ds)) {
237  			dsl_dataset_create_remap_deadlist(ds, tx);
238  		}
239  		mutex_exit(&ds->ds_remap_deadlist_lock);
240  
241  		BP_ZERO(&fakebp);
242  		BP_SET_LOGICAL_BIRTH(&fakebp, birth);
243  		DVA_SET_VDEV(dva, vdev);
244  		DVA_SET_OFFSET(dva, offset);
245  		DVA_SET_ASIZE(dva, size);
246  		dsl_deadlist_insert(&ds->ds_remap_deadlist, &fakebp, B_FALSE,
247  		    tx);
248  	}
249  }
250  
251  int
dsl_dataset_block_kill(dsl_dataset_t * ds,const blkptr_t * bp,dmu_tx_t * tx,boolean_t async)252  dsl_dataset_block_kill(dsl_dataset_t *ds, const blkptr_t *bp, dmu_tx_t *tx,
253      boolean_t async)
254  {
255  	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
256  
257  	int used = bp_get_dsize_sync(spa, bp);
258  	int compressed = BP_GET_PSIZE(bp);
259  	int uncompressed = BP_GET_UCSIZE(bp);
260  
261  	if (BP_IS_HOLE(bp) || BP_IS_REDACTED(bp))
262  		return (0);
263  
264  	ASSERT(dmu_tx_is_syncing(tx));
265  	ASSERT(BP_GET_LOGICAL_BIRTH(bp) <= tx->tx_txg);
266  
267  	if (ds == NULL) {
268  		dsl_free(tx->tx_pool, tx->tx_txg, bp);
269  		dsl_pool_mos_diduse_space(tx->tx_pool,
270  		    -used, -compressed, -uncompressed);
271  		return (used);
272  	}
273  	ASSERT3P(tx->tx_pool, ==, ds->ds_dir->dd_pool);
274  
275  	ASSERT(!ds->ds_is_snapshot);
276  	dmu_buf_will_dirty(ds->ds_dbuf, tx);
277  
278  	/*
279  	 * Track block for livelist, but ignore embedded blocks because
280  	 * they do not need to be freed.
281  	 */
282  	if (dsl_deadlist_is_open(&ds->ds_dir->dd_livelist) &&
283  	    BP_GET_LOGICAL_BIRTH(bp) > ds->ds_dir->dd_origin_txg &&
284  	    !(BP_IS_EMBEDDED(bp))) {
285  		ASSERT(dsl_dir_is_clone(ds->ds_dir));
286  		ASSERT(spa_feature_is_enabled(spa,
287  		    SPA_FEATURE_LIVELIST));
288  		bplist_append(&ds->ds_dir->dd_pending_frees, bp);
289  	}
290  
291  	if (BP_GET_LOGICAL_BIRTH(bp) > dsl_dataset_phys(ds)->ds_prev_snap_txg) {
292  		int64_t delta;
293  
294  		/*
295  		 * Put blocks that would create IO on the pool's deadlist for
296  		 * dsl_process_async_destroys() to find. This is to prevent
297  		 * zio_free() from creating a ZIO_TYPE_FREE IO for them, which
298  		 * are very heavy and can lead to out-of-memory conditions if
299  		 * something tries to free millions of blocks on the same txg.
300  		 */
301  		boolean_t defer = spa_version(spa) >= SPA_VERSION_DEADLISTS &&
302  		    (BP_IS_GANG(bp) || BP_GET_DEDUP(bp) ||
303  		    brt_maybe_exists(spa, bp));
304  
305  		if (defer) {
306  			dprintf_bp(bp, "putting on free list: %s", "");
307  			bpobj_enqueue(&ds->ds_dir->dd_pool->dp_free_bpobj,
308  			    bp, B_FALSE, tx);
309  		} else {
310  			dprintf_bp(bp, "freeing ds=%llu",
311  			    (u_longlong_t)ds->ds_object);
312  			dsl_free(tx->tx_pool, tx->tx_txg, bp);
313  		}
314  
315  		mutex_enter(&ds->ds_lock);
316  		ASSERT(dsl_dataset_phys(ds)->ds_unique_bytes >= used ||
317  		    !DS_UNIQUE_IS_ACCURATE(ds));
318  		delta = parent_delta(ds, -used);
319  		dsl_dataset_phys(ds)->ds_unique_bytes -= used;
320  		mutex_exit(&ds->ds_lock);
321  
322  		dsl_dir_diduse_transfer_space(ds->ds_dir,
323  		    delta, -compressed, -uncompressed, -used,
324  		    DD_USED_REFRSRV, DD_USED_HEAD, tx);
325  
326  		if (defer)
327  			dsl_dir_diduse_space(tx->tx_pool->dp_free_dir,
328  			    DD_USED_HEAD, used, compressed, uncompressed, tx);
329  	} else {
330  		dprintf_bp(bp, "putting on dead list: %s", "");
331  		if (async) {
332  			/*
333  			 * We are here as part of zio's write done callback,
334  			 * which means we're a zio interrupt thread.  We can't
335  			 * call dsl_deadlist_insert() now because it may block
336  			 * waiting for I/O.  Instead, put bp on the deferred
337  			 * queue and let dsl_pool_sync() finish the job.
338  			 */
339  			bplist_append(&ds->ds_pending_deadlist, bp);
340  		} else {
341  			dsl_deadlist_insert(&ds->ds_deadlist, bp, B_FALSE, tx);
342  		}
343  		ASSERT3U(ds->ds_prev->ds_object, ==,
344  		    dsl_dataset_phys(ds)->ds_prev_snap_obj);
345  		ASSERT(dsl_dataset_phys(ds->ds_prev)->ds_num_children > 0);
346  		/* if (logical birth > prev prev snap txg) prev unique += bs */
347  		if (dsl_dataset_phys(ds->ds_prev)->ds_next_snap_obj ==
348  		    ds->ds_object && BP_GET_LOGICAL_BIRTH(bp) >
349  		    dsl_dataset_phys(ds->ds_prev)->ds_prev_snap_txg) {
350  			dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
351  			mutex_enter(&ds->ds_prev->ds_lock);
352  			dsl_dataset_phys(ds->ds_prev)->ds_unique_bytes += used;
353  			mutex_exit(&ds->ds_prev->ds_lock);
354  		}
355  		if (BP_GET_LOGICAL_BIRTH(bp) > ds->ds_dir->dd_origin_txg) {
356  			dsl_dir_transfer_space(ds->ds_dir, used,
357  			    DD_USED_HEAD, DD_USED_SNAP, tx);
358  		}
359  	}
360  
361  	dsl_bookmark_block_killed(ds, bp, tx);
362  
363  	mutex_enter(&ds->ds_lock);
364  	ASSERT3U(dsl_dataset_phys(ds)->ds_referenced_bytes, >=, used);
365  	dsl_dataset_phys(ds)->ds_referenced_bytes -= used;
366  	ASSERT3U(dsl_dataset_phys(ds)->ds_compressed_bytes, >=, compressed);
367  	dsl_dataset_phys(ds)->ds_compressed_bytes -= compressed;
368  	ASSERT3U(dsl_dataset_phys(ds)->ds_uncompressed_bytes, >=, uncompressed);
369  	dsl_dataset_phys(ds)->ds_uncompressed_bytes -= uncompressed;
370  	mutex_exit(&ds->ds_lock);
371  
372  	return (used);
373  }
374  
375  struct feature_type_uint64_array_arg {
376  	uint64_t length;
377  	uint64_t *array;
378  };
379  
380  static void
unload_zfeature(dsl_dataset_t * ds,spa_feature_t f)381  unload_zfeature(dsl_dataset_t *ds, spa_feature_t f)
382  {
383  	switch (spa_feature_table[f].fi_type) {
384  	case ZFEATURE_TYPE_BOOLEAN:
385  		break;
386  	case ZFEATURE_TYPE_UINT64_ARRAY:
387  	{
388  		struct feature_type_uint64_array_arg *ftuaa = ds->ds_feature[f];
389  		kmem_free(ftuaa->array, ftuaa->length * sizeof (uint64_t));
390  		kmem_free(ftuaa, sizeof (*ftuaa));
391  		break;
392  	}
393  	default:
394  		panic("Invalid zfeature type %d", spa_feature_table[f].fi_type);
395  	}
396  }
397  
398  static int
load_zfeature(objset_t * mos,dsl_dataset_t * ds,spa_feature_t f)399  load_zfeature(objset_t *mos, dsl_dataset_t *ds, spa_feature_t f)
400  {
401  	int err = 0;
402  	switch (spa_feature_table[f].fi_type) {
403  	case ZFEATURE_TYPE_BOOLEAN:
404  		err = zap_contains(mos, ds->ds_object,
405  		    spa_feature_table[f].fi_guid);
406  		if (err == 0) {
407  			ds->ds_feature[f] = (void *)B_TRUE;
408  		} else {
409  			ASSERT3U(err, ==, ENOENT);
410  			err = 0;
411  		}
412  		break;
413  	case ZFEATURE_TYPE_UINT64_ARRAY:
414  	{
415  		uint64_t int_size, num_int;
416  		uint64_t *data;
417  		err = zap_length(mos, ds->ds_object,
418  		    spa_feature_table[f].fi_guid, &int_size, &num_int);
419  		if (err != 0) {
420  			ASSERT3U(err, ==, ENOENT);
421  			err = 0;
422  			break;
423  		}
424  		ASSERT3U(int_size, ==, sizeof (uint64_t));
425  		data = kmem_alloc(int_size * num_int, KM_SLEEP);
426  		VERIFY0(zap_lookup(mos, ds->ds_object,
427  		    spa_feature_table[f].fi_guid, int_size, num_int, data));
428  		struct feature_type_uint64_array_arg *ftuaa =
429  		    kmem_alloc(sizeof (*ftuaa), KM_SLEEP);
430  		ftuaa->length = num_int;
431  		ftuaa->array = data;
432  		ds->ds_feature[f] = ftuaa;
433  		break;
434  	}
435  	default:
436  		panic("Invalid zfeature type %d", spa_feature_table[f].fi_type);
437  	}
438  	return (err);
439  }
440  
441  /*
442   * We have to release the fsid synchronously or we risk that a subsequent
443   * mount of the same dataset will fail to unique_insert the fsid.  This
444   * failure would manifest itself as the fsid of this dataset changing
445   * between mounts which makes NFS clients quite unhappy.
446   */
447  static void
dsl_dataset_evict_sync(void * dbu)448  dsl_dataset_evict_sync(void *dbu)
449  {
450  	dsl_dataset_t *ds = dbu;
451  
452  	ASSERT(ds->ds_owner == NULL);
453  
454  	unique_remove(ds->ds_fsid_guid);
455  }
456  
457  static void
dsl_dataset_evict_async(void * dbu)458  dsl_dataset_evict_async(void *dbu)
459  {
460  	dsl_dataset_t *ds = dbu;
461  
462  	ASSERT(ds->ds_owner == NULL);
463  
464  	ds->ds_dbuf = NULL;
465  
466  	if (ds->ds_objset != NULL)
467  		dmu_objset_evict(ds->ds_objset);
468  
469  	if (ds->ds_prev) {
470  		dsl_dataset_rele(ds->ds_prev, ds);
471  		ds->ds_prev = NULL;
472  	}
473  
474  	dsl_bookmark_fini_ds(ds);
475  
476  	bplist_destroy(&ds->ds_pending_deadlist);
477  	if (dsl_deadlist_is_open(&ds->ds_deadlist))
478  		dsl_deadlist_close(&ds->ds_deadlist);
479  	if (dsl_deadlist_is_open(&ds->ds_remap_deadlist))
480  		dsl_deadlist_close(&ds->ds_remap_deadlist);
481  	if (ds->ds_dir)
482  		dsl_dir_async_rele(ds->ds_dir, ds);
483  
484  	ASSERT(!list_link_active(&ds->ds_synced_link));
485  
486  	for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
487  		if (dsl_dataset_feature_is_active(ds, f))
488  			unload_zfeature(ds, f);
489  	}
490  
491  	list_destroy(&ds->ds_prop_cbs);
492  	mutex_destroy(&ds->ds_lock);
493  	mutex_destroy(&ds->ds_opening_lock);
494  	mutex_destroy(&ds->ds_sendstream_lock);
495  	mutex_destroy(&ds->ds_remap_deadlist_lock);
496  	zfs_refcount_destroy(&ds->ds_longholds);
497  	rrw_destroy(&ds->ds_bp_rwlock);
498  
499  	kmem_free(ds, sizeof (dsl_dataset_t));
500  }
501  
502  int
dsl_dataset_get_snapname(dsl_dataset_t * ds)503  dsl_dataset_get_snapname(dsl_dataset_t *ds)
504  {
505  	dsl_dataset_phys_t *headphys;
506  	int err;
507  	dmu_buf_t *headdbuf;
508  	dsl_pool_t *dp = ds->ds_dir->dd_pool;
509  	objset_t *mos = dp->dp_meta_objset;
510  
511  	if (ds->ds_snapname[0])
512  		return (0);
513  	if (dsl_dataset_phys(ds)->ds_next_snap_obj == 0)
514  		return (0);
515  
516  	err = dmu_bonus_hold(mos, dsl_dir_phys(ds->ds_dir)->dd_head_dataset_obj,
517  	    FTAG, &headdbuf);
518  	if (err != 0)
519  		return (err);
520  	headphys = headdbuf->db_data;
521  	err = zap_value_search(dp->dp_meta_objset,
522  	    headphys->ds_snapnames_zapobj, ds->ds_object, 0, ds->ds_snapname,
523  	    sizeof (ds->ds_snapname));
524  	if (err != 0 && zfs_recover == B_TRUE) {
525  		err = 0;
526  		(void) snprintf(ds->ds_snapname, sizeof (ds->ds_snapname),
527  		    "SNAPOBJ=%llu-ERR=%d",
528  		    (unsigned long long)ds->ds_object, err);
529  	}
530  	dmu_buf_rele(headdbuf, FTAG);
531  	return (err);
532  }
533  
534  int
dsl_dataset_snap_lookup(dsl_dataset_t * ds,const char * name,uint64_t * value)535  dsl_dataset_snap_lookup(dsl_dataset_t *ds, const char *name, uint64_t *value)
536  {
537  	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
538  	uint64_t snapobj = dsl_dataset_phys(ds)->ds_snapnames_zapobj;
539  	matchtype_t mt = 0;
540  	int err;
541  
542  	if (dsl_dataset_phys(ds)->ds_flags & DS_FLAG_CI_DATASET)
543  		mt = MT_NORMALIZE;
544  
545  	err = zap_lookup_norm(mos, snapobj, name, 8, 1,
546  	    value, mt, NULL, 0, NULL);
547  	if (err == ENOTSUP && (mt & MT_NORMALIZE))
548  		err = zap_lookup(mos, snapobj, name, 8, 1, value);
549  	return (err);
550  }
551  
552  int
dsl_dataset_snap_remove(dsl_dataset_t * ds,const char * name,dmu_tx_t * tx,boolean_t adj_cnt)553  dsl_dataset_snap_remove(dsl_dataset_t *ds, const char *name, dmu_tx_t *tx,
554      boolean_t adj_cnt)
555  {
556  	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
557  	uint64_t snapobj = dsl_dataset_phys(ds)->ds_snapnames_zapobj;
558  	matchtype_t mt = 0;
559  	int err;
560  
561  	dsl_dir_snap_cmtime_update(ds->ds_dir, tx);
562  
563  	if (dsl_dataset_phys(ds)->ds_flags & DS_FLAG_CI_DATASET)
564  		mt = MT_NORMALIZE;
565  
566  	err = zap_remove_norm(mos, snapobj, name, mt, tx);
567  	if (err == ENOTSUP && (mt & MT_NORMALIZE))
568  		err = zap_remove(mos, snapobj, name, tx);
569  
570  	if (err == 0 && adj_cnt)
571  		dsl_fs_ss_count_adjust(ds->ds_dir, -1,
572  		    DD_FIELD_SNAPSHOT_COUNT, tx);
573  
574  	return (err);
575  }
576  
577  boolean_t
dsl_dataset_try_add_ref(dsl_pool_t * dp,dsl_dataset_t * ds,const void * tag)578  dsl_dataset_try_add_ref(dsl_pool_t *dp, dsl_dataset_t *ds, const void *tag)
579  {
580  	dmu_buf_t *dbuf = ds->ds_dbuf;
581  	boolean_t result = B_FALSE;
582  
583  	if (dbuf != NULL && dmu_buf_try_add_ref(dbuf, dp->dp_meta_objset,
584  	    ds->ds_object, DMU_BONUS_BLKID, tag)) {
585  
586  		if (ds == dmu_buf_get_user(dbuf))
587  			result = B_TRUE;
588  		else
589  			dmu_buf_rele(dbuf, tag);
590  	}
591  
592  	return (result);
593  }
594  
595  int
dsl_dataset_hold_obj(dsl_pool_t * dp,uint64_t dsobj,const void * tag,dsl_dataset_t ** dsp)596  dsl_dataset_hold_obj(dsl_pool_t *dp, uint64_t dsobj, const void *tag,
597      dsl_dataset_t **dsp)
598  {
599  	objset_t *mos = dp->dp_meta_objset;
600  	dmu_buf_t *dbuf;
601  	dsl_dataset_t *ds;
602  	int err;
603  	dmu_object_info_t doi;
604  
605  	ASSERT(dsl_pool_config_held(dp));
606  
607  	err = dmu_bonus_hold(mos, dsobj, tag, &dbuf);
608  	if (err != 0)
609  		return (err);
610  
611  	/* Make sure dsobj has the correct object type. */
612  	dmu_object_info_from_db(dbuf, &doi);
613  	if (doi.doi_bonus_type != DMU_OT_DSL_DATASET) {
614  		dmu_buf_rele(dbuf, tag);
615  		return (SET_ERROR(EINVAL));
616  	}
617  
618  	ds = dmu_buf_get_user(dbuf);
619  	if (ds == NULL) {
620  		dsl_dataset_t *winner = NULL;
621  
622  		ds = kmem_zalloc(sizeof (dsl_dataset_t), KM_SLEEP);
623  		ds->ds_dbuf = dbuf;
624  		ds->ds_object = dsobj;
625  		ds->ds_is_snapshot = dsl_dataset_phys(ds)->ds_num_children != 0;
626  		list_link_init(&ds->ds_synced_link);
627  
628  		err = dsl_dir_hold_obj(dp, dsl_dataset_phys(ds)->ds_dir_obj,
629  		    NULL, ds, &ds->ds_dir);
630  		if (err != 0) {
631  			kmem_free(ds, sizeof (dsl_dataset_t));
632  			dmu_buf_rele(dbuf, tag);
633  			return (err);
634  		}
635  
636  		mutex_init(&ds->ds_lock, NULL, MUTEX_DEFAULT, NULL);
637  		mutex_init(&ds->ds_opening_lock, NULL, MUTEX_DEFAULT, NULL);
638  		mutex_init(&ds->ds_sendstream_lock, NULL, MUTEX_DEFAULT, NULL);
639  		mutex_init(&ds->ds_remap_deadlist_lock,
640  		    NULL, MUTEX_DEFAULT, NULL);
641  		rrw_init(&ds->ds_bp_rwlock, B_FALSE);
642  		zfs_refcount_create(&ds->ds_longholds);
643  
644  		bplist_create(&ds->ds_pending_deadlist);
645  
646  		list_create(&ds->ds_sendstreams, sizeof (dmu_sendstatus_t),
647  		    offsetof(dmu_sendstatus_t, dss_link));
648  
649  		list_create(&ds->ds_prop_cbs, sizeof (dsl_prop_cb_record_t),
650  		    offsetof(dsl_prop_cb_record_t, cbr_ds_node));
651  
652  		if (doi.doi_type == DMU_OTN_ZAP_METADATA) {
653  			spa_feature_t f;
654  
655  			for (f = 0; f < SPA_FEATURES; f++) {
656  				if (!(spa_feature_table[f].fi_flags &
657  				    ZFEATURE_FLAG_PER_DATASET))
658  					continue;
659  				err = load_zfeature(mos, ds, f);
660  			}
661  		}
662  
663  		if (!ds->ds_is_snapshot) {
664  			ds->ds_snapname[0] = '\0';
665  			if (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {
666  				err = dsl_dataset_hold_obj(dp,
667  				    dsl_dataset_phys(ds)->ds_prev_snap_obj,
668  				    ds, &ds->ds_prev);
669  			}
670  			if (err != 0)
671  				goto after_dsl_bookmark_fini;
672  			err = dsl_bookmark_init_ds(ds);
673  		} else {
674  			if (zfs_flags & ZFS_DEBUG_SNAPNAMES)
675  				err = dsl_dataset_get_snapname(ds);
676  			if (err == 0 &&
677  			    dsl_dataset_phys(ds)->ds_userrefs_obj != 0) {
678  				err = zap_count(
679  				    ds->ds_dir->dd_pool->dp_meta_objset,
680  				    dsl_dataset_phys(ds)->ds_userrefs_obj,
681  				    &ds->ds_userrefs);
682  			}
683  		}
684  
685  		if (err == 0 && !ds->ds_is_snapshot) {
686  			err = dsl_prop_get_int_ds(ds,
687  			    zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
688  			    &ds->ds_reserved);
689  			if (err == 0) {
690  				err = dsl_prop_get_int_ds(ds,
691  				    zfs_prop_to_name(ZFS_PROP_REFQUOTA),
692  				    &ds->ds_quota);
693  			}
694  		} else {
695  			ds->ds_reserved = ds->ds_quota = 0;
696  		}
697  
698  		if (err == 0 && ds->ds_dir->dd_crypto_obj != 0 &&
699  		    ds->ds_is_snapshot &&
700  		    zap_contains(mos, dsobj, DS_FIELD_IVSET_GUID) != 0) {
701  			dp->dp_spa->spa_errata =
702  			    ZPOOL_ERRATA_ZOL_8308_ENCRYPTION;
703  		}
704  
705  		if (err == 0) {
706  			err = dsl_deadlist_open(&ds->ds_deadlist,
707  			    mos, dsl_dataset_phys(ds)->ds_deadlist_obj);
708  		}
709  		if (err == 0) {
710  			uint64_t remap_deadlist_obj =
711  			    dsl_dataset_get_remap_deadlist_object(ds);
712  			if (remap_deadlist_obj != 0) {
713  				err = dsl_deadlist_open(&ds->ds_remap_deadlist,
714  				    mos, remap_deadlist_obj);
715  			}
716  		}
717  
718  		dmu_buf_init_user(&ds->ds_dbu, dsl_dataset_evict_sync,
719  		    dsl_dataset_evict_async, &ds->ds_dbuf);
720  		if (err == 0)
721  			winner = dmu_buf_set_user_ie(dbuf, &ds->ds_dbu);
722  
723  		if (err != 0 || winner != NULL) {
724  			if (dsl_deadlist_is_open(&ds->ds_deadlist))
725  				dsl_deadlist_close(&ds->ds_deadlist);
726  			if (dsl_deadlist_is_open(&ds->ds_remap_deadlist))
727  				dsl_deadlist_close(&ds->ds_remap_deadlist);
728  			dsl_bookmark_fini_ds(ds);
729  after_dsl_bookmark_fini:
730  			if (ds->ds_prev)
731  				dsl_dataset_rele(ds->ds_prev, ds);
732  			dsl_dir_rele(ds->ds_dir, ds);
733  			for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
734  				if (dsl_dataset_feature_is_active(ds, f))
735  					unload_zfeature(ds, f);
736  			}
737  
738  			list_destroy(&ds->ds_prop_cbs);
739  			list_destroy(&ds->ds_sendstreams);
740  			bplist_destroy(&ds->ds_pending_deadlist);
741  			mutex_destroy(&ds->ds_lock);
742  			mutex_destroy(&ds->ds_opening_lock);
743  			mutex_destroy(&ds->ds_sendstream_lock);
744  			mutex_destroy(&ds->ds_remap_deadlist_lock);
745  			zfs_refcount_destroy(&ds->ds_longholds);
746  			rrw_destroy(&ds->ds_bp_rwlock);
747  			kmem_free(ds, sizeof (dsl_dataset_t));
748  			if (err != 0) {
749  				dmu_buf_rele(dbuf, tag);
750  				return (err);
751  			}
752  			ds = winner;
753  		} else {
754  			ds->ds_fsid_guid =
755  			    unique_insert(dsl_dataset_phys(ds)->ds_fsid_guid);
756  			if (ds->ds_fsid_guid !=
757  			    dsl_dataset_phys(ds)->ds_fsid_guid) {
758  				zfs_dbgmsg("ds_fsid_guid changed from "
759  				    "%llx to %llx for pool %s dataset id %llu",
760  				    (long long)
761  				    dsl_dataset_phys(ds)->ds_fsid_guid,
762  				    (long long)ds->ds_fsid_guid,
763  				    spa_name(dp->dp_spa),
764  				    (u_longlong_t)dsobj);
765  			}
766  		}
767  	}
768  
769  	ASSERT3P(ds->ds_dbuf, ==, dbuf);
770  	ASSERT3P(dsl_dataset_phys(ds), ==, dbuf->db_data);
771  	ASSERT(dsl_dataset_phys(ds)->ds_prev_snap_obj != 0 ||
772  	    spa_version(dp->dp_spa) < SPA_VERSION_ORIGIN ||
773  	    dp->dp_origin_snap == NULL || ds == dp->dp_origin_snap);
774  	*dsp = ds;
775  
776  	return (0);
777  }
778  
779  int
dsl_dataset_create_key_mapping(dsl_dataset_t * ds)780  dsl_dataset_create_key_mapping(dsl_dataset_t *ds)
781  {
782  	dsl_dir_t *dd = ds->ds_dir;
783  
784  	if (dd->dd_crypto_obj == 0)
785  		return (0);
786  
787  	return (spa_keystore_create_mapping(dd->dd_pool->dp_spa,
788  	    ds, ds, &ds->ds_key_mapping));
789  }
790  
791  int
dsl_dataset_hold_obj_flags(dsl_pool_t * dp,uint64_t dsobj,ds_hold_flags_t flags,const void * tag,dsl_dataset_t ** dsp)792  dsl_dataset_hold_obj_flags(dsl_pool_t *dp, uint64_t dsobj,
793      ds_hold_flags_t flags, const void *tag, dsl_dataset_t **dsp)
794  {
795  	int err;
796  
797  	err = dsl_dataset_hold_obj(dp, dsobj, tag, dsp);
798  	if (err != 0)
799  		return (err);
800  
801  	ASSERT3P(*dsp, !=, NULL);
802  
803  	if (flags & DS_HOLD_FLAG_DECRYPT) {
804  		err = dsl_dataset_create_key_mapping(*dsp);
805  		if (err != 0)
806  			dsl_dataset_rele(*dsp, tag);
807  	}
808  
809  	return (err);
810  }
811  
812  int
dsl_dataset_hold_flags(dsl_pool_t * dp,const char * name,ds_hold_flags_t flags,const void * tag,dsl_dataset_t ** dsp)813  dsl_dataset_hold_flags(dsl_pool_t *dp, const char *name, ds_hold_flags_t flags,
814      const void *tag, dsl_dataset_t **dsp)
815  {
816  	dsl_dir_t *dd;
817  	const char *snapname;
818  	uint64_t obj;
819  	int err = 0;
820  	dsl_dataset_t *ds;
821  
822  	err = dsl_dir_hold(dp, name, FTAG, &dd, &snapname);
823  	if (err != 0)
824  		return (err);
825  
826  	ASSERT(dsl_pool_config_held(dp));
827  	obj = dsl_dir_phys(dd)->dd_head_dataset_obj;
828  	if (obj != 0)
829  		err = dsl_dataset_hold_obj_flags(dp, obj, flags, tag, &ds);
830  	else
831  		err = SET_ERROR(ENOENT);
832  
833  	/* we may be looking for a snapshot */
834  	if (err == 0 && snapname != NULL) {
835  		dsl_dataset_t *snap_ds;
836  
837  		if (*snapname++ != '@') {
838  			dsl_dataset_rele_flags(ds, flags, tag);
839  			dsl_dir_rele(dd, FTAG);
840  			return (SET_ERROR(ENOENT));
841  		}
842  
843  		dprintf("looking for snapshot '%s'\n", snapname);
844  		err = dsl_dataset_snap_lookup(ds, snapname, &obj);
845  		if (err == 0) {
846  			err = dsl_dataset_hold_obj_flags(dp, obj, flags, tag,
847  			    &snap_ds);
848  		}
849  		dsl_dataset_rele_flags(ds, flags, tag);
850  
851  		if (err == 0) {
852  			mutex_enter(&snap_ds->ds_lock);
853  			if (snap_ds->ds_snapname[0] == 0)
854  				(void) strlcpy(snap_ds->ds_snapname, snapname,
855  				    sizeof (snap_ds->ds_snapname));
856  			mutex_exit(&snap_ds->ds_lock);
857  			ds = snap_ds;
858  		}
859  	}
860  	if (err == 0)
861  		*dsp = ds;
862  	dsl_dir_rele(dd, FTAG);
863  	return (err);
864  }
865  
866  int
dsl_dataset_hold(dsl_pool_t * dp,const char * name,const void * tag,dsl_dataset_t ** dsp)867  dsl_dataset_hold(dsl_pool_t *dp, const char *name, const void *tag,
868      dsl_dataset_t **dsp)
869  {
870  	return (dsl_dataset_hold_flags(dp, name, 0, tag, dsp));
871  }
872  
873  static int
dsl_dataset_own_obj_impl(dsl_pool_t * dp,uint64_t dsobj,ds_hold_flags_t flags,const void * tag,boolean_t override,dsl_dataset_t ** dsp)874  dsl_dataset_own_obj_impl(dsl_pool_t *dp, uint64_t dsobj, ds_hold_flags_t flags,
875      const void *tag, boolean_t override, dsl_dataset_t **dsp)
876  {
877  	int err = dsl_dataset_hold_obj_flags(dp, dsobj, flags, tag, dsp);
878  	if (err != 0)
879  		return (err);
880  	if (!dsl_dataset_tryown(*dsp, tag, override)) {
881  		dsl_dataset_rele_flags(*dsp, flags, tag);
882  		*dsp = NULL;
883  		return (SET_ERROR(EBUSY));
884  	}
885  	return (0);
886  }
887  
888  
889  int
dsl_dataset_own_obj(dsl_pool_t * dp,uint64_t dsobj,ds_hold_flags_t flags,const void * tag,dsl_dataset_t ** dsp)890  dsl_dataset_own_obj(dsl_pool_t *dp, uint64_t dsobj, ds_hold_flags_t flags,
891      const void *tag, dsl_dataset_t **dsp)
892  {
893  	return (dsl_dataset_own_obj_impl(dp, dsobj, flags, tag, B_FALSE, dsp));
894  }
895  
896  int
dsl_dataset_own_obj_force(dsl_pool_t * dp,uint64_t dsobj,ds_hold_flags_t flags,const void * tag,dsl_dataset_t ** dsp)897  dsl_dataset_own_obj_force(dsl_pool_t *dp, uint64_t dsobj,
898      ds_hold_flags_t flags, const void *tag, dsl_dataset_t **dsp)
899  {
900  	return (dsl_dataset_own_obj_impl(dp, dsobj, flags, tag, B_TRUE, dsp));
901  }
902  
903  static int
dsl_dataset_own_impl(dsl_pool_t * dp,const char * name,ds_hold_flags_t flags,const void * tag,boolean_t override,dsl_dataset_t ** dsp)904  dsl_dataset_own_impl(dsl_pool_t *dp, const char *name, ds_hold_flags_t flags,
905      const void *tag, boolean_t override, dsl_dataset_t **dsp)
906  {
907  	int err = dsl_dataset_hold_flags(dp, name, flags, tag, dsp);
908  	if (err != 0)
909  		return (err);
910  	if (!dsl_dataset_tryown(*dsp, tag, override)) {
911  		dsl_dataset_rele_flags(*dsp, flags, tag);
912  		return (SET_ERROR(EBUSY));
913  	}
914  	return (0);
915  }
916  
917  int
dsl_dataset_own_force(dsl_pool_t * dp,const char * name,ds_hold_flags_t flags,const void * tag,dsl_dataset_t ** dsp)918  dsl_dataset_own_force(dsl_pool_t *dp, const char *name, ds_hold_flags_t flags,
919      const void *tag, dsl_dataset_t **dsp)
920  {
921  	return (dsl_dataset_own_impl(dp, name, flags, tag, B_TRUE, dsp));
922  }
923  
924  int
dsl_dataset_own(dsl_pool_t * dp,const char * name,ds_hold_flags_t flags,const void * tag,dsl_dataset_t ** dsp)925  dsl_dataset_own(dsl_pool_t *dp, const char *name, ds_hold_flags_t flags,
926      const void *tag, dsl_dataset_t **dsp)
927  {
928  	return (dsl_dataset_own_impl(dp, name, flags, tag, B_FALSE, dsp));
929  }
930  
931  /*
932   * See the comment above dsl_pool_hold() for details.  In summary, a long
933   * hold is used to prevent destruction of a dataset while the pool hold
934   * is dropped, allowing other concurrent operations (e.g. spa_sync()).
935   *
936   * The dataset and pool must be held when this function is called.  After it
937   * is called, the pool hold may be released while the dataset is still held
938   * and accessed.
939   */
940  void
dsl_dataset_long_hold(dsl_dataset_t * ds,const void * tag)941  dsl_dataset_long_hold(dsl_dataset_t *ds, const void *tag)
942  {
943  	ASSERT(dsl_pool_config_held(ds->ds_dir->dd_pool));
944  	(void) zfs_refcount_add(&ds->ds_longholds, tag);
945  }
946  
947  void
dsl_dataset_long_rele(dsl_dataset_t * ds,const void * tag)948  dsl_dataset_long_rele(dsl_dataset_t *ds, const void *tag)
949  {
950  	(void) zfs_refcount_remove(&ds->ds_longholds, tag);
951  }
952  
953  /* Return B_TRUE if there are any long holds on this dataset. */
954  boolean_t
dsl_dataset_long_held(dsl_dataset_t * ds)955  dsl_dataset_long_held(dsl_dataset_t *ds)
956  {
957  	return (!zfs_refcount_is_zero(&ds->ds_longholds));
958  }
959  
960  void
dsl_dataset_name(dsl_dataset_t * ds,char * name)961  dsl_dataset_name(dsl_dataset_t *ds, char *name)
962  {
963  	if (ds == NULL) {
964  		(void) strlcpy(name, "mos", ZFS_MAX_DATASET_NAME_LEN);
965  	} else {
966  		dsl_dir_name(ds->ds_dir, name);
967  		VERIFY0(dsl_dataset_get_snapname(ds));
968  		if (ds->ds_snapname[0]) {
969  			VERIFY3U(strlcat(name, "@", ZFS_MAX_DATASET_NAME_LEN),
970  			    <, ZFS_MAX_DATASET_NAME_LEN);
971  			/*
972  			 * We use a "recursive" mutex so that we
973  			 * can call dprintf_ds() with ds_lock held.
974  			 */
975  			if (!MUTEX_HELD(&ds->ds_lock)) {
976  				mutex_enter(&ds->ds_lock);
977  				VERIFY3U(strlcat(name, ds->ds_snapname,
978  				    ZFS_MAX_DATASET_NAME_LEN), <,
979  				    ZFS_MAX_DATASET_NAME_LEN);
980  				mutex_exit(&ds->ds_lock);
981  			} else {
982  				VERIFY3U(strlcat(name, ds->ds_snapname,
983  				    ZFS_MAX_DATASET_NAME_LEN), <,
984  				    ZFS_MAX_DATASET_NAME_LEN);
985  			}
986  		}
987  	}
988  }
989  
990  int
dsl_dataset_namelen(dsl_dataset_t * ds)991  dsl_dataset_namelen(dsl_dataset_t *ds)
992  {
993  	VERIFY0(dsl_dataset_get_snapname(ds));
994  	mutex_enter(&ds->ds_lock);
995  	int len = strlen(ds->ds_snapname);
996  	mutex_exit(&ds->ds_lock);
997  	/* add '@' if ds is a snap */
998  	if (len > 0)
999  		len++;
1000  	len += dsl_dir_namelen(ds->ds_dir);
1001  	return (len);
1002  }
1003  
1004  void
dsl_dataset_rele(dsl_dataset_t * ds,const void * tag)1005  dsl_dataset_rele(dsl_dataset_t *ds, const void *tag)
1006  {
1007  	dmu_buf_rele(ds->ds_dbuf, tag);
1008  }
1009  
1010  void
dsl_dataset_remove_key_mapping(dsl_dataset_t * ds)1011  dsl_dataset_remove_key_mapping(dsl_dataset_t *ds)
1012  {
1013  	dsl_dir_t *dd = ds->ds_dir;
1014  
1015  	if (dd == NULL || dd->dd_crypto_obj == 0)
1016  		return;
1017  
1018  	(void) spa_keystore_remove_mapping(dd->dd_pool->dp_spa,
1019  	    ds->ds_object, ds);
1020  }
1021  
1022  void
dsl_dataset_rele_flags(dsl_dataset_t * ds,ds_hold_flags_t flags,const void * tag)1023  dsl_dataset_rele_flags(dsl_dataset_t *ds, ds_hold_flags_t flags,
1024      const void *tag)
1025  {
1026  	if (flags & DS_HOLD_FLAG_DECRYPT)
1027  		dsl_dataset_remove_key_mapping(ds);
1028  
1029  	dsl_dataset_rele(ds, tag);
1030  }
1031  
1032  void
dsl_dataset_disown(dsl_dataset_t * ds,ds_hold_flags_t flags,const void * tag)1033  dsl_dataset_disown(dsl_dataset_t *ds, ds_hold_flags_t flags, const void *tag)
1034  {
1035  	ASSERT3P(ds->ds_owner, ==, tag);
1036  	ASSERT(ds->ds_dbuf != NULL);
1037  
1038  	mutex_enter(&ds->ds_lock);
1039  	ds->ds_owner = NULL;
1040  	mutex_exit(&ds->ds_lock);
1041  	dsl_dataset_long_rele(ds, tag);
1042  	dsl_dataset_rele_flags(ds, flags, tag);
1043  }
1044  
1045  boolean_t
dsl_dataset_tryown(dsl_dataset_t * ds,const void * tag,boolean_t override)1046  dsl_dataset_tryown(dsl_dataset_t *ds, const void *tag, boolean_t override)
1047  {
1048  	boolean_t gotit = FALSE;
1049  
1050  	ASSERT(dsl_pool_config_held(ds->ds_dir->dd_pool));
1051  	mutex_enter(&ds->ds_lock);
1052  	if (ds->ds_owner == NULL && (override || !(DS_IS_INCONSISTENT(ds) ||
1053  	    (dsl_dataset_feature_is_active(ds,
1054  	    SPA_FEATURE_REDACTED_DATASETS) &&
1055  	    !zfs_allow_redacted_dataset_mount)))) {
1056  		ds->ds_owner = tag;
1057  		dsl_dataset_long_hold(ds, tag);
1058  		gotit = TRUE;
1059  	}
1060  	mutex_exit(&ds->ds_lock);
1061  	return (gotit);
1062  }
1063  
1064  boolean_t
dsl_dataset_has_owner(dsl_dataset_t * ds)1065  dsl_dataset_has_owner(dsl_dataset_t *ds)
1066  {
1067  	boolean_t rv;
1068  	mutex_enter(&ds->ds_lock);
1069  	rv = (ds->ds_owner != NULL);
1070  	mutex_exit(&ds->ds_lock);
1071  	return (rv);
1072  }
1073  
1074  static boolean_t
zfeature_active(spa_feature_t f,void * arg)1075  zfeature_active(spa_feature_t f, void *arg)
1076  {
1077  	switch (spa_feature_table[f].fi_type) {
1078  	case ZFEATURE_TYPE_BOOLEAN: {
1079  		boolean_t val = (boolean_t)(uintptr_t)arg;
1080  		ASSERT(val == B_FALSE || val == B_TRUE);
1081  		return (val);
1082  	}
1083  	case ZFEATURE_TYPE_UINT64_ARRAY:
1084  		/*
1085  		 * In this case, arg is a uint64_t array.  The feature is active
1086  		 * if the array is non-null.
1087  		 */
1088  		return (arg != NULL);
1089  	default:
1090  		panic("Invalid zfeature type %d", spa_feature_table[f].fi_type);
1091  		return (B_FALSE);
1092  	}
1093  }
1094  
1095  boolean_t
dsl_dataset_feature_is_active(dsl_dataset_t * ds,spa_feature_t f)1096  dsl_dataset_feature_is_active(dsl_dataset_t *ds, spa_feature_t f)
1097  {
1098  	return (zfeature_active(f, ds->ds_feature[f]));
1099  }
1100  
1101  /*
1102   * The buffers passed out by this function are references to internal buffers;
1103   * they should not be freed by callers of this function, and they should not be
1104   * used after the dataset has been released.
1105   */
1106  boolean_t
dsl_dataset_get_uint64_array_feature(dsl_dataset_t * ds,spa_feature_t f,uint64_t * outlength,uint64_t ** outp)1107  dsl_dataset_get_uint64_array_feature(dsl_dataset_t *ds, spa_feature_t f,
1108      uint64_t *outlength, uint64_t **outp)
1109  {
1110  	VERIFY(spa_feature_table[f].fi_type & ZFEATURE_TYPE_UINT64_ARRAY);
1111  	if (!dsl_dataset_feature_is_active(ds, f)) {
1112  		return (B_FALSE);
1113  	}
1114  	struct feature_type_uint64_array_arg *ftuaa = ds->ds_feature[f];
1115  	*outp = ftuaa->array;
1116  	*outlength = ftuaa->length;
1117  	return (B_TRUE);
1118  }
1119  
1120  void
dsl_dataset_activate_feature(uint64_t dsobj,spa_feature_t f,void * arg,dmu_tx_t * tx)1121  dsl_dataset_activate_feature(uint64_t dsobj, spa_feature_t f, void *arg,
1122      dmu_tx_t *tx)
1123  {
1124  	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
1125  	objset_t *mos = dmu_tx_pool(tx)->dp_meta_objset;
1126  	uint64_t zero = 0;
1127  
1128  	VERIFY(spa_feature_table[f].fi_flags & ZFEATURE_FLAG_PER_DATASET);
1129  
1130  	spa_feature_incr(spa, f, tx);
1131  	dmu_object_zapify(mos, dsobj, DMU_OT_DSL_DATASET, tx);
1132  
1133  	switch (spa_feature_table[f].fi_type) {
1134  	case ZFEATURE_TYPE_BOOLEAN:
1135  		ASSERT3S((boolean_t)(uintptr_t)arg, ==, B_TRUE);
1136  		VERIFY0(zap_add(mos, dsobj, spa_feature_table[f].fi_guid,
1137  		    sizeof (zero), 1, &zero, tx));
1138  		break;
1139  	case ZFEATURE_TYPE_UINT64_ARRAY:
1140  	{
1141  		struct feature_type_uint64_array_arg *ftuaa = arg;
1142  		VERIFY0(zap_add(mos, dsobj, spa_feature_table[f].fi_guid,
1143  		    sizeof (uint64_t), ftuaa->length, ftuaa->array, tx));
1144  		break;
1145  	}
1146  	default:
1147  		panic("Invalid zfeature type %d", spa_feature_table[f].fi_type);
1148  	}
1149  }
1150  
1151  static void
dsl_dataset_deactivate_feature_impl(dsl_dataset_t * ds,spa_feature_t f,dmu_tx_t * tx)1152  dsl_dataset_deactivate_feature_impl(dsl_dataset_t *ds, spa_feature_t f,
1153      dmu_tx_t *tx)
1154  {
1155  	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
1156  	objset_t *mos = dmu_tx_pool(tx)->dp_meta_objset;
1157  	uint64_t dsobj = ds->ds_object;
1158  
1159  	VERIFY(spa_feature_table[f].fi_flags & ZFEATURE_FLAG_PER_DATASET);
1160  
1161  	VERIFY0(zap_remove(mos, dsobj, spa_feature_table[f].fi_guid, tx));
1162  	spa_feature_decr(spa, f, tx);
1163  	ds->ds_feature[f] = NULL;
1164  }
1165  
1166  void
dsl_dataset_deactivate_feature(dsl_dataset_t * ds,spa_feature_t f,dmu_tx_t * tx)1167  dsl_dataset_deactivate_feature(dsl_dataset_t *ds, spa_feature_t f, dmu_tx_t *tx)
1168  {
1169  	unload_zfeature(ds, f);
1170  	dsl_dataset_deactivate_feature_impl(ds, f, tx);
1171  }
1172  
1173  uint64_t
dsl_dataset_create_sync_dd(dsl_dir_t * dd,dsl_dataset_t * origin,dsl_crypto_params_t * dcp,uint64_t flags,dmu_tx_t * tx)1174  dsl_dataset_create_sync_dd(dsl_dir_t *dd, dsl_dataset_t *origin,
1175      dsl_crypto_params_t *dcp, uint64_t flags, dmu_tx_t *tx)
1176  {
1177  	dsl_pool_t *dp = dd->dd_pool;
1178  	dmu_buf_t *dbuf;
1179  	dsl_dataset_phys_t *dsphys;
1180  	uint64_t dsobj;
1181  	objset_t *mos = dp->dp_meta_objset;
1182  
1183  	if (origin == NULL)
1184  		origin = dp->dp_origin_snap;
1185  
1186  	ASSERT(origin == NULL || origin->ds_dir->dd_pool == dp);
1187  	ASSERT(origin == NULL || dsl_dataset_phys(origin)->ds_num_children > 0);
1188  	ASSERT(dmu_tx_is_syncing(tx));
1189  	ASSERT(dsl_dir_phys(dd)->dd_head_dataset_obj == 0);
1190  
1191  	dsobj = dmu_object_alloc(mos, DMU_OT_DSL_DATASET, 0,
1192  	    DMU_OT_DSL_DATASET, sizeof (dsl_dataset_phys_t), tx);
1193  	VERIFY0(dmu_bonus_hold(mos, dsobj, FTAG, &dbuf));
1194  	dmu_buf_will_dirty(dbuf, tx);
1195  	dsphys = dbuf->db_data;
1196  	memset(dsphys, 0, sizeof (dsl_dataset_phys_t));
1197  	dsphys->ds_dir_obj = dd->dd_object;
1198  	dsphys->ds_flags = flags;
1199  	dsphys->ds_fsid_guid = unique_create();
1200  	(void) random_get_pseudo_bytes((void*)&dsphys->ds_guid,
1201  	    sizeof (dsphys->ds_guid));
1202  	dsphys->ds_snapnames_zapobj =
1203  	    zap_create_norm(mos, U8_TEXTPREP_TOUPPER, DMU_OT_DSL_DS_SNAP_MAP,
1204  	    DMU_OT_NONE, 0, tx);
1205  	dsphys->ds_creation_time = gethrestime_sec();
1206  	dsphys->ds_creation_txg = tx->tx_txg == TXG_INITIAL ? 1 : tx->tx_txg;
1207  
1208  	if (origin == NULL) {
1209  		dsphys->ds_deadlist_obj = dsl_deadlist_alloc(mos, tx);
1210  	} else {
1211  		dsl_dataset_t *ohds; /* head of the origin snapshot */
1212  
1213  		dsphys->ds_prev_snap_obj = origin->ds_object;
1214  		dsphys->ds_prev_snap_txg =
1215  		    dsl_dataset_phys(origin)->ds_creation_txg;
1216  		dsphys->ds_referenced_bytes =
1217  		    dsl_dataset_phys(origin)->ds_referenced_bytes;
1218  		dsphys->ds_compressed_bytes =
1219  		    dsl_dataset_phys(origin)->ds_compressed_bytes;
1220  		dsphys->ds_uncompressed_bytes =
1221  		    dsl_dataset_phys(origin)->ds_uncompressed_bytes;
1222  		rrw_enter(&origin->ds_bp_rwlock, RW_READER, FTAG);
1223  		dsphys->ds_bp = dsl_dataset_phys(origin)->ds_bp;
1224  		rrw_exit(&origin->ds_bp_rwlock, FTAG);
1225  
1226  		/*
1227  		 * Inherit flags that describe the dataset's contents
1228  		 * (INCONSISTENT) or properties (Case Insensitive).
1229  		 */
1230  		dsphys->ds_flags |= dsl_dataset_phys(origin)->ds_flags &
1231  		    (DS_FLAG_INCONSISTENT | DS_FLAG_CI_DATASET);
1232  
1233  		for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
1234  			if (zfeature_active(f, origin->ds_feature[f])) {
1235  				dsl_dataset_activate_feature(dsobj, f,
1236  				    origin->ds_feature[f], tx);
1237  			}
1238  		}
1239  
1240  		dmu_buf_will_dirty(origin->ds_dbuf, tx);
1241  		dsl_dataset_phys(origin)->ds_num_children++;
1242  
1243  		VERIFY0(dsl_dataset_hold_obj(dp,
1244  		    dsl_dir_phys(origin->ds_dir)->dd_head_dataset_obj,
1245  		    FTAG, &ohds));
1246  		dsphys->ds_deadlist_obj = dsl_deadlist_clone(&ohds->ds_deadlist,
1247  		    dsphys->ds_prev_snap_txg, dsphys->ds_prev_snap_obj, tx);
1248  		dsl_dataset_rele(ohds, FTAG);
1249  
1250  		if (spa_version(dp->dp_spa) >= SPA_VERSION_NEXT_CLONES) {
1251  			if (dsl_dataset_phys(origin)->ds_next_clones_obj == 0) {
1252  				dsl_dataset_phys(origin)->ds_next_clones_obj =
1253  				    zap_create(mos,
1254  				    DMU_OT_NEXT_CLONES, DMU_OT_NONE, 0, tx);
1255  			}
1256  			VERIFY0(zap_add_int(mos,
1257  			    dsl_dataset_phys(origin)->ds_next_clones_obj,
1258  			    dsobj, tx));
1259  		}
1260  
1261  		dmu_buf_will_dirty(dd->dd_dbuf, tx);
1262  		dsl_dir_phys(dd)->dd_origin_obj = origin->ds_object;
1263  		if (spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
1264  			if (dsl_dir_phys(origin->ds_dir)->dd_clones == 0) {
1265  				dmu_buf_will_dirty(origin->ds_dir->dd_dbuf, tx);
1266  				dsl_dir_phys(origin->ds_dir)->dd_clones =
1267  				    zap_create(mos,
1268  				    DMU_OT_DSL_CLONES, DMU_OT_NONE, 0, tx);
1269  			}
1270  			VERIFY0(zap_add_int(mos,
1271  			    dsl_dir_phys(origin->ds_dir)->dd_clones,
1272  			    dsobj, tx));
1273  		}
1274  	}
1275  
1276  	/* handle encryption */
1277  	dsl_dataset_create_crypt_sync(dsobj, dd, origin, dcp, tx);
1278  
1279  	if (spa_version(dp->dp_spa) >= SPA_VERSION_UNIQUE_ACCURATE)
1280  		dsphys->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
1281  
1282  	dmu_buf_rele(dbuf, FTAG);
1283  
1284  	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1285  	dsl_dir_phys(dd)->dd_head_dataset_obj = dsobj;
1286  
1287  	return (dsobj);
1288  }
1289  
1290  static void
dsl_dataset_zero_zil(dsl_dataset_t * ds,dmu_tx_t * tx)1291  dsl_dataset_zero_zil(dsl_dataset_t *ds, dmu_tx_t *tx)
1292  {
1293  	objset_t *os;
1294  
1295  	VERIFY0(dmu_objset_from_ds(ds, &os));
1296  	if (memcmp(&os->os_zil_header, &zero_zil, sizeof (zero_zil)) != 0) {
1297  		dsl_pool_t *dp = ds->ds_dir->dd_pool;
1298  		zio_t *zio;
1299  
1300  		memset(&os->os_zil_header, 0, sizeof (os->os_zil_header));
1301  		if (os->os_encrypted)
1302  			os->os_next_write_raw[tx->tx_txg & TXG_MASK] = B_TRUE;
1303  
1304  		zio = zio_root(dp->dp_spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
1305  		dsl_dataset_sync(ds, zio, tx);
1306  		VERIFY0(zio_wait(zio));
1307  		dsl_dataset_sync_done(ds, tx);
1308  	}
1309  }
1310  
1311  uint64_t
dsl_dataset_create_sync(dsl_dir_t * pdd,const char * lastname,dsl_dataset_t * origin,uint64_t flags,cred_t * cr,dsl_crypto_params_t * dcp,dmu_tx_t * tx)1312  dsl_dataset_create_sync(dsl_dir_t *pdd, const char *lastname,
1313      dsl_dataset_t *origin, uint64_t flags, cred_t *cr,
1314      dsl_crypto_params_t *dcp, dmu_tx_t *tx)
1315  {
1316  	dsl_pool_t *dp = pdd->dd_pool;
1317  	uint64_t dsobj, ddobj;
1318  	dsl_dir_t *dd;
1319  
1320  	ASSERT(dmu_tx_is_syncing(tx));
1321  	ASSERT(lastname[0] != '@');
1322  	/*
1323  	 * Filesystems will eventually have their origin set to dp_origin_snap,
1324  	 * but that's taken care of in dsl_dataset_create_sync_dd. When
1325  	 * creating a filesystem, this function is called with origin equal to
1326  	 * NULL.
1327  	 */
1328  	if (origin != NULL)
1329  		ASSERT3P(origin, !=, dp->dp_origin_snap);
1330  
1331  	ddobj = dsl_dir_create_sync(dp, pdd, lastname, tx);
1332  	VERIFY0(dsl_dir_hold_obj(dp, ddobj, lastname, FTAG, &dd));
1333  
1334  	dsobj = dsl_dataset_create_sync_dd(dd, origin, dcp,
1335  	    flags & ~DS_CREATE_FLAG_NODIRTY, tx);
1336  
1337  	dsl_deleg_set_create_perms(dd, tx, cr);
1338  
1339  	/*
1340  	 * If we are creating a clone and the livelist feature is enabled,
1341  	 * add the entry DD_FIELD_LIVELIST to ZAP.
1342  	 */
1343  	if (origin != NULL &&
1344  	    spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LIVELIST)) {
1345  		objset_t *mos = dd->dd_pool->dp_meta_objset;
1346  		dsl_dir_zapify(dd, tx);
1347  		uint64_t obj = dsl_deadlist_alloc(mos, tx);
1348  		VERIFY0(zap_add(mos, dd->dd_object, DD_FIELD_LIVELIST,
1349  		    sizeof (uint64_t), 1, &obj, tx));
1350  		spa_feature_incr(dp->dp_spa, SPA_FEATURE_LIVELIST, tx);
1351  	}
1352  
1353  	/*
1354  	 * Since we're creating a new node we know it's a leaf, so we can
1355  	 * initialize the counts if the limit feature is active.
1356  	 */
1357  	if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_FS_SS_LIMIT)) {
1358  		uint64_t cnt = 0;
1359  		objset_t *os = dd->dd_pool->dp_meta_objset;
1360  
1361  		dsl_dir_zapify(dd, tx);
1362  		VERIFY0(zap_add(os, dd->dd_object, DD_FIELD_FILESYSTEM_COUNT,
1363  		    sizeof (cnt), 1, &cnt, tx));
1364  		VERIFY0(zap_add(os, dd->dd_object, DD_FIELD_SNAPSHOT_COUNT,
1365  		    sizeof (cnt), 1, &cnt, tx));
1366  	}
1367  
1368  	dsl_dir_rele(dd, FTAG);
1369  
1370  	/*
1371  	 * If we are creating a clone, make sure we zero out any stale
1372  	 * data from the origin snapshots zil header.
1373  	 */
1374  	if (origin != NULL && !(flags & DS_CREATE_FLAG_NODIRTY)) {
1375  		dsl_dataset_t *ds;
1376  
1377  		VERIFY0(dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
1378  		dsl_dataset_zero_zil(ds, tx);
1379  		dsl_dataset_rele(ds, FTAG);
1380  	}
1381  
1382  	return (dsobj);
1383  }
1384  
1385  /*
1386   * The unique space in the head dataset can be calculated by subtracting
1387   * the space used in the most recent snapshot, that is still being used
1388   * in this file system, from the space currently in use.  To figure out
1389   * the space in the most recent snapshot still in use, we need to take
1390   * the total space used in the snapshot and subtract out the space that
1391   * has been freed up since the snapshot was taken.
1392   */
1393  void
dsl_dataset_recalc_head_uniq(dsl_dataset_t * ds)1394  dsl_dataset_recalc_head_uniq(dsl_dataset_t *ds)
1395  {
1396  	uint64_t mrs_used;
1397  	uint64_t dlused, dlcomp, dluncomp;
1398  
1399  	ASSERT(!ds->ds_is_snapshot);
1400  
1401  	if (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0)
1402  		mrs_used = dsl_dataset_phys(ds->ds_prev)->ds_referenced_bytes;
1403  	else
1404  		mrs_used = 0;
1405  
1406  	dsl_deadlist_space(&ds->ds_deadlist, &dlused, &dlcomp, &dluncomp);
1407  
1408  	ASSERT3U(dlused, <=, mrs_used);
1409  	dsl_dataset_phys(ds)->ds_unique_bytes =
1410  	    dsl_dataset_phys(ds)->ds_referenced_bytes - (mrs_used - dlused);
1411  
1412  	if (spa_version(ds->ds_dir->dd_pool->dp_spa) >=
1413  	    SPA_VERSION_UNIQUE_ACCURATE)
1414  		dsl_dataset_phys(ds)->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
1415  }
1416  
1417  void
dsl_dataset_remove_from_next_clones(dsl_dataset_t * ds,uint64_t obj,dmu_tx_t * tx)1418  dsl_dataset_remove_from_next_clones(dsl_dataset_t *ds, uint64_t obj,
1419      dmu_tx_t *tx)
1420  {
1421  	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
1422  	uint64_t count __maybe_unused;
1423  	int err;
1424  
1425  	ASSERT(dsl_dataset_phys(ds)->ds_num_children >= 2);
1426  	err = zap_remove_int(mos, dsl_dataset_phys(ds)->ds_next_clones_obj,
1427  	    obj, tx);
1428  	/*
1429  	 * The err should not be ENOENT, but a bug in a previous version
1430  	 * of the code could cause upgrade_clones_cb() to not set
1431  	 * ds_next_snap_obj when it should, leading to a missing entry.
1432  	 * If we knew that the pool was created after
1433  	 * SPA_VERSION_NEXT_CLONES, we could assert that it isn't
1434  	 * ENOENT.  However, at least we can check that we don't have
1435  	 * too many entries in the next_clones_obj even after failing to
1436  	 * remove this one.
1437  	 */
1438  	if (err != ENOENT)
1439  		VERIFY0(err);
1440  	ASSERT0(zap_count(mos, dsl_dataset_phys(ds)->ds_next_clones_obj,
1441  	    &count));
1442  	ASSERT3U(count, <=, dsl_dataset_phys(ds)->ds_num_children - 2);
1443  }
1444  
1445  
1446  blkptr_t *
dsl_dataset_get_blkptr(dsl_dataset_t * ds)1447  dsl_dataset_get_blkptr(dsl_dataset_t *ds)
1448  {
1449  	return (&dsl_dataset_phys(ds)->ds_bp);
1450  }
1451  
1452  spa_t *
dsl_dataset_get_spa(dsl_dataset_t * ds)1453  dsl_dataset_get_spa(dsl_dataset_t *ds)
1454  {
1455  	return (ds->ds_dir->dd_pool->dp_spa);
1456  }
1457  
1458  void
dsl_dataset_dirty(dsl_dataset_t * ds,dmu_tx_t * tx)1459  dsl_dataset_dirty(dsl_dataset_t *ds, dmu_tx_t *tx)
1460  {
1461  	dsl_pool_t *dp;
1462  
1463  	if (ds == NULL) /* this is the meta-objset */
1464  		return;
1465  
1466  	ASSERT(ds->ds_objset != NULL);
1467  
1468  	if (dsl_dataset_phys(ds)->ds_next_snap_obj != 0)
1469  		panic("dirtying snapshot!");
1470  
1471  	/* Must not dirty a dataset in the same txg where it got snapshotted. */
1472  	ASSERT3U(tx->tx_txg, >, dsl_dataset_phys(ds)->ds_prev_snap_txg);
1473  
1474  	dp = ds->ds_dir->dd_pool;
1475  	if (txg_list_add(&dp->dp_dirty_datasets, ds, tx->tx_txg)) {
1476  		objset_t *os = ds->ds_objset;
1477  
1478  		/* up the hold count until we can be written out */
1479  		dmu_buf_add_ref(ds->ds_dbuf, ds);
1480  
1481  		/* if this dataset is encrypted, grab a reference to the DCK */
1482  		if (ds->ds_dir->dd_crypto_obj != 0 &&
1483  		    !os->os_raw_receive &&
1484  		    !os->os_next_write_raw[tx->tx_txg & TXG_MASK]) {
1485  			ASSERT3P(ds->ds_key_mapping, !=, NULL);
1486  			key_mapping_add_ref(ds->ds_key_mapping, ds);
1487  		}
1488  	}
1489  }
1490  
1491  static int
dsl_dataset_snapshot_reserve_space(dsl_dataset_t * ds,dmu_tx_t * tx)1492  dsl_dataset_snapshot_reserve_space(dsl_dataset_t *ds, dmu_tx_t *tx)
1493  {
1494  	uint64_t asize;
1495  
1496  	if (!dmu_tx_is_syncing(tx))
1497  		return (0);
1498  
1499  	/*
1500  	 * If there's an fs-only reservation, any blocks that might become
1501  	 * owned by the snapshot dataset must be accommodated by space
1502  	 * outside of the reservation.
1503  	 */
1504  	ASSERT(ds->ds_reserved == 0 || DS_UNIQUE_IS_ACCURATE(ds));
1505  	asize = MIN(dsl_dataset_phys(ds)->ds_unique_bytes, ds->ds_reserved);
1506  	if (asize > dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE))
1507  		return (SET_ERROR(ENOSPC));
1508  
1509  	/*
1510  	 * Propagate any reserved space for this snapshot to other
1511  	 * snapshot checks in this sync group.
1512  	 */
1513  	if (asize > 0)
1514  		dsl_dir_willuse_space(ds->ds_dir, asize, tx);
1515  
1516  	return (0);
1517  }
1518  
1519  int
dsl_dataset_snapshot_check_impl(dsl_dataset_t * ds,const char * snapname,dmu_tx_t * tx,boolean_t recv,uint64_t cnt,cred_t * cr,proc_t * proc)1520  dsl_dataset_snapshot_check_impl(dsl_dataset_t *ds, const char *snapname,
1521      dmu_tx_t *tx, boolean_t recv, uint64_t cnt, cred_t *cr, proc_t *proc)
1522  {
1523  	int error;
1524  	uint64_t value;
1525  
1526  	ds->ds_trysnap_txg = tx->tx_txg;
1527  
1528  	if (!dmu_tx_is_syncing(tx))
1529  		return (0);
1530  
1531  	/*
1532  	 * We don't allow multiple snapshots of the same txg.  If there
1533  	 * is already one, try again.
1534  	 */
1535  	if (dsl_dataset_phys(ds)->ds_prev_snap_txg >= tx->tx_txg)
1536  		return (SET_ERROR(EAGAIN));
1537  
1538  	/*
1539  	 * Check for conflicting snapshot name.
1540  	 */
1541  	error = dsl_dataset_snap_lookup(ds, snapname, &value);
1542  	if (error == 0)
1543  		return (SET_ERROR(EEXIST));
1544  	if (error != ENOENT)
1545  		return (error);
1546  
1547  	/*
1548  	 * We don't allow taking snapshots of inconsistent datasets, such as
1549  	 * those into which we are currently receiving.  However, if we are
1550  	 * creating this snapshot as part of a receive, this check will be
1551  	 * executed atomically with respect to the completion of the receive
1552  	 * itself but prior to the clearing of DS_FLAG_INCONSISTENT; in this
1553  	 * case we ignore this, knowing it will be fixed up for us shortly in
1554  	 * dmu_recv_end_sync().
1555  	 */
1556  	if (!recv && DS_IS_INCONSISTENT(ds))
1557  		return (SET_ERROR(EBUSY));
1558  
1559  	/*
1560  	 * Skip the check for temporary snapshots or if we have already checked
1561  	 * the counts in dsl_dataset_snapshot_check. This means we really only
1562  	 * check the count here when we're receiving a stream.
1563  	 */
1564  	if (cnt != 0 && cr != NULL) {
1565  		error = dsl_fs_ss_limit_check(ds->ds_dir, cnt,
1566  		    ZFS_PROP_SNAPSHOT_LIMIT, NULL, cr, proc);
1567  		if (error != 0)
1568  			return (error);
1569  	}
1570  
1571  	error = dsl_dataset_snapshot_reserve_space(ds, tx);
1572  	if (error != 0)
1573  		return (error);
1574  
1575  	return (0);
1576  }
1577  
1578  int
dsl_dataset_snapshot_check(void * arg,dmu_tx_t * tx)1579  dsl_dataset_snapshot_check(void *arg, dmu_tx_t *tx)
1580  {
1581  	dsl_dataset_snapshot_arg_t *ddsa = arg;
1582  	dsl_pool_t *dp = dmu_tx_pool(tx);
1583  	nvpair_t *pair;
1584  	int rv = 0;
1585  
1586  	/*
1587  	 * Pre-compute how many total new snapshots will be created for each
1588  	 * level in the tree and below. This is needed for validating the
1589  	 * snapshot limit when either taking a recursive snapshot or when
1590  	 * taking multiple snapshots.
1591  	 *
1592  	 * The problem is that the counts are not actually adjusted when
1593  	 * we are checking, only when we finally sync. For a single snapshot,
1594  	 * this is easy, the count will increase by 1 at each node up the tree,
1595  	 * but its more complicated for the recursive/multiple snapshot case.
1596  	 *
1597  	 * The dsl_fs_ss_limit_check function does recursively check the count
1598  	 * at each level up the tree but since it is validating each snapshot
1599  	 * independently we need to be sure that we are validating the complete
1600  	 * count for the entire set of snapshots. We do this by rolling up the
1601  	 * counts for each component of the name into an nvlist and then
1602  	 * checking each of those cases with the aggregated count.
1603  	 *
1604  	 * This approach properly handles not only the recursive snapshot
1605  	 * case (where we get all of those on the ddsa_snaps list) but also
1606  	 * the sibling case (e.g. snapshot a/b and a/c so that we will also
1607  	 * validate the limit on 'a' using a count of 2).
1608  	 *
1609  	 * We validate the snapshot names in the third loop and only report
1610  	 * name errors once.
1611  	 */
1612  	if (dmu_tx_is_syncing(tx)) {
1613  		char *nm;
1614  		nvlist_t *cnt_track = NULL;
1615  		cnt_track = fnvlist_alloc();
1616  
1617  		nm = kmem_alloc(MAXPATHLEN, KM_SLEEP);
1618  
1619  		/* Rollup aggregated counts into the cnt_track list */
1620  		for (pair = nvlist_next_nvpair(ddsa->ddsa_snaps, NULL);
1621  		    pair != NULL;
1622  		    pair = nvlist_next_nvpair(ddsa->ddsa_snaps, pair)) {
1623  			char *pdelim;
1624  			uint64_t val;
1625  
1626  			(void) strlcpy(nm, nvpair_name(pair), MAXPATHLEN);
1627  			pdelim = strchr(nm, '@');
1628  			if (pdelim == NULL)
1629  				continue;
1630  			*pdelim = '\0';
1631  
1632  			do {
1633  				if (nvlist_lookup_uint64(cnt_track, nm,
1634  				    &val) == 0) {
1635  					/* update existing entry */
1636  					fnvlist_add_uint64(cnt_track, nm,
1637  					    val + 1);
1638  				} else {
1639  					/* add to list */
1640  					fnvlist_add_uint64(cnt_track, nm, 1);
1641  				}
1642  
1643  				pdelim = strrchr(nm, '/');
1644  				if (pdelim != NULL)
1645  					*pdelim = '\0';
1646  			} while (pdelim != NULL);
1647  		}
1648  
1649  		kmem_free(nm, MAXPATHLEN);
1650  
1651  		/* Check aggregated counts at each level */
1652  		for (pair = nvlist_next_nvpair(cnt_track, NULL);
1653  		    pair != NULL; pair = nvlist_next_nvpair(cnt_track, pair)) {
1654  			int error = 0;
1655  			const char *name;
1656  			uint64_t cnt = 0;
1657  			dsl_dataset_t *ds;
1658  
1659  			name = nvpair_name(pair);
1660  			cnt = fnvpair_value_uint64(pair);
1661  			ASSERT(cnt > 0);
1662  
1663  			error = dsl_dataset_hold(dp, name, FTAG, &ds);
1664  			if (error == 0) {
1665  				error = dsl_fs_ss_limit_check(ds->ds_dir, cnt,
1666  				    ZFS_PROP_SNAPSHOT_LIMIT, NULL,
1667  				    ddsa->ddsa_cr, ddsa->ddsa_proc);
1668  				dsl_dataset_rele(ds, FTAG);
1669  			}
1670  
1671  			if (error != 0) {
1672  				if (ddsa->ddsa_errors != NULL)
1673  					fnvlist_add_int32(ddsa->ddsa_errors,
1674  					    name, error);
1675  				rv = error;
1676  				/* only report one error for this check */
1677  				break;
1678  			}
1679  		}
1680  		nvlist_free(cnt_track);
1681  	}
1682  
1683  	for (pair = nvlist_next_nvpair(ddsa->ddsa_snaps, NULL);
1684  	    pair != NULL; pair = nvlist_next_nvpair(ddsa->ddsa_snaps, pair)) {
1685  		int error = 0;
1686  		dsl_dataset_t *ds;
1687  		const char *name, *atp = NULL;
1688  		char dsname[ZFS_MAX_DATASET_NAME_LEN];
1689  
1690  		name = nvpair_name(pair);
1691  		if (strlen(name) >= ZFS_MAX_DATASET_NAME_LEN)
1692  			error = SET_ERROR(ENAMETOOLONG);
1693  		if (error == 0) {
1694  			atp = strchr(name, '@');
1695  			if (atp == NULL)
1696  				error = SET_ERROR(EINVAL);
1697  			if (error == 0)
1698  				(void) strlcpy(dsname, name, atp - name + 1);
1699  		}
1700  		if (error == 0)
1701  			error = dsl_dataset_hold(dp, dsname, FTAG, &ds);
1702  		if (error == 0) {
1703  			/* passing 0/NULL skips dsl_fs_ss_limit_check */
1704  			error = dsl_dataset_snapshot_check_impl(ds,
1705  			    atp + 1, tx, B_FALSE, 0, NULL, NULL);
1706  			dsl_dataset_rele(ds, FTAG);
1707  		}
1708  
1709  		if (error != 0) {
1710  			if (ddsa->ddsa_errors != NULL) {
1711  				fnvlist_add_int32(ddsa->ddsa_errors,
1712  				    name, error);
1713  			}
1714  			rv = error;
1715  		}
1716  	}
1717  
1718  	return (rv);
1719  }
1720  
1721  void
dsl_dataset_snapshot_sync_impl(dsl_dataset_t * ds,const char * snapname,dmu_tx_t * tx)1722  dsl_dataset_snapshot_sync_impl(dsl_dataset_t *ds, const char *snapname,
1723      dmu_tx_t *tx)
1724  {
1725  	dsl_pool_t *dp = ds->ds_dir->dd_pool;
1726  	dmu_buf_t *dbuf;
1727  	dsl_dataset_phys_t *dsphys;
1728  	uint64_t dsobj, crtxg;
1729  	objset_t *mos = dp->dp_meta_objset;
1730  	objset_t *os __maybe_unused;
1731  
1732  	ASSERT(RRW_WRITE_HELD(&dp->dp_config_rwlock));
1733  
1734  	/*
1735  	 * If we are on an old pool, the zil must not be active, in which
1736  	 * case it will be zeroed.  Usually zil_suspend() accomplishes this.
1737  	 */
1738  	ASSERT(spa_version(dmu_tx_pool(tx)->dp_spa) >= SPA_VERSION_FAST_SNAP ||
1739  	    dmu_objset_from_ds(ds, &os) != 0 ||
1740  	    memcmp(&os->os_phys->os_zil_header, &zero_zil,
1741  	    sizeof (zero_zil)) == 0);
1742  
1743  	/* Should not snapshot a dirty dataset. */
1744  	ASSERT(!txg_list_member(&ds->ds_dir->dd_pool->dp_dirty_datasets,
1745  	    ds, tx->tx_txg));
1746  
1747  	dsl_fs_ss_count_adjust(ds->ds_dir, 1, DD_FIELD_SNAPSHOT_COUNT, tx);
1748  
1749  	/*
1750  	 * The origin's ds_creation_txg has to be < TXG_INITIAL
1751  	 */
1752  	if (strcmp(snapname, ORIGIN_DIR_NAME) == 0)
1753  		crtxg = 1;
1754  	else
1755  		crtxg = tx->tx_txg;
1756  
1757  	dsobj = dmu_object_alloc(mos, DMU_OT_DSL_DATASET, 0,
1758  	    DMU_OT_DSL_DATASET, sizeof (dsl_dataset_phys_t), tx);
1759  	VERIFY0(dmu_bonus_hold(mos, dsobj, FTAG, &dbuf));
1760  	dmu_buf_will_dirty(dbuf, tx);
1761  	dsphys = dbuf->db_data;
1762  	memset(dsphys, 0, sizeof (dsl_dataset_phys_t));
1763  	dsphys->ds_dir_obj = ds->ds_dir->dd_object;
1764  	dsphys->ds_fsid_guid = unique_create();
1765  	(void) random_get_pseudo_bytes((void*)&dsphys->ds_guid,
1766  	    sizeof (dsphys->ds_guid));
1767  	dsphys->ds_prev_snap_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
1768  	dsphys->ds_prev_snap_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;
1769  	dsphys->ds_next_snap_obj = ds->ds_object;
1770  	dsphys->ds_num_children = 1;
1771  	dsphys->ds_creation_time = gethrestime_sec();
1772  	dsphys->ds_creation_txg = crtxg;
1773  	dsphys->ds_deadlist_obj = dsl_dataset_phys(ds)->ds_deadlist_obj;
1774  	dsphys->ds_referenced_bytes = dsl_dataset_phys(ds)->ds_referenced_bytes;
1775  	dsphys->ds_compressed_bytes = dsl_dataset_phys(ds)->ds_compressed_bytes;
1776  	dsphys->ds_uncompressed_bytes =
1777  	    dsl_dataset_phys(ds)->ds_uncompressed_bytes;
1778  	dsphys->ds_flags = dsl_dataset_phys(ds)->ds_flags;
1779  	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
1780  	dsphys->ds_bp = dsl_dataset_phys(ds)->ds_bp;
1781  	rrw_exit(&ds->ds_bp_rwlock, FTAG);
1782  	dmu_buf_rele(dbuf, FTAG);
1783  
1784  	for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
1785  		if (zfeature_active(f, ds->ds_feature[f])) {
1786  			dsl_dataset_activate_feature(dsobj, f,
1787  			    ds->ds_feature[f], tx);
1788  		}
1789  	}
1790  
1791  	ASSERT3U(ds->ds_prev != 0, ==,
1792  	    dsl_dataset_phys(ds)->ds_prev_snap_obj != 0);
1793  	if (ds->ds_prev) {
1794  		uint64_t next_clones_obj =
1795  		    dsl_dataset_phys(ds->ds_prev)->ds_next_clones_obj;
1796  		ASSERT(dsl_dataset_phys(ds->ds_prev)->ds_next_snap_obj ==
1797  		    ds->ds_object ||
1798  		    dsl_dataset_phys(ds->ds_prev)->ds_num_children > 1);
1799  		if (dsl_dataset_phys(ds->ds_prev)->ds_next_snap_obj ==
1800  		    ds->ds_object) {
1801  			dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
1802  			ASSERT3U(dsl_dataset_phys(ds)->ds_prev_snap_txg, ==,
1803  			    dsl_dataset_phys(ds->ds_prev)->ds_creation_txg);
1804  			dsl_dataset_phys(ds->ds_prev)->ds_next_snap_obj = dsobj;
1805  		} else if (next_clones_obj != 0) {
1806  			dsl_dataset_remove_from_next_clones(ds->ds_prev,
1807  			    dsphys->ds_next_snap_obj, tx);
1808  			VERIFY0(zap_add_int(mos,
1809  			    next_clones_obj, dsobj, tx));
1810  		}
1811  	}
1812  
1813  	/*
1814  	 * If we have a reference-reservation on this dataset, we will
1815  	 * need to increase the amount of refreservation being charged
1816  	 * since our unique space is going to zero.
1817  	 */
1818  	if (ds->ds_reserved) {
1819  		int64_t delta;
1820  		ASSERT(DS_UNIQUE_IS_ACCURATE(ds));
1821  		delta = MIN(dsl_dataset_phys(ds)->ds_unique_bytes,
1822  		    ds->ds_reserved);
1823  		dsl_dir_diduse_space(ds->ds_dir, DD_USED_REFRSRV,
1824  		    delta, 0, 0, tx);
1825  	}
1826  
1827  	dmu_buf_will_dirty(ds->ds_dbuf, tx);
1828  	dsl_dataset_phys(ds)->ds_deadlist_obj =
1829  	    dsl_deadlist_clone(&ds->ds_deadlist, UINT64_MAX,
1830  	    dsl_dataset_phys(ds)->ds_prev_snap_obj, tx);
1831  	dsl_deadlist_close(&ds->ds_deadlist);
1832  	VERIFY0(dsl_deadlist_open(&ds->ds_deadlist, mos,
1833  	    dsl_dataset_phys(ds)->ds_deadlist_obj));
1834  	dsl_deadlist_add_key(&ds->ds_deadlist,
1835  	    dsl_dataset_phys(ds)->ds_prev_snap_txg, tx);
1836  	dsl_bookmark_snapshotted(ds, tx);
1837  
1838  	if (dsl_dataset_remap_deadlist_exists(ds)) {
1839  		uint64_t remap_deadlist_obj =
1840  		    dsl_dataset_get_remap_deadlist_object(ds);
1841  		/*
1842  		 * Move the remap_deadlist to the snapshot.  The head
1843  		 * will create a new remap deadlist on demand, from
1844  		 * dsl_dataset_block_remapped().
1845  		 */
1846  		dsl_dataset_unset_remap_deadlist_object(ds, tx);
1847  		dsl_deadlist_close(&ds->ds_remap_deadlist);
1848  
1849  		dmu_object_zapify(mos, dsobj, DMU_OT_DSL_DATASET, tx);
1850  		VERIFY0(zap_add(mos, dsobj, DS_FIELD_REMAP_DEADLIST,
1851  		    sizeof (remap_deadlist_obj), 1, &remap_deadlist_obj, tx));
1852  	}
1853  
1854  	/*
1855  	 * Create a ivset guid for this snapshot if the dataset is
1856  	 * encrypted. This may be overridden by a raw receive. A
1857  	 * previous implementation of this code did not have this
1858  	 * field as part of the on-disk format for ZFS encryption
1859  	 * (see errata #4). As part of the remediation for this
1860  	 * issue, we ask the user to enable the bookmark_v2 feature
1861  	 * which is now a dependency of the encryption feature. We
1862  	 * use this as a heuristic to determine when the user has
1863  	 * elected to correct any datasets created with the old code.
1864  	 * As a result, we only do this step if the bookmark_v2
1865  	 * feature is enabled, which limits the number of states a
1866  	 * given pool / dataset can be in with regards to terms of
1867  	 * correcting the issue.
1868  	 */
1869  	if (ds->ds_dir->dd_crypto_obj != 0 &&
1870  	    spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_BOOKMARK_V2)) {
1871  		uint64_t ivset_guid = unique_create();
1872  
1873  		dmu_object_zapify(mos, dsobj, DMU_OT_DSL_DATASET, tx);
1874  		VERIFY0(zap_add(mos, dsobj, DS_FIELD_IVSET_GUID,
1875  		    sizeof (ivset_guid), 1, &ivset_guid, tx));
1876  	}
1877  
1878  	ASSERT3U(dsl_dataset_phys(ds)->ds_prev_snap_txg, <, tx->tx_txg);
1879  	dsl_dataset_phys(ds)->ds_prev_snap_obj = dsobj;
1880  	dsl_dataset_phys(ds)->ds_prev_snap_txg = crtxg;
1881  	dsl_dataset_phys(ds)->ds_unique_bytes = 0;
1882  
1883  	if (spa_version(dp->dp_spa) >= SPA_VERSION_UNIQUE_ACCURATE)
1884  		dsl_dataset_phys(ds)->ds_flags |= DS_FLAG_UNIQUE_ACCURATE;
1885  
1886  	VERIFY0(zap_add(mos, dsl_dataset_phys(ds)->ds_snapnames_zapobj,
1887  	    snapname, 8, 1, &dsobj, tx));
1888  
1889  	if (ds->ds_prev)
1890  		dsl_dataset_rele(ds->ds_prev, ds);
1891  	VERIFY0(dsl_dataset_hold_obj(dp,
1892  	    dsl_dataset_phys(ds)->ds_prev_snap_obj, ds, &ds->ds_prev));
1893  
1894  	dsl_scan_ds_snapshotted(ds, tx);
1895  
1896  	dsl_dir_snap_cmtime_update(ds->ds_dir, tx);
1897  
1898  	if (zfs_snapshot_history_enabled)
1899  		spa_history_log_internal_ds(ds->ds_prev, "snapshot", tx, " ");
1900  }
1901  
1902  void
dsl_dataset_snapshot_sync(void * arg,dmu_tx_t * tx)1903  dsl_dataset_snapshot_sync(void *arg, dmu_tx_t *tx)
1904  {
1905  	dsl_dataset_snapshot_arg_t *ddsa = arg;
1906  	dsl_pool_t *dp = dmu_tx_pool(tx);
1907  	nvpair_t *pair;
1908  
1909  	for (pair = nvlist_next_nvpair(ddsa->ddsa_snaps, NULL);
1910  	    pair != NULL; pair = nvlist_next_nvpair(ddsa->ddsa_snaps, pair)) {
1911  		dsl_dataset_t *ds;
1912  		const char *name, *atp;
1913  		char dsname[ZFS_MAX_DATASET_NAME_LEN];
1914  
1915  		name = nvpair_name(pair);
1916  		atp = strchr(name, '@');
1917  		(void) strlcpy(dsname, name, atp - name + 1);
1918  		VERIFY0(dsl_dataset_hold(dp, dsname, FTAG, &ds));
1919  
1920  		dsl_dataset_snapshot_sync_impl(ds, atp + 1, tx);
1921  		if (ddsa->ddsa_props != NULL) {
1922  			dsl_props_set_sync_impl(ds->ds_prev,
1923  			    ZPROP_SRC_LOCAL, ddsa->ddsa_props, tx);
1924  		}
1925  		dsl_dataset_rele(ds, FTAG);
1926  	}
1927  }
1928  
1929  /*
1930   * The snapshots must all be in the same pool.
1931   * All-or-nothing: if there are any failures, nothing will be modified.
1932   */
1933  int
dsl_dataset_snapshot(nvlist_t * snaps,nvlist_t * props,nvlist_t * errors)1934  dsl_dataset_snapshot(nvlist_t *snaps, nvlist_t *props, nvlist_t *errors)
1935  {
1936  	dsl_dataset_snapshot_arg_t ddsa;
1937  	nvpair_t *pair;
1938  	boolean_t needsuspend;
1939  	int error;
1940  	spa_t *spa;
1941  	const char *firstname;
1942  	nvlist_t *suspended = NULL;
1943  
1944  	pair = nvlist_next_nvpair(snaps, NULL);
1945  	if (pair == NULL)
1946  		return (0);
1947  	firstname = nvpair_name(pair);
1948  
1949  	error = spa_open(firstname, &spa, FTAG);
1950  	if (error != 0)
1951  		return (error);
1952  	needsuspend = (spa_version(spa) < SPA_VERSION_FAST_SNAP);
1953  	spa_close(spa, FTAG);
1954  
1955  	if (needsuspend) {
1956  		suspended = fnvlist_alloc();
1957  		for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
1958  		    pair = nvlist_next_nvpair(snaps, pair)) {
1959  			char fsname[ZFS_MAX_DATASET_NAME_LEN];
1960  			const char *snapname = nvpair_name(pair);
1961  			const char *atp;
1962  			void *cookie;
1963  
1964  			atp = strchr(snapname, '@');
1965  			if (atp == NULL) {
1966  				error = SET_ERROR(EINVAL);
1967  				break;
1968  			}
1969  			(void) strlcpy(fsname, snapname, atp - snapname + 1);
1970  
1971  			error = zil_suspend(fsname, &cookie);
1972  			if (error != 0)
1973  				break;
1974  			fnvlist_add_uint64(suspended, fsname,
1975  			    (uintptr_t)cookie);
1976  		}
1977  	}
1978  
1979  	ddsa.ddsa_snaps = snaps;
1980  	ddsa.ddsa_props = props;
1981  	ddsa.ddsa_errors = errors;
1982  	ddsa.ddsa_cr = CRED();
1983  	ddsa.ddsa_proc = curproc;
1984  
1985  	if (error == 0) {
1986  		error = dsl_sync_task(firstname, dsl_dataset_snapshot_check,
1987  		    dsl_dataset_snapshot_sync, &ddsa,
1988  		    fnvlist_num_pairs(snaps) * 3, ZFS_SPACE_CHECK_NORMAL);
1989  	}
1990  
1991  	if (suspended != NULL) {
1992  		for (pair = nvlist_next_nvpair(suspended, NULL); pair != NULL;
1993  		    pair = nvlist_next_nvpair(suspended, pair)) {
1994  			zil_resume((void *)(uintptr_t)
1995  			    fnvpair_value_uint64(pair));
1996  		}
1997  		fnvlist_free(suspended);
1998  	}
1999  
2000  	if (error == 0) {
2001  		for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
2002  		    pair = nvlist_next_nvpair(snaps, pair)) {
2003  			zvol_create_minor(nvpair_name(pair));
2004  		}
2005  	}
2006  
2007  	return (error);
2008  }
2009  
2010  typedef struct dsl_dataset_snapshot_tmp_arg {
2011  	const char *ddsta_fsname;
2012  	const char *ddsta_snapname;
2013  	minor_t ddsta_cleanup_minor;
2014  	const char *ddsta_htag;
2015  } dsl_dataset_snapshot_tmp_arg_t;
2016  
2017  static int
dsl_dataset_snapshot_tmp_check(void * arg,dmu_tx_t * tx)2018  dsl_dataset_snapshot_tmp_check(void *arg, dmu_tx_t *tx)
2019  {
2020  	dsl_dataset_snapshot_tmp_arg_t *ddsta = arg;
2021  	dsl_pool_t *dp = dmu_tx_pool(tx);
2022  	dsl_dataset_t *ds;
2023  	int error;
2024  
2025  	error = dsl_dataset_hold(dp, ddsta->ddsta_fsname, FTAG, &ds);
2026  	if (error != 0)
2027  		return (error);
2028  
2029  	/* NULL cred means no limit check for tmp snapshot */
2030  	error = dsl_dataset_snapshot_check_impl(ds, ddsta->ddsta_snapname,
2031  	    tx, B_FALSE, 0, NULL, NULL);
2032  	if (error != 0) {
2033  		dsl_dataset_rele(ds, FTAG);
2034  		return (error);
2035  	}
2036  
2037  	if (spa_version(dp->dp_spa) < SPA_VERSION_USERREFS) {
2038  		dsl_dataset_rele(ds, FTAG);
2039  		return (SET_ERROR(ENOTSUP));
2040  	}
2041  	error = dsl_dataset_user_hold_check_one(NULL, ddsta->ddsta_htag,
2042  	    B_TRUE, tx);
2043  	if (error != 0) {
2044  		dsl_dataset_rele(ds, FTAG);
2045  		return (error);
2046  	}
2047  
2048  	dsl_dataset_rele(ds, FTAG);
2049  	return (0);
2050  }
2051  
2052  static void
dsl_dataset_snapshot_tmp_sync(void * arg,dmu_tx_t * tx)2053  dsl_dataset_snapshot_tmp_sync(void *arg, dmu_tx_t *tx)
2054  {
2055  	dsl_dataset_snapshot_tmp_arg_t *ddsta = arg;
2056  	dsl_pool_t *dp = dmu_tx_pool(tx);
2057  	dsl_dataset_t *ds = NULL;
2058  
2059  	VERIFY0(dsl_dataset_hold(dp, ddsta->ddsta_fsname, FTAG, &ds));
2060  
2061  	dsl_dataset_snapshot_sync_impl(ds, ddsta->ddsta_snapname, tx);
2062  	dsl_dataset_user_hold_sync_one(ds->ds_prev, ddsta->ddsta_htag,
2063  	    ddsta->ddsta_cleanup_minor, gethrestime_sec(), tx);
2064  	dsl_destroy_snapshot_sync_impl(ds->ds_prev, B_TRUE, tx);
2065  
2066  	dsl_dataset_rele(ds, FTAG);
2067  }
2068  
2069  int
dsl_dataset_snapshot_tmp(const char * fsname,const char * snapname,minor_t cleanup_minor,const char * htag)2070  dsl_dataset_snapshot_tmp(const char *fsname, const char *snapname,
2071      minor_t cleanup_minor, const char *htag)
2072  {
2073  	dsl_dataset_snapshot_tmp_arg_t ddsta;
2074  	int error;
2075  	spa_t *spa;
2076  	boolean_t needsuspend;
2077  	void *cookie;
2078  
2079  	ddsta.ddsta_fsname = fsname;
2080  	ddsta.ddsta_snapname = snapname;
2081  	ddsta.ddsta_cleanup_minor = cleanup_minor;
2082  	ddsta.ddsta_htag = htag;
2083  
2084  	error = spa_open(fsname, &spa, FTAG);
2085  	if (error != 0)
2086  		return (error);
2087  	needsuspend = (spa_version(spa) < SPA_VERSION_FAST_SNAP);
2088  	spa_close(spa, FTAG);
2089  
2090  	if (needsuspend) {
2091  		error = zil_suspend(fsname, &cookie);
2092  		if (error != 0)
2093  			return (error);
2094  	}
2095  
2096  	error = dsl_sync_task(fsname, dsl_dataset_snapshot_tmp_check,
2097  	    dsl_dataset_snapshot_tmp_sync, &ddsta, 3, ZFS_SPACE_CHECK_RESERVED);
2098  
2099  	if (needsuspend)
2100  		zil_resume(cookie);
2101  	return (error);
2102  }
2103  
2104  /* Nonblocking dataset sync. Assumes dataset:objset is always 1:1 */
2105  void
dsl_dataset_sync(dsl_dataset_t * ds,zio_t * rio,dmu_tx_t * tx)2106  dsl_dataset_sync(dsl_dataset_t *ds, zio_t *rio, dmu_tx_t *tx)
2107  {
2108  	ASSERT(dmu_tx_is_syncing(tx));
2109  	ASSERT(ds->ds_objset != NULL);
2110  	ASSERT(dsl_dataset_phys(ds)->ds_next_snap_obj == 0);
2111  
2112  	/*
2113  	 * in case we had to change ds_fsid_guid when we opened it,
2114  	 * sync it out now.
2115  	 */
2116  	dmu_buf_will_dirty(ds->ds_dbuf, tx);
2117  	dsl_dataset_phys(ds)->ds_fsid_guid = ds->ds_fsid_guid;
2118  
2119  	if (ds->ds_resume_bytes[tx->tx_txg & TXG_MASK] != 0) {
2120  		VERIFY0(zap_update(tx->tx_pool->dp_meta_objset,
2121  		    ds->ds_object, DS_FIELD_RESUME_OBJECT, 8, 1,
2122  		    &ds->ds_resume_object[tx->tx_txg & TXG_MASK], tx));
2123  		VERIFY0(zap_update(tx->tx_pool->dp_meta_objset,
2124  		    ds->ds_object, DS_FIELD_RESUME_OFFSET, 8, 1,
2125  		    &ds->ds_resume_offset[tx->tx_txg & TXG_MASK], tx));
2126  		VERIFY0(zap_update(tx->tx_pool->dp_meta_objset,
2127  		    ds->ds_object, DS_FIELD_RESUME_BYTES, 8, 1,
2128  		    &ds->ds_resume_bytes[tx->tx_txg & TXG_MASK], tx));
2129  		ds->ds_resume_object[tx->tx_txg & TXG_MASK] = 0;
2130  		ds->ds_resume_offset[tx->tx_txg & TXG_MASK] = 0;
2131  		ds->ds_resume_bytes[tx->tx_txg & TXG_MASK] = 0;
2132  	}
2133  
2134  	dmu_objset_sync(ds->ds_objset, rio, tx);
2135  }
2136  
2137  /*
2138   * Check if the percentage of blocks shared between the clone and the
2139   * snapshot (as opposed to those that are clone only) is below a certain
2140   * threshold
2141   */
2142  static boolean_t
dsl_livelist_should_disable(dsl_dataset_t * ds)2143  dsl_livelist_should_disable(dsl_dataset_t *ds)
2144  {
2145  	uint64_t used, referenced;
2146  	int percent_shared;
2147  
2148  	used = dsl_dir_get_usedds(ds->ds_dir);
2149  	referenced = dsl_get_referenced(ds);
2150  	if (referenced == 0)
2151  		return (B_FALSE);
2152  	percent_shared = (100 * (referenced - used)) / referenced;
2153  	if (percent_shared <= zfs_livelist_min_percent_shared)
2154  		return (B_TRUE);
2155  	return (B_FALSE);
2156  }
2157  
2158  /*
2159   *  Check if it is possible to combine two livelist entries into one.
2160   *  This is the case if the combined number of 'live' blkptrs (ALLOCs that
2161   *  don't have a matching FREE) is under the maximum sublist size.
2162   *  We check this by subtracting twice the total number of frees from the total
2163   *  number of blkptrs. FREEs are counted twice because each FREE blkptr
2164   *  will cancel out an ALLOC blkptr when the livelist is processed.
2165   */
2166  static boolean_t
dsl_livelist_should_condense(dsl_deadlist_entry_t * first,dsl_deadlist_entry_t * next)2167  dsl_livelist_should_condense(dsl_deadlist_entry_t *first,
2168      dsl_deadlist_entry_t *next)
2169  {
2170  	uint64_t total_free = first->dle_bpobj.bpo_phys->bpo_num_freed +
2171  	    next->dle_bpobj.bpo_phys->bpo_num_freed;
2172  	uint64_t total_entries = first->dle_bpobj.bpo_phys->bpo_num_blkptrs +
2173  	    next->dle_bpobj.bpo_phys->bpo_num_blkptrs;
2174  	if ((total_entries - (2 * total_free)) < zfs_livelist_max_entries)
2175  		return (B_TRUE);
2176  	return (B_FALSE);
2177  }
2178  
2179  typedef struct try_condense_arg {
2180  	spa_t *spa;
2181  	dsl_dataset_t *ds;
2182  } try_condense_arg_t;
2183  
2184  /*
2185   * Iterate over the livelist entries, searching for a pair to condense.
2186   * A nonzero return value means stop, 0 means keep looking.
2187   */
2188  static int
dsl_livelist_try_condense(void * arg,dsl_deadlist_entry_t * first)2189  dsl_livelist_try_condense(void *arg, dsl_deadlist_entry_t *first)
2190  {
2191  	try_condense_arg_t *tca = arg;
2192  	spa_t *spa = tca->spa;
2193  	dsl_dataset_t *ds = tca->ds;
2194  	dsl_deadlist_t *ll = &ds->ds_dir->dd_livelist;
2195  	dsl_deadlist_entry_t *next;
2196  
2197  	/* The condense thread has not yet been created at import */
2198  	if (spa->spa_livelist_condense_zthr == NULL)
2199  		return (1);
2200  
2201  	/* A condense is already in progress */
2202  	if (spa->spa_to_condense.ds != NULL)
2203  		return (1);
2204  
2205  	next = AVL_NEXT(&ll->dl_tree, &first->dle_node);
2206  	/* The livelist has only one entry - don't condense it */
2207  	if (next == NULL)
2208  		return (1);
2209  
2210  	/* Next is the newest entry - don't condense it */
2211  	if (AVL_NEXT(&ll->dl_tree, &next->dle_node) == NULL)
2212  		return (1);
2213  
2214  	/* This pair is not ready to condense but keep looking */
2215  	if (!dsl_livelist_should_condense(first, next))
2216  		return (0);
2217  
2218  	/*
2219  	 * Add a ref to prevent the dataset from being evicted while
2220  	 * the condense zthr or synctask are running. Ref will be
2221  	 * released at the end of the condense synctask
2222  	 */
2223  	dmu_buf_add_ref(ds->ds_dbuf, spa);
2224  
2225  	spa->spa_to_condense.ds = ds;
2226  	spa->spa_to_condense.first = first;
2227  	spa->spa_to_condense.next = next;
2228  	spa->spa_to_condense.syncing = B_FALSE;
2229  	spa->spa_to_condense.cancelled = B_FALSE;
2230  
2231  	zthr_wakeup(spa->spa_livelist_condense_zthr);
2232  	return (1);
2233  }
2234  
2235  static void
dsl_flush_pending_livelist(dsl_dataset_t * ds,dmu_tx_t * tx)2236  dsl_flush_pending_livelist(dsl_dataset_t *ds, dmu_tx_t *tx)
2237  {
2238  	dsl_dir_t *dd = ds->ds_dir;
2239  	spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
2240  	dsl_deadlist_entry_t *last = dsl_deadlist_last(&dd->dd_livelist);
2241  
2242  	/* Check if we need to add a new sub-livelist */
2243  	if (last == NULL) {
2244  		/* The livelist is empty */
2245  		dsl_deadlist_add_key(&dd->dd_livelist,
2246  		    tx->tx_txg - 1, tx);
2247  	} else if (spa_sync_pass(spa) == 1) {
2248  		/*
2249  		 * Check if the newest entry is full. If it is, make a new one.
2250  		 * We only do this once per sync because we could overfill a
2251  		 * sublist in one sync pass and don't want to add another entry
2252  		 * for a txg that is already represented. This ensures that
2253  		 * blkptrs born in the same txg are stored in the same sublist.
2254  		 */
2255  		bpobj_t bpobj = last->dle_bpobj;
2256  		uint64_t all = bpobj.bpo_phys->bpo_num_blkptrs;
2257  		uint64_t free = bpobj.bpo_phys->bpo_num_freed;
2258  		uint64_t alloc = all - free;
2259  		if (alloc > zfs_livelist_max_entries) {
2260  			dsl_deadlist_add_key(&dd->dd_livelist,
2261  			    tx->tx_txg - 1, tx);
2262  		}
2263  	}
2264  
2265  	/* Insert each entry into the on-disk livelist */
2266  	bplist_iterate(&dd->dd_pending_allocs,
2267  	    dsl_deadlist_insert_alloc_cb, &dd->dd_livelist, tx);
2268  	bplist_iterate(&dd->dd_pending_frees,
2269  	    dsl_deadlist_insert_free_cb, &dd->dd_livelist, tx);
2270  
2271  	/* Attempt to condense every pair of adjacent entries */
2272  	try_condense_arg_t arg = {
2273  	    .spa = spa,
2274  	    .ds = ds
2275  	};
2276  	dsl_deadlist_iterate(&dd->dd_livelist, dsl_livelist_try_condense,
2277  	    &arg);
2278  }
2279  
2280  void
dsl_dataset_sync_done(dsl_dataset_t * ds,dmu_tx_t * tx)2281  dsl_dataset_sync_done(dsl_dataset_t *ds, dmu_tx_t *tx)
2282  {
2283  	objset_t *os = ds->ds_objset;
2284  
2285  	bplist_iterate(&ds->ds_pending_deadlist,
2286  	    dsl_deadlist_insert_alloc_cb, &ds->ds_deadlist, tx);
2287  
2288  	if (dsl_deadlist_is_open(&ds->ds_dir->dd_livelist)) {
2289  		dsl_flush_pending_livelist(ds, tx);
2290  		if (dsl_livelist_should_disable(ds)) {
2291  			dsl_dir_remove_livelist(ds->ds_dir, tx, B_TRUE);
2292  		}
2293  	}
2294  
2295  	dsl_bookmark_sync_done(ds, tx);
2296  
2297  	multilist_destroy(&os->os_synced_dnodes);
2298  
2299  	if (os->os_encrypted)
2300  		os->os_next_write_raw[tx->tx_txg & TXG_MASK] = B_FALSE;
2301  	else
2302  		ASSERT0(os->os_next_write_raw[tx->tx_txg & TXG_MASK]);
2303  
2304  	for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
2305  		if (zfeature_active(f,
2306  		    ds->ds_feature_activation[f])) {
2307  			if (zfeature_active(f, ds->ds_feature[f]))
2308  				continue;
2309  			dsl_dataset_activate_feature(ds->ds_object, f,
2310  			    ds->ds_feature_activation[f], tx);
2311  			ds->ds_feature[f] = ds->ds_feature_activation[f];
2312  		}
2313  	}
2314  
2315  	ASSERT(!dmu_objset_is_dirty(os, dmu_tx_get_txg(tx)));
2316  }
2317  
2318  int
get_clones_stat_impl(dsl_dataset_t * ds,nvlist_t * val)2319  get_clones_stat_impl(dsl_dataset_t *ds, nvlist_t *val)
2320  {
2321  	uint64_t count = 0;
2322  	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
2323  	zap_cursor_t zc;
2324  	zap_attribute_t *za;
2325  
2326  	ASSERT(dsl_pool_config_held(ds->ds_dir->dd_pool));
2327  
2328  	/*
2329  	 * There may be missing entries in ds_next_clones_obj
2330  	 * due to a bug in a previous version of the code.
2331  	 * Only trust it if it has the right number of entries.
2332  	 */
2333  	if (dsl_dataset_phys(ds)->ds_next_clones_obj != 0) {
2334  		VERIFY0(zap_count(mos, dsl_dataset_phys(ds)->ds_next_clones_obj,
2335  		    &count));
2336  	}
2337  	if (count != dsl_dataset_phys(ds)->ds_num_children - 1) {
2338  		return (SET_ERROR(ENOENT));
2339  	}
2340  
2341  	za = zap_attribute_alloc();
2342  	for (zap_cursor_init(&zc, mos,
2343  	    dsl_dataset_phys(ds)->ds_next_clones_obj);
2344  	    zap_cursor_retrieve(&zc, za) == 0;
2345  	    zap_cursor_advance(&zc)) {
2346  		dsl_dataset_t *clone;
2347  		char buf[ZFS_MAX_DATASET_NAME_LEN];
2348  		VERIFY0(dsl_dataset_hold_obj(ds->ds_dir->dd_pool,
2349  		    za->za_first_integer, FTAG, &clone));
2350  		dsl_dir_name(clone->ds_dir, buf);
2351  		fnvlist_add_boolean(val, buf);
2352  		dsl_dataset_rele(clone, FTAG);
2353  	}
2354  	zap_cursor_fini(&zc);
2355  	zap_attribute_free(za);
2356  	return (0);
2357  }
2358  
2359  void
get_clones_stat(dsl_dataset_t * ds,nvlist_t * nv)2360  get_clones_stat(dsl_dataset_t *ds, nvlist_t *nv)
2361  {
2362  	nvlist_t *propval = fnvlist_alloc();
2363  	nvlist_t *val = fnvlist_alloc();
2364  
2365  	if (get_clones_stat_impl(ds, val) == 0) {
2366  		fnvlist_add_nvlist(propval, ZPROP_VALUE, val);
2367  		fnvlist_add_nvlist(nv, zfs_prop_to_name(ZFS_PROP_CLONES),
2368  		    propval);
2369  	}
2370  
2371  	nvlist_free(val);
2372  	nvlist_free(propval);
2373  }
2374  
2375  static char *
get_receive_resume_token_impl(dsl_dataset_t * ds)2376  get_receive_resume_token_impl(dsl_dataset_t *ds)
2377  {
2378  	if (!dsl_dataset_has_resume_receive_state(ds))
2379  		return (NULL);
2380  
2381  	dsl_pool_t *dp = ds->ds_dir->dd_pool;
2382  	char *str;
2383  	void *packed;
2384  	uint8_t *compressed;
2385  	uint64_t val;
2386  	nvlist_t *token_nv = fnvlist_alloc();
2387  	size_t packed_size, compressed_size;
2388  
2389  	if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2390  	    DS_FIELD_RESUME_FROMGUID, sizeof (val), 1, &val) == 0) {
2391  		fnvlist_add_uint64(token_nv, "fromguid", val);
2392  	}
2393  	if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2394  	    DS_FIELD_RESUME_OBJECT, sizeof (val), 1, &val) == 0) {
2395  		fnvlist_add_uint64(token_nv, "object", val);
2396  	}
2397  	if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2398  	    DS_FIELD_RESUME_OFFSET, sizeof (val), 1, &val) == 0) {
2399  		fnvlist_add_uint64(token_nv, "offset", val);
2400  	}
2401  	if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2402  	    DS_FIELD_RESUME_BYTES, sizeof (val), 1, &val) == 0) {
2403  		fnvlist_add_uint64(token_nv, "bytes", val);
2404  	}
2405  	if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2406  	    DS_FIELD_RESUME_TOGUID, sizeof (val), 1, &val) == 0) {
2407  		fnvlist_add_uint64(token_nv, "toguid", val);
2408  	}
2409  	char buf[MAXNAMELEN];
2410  	if (zap_lookup(dp->dp_meta_objset, ds->ds_object,
2411  	    DS_FIELD_RESUME_TONAME, 1, sizeof (buf), buf) == 0) {
2412  		fnvlist_add_string(token_nv, "toname", buf);
2413  	}
2414  	if (zap_contains(dp->dp_meta_objset, ds->ds_object,
2415  	    DS_FIELD_RESUME_LARGEBLOCK) == 0) {
2416  		fnvlist_add_boolean(token_nv, "largeblockok");
2417  	}
2418  	if (zap_contains(dp->dp_meta_objset, ds->ds_object,
2419  	    DS_FIELD_RESUME_EMBEDOK) == 0) {
2420  		fnvlist_add_boolean(token_nv, "embedok");
2421  	}
2422  	if (zap_contains(dp->dp_meta_objset, ds->ds_object,
2423  	    DS_FIELD_RESUME_COMPRESSOK) == 0) {
2424  		fnvlist_add_boolean(token_nv, "compressok");
2425  	}
2426  	if (zap_contains(dp->dp_meta_objset, ds->ds_object,
2427  	    DS_FIELD_RESUME_RAWOK) == 0) {
2428  		fnvlist_add_boolean(token_nv, "rawok");
2429  	}
2430  	if (dsl_dataset_feature_is_active(ds,
2431  	    SPA_FEATURE_REDACTED_DATASETS)) {
2432  		uint64_t num_redact_snaps = 0;
2433  		uint64_t *redact_snaps = NULL;
2434  		VERIFY3B(dsl_dataset_get_uint64_array_feature(ds,
2435  		    SPA_FEATURE_REDACTED_DATASETS, &num_redact_snaps,
2436  		    &redact_snaps), ==, B_TRUE);
2437  		fnvlist_add_uint64_array(token_nv, "redact_snaps",
2438  		    redact_snaps, num_redact_snaps);
2439  	}
2440  	if (zap_contains(dp->dp_meta_objset, ds->ds_object,
2441  	    DS_FIELD_RESUME_REDACT_BOOKMARK_SNAPS) == 0) {
2442  		uint64_t num_redact_snaps = 0, int_size = 0;
2443  		uint64_t *redact_snaps = NULL;
2444  		VERIFY0(zap_length(dp->dp_meta_objset, ds->ds_object,
2445  		    DS_FIELD_RESUME_REDACT_BOOKMARK_SNAPS, &int_size,
2446  		    &num_redact_snaps));
2447  		ASSERT3U(int_size, ==, sizeof (uint64_t));
2448  
2449  		redact_snaps = kmem_alloc(int_size * num_redact_snaps,
2450  		    KM_SLEEP);
2451  		VERIFY0(zap_lookup(dp->dp_meta_objset, ds->ds_object,
2452  		    DS_FIELD_RESUME_REDACT_BOOKMARK_SNAPS, int_size,
2453  		    num_redact_snaps, redact_snaps));
2454  		fnvlist_add_uint64_array(token_nv, "book_redact_snaps",
2455  		    redact_snaps, num_redact_snaps);
2456  		kmem_free(redact_snaps, int_size * num_redact_snaps);
2457  	}
2458  	packed = fnvlist_pack(token_nv, &packed_size);
2459  	fnvlist_free(token_nv);
2460  	compressed = kmem_alloc(packed_size, KM_SLEEP);
2461  
2462  	/* Call compress function directly to avoid hole detection. */
2463  	abd_t pabd, cabd;
2464  	abd_get_from_buf_struct(&pabd, packed, packed_size);
2465  	abd_get_from_buf_struct(&cabd, compressed, packed_size);
2466  	compressed_size = zfs_gzip_compress(&pabd, &cabd,
2467  	    packed_size, packed_size, 6);
2468  	abd_free(&cabd);
2469  	abd_free(&pabd);
2470  
2471  	zio_cksum_t cksum;
2472  	fletcher_4_native_varsize(compressed, compressed_size, &cksum);
2473  
2474  	size_t alloc_size = compressed_size * 2 + 1;
2475  	str = kmem_alloc(alloc_size, KM_SLEEP);
2476  	for (int i = 0; i < compressed_size; i++) {
2477  		size_t offset = i * 2;
2478  		(void) snprintf(str + offset, alloc_size - offset,
2479  	    "%02x", compressed[i]);
2480  	}
2481  	str[compressed_size * 2] = '\0';
2482  	char *propval = kmem_asprintf("%u-%llx-%llx-%s",
2483  	    ZFS_SEND_RESUME_TOKEN_VERSION,
2484  	    (longlong_t)cksum.zc_word[0],
2485  	    (longlong_t)packed_size, str);
2486  	kmem_free(packed, packed_size);
2487  	kmem_free(str, alloc_size);
2488  	kmem_free(compressed, packed_size);
2489  	return (propval);
2490  }
2491  
2492  /*
2493   * Returns a string that represents the receive resume state token. It should
2494   * be freed with strfree(). NULL is returned if no resume state is present.
2495   */
2496  char *
get_receive_resume_token(dsl_dataset_t * ds)2497  get_receive_resume_token(dsl_dataset_t *ds)
2498  {
2499  	/*
2500  	 * A failed "newfs" (e.g. full) resumable receive leaves
2501  	 * the stats set on this dataset.  Check here for the prop.
2502  	 */
2503  	char *token = get_receive_resume_token_impl(ds);
2504  	if (token != NULL)
2505  		return (token);
2506  	/*
2507  	 * A failed incremental resumable receive leaves the
2508  	 * stats set on our child named "%recv".  Check the child
2509  	 * for the prop.
2510  	 */
2511  	/* 6 extra bytes for /%recv */
2512  	char name[ZFS_MAX_DATASET_NAME_LEN + 6];
2513  	dsl_dataset_t *recv_ds;
2514  	dsl_dataset_name(ds, name);
2515  	if (strlcat(name, "/", sizeof (name)) < sizeof (name) &&
2516  	    strlcat(name, recv_clone_name, sizeof (name)) < sizeof (name) &&
2517  	    dsl_dataset_hold(ds->ds_dir->dd_pool, name, FTAG, &recv_ds) == 0) {
2518  		token = get_receive_resume_token_impl(recv_ds);
2519  		dsl_dataset_rele(recv_ds, FTAG);
2520  	}
2521  	return (token);
2522  }
2523  
2524  uint64_t
dsl_get_refratio(dsl_dataset_t * ds)2525  dsl_get_refratio(dsl_dataset_t *ds)
2526  {
2527  	uint64_t ratio = dsl_dataset_phys(ds)->ds_compressed_bytes == 0 ? 100 :
2528  	    (dsl_dataset_phys(ds)->ds_uncompressed_bytes * 100 /
2529  	    dsl_dataset_phys(ds)->ds_compressed_bytes);
2530  	return (ratio);
2531  }
2532  
2533  uint64_t
dsl_get_logicalreferenced(dsl_dataset_t * ds)2534  dsl_get_logicalreferenced(dsl_dataset_t *ds)
2535  {
2536  	return (dsl_dataset_phys(ds)->ds_uncompressed_bytes);
2537  }
2538  
2539  uint64_t
dsl_get_compressratio(dsl_dataset_t * ds)2540  dsl_get_compressratio(dsl_dataset_t *ds)
2541  {
2542  	if (ds->ds_is_snapshot) {
2543  		return (dsl_get_refratio(ds));
2544  	} else {
2545  		dsl_dir_t *dd = ds->ds_dir;
2546  		mutex_enter(&dd->dd_lock);
2547  		uint64_t val = dsl_dir_get_compressratio(dd);
2548  		mutex_exit(&dd->dd_lock);
2549  		return (val);
2550  	}
2551  }
2552  
2553  uint64_t
dsl_get_used(dsl_dataset_t * ds)2554  dsl_get_used(dsl_dataset_t *ds)
2555  {
2556  	if (ds->ds_is_snapshot) {
2557  		return (dsl_dataset_phys(ds)->ds_unique_bytes);
2558  	} else {
2559  		dsl_dir_t *dd = ds->ds_dir;
2560  		mutex_enter(&dd->dd_lock);
2561  		uint64_t val = dsl_dir_get_used(dd);
2562  		mutex_exit(&dd->dd_lock);
2563  		return (val);
2564  	}
2565  }
2566  
2567  uint64_t
dsl_get_creation(dsl_dataset_t * ds)2568  dsl_get_creation(dsl_dataset_t *ds)
2569  {
2570  	return (dsl_dataset_phys(ds)->ds_creation_time);
2571  }
2572  
2573  uint64_t
dsl_get_creationtxg(dsl_dataset_t * ds)2574  dsl_get_creationtxg(dsl_dataset_t *ds)
2575  {
2576  	return (dsl_dataset_phys(ds)->ds_creation_txg);
2577  }
2578  
2579  uint64_t
dsl_get_refquota(dsl_dataset_t * ds)2580  dsl_get_refquota(dsl_dataset_t *ds)
2581  {
2582  	return (ds->ds_quota);
2583  }
2584  
2585  uint64_t
dsl_get_refreservation(dsl_dataset_t * ds)2586  dsl_get_refreservation(dsl_dataset_t *ds)
2587  {
2588  	return (ds->ds_reserved);
2589  }
2590  
2591  uint64_t
dsl_get_guid(dsl_dataset_t * ds)2592  dsl_get_guid(dsl_dataset_t *ds)
2593  {
2594  	return (dsl_dataset_phys(ds)->ds_guid);
2595  }
2596  
2597  uint64_t
dsl_get_unique(dsl_dataset_t * ds)2598  dsl_get_unique(dsl_dataset_t *ds)
2599  {
2600  	return (dsl_dataset_phys(ds)->ds_unique_bytes);
2601  }
2602  
2603  uint64_t
dsl_get_objsetid(dsl_dataset_t * ds)2604  dsl_get_objsetid(dsl_dataset_t *ds)
2605  {
2606  	return (ds->ds_object);
2607  }
2608  
2609  uint64_t
dsl_get_userrefs(dsl_dataset_t * ds)2610  dsl_get_userrefs(dsl_dataset_t *ds)
2611  {
2612  	return (ds->ds_userrefs);
2613  }
2614  
2615  uint64_t
dsl_get_defer_destroy(dsl_dataset_t * ds)2616  dsl_get_defer_destroy(dsl_dataset_t *ds)
2617  {
2618  	return (DS_IS_DEFER_DESTROY(ds) ? 1 : 0);
2619  }
2620  
2621  uint64_t
dsl_get_referenced(dsl_dataset_t * ds)2622  dsl_get_referenced(dsl_dataset_t *ds)
2623  {
2624  	return (dsl_dataset_phys(ds)->ds_referenced_bytes);
2625  }
2626  
2627  uint64_t
dsl_get_numclones(dsl_dataset_t * ds)2628  dsl_get_numclones(dsl_dataset_t *ds)
2629  {
2630  	ASSERT(ds->ds_is_snapshot);
2631  	return (dsl_dataset_phys(ds)->ds_num_children - 1);
2632  }
2633  
2634  uint64_t
dsl_get_inconsistent(dsl_dataset_t * ds)2635  dsl_get_inconsistent(dsl_dataset_t *ds)
2636  {
2637  	return ((dsl_dataset_phys(ds)->ds_flags & DS_FLAG_INCONSISTENT) ?
2638  	    1 : 0);
2639  }
2640  
2641  uint64_t
dsl_get_redacted(dsl_dataset_t * ds)2642  dsl_get_redacted(dsl_dataset_t *ds)
2643  {
2644  	return (dsl_dataset_feature_is_active(ds,
2645  	    SPA_FEATURE_REDACTED_DATASETS));
2646  }
2647  
2648  uint64_t
dsl_get_available(dsl_dataset_t * ds)2649  dsl_get_available(dsl_dataset_t *ds)
2650  {
2651  	uint64_t refdbytes = dsl_get_referenced(ds);
2652  	uint64_t availbytes = dsl_dir_space_available(ds->ds_dir,
2653  	    NULL, 0, TRUE);
2654  	if (ds->ds_reserved > dsl_dataset_phys(ds)->ds_unique_bytes) {
2655  		availbytes +=
2656  		    ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes;
2657  	}
2658  	if (ds->ds_quota != 0) {
2659  		/*
2660  		 * Adjust available bytes according to refquota
2661  		 */
2662  		if (refdbytes < ds->ds_quota) {
2663  			availbytes = MIN(availbytes,
2664  			    ds->ds_quota - refdbytes);
2665  		} else {
2666  			availbytes = 0;
2667  		}
2668  	}
2669  	return (availbytes);
2670  }
2671  
2672  int
dsl_get_written(dsl_dataset_t * ds,uint64_t * written)2673  dsl_get_written(dsl_dataset_t *ds, uint64_t *written)
2674  {
2675  	dsl_pool_t *dp = ds->ds_dir->dd_pool;
2676  	dsl_dataset_t *prev;
2677  	int err = dsl_dataset_hold_obj(dp,
2678  	    dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);
2679  	if (err == 0) {
2680  		uint64_t comp, uncomp;
2681  		err = dsl_dataset_space_written(prev, ds, written,
2682  		    &comp, &uncomp);
2683  		dsl_dataset_rele(prev, FTAG);
2684  	}
2685  	return (err);
2686  }
2687  
2688  /*
2689   * 'snap' should be a buffer of size ZFS_MAX_DATASET_NAME_LEN.
2690   */
2691  int
dsl_get_prev_snap(dsl_dataset_t * ds,char * snap)2692  dsl_get_prev_snap(dsl_dataset_t *ds, char *snap)
2693  {
2694  	dsl_pool_t *dp = ds->ds_dir->dd_pool;
2695  	if (ds->ds_prev != NULL && ds->ds_prev != dp->dp_origin_snap) {
2696  		dsl_dataset_name(ds->ds_prev, snap);
2697  		return (0);
2698  	} else {
2699  		return (SET_ERROR(ENOENT));
2700  	}
2701  }
2702  
2703  void
dsl_get_redact_snaps(dsl_dataset_t * ds,nvlist_t * propval)2704  dsl_get_redact_snaps(dsl_dataset_t *ds, nvlist_t *propval)
2705  {
2706  	uint64_t nsnaps;
2707  	uint64_t *snaps;
2708  	if (dsl_dataset_get_uint64_array_feature(ds,
2709  	    SPA_FEATURE_REDACTED_DATASETS, &nsnaps, &snaps)) {
2710  		fnvlist_add_uint64_array(propval, ZPROP_VALUE, snaps,
2711  		    nsnaps);
2712  	}
2713  }
2714  
2715  /*
2716   * Returns the mountpoint property and source for the given dataset in the value
2717   * and source buffers. The value buffer must be at least as large as MAXPATHLEN
2718   * and the source buffer as least as large a ZFS_MAX_DATASET_NAME_LEN.
2719   * Returns 0 on success and an error on failure.
2720   */
2721  int
dsl_get_mountpoint(dsl_dataset_t * ds,const char * dsname,char * value,char * source)2722  dsl_get_mountpoint(dsl_dataset_t *ds, const char *dsname, char *value,
2723      char *source)
2724  {
2725  	int error;
2726  	dsl_pool_t *dp = ds->ds_dir->dd_pool;
2727  
2728  	/* Retrieve the mountpoint value stored in the zap object */
2729  	error = dsl_prop_get_ds(ds, zfs_prop_to_name(ZFS_PROP_MOUNTPOINT), 1,
2730  	    ZAP_MAXVALUELEN, value, source);
2731  	if (error != 0) {
2732  		return (error);
2733  	}
2734  
2735  	/*
2736  	 * Process the dsname and source to find the full mountpoint string.
2737  	 * Can be skipped for 'legacy' or 'none'.
2738  	 */
2739  	if (value[0] == '/') {
2740  		char *buf = kmem_alloc(ZAP_MAXVALUELEN, KM_SLEEP);
2741  		char *root = buf;
2742  		const char *relpath;
2743  
2744  		/*
2745  		 * If we inherit the mountpoint, even from a dataset
2746  		 * with a received value, the source will be the path of
2747  		 * the dataset we inherit from. If source is
2748  		 * ZPROP_SOURCE_VAL_RECVD, the received value is not
2749  		 * inherited.
2750  		 */
2751  		if (strcmp(source, ZPROP_SOURCE_VAL_RECVD) == 0) {
2752  			relpath = "";
2753  		} else {
2754  			ASSERT0(strncmp(dsname, source, strlen(source)));
2755  			relpath = dsname + strlen(source);
2756  			if (relpath[0] == '/')
2757  				relpath++;
2758  		}
2759  
2760  		spa_altroot(dp->dp_spa, root, ZAP_MAXVALUELEN);
2761  
2762  		/*
2763  		 * Special case an alternate root of '/'. This will
2764  		 * avoid having multiple leading slashes in the
2765  		 * mountpoint path.
2766  		 */
2767  		if (strcmp(root, "/") == 0)
2768  			root++;
2769  
2770  		/*
2771  		 * If the mountpoint is '/' then skip over this
2772  		 * if we are obtaining either an alternate root or
2773  		 * an inherited mountpoint.
2774  		 */
2775  		char *mnt = value;
2776  		if (value[1] == '\0' && (root[0] != '\0' ||
2777  		    relpath[0] != '\0'))
2778  			mnt = value + 1;
2779  
2780  		mnt = kmem_strdup(mnt);
2781  
2782  		if (relpath[0] == '\0') {
2783  			(void) snprintf(value, ZAP_MAXVALUELEN, "%s%s",
2784  			    root, mnt);
2785  		} else {
2786  			(void) snprintf(value, ZAP_MAXVALUELEN, "%s%s%s%s",
2787  			    root, mnt, relpath[0] == '@' ? "" : "/",
2788  			    relpath);
2789  		}
2790  		kmem_free(buf, ZAP_MAXVALUELEN);
2791  		kmem_strfree(mnt);
2792  	}
2793  
2794  	return (0);
2795  }
2796  
2797  void
dsl_dataset_stats(dsl_dataset_t * ds,nvlist_t * nv)2798  dsl_dataset_stats(dsl_dataset_t *ds, nvlist_t *nv)
2799  {
2800  	dsl_pool_t *dp __maybe_unused = ds->ds_dir->dd_pool;
2801  
2802  	ASSERT(dsl_pool_config_held(dp));
2803  
2804  	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFRATIO,
2805  	    dsl_get_refratio(ds));
2806  	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_LOGICALREFERENCED,
2807  	    dsl_get_logicalreferenced(ds));
2808  	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_COMPRESSRATIO,
2809  	    dsl_get_compressratio(ds));
2810  	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USED,
2811  	    dsl_get_used(ds));
2812  
2813  	if (ds->ds_is_snapshot) {
2814  		get_clones_stat(ds, nv);
2815  	} else {
2816  		char buf[ZFS_MAX_DATASET_NAME_LEN];
2817  		if (dsl_get_prev_snap(ds, buf) == 0)
2818  			dsl_prop_nvlist_add_string(nv, ZFS_PROP_PREV_SNAP,
2819  			    buf);
2820  		dsl_dir_stats(ds->ds_dir, nv);
2821  	}
2822  
2823  	nvlist_t *propval = fnvlist_alloc();
2824  	dsl_get_redact_snaps(ds, propval);
2825  	fnvlist_add_nvlist(nv, zfs_prop_to_name(ZFS_PROP_REDACT_SNAPS),
2826  	    propval);
2827  	nvlist_free(propval);
2828  
2829  	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_AVAILABLE,
2830  	    dsl_get_available(ds));
2831  	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFERENCED,
2832  	    dsl_get_referenced(ds));
2833  	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_CREATION,
2834  	    dsl_get_creation(ds));
2835  	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_CREATETXG,
2836  	    dsl_get_creationtxg(ds));
2837  	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFQUOTA,
2838  	    dsl_get_refquota(ds));
2839  	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_REFRESERVATION,
2840  	    dsl_get_refreservation(ds));
2841  	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_GUID,
2842  	    dsl_get_guid(ds));
2843  	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_UNIQUE,
2844  	    dsl_get_unique(ds));
2845  	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_OBJSETID,
2846  	    dsl_get_objsetid(ds));
2847  	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USERREFS,
2848  	    dsl_get_userrefs(ds));
2849  	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_DEFER_DESTROY,
2850  	    dsl_get_defer_destroy(ds));
2851  	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_SNAPSHOTS_CHANGED,
2852  	    dsl_dir_snap_cmtime(ds->ds_dir).tv_sec);
2853  	dsl_dataset_crypt_stats(ds, nv);
2854  
2855  	if (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {
2856  		uint64_t written;
2857  		if (dsl_get_written(ds, &written) == 0) {
2858  			dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_WRITTEN,
2859  			    written);
2860  		}
2861  	}
2862  
2863  	if (!dsl_dataset_is_snapshot(ds)) {
2864  		char *token = get_receive_resume_token(ds);
2865  		if (token != NULL) {
2866  			dsl_prop_nvlist_add_string(nv,
2867  			    ZFS_PROP_RECEIVE_RESUME_TOKEN, token);
2868  			kmem_strfree(token);
2869  		}
2870  	}
2871  }
2872  
2873  void
dsl_dataset_fast_stat(dsl_dataset_t * ds,dmu_objset_stats_t * stat)2874  dsl_dataset_fast_stat(dsl_dataset_t *ds, dmu_objset_stats_t *stat)
2875  {
2876  	dsl_pool_t *dp __maybe_unused = ds->ds_dir->dd_pool;
2877  	ASSERT(dsl_pool_config_held(dp));
2878  
2879  	stat->dds_creation_txg = dsl_get_creationtxg(ds);
2880  	stat->dds_inconsistent = dsl_get_inconsistent(ds);
2881  	stat->dds_guid = dsl_get_guid(ds);
2882  	stat->dds_redacted = dsl_get_redacted(ds);
2883  	stat->dds_origin[0] = '\0';
2884  	if (ds->ds_is_snapshot) {
2885  		stat->dds_is_snapshot = B_TRUE;
2886  		stat->dds_num_clones = dsl_get_numclones(ds);
2887  	} else {
2888  		stat->dds_is_snapshot = B_FALSE;
2889  		stat->dds_num_clones = 0;
2890  
2891  		if (dsl_dir_is_clone(ds->ds_dir)) {
2892  			dsl_dir_get_origin(ds->ds_dir, stat->dds_origin);
2893  		}
2894  	}
2895  }
2896  
2897  uint64_t
dsl_dataset_fsid_guid(dsl_dataset_t * ds)2898  dsl_dataset_fsid_guid(dsl_dataset_t *ds)
2899  {
2900  	return (ds->ds_fsid_guid);
2901  }
2902  
2903  void
dsl_dataset_space(dsl_dataset_t * ds,uint64_t * refdbytesp,uint64_t * availbytesp,uint64_t * usedobjsp,uint64_t * availobjsp)2904  dsl_dataset_space(dsl_dataset_t *ds,
2905      uint64_t *refdbytesp, uint64_t *availbytesp,
2906      uint64_t *usedobjsp, uint64_t *availobjsp)
2907  {
2908  	*refdbytesp = dsl_dataset_phys(ds)->ds_referenced_bytes;
2909  	*availbytesp = dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE);
2910  	if (ds->ds_reserved > dsl_dataset_phys(ds)->ds_unique_bytes)
2911  		*availbytesp +=
2912  		    ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes;
2913  	if (ds->ds_quota != 0) {
2914  		/*
2915  		 * Adjust available bytes according to refquota
2916  		 */
2917  		if (*refdbytesp < ds->ds_quota)
2918  			*availbytesp = MIN(*availbytesp,
2919  			    ds->ds_quota - *refdbytesp);
2920  		else
2921  			*availbytesp = 0;
2922  	}
2923  	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
2924  	*usedobjsp = BP_GET_FILL(&dsl_dataset_phys(ds)->ds_bp);
2925  	rrw_exit(&ds->ds_bp_rwlock, FTAG);
2926  	*availobjsp = DN_MAX_OBJECT - *usedobjsp;
2927  }
2928  
2929  boolean_t
dsl_dataset_modified_since_snap(dsl_dataset_t * ds,dsl_dataset_t * snap)2930  dsl_dataset_modified_since_snap(dsl_dataset_t *ds, dsl_dataset_t *snap)
2931  {
2932  	dsl_pool_t *dp __maybe_unused = ds->ds_dir->dd_pool;
2933  	uint64_t birth;
2934  
2935  	ASSERT(dsl_pool_config_held(dp));
2936  	if (snap == NULL)
2937  		return (B_FALSE);
2938  	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
2939  	birth = BP_GET_LOGICAL_BIRTH(dsl_dataset_get_blkptr(ds));
2940  	rrw_exit(&ds->ds_bp_rwlock, FTAG);
2941  	if (birth > dsl_dataset_phys(snap)->ds_creation_txg) {
2942  		objset_t *os, *os_snap;
2943  		/*
2944  		 * It may be that only the ZIL differs, because it was
2945  		 * reset in the head.  Don't count that as being
2946  		 * modified.
2947  		 */
2948  		if (dmu_objset_from_ds(ds, &os) != 0)
2949  			return (B_TRUE);
2950  		if (dmu_objset_from_ds(snap, &os_snap) != 0)
2951  			return (B_TRUE);
2952  		return (memcmp(&os->os_phys->os_meta_dnode,
2953  		    &os_snap->os_phys->os_meta_dnode,
2954  		    sizeof (os->os_phys->os_meta_dnode)) != 0);
2955  	}
2956  	return (B_FALSE);
2957  }
2958  
2959  static int
dsl_dataset_rename_snapshot_check_impl(dsl_pool_t * dp,dsl_dataset_t * hds,void * arg)2960  dsl_dataset_rename_snapshot_check_impl(dsl_pool_t *dp,
2961      dsl_dataset_t *hds, void *arg)
2962  {
2963  	(void) dp;
2964  	dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
2965  	int error;
2966  	uint64_t val;
2967  
2968  	error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_oldsnapname, &val);
2969  	if (error != 0) {
2970  		/* ignore nonexistent snapshots */
2971  		return (error == ENOENT ? 0 : error);
2972  	}
2973  
2974  	/* new name should not exist */
2975  	error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_newsnapname, &val);
2976  	if (error == 0)
2977  		error = SET_ERROR(EEXIST);
2978  	else if (error == ENOENT)
2979  		error = 0;
2980  
2981  	/* dataset name + 1 for the "@" + the new snapshot name must fit */
2982  	if (dsl_dir_namelen(hds->ds_dir) + 1 +
2983  	    strlen(ddrsa->ddrsa_newsnapname) >= ZFS_MAX_DATASET_NAME_LEN)
2984  		error = SET_ERROR(ENAMETOOLONG);
2985  
2986  	return (error);
2987  }
2988  
2989  int
dsl_dataset_rename_snapshot_check(void * arg,dmu_tx_t * tx)2990  dsl_dataset_rename_snapshot_check(void *arg, dmu_tx_t *tx)
2991  {
2992  	dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
2993  	dsl_pool_t *dp = dmu_tx_pool(tx);
2994  	dsl_dataset_t *hds;
2995  	int error;
2996  
2997  	error = dsl_dataset_hold(dp, ddrsa->ddrsa_fsname, FTAG, &hds);
2998  	if (error != 0)
2999  		return (error);
3000  
3001  	if (ddrsa->ddrsa_recursive) {
3002  		error = dmu_objset_find_dp(dp, hds->ds_dir->dd_object,
3003  		    dsl_dataset_rename_snapshot_check_impl, ddrsa,
3004  		    DS_FIND_CHILDREN);
3005  	} else {
3006  		error = dsl_dataset_rename_snapshot_check_impl(dp, hds, ddrsa);
3007  	}
3008  	dsl_dataset_rele(hds, FTAG);
3009  	return (error);
3010  }
3011  
3012  static int
dsl_dataset_rename_snapshot_sync_impl(dsl_pool_t * dp,dsl_dataset_t * hds,void * arg)3013  dsl_dataset_rename_snapshot_sync_impl(dsl_pool_t *dp,
3014      dsl_dataset_t *hds, void *arg)
3015  {
3016  	dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
3017  	dsl_dataset_t *ds;
3018  	uint64_t val;
3019  	dmu_tx_t *tx = ddrsa->ddrsa_tx;
3020  	char *oldname, *newname;
3021  	int error;
3022  
3023  	error = dsl_dataset_snap_lookup(hds, ddrsa->ddrsa_oldsnapname, &val);
3024  	ASSERT(error == 0 || error == ENOENT);
3025  	if (error == ENOENT) {
3026  		/* ignore nonexistent snapshots */
3027  		return (0);
3028  	}
3029  
3030  	VERIFY0(dsl_dataset_hold_obj(dp, val, FTAG, &ds));
3031  
3032  	/* log before we change the name */
3033  	spa_history_log_internal_ds(ds, "rename", tx,
3034  	    "-> @%s", ddrsa->ddrsa_newsnapname);
3035  
3036  	VERIFY0(dsl_dataset_snap_remove(hds, ddrsa->ddrsa_oldsnapname, tx,
3037  	    B_FALSE));
3038  	mutex_enter(&ds->ds_lock);
3039  	(void) strlcpy(ds->ds_snapname, ddrsa->ddrsa_newsnapname,
3040  	    sizeof (ds->ds_snapname));
3041  	mutex_exit(&ds->ds_lock);
3042  	VERIFY0(zap_add(dp->dp_meta_objset,
3043  	    dsl_dataset_phys(hds)->ds_snapnames_zapobj,
3044  	    ds->ds_snapname, 8, 1, &ds->ds_object, tx));
3045  
3046  	oldname = kmem_asprintf("%s@%s", ddrsa->ddrsa_fsname,
3047  	    ddrsa->ddrsa_oldsnapname);
3048  	newname = kmem_asprintf("%s@%s", ddrsa->ddrsa_fsname,
3049  	    ddrsa->ddrsa_newsnapname);
3050  	zvol_rename_minors(dp->dp_spa, oldname, newname, B_TRUE);
3051  	kmem_strfree(oldname);
3052  	kmem_strfree(newname);
3053  
3054  	dsl_dataset_rele(ds, FTAG);
3055  	return (0);
3056  }
3057  
3058  void
dsl_dataset_rename_snapshot_sync(void * arg,dmu_tx_t * tx)3059  dsl_dataset_rename_snapshot_sync(void *arg, dmu_tx_t *tx)
3060  {
3061  	dsl_dataset_rename_snapshot_arg_t *ddrsa = arg;
3062  	dsl_pool_t *dp = dmu_tx_pool(tx);
3063  	dsl_dataset_t *hds = NULL;
3064  
3065  	VERIFY0(dsl_dataset_hold(dp, ddrsa->ddrsa_fsname, FTAG, &hds));
3066  	ddrsa->ddrsa_tx = tx;
3067  	if (ddrsa->ddrsa_recursive) {
3068  		VERIFY0(dmu_objset_find_dp(dp, hds->ds_dir->dd_object,
3069  		    dsl_dataset_rename_snapshot_sync_impl, ddrsa,
3070  		    DS_FIND_CHILDREN));
3071  	} else {
3072  		VERIFY0(dsl_dataset_rename_snapshot_sync_impl(dp, hds, ddrsa));
3073  	}
3074  	dsl_dataset_rele(hds, FTAG);
3075  }
3076  
3077  int
dsl_dataset_rename_snapshot(const char * fsname,const char * oldsnapname,const char * newsnapname,boolean_t recursive)3078  dsl_dataset_rename_snapshot(const char *fsname,
3079      const char *oldsnapname, const char *newsnapname, boolean_t recursive)
3080  {
3081  	dsl_dataset_rename_snapshot_arg_t ddrsa;
3082  
3083  	ddrsa.ddrsa_fsname = fsname;
3084  	ddrsa.ddrsa_oldsnapname = oldsnapname;
3085  	ddrsa.ddrsa_newsnapname = newsnapname;
3086  	ddrsa.ddrsa_recursive = recursive;
3087  
3088  	return (dsl_sync_task(fsname, dsl_dataset_rename_snapshot_check,
3089  	    dsl_dataset_rename_snapshot_sync, &ddrsa,
3090  	    1, ZFS_SPACE_CHECK_RESERVED));
3091  }
3092  
3093  /*
3094   * If we're doing an ownership handoff, we need to make sure that there is
3095   * only one long hold on the dataset.  We're not allowed to change anything here
3096   * so we don't permanently release the long hold or regular hold here.  We want
3097   * to do this only when syncing to avoid the dataset unexpectedly going away
3098   * when we release the long hold.
3099   */
3100  static int
dsl_dataset_handoff_check(dsl_dataset_t * ds,void * owner,dmu_tx_t * tx)3101  dsl_dataset_handoff_check(dsl_dataset_t *ds, void *owner, dmu_tx_t *tx)
3102  {
3103  	boolean_t held = B_FALSE;
3104  
3105  	if (!dmu_tx_is_syncing(tx))
3106  		return (0);
3107  
3108  	dsl_dir_t *dd = ds->ds_dir;
3109  	mutex_enter(&dd->dd_activity_lock);
3110  	uint64_t holds = zfs_refcount_count(&ds->ds_longholds) -
3111  	    (owner != NULL ? 1 : 0);
3112  	/*
3113  	 * The value of dd_activity_waiters can chance as soon as we drop the
3114  	 * lock, but we're fine with that; new waiters coming in or old
3115  	 * waiters leaving doesn't cause problems, since we're going to cancel
3116  	 * waiters later anyway. The goal of this check is to verify that no
3117  	 * non-waiters have long-holds, and all new long-holds will be
3118  	 * prevented because we're holding the pool config as writer.
3119  	 */
3120  	if (holds != dd->dd_activity_waiters)
3121  		held = B_TRUE;
3122  	mutex_exit(&dd->dd_activity_lock);
3123  
3124  	if (held)
3125  		return (SET_ERROR(EBUSY));
3126  
3127  	return (0);
3128  }
3129  
3130  int
dsl_dataset_rollback_check(void * arg,dmu_tx_t * tx)3131  dsl_dataset_rollback_check(void *arg, dmu_tx_t *tx)
3132  {
3133  	dsl_dataset_rollback_arg_t *ddra = arg;
3134  	dsl_pool_t *dp = dmu_tx_pool(tx);
3135  	dsl_dataset_t *ds;
3136  	int64_t unused_refres_delta;
3137  	int error;
3138  
3139  	error = dsl_dataset_hold(dp, ddra->ddra_fsname, FTAG, &ds);
3140  	if (error != 0)
3141  		return (error);
3142  
3143  	/* must not be a snapshot */
3144  	if (ds->ds_is_snapshot) {
3145  		dsl_dataset_rele(ds, FTAG);
3146  		return (SET_ERROR(EINVAL));
3147  	}
3148  
3149  	/* must have a most recent snapshot */
3150  	if (dsl_dataset_phys(ds)->ds_prev_snap_txg < TXG_INITIAL) {
3151  		dsl_dataset_rele(ds, FTAG);
3152  		return (SET_ERROR(ESRCH));
3153  	}
3154  
3155  	/*
3156  	 * No rollback to a snapshot created in the current txg, because
3157  	 * the rollback may dirty the dataset and create blocks that are
3158  	 * not reachable from the rootbp while having a birth txg that
3159  	 * falls into the snapshot's range.
3160  	 */
3161  	if (dmu_tx_is_syncing(tx) &&
3162  	    dsl_dataset_phys(ds)->ds_prev_snap_txg >= tx->tx_txg) {
3163  		dsl_dataset_rele(ds, FTAG);
3164  		return (SET_ERROR(EAGAIN));
3165  	}
3166  
3167  	/*
3168  	 * If the expected target snapshot is specified, then check that
3169  	 * the latest snapshot is it.
3170  	 */
3171  	if (ddra->ddra_tosnap != NULL) {
3172  		dsl_dataset_t *snapds;
3173  
3174  		/* Check if the target snapshot exists at all. */
3175  		error = dsl_dataset_hold(dp, ddra->ddra_tosnap, FTAG, &snapds);
3176  		if (error != 0) {
3177  			/*
3178  			 * ESRCH is used to signal that the target snapshot does
3179  			 * not exist, while ENOENT is used to report that
3180  			 * the rolled back dataset does not exist.
3181  			 * ESRCH is also used to cover other cases where the
3182  			 * target snapshot is not related to the dataset being
3183  			 * rolled back such as being in a different pool.
3184  			 */
3185  			if (error == ENOENT || error == EXDEV)
3186  				error = SET_ERROR(ESRCH);
3187  			dsl_dataset_rele(ds, FTAG);
3188  			return (error);
3189  		}
3190  		ASSERT(snapds->ds_is_snapshot);
3191  
3192  		/* Check if the snapshot is the latest snapshot indeed. */
3193  		if (snapds != ds->ds_prev) {
3194  			/*
3195  			 * Distinguish between the case where the only problem
3196  			 * is intervening snapshots (EEXIST) vs the snapshot
3197  			 * not being a valid target for rollback (ESRCH).
3198  			 */
3199  			if (snapds->ds_dir == ds->ds_dir ||
3200  			    (dsl_dir_is_clone(ds->ds_dir) &&
3201  			    dsl_dir_phys(ds->ds_dir)->dd_origin_obj ==
3202  			    snapds->ds_object)) {
3203  				error = SET_ERROR(EEXIST);
3204  			} else {
3205  				error = SET_ERROR(ESRCH);
3206  			}
3207  			dsl_dataset_rele(snapds, FTAG);
3208  			dsl_dataset_rele(ds, FTAG);
3209  			return (error);
3210  		}
3211  		dsl_dataset_rele(snapds, FTAG);
3212  	}
3213  
3214  	/* must not have any bookmarks after the most recent snapshot */
3215  	if (dsl_bookmark_latest_txg(ds) >
3216  	    dsl_dataset_phys(ds)->ds_prev_snap_txg) {
3217  		dsl_dataset_rele(ds, FTAG);
3218  		return (SET_ERROR(EEXIST));
3219  	}
3220  
3221  	error = dsl_dataset_handoff_check(ds, ddra->ddra_owner, tx);
3222  	if (error != 0) {
3223  		dsl_dataset_rele(ds, FTAG);
3224  		return (error);
3225  	}
3226  
3227  	/*
3228  	 * Check if the snap we are rolling back to uses more than
3229  	 * the refquota.
3230  	 */
3231  	if (ds->ds_quota != 0 &&
3232  	    dsl_dataset_phys(ds->ds_prev)->ds_referenced_bytes > ds->ds_quota) {
3233  		dsl_dataset_rele(ds, FTAG);
3234  		return (SET_ERROR(EDQUOT));
3235  	}
3236  
3237  	/*
3238  	 * When we do the clone swap, we will temporarily use more space
3239  	 * due to the refreservation (the head will no longer have any
3240  	 * unique space, so the entire amount of the refreservation will need
3241  	 * to be free).  We will immediately destroy the clone, freeing
3242  	 * this space, but the freeing happens over many txg's.
3243  	 */
3244  	unused_refres_delta = (int64_t)MIN(ds->ds_reserved,
3245  	    dsl_dataset_phys(ds)->ds_unique_bytes);
3246  
3247  	if (unused_refres_delta > 0 &&
3248  	    unused_refres_delta >
3249  	    dsl_dir_space_available(ds->ds_dir, NULL, 0, TRUE)) {
3250  		dsl_dataset_rele(ds, FTAG);
3251  		return (SET_ERROR(ENOSPC));
3252  	}
3253  
3254  	dsl_dataset_rele(ds, FTAG);
3255  	return (0);
3256  }
3257  
3258  void
dsl_dataset_rollback_sync(void * arg,dmu_tx_t * tx)3259  dsl_dataset_rollback_sync(void *arg, dmu_tx_t *tx)
3260  {
3261  	dsl_dataset_rollback_arg_t *ddra = arg;
3262  	dsl_pool_t *dp = dmu_tx_pool(tx);
3263  	dsl_dataset_t *ds, *clone;
3264  	uint64_t cloneobj;
3265  	char namebuf[ZFS_MAX_DATASET_NAME_LEN];
3266  
3267  	VERIFY0(dsl_dataset_hold(dp, ddra->ddra_fsname, FTAG, &ds));
3268  
3269  	dsl_dataset_name(ds->ds_prev, namebuf);
3270  	fnvlist_add_string(ddra->ddra_result, "target", namebuf);
3271  
3272  	cloneobj = dsl_dataset_create_sync(ds->ds_dir, "%rollback",
3273  	    ds->ds_prev, DS_CREATE_FLAG_NODIRTY, kcred, NULL, tx);
3274  
3275  	VERIFY0(dsl_dataset_hold_obj(dp, cloneobj, FTAG, &clone));
3276  
3277  	dsl_dataset_clone_swap_sync_impl(clone, ds, tx);
3278  	dsl_dataset_zero_zil(ds, tx);
3279  
3280  	dsl_destroy_head_sync_impl(clone, tx);
3281  
3282  	dsl_dataset_rele(clone, FTAG);
3283  	dsl_dataset_rele(ds, FTAG);
3284  }
3285  
3286  /*
3287   * Rolls back the given filesystem or volume to the most recent snapshot.
3288   * The name of the most recent snapshot will be returned under key "target"
3289   * in the result nvlist.
3290   *
3291   * If owner != NULL:
3292   * - The existing dataset MUST be owned by the specified owner at entry
3293   * - Upon return, dataset will still be held by the same owner, whether we
3294   *   succeed or not.
3295   *
3296   * This mode is required any time the existing filesystem is mounted.  See
3297   * notes above zfs_suspend_fs() for further details.
3298   */
3299  int
dsl_dataset_rollback(const char * fsname,const char * tosnap,void * owner,nvlist_t * result)3300  dsl_dataset_rollback(const char *fsname, const char *tosnap, void *owner,
3301      nvlist_t *result)
3302  {
3303  	dsl_dataset_rollback_arg_t ddra;
3304  
3305  	ddra.ddra_fsname = fsname;
3306  	ddra.ddra_tosnap = tosnap;
3307  	ddra.ddra_owner = owner;
3308  	ddra.ddra_result = result;
3309  
3310  	return (dsl_sync_task(fsname, dsl_dataset_rollback_check,
3311  	    dsl_dataset_rollback_sync, &ddra,
3312  	    1, ZFS_SPACE_CHECK_RESERVED));
3313  }
3314  
3315  struct promotenode {
3316  	list_node_t link;
3317  	dsl_dataset_t *ds;
3318  };
3319  
3320  static int snaplist_space(list_t *l, uint64_t mintxg, uint64_t *spacep);
3321  static int promote_hold(dsl_dataset_promote_arg_t *ddpa, dsl_pool_t *dp,
3322      const void *tag);
3323  static void promote_rele(dsl_dataset_promote_arg_t *ddpa, const void *tag);
3324  
3325  int
dsl_dataset_promote_check(void * arg,dmu_tx_t * tx)3326  dsl_dataset_promote_check(void *arg, dmu_tx_t *tx)
3327  {
3328  	dsl_dataset_promote_arg_t *ddpa = arg;
3329  	dsl_pool_t *dp = dmu_tx_pool(tx);
3330  	dsl_dataset_t *hds;
3331  	struct promotenode *snap;
3332  	int err;
3333  	uint64_t unused;
3334  	uint64_t ss_mv_cnt;
3335  	size_t max_snap_len;
3336  	boolean_t conflicting_snaps;
3337  
3338  	err = promote_hold(ddpa, dp, FTAG);
3339  	if (err != 0)
3340  		return (err);
3341  
3342  	hds = ddpa->ddpa_clone;
3343  	max_snap_len = MAXNAMELEN - strlen(ddpa->ddpa_clonename) - 1;
3344  
3345  	if (dsl_dataset_phys(hds)->ds_flags & DS_FLAG_NOPROMOTE) {
3346  		promote_rele(ddpa, FTAG);
3347  		return (SET_ERROR(EXDEV));
3348  	}
3349  
3350  	snap = list_head(&ddpa->shared_snaps);
3351  	if (snap == NULL) {
3352  		err = SET_ERROR(ENOENT);
3353  		goto out;
3354  	}
3355  	dsl_dataset_t *const origin_ds = snap->ds;
3356  
3357  	/*
3358  	 * Encrypted clones share a DSL Crypto Key with their origin's dsl dir.
3359  	 * When doing a promote we must make sure the encryption root for
3360  	 * both the target and the target's origin does not change to avoid
3361  	 * needing to rewrap encryption keys
3362  	 */
3363  	err = dsl_dataset_promote_crypt_check(hds->ds_dir, origin_ds->ds_dir);
3364  	if (err != 0)
3365  		goto out;
3366  
3367  	/*
3368  	 * Compute and check the amount of space to transfer.  Since this is
3369  	 * so expensive, don't do the preliminary check.
3370  	 */
3371  	if (!dmu_tx_is_syncing(tx)) {
3372  		promote_rele(ddpa, FTAG);
3373  		return (0);
3374  	}
3375  
3376  	/* compute origin's new unique space */
3377  	snap = list_tail(&ddpa->clone_snaps);
3378  	ASSERT(snap != NULL);
3379  	ASSERT3U(dsl_dataset_phys(snap->ds)->ds_prev_snap_obj, ==,
3380  	    origin_ds->ds_object);
3381  	dsl_deadlist_space_range(&snap->ds->ds_deadlist,
3382  	    dsl_dataset_phys(origin_ds)->ds_prev_snap_txg, UINT64_MAX,
3383  	    &ddpa->unique, &unused, &unused);
3384  
3385  	/*
3386  	 * Walk the snapshots that we are moving
3387  	 *
3388  	 * Compute space to transfer.  Consider the incremental changes
3389  	 * to used by each snapshot:
3390  	 * (my used) = (prev's used) + (blocks born) - (blocks killed)
3391  	 * So each snapshot gave birth to:
3392  	 * (blocks born) = (my used) - (prev's used) + (blocks killed)
3393  	 * So a sequence would look like:
3394  	 * (uN - u(N-1) + kN) + ... + (u1 - u0 + k1) + (u0 - 0 + k0)
3395  	 * Which simplifies to:
3396  	 * uN + kN + kN-1 + ... + k1 + k0
3397  	 * Note however, if we stop before we reach the ORIGIN we get:
3398  	 * uN + kN + kN-1 + ... + kM - uM-1
3399  	 */
3400  	conflicting_snaps = B_FALSE;
3401  	ss_mv_cnt = 0;
3402  	ddpa->used = dsl_dataset_phys(origin_ds)->ds_referenced_bytes;
3403  	ddpa->comp = dsl_dataset_phys(origin_ds)->ds_compressed_bytes;
3404  	ddpa->uncomp = dsl_dataset_phys(origin_ds)->ds_uncompressed_bytes;
3405  	for (snap = list_head(&ddpa->shared_snaps); snap;
3406  	    snap = list_next(&ddpa->shared_snaps, snap)) {
3407  		uint64_t val, dlused, dlcomp, dluncomp;
3408  		dsl_dataset_t *ds = snap->ds;
3409  
3410  		ss_mv_cnt++;
3411  
3412  		/*
3413  		 * If there are long holds, we won't be able to evict
3414  		 * the objset.
3415  		 */
3416  		if (dsl_dataset_long_held(ds)) {
3417  			err = SET_ERROR(EBUSY);
3418  			goto out;
3419  		}
3420  
3421  		/* Check that the snapshot name does not conflict */
3422  		VERIFY0(dsl_dataset_get_snapname(ds));
3423  		if (strlen(ds->ds_snapname) >= max_snap_len) {
3424  			err = SET_ERROR(ENAMETOOLONG);
3425  			goto out;
3426  		}
3427  		err = dsl_dataset_snap_lookup(hds, ds->ds_snapname, &val);
3428  		if (err == 0) {
3429  			fnvlist_add_boolean(ddpa->err_ds,
3430  			    snap->ds->ds_snapname);
3431  			conflicting_snaps = B_TRUE;
3432  		} else if (err != ENOENT) {
3433  			goto out;
3434  		}
3435  
3436  		/* The very first snapshot does not have a deadlist */
3437  		if (dsl_dataset_phys(ds)->ds_prev_snap_obj == 0)
3438  			continue;
3439  
3440  		dsl_deadlist_space(&ds->ds_deadlist,
3441  		    &dlused, &dlcomp, &dluncomp);
3442  		ddpa->used += dlused;
3443  		ddpa->comp += dlcomp;
3444  		ddpa->uncomp += dluncomp;
3445  	}
3446  
3447  	/*
3448  	 * Check that bookmarks that are being transferred don't have
3449  	 * name conflicts.
3450  	 */
3451  	for (dsl_bookmark_node_t *dbn = avl_first(&origin_ds->ds_bookmarks);
3452  	    dbn != NULL && dbn->dbn_phys.zbm_creation_txg <=
3453  	    dsl_dataset_phys(origin_ds)->ds_creation_txg;
3454  	    dbn = AVL_NEXT(&origin_ds->ds_bookmarks, dbn)) {
3455  		if (strlen(dbn->dbn_name) >= max_snap_len) {
3456  			err = SET_ERROR(ENAMETOOLONG);
3457  			goto out;
3458  		}
3459  		zfs_bookmark_phys_t bm;
3460  		err = dsl_bookmark_lookup_impl(ddpa->ddpa_clone,
3461  		    dbn->dbn_name, &bm);
3462  
3463  		if (err == 0) {
3464  			fnvlist_add_boolean(ddpa->err_ds, dbn->dbn_name);
3465  			conflicting_snaps = B_TRUE;
3466  		} else if (err == ESRCH) {
3467  			err = 0;
3468  		}
3469  		if (err != 0) {
3470  			goto out;
3471  		}
3472  	}
3473  
3474  	/*
3475  	 * In order to return the full list of conflicting snapshots, we check
3476  	 * whether there was a conflict after traversing all of them.
3477  	 */
3478  	if (conflicting_snaps) {
3479  		err = SET_ERROR(EEXIST);
3480  		goto out;
3481  	}
3482  
3483  	/*
3484  	 * If we are a clone of a clone then we never reached ORIGIN,
3485  	 * so we need to subtract out the clone origin's used space.
3486  	 */
3487  	if (ddpa->origin_origin) {
3488  		ddpa->used -=
3489  		    dsl_dataset_phys(ddpa->origin_origin)->ds_referenced_bytes;
3490  		ddpa->comp -=
3491  		    dsl_dataset_phys(ddpa->origin_origin)->ds_compressed_bytes;
3492  		ddpa->uncomp -=
3493  		    dsl_dataset_phys(ddpa->origin_origin)->
3494  		    ds_uncompressed_bytes;
3495  	}
3496  
3497  	/* Check that there is enough space and limit headroom here */
3498  	err = dsl_dir_transfer_possible(origin_ds->ds_dir, hds->ds_dir,
3499  	    0, ss_mv_cnt, ddpa->used, ddpa->cr, ddpa->proc);
3500  	if (err != 0)
3501  		goto out;
3502  
3503  	/*
3504  	 * Compute the amounts of space that will be used by snapshots
3505  	 * after the promotion (for both origin and clone).  For each,
3506  	 * it is the amount of space that will be on all of their
3507  	 * deadlists (that was not born before their new origin).
3508  	 */
3509  	if (dsl_dir_phys(hds->ds_dir)->dd_flags & DD_FLAG_USED_BREAKDOWN) {
3510  		uint64_t space;
3511  
3512  		/*
3513  		 * Note, typically this will not be a clone of a clone,
3514  		 * so dd_origin_txg will be < TXG_INITIAL, so
3515  		 * these snaplist_space() -> dsl_deadlist_space_range()
3516  		 * calls will be fast because they do not have to
3517  		 * iterate over all bps.
3518  		 */
3519  		snap = list_head(&ddpa->origin_snaps);
3520  		if (snap == NULL) {
3521  			err = SET_ERROR(ENOENT);
3522  			goto out;
3523  		}
3524  		err = snaplist_space(&ddpa->shared_snaps,
3525  		    snap->ds->ds_dir->dd_origin_txg, &ddpa->cloneusedsnap);
3526  		if (err != 0)
3527  			goto out;
3528  
3529  		err = snaplist_space(&ddpa->clone_snaps,
3530  		    snap->ds->ds_dir->dd_origin_txg, &space);
3531  		if (err != 0)
3532  			goto out;
3533  		ddpa->cloneusedsnap += space;
3534  	}
3535  	if (dsl_dir_phys(origin_ds->ds_dir)->dd_flags &
3536  	    DD_FLAG_USED_BREAKDOWN) {
3537  		err = snaplist_space(&ddpa->origin_snaps,
3538  		    dsl_dataset_phys(origin_ds)->ds_creation_txg,
3539  		    &ddpa->originusedsnap);
3540  		if (err != 0)
3541  			goto out;
3542  	}
3543  
3544  out:
3545  	promote_rele(ddpa, FTAG);
3546  	return (err);
3547  }
3548  
3549  void
dsl_dataset_promote_sync(void * arg,dmu_tx_t * tx)3550  dsl_dataset_promote_sync(void *arg, dmu_tx_t *tx)
3551  {
3552  	dsl_dataset_promote_arg_t *ddpa = arg;
3553  	dsl_pool_t *dp = dmu_tx_pool(tx);
3554  	dsl_dataset_t *hds;
3555  	struct promotenode *snap;
3556  	dsl_dataset_t *origin_ds;
3557  	dsl_dataset_t *origin_head;
3558  	dsl_dir_t *dd;
3559  	dsl_dir_t *odd = NULL;
3560  	uint64_t oldnext_obj;
3561  	int64_t delta;
3562  
3563  	ASSERT(nvlist_empty(ddpa->err_ds));
3564  
3565  	VERIFY0(promote_hold(ddpa, dp, FTAG));
3566  	hds = ddpa->ddpa_clone;
3567  
3568  	ASSERT0(dsl_dataset_phys(hds)->ds_flags & DS_FLAG_NOPROMOTE);
3569  
3570  	snap = list_head(&ddpa->shared_snaps);
3571  	origin_ds = snap->ds;
3572  	dd = hds->ds_dir;
3573  
3574  	snap = list_head(&ddpa->origin_snaps);
3575  	origin_head = snap->ds;
3576  
3577  	/*
3578  	 * We need to explicitly open odd, since origin_ds's dd will be
3579  	 * changing.
3580  	 */
3581  	VERIFY0(dsl_dir_hold_obj(dp, origin_ds->ds_dir->dd_object,
3582  	    NULL, FTAG, &odd));
3583  
3584  	dsl_dataset_promote_crypt_sync(hds->ds_dir, odd, tx);
3585  
3586  	/* change origin's next snap */
3587  	dmu_buf_will_dirty(origin_ds->ds_dbuf, tx);
3588  	oldnext_obj = dsl_dataset_phys(origin_ds)->ds_next_snap_obj;
3589  	snap = list_tail(&ddpa->clone_snaps);
3590  	ASSERT3U(dsl_dataset_phys(snap->ds)->ds_prev_snap_obj, ==,
3591  	    origin_ds->ds_object);
3592  	dsl_dataset_phys(origin_ds)->ds_next_snap_obj = snap->ds->ds_object;
3593  
3594  	/* change the origin's next clone */
3595  	if (dsl_dataset_phys(origin_ds)->ds_next_clones_obj) {
3596  		dsl_dataset_remove_from_next_clones(origin_ds,
3597  		    snap->ds->ds_object, tx);
3598  		VERIFY0(zap_add_int(dp->dp_meta_objset,
3599  		    dsl_dataset_phys(origin_ds)->ds_next_clones_obj,
3600  		    oldnext_obj, tx));
3601  	}
3602  
3603  	/* change origin */
3604  	dmu_buf_will_dirty(dd->dd_dbuf, tx);
3605  	ASSERT3U(dsl_dir_phys(dd)->dd_origin_obj, ==, origin_ds->ds_object);
3606  	dsl_dir_phys(dd)->dd_origin_obj = dsl_dir_phys(odd)->dd_origin_obj;
3607  	dd->dd_origin_txg = origin_head->ds_dir->dd_origin_txg;
3608  	dmu_buf_will_dirty(odd->dd_dbuf, tx);
3609  	dsl_dir_phys(odd)->dd_origin_obj = origin_ds->ds_object;
3610  	origin_head->ds_dir->dd_origin_txg =
3611  	    dsl_dataset_phys(origin_ds)->ds_creation_txg;
3612  
3613  	/* change dd_clone entries */
3614  	if (spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
3615  		VERIFY0(zap_remove_int(dp->dp_meta_objset,
3616  		    dsl_dir_phys(odd)->dd_clones, hds->ds_object, tx));
3617  		VERIFY0(zap_add_int(dp->dp_meta_objset,
3618  		    dsl_dir_phys(ddpa->origin_origin->ds_dir)->dd_clones,
3619  		    hds->ds_object, tx));
3620  
3621  		VERIFY0(zap_remove_int(dp->dp_meta_objset,
3622  		    dsl_dir_phys(ddpa->origin_origin->ds_dir)->dd_clones,
3623  		    origin_head->ds_object, tx));
3624  		if (dsl_dir_phys(dd)->dd_clones == 0) {
3625  			dsl_dir_phys(dd)->dd_clones =
3626  			    zap_create(dp->dp_meta_objset, DMU_OT_DSL_CLONES,
3627  			    DMU_OT_NONE, 0, tx);
3628  		}
3629  		VERIFY0(zap_add_int(dp->dp_meta_objset,
3630  		    dsl_dir_phys(dd)->dd_clones, origin_head->ds_object, tx));
3631  	}
3632  
3633  	/*
3634  	 * Move bookmarks to this dir.
3635  	 */
3636  	dsl_bookmark_node_t *dbn_next;
3637  	for (dsl_bookmark_node_t *dbn = avl_first(&origin_head->ds_bookmarks);
3638  	    dbn != NULL && dbn->dbn_phys.zbm_creation_txg <=
3639  	    dsl_dataset_phys(origin_ds)->ds_creation_txg;
3640  	    dbn = dbn_next) {
3641  		dbn_next = AVL_NEXT(&origin_head->ds_bookmarks, dbn);
3642  
3643  		avl_remove(&origin_head->ds_bookmarks, dbn);
3644  		VERIFY0(zap_remove(dp->dp_meta_objset,
3645  		    origin_head->ds_bookmarks_obj, dbn->dbn_name, tx));
3646  
3647  		dsl_bookmark_node_add(hds, dbn, tx);
3648  	}
3649  
3650  	dsl_bookmark_next_changed(hds, origin_ds, tx);
3651  
3652  	/* move snapshots to this dir */
3653  	for (snap = list_head(&ddpa->shared_snaps); snap;
3654  	    snap = list_next(&ddpa->shared_snaps, snap)) {
3655  		dsl_dataset_t *ds = snap->ds;
3656  
3657  		/*
3658  		 * Property callbacks are registered to a particular
3659  		 * dsl_dir.  Since ours is changing, evict the objset
3660  		 * so that they will be unregistered from the old dsl_dir.
3661  		 */
3662  		if (ds->ds_objset) {
3663  			dmu_objset_evict(ds->ds_objset);
3664  			ds->ds_objset = NULL;
3665  		}
3666  
3667  		/* move snap name entry */
3668  		VERIFY0(dsl_dataset_get_snapname(ds));
3669  		VERIFY0(dsl_dataset_snap_remove(origin_head,
3670  		    ds->ds_snapname, tx, B_TRUE));
3671  		VERIFY0(zap_add(dp->dp_meta_objset,
3672  		    dsl_dataset_phys(hds)->ds_snapnames_zapobj, ds->ds_snapname,
3673  		    8, 1, &ds->ds_object, tx));
3674  		dsl_fs_ss_count_adjust(hds->ds_dir, 1,
3675  		    DD_FIELD_SNAPSHOT_COUNT, tx);
3676  
3677  		/* change containing dsl_dir */
3678  		dmu_buf_will_dirty(ds->ds_dbuf, tx);
3679  		ASSERT3U(dsl_dataset_phys(ds)->ds_dir_obj, ==, odd->dd_object);
3680  		dsl_dataset_phys(ds)->ds_dir_obj = dd->dd_object;
3681  		ASSERT3P(ds->ds_dir, ==, odd);
3682  		dsl_dir_rele(ds->ds_dir, ds);
3683  		VERIFY0(dsl_dir_hold_obj(dp, dd->dd_object,
3684  		    NULL, ds, &ds->ds_dir));
3685  
3686  		/* move any clone references */
3687  		if (dsl_dataset_phys(ds)->ds_next_clones_obj &&
3688  		    spa_version(dp->dp_spa) >= SPA_VERSION_DIR_CLONES) {
3689  			zap_cursor_t zc;
3690  			zap_attribute_t *za = zap_attribute_alloc();
3691  
3692  			for (zap_cursor_init(&zc, dp->dp_meta_objset,
3693  			    dsl_dataset_phys(ds)->ds_next_clones_obj);
3694  			    zap_cursor_retrieve(&zc, za) == 0;
3695  			    zap_cursor_advance(&zc)) {
3696  				dsl_dataset_t *cnds;
3697  				uint64_t o;
3698  
3699  				if (za->za_first_integer == oldnext_obj) {
3700  					/*
3701  					 * We've already moved the
3702  					 * origin's reference.
3703  					 */
3704  					continue;
3705  				}
3706  
3707  				VERIFY0(dsl_dataset_hold_obj(dp,
3708  				    za->za_first_integer, FTAG, &cnds));
3709  				o = dsl_dir_phys(cnds->ds_dir)->
3710  				    dd_head_dataset_obj;
3711  
3712  				VERIFY0(zap_remove_int(dp->dp_meta_objset,
3713  				    dsl_dir_phys(odd)->dd_clones, o, tx));
3714  				VERIFY0(zap_add_int(dp->dp_meta_objset,
3715  				    dsl_dir_phys(dd)->dd_clones, o, tx));
3716  				dsl_dataset_rele(cnds, FTAG);
3717  			}
3718  			zap_cursor_fini(&zc);
3719  			zap_attribute_free(za);
3720  		}
3721  
3722  		ASSERT(!dsl_prop_hascb(ds));
3723  	}
3724  
3725  	/*
3726  	 * Change space accounting.
3727  	 * Note, pa->*usedsnap and dd_used_breakdown[SNAP] will either
3728  	 * both be valid, or both be 0 (resulting in delta == 0).  This
3729  	 * is true for each of {clone,origin} independently.
3730  	 */
3731  
3732  	delta = ddpa->cloneusedsnap -
3733  	    dsl_dir_phys(dd)->dd_used_breakdown[DD_USED_SNAP];
3734  	ASSERT3S(delta, >=, 0);
3735  	ASSERT3U(ddpa->used, >=, delta);
3736  	dsl_dir_diduse_space(dd, DD_USED_SNAP, delta, 0, 0, tx);
3737  	dsl_dir_diduse_space(dd, DD_USED_HEAD,
3738  	    ddpa->used - delta, ddpa->comp, ddpa->uncomp, tx);
3739  
3740  	delta = ddpa->originusedsnap -
3741  	    dsl_dir_phys(odd)->dd_used_breakdown[DD_USED_SNAP];
3742  	ASSERT3S(delta, <=, 0);
3743  	ASSERT3U(ddpa->used, >=, -delta);
3744  	dsl_dir_diduse_space(odd, DD_USED_SNAP, delta, 0, 0, tx);
3745  	dsl_dir_diduse_space(odd, DD_USED_HEAD,
3746  	    -ddpa->used - delta, -ddpa->comp, -ddpa->uncomp, tx);
3747  
3748  	dsl_dataset_phys(origin_ds)->ds_unique_bytes = ddpa->unique;
3749  
3750  	/*
3751  	 * Since livelists are specific to a clone's origin txg, they
3752  	 * are no longer accurate. Destroy the livelist from the clone being
3753  	 * promoted. If the origin dataset is a clone, destroy its livelist
3754  	 * as well.
3755  	 */
3756  	dsl_dir_remove_livelist(dd, tx, B_TRUE);
3757  	dsl_dir_remove_livelist(odd, tx, B_TRUE);
3758  
3759  	/* log history record */
3760  	spa_history_log_internal_ds(hds, "promote", tx, " ");
3761  
3762  	dsl_dir_rele(odd, FTAG);
3763  
3764  	/*
3765  	 * Transfer common error blocks from old head to new head, before
3766  	 * calling promote_rele() on ddpa since we need to dereference
3767  	 * origin_head and hds.
3768  	 */
3769  	if (spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_HEAD_ERRLOG)) {
3770  		uint64_t old_head = origin_head->ds_object;
3771  		uint64_t new_head = hds->ds_object;
3772  		spa_swap_errlog(dp->dp_spa, new_head, old_head, tx);
3773  	}
3774  
3775  	promote_rele(ddpa, FTAG);
3776  }
3777  
3778  /*
3779   * Make a list of dsl_dataset_t's for the snapshots between first_obj
3780   * (exclusive) and last_obj (inclusive).  The list will be in reverse
3781   * order (last_obj will be the list_head()).  If first_obj == 0, do all
3782   * snapshots back to this dataset's origin.
3783   */
3784  static int
snaplist_make(dsl_pool_t * dp,uint64_t first_obj,uint64_t last_obj,list_t * l,const void * tag)3785  snaplist_make(dsl_pool_t *dp,
3786      uint64_t first_obj, uint64_t last_obj, list_t *l, const void *tag)
3787  {
3788  	uint64_t obj = last_obj;
3789  
3790  	list_create(l, sizeof (struct promotenode),
3791  	    offsetof(struct promotenode, link));
3792  
3793  	while (obj != first_obj) {
3794  		dsl_dataset_t *ds;
3795  		struct promotenode *snap;
3796  		int err;
3797  
3798  		err = dsl_dataset_hold_obj(dp, obj, tag, &ds);
3799  		ASSERT(err != ENOENT);
3800  		if (err != 0)
3801  			return (err);
3802  
3803  		if (first_obj == 0)
3804  			first_obj = dsl_dir_phys(ds->ds_dir)->dd_origin_obj;
3805  
3806  		snap = kmem_alloc(sizeof (*snap), KM_SLEEP);
3807  		snap->ds = ds;
3808  		list_insert_tail(l, snap);
3809  		obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
3810  	}
3811  
3812  	return (0);
3813  }
3814  
3815  static int
snaplist_space(list_t * l,uint64_t mintxg,uint64_t * spacep)3816  snaplist_space(list_t *l, uint64_t mintxg, uint64_t *spacep)
3817  {
3818  	struct promotenode *snap;
3819  
3820  	*spacep = 0;
3821  	for (snap = list_head(l); snap; snap = list_next(l, snap)) {
3822  		uint64_t used, comp, uncomp;
3823  		dsl_deadlist_space_range(&snap->ds->ds_deadlist,
3824  		    mintxg, UINT64_MAX, &used, &comp, &uncomp);
3825  		*spacep += used;
3826  	}
3827  	return (0);
3828  }
3829  
3830  static void
snaplist_destroy(list_t * l,const void * tag)3831  snaplist_destroy(list_t *l, const void *tag)
3832  {
3833  	struct promotenode *snap;
3834  
3835  	if (l == NULL || !list_link_active(&l->list_head))
3836  		return;
3837  
3838  	while ((snap = list_remove_tail(l)) != NULL) {
3839  		dsl_dataset_rele(snap->ds, tag);
3840  		kmem_free(snap, sizeof (*snap));
3841  	}
3842  	list_destroy(l);
3843  }
3844  
3845  static int
promote_hold(dsl_dataset_promote_arg_t * ddpa,dsl_pool_t * dp,const void * tag)3846  promote_hold(dsl_dataset_promote_arg_t *ddpa, dsl_pool_t *dp, const void *tag)
3847  {
3848  	int error;
3849  	dsl_dir_t *dd;
3850  	struct promotenode *snap;
3851  
3852  	error = dsl_dataset_hold(dp, ddpa->ddpa_clonename, tag,
3853  	    &ddpa->ddpa_clone);
3854  	if (error != 0)
3855  		return (error);
3856  	dd = ddpa->ddpa_clone->ds_dir;
3857  
3858  	if (ddpa->ddpa_clone->ds_is_snapshot ||
3859  	    !dsl_dir_is_clone(dd)) {
3860  		dsl_dataset_rele(ddpa->ddpa_clone, tag);
3861  		return (SET_ERROR(EINVAL));
3862  	}
3863  
3864  	error = snaplist_make(dp, 0, dsl_dir_phys(dd)->dd_origin_obj,
3865  	    &ddpa->shared_snaps, tag);
3866  	if (error != 0)
3867  		goto out;
3868  
3869  	error = snaplist_make(dp, 0, ddpa->ddpa_clone->ds_object,
3870  	    &ddpa->clone_snaps, tag);
3871  	if (error != 0)
3872  		goto out;
3873  
3874  	snap = list_head(&ddpa->shared_snaps);
3875  	ASSERT3U(snap->ds->ds_object, ==, dsl_dir_phys(dd)->dd_origin_obj);
3876  	error = snaplist_make(dp, dsl_dir_phys(dd)->dd_origin_obj,
3877  	    dsl_dir_phys(snap->ds->ds_dir)->dd_head_dataset_obj,
3878  	    &ddpa->origin_snaps, tag);
3879  	if (error != 0)
3880  		goto out;
3881  
3882  	if (dsl_dir_phys(snap->ds->ds_dir)->dd_origin_obj != 0) {
3883  		error = dsl_dataset_hold_obj(dp,
3884  		    dsl_dir_phys(snap->ds->ds_dir)->dd_origin_obj,
3885  		    tag, &ddpa->origin_origin);
3886  		if (error != 0)
3887  			goto out;
3888  	}
3889  out:
3890  	if (error != 0)
3891  		promote_rele(ddpa, tag);
3892  	return (error);
3893  }
3894  
3895  static void
promote_rele(dsl_dataset_promote_arg_t * ddpa,const void * tag)3896  promote_rele(dsl_dataset_promote_arg_t *ddpa, const void *tag)
3897  {
3898  	snaplist_destroy(&ddpa->shared_snaps, tag);
3899  	snaplist_destroy(&ddpa->clone_snaps, tag);
3900  	snaplist_destroy(&ddpa->origin_snaps, tag);
3901  	if (ddpa->origin_origin != NULL)
3902  		dsl_dataset_rele(ddpa->origin_origin, tag);
3903  	dsl_dataset_rele(ddpa->ddpa_clone, tag);
3904  }
3905  
3906  /*
3907   * Promote a clone.
3908   *
3909   * If it fails due to a conflicting snapshot name, "conflsnap" will be filled
3910   * in with the name.  (It must be at least ZFS_MAX_DATASET_NAME_LEN bytes long.)
3911   */
3912  int
dsl_dataset_promote(const char * name,char * conflsnap)3913  dsl_dataset_promote(const char *name, char *conflsnap)
3914  {
3915  	dsl_dataset_promote_arg_t ddpa = { 0 };
3916  	uint64_t numsnaps;
3917  	int error;
3918  	nvpair_t *snap_pair;
3919  	objset_t *os;
3920  
3921  	/*
3922  	 * We will modify space proportional to the number of
3923  	 * snapshots.  Compute numsnaps.
3924  	 */
3925  	error = dmu_objset_hold(name, FTAG, &os);
3926  	if (error != 0)
3927  		return (error);
3928  	error = zap_count(dmu_objset_pool(os)->dp_meta_objset,
3929  	    dsl_dataset_phys(dmu_objset_ds(os))->ds_snapnames_zapobj,
3930  	    &numsnaps);
3931  	dmu_objset_rele(os, FTAG);
3932  	if (error != 0)
3933  		return (error);
3934  
3935  	ddpa.ddpa_clonename = name;
3936  	ddpa.err_ds = fnvlist_alloc();
3937  	ddpa.cr = CRED();
3938  	ddpa.proc = curproc;
3939  
3940  	error = dsl_sync_task(name, dsl_dataset_promote_check,
3941  	    dsl_dataset_promote_sync, &ddpa,
3942  	    2 + numsnaps, ZFS_SPACE_CHECK_RESERVED);
3943  
3944  	/*
3945  	 * Return the first conflicting snapshot found.
3946  	 */
3947  	snap_pair = nvlist_next_nvpair(ddpa.err_ds, NULL);
3948  	if (snap_pair != NULL && conflsnap != NULL)
3949  		(void) strlcpy(conflsnap, nvpair_name(snap_pair),
3950  		    ZFS_MAX_DATASET_NAME_LEN);
3951  
3952  	fnvlist_free(ddpa.err_ds);
3953  	return (error);
3954  }
3955  
3956  int
dsl_dataset_clone_swap_check_impl(dsl_dataset_t * clone,dsl_dataset_t * origin_head,boolean_t force,void * owner,dmu_tx_t * tx)3957  dsl_dataset_clone_swap_check_impl(dsl_dataset_t *clone,
3958      dsl_dataset_t *origin_head, boolean_t force, void *owner, dmu_tx_t *tx)
3959  {
3960  	/*
3961  	 * "slack" factor for received datasets with refquota set on them.
3962  	 * See the bottom of this function for details on its use.
3963  	 */
3964  	uint64_t refquota_slack = (uint64_t)DMU_MAX_ACCESS *
3965  	    spa_asize_inflation;
3966  	int64_t unused_refres_delta;
3967  
3968  	/* they should both be heads */
3969  	if (clone->ds_is_snapshot ||
3970  	    origin_head->ds_is_snapshot)
3971  		return (SET_ERROR(EINVAL));
3972  
3973  	/* if we are not forcing, the branch point should be just before them */
3974  	if (!force && clone->ds_prev != origin_head->ds_prev)
3975  		return (SET_ERROR(EINVAL));
3976  
3977  	/* clone should be the clone (unless they are unrelated) */
3978  	if (clone->ds_prev != NULL &&
3979  	    clone->ds_prev != clone->ds_dir->dd_pool->dp_origin_snap &&
3980  	    origin_head->ds_dir != clone->ds_prev->ds_dir)
3981  		return (SET_ERROR(EINVAL));
3982  
3983  	/* the clone should be a child of the origin */
3984  	if (clone->ds_dir->dd_parent != origin_head->ds_dir)
3985  		return (SET_ERROR(EINVAL));
3986  
3987  	/* origin_head shouldn't be modified unless 'force' */
3988  	if (!force &&
3989  	    dsl_dataset_modified_since_snap(origin_head, origin_head->ds_prev))
3990  		return (SET_ERROR(ETXTBSY));
3991  
3992  	/* origin_head should have no long holds (e.g. is not mounted) */
3993  	if (dsl_dataset_handoff_check(origin_head, owner, tx))
3994  		return (SET_ERROR(EBUSY));
3995  
3996  	/* check amount of any unconsumed refreservation */
3997  	unused_refres_delta =
3998  	    (int64_t)MIN(origin_head->ds_reserved,
3999  	    dsl_dataset_phys(origin_head)->ds_unique_bytes) -
4000  	    (int64_t)MIN(origin_head->ds_reserved,
4001  	    dsl_dataset_phys(clone)->ds_unique_bytes);
4002  
4003  	if (unused_refres_delta > 0 &&
4004  	    unused_refres_delta >
4005  	    dsl_dir_space_available(origin_head->ds_dir, NULL, 0, TRUE))
4006  		return (SET_ERROR(ENOSPC));
4007  
4008  	/*
4009  	 * The clone can't be too much over the head's refquota.
4010  	 *
4011  	 * To ensure that the entire refquota can be used, we allow one
4012  	 * transaction to exceed the refquota.  Therefore, this check
4013  	 * needs to also allow for the space referenced to be more than the
4014  	 * refquota.  The maximum amount of space that one transaction can use
4015  	 * on disk is DMU_MAX_ACCESS * spa_asize_inflation.  Allowing this
4016  	 * overage ensures that we are able to receive a filesystem that
4017  	 * exceeds the refquota on the source system.
4018  	 *
4019  	 * So that overage is the refquota_slack we use below.
4020  	 */
4021  	if (origin_head->ds_quota != 0 &&
4022  	    dsl_dataset_phys(clone)->ds_referenced_bytes >
4023  	    origin_head->ds_quota + refquota_slack)
4024  		return (SET_ERROR(EDQUOT));
4025  
4026  	return (0);
4027  }
4028  
4029  static void
dsl_dataset_swap_remap_deadlists(dsl_dataset_t * clone,dsl_dataset_t * origin,dmu_tx_t * tx)4030  dsl_dataset_swap_remap_deadlists(dsl_dataset_t *clone,
4031      dsl_dataset_t *origin, dmu_tx_t *tx)
4032  {
4033  	uint64_t clone_remap_dl_obj, origin_remap_dl_obj;
4034  	dsl_pool_t *dp = dmu_tx_pool(tx);
4035  
4036  	ASSERT(dsl_pool_sync_context(dp));
4037  
4038  	clone_remap_dl_obj = dsl_dataset_get_remap_deadlist_object(clone);
4039  	origin_remap_dl_obj = dsl_dataset_get_remap_deadlist_object(origin);
4040  
4041  	if (clone_remap_dl_obj != 0) {
4042  		dsl_deadlist_close(&clone->ds_remap_deadlist);
4043  		dsl_dataset_unset_remap_deadlist_object(clone, tx);
4044  	}
4045  	if (origin_remap_dl_obj != 0) {
4046  		dsl_deadlist_close(&origin->ds_remap_deadlist);
4047  		dsl_dataset_unset_remap_deadlist_object(origin, tx);
4048  	}
4049  
4050  	if (clone_remap_dl_obj != 0) {
4051  		dsl_dataset_set_remap_deadlist_object(origin,
4052  		    clone_remap_dl_obj, tx);
4053  		VERIFY0(dsl_deadlist_open(&origin->ds_remap_deadlist,
4054  		    dp->dp_meta_objset, clone_remap_dl_obj));
4055  	}
4056  	if (origin_remap_dl_obj != 0) {
4057  		dsl_dataset_set_remap_deadlist_object(clone,
4058  		    origin_remap_dl_obj, tx);
4059  		VERIFY0(dsl_deadlist_open(&clone->ds_remap_deadlist,
4060  		    dp->dp_meta_objset, origin_remap_dl_obj));
4061  	}
4062  }
4063  
4064  void
dsl_dataset_clone_swap_sync_impl(dsl_dataset_t * clone,dsl_dataset_t * origin_head,dmu_tx_t * tx)4065  dsl_dataset_clone_swap_sync_impl(dsl_dataset_t *clone,
4066      dsl_dataset_t *origin_head, dmu_tx_t *tx)
4067  {
4068  	dsl_pool_t *dp = dmu_tx_pool(tx);
4069  	int64_t unused_refres_delta;
4070  
4071  	ASSERT(clone->ds_reserved == 0);
4072  	/*
4073  	 * NOTE: On DEBUG kernels there could be a race between this and
4074  	 * the check function if spa_asize_inflation is adjusted...
4075  	 */
4076  	ASSERT(origin_head->ds_quota == 0 ||
4077  	    dsl_dataset_phys(clone)->ds_unique_bytes <= origin_head->ds_quota +
4078  	    DMU_MAX_ACCESS * spa_asize_inflation);
4079  	ASSERT3P(clone->ds_prev, ==, origin_head->ds_prev);
4080  
4081  	dsl_dir_cancel_waiters(origin_head->ds_dir);
4082  
4083  	/*
4084  	 * Swap per-dataset feature flags.
4085  	 */
4086  	for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
4087  		if (!(spa_feature_table[f].fi_flags &
4088  		    ZFEATURE_FLAG_PER_DATASET)) {
4089  			ASSERT(!dsl_dataset_feature_is_active(clone, f));
4090  			ASSERT(!dsl_dataset_feature_is_active(origin_head, f));
4091  			continue;
4092  		}
4093  
4094  		boolean_t clone_inuse = dsl_dataset_feature_is_active(clone, f);
4095  		void *clone_feature = clone->ds_feature[f];
4096  		boolean_t origin_head_inuse =
4097  		    dsl_dataset_feature_is_active(origin_head, f);
4098  		void *origin_head_feature = origin_head->ds_feature[f];
4099  
4100  		if (clone_inuse)
4101  			dsl_dataset_deactivate_feature_impl(clone, f, tx);
4102  		if (origin_head_inuse)
4103  			dsl_dataset_deactivate_feature_impl(origin_head, f, tx);
4104  
4105  		if (clone_inuse) {
4106  			dsl_dataset_activate_feature(origin_head->ds_object, f,
4107  			    clone_feature, tx);
4108  			origin_head->ds_feature[f] = clone_feature;
4109  		}
4110  		if (origin_head_inuse) {
4111  			dsl_dataset_activate_feature(clone->ds_object, f,
4112  			    origin_head_feature, tx);
4113  			clone->ds_feature[f] = origin_head_feature;
4114  		}
4115  	}
4116  
4117  	dmu_buf_will_dirty(clone->ds_dbuf, tx);
4118  	dmu_buf_will_dirty(origin_head->ds_dbuf, tx);
4119  
4120  	if (clone->ds_objset != NULL) {
4121  		dmu_objset_evict(clone->ds_objset);
4122  		clone->ds_objset = NULL;
4123  	}
4124  
4125  	if (origin_head->ds_objset != NULL) {
4126  		dmu_objset_evict(origin_head->ds_objset);
4127  		origin_head->ds_objset = NULL;
4128  	}
4129  
4130  	unused_refres_delta =
4131  	    (int64_t)MIN(origin_head->ds_reserved,
4132  	    dsl_dataset_phys(origin_head)->ds_unique_bytes) -
4133  	    (int64_t)MIN(origin_head->ds_reserved,
4134  	    dsl_dataset_phys(clone)->ds_unique_bytes);
4135  
4136  	/*
4137  	 * Reset origin's unique bytes.
4138  	 */
4139  	{
4140  		dsl_dataset_t *origin = clone->ds_prev;
4141  		uint64_t comp, uncomp;
4142  
4143  		dmu_buf_will_dirty(origin->ds_dbuf, tx);
4144  		dsl_deadlist_space_range(&clone->ds_deadlist,
4145  		    dsl_dataset_phys(origin)->ds_prev_snap_txg, UINT64_MAX,
4146  		    &dsl_dataset_phys(origin)->ds_unique_bytes, &comp, &uncomp);
4147  	}
4148  
4149  	/* swap blkptrs */
4150  	{
4151  		rrw_enter(&clone->ds_bp_rwlock, RW_WRITER, FTAG);
4152  		rrw_enter(&origin_head->ds_bp_rwlock, RW_WRITER, FTAG);
4153  		blkptr_t tmp;
4154  		tmp = dsl_dataset_phys(origin_head)->ds_bp;
4155  		dsl_dataset_phys(origin_head)->ds_bp =
4156  		    dsl_dataset_phys(clone)->ds_bp;
4157  		dsl_dataset_phys(clone)->ds_bp = tmp;
4158  		rrw_exit(&origin_head->ds_bp_rwlock, FTAG);
4159  		rrw_exit(&clone->ds_bp_rwlock, FTAG);
4160  	}
4161  
4162  	/* set dd_*_bytes */
4163  	{
4164  		int64_t dused, dcomp, duncomp;
4165  		uint64_t cdl_used, cdl_comp, cdl_uncomp;
4166  		uint64_t odl_used, odl_comp, odl_uncomp;
4167  
4168  		ASSERT3U(dsl_dir_phys(clone->ds_dir)->
4169  		    dd_used_breakdown[DD_USED_SNAP], ==, 0);
4170  
4171  		dsl_deadlist_space(&clone->ds_deadlist,
4172  		    &cdl_used, &cdl_comp, &cdl_uncomp);
4173  		dsl_deadlist_space(&origin_head->ds_deadlist,
4174  		    &odl_used, &odl_comp, &odl_uncomp);
4175  
4176  		dused = dsl_dataset_phys(clone)->ds_referenced_bytes +
4177  		    cdl_used -
4178  		    (dsl_dataset_phys(origin_head)->ds_referenced_bytes +
4179  		    odl_used);
4180  		dcomp = dsl_dataset_phys(clone)->ds_compressed_bytes +
4181  		    cdl_comp -
4182  		    (dsl_dataset_phys(origin_head)->ds_compressed_bytes +
4183  		    odl_comp);
4184  		duncomp = dsl_dataset_phys(clone)->ds_uncompressed_bytes +
4185  		    cdl_uncomp -
4186  		    (dsl_dataset_phys(origin_head)->ds_uncompressed_bytes +
4187  		    odl_uncomp);
4188  
4189  		dsl_dir_diduse_space(origin_head->ds_dir, DD_USED_HEAD,
4190  		    dused, dcomp, duncomp, tx);
4191  		dsl_dir_diduse_space(clone->ds_dir, DD_USED_HEAD,
4192  		    -dused, -dcomp, -duncomp, tx);
4193  
4194  		/*
4195  		 * The difference in the space used by snapshots is the
4196  		 * difference in snapshot space due to the head's
4197  		 * deadlist (since that's the only thing that's
4198  		 * changing that affects the snapused).
4199  		 */
4200  		dsl_deadlist_space_range(&clone->ds_deadlist,
4201  		    origin_head->ds_dir->dd_origin_txg, UINT64_MAX,
4202  		    &cdl_used, &cdl_comp, &cdl_uncomp);
4203  		dsl_deadlist_space_range(&origin_head->ds_deadlist,
4204  		    origin_head->ds_dir->dd_origin_txg, UINT64_MAX,
4205  		    &odl_used, &odl_comp, &odl_uncomp);
4206  		dsl_dir_transfer_space(origin_head->ds_dir, cdl_used - odl_used,
4207  		    DD_USED_HEAD, DD_USED_SNAP, tx);
4208  	}
4209  
4210  	/* swap ds_*_bytes */
4211  	SWITCH64(dsl_dataset_phys(origin_head)->ds_referenced_bytes,
4212  	    dsl_dataset_phys(clone)->ds_referenced_bytes);
4213  	SWITCH64(dsl_dataset_phys(origin_head)->ds_compressed_bytes,
4214  	    dsl_dataset_phys(clone)->ds_compressed_bytes);
4215  	SWITCH64(dsl_dataset_phys(origin_head)->ds_uncompressed_bytes,
4216  	    dsl_dataset_phys(clone)->ds_uncompressed_bytes);
4217  	SWITCH64(dsl_dataset_phys(origin_head)->ds_unique_bytes,
4218  	    dsl_dataset_phys(clone)->ds_unique_bytes);
4219  
4220  	/* apply any parent delta for change in unconsumed refreservation */
4221  	dsl_dir_diduse_space(origin_head->ds_dir, DD_USED_REFRSRV,
4222  	    unused_refres_delta, 0, 0, tx);
4223  
4224  	/*
4225  	 * Swap deadlists.
4226  	 */
4227  	dsl_deadlist_close(&clone->ds_deadlist);
4228  	dsl_deadlist_close(&origin_head->ds_deadlist);
4229  	SWITCH64(dsl_dataset_phys(origin_head)->ds_deadlist_obj,
4230  	    dsl_dataset_phys(clone)->ds_deadlist_obj);
4231  	VERIFY0(dsl_deadlist_open(&clone->ds_deadlist, dp->dp_meta_objset,
4232  	    dsl_dataset_phys(clone)->ds_deadlist_obj));
4233  	VERIFY0(dsl_deadlist_open(&origin_head->ds_deadlist, dp->dp_meta_objset,
4234  	    dsl_dataset_phys(origin_head)->ds_deadlist_obj));
4235  	dsl_dataset_swap_remap_deadlists(clone, origin_head, tx);
4236  
4237  	/*
4238  	 * If there is a bookmark at the origin, its "next dataset" is
4239  	 * changing, so we need to reset its FBN.
4240  	 */
4241  	dsl_bookmark_next_changed(origin_head, origin_head->ds_prev, tx);
4242  
4243  	dsl_scan_ds_clone_swapped(origin_head, clone, tx);
4244  
4245  	/*
4246  	 * Destroy any livelists associated with the clone or the origin,
4247  	 * since after the swap the corresponding livelists are no longer
4248  	 * valid.
4249  	 */
4250  	dsl_dir_remove_livelist(clone->ds_dir, tx, B_TRUE);
4251  	dsl_dir_remove_livelist(origin_head->ds_dir, tx, B_TRUE);
4252  
4253  	spa_history_log_internal_ds(clone, "clone swap", tx,
4254  	    "parent=%s", origin_head->ds_dir->dd_myname);
4255  }
4256  
4257  /*
4258   * Given a pool name and a dataset object number in that pool,
4259   * return the name of that dataset.
4260   */
4261  int
dsl_dsobj_to_dsname(char * pname,uint64_t obj,char * buf)4262  dsl_dsobj_to_dsname(char *pname, uint64_t obj, char *buf)
4263  {
4264  	dsl_pool_t *dp;
4265  	dsl_dataset_t *ds;
4266  	int error;
4267  
4268  	error = dsl_pool_hold(pname, FTAG, &dp);
4269  	if (error != 0)
4270  		return (error);
4271  
4272  	error = dsl_dataset_hold_obj(dp, obj, FTAG, &ds);
4273  	if (error == 0) {
4274  		dsl_dataset_name(ds, buf);
4275  		dsl_dataset_rele(ds, FTAG);
4276  	}
4277  	dsl_pool_rele(dp, FTAG);
4278  
4279  	return (error);
4280  }
4281  
4282  int
dsl_dataset_check_quota(dsl_dataset_t * ds,boolean_t check_quota,uint64_t asize,uint64_t inflight,uint64_t * used,uint64_t * ref_rsrv)4283  dsl_dataset_check_quota(dsl_dataset_t *ds, boolean_t check_quota,
4284      uint64_t asize, uint64_t inflight, uint64_t *used, uint64_t *ref_rsrv)
4285  {
4286  	int error = 0;
4287  
4288  	ASSERT3S(asize, >, 0);
4289  
4290  	/*
4291  	 * *ref_rsrv is the portion of asize that will come from any
4292  	 * unconsumed refreservation space.
4293  	 */
4294  	*ref_rsrv = 0;
4295  
4296  	mutex_enter(&ds->ds_lock);
4297  	/*
4298  	 * Make a space adjustment for reserved bytes.
4299  	 */
4300  	if (ds->ds_reserved > dsl_dataset_phys(ds)->ds_unique_bytes) {
4301  		ASSERT3U(*used, >=,
4302  		    ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes);
4303  		*used -=
4304  		    (ds->ds_reserved - dsl_dataset_phys(ds)->ds_unique_bytes);
4305  		*ref_rsrv =
4306  		    asize - MIN(asize, parent_delta(ds, asize + inflight));
4307  	}
4308  
4309  	if (!check_quota || ds->ds_quota == 0) {
4310  		mutex_exit(&ds->ds_lock);
4311  		return (0);
4312  	}
4313  	/*
4314  	 * If they are requesting more space, and our current estimate
4315  	 * is over quota, they get to try again unless the actual
4316  	 * on-disk is over quota and there are no pending changes (which
4317  	 * may free up space for us).
4318  	 */
4319  	if (dsl_dataset_phys(ds)->ds_referenced_bytes + inflight >=
4320  	    ds->ds_quota) {
4321  		if (inflight > 0 ||
4322  		    dsl_dataset_phys(ds)->ds_referenced_bytes < ds->ds_quota)
4323  			error = SET_ERROR(ERESTART);
4324  		else
4325  			error = SET_ERROR(EDQUOT);
4326  	}
4327  	mutex_exit(&ds->ds_lock);
4328  
4329  	return (error);
4330  }
4331  
4332  typedef struct dsl_dataset_set_qr_arg {
4333  	const char *ddsqra_name;
4334  	zprop_source_t ddsqra_source;
4335  	uint64_t ddsqra_value;
4336  } dsl_dataset_set_qr_arg_t;
4337  
4338  
4339  static int
dsl_dataset_set_refquota_check(void * arg,dmu_tx_t * tx)4340  dsl_dataset_set_refquota_check(void *arg, dmu_tx_t *tx)
4341  {
4342  	dsl_dataset_set_qr_arg_t *ddsqra = arg;
4343  	dsl_pool_t *dp = dmu_tx_pool(tx);
4344  	dsl_dataset_t *ds;
4345  	int error;
4346  	uint64_t newval;
4347  
4348  	if (spa_version(dp->dp_spa) < SPA_VERSION_REFQUOTA)
4349  		return (SET_ERROR(ENOTSUP));
4350  
4351  	error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
4352  	if (error != 0)
4353  		return (error);
4354  
4355  	if (ds->ds_is_snapshot) {
4356  		dsl_dataset_rele(ds, FTAG);
4357  		return (SET_ERROR(EINVAL));
4358  	}
4359  
4360  	error = dsl_prop_predict(ds->ds_dir,
4361  	    zfs_prop_to_name(ZFS_PROP_REFQUOTA),
4362  	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
4363  	if (error != 0) {
4364  		dsl_dataset_rele(ds, FTAG);
4365  		return (error);
4366  	}
4367  
4368  	if (newval == 0) {
4369  		dsl_dataset_rele(ds, FTAG);
4370  		return (0);
4371  	}
4372  
4373  	if (newval < dsl_dataset_phys(ds)->ds_referenced_bytes ||
4374  	    newval < ds->ds_reserved) {
4375  		dsl_dataset_rele(ds, FTAG);
4376  		return (SET_ERROR(ENOSPC));
4377  	}
4378  
4379  	dsl_dataset_rele(ds, FTAG);
4380  	return (0);
4381  }
4382  
4383  static void
dsl_dataset_set_refquota_sync(void * arg,dmu_tx_t * tx)4384  dsl_dataset_set_refquota_sync(void *arg, dmu_tx_t *tx)
4385  {
4386  	dsl_dataset_set_qr_arg_t *ddsqra = arg;
4387  	dsl_pool_t *dp = dmu_tx_pool(tx);
4388  	dsl_dataset_t *ds = NULL;
4389  	uint64_t newval;
4390  
4391  	VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
4392  
4393  	dsl_prop_set_sync_impl(ds,
4394  	    zfs_prop_to_name(ZFS_PROP_REFQUOTA),
4395  	    ddsqra->ddsqra_source, sizeof (ddsqra->ddsqra_value), 1,
4396  	    &ddsqra->ddsqra_value, tx);
4397  
4398  	VERIFY0(dsl_prop_get_int_ds(ds,
4399  	    zfs_prop_to_name(ZFS_PROP_REFQUOTA), &newval));
4400  
4401  	if (ds->ds_quota != newval) {
4402  		dmu_buf_will_dirty(ds->ds_dbuf, tx);
4403  		ds->ds_quota = newval;
4404  	}
4405  	dsl_dataset_rele(ds, FTAG);
4406  }
4407  
4408  int
dsl_dataset_set_refquota(const char * dsname,zprop_source_t source,uint64_t refquota)4409  dsl_dataset_set_refquota(const char *dsname, zprop_source_t source,
4410      uint64_t refquota)
4411  {
4412  	dsl_dataset_set_qr_arg_t ddsqra;
4413  
4414  	ddsqra.ddsqra_name = dsname;
4415  	ddsqra.ddsqra_source = source;
4416  	ddsqra.ddsqra_value = refquota;
4417  
4418  	return (dsl_sync_task(dsname, dsl_dataset_set_refquota_check,
4419  	    dsl_dataset_set_refquota_sync, &ddsqra, 0,
4420  	    ZFS_SPACE_CHECK_EXTRA_RESERVED));
4421  }
4422  
4423  static int
dsl_dataset_set_refreservation_check(void * arg,dmu_tx_t * tx)4424  dsl_dataset_set_refreservation_check(void *arg, dmu_tx_t *tx)
4425  {
4426  	dsl_dataset_set_qr_arg_t *ddsqra = arg;
4427  	dsl_pool_t *dp = dmu_tx_pool(tx);
4428  	dsl_dataset_t *ds;
4429  	int error;
4430  	uint64_t newval, unique;
4431  
4432  	if (spa_version(dp->dp_spa) < SPA_VERSION_REFRESERVATION)
4433  		return (SET_ERROR(ENOTSUP));
4434  
4435  	error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
4436  	if (error != 0)
4437  		return (error);
4438  
4439  	if (ds->ds_is_snapshot) {
4440  		dsl_dataset_rele(ds, FTAG);
4441  		return (SET_ERROR(EINVAL));
4442  	}
4443  
4444  	error = dsl_prop_predict(ds->ds_dir,
4445  	    zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
4446  	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
4447  	if (error != 0) {
4448  		dsl_dataset_rele(ds, FTAG);
4449  		return (error);
4450  	}
4451  
4452  	/*
4453  	 * If we are doing the preliminary check in open context, the
4454  	 * space estimates may be inaccurate.
4455  	 */
4456  	if (!dmu_tx_is_syncing(tx)) {
4457  		dsl_dataset_rele(ds, FTAG);
4458  		return (0);
4459  	}
4460  
4461  	mutex_enter(&ds->ds_lock);
4462  	if (!DS_UNIQUE_IS_ACCURATE(ds))
4463  		dsl_dataset_recalc_head_uniq(ds);
4464  	unique = dsl_dataset_phys(ds)->ds_unique_bytes;
4465  	mutex_exit(&ds->ds_lock);
4466  
4467  	if (MAX(unique, newval) > MAX(unique, ds->ds_reserved)) {
4468  		uint64_t delta = MAX(unique, newval) -
4469  		    MAX(unique, ds->ds_reserved);
4470  
4471  		if (delta >
4472  		    dsl_dir_space_available(ds->ds_dir, NULL, 0, B_TRUE) ||
4473  		    (ds->ds_quota > 0 && newval > ds->ds_quota)) {
4474  			dsl_dataset_rele(ds, FTAG);
4475  			return (SET_ERROR(ENOSPC));
4476  		}
4477  	}
4478  
4479  	dsl_dataset_rele(ds, FTAG);
4480  	return (0);
4481  }
4482  
4483  void
dsl_dataset_set_refreservation_sync_impl(dsl_dataset_t * ds,zprop_source_t source,uint64_t value,dmu_tx_t * tx)4484  dsl_dataset_set_refreservation_sync_impl(dsl_dataset_t *ds,
4485      zprop_source_t source, uint64_t value, dmu_tx_t *tx)
4486  {
4487  	uint64_t newval;
4488  	uint64_t unique;
4489  	int64_t delta;
4490  
4491  	dsl_prop_set_sync_impl(ds, zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
4492  	    source, sizeof (value), 1, &value, tx);
4493  
4494  	VERIFY0(dsl_prop_get_int_ds(ds,
4495  	    zfs_prop_to_name(ZFS_PROP_REFRESERVATION), &newval));
4496  
4497  	dmu_buf_will_dirty(ds->ds_dbuf, tx);
4498  	mutex_enter(&ds->ds_dir->dd_lock);
4499  	mutex_enter(&ds->ds_lock);
4500  	ASSERT(DS_UNIQUE_IS_ACCURATE(ds));
4501  	unique = dsl_dataset_phys(ds)->ds_unique_bytes;
4502  	delta = MAX(0, (int64_t)(newval - unique)) -
4503  	    MAX(0, (int64_t)(ds->ds_reserved - unique));
4504  	ds->ds_reserved = newval;
4505  	mutex_exit(&ds->ds_lock);
4506  
4507  	dsl_dir_diduse_space(ds->ds_dir, DD_USED_REFRSRV, delta, 0, 0, tx);
4508  	mutex_exit(&ds->ds_dir->dd_lock);
4509  }
4510  
4511  static void
dsl_dataset_set_refreservation_sync(void * arg,dmu_tx_t * tx)4512  dsl_dataset_set_refreservation_sync(void *arg, dmu_tx_t *tx)
4513  {
4514  	dsl_dataset_set_qr_arg_t *ddsqra = arg;
4515  	dsl_pool_t *dp = dmu_tx_pool(tx);
4516  	dsl_dataset_t *ds = NULL;
4517  
4518  	VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
4519  	dsl_dataset_set_refreservation_sync_impl(ds,
4520  	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, tx);
4521  	dsl_dataset_rele(ds, FTAG);
4522  }
4523  
4524  int
dsl_dataset_set_refreservation(const char * dsname,zprop_source_t source,uint64_t refreservation)4525  dsl_dataset_set_refreservation(const char *dsname, zprop_source_t source,
4526      uint64_t refreservation)
4527  {
4528  	dsl_dataset_set_qr_arg_t ddsqra;
4529  
4530  	ddsqra.ddsqra_name = dsname;
4531  	ddsqra.ddsqra_source = source;
4532  	ddsqra.ddsqra_value = refreservation;
4533  
4534  	return (dsl_sync_task(dsname, dsl_dataset_set_refreservation_check,
4535  	    dsl_dataset_set_refreservation_sync, &ddsqra, 0,
4536  	    ZFS_SPACE_CHECK_EXTRA_RESERVED));
4537  }
4538  
4539  typedef struct dsl_dataset_set_compression_arg {
4540  	const char *ddsca_name;
4541  	zprop_source_t ddsca_source;
4542  	uint64_t ddsca_value;
4543  } dsl_dataset_set_compression_arg_t;
4544  
4545  static int
dsl_dataset_set_compression_check(void * arg,dmu_tx_t * tx)4546  dsl_dataset_set_compression_check(void *arg, dmu_tx_t *tx)
4547  {
4548  	dsl_dataset_set_compression_arg_t *ddsca = arg;
4549  	dsl_pool_t *dp = dmu_tx_pool(tx);
4550  
4551  	uint64_t compval = ZIO_COMPRESS_ALGO(ddsca->ddsca_value);
4552  	spa_feature_t f = zio_compress_to_feature(compval);
4553  
4554  	if (f == SPA_FEATURE_NONE)
4555  		return (SET_ERROR(EINVAL));
4556  
4557  	if (!spa_feature_is_enabled(dp->dp_spa, f))
4558  		return (SET_ERROR(ENOTSUP));
4559  
4560  	return (0);
4561  }
4562  
4563  static void
dsl_dataset_set_compression_sync(void * arg,dmu_tx_t * tx)4564  dsl_dataset_set_compression_sync(void *arg, dmu_tx_t *tx)
4565  {
4566  	dsl_dataset_set_compression_arg_t *ddsca = arg;
4567  	dsl_pool_t *dp = dmu_tx_pool(tx);
4568  	dsl_dataset_t *ds = NULL;
4569  
4570  	uint64_t compval = ZIO_COMPRESS_ALGO(ddsca->ddsca_value);
4571  	spa_feature_t f = zio_compress_to_feature(compval);
4572  	ASSERT3S(f, !=, SPA_FEATURE_NONE);
4573  	ASSERT3S(spa_feature_table[f].fi_type, ==, ZFEATURE_TYPE_BOOLEAN);
4574  
4575  	VERIFY0(dsl_dataset_hold(dp, ddsca->ddsca_name, FTAG, &ds));
4576  	if (zfeature_active(f, ds->ds_feature[f]) != B_TRUE) {
4577  		ds->ds_feature_activation[f] = (void *)B_TRUE;
4578  		dsl_dataset_activate_feature(ds->ds_object, f,
4579  		    ds->ds_feature_activation[f], tx);
4580  		ds->ds_feature[f] = ds->ds_feature_activation[f];
4581  	}
4582  	dsl_dataset_rele(ds, FTAG);
4583  }
4584  
4585  int
dsl_dataset_set_compression(const char * dsname,zprop_source_t source,uint64_t compression)4586  dsl_dataset_set_compression(const char *dsname, zprop_source_t source,
4587      uint64_t compression)
4588  {
4589  	dsl_dataset_set_compression_arg_t ddsca;
4590  
4591  	/*
4592  	 * The sync task is only required for zstd in order to activate
4593  	 * the feature flag when the property is first set.
4594  	 */
4595  	if (ZIO_COMPRESS_ALGO(compression) != ZIO_COMPRESS_ZSTD)
4596  		return (0);
4597  
4598  	ddsca.ddsca_name = dsname;
4599  	ddsca.ddsca_source = source;
4600  	ddsca.ddsca_value = compression;
4601  
4602  	return (dsl_sync_task(dsname, dsl_dataset_set_compression_check,
4603  	    dsl_dataset_set_compression_sync, &ddsca, 0,
4604  	    ZFS_SPACE_CHECK_EXTRA_RESERVED));
4605  }
4606  
4607  /*
4608   * Return (in *usedp) the amount of space referenced by "new" that was not
4609   * referenced at the time the bookmark corresponds to.  "New" may be a
4610   * snapshot or a head.  The bookmark must be before new, in
4611   * new's filesystem (or its origin) -- caller verifies this.
4612   *
4613   * The written space is calculated by considering two components:  First, we
4614   * ignore any freed space, and calculate the written as new's used space
4615   * minus old's used space.  Next, we add in the amount of space that was freed
4616   * between the two time points, thus reducing new's used space relative to
4617   * old's. Specifically, this is the space that was born before
4618   * zbm_creation_txg, and freed before new (ie. on new's deadlist or a
4619   * previous deadlist).
4620   *
4621   * space freed                         [---------------------]
4622   * snapshots                       ---O-------O--------O-------O------
4623   *                                         bookmark           new
4624   *
4625   * Note, the bookmark's zbm_*_bytes_refd must be valid, but if the HAS_FBN
4626   * flag is not set, we will calculate the freed_before_next based on the
4627   * next snapshot's deadlist, rather than using zbm_*_freed_before_next_snap.
4628   */
4629  static int
dsl_dataset_space_written_impl(zfs_bookmark_phys_t * bmp,dsl_dataset_t * new,uint64_t * usedp,uint64_t * compp,uint64_t * uncompp)4630  dsl_dataset_space_written_impl(zfs_bookmark_phys_t *bmp,
4631      dsl_dataset_t *new, uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4632  {
4633  	int err = 0;
4634  	dsl_pool_t *dp = new->ds_dir->dd_pool;
4635  
4636  	ASSERT(dsl_pool_config_held(dp));
4637  	if (dsl_dataset_is_snapshot(new)) {
4638  		ASSERT3U(bmp->zbm_creation_txg, <,
4639  		    dsl_dataset_phys(new)->ds_creation_txg);
4640  	}
4641  
4642  	*usedp = 0;
4643  	*usedp += dsl_dataset_phys(new)->ds_referenced_bytes;
4644  	*usedp -= bmp->zbm_referenced_bytes_refd;
4645  
4646  	*compp = 0;
4647  	*compp += dsl_dataset_phys(new)->ds_compressed_bytes;
4648  	*compp -= bmp->zbm_compressed_bytes_refd;
4649  
4650  	*uncompp = 0;
4651  	*uncompp += dsl_dataset_phys(new)->ds_uncompressed_bytes;
4652  	*uncompp -= bmp->zbm_uncompressed_bytes_refd;
4653  
4654  	dsl_dataset_t *snap = new;
4655  
4656  	while (dsl_dataset_phys(snap)->ds_prev_snap_txg >
4657  	    bmp->zbm_creation_txg) {
4658  		uint64_t used, comp, uncomp;
4659  
4660  		dsl_deadlist_space_range(&snap->ds_deadlist,
4661  		    0, bmp->zbm_creation_txg,
4662  		    &used, &comp, &uncomp);
4663  		*usedp += used;
4664  		*compp += comp;
4665  		*uncompp += uncomp;
4666  
4667  		uint64_t snapobj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
4668  		if (snap != new)
4669  			dsl_dataset_rele(snap, FTAG);
4670  		err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &snap);
4671  		if (err != 0)
4672  			break;
4673  	}
4674  
4675  	/*
4676  	 * We might not have the FBN if we are calculating written from
4677  	 * a snapshot (because we didn't know the correct "next" snapshot
4678  	 * until now).
4679  	 */
4680  	if (bmp->zbm_flags & ZBM_FLAG_HAS_FBN) {
4681  		*usedp += bmp->zbm_referenced_freed_before_next_snap;
4682  		*compp += bmp->zbm_compressed_freed_before_next_snap;
4683  		*uncompp += bmp->zbm_uncompressed_freed_before_next_snap;
4684  	} else {
4685  		ASSERT3U(dsl_dataset_phys(snap)->ds_prev_snap_txg, ==,
4686  		    bmp->zbm_creation_txg);
4687  		uint64_t used, comp, uncomp;
4688  		dsl_deadlist_space(&snap->ds_deadlist, &used, &comp, &uncomp);
4689  		*usedp += used;
4690  		*compp += comp;
4691  		*uncompp += uncomp;
4692  	}
4693  	if (snap != new)
4694  		dsl_dataset_rele(snap, FTAG);
4695  	return (err);
4696  }
4697  
4698  /*
4699   * Return (in *usedp) the amount of space written in new that was not
4700   * present at the time the bookmark corresponds to.  New may be a
4701   * snapshot or the head.  Old must be a bookmark before new, in
4702   * new's filesystem (or its origin) -- caller verifies this.
4703   */
4704  int
dsl_dataset_space_written_bookmark(zfs_bookmark_phys_t * bmp,dsl_dataset_t * new,uint64_t * usedp,uint64_t * compp,uint64_t * uncompp)4705  dsl_dataset_space_written_bookmark(zfs_bookmark_phys_t *bmp,
4706      dsl_dataset_t *new, uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4707  {
4708  	if (!(bmp->zbm_flags & ZBM_FLAG_HAS_FBN))
4709  		return (SET_ERROR(ENOTSUP));
4710  	return (dsl_dataset_space_written_impl(bmp, new,
4711  	    usedp, compp, uncompp));
4712  }
4713  
4714  /*
4715   * Return (in *usedp) the amount of space written in new that is not
4716   * present in oldsnap.  New may be a snapshot or the head.  Old must be
4717   * a snapshot before new, in new's filesystem (or its origin).  If not then
4718   * fail and return EINVAL.
4719   */
4720  int
dsl_dataset_space_written(dsl_dataset_t * oldsnap,dsl_dataset_t * new,uint64_t * usedp,uint64_t * compp,uint64_t * uncompp)4721  dsl_dataset_space_written(dsl_dataset_t *oldsnap, dsl_dataset_t *new,
4722      uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4723  {
4724  	if (!dsl_dataset_is_before(new, oldsnap, 0))
4725  		return (SET_ERROR(EINVAL));
4726  
4727  	zfs_bookmark_phys_t zbm = { 0 };
4728  	dsl_dataset_phys_t *dsp = dsl_dataset_phys(oldsnap);
4729  	zbm.zbm_guid = dsp->ds_guid;
4730  	zbm.zbm_creation_txg = dsp->ds_creation_txg;
4731  	zbm.zbm_creation_time = dsp->ds_creation_time;
4732  	zbm.zbm_referenced_bytes_refd = dsp->ds_referenced_bytes;
4733  	zbm.zbm_compressed_bytes_refd = dsp->ds_compressed_bytes;
4734  	zbm.zbm_uncompressed_bytes_refd = dsp->ds_uncompressed_bytes;
4735  
4736  	/*
4737  	 * If oldsnap is the origin (or origin's origin, ...) of new,
4738  	 * we can't easily calculate the effective FBN.  Therefore,
4739  	 * we do not set ZBM_FLAG_HAS_FBN, so that the _impl will calculate
4740  	 * it relative to the correct "next": the next snapshot towards "new",
4741  	 * rather than the next snapshot in oldsnap's dsl_dir.
4742  	 */
4743  	return (dsl_dataset_space_written_impl(&zbm, new,
4744  	    usedp, compp, uncompp));
4745  }
4746  
4747  /*
4748   * Return (in *usedp) the amount of space that will be reclaimed if firstsnap,
4749   * lastsnap, and all snapshots in between are deleted.
4750   *
4751   * blocks that would be freed            [---------------------------]
4752   * snapshots                       ---O-------O--------O-------O--------O
4753   *                                        firstsnap        lastsnap
4754   *
4755   * This is the set of blocks that were born after the snap before firstsnap,
4756   * (birth > firstsnap->prev_snap_txg) and died before the snap after the
4757   * last snap (ie, is on lastsnap->ds_next->ds_deadlist or an earlier deadlist).
4758   * We calculate this by iterating over the relevant deadlists (from the snap
4759   * after lastsnap, backward to the snap after firstsnap), summing up the
4760   * space on the deadlist that was born after the snap before firstsnap.
4761   */
4762  int
dsl_dataset_space_wouldfree(dsl_dataset_t * firstsnap,dsl_dataset_t * lastsnap,uint64_t * usedp,uint64_t * compp,uint64_t * uncompp)4763  dsl_dataset_space_wouldfree(dsl_dataset_t *firstsnap,
4764      dsl_dataset_t *lastsnap,
4765      uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
4766  {
4767  	int err = 0;
4768  	uint64_t snapobj;
4769  	dsl_pool_t *dp = firstsnap->ds_dir->dd_pool;
4770  
4771  	ASSERT(firstsnap->ds_is_snapshot);
4772  	ASSERT(lastsnap->ds_is_snapshot);
4773  
4774  	/*
4775  	 * Check that the snapshots are in the same dsl_dir, and firstsnap
4776  	 * is before lastsnap.
4777  	 */
4778  	if (firstsnap->ds_dir != lastsnap->ds_dir ||
4779  	    dsl_dataset_phys(firstsnap)->ds_creation_txg >
4780  	    dsl_dataset_phys(lastsnap)->ds_creation_txg)
4781  		return (SET_ERROR(EINVAL));
4782  
4783  	*usedp = *compp = *uncompp = 0;
4784  
4785  	snapobj = dsl_dataset_phys(lastsnap)->ds_next_snap_obj;
4786  	while (snapobj != firstsnap->ds_object) {
4787  		dsl_dataset_t *ds;
4788  		uint64_t used, comp, uncomp;
4789  
4790  		err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &ds);
4791  		if (err != 0)
4792  			break;
4793  
4794  		dsl_deadlist_space_range(&ds->ds_deadlist,
4795  		    dsl_dataset_phys(firstsnap)->ds_prev_snap_txg, UINT64_MAX,
4796  		    &used, &comp, &uncomp);
4797  		*usedp += used;
4798  		*compp += comp;
4799  		*uncompp += uncomp;
4800  
4801  		snapobj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
4802  		ASSERT3U(snapobj, !=, 0);
4803  		dsl_dataset_rele(ds, FTAG);
4804  	}
4805  	return (err);
4806  }
4807  
4808  /*
4809   * Return TRUE if 'earlier' is an earlier snapshot in 'later's timeline.
4810   * For example, they could both be snapshots of the same filesystem, and
4811   * 'earlier' is before 'later'.  Or 'earlier' could be the origin of
4812   * 'later's filesystem.  Or 'earlier' could be an older snapshot in the origin's
4813   * filesystem.  Or 'earlier' could be the origin's origin.
4814   *
4815   * If non-zero, earlier_txg is used instead of earlier's ds_creation_txg.
4816   */
4817  boolean_t
dsl_dataset_is_before(dsl_dataset_t * later,dsl_dataset_t * earlier,uint64_t earlier_txg)4818  dsl_dataset_is_before(dsl_dataset_t *later, dsl_dataset_t *earlier,
4819      uint64_t earlier_txg)
4820  {
4821  	dsl_pool_t *dp = later->ds_dir->dd_pool;
4822  	int error;
4823  	boolean_t ret;
4824  
4825  	ASSERT(dsl_pool_config_held(dp));
4826  	ASSERT(earlier->ds_is_snapshot || earlier_txg != 0);
4827  
4828  	if (earlier_txg == 0)
4829  		earlier_txg = dsl_dataset_phys(earlier)->ds_creation_txg;
4830  
4831  	if (later->ds_is_snapshot &&
4832  	    earlier_txg >= dsl_dataset_phys(later)->ds_creation_txg)
4833  		return (B_FALSE);
4834  
4835  	if (later->ds_dir == earlier->ds_dir)
4836  		return (B_TRUE);
4837  
4838  	/*
4839  	 * We check dd_origin_obj explicitly here rather than using
4840  	 * dsl_dir_is_clone() so that we will return TRUE if "earlier"
4841  	 * is $ORIGIN@$ORIGIN.  dsl_dataset_space_written() depends on
4842  	 * this behavior.
4843  	 */
4844  	if (dsl_dir_phys(later->ds_dir)->dd_origin_obj == 0)
4845  		return (B_FALSE);
4846  
4847  	dsl_dataset_t *origin;
4848  	error = dsl_dataset_hold_obj(dp,
4849  	    dsl_dir_phys(later->ds_dir)->dd_origin_obj, FTAG, &origin);
4850  	if (error != 0)
4851  		return (B_FALSE);
4852  	if (dsl_dataset_phys(origin)->ds_creation_txg == earlier_txg &&
4853  	    origin->ds_dir == earlier->ds_dir) {
4854  		dsl_dataset_rele(origin, FTAG);
4855  		return (B_TRUE);
4856  	}
4857  	ret = dsl_dataset_is_before(origin, earlier, earlier_txg);
4858  	dsl_dataset_rele(origin, FTAG);
4859  	return (ret);
4860  }
4861  
4862  void
dsl_dataset_zapify(dsl_dataset_t * ds,dmu_tx_t * tx)4863  dsl_dataset_zapify(dsl_dataset_t *ds, dmu_tx_t *tx)
4864  {
4865  	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
4866  	dmu_object_zapify(mos, ds->ds_object, DMU_OT_DSL_DATASET, tx);
4867  }
4868  
4869  boolean_t
dsl_dataset_is_zapified(dsl_dataset_t * ds)4870  dsl_dataset_is_zapified(dsl_dataset_t *ds)
4871  {
4872  	dmu_object_info_t doi;
4873  
4874  	dmu_object_info_from_db(ds->ds_dbuf, &doi);
4875  	return (doi.doi_type == DMU_OTN_ZAP_METADATA);
4876  }
4877  
4878  boolean_t
dsl_dataset_has_resume_receive_state(dsl_dataset_t * ds)4879  dsl_dataset_has_resume_receive_state(dsl_dataset_t *ds)
4880  {
4881  	return (dsl_dataset_is_zapified(ds) &&
4882  	    zap_contains(ds->ds_dir->dd_pool->dp_meta_objset,
4883  	    ds->ds_object, DS_FIELD_RESUME_TOGUID) == 0);
4884  }
4885  
4886  uint64_t
dsl_dataset_get_remap_deadlist_object(dsl_dataset_t * ds)4887  dsl_dataset_get_remap_deadlist_object(dsl_dataset_t *ds)
4888  {
4889  	uint64_t remap_deadlist_obj;
4890  	int err;
4891  
4892  	if (!dsl_dataset_is_zapified(ds))
4893  		return (0);
4894  
4895  	err = zap_lookup(ds->ds_dir->dd_pool->dp_meta_objset, ds->ds_object,
4896  	    DS_FIELD_REMAP_DEADLIST, sizeof (remap_deadlist_obj), 1,
4897  	    &remap_deadlist_obj);
4898  
4899  	if (err != 0) {
4900  		VERIFY3S(err, ==, ENOENT);
4901  		return (0);
4902  	}
4903  
4904  	ASSERT(remap_deadlist_obj != 0);
4905  	return (remap_deadlist_obj);
4906  }
4907  
4908  boolean_t
dsl_dataset_remap_deadlist_exists(dsl_dataset_t * ds)4909  dsl_dataset_remap_deadlist_exists(dsl_dataset_t *ds)
4910  {
4911  	EQUIV(dsl_deadlist_is_open(&ds->ds_remap_deadlist),
4912  	    dsl_dataset_get_remap_deadlist_object(ds) != 0);
4913  	return (dsl_deadlist_is_open(&ds->ds_remap_deadlist));
4914  }
4915  
4916  static void
dsl_dataset_set_remap_deadlist_object(dsl_dataset_t * ds,uint64_t obj,dmu_tx_t * tx)4917  dsl_dataset_set_remap_deadlist_object(dsl_dataset_t *ds, uint64_t obj,
4918      dmu_tx_t *tx)
4919  {
4920  	ASSERT(obj != 0);
4921  	dsl_dataset_zapify(ds, tx);
4922  	VERIFY0(zap_add(ds->ds_dir->dd_pool->dp_meta_objset, ds->ds_object,
4923  	    DS_FIELD_REMAP_DEADLIST, sizeof (obj), 1, &obj, tx));
4924  }
4925  
4926  static void
dsl_dataset_unset_remap_deadlist_object(dsl_dataset_t * ds,dmu_tx_t * tx)4927  dsl_dataset_unset_remap_deadlist_object(dsl_dataset_t *ds, dmu_tx_t *tx)
4928  {
4929  	VERIFY0(zap_remove(ds->ds_dir->dd_pool->dp_meta_objset,
4930  	    ds->ds_object, DS_FIELD_REMAP_DEADLIST, tx));
4931  }
4932  
4933  void
dsl_dataset_destroy_remap_deadlist(dsl_dataset_t * ds,dmu_tx_t * tx)4934  dsl_dataset_destroy_remap_deadlist(dsl_dataset_t *ds, dmu_tx_t *tx)
4935  {
4936  	uint64_t remap_deadlist_object;
4937  	spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
4938  
4939  	ASSERT(dmu_tx_is_syncing(tx));
4940  	ASSERT(dsl_dataset_remap_deadlist_exists(ds));
4941  
4942  	remap_deadlist_object = ds->ds_remap_deadlist.dl_object;
4943  	dsl_deadlist_close(&ds->ds_remap_deadlist);
4944  	dsl_deadlist_free(spa_meta_objset(spa), remap_deadlist_object, tx);
4945  	dsl_dataset_unset_remap_deadlist_object(ds, tx);
4946  	spa_feature_decr(spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
4947  }
4948  
4949  void
dsl_dataset_create_remap_deadlist(dsl_dataset_t * ds,dmu_tx_t * tx)4950  dsl_dataset_create_remap_deadlist(dsl_dataset_t *ds, dmu_tx_t *tx)
4951  {
4952  	uint64_t remap_deadlist_obj;
4953  	spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
4954  
4955  	ASSERT(dmu_tx_is_syncing(tx));
4956  	ASSERT(MUTEX_HELD(&ds->ds_remap_deadlist_lock));
4957  	/*
4958  	 * Currently we only create remap deadlists when there are indirect
4959  	 * vdevs with referenced mappings.
4960  	 */
4961  	ASSERT(spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL));
4962  
4963  	remap_deadlist_obj = dsl_deadlist_clone(
4964  	    &ds->ds_deadlist, UINT64_MAX,
4965  	    dsl_dataset_phys(ds)->ds_prev_snap_obj, tx);
4966  	dsl_dataset_set_remap_deadlist_object(ds,
4967  	    remap_deadlist_obj, tx);
4968  	VERIFY0(dsl_deadlist_open(&ds->ds_remap_deadlist, spa_meta_objset(spa),
4969  	    remap_deadlist_obj));
4970  	spa_feature_incr(spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
4971  }
4972  
4973  void
dsl_dataset_activate_redaction(dsl_dataset_t * ds,uint64_t * redact_snaps,uint64_t num_redact_snaps,dmu_tx_t * tx)4974  dsl_dataset_activate_redaction(dsl_dataset_t *ds, uint64_t *redact_snaps,
4975      uint64_t num_redact_snaps, dmu_tx_t *tx)
4976  {
4977  	uint64_t dsobj = ds->ds_object;
4978  	struct feature_type_uint64_array_arg *ftuaa =
4979  	    kmem_zalloc(sizeof (*ftuaa), KM_SLEEP);
4980  	ftuaa->length = (int64_t)num_redact_snaps;
4981  	if (num_redact_snaps > 0) {
4982  		ftuaa->array = kmem_alloc(num_redact_snaps * sizeof (uint64_t),
4983  		    KM_SLEEP);
4984  		memcpy(ftuaa->array, redact_snaps, num_redact_snaps *
4985  		    sizeof (uint64_t));
4986  	}
4987  	dsl_dataset_activate_feature(dsobj, SPA_FEATURE_REDACTED_DATASETS,
4988  	    ftuaa, tx);
4989  	ds->ds_feature[SPA_FEATURE_REDACTED_DATASETS] = ftuaa;
4990  }
4991  
4992  /*
4993   * Find and return (in *oldest_dsobj) the oldest snapshot of the dsobj
4994   * dataset whose birth time is >= min_txg.
4995   */
4996  int
dsl_dataset_oldest_snapshot(spa_t * spa,uint64_t head_ds,uint64_t min_txg,uint64_t * oldest_dsobj)4997  dsl_dataset_oldest_snapshot(spa_t *spa, uint64_t head_ds, uint64_t min_txg,
4998      uint64_t *oldest_dsobj)
4999  {
5000  	dsl_dataset_t *ds;
5001  	dsl_pool_t *dp = spa->spa_dsl_pool;
5002  
5003  	int error = dsl_dataset_hold_obj(dp, head_ds, FTAG, &ds);
5004  	if (error != 0)
5005  		return (error);
5006  
5007  	uint64_t prev_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
5008  	uint64_t prev_obj_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;
5009  
5010  	while (prev_obj != 0 && min_txg < prev_obj_txg) {
5011  		dsl_dataset_rele(ds, FTAG);
5012  		if ((error = dsl_dataset_hold_obj(dp, prev_obj,
5013  		    FTAG, &ds)) != 0)
5014  			return (error);
5015  		prev_obj_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;
5016  		prev_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
5017  	}
5018  	*oldest_dsobj = ds->ds_object;
5019  	dsl_dataset_rele(ds, FTAG);
5020  	return (0);
5021  }
5022  
5023  ZFS_MODULE_PARAM(zfs, zfs_, max_recordsize, UINT, ZMOD_RW,
5024  	"Max allowed record size");
5025  
5026  ZFS_MODULE_PARAM(zfs, zfs_, allow_redacted_dataset_mount, INT, ZMOD_RW,
5027  	"Allow mounting of redacted datasets");
5028  
5029  ZFS_MODULE_PARAM(zfs, zfs_, snapshot_history_enabled, INT, ZMOD_RW,
5030  	"Include snapshot events in pool history/events");
5031  
5032  EXPORT_SYMBOL(dsl_dataset_hold);
5033  EXPORT_SYMBOL(dsl_dataset_hold_flags);
5034  EXPORT_SYMBOL(dsl_dataset_hold_obj);
5035  EXPORT_SYMBOL(dsl_dataset_hold_obj_flags);
5036  EXPORT_SYMBOL(dsl_dataset_own);
5037  EXPORT_SYMBOL(dsl_dataset_own_obj);
5038  EXPORT_SYMBOL(dsl_dataset_name);
5039  EXPORT_SYMBOL(dsl_dataset_rele);
5040  EXPORT_SYMBOL(dsl_dataset_rele_flags);
5041  EXPORT_SYMBOL(dsl_dataset_disown);
5042  EXPORT_SYMBOL(dsl_dataset_tryown);
5043  EXPORT_SYMBOL(dsl_dataset_create_sync);
5044  EXPORT_SYMBOL(dsl_dataset_create_sync_dd);
5045  EXPORT_SYMBOL(dsl_dataset_snapshot_check);
5046  EXPORT_SYMBOL(dsl_dataset_snapshot_sync);
5047  EXPORT_SYMBOL(dsl_dataset_promote);
5048  EXPORT_SYMBOL(dsl_dataset_user_hold);
5049  EXPORT_SYMBOL(dsl_dataset_user_release);
5050  EXPORT_SYMBOL(dsl_dataset_get_holds);
5051  EXPORT_SYMBOL(dsl_dataset_get_blkptr);
5052  EXPORT_SYMBOL(dsl_dataset_get_spa);
5053  EXPORT_SYMBOL(dsl_dataset_modified_since_snap);
5054  EXPORT_SYMBOL(dsl_dataset_space_written);
5055  EXPORT_SYMBOL(dsl_dataset_space_wouldfree);
5056  EXPORT_SYMBOL(dsl_dataset_sync);
5057  EXPORT_SYMBOL(dsl_dataset_block_born);
5058  EXPORT_SYMBOL(dsl_dataset_block_kill);
5059  EXPORT_SYMBOL(dsl_dataset_dirty);
5060  EXPORT_SYMBOL(dsl_dataset_stats);
5061  EXPORT_SYMBOL(dsl_dataset_fast_stat);
5062  EXPORT_SYMBOL(dsl_dataset_space);
5063  EXPORT_SYMBOL(dsl_dataset_fsid_guid);
5064  EXPORT_SYMBOL(dsl_dsobj_to_dsname);
5065  EXPORT_SYMBOL(dsl_dataset_check_quota);
5066  EXPORT_SYMBOL(dsl_dataset_clone_swap_check_impl);
5067  EXPORT_SYMBOL(dsl_dataset_clone_swap_sync_impl);
5068