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