2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2017 Kyle J. Kneitinger <kyle@kneit.in>
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
31 #include <sys/param.h>
32 #include <sys/mount.h>
34 #include <sys/ucred.h>
35 #include <sys/queue.h>
36 #include <sys/zfs_context.h>
37 #include <sys/mntent.h>
38 #include <sys/zfs_ioctl.h>
43 #include <libzfs_core.h>
44 #include <libzfs_impl.h>
53 struct promote_entry {
54 char name[BE_MAXPATHLEN];
55 SLIST_ENTRY(promote_entry) link;
58 struct be_destroy_data {
60 char target_name[BE_MAXPATHLEN];
62 SLIST_HEAD(, promote_entry) promotelist;
66 static int be_create_child_noent(libbe_handle_t *lbh, const char *active,
67 const char *child_path);
68 static int be_create_child_cloned(libbe_handle_t *lbh, const char *active);
71 /* Arbitrary... should tune */
72 #define BE_SNAP_SERIAL_MAX 1024
75 * Iterator function for locating the rootfs amongst the children of the
76 * zfs_be_root set by loader(8). data is expected to be a libbe_handle_t *.
79 be_locate_rootfs(libbe_handle_t *lbh)
86 * Check first if root is ZFS; if not, we'll bail on rootfs capture.
87 * Unfortunately needed because zfs_path_to_zhandle will emit to
88 * stderr if / isn't actually a ZFS filesystem, which we'd like
91 if (statfs("/", &sfs) == 0) {
92 statfs2mnttab(&sfs, &entry);
93 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
97 zfs = zfs_path_to_zhandle(lbh->lzh, "/", ZFS_TYPE_FILESYSTEM);
101 strlcpy(lbh->rootfs, zfs_get_name(zfs), sizeof(lbh->rootfs));
107 * Initializes the libbe context to operate in the root boot environment
108 * dataset, for example, zroot/ROOT.
111 libbe_init(const char *root)
113 char altroot[MAXPATHLEN];
115 char *poolname, *pos;
119 poolname = pos = NULL;
121 if ((lbh = calloc(1, sizeof(libbe_handle_t))) == NULL)
124 if ((lbh->lzh = libzfs_init()) == NULL)
128 * Grab rootfs, we'll work backwards from there if an optional BE root
129 * has not been passed in.
131 if (be_locate_rootfs(lbh) != 0) {
137 /* Strip off the final slash from rootfs to get the be root */
138 strlcpy(lbh->root, lbh->rootfs, sizeof(lbh->root));
139 pos = strrchr(lbh->root, '/');
144 strlcpy(lbh->root, root, sizeof(lbh->root));
146 if ((pos = strchr(lbh->root, '/')) == NULL)
149 pnamelen = pos - lbh->root;
150 poolname = malloc(pnamelen + 1);
151 if (poolname == NULL)
154 strlcpy(poolname, lbh->root, pnamelen + 1);
155 if ((lbh->active_phandle = zpool_open(lbh->lzh, poolname)) == NULL)
160 if (zpool_get_prop(lbh->active_phandle, ZPOOL_PROP_BOOTFS, lbh->bootfs,
161 sizeof(lbh->bootfs), NULL, true) != 0)
164 if (zpool_get_prop(lbh->active_phandle, ZPOOL_PROP_ALTROOT,
165 altroot, sizeof(altroot), NULL, true) == 0 &&
166 strcmp(altroot, "-") != 0)
167 lbh->altroot_len = strlen(altroot);
172 if (lbh->active_phandle != NULL)
173 zpool_close(lbh->active_phandle);
174 if (lbh->lzh != NULL)
175 libzfs_fini(lbh->lzh);
184 * Free memory allocated by libbe_init()
187 libbe_close(libbe_handle_t *lbh)
190 if (lbh->active_phandle != NULL)
191 zpool_close(lbh->active_phandle);
192 libzfs_fini(lbh->lzh);
197 * Proxy through to libzfs for the moment.
200 be_nicenum(uint64_t num, char *buf, size_t buflen)
203 zfs_nicenum(num, buf, buflen);
207 be_should_promote_clones(zfs_handle_t *zfs_hdl, struct be_destroy_data *bdd)
211 if (zfs_get_type(zfs_hdl) != ZFS_TYPE_SNAPSHOT)
215 * If we're deleting a snapshot, we need to make sure we only promote
216 * clones that are derived from one of the snapshots we're deleting,
217 * rather than that of a snapshot we're not touching. This keeps stuff
218 * in a consistent state, making sure that we don't error out unless
221 if (bdd->snapname == NULL)
224 atpos = strchr(zfs_get_name(zfs_hdl), '@');
225 return (strcmp(atpos + 1, bdd->snapname) == 0);
229 * This is executed from be_promote_dependent_clones via zfs_iter_dependents,
230 * It checks if the dependent type is a snapshot then attempts to find any
231 * clones associated with it. Any clones not related to the destroy target are
232 * added to the promote list.
235 be_dependent_clone_cb(zfs_handle_t *zfs_hdl, void *data)
242 struct be_destroy_data *bdd;
243 struct promote_entry *entry, *newentry;
247 bdd = (struct be_destroy_data *)data;
249 if (be_should_promote_clones(zfs_hdl, bdd) &&
250 (nvl = zfs_get_clones_nvl(zfs_hdl)) != NULL) {
251 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
252 name = nvpair_name(nvp);
255 * Skip if the clone is equal to, or a child of, the
258 if (strncmp(name, bdd->target_name,
259 strlen(bdd->target_name)) == 0 ||
260 strstr(name, bdd->target_name) == name) {
265 SLIST_FOREACH(entry, &bdd->promotelist, link) {
266 if (strcmp(entry->name, name) == 0) {
275 newentry = malloc(sizeof(struct promote_entry));
276 if (newentry == NULL) {
281 #define BE_COPY_NAME(entry, src) \
282 strlcpy((entry)->name, (src), sizeof((entry)->name))
283 if (BE_COPY_NAME(newentry, name) >=
284 sizeof(newentry->name)) {
285 /* Shouldn't happen. */
293 * We're building up a SLIST here to make sure both that
294 * we get the order right and so that we don't
295 * inadvertently observe the wrong state by promoting
296 * datasets while we're still walking the tree. The
297 * latter can lead to situations where we promote a BE
298 * then effectively demote it again.
300 SLIST_INSERT_HEAD(&bdd->promotelist, newentry, link);
309 * This is called before a destroy, so that any datasets(environments) that are
310 * dependent on this one get promoted before destroying the target.
313 be_promote_dependent_clones(zfs_handle_t *zfs_hdl, struct be_destroy_data *bdd)
317 struct promote_entry *entry;
319 snprintf(bdd->target_name, BE_MAXPATHLEN, "%s/", zfs_get_name(zfs_hdl));
320 err = zfs_iter_dependents(zfs_hdl, true, be_dependent_clone_cb, bdd);
323 * Drain the list and walk away from it if we're only deleting a
326 if (bdd->snapname != NULL && !SLIST_EMPTY(&bdd->promotelist))
327 err = BE_ERR_HASCLONES;
328 while (!SLIST_EMPTY(&bdd->promotelist)) {
329 entry = SLIST_FIRST(&bdd->promotelist);
330 SLIST_REMOVE_HEAD(&bdd->promotelist, link);
332 #define ZFS_GRAB_CLONE() \
333 zfs_open(bdd->lbh->lzh, entry->name, ZFS_TYPE_FILESYSTEM)
335 * Just skip this part on error, we still want to clean up the
336 * promotion list after the first error. We'll then preserve it
339 if (err == 0 && (clone = ZFS_GRAB_CLONE()) != NULL) {
340 err = zfs_promote(clone);
342 err = BE_ERR_DESTROYMNT;
345 #undef ZFS_GRAB_CLONE
353 be_destroy_cb(zfs_handle_t *zfs_hdl, void *data)
355 char path[BE_MAXPATHLEN];
356 struct be_destroy_data *bdd;
360 bdd = (struct be_destroy_data *)data;
361 if (bdd->snapname == NULL) {
362 err = zfs_iter_children(zfs_hdl, be_destroy_cb, data);
365 return (zfs_destroy(zfs_hdl, false));
367 /* If we're dealing with snapshots instead, delete that one alone */
368 err = zfs_iter_filesystems(zfs_hdl, be_destroy_cb, data);
372 * This part is intentionally glossing over any potential errors,
373 * because there's a lot less potential for errors when we're cleaning
374 * up snapshots rather than a full deep BE. The primary error case
375 * here being if the snapshot doesn't exist in the first place, which
376 * the caller will likely deem insignificant as long as it doesn't
377 * exist after the call. Thus, such a missing snapshot shouldn't jam
378 * up the destruction.
380 snprintf(path, sizeof(path), "%s@%s", zfs_get_name(zfs_hdl),
382 if (!zfs_dataset_exists(bdd->lbh->lzh, path, ZFS_TYPE_SNAPSHOT))
384 snap = zfs_open(bdd->lbh->lzh, path, ZFS_TYPE_SNAPSHOT);
386 zfs_destroy(snap, false);
390 #define BE_DESTROY_WANTORIGIN (BE_DESTROY_ORIGIN | BE_DESTROY_AUTOORIGIN)
392 * Destroy the boot environment or snapshot specified by the name
393 * parameter. Options are or'd together with the possible values:
394 * BE_DESTROY_FORCE : forces operation on mounted datasets
395 * BE_DESTROY_ORIGIN: destroy the origin snapshot as well
398 be_destroy_internal(libbe_handle_t *lbh, const char *name, int options,
401 struct be_destroy_data bdd;
402 char origin[BE_MAXPATHLEN], path[BE_MAXPATHLEN];
405 int err, force, mounted;
410 SLIST_INIT(&bdd.promotelist);
411 force = options & BE_DESTROY_FORCE;
414 be_root_concat(lbh, name, path);
416 if ((snapdelim = strchr(path, '@')) == NULL) {
417 if (!zfs_dataset_exists(lbh->lzh, path, ZFS_TYPE_FILESYSTEM))
418 return (set_error(lbh, BE_ERR_NOENT));
420 if (strcmp(path, lbh->rootfs) == 0 ||
421 strcmp(path, lbh->bootfs) == 0)
422 return (set_error(lbh, BE_ERR_DESTROYACT));
424 fs = zfs_open(lbh->lzh, path, ZFS_TYPE_FILESYSTEM);
426 return (set_error(lbh, BE_ERR_ZFSOPEN));
428 /* Don't destroy a mounted dataset unless force is specified */
429 if ((mounted = zfs_is_mounted(fs, NULL)) != 0) {
431 zfs_unmount(fs, NULL, 0);
434 return (set_error(lbh, BE_ERR_DESTROYMNT));
439 * If we're initially destroying a snapshot, origin options do
440 * not make sense. If we're destroying the origin snapshot of
441 * a BE, we want to maintain the options in case we need to
442 * fake success after failing to promote.
445 options &= ~BE_DESTROY_WANTORIGIN;
446 if (!zfs_dataset_exists(lbh->lzh, path, ZFS_TYPE_SNAPSHOT))
447 return (set_error(lbh, BE_ERR_NOENT));
449 bdd.snapname = strdup(snapdelim + 1);
450 if (bdd.snapname == NULL)
451 return (set_error(lbh, BE_ERR_NOMEM));
453 fs = zfs_open(lbh->lzh, path, ZFS_TYPE_DATASET);
456 return (set_error(lbh, BE_ERR_ZFSOPEN));
461 * Whether we're destroying a BE or a single snapshot, we need to walk
462 * the tree of what we're going to destroy and promote everything in our
463 * path so that we can make it happen.
465 if ((err = be_promote_dependent_clones(fs, &bdd)) != 0) {
469 * If we're just destroying the origin of some other dataset
470 * we were invoked to destroy, then we just ignore
471 * BE_ERR_HASCLONES and return success unless the caller wanted
472 * to force the issue.
474 if (odestroyer && err == BE_ERR_HASCLONES &&
475 (options & BE_DESTROY_AUTOORIGIN) != 0)
477 return (set_error(lbh, err));
481 * This was deferred until after we promote all of the derivatives so
482 * that we grab the new origin after everything's settled down.
484 if ((options & BE_DESTROY_WANTORIGIN) != 0 &&
485 zfs_prop_get(fs, ZFS_PROP_ORIGIN, origin, sizeof(origin),
486 NULL, NULL, 0, 1) != 0 &&
487 (options & BE_DESTROY_ORIGIN) != 0)
488 return (set_error(lbh, BE_ERR_NOORIGIN));
491 * If the caller wants auto-origin destruction and the origin
492 * name matches one of our automatically created snapshot names
493 * (i.e. strftime("%F-%T") with a serial at the end), then
494 * we'll set the DESTROY_ORIGIN flag and nuke it
495 * be_is_auto_snapshot_name is exported from libbe(3) so that
496 * the caller can determine if it needs to warn about the origin
497 * not being destroyed or not.
499 if ((options & BE_DESTROY_AUTOORIGIN) != 0 && *origin != '\0' &&
500 be_is_auto_snapshot_name(lbh, origin))
501 options |= BE_DESTROY_ORIGIN;
503 err = be_destroy_cb(fs, &bdd);
507 /* Children are still present or the mount is referenced */
509 return (set_error(lbh, BE_ERR_DESTROYMNT));
510 return (set_error(lbh, BE_ERR_UNKNOWN));
513 if ((options & BE_DESTROY_ORIGIN) == 0)
516 /* The origin can't possibly be shorter than the BE root */
517 rootlen = strlen(lbh->root);
518 if (*origin == '\0' || strlen(origin) <= rootlen + 1)
519 return (set_error(lbh, BE_ERR_INVORIGIN));
522 * We'll be chopping off the BE root and running this back through
523 * be_destroy, so that we properly handle the origin snapshot whether
524 * it be that of a deep BE or not.
526 if (strncmp(origin, lbh->root, rootlen) != 0 || origin[rootlen] != '/')
529 return (be_destroy_internal(lbh, origin + rootlen + 1,
530 options & ~BE_DESTROY_ORIGIN, true));
534 be_destroy(libbe_handle_t *lbh, const char *name, int options)
538 * The consumer must not set both BE_DESTROY_AUTOORIGIN and
539 * BE_DESTROY_ORIGIN. Internally, we'll set the latter from the former.
540 * The latter should imply that we must succeed at destroying the
541 * origin, or complain otherwise.
543 if ((options & BE_DESTROY_WANTORIGIN) == BE_DESTROY_WANTORIGIN)
544 return (set_error(lbh, BE_ERR_UNKNOWN));
545 return (be_destroy_internal(lbh, name, options, false));
549 be_setup_snapshot_name(libbe_handle_t *lbh, char *buf, size_t buflen)
556 len += strftime(buf + len, buflen - len, "@%F-%T", localtime(&rawtime));
557 /* No room for serial... caller will do its best */
558 if (buflen - len < 2)
561 for (serial = 0; serial < BE_SNAP_SERIAL_MAX; ++serial) {
562 snprintf(buf + len, buflen - len, "-%d", serial);
563 if (!zfs_dataset_exists(lbh->lzh, buf, ZFS_TYPE_SNAPSHOT))
569 be_is_auto_snapshot_name(libbe_handle_t *lbh __unused, const char *name)
572 int day, hour, minute, month, second, serial, year;
574 if ((snap = strchr(name, '@')) == NULL)
577 /* We'll grab the individual components and do some light validation. */
578 if (sscanf(snap, "%d-%d-%d-%d:%d:%d-%d", &year, &month, &day, &hour,
579 &minute, &second, &serial) != 7)
581 return (year >= 1970) && (month >= 1 && month <= 12) &&
582 (day >= 1 && day <= 31) && (hour >= 0 && hour <= 23) &&
583 (minute >= 0 && minute <= 59) && (second >= 0 && second <= 60) &&
588 be_snapshot(libbe_handle_t *lbh, const char *source, const char *snap_name,
589 bool recursive, char *result)
591 char buf[BE_MAXPATHLEN];
594 be_root_concat(lbh, source, buf);
596 if ((err = be_exists(lbh, buf)) != 0)
597 return (set_error(lbh, err));
599 if (snap_name != NULL) {
600 if (strlcat(buf, "@", sizeof(buf)) >= sizeof(buf))
601 return (set_error(lbh, BE_ERR_INVALIDNAME));
603 if (strlcat(buf, snap_name, sizeof(buf)) >= sizeof(buf))
604 return (set_error(lbh, BE_ERR_INVALIDNAME));
607 snprintf(result, BE_MAXPATHLEN, "%s@%s", source,
610 be_setup_snapshot_name(lbh, buf, sizeof(buf));
612 if (result != NULL && strlcpy(result, strrchr(buf, '/') + 1,
613 sizeof(buf)) >= sizeof(buf))
614 return (set_error(lbh, BE_ERR_INVALIDNAME));
616 if ((err = zfs_snapshot(lbh->lzh, buf, recursive, NULL)) != 0) {
618 case EZFS_INVALIDNAME:
619 return (set_error(lbh, BE_ERR_INVALIDNAME));
623 * The other errors that zfs_ioc_snapshot might return
624 * shouldn't happen if we've set things up properly, so
625 * we'll gloss over them and call it UNKNOWN as it will
626 * require further triage.
628 if (errno == ENOTSUP)
629 return (set_error(lbh, BE_ERR_NOPOOL));
630 return (set_error(lbh, BE_ERR_UNKNOWN));
634 return (BE_ERR_SUCCESS);
639 * Create the boot environment specified by the name parameter
642 be_create(libbe_handle_t *lbh, const char *name)
646 err = be_create_from_existing(lbh, name, be_active_path(lbh));
648 return (set_error(lbh, err));
652 be_deep_clone_prop(int prop, void *cb)
655 struct libbe_dccb *dccb;
657 char pval[BE_MAXPATHLEN];
658 char source[BE_MAXPATHLEN];
662 /* Skip some properties we don't want to touch */
663 if (prop == ZFS_PROP_CANMOUNT)
666 /* Don't copy readonly properties */
667 if (zfs_prop_readonly(prop))
670 if ((err = zfs_prop_get(dccb->zhp, prop, (char *)&pval,
671 sizeof(pval), &src, (char *)&source, sizeof(source), false)))
672 /* Just continue if we fail to read a property */
676 * Only copy locally defined or received properties. This continues
677 * to avoid temporary/default/local properties intentionally without
678 * breaking received datasets.
680 if (src != ZPROP_SRC_LOCAL && src != ZPROP_SRC_RECEIVED)
683 /* Augment mountpoint with altroot, if needed */
685 if (prop == ZFS_PROP_MOUNTPOINT)
686 val = be_mountpoint_augmented(dccb->lbh, val);
688 nvlist_add_string(dccb->props, zfs_prop_to_name(prop), val);
694 * Return the corresponding boot environment path for a given
695 * dataset path, the constructed path is placed in 'result'.
697 * example: say our new boot environment name is 'bootenv' and
698 * the dataset path is 'zroot/ROOT/default/data/set'.
700 * result should produce: 'zroot/ROOT/bootenv/data/set'
703 be_get_path(struct libbe_deep_clone *ldc, const char *dspath, char *result, int result_size)
708 /* match the root path for the boot environments */
709 pos = strstr(dspath, ldc->lbh->root);
711 /* no match, different pools? */
713 return (BE_ERR_BADPATH);
715 /* root path of the new boot environment */
716 snprintf(result, result_size, "%s/%s", ldc->lbh->root, ldc->bename);
718 /* gets us to the parent dataset, the +1 consumes a trailing slash */
719 pos += strlen(ldc->lbh->root) + 1;
721 /* skip the parent dataset */
722 if ((child_dataset = strchr(pos, '/')) != NULL)
723 strlcat(result, child_dataset, result_size);
725 return (BE_ERR_SUCCESS);
729 be_clone_cb(zfs_handle_t *ds, void *data)
732 char be_path[BE_MAXPATHLEN];
733 char snap_path[BE_MAXPATHLEN];
735 zfs_handle_t *snap_hdl;
737 struct libbe_deep_clone *ldc;
738 struct libbe_dccb dccb;
740 ldc = (struct libbe_deep_clone *)data;
741 dspath = zfs_get_name(ds);
743 snprintf(snap_path, sizeof(snap_path), "%s@%s", dspath, ldc->snapname);
745 /* construct the boot environment path from the dataset we're cloning */
746 if (be_get_path(ldc, dspath, be_path, sizeof(be_path)) != BE_ERR_SUCCESS)
747 return (set_error(ldc->lbh, BE_ERR_UNKNOWN));
749 /* the dataset to be created (i.e. the boot environment) already exists */
750 if (zfs_dataset_exists(ldc->lbh->lzh, be_path, ZFS_TYPE_DATASET))
751 return (set_error(ldc->lbh, BE_ERR_EXISTS));
753 /* no snapshot found for this dataset, silently skip it */
754 if (!zfs_dataset_exists(ldc->lbh->lzh, snap_path, ZFS_TYPE_SNAPSHOT))
758 zfs_open(ldc->lbh->lzh, snap_path, ZFS_TYPE_SNAPSHOT)) == NULL)
759 return (set_error(ldc->lbh, BE_ERR_ZFSOPEN));
761 nvlist_alloc(&props, NV_UNIQUE_NAME, KM_SLEEP);
762 nvlist_add_string(props, "canmount", "noauto");
767 if (zprop_iter(be_deep_clone_prop, &dccb, B_FALSE, B_FALSE,
768 ZFS_TYPE_FILESYSTEM) == ZPROP_INVAL)
771 if ((err = zfs_clone(snap_hdl, be_path, props)) != 0)
772 return (set_error(ldc->lbh, BE_ERR_ZFSCLONE));
777 if (ldc->depth_limit == -1 || ldc->depth < ldc->depth_limit) {
779 err = zfs_iter_filesystems(ds, be_clone_cb, ldc);
783 return (set_error(ldc->lbh, err));
787 * Create a boot environment with a given name from a given snapshot.
788 * Snapshots can be in the format 'zroot/ROOT/default@snapshot' or
789 * 'default@snapshot'. In the latter case, 'default@snapshot' will be prepended
790 * with the root path that libbe was initailized with.
793 be_clone(libbe_handle_t *lbh, const char *bename, const char *snapshot, int depth)
796 char snap_path[BE_MAXPATHLEN];
797 char *parentname, *snapname;
798 zfs_handle_t *parent_hdl;
799 struct libbe_deep_clone ldc;
801 /* ensure the boot environment name is valid */
802 if ((err = be_validate_name(lbh, bename)) != 0)
803 return (set_error(lbh, err));
806 * prepend the boot environment root path if we're
807 * given a partial snapshot name.
809 if ((err = be_root_concat(lbh, snapshot, snap_path)) != 0)
810 return (set_error(lbh, err));
812 /* ensure the snapshot exists */
813 if ((err = be_validate_snap(lbh, snap_path)) != 0)
814 return (set_error(lbh, err));
816 /* get a copy of the snapshot path so we can disect it */
817 if ((parentname = strdup(snap_path)) == NULL)
818 return (set_error(lbh, BE_ERR_UNKNOWN));
820 /* split dataset name from snapshot name */
821 snapname = strchr(parentname, '@');
822 if (snapname == NULL) {
824 return (set_error(lbh, BE_ERR_UNKNOWN));
829 /* set-up the boot environment */
832 ldc.snapname = snapname;
834 ldc.depth_limit = depth;
836 /* the boot environment will be cloned from this dataset */
837 parent_hdl = zfs_open(lbh->lzh, parentname, ZFS_TYPE_DATASET);
839 /* create the boot environment */
840 err = be_clone_cb(parent_hdl, &ldc);
843 return (set_error(lbh, err));
847 * Create a boot environment from pre-existing snapshot, specifying a depth.
849 int be_create_depth(libbe_handle_t *lbh, const char *bename,
850 const char *snap, int depth)
852 return (be_clone(lbh, bename, snap, depth));
856 * Create the boot environment from pre-existing snapshot
859 be_create_from_existing_snap(libbe_handle_t *lbh, const char *bename,
862 return (be_clone(lbh, bename, snap, -1));
867 * Create a boot environment from an existing boot environment
870 be_create_from_existing(libbe_handle_t *lbh, const char *bename, const char *old)
873 char snap[BE_MAXPATHLEN];
875 if ((err = be_snapshot(lbh, old, NULL, true, snap)) != 0)
876 return (set_error(lbh, err));
878 err = be_clone(lbh, bename, snap, -1);
880 return (set_error(lbh, err));
885 * Verifies that a snapshot has a valid name, exists, and has a mountpoint of
886 * '/'. Returns BE_ERR_SUCCESS (0), upon success, or the relevant BE_ERR_* upon
887 * failure. Does not set the internal library error state.
890 be_validate_snap(libbe_handle_t *lbh, const char *snap_name)
893 if (strlen(snap_name) >= BE_MAXPATHLEN)
894 return (BE_ERR_PATHLEN);
896 if (!zfs_name_valid(snap_name, ZFS_TYPE_SNAPSHOT))
897 return (BE_ERR_INVALIDNAME);
899 if (!zfs_dataset_exists(lbh->lzh, snap_name,
901 return (BE_ERR_NOENT);
903 return (BE_ERR_SUCCESS);
908 * Idempotently appends the name argument to the root boot environment path
909 * and copies the resulting string into the result buffer (which is assumed
910 * to be at least BE_MAXPATHLEN characters long. Returns BE_ERR_SUCCESS upon
911 * success, BE_ERR_PATHLEN if the resulting path is longer than BE_MAXPATHLEN,
912 * or BE_ERR_INVALIDNAME if the name is a path that does not begin with
913 * zfs_be_root. Does not set internal library error state.
916 be_root_concat(libbe_handle_t *lbh, const char *name, char *result)
918 size_t name_len, root_len;
920 name_len = strlen(name);
921 root_len = strlen(lbh->root);
923 /* Act idempotently; return be name if it is already a full path */
924 if (strrchr(name, '/') != NULL) {
925 if (strstr(name, lbh->root) != name)
926 return (BE_ERR_INVALIDNAME);
928 if (name_len >= BE_MAXPATHLEN)
929 return (BE_ERR_PATHLEN);
931 strlcpy(result, name, BE_MAXPATHLEN);
932 return (BE_ERR_SUCCESS);
933 } else if (name_len + root_len + 1 < BE_MAXPATHLEN) {
934 snprintf(result, BE_MAXPATHLEN, "%s/%s", lbh->root,
936 return (BE_ERR_SUCCESS);
939 return (BE_ERR_PATHLEN);
944 * Verifies the validity of a boot environment name (A-Za-z0-9-_.). Returns
945 * BE_ERR_SUCCESS (0) if name is valid, otherwise returns BE_ERR_INVALIDNAME
947 * Does not set internal library error state.
950 be_validate_name(libbe_handle_t *lbh, const char *name)
954 * Impose the additional restriction that the entire dataset name must
955 * not exceed the maximum length of a dataset, i.e. MAXNAMELEN.
957 if (strlen(lbh->root) + 1 + strlen(name) > MAXNAMELEN)
958 return (BE_ERR_PATHLEN);
960 if (!zfs_name_valid(name, ZFS_TYPE_DATASET))
961 return (BE_ERR_INVALIDNAME);
963 return (BE_ERR_SUCCESS);
971 be_rename(libbe_handle_t *lbh, const char *old, const char *new)
973 char full_old[BE_MAXPATHLEN];
974 char full_new[BE_MAXPATHLEN];
975 zfs_handle_t *zfs_hdl;
979 * be_validate_name is documented not to set error state, so we should
982 if ((err = be_validate_name(lbh, new)) != 0)
983 return (set_error(lbh, err));
984 if ((err = be_root_concat(lbh, old, full_old)) != 0)
985 return (set_error(lbh, err));
986 if ((err = be_root_concat(lbh, new, full_new)) != 0)
987 return (set_error(lbh, err));
989 if (!zfs_dataset_exists(lbh->lzh, full_old, ZFS_TYPE_DATASET))
990 return (set_error(lbh, BE_ERR_NOENT));
992 if (zfs_dataset_exists(lbh->lzh, full_new, ZFS_TYPE_DATASET))
993 return (set_error(lbh, BE_ERR_EXISTS));
995 if ((zfs_hdl = zfs_open(lbh->lzh, full_old,
996 ZFS_TYPE_FILESYSTEM)) == NULL)
997 return (set_error(lbh, BE_ERR_ZFSOPEN));
999 /* recurse, nounmount, forceunmount */
1000 struct renameflags flags = {
1003 err = zfs_rename(zfs_hdl, full_new, flags);
1007 return (set_error(lbh, BE_ERR_UNKNOWN));
1013 be_export(libbe_handle_t *lbh, const char *bootenv, int fd)
1015 char snap_name[BE_MAXPATHLEN];
1016 char buf[BE_MAXPATHLEN];
1018 sendflags_t flags = { 0 };
1021 if ((err = be_snapshot(lbh, bootenv, NULL, true, snap_name)) != 0)
1022 /* Use the error set by be_snapshot */
1025 be_root_concat(lbh, snap_name, buf);
1027 if ((zfs = zfs_open(lbh->lzh, buf, ZFS_TYPE_DATASET)) == NULL)
1028 return (set_error(lbh, BE_ERR_ZFSOPEN));
1030 err = zfs_send_one(zfs, NULL, fd, &flags, /* redactbook */ NULL);
1038 be_import(libbe_handle_t *lbh, const char *bootenv, int fd)
1040 char buf[BE_MAXPATHLEN];
1043 recvflags_t flags = { .nomount = 1 };
1046 be_root_concat(lbh, bootenv, buf);
1048 if ((err = zfs_receive(lbh->lzh, buf, NULL, &flags, fd, NULL)) != 0) {
1051 return (set_error(lbh, BE_ERR_NOORIGIN));
1053 return (set_error(lbh, BE_ERR_NOENT));
1055 return (set_error(lbh, BE_ERR_IO));
1057 return (set_error(lbh, BE_ERR_UNKNOWN));
1061 if ((zfs = zfs_open(lbh->lzh, buf, ZFS_TYPE_FILESYSTEM)) == NULL)
1062 return (set_error(lbh, BE_ERR_ZFSOPEN));
1064 nvlist_alloc(&props, NV_UNIQUE_NAME, KM_SLEEP);
1065 nvlist_add_string(props, "canmount", "noauto");
1066 nvlist_add_string(props, "mountpoint", "none");
1068 err = zfs_prop_set_list(zfs, props);
1074 return (set_error(lbh, BE_ERR_UNKNOWN));
1081 be_create_child_noent(libbe_handle_t *lbh, const char *active,
1082 const char *child_path)
1088 nvlist_alloc(&props, NV_UNIQUE_NAME, KM_SLEEP);
1089 nvlist_add_string(props, "canmount", "noauto");
1090 nvlist_add_string(props, "mountpoint", child_path);
1093 if ((err = zfs_create(lbh->lzh, active, ZFS_TYPE_DATASET,
1097 return (set_error(lbh, BE_ERR_EXISTS));
1099 return (set_error(lbh, BE_ERR_NOENT));
1101 case EZFS_BADVERSION:
1102 return (set_error(lbh, BE_ERR_NOPOOL));
1105 /* We set something up wrong, probably... */
1106 return (set_error(lbh, BE_ERR_UNKNOWN));
1111 if ((zfs = zfs_open(lbh->lzh, active, ZFS_TYPE_DATASET)) == NULL)
1112 return (set_error(lbh, BE_ERR_ZFSOPEN));
1115 if ((err = zfs_prop_set(zfs, "canmount", "noauto")) != 0) {
1118 * Similar to other cases, this shouldn't fail unless we've
1119 * done something wrong. This is a new dataset that shouldn't
1120 * have been mounted anywhere between creation and now.
1122 if (err == EZFS_NOMEM)
1123 return (set_error(lbh, BE_ERR_NOMEM));
1124 return (set_error(lbh, BE_ERR_UNKNOWN));
1127 return (BE_ERR_SUCCESS);
1131 be_create_child_cloned(libbe_handle_t *lbh, const char *active)
1133 char buf[BE_MAXPATHLEN], tmp[BE_MAXPATHLEN];;
1140 * Establish if the existing path is a zfs dataset or just
1141 * the subdirectory of one
1143 strlcpy(tmp, "tmp/be_snap.XXXXX", sizeof(tmp));
1144 if (mktemp(tmp) == NULL)
1145 return (set_error(lbh, BE_ERR_UNKNOWN));
1147 be_root_concat(lbh, tmp, buf);
1148 printf("Here %s?\n", buf);
1149 if ((err = zfs_snapshot(lbh->lzh, buf, false, NULL)) != 0) {
1151 case EZFS_INVALIDNAME:
1152 return (set_error(lbh, BE_ERR_INVALIDNAME));
1156 * The other errors that zfs_ioc_snapshot might return
1157 * shouldn't happen if we've set things up properly, so
1158 * we'll gloss over them and call it UNKNOWN as it will
1159 * require further triage.
1161 if (errno == ENOTSUP)
1162 return (set_error(lbh, BE_ERR_NOPOOL));
1163 return (set_error(lbh, BE_ERR_UNKNOWN));
1168 if ((zfs = zfs_open(lbh->lzh, buf, ZFS_TYPE_SNAPSHOT)) == NULL)
1169 return (BE_ERR_ZFSOPEN);
1171 if ((err = zfs_clone(zfs, active, NULL)) != 0)
1172 /* XXX TODO correct error */
1173 return (set_error(lbh, BE_ERR_UNKNOWN));
1177 return (BE_ERR_SUCCESS);
1181 be_add_child(libbe_handle_t *lbh, const char *child_path, bool cp_if_exists)
1184 char active[BE_MAXPATHLEN], buf[BE_MAXPATHLEN];
1188 /* Require absolute paths */
1189 if (*child_path != '/')
1190 return (set_error(lbh, BE_ERR_BADPATH));
1192 strlcpy(active, be_active_path(lbh), BE_MAXPATHLEN);
1193 strcpy(buf, active);
1195 /* Create non-mountable parent dataset(s) */
1197 for (char *p; (p = strchr(s+1, '/')) != NULL; s = p) {
1199 strncat(buf, s, len);
1201 nvlist_alloc(&props, NV_UNIQUE_NAME, KM_SLEEP);
1202 nvlist_add_string(props, "canmount", "off");
1203 nvlist_add_string(props, "mountpoint", "none");
1204 zfs_create(lbh->lzh, buf, ZFS_TYPE_DATASET, props);
1208 /* Path does not exist as a descendent of / yet */
1209 if (strlcat(active, child_path, BE_MAXPATHLEN) >= BE_MAXPATHLEN)
1210 return (set_error(lbh, BE_ERR_PATHLEN));
1212 if (stat(child_path, &sb) != 0) {
1213 /* Verify that error is ENOENT */
1214 if (errno != ENOENT)
1215 return (set_error(lbh, BE_ERR_UNKNOWN));
1216 return (be_create_child_noent(lbh, active, child_path));
1217 } else if (cp_if_exists)
1218 /* Path is already a descendent of / and should be copied */
1219 return (be_create_child_cloned(lbh, active));
1220 return (set_error(lbh, BE_ERR_EXISTS));
1225 be_set_nextboot(libbe_handle_t *lbh, nvlist_t *config, uint64_t pool_guid,
1232 if (nvlist_lookup_nvlist_array(config, ZPOOL_CONFIG_CHILDREN, &child,
1234 for (c = 0; c < children; ++c)
1235 if (be_set_nextboot(lbh, child[c], pool_guid, zfsdev) != 0)
1240 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID,
1245 if (zpool_nextboot(lbh->lzh, pool_guid, vdev_guid, zfsdev) != 0) {
1246 perror("ZFS_IOC_NEXTBOOT failed");
1254 * Deactivate old BE dataset; currently just sets canmount=noauto
1257 be_deactivate(libbe_handle_t *lbh, const char *ds)
1261 if ((zfs = zfs_open(lbh->lzh, ds, ZFS_TYPE_DATASET)) == NULL)
1263 if (zfs_prop_set(zfs, "canmount", "noauto") != 0)
1270 be_activate(libbe_handle_t *lbh, const char *bootenv, bool temporary)
1272 char be_path[BE_MAXPATHLEN];
1273 char buf[BE_MAXPATHLEN];
1274 nvlist_t *config, *dsprops, *vdevs;
1280 be_root_concat(lbh, bootenv, be_path);
1282 /* Note: be_exists fails if mountpoint is not / */
1283 if ((err = be_exists(lbh, be_path)) != 0)
1284 return (set_error(lbh, err));
1287 config = zpool_get_config(lbh->active_phandle, NULL);
1289 /* config should be fetchable... */
1290 return (set_error(lbh, BE_ERR_UNKNOWN));
1292 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
1294 /* Similarly, it shouldn't be possible */
1295 return (set_error(lbh, BE_ERR_UNKNOWN));
1297 /* Expected format according to zfsbootcfg(8) man */
1298 snprintf(buf, sizeof(buf), "zfs:%s:", be_path);
1300 /* We have no config tree */
1301 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1303 return (set_error(lbh, BE_ERR_NOPOOL));
1305 return (be_set_nextboot(lbh, vdevs, pool_guid, buf));
1307 if (be_deactivate(lbh, lbh->bootfs) != 0)
1310 /* Obtain bootenv zpool */
1311 err = zpool_set_prop(lbh->active_phandle, "bootfs", be_path);
1315 zhp = zfs_open(lbh->lzh, be_path, ZFS_TYPE_FILESYSTEM);
1319 if (be_prop_list_alloc(&dsprops) != 0)
1322 if (be_get_dataset_props(lbh, be_path, dsprops) != 0) {
1323 nvlist_free(dsprops);
1327 if (nvlist_lookup_string(dsprops, "origin", &origin) == 0)
1328 err = zfs_promote(zhp);
1329 nvlist_free(dsprops);
1337 return (BE_ERR_SUCCESS);