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>
49 #include <libzfsbootenv.h>
54 struct promote_entry {
55 char name[BE_MAXPATHLEN];
56 SLIST_ENTRY(promote_entry) link;
59 struct be_destroy_data {
61 char target_name[BE_MAXPATHLEN];
63 SLIST_HEAD(, promote_entry) promotelist;
67 static int be_create_child_noent(libbe_handle_t *lbh, const char *active,
68 const char *child_path);
69 static int be_create_child_cloned(libbe_handle_t *lbh, const char *active);
72 /* Arbitrary... should tune */
73 #define BE_SNAP_SERIAL_MAX 1024
76 * Iterator function for locating the rootfs amongst the children of the
77 * zfs_be_root set by loader(8). data is expected to be a libbe_handle_t *.
80 be_locate_rootfs(libbe_handle_t *lbh)
87 * Check first if root is ZFS; if not, we'll bail on rootfs capture.
88 * Unfortunately needed because zfs_path_to_zhandle will emit to
89 * stderr if / isn't actually a ZFS filesystem, which we'd like
92 if (statfs("/", &sfs) == 0) {
93 statfs2mnttab(&sfs, &entry);
94 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
98 zfs = zfs_path_to_zhandle(lbh->lzh, "/", ZFS_TYPE_FILESYSTEM);
102 strlcpy(lbh->rootfs, zfs_get_name(zfs), sizeof(lbh->rootfs));
108 * Initializes the libbe context to operate in the root boot environment
109 * dataset, for example, zroot/ROOT.
112 libbe_init(const char *root)
114 char altroot[MAXPATHLEN];
116 char *poolname, *pos;
120 poolname = pos = NULL;
122 if ((lbh = calloc(1, sizeof(libbe_handle_t))) == NULL)
125 if ((lbh->lzh = libzfs_init()) == NULL)
129 * Grab rootfs, we'll work backwards from there if an optional BE root
130 * has not been passed in.
132 if (be_locate_rootfs(lbh) != 0) {
138 /* Strip off the final slash from rootfs to get the be root */
139 strlcpy(lbh->root, lbh->rootfs, sizeof(lbh->root));
140 pos = strrchr(lbh->root, '/');
145 strlcpy(lbh->root, root, sizeof(lbh->root));
147 if ((pos = strchr(lbh->root, '/')) == NULL)
150 pnamelen = pos - lbh->root;
151 poolname = malloc(pnamelen + 1);
152 if (poolname == NULL)
155 strlcpy(poolname, lbh->root, pnamelen + 1);
156 if ((lbh->active_phandle = zpool_open(lbh->lzh, poolname)) == NULL)
161 if (zpool_get_prop(lbh->active_phandle, ZPOOL_PROP_BOOTFS, lbh->bootfs,
162 sizeof(lbh->bootfs), NULL, true) != 0)
165 if (zpool_get_prop(lbh->active_phandle, ZPOOL_PROP_ALTROOT,
166 altroot, sizeof(altroot), NULL, true) == 0 &&
167 strcmp(altroot, "-") != 0)
168 lbh->altroot_len = strlen(altroot);
173 if (lbh->active_phandle != NULL)
174 zpool_close(lbh->active_phandle);
175 if (lbh->lzh != NULL)
176 libzfs_fini(lbh->lzh);
185 * Free memory allocated by libbe_init()
188 libbe_close(libbe_handle_t *lbh)
191 if (lbh->active_phandle != NULL)
192 zpool_close(lbh->active_phandle);
193 libzfs_fini(lbh->lzh);
198 * Proxy through to libzfs for the moment.
201 be_nicenum(uint64_t num, char *buf, size_t buflen)
204 zfs_nicenum(num, buf, buflen);
208 be_should_promote_clones(zfs_handle_t *zfs_hdl, struct be_destroy_data *bdd)
212 if (zfs_get_type(zfs_hdl) != ZFS_TYPE_SNAPSHOT)
216 * If we're deleting a snapshot, we need to make sure we only promote
217 * clones that are derived from one of the snapshots we're deleting,
218 * rather than that of a snapshot we're not touching. This keeps stuff
219 * in a consistent state, making sure that we don't error out unless
222 if (bdd->snapname == NULL)
225 atpos = strchr(zfs_get_name(zfs_hdl), '@');
226 return (strcmp(atpos + 1, bdd->snapname) == 0);
230 * This is executed from be_promote_dependent_clones via zfs_iter_dependents,
231 * It checks if the dependent type is a snapshot then attempts to find any
232 * clones associated with it. Any clones not related to the destroy target are
233 * added to the promote list.
236 be_dependent_clone_cb(zfs_handle_t *zfs_hdl, void *data)
243 struct be_destroy_data *bdd;
244 struct promote_entry *entry, *newentry;
248 bdd = (struct be_destroy_data *)data;
250 if (be_should_promote_clones(zfs_hdl, bdd) &&
251 (nvl = zfs_get_clones_nvl(zfs_hdl)) != NULL) {
252 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
253 name = nvpair_name(nvp);
256 * Skip if the clone is equal to, or a child of, the
259 if (strncmp(name, bdd->target_name,
260 strlen(bdd->target_name)) == 0 ||
261 strstr(name, bdd->target_name) == name) {
266 SLIST_FOREACH(entry, &bdd->promotelist, link) {
267 if (strcmp(entry->name, name) == 0) {
276 newentry = malloc(sizeof(struct promote_entry));
277 if (newentry == NULL) {
282 #define BE_COPY_NAME(entry, src) \
283 strlcpy((entry)->name, (src), sizeof((entry)->name))
284 if (BE_COPY_NAME(newentry, name) >=
285 sizeof(newentry->name)) {
286 /* Shouldn't happen. */
294 * We're building up a SLIST here to make sure both that
295 * we get the order right and so that we don't
296 * inadvertently observe the wrong state by promoting
297 * datasets while we're still walking the tree. The
298 * latter can lead to situations where we promote a BE
299 * then effectively demote it again.
301 SLIST_INSERT_HEAD(&bdd->promotelist, newentry, link);
310 * This is called before a destroy, so that any datasets(environments) that are
311 * dependent on this one get promoted before destroying the target.
314 be_promote_dependent_clones(zfs_handle_t *zfs_hdl, struct be_destroy_data *bdd)
318 struct promote_entry *entry;
320 snprintf(bdd->target_name, BE_MAXPATHLEN, "%s/", zfs_get_name(zfs_hdl));
321 err = zfs_iter_dependents(zfs_hdl, 0, true, be_dependent_clone_cb, bdd);
324 * Drain the list and walk away from it if we're only deleting a
327 if (bdd->snapname != NULL && !SLIST_EMPTY(&bdd->promotelist))
328 err = BE_ERR_HASCLONES;
329 while (!SLIST_EMPTY(&bdd->promotelist)) {
330 entry = SLIST_FIRST(&bdd->promotelist);
331 SLIST_REMOVE_HEAD(&bdd->promotelist, link);
333 #define ZFS_GRAB_CLONE() \
334 zfs_open(bdd->lbh->lzh, entry->name, ZFS_TYPE_FILESYSTEM)
336 * Just skip this part on error, we still want to clean up the
337 * promotion list after the first error. We'll then preserve it
340 if (err == 0 && (clone = ZFS_GRAB_CLONE()) != NULL) {
341 err = zfs_promote(clone);
343 err = BE_ERR_DESTROYMNT;
346 #undef ZFS_GRAB_CLONE
354 be_destroy_cb(zfs_handle_t *zfs_hdl, void *data)
356 char path[BE_MAXPATHLEN];
357 struct be_destroy_data *bdd;
361 bdd = (struct be_destroy_data *)data;
362 if (bdd->snapname == NULL) {
363 err = zfs_iter_children(zfs_hdl, 0, be_destroy_cb, data);
366 return (zfs_destroy(zfs_hdl, false));
368 /* If we're dealing with snapshots instead, delete that one alone */
369 err = zfs_iter_filesystems(zfs_hdl, 0, be_destroy_cb, data);
373 * This part is intentionally glossing over any potential errors,
374 * because there's a lot less potential for errors when we're cleaning
375 * up snapshots rather than a full deep BE. The primary error case
376 * here being if the snapshot doesn't exist in the first place, which
377 * the caller will likely deem insignificant as long as it doesn't
378 * exist after the call. Thus, such a missing snapshot shouldn't jam
379 * up the destruction.
381 snprintf(path, sizeof(path), "%s@%s", zfs_get_name(zfs_hdl),
383 if (!zfs_dataset_exists(bdd->lbh->lzh, path, ZFS_TYPE_SNAPSHOT))
385 snap = zfs_open(bdd->lbh->lzh, path, ZFS_TYPE_SNAPSHOT);
387 zfs_destroy(snap, false);
391 #define BE_DESTROY_WANTORIGIN (BE_DESTROY_ORIGIN | BE_DESTROY_AUTOORIGIN)
393 * Destroy the boot environment or snapshot specified by the name
394 * parameter. Options are or'd together with the possible values:
395 * BE_DESTROY_FORCE : forces operation on mounted datasets
396 * BE_DESTROY_ORIGIN: destroy the origin snapshot as well
399 be_destroy_internal(libbe_handle_t *lbh, const char *name, int options,
402 struct be_destroy_data bdd;
403 char origin[BE_MAXPATHLEN], path[BE_MAXPATHLEN];
406 int err, force, mounted;
411 SLIST_INIT(&bdd.promotelist);
412 force = options & BE_DESTROY_FORCE;
415 be_root_concat(lbh, name, path);
417 if ((snapdelim = strchr(path, '@')) == NULL) {
418 if (!zfs_dataset_exists(lbh->lzh, path, ZFS_TYPE_FILESYSTEM))
419 return (set_error(lbh, BE_ERR_NOENT));
421 if (strcmp(path, lbh->rootfs) == 0 ||
422 strcmp(path, lbh->bootfs) == 0)
423 return (set_error(lbh, BE_ERR_DESTROYACT));
425 fs = zfs_open(lbh->lzh, path, ZFS_TYPE_FILESYSTEM);
427 return (set_error(lbh, BE_ERR_ZFSOPEN));
429 /* Don't destroy a mounted dataset unless force is specified */
430 if ((mounted = zfs_is_mounted(fs, NULL)) != 0) {
432 zfs_unmount(fs, NULL, 0);
435 return (set_error(lbh, BE_ERR_DESTROYMNT));
440 * If we're initially destroying a snapshot, origin options do
441 * not make sense. If we're destroying the origin snapshot of
442 * a BE, we want to maintain the options in case we need to
443 * fake success after failing to promote.
446 options &= ~BE_DESTROY_WANTORIGIN;
447 if (!zfs_dataset_exists(lbh->lzh, path, ZFS_TYPE_SNAPSHOT))
448 return (set_error(lbh, BE_ERR_NOENT));
450 bdd.snapname = strdup(snapdelim + 1);
451 if (bdd.snapname == NULL)
452 return (set_error(lbh, BE_ERR_NOMEM));
454 fs = zfs_open(lbh->lzh, path, ZFS_TYPE_DATASET);
457 return (set_error(lbh, BE_ERR_ZFSOPEN));
462 * Whether we're destroying a BE or a single snapshot, we need to walk
463 * the tree of what we're going to destroy and promote everything in our
464 * path so that we can make it happen.
466 if ((err = be_promote_dependent_clones(fs, &bdd)) != 0) {
470 * If we're just destroying the origin of some other dataset
471 * we were invoked to destroy, then we just ignore
472 * BE_ERR_HASCLONES and return success unless the caller wanted
473 * to force the issue.
475 if (odestroyer && err == BE_ERR_HASCLONES &&
476 (options & BE_DESTROY_AUTOORIGIN) != 0)
478 return (set_error(lbh, err));
482 * This was deferred until after we promote all of the derivatives so
483 * that we grab the new origin after everything's settled down.
485 if ((options & BE_DESTROY_WANTORIGIN) != 0 &&
486 zfs_prop_get(fs, ZFS_PROP_ORIGIN, origin, sizeof(origin),
487 NULL, NULL, 0, 1) != 0 &&
488 (options & BE_DESTROY_ORIGIN) != 0)
489 return (set_error(lbh, BE_ERR_NOORIGIN));
492 * If the caller wants auto-origin destruction and the origin
493 * name matches one of our automatically created snapshot names
494 * (i.e. strftime("%F-%T") with a serial at the end), then
495 * we'll set the DESTROY_ORIGIN flag and nuke it
496 * be_is_auto_snapshot_name is exported from libbe(3) so that
497 * the caller can determine if it needs to warn about the origin
498 * not being destroyed or not.
500 if ((options & BE_DESTROY_AUTOORIGIN) != 0 && *origin != '\0' &&
501 be_is_auto_snapshot_name(lbh, origin))
502 options |= BE_DESTROY_ORIGIN;
504 err = be_destroy_cb(fs, &bdd);
508 /* Children are still present or the mount is referenced */
510 return (set_error(lbh, BE_ERR_DESTROYMNT));
511 return (set_error(lbh, BE_ERR_UNKNOWN));
514 if ((options & BE_DESTROY_ORIGIN) == 0)
517 /* The origin can't possibly be shorter than the BE root */
518 rootlen = strlen(lbh->root);
519 if (*origin == '\0' || strlen(origin) <= rootlen + 1)
520 return (set_error(lbh, BE_ERR_INVORIGIN));
523 * We'll be chopping off the BE root and running this back through
524 * be_destroy, so that we properly handle the origin snapshot whether
525 * it be that of a deep BE or not.
527 if (strncmp(origin, lbh->root, rootlen) != 0 || origin[rootlen] != '/')
530 return (be_destroy_internal(lbh, origin + rootlen + 1,
531 options & ~BE_DESTROY_ORIGIN, true));
535 be_destroy(libbe_handle_t *lbh, const char *name, int options)
539 * The consumer must not set both BE_DESTROY_AUTOORIGIN and
540 * BE_DESTROY_ORIGIN. Internally, we'll set the latter from the former.
541 * The latter should imply that we must succeed at destroying the
542 * origin, or complain otherwise.
544 if ((options & BE_DESTROY_WANTORIGIN) == BE_DESTROY_WANTORIGIN)
545 return (set_error(lbh, BE_ERR_UNKNOWN));
546 return (be_destroy_internal(lbh, name, options, false));
550 be_setup_snapshot_name(libbe_handle_t *lbh, char *buf, size_t buflen)
557 len += strftime(buf + len, buflen - len, "@%F-%T", localtime(&rawtime));
558 /* No room for serial... caller will do its best */
559 if (buflen - len < 2)
562 for (serial = 0; serial < BE_SNAP_SERIAL_MAX; ++serial) {
563 snprintf(buf + len, buflen - len, "-%d", serial);
564 if (!zfs_dataset_exists(lbh->lzh, buf, ZFS_TYPE_SNAPSHOT))
570 be_is_auto_snapshot_name(libbe_handle_t *lbh __unused, const char *name)
573 int day, hour, minute, month, second, serial, year;
575 if ((snap = strchr(name, '@')) == NULL)
578 /* We'll grab the individual components and do some light validation. */
579 if (sscanf(snap, "%d-%d-%d-%d:%d:%d-%d", &year, &month, &day, &hour,
580 &minute, &second, &serial) != 7)
582 return (year >= 1970) && (month >= 1 && month <= 12) &&
583 (day >= 1 && day <= 31) && (hour >= 0 && hour <= 23) &&
584 (minute >= 0 && minute <= 59) && (second >= 0 && second <= 60) &&
589 be_snapshot(libbe_handle_t *lbh, const char *source, const char *snap_name,
590 bool recursive, char *result)
592 char buf[BE_MAXPATHLEN];
595 be_root_concat(lbh, source, buf);
597 if ((err = be_exists(lbh, buf)) != 0)
598 return (set_error(lbh, err));
600 if (snap_name != NULL) {
601 if (strlcat(buf, "@", sizeof(buf)) >= sizeof(buf))
602 return (set_error(lbh, BE_ERR_INVALIDNAME));
604 if (strlcat(buf, snap_name, sizeof(buf)) >= sizeof(buf))
605 return (set_error(lbh, BE_ERR_INVALIDNAME));
608 snprintf(result, BE_MAXPATHLEN, "%s@%s", source,
611 be_setup_snapshot_name(lbh, buf, sizeof(buf));
613 if (result != NULL && strlcpy(result, strrchr(buf, '/') + 1,
614 sizeof(buf)) >= sizeof(buf))
615 return (set_error(lbh, BE_ERR_INVALIDNAME));
617 if ((err = zfs_snapshot(lbh->lzh, buf, recursive, NULL)) != 0) {
619 case EZFS_INVALIDNAME:
620 return (set_error(lbh, BE_ERR_INVALIDNAME));
624 * The other errors that zfs_ioc_snapshot might return
625 * shouldn't happen if we've set things up properly, so
626 * we'll gloss over them and call it UNKNOWN as it will
627 * require further triage.
629 if (errno == ENOTSUP)
630 return (set_error(lbh, BE_ERR_NOPOOL));
631 return (set_error(lbh, BE_ERR_UNKNOWN));
635 return (BE_ERR_SUCCESS);
640 * Create the boot environment specified by the name parameter
643 be_create(libbe_handle_t *lbh, const char *name)
647 err = be_create_from_existing(lbh, name, be_active_path(lbh));
649 return (set_error(lbh, err));
653 be_deep_clone_prop(int prop, void *cb)
656 struct libbe_dccb *dccb;
658 char pval[BE_MAXPATHLEN];
659 char source[BE_MAXPATHLEN];
663 /* Skip some properties we don't want to touch */
664 if (prop == ZFS_PROP_CANMOUNT)
667 /* Don't copy readonly properties */
668 if (zfs_prop_readonly(prop))
671 if ((err = zfs_prop_get(dccb->zhp, prop, (char *)&pval,
672 sizeof(pval), &src, (char *)&source, sizeof(source), false)))
673 /* Just continue if we fail to read a property */
677 * Only copy locally defined or received properties. This continues
678 * to avoid temporary/default/local properties intentionally without
679 * breaking received datasets.
681 if (src != ZPROP_SRC_LOCAL && src != ZPROP_SRC_RECEIVED)
684 /* Augment mountpoint with altroot, if needed */
686 if (prop == ZFS_PROP_MOUNTPOINT)
687 val = be_mountpoint_augmented(dccb->lbh, val);
689 nvlist_add_string(dccb->props, zfs_prop_to_name(prop), val);
695 * Return the corresponding boot environment path for a given
696 * dataset path, the constructed path is placed in 'result'.
698 * example: say our new boot environment name is 'bootenv' and
699 * the dataset path is 'zroot/ROOT/default/data/set'.
701 * result should produce: 'zroot/ROOT/bootenv/data/set'
704 be_get_path(struct libbe_deep_clone *ldc, const char *dspath, char *result, int result_size)
709 /* match the root path for the boot environments */
710 pos = strstr(dspath, ldc->lbh->root);
712 /* no match, different pools? */
714 return (BE_ERR_BADPATH);
716 /* root path of the new boot environment */
717 snprintf(result, result_size, "%s/%s", ldc->lbh->root, ldc->bename);
719 /* gets us to the parent dataset, the +1 consumes a trailing slash */
720 pos += strlen(ldc->lbh->root) + 1;
722 /* skip the parent dataset */
723 if ((child_dataset = strchr(pos, '/')) != NULL)
724 strlcat(result, child_dataset, result_size);
726 return (BE_ERR_SUCCESS);
730 be_clone_cb(zfs_handle_t *ds, void *data)
733 char be_path[BE_MAXPATHLEN];
734 char snap_path[BE_MAXPATHLEN];
736 zfs_handle_t *snap_hdl;
738 struct libbe_deep_clone *ldc;
739 struct libbe_dccb dccb;
741 ldc = (struct libbe_deep_clone *)data;
742 dspath = zfs_get_name(ds);
744 snprintf(snap_path, sizeof(snap_path), "%s@%s", dspath, ldc->snapname);
746 /* construct the boot environment path from the dataset we're cloning */
747 if (be_get_path(ldc, dspath, be_path, sizeof(be_path)) != BE_ERR_SUCCESS)
748 return (set_error(ldc->lbh, BE_ERR_UNKNOWN));
750 /* the dataset to be created (i.e. the boot environment) already exists */
751 if (zfs_dataset_exists(ldc->lbh->lzh, be_path, ZFS_TYPE_DATASET))
752 return (set_error(ldc->lbh, BE_ERR_EXISTS));
754 /* no snapshot found for this dataset, silently skip it */
755 if (!zfs_dataset_exists(ldc->lbh->lzh, snap_path, ZFS_TYPE_SNAPSHOT))
759 zfs_open(ldc->lbh->lzh, snap_path, ZFS_TYPE_SNAPSHOT)) == NULL)
760 return (set_error(ldc->lbh, BE_ERR_ZFSOPEN));
762 nvlist_alloc(&props, NV_UNIQUE_NAME, KM_SLEEP);
763 nvlist_add_string(props, "canmount", "noauto");
768 if (zprop_iter(be_deep_clone_prop, &dccb, B_FALSE, B_FALSE,
769 ZFS_TYPE_FILESYSTEM) == ZPROP_INVAL)
772 if ((err = zfs_clone(snap_hdl, be_path, props)) != 0)
773 return (set_error(ldc->lbh, BE_ERR_ZFSCLONE));
778 if (ldc->depth_limit == -1 || ldc->depth < ldc->depth_limit) {
780 err = zfs_iter_filesystems(ds, 0, be_clone_cb, ldc);
784 return (set_error(ldc->lbh, err));
788 * Create a boot environment with a given name from a given snapshot.
789 * Snapshots can be in the format 'zroot/ROOT/default@snapshot' or
790 * 'default@snapshot'. In the latter case, 'default@snapshot' will be prepended
791 * with the root path that libbe was initailized with.
794 be_clone(libbe_handle_t *lbh, const char *bename, const char *snapshot, int depth)
797 char snap_path[BE_MAXPATHLEN];
798 char *parentname, *snapname;
799 zfs_handle_t *parent_hdl;
800 struct libbe_deep_clone ldc;
802 /* ensure the boot environment name is valid */
803 if ((err = be_validate_name(lbh, bename)) != 0)
804 return (set_error(lbh, err));
807 * prepend the boot environment root path if we're
808 * given a partial snapshot name.
810 if ((err = be_root_concat(lbh, snapshot, snap_path)) != 0)
811 return (set_error(lbh, err));
813 /* ensure the snapshot exists */
814 if ((err = be_validate_snap(lbh, snap_path)) != 0)
815 return (set_error(lbh, err));
817 /* get a copy of the snapshot path so we can disect it */
818 if ((parentname = strdup(snap_path)) == NULL)
819 return (set_error(lbh, BE_ERR_UNKNOWN));
821 /* split dataset name from snapshot name */
822 snapname = strchr(parentname, '@');
823 if (snapname == NULL) {
825 return (set_error(lbh, BE_ERR_UNKNOWN));
830 /* set-up the boot environment */
833 ldc.snapname = snapname;
835 ldc.depth_limit = depth;
837 /* the boot environment will be cloned from this dataset */
838 parent_hdl = zfs_open(lbh->lzh, parentname, ZFS_TYPE_DATASET);
840 /* create the boot environment */
841 err = be_clone_cb(parent_hdl, &ldc);
844 return (set_error(lbh, err));
848 * Create a boot environment from pre-existing snapshot, specifying a depth.
850 int be_create_depth(libbe_handle_t *lbh, const char *bename,
851 const char *snap, int depth)
853 return (be_clone(lbh, bename, snap, depth));
857 * Create the boot environment from pre-existing snapshot
860 be_create_from_existing_snap(libbe_handle_t *lbh, const char *bename,
863 return (be_clone(lbh, bename, snap, -1));
868 * Create a boot environment from an existing boot environment
871 be_create_from_existing(libbe_handle_t *lbh, const char *bename, const char *old)
874 char snap[BE_MAXPATHLEN];
876 if ((err = be_snapshot(lbh, old, NULL, true, snap)) != 0)
877 return (set_error(lbh, err));
879 err = be_clone(lbh, bename, snap, -1);
881 return (set_error(lbh, err));
886 * Verifies that a snapshot has a valid name, exists, and has a mountpoint of
887 * '/'. Returns BE_ERR_SUCCESS (0), upon success, or the relevant BE_ERR_* upon
888 * failure. Does not set the internal library error state.
891 be_validate_snap(libbe_handle_t *lbh, const char *snap_name)
894 if (strlen(snap_name) >= BE_MAXPATHLEN)
895 return (BE_ERR_PATHLEN);
897 if (!zfs_name_valid(snap_name, ZFS_TYPE_SNAPSHOT))
898 return (BE_ERR_INVALIDNAME);
900 if (!zfs_dataset_exists(lbh->lzh, snap_name,
902 return (BE_ERR_NOENT);
904 return (BE_ERR_SUCCESS);
909 * Idempotently appends the name argument to the root boot environment path
910 * and copies the resulting string into the result buffer (which is assumed
911 * to be at least BE_MAXPATHLEN characters long. Returns BE_ERR_SUCCESS upon
912 * success, BE_ERR_PATHLEN if the resulting path is longer than BE_MAXPATHLEN,
913 * or BE_ERR_INVALIDNAME if the name is a path that does not begin with
914 * zfs_be_root. Does not set internal library error state.
917 be_root_concat(libbe_handle_t *lbh, const char *name, char *result)
919 size_t name_len, root_len;
921 name_len = strlen(name);
922 root_len = strlen(lbh->root);
924 /* Act idempotently; return be name if it is already a full path */
925 if (strrchr(name, '/') != NULL) {
926 if (strstr(name, lbh->root) != name)
927 return (BE_ERR_INVALIDNAME);
929 if (name_len >= BE_MAXPATHLEN)
930 return (BE_ERR_PATHLEN);
932 strlcpy(result, name, BE_MAXPATHLEN);
933 return (BE_ERR_SUCCESS);
934 } else if (name_len + root_len + 1 < BE_MAXPATHLEN) {
935 snprintf(result, BE_MAXPATHLEN, "%s/%s", lbh->root,
937 return (BE_ERR_SUCCESS);
940 return (BE_ERR_PATHLEN);
945 * Verifies the validity of a boot environment name (A-Za-z0-9-_.). Returns
946 * BE_ERR_SUCCESS (0) if name is valid, otherwise returns BE_ERR_INVALIDNAME
948 * Does not set internal library error state.
951 be_validate_name(libbe_handle_t *lbh, const char *name)
955 * Impose the additional restriction that the entire dataset name must
956 * not exceed the maximum length of a dataset, i.e. MAXNAMELEN.
958 if (strlen(lbh->root) + 1 + strlen(name) > MAXNAMELEN)
959 return (BE_ERR_PATHLEN);
961 if (!zfs_name_valid(name, ZFS_TYPE_DATASET))
962 return (BE_ERR_INVALIDNAME);
965 * ZFS allows spaces in boot environment names, but the kernel can't
966 * handle booting from such a dataset right now. vfs.root.mountfrom
967 * is defined to be a space-separated list, and there's no protocol for
968 * escaping whitespace in the path component of a dev:path spec. So
969 * while loader can handle this situation alright, it can't safely pass
970 * it on to mountroot.
972 if (strchr(name, ' ') != NULL)
973 return (BE_ERR_INVALIDNAME);
975 return (BE_ERR_SUCCESS);
983 be_rename(libbe_handle_t *lbh, const char *old, const char *new)
985 char full_old[BE_MAXPATHLEN];
986 char full_new[BE_MAXPATHLEN];
987 zfs_handle_t *zfs_hdl;
991 * be_validate_name is documented not to set error state, so we should
994 if ((err = be_validate_name(lbh, new)) != 0)
995 return (set_error(lbh, err));
996 if ((err = be_root_concat(lbh, old, full_old)) != 0)
997 return (set_error(lbh, err));
998 if ((err = be_root_concat(lbh, new, full_new)) != 0)
999 return (set_error(lbh, err));
1001 if (!zfs_dataset_exists(lbh->lzh, full_old, ZFS_TYPE_DATASET))
1002 return (set_error(lbh, BE_ERR_NOENT));
1004 if (zfs_dataset_exists(lbh->lzh, full_new, ZFS_TYPE_DATASET))
1005 return (set_error(lbh, BE_ERR_EXISTS));
1007 if ((zfs_hdl = zfs_open(lbh->lzh, full_old,
1008 ZFS_TYPE_FILESYSTEM)) == NULL)
1009 return (set_error(lbh, BE_ERR_ZFSOPEN));
1011 /* recurse, nounmount, forceunmount */
1012 struct renameflags flags = {
1015 err = zfs_rename(zfs_hdl, full_new, flags);
1019 return (set_error(lbh, BE_ERR_UNKNOWN));
1025 be_export(libbe_handle_t *lbh, const char *bootenv, int fd)
1027 char snap_name[BE_MAXPATHLEN];
1028 char buf[BE_MAXPATHLEN];
1030 sendflags_t flags = { 0 };
1033 if ((err = be_snapshot(lbh, bootenv, NULL, true, snap_name)) != 0)
1034 /* Use the error set by be_snapshot */
1037 be_root_concat(lbh, snap_name, buf);
1039 if ((zfs = zfs_open(lbh->lzh, buf, ZFS_TYPE_DATASET)) == NULL)
1040 return (set_error(lbh, BE_ERR_ZFSOPEN));
1042 err = zfs_send_one(zfs, NULL, fd, &flags, /* redactbook */ NULL);
1050 be_import(libbe_handle_t *lbh, const char *bootenv, int fd)
1052 char buf[BE_MAXPATHLEN];
1055 recvflags_t flags = { .nomount = 1 };
1058 be_root_concat(lbh, bootenv, buf);
1060 if ((err = zfs_receive(lbh->lzh, buf, NULL, &flags, fd, NULL)) != 0) {
1063 return (set_error(lbh, BE_ERR_NOORIGIN));
1065 return (set_error(lbh, BE_ERR_NOENT));
1067 return (set_error(lbh, BE_ERR_IO));
1069 return (set_error(lbh, BE_ERR_UNKNOWN));
1073 if ((zfs = zfs_open(lbh->lzh, buf, ZFS_TYPE_FILESYSTEM)) == NULL)
1074 return (set_error(lbh, BE_ERR_ZFSOPEN));
1076 nvlist_alloc(&props, NV_UNIQUE_NAME, KM_SLEEP);
1077 nvlist_add_string(props, "canmount", "noauto");
1078 nvlist_add_string(props, "mountpoint", "none");
1080 err = zfs_prop_set_list(zfs, props);
1086 return (set_error(lbh, BE_ERR_UNKNOWN));
1093 be_create_child_noent(libbe_handle_t *lbh, const char *active,
1094 const char *child_path)
1100 nvlist_alloc(&props, NV_UNIQUE_NAME, KM_SLEEP);
1101 nvlist_add_string(props, "canmount", "noauto");
1102 nvlist_add_string(props, "mountpoint", child_path);
1105 if ((err = zfs_create(lbh->lzh, active, ZFS_TYPE_DATASET,
1109 return (set_error(lbh, BE_ERR_EXISTS));
1111 return (set_error(lbh, BE_ERR_NOENT));
1113 case EZFS_BADVERSION:
1114 return (set_error(lbh, BE_ERR_NOPOOL));
1117 /* We set something up wrong, probably... */
1118 return (set_error(lbh, BE_ERR_UNKNOWN));
1123 if ((zfs = zfs_open(lbh->lzh, active, ZFS_TYPE_DATASET)) == NULL)
1124 return (set_error(lbh, BE_ERR_ZFSOPEN));
1127 if ((err = zfs_prop_set(zfs, "canmount", "noauto")) != 0) {
1130 * Similar to other cases, this shouldn't fail unless we've
1131 * done something wrong. This is a new dataset that shouldn't
1132 * have been mounted anywhere between creation and now.
1134 if (err == EZFS_NOMEM)
1135 return (set_error(lbh, BE_ERR_NOMEM));
1136 return (set_error(lbh, BE_ERR_UNKNOWN));
1139 return (BE_ERR_SUCCESS);
1143 be_create_child_cloned(libbe_handle_t *lbh, const char *active)
1145 char buf[BE_MAXPATHLEN], tmp[BE_MAXPATHLEN];;
1152 * Establish if the existing path is a zfs dataset or just
1153 * the subdirectory of one
1155 strlcpy(tmp, "tmp/be_snap.XXXXX", sizeof(tmp));
1156 if (mktemp(tmp) == NULL)
1157 return (set_error(lbh, BE_ERR_UNKNOWN));
1159 be_root_concat(lbh, tmp, buf);
1160 printf("Here %s?\n", buf);
1161 if ((err = zfs_snapshot(lbh->lzh, buf, false, NULL)) != 0) {
1163 case EZFS_INVALIDNAME:
1164 return (set_error(lbh, BE_ERR_INVALIDNAME));
1168 * The other errors that zfs_ioc_snapshot might return
1169 * shouldn't happen if we've set things up properly, so
1170 * we'll gloss over them and call it UNKNOWN as it will
1171 * require further triage.
1173 if (errno == ENOTSUP)
1174 return (set_error(lbh, BE_ERR_NOPOOL));
1175 return (set_error(lbh, BE_ERR_UNKNOWN));
1180 if ((zfs = zfs_open(lbh->lzh, buf, ZFS_TYPE_SNAPSHOT)) == NULL)
1181 return (BE_ERR_ZFSOPEN);
1183 if ((err = zfs_clone(zfs, active, NULL)) != 0)
1184 /* XXX TODO correct error */
1185 return (set_error(lbh, BE_ERR_UNKNOWN));
1189 return (BE_ERR_SUCCESS);
1193 be_add_child(libbe_handle_t *lbh, const char *child_path, bool cp_if_exists)
1196 char active[BE_MAXPATHLEN], buf[BE_MAXPATHLEN];
1200 /* Require absolute paths */
1201 if (*child_path != '/')
1202 return (set_error(lbh, BE_ERR_BADPATH));
1204 strlcpy(active, be_active_path(lbh), BE_MAXPATHLEN);
1205 strcpy(buf, active);
1207 /* Create non-mountable parent dataset(s) */
1209 for (char *p; (p = strchr(s+1, '/')) != NULL; s = p) {
1211 strncat(buf, s, len);
1213 nvlist_alloc(&props, NV_UNIQUE_NAME, KM_SLEEP);
1214 nvlist_add_string(props, "canmount", "off");
1215 nvlist_add_string(props, "mountpoint", "none");
1216 zfs_create(lbh->lzh, buf, ZFS_TYPE_DATASET, props);
1220 /* Path does not exist as a descendent of / yet */
1221 if (strlcat(active, child_path, BE_MAXPATHLEN) >= BE_MAXPATHLEN)
1222 return (set_error(lbh, BE_ERR_PATHLEN));
1224 if (stat(child_path, &sb) != 0) {
1225 /* Verify that error is ENOENT */
1226 if (errno != ENOENT)
1227 return (set_error(lbh, BE_ERR_UNKNOWN));
1228 return (be_create_child_noent(lbh, active, child_path));
1229 } else if (cp_if_exists)
1230 /* Path is already a descendent of / and should be copied */
1231 return (be_create_child_cloned(lbh, active));
1232 return (set_error(lbh, BE_ERR_EXISTS));
1237 * Deactivate old BE dataset; currently just sets canmount=noauto or
1238 * resets boot once configuration.
1241 be_deactivate(libbe_handle_t *lbh, const char *ds, bool temporary)
1246 return (lzbe_set_boot_device(
1247 zpool_get_name(lbh->active_phandle), lzbe_add, NULL));
1250 if ((zfs = zfs_open(lbh->lzh, ds, ZFS_TYPE_DATASET)) == NULL)
1252 if (zfs_prop_set(zfs, "canmount", "noauto") != 0)
1259 be_activate(libbe_handle_t *lbh, const char *bootenv, bool temporary)
1261 char be_path[BE_MAXPATHLEN];
1267 be_root_concat(lbh, bootenv, be_path);
1269 /* Note: be_exists fails if mountpoint is not / */
1270 if ((err = be_exists(lbh, be_path)) != 0)
1271 return (set_error(lbh, err));
1274 return (lzbe_set_boot_device(
1275 zpool_get_name(lbh->active_phandle), lzbe_add, be_path));
1277 if (strncmp(lbh->bootfs, "-", 1) != 0 &&
1278 be_deactivate(lbh, lbh->bootfs, false) != 0)
1281 /* Obtain bootenv zpool */
1282 err = zpool_set_prop(lbh->active_phandle, "bootfs", be_path);
1286 zhp = zfs_open(lbh->lzh, be_path, ZFS_TYPE_FILESYSTEM);
1290 if (be_prop_list_alloc(&dsprops) != 0)
1293 if (be_get_dataset_props(lbh, be_path, dsprops) != 0) {
1294 nvlist_free(dsprops);
1298 if (nvlist_lookup_string(dsprops, "origin", &origin) == 0)
1299 err = zfs_promote(zhp);
1300 nvlist_free(dsprops);
1308 return (BE_ERR_SUCCESS);