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